Files
cantabile-ha-addons/cantabile_modbus/ha_source.py
T

139 lines
5.8 KiB
Python

# 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