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,51 @@
|
||||
# Cantabile Modbus bridge
|
||||
|
||||
The bridge reads inverters, meters and batteries over Modbus TCP by
|
||||
Cantabile's device profiles and shows them in Home Assistant (MQTT
|
||||
discovery, the device under its own name), in Cantabile's units, so the
|
||||
Cantabile agent maps them exactly.
|
||||
|
||||
## Devices
|
||||
|
||||
Add each device in the options: its profile (for example `hm8042-hybrid`),
|
||||
a name, the address and port of its Modbus TCP gateway, and its Modbus id.
|
||||
The add-on makes everything else from the profile at every start; nothing
|
||||
is kept by hand.
|
||||
|
||||
One Modbus master per gateway: if Home Assistant's own modbus integration
|
||||
already reads a device, keep that, or stop it before the bridge reads it.
|
||||
Some RS485 gateways send every answer to every connected client, so a
|
||||
second master's answers reach the first one too.
|
||||
|
||||
Per device, optionally: `poll_s` (seconds between reads, at least 10),
|
||||
`read_only` (commands are checked and logged but never written: a dry run)
|
||||
and `simulate` (this device only).
|
||||
|
||||
## Circuits from Home Assistant
|
||||
|
||||
A SONOFF SPM-4Relay (profile `sonoff-spm`) is read from the SonoffLAN
|
||||
integration's entities (LAN mode is enough): give its eWeLink id as
|
||||
`device` (the `ab40...` in `switch.sonoff_ab40..._1`). Each of its four
|
||||
circuits shows its switch, power, current and voltage under Cantabile's
|
||||
names; the energy is added up from the power (SonoffLAN reads energy only
|
||||
from the cloud). A circuit is switched only through this add-on's switch,
|
||||
after its protection check.
|
||||
|
||||
## Protection
|
||||
|
||||
Each control has a protection: **none**, **protected** (commands that would
|
||||
switch it off are refused; for a control without an off, every command) or
|
||||
**sealed** (set by Cantabile, locked). Every relay and circuit, and the
|
||||
inverter's settings, start protected. Only
|
||||
you lift a protection, on the add-on's page (Cantabile devices in the
|
||||
sidebar); every change is written to the add-on's log with who and when.
|
||||
|
||||
## Simulate
|
||||
|
||||
With **Simulate** on, the add-on answers for the devices itself, from a
|
||||
recorded trace in `/share/cantabile/trace-<profile>.json`, and never
|
||||
touches the real devices.
|
||||
|
||||
---
|
||||
|
||||
© 2026 Setti Solutions S.R.L, [www.setti.md](https://www.setti.md). All rights reserved.
|
||||
@@ -0,0 +1,16 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
# The Modbus bridge add-on's image: the Hub's bridge, its Modbus code and the
|
||||
# device profiles, with run.py in front (the add-on's options, MQTT from the
|
||||
# Supervisor, the page). Built from the repository's root:
|
||||
# docker build -f cantabile_modbus/Dockerfile --build-arg VERSION=<v> \
|
||||
# -t <registry>/cantabile-ha-modbus-amd64:<v> .
|
||||
FROM docker.io/library/python:3.13-alpine
|
||||
ARG VERSION ARCH=amd64 REVISION
|
||||
LABEL io.hass.version="${VERSION}" io.hass.type="addon" io.hass.arch="${ARCH}" \
|
||||
org.opencontainers.image.revision="${REVISION}"
|
||||
RUN pip install --no-cache-dir paho-mqtt==2.1.0 websocket-client==1.8.0
|
||||
COPY src/modbus-bridge/cantabile_modbus.py /app/cantabile_modbus.py
|
||||
COPY src/modbus-bridge/bridge.py /app/bridge.py
|
||||
COPY src/profiles/*.json /app/profiles/
|
||||
COPY cantabile_modbus/run.py cantabile_modbus/sim.py cantabile_modbus/ha_source.py cantabile_modbus/page.py /app/
|
||||
ENTRYPOINT ["python3", "-u", "/app/run.py"]
|
||||
@@ -0,0 +1,44 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
# Cantabile's Modbus bridge as a Home Assistant add-on: the Hub's bridge
|
||||
# (src/modbus-bridge) with its device profiles (src/profiles), for a
|
||||
# Home Assistant that isn't a Cantabile Hub. Devices come from the options;
|
||||
# the page (ingress) shows them and each control's protection.
|
||||
name: Cantabile Modbus bridge
|
||||
version: "0.1.400"
|
||||
slug: cantabile_modbus
|
||||
description: Reads inverters, meters, relays and circuits by Cantabile's device profiles (Modbus, or Home Assistant's own entities) and shows them in Home Assistant, each control with its protection.
|
||||
url: https://cantabile.cloud
|
||||
arch: [amd64]
|
||||
image: git.setti.solutions/daniel/cantabile-ha-modbus-{arch}
|
||||
stage: experimental
|
||||
startup: application
|
||||
boot: auto
|
||||
services:
|
||||
- mqtt:need
|
||||
# Devices read from Home Assistant's own entities (SONOFF SPM through
|
||||
# SonoffLAN): their states, and switch.turn_on/off after the protection check.
|
||||
homeassistant_api: true
|
||||
ingress: true
|
||||
ingress_port: 8098
|
||||
panel_icon: mdi:solar-power-variant
|
||||
panel_title: Cantabile devices
|
||||
panel_admin: true
|
||||
# The simulator's traces (/share/cantabile/trace-<profile>.json).
|
||||
map:
|
||||
- type: share
|
||||
read_only: true
|
||||
options:
|
||||
devices: []
|
||||
simulate: false
|
||||
schema:
|
||||
devices:
|
||||
- profile: str
|
||||
name: str
|
||||
host: str?
|
||||
port: "int(1,65535)?"
|
||||
unit_id: "int(0,247)?"
|
||||
device: str?
|
||||
poll_s: "int(10,3600)?"
|
||||
read_only: bool?
|
||||
simulate: bool?
|
||||
simulate: bool
|
||||
@@ -0,0 +1,138 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Devices read from Home Assistant's own entities (a profile's "ha" map, e.g.
|
||||
SONOFF SPM circuits through SonoffLAN in LAN mode): the bridge's source "ha".
|
||||
The entities are found by their unique ids in HA's entity registry (an owner
|
||||
may have renamed them), the profile's entity id the fallback. Values from
|
||||
HA's states (through the Supervisor), a circuit's energy added
|
||||
from its power where the integration has none, a command as HA's
|
||||
switch.turn_on/turn_off on the entity, after the bridge's protection check.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
import cantabile_modbus as mb
|
||||
|
||||
API = "http://supervisor/core/api"
|
||||
WS = "ws://supervisor/core/websocket"
|
||||
ENERGY = "/data/energy-{}.json" # per device: "<dev>/<key>" -> Wh, kept over restarts
|
||||
GAP_S = 300 # no power for longer: that time is not counted
|
||||
|
||||
|
||||
def call(method, path, body=None):
|
||||
req = urllib.request.Request(API + path, method=method, data=None if body is None else json.dumps(body).encode(),
|
||||
headers={"Authorization": f"Bearer {os.environ.get('SUPERVISOR_TOKEN', '')}",
|
||||
"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.load(r)
|
||||
|
||||
|
||||
def registry():
|
||||
"""({(domain, platform, unique id): entity id}, {entity id: its name})
|
||||
from HA's entity registry (a unique id is unique per domain only:
|
||||
SonoffLAN's circuit switch and its power-on select share one; a disabled
|
||||
entity has a name there but no state)."""
|
||||
import websocket
|
||||
ws = websocket.create_connection(WS, timeout=20)
|
||||
try:
|
||||
ws.recv()
|
||||
ws.send(json.dumps({"type": "auth", "access_token": os.environ.get("SUPERVISOR_TOKEN", "")}))
|
||||
if json.loads(ws.recv()).get("type") != "auth_ok":
|
||||
raise OSError("Home Assistant refused the add-on's token")
|
||||
ws.send(json.dumps({"id": 1, "type": "config/entity_registry/list"}))
|
||||
while True:
|
||||
m = json.loads(ws.recv())
|
||||
if m.get("id") == 1:
|
||||
break
|
||||
finally:
|
||||
ws.close()
|
||||
entries = m.get("result") or []
|
||||
ids = {(x["entity_id"].split(".", 1)[0], x["platform"], x["unique_id"]): x["entity_id"] for x in entries}
|
||||
names = {x["entity_id"]: x.get("name") or x.get("original_name") for x in entries}
|
||||
return ids, names
|
||||
|
||||
|
||||
def expand(profile, device, name_of=None, ids=None):
|
||||
"""A profile's "ha" registers for one device: {n} the channel, {device}
|
||||
its id. ids: {(domain, platform, unique id): entity id} (HA's registry);
|
||||
name_of(entity) gives a control's name from HA (the circuit's)."""
|
||||
out = []
|
||||
ha = profile["ha"]
|
||||
for n in range(1, int(ha.get("channels", 1)) + 1):
|
||||
for t in ha["registers"]:
|
||||
r = {k: (v.replace("{n}", str(n)).replace("{device}", device) if isinstance(v, str) else v) for k, v in t.items()}
|
||||
r.update(table="ha", type="ha", address=0)
|
||||
if "unique_id" in r:
|
||||
key = (r["entity"].split(".", 1)[0], ha["domain"], r.pop("unique_id"))
|
||||
r["entity"] = (ids or {}).get(key, r["entity"])
|
||||
if r.get("write") and name_of:
|
||||
r["name"] = name_of(r["entity"]) or r["name"]
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def number(r, state):
|
||||
if r.get("write"):
|
||||
return {"on": 1, "off": 0}.get(state)
|
||||
try:
|
||||
return float(state)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
class HASource:
|
||||
def __init__(self, dev, states=None, service=None, energy=None):
|
||||
self.dev, self.path = dev, energy or ENERGY.format(dev["id"])
|
||||
self.states = states or (lambda: call("GET", "/states"))
|
||||
self.service = service or (lambda domain, svc, body: call("POST", f"/services/{domain}/{svc}", body))
|
||||
self.last = {} # key -> (time, power)
|
||||
try:
|
||||
with open(self.path) as f:
|
||||
self.energy = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
self.energy = {}
|
||||
|
||||
def read_values(self, regs, now=None):
|
||||
now = now or time.time()
|
||||
try:
|
||||
st = {s["entity_id"]: s["state"] for s in self.states()}
|
||||
except Exception as e: # HA restarting: nothing read this time
|
||||
return {}, {r["key"]: f"Home Assistant: {e}" for r in regs}
|
||||
values, errors = {}, {}
|
||||
for r in regs:
|
||||
if "entity" in r:
|
||||
v = number(r, st.get(r["entity"]))
|
||||
if v is None:
|
||||
errors[r["key"]] = f"{r['entity']}: {st.get(r['entity'], 'missing')}"
|
||||
else:
|
||||
values[r["key"]] = v
|
||||
changed = False
|
||||
for r in regs:
|
||||
if "integrate" not in r:
|
||||
continue
|
||||
k = f"{self.dev['id']}/{r['key']}"
|
||||
p = values.get(r["integrate"])
|
||||
if p is not None:
|
||||
t0, p0 = self.last.get(r["key"], (None, None))
|
||||
if t0 is not None and 0 < now - t0 <= GAP_S:
|
||||
self.energy[k] = self.energy.get(k, 0.0) + (p + p0) / 2 * (now - t0) / 3600
|
||||
changed = True
|
||||
self.last[r["key"]] = (now, p)
|
||||
if k in self.energy:
|
||||
values[r["key"]] = round(self.energy[k], 1)
|
||||
if changed:
|
||||
tmp = self.path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(self.energy, f)
|
||||
os.replace(tmp, self.path)
|
||||
return values, errors
|
||||
|
||||
def write_value(self, r, v):
|
||||
if "entity" not in r or not r.get("write"):
|
||||
raise mb.ModbusError(f"{r['key']} is not written")
|
||||
domain = r["entity"].split(".", 1)[0]
|
||||
try:
|
||||
self.service(domain, "turn_on" if v else "turn_off", {"entity_id": r["entity"]})
|
||||
except Exception as e:
|
||||
raise mb.ModbusError(f"Home Assistant: {e}") from None
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,438 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The add-on's page (ingress): a list of devices, and per device (#<id>, so a
|
||||
reload stays there) its values in sets, its channels as tiles, an inverter's
|
||||
power flow, sparklines of the last hour, and its controls with their
|
||||
protection. Plain HTML, CSS and SVG; HA's light and dark; English and German
|
||||
(the browser's language).
|
||||
|
||||
Value sets: a register's "group", else its key's first word; a set of one
|
||||
value is a line, not a card. Registers with "bits" are under "details"
|
||||
unless not zero. Keys ending _<n> on two or more channels are a channel grid
|
||||
(SPM circuits). The bridge's derived values (modbus.derived) come like
|
||||
registers. A profile's "view": {"headline": [refs], "flow": {"pv", "grid",
|
||||
"load", "battery", "soc", "bypass": ref}, "energy": [refs]}; a ref is a
|
||||
register key or a quantity (the register that gives it). The rest of the
|
||||
view (card, values, channels) is for the dashboard in Home Assistant.
|
||||
|
||||
In HA's app panel the page is in an iframe whose own address has no
|
||||
#<device>: the parent's hash is read at start and kept in step.
|
||||
"""
|
||||
import html
|
||||
import re
|
||||
import time
|
||||
|
||||
e = html.escape
|
||||
HIST_MIN = 60 # sparklines: the last hour, a value a minute
|
||||
|
||||
T = {
|
||||
"en": {"title": "Cantabile devices", "back": "All devices", "online": "online", "offline": "offline",
|
||||
"ro": "read only", "sim": "simulated", "every": "every {} s", "ha": "Home Assistant",
|
||||
"prot_sum": "{} of {} controls protected", "no_controls": "no controls", "values": "Values",
|
||||
"controls": "Controls", "details": "Details", "total": "Total", "on_of": "{} of {} on",
|
||||
"protected": "protected", "none": "not protected", "sealed": "sealed", "lift": "Lift",
|
||||
"protect": "Protect", "protect_all": "Protect all", "never_off": "Off refused", "all_refused": "every command refused",
|
||||
"confirm": "Lift the protection of {}? Cantabile may then switch it.", "history": "Protection changes",
|
||||
"none_yet": "none yet", "lock": "set by Cantabile, locked", "pv": "Solar", "grid": "Grid", "load": "Output",
|
||||
"battery": "Battery", "inverter": "Inverter", "charging": "charging", "discharging": "discharging",
|
||||
"energy": "Energy", "intro": "A <b>protected</b> control refuses the commands that would switch it off; "
|
||||
"only you lift a protection, here, one control at a time. <b>Sealed</b> ones are set by Cantabile and locked.",
|
||||
"ro_note": "Read only: commands are checked and logged, never written.", "voltage": "Voltage", "circuit": "Circuit {}", "all": "All:",
|
||||
"bypass": "bypass", "bypass_est": "via bypass, estimated"},
|
||||
"de": {"title": "Cantabile-Geräte", "back": "Alle Geräte", "online": "online", "offline": "offline",
|
||||
"ro": "nur lesen", "sim": "simuliert", "every": "alle {} s", "ha": "Home Assistant",
|
||||
"prot_sum": "{} von {} Steuerungen geschützt", "no_controls": "keine Steuerungen", "values": "Werte",
|
||||
"controls": "Steuerungen", "details": "Details", "total": "Gesamt", "on_of": "{} von {} an",
|
||||
"protected": "geschützt", "none": "nicht geschützt", "sealed": "versiegelt", "lift": "Aufheben",
|
||||
"protect": "Schützen", "protect_all": "Alle schützen", "never_off": "Aus wird abgelehnt", "all_refused": "jeder Befehl abgelehnt",
|
||||
"confirm": "Schutz von {} aufheben? Cantabile darf es dann schalten.", "history": "Änderungen am Schutz",
|
||||
"none_yet": "noch keine", "lock": "von Cantabile gesetzt, gesperrt", "pv": "Solar", "grid": "Netz", "load": "Ausgang",
|
||||
"battery": "Batterie", "inverter": "Wechselrichter", "charging": "lädt", "discharging": "entlädt",
|
||||
"energy": "Energie", "intro": "Eine <b>geschützte</b> Steuerung lehnt Befehle ab, die sie ausschalten würden; "
|
||||
"nur Sie heben einen Schutz auf, hier, je Steuerung. <b>Versiegelte</b> setzt Cantabile, sie sind gesperrt.",
|
||||
"ro_note": "Nur lesen: Befehle werden geprüft und protokolliert, nie geschrieben.", "voltage": "Spannung",
|
||||
"circuit": "Stromkreis {}", "all": "Alle:",
|
||||
"bypass": "Bypass", "bypass_est": "über Bypass, geschätzt"},
|
||||
}
|
||||
|
||||
CSS = """:root{--bg:#f6f8f7;--fg:#1d2a24;--card:#fff;--line:#d5ded9;--soft:#e3e9e5;--mute:#5a6b62;--acc:#2f6f55;--prot:#1f6b45;--warn:#7a4b00;--bar:#cfe3d8}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#111915;--fg:#e3ebe6;--card:#18221d;--line:#2b3a32;--soft:#22302a;--mute:#9fb0a6;--acc:#5fb38c;--prot:#7fd1a6;--warn:#e0a54a;--bar:#2c4a3b}}
|
||||
body{font-family:system-ui,sans-serif;margin:0;padding:16px;overflow-wrap:anywhere;max-width:56rem;color:var(--fg);background:var(--bg)}
|
||||
h2{margin:.2rem 0 1rem}h3{margin:0 0 .4rem;font-size:1rem}a{color:inherit}
|
||||
.card{background:var(--card);border:1px solid var(--line);border-radius:8px;padding:.7rem .8rem;margin:.5rem 0}
|
||||
a.card{display:block;text-decoration:none}a.card:hover{border-color:var(--acc)}
|
||||
.row{display:flex;flex-wrap:wrap;gap:.3rem .9rem;align-items:baseline}.grow{flex:1}
|
||||
.note{color:var(--mute);font-size:.88rem}.big{font-size:1.5rem;font-weight:600}.small{font-size:.82rem;color:var(--mute)}
|
||||
.badge{display:inline-block;font-size:.75rem;padding:.05rem .45rem;border-radius:9px;background:var(--soft);color:var(--mute)}
|
||||
.ok{color:var(--prot)}.bad{color:var(--warn)}.prot{background:var(--bar);color:var(--prot);font-weight:600}.lock{color:var(--warn)}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(10.5rem,100%),1fr));gap:.5rem}
|
||||
.tiles{grid-template-columns:repeat(auto-fill,minmax(min(8rem,100%),1fr))}.tiles .card{padding:.45rem .6rem}
|
||||
table.sparks td{border:0;padding:.15rem .4rem;vertical-align:middle}table.sparks td:first-child{width:40%}
|
||||
.sets{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(14rem,100%),1fr));gap:.5rem}
|
||||
.bar{height:6px;border-radius:3px;background:var(--soft);margin:.3rem 0}.bar i{display:block;height:100%;border-radius:3px;background:var(--acc)}
|
||||
table{border-collapse:collapse;width:100%}td,th{text-align:left;padding:.3rem .4rem;border-bottom:1px solid var(--soft);font-size:.9rem}
|
||||
td.v{text-align:right;white-space:nowrap}
|
||||
button{font:inherit;font-size:.82rem;padding:.2rem .7rem;border:0;border-radius:6px;background:var(--acc);color:#fff;cursor:pointer}
|
||||
button.off{background:var(--soft);color:var(--fg)}form{display:inline;margin:0}
|
||||
details summary{cursor:pointer;color:var(--mute);font-size:.88rem}pre{white-space:pre-wrap;font-size:.8rem}
|
||||
section.dev{display:none}section.dev:target{display:block}body:has(section.dev:target) #list{display:none}
|
||||
svg text{fill:var(--fg);font-size:12px}svg text.sub{font-size:9.5px}svg .mute{fill:var(--mute)}svg .ln{stroke:var(--acc);fill:none}svg .box{fill:var(--card);stroke:var(--line)}
|
||||
svg .soc{fill:var(--acc)}svg .spark{stroke:var(--acc);fill:none;stroke-width:1.5}"""
|
||||
|
||||
|
||||
# HA's app panel shows the page in an iframe (same origin) without the
|
||||
# #<device> of its own address: take the parent's at start and keep both in
|
||||
# step, so a link, back and reload land on the device. Reload every 30 s.
|
||||
SCRIPT = """(function(){var P=null;try{if(window.parent!==window){P=window.parent;P.location.hash}}catch(x){P=null}
|
||||
function dev(h){return h&&h.length>1&&document.getElementById(decodeURIComponent(h.slice(1)))?h:''}
|
||||
if(P&&!location.hash){var h=dev(P.location.hash);if(h)location.replace(h)}
|
||||
if(P){window.addEventListener('hashchange',function(){try{var h=location.hash;if(P.location.hash!==h&&!(h===''&&P.location.hash==='#'))P.location.hash=h}catch(x){}});
|
||||
P.addEventListener('hashchange',function(){var h=dev(P.location.hash);if(h!==location.hash&&!(h===''&&location.hash==='#'))location.hash=h})}
|
||||
setTimeout(function(){location.reload()},30000)})();"""
|
||||
|
||||
|
||||
def lang_of(accept):
|
||||
return "de" if (accept or "").lower().startswith("de") else "en"
|
||||
|
||||
|
||||
def num(s):
|
||||
try:
|
||||
return float(s)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def fmt(v, unit):
|
||||
"""A value for people: W to kW and Wh to kWh above 1000, sensible digits."""
|
||||
x = num(v)
|
||||
if x is None:
|
||||
return "–" if v is None else e(str(v))
|
||||
if unit == "Wh":
|
||||
return f"{x / 1000:,.1f} kWh" if abs(x) >= 1000 else f"{x:.0f} Wh"
|
||||
if unit == "W":
|
||||
return f"{x / 1000:.2f} kW" if abs(x) >= 1000 else f"{x:.0f} W" if abs(x) >= 100 or x == 0 else f"{x:.1f} W"
|
||||
digits = {"V": 1, "A": 2, "%": 0, "°C": 1, "Hz": 2}.get(unit, 2)
|
||||
s = f"{x:.{digits}f}"
|
||||
return f"{s} {e(unit)}" if unit else s
|
||||
|
||||
|
||||
def channel_of(key):
|
||||
m = re.fullmatch(r"(.+)_(\d+)", key)
|
||||
return (m.group(1), int(m.group(2))) if m else (None, None)
|
||||
|
||||
|
||||
def is_switch(r):
|
||||
return set((r.get("write") or {}).get("options") or {}) == {"0", "1"}
|
||||
|
||||
|
||||
class View:
|
||||
"""One device's values for the page: the registers' and the derived ones
|
||||
(the bridge publishes both; energy comes in kWh, kept here in Wh), and
|
||||
their last hour."""
|
||||
|
||||
def __init__(self, dev, values, hist):
|
||||
self.dev, self.hist = dev, hist
|
||||
self.regs = {r["key"]: r for r in dev["registers"]}
|
||||
self.regs.update({d["key"]: dict(d, type="derived") for d in dev.get("derived") or []})
|
||||
self.v = {k: values.get(f"{dev['id']}/{k}") for k in self.regs}
|
||||
for k, r in self.regs.items():
|
||||
if r.get("unit") == "Wh" and num(self.v[k]) is not None:
|
||||
self.v[k] = num(self.v[k]) * 1000
|
||||
# the view's references as register keys (a quantity: its register)
|
||||
by_q = {}
|
||||
for k, r in self.regs.items():
|
||||
if r.get("quantity"):
|
||||
by_q.setdefault(r["quantity"], k)
|
||||
v = dev.get("view") or {}
|
||||
ref = lambda x: by_q.get(x, x) if isinstance(x, str) else x # noqa: E731
|
||||
self.view = dict(v, headline=[ref(x) for x in v.get("headline") or []],
|
||||
energy=[ref(x) for x in v.get("energy") or []])
|
||||
if v.get("flow"):
|
||||
self.view["flow"] = {k: ref(x) for k, x in v["flow"].items()}
|
||||
|
||||
def series(self, key):
|
||||
"""[value per minute] of the last hour."""
|
||||
now = int(time.time() // 60)
|
||||
return [self.hist.get(f"{self.dev['id']}/{key}", {}).get(m) for m in range(now - HIST_MIN + 1, now + 1)]
|
||||
|
||||
def channels(self):
|
||||
"""{n: {base: key}} when two or more channels carry values."""
|
||||
ch = {}
|
||||
for k, r in self.regs.items():
|
||||
base, n = channel_of(k)
|
||||
if n is not None:
|
||||
ch.setdefault(n, {})[base] = k
|
||||
valued = {n: c for n, c in ch.items() if any(not self.regs[k].get("write") for k in c.values())}
|
||||
return valued if len(valued) >= 2 else {}
|
||||
|
||||
def headline(self, t):
|
||||
out = []
|
||||
for k in self.view.get("headline") or []:
|
||||
if k in self.regs:
|
||||
out.append((self.regs[k].get("name") or k, fmt(self.v.get(k), self.regs[k].get("unit", ""))))
|
||||
ch = self.channels()
|
||||
if not out and ch:
|
||||
tot = sum(num(self.v.get(c.get("power"))) or 0 for c in ch.values())
|
||||
out.append((t["total"], fmt(tot, "W")))
|
||||
sw = [k for k, r in self.regs.items() if is_switch(r)]
|
||||
if len(sw) >= 3 and not ch:
|
||||
on = sum(1 for k in sw if str(self.v.get(k)) == (self.regs[k]["write"]["options"]["1"]))
|
||||
out.append(("", t["on_of"].format(on, len(sw))))
|
||||
return out
|
||||
|
||||
|
||||
def spark(vals, w=120, h=26):
|
||||
pts = [(i, v) for i, v in enumerate(vals) if v is not None]
|
||||
if len(pts) < 2:
|
||||
return ""
|
||||
lo, hi = min(v for _, v in pts), max(v for _, v in pts)
|
||||
span = (hi - lo) or 1
|
||||
xy = " ".join(f"{i * w / (len(vals) - 1):.1f},{h - 2 - (v - lo) / span * (h - 4):.1f}" for i, v in pts)
|
||||
return f"<svg width={w} height={h} viewBox='0 0 {w} {h}' aria-hidden=true><polyline class=spark points='{xy}'/></svg>"
|
||||
|
||||
|
||||
def flow(vw):
|
||||
"""The flow's powers: pv, grid (into the inverter +), load, battery
|
||||
(charge +), soc, and whether the grid figure is estimated: with the
|
||||
bypass on the utility feeds the output directly, which no register
|
||||
counts (the grid register is the utility's charging power only)."""
|
||||
f = vw.view["flow"]
|
||||
p = {k: num(vw.v.get(f.get(k))) for k in ("pv", "grid", "load", "battery", "soc")}
|
||||
p["bypass"] = bool(num(vw.v.get(f.get("bypass")))) # the grid's value then includes the output (estimated)
|
||||
return p
|
||||
|
||||
|
||||
def flow_svg(vw, t):
|
||||
"""Four nodes around the inverter: solar above, grid left, output right,
|
||||
battery below (its charge as a bar inside); each arrow along the flow."""
|
||||
p = flow(vw)
|
||||
bp, soc = p["battery"], p["soc"]
|
||||
|
||||
def width(x):
|
||||
return 1.5 + min(6, abs(x or 0) / 300)
|
||||
|
||||
def line(x1, y1, x2, y2, power):
|
||||
"""From (x1, y1) to (x2, y2) when power > 0, the other way when < 0."""
|
||||
if not power or abs(power) < 1:
|
||||
return f"<line x1={x1} y1={y1} x2={x2} y2={y2} class=ln stroke-width=1 stroke-dasharray='3 4' opacity=.5 />"
|
||||
if power < 0:
|
||||
x1, y1, x2, y2 = x2, y2, x1, y1
|
||||
return f"<line x1={x1} y1={y1} x2={x2} y2={y2} class=ln stroke-width={width(power):.1f} marker-end='url(#arr)'/>"
|
||||
|
||||
def node(cx, cy, label, value, sub=""):
|
||||
return (f"<rect x={cx - 56} y={cy - 26} width=112 height=52 rx=8 class=box />"
|
||||
f"<text x={cx} y={cy - 8} text-anchor=middle class=mute>{e(label)}</text>"
|
||||
f"<text x={cx} y={cy + 9} text-anchor=middle font-weight=600>{value}</text>"
|
||||
+ (f"<text x={cx} y={cy + 22} text-anchor=middle class='mute sub'>{e(sub)}</text>" if sub else ""))
|
||||
grid_sub = t["bypass_est"] if p["bypass"] else ""
|
||||
bat_sub = t["charging"] if (bp or 0) >= 1 else t["discharging"] if (bp or 0) <= -1 else ""
|
||||
bat_label = t["battery"] + (f" · {soc:.0f} %" if soc is not None else "")
|
||||
socbar = ""
|
||||
if soc is not None:
|
||||
w = max(0, min(100, soc)) * 0.96
|
||||
socbar = (f"<rect x=132 y=299 width=96 height=5 rx=2 class=box /><rect x=132 y=299 width={w:.1f} height=5 rx=2 class=soc />")
|
||||
# inverter 130..230 x 124..176 (centre 180,150); nodes 46 px away from it on each side
|
||||
return "".join([
|
||||
"<svg viewBox='0 0 360 316' width=100% style='max-width:30rem' role=img>",
|
||||
"<defs><marker id=arr viewBox='0 0 10 10' refX=9 refY=5 markerWidth=5 markerHeight=5 orient=auto>"
|
||||
"<path d='M0,0L10,5L0,10z' class=soc /></marker></defs>",
|
||||
line(180, 54, 180, 124, p["pv"]), # solar -> inverter
|
||||
line(112, 150, 130, 150, p["grid"]), # grid -> inverter (+)
|
||||
line(230, 150, 248, 150, p["load"]), # inverter -> output
|
||||
line(180, 176, 180, 246, bp), # inverter -> battery (charge +)
|
||||
node(180, 28, t["pv"], fmt(p["pv"], "W")),
|
||||
node(56, 150, t["grid"], ("≈ " if p["bypass"] else "") + fmt(p["grid"], "W"), grid_sub),
|
||||
f"<rect x=130 y=124 width=100 height=52 rx=8 class=box /><text x=180 y={148 if not p['bypass'] else 144} text-anchor=middle font-weight=600>{t['inverter']}</text>"
|
||||
+ (f"<text x=180 y=162 text-anchor=middle class='mute sub'>{t['bypass']}</text>" if p["bypass"] else ""),
|
||||
node(304, 150, t["load"], fmt(p["load"], "W")),
|
||||
f"<rect x=124 y=246 width=112 height=64 rx=8 class=box />"
|
||||
f"<text x=180 y=264 text-anchor=middle class=mute>{e(bat_label)}</text>"
|
||||
f"<text x=180 y=281 text-anchor=middle font-weight=600>{fmt(abs(bp) if bp is not None else None, 'W')}</text>"
|
||||
f"<text x=180 y=294 text-anchor=middle class='mute sub'>{e(bat_sub)}</text>",
|
||||
socbar, "</svg>"])
|
||||
|
||||
|
||||
def badge(level, refuse, t):
|
||||
if level == "sealed":
|
||||
return f"<span class='badge lock'>🔒 {t['sealed']}</span>"
|
||||
if level == "protected":
|
||||
what = t["never_off"] if refuse is not None and set(refuse) == {0.0} else t["all_refused"]
|
||||
return f"<span class='badge prot' title='{e(what)}'>{t['protected']} · {e(what)}</span>"
|
||||
return f"<span class=badge>{t['none']}</span>"
|
||||
|
||||
|
||||
def toggle(dev, r, level, t):
|
||||
if level == "sealed":
|
||||
return f"<span class='small lock'>{t['lock']}</span>"
|
||||
name = r.get("name") or r["key"]
|
||||
if level == "protected":
|
||||
msg = t["confirm"].format(name).replace("'", "’")
|
||||
return (f"<form method=post action=protect onsubmit=\"return confirm('{e(msg)}')\"><input type=hidden name=dev value='{e(dev['id'])}'>"
|
||||
f"<input type=hidden name=key value='{e(r['key'])}'><input type=hidden name=level value=none>"
|
||||
f"<button class=off>{t['lift']}</button></form>")
|
||||
return (f"<form method=post action=protect><input type=hidden name=dev value='{e(dev['id'])}'>"
|
||||
f"<input type=hidden name=key value='{e(r['key'])}'><input type=hidden name=level value=protected>"
|
||||
f"<button>{t['protect']}</button></form>")
|
||||
|
||||
|
||||
def controls(dev, vw, level_of, refuse_of, t):
|
||||
ctl = [r for r in dev["registers"] if r.get("write")]
|
||||
if not ctl:
|
||||
return ""
|
||||
prot = dev.get("protection") or {}
|
||||
notes = {(prot.get(r["key"]) or prot.get("*") or {}).get("note", "") for r in ctl}
|
||||
out = [f"<div class=card><h3>{t['controls']}</h3>"]
|
||||
if len(notes) == 1 and next(iter(notes)):
|
||||
out.append(f"<p class=note>{e(next(iter(notes)))}</p>")
|
||||
if dev.get("read_only"):
|
||||
out.append(f"<p class=note>{t['ro_note']}</p>")
|
||||
levels = {r["key"]: level_of(dev, r["key"]) for r in ctl}
|
||||
if len(ctl) >= 8 and all(is_switch(r) for r in ctl):
|
||||
same = len({(levels[r["key"]], str(refuse_of(dev, r["key"]))) for r in ctl}) == 1
|
||||
if same:
|
||||
out.append(f"<p>{t['all']} {badge(levels[ctl[0]['key']], refuse_of(dev, ctl[0]['key']), t)}</p>")
|
||||
out.append("<div class='grid tiles'>")
|
||||
for r in ctl:
|
||||
on = str(vw.v.get(r["key"])) == r["write"]["options"]["1"]
|
||||
out.append(f"<div class=card style='margin:0'><div class=row><b class=grow>{e(r.get('name') or r['key'])}</b>"
|
||||
f"<span class={'ok' if on else 'small'}>{e(str(vw.v.get(r['key']) or '–'))}</span></div>"
|
||||
f"<div class=row style='margin-top:.2rem'>{'' if same else badge(levels[r['key']], refuse_of(dev, r['key']), t)}"
|
||||
f"<span class=grow></span>{toggle(dev, r, levels[r['key']], t)}</div></div>")
|
||||
out.append("</div>")
|
||||
else:
|
||||
out.append("<table>")
|
||||
for r in ctl:
|
||||
n = (prot.get(r["key"]) or {}).get("note", "") if len(notes) > 1 else ""
|
||||
out.append(f"<tr><td>{e(r.get('name') or r['key'])}" + (f"<br><span class=small>{e(n)}</span>" if n else "")
|
||||
+ f"</td><td>{e(str(vw.v.get(r['key']) or '–'))}</td><td>{badge(levels[r['key']], refuse_of(dev, r['key']), t)}</td>"
|
||||
f"<td class=v>{toggle(dev, r, levels[r['key']], t)}</td></tr>")
|
||||
out.append("</table>")
|
||||
if sum(1 for lv in levels.values() if lv == "none") >= 2:
|
||||
out.append(f"<p><form method=post action=protect><input type=hidden name=dev value='{e(dev['id'])}'>"
|
||||
f"<input type=hidden name=key value='*'><input type=hidden name=level value=protected>"
|
||||
f"<button>{t['protect_all']}</button></form></p>")
|
||||
out.append("</div>")
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def value_sets(vw, skip, t):
|
||||
"""The values not shown elsewhere, in sets; one value: a line."""
|
||||
groups, bits = {}, []
|
||||
for k, r in vw.regs.items():
|
||||
if r.get("write") or k in skip or r.get("type") == "string":
|
||||
continue
|
||||
if r.get("bits"):
|
||||
x = num(vw.v.get(k))
|
||||
if not x:
|
||||
bits.append((r, vw.v.get(k)))
|
||||
continue
|
||||
groups.setdefault(r.get("group") or k.split("_")[0].capitalize(), []).append(r)
|
||||
cards, lines = [], []
|
||||
for g, rs in groups.items():
|
||||
if len(rs) == 1:
|
||||
r = rs[0]
|
||||
lines.append(f"<div class=row><span class=grow>{e(r.get('name') or r['key'])}</span><b>{fmt(vw.v.get(r['key']), r.get('unit', ''))}</b></div>")
|
||||
continue
|
||||
rows = "".join(f"<tr><td>{e(r.get('name') or r['key'])}</td><td class=v>{fmt(vw.v.get(r['key']), r.get('unit', ''))}"
|
||||
+ (f"<br>{spark(vw.series(r['key']), 80, 18)}" if r.get("unit") == "W" else "") + "</td></tr>" for r in rs)
|
||||
cards.append(f"<div class=card style='margin:0'><h3>{e(g)}</h3><table>{rows}</table></div>")
|
||||
out = ""
|
||||
if cards:
|
||||
out += f"<div class=sets>{''.join(cards)}</div>"
|
||||
if lines:
|
||||
out += f"<div class=card>{''.join(lines)}</div>"
|
||||
if bits:
|
||||
out += (f"<details class=card><summary>{t['details']}</summary><table>"
|
||||
+ "".join(f"<tr><td>{e(r.get('name') or r['key'])}</td><td class=v>{e(str(v if v is not None else '–'))}</td></tr>" for r, v in bits)
|
||||
+ "</table></details>")
|
||||
return out
|
||||
|
||||
|
||||
def channel_grid(vw, t):
|
||||
ch = vw.channels()
|
||||
pw = {n: num(vw.v.get(c.get("power"))) for n, c in ch.items()}
|
||||
total = sum(x or 0 for x in pw.values())
|
||||
volts = [num(vw.v.get(c.get("voltage"))) for c in ch.values() if c.get("voltage")]
|
||||
volts = [x for x in volts if x is not None]
|
||||
one_v = volts and max(volts) - min(volts) <= 5
|
||||
head = (f"<div class=card><div class=row><span class=grow>{t['total']}</span><span class=big>{fmt(total, 'W')}</span>"
|
||||
f"{spark([sum(x or 0 for x in s) if any(x is not None for x in s) else None for s in zip(*[vw.series(c['power']) for c in ch.values() if c.get('power')])])}</div>"
|
||||
+ (f"<div class=small>{t['voltage']} {fmt(sum(volts) / len(volts), 'V')}</div>" if one_v else "") + "</div>")
|
||||
tiles = []
|
||||
for n in sorted(ch):
|
||||
c = ch[n]
|
||||
sw = c.get("circuit") or next((k for k in c.values() if vw.regs[k].get("write")), None)
|
||||
name = (vw.regs[sw].get("name") if sw else None) or t["circuit"].format(n)
|
||||
state = f" <span class=small>{e(str(vw.v.get(sw) or '–'))}</span>" if sw else ""
|
||||
share = (pw[n] or 0) / total * 100 if total else 0
|
||||
small = [fmt(vw.v.get(c[b]), vw.regs[c[b]].get("unit", "")) for b in ("current", "energy") if c.get(b)]
|
||||
if c.get("voltage") and not one_v:
|
||||
small.append(fmt(vw.v.get(c["voltage"]), "V"))
|
||||
tiles.append(f"<div class=card style='margin:0'><div class=row><b class=grow>{e(name)}</b>{state}</div>"
|
||||
f"<div class=big>{fmt(pw[n], 'W')}</div><div class=bar><i style='width:{share:.0f}%'></i></div>"
|
||||
f"<div class=small>{' · '.join(small)}</div></div>")
|
||||
return head + f"<div class=grid>{''.join(tiles)}</div>", {k for c in ch.values() for k in c.values()}
|
||||
|
||||
|
||||
def device_view(dev, vw, status, level_of, refuse_of, t):
|
||||
out = [f"<section class=dev id='{e(dev['id'])}'><p><a href='#'>← {t['back']}</a></p>",
|
||||
f"<h2>{e(dev['name'])}</h2><p class=note>{e(dev['manufacturer'])} {e(dev['model'])} · {where(dev, t)} · "
|
||||
f"{t['every'].format(dev.get('poll_s', 10))} {state_badges(dev, status, t)}</p>"]
|
||||
skip = set()
|
||||
if vw.view.get("flow"):
|
||||
f = vw.view["flow"]
|
||||
skip |= {f.get(k) for k in ("pv", "grid", "load", "battery", "soc", "bypass")}
|
||||
for d in vw.dev.get("derived") or []:
|
||||
skip |= set(d.get("product") or [])
|
||||
sparks = "<table class=sparks>" + "".join(
|
||||
f"<tr><td>{e(vw.regs[k].get('name') or k)}</td><td class=v>{fmt(vw.v.get(k), 'W')}</td><td>{spark(vw.series(k), 160, 32)}</td></tr>"
|
||||
for k in (f.get("pv"), f.get("load"), f.get("battery"), f.get("grid")) if k in vw.regs) + "</table>"
|
||||
energy = " · ".join(f"{e(vw.regs[k].get('name') or k)} {fmt(vw.v.get(k), 'Wh')}" for k in vw.view.get("energy") or [] if k in vw.regs)
|
||||
skip |= set(vw.view.get("energy") or [])
|
||||
out.append(f"<div class=card>{flow_svg(vw, t)}{sparks}" + (f"<p class=small>{t['energy']}: {energy}</p>" if energy else "") + "</div>")
|
||||
if vw.channels():
|
||||
grid, used = channel_grid(vw, t)
|
||||
out.append(grid)
|
||||
skip |= used
|
||||
out.append(value_sets(vw, skip, t))
|
||||
out.append(controls(dev, vw, level_of, refuse_of, t))
|
||||
out.append("</section>")
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def where(dev, t):
|
||||
if dev.get("source") == "ha":
|
||||
return f"{t['ha']} ({e(dev.get('device', ''))})"
|
||||
return f"{e(dev['host'])}:{dev['port']} · unit {dev['unit_id']}"
|
||||
|
||||
|
||||
def state_badges(dev, status, t):
|
||||
b = [f"<span class='badge {'ok' if status == 'online' else 'bad'}'>{t['online'] if status == 'online' else t['offline']}</span>"] \
|
||||
if status else []
|
||||
if dev.get("read_only"):
|
||||
b.append(f"<span class=badge>{t['ro']}</span>")
|
||||
if dev.get("simulated"):
|
||||
b.append(f"<span class=badge>{t['sim']}</span>")
|
||||
return " ".join(b)
|
||||
|
||||
|
||||
def render(devs, values, statuses, hist, level_of, refuse_of, lang="en", plog=()):
|
||||
t = T.get(lang, T["en"])
|
||||
out = [f"<!doctype html><html lang={lang}><meta charset=utf-8><meta name=viewport content='width=device-width,initial-scale=1'>"
|
||||
f"<title>{t['title']}</title><style>{CSS}</style><body><div id=list><h2>{t['title']}</h2><p class=note>{t['intro']}</p>"]
|
||||
views = {d["id"]: View(d, values, hist) for d in devs}
|
||||
for d in devs:
|
||||
vw = views[d["id"]]
|
||||
ctl = [r for r in d["registers"] if r.get("write")]
|
||||
n_prot = sum(1 for r in ctl if level_of(d, r["key"]) in ("protected", "sealed"))
|
||||
heads = " · ".join((f"{e(k)} <b>{v}</b>" if k else f"<b>{v}</b>") for k, v in vw.headline(t))
|
||||
summary = t["prot_sum"].format(n_prot, len(ctl)) if ctl else t["no_controls"]
|
||||
out.append(f"<a class=card href='#{e(d['id'])}'><div class=row><h3 class=grow>{e(d['name'])}</h3>"
|
||||
f"{state_badges(d, statuses.get(d['id']), t)}</div>"
|
||||
f"<div class=note>{e(d['model'])} · {where(d, t)}</div>"
|
||||
+ (f"<div style='margin:.3rem 0'>{heads}</div>" if heads else "")
|
||||
+ f"<div class=small>{summary}</div></a>")
|
||||
out.append(f"<details class=card><summary>{t['history']}</summary><pre>{e(chr(10).join(plog)) or t['none_yet']}</pre></details></div>")
|
||||
for d in devs:
|
||||
out.append(device_view(d, views[d["id"]], statuses.get(d["id"]), level_of, refuse_of, t))
|
||||
out.append("<script>" + SCRIPT + "</script></body></html>")
|
||||
return "".join(out).encode()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,125 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""A Modbus TCP device from a profile's register map, for showing the bridge
|
||||
without the real device (the add-on's "simulate" option): one server per
|
||||
device on 127.0.0.1, answering reads (functions 1-4) and writes (5, 6 and
|
||||
16) of the profile's registers and coils. Values come from a trace (a device's history
|
||||
as Home Assistant recorded it, one value per register key and step), played
|
||||
in a loop; a written control keeps the value written.
|
||||
|
||||
Trace (/share/cantabile/trace-<profile>.json):
|
||||
{"step_s": 60, "values": {"<register key>": [v0, v1, ...], ...}}
|
||||
"""
|
||||
import json
|
||||
import socketserver
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
|
||||
import cantabile_modbus as mb
|
||||
|
||||
|
||||
class Device:
|
||||
def __init__(self, profile, trace):
|
||||
self.regs = [r for r in profile["modbus"]["registers"] if r["type"] != "string"]
|
||||
self.trace = trace or {"step_s": 60, "values": {}}
|
||||
self.written = {}
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def value(self, r):
|
||||
if r["key"] in self.written:
|
||||
return self.written[r["key"]]
|
||||
vs = self.trace["values"].get(r["key"]) or [0]
|
||||
i = int(time.time() // max(1, self.trace.get("step_s", 60))) % len(vs)
|
||||
return vs[i] if vs[i] is not None else 0
|
||||
|
||||
def words(self, table, start, count):
|
||||
out = {}
|
||||
for r in self.regs:
|
||||
if r.get("table", "holding") != table:
|
||||
continue
|
||||
try:
|
||||
ws = mb.encode(r, self.value(r))
|
||||
except mb.ModbusError:
|
||||
ws = [0] * mb.size(r)
|
||||
for i, w in enumerate(ws):
|
||||
out[r["address"] + i] = w
|
||||
return [out.get(a, 0) for a in range(start, start + count)]
|
||||
|
||||
def write(self, start, words, table="holding"):
|
||||
with self.lock:
|
||||
for r in self.regs:
|
||||
if r.get("write") and r.get("table", "holding") == table and r["address"] == start \
|
||||
and len(words) >= mb.size(r):
|
||||
self.written[r["key"]] = mb.decode(r, words)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def handler(dev, unit):
|
||||
class H(socketserver.BaseRequestHandler):
|
||||
def handle(self):
|
||||
s = self.request
|
||||
while True:
|
||||
head = recv(s, 7)
|
||||
if not head:
|
||||
return
|
||||
tid, _proto, length, uid = struct.unpack(">HHHB", head)
|
||||
pdu = recv(s, length - 1)
|
||||
if not pdu:
|
||||
return
|
||||
fc = pdu[0]
|
||||
if uid != unit:
|
||||
reply = bytes([fc | 0x80, 11])
|
||||
elif fc in (1, 2):
|
||||
start, count = struct.unpack(">HH", pdu[1:5])
|
||||
bits = dev.words("coil" if fc == 1 else "discrete", start, count)
|
||||
packed = bytes(sum(b << i for i, b in enumerate(bits[j:j + 8]) if b) for j in range(0, count, 8))
|
||||
reply = bytes([fc, len(packed)]) + packed
|
||||
elif fc == 5:
|
||||
start, w = struct.unpack(">HH", pdu[1:5])
|
||||
reply = pdu[:5] if dev.write(start, [1 if w == 0xFF00 else 0], "coil") else bytes([fc | 0x80, 2])
|
||||
elif fc in (3, 4):
|
||||
start, count = struct.unpack(">HH", pdu[1:5])
|
||||
ws = dev.words("holding" if fc == 3 else "input", start, count)
|
||||
reply = bytes([fc, 2 * count]) + struct.pack(f">{count}H", *ws)
|
||||
elif fc == 6:
|
||||
start, w = struct.unpack(">HH", pdu[1:5])
|
||||
reply = pdu[:5] if dev.write(start, [w]) else bytes([fc | 0x80, 2])
|
||||
elif fc == 16:
|
||||
start, count = struct.unpack(">HH", pdu[1:5])
|
||||
ws = list(struct.unpack(f">{count}H", pdu[6:6 + 2 * count]))
|
||||
reply = pdu[:5] if dev.write(start, ws) else bytes([fc | 0x80, 2])
|
||||
else:
|
||||
reply = bytes([fc | 0x80, 1])
|
||||
s.sendall(struct.pack(">HHHB", tid, 0, len(reply) + 1, uid) + reply)
|
||||
return H
|
||||
|
||||
|
||||
def recv(s, n):
|
||||
out = b""
|
||||
while len(out) < n:
|
||||
c = s.recv(n - len(out))
|
||||
if not c:
|
||||
return b""
|
||||
out += c
|
||||
return out
|
||||
|
||||
|
||||
class Server(socketserver.ThreadingTCPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
def serve(profile, trace, unit, port):
|
||||
"""Start one simulated device on 127.0.0.1:<port> (a thread)."""
|
||||
srv = Server(("127.0.0.1", port), handler(Device(profile, trace), unit))
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
return srv
|
||||
|
||||
|
||||
def load_trace(path):
|
||||
try:
|
||||
with open(path) as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
@@ -0,0 +1,16 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
configuration:
|
||||
devices:
|
||||
name: Geräte
|
||||
description: >-
|
||||
Je Gerät: sein Cantabile-Profil (z. B. hm8042-hybrid), ein Name, und
|
||||
für Modbus Adresse und Port seines Gateways und seine Modbus-ID; für
|
||||
ein Gerät aus Home Assistant (sonoff-spm) seine ID dort (device, z. B.
|
||||
ab00000001). Wahlweise: poll_s (Sekunden, mindestens 10), read_only
|
||||
(Befehle werden geprüft und protokolliert, nie geschrieben), simulate
|
||||
(nur dieses Gerät).
|
||||
simulate:
|
||||
name: Simulieren
|
||||
description: >-
|
||||
Für die Geräte aus einer Aufzeichnung antworten, statt sie zu lesen
|
||||
(zum Ausprobieren, ohne die echten Geräte zu berühren).
|
||||
@@ -0,0 +1,16 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
configuration:
|
||||
devices:
|
||||
name: Devices
|
||||
description: >-
|
||||
Each device: its Cantabile profile (e.g. hm8042-hybrid), a name, and
|
||||
for Modbus the address and port of its gateway and its Modbus id; for
|
||||
a device read from Home Assistant (sonoff-spm) its id there (device,
|
||||
e.g. ab00000001). Optional: poll_s (seconds, at least 10), read_only
|
||||
(commands are checked and logged, never written), simulate (this
|
||||
device only).
|
||||
simulate:
|
||||
name: Simulate
|
||||
description: >-
|
||||
Answer for the devices from a recorded trace instead of reading them
|
||||
(for trying the bridge without touching the real devices).
|
||||
Reference in new issue
Block a user