cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.400: full source
This commit is contained in:
1 parent
343331d234
commit
d5fbcacaa4
176 files changed
+32511
-19
No files matched your search
@@ -0,0 +1,274 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The Modbus bridge add-on's start: its devices from the add-on's options and
|
||||
Cantabile's profiles (parameters only: /data/devices.json is made again at
|
||||
every start, never edited), the simulator when asked, the broker from the
|
||||
Supervisor, the bridge, and the page (ingress): devices, values, and each
|
||||
control's protection.
|
||||
|
||||
A device is read over Modbus (the profile's register map) or, for a profile
|
||||
with an "ha" map (SONOFF SPM through SonoffLAN), from Home Assistant's own
|
||||
entities (ha_source). Per device: "read_only" (commands are checked and
|
||||
logged, never written: a dry run), "simulate" (only this device), "poll_s"
|
||||
(at least 10 s: a gateway may have another master, e.g. HA's own modbus).
|
||||
|
||||
Protection (none | protected | sealed): the profile's default, over it the
|
||||
owner's choice in /data/policy.json, set only on this page by a Home
|
||||
Assistant administrator, by hand. Every change is logged (who, when) in the
|
||||
add-on's log and in /data/protection.log. Sealed is shown locked: it changes
|
||||
only by a signed policy from Cantabile, never here.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
sys.path.insert(0, "/app")
|
||||
import bridge # noqa: E402
|
||||
import ha_source # noqa: E402
|
||||
import page as view # noqa: E402
|
||||
import sim # noqa: E402
|
||||
|
||||
DATA = "/data"
|
||||
PROFILES = "/app/profiles"
|
||||
DEVICES = f"{DATA}/devices.json"
|
||||
POLICY = f"{DATA}/policy.json"
|
||||
PLOG = f"{DATA}/protection.log"
|
||||
INGRESS_PEER = "172.30.32.2" # the Supervisor's ingress proxy
|
||||
SIM_PORT = 15020
|
||||
MIN_POLL_S = 10
|
||||
values = {} # "<dev>/<key>" -> last value (from MQTT)
|
||||
statuses = {} # "<dev>" -> online | offline
|
||||
hist = {} # "<dev>/<key>" -> {minute: value}, the last hour (sparklines)
|
||||
lock = threading.Lock()
|
||||
|
||||
|
||||
def log(msg):
|
||||
print(f"cantabile-modbus: {msg}", flush=True)
|
||||
|
||||
|
||||
def slug(s):
|
||||
return "".join(c if c.isalnum() else "_" for c in s.lower()).strip("_")[:40] or "device"
|
||||
|
||||
|
||||
def profiles():
|
||||
out = {}
|
||||
for n in sorted(os.listdir(PROFILES)):
|
||||
if not n.endswith(".json"):
|
||||
continue
|
||||
with open(os.path.join(PROFILES, n)) as f:
|
||||
p = json.load(f)
|
||||
if p.get("modbus", {}).get("registers") or p.get("ha", {}).get("registers"):
|
||||
out[p["id"]] = p
|
||||
return out
|
||||
|
||||
|
||||
def ha_names():
|
||||
"""(entity id -> its name in HA (a circuit's name), (domain, platform,
|
||||
unique id) -> entity id); empty without HA."""
|
||||
try:
|
||||
ids, reg_names = ha_source.registry()
|
||||
names = {k: v for k, v in reg_names.items() if v}
|
||||
names.update({s["entity_id"]: s["attributes"].get("friendly_name") for s in ha_source.call("GET", "/states")
|
||||
if s["attributes"].get("friendly_name")})
|
||||
return names, ids
|
||||
except Exception as e:
|
||||
log(f"Home Assistant's entities not read ({e}): the profile's entity ids and names")
|
||||
return {}, {}
|
||||
|
||||
|
||||
def make_devices(opts, ps, names=None, ids=None):
|
||||
"""devices.json for the bridge, from the options (the same shape the
|
||||
Hub's devices tool writes)."""
|
||||
out = []
|
||||
for i, d in enumerate(opts.get("devices", [])):
|
||||
p = ps.get(d["profile"])
|
||||
if not p:
|
||||
log(f"{d['name']}: no profile {d['profile']!r} with a register map: left out")
|
||||
continue
|
||||
base = p.get("modbus") or p["ha"]
|
||||
dev = {"id": slug(d["name"]), "name": d["name"], "manufacturer": p["manufacturer"], "model": p["name"],
|
||||
"poll_s": max(MIN_POLL_S, int(d.get("poll_s") or base.get("poll_s", 10))),
|
||||
"protection": p.get("register_protection", {}), "read_only": bool(d.get("read_only")), "view": p.get("view", {}),
|
||||
"node": "cantabile_modbus", "profile": p["id"]}
|
||||
if p.get("modbus", {}).get("registers"):
|
||||
if not d.get("host") or not d.get("port") or d.get("unit_id") is None:
|
||||
log(f"{d['name']}: {p['id']} needs host, port and unit_id: left out")
|
||||
continue
|
||||
host, port = d["host"], d["port"]
|
||||
if opts.get("simulate") or d.get("simulate"):
|
||||
trace = sim.load_trace(f"/share/cantabile/trace-{p['id']}.json")
|
||||
host, port = "127.0.0.1", SIM_PORT + i
|
||||
sim.serve(p, trace, d["unit_id"], port)
|
||||
dev["simulated"] = True
|
||||
log(f"{d['name']}: simulated on {host}:{port} ({'a recorded trace' if trace else 'zeros: no trace'})")
|
||||
dev.update(host=host, port=port, unit_id=d["unit_id"], registers=p["modbus"]["registers"],
|
||||
derived=p["modbus"].get("derived", []))
|
||||
else:
|
||||
if not d.get("device"):
|
||||
log(f"{d['name']}: {p['id']} needs the device's id in Home Assistant (device): left out")
|
||||
continue
|
||||
if names is None:
|
||||
names, ids = ha_names()
|
||||
dev.update(source="ha", host="Home Assistant", port=0, unit_id=0, device=d["device"],
|
||||
registers=ha_source.expand(p, d["device"], names.get, ids))
|
||||
out.append(dev)
|
||||
with open(DEVICES, "w") as f:
|
||||
json.dump({"devices": out}, f, indent=1)
|
||||
return out
|
||||
|
||||
|
||||
def mqtt_service():
|
||||
req = urllib.request.Request("http://supervisor/services/mqtt",
|
||||
headers={"Authorization": f"Bearer {os.environ.get('SUPERVISOR_TOKEN', '')}"})
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.load(r)["data"]
|
||||
|
||||
|
||||
def policy():
|
||||
try:
|
||||
with open(POLICY) as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def level_of(dev, key):
|
||||
return bridge.protection(dev, key)[0]
|
||||
|
||||
|
||||
def set_level(dev, key, new, who):
|
||||
old = level_of(dev, key)
|
||||
if old == "sealed" or new not in ("none", "protected") or old == new:
|
||||
return False
|
||||
p = policy()
|
||||
p[f"{dev['id']}/{key}"] = new
|
||||
tmp = POLICY + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(p, f, indent=1)
|
||||
os.replace(tmp, POLICY)
|
||||
line = f"{time.strftime('%Y-%m-%d %H:%M:%S %Z')}: {dev['name']} / {key}: {old} -> {new}, by {who} (the add-on's page)"
|
||||
with open(PLOG, "a") as f:
|
||||
f.write(line + "\n")
|
||||
log("protection " + line)
|
||||
return True
|
||||
|
||||
|
||||
def record(dev, key, payload, now=None):
|
||||
"""A value from MQTT: the last one, and one a minute for the last hour."""
|
||||
with lock:
|
||||
if key == "status":
|
||||
statuses[dev] = payload
|
||||
return
|
||||
values[f"{dev}/{key}"] = payload
|
||||
x = view.num(payload)
|
||||
if x is not None:
|
||||
m = int((now or time.time()) // 60)
|
||||
h = hist.setdefault(f"{dev}/{key}", {})
|
||||
h[m] = x
|
||||
for old in [k for k in h if k <= m - view.HIST_MIN]:
|
||||
del h[old]
|
||||
|
||||
|
||||
def watch_values(svc):
|
||||
import paho.mqtt.client as paho
|
||||
m = paho.Client(paho.CallbackAPIVersion.VERSION2, client_id="cantabile-modbus-page")
|
||||
if svc.get("username"):
|
||||
m.username_pw_set(svc["username"], svc.get("password", ""))
|
||||
|
||||
def on_message(_c, _u, msg):
|
||||
parts = msg.topic.split("/")
|
||||
if len(parts) == 3:
|
||||
record(parts[1], parts[2], msg.payload.decode(errors="replace"))
|
||||
m.on_connect = lambda c, *_a: c.subscribe(f"{bridge.BASE}/#")
|
||||
m.on_message = on_message
|
||||
m.connect(svc["host"], int(svc.get("port", 1883)))
|
||||
m.loop_start()
|
||||
|
||||
|
||||
def page(devs, lang="en"):
|
||||
try:
|
||||
with open(PLOG) as f:
|
||||
plog = f.read().strip().splitlines()[-20:]
|
||||
except OSError:
|
||||
plog = []
|
||||
with lock:
|
||||
vs, st, hs = dict(values), dict(statuses), {k: dict(v) for k, v in hist.items()}
|
||||
return view.render(devs, vs, st, hs, level_of, lambda d, k: bridge.protection(d, k)[1], lang, plog)
|
||||
|
||||
|
||||
def protect_all(dev, who):
|
||||
"""Every control of the device that is not protected: protected (the
|
||||
safe way only; lifting is always one control at a time)."""
|
||||
return [r["key"] for r in dev["registers"] if r.get("write") and set_level(dev, r["key"], "protected", who)]
|
||||
|
||||
|
||||
def serve_page(devs):
|
||||
by_id = {d["id"]: d for d in devs}
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def allowed(self):
|
||||
if self.client_address[0] != INGRESS_PEER:
|
||||
self.send_error(403)
|
||||
return False
|
||||
return True
|
||||
|
||||
def send(self, body, code=200):
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
if self.allowed():
|
||||
self.send(page(devs, view.lang_of(self.headers.get("Accept-Language"))))
|
||||
|
||||
def do_POST(self):
|
||||
if not self.allowed():
|
||||
return
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
q = urllib.parse.parse_qs(self.rfile.read(n).decode())
|
||||
dev = by_id.get((q.get("dev") or [""])[0])
|
||||
key = (q.get("key") or [""])[0]
|
||||
who = self.headers.get("X-Remote-User-Display-Name") or self.headers.get("X-Remote-User-Name") or "?"
|
||||
level = (q.get("level") or [""])[0]
|
||||
if dev and key == "*" and level == "protected":
|
||||
protect_all(dev, who)
|
||||
elif dev and any(r["key"] == key and r.get("write") for r in dev["registers"]):
|
||||
set_level(dev, key, level, who)
|
||||
self.send_response(303)
|
||||
self.send_header("Location", (self.headers.get("X-Ingress-Path") or "") + "/" + (f"#{dev['id']}" if dev else ""))
|
||||
self.end_headers()
|
||||
|
||||
ThreadingHTTPServer(("0.0.0.0", 8098), H).serve_forever()
|
||||
|
||||
|
||||
def main():
|
||||
with open(f"{DATA}/options.json") as f:
|
||||
opts = json.load(f)
|
||||
devs = make_devices(opts, profiles())
|
||||
svc = mqtt_service()
|
||||
if svc.get("ssl"):
|
||||
log("the broker wants TLS, which the bridge does not speak yet")
|
||||
sys.exit(1)
|
||||
with open(f"{DATA}/mqtt-password", "w") as f:
|
||||
f.write(svc.get("password", ""))
|
||||
os.environ.update(MQTT_HOST=str(svc["host"]), MQTT_PORT=str(svc.get("port", 1883)), MQTT_USERNAME=svc.get("username", ""),
|
||||
MQTT_PASSWORD_FILE=f"{DATA}/mqtt-password")
|
||||
bridge.CONFIG, bridge.POLICY = DEVICES, POLICY
|
||||
bridge.SOURCES["ha"] = ha_source.HASource
|
||||
log(f"{len(devs)} devices; broker {svc['host']}:{svc.get('port', 1883)}")
|
||||
threading.Thread(target=bridge.main, daemon=True).start()
|
||||
watch_values(svc)
|
||||
serve_page(devs)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user