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,216 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Home Assistant connector: the WebSocket API only (no REST, no MQTT), so
|
||||
the agent needs nothing from HA but a token. Reconnects with backoff.
|
||||
|
||||
Read-only by construction: send() refuses every message type that is not
|
||||
in READ_ONLY. v1 adds exactly two ways past it:
|
||||
- call_service(), for an action the actuation guard allowed: it takes the
|
||||
guard's check (allowed(domain, service, entity)) and refuses anything it
|
||||
doesn't allow; nothing else in the agent calls services;
|
||||
- weather_forecast(): weather.get_forecasts, a service that only reads.
|
||||
and one for the dashboards Cantabile keeps for the owner (dashboards.py):
|
||||
- dashboard(): Lovelace dashboards whose url_path starts with "cantabile-"
|
||||
(create, change, delete only those it listed itself, their config), and
|
||||
HA's Energy preferences (the caller saves them only while they are empty:
|
||||
the owner's own are never overwritten).
|
||||
And for Cantabile's area (areas.py): create_area() and place_device(), a
|
||||
device's area only.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import random
|
||||
from collections.abc import Awaitable, Callable
|
||||
|
||||
import websockets
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
READ_ONLY = frozenset({
|
||||
"get_states",
|
||||
"get_panels",
|
||||
"get_config",
|
||||
"subscribe_events",
|
||||
"subscribe_entities",
|
||||
"config/entity_registry/list",
|
||||
"config/device_registry/list",
|
||||
"config/area_registry/list",
|
||||
"recorder/statistics_during_period",
|
||||
"recorder/list_statistic_ids",
|
||||
"ping",
|
||||
})
|
||||
|
||||
|
||||
# dashboard(): what it may send, and for which dashboards
|
||||
DASHBOARD = frozenset({"lovelace/dashboards/list", "lovelace/dashboards/create", "lovelace/dashboards/update",
|
||||
"lovelace/dashboards/delete", "lovelace/config", "lovelace/config/save",
|
||||
"energy/get_prefs", "energy/save_prefs"})
|
||||
OURS = "cantabile-"
|
||||
|
||||
|
||||
class HAError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class HAClient:
|
||||
def __init__(self, url: str, token: str):
|
||||
self.url, self._token = url, token
|
||||
self._ws = None
|
||||
self._id = 0
|
||||
self._pending: dict[int, asyncio.Future] = {}
|
||||
self._subs: dict[int, Callable[[dict], None]] = {}
|
||||
self.version = None
|
||||
self._our_dashboards: set[str] = set() # ids of "cantabile-" dashboards HA listed
|
||||
|
||||
async def connect(self):
|
||||
self._ws = await websockets.connect(self.url, max_size=64 * 1024 * 1024, ping_interval=30)
|
||||
hello = json.loads(await self._ws.recv())
|
||||
if hello.get("type") != "auth_required":
|
||||
raise HAError(f"unexpected greeting {hello.get('type')}")
|
||||
await self._ws.send(json.dumps({"type": "auth", "access_token": self._token}))
|
||||
ok = json.loads(await self._ws.recv())
|
||||
if ok.get("type") != "auth_ok":
|
||||
raise HAError("authentication failed") # never log the token
|
||||
self.version = ok.get("ha_version")
|
||||
self._reader = asyncio.create_task(self._read())
|
||||
|
||||
async def close(self):
|
||||
if self._ws:
|
||||
await self._ws.close()
|
||||
|
||||
async def _read(self):
|
||||
try:
|
||||
async for raw in self._ws:
|
||||
msg = json.loads(raw)
|
||||
# HA may coalesce several messages into one JSON array.
|
||||
for m in msg if isinstance(msg, list) else [msg]:
|
||||
self._dispatch(m)
|
||||
finally:
|
||||
for f in self._pending.values():
|
||||
if not f.done():
|
||||
f.set_exception(HAError("connection closed"))
|
||||
self._pending.clear()
|
||||
|
||||
def _dispatch(self, m: dict):
|
||||
if m.get("type") == "event" and m.get("id") in self._subs:
|
||||
self._subs[m["id"]](m["event"])
|
||||
elif m.get("type") in ("result", "pong") and m.get("id") in self._pending:
|
||||
f = self._pending.pop(m["id"])
|
||||
if m.get("type") == "pong" or m.get("success"):
|
||||
f.set_result(m.get("result"))
|
||||
else:
|
||||
f.set_exception(HAError(str(m.get("error"))))
|
||||
|
||||
async def send(self, type_: str, timeout: float = 60, _events=None, **fields):
|
||||
if type_ not in READ_ONLY:
|
||||
raise HAError(f"{type_} is not allowed: reads only (actions go through call_service)")
|
||||
return await self._send(type_, timeout, _events, **fields)
|
||||
|
||||
async def call_service(self, domain: str, service: str, entity_id: str, data: dict,
|
||||
allowed: Callable[[str, str, str], bool], timeout: float = 30):
|
||||
"""One action on one entity, only if the guard allows exactly it."""
|
||||
if not allowed(domain, service, entity_id):
|
||||
raise HAError(f"{domain}.{service} on {entity_id} is not allowed")
|
||||
return await self._send("call_service", timeout, domain=domain, service=service,
|
||||
service_data=dict(data), target={"entity_id": entity_id})
|
||||
|
||||
async def dashboard(self, type_: str, timeout: float = 30, **fields):
|
||||
"""Cantabile's own dashboards and the Energy preferences, nothing else."""
|
||||
if type_ not in DASHBOARD:
|
||||
raise HAError(f"{type_} is not a dashboard message")
|
||||
if type_ in ("lovelace/dashboards/create", "lovelace/config", "lovelace/config/save") \
|
||||
and not str(fields.get("url_path") or "").startswith(OURS):
|
||||
raise HAError(f"{type_}: only Cantabile's own dashboards ({OURS}*)")
|
||||
if type_ in ("lovelace/dashboards/update", "lovelace/dashboards/delete") \
|
||||
and fields.get("dashboard_id") not in self._our_dashboards:
|
||||
raise HAError(f"{type_}: not one of Cantabile's dashboards")
|
||||
r = await self._send(type_, timeout, **fields)
|
||||
if type_ == "lovelace/dashboards/list":
|
||||
self._our_dashboards = {d["id"] for d in r or [] if str(d.get("url_path", "")).startswith(OURS)}
|
||||
elif type_ == "lovelace/dashboards/create" and isinstance(r, dict) and r.get("id"):
|
||||
self._our_dashboards.add(r["id"])
|
||||
return r
|
||||
|
||||
async def create_area(self, name: str, icon: str) -> dict:
|
||||
"""An area (areas.py: "Cantabile"); nothing else in the area registry."""
|
||||
return await self._send("config/area_registry/create", 30, name=name, icon=icon)
|
||||
|
||||
async def place_device(self, device_id: str, area_id: str):
|
||||
"""A device's area and only that (areas.py: Cantabile's own devices)."""
|
||||
return await self._send("config/device_registry/update", 30, device_id=device_id, area_id=area_id)
|
||||
|
||||
async def is_admin(self, user_id: str) -> bool:
|
||||
"""Is this HA user an administrator (the owner, or in the admin
|
||||
group)? The add-on's pages: HA's ingress names the user
|
||||
(X-Remote-User-Id); only what that needs is kept from the list."""
|
||||
for u in await self._send("config/auth/list", 30) or []:
|
||||
if u.get("id") == user_id:
|
||||
return bool(u.get("is_active", True)) and (bool(u.get("is_owner"))
|
||||
or "system-admin" in (u.get("group_ids") or []))
|
||||
return False
|
||||
|
||||
async def weather_forecast(self, entity_id: str, kind: str = "hourly") -> list[dict]:
|
||||
"""A weather entity's forecast (a service that only reads)."""
|
||||
r = await self._send("call_service", 30, domain="weather", service="get_forecasts",
|
||||
service_data={"type": kind}, target={"entity_id": entity_id}, return_response=True)
|
||||
return ((r or {}).get("response") or {}).get(entity_id, {}).get("forecast") or []
|
||||
|
||||
async def _send(self, type_: str, timeout: float = 60, _events=None, **fields):
|
||||
self._id += 1
|
||||
mid = self._id # taken before any await: sends may overlap
|
||||
fut = asyncio.get_running_loop().create_future()
|
||||
self._pending[mid] = fut
|
||||
if _events:
|
||||
self._subs[mid] = _events # events may arrive right after the result
|
||||
await self._ws.send(json.dumps({"id": mid, "type": type_, **fields}))
|
||||
return await asyncio.wait_for(fut, timeout)
|
||||
|
||||
async def subscribe(self, event_type: str, handler: Callable[[dict], None]):
|
||||
await self.send("subscribe_events", event_type=event_type, _events=handler)
|
||||
|
||||
async def subscribe_entities(self, entity_ids: list[str], handler: Callable[[dict], None]):
|
||||
"""Only these entities, in HA's compact form: first {"a": all},
|
||||
then {"c": changes}. Far less traffic than every state_changed."""
|
||||
await self.send("subscribe_entities", entity_ids=entity_ids, _events=handler)
|
||||
|
||||
async def wait_closed(self):
|
||||
await self._reader
|
||||
|
||||
async def registries(self) -> dict:
|
||||
return {
|
||||
"entities": await self.send("config/entity_registry/list"),
|
||||
"devices": await self.send("config/device_registry/list"),
|
||||
"areas": await self.send("config/area_registry/list"),
|
||||
}
|
||||
|
||||
|
||||
async def run_forever(url: str, token: str, on_connect: Callable[[HAClient], Awaitable[None]],
|
||||
stop: asyncio.Event):
|
||||
"""Keep a connection: on_connect runs after each (re)connect; backoff
|
||||
1 s doubling to 60 s with jitter, reset after a connection held 60 s."""
|
||||
wait = 1.0
|
||||
while not stop.is_set():
|
||||
client = HAClient(url, token)
|
||||
started = asyncio.get_running_loop().time()
|
||||
try:
|
||||
await client.connect()
|
||||
log.info("connected to Home Assistant %s", client.version)
|
||||
await on_connect(client)
|
||||
done, _ = await asyncio.wait([asyncio.ensure_future(client.wait_closed()),
|
||||
asyncio.ensure_future(stop.wait())],
|
||||
return_when=asyncio.FIRST_COMPLETED)
|
||||
except (OSError, HAError, websockets.WebSocketException, asyncio.TimeoutError) as e:
|
||||
log.warning("Home Assistant connection: %s", e)
|
||||
finally:
|
||||
await client.close()
|
||||
if stop.is_set():
|
||||
return
|
||||
if asyncio.get_running_loop().time() - started > 60:
|
||||
wait = 1.0
|
||||
delay = wait * (0.8 + 0.4 * random.random())
|
||||
log.info("reconnecting in %.1f s", delay)
|
||||
try:
|
||||
await asyncio.wait_for(stop.wait(), delay)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
wait = min(wait * 2, 60)
|
||||
Reference in new issue
Block a user