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,5 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Cantabile Edge Agent v0: reads Home Assistant,
|
||||
turns mapped entities into 1-minute telemetry and sends it upstream through
|
||||
a store-and-forward queue. v0 never acts on devices."""
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,4 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
from .cli import main
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,343 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The agent's run loop: HA connection -> aggregator -> queue -> uplink.
|
||||
|
||||
Three tasks: the HA connection (samples), the ticker (closes a window every
|
||||
interval and queues it) and the uploader (sends queued batches in order).
|
||||
They only share the aggregator and the queue, so an HA outage or an uplink
|
||||
outage never stops the others: telemetry waits in the queue until the
|
||||
uplink is back. Nothing is collected or sent without the owner's consent
|
||||
for the site (consent.py), on top of the mapping's per entity. With an MQTT
|
||||
broker (cfg.mqtt_host) the agent also shows itself in Home Assistant
|
||||
(announce.py): read only, its connection to the platform.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
from . import areas, ha, propose, sinks
|
||||
from .announce import Announcer
|
||||
from .consent import Consent
|
||||
from .controller import Controller
|
||||
from .inventory import Inventory
|
||||
from .dashboards import Dashboards
|
||||
from .devpage import App, Devices
|
||||
from .joinpage import Fleet
|
||||
from .mapping import Mapping, convert, scaled, value_of
|
||||
from .store import Queue
|
||||
from .telemetry import Aggregator
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
RESTART = 75 # the exit status that asks addon-run to start the agent again
|
||||
RESTART_DELAY_S = 1.0
|
||||
|
||||
|
||||
def number(state: str | None) -> float | None:
|
||||
try:
|
||||
v = float(state)
|
||||
except (TypeError, ValueError):
|
||||
return None # unavailable, unknown, text
|
||||
return v if v == v and abs(v) != float("inf") else None
|
||||
|
||||
|
||||
class Agent:
|
||||
def __init__(self, cfg, mapping: Mapping, queue: Queue, sink):
|
||||
self.cfg, self.mapping, self.queue, self.sink = cfg, mapping, queue, sink
|
||||
self.agg = Aggregator(cfg.interval_s)
|
||||
self.units: dict[str, str | None] = {}
|
||||
self.parts: dict[str, float | None] = {} # parts' last values (their totals: mapping.py)
|
||||
self.attrs: dict[str, dict] = {} # entity -> its last attributes (assets reading one)
|
||||
self.states: dict[str, str | None] = {}
|
||||
self.stop = asyncio.Event()
|
||||
self.inventory_now = asyncio.Event()
|
||||
self.consent = Consent(cfg.state_dir)
|
||||
self.last_sent = 0.0 # when a batch was last stored on the other side
|
||||
self.started = 0.0
|
||||
self.clock = time.time # tests set their own
|
||||
self.ha_language = "en" # HA's language (its config): names in HA (names.py)
|
||||
self.dashboards = Dashboards(self) if cfg.dashboards else None
|
||||
# v1: plans and actions for the mapping's controls (controller.py)
|
||||
self.control = Controller(cfg, mapping, self.consent, sink) if mapping.controls else None
|
||||
if self.control is not None and hasattr(sink, "on_command"):
|
||||
sink.on_command = self.control.command
|
||||
# the devices' specs for the cloud (inventory.py)
|
||||
self.inventory = Inventory(cfg, mapping, self.consent, sink,
|
||||
self.control.policy if self.control is not None else None)
|
||||
self.client = None
|
||||
self.exit_code = 0 # RESTART: start again (restart())
|
||||
# A mapping for a site without one (propose.py): the HA add-on
|
||||
self.profiles = propose.load_profiles() if cfg.propose else []
|
||||
|
||||
# -- the mapping ------------------------------------------------------
|
||||
async def ensure_mapping(self, client) -> bool:
|
||||
"""Import or propose a mapping while it is ours to write (propose.py);
|
||||
True when the mapping changed (loaded again at once)."""
|
||||
if not self.cfg.propose or propose.source_of(self.cfg.mapping) is None:
|
||||
return False
|
||||
states = await client.send("get_states") or []
|
||||
reg = await client.registries()
|
||||
done = await asyncio.to_thread(propose.ensure, self.cfg.mapping, self.cfg.state_dir, states, reg,
|
||||
self.profiles)
|
||||
if not done:
|
||||
return False
|
||||
try:
|
||||
m = Mapping.load(self.cfg.mapping)
|
||||
except Exception as e: # propose.write checked it; a hand edit since?
|
||||
log.warning("mapping not loaded again: %s", e)
|
||||
return False
|
||||
self.mapping = self.inventory.mapping = m
|
||||
if m.controls and self.control is None:
|
||||
log.info("the mapping has controls now: they are planned for after the next start")
|
||||
if self.dashboards is not None:
|
||||
self.dashboards.poke.set()
|
||||
self.inventory_now.set()
|
||||
return True
|
||||
|
||||
async def mapping_loop(self):
|
||||
"""New devices into a proposed mapping (every EVERY_S)."""
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
await asyncio.wait_for(self.stop.wait(), areas.EVERY_S)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
if self.client is not None and not self.stop.is_set():
|
||||
try:
|
||||
await self.ensure_mapping(self.client)
|
||||
except Exception as e:
|
||||
log.warning("mapping: %s", e)
|
||||
|
||||
def restart(self):
|
||||
"""Stop and be started again (exit RESTART: the HA add-on's addon-run
|
||||
starts the agent again), as the Hub's devices tool restarts it after
|
||||
a consent or control change: the consented entities' subscription
|
||||
and the controls' planner are made at start."""
|
||||
log.info("restarting for the devices' new consent or controls")
|
||||
self.exit_code = RESTART
|
||||
# a moment later: the page that asked answers first
|
||||
asyncio.get_running_loop().call_later(RESTART_DELAY_S, self.stop.set)
|
||||
|
||||
async def devices_changed(self, restart: bool = False):
|
||||
"""The add-on's Devices page wrote a device's fragment (devpage.py):
|
||||
the proposal yields to it, the mapping is loaded again, the device
|
||||
goes to the area "Cantabile" (without an area of its own) and onto
|
||||
the dashboard. restart: a consent or a control changed (as on the
|
||||
Hub, the agent starts again; restart())."""
|
||||
if restart:
|
||||
self.restart()
|
||||
return
|
||||
if self.client is not None:
|
||||
try:
|
||||
await self.ensure_mapping(self.client)
|
||||
except Exception as e:
|
||||
log.warning("mapping: %s", e)
|
||||
try:
|
||||
m = Mapping.load(self.cfg.mapping)
|
||||
except Exception as e:
|
||||
log.warning("mapping not loaded again: %s", e)
|
||||
return
|
||||
self.mapping = self.inventory.mapping = m
|
||||
if self.dashboards is not None:
|
||||
self.dashboards.poke.set()
|
||||
self.inventory_now.set()
|
||||
if self.client is not None:
|
||||
try:
|
||||
await areas.place(self.client, f"cantabile_{self.cfg.site_id}", self.ha_language,
|
||||
areas.used(self.cfg.state_dir))
|
||||
except Exception as e:
|
||||
log.warning("areas: %s", e)
|
||||
|
||||
# -- samples ----------------------------------------------------------
|
||||
def set_consent(self, share: bool, by: str):
|
||||
self.consent.set(share, by)
|
||||
log.info("consent to share energy data: %s (from %s)", "on" if share else "off", by)
|
||||
if not share:
|
||||
self.agg.flush(self.clock()) # the open window too
|
||||
self.queue.clear()
|
||||
|
||||
async def cloud(self) -> bool:
|
||||
"""The uplink's own word on its connection, else its last send."""
|
||||
q = getattr(self.sink, "cloud", None)
|
||||
if q is not None:
|
||||
return await q()
|
||||
return self.last_sent > 0
|
||||
|
||||
def sample(self, entity_id: str, state: str | None, ts: float):
|
||||
if not self.consent.share:
|
||||
return # the owner has not (or no longer) agreed
|
||||
for a in self.mapping.consented_all(entity_id): # none: not mapped or no consent, never leaves
|
||||
raw = value_of(a, state, self.attrs.get(entity_id))
|
||||
v = number(raw)
|
||||
if v is not None and not a.equals:
|
||||
# an attribute is in HA's units (a climate's temperature): the asset's own
|
||||
unit = a.unit if a.attribute else self.units.get(entity_id)
|
||||
v = scaled(convert(v, unit, a.unit), a)
|
||||
if v is None:
|
||||
log.warning("%s: unit %s cannot become %s; value dropped", a.asset, unit, a.unit)
|
||||
self.agg.sample(a.asset, a.kind, v, ts)
|
||||
total = self.mapping.part_total.get(a.asset)
|
||||
if total:
|
||||
self.sample_total(self.mapping.totals[total], a.asset, v, ts)
|
||||
|
||||
def sample_total(self, t, part: str, v: float | None, ts: float):
|
||||
"""A total of parts (pv.power from pv.1.power, pv.2.power: mapping.py)
|
||||
from its consented parts' last values: their sum (the mean for % and
|
||||
°C); unknown while a part is (a counter then waits: a missing part
|
||||
must not look like a meter reset)."""
|
||||
self.parts[part] = v
|
||||
parts = [p for p in t.parts if getattr(self.mapping.by_asset.get(p), "consent", False)]
|
||||
vals = [self.parts.get(p) for p in parts]
|
||||
if not vals or None in vals:
|
||||
if t.kind == "gauge":
|
||||
self.agg.sample(t.asset, t.kind, None, ts)
|
||||
return
|
||||
self.agg.sample(t.asset, t.kind, sum(vals) / (len(vals) if t.mean else 1), ts)
|
||||
|
||||
def on_entities(self, ev: dict):
|
||||
now = self.clock()
|
||||
for eid, s in (ev.get("a") or {}).items():
|
||||
self.units[eid] = (s.get("a") or {}).get("unit_of_measurement")
|
||||
self.attrs[eid] = dict(s.get("a") or {})
|
||||
self.states[eid] = s.get("s")
|
||||
self.sample(eid, s.get("s"), now) # the value as of now
|
||||
for eid, c in (ev.get("c") or {}).items():
|
||||
plus = c.get("+") or {}
|
||||
if "unit_of_measurement" in (plus.get("a") or {}):
|
||||
self.units[eid] = plus["a"]["unit_of_measurement"]
|
||||
if plus.get("a"):
|
||||
self.attrs.setdefault(eid, {}).update(plus["a"])
|
||||
for k in (c.get("-") or {}).get("a") or []:
|
||||
self.attrs.get(eid, {}).pop(k, None)
|
||||
if "s" in plus:
|
||||
self.states[eid] = plus["s"]
|
||||
if "s" in plus or plus.get("a"): # an attribute alone (hvac_action) is news too
|
||||
self.sample(eid, self.states.get(eid), min(plus.get("lu") or plus.get("lc") or now, now))
|
||||
|
||||
async def on_connect(self, client: ha.HAClient):
|
||||
try:
|
||||
self.ha_language = (await client.send("get_config") or {}).get("language") or "en"
|
||||
except Exception as e:
|
||||
log.info("get_config: %s", e)
|
||||
try:
|
||||
await self.ensure_mapping(client)
|
||||
except Exception as e: # never keeps the agent from reading
|
||||
log.warning("mapping: %s", e)
|
||||
ids = list(dict.fromkeys(a.entity for a in self.mapping.assets if a.consent)) # one entity may feed several
|
||||
await client.subscribe_entities(ids, self.on_entities)
|
||||
log.info("subscribed to %d consented entities (mapping v%d)", len(ids), self.mapping.version)
|
||||
if self.control is not None:
|
||||
await self.control.on_connect(client)
|
||||
if self.dashboards is not None:
|
||||
self.dashboards.connected(client)
|
||||
self.client = client
|
||||
self.inventory_now.set()
|
||||
|
||||
async def inventory_loop(self):
|
||||
"""The inventory at connecting, then every 30 minutes if it changed
|
||||
(and once a day anyway)."""
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
await asyncio.wait_for(self.inventory_now.wait(), 1800)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
self.inventory_now.clear()
|
||||
if self.stop.is_set():
|
||||
return
|
||||
try:
|
||||
await self.inventory.maybe_send(self.client)
|
||||
except Exception as e:
|
||||
log.warning("inventory: %s", e)
|
||||
|
||||
# -- windows and uplink -----------------------------------------------
|
||||
def close_window(self, end: float):
|
||||
start = self.agg.start
|
||||
records = self.agg.flush(end)
|
||||
if not records:
|
||||
return
|
||||
seq = self.queue.put("tel", {
|
||||
"window_start": start, "window_end": end, "mapping_version": self.mapping.version,
|
||||
# partial: the agent started or stopped inside this window
|
||||
"partial": start < self.started or end - start < self.cfg.interval_s,
|
||||
"records": records})
|
||||
log.info("window %s queued as %d (%d records; queue %d, dropped %d)",
|
||||
time.strftime("%H:%M", time.gmtime(start)), seq, len(records),
|
||||
self.queue.depth(), self.queue.dropped())
|
||||
|
||||
async def ticker(self):
|
||||
i = self.cfg.interval_s
|
||||
while not self.stop.is_set():
|
||||
end = self.agg.start + i
|
||||
try:
|
||||
await asyncio.wait_for(self.stop.wait(), max(0.0, end - time.time()))
|
||||
except asyncio.TimeoutError:
|
||||
self.close_window(end)
|
||||
|
||||
async def uploader(self):
|
||||
wait = 1.0
|
||||
while not self.stop.is_set():
|
||||
failed = False
|
||||
if not self.consent.share and self.queue.depth():
|
||||
log.info("no consent: %d queued batches deleted, not sent", self.queue.depth())
|
||||
self.queue.clear() # the switch may have changed in the file (the panel)
|
||||
for seq, kind, payload in self.queue.peek(50):
|
||||
if not await self.sink.send(seq, kind, payload):
|
||||
failed = True # keep order: nothing after it goes first
|
||||
break
|
||||
self.queue.ack(seq)
|
||||
self.last_sent = time.time()
|
||||
# back off while the uplink is down (1 s doubling to 60 s)
|
||||
wait = min(wait * 2, 60) if failed else 1.0
|
||||
try:
|
||||
await asyncio.wait_for(self.stop.wait(), wait)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
async def run(self):
|
||||
self.started = time.time()
|
||||
self.agg.begin(self.started)
|
||||
if self.cfg.mode == "off":
|
||||
log.info("mode off: not reading Home Assistant")
|
||||
await self.stop.wait()
|
||||
return
|
||||
tasks = [asyncio.create_task(ha.run_forever(self.cfg.ha_url, self.cfg.ha_token, self.on_connect,
|
||||
self.stop)),
|
||||
asyncio.create_task(self.ticker()), asyncio.create_task(self.uploader()),
|
||||
asyncio.create_task(self.inventory_loop())]
|
||||
if self.cfg.mqtt_host:
|
||||
tasks.append(asyncio.create_task(Announcer(
|
||||
self, self.cfg.mqtt_host, self.cfg.mqtt_port, username=self.cfg.mqtt_user,
|
||||
password_file=self.cfg.mqtt_password_file, password=self.cfg.mqtt_password).run()))
|
||||
if self.control is not None:
|
||||
tasks.append(asyncio.create_task(self.control.run(self.stop)))
|
||||
if self.dashboards is not None:
|
||||
tasks.append(asyncio.create_task(self.dashboards.run(self.stop)))
|
||||
tasks.append(asyncio.create_task(areas.run(self, self.stop)))
|
||||
if self.cfg.propose:
|
||||
tasks.append(asyncio.create_task(self.mapping_loop()))
|
||||
if self.cfg.join_page_port:
|
||||
# the add-on's pages: Devices (HA's devices a profile knows) and
|
||||
# Building or community
|
||||
page = App(Fleet(self.cfg.state_dir, site_id=self.cfg.site_id),
|
||||
Devices(self.cfg.mapping, self.cfg.state_dir, self.profiles or propose.load_profiles(),
|
||||
ha=lambda: self.client, changed=self.devices_changed))
|
||||
tasks.append(asyncio.create_task(page.run(self.cfg.join_page_port, self.stop)))
|
||||
await self.stop.wait()
|
||||
self.inventory_now.set()
|
||||
self.close_window(time.time()) # the open window, marked partial by its end
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
# last chance to send what is queued; the rest waits on disk
|
||||
for seq, kind, payload in self.queue.peek(50) if self.consent.share else ():
|
||||
if not await self.sink.send(seq, kind, payload):
|
||||
break
|
||||
self.queue.ack(seq)
|
||||
await self.sink.close()
|
||||
log.info("stopped; %d batches stay queued", self.queue.depth())
|
||||
|
||||
|
||||
def open_queue(cfg) -> Queue:
|
||||
os.makedirs(cfg.state_dir, exist_ok=True)
|
||||
return Queue(os.path.join(cfg.state_dir, "queue.db"), cfg.queue_max)
|
||||
|
||||
|
||||
def build(cfg) -> Agent:
|
||||
return Agent(cfg, Mapping.load(cfg.mapping), open_queue(cfg), sinks.make(cfg))
|
||||
@@ -0,0 +1,441 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The agent in Home Assistant, through MQTT discovery: a device
|
||||
"Cantabile" (one per site) under HA's MQTT integration, in the area
|
||||
"Cantabile" (suggested_area, in HA's language: names.py), with
|
||||
availability (offline when the agent stops: MQTT's last will, or said
|
||||
before a clean stop). Read only: nothing in HA changes the agent; the
|
||||
owner's consent is given in the box's setup wizard and panel only (sensitive).
|
||||
|
||||
What it shows (what goes between the cloud or the
|
||||
building and the home, and what the agent does to each device):
|
||||
binary_sensor cloud the link's connection to the platform
|
||||
sensor control_mode, next_action, plan_<control>
|
||||
(controls by their names: the mapping's `name`,
|
||||
else the id in words)
|
||||
the plan, in advisory and auto (in shadow and
|
||||
off taken out of HA again: an empty retained config)
|
||||
sensor price_import_now, price_import_next, price_export_now, price_<carrier>
|
||||
the tariff in force, its 48 h curve as attributes
|
||||
sensor model the forecast model (source, issued, expires)
|
||||
event commands each command or bundle received: mode, control,
|
||||
release, limits, tariff, model, building; who
|
||||
sent it (cloud, building, grid), its arguments
|
||||
(no signatures or proofs), applied or refused and why
|
||||
sensor received the last 10 of them as a list (attribute commands:
|
||||
at, what in words, by, result, why), kept across
|
||||
restarts (the dashboard's "Commands received")
|
||||
sensor set_<control> per control: the value the agent wants it at now
|
||||
and from whom (plan, cloud, building, owner, safe
|
||||
default), whether it acts, the limits per level
|
||||
On a building's own box (flats.json, a signed `flats` bundle from the
|
||||
cloud: bundles.py) each flat is a device of its own ("Flat", via the
|
||||
building's Cantabile device, area "Flats"): its grid power, its
|
||||
flexibility, the building's requests to it.
|
||||
|
||||
Topics: homeassistant/<component>/cantabile_<site>[_flat_<id>]/<object>/config
|
||||
(retained); cantabile/<site>/state, /availability, /plan, /tariff, /model,
|
||||
/actuators, /command (not retained), /flat/<id>.
|
||||
|
||||
On the Cantabile Hub the broker is Mosquitto on the box (127.0.0.1:1883, with
|
||||
the agent's own user: hub mqtt-users); without a broker this does nothing.
|
||||
"""
|
||||
import asyncio
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from . import gridorder
|
||||
from . import __version__
|
||||
from . import names, shades
|
||||
from .bundles import Bundles
|
||||
from .mqtt import Client
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
INTERVAL = 30 # state at least this often (seconds)
|
||||
RETIRED = (("switch", "share"), ("sensor", "queued"), ("sensor", "last_sent"), ("sensor", "mode"))
|
||||
RECEIVED = 10 # commands listed in HA (sensor received)
|
||||
COMMANDS = ("mode", "control", "release", "limits", "tariff", "model", "building")
|
||||
MAX_FLATS = 200
|
||||
|
||||
|
||||
def _slug(s: str) -> str:
|
||||
return re.sub(r"[^a-z0-9_]", "_", str(s).lower())[:48]
|
||||
|
||||
|
||||
class Announcer:
|
||||
def __init__(self, agent, host: str, port: int, prefix: str = "homeassistant",
|
||||
username: str = "", password_file: str = "", password: str = ""):
|
||||
self.agent, self.host, self.port, self.prefix = agent, host, port, prefix
|
||||
self.username, self.password_file, self.password = username, password_file, password
|
||||
site = agent.cfg.site_id
|
||||
self.site = site
|
||||
self.base = f"cantabile/{site}"
|
||||
self.uid = f"cantabile_{site}"
|
||||
self.client = None
|
||||
self.changed = asyncio.Event()
|
||||
self.sent: dict[tuple, str] = {} # (node, component, object) -> config sent (JSON)
|
||||
ctl = getattr(agent, "control", None)
|
||||
self.bundles = ctl.bundles if ctl is not None else Bundles(agent.cfg.state_dir, site)
|
||||
if ctl is not None:
|
||||
ctl.on_plan.append(self._planned)
|
||||
ctl.on_received.append(self._received)
|
||||
|
||||
@property
|
||||
def lang(self) -> str:
|
||||
return getattr(self.agent, "ha_language", None) or "en"
|
||||
|
||||
async def _planned(self, plan):
|
||||
self.changed.set()
|
||||
|
||||
async def _received(self, ev: dict):
|
||||
"""A command or bundle arrived: an event in HA now."""
|
||||
if self.client is not None and not self.client.closed.is_set():
|
||||
try:
|
||||
await self.client.publish(f"{self.base}/command",
|
||||
json.dumps({"event_type": ev["cmd"], **{k: v for k, v in ev.items()
|
||||
if k != "cmd"}}))
|
||||
except Exception as e:
|
||||
log.info("mqtt: command event not shown: %s", e)
|
||||
self.changed.set()
|
||||
|
||||
# -- what HA should have -------------------------------------------------
|
||||
def _device(self):
|
||||
return {"identifiers": [self.uid], "name": "Cantabile", "manufacturer": "Cantabile",
|
||||
"model": "Edge Agent", "sw_version": __version__,
|
||||
"suggested_area": names.area("cantabile", self.lang)}
|
||||
|
||||
def _avail(self):
|
||||
return {"availability_topic": f"{self.base}/availability"}
|
||||
|
||||
def _configs(self):
|
||||
"""The agent's own entities: always there."""
|
||||
return {
|
||||
("binary_sensor", "cloud"): {
|
||||
"name": names.name("cloud", self.lang),
|
||||
"unique_id": f"{self.uid}_cloud", "device_class": "connectivity",
|
||||
"state_topic": f"{self.base}/state", "value_template": "{{ value_json.cloud }}",
|
||||
"payload_on": "on", "payload_off": "off", **self._avail(), "device": self._device()},
|
||||
}
|
||||
|
||||
def _plan_objects(self) -> dict:
|
||||
"""The plan's entities, when the mode shows them (advisory, auto)."""
|
||||
ctl = getattr(self.agent, "control", None)
|
||||
if ctl is None or ctl.mode() not in ("advisory", "auto"):
|
||||
return {}
|
||||
common = {"state_topic": f"{self.base}/plan", **self._avail(), "device": self._device()}
|
||||
out = {("sensor", "control_mode"): {"name": names.name("mode", self.lang),
|
||||
"unique_id": f"{self.uid}_control_mode",
|
||||
"value_template": "{{ value_json.mode }}", **common},
|
||||
("sensor", "next_action"): {"name": names.name("next_action", self.lang),
|
||||
"unique_id": f"{self.uid}_next_action",
|
||||
"value_template": "{{ value_json.next }}",
|
||||
"json_attributes_topic": f"{self.base}/plan",
|
||||
"json_attributes_template": "{{ value_json.attrs | tojson }}",
|
||||
**common}}
|
||||
for c in ctl.controls:
|
||||
out[("sensor", f"plan_{c.id}")] = {
|
||||
"name": names.name("plan", self.lang, c.label()), "unique_id": f"{self.uid}_plan_{c.id}",
|
||||
"value_template": "{{ value_json.controls['%s'].now }}" % c.id,
|
||||
"json_attributes_topic": f"{self.base}/plan",
|
||||
"json_attributes_template": "{{ value_json.controls['%s'] | tojson }}" % c.id, **common}
|
||||
return out
|
||||
|
||||
def _exchange_objects(self, tariff: dict | None, model: dict | None) -> dict:
|
||||
"""What came from the cloud or the building, and the agent's wish per
|
||||
control: in every mode but off."""
|
||||
ctl = getattr(self.agent, "control", None)
|
||||
dev, out = self._device(), {}
|
||||
if ctl is not None and ctl.mode() == "off":
|
||||
return out
|
||||
if tariff is not None:
|
||||
# In <currency>/kWh, as HA's Energy dashboard takes a price
|
||||
# (dashboards.py; ct/kWh it would not take), shown with 3
|
||||
# decimals (0.167 EUR/kWh); the bundle's ct/kWh curve as
|
||||
# attributes. The dashboard shows ct/kWh.
|
||||
t = {"state_topic": f"{self.base}/tariff", "unit_of_measurement": f"{tariff['currency']}/kWh",
|
||||
"suggested_display_precision": 3, "state_class": "measurement", "icon": "mdi:cash", **self._avail(), "device": dev,
|
||||
"json_attributes_topic": f"{self.base}/tariff",
|
||||
"json_attributes_template": "{{ value_json.curve | tojson }}"}
|
||||
|
||||
def per_kwh(path):
|
||||
return ("{% set v = value_json." + path + " %}"
|
||||
"{{ (v / 100) | round(4) if v is not none else none }}")
|
||||
out[("sensor", "price_import_now")] = {"name": names.name("price_import_now", self.lang),
|
||||
"unique_id": f"{self.uid}_price_import_now",
|
||||
"value_template": per_kwh("import_now"), **t}
|
||||
out[("sensor", "price_import_next")] = {"name": names.name("price_import_next", self.lang),
|
||||
"unique_id": f"{self.uid}_price_import_next",
|
||||
"value_template": per_kwh("import_next"), **t}
|
||||
if any(x is not None for x in tariff["curve"].get("export") or []):
|
||||
out[("sensor", "price_export_now")] = {"name": names.name("price_export_now", self.lang),
|
||||
"unique_id": f"{self.uid}_price_export_now",
|
||||
"value_template": per_kwh("export_now"), **t}
|
||||
for carrier in sorted(tariff.get("other") or {})[:8]:
|
||||
k = _slug(carrier)
|
||||
out[("sensor", f"price_{k}")] = {
|
||||
"name": names.name("price_other", self.lang, carrier), "unique_id": f"{self.uid}_price_{k}",
|
||||
"value_template": per_kwh("other['%s']" % carrier), **t}
|
||||
if model is not None:
|
||||
out[("sensor", "model")] = {"name": names.name("model", self.lang), "unique_id": f"{self.uid}_model",
|
||||
"state_topic": f"{self.base}/model", "icon": "mdi:chart-bell-curve",
|
||||
"value_template": "{{ value_json.source }}",
|
||||
"json_attributes_topic": f"{self.base}/model", **self._avail(), "device": dev}
|
||||
if ctl is not None:
|
||||
out[("event", "commands")] = {"name": names.name("commands", self.lang), "unique_id": f"{self.uid}_commands",
|
||||
"state_topic": f"{self.base}/command", "event_types": list(COMMANDS),
|
||||
"icon": "mdi:message-arrow-left", **self._avail(), "device": dev}
|
||||
# the last commands as a list (the event entity has only the
|
||||
# last one, and goes unknown at each restart): the dashboard's
|
||||
out[("sensor", "received")] = {"name": names.name("received", self.lang), "unique_id": f"{self.uid}_received",
|
||||
"state_topic": f"{self.base}/received", "icon": "mdi:message-arrow-left",
|
||||
"value_template": "{{ value_json.commands | count }}",
|
||||
"json_attributes_topic": f"{self.base}/received",
|
||||
"json_attributes_template": "{{ {'commands': value_json.commands} | tojson }}",
|
||||
"device": dev}
|
||||
for c in ctl.controls:
|
||||
out[("sensor", f"set_{c.id}")] = {
|
||||
"name": names.name("commanded", self.lang, c.label()), "unique_id": f"{self.uid}_set_{c.id}",
|
||||
"state_topic": f"{self.base}/actuators", "icon": "mdi:tune-variant",
|
||||
"value_template": "{{ value_json['%s'].value }}" % c.id,
|
||||
"json_attributes_topic": f"{self.base}/actuators",
|
||||
"json_attributes_template": "{{ value_json['%s'] | tojson }}" % c.id,
|
||||
**self._avail(), "device": dev}
|
||||
return out
|
||||
|
||||
def _flat_objects(self, flats: list[dict]) -> dict:
|
||||
"""Each flat of the building a device of its own (node: the flat)."""
|
||||
out = {}
|
||||
for f in flats[:MAX_FLATS]:
|
||||
fid = _slug(f["id"])
|
||||
node = f"{self.uid}_flat_{fid}"
|
||||
dev = {"identifiers": [node], "name": f.get("label") or f["id"], "manufacturer": "Cantabile",
|
||||
"model": "Flat", "via_device": self.uid, "suggested_area": names.area("flats", self.lang)}
|
||||
common = {"state_topic": f"{self.base}/flat/{fid}", **self._avail(), "device": dev}
|
||||
out[(node, "sensor", "grid")] = {
|
||||
"name": names.name("flat_grid", self.lang), "unique_id": f"{node}_grid",
|
||||
"value_template": "{{ value_json.grid_w }}", "unit_of_measurement": "W", "device_class": "power",
|
||||
"state_class": "measurement", "json_attributes_topic": f"{self.base}/flat/{fid}",
|
||||
"json_attributes_template": "{{ value_json.state | tojson }}", **common}
|
||||
out[(node, "sensor", "flex")] = {
|
||||
"name": names.name("flat_flex", self.lang), "unique_id": f"{node}_flex",
|
||||
"value_template": "{{ value_json.flex_now }}", "unit_of_measurement": "W", "device_class": "power",
|
||||
"state_class": "measurement", "json_attributes_topic": f"{self.base}/flat/{fid}",
|
||||
"json_attributes_template": "{{ value_json.flex | tojson }}", **common}
|
||||
out[(node, "sensor", "request")] = {
|
||||
"name": names.name("flat_request", self.lang), "unique_id": f"{node}_request",
|
||||
"value_template": "{{ value_json.request }}", "icon": "mdi:office-building",
|
||||
"json_attributes_topic": f"{self.base}/flat/{fid}",
|
||||
"json_attributes_template": "{{ {'commands': value_json.commands} | tojson }}", **common}
|
||||
return out
|
||||
|
||||
def objects(self) -> dict:
|
||||
"""Every discovery config HA should have now: (node, component,
|
||||
object) -> config; node is the site's or a flat's."""
|
||||
now = time.time()
|
||||
tariff, model = self.bundles.tariff_now(now), self.bundles.model_info()
|
||||
out = {}
|
||||
for (comp, obj), conf in {**self._configs(), **self._plan_objects(),
|
||||
**self._exchange_objects(tariff, model)}.items():
|
||||
out[(self.uid, comp, obj)] = conf
|
||||
out.update(self._flat_objects(self.bundles.flat_list()))
|
||||
# The entity ids themselves (HA 2025.10+): without them HA makes them
|
||||
# from the device's and the entity's names, which gave
|
||||
# binary_sensor.cantabile_cantabile_cloud on 0.3.0's check; ids stay
|
||||
# the same in every language. A flat's: cantabile_flat_<id>_<object>.
|
||||
for (node, comp, obj), conf in out.items():
|
||||
prefix = "cantabile" + node[len(self.uid):]
|
||||
conf.setdefault("default_entity_id", f"{comp}.{prefix}_{obj}")
|
||||
return out
|
||||
|
||||
# -- state ---------------------------------------------------------------
|
||||
def _plan_state(self) -> dict:
|
||||
ctl = self.agent.control
|
||||
plan, now = ctl.plan or {}, time.time()
|
||||
nxt, upcoming, per = "no plan yet", [], {}
|
||||
kinds = {c.id: c.kind for c in ctl.controls}
|
||||
for cid, entries in (plan.get("devices") or {}).items():
|
||||
cur = None
|
||||
future = []
|
||||
for e in entries:
|
||||
if e["t"] <= now:
|
||||
cur = e
|
||||
elif e.get("set") is not None: # a shade's hold between its moves: nothing to do
|
||||
future.append(e)
|
||||
if kinds.get(cid) == "cover":
|
||||
# a shade's moves in words: "close to 30 %", "open"
|
||||
future = [dict(e, set=shades.say(e["set"], self.lang), why=shades.why_words(e["why"], self.lang))
|
||||
for e in future]
|
||||
per[cid] = {"now": str("-" if (cur or {}).get("set") is None else cur["set"]), "why": (cur or {}).get("why", ""),
|
||||
"next": [{"at": time.strftime("%H:%M", time.localtime(e["t"])), "set": e["set"],
|
||||
"why": e["why"]} for e in future[:12]]}
|
||||
upcoming += [(e["t"], cid, e) for e in future[:3]]
|
||||
for c in ctl.controls:
|
||||
per.setdefault(c.id, {"now": "-", "why": "", "next": []})
|
||||
upcoming.sort(key=lambda x: x[0])
|
||||
label = {c.id: c.label() for c in ctl.controls}
|
||||
if upcoming:
|
||||
t, cid, e = upcoming[0]
|
||||
when = time.strftime('%H:%M', time.localtime(t))
|
||||
nxt = (f"{label.get(cid, cid)}: {e['set']} at {when} — {e['why']}" if kinds.get(cid) == "cover" else
|
||||
f"{label.get(cid, cid)}: {e['set']} at {when} ({e['why']})")[:250]
|
||||
attrs = {"next": [{"at": time.strftime("%H:%M", time.localtime(t)), "control": cid,
|
||||
"name": label.get(cid, cid), "set": e["set"], "why": e["why"]}
|
||||
for t, cid, e in upcoming[:10]],
|
||||
"cost_eur": plan.get("cost_eur"), "baseline_eur": plan.get("baseline_eur"),
|
||||
"prices": plan.get("price_note", ""), "made": plan.get("made")}
|
||||
return {"mode": ctl.mode(), "next": nxt, "attrs": attrs, "controls": per}
|
||||
|
||||
def received_list(self, ctl) -> list[dict]:
|
||||
"""The last commands, newest first, as people read them: when, what
|
||||
(the control's name, not its id), from whom, applied or refused and
|
||||
why."""
|
||||
label = {c.id: c.label() for c in ctl.controls}
|
||||
out = []
|
||||
for ev in reversed(ctl.received[-RECEIVED:]):
|
||||
a = ev.get("args") or {}
|
||||
cid = a.get("asset", "")
|
||||
what = names.name(f"cmd_{ev['cmd']}", self.lang, label.get(cid, cid), a.get("set", ""),
|
||||
a.get("mode", "")) if f"cmd_{ev['cmd']}" in names.NAMES else ev["cmd"]
|
||||
out.append({"at": ev["at"], "what": what.strip(), "by": ev.get("by", ""), "result": ev.get("result", ""),
|
||||
"why": str(ev.get("why", ""))[:120]})
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def flat_state(f: dict, now: float) -> dict:
|
||||
"""A flat's values for HA: grid power, the flexibility now and its
|
||||
curve, the building's requests in force (a short summary)."""
|
||||
st = dict(f.get("state") or {})
|
||||
flex = f.get("flex") or {}
|
||||
shed = flex.get("shed_w") or []
|
||||
k = int((now - flex["start"]) // flex.get("step_s", 900)) if flex.get("start") else 0
|
||||
cmds = [c for c in f.get("commands") or [] if not c.get("until") or c["until"] > now][:10]
|
||||
req = "; ".join(f"{c.get('control')} {c.get('value')} ({c.get('level')})" for c in cmds)[:250] or "none"
|
||||
return {"grid_w": st.get("grid_w"), "state": st, "flex_now": shed[k] if 0 <= k < len(shed) else None,
|
||||
"flex": flex, "request": req, "commands": cmds}
|
||||
|
||||
async def _states(self):
|
||||
c, now = self.client, time.time()
|
||||
st = {"cloud": "on" if await self.agent.cloud() else "off"}
|
||||
await c.publish(f"{self.base}/state", json.dumps(st), retain=True)
|
||||
ctl = getattr(self.agent, "control", None)
|
||||
if ctl is not None and ctl.mode() in ("advisory", "auto"):
|
||||
await c.publish(f"{self.base}/plan", json.dumps(self._plan_state()), retain=True)
|
||||
tariff = self.bundles.tariff_now(now)
|
||||
if tariff is not None:
|
||||
await c.publish(f"{self.base}/tariff", json.dumps(tariff), retain=True)
|
||||
model = self.bundles.model_info()
|
||||
if model is not None:
|
||||
await c.publish(f"{self.base}/model", json.dumps(model), retain=True)
|
||||
if ctl is not None and ctl.mode() != "off":
|
||||
await c.publish(f"{self.base}/actuators", json.dumps(ctl.actuators(), default=str), retain=True)
|
||||
if ctl is not None and ctl.received:
|
||||
# kept (retained) across restarts until new ones come
|
||||
await c.publish(f"{self.base}/received", json.dumps({"commands": self.received_list(ctl)}), retain=True)
|
||||
for f in self.bundles.flat_list()[:MAX_FLATS]:
|
||||
await c.publish(f"{self.base}/flat/{_slug(f['id'])}", json.dumps(self.flat_state(f, now)), retain=True)
|
||||
|
||||
async def _sync(self):
|
||||
"""Configs in or out of HA as they should be now, then the states."""
|
||||
want = {k: json.dumps(v, sort_keys=True) for k, v in self.objects().items()}
|
||||
for key in set(self.sent) - set(want):
|
||||
node, component, obj = key
|
||||
await self.client.publish(f"{self.prefix}/{component}/{node}/{obj}/config", b"", retain=True)
|
||||
del self.sent[key]
|
||||
for key, conf in want.items():
|
||||
if self.sent.get(key) != conf:
|
||||
node, component, obj = key
|
||||
await self.client.publish(f"{self.prefix}/{component}/{node}/{obj}/config", conf, retain=True)
|
||||
self.sent[key] = conf
|
||||
await self._states()
|
||||
|
||||
async def _retained(self, c, wait: float = 1.0) -> dict:
|
||||
"""The retained discovery configs of this site's nodes (its own and
|
||||
its flats'), read for a moment after subscribing."""
|
||||
found: dict[tuple, str] = {}
|
||||
pat = re.compile(rf"^{re.escape(self.prefix)}/([^/]+)/({re.escape(self.uid)}(?:_flat_[a-z0-9_]+)?)/([^/]+)/config$")
|
||||
|
||||
def on(topic, payload):
|
||||
m = pat.match(topic)
|
||||
if m and payload:
|
||||
found[(m.group(2), m.group(1), m.group(3))] = payload.decode(errors="replace")
|
||||
c.on_message = on
|
||||
try:
|
||||
await c.subscribe(f"{self.prefix}/+/+/+/config")
|
||||
await asyncio.sleep(wait)
|
||||
except Exception as e:
|
||||
log.info("mqtt: earlier configs not read: %s", e)
|
||||
c.on_message = None
|
||||
return found
|
||||
|
||||
async def _grid_orders(self, c):
|
||||
"""The EEBUS bridge's grid order (gridorder.py), to the
|
||||
controller: the grid operator's limit as a higher-rank decision."""
|
||||
ctl = getattr(self.agent, "control", None)
|
||||
if ctl is None:
|
||||
return
|
||||
|
||||
def on(topic, payload):
|
||||
if topic == gridorder.TOPIC and payload:
|
||||
asyncio.ensure_future(ctl.grid_order(payload))
|
||||
c.on_message = on
|
||||
try:
|
||||
await c.subscribe(gridorder.TOPIC)
|
||||
except Exception as e:
|
||||
log.info("mqtt: grid orders not subscribed: %s", e)
|
||||
|
||||
def _password(self) -> str:
|
||||
if self.password_file:
|
||||
try:
|
||||
with open(self.password_file) as f:
|
||||
return f.read().strip()
|
||||
except OSError:
|
||||
return ""
|
||||
return self.password
|
||||
|
||||
async def _session(self):
|
||||
c = self.client = Client(self.host, self.port, f"cantabile-edge-{self.site[:12]}",
|
||||
username=self.username, password=self._password())
|
||||
await c.connect(f"{self.base}/availability", b"offline")
|
||||
# Entities of earlier builds (the consent switch, diagnostics): gone from HA.
|
||||
for component, obj in RETIRED:
|
||||
await c.publish(f"{self.prefix}/{component}/{self.uid}/{obj}/config", b"", retain=True)
|
||||
await c.publish(f"{self.base}/share", b"", retain=True)
|
||||
# What the broker keeps from earlier sessions (retained configs of
|
||||
# this site and its flats): anything not wanted now is taken out,
|
||||
# the rest sent again (HA may have restarted).
|
||||
self.sent = await self._retained(c)
|
||||
for key in self.sent:
|
||||
self.sent[key] = ""
|
||||
await self._sync()
|
||||
await c.publish(f"{self.base}/availability", "online", retain=True)
|
||||
log.info("in Home Assistant through MQTT discovery (%s:%d)", self.host, self.port)
|
||||
await self._grid_orders(c)
|
||||
while not c.closed.is_set() and not self.agent.stop.is_set():
|
||||
self.changed.clear()
|
||||
waits = [asyncio.create_task(e.wait()) for e in (self.changed, c.closed, self.agent.stop)]
|
||||
await asyncio.wait(waits, timeout=INTERVAL, return_when=asyncio.FIRST_COMPLETED)
|
||||
for t in waits:
|
||||
t.cancel()
|
||||
if not c.closed.is_set() and not self.agent.stop.is_set():
|
||||
await self._sync()
|
||||
|
||||
async def run(self):
|
||||
wait = 2.0
|
||||
while not self.agent.stop.is_set():
|
||||
try:
|
||||
await self._session()
|
||||
wait = 2.0
|
||||
except Exception as e:
|
||||
log.warning("mqtt %s:%d: %s", self.host, self.port, str(e) or type(e).__name__)
|
||||
if self.client is not None:
|
||||
if self.agent.stop.is_set():
|
||||
try: # a clean stop sends no last will: say it
|
||||
await self.client.publish(f"{self.base}/availability", "offline", retain=True)
|
||||
except Exception:
|
||||
pass
|
||||
await self.client.close()
|
||||
try:
|
||||
await asyncio.wait_for(self.agent.stop.wait(), wait)
|
||||
except asyncio.TimeoutError:
|
||||
wait = min(wait * 2, 60)
|
||||
@@ -0,0 +1,75 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Cantabile's devices in HA's area "Cantabile" (part of
|
||||
installing and of moving a site onto Cantabile). MQTT discovery's
|
||||
suggested_area only places a device when HA first makes it, so this places
|
||||
what came before, or what came without the hint: the agent's own device,
|
||||
the Modbus and EEBUS bridges' devices (identifiers cantabile_modbus_*,
|
||||
cantabile_eebus_*) and Cantabile's
|
||||
HA add-ons (the Supervisor's devices, slugs *cantabile_*), and on an HA
|
||||
add-on site the devices the owner uses with Cantabile on its Devices page
|
||||
(devpage.py; <state dir>/devices.json). A device the owner put in an area
|
||||
stays there (a thermostat in its room keeps its room); the flats keep their own area. At connecting,
|
||||
then every EVERY_S."""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
|
||||
from . import names
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
EVERY_S = 600
|
||||
|
||||
|
||||
def used(state_dir: str) -> set:
|
||||
"""The HA devices the owner uses with Cantabile (the add-on's Devices page)."""
|
||||
try:
|
||||
with open(os.path.join(state_dir, "devices.json")) as f:
|
||||
devs = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return set()
|
||||
return {d.get("ha_device") for d in (devs.values() if isinstance(devs, dict) else []) if isinstance(d, dict)} - {None}
|
||||
|
||||
|
||||
def ours(d: dict, uid: str, used_ids=()) -> bool:
|
||||
"""A device Cantabile made (the agent's, the bridge's or an add-on's) or
|
||||
one the owner uses with it."""
|
||||
if d.get("id") in used_ids:
|
||||
return True
|
||||
for domain, ident in (tuple(i) for i in d.get("identifiers") or [] if len(i) == 2):
|
||||
if domain == "mqtt" and (ident == uid or str(ident).startswith(("cantabile_modbus_", "cantabile_eebus_"))):
|
||||
return True
|
||||
if domain == "hassio" and "cantabile_" in str(ident):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def place(client, uid: str, language: str | None, used_ids=()) -> int:
|
||||
"""Puts our devices without an area into "Cantabile" (made if missing);
|
||||
how many it moved."""
|
||||
devices = [d for d in await client.send("config/device_registry/list") or []
|
||||
if ours(d, uid, used_ids) and not d.get("area_id")]
|
||||
if not devices:
|
||||
return 0
|
||||
name = names.area("cantabile", language)
|
||||
areas = await client.send("config/area_registry/list") or []
|
||||
a = next((x for x in areas if x.get("name") == name), None) or await client.create_area(name, "mdi:leaf")
|
||||
for d in devices:
|
||||
await client.place_device(d["id"], a["area_id"])
|
||||
log.info("%s put in the area %s", d.get("name_by_user") or d.get("name"), name)
|
||||
return len(devices)
|
||||
|
||||
|
||||
async def run(agent, stop: asyncio.Event):
|
||||
while not stop.is_set():
|
||||
if agent.client is not None:
|
||||
try:
|
||||
await place(agent.client, f"cantabile_{agent.cfg.site_id}", getattr(agent, "ha_language", "en"),
|
||||
used(agent.cfg.state_dir))
|
||||
except Exception as e:
|
||||
log.warning("areas: %s", e)
|
||||
try: # soon after starting (HA not connected yet), then every EVERY_S
|
||||
await asyncio.wait_for(stop.wait(), EVERY_S if agent.client is not None else 30)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
@@ -0,0 +1,64 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""History backfill: HA's long-term statistics (hourly mean/min/max for
|
||||
gauges, the running sum for counters) for consented assets, queued as
|
||||
"stats" batches and sent like telemetry. Chunks of a week keep each HA
|
||||
answer and each batch small."""
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from .agent import number
|
||||
from .ha import HAClient
|
||||
from .mapping import convert, scaled
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
CHUNK = timedelta(days=7)
|
||||
|
||||
|
||||
def _ts(v) -> float:
|
||||
# HA sends epoch milliseconds (newer) or ISO strings (older)
|
||||
if isinstance(v, (int, float)):
|
||||
return v / 1000
|
||||
return datetime.fromisoformat(v).timestamp()
|
||||
|
||||
|
||||
async def backfill(client: HAClient, mapping, queue, since: datetime, until: datetime,
|
||||
period: str = "hour") -> int:
|
||||
"""period: hour (kept for ever) or 5minute (HA keeps those ~10 days)."""
|
||||
assets = {a.entity: a for a in mapping.assets if a.consent}
|
||||
meta = await client.send("recorder/list_statistic_ids") # no type: both mean and sum
|
||||
units = {m["statistic_id"]: m.get("statistics_unit_of_measurement") for m in meta}
|
||||
ids = [e for e in assets if e in units]
|
||||
log.info("backfill %d of %d consented entities have statistics", len(ids), len(assets))
|
||||
batches, start = 0, since
|
||||
while start < until and ids:
|
||||
end = min(start + CHUNK, until)
|
||||
res = await client.send("recorder/statistics_during_period", timeout=300,
|
||||
start_time=start.isoformat(), end_time=end.isoformat(),
|
||||
statistic_ids=ids, period=period,
|
||||
types=["mean", "min", "max", "sum", "state"])
|
||||
records = []
|
||||
for eid, rows in sorted((res or {}).items()):
|
||||
a, unit = assets[eid], units.get(eid)
|
||||
out = []
|
||||
for r in rows:
|
||||
row = {"start": _ts(r["start"])}
|
||||
for k in (("sum", "state") if a.kind == "counter" else ("mean", "min", "max")):
|
||||
v = number(r.get(k))
|
||||
row[k] = None if v is None else scaled(convert(v, unit, a.unit), a)
|
||||
out.append(row)
|
||||
records.append({"asset": a.asset, "kind": a.kind, "rows": out})
|
||||
if records:
|
||||
queue.put("stats", {"period": period, "window_start": start.timestamp(),
|
||||
"window_end": end.timestamp(), "mapping_version": mapping.version,
|
||||
"records": records})
|
||||
batches += 1
|
||||
start = end
|
||||
return batches
|
||||
|
||||
|
||||
def parse_since(s: str) -> datetime:
|
||||
"""An ISO date/time (UTC unless it says otherwise) or days back, e.g. 30d."""
|
||||
if s.endswith("d") and s[:-1].isdigit():
|
||||
return datetime.now(timezone.utc) - timedelta(days=int(s[:-1]))
|
||||
d = datetime.fromisoformat(s)
|
||||
return d if d.tzinfo else d.replace(tzinfo=timezone.utc)
|
||||
@@ -0,0 +1,151 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The building's requests to this flat (agreed with the building side,
|
||||
2026-10-28). Fleet sends a signed command `building` (the link checks it
|
||||
like every command) with string args:
|
||||
|
||||
{"v": "1", "id", "building", "level": "flexible|binding",
|
||||
"control": "load_limit|shift_request|thermostat_cap", "value",
|
||||
"from": unix, "until": unix (<= from + 24 h), "why"}
|
||||
|
||||
load_limit the flat's highest grid import, W, in [from, until)
|
||||
shift_request kWh the flat is asked to move out of [from, until): the
|
||||
optimiser decides how and where (a soft target)
|
||||
thermostat_cap the highest heating setpoint, °C (cooling: the lowest)
|
||||
|
||||
Rules: always within the flat's own floors (a cap below the comfort floor
|
||||
of the owner or the tenant is refused: "floor"); a newer command for the
|
||||
same control replaces the older; each is dropped at `until`. The level sits
|
||||
in the 3b ladder: binding, the flat's owner cannot lift it (applied again);
|
||||
flexible, the owner's change by hand ends it. Everything else is in each
|
||||
command. Kept in <state dir>/building.json across restarts.
|
||||
|
||||
Membership (2026-10-29, joining a building): the Hub's panel writes
|
||||
<state dir>/membership.json {"buildings": [ids]} after the owner joined
|
||||
or left (the buildings and communities this site belongs to, and the
|
||||
building whose own box it is; /usr/lib/cantabile/building). With it, a
|
||||
command from any other building is refused ("not a member"), besides
|
||||
fleet's own check. Without it (an HA add-on, an older panel), fleet's
|
||||
check alone decides.
|
||||
|
||||
The optimiser takes them as constraints (a cap, a limit: binding nearly
|
||||
hard, flexible with a price) and a soft target (a shift). Results go out as
|
||||
`action` messages with entity "building:<id>", service
|
||||
"building.<control>".
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
CONTROLS = ("load_limit", "shift_request", "thermostat_cap")
|
||||
PENALTY = { # EUR per unit across a building's request in the plan
|
||||
"binding": {"load_limit": 50.0, "shift_request": 5.0, "thermostat_cap": 50.0}, # per kWh, per kWh, per K·h
|
||||
"flexible": {"load_limit": 1.0, "shift_request": 0.5, "thermostat_cap": 2.0},
|
||||
# a grid operator's order relayed by the building (§14a), with proof the
|
||||
# link checked (edge/link/gridorder.go): nobody overrides it
|
||||
"emergency": {"load_limit": 500.0, "shift_request": 50.0, "thermostat_cap": 500.0},
|
||||
}
|
||||
|
||||
|
||||
class Building:
|
||||
def __init__(self, state_dir: str, clock=time.time):
|
||||
self.path, self.clock = os.path.join(state_dir, "building.json"), clock
|
||||
self.membership_path = os.path.join(state_dir, "membership.json")
|
||||
self.active: dict[str, dict] = {} # control -> the command's args (parsed)
|
||||
try:
|
||||
with open(self.path) as f:
|
||||
self.active = {k: v for k, v in json.load(f).items() if k in CONTROLS}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
self.drop_ended()
|
||||
|
||||
def memberships(self) -> set[str] | None:
|
||||
"""The buildings this site belongs to (membership.json), or None
|
||||
when the panel wrote none."""
|
||||
try:
|
||||
with open(self.membership_path) as f:
|
||||
ids = json.load(f).get("buildings")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return None
|
||||
return {str(i) for i in ids} if isinstance(ids, list) else None
|
||||
|
||||
def _save(self):
|
||||
tmp = self.path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(self.active, f)
|
||||
os.replace(tmp, self.path)
|
||||
|
||||
def drop_ended(self) -> list[dict]:
|
||||
now = self.clock()
|
||||
ended = [c for c in self.active.values() if now >= c["until"]]
|
||||
if ended:
|
||||
self.active = {k: c for k, c in self.active.items() if now < c["until"]}
|
||||
self._save()
|
||||
return ended
|
||||
|
||||
@staticmethod
|
||||
def parse(a: dict) -> dict:
|
||||
try:
|
||||
c = {"id": a["id"], "building": a["building"], "level": a.get("level", "flexible"),
|
||||
"control": a["control"], "value": float(a["value"]), "from": int(float(a["from"])),
|
||||
"until": int(float(a["until"])), "why": a.get("why", "")[:120], "proof": a.get("proof", "")}
|
||||
except (KeyError, ValueError, TypeError) as e:
|
||||
raise ValueError(f"building: {e} (id, building, control, value, from, until needed)")
|
||||
if str(a.get("v", "1")) != "1":
|
||||
raise ValueError("building: v 1 only")
|
||||
if c["level"] not in ("flexible", "binding", "emergency"):
|
||||
raise ValueError("building: level flexible, binding or emergency")
|
||||
if c["level"] == "emergency" and not (c["proof"].startswith("verified:") and c["control"] == "load_limit"):
|
||||
# only a grid operator's order the link verified (2026-10-29)
|
||||
raise ValueError("building: an emergency needs the grid operator's verified proof (a relayed load_limit)")
|
||||
if c["control"] not in CONTROLS:
|
||||
raise ValueError(f"building: control one of {', '.join(CONTROLS)}")
|
||||
if not c["from"] < c["until"] <= c["from"] + 86400:
|
||||
raise ValueError("building: from < until <= from + 24 h")
|
||||
if c["control"] in ("load_limit", "shift_request") and c["value"] < 0:
|
||||
raise ValueError(f"building: {c['control']} must not be negative")
|
||||
return c
|
||||
|
||||
def take(self, c: dict, floors: list[tuple[str, float, float, str]]) -> tuple[bool, str]:
|
||||
"""A parsed command. floors: (control id, the flat's floor, the
|
||||
flat's limit, kind) of each heating/cooling room, for the cap."""
|
||||
if self.clock() >= c["until"]:
|
||||
return False, "already over"
|
||||
members = self.memberships()
|
||||
if members is not None and c["building"] not in members:
|
||||
return False, "not a member of that building"
|
||||
if c["control"] == "thermostat_cap":
|
||||
for cid, lo, hi, kind in floors:
|
||||
if kind == "heating" and c["value"] < lo:
|
||||
return False, f"floor: {cid}'s comfort floor is {lo:g} °C, the cap {c['value']:g} °C"
|
||||
if kind == "cooling" and c["value"] > hi:
|
||||
return False, f"floor: {cid}'s limit is {hi:g} °C, the cap {c['value']:g} °C"
|
||||
old = self.active.get(c["control"])
|
||||
self.active[c["control"]] = c
|
||||
self._save()
|
||||
replaced = f" (replaces {old['id']})" if old and old["id"] != c["id"] else ""
|
||||
return True, f"{c['control']} {c['value']:g} {c['level']} until {time.strftime('%H:%M UTC', time.gmtime(c['until']))}{replaced}"
|
||||
|
||||
def lift(self, control: str):
|
||||
"""The owner overrode a flexible request: it ends."""
|
||||
if self.active.pop(control, None) is not None:
|
||||
self._save()
|
||||
|
||||
def for_model(self, start: int, step_s: int, steps: int) -> dict:
|
||||
"""The requests as the optimiser takes them: per step, or a window."""
|
||||
self.drop_ended()
|
||||
out = {}
|
||||
for ctl, c in self.active.items():
|
||||
a = max(0, (c["from"] - start) // step_s)
|
||||
b = min(steps, -(-(c["until"] - start) // step_s))
|
||||
if a >= b:
|
||||
continue
|
||||
out[ctl] = {"value": c["value"], "level": c["level"], "from_step": int(a), "to_step": int(b),
|
||||
"penalty": PENALTY[c["level"]][ctl], "id": c["id"], "building": c["building"]}
|
||||
return out
|
||||
|
||||
def cap(self, kind: str, now: float) -> tuple[float | None, dict | None]:
|
||||
"""The thermostat cap in force now for a heating/cooling room."""
|
||||
c = self.active.get("thermostat_cap")
|
||||
if c and c["from"] <= now < c["until"] and kind in ("heating", "cooling"):
|
||||
return c["value"], c
|
||||
return None, None
|
||||
@@ -0,0 +1,209 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Data bundles the optimiser reads: tariffs and the forecast model.
|
||||
|
||||
Both arrive as signed commands; the link checks the signature with the
|
||||
bundle key, the kind, site and expiry, keeps only the newest, and writes the
|
||||
JSON into the state directory (edge/link/bundles.go). Here they are read
|
||||
(again when the file changes), their form checked, and turned into series
|
||||
for the planning horizon. Data only: nothing in a bundle is ever run.
|
||||
|
||||
Tariff v1 (agreed with the cloud side, 2026-10-28):
|
||||
{"v":1, "kind":"tariff", "id", "site", "issued", "start": <unix, a
|
||||
quarter hour>, "step_s": 900, "steps": 192, "expires", "currency": "EUR",
|
||||
"unit": "ct/kWh", "import": [192 numbers|null], "export": [...],
|
||||
"estimated": [indexes], "other": {...}, "sources": [...]}
|
||||
After `expires` (or outside its steps): the last known flat price (the
|
||||
mean of its import prices), and the plan says so. Without any tariff:
|
||||
the configured default price.
|
||||
|
||||
Model v1 (the forecasts' data; the ML in ml/ is a placeholder, 2026-10-28):
|
||||
{"v":1, "kind":"model", "id", "site" (or "*"), "issued", "expires"?,
|
||||
"forecasts": {"load_w": {"profile": "hour_of_week", "values": [168]},
|
||||
"pv_w": {"profile": "hour_of_week", "values": [168]}},
|
||||
"source": "..."}
|
||||
hour_of_week = weekday (Monday 0) * 24 + hour, in the site's time zone.
|
||||
Without a model (or a series): the same quarter hour yesterday from the
|
||||
agent's own history (inputs.History), else 0.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _File:
|
||||
"""A JSON file re-read when it changes (inode, mtime, size)."""
|
||||
|
||||
def __init__(self, path: str, check):
|
||||
self.path, self.check = path, check
|
||||
self._key, self.data, self.error = None, None, ""
|
||||
|
||||
def stamp(self):
|
||||
"""The file's identity now (inode, mtime, size), or None: cheap, to
|
||||
notice a new bundle without reading it."""
|
||||
try:
|
||||
st = os.stat(self.path)
|
||||
return (st.st_ino, st.st_mtime_ns, st.st_size)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
def get(self):
|
||||
try:
|
||||
st = os.stat(self.path)
|
||||
key = (st.st_ino, st.st_mtime_ns, st.st_size)
|
||||
except OSError:
|
||||
self._key, self.data, self.error = None, None, ""
|
||||
return None
|
||||
if key != self._key:
|
||||
self._key = key
|
||||
try:
|
||||
with open(self.path) as f:
|
||||
d = json.load(f)
|
||||
self.check(d)
|
||||
self.data, self.error = d, ""
|
||||
except (OSError, ValueError, KeyError, TypeError) as e:
|
||||
self.data, self.error = None, f"{os.path.basename(self.path)}: {e}"
|
||||
log.warning("bundle refused: %s", self.error)
|
||||
return self.data
|
||||
|
||||
|
||||
def _check_tariff(d: dict):
|
||||
if d.get("v") != 1 or d.get("kind") != "tariff":
|
||||
raise ValueError("not a v1 tariff")
|
||||
if int(d["step_s"]) != 900 or int(d["start"]) % 900:
|
||||
raise ValueError("steps of 900 s from a quarter hour")
|
||||
for k in ("import", "export"):
|
||||
v = d.get(k) or []
|
||||
if not isinstance(v, list) or not all(x is None or isinstance(x, (int, float)) for x in v):
|
||||
raise ValueError(f"{k}: numbers or null")
|
||||
if not [x for x in d.get("import") or [] if x is not None]:
|
||||
raise ValueError("no import price")
|
||||
|
||||
|
||||
def _check_model(d: dict):
|
||||
if d.get("v") != 1 or d.get("kind") != "model":
|
||||
raise ValueError("not a v1 model")
|
||||
for name, f in (d.get("forecasts") or {}).items():
|
||||
if f.get("profile") != "hour_of_week" or len(f.get("values") or []) != 168:
|
||||
raise ValueError(f"{name}: an hour_of_week profile of 168 values")
|
||||
if not all(isinstance(x, (int, float)) for x in f["values"]):
|
||||
raise ValueError(f"{name}: numbers")
|
||||
|
||||
|
||||
def _check_flats(d: dict):
|
||||
"""A building's flats, for the building's own box (announce.py: each
|
||||
flat a device in HA). Written by the link from a signed `flats` bundle,
|
||||
like a tariff; only flats whose owner granted the building operator are in it, the cloud decides that."""
|
||||
if d.get("v") != 1 or d.get("kind") != "flats":
|
||||
raise ValueError("not a v1 flats bundle")
|
||||
for f in d.get("flats") or []:
|
||||
if not isinstance(f.get("id"), str) or not f["id"] or len(f["id"]) > 64:
|
||||
raise ValueError("flat id: a string")
|
||||
if not isinstance(f.get("label", ""), str):
|
||||
raise ValueError("flat label: a string")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Prices:
|
||||
import_ct: list[float]
|
||||
export_ct: list[float]
|
||||
note: str # what the prices are ("tariff <id>", "flat fallback ...")
|
||||
|
||||
|
||||
class Bundles:
|
||||
def __init__(self, state_dir: str, site: str, default_price_ct: float = 30.0):
|
||||
self.site, self.default = site, default_price_ct
|
||||
self.tariff = _File(os.path.join(state_dir, "tariff.json"), _check_tariff)
|
||||
self.model = _File(os.path.join(state_dir, "model.json"), _check_model)
|
||||
self.flats = _File(os.path.join(state_dir, "flats.json"), _check_flats)
|
||||
self.flat: float | None = None # the last known tariff's mean import price
|
||||
|
||||
def stamps(self):
|
||||
"""The tariff's and the model's file identities: a change means a new
|
||||
bundle arrived (the controller plans again at once)."""
|
||||
return (self.tariff.stamp(), self.model.stamp())
|
||||
|
||||
def prices(self, start: int, step_s: int, steps: int, now: float) -> Prices:
|
||||
t = self.tariff.get()
|
||||
if t is not None and t.get("site") not in (self.site, None, ""):
|
||||
t = None # the link refuses these; a copied file must not count either
|
||||
if t is not None:
|
||||
imp = [x for x in t["import"] if x is not None]
|
||||
self.flat = sum(imp) / len(imp)
|
||||
flat = self.flat if self.flat is not None else self.default
|
||||
if t is None:
|
||||
note = "no tariff yet: default price" if self.flat is None else "no tariff: last known flat price"
|
||||
return Prices([flat] * steps, [0.0] * steps, note)
|
||||
expired = now >= t.get("expires", 0)
|
||||
out_i, out_e, outside = [], [], 0
|
||||
for k in range(steps):
|
||||
i = (start + k * step_s - t["start"]) // 900
|
||||
pi = t["import"][i] if not expired and 0 <= i < len(t["import"]) else None
|
||||
pe = (t.get("export") or [])[i] if not expired and 0 <= i < len(t.get("export") or []) else None
|
||||
outside += pi is None
|
||||
out_i.append(pi if pi is not None else flat)
|
||||
out_e.append(pe if pe is not None else 0.0)
|
||||
if expired:
|
||||
note = f"tariff {t.get('id')} expired: flat {flat:.1f} ct/kWh"
|
||||
elif outside:
|
||||
note = f"tariff {t.get('id')}; {outside} of {steps} steps at the flat {flat:.1f} ct/kWh"
|
||||
else:
|
||||
note = f"tariff {t.get('id')}"
|
||||
return Prices(out_i, out_e, note)
|
||||
|
||||
def tariff_now(self, now: float) -> dict | None:
|
||||
"""The tariff in force for HA: import now and next step, export now,
|
||||
the curves and where they come from; None without one (or expired)."""
|
||||
t = self.tariff.get()
|
||||
if t is None or t.get("site") not in (self.site, None, "") or now >= t.get("expires", 0):
|
||||
return None
|
||||
i = int((now - t["start"]) // t["step_s"])
|
||||
imp, exp = t.get("import") or [], t.get("export") or []
|
||||
|
||||
def at(v, k):
|
||||
return v[k] if 0 <= k < len(v) else None
|
||||
return {"import_now": at(imp, i), "import_next": at(imp, i + 1), "export_now": at(exp, i),
|
||||
"other": dict(t.get("other") or {}), "currency": t.get("currency") or "EUR",
|
||||
"curve": {"id": t.get("id"), "start": t["start"], "step_s": t["step_s"], "import": imp,
|
||||
"export": exp, "estimated": t.get("estimated") or [], "sources": t.get("sources") or [],
|
||||
"issued": t.get("issued"), "expires": t.get("expires"), "unit": t.get("unit", "ct/kWh")}}
|
||||
|
||||
def model_info(self) -> dict | None:
|
||||
m = self.model.get()
|
||||
if m is None or m.get("site") not in (self.site, "*"):
|
||||
return None
|
||||
return {"id": m.get("id"), "source": m.get("source") or m.get("id"), "issued": m.get("issued"),
|
||||
"expires": m.get("expires"), "series": sorted((m.get("forecasts") or {}))}
|
||||
|
||||
def flat_list(self) -> list[dict]:
|
||||
d = self.flats.get()
|
||||
if d is None or d.get("site") not in (self.site, None, ""):
|
||||
return []
|
||||
if d.get("expires") and d["expires"] <= time.time():
|
||||
return []
|
||||
return list(d.get("flats") or [])
|
||||
|
||||
def forecast(self, name: str, start: int, step_s: int, steps: int, tz: str) -> list[float] | None:
|
||||
"""A model series for the horizon, or None (no model or no such
|
||||
series: the caller falls back to history)."""
|
||||
m = self.model.get()
|
||||
if m is None or m.get("site") not in (self.site, "*") or (m.get("expires") and m["expires"] <= start):
|
||||
return None
|
||||
f = (m.get("forecasts") or {}).get(name)
|
||||
if f is None:
|
||||
return None
|
||||
zone = ZoneInfo(tz or "UTC")
|
||||
out = []
|
||||
for k in range(steps):
|
||||
d = datetime.fromtimestamp(start + k * step_s, timezone.utc).astimezone(zone)
|
||||
out.append(float(f["values"][d.weekday() * 24 + d.hour]))
|
||||
return out
|
||||
|
||||
def model_id(self) -> str:
|
||||
m = self.model.get()
|
||||
return m.get("id", "") if m else ""
|
||||
@@ -0,0 +1,95 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""cantabile-edge run | suggest-mapping | backfill
|
||||
|
||||
Logs go to stderr as JSON lines (stdout stays free for the stdout sink and
|
||||
for the mapping draft); SIGTERM stops gracefully.
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import yaml
|
||||
|
||||
from . import __version__, agent, config, ha, sinks
|
||||
from .backfill import backfill, parse_since
|
||||
from .mapping import Mapping, suggest
|
||||
|
||||
|
||||
class _Json(logging.Formatter):
|
||||
def format(self, r):
|
||||
return json.dumps({"time": self.formatTime(r, "%Y-%m-%dT%H:%M:%S"), "level": r.levelname,
|
||||
"logger": r.name, "msg": r.getMessage()})
|
||||
|
||||
|
||||
def _logging():
|
||||
h = logging.StreamHandler(sys.stderr)
|
||||
h.setFormatter(_Json())
|
||||
logging.basicConfig(level=logging.INFO, handlers=[h])
|
||||
logging.getLogger("websockets").setLevel(logging.WARNING)
|
||||
|
||||
|
||||
async def _run(cfg):
|
||||
a = agent.build(cfg)
|
||||
loop = asyncio.get_running_loop()
|
||||
for s in (signal.SIGTERM, signal.SIGINT):
|
||||
loop.add_signal_handler(s, a.stop.set)
|
||||
logging.info("cantabile-edge %s site %s mode %s", __version__, cfg.site_id, cfg.mode)
|
||||
await a.run()
|
||||
return a.exit_code
|
||||
|
||||
|
||||
async def _suggest(cfg):
|
||||
c = ha.HAClient(cfg.ha_url, cfg.ha_token)
|
||||
await c.connect()
|
||||
try:
|
||||
draft = suggest(await c.send("get_states"), await c.registries())
|
||||
finally:
|
||||
await c.close()
|
||||
print("# Mapping draft: check each asset id and kind, then set consent: true")
|
||||
print("# for the assets that may leave the site.")
|
||||
yaml.safe_dump(draft, sys.stdout, sort_keys=False, allow_unicode=True)
|
||||
|
||||
|
||||
async def _backfill(cfg, since, until, period):
|
||||
q = agent.open_queue(cfg)
|
||||
c = ha.HAClient(cfg.ha_url, cfg.ha_token)
|
||||
await c.connect()
|
||||
try:
|
||||
n = await backfill(c, Mapping.load(cfg.mapping), q, since, until, period)
|
||||
finally:
|
||||
await c.close()
|
||||
logging.info("backfill queued %d batches; sending", n)
|
||||
sink = sinks.make(cfg)
|
||||
for seq, kind, payload in q.peek(1_000_000):
|
||||
if not await sink.send(seq, kind, payload):
|
||||
logging.warning("uplink down: %d batches stay queued for the agent", q.depth())
|
||||
break
|
||||
q.ack(seq)
|
||||
await sink.close()
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(prog="cantabile-edge")
|
||||
p.add_argument("--config", "-c", help="YAML config file")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
sub.add_parser("run", help="read HA, aggregate, send (shadow mode: never acts)")
|
||||
sub.add_parser("suggest-mapping", help="print a mapping draft from HA's entities")
|
||||
b = sub.add_parser("backfill", help="send HA's long-term statistics")
|
||||
b.add_argument("--since", required=True, help="ISO date/time or e.g. 30d")
|
||||
b.add_argument("--until", help="ISO date/time (default now)")
|
||||
b.add_argument("--period", choices=("hour", "5minute"), default="hour")
|
||||
args = p.parse_args()
|
||||
_logging()
|
||||
cfg = config.load(args.config, require_site=args.cmd != "suggest-mapping")
|
||||
if args.cmd == "run":
|
||||
# 75: the agent asks to be started again (the HA add-on: addon-run)
|
||||
sys.exit(asyncio.run(_run(cfg)) or 0)
|
||||
elif args.cmd == "suggest-mapping":
|
||||
asyncio.run(_suggest(cfg))
|
||||
else:
|
||||
until = parse_since(args.until) if args.until else datetime.now(timezone.utc)
|
||||
asyncio.run(_backfill(cfg, parse_since(args.since), until, args.period))
|
||||
@@ -0,0 +1,105 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Configuration: one YAML file; environment variables win (the container
|
||||
and add-on wrappers set them). Secrets only as files, never in the YAML."""
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import yaml
|
||||
|
||||
SITE_ID = re.compile(r"^[0-9a-f]{32}$") # the format of box ids
|
||||
# The configuration may only say off or shadow: a new site starts in shadow;
|
||||
# advisory and auto come by command from the console (controller.py).
|
||||
MODES = ("off", "shadow")
|
||||
|
||||
|
||||
@dataclass
|
||||
class SinkConfig:
|
||||
kind: str = "file" # file | stdout | nats | link
|
||||
path: str = "/data/telemetry.jsonl" # file sink; link: its socket (/run/cantabile/link.sock)
|
||||
url: str = "nats://127.0.0.1:4222" # nats sink
|
||||
subject_prefix: str = "ctb.site" # -> <prefix>.<site_id>.tel
|
||||
ensure_stream: bool = False # tests only: create the stream
|
||||
|
||||
|
||||
@dataclass
|
||||
class Config:
|
||||
site_id: str = ""
|
||||
mode: str = "shadow"
|
||||
ha_url: str = "ws://127.0.0.1:8123/api/websocket"
|
||||
ha_token: str = field(default="", repr=False)
|
||||
mapping: str = "/data/mapping.yaml"
|
||||
state_dir: str = "/data"
|
||||
interval_s: int = 60
|
||||
queue_max: int = 43200 # batches: 30 days at one per minute
|
||||
sink: SinkConfig = field(default_factory=SinkConfig)
|
||||
# MQTT broker for Home Assistant's discovery (announce.py); empty: none.
|
||||
mqtt_host: str = ""
|
||||
mqtt_port: int = 1883
|
||||
mqtt_user: str = "" # the Hub's Mosquitto has no anonymous access
|
||||
mqtt_password: str = field(default="", repr=False)
|
||||
mqtt_password_file: str = "" # read at each connection (it may come later)
|
||||
dashboards: bool = True # Cantabile's dashboards in HA (dashboards.py)
|
||||
# The Building page for HA's ingress (joinpage.py): HA add-on sites only
|
||||
# (the Hub's panel has its own); 0 = off. On by default in an add-on.
|
||||
join_page_port: int = 0
|
||||
# Import or propose a mapping while the site has none (propose.py): HA
|
||||
# add-on sites (addon-run sets CANTABILE_PROPOSE=1); the Hub's panel
|
||||
# writes its devices' fragments itself.
|
||||
propose: bool = False
|
||||
# v1: plans and actions (controller.py, guard.py)
|
||||
control_interval_s: int = 900 # a new plan every 15 minutes
|
||||
act_interval_s: int = 60 # the executor's round
|
||||
bundle_poll_s: float = 2.0 # how often a new tariff/model file is looked for
|
||||
replan_debounce_s: float = 3.0 # a pause after a change before planning again
|
||||
solve_timeout_s: float = 60.0 # the optimiser's subprocess is killed after this
|
||||
plan_stale_s: int = 1800 # older plans: the safe defaults
|
||||
default_price_ct: float = 30.0 # ct/kWh when no tariff ever came
|
||||
override_hold_s: int = 7200 # hands off a control the owner changed by hand
|
||||
min_switch_s: int = 600 # anti-cycling: a switch stays on/off at least this long
|
||||
max_actions_per_hour: int = 12 # per control
|
||||
|
||||
|
||||
def _read_secret(path: str) -> str:
|
||||
with open(path) as f:
|
||||
return f.read().strip()
|
||||
|
||||
|
||||
def load(path: str | None, require_site: bool = True) -> Config:
|
||||
raw = {}
|
||||
if path:
|
||||
with open(path) as f:
|
||||
raw = yaml.safe_load(f) or {}
|
||||
sink = SinkConfig(**(raw.pop("sink", None) or {}))
|
||||
ha = raw.pop("ha", None) or {}
|
||||
token_file = os.environ.get("HA_TOKEN_FILE", ha.get("token_file", ""))
|
||||
cfg = Config(sink=sink, ha_url=ha.get("url", Config.ha_url), **raw)
|
||||
env = os.environ
|
||||
cfg.site_id = env.get("CANTABILE_SITE_ID", cfg.site_id)
|
||||
# With the link the site id is the link's (edge/link writes it into its
|
||||
# state directory): one id, made from Home Assistant's instance id.
|
||||
if not cfg.site_id and env.get("CANTABILE_SITE_ID_FILE"):
|
||||
cfg.site_id = _read_secret(env["CANTABILE_SITE_ID_FILE"])
|
||||
cfg.mode = env.get("CANTABILE_MODE", cfg.mode)
|
||||
cfg.ha_url = env.get("HA_URL", cfg.ha_url)
|
||||
cfg.mqtt_host = env.get("CANTABILE_MQTT_HOST", cfg.mqtt_host)
|
||||
cfg.mqtt_port = int(env.get("CANTABILE_MQTT_PORT", cfg.mqtt_port))
|
||||
cfg.mqtt_user = env.get("CANTABILE_MQTT_USER", cfg.mqtt_user)
|
||||
cfg.mqtt_password_file = env.get("CANTABILE_MQTT_PASSWORD_FILE", cfg.mqtt_password_file)
|
||||
if env.get("CANTABILE_DASHBOARDS") in ("0", "false", "off"):
|
||||
cfg.dashboards = False
|
||||
if env.get("CANTABILE_PROPOSE") in ("1", "true", "on"):
|
||||
cfg.propose = True
|
||||
if token_file:
|
||||
cfg.ha_token = _read_secret(token_file)
|
||||
# Inside a Supervisor add-on the Supervisor proxies Core's API and hands
|
||||
# the add-on its own token: no long-lived token exists.
|
||||
cfg.join_page_port = int(env.get("CANTABILE_JOIN_PAGE_PORT", cfg.join_page_port or (8099 if env.get("SUPERVISOR_TOKEN") else 0)))
|
||||
if env.get("SUPERVISOR_TOKEN") and not cfg.ha_token:
|
||||
cfg.ha_url = env.get("HA_URL", "ws://supervisor/core/websocket")
|
||||
cfg.ha_token = env["SUPERVISOR_TOKEN"]
|
||||
if require_site and not SITE_ID.match(cfg.site_id or ""):
|
||||
raise ValueError("site_id must be 32 lowercase hex characters")
|
||||
if cfg.mode not in MODES:
|
||||
raise ValueError(f"mode must be one of {MODES} here (advisory and auto: by command from the console)")
|
||||
return cfg
|
||||
@@ -0,0 +1,64 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The owner's consent to share energy data with Cantabile: one switch for
|
||||
the whole site, on top of the mapping's per-entity consent (mapping.py).
|
||||
Off until the owner turns it on. Kept in <state dir>/consent.json
|
||||
({"share": bool, "at": unix time, "by": "panel"|"ha-addon-config",
|
||||
"source", "text_version"}), written by the Hub's setup wizard and panel
|
||||
(/usr/lib/cantabile/web) or, on an HA add-on site, by addon-run from the
|
||||
add-on's configuration at installation;
|
||||
never by support; re-read when it changes.
|
||||
Off means: nothing is collected, and what is queued is not sent (deleted).
|
||||
|
||||
Control (v1) has its own switch in the same file, "control": true, off
|
||||
unless set: the owner allows Cantabile to act on the devices whose controls
|
||||
have their own consent (controls.py). Data sharing alone never allows
|
||||
control. The Hub's panel writes it with the consent text that covers control
|
||||
(pre-launch notes: a working text until the legal team's)."""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
|
||||
class Consent:
|
||||
def __init__(self, state_dir: str):
|
||||
self.path = os.path.join(state_dir, "consent.json")
|
||||
self._key = None
|
||||
self._share = False
|
||||
self._control = False
|
||||
|
||||
def _stat(self):
|
||||
try:
|
||||
st = os.stat(self.path)
|
||||
return (st.st_ino, st.st_mtime_ns, st.st_size)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
def _load(self):
|
||||
key = self._stat()
|
||||
if key != self._key:
|
||||
self._key = key
|
||||
try:
|
||||
with open(self.path) as f:
|
||||
d = json.load(f)
|
||||
self._share, self._control = d.get("share") is True, d.get("control") is True
|
||||
except (OSError, ValueError, AttributeError):
|
||||
self._share = self._control = False
|
||||
|
||||
@property
|
||||
def share(self) -> bool:
|
||||
self._load()
|
||||
return self._share
|
||||
|
||||
@property
|
||||
def control(self) -> bool:
|
||||
self._load()
|
||||
return self._control
|
||||
|
||||
def set(self, share: bool, by: str):
|
||||
tmp = self.path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
# keeps the control switch as it was (the panel sets both)
|
||||
json.dump({"share": bool(share), "control": self.control and bool(share), "at": int(time.time()),
|
||||
"by": by}, f)
|
||||
os.replace(tmp, self.path)
|
||||
self._key = None
|
||||
@@ -0,0 +1,589 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""v1's control loop beside the telemetry: inputs -> plan -> actions.
|
||||
|
||||
every control_interval_s (15 min): the model state (inputs.py), a plan
|
||||
from the optimiser in a subprocess with a time limit (optimizer.py),
|
||||
published: to the link in every mode (ctb.site.<id>.plan, for the
|
||||
console), to Home Assistant in advisory and auto (announce.py)
|
||||
every minute: owner overrides; in auto the executor's actions through the
|
||||
guard (executor.py, guard.py)
|
||||
|
||||
Modes: off, shadow (plan and publish, act on nothing),
|
||||
advisory (also show the plan in Home Assistant), auto (act through the
|
||||
guard). The configuration may only say off or shadow: a new site starts in
|
||||
shadow; advisory and auto come only by command from the console (`mode`),
|
||||
and are kept in <state dir>/mode.json across restarts. No mode acts on a
|
||||
control without its consent.
|
||||
|
||||
Commands (from the console through the link, which checked the signature):
|
||||
mode {"mode": "off|shadow|advisory|auto"}
|
||||
control {"asset", "set", "level": "flexible|binding|emergency",
|
||||
"until": unix time | "minutes": n, "why"?}
|
||||
release {"asset"}: back to the plan
|
||||
limits {"asset", "quantity", "level": "cloud|building|grid",
|
||||
"floor"?, "limit"? (empty: none), "until"?}
|
||||
building {"v", "id", "building", "level", "control", "value", "from",
|
||||
"until", "why"}: the building's requests (building.py)
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from . import inputs as inputs_mod
|
||||
from .building import Building
|
||||
from .bundles import Bundles
|
||||
from .executor import Executor, building_msg
|
||||
from .gridorder import GridOrders
|
||||
from .guard import Guard
|
||||
from .policy import Policy
|
||||
from .switchover import Switchover
|
||||
from .inputs import Collector, History
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
MODES = ("off", "shadow", "advisory", "auto")
|
||||
|
||||
|
||||
class Mode:
|
||||
def __init__(self, state_dir: str, default: str):
|
||||
self.path, self.default = os.path.join(state_dir, "mode.json"), default
|
||||
try:
|
||||
with open(self.path) as f:
|
||||
m = json.load(f).get("mode")
|
||||
self.current = m if m in MODES else default
|
||||
except (OSError, ValueError, AttributeError):
|
||||
self.current = default
|
||||
|
||||
def set(self, mode: str, by: str):
|
||||
tmp = self.path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump({"mode": mode, "at": int(time.time()), "by": by}, f)
|
||||
os.replace(tmp, self.path)
|
||||
self.current = mode
|
||||
|
||||
def __call__(self) -> str:
|
||||
return self.current
|
||||
|
||||
|
||||
class Controller:
|
||||
def __init__(self, cfg, mapping, consent, sink, clock=time.time):
|
||||
self.cfg, self.mapping, self.sink, self.clock = cfg, mapping, sink, clock
|
||||
self.controls = mapping.controls
|
||||
self.inputs = mapping.inputs
|
||||
self.mode = Mode(cfg.state_dir, cfg.mode)
|
||||
self.col = Collector()
|
||||
self.history = History(os.path.join(cfg.state_dir, "history.json"))
|
||||
self.bundles = Bundles(cfg.state_dir, cfg.site_id, cfg.default_price_ct)
|
||||
self.guard = Guard(self.controls, consent, self.mode, override_hold_s=cfg.override_hold_s,
|
||||
min_switch_s=cfg.min_switch_s, max_actions_per_hour=cfg.max_actions_per_hour, clock=clock)
|
||||
self.saved_limits = self._load_limits() # the console's (limits.json)
|
||||
self.gridorders = GridOrders(cfg.state_dir, clock) # the grid operator's, from the EEBUS bridge (3q)
|
||||
self.guard.extra_limits = self.saved_limits
|
||||
self.policy = Policy(cfg.state_dir, cfg.site_id, clock)
|
||||
self.guard.policy = self.policy
|
||||
# a thermostat that heats and cools: one of its two controls at a time
|
||||
self.switchover = Switchover(cfg.state_dir)
|
||||
self.guard.switchover = self.switchover
|
||||
self.tz = "UTC"
|
||||
self.switchover.update(self.controls, clock(), self.tz, None)
|
||||
self.building = Building(cfg.state_dir, clock)
|
||||
self.executor = Executor(self.controls, self.guard, self.col, self._publish, stale_s=cfg.plan_stale_s,
|
||||
clock=clock, building=self.building)
|
||||
self.col.observers.append(self._observe)
|
||||
self.client = None
|
||||
self.tz = "UTC"
|
||||
self.location: dict = {} # the site's latitude and longitude (HA's configuration)
|
||||
self.plan: dict | None = None
|
||||
self.plan_error = ""
|
||||
self.forecast: list[dict] = [] # the weather entity's hourly forecast
|
||||
self.wake = asyncio.Event()
|
||||
self.act_now = asyncio.Event() # a control, release or new plan: act at once
|
||||
self.on_plan = [] # callbacks (the announcer) when a plan is made
|
||||
self.received: list[dict] = [] # the last commands and bundles (shown in HA, announce.py)
|
||||
self.on_received = [] # callbacks (the announcer) for each
|
||||
|
||||
# -- Home Assistant ----------------------------------------------------
|
||||
def outside_entity(self) -> str:
|
||||
"""The outdoor temperature: the inputs' (outside_temp), else the
|
||||
mapped outside.temp."""
|
||||
if self.inputs.outside_temp:
|
||||
return self.inputs.outside_temp
|
||||
a = self.mapping.by_asset.get("outside.temp") if hasattr(self.mapping, "by_asset") else None
|
||||
return a.entity if a else ""
|
||||
|
||||
def switch_sides(self) -> bool:
|
||||
"""Heating or cooling for each thermostat that does both (switchover.py);
|
||||
True when a side changed (plan again)."""
|
||||
ent = self.outside_entity()
|
||||
t_out = self.col.value(ent) if ent else None
|
||||
return self.switchover.update(self.controls, self.clock(), self.tz, t_out)
|
||||
|
||||
def entities(self) -> list[str]:
|
||||
out = set(self.inputs.entities())
|
||||
if self.outside_entity() and any(c.switchover or c.kind == "cover" for c in self.controls):
|
||||
out.add(self.outside_entity())
|
||||
for c in self.controls:
|
||||
out.update(c.entities.values())
|
||||
if c.kind == "cover":
|
||||
out.update(a.entity for a in self.room_assets(c) if a)
|
||||
return sorted(out)
|
||||
|
||||
# -- shades ---------------------------------------------------------------
|
||||
def room_assets(self, c) -> tuple:
|
||||
"""A shade's room readings in the mapping: room.<area>.temp and
|
||||
.setpoint (params.area), or None each."""
|
||||
area = str(c.p("area") or "")
|
||||
by = getattr(self.mapping, "by_asset", {}) or {}
|
||||
return (by.get(f"room.{area}.temp"), by.get(f"room.{area}.setpoint")) if area else (None, None)
|
||||
|
||||
def _asset_value(self, a):
|
||||
if a is None:
|
||||
return None
|
||||
return inputs_mod.number(self.col.attr(a.entity, a.attribute) if a.attribute else self.col.state(a.entity))
|
||||
|
||||
def shade_ctx(self) -> dict:
|
||||
"""Per shade its room for the rules (shades.py): the temperature and
|
||||
setpoint (its room's heating or cooling control, else the mapping's
|
||||
room.<area>.temp and .setpoint) and the season (the room control's
|
||||
kind, of a thermostat that does both its active side)."""
|
||||
by_id = {c.id: c for c in self.controls}
|
||||
out = {}
|
||||
for c in self.controls:
|
||||
if c.kind != "cover":
|
||||
continue
|
||||
ctx = {}
|
||||
room = by_id.get(str(c.p("room") or ""))
|
||||
if room is not None:
|
||||
side = room
|
||||
if room.switchover and not self.switchover.active(room):
|
||||
side = next((o for o in self.controls if o.switchover and o.id != room.id
|
||||
and o.entities.get("climate") == room.entities.get("climate")), room)
|
||||
ctx["season"] = side.kind
|
||||
st = inputs_mod.device_state(room, self.col, self.clock())
|
||||
ctx["temp_c"], ctx["setpoint_c"] = st.get("temp_c"), st.get("target_c")
|
||||
ta, sa = self.room_assets(c)
|
||||
if ctx.get("temp_c") is None:
|
||||
ctx["temp_c"] = self._asset_value(ta)
|
||||
if ctx.get("setpoint_c") is None:
|
||||
ctx["setpoint_c"] = self._asset_value(sa)
|
||||
out[c.id] = ctx
|
||||
return out
|
||||
|
||||
async def on_connect(self, client):
|
||||
self.client = client
|
||||
try:
|
||||
cfg = await client.send("get_config")
|
||||
self.tz = (cfg or {}).get("time_zone") or "UTC"
|
||||
lat, lon = (cfg or {}).get("latitude"), (cfg or {}).get("longitude")
|
||||
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
|
||||
self.location = {"latitude": float(lat), "longitude": float(lon)}
|
||||
except Exception as e:
|
||||
log.warning("get_config: %s", e)
|
||||
ids = self.entities()
|
||||
if ids:
|
||||
await client.subscribe_entities(ids, self.col.on_entities)
|
||||
log.info("control: %d controls, %d inputs, mode %s", len(self.controls), len(ids), self.mode())
|
||||
self.wake.set()
|
||||
|
||||
def _observe(self, eid: str, st: dict, now: float):
|
||||
for c in self.controls:
|
||||
if not self.switchover.active(c):
|
||||
continue # the other control of the thermostat watches it
|
||||
for role, ent in c.writable().items():
|
||||
if ent != eid:
|
||||
continue
|
||||
if c.kind == "cover":
|
||||
if st.get("s") in ("opening", "closing"):
|
||||
return # still moving to what it was told
|
||||
value = st["a"].get("current_position")
|
||||
if value is None: # open and close only
|
||||
value = {"open": 100.0, "closed": 0.0}.get(st.get("s"))
|
||||
elif ent.startswith("climate."):
|
||||
value = st["a"].get("temperature")
|
||||
cmd = self.guard._t(c.id).commanded.get(ent)
|
||||
if cmd and inputs_mod.number(cmd[1]) is None:
|
||||
value = st.get("s") # the agent last set the mode
|
||||
else:
|
||||
value = st.get("s")
|
||||
self.guard.observe(c.id, eid, value, now)
|
||||
|
||||
# -- plans ---------------------------------------------------------------
|
||||
def model_state(self) -> dict:
|
||||
now = self.clock()
|
||||
start = int(now // inputs_mod.STEP_S * inputs_mod.STEP_S)
|
||||
# sealed devices are not planned at all
|
||||
# and of a thermostat that heats and cools only its active side
|
||||
self.switch_sides()
|
||||
controls = [c for c in self.controls if self.policy.plannable(c) and self.switchover.active(c)]
|
||||
return inputs_mod.model_state(now, controls, self.inputs, self.col, self.bundles,
|
||||
self.history, self.tz, self.forecast, self.guard.extra_limits,
|
||||
building=self.building.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS),
|
||||
location=self.location, shade_ctx=self.shade_ctx(),
|
||||
grid_order=self.gridorders.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS))
|
||||
|
||||
async def make_plan(self) -> dict | None:
|
||||
self.forecast = []
|
||||
if self.client is not None and self.inputs.weather:
|
||||
try:
|
||||
self.forecast = await self.client.weather_forecast(self.inputs.weather)
|
||||
except Exception as e:
|
||||
log.info("weather forecast: %s", e)
|
||||
state = self.model_state()
|
||||
plan = await solve(state, self.cfg.solve_timeout_s)
|
||||
if "error" in plan:
|
||||
self.plan_error = plan["error"]
|
||||
log.warning("no new plan: %s (the last one stays while fresh)", plan["error"])
|
||||
return None
|
||||
plan["mode"] = self.mode()
|
||||
plan["id"] = f"{self.cfg.site_id[:8]}-{plan['made']}"
|
||||
plan["model"] = self.bundles.model_id()
|
||||
self.plan, self.plan_error = plan, ""
|
||||
self.executor.plan = plan
|
||||
self.executor.inputs_ok = self.inputs_fresh()
|
||||
self.act_now.set() # carry out a new plan now
|
||||
n = sum(len(v) for v in plan["devices"].values())
|
||||
log.info("plan %s (%s, %.1f s): %d changes in 48 h, %.2f EUR vs %.2f EUR baseline; %s",
|
||||
plan["id"], plan["status"], plan["solve_s"], n, plan["cost_eur"], plan["baseline_eur"],
|
||||
plan.get("price_note", ""))
|
||||
await self._publish("plan", self.public_plan(plan))
|
||||
for cb in self.on_plan:
|
||||
await cb(plan)
|
||||
return plan
|
||||
|
||||
def public_plan(self, plan: dict) -> dict:
|
||||
"""The agreed form (v1): the plan's steps per asset, cost, baseline."""
|
||||
return {"v": 1, "id": plan["id"], "made": plan["made"], "start": plan["start"], "step_s": plan["step_s"],
|
||||
"mode": plan["mode"], "devices": plan["devices"], "cost_eur": plan["cost_eur"],
|
||||
"baseline_eur": plan["baseline_eur"], "status": plan["status"],
|
||||
"prices": plan.get("price_note", ""), "model": plan.get("model", ""),
|
||||
"sources": plan.get("sources", {}),
|
||||
# for the building (shed_w/grid_w per step, 24 h): absent from older agents
|
||||
"flex": plan.get("flex", {})}
|
||||
|
||||
def inputs_fresh(self) -> bool:
|
||||
"""The plan's room temperatures and the battery's state are not older
|
||||
than an hour (a sensor that stopped must not steer)."""
|
||||
now = self.clock()
|
||||
for c in self.controls:
|
||||
for role in ("temp", "soc"):
|
||||
if role in c.entities and self.col.age(c.entities[role], now) > 3600:
|
||||
return False
|
||||
return True
|
||||
|
||||
async def _publish(self, kind, data):
|
||||
pub = getattr(self.sink, "publish", None)
|
||||
if pub is not None:
|
||||
await pub(kind, data)
|
||||
|
||||
def actuators(self) -> dict:
|
||||
"""Per control what the agent wants it at now and from whom (plan,
|
||||
cloud: a hand control from the console, building, owner: an override
|
||||
by hand that holds, safe default), whether it acts (auto and the
|
||||
control's consent), and the limits in force per level and quantity
|
||||
with the effective bounds. Shown in HA (announce.py)."""
|
||||
now = self.clock()
|
||||
out = {}
|
||||
for c in self.controls:
|
||||
want, level, why = self.executor.wanted(c, now)
|
||||
if self.guard.overridden(c.id):
|
||||
source = "owner"
|
||||
elif why.startswith("building"):
|
||||
source = "building"
|
||||
elif level in ("flexible", "binding", "emergency") and c.id in self.executor.commands:
|
||||
source = "cloud"
|
||||
elif why.startswith("safe default"):
|
||||
source = "safe default"
|
||||
else:
|
||||
source = "plan"
|
||||
extra = self.guard.extra_limits.get(c.id) or {}
|
||||
lims = {}
|
||||
for q in set(c.limits) | set(extra):
|
||||
layers = {**c.limits.get(q, {}), **extra.get(q, {})}
|
||||
b = c.bounds(q, extra)
|
||||
lims[q] = {"levels": {lvl: list(v) for lvl, v in layers.items()},
|
||||
"effective": [b.lo, b.hi], "floor_by": b.lo_by, "limit_by": b.hi_by}
|
||||
value = want.get("set") if isinstance(want, dict) else want
|
||||
active = self.switchover.active(c)
|
||||
attrs = {"source": source, "level": level, "why": why, "limits": lims,
|
||||
"acting": self.mode() == "auto" and bool(c.consent) and active, "kind": c.kind}
|
||||
if c.switchover:
|
||||
attrs["switchover"] = dict(c.switchover, active=active)
|
||||
if isinstance(want, dict) and "grid" in want:
|
||||
attrs["charge_from_grid"] = bool(want["grid"])
|
||||
out[c.id] = {"value": value, **attrs}
|
||||
return out
|
||||
|
||||
# -- loops ---------------------------------------------------------------
|
||||
async def run(self, stop: asyncio.Event):
|
||||
if not self.controls:
|
||||
log.info("control: no controls in the mapping (v3): nothing to plan")
|
||||
await stop.wait()
|
||||
return
|
||||
tasks = [asyncio.create_task(self._planner(stop)), asyncio.create_task(self._actor(stop)),
|
||||
asyncio.create_task(self._bundle_watch(stop))]
|
||||
await stop.wait()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
|
||||
async def _bundle_watch(self, stop):
|
||||
"""A new tariff or model (the link writes them) plans again at once,
|
||||
not at the next 15-minute plan (a test run priced a plan made one
|
||||
second before the tariff came with the old one)."""
|
||||
last = self.bundles.stamps()
|
||||
while not stop.is_set():
|
||||
try:
|
||||
await asyncio.wait_for(stop.wait(), self.cfg.bundle_poll_s)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
now = self.bundles.stamps()
|
||||
if now != last:
|
||||
for kind, a, b in zip(("tariff", "model"), last, now):
|
||||
if a != b and b is not None:
|
||||
f = self.bundles.tariff if kind == "tariff" else self.bundles.model
|
||||
d = f.get() or {}
|
||||
await self._received(kind, {"id": d.get("id", "")}, "cloud",
|
||||
d != {}, f.error or "stored")
|
||||
last = now
|
||||
log.info("plan: a new tariff or model: planning again")
|
||||
self.wake.set()
|
||||
|
||||
async def _planner(self, stop):
|
||||
woken = False
|
||||
while not stop.is_set():
|
||||
if woken and self.cfg.replan_debounce_s > 0:
|
||||
# several changes often come together (mode, limits, a
|
||||
# tariff): one plan after a short pause, not one each
|
||||
try:
|
||||
await asyncio.wait_for(stop.wait(), self.cfg.replan_debounce_s)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
if self.mode() != "off" and self.client is not None:
|
||||
try:
|
||||
await self.make_plan()
|
||||
except Exception as e:
|
||||
log.warning("plan: %s", e)
|
||||
self.wake.clear()
|
||||
woken = False
|
||||
try:
|
||||
await asyncio.wait_for(asyncio.wait([asyncio.ensure_future(stop.wait()),
|
||||
asyncio.ensure_future(self.wake.wait())],
|
||||
return_when=asyncio.FIRST_COMPLETED),
|
||||
self.cfg.control_interval_s)
|
||||
woken = self.wake.is_set()
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
async def _actor(self, stop):
|
||||
while not stop.is_set():
|
||||
now = self.clock()
|
||||
self.history.add("load_w", self.col.total(self.inputs.load_power), now)
|
||||
self.history.add("pv_w", self.col.total(self.inputs.pv_power), now)
|
||||
if int(now) % 900 < 60:
|
||||
try:
|
||||
self.history.save(now)
|
||||
except OSError as e:
|
||||
log.warning("history: %s", e)
|
||||
self.executor.inputs_ok = self.inputs_fresh()
|
||||
self.grid_tick()
|
||||
if self.switch_sides():
|
||||
self.wake.set() # heating <-> cooling: a plan for the new side
|
||||
try:
|
||||
await self.executor.tick(self.client, self.mode() == "auto")
|
||||
except Exception as e:
|
||||
log.warning("actions: %s", e)
|
||||
self.act_now.clear()
|
||||
try:
|
||||
await asyncio.wait_for(asyncio.wait([asyncio.ensure_future(stop.wait()),
|
||||
asyncio.ensure_future(self.act_now.wait())],
|
||||
return_when=asyncio.FIRST_COMPLETED),
|
||||
self.cfg.act_interval_s)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
# -- commands ------------------------------------------------------------
|
||||
async def command(self, cmd: str, args: dict) -> tuple[bool, str]:
|
||||
ok, why = await self._command(cmd, args)
|
||||
await self._received(cmd, args, sender(cmd, args), ok, why)
|
||||
return ok, why
|
||||
|
||||
async def _received(self, cmd: str, args: dict, by: str, ok: bool, why: str):
|
||||
ev = {"at": int(self.clock()), "cmd": cmd, "by": by, "args": public_args(args),
|
||||
"result": "applied" if ok else "refused", "why": why}
|
||||
self.received = (self.received + [ev])[-50:]
|
||||
for cb in self.on_received:
|
||||
try:
|
||||
await cb(ev)
|
||||
except Exception as e:
|
||||
log.warning("received: %s", e)
|
||||
|
||||
async def _command(self, cmd: str, args: dict) -> tuple[bool, str]:
|
||||
now = self.clock()
|
||||
if cmd == "mode":
|
||||
m = args.get("mode", "")
|
||||
if m not in MODES:
|
||||
return False, f"mode: one of {', '.join(MODES)}"
|
||||
self.mode.set(m, args.get("by", "console"))
|
||||
log.info("mode %s (console)", m)
|
||||
self.wake.set() # a plan in the new mode now
|
||||
if m in ("advisory", "auto") and not any(c.consent for c in self.controls):
|
||||
return True, f"mode {m}; note: no control has consent, nothing will be acted on"
|
||||
return True, f"mode {m}"
|
||||
if cmd == "control":
|
||||
ok, msg = self.executor.command(args, now)
|
||||
if ok:
|
||||
self.act_now.set()
|
||||
return ok, msg
|
||||
if cmd == "release":
|
||||
ok, msg = self.executor.release(args.get("asset", ""))
|
||||
if ok:
|
||||
self.act_now.set() # back to the plan now, not at the next round
|
||||
return ok, msg
|
||||
if cmd == "limits":
|
||||
ok, msg = self.set_limit(args, now)
|
||||
if ok:
|
||||
self.wake.set() # a plan within the new limits now
|
||||
return ok, msg
|
||||
if cmd == "building":
|
||||
return await self.building_command(args, now)
|
||||
return False, f"unknown command {cmd!r}"
|
||||
|
||||
async def building_command(self, args: dict, now: float) -> tuple[bool, str]:
|
||||
try:
|
||||
c = Building.parse(args)
|
||||
except ValueError as e:
|
||||
return False, str(e)
|
||||
floors = []
|
||||
for ctl in self.controls:
|
||||
if ctl.kind in ("heating", "cooling"):
|
||||
b = ctl.bounds("temp_c", self.guard.extra_limits.get(ctl.id))
|
||||
floors.append((ctl.id, b.lo, b.hi, ctl.kind))
|
||||
ok, msg = self.building.take(c, floors)
|
||||
await self._publish("action", building_msg(c, "done" if ok else "refused", msg if ok else msg, now))
|
||||
if ok:
|
||||
self.wake.set() # a plan with it now
|
||||
return ok, msg
|
||||
|
||||
def set_limit(self, a: dict, now: float) -> tuple[bool, str]:
|
||||
from .limits import QUANTITIES
|
||||
c = {c.id: c for c in self.controls}.get(a.get("asset", ""))
|
||||
if c is None:
|
||||
return False, f"no control {a.get('asset')!r}"
|
||||
q, lvl = a.get("quantity", ""), a.get("level", "")
|
||||
if q not in QUANTITIES or lvl not in ("cloud", "building", "grid"):
|
||||
return False, "quantity: one of " + ", ".join(QUANTITIES) + "; level: cloud, building or grid"
|
||||
try:
|
||||
f = float(a["floor"]) if a.get("floor") not in (None, "") else None
|
||||
lim = float(a["limit"]) if a.get("limit") not in (None, "") else None
|
||||
except ValueError:
|
||||
return False, "floor and limit: numbers (or empty: none)"
|
||||
if f is not None and lim is not None and f > lim:
|
||||
return False, "floor above limit"
|
||||
per = self.saved_limits.setdefault(c.id, {}).setdefault(q, {})
|
||||
if f is None and lim is None:
|
||||
per.pop(lvl, None)
|
||||
else:
|
||||
per[lvl] = (f, lim)
|
||||
self._save_limits()
|
||||
self._merge_limits()
|
||||
b = c.bounds(q, self.guard.extra_limits.get(c.id))
|
||||
self.wake.set()
|
||||
return True, f"{c.id} {q}: {b.lo:g}..{b.hi:g} now (floor by {b.lo_by}, limit by {b.hi_by})"
|
||||
|
||||
def _load_limits(self) -> dict:
|
||||
try:
|
||||
with open(os.path.join(self.cfg.state_dir, "limits.json")) as f:
|
||||
raw = json.load(f)
|
||||
return {c: {q: {lvl: tuple(v) for lvl, v in lv.items()} for q, lv in qs.items()} for c, qs in raw.items()}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return {}
|
||||
|
||||
def _save_limits(self):
|
||||
p = os.path.join(self.cfg.state_dir, "limits.json")
|
||||
with open(p + ".tmp", "w") as f:
|
||||
json.dump(self.saved_limits, f)
|
||||
os.replace(p + ".tmp", p)
|
||||
|
||||
|
||||
# -- the grid operator's limit (EEBUS LPC, gridorder.py) -----------------
|
||||
def _merge_limits(self):
|
||||
"""The guard's limits: the console's, and over them the grid order's
|
||||
at level grid (the lower limit of the two holds)."""
|
||||
merged = {c: {q: dict(lv) for q, lv in qs.items()} for c, qs in self.saved_limits.items()}
|
||||
for cid, qs in self.gridorders.limits(self.controls).items():
|
||||
for q, (f, lim) in qs.items():
|
||||
per = merged.setdefault(cid, {}).setdefault(q, {})
|
||||
old = per.get("grid")
|
||||
if old and old[1] is not None and lim is not None:
|
||||
lim = min(lim, old[1])
|
||||
per["grid"] = (old[0] if old else f, lim)
|
||||
self.guard.extra_limits = merged
|
||||
|
||||
async def grid_order(self, payload: bytes) -> bool:
|
||||
"""A message on cantabile-eebus/gridorder (the announcer's MQTT
|
||||
session): a changed order is a grid operator's decision: limits now,
|
||||
a plan within them now, and shown to the owner like a command."""
|
||||
changed, why = self.gridorders.take(payload)
|
||||
if not changed:
|
||||
return False
|
||||
self._merge_limits()
|
||||
o = self.gridorders.active()
|
||||
args = {"level": "emergency", "control": "load_limit", "source": "eebus-lpc"}
|
||||
if o:
|
||||
args.update(id=o["id"], value=str(o["limit_w"]), until=str(o.get("until") or ""), state=o.get("state", ""),
|
||||
proof=self.gridorders.proof())
|
||||
log.warning("grid operator's limit %.0f W (%s, order %s): planning within it", o["limit_w"], o.get("state"), o["id"])
|
||||
else:
|
||||
args.update(value="", state="normal")
|
||||
log.info("grid operator's limit ended")
|
||||
await self._received("grid", args, "grid", True, "limited" if o else "ended")
|
||||
self.wake.set()
|
||||
self.act_now.set()
|
||||
return True
|
||||
|
||||
def grid_tick(self):
|
||||
"""An order that went stale or ended takes its limits away."""
|
||||
if self.gridorders.order and not self.gridorders.active() and any(
|
||||
"grid" in lv for qs in self.guard.extra_limits.values() for lv in qs.values()) \
|
||||
and not any("grid" in lv for qs in self.saved_limits.values() for lv in qs.values()):
|
||||
self._merge_limits()
|
||||
self.wake.set()
|
||||
|
||||
|
||||
def sender(cmd: str, args: dict) -> str:
|
||||
"""Who a command comes from, for the owner (HA): the building's requests
|
||||
(a relayed grid order: the grid operator), limits at their level, the
|
||||
rest from Cantabile's cloud (the console)."""
|
||||
if cmd == "building":
|
||||
return "grid" if args.get("level") == "emergency" else "building"
|
||||
if cmd == "limits" and args.get("level") in ("building", "grid"):
|
||||
return args["level"]
|
||||
return "cloud"
|
||||
|
||||
|
||||
SECRET_ARGS = ("proof", "sig", "bundle", "token", "password")
|
||||
|
||||
|
||||
def public_args(args: dict) -> dict:
|
||||
"""A command's arguments as HA may show them: no signatures, proofs or
|
||||
bundles, short values."""
|
||||
return {k: str(v)[:120] for k, v in (args or {}).items() if k not in SECRET_ARGS}
|
||||
|
||||
|
||||
async def solve(state: dict, timeout: float) -> dict:
|
||||
"""The optimiser in a subprocess: a bad model or a long solve never
|
||||
stops the agent; past the timeout it is killed."""
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
sys.executable, "-m", "cantabile_edge.optimizer", str(max(5.0, timeout - 5)),
|
||||
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
|
||||
try:
|
||||
out, err = await asyncio.wait_for(proc.communicate(json.dumps(state).encode()), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
proc.kill()
|
||||
await proc.wait()
|
||||
return {"error": f"the optimiser took longer than {timeout:g} s"}
|
||||
try:
|
||||
return json.loads(out)
|
||||
except ValueError:
|
||||
return {"error": (err.decode(errors="replace").strip().splitlines() or ["no output"])[-1][:300]}
|
||||
@@ -0,0 +1,272 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""What the agent may control (mapping v3, `controls:`), and how.
|
||||
|
||||
A control is one device the optimiser plans for and the executor may act
|
||||
on, always through Home Assistant service calls on the control's own
|
||||
entities (the agent never talks to devices). Every control has its own
|
||||
consent, separate from the reading consent of the mapping's assets and off
|
||||
by default: an installer or the owner turns it on per control. On top of
|
||||
that the owner's consent for the whole site must cover control
|
||||
(consent.py, "control": true).
|
||||
|
||||
controls:
|
||||
- id: battery # the asset id plans and actions use
|
||||
name: Home battery # optional: how HA and the dashboard call it
|
||||
kind: battery
|
||||
consent: false
|
||||
entities: {charge_from_grid: switch.inverter_charge_from_grid,
|
||||
setpoint: number.battery_power, soc: sensor.battery_soc}
|
||||
params: {capacity_wh: 10000, max_charge_w: 3000, max_discharge_w: 3000}
|
||||
limits: {soc_pct: {owner: [20, 100]}}
|
||||
safe: {charge_from_grid: false}
|
||||
|
||||
params.min_switch_s: how long an on/off switch or mode stays before it
|
||||
may change again (anti-cycling). It protects equipment that wears from
|
||||
short cycles (compressors, burners): heating and cooling 600 s by default;
|
||||
0 for batteries, EV chargers and covers, which a release or a new plan may
|
||||
change at once.
|
||||
|
||||
Kinds, their entities (* needed) and what the executor sets (channels):
|
||||
battery charge_from_grid (switch) and/or setpoint (number, W: + charge,
|
||||
- discharge); mode (select: the inverter's own mode, set to
|
||||
params.manual_option while the plan sets power, else to
|
||||
params.auto_option); soc (sensor %), power (sensor W).
|
||||
With a setpoint the agent sets the power there (and the mode)
|
||||
and keeps charge_from_grid OFF: on many inverters (and the
|
||||
simulated ones) the switch means "charge at full power" and would
|
||||
override the setpoint (seen in simulation: 5000 W for 3000).
|
||||
Only a battery without a setpoint (an HM8042 as the
|
||||
profile has it: the switch alone) is driven through charge_from_grid.
|
||||
heating climate* (target temperature) or switch* (on/off, a boiler);
|
||||
temp (sensor °C, else the climate's current temperature)
|
||||
cooling climate* (hvac_mode cool/off, target temperature); temp
|
||||
A climate's own range (its min_temp..max_temp) narrows the
|
||||
kind's range, and a target temperature is rounded to its
|
||||
target_temp_step (any thermostat: hub/profiles/ha-thermostat.json).
|
||||
ev switch* (charging on/off); current (number A); connected
|
||||
(binary_sensor); soc (sensor %); energy_needed (sensor Wh/kWh)
|
||||
and departure (sensor: a time) override params need_wh/departure
|
||||
cover cover* (position %; open/close only where the cover cannot be
|
||||
set to a position); room: the heating/cooling control whose
|
||||
room it shades (params.room), area: the room's name (its
|
||||
room.<area>.temp and .setpoint), facing: the window's
|
||||
orientation (degrees from north, -1 not known); its moves come
|
||||
from rules on the sun (shades.py): quiet_from..quiet_to no
|
||||
moves (night_moves 1: allowed), min_move_s between moves,
|
||||
override_hold_s off it after the owner moved it by hand
|
||||
|
||||
Two controls never write the same entity, with one exception: a heating
|
||||
and a cooling control on one climate that both have `switchover` (a
|
||||
thermostat that can do both); only one of them is active at a time
|
||||
(switchover.py). Any other control that writes an entity an earlier one
|
||||
writes is left out (mapping.py, logged).
|
||||
"""
|
||||
import logging
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from . import limits as limits_mod
|
||||
from . import switchover as switchover_mod
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# kind -> {entity role: allowed domains}; the roles the executor writes
|
||||
ENTITIES = {
|
||||
"battery": {"charge_from_grid": ("switch", "input_boolean"), "setpoint": ("number", "input_number"),
|
||||
"mode": ("select", "input_select"), "soc": ("sensor", "input_number"), "power": ("sensor",)},
|
||||
"heating": {"climate": ("climate",), "switch": ("switch", "input_boolean"), "temp": ("sensor",)},
|
||||
"cooling": {"climate": ("climate",), "temp": ("sensor",)},
|
||||
"ev": {"switch": ("switch", "input_boolean"), "current": ("number", "input_number"),
|
||||
"connected": ("binary_sensor", "input_boolean"), "soc": ("sensor", "input_number"),
|
||||
"energy_needed": ("sensor",), "departure": ("sensor", "input_datetime")},
|
||||
"cover": {"cover": ("cover",)},
|
||||
}
|
||||
WRITES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover"}
|
||||
NEEDED = {"battery": (("charge_from_grid", "setpoint"),), "heating": (("climate", "switch"),),
|
||||
"cooling": (("climate",),), "ev": (("switch",),), "cover": (("cover",),)}
|
||||
# defaults per kind (params may override each)
|
||||
PARAMS = {
|
||||
"battery": {"capacity_wh": 5000.0, "max_charge_w": 2500.0, "max_discharge_w": 2500.0, "efficiency": 0.95,
|
||||
"soc_pct": 50.0, # soc_pct: the estimate when no sensor says
|
||||
"manual_option": "manual", "auto_option": "self-consumption", "min_switch_s": 0.0},
|
||||
"heating": {"r_k_per_kw": 10.0, "c_kwh_per_k": 3.0, "max_power_w": 2000.0, "comfort_c": 21.0,
|
||||
"setback_c": 17.0, "cop": 1.0, # cop 1: electric; a heat pump ~3
|
||||
"min_switch_s": 600.0},
|
||||
"cooling": {"r_k_per_kw": 10.0, "c_kwh_per_k": 3.0, "max_power_w": 1500.0, "comfort_c": 25.0,
|
||||
"setup_c": 28.0, "cop": 3.0, "min_switch_s": 600.0},
|
||||
"ev": {"need_wh": 10000.0, "departure": "07:00", "min_current_a": 6.0, "max_current_a": 16.0,
|
||||
"phases": 1.0, "voltage": 230.0, "min_switch_s": 0.0},
|
||||
"cover": {"room": "", "gain_w": 800.0, "min_switch_s": 0.0, "area": "", "facing": -1.0,
|
||||
"open_pct": 100.0, "shade_pct": 30.0, "closed_pct": 0.0, "quiet_from": "22:00", "quiet_to": "07:00",
|
||||
"night_moves": 0.0, "min_move_s": 1800.0, "override_hold_s": 14400.0},
|
||||
}
|
||||
HHMM_RE = re.compile(r"^([01][0-9]|2[0-3]):[0-5][0-9]$")
|
||||
# each kind's device range per quantity (firmware's; limits.effective)
|
||||
RANGE = {
|
||||
"battery": {"soc_pct": (0.0, 100.0)},
|
||||
"heating": {"temp_c": (5.0, 30.0)},
|
||||
"cooling": {"temp_c": (16.0, 32.0)},
|
||||
"ev": {"current_a": (0.0, 32.0)},
|
||||
"cover": {"position_pct": (0.0, 100.0)},
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Control:
|
||||
id: str
|
||||
kind: str
|
||||
entities: dict[str, str]
|
||||
consent: bool = False
|
||||
params: dict = field(default_factory=dict)
|
||||
limits: dict = field(default_factory=dict) # quantity -> level -> (floor, limit)
|
||||
safe: dict = field(default_factory=dict) # channel -> value when plans or data are stale
|
||||
device: str = "" # the box's device it came with (mapping.d; policy.py)
|
||||
entity_range: dict = field(default_factory=dict) # quantity -> (lo, hi) the device itself reports (a climate's)
|
||||
switchover: dict = field(default_factory=dict) # heating/cooling pair on one climate (switchover.py)
|
||||
name: str = "" # the owner's name for it (mapping `name`), else label() guesses
|
||||
|
||||
def label(self) -> str:
|
||||
"""A name for people: the mapping's, else the id in words
|
||||
("living_room_cooling": "Living room cooling")."""
|
||||
return self.name or (self.id.replace("_", " ").strip().capitalize() or self.id)
|
||||
|
||||
def p(self, name: str) -> float | str:
|
||||
return self.params.get(name, PARAMS[self.kind][name])
|
||||
|
||||
def device_range(self, q: str) -> tuple[float, float]:
|
||||
if self.kind == "battery" and q == "power_w":
|
||||
return (-float(self.p("max_discharge_w")), float(self.p("max_charge_w")))
|
||||
if self.kind == "ev" and q == "current_a":
|
||||
return (0.0, float(self.p("max_current_a")))
|
||||
lo, hi = RANGE[self.kind][q]
|
||||
own = self.entity_range.get(q)
|
||||
if own and max(lo, own[0]) <= min(hi, own[1]):
|
||||
lo, hi = max(lo, own[0]), min(hi, own[1])
|
||||
return (lo, hi)
|
||||
|
||||
def learn_range(self, col):
|
||||
"""A climate's own min_temp..max_temp (HA's attributes, from the
|
||||
collector): the setpoint never goes outside it."""
|
||||
ent = self.entities.get("climate")
|
||||
if not ent or col is None:
|
||||
return
|
||||
lo, hi = _num(col.attr(ent, "min_temp")), _num(col.attr(ent, "max_temp"))
|
||||
if lo is not None and hi is not None and lo <= hi:
|
||||
self.entity_range["temp_c"] = (lo, hi)
|
||||
|
||||
def temp_step(self, col) -> float:
|
||||
ent = self.entities.get("climate")
|
||||
step = _num(col.attr(ent, "target_temp_step")) if ent and col is not None else None
|
||||
return step if step and step > 0 else 0.0
|
||||
|
||||
def bounds(self, q: str, extra: dict | None = None) -> limits_mod.Bounds:
|
||||
"""Effective bounds: the mapping's levels plus those commands set
|
||||
(cloud, building, grid: extra)."""
|
||||
layers = dict(self.limits.get(q, {}))
|
||||
layers.update((extra or {}).get(q, {}))
|
||||
return limits_mod.effective(self.device_range(q), layers)
|
||||
|
||||
def writable(self) -> dict[str, str]:
|
||||
"""role -> entity for the entities the executor may write."""
|
||||
return {r: e for r, e in self.entities.items() if r in WRITES}
|
||||
|
||||
|
||||
def _num(v) -> float | None:
|
||||
try:
|
||||
x = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return x if x == x and abs(x) != float("inf") else None
|
||||
|
||||
|
||||
def _check_cover(cid: str, p: dict):
|
||||
for k in ("open_pct", "shade_pct", "closed_pct"):
|
||||
if k in p and (_num(p[k]) is None or not 0 <= float(p[k]) <= 100):
|
||||
raise ValueError(f"control {cid}: {k} is 0-100 (%)")
|
||||
if "facing" in p and (_num(p["facing"]) is None or not (float(p["facing"]) == -1 or 0 <= float(p["facing"]) <= 360)):
|
||||
raise ValueError(f"control {cid}: facing is degrees from north (0-360), -1 when not known")
|
||||
for k in ("quiet_from", "quiet_to"):
|
||||
if k in p and not HHMM_RE.match(str(p[k])):
|
||||
raise ValueError(f"control {cid}: {k} is a time, HH:MM")
|
||||
for k in ("min_move_s", "override_hold_s", "night_moves", "gain_w"):
|
||||
if k in p and (_num(p[k]) is None or float(p[k]) < 0):
|
||||
raise ValueError(f"control {cid}: {k} is a number, 0 or more")
|
||||
|
||||
|
||||
def parse(raw: list | None, reading_assets: set[str], rooms: set[str] | None = None,
|
||||
strict: bool = True) -> list[Control]:
|
||||
"""The controls of one list (the mapping's or a device's fragment).
|
||||
rooms: heating and cooling controls elsewhere on the site (a cover in a
|
||||
device's fragment shades a room another device heats). A cover's room
|
||||
that is no heating or cooling control is an error (strict: the
|
||||
mapping's own), else dropped (logged: a device's fragment)."""
|
||||
out, seen = [], set()
|
||||
for c in raw or []:
|
||||
cid, kind = c.get("id", ""), c.get("kind", "")
|
||||
if kind not in ENTITIES:
|
||||
raise ValueError(f"control {cid!r}: kind must be one of {', '.join(ENTITIES)}")
|
||||
if not cid or cid in seen or cid in reading_assets:
|
||||
raise ValueError(f"control id {cid!r}: needed, and unique among controls and assets")
|
||||
seen.add(cid)
|
||||
ents = c.get("entities") or {}
|
||||
for role, eid in ents.items():
|
||||
doms = ENTITIES[kind].get(role)
|
||||
if doms is None:
|
||||
raise ValueError(f"control {cid}: a {kind} has no entity role {role!r}")
|
||||
if eid.split(".", 1)[0] not in doms:
|
||||
raise ValueError(f"control {cid}: {role} must be a {' or '.join(doms)} entity, not {eid}")
|
||||
for alts in NEEDED[kind]:
|
||||
if not any(a in ents for a in alts):
|
||||
raise ValueError(f"control {cid}: needs {' or '.join(alts)}")
|
||||
params = dict(c.get("params") or {})
|
||||
unknown = set(params) - set(PARAMS[kind])
|
||||
if unknown:
|
||||
raise ValueError(f"control {cid}: unknown params {', '.join(sorted(unknown))}")
|
||||
if kind == "cover":
|
||||
_check_cover(cid, params)
|
||||
sw = {}
|
||||
if c.get("switchover") is not None:
|
||||
if kind not in ("heating", "cooling") or "climate" not in ents:
|
||||
raise ValueError(f"control {cid}: switchover only on a heating or cooling climate")
|
||||
sw = switchover_mod.check(c["switchover"])
|
||||
out.append(Control(cid, kind, dict(ents), bool(c.get("consent", False)), params,
|
||||
limits_mod.parse(c.get("limits")), dict(c.get("safe") or {}), switchover=sw,
|
||||
name=str(c.get("name") or "")[:60]))
|
||||
# a cover's room is a heating or cooling control
|
||||
known = {c.id for c in out if c.kind in ("heating", "cooling")} | set(rooms or ())
|
||||
for c in out:
|
||||
if c.kind == "cover" and c.p("room") and c.p("room") not in known:
|
||||
if strict:
|
||||
raise ValueError(f"control {c.id}: room {c.p('room')!r} is no heating or cooling control")
|
||||
log.warning("control %s: room %r is no heating or cooling control: left out", c.id, c.p("room"))
|
||||
c.params.pop("room", None)
|
||||
return out
|
||||
|
||||
|
||||
@dataclass
|
||||
class Inputs:
|
||||
"""Sensors the optimiser reads (mapping v3, `inputs:`); they never
|
||||
leave the site (the plan does, not these)."""
|
||||
presence: list[str] = field(default_factory=list) # binary_sensor / input_boolean / person
|
||||
outside_temp: str = ""
|
||||
weather: str = "" # weather.* (now and its hourly forecast)
|
||||
sun: str = "sun.sun"
|
||||
load_power: str | list = "" # sensor W: the house's load (history fallback)
|
||||
pv_power: str | list = "" # sensor W: PV (history fallback); a list: their sum
|
||||
humidity: list[str] = field(default_factory=list)
|
||||
|
||||
def entities(self) -> list[str]:
|
||||
one = [self.outside_temp, self.weather, self.sun]
|
||||
summed = [e for x in (self.load_power, self.pv_power) for e in ([x] if isinstance(x, str) else x)]
|
||||
return [e for e in self.presence + self.humidity + one + summed if e]
|
||||
|
||||
|
||||
def parse_inputs(raw: dict | None) -> Inputs:
|
||||
raw = dict(raw or {})
|
||||
for k in ("presence", "humidity"):
|
||||
if isinstance(raw.get(k), str):
|
||||
raw[k] = [raw[k]]
|
||||
unknown = set(raw) - set(Inputs.__dataclass_fields__)
|
||||
if unknown:
|
||||
raise ValueError(f"inputs: unknown keys {', '.join(sorted(unknown))}")
|
||||
return Inputs(**raw)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,776 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The add-on's Devices page ("HA-only sites"): what the Hub
|
||||
panel's Devices section does with devices Home Assistant has already, on
|
||||
the add-on's own page (HA's ingress; reached from Cantabile's dashboard,
|
||||
not the sidebar). With the Building or community page (joinpage.py) it
|
||||
makes the add-on's small app (App): ?p=devices (the first page) and
|
||||
?p=building; Cantabile's dashboard opens them as /app/<slug>#devices and
|
||||
#building (the page takes HA's hash at start, as the Modbus bridge's does).
|
||||
|
||||
For each HA device a device profile recognises (specific profiles first; a
|
||||
generic one such as ha-thermostat only where none fits) the page shows what
|
||||
Cantabile would read and could control. "Use with Cantabile" writes the
|
||||
device's mapping fragment, <mapping dir>/mapping.d/<id>.yaml, as the Hub's
|
||||
devices tool does and with the same shared code (devprofiles.py): every
|
||||
value and control with consent off, the profile's protection defaults in
|
||||
<state dir>/protection.json, the device in <state dir>/devices.json and its
|
||||
specs for the inventory (devices-specs.json). The agent then loads the
|
||||
mapping again (agent.devices_changed): the device is on Cantabile's
|
||||
dashboard, and in HA's area "Cantabile" when it has no area of its own.
|
||||
Nothing is installed or set up in HA here: no add-on installs, no
|
||||
integrations (the owner's own HA does that); only devices HA has.
|
||||
|
||||
The mapping's proposal (propose.py) and the owner's devices: a proposal is
|
||||
a starting point; "Use with Cantabile" is the owner's confirmation, and
|
||||
from then on the proposal leaves that device (its entities, ids and summed
|
||||
systems) to its fragment. Removing the device gives it back to the
|
||||
proposal. A mapping written by hand is never changed: its entries win and
|
||||
are left out of a device's fragment (shown). One writer per entity: a
|
||||
control on an entity another control writes is left out.
|
||||
|
||||
Owner only, both pages: every request must come from a Home Assistant
|
||||
administrator.
|
||||
panel_admin only keeps the sidebar entry from other users; HA lets any
|
||||
signed-in user open an add-on's ingress session. So the page asks HA who
|
||||
the user is (the ingress proxy's X-Remote-User-Id) and refuses anyone else.
|
||||
|
||||
Consent: an HA add-on site's consent is
|
||||
given when the add-on is installed from Cantabile's repository, in its
|
||||
configuration (addon-run records it in <state dir>/consent.json: share,
|
||||
control, the texts' version, source). With it, each device's reading and
|
||||
control are switched on here as on the Hub's Devices page (the agent starts
|
||||
again, as the Hub's tool restarts it); without it the page points to the
|
||||
add-on's configuration. Protection (protected / not, never sealed) and a thermostat's heating or
|
||||
cooling choice are the owner's, here as on the Hub.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import yaml
|
||||
|
||||
from . import devprofiles as dp
|
||||
from .consent import Consent
|
||||
from . import i18n
|
||||
from .i18n import M, T, TN
|
||||
from .joinpage import CSS, E, JoinPage
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
PAGES = ("devices", "building")
|
||||
SWITCHOVER_WORDS = {"heating": M("Heating"), "cooling": M("Cooling"),
|
||||
"season": M("By season (heating October to April, cooling May to September)"),
|
||||
"outdoor": M("By outdoor temperature")}
|
||||
CUSTODIAN_WORDS = {"building_operator": M("the building's operator"), "grid_operator": M("the grid operator"),
|
||||
"metering_operator": M("the metering operator"), "community_operator": M("the energy community's operator")}
|
||||
PROFILE_STATUS = {"verified": M("Checked on a device"),
|
||||
"documented": M("From the maker's documentation, not yet checked on a device"),
|
||||
"draft": M("Draft: check the values before you turn reading on")}
|
||||
CONTROL_WORDS = {"battery": M("battery"), "heating": M("heating"), "cooling": M("cooling"), "ev": M("charging"),
|
||||
"cover": M("blinds and curtains")}
|
||||
MORE_CSS = """nav{display:flex;gap:1rem;margin:0 0 1rem;border-bottom:1px solid #d5ded9;padding-bottom:.5rem}
|
||||
nav a{color:inherit;text-decoration:none}nav a.on{font-weight:600;border-bottom:2px solid #2f6f55}
|
||||
.badge{display:inline-block;font-size:.8rem;padding:.05rem .45rem;border-radius:4px;background:#e2e9e5;margin-left:.3rem}
|
||||
ul.plain{margin:.3rem 0;padding-left:1.2rem}form.inline{display:inline}form.inline button{margin:0 0 0 .4rem;padding:.2rem .6rem}
|
||||
@media (prefers-color-scheme:dark){nav{border-color:#2b3a32}.badge{background:#2b3a32}}"""
|
||||
# HA's hash (#devices, #building: Cantabile's dashboard) to this page's ?p=
|
||||
HASH_SCRIPT = ("(function(){try{var P=window.parent;if(P===window)return;var m=/^#(devices|building)$/.exec(P.location.hash||'');"
|
||||
"if(m&&location.search.indexOf('p=')<0&&location.search.indexOf('code=')<0)location.replace('?p='+m[1])}"
|
||||
"catch(x){}})();")
|
||||
|
||||
|
||||
def _read_json(path: str, default):
|
||||
try:
|
||||
with open(path) as f:
|
||||
v = json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return default
|
||||
return v if isinstance(v, type(default)) else default
|
||||
|
||||
|
||||
def _write_json(path: str, data, mode: int = 0o644):
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
tmp = path + ".tmp"
|
||||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
json.dump(data, f, indent=1, sort_keys=True, ensure_ascii=False)
|
||||
f.write("\n")
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def quantity_words(q: str) -> str:
|
||||
return q.replace("_", " ").replace(".", ": ", 1)
|
||||
|
||||
|
||||
def with_attrs(ents: list[dict], states: dict) -> list[dict]:
|
||||
"""Registry entries with HA's attributes now (where the state is known:
|
||||
the profiles' conditions on attributes, as the Hub's registry has them)."""
|
||||
out = []
|
||||
for e in ents:
|
||||
st = states.get(e["entity_id"])
|
||||
if st and st.get("state") not in ("unavailable", "unknown"):
|
||||
e = dict(e, attributes=st.get("attributes") or {})
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
class Devices:
|
||||
"""The devices used with Cantabile on this site and HA's offers; the
|
||||
page's actions. ha(): the agent's HA client (None while not connected);
|
||||
changed(): the agent loads the mapping again."""
|
||||
|
||||
def __init__(self, mapping_path: str, state_dir: str, profiles: list[dict], ha=lambda: None, changed=None):
|
||||
self.mapping_path, self.state_dir, self.profiles = mapping_path, state_dir, profiles
|
||||
self.ha, self.changed = ha, changed
|
||||
self.mapping_d = os.path.join(os.path.dirname(mapping_path) or ".", "mapping.d")
|
||||
self.devices_path = os.path.join(state_dir, "devices.json")
|
||||
self.lock = asyncio.Lock()
|
||||
|
||||
# -- files ------------------------------------------------------------------------
|
||||
def load(self) -> dict:
|
||||
return {k: v for k, v in _read_json(self.devices_path, {}).items() if isinstance(v, dict)}
|
||||
|
||||
def save(self, devs: dict):
|
||||
_write_json(self.devices_path, devs, 0o600)
|
||||
|
||||
def frag_path(self, dev_id: str) -> str:
|
||||
return os.path.join(self.mapping_d, f"{dev_id}.yaml")
|
||||
|
||||
def frag(self, dev_id: str) -> dict:
|
||||
return _read_json(self.frag_path(dev_id), {})
|
||||
|
||||
def write_frag(self, dev_id: str, frag: dict):
|
||||
os.makedirs(self.mapping_d, mode=0o755, exist_ok=True)
|
||||
_write_json(self.frag_path(dev_id), frag, 0o644) # JSON is YAML
|
||||
|
||||
def main(self) -> dict:
|
||||
"""The site's own mapping (mapping.yaml)."""
|
||||
try:
|
||||
with open(self.mapping_path) as f:
|
||||
raw = yaml.safe_load(f) or {}
|
||||
except (OSError, yaml.YAMLError):
|
||||
raw = {}
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
|
||||
def local(self) -> dict:
|
||||
return dp.local_entries(_read_json(os.path.join(self.state_dir, "protection.json"), {}))
|
||||
|
||||
def save_local(self, entries: dict):
|
||||
_write_json(os.path.join(self.state_dir, "protection.json"), {"v": 1, "entries": entries})
|
||||
|
||||
def policy(self) -> dict:
|
||||
return dp.merge_policy(dp.acl_entries(_read_json(os.path.join(self.state_dir, "acl.json"), {})), self.local())
|
||||
|
||||
def profile(self, pid: str) -> dict | None:
|
||||
return next((p for p in self.profiles if p.get("id") == pid), None)
|
||||
|
||||
def write_specs(self, devs: dict):
|
||||
"""Each device's specs for the agent's inventory (as the Hub's tool)."""
|
||||
policy, out = self.policy(), {}
|
||||
for d in devs.values():
|
||||
p = self.profile(d["profile"]) or {}
|
||||
frag = self.frag(d["id"])
|
||||
lvl, e = dp.level_of(policy, [f"device:{d['id']}"])
|
||||
out[d["id"]] = {"name": d["name"], "profile": d["profile"], "profile_version": d.get("profile_version", ""),
|
||||
"category": d.get("category") or p.get("category", ""), "manufacturer": p.get("manufacturer", ""),
|
||||
"model": p.get("name", d["profile"]), "path": "existing", "ratings": d.get("ratings") or {},
|
||||
"ha_device": d.get("ha_device"), "entry_id": None, "entities": dp.fragment_entities(frag),
|
||||
"controls": [c["id"] for c in frag.get("controls", [])], "protection": lvl,
|
||||
"custodian": (e or {}).get("custodian")}
|
||||
_write_json(os.path.join(self.state_dir, "devices-specs.json"), {"v": 1, "made": int(time.time()), "devices": out})
|
||||
|
||||
# -- HA ---------------------------------------------------------------------------
|
||||
async def snapshot(self) -> tuple[dict, dict]:
|
||||
client = self.ha()
|
||||
if client is None:
|
||||
raise dp.Fail(T("Home Assistant is not connected yet; try again in a moment."))
|
||||
reg = dict(await client.registries())
|
||||
# each device's integrations, as the Hub's registry gives them: its
|
||||
# entities' platforms (the profiles' recognise.ha "domain")
|
||||
plat = {}
|
||||
for e in reg.get("entities") or []:
|
||||
if e.get("device_id") and e.get("platform"):
|
||||
plat.setdefault(e["device_id"], set()).add(e["platform"])
|
||||
reg["devices"] = [dict(d, domains=sorted(plat.get(d["id"], ()))) for d in reg.get("devices") or []]
|
||||
states = {s["entity_id"]: s for s in await client.send("get_states") or []}
|
||||
# each entity's device class (HA's state attribute: the owner's choice
|
||||
# in HA wins; also while unavailable): which profile fits (a garage
|
||||
# door is never a shade, a CPU temperature never a room's)
|
||||
reg["entities"] = [dict(e, device_class=((states.get(e.get("entity_id")) or {}).get("attributes") or {})
|
||||
.get("device_class") or e.get("device_class") or e.get("original_device_class"))
|
||||
for e in reg.get("entities") or []]
|
||||
return reg, states
|
||||
|
||||
# -- what a device would give ----------------------------------------------------------
|
||||
def plan(self, reg: dict, states: dict, ha_device: str, p: dict, dev_id: str, devs: dict) -> tuple:
|
||||
"""(setup path, fragment, missing, left out, entities) for an HA
|
||||
device with this profile, as "Use with Cantabile" would write it."""
|
||||
dv = next((d for d in reg.get("devices") or [] if d["id"] == ha_device), None)
|
||||
if not dv:
|
||||
raise dp.Fail(T("Home Assistant has no such device."))
|
||||
s = dp.setup_for(p, dv.get("domains") or [])
|
||||
if not s:
|
||||
raise dp.Fail(T("{profile}: this profile does not know the device's integration.", profile=p["name"]))
|
||||
s = dict(s, path="existing", fields=[])
|
||||
ents = with_attrs([e for e in reg.get("entities") or [] if e.get("device_id") == ha_device
|
||||
and not e.get("disabled_by")], states)
|
||||
main = self.main()
|
||||
proposed = main.get("source") == "proposed" # yields to the owner's devices (propose.py)
|
||||
others = [self.frag(i) for i in devs if i != dev_id]
|
||||
m_assets = [] if proposed else [a for a in main.get("assets") or [] if isinstance(a, dict)]
|
||||
m_controls = [] if proposed else [c for c in main.get("controls") or [] if isinstance(c, dict)]
|
||||
main_ids = {a.get("asset") for a in m_assets} | {c.get("id") for c in m_controls}
|
||||
taken = set(main_ids) | {a["asset"] for f in others for a in f.get("assets", [])} \
|
||||
| {c["id"] for f in others for c in f.get("controls", [])}
|
||||
frag, missing = dp.mapping_for(dev_id, p, s, ents, dp.area_of(reg, ents, ha_device), taken, main_ids)
|
||||
busy = {a.get("entity") for a in m_assets} | {a["entity"] for f in others for a in f.get("assets", [])}
|
||||
writes = dp.control_writes(m_controls) | {e for f in others for e in dp.control_writes(f.get("controls"))}
|
||||
gone_a, gone_c = dp.leave_out(frag, busy, writes)
|
||||
return s, frag, missing, {"values": gone_a, "controls": gone_c}, ents
|
||||
|
||||
async def view(self) -> dict:
|
||||
"""The page's data: the devices used here, HA's devices with a
|
||||
profile (and what each would give), the rest, or HA's error."""
|
||||
devs, policy = self.load(), self.policy()
|
||||
used = []
|
||||
for d in sorted(devs.values(), key=lambda d: d.get("added", 0)):
|
||||
frag, p = self.frag(d["id"]), self.profile(d["profile"]) or {}
|
||||
targets = dp.device_targets(d, frag, self.local())
|
||||
used.append(dict(d, manufacturer=p.get("manufacturer", ""), model=p.get("name", d["profile"]),
|
||||
status=p.get("status", ""), assets=frag.get("assets", []), controls=frag.get("controls", []),
|
||||
switchover=dp.switchover_of(frag), shade=dp.shade_of(frag), place=dp.place_of(frag),
|
||||
weather=dp.weather_of(frag), policy={t: policy[t] for t in targets if t in policy},
|
||||
protection=dp.level_of(policy, [f"device:{d['id']}"])[0]))
|
||||
try:
|
||||
reg, states = await self.snapshot()
|
||||
except Exception as e:
|
||||
return {"devices": used, "offers": [], "rest": [], "ha_error": str(e), "site": self.site(), "rooms": []}
|
||||
main = self.main()
|
||||
src = main.get("source")
|
||||
mapped = {}
|
||||
for a in main.get("assets") or []:
|
||||
if isinstance(a, dict):
|
||||
mapped.setdefault(a.get("entity"), []).append(a.get("asset"))
|
||||
by_dev = {}
|
||||
for e in reg.get("entities") or []:
|
||||
by_dev.setdefault(e.get("device_id"), []).append(e["entity_id"])
|
||||
offers, rest = [], []
|
||||
for h in dp.offers(reg, self.profiles, {d.get("ha_device") for d in devs.values()}):
|
||||
if not h["profiles"]:
|
||||
rest.append(h)
|
||||
continue
|
||||
p = self.profile(h["profiles"][0])
|
||||
try:
|
||||
_, frag, missing, gone, _ = self.plan(reg, states, h["id"], p, "preview", devs)
|
||||
except dp.Fail as e:
|
||||
frag, missing, gone = {"assets": [], "controls": []}, [str(e)], {"values": [], "controls": []}
|
||||
ids = [i for e in by_dev.get(h["id"], []) for i in mapped.get(e, [])]
|
||||
offers.append(dict(h, profile=p, assets=frag["assets"], controls=frag["controls"], missing=missing,
|
||||
left_out=gone, in_mapping=ids, mapping_source=src))
|
||||
rooms = sorted({a.get("name") for a in reg.get("areas") or [] if a.get("name")})
|
||||
return {"devices": used, "offers": offers, "rest": rest, "site": self.site(), "rooms": rooms}
|
||||
|
||||
# -- actions --------------------------------------------------------------------------
|
||||
def site(self) -> dict:
|
||||
"""The site's consent (the add-on's configuration): share, control."""
|
||||
c = Consent(self.state_dir)
|
||||
return {"share": c.share, "control": c.control}
|
||||
|
||||
async def _done(self, devs: dict, restart: bool = False):
|
||||
self.write_specs(devs)
|
||||
if self.changed is not None:
|
||||
await (self.changed(restart=True) if restart else self.changed())
|
||||
|
||||
async def use(self, ha_device: str, pid: str, name: str = "") -> dict:
|
||||
async with self.lock:
|
||||
p = self.profile(pid)
|
||||
if not p:
|
||||
raise dp.Fail(T("No such profile."))
|
||||
devs = self.load()
|
||||
if any(d.get("ha_device") == ha_device for d in devs.values()):
|
||||
raise dp.Fail(T("This device is used with Cantabile already."))
|
||||
reg, states = await self.snapshot()
|
||||
dev_id = dp.new_id(p, devs)
|
||||
s, frag, missing, gone, ents = self.plan(reg, states, ha_device, p, dev_id, devs)
|
||||
if not frag["assets"] and not frag["controls"]:
|
||||
raise dp.Fail(T("Home Assistant shows none of the values this profile knows, or your mapping has them "
|
||||
"all already."))
|
||||
dv = next(d for d in reg["devices"] if d["id"] == ha_device)
|
||||
name = (name or "").strip()[:60] or dv.get("name_by_user") or dv.get("name") or f"{p['manufacturer']} {p['name']}"
|
||||
dev = {"id": dev_id, "name": name, "profile": p["id"], "profile_version": p.get("version", ""),
|
||||
"path": "existing", "ha_device": ha_device, "added": int(time.time()), "read": False,
|
||||
"control": False, "category": p.get("category", ""), "ratings": dp.ratings_of(p, {}),
|
||||
"missing": missing, "left_out": gone}
|
||||
dp.one_weather(frag, [self.frag(i) for i in devs]) # one weather service plans
|
||||
self.write_frag(dev_id, frag)
|
||||
defaults = dp.profile_protection(dev_id, p, s, ents, frag)
|
||||
if defaults:
|
||||
entries = self.local()
|
||||
entries.update(defaults)
|
||||
self.save_local(entries)
|
||||
devs[dev_id] = dev
|
||||
self.save(devs)
|
||||
log.info("device %s (%s) used with Cantabile: %d values, %d controls, consent off", name, p["id"],
|
||||
len(frag["assets"]), len(frag["controls"]))
|
||||
await self._done(devs)
|
||||
return dev
|
||||
|
||||
def _dev(self, devs: dict, dev_id: str) -> dict:
|
||||
d = devs.get(dev_id)
|
||||
if not d:
|
||||
raise dp.Fail(T("No such device."))
|
||||
return d
|
||||
|
||||
async def remove(self, dev_id: str):
|
||||
async with self.lock:
|
||||
devs = self.load()
|
||||
dev = self._dev(devs, dev_id)
|
||||
frag = self.frag(dev_id)
|
||||
seal = dp.sealed(self.policy(), dev_id)
|
||||
if seal:
|
||||
raise dp.Fail(T("Sealed: only {who} can remove it.", who=custodian(seal)))
|
||||
mine = set(dp.device_targets(dev, frag, self.local()))
|
||||
try:
|
||||
os.remove(self.frag_path(dev_id))
|
||||
except OSError:
|
||||
pass
|
||||
entries = self.local()
|
||||
if mine & set(entries):
|
||||
self.save_local({t: e for t, e in entries.items() if t not in mine})
|
||||
del devs[dev_id]
|
||||
self.save(devs)
|
||||
log.info("device %s no longer used with Cantabile", dev["name"])
|
||||
await self._done(devs, restart=bool(dev.get("read") or dev.get("control")))
|
||||
|
||||
async def consent(self, dev_id: str, read: bool, control: bool):
|
||||
if not self.site()["share"]:
|
||||
raise dp.Fail(T("First give your consent in the add-on's configuration (Settings, Add-ons, Cantabile Edge "
|
||||
"Agent, Configuration)."))
|
||||
async with self.lock:
|
||||
devs = self.load()
|
||||
dev = self._dev(devs, dev_id)
|
||||
frag = self.frag(dev_id)
|
||||
if not frag:
|
||||
raise dp.Fail(T("The device's mapping is gone; use it with Cantabile again."))
|
||||
seal = dp.sealed(self.policy(), dev_id)
|
||||
if seal and bool(control) != bool(dev.get("control")):
|
||||
raise dp.Fail(T("Sealed: only {who} can change its control.", who=custodian(seal)))
|
||||
dev["read"], dev["control"] = bool(read), bool(control)
|
||||
dp.set_consent(frag, dev["read"], dev["control"])
|
||||
self.write_frag(dev_id, frag)
|
||||
self.save(devs)
|
||||
log.info("consent: %s: reading %s, control %s", dev["name"], "on" if dev["read"] else "off",
|
||||
"on" if dev["control"] else "off")
|
||||
await self._done(devs, restart=True)
|
||||
|
||||
async def protect(self, dev_id: str, target: str, level: str, by: str):
|
||||
async with self.lock:
|
||||
devs = self.load()
|
||||
dev = self._dev(devs, dev_id)
|
||||
frag = self.frag(dev_id)
|
||||
entries = self.local()
|
||||
target = target or f"device:{dev_id}"
|
||||
entries[target] = dp.owner_entry(self.policy(), dp.device_targets(dev, frag, entries), dev_id, target,
|
||||
level, by)
|
||||
self.save_local(entries)
|
||||
log.info("protection: %s: %s %s (by %s)", dev["name"], target, level, by)
|
||||
await self._done(devs)
|
||||
|
||||
async def switchover(self, dev_id: str, data: dict):
|
||||
async with self.lock:
|
||||
devs = self.load()
|
||||
dev = self._dev(devs, dev_id)
|
||||
frag = self.frag(dev_id)
|
||||
seal = dp.sealed(self.policy(), dev_id)
|
||||
if seal:
|
||||
raise dp.Fail(T("Sealed: only {who} can change its control.", who=custodian(seal)))
|
||||
sw = dp.set_switchover(frag, data)
|
||||
self.write_frag(dev_id, frag)
|
||||
log.info("heating or cooling: %s: %s", dev["name"], sw["mode"])
|
||||
await self._done(devs, restart=True)
|
||||
|
||||
|
||||
async def _setting(self, dev_id: str):
|
||||
devs = self.load()
|
||||
dev = self._dev(devs, dev_id)
|
||||
frag = self.frag(dev_id)
|
||||
if not frag:
|
||||
raise dp.Fail(T("The device's mapping is gone; use it with Cantabile again."))
|
||||
seal = dp.sealed(self.policy(), dev_id)
|
||||
if seal:
|
||||
raise dp.Fail(T("Sealed: only {who} can change its control.", who=custodian(seal)))
|
||||
return devs, dev, frag
|
||||
|
||||
async def shade(self, dev_id: str, data: dict):
|
||||
"""A shade's room and its window's orientation."""
|
||||
async with self.lock:
|
||||
devs, dev, frag = await self._setting(dev_id)
|
||||
sh = dp.set_shade(frag, data, [self.frag(i) for i in devs if i != dev_id])
|
||||
self.write_frag(dev_id, frag)
|
||||
log.info("shade: %s: room %s, facing %g", dev["name"], sh["area"] or "-", sh["facing"])
|
||||
await self._done(devs, restart=True)
|
||||
|
||||
async def place(self, dev_id: str, data: dict):
|
||||
"""A temperature sensor indoor (its room) or outdoor."""
|
||||
async with self.lock:
|
||||
devs, dev, frag = await self._setting(dev_id)
|
||||
main = self.main()
|
||||
taken = {a.get("asset") for a in main.get("assets") or [] if isinstance(a, dict)} \
|
||||
| {a["asset"] for i in devs if i != dev_id for a in self.frag(i).get("assets", [])}
|
||||
pl = dp.set_place(frag, data, taken)
|
||||
self.write_frag(dev_id, frag)
|
||||
log.info("place: %s: %s %s", dev["name"], pl["place"], pl["area"])
|
||||
await self._done(devs, restart=True)
|
||||
|
||||
async def weather(self, dev_id: str):
|
||||
"""This weather service's forecast plans; the others are kept, unused."""
|
||||
async with self.lock:
|
||||
devs, dev, _ = await self._setting(dev_id)
|
||||
frags = {i: self.frag(i) for i in devs}
|
||||
dp.set_weather(frags, dev_id)
|
||||
for i, f in frags.items():
|
||||
if f.get("profile") == "ha-weather":
|
||||
self.write_frag(i, f)
|
||||
log.info("weather: %s plans", dev["name"])
|
||||
await self._done(devs, restart=True)
|
||||
|
||||
|
||||
def custodian(e: dict | None) -> str:
|
||||
c = (e or {}).get("custodian")
|
||||
return T(CUSTODIAN_WORDS[c]) if c in CUSTODIAN_WORDS else T("its custodian")
|
||||
|
||||
|
||||
# ---- the page -----------------------------------------------------------------------------
|
||||
|
||||
def form(do: str, inner: str, button: str, cls: str = "", inline: bool = False) -> str:
|
||||
return (f'<form method="post" action=""{" class=" + chr(34) + "inline" + chr(34) if inline else ""}>'
|
||||
f'<input type="hidden" name="do" value="{E(do)}">{inner}'
|
||||
f'<button{" class=" + chr(34) + cls + chr(34) if cls else ""}>{E(button)}</button></form>')
|
||||
|
||||
|
||||
def hidden(**kw) -> str:
|
||||
return "".join(f'<input type="hidden" name="{E(k)}" value="{E(str(v))}">' for k, v in kw.items())
|
||||
|
||||
|
||||
def what_lines(assets: list, controls: list, would: bool) -> str:
|
||||
reads = ", ".join(quantity_words(a["asset"]) for a in assets) or T("nothing")
|
||||
kinds = ", ".join(dict.fromkeys(T(CONTROL_WORDS.get(c["kind"], c["kind"])) for c in controls))
|
||||
if would:
|
||||
out = T("Cantabile would read: {values}.", values=reads)
|
||||
if kinds:
|
||||
out += " " + T("It could control: {controls}.", controls=kinds)
|
||||
else:
|
||||
out = T("Cantabile reads: {values}.", values=reads)
|
||||
if kinds:
|
||||
out += " " + T("It may control: {controls}.", controls=kinds)
|
||||
return f'<p class="note">{E(out)}</p>'
|
||||
|
||||
|
||||
def notes(d: dict) -> str:
|
||||
out = []
|
||||
if d.get("missing"):
|
||||
out.append(T("Not found in Home Assistant: {entities}.", entities=", ".join(d["missing"])))
|
||||
gone = d.get("left_out") or {}
|
||||
if gone.get("values"):
|
||||
out.append(T("Read by your own mapping already, so left out here: {values}.",
|
||||
values=", ".join(quantity_words(q) for q in gone["values"])))
|
||||
if gone.get("controls"):
|
||||
out.append(T("Another control writes to this device already, so Cantabile leaves out: {controls}.",
|
||||
controls=", ".join(T(CONTROL_WORDS.get(k, k)) for k in gone["controls"])))
|
||||
assumed = [a["asset"] for a in d.get("assets") or [] if a.get("assumed")]
|
||||
if assumed:
|
||||
out.append(T("Assumed, not measured: {values}. This device does not report back (infrared): Cantabile shows "
|
||||
"what was last sent to it and never takes it as feedback.",
|
||||
values=", ".join(quantity_words(q) for q in assumed)))
|
||||
return "".join(f'<p class="note">{E(x)}</p>' for x in out)
|
||||
|
||||
|
||||
def consent_html(d: dict, site: dict) -> str:
|
||||
"""Reading and control, the owner's per device, as on the Hub's Devices
|
||||
page; only with the site's consent (the add-on's configuration)."""
|
||||
kinds = ", ".join(dict.fromkeys(T(CONTROL_WORDS.get(c["kind"], c["kind"])) for c in d.get("controls") or []))
|
||||
if not site.get("share"):
|
||||
return ('<p class="note">' + E(T("Reading and control are off. To switch them on, first give your consent in the "
|
||||
"add-on's configuration (Settings, Add-ons, Cantabile Edge Agent, Configuration)."))
|
||||
+ "</p>")
|
||||
ctl = ('<label class="check"><input type="checkbox" name="control" value="1"' + (" checked" if d.get("control") else "")
|
||||
+ "><span>" + E(T("Cantabile may control it ({controls}), within your limits", controls=kinds))
|
||||
+ "</span></label>") if kinds else ""
|
||||
note = ('<p class="note">' + E(T("Control also needs your consent to control devices in the add-on's configuration."))
|
||||
+ "</p>") if kinds and not site.get("control") else ""
|
||||
return form("consent", hidden(id=d["id"]) + '<label class="check"><input type="checkbox" name="read" value="1"'
|
||||
+ (" checked" if d.get("read") else "") + "><span>" + E(T("Cantabile may read these values"))
|
||||
+ f"</span></label>{ctl}", T("Save")) + note
|
||||
|
||||
|
||||
def switchover_html(d: dict) -> str:
|
||||
sw = d.get("switchover")
|
||||
if not sw:
|
||||
return ""
|
||||
mode = sw.get("mode", "season")
|
||||
lo, hi = sw.get("heat_below_c", 15), sw.get("cool_above_c", 22)
|
||||
radios = "".join(f'<label class="check"><input type="radio" name="mode" value="{k}"{" checked" if k == mode else ""}>'
|
||||
f"<span>{E(T(w))}</span></label>" for k, w in SWITCHOVER_WORDS.items())
|
||||
inner = (hidden(id=d["id"]) + f'<p class="note">{E(T("This thermostat can heat and cool. Cantabile uses one at a time; the other is never touched."))}</p>'
|
||||
+ radios
|
||||
+ f'<label for="lo-{E(d["id"])}">{E(T("By outdoor temperature: heat below (°C)"))}</label>'
|
||||
f'<input id="lo-{E(d["id"])}" type="number" step="0.5" name="heat_below_c" value="{E(f"{lo:g}")}">'
|
||||
f'<label for="hi-{E(d["id"])}">{E(T("cool above (°C)"))}</label>'
|
||||
f'<input id="hi-{E(d["id"])}" type="number" step="0.5" name="cool_above_c" value="{E(f"{hi:g}")}">'
|
||||
f'<p class="note">{E(T("Between the two it stays as it is, so it does not switch back and forth on a mild day."))}</p>')
|
||||
return f"<details><summary>{E(T('Heating or cooling'))}</summary>{form('switchover', inner, T('Save'))}</details>"
|
||||
|
||||
|
||||
FACING_WORDS = {"": M("Not known"), "N": M("North"), "NE": M("North-east"), "E": M("East"), "SE": M("South-east"),
|
||||
"S": M("South"), "SW": M("South-west"), "W": M("West"), "NW": M("North-west")}
|
||||
|
||||
|
||||
def _room_options(rooms, current: str) -> str:
|
||||
names = list(rooms)
|
||||
if current and current not in {dp.slug(r) for r in names}:
|
||||
names.append(current)
|
||||
return f'<option value="">{E(T("No room"))}</option>' + "".join(
|
||||
f'<option value="{E(r)}"{" selected" if dp.slug(r) == current else ""}>{E(r)}</option>' for r in names)
|
||||
|
||||
|
||||
def shade_html(d: dict, rooms) -> str:
|
||||
"""A shade (ha-cover): the room it shades and the window's orientation."""
|
||||
sh = d.get("shade")
|
||||
if not sh:
|
||||
return ""
|
||||
face = sh.get("facing", -1)
|
||||
cur = next((k for k, v in dp.ORIENTATIONS.items() if face >= 0 and abs(v - face) < 0.5), "" if face < 0 else None)
|
||||
opts = "".join(f'<option value="{k}"{" selected" if k == cur else ""}>{E(T(w))}</option>' for k, w in FACING_WORDS.items())
|
||||
if cur is None:
|
||||
opts += f'<option value="{face:g}" selected>{face:g}°</option>'
|
||||
inner = (hidden(id=d["id"]) + '<p class="note">' + E(T(
|
||||
"Cantabile moves it by the sun: in summer it closes it while the sun is on the window and the room is warm; in "
|
||||
"winter it opens it for the sun's warmth and closes it at night. Never between 22:00 and 07:00, and after you "
|
||||
"move it by hand it waits 4 hours.")) + "</p>"
|
||||
f'<label for="area-{E(d["id"])}">{E(T("Room it shades"))}</label><select id="area-{E(d["id"])}" name="area">'
|
||||
f'{_room_options(rooms, sh.get("area") or "")}</select>'
|
||||
f'<label for="face-{E(d["id"])}">{E(T("The window faces"))}</label><select id="face-{E(d["id"])}" name="facing">{opts}</select>'
|
||||
'<p class="note">' + E(T("Without the window's direction Cantabile only closes it at night in winter.")) + "</p>")
|
||||
return f"<details><summary>{E(T('Room and window'))}</summary>{form('shade', inner, T('Save'))}</details>"
|
||||
|
||||
|
||||
def place_html(d: dict, rooms) -> str:
|
||||
"""A temperature sensor (ha-climate-sensor): indoor (its room) or outdoor."""
|
||||
pl = d.get("place")
|
||||
if not pl:
|
||||
return ""
|
||||
chk = lambda k: " checked" if pl["place"] == k else "" # noqa: E731
|
||||
inner = (hidden(id=d["id"])
|
||||
+ f'<label class="check"><input type="radio" name="place" value="indoor"{chk("indoor")}><span>{E(T("Indoor, in the room:"))}</span></label>'
|
||||
+ f'<select name="area" aria-label="{E(T("Room"))}">{_room_options(rooms, pl.get("area") or "")}</select>'
|
||||
+ f'<label class="check"><input type="radio" name="place" value="outdoor"{chk("outdoor")}><span>{E(T("Outdoor: Cantabile's outside temperature"))}</span></label>'
|
||||
+ '<p class="note">' + E(T("An outdoor sensor counts before the weather service's temperature.")) + "</p>")
|
||||
return f"<details><summary>{E(T('Indoor or outdoor'))}</summary>{form('place', inner, T('Save'))}</details>"
|
||||
|
||||
|
||||
def weather_html(d: dict) -> str:
|
||||
"""A weather service (ha-weather): whether its forecast plans."""
|
||||
w = d.get("weather")
|
||||
if not w:
|
||||
return ""
|
||||
if w.get("active"):
|
||||
return '<p class="note">' + E(T("Cantabile plans with this forecast: solar, heating, cooling and the shades.")) + "</p>"
|
||||
return ('<p class="note">' + E(T("Not used for planning: Cantabile plans with one weather forecast, another one's."))
|
||||
+ "</p>" + form("weather", hidden(id=d["id"]), T("Plan with this forecast"), "secondary"))
|
||||
|
||||
|
||||
def protection_html(d: dict) -> str:
|
||||
"""Per target a switch for the owner; sealed ones locked with their
|
||||
custodian."""
|
||||
pol = d.get("policy") or {}
|
||||
targets = [f"device:{d['id']}"] + [f"control:{c['id']}" for c in d.get("controls") or [] if c.get("id")]
|
||||
targets += [t for t in pol if t not in targets]
|
||||
seal = (pol.get(f"device:{d['id']}") or {}) if d.get("protection") == "sealed" else None
|
||||
rows = []
|
||||
covers = {f"control:{c['id']}" for c in d.get("controls") or [] if c.get("kind") == "cover" and c.get("id")}
|
||||
for t in targets:
|
||||
e = pol.get(t) or {}
|
||||
kind, _, name = t.partition(":")
|
||||
what = {"device": T("The whole device"), "control": T("Control {name}", name=name)}.get(kind, name)
|
||||
lift = T("Allow Cantabile to move it") if t in covers else T("Allow switching off")
|
||||
lvl = "sealed" if seal else e.get("level", "none")
|
||||
if lvl == "sealed":
|
||||
why = (seal or e).get("why")
|
||||
rows.append(f'<li>{E(what)}: <b>{E(T("Sealed"))}</b> · {E(T("only {who} can change it", who=custodian(seal or e)))}'
|
||||
f'{": " + E(why) if why else ""}</li>')
|
||||
continue
|
||||
why = f" ({E(e['why'])})" if e.get("why") and lvl == "protected" else ""
|
||||
state = f"<b>{E(T('protected'))}</b>" if lvl == "protected" else E(T("not protected"))
|
||||
rows.append(f"<li>{E(what)}: {state}{why} "
|
||||
+ form("protect", hidden(id=d["id"], target=t, level="none" if lvl == "protected" else "protected"),
|
||||
lift if lvl == "protected" else T("Protect"), "secondary", inline=True)
|
||||
+ "</li>")
|
||||
return (f"<details><summary>{E(T('Protection'))}</summary><p class=\"note\">"
|
||||
+ E(T("Protected: Cantabile never switches it off or cuts it; you still can, by hand. Sealed: only its "
|
||||
"custodian can change it.")) + ("" if not covers else " " + E(T(
|
||||
"A protected blind or curtain is not moved by Cantabile at all.")))
|
||||
+ f'</p><ul class="plain">{"".join(rows)}</ul></details>')
|
||||
|
||||
|
||||
def badges(d: dict) -> str:
|
||||
st = PROFILE_STATUS.get(d.get("status"))
|
||||
out = f'<span class="badge">{E(d.get("manufacturer", ""))} {E(d.get("model", ""))}</span>'
|
||||
if d.get("generic"):
|
||||
out += f'<span class="badge">{E(T("generic profile"))}</span>'
|
||||
if st:
|
||||
out += f'<span class="badge">{E(T(st))}</span>'
|
||||
return out
|
||||
|
||||
|
||||
def device_card(d: dict, site: dict, rooms=()) -> str:
|
||||
return (f'<div class="box"><b>{E(d["name"])}</b>{badges(d)}{what_lines(d.get("assets") or [], d.get("controls") or [], False)}'
|
||||
f'{notes(d)}{consent_html(d, site)}{switchover_html(d)}{shade_html(d, rooms)}{place_html(d, rooms)}'
|
||||
f'{weather_html(d)}{protection_html(d)}'
|
||||
f"<details><summary>{E(T('Remove'))}</summary><p class=\"note\">"
|
||||
+ E(T("Cantabile stops using it. Home Assistant keeps the device as it is."))
|
||||
+ "</p>" + form("remove", hidden(id=d["id"]), T("Stop using it with Cantabile"), "secondary") + "</details></div>")
|
||||
|
||||
|
||||
def offer_card(h: dict) -> str:
|
||||
p = h["profile"]
|
||||
name = h["name"] or h["model"]
|
||||
proposed = ""
|
||||
if h.get("in_mapping"):
|
||||
ids = ", ".join(quantity_words(i) for i in h["in_mapping"])
|
||||
proposed = '<p class="note">' + E(
|
||||
T("Proposed by Cantabile (not checked yet): {values}. Use it with Cantabile to confirm it as this profile "
|
||||
"sees it.", values=ids) if h.get("mapping_source") in ("proposed", "imported")
|
||||
else T("In your own mapping: {values}. Those stay as they are.", values=ids)) + "</p>"
|
||||
body = what_lines(h["assets"], h["controls"], True) + notes(h) + proposed
|
||||
view = dict(h, status=p.get("status"))
|
||||
if not h["assets"] and not h["controls"]:
|
||||
return f'<div class="box"><b>{E(name)}</b>{badges(view)}{body}</div>'
|
||||
return (f'<div class="box"><b>{E(name)}</b>{badges(view)}{body}'
|
||||
+ form("use", hidden(ha_device=h["id"], profile=p["id"], name=name), T("Use with Cantabile")) + "</div>")
|
||||
|
||||
|
||||
def nav(page: str) -> str:
|
||||
items = (("devices", T("Devices")), ("building", T("Building or community")))
|
||||
return "<nav>" + "".join(f'<a href="?p={k}"{" class=" + chr(34) + "on" + chr(34) if k == page else ""}>{E(w)}</a>'
|
||||
for k, w in items) + "</nav>"
|
||||
|
||||
|
||||
def html(title: str, body: str, page: str) -> str:
|
||||
return (f"<!doctype html><html lang=\"{i18n.current()}\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" "
|
||||
f"content=\"width=device-width,initial-scale=1\"><title>{E(title)}</title><style>{CSS}\n{MORE_CSS}</style>"
|
||||
f"<script>{HASH_SCRIPT}</script></head><body>{nav(page)}{body}</body></html>")
|
||||
|
||||
|
||||
def page_devices(v: dict, msg: str = "", err: str = "") -> str:
|
||||
body = [f"<h2>{E(T('Devices'))}</h2><p class=\"note\">"
|
||||
+ E(T("Home Assistant's devices that a Cantabile device profile knows. Use one with Cantabile to see it on "
|
||||
"Cantabile's dashboard and to let Cantabile read it once you have given your consent.")) + "</p>"]
|
||||
if msg:
|
||||
body.append(f'<div class="box ok">{E(msg)}</div>')
|
||||
if err:
|
||||
body.append(f'<div class="box err">{E(err)}</div>')
|
||||
if v.get("devices"):
|
||||
body.append(f"<h3>{E(T('Used with Cantabile'))}</h3>")
|
||||
body += [device_card(d, v.get("site") or {}, v.get("rooms") or []) for d in v["devices"]]
|
||||
if v.get("offers"):
|
||||
body.append(f"<h3>{E(T('In Home Assistant, with a profile'))}</h3>")
|
||||
body += [offer_card(h) for h in v["offers"]]
|
||||
elif not v.get("ha_error") and not v.get("devices"):
|
||||
body.append('<p class="note">' + E(T("No device in Home Assistant fits a Cantabile profile yet.")) + "</p>")
|
||||
if v.get("rest"):
|
||||
n = len(v["rest"])
|
||||
body.append(f"<details><summary>{E(TN('{n} more in Home Assistant without a profile (not used by Cantabile)', '{n} more in Home Assistant without a profile (not used by Cantabile)', n))}</summary><ul class=\"plain\">"
|
||||
+ "".join(f"<li>{E(h['name'] or h['model'])} <small>{E(h['manufacturer'])} {E(h['model'])}</small></li>"
|
||||
for h in v["rest"]) + "</ul></details>")
|
||||
if v.get("ha_error"):
|
||||
body.append('<p class="note">' + E(T("Home Assistant's devices could not be read: {error}", error=v["ha_error"])) + "</p>")
|
||||
return html(T("Cantabile: devices"), "".join(body), "devices")
|
||||
|
||||
|
||||
def page_refused(why: str, page: str = "devices") -> str:
|
||||
head = T("Devices") if page == "devices" else T("Building or community")
|
||||
return html("Cantabile", f"<h2>{E(head)}</h2><div class=\"box err\">{E(why)}</div>", page)
|
||||
|
||||
|
||||
class App(JoinPage):
|
||||
"""The add-on's pages: Devices (the first) and Building or community."""
|
||||
|
||||
def __init__(self, fleet, devices: Devices, location=None, admin=None):
|
||||
super().__init__(fleet, **({"location": location} if location else {}))
|
||||
self.devices = devices
|
||||
# admin(user_id) -> bool: the agent's HA client asks HA (ha.is_admin)
|
||||
self.admin = admin or self._admin
|
||||
|
||||
async def _admin(self, user_id: str) -> bool:
|
||||
client = self.devices.ha()
|
||||
if client is None:
|
||||
raise dp.Fail(T("Home Assistant is not connected yet; try again in a moment."))
|
||||
return await client.is_admin(user_id)
|
||||
|
||||
async def respond(self, method, url, hdr, data, peer):
|
||||
q = urllib.parse.parse_qs(url.query)
|
||||
page = (q.get("p") or [""])[0]
|
||||
if page not in PAGES:
|
||||
page = "building" if q.get("code") else "devices"
|
||||
# owner only, both pages: an administrator of Home Assistant (HA's
|
||||
# ingress names the user; this container itself is trusted)
|
||||
user = hdr.get("x-remote-user-id", "")
|
||||
if peer not in ("127.0.0.1", "::1"):
|
||||
try:
|
||||
ok = bool(user) and await self.admin(user)
|
||||
except Exception as e:
|
||||
return 200, page_refused(T("Cantabile could not ask Home Assistant who you are ({error}).", error=e), page)
|
||||
if not ok:
|
||||
return 200, page_refused(T("Only an administrator of Home Assistant can use this page."), page)
|
||||
if page == "building":
|
||||
status, out = await super().respond(method, url, hdr, data, peer)
|
||||
if status == 200:
|
||||
out = out.replace("</style>", f"\n{MORE_CSS}</style><script>{HASH_SCRIPT}</script>", 1) \
|
||||
.replace("<body>", "<body>" + nav("building"), 1)
|
||||
return status, out
|
||||
if url.path not in ("/", "") or method not in ("GET", "POST"):
|
||||
return 404, T("Not found")
|
||||
if method == "GET":
|
||||
return 200, page_devices(await self.devices.view())
|
||||
f = {k: v[0] for k, v in urllib.parse.parse_qs(data.decode("utf-8", "replace")).items()}
|
||||
by = hdr.get("x-remote-user-display-name") or hdr.get("x-remote-user-name") or "owner"
|
||||
return 200, await self.post_devices(f, by)
|
||||
|
||||
async def post_devices(self, f: dict, by: str = "owner") -> str:
|
||||
dv, do, msg, err = self.devices, f.get("do", ""), "", ""
|
||||
try:
|
||||
if do == "use":
|
||||
d = await dv.use(f.get("ha_device", ""), f.get("profile", ""), f.get("name", ""))
|
||||
msg = T("{name} is used with Cantabile now. It is on Cantabile's dashboard; reading and control are off "
|
||||
"until you switch them on below.",
|
||||
name=d["name"])
|
||||
elif do == "remove":
|
||||
await dv.remove(f.get("id", ""))
|
||||
msg = T("Cantabile no longer uses it.")
|
||||
elif do == "consent":
|
||||
await dv.consent(f.get("id", ""), f.get("read") == "1", f.get("control") == "1")
|
||||
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
|
||||
elif do == "protect":
|
||||
await dv.protect(f.get("id", ""), f.get("target", ""), f.get("level", ""), by)
|
||||
msg = T("Saved.")
|
||||
elif do == "shade":
|
||||
await dv.shade(f.get("id", ""), {"area": f.get("area", ""), "facing": f.get("facing", "")})
|
||||
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
|
||||
elif do == "place":
|
||||
await dv.place(f.get("id", ""), {"place": f.get("place", ""), "area": f.get("area", "")})
|
||||
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
|
||||
elif do == "weather":
|
||||
await dv.weather(f.get("id", ""))
|
||||
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
|
||||
elif do == "switchover":
|
||||
data = {"mode": f.get("mode", "")}
|
||||
if data["mode"] == "outdoor":
|
||||
data.update(heat_below_c=f.get("heat_below_c", ""), cool_above_c=f.get("cool_above_c", ""))
|
||||
await dv.switchover(f.get("id", ""), data)
|
||||
msg = T("Saved. Cantabile starts again to apply it (a few seconds).")
|
||||
except dp.Fail as e:
|
||||
err = str(e)
|
||||
return page_devices(await dv.view(), msg, err)
|
||||
@@ -0,0 +1,697 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Device profiles applied to Home Assistant's devices, shared
|
||||
by both places a device is taken into Cantabile:
|
||||
- the Hub's devices tool (/usr/lib/cantabile/devices; the build installs
|
||||
this file there as /usr/lib/cantabile/python/cantabile_devprofiles.py);
|
||||
- the HA add-on: its Devices page (devpage.py), the mapping's proposal
|
||||
(propose.py) and the dashboard's device views (devview.py).
|
||||
Standard library only, no imports from the edge package: the Hub runs it
|
||||
outside the agent's image.
|
||||
|
||||
What is here: Cantabile's quantities, which profile recognises an HA device
|
||||
(specific profiles first, a generic one such as ha-thermostat only where
|
||||
none fits), a profile's matchers on HA's entities, the agent's mapping
|
||||
fragment for one device (consent off), per-device consent, and the
|
||||
protection rules (protected = never switched off by
|
||||
Cantabile, lifted only by the owner; sealed = only its custodian, from the
|
||||
cloud). Where the files live and how HA is asked is each caller's own.
|
||||
"""
|
||||
import fnmatch
|
||||
import re
|
||||
import time
|
||||
|
||||
|
||||
class Fail(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# Cantabile's quantities: the asset ids the agent, the dashboards and the
|
||||
# cloud use, with unit and kind. Signs: grid import +, battery charge +.
|
||||
QUANTITIES = {
|
||||
"grid.power": ("W", "gauge"), "grid.import_power": ("W", "gauge"), "grid.export_power": ("W", "gauge"),
|
||||
"grid.import_energy": ("Wh", "counter"), "grid.export_energy": ("Wh", "counter"),
|
||||
"pv.power": ("W", "gauge"), "pv.energy": ("Wh", "counter"),
|
||||
"battery.power": ("W", "gauge"), "battery.soc": ("%", "gauge"),
|
||||
"battery.charge_energy": ("Wh", "counter"), "battery.discharge_energy": ("Wh", "counter"),
|
||||
"load.power": ("W", "gauge"), "load.energy": ("Wh", "counter"),
|
||||
"heatpump.power": ("W", "gauge"), "heatpump.energy": ("Wh", "counter"),
|
||||
"heat.power": ("W", "gauge"), "heat.energy": ("Wh", "counter"),
|
||||
"heatpump.flow_temp": ("°C", "gauge"), "heatpump.dhw_temp": ("°C", "gauge"),
|
||||
"outside.temp": ("°C", "gauge"), "outside.humidity": ("%", "gauge"), "heating.state": ("", "gauge"), "cooling.state": ("", "gauge"), "gas.energy": ("Wh", "counter"),
|
||||
"ev.power": ("W", "gauge"), "ev.energy": ("Wh", "counter"),
|
||||
"room.temp": ("°C", "gauge"), "room.humidity": ("%", "gauge"), "room.setpoint": ("°C", "gauge"),
|
||||
"room.setpoint_low": ("°C", "gauge"), "room.setpoint_high": ("°C", "gauge"),
|
||||
"room.shade_position": ("%", "gauge"), "room.shade_tilt": ("%", "gauge"), "circuit.power": ("W", "gauge"),
|
||||
"circuit.energy": ("Wh", "counter"),
|
||||
}
|
||||
# room.* and circuit.* are per place: room.<area>.temp (the device's area).
|
||||
PER_PLACE = ("room", "circuit")
|
||||
# Systems whose quantities may come from several devices: the agent numbers
|
||||
# them (pv.1.power, pv.2.power) and sums their total (edge mapping.py).
|
||||
SUMMED = ("grid", "pv", "battery", "load", "heatpump", "heat", "ev", "gas")
|
||||
PART_RE = re.compile(r"^(" + "|".join(SUMMED) + r")\.(\d{1,3})\.([a-z_]+)$")
|
||||
# A control's roles that write to the device.
|
||||
WRITE_ROLES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover"}
|
||||
# Heating or cooling for a thermostat that does both (the agent's
|
||||
# switchover.py): the owner's choice; by season at first.
|
||||
SWITCHOVER_MODES = ("heating", "cooling", "season", "outdoor")
|
||||
SWITCHOVER_DEFAULT = {"mode": "season"}
|
||||
# Cantabile's Modbus bridge: its entities' unique ids and devices' identifiers.
|
||||
BRIDGE = "cantabile_modbus_"
|
||||
LEVELS = ("none", "protected", "sealed")
|
||||
RANK = {"none": 0, "protected": 1, "sealed": 2}
|
||||
# Asset and control ids in a mapping's text (the Hub's base has no YAML
|
||||
# parser: the ids are found by their keys).
|
||||
IDS_RE = re.compile(r"""(?:^|[\s{,-])["']?(?:asset|id)["']?\s*:\s*["']?([A-Za-z0-9_.-]+)""", re.M)
|
||||
|
||||
|
||||
def part_of(asset: str):
|
||||
"""pv.2.power -> ("pv.power", 2); None for anything else."""
|
||||
m = PART_RE.match(asset)
|
||||
return (f"{m.group(1)}.{m.group(3)}", int(m.group(2))) if m else None
|
||||
|
||||
|
||||
def quantity_of(q: str):
|
||||
"""(unit, kind) of a quantity: room.kitchen.temp and room.{area}.temp
|
||||
as room.temp, pv.2.power as pv.power; None if it is not one."""
|
||||
head, _, rest = q.partition(".")
|
||||
if head in PER_PLACE and "." in rest:
|
||||
return QUANTITIES.get(f"{head}.{rest.rsplit('.', 1)[1]}")
|
||||
part = part_of(q)
|
||||
return QUANTITIES.get(part[0] if part else q)
|
||||
|
||||
|
||||
def slug(s) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "_", str(s).lower()).strip("_") or "x"
|
||||
|
||||
|
||||
def ids_in(text: str) -> set:
|
||||
return set(IDS_RE.findall(text or ""))
|
||||
|
||||
|
||||
def free_id(want: str, taken: set) -> str:
|
||||
out, n = want, 2
|
||||
while out in taken:
|
||||
out, n = f"{want}_{n}", n + 1
|
||||
taken.add(out)
|
||||
return out
|
||||
|
||||
|
||||
def bridge_uid(dev_id: str, key: str) -> str:
|
||||
return f"{BRIDGE}{slug(dev_id)}_{key}"
|
||||
|
||||
|
||||
# --- which profile fits an HA device ------------------------------------------------------
|
||||
|
||||
def glob_match(pattern, value) -> bool:
|
||||
return value is not None and fnmatch.fnmatch(str(value).lower(), str(pattern).lower())
|
||||
|
||||
|
||||
def _fits(h: dict, d: dict, domains, entity_domains) -> bool:
|
||||
return all((k == "domain" and any(glob_match(v, x) for x in domains)) or
|
||||
(k == "entity_domain" and any(glob_match(v, x) for x in entity_domains)) or
|
||||
(k not in ("domain", "entity_domain") and glob_match(v, d.get(k))) for k, v in h.items())
|
||||
|
||||
|
||||
def recognise(p: dict, d: dict, domains=(), entity_domains=()) -> bool:
|
||||
"""Does this HA device fit the profile (recognise.ha patterns: maker,
|
||||
model, domain: its integration's, entity_domain: a domain of one of its
|
||||
entities, e.g. climate, or a domain with the entity's device class,
|
||||
e.g. cover.curtain, sensor.temperature)? A device that fits one of
|
||||
recognise.exclude (the same patterns) never fits: a garage door is never
|
||||
a shade, the box's own CPU temperature never a room's."""
|
||||
rec = p.get("recognise") or {}
|
||||
if any(_fits(h, d, domains, entity_domains) for h in rec.get("exclude", [])):
|
||||
return False
|
||||
return any(_fits(h, d, domains, entity_domains) for h in rec.get("ha", []))
|
||||
|
||||
|
||||
def fallback(p: dict) -> bool:
|
||||
"""A generic profile (any climate device): only where no specific one fits."""
|
||||
return bool((p.get("recognise") or {}).get("fallback"))
|
||||
|
||||
|
||||
def by_priority(profiles) -> list:
|
||||
"""Specific profiles first, generic (fallback) ones last."""
|
||||
return sorted(profiles, key=fallback)
|
||||
|
||||
|
||||
def fitting(profiles, d: dict, domains=(), entity_domains=()) -> list:
|
||||
"""The profiles that recognise an HA device, specific ones first; a
|
||||
fallback profile only when none of those does."""
|
||||
fits = [p for p in profiles if recognise(p, d, domains, entity_domains)]
|
||||
specific = [p for p in fits if not fallback(p)]
|
||||
return sorted(specific or fits, key=lambda p: p["id"])
|
||||
|
||||
|
||||
def device_class(e: dict, attrs=None):
|
||||
"""The entity's device class: HA's state attribute (the owner's choice
|
||||
in HA wins there), else the registry's."""
|
||||
a = attrs if isinstance(attrs, dict) else attrs_of(e) or {}
|
||||
return a.get("device_class") or e.get("device_class") or e.get("original_device_class")
|
||||
|
||||
|
||||
def kinds_of(e: dict, attrs=None) -> set:
|
||||
"""An entity's domain, and with its device class "<domain>.<class>"
|
||||
(cover.curtain, sensor.temperature); a diagnostic or configuration
|
||||
entity (a device's own CPU temperature) only its domain."""
|
||||
dom = str(e.get("entity_id", "")).split(".")[0]
|
||||
dc = None if e.get("entity_category") else device_class(e, attrs)
|
||||
return {dom} | ({f"{dom}.{dc}"} if dc else set())
|
||||
|
||||
|
||||
def entity_domains(reg: dict, dev_id: str) -> list:
|
||||
return sorted({k for e in reg.get("entities") or [] if e.get("device_id") == dev_id and not e.get("disabled_by")
|
||||
and "." in str(e.get("entity_id")) for k in kinds_of(e)})
|
||||
|
||||
|
||||
def setup_for(p: dict, domains) -> dict | None:
|
||||
"""The setup path of a device HA has already: its integration's (its
|
||||
entities have that path's names), else the profile's "existing" path."""
|
||||
for s in p.get("setup") or []:
|
||||
if s.get("domain") and s["domain"] in (domains or []):
|
||||
return s
|
||||
return next((s for s in p.get("setup") or [] if s["path"] == "existing"), None)
|
||||
|
||||
|
||||
# --- matchers on HA's entities ------------------------------------------------------------
|
||||
|
||||
_KNOWN = object()
|
||||
|
||||
|
||||
def attrs_of(e: dict) -> dict | None:
|
||||
"""The entity's attributes, where the caller put them with it (the Hub's
|
||||
ha-setup registry; the add-on adds them from HA's states)."""
|
||||
a = e.get("attributes")
|
||||
return a if isinstance(a, dict) else None
|
||||
|
||||
|
||||
def assumed_state(e: dict, attrs: dict | None) -> bool | None:
|
||||
"""No feedback from the device: HA assumes its state (assumed_state; a
|
||||
climate without hvac_action: ESPHome's infrared climates). None when
|
||||
HA's state is not known."""
|
||||
if attrs is None:
|
||||
return None
|
||||
if attrs.get("assumed_state"):
|
||||
return True
|
||||
return e["entity_id"].startswith("climate.") and attrs.get("hvac_action") is None
|
||||
|
||||
|
||||
def entity_matches(m: dict, e: dict, attrs=_KNOWN) -> bool:
|
||||
"""A profile's matcher on an entity, with its conditions on HA's
|
||||
attributes (attribute: has it; supports: an hvac mode; assumed;
|
||||
device_class: HA's class of it, never a diagnostic entity). Where the
|
||||
state is not known the conditions hold (and the entity is taken as
|
||||
reporting back), except device_class (the registry's then, else no).
|
||||
attrs: the entity's attributes, else attrs_of(e)."""
|
||||
if attrs is _KNOWN:
|
||||
attrs = attrs_of(e)
|
||||
for k in ("entity_id", "unique_id", "original_name"):
|
||||
if k in m and not re.search(m[k], str(e.get(k) or "")):
|
||||
return False
|
||||
if "translation_key" in m and e.get("translation_key") != m["translation_key"]:
|
||||
return False
|
||||
if "device_class" in m and (e.get("entity_category") or device_class(e, attrs) != m["device_class"]):
|
||||
return False # a diagnostic entity (an inverter's own temperature) never
|
||||
if attrs is not None:
|
||||
if m.get("attribute") and attrs.get(m["attribute"]) is None:
|
||||
return False
|
||||
if m.get("supports") and m["supports"] not in (attrs.get("hvac_modes") or []):
|
||||
return False
|
||||
if "assumed" in m and bool(assumed_state(e, attrs)) != m["assumed"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def alternatives(m) -> list:
|
||||
"""A value's matcher, or its list of alternatives (the first that finds)."""
|
||||
return [x for x in (m if isinstance(m, list) else [m]) if isinstance(x, dict)]
|
||||
|
||||
|
||||
# --- the agent's mapping fragment for one device ------------------------------------------
|
||||
|
||||
def mapping_for(dev_id, p, s, ents, area, taken, main=()):
|
||||
"""The agent's fragment for one device: its assets and controls, consent
|
||||
off; and what could not be found (shown to the owner). ents: the
|
||||
device's entities (registry entries, attributes where known); taken:
|
||||
the ids in use (grows); main: the ids of the site's own mapping (a
|
||||
summed system's quantity there makes this device's an id of its own)."""
|
||||
assets, controls, missing = [], [], []
|
||||
values = dict(s.get("values") or {})
|
||||
if s["path"] == "modbus":
|
||||
for r in p["modbus"]["registers"]:
|
||||
if "quantity" in r:
|
||||
values.setdefault(r["quantity"], {"key": r["key"]})
|
||||
for q in (r.get("split") or {}).values():
|
||||
values.setdefault(q, {"key": r["key"], "part": q})
|
||||
|
||||
def find(m):
|
||||
hits = [e for e in ents if entity_matches(m, e)] if s["path"] != "modbus" else \
|
||||
[e for e in ents if e.get("unique_id") == bridge_uid(dev_id, m.get("part") and slug(m["part"]) or m["key"])]
|
||||
return hits[0] if hits else None
|
||||
|
||||
for q, alts in values.items():
|
||||
e = m = None
|
||||
for m in (alts if isinstance(alts, list) else [alts]):
|
||||
e = find(m)
|
||||
if e:
|
||||
break
|
||||
if not e:
|
||||
missing.append(q)
|
||||
continue
|
||||
quantity = q.replace("{area}", slug(area or "home"))
|
||||
unit, kind = quantity_of(q)
|
||||
# pv.power of a second inverter stays pv.power here: the agent numbers
|
||||
# the devices' parts (pv.1.power, pv.2.power) and sums their total
|
||||
own = quantity.split(".")[0] in SUMMED and quantity not in main
|
||||
a = {"entity": e["entity_id"], "asset": quantity if own else free_id(quantity, taken), "kind": kind,
|
||||
"unit": unit, "consent": False}
|
||||
if m.get("scale", 1) != 1:
|
||||
a["scale"] = m["scale"]
|
||||
for k in ("attribute", "equals"):
|
||||
if m.get(k):
|
||||
a[k] = m[k]
|
||||
if m.get("assumed"):
|
||||
a["assumed"] = True # no feedback: never taken as measured
|
||||
if m.get("fallback"):
|
||||
a["fallback"] = True # yields its id to a measured one (the weather's outside.temp)
|
||||
assets.append(a)
|
||||
written = {} # entity -> the control that writes it
|
||||
for c in s.get("controls", []):
|
||||
ents_c, lost = {}, []
|
||||
for role, m in c["entities"].items():
|
||||
e = find(m)
|
||||
if e:
|
||||
ents_c[role] = e["entity_id"]
|
||||
elif m.get("supports") and find({k: v for k, v in m.items() if k != "supports"}):
|
||||
lost.append(None) # the device has no such mode (a cooling-only A/C: no heating)
|
||||
else:
|
||||
lost.append(role)
|
||||
if None in lost:
|
||||
continue
|
||||
if lost:
|
||||
missing.append(f"{c['kind']} control ({', '.join(lost)})")
|
||||
continue
|
||||
writes = {e for r, e in ents_c.items() if r in WRITE_ROLES}
|
||||
ctl = {"id": free_id(c["kind"], taken) if not writes & set(written) else None, "kind": c["kind"],
|
||||
"consent": False, "entities": ents_c}
|
||||
if writes & set(written):
|
||||
# one control per entity; a thermostat that heats and cools has
|
||||
# both, paired: the agent uses one at a time (switchover)
|
||||
other = written[next(iter(writes & set(written)))]
|
||||
if not (set(ents_c) == {"climate"} == set(other["entities"]) and {c["kind"], other["kind"]}
|
||||
== {"heating", "cooling"} and "switchover" not in other):
|
||||
continue
|
||||
other["switchover"] = dict(SWITCHOVER_DEFAULT)
|
||||
ctl["id"] = free_id(c["kind"], taken)
|
||||
ctl["switchover"] = dict(SWITCHOVER_DEFAULT)
|
||||
for e in writes:
|
||||
written.setdefault(e, ctl)
|
||||
if c.get("params"):
|
||||
ctl["params"] = dict(c["params"])
|
||||
if c["kind"] == "cover" and area:
|
||||
ctl.setdefault("params", {})["area"] = slug(area) # the room it shades: its device's area at first
|
||||
if c.get("safe"):
|
||||
ctl["safe"] = c["safe"]
|
||||
controls.append(ctl)
|
||||
frag = {"version": 3, "device": dev_id, "profile": p["id"], "assets": assets, "controls": controls}
|
||||
# the optimiser's inputs the device gives (a weather entity: its forecast)
|
||||
for k, m in (s.get("inputs") or {}).items():
|
||||
e = next((x for x in (find(y) for y in alternatives(m)) if x), None)
|
||||
if e:
|
||||
frag.setdefault("inputs", {})[k] = e["entity_id"]
|
||||
return frag, missing
|
||||
|
||||
|
||||
def leave_out(frag: dict, entities=(), written=()) -> tuple[list, list]:
|
||||
"""Takes out of a fragment what the site already has elsewhere: values of
|
||||
entities another mapping reads (entities), and controls writing to an
|
||||
entity another control writes (written): one writer per entity. In
|
||||
place; (the values' ids, the controls' kinds) left out."""
|
||||
entities, written = set(entities), set(written)
|
||||
gone_a = [a["asset"] for a in frag.get("assets", []) if a["entity"] in entities]
|
||||
frag["assets"] = [a for a in frag.get("assets", []) if a["entity"] not in entities]
|
||||
gone_c, keep = [], []
|
||||
for c in frag.get("controls", []):
|
||||
writes = {e for r, e in (c.get("entities") or {}).items() if r in WRITE_ROLES}
|
||||
(gone_c.append(c["kind"]) if writes & written else keep.append(c))
|
||||
frag["controls"] = keep
|
||||
return gone_a, gone_c
|
||||
|
||||
|
||||
def control_writes(controls) -> set:
|
||||
"""The entities some control writes to."""
|
||||
return {e for c in controls or [] for r, e in (c.get("entities") or {}).items() if r in WRITE_ROLES}
|
||||
|
||||
|
||||
def switchover_of(frag: dict) -> dict | None:
|
||||
"""The heating/cooling choice of a device that has both, or None."""
|
||||
pair = [c for c in frag.get("controls", []) if "switchover" in c]
|
||||
return dict(pair[0]["switchover"]) if len(pair) >= 2 else None
|
||||
|
||||
|
||||
def set_switchover(frag: dict, data: dict) -> dict:
|
||||
"""The owner's choice for a thermostat that heats and cools: heating,
|
||||
cooling, by season (October-April heating), or by the outdoor
|
||||
temperature (heating below heat_below_c, cooling above cool_above_c, the
|
||||
side it was on between them). Into both its controls (in place)."""
|
||||
pair = [c for c in frag.get("controls", []) if "switchover" in c]
|
||||
if len(pair) < 2:
|
||||
raise Fail("this device has no heating and cooling to choose between")
|
||||
mode = data.get("mode")
|
||||
if mode not in SWITCHOVER_MODES:
|
||||
raise Fail(f"mode is one of {', '.join(SWITCHOVER_MODES)}")
|
||||
sw = {"mode": mode}
|
||||
if mode == "outdoor":
|
||||
try:
|
||||
lo, hi = float(data.get("heat_below_c", 15)), float(data.get("cool_above_c", 22))
|
||||
except (TypeError, ValueError):
|
||||
raise Fail("the temperatures are numbers") from None
|
||||
if not -30 <= lo < hi <= 45:
|
||||
raise Fail("heat below a lower temperature than cool above (-30 to 45 °C)")
|
||||
sw.update(heat_below_c=lo, cool_above_c=hi)
|
||||
for c in pair:
|
||||
c["switchover"] = dict(sw)
|
||||
return sw
|
||||
|
||||
|
||||
def area_of(reg: dict, ents, ha_device=None):
|
||||
areas = {a["area_id"]: a["name"] for a in reg.get("areas") or []}
|
||||
devices = {d["id"]: d for d in reg.get("devices") or []}
|
||||
for e in ents:
|
||||
a = e.get("area_id") or (devices.get(e.get("device_id")) or {}).get("area_id")
|
||||
if a in areas:
|
||||
return areas[a]
|
||||
return areas.get((devices.get(ha_device) or {}).get("area_id"))
|
||||
|
||||
|
||||
def fragment_entities(frag: dict) -> list:
|
||||
out = [a["entity"] for a in frag.get("assets", [])]
|
||||
for c in frag.get("controls", []):
|
||||
out += list((c.get("entities") or {}).values())
|
||||
return sorted(set(out))
|
||||
|
||||
|
||||
def set_consent(frag: dict, read: bool, control: bool):
|
||||
"""The owner's consent for one device: every value read, every control
|
||||
(in place)."""
|
||||
for a in frag.get("assets", []):
|
||||
a["consent"] = bool(read)
|
||||
for c in frag.get("controls", []):
|
||||
c["consent"] = bool(control)
|
||||
|
||||
|
||||
def offers(reg: dict, profiles, taken=()) -> list:
|
||||
"""HA's devices with the profiles that fit each (none: not used by
|
||||
Cantabile), without those taken (used already: an HA device id or a
|
||||
config entry id); with a profile first."""
|
||||
taken = set(taken)
|
||||
out = []
|
||||
for dv in reg.get("devices") or []:
|
||||
if dv.get("disabled_by") or not (dv.get("manufacturer") or dv.get("model") or dv.get("entry_type") == "service"):
|
||||
continue
|
||||
# HA's services (Backup, Google Translate, the Supervisor's apps) and
|
||||
# Cantabile's own agent are no devices to offer
|
||||
# (a weather service, met.no's "Forecast", is offered: its forecast plans)
|
||||
edoms = entity_domains(reg, dv["id"])
|
||||
if (dv.get("entry_type") == "service" and "weather" not in edoms) or dv.get("manufacturer") == "Cantabile" \
|
||||
or "hassio" in (dv.get("domains") or []):
|
||||
continue
|
||||
if dv["id"] in taken or set(dv.get("config_entries") or []) & taken:
|
||||
continue
|
||||
fits = fitting(profiles, dv, dv.get("domains") or [], edoms)
|
||||
out.append({"id": dv["id"], "name": dv.get("name_by_user") or dv.get("name") or "",
|
||||
"manufacturer": dv.get("manufacturer") or "", "model": dv.get("model") or "",
|
||||
"domains": dv.get("domains") or [], "profiles": [p["id"] for p in fits],
|
||||
"generic": bool(fits) and fallback(fits[0])})
|
||||
return sorted(out, key=lambda x: (not x["profiles"], x["manufacturer"], x["name"]))
|
||||
|
||||
|
||||
def new_id(p: dict, devs) -> str:
|
||||
base = slug(p["id"]).replace("_", "-")
|
||||
n = 1
|
||||
while f"{base}-{n}" in devs:
|
||||
n += 1
|
||||
return f"{base}-{n}"
|
||||
|
||||
|
||||
def ratings_of(p: dict, vals: dict) -> dict:
|
||||
"""The device's ratings: the profile's, the owner's answers over them."""
|
||||
out = dict(p.get("ratings") or {})
|
||||
for f in p.get("fields", []):
|
||||
if f.get("rating") and f["name"] in vals:
|
||||
out[f["rating"]] = vals[f["name"]]
|
||||
return out
|
||||
|
||||
|
||||
# --- protection -------------------------------------------------------------
|
||||
# Targets: "device:<id here>", "control:<the agent's control id>",
|
||||
# "entity:<HA entity id>". An entry: {level: none|protected|sealed,
|
||||
# custodian (sealed), set_by, role, at, why, source: cloud|owner|profile}.
|
||||
# In force per target: a sealed entry from the cloud always; the box's own
|
||||
# never lowers it; otherwise the newer entry (a custodian lifting a
|
||||
# profile's seal from the cloud is newer than the profile's default).
|
||||
|
||||
def acl_entries(acl: dict) -> dict:
|
||||
"""The cloud's entries (the link checked the bundle's signature, site
|
||||
and expiry; here its form)."""
|
||||
if not isinstance(acl, dict) or acl.get("v") != 1 or acl.get("kind") != "acl":
|
||||
return {}
|
||||
out = {}
|
||||
for e in acl.get("entries") or []:
|
||||
if isinstance(e, dict) and isinstance(e.get("target"), str) and e.get("level") in LEVELS:
|
||||
out[e["target"]] = dict(e, source="cloud")
|
||||
return out
|
||||
|
||||
|
||||
def local_entries(prot: dict) -> dict:
|
||||
"""The box's own entries (protection.json: the owner's, a profile's)."""
|
||||
return {t: e for t, e in ((prot if isinstance(prot, dict) else {}).get("entries") or {}).items()
|
||||
if isinstance(e, dict) and e.get("level") in LEVELS}
|
||||
|
||||
|
||||
def merge_policy(cloud: dict, local: dict) -> dict:
|
||||
out = dict(cloud)
|
||||
for t, e in local.items():
|
||||
cur = out.get(t)
|
||||
if cur and cur["level"] == "sealed":
|
||||
continue # only its custodian, from the cloud
|
||||
if cur is None or float(e.get("at", 0)) > float(cur.get("at", 0)):
|
||||
out[t] = e
|
||||
return out
|
||||
|
||||
|
||||
def level_of(policy: dict, targets) -> tuple:
|
||||
"""The strongest level among the targets (a device's covers its
|
||||
controls and entities), and its entry."""
|
||||
best = ("none", None)
|
||||
for t in targets:
|
||||
e = policy.get(t)
|
||||
if e and RANK[e["level"]] > RANK[best[0]]:
|
||||
best = (e["level"], e)
|
||||
return best
|
||||
|
||||
|
||||
def device_targets(dev: dict, frag: dict, local: dict) -> list:
|
||||
"""The device, its controls and entities, and what its profile
|
||||
protects (an entity Cantabile does not map, e.g. an inverter's output
|
||||
switch)."""
|
||||
ts = [f"device:{dev['id']}"]
|
||||
ts += [f"control:{c['id']}" for c in frag.get("controls", [])]
|
||||
ts += [f"entity:{e}" for e in fragment_entities(frag)]
|
||||
ts += [t for t, e in local.items() if e.get("device") == dev["id"] and t not in ts]
|
||||
return ts
|
||||
|
||||
|
||||
def profile_protection(dev_id, p, s, ents, frag, now=None) -> dict:
|
||||
"""A new device's entries from its profile: the device's, its controls'
|
||||
and the entities its setup path protects."""
|
||||
now = time.time() if now is None else now
|
||||
out = {}
|
||||
|
||||
def put(target, x):
|
||||
out[target] = {"level": x["level"], **({"custodian": x["custodian"]} if x.get("custodian") else {}),
|
||||
"why": x.get("why") or f"{p['manufacturer']} {p['name']}", "set_by": f"profile {p['id']}",
|
||||
"role": "profile", "at": now, "source": "profile", "device": dev_id}
|
||||
if p.get("protection"):
|
||||
put(f"device:{dev_id}", p["protection"])
|
||||
kinds = {}
|
||||
for c in s.get("controls", []):
|
||||
if c.get("protection"):
|
||||
kinds[c["kind"]] = {"level": c["protection"], "custodian": c.get("custodian") or (p.get("protection") or {}).get("custodian")}
|
||||
for c in frag.get("controls", []):
|
||||
if c["kind"] in kinds:
|
||||
put(f"control:{c['id']}", kinds[c["kind"]])
|
||||
for x in s.get("protect", []):
|
||||
m = x["match"]
|
||||
if s["path"] == "modbus":
|
||||
hits = [e for e in ents if e.get("unique_id") == bridge_uid(dev_id, m["key"])]
|
||||
else:
|
||||
hits = [e for e in ents if entity_matches(m, e)]
|
||||
for e in hits:
|
||||
put(f"entity:{e['entity_id']}", x)
|
||||
return out
|
||||
|
||||
|
||||
def custodian_words(e: dict | None) -> str:
|
||||
return (e or {}).get("custodian", "?").replace("_", " ")
|
||||
|
||||
|
||||
def owner_entry(policy: dict, targets, dev_id: str, target: str, level: str, by: str = "owner",
|
||||
why: str = "", now=None) -> dict:
|
||||
"""The owner's protection of one of the device's targets: none or
|
||||
protected, never a sealed one, never to sealed (a custodian's, from
|
||||
Cantabile). The new entry for the box's own policy."""
|
||||
if target not in targets:
|
||||
raise Fail("not this device's")
|
||||
if level not in ("none", "protected"):
|
||||
raise Fail("the owner sets none or protected; sealed is a custodian's, from Cantabile")
|
||||
cur, entry = level_of(policy, targets)
|
||||
own = policy.get(target)
|
||||
if (own and own["level"] == "sealed") or (cur == "sealed" and target == f"device:{dev_id}"):
|
||||
raise Fail(f"sealed by its custodian ({custodian_words(entry or own)}): only they can change it")
|
||||
return {"level": level, "set_by": str(by or "owner")[:60], "role": "owner",
|
||||
"at": time.time() if now is None else now, "why": str(why or "")[:200], "source": "owner", "device": dev_id}
|
||||
|
||||
|
||||
def sealed(policy: dict, dev_id: str) -> dict | None:
|
||||
"""The seal on the whole device, if any."""
|
||||
lvl, e = level_of(policy, [f"device:{dev_id}"])
|
||||
return e if lvl == "sealed" else None
|
||||
|
||||
|
||||
# --- the owner's settings per device kind -------------------------------------------------
|
||||
# A shade (ha-cover): the room it shades and its window's orientation.
|
||||
ORIENTATIONS = {"N": 0, "NE": 45, "E": 90, "SE": 135, "S": 180, "SW": 225, "W": 270, "NW": 315}
|
||||
|
||||
|
||||
def parse_facing(v) -> float:
|
||||
""""N", "SW", degrees (0-360) or "" (not known: -1)."""
|
||||
t = str(v if v is not None else "").strip().upper()
|
||||
if t in ("", "-1", "?"):
|
||||
return -1.0
|
||||
if t in ORIENTATIONS:
|
||||
return float(ORIENTATIONS[t])
|
||||
try:
|
||||
x = float(t)
|
||||
except ValueError:
|
||||
raise Fail("the window faces N, NE, E, SE, S, SW, W, NW or degrees (0-360)") from None
|
||||
if not 0 <= x <= 360:
|
||||
raise Fail("the window faces N, NE, E, SE, S, SW, W, NW or degrees (0-360)")
|
||||
return x % 360
|
||||
|
||||
|
||||
def shade_of(frag: dict) -> dict | None:
|
||||
"""A shade's settings (its first cover control): area, facing, room."""
|
||||
c = next((c for c in frag.get("controls", []) if c.get("kind") == "cover"), None)
|
||||
if c is None:
|
||||
return None
|
||||
p = c.get("params") or {}
|
||||
return {"area": p.get("area", ""), "facing": float(p.get("facing", -1)), "room": p.get("room", "")}
|
||||
|
||||
|
||||
def room_control(frags, area_slug: str) -> str:
|
||||
"""The heating or cooling control of a room (a device whose values are
|
||||
that room's), "" when none: the optimiser counts a shade's sun there."""
|
||||
for f in frags:
|
||||
if any(str(a.get("asset", "")).startswith(f"room.{area_slug}.") for a in f.get("assets") or []):
|
||||
for c in f.get("controls") or []:
|
||||
if c.get("kind") in ("heating", "cooling") and c.get("id"):
|
||||
return c["id"]
|
||||
return ""
|
||||
|
||||
|
||||
def set_shade(frag: dict, data: dict, others=()) -> dict:
|
||||
"""The owner's shade settings into its cover controls (in place): area
|
||||
(a room's name or its slug; "" none), facing (see parse_facing); the
|
||||
room's heating or cooling control from the other devices' fragments."""
|
||||
covers = [c for c in frag.get("controls", []) if c.get("kind") == "cover"]
|
||||
if not covers:
|
||||
raise Fail("this device is no shade")
|
||||
area = slug(data.get("area")) if str(data.get("area") or "").strip() else ""
|
||||
face = parse_facing(data.get("facing"))
|
||||
room = room_control(others, area) if area else ""
|
||||
for c in covers:
|
||||
p = c.setdefault("params", {})
|
||||
p["area"], p["facing"] = area, face
|
||||
if room:
|
||||
p["room"] = room
|
||||
else:
|
||||
p.pop("room", None)
|
||||
return shade_of(frag)
|
||||
|
||||
|
||||
# A temperature and humidity sensor (ha-climate-sensor): indoor (a room) or outdoor.
|
||||
PLACES = ("indoor", "outdoor")
|
||||
|
||||
|
||||
def place_of(frag: dict) -> dict | None:
|
||||
"""Indoor (its room) or outdoor: a temperature sensor's place."""
|
||||
if frag.get("profile") != "ha-climate-sensor":
|
||||
return None
|
||||
out = any(str(a.get("asset", "")).startswith("outside.") for a in frag.get("assets", []))
|
||||
area = next((str(a["asset"]).split(".")[1] for a in frag.get("assets", [])
|
||||
if str(a.get("asset", "")).startswith("room.")), "")
|
||||
return {"place": "outdoor" if out else "indoor", "area": area}
|
||||
|
||||
|
||||
def set_place(frag: dict, data: dict, taken=()) -> dict:
|
||||
"""Indoor in a room (room.<area>.temp, .humidity; temp_2 where the room
|
||||
has one already) or outdoor (outside.temp, outside.humidity, and the
|
||||
optimiser's outside temperature: a measured one, over the weather's).
|
||||
taken: the ids the site's other mappings use. In place."""
|
||||
if frag.get("profile") != "ha-climate-sensor":
|
||||
raise Fail("this device is no temperature sensor")
|
||||
where = data.get("place")
|
||||
if where not in PLACES:
|
||||
raise Fail("indoor or outdoor")
|
||||
area = slug(data.get("area") or "home")
|
||||
taken = set(taken) - {a["asset"] for a in frag.get("assets", [])}
|
||||
temp = None
|
||||
for a in frag.get("assets", []):
|
||||
what = "humidity" if "humidity" in a["asset"] else "temp"
|
||||
want = f"outside.{what}" if where == "outdoor" else f"room.{area}.{what}"
|
||||
a["asset"] = free_id(want, taken)
|
||||
if what == "temp":
|
||||
temp = a["entity"]
|
||||
frag.pop("inputs", None)
|
||||
if where == "outdoor" and temp:
|
||||
frag["inputs"] = {"outside_temp": temp}
|
||||
return place_of(frag)
|
||||
|
||||
|
||||
# A weather service (ha-weather): only one plans (the mapping's inputs.weather).
|
||||
def weather_of(frag: dict) -> dict | None:
|
||||
if frag.get("profile") != "ha-weather":
|
||||
return None
|
||||
return {"active": bool((frag.get("inputs") or {}).get("weather")),
|
||||
"entity": next((a["entity"] for a in frag.get("assets", []) if a["entity"].startswith("weather.")),
|
||||
(frag.get("inputs") or {}).get("weather") or (frag.get("weather_entity") or ""))}
|
||||
|
||||
|
||||
def set_weather(frags: dict, dev_id: str) -> None:
|
||||
"""This weather device's forecast plans; every other weather device's
|
||||
is kept but not used (one weather source). frags: {device: fragment},
|
||||
in place."""
|
||||
if (frags.get(dev_id) or {}).get("profile") != "ha-weather":
|
||||
raise Fail("this device is no weather service")
|
||||
for i, f in frags.items():
|
||||
if f.get("profile") != "ha-weather":
|
||||
continue
|
||||
ent = (f.get("inputs") or {}).get("weather") or f.get("weather_entity")
|
||||
if not ent:
|
||||
continue
|
||||
f["weather_entity"] = ent
|
||||
if i == dev_id:
|
||||
f["inputs"] = {"weather": ent}
|
||||
else:
|
||||
f.pop("inputs", None)
|
||||
|
||||
|
||||
def one_weather(frag: dict, others) -> None:
|
||||
"""A new weather device plans only when no other one does (in place)."""
|
||||
ent = (frag.get("inputs") or {}).get("weather")
|
||||
if ent:
|
||||
frag["weather_entity"] = ent
|
||||
if any((o.get("inputs") or {}).get("weather") for o in others):
|
||||
frag.pop("inputs", None)
|
||||
@@ -0,0 +1,321 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""What one device shows on Cantabile's dashboard (dashboards.py): its
|
||||
device profile's "view" (hub/profiles/README.md) resolved to the device's
|
||||
entities in HA, or, for a device no profile describes, a view guessed from
|
||||
HA's device classes.
|
||||
|
||||
A profile's view names values by reference:
|
||||
- a quantity of Cantabile's ("pv.power", "room.{area}.temp"): on Cantabile's
|
||||
Modbus bridge, the register that gives it; on a device of an HA
|
||||
integration, the matcher of the profile's setup path for that integration
|
||||
(else its "existing" path), as the mapping's proposal does (propose.py);
|
||||
- a name in view.values: {name: matcher}, a matcher with a register "key"
|
||||
(the bridge) and/or HA's entity fields (entity_id, unique_id,
|
||||
original_name: regular expressions; translation_key, domain, device_class:
|
||||
exact);
|
||||
- a register key (the bridge's devices).
|
||||
Channels (circuits, phases, relays) are view.channels: {role: matcher}
|
||||
with "{n}" where the channel's number or letter is; the roles are power,
|
||||
energy, current, voltage and switch.
|
||||
|
||||
Devices of the bridges are known by their identifiers (mqtt,
|
||||
cantabile_modbus_<id>, or the EEBUS bridge's cantabile_eebus_<id>) and their
|
||||
model (the profile's name); others by the
|
||||
profile's recognise.ha patterns, as on the Hub's Devices page (specific
|
||||
profiles first; a generic one, recognise.fallback, such as ha-thermostat
|
||||
for any climate device, only where none fits).
|
||||
|
||||
A cover card (a shade) shows HA's tile of the cover with its features
|
||||
(position slider where it can be set to one, else open/close; tilt where
|
||||
it has one); a weather card the service's hourly forecast.
|
||||
|
||||
A climate card shows the thermostat, its view.climate_state attributes
|
||||
(hvac_action, fan_mode) read-only, and, for a thermostat that does not
|
||||
report back (HA's assumed_state, or no hvac_action: an infrared one), a
|
||||
note that what it shows is assumed.
|
||||
"""
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .devprofiles import kinds_of
|
||||
from .propose import alternatives, assumed_state, bridge_device, bridge_prefix, by_priority, recognise
|
||||
|
||||
CARDS = ("flow", "gauge", "circuits", "switches", "climate", "charger", "meter", "sensor", "cover", "weather")
|
||||
ROLES = ("power", "energy", "current", "voltage", "switch")
|
||||
FLOW = ("pv", "grid", "load", "battery", "soc")
|
||||
N_RE = r"(?P<n>[0-9]+|[a-z])"
|
||||
HEADLINE_MAX = 6
|
||||
|
||||
|
||||
@dataclass
|
||||
class DeviceView:
|
||||
card: str
|
||||
profile: str | None = None
|
||||
category: str | None = None # the profile's (inverter, sensor, ...)
|
||||
headline: list[str] = field(default_factory=list) # entity ids, in order
|
||||
flow: dict[str, str] = field(default_factory=dict) # pv/grid/load/battery/soc -> entity
|
||||
energy: list[str] = field(default_factory=list) # counters (energy today)
|
||||
channels: list[dict] = field(default_factory=list) # [{"n", role: entity}], in order
|
||||
climate: str | None = None
|
||||
switches: list[str] = field(default_factory=list)
|
||||
climate_state: list[str] = field(default_factory=list) # the thermostat's attributes shown read-only
|
||||
assumed: bool = False # the thermostat does not report back
|
||||
cover: str | None = None # a shade's cover entity (HA's tile with its features)
|
||||
weather: str | None = None # a weather service's entity (its forecast card)
|
||||
|
||||
def entities(self) -> set[str]:
|
||||
out = set(self.headline) | set(self.flow.values()) | set(self.energy) | set(self.switches)
|
||||
out |= {e for c in self.channels for k, e in c.items() if k != "n"}
|
||||
out |= {e for e in (self.cover, self.weather) if e}
|
||||
return out | ({self.climate} if self.climate else set())
|
||||
|
||||
def empty(self) -> bool:
|
||||
return not (self.headline or self.flow or self.channels or self.climate or self.switches or self.cover
|
||||
or self.weather)
|
||||
|
||||
|
||||
class Device:
|
||||
"""One HA device with its entities (not hidden, not disabled, not
|
||||
diagnostic or configuration) and their states."""
|
||||
|
||||
def __init__(self, d: dict, ents: list[dict], states: dict | None):
|
||||
self.d, self.states = d, states
|
||||
self.ents = [e for e in ents if not e.get("entity_category")]
|
||||
self.bridge = bridge_device(d)
|
||||
self.prefix = bridge_prefix(d) # cantabile_modbus_ or cantabile_eebus_
|
||||
self.domains = sorted({e.get("platform") for e in ents if e.get("platform")})
|
||||
# domains, and with the device class (cover.curtain, sensor.temperature)
|
||||
self.entity_domains = sorted({k for e in ents for k in kinds_of(e, self._attrs(e))})
|
||||
self.by_uid = {str(e.get("unique_id")): e for e in self.ents}
|
||||
|
||||
def _attrs(self, e: dict) -> dict | None:
|
||||
st = (self.states or {}).get(e["entity_id"])
|
||||
return (st or {}).get("attributes") if st else None
|
||||
|
||||
def attr(self, e: dict, name: str):
|
||||
return (((self.states or {}).get(e["entity_id"]) or {}).get("attributes") or {}).get(name)
|
||||
|
||||
def device_class(self, e: dict):
|
||||
return self.attr(e, "device_class") or e.get("device_class") or e.get("original_device_class")
|
||||
|
||||
def matches(self, m: dict, e: dict, n_ok: bool = False) -> re.Match | bool | None:
|
||||
"""Does the matcher's HA part fit the entity (with {n}: the match,
|
||||
whose group "n" is the channel)?"""
|
||||
found = True
|
||||
for k in ("entity_id", "unique_id", "original_name"):
|
||||
if k in m:
|
||||
pat = m[k].replace("{n}", N_RE) if n_ok else m[k]
|
||||
x = re.search(pat, str(e.get(k) or ""))
|
||||
if not x:
|
||||
return None
|
||||
if "n" in x.groupdict():
|
||||
found = x
|
||||
if "translation_key" in m and e.get("translation_key") != m["translation_key"]:
|
||||
return None
|
||||
if "domain" in m and e["entity_id"].split(".")[0] != m["domain"]:
|
||||
return None
|
||||
if "device_class" in m and self.device_class(e) != m["device_class"]:
|
||||
return None
|
||||
return found
|
||||
|
||||
def find(self, m: dict | None) -> str | None:
|
||||
"""The entity a matcher names on this device."""
|
||||
if not m:
|
||||
return None
|
||||
if self.bridge and "key" in m:
|
||||
e = self.by_uid.get(f"{self.prefix}{self.bridge}_{m['key']}")
|
||||
return e["entity_id"] if e else None
|
||||
if not set(m) & {"entity_id", "unique_id", "original_name", "translation_key", "domain", "device_class"}:
|
||||
return None
|
||||
return next((e["entity_id"] for e in self.ents if self.matches(m, e)), None)
|
||||
|
||||
def channel(self, m: dict) -> dict[str, str]:
|
||||
"""{channel: entity} of a matcher with {n}."""
|
||||
out = {}
|
||||
if self.bridge and "key" in m:
|
||||
pat = re.compile(re.escape(f"{self.prefix}{self.bridge}_") + m["key"].replace("{n}", N_RE) + "$")
|
||||
for uid, e in self.by_uid.items():
|
||||
x = pat.match(uid)
|
||||
if x:
|
||||
out[x.group("n")] = e["entity_id"]
|
||||
return out
|
||||
if not set(m) & {"entity_id", "unique_id", "original_name"}:
|
||||
return out
|
||||
for e in self.ents:
|
||||
x = self.matches(m, e, n_ok=True)
|
||||
if isinstance(x, re.Match):
|
||||
out.setdefault(x.group("n"), e["entity_id"])
|
||||
return out
|
||||
|
||||
|
||||
def _order(n: str):
|
||||
return (0, int(n), "") if n.isdigit() else (1, 0, n)
|
||||
|
||||
|
||||
def profile_of(dev: Device, profiles: list[dict]) -> dict | None:
|
||||
"""The profile of a bridge device (its model is the profile's name) or
|
||||
of an HA device it recognises; only profiles with a view."""
|
||||
with_view = [p for p in profiles if isinstance(p.get("view"), dict) and p["view"].get("card")]
|
||||
if dev.bridge:
|
||||
return next((p for p in with_view if p.get("name") == dev.d.get("model")), None)
|
||||
if dev.d.get("manufacturer") or dev.d.get("model"):
|
||||
return next((p for p in by_priority(with_view) if recognise(p, dev.d, dev.domains, dev.entity_domains)), None)
|
||||
return None
|
||||
|
||||
|
||||
def _registers(p: dict) -> list[dict]:
|
||||
mb = p.get("modbus") or {}
|
||||
return [*(mb.get("registers") or []), *(mb.get("derived") or []), *((p.get("ha") or {}).get("registers") or []),
|
||||
*((p.get("eebus") or {}).get("values") or [])]
|
||||
|
||||
|
||||
def _ref_matcher(p: dict, dev: Device, ref: str) -> dict | None:
|
||||
"""A reference (quantity, value name, register key) as a matcher on this device."""
|
||||
view = p.get("view") or {}
|
||||
if ref in (view.get("values") or {}):
|
||||
return view["values"][ref]
|
||||
if "." not in ref:
|
||||
return {"key": ref} if dev.bridge else None
|
||||
if dev.bridge:
|
||||
for r in _registers(p):
|
||||
if r.get("quantity") == ref:
|
||||
return {"key": r["key"]}
|
||||
for q in (r.get("split") or {}).values():
|
||||
if q == ref:
|
||||
return {"key": q.replace(".", "_")}
|
||||
return None
|
||||
paths = [s for s in p.get("setup") or [] if s.get("path") != "modbus"]
|
||||
s = next((s for s in paths if s.get("domain") and s["domain"] in dev.domains), None) or \
|
||||
next((s for s in paths if s["path"] == "existing"), None) or (paths[0] if paths else None)
|
||||
# an entity's own value (not one read from its attributes); of
|
||||
# alternatives the first this device has
|
||||
alts = [{k: v for k, v in m.items() if k != "scale"}
|
||||
for m in alternatives(((s or {}).get("values") or {}).get(ref)) if not m.get("attribute") and not m.get("equals")]
|
||||
alts = [{k: v for k, v in m.items() if k not in ("assumed", "supports")} for m in alts]
|
||||
return next((m for m in alts if dev.find(m)), alts[-1] if alts else None)
|
||||
|
||||
|
||||
def from_profile(p: dict, dev: Device) -> DeviceView:
|
||||
view = p["view"]
|
||||
dv = DeviceView(view["card"], p["id"], p.get("category"))
|
||||
|
||||
def ref(r):
|
||||
return dev.find(_ref_matcher(p, dev, r)) if isinstance(r, str) else None
|
||||
dv.flow = {k: e for k in FLOW if (e := ref((view.get("flow") or {}).get(k)))}
|
||||
dv.energy = [e for e in (ref(r) for r in view.get("energy") or []) if e]
|
||||
chans: dict[str, dict] = {}
|
||||
for role, m in (view.get("channels") or {}).items():
|
||||
for n, e in dev.channel(m).items():
|
||||
chans.setdefault(n, {"n": n})[role] = e
|
||||
dv.channels = [chans[n] for n in sorted(chans, key=_order)]
|
||||
if dv.card == "circuits" and not any("power" in c for c in dv.channels):
|
||||
dv.channels = []
|
||||
dv.climate = ref(view.get("climate")) if view.get("climate") else \
|
||||
next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("climate.")), None) \
|
||||
if dv.card == "climate" else None
|
||||
if dv.climate:
|
||||
e = next((x for x in dev.ents if x["entity_id"] == dv.climate), {"entity_id": dv.climate})
|
||||
st = ((dev.states or {}).get(dv.climate) or {})
|
||||
attrs = None if dev.states is None or not st or st.get("state") in ("unavailable", "unknown") \
|
||||
else st.get("attributes") or {}
|
||||
# HA's assumed_state always; no hvac_action (an infrared climate) for
|
||||
# a view that shows the climate's state (the generic thermostat)
|
||||
dv.assumed = bool((attrs or {}).get("assumed_state")) or \
|
||||
("climate_state" in view and bool(assumed_state(e, attrs)))
|
||||
dv.climate_state = [a for a in view.get("climate_state") or []
|
||||
if dev.states is None or dev.attr(e, a) is not None]
|
||||
if dv.card == "switches":
|
||||
dv.switches = [c["switch"] for c in dv.channels if c.get("switch")]
|
||||
dv.channels = []
|
||||
if dv.card == "cover":
|
||||
dv.cover = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("cover.")), None)
|
||||
if dv.card == "weather":
|
||||
dv.weather = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("weather.")), None)
|
||||
seen = set(dv.flow.values()) | ({dv.climate} if dv.climate else set()) | {e for e in (dv.cover, dv.weather) if e}
|
||||
for r in view.get("headline") or []:
|
||||
e = ref(r)
|
||||
if e and e not in dv.headline and e not in seen:
|
||||
dv.headline.append(e)
|
||||
dv.headline = dv.headline[:HEADLINE_MAX]
|
||||
return dv
|
||||
|
||||
|
||||
# -- devices without a profile: HA's device classes ------------------------------------
|
||||
|
||||
MAIN = ("battery", "power", "temperature", "humidity")
|
||||
|
||||
|
||||
def _stem(uid: str) -> tuple[str, str] | None:
|
||||
m = re.fullmatch(r"(.*\D)(\d+)", uid)
|
||||
return (m.group(1), m.group(2)) if m else None
|
||||
|
||||
|
||||
def guessed(dev: Device, alive=lambda e: True) -> DeviceView:
|
||||
"""Today's heuristic, widened: battery and power first (then temperature
|
||||
and humidity); power sensors numbered alike (…_power_1, …_power_2) are
|
||||
channels, named after the switch of the same number; a climate entity is
|
||||
a thermostat; a plug sensor makes a charger."""
|
||||
sensors = [e for e in dev.ents if e["entity_id"].startswith("sensor.") and dev.device_class(e) in MAIN
|
||||
and alive(e["entity_id"])]
|
||||
power = [e for e in sensors if dev.device_class(e) == "power"]
|
||||
stems: dict[str, dict[str, dict]] = {}
|
||||
for e in power:
|
||||
s = _stem(str(e.get("unique_id")))
|
||||
if s:
|
||||
stems.setdefault(s[0], {})[s[1]] = e
|
||||
chan = max(stems.values(), key=len, default={})
|
||||
channels = []
|
||||
if len(chan) > 1:
|
||||
switches: dict[str, dict[str, dict]] = {}
|
||||
for e in dev.ents:
|
||||
s = _stem(str(e.get("unique_id")))
|
||||
if s and e["entity_id"].split(".")[0] in ("switch", "light"):
|
||||
switches.setdefault(s[0], {})[s[1]] = e
|
||||
sw = max((x for x in switches.values() if set(chan) <= set(x)), key=len, default={})
|
||||
for n in sorted(chan, key=_order):
|
||||
c = {"n": n, "power": chan[n]["entity_id"]}
|
||||
if n in sw:
|
||||
c["switch"] = sw[n]["entity_id"]
|
||||
channels.append(c)
|
||||
sensors = [e for e in sensors if e not in chan.values()]
|
||||
order = {c: i for i, c in enumerate(MAIN)}
|
||||
main = [e for e in sensors if dev.device_class(e) in ("battery", "power")] or sensors
|
||||
headline = [e["entity_id"] for e in sorted(main, key=lambda e: order[dev.device_class(e)])][:4]
|
||||
climate = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("climate.")), None)
|
||||
plug = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("binary_sensor.")
|
||||
and dev.device_class(e) in ("plug", "battery_charging")), None)
|
||||
soc = next((e["entity_id"] for e in sensors if dev.device_class(e) == "battery"), None)
|
||||
dv = DeviceView("sensor", headline=headline, channels=channels, climate=climate)
|
||||
cover = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("cover.")), None)
|
||||
weather = next((e["entity_id"] for e in dev.ents if e["entity_id"].startswith("weather.")), None)
|
||||
if climate:
|
||||
dv.card = "climate"
|
||||
elif cover:
|
||||
dv.card, dv.cover = "cover", cover
|
||||
elif weather and not headline:
|
||||
dv.card, dv.weather = "weather", weather
|
||||
elif plug:
|
||||
dv.card, dv.headline = "charger", [plug] + headline
|
||||
elif channels:
|
||||
dv.card = "circuits"
|
||||
elif soc and power:
|
||||
dv.card = "gauge"
|
||||
if dv.empty():
|
||||
sw = [e["entity_id"] for e in dev.ents if e["entity_id"].startswith("switch.")]
|
||||
if sw:
|
||||
dv.card, dv.switches = "switches", sw
|
||||
return dv
|
||||
|
||||
|
||||
def view_of(d: dict, ents: list[dict], states: dict | None, profiles: list[dict],
|
||||
alive=lambda e: True) -> DeviceView:
|
||||
dev = Device(d, ents, states)
|
||||
p = profile_of(dev, profiles)
|
||||
if p is not None:
|
||||
dv = from_profile(p, dev)
|
||||
if not dv.empty():
|
||||
dv.headline = [e for e in dv.headline if alive(e)]
|
||||
dv.flow = {k: e for k, e in dv.flow.items() if alive(e)}
|
||||
dv.energy = [e for e in dv.energy if alive(e)]
|
||||
return dv
|
||||
return guessed(dev, alive)
|
||||
@@ -0,0 +1,296 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""From what is wanted to Home Assistant service calls, through the guard.
|
||||
|
||||
Each control has one wanted value at a time, from (highest first):
|
||||
1. a command from the console (`control`, with its level: flexible,
|
||||
binding, emergency), until it ends or is released;
|
||||
2. the current plan's step, while the plan is fresh (made in the last
|
||||
stale_s) and its inputs were fresh;
|
||||
3. the control's safe defaults (mapping `safe:`), when the plan or its
|
||||
data is stale; a battery's default is no grid charging and power 0.
|
||||
The wanted value becomes actions on the control's channels, but only where
|
||||
the device differs from it (no repeated calls), each checked by the guard.
|
||||
Every action, refusal and owner override is reported (`action` messages:
|
||||
ctb.site.<id>.action) and logged; a refusal once per control and reason
|
||||
per hour.
|
||||
|
||||
A flexible command the owner overrides by hand ends (reported "overridden");
|
||||
binding and emergency commands are applied again (the flat cannot lift them).
|
||||
"""
|
||||
import logging
|
||||
import time
|
||||
|
||||
from .guard import Action
|
||||
from .inputs import cover_position, cover_positions, number
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
RELEASE = "release" # a safe value meaning: leave the device as it is
|
||||
|
||||
|
||||
def _plan_value(plan: dict, cid: str, now: float):
|
||||
cur = None
|
||||
for e in (plan or {}).get("devices", {}).get(cid, []):
|
||||
if e["t"] <= now:
|
||||
cur = e
|
||||
return cur
|
||||
|
||||
|
||||
def actions_for(c, want, col, level="plan", why="") -> list[Action]:
|
||||
"""The actions that bring control c to `want` (a plan entry's set, a
|
||||
command's set, or a safe value), only where the device differs."""
|
||||
e = c.entities
|
||||
out = []
|
||||
|
||||
def act(channel, service, data, value, quantity=""):
|
||||
ent = e[channel]
|
||||
out.append(Action(c.id, channel, ent, ent.split(".", 1)[0], service, data, value, quantity, level, why))
|
||||
|
||||
def switch(channel, on: bool):
|
||||
if channel in e and (col.state(e[channel]) == "on") != on:
|
||||
act(channel, "turn_on" if on else "turn_off", {}, "on" if on else "off")
|
||||
|
||||
def setnum(channel, v: float, quantity: str):
|
||||
if channel in e and (number(col.state(e[channel])) is None or abs(number(col.state(e[channel])) - v) > 0.5):
|
||||
act(channel, "set_value", {"value": v}, v, quantity)
|
||||
|
||||
if want is None or want == RELEASE:
|
||||
return out
|
||||
if c.kind == "battery":
|
||||
if isinstance(want, dict): # a plan entry: power and whether from the grid
|
||||
power, grid = float(want.get("set", 0)), bool(want.get("grid"))
|
||||
else:
|
||||
power, grid = float(want), float(want) > 0
|
||||
# With a setpoint the power is set there and the grid switch stays
|
||||
# off (it means "full power" on many inverters and would override
|
||||
# the setpoint); a battery with the switch alone is driven by it.
|
||||
switch("charge_from_grid", grid and "setpoint" not in e)
|
||||
if "mode" in e:
|
||||
# the inverter's own mode: manual while the plan sets power,
|
||||
# its self-consumption otherwise (the setpoint counts in manual only)
|
||||
opt = str(c.p("manual_option") if abs(power) >= 50 else c.p("auto_option"))
|
||||
if col.state(e["mode"]) != opt:
|
||||
act("mode", "select_option", {"option": opt}, opt)
|
||||
setnum("setpoint", power, "power_w")
|
||||
elif c.kind in ("heating", "cooling"):
|
||||
v = want.get("set") if isinstance(want, dict) else want
|
||||
if "climate" in e:
|
||||
c.learn_range(col)
|
||||
step = c.temp_step(col)
|
||||
if number(v) is not None and step:
|
||||
# the thermostat's step (0.5, 1): a value it can take
|
||||
lo, hi = c.device_range("temp_c")
|
||||
r = round(float(v) / step) * step
|
||||
r = r + step if r < lo - 1e-9 else r - step if r > hi + 1e-9 else r
|
||||
v = round(r, 3)
|
||||
state = col.state(e["climate"])
|
||||
mode = "cool" if c.kind == "cooling" else "heat"
|
||||
if v == "off":
|
||||
if state not in ("off", None):
|
||||
act("climate", "set_hvac_mode", {"hvac_mode": "off"}, "off")
|
||||
elif number(v) is not None:
|
||||
if state != mode:
|
||||
act("climate", "set_hvac_mode", {"hvac_mode": mode}, mode)
|
||||
cur = number(col.attr(e["climate"], "temperature"))
|
||||
if cur is None or abs(cur - float(v)) > 0.25:
|
||||
act("climate", "set_temperature", {"temperature": float(v)}, float(v), "temp_c")
|
||||
elif v in ("on", "off"):
|
||||
switch("switch", v == "on")
|
||||
elif c.kind == "ev":
|
||||
v = want.get("set") if isinstance(want, dict) else want
|
||||
if v == "off":
|
||||
switch("switch", False)
|
||||
elif number(v) is not None:
|
||||
setnum("current", float(v), "current_a")
|
||||
switch("switch", True)
|
||||
elif c.kind == "cover":
|
||||
v = number(want.get("set") if isinstance(want, dict) else want)
|
||||
if v is not None:
|
||||
if col.state(e["cover"]) in ("opening", "closing"):
|
||||
return out # moving: wait for it to stop
|
||||
cur = cover_position(col, e["cover"])
|
||||
if cover_positions(col, e["cover"]):
|
||||
if cur is None or abs(cur - v) > 2:
|
||||
act("cover", "set_cover_position", {"position": int(round(v))}, v, "position_pct")
|
||||
elif v >= 50 and cur != 100.0:
|
||||
# open and close only: halfway or more is open
|
||||
act("cover", "open_cover", {}, 100.0, "position_pct")
|
||||
elif v < 50 and cur != 0.0:
|
||||
act("cover", "close_cover", {}, 0.0, "position_pct")
|
||||
return out
|
||||
|
||||
|
||||
def building_msg(c: dict, result: str, why: str, at: float) -> dict:
|
||||
"""An `action` message about a building request (agreed form)."""
|
||||
return {"v": 1, "at": int(at), "asset": "", "entity": f"building:{c['building']}",
|
||||
"service": f"building.{c['control']}", "value": c["value"], "result": result, "why": why,
|
||||
"level": c["level"], "id": c["id"]}
|
||||
|
||||
|
||||
def safe_want(c):
|
||||
"""The control's safe value when plans or data are stale."""
|
||||
if c.kind == "battery":
|
||||
s = c.safe or {}
|
||||
return {"set": float(s.get("setpoint", 0)), "grid": bool(s.get("charge_from_grid", False))}
|
||||
v = (c.safe or {}).get(next(iter(c.writable()), ""), RELEASE)
|
||||
return v
|
||||
|
||||
|
||||
class Executor:
|
||||
def __init__(self, controls, guard, col, publish, *, stale_s=1800, clock=time.time, building=None):
|
||||
self.building = building # the building's requests (building.py), or None
|
||||
self.controls = {c.id: c for c in controls}
|
||||
self.guard, self.col, self.publish, self.stale, self.clock = guard, col, publish, stale_s, clock
|
||||
self.plan: dict | None = None
|
||||
self.inputs_ok = True
|
||||
self.commands: dict[str, dict] = {} # control -> {"set", "level", "until", "id", "why"}
|
||||
self._refused: dict[tuple, float] = {}
|
||||
self.log: list[dict] = [] # the last actions (tests, status)
|
||||
|
||||
# -- what is wanted ------------------------------------------------------
|
||||
def wanted(self, c, now):
|
||||
want, level, why = self._wanted(c, now)
|
||||
return self._capped(c, want, level, why, now)
|
||||
|
||||
def _wanted(self, c, now):
|
||||
cmd = self.commands.get(c.id)
|
||||
if cmd and now < cmd["until"]:
|
||||
return cmd["set"], cmd["level"], cmd.get("why") or f"{cmd['level']} command"
|
||||
if cmd:
|
||||
self.commands.pop(c.id, None)
|
||||
fresh = self.plan is not None and now - self.plan.get("made", 0) <= self.stale and self.inputs_ok
|
||||
if fresh:
|
||||
e = _plan_value(self.plan, c.id, now)
|
||||
return e, "plan", (e or {}).get("why", "")
|
||||
return safe_want(c), "plan", "safe default: the plan or its data is stale"
|
||||
|
||||
def _capped(self, c, want, level, why, now):
|
||||
"""The building's thermostat cap on a climate's setpoint (heating: at
|
||||
most, cooling: at least), at the cap's level: a binding cap applies
|
||||
again when the owner changes it by hand."""
|
||||
if self.building is None or "climate" not in c.entities:
|
||||
return want, level, why
|
||||
cap, cmd = self.building.cap(c.kind, now)
|
||||
if cap is None:
|
||||
return want, level, why
|
||||
v = want.get("set") if isinstance(want, dict) else want
|
||||
if number(v) is None:
|
||||
return want, level, why
|
||||
v = float(v)
|
||||
capped = min(v, cap) if c.kind == "heating" else max(v, cap)
|
||||
if capped == v and level != "plan":
|
||||
return want, level, why
|
||||
lvl = cmd["level"] if level in ("plan", "flexible") else level
|
||||
return {"set": capped}, lvl, f"building {cmd['building']}: {cmd['why'] or 'thermostat cap'} ({cap:g} °C)"
|
||||
|
||||
# -- one round ---------------------------------------------------------------
|
||||
async def tick(self, client, auto: bool):
|
||||
"""One round: overrides seen since the last, then each control. With
|
||||
auto False only overrides are reported (the guard refuses anyway)."""
|
||||
now = self.clock()
|
||||
await self._overrides(now)
|
||||
if not auto or client is None:
|
||||
return
|
||||
sw = self.guard.switchover
|
||||
for c in self.controls.values():
|
||||
if sw is not None and not sw.active(c):
|
||||
continue # the thermostat's other control acts (switchover.py)
|
||||
want, level, why = self.wanted(c, now)
|
||||
acts = actions_for(c, want, self.col, level, why)
|
||||
if why.startswith("building") and not any(a.channel == "climate" for a in acts):
|
||||
# the room is within the building's cap already: a change by
|
||||
# hand still counts as an override of the cap
|
||||
self.guard.expect(c.id, c.entities["climate"], want["set"])
|
||||
for a in acts:
|
||||
await self._do(client, a, now)
|
||||
|
||||
async def _do(self, client, a: Action, now):
|
||||
ok, reason = self.guard.check(a)
|
||||
if not ok:
|
||||
key = (a.control, reason.split(" ")[0] + reason[-12:])
|
||||
if now - self._refused.get(key, 0) >= 3600:
|
||||
self._refused[key] = now
|
||||
await self._report(a, "refused", reason, now)
|
||||
return
|
||||
try:
|
||||
await client.call_service(a.domain, a.service, a.entity, a.data, self._allowed(a))
|
||||
except Exception as e:
|
||||
await self._report(a, "failed", str(e)[:200], now)
|
||||
return
|
||||
self.guard.done(a)
|
||||
await self._report(a, "done", a.why, now)
|
||||
|
||||
@staticmethod
|
||||
def _allowed(a: Action):
|
||||
"""The HA client's check: exactly this action and nothing else."""
|
||||
return lambda d, s, ent: (d, s, ent) == (a.domain, a.service, a.entity)
|
||||
|
||||
async def _overrides(self, now):
|
||||
while self.guard.events:
|
||||
ev = self.guard.events.pop(0)
|
||||
c = self.controls.get(ev["control"])
|
||||
cap, bcmd = self.building.cap(c.kind, now) if self.building is not None and c else (None, None)
|
||||
if bcmd is not None and "climate" in c.entities and ev["entity"] == c.entities["climate"]:
|
||||
await self._building_override(bcmd, ev)
|
||||
cmd = self.commands.get(ev["control"])
|
||||
if cmd and cmd["level"] == "flexible":
|
||||
self.commands.pop(ev["control"], None) # the owner wins over a flexible command
|
||||
why = f"the owner changed it by hand: flexible command {cmd.get('id', '')} ended"
|
||||
elif cmd:
|
||||
why = f"the owner changed it by hand: {cmd['level']} command applied again"
|
||||
else:
|
||||
why = f"the owner changed it by hand: hands off until {time.strftime('%H:%M UTC', time.gmtime(ev['until']))}"
|
||||
await self.publish("action", {"v": 1, "at": ev["at"], "asset": ev["control"], "entity": ev["entity"],
|
||||
"service": "", "value": ev["value"], "result": "overridden", "why": why})
|
||||
log.info("override: %s %s=%s (%s)", ev["control"], ev["entity"], ev["value"], why)
|
||||
self.log.append({"result": "overridden", **ev})
|
||||
|
||||
async def _building_override(self, bcmd, ev):
|
||||
"""The owner changed a room the building's cap holds: a flexible cap
|
||||
ends, a binding one stays (applied again)."""
|
||||
if bcmd["level"] == "flexible":
|
||||
self.building.lift("thermostat_cap")
|
||||
why = "the owner changed it by hand: the flexible cap ended"
|
||||
else:
|
||||
why = "the owner changed it by hand: the binding cap applied again"
|
||||
await self.publish("action", building_msg(bcmd, "overridden", why, ev["at"]))
|
||||
|
||||
async def _report(self, a: Action, result, why, now):
|
||||
msg = {"v": 1, "at": int(now), "asset": a.control, "entity": a.entity,
|
||||
"service": f"{a.domain}.{a.service}", "value": a.value, "result": result, "why": why,
|
||||
"level": a.level}
|
||||
self.log.append(msg)
|
||||
self.log = self.log[-200:]
|
||||
log.info("action %s: %s %s %s=%s (%s)", result, a.control, msg["service"], a.entity, a.value, why)
|
||||
await self.publish("action", msg)
|
||||
|
||||
# -- commands from the console ------------------------------------------
|
||||
def command(self, args: dict, now: float) -> tuple[bool, str]:
|
||||
cid = args.get("asset", "")
|
||||
c = self.controls.get(cid)
|
||||
if c is None:
|
||||
return False, f"no control {cid!r}"
|
||||
sw = self.guard.switchover
|
||||
if sw is not None and not sw.active(c):
|
||||
return False, f"{cid}: not active now (the thermostat is on its other side: switchover)"
|
||||
level = args.get("level", "flexible")
|
||||
if level not in ("flexible", "binding", "emergency"):
|
||||
return False, "level: flexible, binding or emergency"
|
||||
try:
|
||||
until = float(args["until"]) if args.get("until") else now + 60 * float(args.get("minutes", 60))
|
||||
except ValueError:
|
||||
return False, "until: unix time, or minutes"
|
||||
if until <= now:
|
||||
return False, "already over"
|
||||
v = args.get("set", "")
|
||||
want = float(v) if number(v) is not None else v
|
||||
if want in ("", None):
|
||||
return False, "set: a value"
|
||||
self.commands[cid] = {"set": want, "level": level, "until": until, "id": args.get("id", ""),
|
||||
"why": args.get("why") or f"{level} command"}
|
||||
return True, f"{cid}: {want} ({level}) until {time.strftime('%H:%M UTC', time.gmtime(until))}"
|
||||
|
||||
def release(self, cid: str) -> tuple[bool, str]:
|
||||
if self.commands.pop(cid, None) is None:
|
||||
return False, f"no command for {cid!r}"
|
||||
return True, f"{cid}: back to the plan"
|
||||
@@ -0,0 +1,231 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The grid operator's limit from the EEBUS bridge: §14a EnWG
|
||||
dimming through the grid operator's control box (EEBUS LPC), as a
|
||||
higher-rank decision of the agent.
|
||||
|
||||
The bridge (hub/addons/eebus-bridge, order.go) publishes retained on
|
||||
`cantabile-eebus/gridorder`:
|
||||
|
||||
{"order": "<JSON text>", "sig": base64, "key": base64}
|
||||
|
||||
the order text signed with the bridge's own Ed25519 key:
|
||||
|
||||
{"v": 1, "kind": "eebus-lpc", "id", "state": "normal|limited|failsafe|autonomous",
|
||||
"active", "limit_w", "from", "until" (0: until changed), "failsafe_w",
|
||||
"failsafe_s", "control_box": {"ski", "device"}, "scope": "controllable",
|
||||
"issued"}
|
||||
|
||||
Trust chain (what makes this the "verified proof" an emergency needs,
|
||||
building.py; the link's relayed grid orders are the cloud's way, this is
|
||||
the local one):
|
||||
1. control box -> bridge: SHIP's mutual TLS; the bridge trusts the control
|
||||
box's SKI only after the owner or installer compared it with the box's
|
||||
own and paired it on the bridge's page; only that SKI's LPC writes are
|
||||
approved, and the paired control box is sealed (custodian
|
||||
grid_operator): it can't be unpaired or overridden on the box.
|
||||
2. bridge -> agent: the order signed with the bridge's key. The agent pins
|
||||
the first key it sees (<state>/eebus-bridge.key, trust on first use)
|
||||
and refuses a different one until the pin is removed on the box (a
|
||||
reinstalled bridge; logged). On the Hub the broker's ACL also lets
|
||||
only the bridge's user and HA's publish there.
|
||||
3. agent: a good order from a control box becomes the proof
|
||||
"verified:eebus-lpc:<control box SKI>:<order id>" and a grid-level
|
||||
limit: the optimiser's constraint on the controllable consumers' draw,
|
||||
the guard's bound per controllable device. The control box's SKI goes
|
||||
to the cloud in the inventory, so the grid operator can see which box
|
||||
limits.
|
||||
A box's root owner can always change software on their own box (3n):
|
||||
this makes tampering visible, not impossible.
|
||||
|
||||
An order older than STALE_S (the bridge sends it every 15 s) is dropped:
|
||||
the bridge's own failsafe (LPC) holds the devices then.
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
TOPIC = "cantabile-eebus/gridorder"
|
||||
STALE_S = 300
|
||||
PENALTY_EUR_KWH = 500.0 # like a relayed emergency (building.py): nobody overrides it
|
||||
|
||||
# -- Ed25519 verification (RFC 8032, 5.1.7), pure Python ----------------------
|
||||
|
||||
_P = 2 ** 255 - 19
|
||||
_L = 2 ** 252 + 27742317777372353535851937790883648493
|
||||
_D = -121665 * pow(121666, _P - 2, _P) % _P
|
||||
_I = pow(2, (_P - 1) // 4, _P)
|
||||
|
||||
|
||||
def _xrecover(y: int, sign: int) -> int | None:
|
||||
xx = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P) % _P
|
||||
x = pow(xx, (_P + 3) // 8, _P)
|
||||
if (x * x - xx) % _P:
|
||||
x = x * _I % _P
|
||||
if (x * x - xx) % _P:
|
||||
return None
|
||||
if x == 0 and sign:
|
||||
return None
|
||||
if x & 1 != sign:
|
||||
x = _P - x
|
||||
return x
|
||||
|
||||
|
||||
def _decode(b: bytes):
|
||||
if len(b) != 32:
|
||||
return None
|
||||
y = int.from_bytes(b, "little")
|
||||
sign, y = y >> 255, y & ((1 << 255) - 1)
|
||||
if y >= _P:
|
||||
return None
|
||||
x = _xrecover(y, sign)
|
||||
return None if x is None else (x, y, 1, x * y % _P)
|
||||
|
||||
|
||||
def _add(a, b):
|
||||
x1, y1, z1, t1 = a
|
||||
x2, y2, z2, t2 = b
|
||||
A = (y1 - x1) * (y2 - x2) % _P
|
||||
B = (y1 + x1) * (y2 + x2) % _P
|
||||
C = t1 * 2 * _D * t2 % _P
|
||||
Dd = z1 * 2 * z2 % _P
|
||||
E, F, G, H = B - A, Dd - C, Dd + C, B + A
|
||||
return (E * F % _P, G * H % _P, F * G % _P, E * H % _P)
|
||||
|
||||
|
||||
def _mul(s: int, p):
|
||||
q = (0, 1, 1, 0)
|
||||
while s:
|
||||
if s & 1:
|
||||
q = _add(q, p)
|
||||
p = _add(p, p)
|
||||
s >>= 1
|
||||
return q
|
||||
|
||||
|
||||
def _eq(a, b) -> bool:
|
||||
return (a[0] * b[2] - b[0] * a[2]) % _P == 0 and (a[1] * b[2] - b[1] * a[2]) % _P == 0
|
||||
|
||||
|
||||
_GY = 4 * pow(5, _P - 2, _P) % _P
|
||||
_G = (_xrecover(_GY, 0), _GY, 1, _xrecover(_GY, 0) * _GY % _P)
|
||||
|
||||
|
||||
def verify(key: bytes, msg: bytes, sig: bytes) -> bool:
|
||||
"""An Ed25519 signature (RFC 8032), checked."""
|
||||
if len(sig) != 64:
|
||||
return False
|
||||
A, R = _decode(key), _decode(sig[:32])
|
||||
s = int.from_bytes(sig[32:], "little")
|
||||
if A is None or R is None or s >= _L:
|
||||
return False
|
||||
h = int.from_bytes(hashlib.sha512(sig[:32] + key + msg).digest(), "little") % _L
|
||||
return _eq(_mul(s, _G), _add(R, _mul(h, A)))
|
||||
|
||||
|
||||
# -- orders -------------------------------------------------------------------
|
||||
|
||||
class GridOrders:
|
||||
def __init__(self, state_dir: str, clock=time.time):
|
||||
self.pin_path = os.path.join(state_dir, "eebus-bridge.key")
|
||||
self.clock = clock
|
||||
self.order: dict | None = None # the last good order
|
||||
self.received = 0.0
|
||||
self.error = ""
|
||||
|
||||
def pinned(self) -> str:
|
||||
try:
|
||||
with open(self.pin_path) as f:
|
||||
return f.read().strip()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
def take(self, payload: bytes | str) -> tuple[bool, str]:
|
||||
"""A message from the bridge: (changed, why). A bad one changes
|
||||
nothing (the last good order holds until it is stale)."""
|
||||
try:
|
||||
msg = json.loads(payload)
|
||||
text, key = msg["order"], msg["key"]
|
||||
raw_key, sig = base64.b64decode(key), base64.b64decode(msg["sig"])
|
||||
except (ValueError, KeyError, TypeError) as e:
|
||||
return self._bad(f"not a grid order: {e}")
|
||||
pin = self.pinned()
|
||||
if pin and pin != key:
|
||||
return self._bad("signed by another key than the paired bridge's (remove eebus-bridge.key on the box after a reinstall)")
|
||||
if not verify(raw_key, text.encode(), sig):
|
||||
return self._bad("bad signature")
|
||||
try:
|
||||
o = json.loads(text)
|
||||
except ValueError:
|
||||
return self._bad("the order is not JSON")
|
||||
if o.get("v") != 1 or o.get("kind") != "eebus-lpc" or o.get("scope") != "controllable":
|
||||
return self._bad("not an EEBUS LPC order v1")
|
||||
if o.get("active") and not (o.get("control_box") or {}).get("ski"):
|
||||
return self._bad("an active order without its control box")
|
||||
if not pin:
|
||||
tmp = self.pin_path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
f.write(key)
|
||||
os.replace(tmp, self.pin_path)
|
||||
log.info("grid order: the EEBUS bridge's key pinned")
|
||||
old = self.active()
|
||||
self.order, self.received, self.error = o, self.clock(), ""
|
||||
new = self.active()
|
||||
changed = (old or {}).get("id") != (new or {}).get("id") or (old or {}).get("limit_w") != (new or {}).get("limit_w") \
|
||||
or bool(old) != bool(new)
|
||||
return changed, "taken"
|
||||
|
||||
def _bad(self, why: str) -> tuple[bool, str]:
|
||||
if why != self.error:
|
||||
log.warning("grid order refused: %s", why)
|
||||
self.error = why
|
||||
return False, why
|
||||
|
||||
def active(self) -> dict | None:
|
||||
"""The order in force now, or None (none, ended, stale)."""
|
||||
o, now = self.order, self.clock()
|
||||
if not o or not o.get("active") or now - self.received > STALE_S:
|
||||
return None
|
||||
if o.get("until") and now >= o["until"]:
|
||||
return None
|
||||
return o
|
||||
|
||||
def proof(self) -> str:
|
||||
o = self.active()
|
||||
return f"verified:eebus-lpc:{o['control_box']['ski']}:{o['id']}" if o else ""
|
||||
|
||||
def for_model(self, start: int, step_s: int, steps: int) -> dict:
|
||||
"""The optimiser's constraint: the controllable consumers' draw from
|
||||
the grid at most limit_w (state["grid_order"])."""
|
||||
o = self.active()
|
||||
if not o:
|
||||
return {}
|
||||
until = o.get("until") or (start + steps * step_s)
|
||||
a = max(0, (int(o.get("from") or start) - start) // step_s)
|
||||
b = min(steps, -(-(int(until) - start) // step_s))
|
||||
if a >= b:
|
||||
return {}
|
||||
return {"limit_w": float(o["limit_w"]), "from_step": int(a), "to_step": int(b), "penalty": PENALTY_EUR_KWH,
|
||||
"id": o["id"], "proof": self.proof(), "state": o.get("state", "")}
|
||||
|
||||
def limits(self, controls) -> dict:
|
||||
"""Grid-level bounds per controllable device (§14a: chargers,
|
||||
batteries' charging; heat pumps are held by the bridge itself): no
|
||||
single one above the whole limit. {control id: {quantity: (floor,
|
||||
limit)}}."""
|
||||
o = self.active()
|
||||
if not o:
|
||||
return {}
|
||||
w = float(o["limit_w"])
|
||||
out = {}
|
||||
for c in controls:
|
||||
if c.kind == "ev":
|
||||
volts = float(c.params.get("voltage", 230)) * float(c.params.get("phases", 3))
|
||||
out[c.id] = {"current_a": (None, round(w / volts, 1))}
|
||||
elif c.kind == "battery":
|
||||
out[c.id] = {"power_w": (None, w)}
|
||||
return out
|
||||
@@ -0,0 +1,202 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The actuation guard: every action the agent would take goes through
|
||||
check() first, and only an allowed one becomes a Home Assistant service
|
||||
call (executor.py). In this order:
|
||||
|
||||
0. policy the device's protection (policy.py): never
|
||||
anything on a sealed device, never off on a protected one,
|
||||
whatever the command's level
|
||||
0b. switchover a thermostat that heats and cools: only its active control
|
||||
(heating or cooling, switchover.py) may act
|
||||
1. mode only in `auto` (shadow and advisory never act)
|
||||
2. consent the owner's for the site ("control" in consent.json) and the
|
||||
control's own (mapping v3), both off by default
|
||||
3. allow-list the control's own entities, with the service its kind uses
|
||||
4. bounds inside the effective floors and limits (limits.py: the
|
||||
device's range, the owner's, the building's, the cloud's, the
|
||||
grid operator's)
|
||||
5. override the owner changed it by hand: the agent keeps off it for
|
||||
override_hold_s (flexible), unless a binding or emergency
|
||||
command says otherwise (3b command levels)
|
||||
6. cycling a switch stays on/off for its minimum time (anti-cycling; only
|
||||
for equipment that wears from short cycles: heating, cooling)
|
||||
7. rate at most max_actions_per_hour per control; a cover moves at
|
||||
most once in its params.min_move_s (default 30 min)
|
||||
|
||||
Emergency commands skip 5-7 (nobody overrides them; device safety and the
|
||||
bounds still hold). Binding ones skip 5: the flat cannot lift them, only the
|
||||
building or the cloud. Every refusal has a reason, and is reported once per
|
||||
control and reason per hour (not every minute).
|
||||
"""
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
LEVELS = ("plan", "flexible", "binding", "emergency") # plan: the optimiser's own
|
||||
|
||||
|
||||
@dataclass
|
||||
class Action:
|
||||
control: str
|
||||
channel: str # the entity role (charge_from_grid, setpoint, climate, switch, current, cover)
|
||||
entity: str
|
||||
domain: str
|
||||
service: str
|
||||
data: dict
|
||||
value: float | str # what is set (W, °C, A, %, "on"/"off"/"cool"/...)
|
||||
quantity: str = "" # what bounds it (temp_c, power_w, current_a, position_pct; "" for on/off)
|
||||
level: str = "plan"
|
||||
why: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Track:
|
||||
times: list = field(default_factory=list) # when actions were taken (rate limit)
|
||||
switched: dict = field(default_factory=dict) # channel -> (time, value) of the last on/off change
|
||||
commanded: dict = field(default_factory=dict) # entity -> (time, value) the agent last set
|
||||
override_until: float = 0.0
|
||||
override_entity: str = ""
|
||||
moved: float = -1e18 # when a cover was last moved by the agent
|
||||
|
||||
|
||||
# The service each channel uses, by domain: nothing else can be called.
|
||||
SERVICES = {
|
||||
"switch": {"turn_on", "turn_off"},
|
||||
"input_boolean": {"turn_on", "turn_off"},
|
||||
"number": {"set_value"},
|
||||
"input_number": {"set_value"},
|
||||
"climate": {"set_temperature", "set_hvac_mode"},
|
||||
"cover": {"set_cover_position", "open_cover", "close_cover"},
|
||||
"select": {"select_option"},
|
||||
"input_select": {"select_option"},
|
||||
}
|
||||
|
||||
|
||||
class Guard:
|
||||
def __init__(self, controls, consent, mode=lambda: "shadow", *, override_hold_s=7200, min_switch_s=600,
|
||||
max_actions_per_hour=12, settle_s=90, clock=time.time):
|
||||
self.controls = {c.id: c for c in controls}
|
||||
self.consent, self.mode, self.clock = consent, mode, clock
|
||||
self.hold, self.min_switch, self.max_rate, self.settle = override_hold_s, min_switch_s, max_actions_per_hour, settle_s
|
||||
self.extra_limits: dict = {} # control -> quantity -> level -> (floor, limit), from commands
|
||||
self.policy = None # policy.Policy: the devices' protection
|
||||
self.switchover = None # switchover.Switchover: heating or cooling now
|
||||
self.track: dict[str, _Track] = {}
|
||||
self.events: list[dict] = [] # overrides seen (the executor reports them)
|
||||
|
||||
def min_switch_for(self, c) -> float:
|
||||
"""Anti-cycling time for this control: the mapping's
|
||||
params.min_switch_s if set; else the guard's min_switch_s for kinds
|
||||
whose equipment wears from short cycles (heating, cooling: their
|
||||
default is > 0), and 0 for batteries, EV chargers and covers."""
|
||||
if "min_switch_s" in (c.params or {}):
|
||||
return float(c.params["min_switch_s"])
|
||||
from .controls import PARAMS
|
||||
return float(self.min_switch) if PARAMS.get(c.kind, {}).get("min_switch_s", 0) > 0 else 0.0
|
||||
|
||||
def _t(self, cid) -> _Track:
|
||||
return self.track.setdefault(cid, _Track())
|
||||
|
||||
def bounds(self, c, q):
|
||||
return c.bounds(q, self.extra_limits.get(c.id))
|
||||
|
||||
def check(self, a: Action) -> tuple[bool, str]:
|
||||
now = self.clock()
|
||||
c = self.controls.get(a.control)
|
||||
if c is None:
|
||||
return False, "no such control"
|
||||
if self.policy is not None:
|
||||
why = self.policy.refuses(a, c)
|
||||
if why:
|
||||
return False, why
|
||||
if self.switchover is not None and not self.switchover.active(c):
|
||||
return False, f"{c.kind} is not active now (switchover: the thermostat's other control is)"
|
||||
if self.mode() != "auto":
|
||||
return False, f"mode {self.mode()}: the agent does not act"
|
||||
if not self.consent.control:
|
||||
return False, "the owner has not allowed control (site consent)"
|
||||
if not c.consent:
|
||||
return False, "no consent for this control"
|
||||
if c.writable().get(a.channel) != a.entity:
|
||||
return False, f"{a.entity} is not this control's {a.channel}"
|
||||
if a.service not in SERVICES.get(a.domain, ()) or a.entity.split(".", 1)[0] != a.domain:
|
||||
return False, f"{a.domain}.{a.service} is not allowed for {a.entity}"
|
||||
if a.quantity:
|
||||
b = self.bounds(c, a.quantity)
|
||||
try:
|
||||
v = float(a.value)
|
||||
except (TypeError, ValueError):
|
||||
return False, f"{a.value!r} is not a number"
|
||||
if not b.holds(v):
|
||||
return False, (f"{v:g} outside {b.lo:g}..{b.hi:g} {a.quantity} "
|
||||
f"(floor by {b.lo_by}, limit by {b.hi_by})")
|
||||
tr = self._t(c.id)
|
||||
urgent = a.level == "emergency"
|
||||
if now < tr.override_until and a.level not in ("binding", "emergency"):
|
||||
return False, f"the owner changed {tr.override_entity} by hand: hands off until {_hhmm(tr.override_until)}"
|
||||
min_switch = self.min_switch_for(c)
|
||||
if not urgent and min_switch > 0 and a.quantity == "" and a.channel in tr.switched:
|
||||
when, last = tr.switched[a.channel]
|
||||
if last != a.value and now - when < min_switch:
|
||||
return False, f"switched {last} {int(now - when)} s ago (minimum {min_switch:g} s)"
|
||||
tr.times = [t for t in tr.times if now - t < 3600]
|
||||
if not urgent and c.kind == "cover" and now - tr.moved < float(c.p("min_move_s")):
|
||||
return False, (f"moved {int(now - tr.moved)} s ago (at most once in {float(c.p('min_move_s')):g} s)")
|
||||
if not urgent and len(tr.times) >= self.max_rate:
|
||||
return False, f"{len(tr.times)} actions in the last hour (at most {self.max_rate})"
|
||||
return True, ""
|
||||
|
||||
def done(self, a: Action):
|
||||
"""An action was carried out: count it, remember what was set."""
|
||||
now = self.clock()
|
||||
tr = self._t(a.control)
|
||||
tr.times.append(now)
|
||||
tr.commanded[a.entity] = (now, a.value)
|
||||
if a.domain == "cover":
|
||||
tr.moved = now
|
||||
if a.quantity == "":
|
||||
prev = tr.switched.get(a.channel)
|
||||
if prev is None or prev[1] != a.value:
|
||||
tr.switched[a.channel] = (now, a.value)
|
||||
|
||||
def expect(self, control_id: str, entity: str, value):
|
||||
"""The agent wants this value and the device already has it (no
|
||||
action needed): a later change by hand counts as an override, as if
|
||||
the agent had set it (not counted as an action)."""
|
||||
tr = self._t(control_id)
|
||||
if entity not in tr.commanded:
|
||||
tr.commanded[entity] = (self.clock() - self.settle, value)
|
||||
|
||||
def observe(self, control_id: str, entity: str, value, now: float | None = None):
|
||||
"""A state change of a control's entity: if it differs from what the
|
||||
agent set, and not right after the agent set it, the owner changed
|
||||
it by hand."""
|
||||
now = self.clock() if now is None else now
|
||||
tr = self._t(control_id)
|
||||
cmd = tr.commanded.get(entity)
|
||||
if cmd is None:
|
||||
return
|
||||
when, want = cmd
|
||||
c = self.controls.get(control_id)
|
||||
cover = c is not None and c.kind == "cover"
|
||||
if now - when < self.settle or _same(value, want, 3.0 if cover else 0.26):
|
||||
return
|
||||
# a shade the owner moved: off it for its own pause (params.override_hold_s)
|
||||
tr.override_until = now + (float(c.p("override_hold_s")) if cover else self.hold)
|
||||
tr.override_entity = entity
|
||||
tr.commanded.pop(entity, None)
|
||||
self.events.append({"control": control_id, "entity": entity, "value": value, "agent_set": want,
|
||||
"until": int(tr.override_until), "at": int(now)})
|
||||
|
||||
def overridden(self, control_id: str) -> bool:
|
||||
return self.clock() < self._t(control_id).override_until
|
||||
|
||||
|
||||
def _same(a, b, tol: float = 0.26) -> bool:
|
||||
try:
|
||||
return abs(float(a) - float(b)) < tol
|
||||
except (TypeError, ValueError):
|
||||
return str(a) == str(b)
|
||||
|
||||
|
||||
def _hhmm(t: float) -> str:
|
||||
return time.strftime("%H:%M UTC", time.gmtime(t))
|
||||
@@ -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)
|
||||
@@ -0,0 +1,116 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The language of the add-on's own page (joinpage.py): English or German,
|
||||
from the browser's Accept-Language (HA's ingress forwards it), else
|
||||
English. Home Assistant's own language (names.py) is another setting.
|
||||
|
||||
The pattern of the box's panel (cantabile_i18n.py there; the edge package
|
||||
is separate, so its own copy): the texts stay English in the code,
|
||||
T("Join"), T("Unit {unit}", unit=x) with str.format values, TN("{n} day",
|
||||
"{n} days", n) for plurals, M("...") in tables built at import (T() where
|
||||
shown). German is cantabile_edge/i18n_de.py, MESSAGES {English: German}; a
|
||||
plural's key is the tuple (one, other). A text missing there shows in
|
||||
English; tests/test_joinpage_i18n.py finds every text of the page missing.
|
||||
|
||||
The language is a context variable: each connection of the page is its own
|
||||
asyncio task, and asyncio.to_thread carries the context into the thread.
|
||||
"""
|
||||
import contextvars
|
||||
import datetime
|
||||
import importlib
|
||||
|
||||
LANGUAGES = {"en": "English", "de": "Deutsch"}
|
||||
DEFAULT = "en"
|
||||
PLURAL = {"en": lambda n: 0 if n == 1 else 1, "de": lambda n: 0 if n == 1 else 1}
|
||||
MONTHS = {
|
||||
"en": ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"),
|
||||
"de": ("Jan.", "Feb.", "März", "Apr.", "Mai", "Juni", "Juli", "Aug.", "Sept.", "Okt.", "Nov.", "Dez."),
|
||||
}
|
||||
DECIMAL = {"en": ".", "de": ","}
|
||||
|
||||
_lang = contextvars.ContextVar("cantabile_edge_lang", default=DEFAULT)
|
||||
_catalogues = {}
|
||||
|
||||
|
||||
def use(lang):
|
||||
"""The language of what this request renders (its context)."""
|
||||
return _lang.set(lang if lang in LANGUAGES else DEFAULT)
|
||||
|
||||
|
||||
def current():
|
||||
return _lang.get()
|
||||
|
||||
|
||||
def from_accept(header):
|
||||
"""The best of ours in an Accept-Language header ("de-DE,de;q=0.9,en;q=0.8"), or None."""
|
||||
best, best_q = None, 0.0
|
||||
for i, part in enumerate((header or "").split(",")):
|
||||
tag, _, params = part.strip().partition(";")
|
||||
code = tag.strip().lower().split("-")[0]
|
||||
q = 1.0
|
||||
for p in params.split(";"):
|
||||
k, _, v = p.strip().partition("=")
|
||||
if k.strip() == "q":
|
||||
try:
|
||||
q = float(v)
|
||||
except ValueError:
|
||||
q = 0.0
|
||||
q -= i * 1e-6 # equal weights: the first wins
|
||||
if code in LANGUAGES and q > best_q:
|
||||
best, best_q = code, q
|
||||
return best
|
||||
|
||||
|
||||
def catalogue(lang):
|
||||
if lang == DEFAULT:
|
||||
return {}
|
||||
if lang not in _catalogues:
|
||||
try:
|
||||
_catalogues[lang] = importlib.import_module(f"{__package__}.i18n_{lang}").MESSAGES
|
||||
except ImportError:
|
||||
_catalogues[lang] = {}
|
||||
return _catalogues[lang]
|
||||
|
||||
|
||||
def T(text, **values):
|
||||
"""text in the current language; {name}s filled from values."""
|
||||
s = catalogue(current()).get(text, text)
|
||||
return s.format(**values) if values else s
|
||||
|
||||
|
||||
def M(text):
|
||||
"""A text marked for the catalogue but kept English here (tables built at
|
||||
import); T(table[k]) translates it where it is shown."""
|
||||
return text
|
||||
|
||||
|
||||
def TN(one, other, n, **values):
|
||||
"""The plural for n ({n} is filled too)."""
|
||||
lang = current()
|
||||
forms = catalogue(lang).get((one, other)) or (one, other)
|
||||
s = forms[min(PLURAL.get(lang, PLURAL[DEFAULT])(n), len(forms) - 1)]
|
||||
return s.format(n=n, **values)
|
||||
|
||||
|
||||
def date(d, year=True):
|
||||
"""29 Oct 2026 / 29. Okt. 2026 (a date or datetime)."""
|
||||
lang = current()
|
||||
m = MONTHS.get(lang, MONTHS[DEFAULT])[d.month - 1]
|
||||
day = f"{d.day}." if lang == "de" else f"{d.day}"
|
||||
return f"{day} {m} {d.year}" if year else f"{day} {m}"
|
||||
|
||||
|
||||
def iso_date(s):
|
||||
"""An ISO time from Cantabile ("2026-10-29T10:00:00Z") as a date: kept as
|
||||
2026-10-29 in English, 29. Okt. 2026 in German."""
|
||||
s = (s or "")[:10]
|
||||
if current() == DEFAULT:
|
||||
return s
|
||||
try:
|
||||
return date(datetime.date.fromisoformat(s))
|
||||
except ValueError:
|
||||
return s
|
||||
|
||||
|
||||
def number(v):
|
||||
"""A short number as :g writes it, with the language's decimal mark (1.5 / 1,5)."""
|
||||
return f"{v:g}".replace(".", DECIMAL.get(current(), "."))
|
||||
@@ -0,0 +1,350 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""German for the add-on's pages (joinpage.py, devpage.py): {English: German}; a plural's
|
||||
key is (one, other), its value (one, other) in German. Formal "Sie"; the
|
||||
words of the console's German manual (Beitrittscode, Betreiber, Gemeinschaft,
|
||||
Einwilligung, Kündigungsfrist, Zählpunkt, austreten)."""
|
||||
|
||||
MESSAGES = {
|
||||
# the page
|
||||
"Cantabile: building or community": "Cantabile: Gebäude oder Gemeinschaft",
|
||||
"Building or community": "Gebäude oder Gemeinschaft",
|
||||
"Open this page from Home Assistant.": "Öffnen Sie diese Seite über Home Assistant.",
|
||||
"Not found": "Nicht gefunden",
|
||||
"Cantabile could not be reached ({error}); this is what it said last.":
|
||||
"Cantabile war nicht erreichbar ({error}); angezeigt wird der zuletzt bekannte Stand.",
|
||||
"Cantabile could not be reached ({error}).": "Cantabile war nicht erreichbar ({error}).",
|
||||
"given": "erteilt",
|
||||
"not given": "nicht erteilt",
|
||||
# a membership
|
||||
"Your flat is a member of this building (unit <b>{unit}</b>, since {since}).":
|
||||
"Ihre Wohnung ist Mitglied dieses Gebäudes (Einheit <b>{unit}</b>, seit {since}).",
|
||||
"The building's operator ended your membership: it ends on {date}.":
|
||||
"Der Betreiber des Gebäudes hat Ihre Mitgliedschaft beendet: Sie endet am {date}.",
|
||||
"The building's rules": "Regeln des Gebäudes",
|
||||
"Your consent for the building's operator: {state}.": "Ihre Einwilligung für den Betreiber des Gebäudes: {state}.",
|
||||
"Leave this building. Its requests to your home end now; to join again you need a new code from the operator.":
|
||||
"Aus diesem Gebäude austreten. Die Anfragen des Gebäudes an Ihr Zuhause enden sofort; für einen erneuten Beitritt brauchen "
|
||||
"Sie einen neuen Code vom Betreiber.",
|
||||
"Leave the building": "Aus dem Gebäude austreten",
|
||||
"Your home is a member of the energy community <b>{name}</b> (run by {operator}, since {since}).":
|
||||
"Ihr Zuhause ist Mitglied der Energiegemeinschaft <b>{name}</b> (betrieben von {operator}, seit {since}).",
|
||||
"Your home is a member of the energy community <b>{name}</b> (run by {operator}).":
|
||||
"Ihr Zuhause ist Mitglied der Energiegemeinschaft <b>{name}</b> (betrieben von {operator}).",
|
||||
"The community's operator ended your membership: it ends on {date}.":
|
||||
"Der Betreiber der Gemeinschaft hat Ihre Mitgliedschaft beendet: Sie endet am {date}.",
|
||||
"The community's rules": "Regeln der Gemeinschaft",
|
||||
"Your consent for the community's operator: {state}.": "Ihre Einwilligung für den Betreiber der Gemeinschaft: {state}.",
|
||||
"Leave this community. Its requests to your home end now; to join again you need a new code or its operator's yes.":
|
||||
"Aus dieser Gemeinschaft austreten. Die Anfragen der Gemeinschaft an Ihr Zuhause enden sofort; für einen erneuten Beitritt "
|
||||
"brauchen Sie einen neuen Code oder die Zusage ihres Betreibers.",
|
||||
"Leave the community": "Aus der Gemeinschaft austreten",
|
||||
"Your membership of {name} ended on {date}: {reason}.": "Ihre Mitgliedschaft bei {name} endete am {date}: {reason}.",
|
||||
# requests
|
||||
"unit {unit}": "Einheit {unit}",
|
||||
"You asked to join {name}: waiting for the community's operator.":
|
||||
"Sie haben den Beitritt zu {name} angefragt: Die Antwort des Betreibers der Gemeinschaft steht noch aus.",
|
||||
"You asked to join {name}: waiting for the building's operator.":
|
||||
"Sie haben den Beitritt zu {name} angefragt: Die Antwort des Betreibers des Gebäudes steht noch aus.",
|
||||
"Withdraw the request": "Anfrage zurückziehen",
|
||||
"{name} declined your request: {reason}.": "{name} hat Ihre Anfrage abgelehnt: {reason}.",
|
||||
"{name} declined your request.": "{name} hat Ihre Anfrage abgelehnt.",
|
||||
# joining
|
||||
"Join": "Beitreten",
|
||||
"Join {name}": "{name} beitreten",
|
||||
"Its rules": "Regeln",
|
||||
"Unit <b>{unit}</b> of this building:": "Einheit <b>{unit}</b> in diesem Gebäude:",
|
||||
"This energy community (energy shared between buildings and homes):":
|
||||
"Diese Energiegemeinschaft (Energie, die zwischen Gebäuden und Häusern geteilt wird):",
|
||||
"Your meter point (on your meter or your electricity bill)": "Ihr Zählpunkt (auf Ihrem Zähler oder Ihrer Stromrechnung)",
|
||||
"Join with a code": "Mit einem Code beitreten",
|
||||
"A building's operator gives each flat a code; an energy community's operator gives each home a code (or a QR code: "
|
||||
"open its link here, or type the code).":
|
||||
"Der Betreiber eines Gebäudes gibt jeder Wohnung einen Code, der Betreiber einer Energiegemeinschaft jedem "
|
||||
"Zuhause (oder einen QR-Code: Öffnen Sie seinen Link hier oder geben Sie den Code ein).",
|
||||
"Join code": "Beitrittscode",
|
||||
"Continue": "Weiter",
|
||||
"No building or energy community using Cantabile was found near your home.":
|
||||
"In der Nähe Ihres Zuhauses wurde kein Gebäude und keine Energiegemeinschaft mit Cantabile gefunden.",
|
||||
"Your flat (as on your door or contract)": "Ihre Wohnung (wie an Ihrer Tür oder im Vertrag)",
|
||||
"An energy community.": "Eine Energiegemeinschaft.",
|
||||
"A note for the operator (optional)": "Eine Nachricht an den Betreiber (optional)",
|
||||
"Ask to join": "Beitritt anfragen",
|
||||
"No code?": "Kein Code?",
|
||||
"Look for buildings and energy communities using Cantabile near your home (Home Assistant's location goes to "
|
||||
"Cantabile only when you press this).":
|
||||
"Suchen Sie Gebäude und Energiegemeinschaften mit Cantabile in der Nähe Ihres Zuhauses (der Standort aus Home "
|
||||
"Assistant geht erst an Cantabile, wenn Sie hier klicken).",
|
||||
"Near my home": "In meiner Nähe",
|
||||
"{m} m away": "{m} m entfernt",
|
||||
"Run by {operator}": "Betrieben von {operator}",
|
||||
"Share my flat's energy data with the building's operator (per flat, every 15 minutes, if the building's rules ask "
|
||||
"for it).":
|
||||
"Die Energiedaten meiner Wohnung mit dem Betreiber des Gebäudes teilen (je Wohnung, alle 15 Minuten, wenn die "
|
||||
"Regeln des Gebäudes es vorsehen).",
|
||||
"Share my home's energy data with the community's operator (every 15 minutes, if the community's rules ask for it).":
|
||||
"Die Energiedaten meines Zuhauses mit dem Betreiber der Gemeinschaft teilen (alle 15 Minuten, wenn die Regeln "
|
||||
"der Gemeinschaft es vorsehen).",
|
||||
# answers
|
||||
"A join code has 12 letters and digits: XXXX-XXXX-XXXX.":
|
||||
"Ein Beitrittscode besteht aus 12 Buchstaben und Ziffern: XXXX-XXXX-XXXX.",
|
||||
"Welcome: your home is a member of the community now.": "Willkommen: Ihr Zuhause ist jetzt Mitglied der Gemeinschaft.",
|
||||
"Welcome: your flat is a member now.": "Willkommen: Ihre Wohnung ist jetzt Mitglied.",
|
||||
"Home Assistant has no home location (Settings, System, General).":
|
||||
"In Home Assistant ist kein Standort für Ihr Zuhause eingetragen (Einstellungen, System, Allgemein).",
|
||||
"Which building or community?": "Welches Gebäude oder welche Gemeinschaft?",
|
||||
"Asked. The community's operator decides; this page shows the answer.":
|
||||
"Angefragt. Der Betreiber der Gemeinschaft entscheidet; diese Seite zeigt die Antwort.",
|
||||
"Asked. The building's operator decides; this page shows the answer.":
|
||||
"Angefragt. Der Betreiber des Gebäudes entscheidet; diese Seite zeigt die Antwort.",
|
||||
"Your request was withdrawn.": "Ihre Anfrage wurde zurückgezogen.",
|
||||
"Tick the box to leave.": "Setzen Sie das Häkchen, um auszutreten.",
|
||||
"You left.": "Sie sind ausgetreten.",
|
||||
# errors
|
||||
"this Home Assistant is not connected to Cantabile yet": "dieses Home Assistant ist noch nicht mit Cantabile verbunden",
|
||||
"cannot sign: {error}": "Signieren nicht möglich: {error}",
|
||||
"no key yet": "noch kein Schlüssel",
|
||||
"Cantabile answered {code}": "Cantabile antwortete mit {code}",
|
||||
"Cantabile cannot be reached: {error}": "Cantabile ist nicht erreichbar: {error}",
|
||||
# the rules
|
||||
"The building sees your flat's energy use every 15 minutes, if you allow it below.":
|
||||
"Das Gebäude sieht den Energieverbrauch Ihrer Wohnung alle 15 Minuten, wenn Sie es unten erlauben.",
|
||||
"The building sees your energy use only summed up with the other flats.":
|
||||
"Das Gebäude sieht Ihren Energieverbrauch nur zusammengefasst mit dem der anderen Wohnungen.",
|
||||
"Your 15-minute consumption is used for the building's bills (for example shared solar power), never shown to the "
|
||||
"operator as a time series.":
|
||||
"Ihr 15-Minuten-Verbrauch wird für die Abrechnungen des Gebäudes verwendet (zum Beispiel für gemeinsamen "
|
||||
"Solarstrom) und dem Betreiber nie als Zeitreihe gezeigt.",
|
||||
"Cantabile makes no bills for this building.": "Cantabile erstellt für dieses Gebäude keine Abrechnungen.",
|
||||
"The community sees your home's energy use every 15 minutes, if you allow it below.":
|
||||
"Die Gemeinschaft sieht den Energieverbrauch Ihres Zuhauses alle 15 Minuten, wenn Sie es unten erlauben.",
|
||||
"The community sees your energy use only summed up with its other members.":
|
||||
"Die Gemeinschaft sieht Ihren Energieverbrauch nur zusammengefasst mit dem ihrer anderen Mitglieder.",
|
||||
"Your 15-minute values are used to settle the energy shared in the community, never shown to its operator as a "
|
||||
"time series.":
|
||||
"Ihre 15-Minuten-Werte werden zur Abrechnung der in der Gemeinschaft geteilten Energie verwendet und ihrem "
|
||||
"Betreiber nie als Zeitreihe gezeigt.",
|
||||
"Cantabile settles nothing for this community.": "Cantabile rechnet für diese Gemeinschaft nichts ab.",
|
||||
"a limit on what your home draws from the grid": "eine Begrenzung dessen, was Ihr Zuhause aus dem Netz bezieht",
|
||||
"requests to move some of your energy use to another time":
|
||||
"Anfragen, einen Teil Ihres Energieverbrauchs auf eine andere Zeit zu verschieben",
|
||||
"a cap on your heating's setpoints": "eine Obergrenze für die Solltemperaturen Ihrer Heizung",
|
||||
"at least {v} {unit}": "mindestens {v} {unit}",
|
||||
"at most {v} {unit}": "höchstens {v} {unit}",
|
||||
"The building may send {controls}.": "Das Gebäude darf Folgendes senden: {controls}.",
|
||||
"The community may send {controls}.": "Die Gemeinschaft darf Folgendes senden: {controls}.",
|
||||
"You can always override them.": "Sie können sie jederzeit übersteuern.",
|
||||
"They apply until they end; your comfort settings always win.":
|
||||
"Sie gelten bis zu ihrem Ende; Ihre Komforteinstellungen haben immer Vorrang.",
|
||||
"The building sends your home no requests.": "Das Gebäude sendet Ihrem Zuhause keine Anfragen.",
|
||||
"The community sends your home no requests.": "Die Gemeinschaft sendet Ihrem Zuhause keine Anfragen.",
|
||||
("Notice when the operator ends your membership or closes the building: {days} day.",
|
||||
"Notice when the operator ends your membership or closes the building: {days} days."):
|
||||
("Kündigungsfrist, wenn der Betreiber Ihre Mitgliedschaft beendet oder das Gebäude schließt: {days} Tag.",
|
||||
"Kündigungsfrist, wenn der Betreiber Ihre Mitgliedschaft beendet oder das Gebäude schließt: {days} Tage."),
|
||||
("Notice when the operator ends your membership or closes the community: {days} day.",
|
||||
"Notice when the operator ends your membership or closes the community: {days} days."):
|
||||
("Kündigungsfrist, wenn der Betreiber Ihre Mitgliedschaft beendet oder die Gemeinschaft schließt: {days} Tag.",
|
||||
"Kündigungsfrist, wenn der Betreiber Ihre Mitgliedschaft beendet oder die Gemeinschaft schließt: {days} Tage."),
|
||||
"Shared solar power: {pv} ct/kWh; grid power when no tariff covers you: {grid} ct/kWh.":
|
||||
"Gemeinsamer Solarstrom: {pv} ct/kWh; Netzstrom, wenn kein Tarif für Sie gilt: {grid} ct/kWh.",
|
||||
# a community's terms
|
||||
"the day-ahead price (around {ct} ct/kWh)": "dem Day-Ahead-Börsenpreis (etwa {ct} ct/kWh)",
|
||||
"Energy shared in the community: {delta} ct/kWh below {reference}; a surplus nobody in it takes goes to the grid at "
|
||||
"{feed_in} ct/kWh.":
|
||||
"In der Gemeinschaft geteilte Energie: {delta} ct/kWh unter {reference}; ein Überschuss, den niemand in der "
|
||||
"Gemeinschaft abnimmt, wird für {feed_in} ct/kWh ins Netz eingespeist.",
|
||||
"Energy shared in the community: {delta} ct/kWh above {reference}; a surplus nobody in it takes goes to the grid at "
|
||||
"{feed_in} ct/kWh.":
|
||||
"In der Gemeinschaft geteilte Energie: {delta} ct/kWh über {reference}; ein Überschuss, den niemand in der "
|
||||
"Gemeinschaft abnimmt, wird für {feed_in} ct/kWh ins Netz eingespeist.",
|
||||
"{v} kW guaranteed": "{v} kW garantiert",
|
||||
"at least {v} kWh": "mindestens {v} kWh",
|
||||
"at most {v} kW": "höchstens {v} kW",
|
||||
"{v} ct/kWh for a deviation": "{v} ct/kWh bei einer Abweichung",
|
||||
"{v} ct/kWh for overriding a request": "{v} ct/kWh für das Übersteuern einer Anfrage",
|
||||
"Per quarter-hour: {terms}, summed per {period} (Cantabile records these; it does not apply or bill them yet).":
|
||||
"Je Viertelstunde: {terms}, summiert je {period} (Cantabile erfasst diese Werte, wendet sie aber noch nicht an "
|
||||
"und rechnet sie noch nicht ab).",
|
||||
"month": "Monat",
|
||||
"quarter": "Quartal",
|
||||
"year": "Jahr",
|
||||
# the restore offer (a reinstall recognised)
|
||||
"Its name": "Sein Name",
|
||||
"Its tags": "Seine Tags",
|
||||
"Its building": "Sein Gebäude",
|
||||
"Its energy communities": "Seine Energiegemeinschaften",
|
||||
"Its tariff": "Sein Tarif",
|
||||
"Its device protection": "Sein Geräteschutz",
|
||||
"Its devices' details": "Die Angaben zu seinen Geräten",
|
||||
"Your building's operator receives this home's energy data every 15 minutes":
|
||||
"Der Betreiber Ihres Gebäudes erhält die Energiedaten dieses Zuhauses alle 15 Minuten",
|
||||
"Your energy community's operator receives this home's energy data every 15 minutes":
|
||||
"Der Betreiber Ihrer Energiegemeinschaft erhält die Energiedaten dieses Zuhauses alle 15 Minuten",
|
||||
"of this home": "dieses Zuhauses",
|
||||
"Kept by Cantabile already:": "Bereits bei Cantabile gespeichert:",
|
||||
"Your earlier consents, as you gave them. They count only with your yes below.":
|
||||
"Ihre früheren Einwilligungen, so wie Sie sie erteilt hatten. Sie gelten nur mit Ihrem Ja unten.",
|
||||
"Yes, I give these consents again.": "Ja, ich erteile diese Einwilligungen erneut.",
|
||||
"Cantabile keeps no backup of your home: which entities it may read, the devices and the add-on's options are set up again in Home Assistant.":
|
||||
"Cantabile speichert keine Sicherung Ihres Zuhauses: Welche Entitäten es lesen darf, die Geräte und die Optionen des Add-ons richten Sie in Home Assistant neu ein.",
|
||||
"This looks like your earlier Cantabile box {name}. Restore its settings?":
|
||||
"Das sieht nach Ihrer früheren Cantabile-Box {name} aus. Ihre Einstellungen wiederherstellen?",
|
||||
"Not now": "Jetzt nicht",
|
||||
"Restore what is ticked": "Ausgewähltes wiederherstellen",
|
||||
"consents given again": "Einwilligungen erneut erteilt",
|
||||
"Restored: {what}.": "Wiederhergestellt: {what}.",
|
||||
"Nothing restored.": "Nichts wiederhergestellt.",
|
||||
# the Devices page (devpage.py; the Hub panel's words where it has them)
|
||||
"Devices": "Geräte",
|
||||
"Cantabile: devices": "Cantabile: Geräte",
|
||||
"Home Assistant's devices that a Cantabile device profile knows. Use one with Cantabile to see it on Cantabile's "
|
||||
"dashboard and to let Cantabile read it once you have given your consent.":
|
||||
"Geräte aus Home Assistant, die ein Geräteprofil von Cantabile kennt. Nutzen Sie eines mit Cantabile, um es im "
|
||||
"Dashboard von Cantabile zu sehen und, sobald Sie eingewilligt haben, von Cantabile auslesen zu lassen.",
|
||||
"Used with Cantabile": "Mit Cantabile genutzt",
|
||||
"In Home Assistant, with a profile": "In Home Assistant, mit Profil",
|
||||
"No device in Home Assistant fits a Cantabile profile yet.":
|
||||
"Noch passt kein Gerät in Home Assistant zu einem Profil von Cantabile.",
|
||||
("{n} more in Home Assistant without a profile (not used by Cantabile)",
|
||||
"{n} more in Home Assistant without a profile (not used by Cantabile)"):
|
||||
("{n} weiteres Gerät in Home Assistant ohne Profil (von Cantabile nicht genutzt)",
|
||||
"{n} weitere Geräte in Home Assistant ohne Profil (von Cantabile nicht genutzt)"),
|
||||
"Home Assistant's devices could not be read: {error}": "Die Geräte von Home Assistant konnten nicht gelesen werden: {error}",
|
||||
"Use with Cantabile": "Mit Cantabile nutzen",
|
||||
"generic profile": "allgemeines Profil",
|
||||
"Checked on a device": "An einem Gerät geprüft",
|
||||
"From the maker's documentation, not yet checked on a device":
|
||||
"Aus der Dokumentation des Herstellers, noch nicht an einem Gerät geprüft",
|
||||
"Draft: check the values before you turn reading on": "Entwurf: Prüfen Sie die Werte, bevor Sie das Auslesen einschalten",
|
||||
"nothing": "nichts",
|
||||
"battery": "Batterie",
|
||||
"heating": "Heizen",
|
||||
"cooling": "Kühlen",
|
||||
"charging": "Laden",
|
||||
"blinds and curtains": "Jalousien und Vorhänge",
|
||||
"Not known": "Unbekannt",
|
||||
"North": "Norden",
|
||||
"North-east": "Nordosten",
|
||||
"East": "Osten",
|
||||
"South-east": "Südosten",
|
||||
"South": "Süden",
|
||||
"South-west": "Südwesten",
|
||||
"West": "Westen",
|
||||
"North-west": "Nordwesten",
|
||||
"No room": "Kein Raum",
|
||||
"Room": "Raum",
|
||||
"Room and window": "Raum und Fenster",
|
||||
"Cantabile moves it by the sun: in summer it closes it while the sun is on the window and the room is warm; in "
|
||||
"winter it opens it for the sun's warmth and closes it at night. Never between 22:00 and 07:00, and after you move "
|
||||
"it by hand it waits 4 hours.":
|
||||
"Cantabile bewegt sie nach der Sonne: im Sommer schließt es sie, solange die Sonne auf das Fenster scheint und "
|
||||
"der Raum warm ist; im Winter öffnet es sie für die Wärme der Sonne und schließt sie nachts. Nie zwischen 22:00 "
|
||||
"und 07:00 Uhr, und nachdem Sie sie von Hand bewegt haben, wartet es 4 Stunden.",
|
||||
"Room it shades": "Raum, den sie beschattet",
|
||||
"The window faces": "Das Fenster zeigt nach",
|
||||
"Without the window's direction Cantabile only closes it at night in winter.":
|
||||
"Ohne die Richtung des Fensters schließt Cantabile sie nur im Winter nachts.",
|
||||
"Indoor or outdoor": "Innen oder außen",
|
||||
"Indoor, in the room:": "Innen, im Raum:",
|
||||
"Outdoor: Cantabile's outside temperature": "Außen: die Außentemperatur für Cantabile",
|
||||
"An outdoor sensor counts before the weather service's temperature.":
|
||||
"Ein Außensensor geht der Temperatur des Wetterdienstes vor.",
|
||||
"Cantabile plans with this forecast: solar, heating, cooling and the shades.":
|
||||
"Cantabile plant mit dieser Vorhersage: Solarstrom, Heizen, Kühlen und die Beschattung.",
|
||||
"Not used for planning: Cantabile plans with one weather forecast, another one's.":
|
||||
"Nicht für die Planung genutzt: Cantabile plant mit einer Wettervorhersage, einer anderen.",
|
||||
"Plan with this forecast": "Mit dieser Vorhersage planen",
|
||||
"Allow Cantabile to move it": "Bewegen durch Cantabile erlauben",
|
||||
"A protected blind or curtain is not moved by Cantabile at all.":
|
||||
"Eine geschützte Jalousie oder ein geschützter Vorhang wird von Cantabile gar nicht bewegt.",
|
||||
"Cantabile would read: {values}.": "Cantabile würde auslesen: {values}.",
|
||||
"It could control: {controls}.": "Steuern könnte es: {controls}.",
|
||||
"Cantabile reads: {values}.": "Cantabile liest aus: {values}.",
|
||||
"It may control: {controls}.": "Steuern darf es: {controls}.",
|
||||
"Not found in Home Assistant: {entities}.": "In Home Assistant nicht gefunden: {entities}.",
|
||||
"Read by your own mapping already, so left out here: {values}.":
|
||||
"Schon von Ihrer eigenen Zuordnung ausgelesen, daher hier weggelassen: {values}.",
|
||||
"Another control writes to this device already, so Cantabile leaves out: {controls}.":
|
||||
"Eine andere Steuerung schreibt schon auf dieses Gerät, daher lässt Cantabile weg: {controls}.",
|
||||
"Assumed, not measured: {values}. This device does not report back (infrared): Cantabile shows what was last sent "
|
||||
"to it and never takes it as feedback.":
|
||||
"Angenommen, nicht gemessen: {values}. Dieses Gerät meldet nichts zurück (Infrarot): Cantabile zeigt, was zuletzt "
|
||||
"an es gesendet wurde, und wertet das nie als Rückmeldung.",
|
||||
"Proposed by Cantabile (not checked yet): {values}. Use it with Cantabile to confirm it as this profile sees it.":
|
||||
"Von Cantabile vorgeschlagen (noch nicht geprüft): {values}. Nutzen Sie es mit Cantabile, um es so zu bestätigen, "
|
||||
"wie dieses Profil es sieht.",
|
||||
"In your own mapping: {values}. Those stay as they are.": "In Ihrer eigenen Zuordnung: {values}. Diese bleiben, wie sie sind.",
|
||||
"Cantabile may read these values": "Cantabile darf diese Werte auslesen",
|
||||
"Save": "Speichern",
|
||||
"Saved.": "Gespeichert.",
|
||||
"Heating or cooling": "Heizen oder Kühlen",
|
||||
"Heating": "Heizen",
|
||||
"Cooling": "Kühlen",
|
||||
"By season (heating October to April, cooling May to September)":
|
||||
"Nach Jahreszeit (Heizen Oktober bis April, Kühlen Mai bis September)",
|
||||
"By outdoor temperature": "Nach Außentemperatur",
|
||||
"This thermostat can heat and cool. Cantabile uses one at a time; the other is never touched.":
|
||||
"Dieses Thermostat kann heizen und kühlen. Cantabile nutzt immer nur eines; das andere bleibt unberührt.",
|
||||
"By outdoor temperature: heat below (°C)": "Nach Außentemperatur: heizen unter (°C)",
|
||||
"cool above (°C)": "kühlen über (°C)",
|
||||
"Between the two it stays as it is, so it does not switch back and forth on a mild day.":
|
||||
"Dazwischen bleibt es, wie es ist, damit es an einem milden Tag nicht hin und her schaltet.",
|
||||
"Protection": "Schutz",
|
||||
"Protected: Cantabile never switches it off or cuts it; you still can, by hand. Sealed: only its custodian can "
|
||||
"change it.":
|
||||
"Geschützt: Cantabile schaltet es nie ab und drosselt es nie; Sie selbst können es weiterhin von Hand. "
|
||||
"Versiegelt: Nur sein Verwalter kann das ändern.",
|
||||
"The whole device": "Das ganze Gerät",
|
||||
"Control {name}": "Steuerung {name}",
|
||||
"Sealed": "Versiegelt",
|
||||
"only {who} can change it": "nur {who} kann es ändern",
|
||||
"protected": "geschützt",
|
||||
"not protected": "nicht geschützt",
|
||||
"Allow switching off": "Abschalten erlauben",
|
||||
"Protect": "Schützen",
|
||||
"its custodian": "sein Verwalter",
|
||||
"the building's operator": "der Betreiber des Gebäudes",
|
||||
"the grid operator": "der Netzbetreiber",
|
||||
"the metering operator": "der Messstellenbetreiber",
|
||||
"the energy community's operator": "der Betreiber der Energiegemeinschaft",
|
||||
"Remove": "Entfernen",
|
||||
"Cantabile stops using it. Home Assistant keeps the device as it is.":
|
||||
"Cantabile nutzt es nicht mehr. Home Assistant behält das Gerät, wie es ist.",
|
||||
"Stop using it with Cantabile": "Nicht mehr mit Cantabile nutzen",
|
||||
"Cantabile no longer uses it.": "Cantabile nutzt es nicht mehr.",
|
||||
"Cantabile could not ask Home Assistant who you are ({error}).":
|
||||
"Cantabile konnte Home Assistant nicht fragen, wer Sie sind ({error}).",
|
||||
"Home Assistant is not connected yet; try again in a moment.":
|
||||
"Home Assistant ist noch nicht verbunden; versuchen Sie es gleich noch einmal.",
|
||||
"Home Assistant has no such device.": "Dieses Gerät gibt es in Home Assistant nicht.",
|
||||
"{profile}: this profile does not know the device's integration.":
|
||||
"{profile}: Dieses Profil kennt die Integration des Geräts nicht.",
|
||||
"No such profile.": "Dieses Profil gibt es nicht.",
|
||||
"No such device.": "Dieses Gerät gibt es nicht.",
|
||||
"This device is used with Cantabile already.": "Dieses Gerät wird schon mit Cantabile genutzt.",
|
||||
"Home Assistant shows none of the values this profile knows, or your mapping has them all already.":
|
||||
"Home Assistant zeigt keinen der Werte, die dieses Profil kennt, oder Ihre Zuordnung hat sie alle schon.",
|
||||
"Sealed: only {who} can remove it.": "Versiegelt: Nur {who} kann es entfernen.",
|
||||
"Sealed: only {who} can change its control.": "Versiegelt: Nur {who} kann seine Steuerung ändern.",
|
||||
"The device's mapping is gone; use it with Cantabile again.":
|
||||
"Die Zuordnung des Geräts fehlt; nutzen Sie es erneut mit Cantabile.",
|
||||
"Reading and control are off. To switch them on, first give your consent in the add-on's configuration (Settings, "
|
||||
"Add-ons, Cantabile Edge Agent, Configuration).":
|
||||
"Auslesen und Steuern sind aus. Um sie einzuschalten, geben Sie zuerst Ihre Einwilligung in der Konfiguration "
|
||||
"des Add-ons (Einstellungen, Add-ons, Cantabile Edge Agent, Konfiguration).",
|
||||
"First give your consent in the add-on's configuration (Settings, Add-ons, Cantabile Edge Agent, Configuration).":
|
||||
"Geben Sie zuerst Ihre Einwilligung in der Konfiguration des Add-ons (Einstellungen, Add-ons, Cantabile Edge "
|
||||
"Agent, Konfiguration).",
|
||||
"Cantabile may control it ({controls}), within your limits":
|
||||
"Cantabile darf es steuern ({controls}), innerhalb Ihrer Grenzen",
|
||||
"Control also needs your consent to control devices in the add-on's configuration.":
|
||||
"Zum Steuern braucht es außerdem Ihre Einwilligung zum Steuern von Geräten in der Konfiguration des Add-ons.",
|
||||
"Saved. Cantabile starts again to apply it (a few seconds).":
|
||||
"Gespeichert. Cantabile startet neu, um es zu übernehmen (einige Sekunden).",
|
||||
"{name} is used with Cantabile now. It is on Cantabile's dashboard; reading and control are off until you switch "
|
||||
"them on below.":
|
||||
"{name} wird jetzt mit Cantabile genutzt. Es steht im Dashboard von Cantabile; Auslesen und Steuern sind aus, "
|
||||
"bis Sie sie unten einschalten.",
|
||||
"Only an administrator of Home Assistant can use this page.":
|
||||
"Nur ein Administrator von Home Assistant kann diese Seite nutzen.",
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Inputs for the optimiser: the latest states of the controls' and the
|
||||
inputs' entities (presence, temperatures, humidity, outside temperature,
|
||||
sun, weather), a short local history of load and PV (the fallback when no
|
||||
model bundle says), and the 15-minute model state for the horizon.
|
||||
|
||||
None of this leaves the site; only the plan does (controller.py).
|
||||
|
||||
Placeholders (quality is not a goal yet):
|
||||
- occupancy beyond the next hour: the presence now for one hour, then
|
||||
06:00-22:00 local as "occupied" (a learned schedule comes later);
|
||||
- sun: the PV forecast scaled to its peak, else the sun's elevation.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
STEP_S = 900
|
||||
STEPS = 192 # 48 h
|
||||
HISTORY_S = 3 * 86400
|
||||
|
||||
|
||||
def number(v) -> float | None:
|
||||
try:
|
||||
x = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return x if x == x and abs(x) != math.inf else None
|
||||
|
||||
|
||||
class Collector:
|
||||
"""States of the entities the agent watches, in HA's compact
|
||||
subscribe_entities form. Observers (the guard) see every change."""
|
||||
|
||||
def __init__(self):
|
||||
self.states: dict[str, dict] = {}
|
||||
self.observers = []
|
||||
|
||||
def on_entities(self, ev: dict, now: float | None = None):
|
||||
now = time.time() if now is None else now
|
||||
for eid, s in (ev.get("a") or {}).items():
|
||||
self.states[eid] = {"s": s.get("s"), "a": dict(s.get("a") or {}), "t": s.get("lc") or now}
|
||||
for eid, c in (ev.get("c") or {}).items():
|
||||
cur = self.states.setdefault(eid, {"s": None, "a": {}, "t": now})
|
||||
plus, minus = c.get("+") or {}, c.get("-") or {}
|
||||
if "s" in plus:
|
||||
cur["s"] = plus["s"]
|
||||
cur["a"].update(plus.get("a") or {})
|
||||
for k in minus.get("a") or []:
|
||||
cur["a"].pop(k, None)
|
||||
cur["t"] = plus.get("lc") or plus.get("lu") or now
|
||||
for obs in self.observers:
|
||||
obs(eid, cur, now)
|
||||
|
||||
def state(self, eid: str):
|
||||
return (self.states.get(eid) or {}).get("s")
|
||||
|
||||
def attr(self, eid: str, name: str):
|
||||
return ((self.states.get(eid) or {}).get("a") or {}).get(name)
|
||||
|
||||
def value(self, eid: str) -> float | None:
|
||||
return number(self.state(eid)) if eid else None
|
||||
|
||||
def total(self, eids: str | list) -> float | None:
|
||||
"""One entity's value, or the sum of several (parts: pv.1.power, ...);
|
||||
None while any of them has none."""
|
||||
if isinstance(eids, str):
|
||||
return self.value(eids)
|
||||
vals = [self.value(e) for e in eids or []]
|
||||
return None if not vals or None in vals else sum(vals)
|
||||
|
||||
def age(self, eid: str, now: float) -> float:
|
||||
st = self.states.get(eid)
|
||||
return now - float(st["t"]) if st and st.get("t") else math.inf
|
||||
|
||||
|
||||
class History:
|
||||
"""Quarter-hour means of load and PV (W) for the last 3 days, kept on
|
||||
disk, for "the same quarter hour yesterday"."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self.path = path
|
||||
self.slots: dict[str, dict[int, list[float]]] = {"load_w": {}, "pv_w": {}}
|
||||
try:
|
||||
with open(path) as f:
|
||||
raw = json.load(f)
|
||||
self.slots = {k: {int(t): v for t, v in raw.get(k, {}).items()} for k in self.slots}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
def add(self, name: str, value: float | None, now: float):
|
||||
if value is None:
|
||||
return
|
||||
slot = int(now // STEP_S * STEP_S)
|
||||
s, n = self.slots[name].get(slot, [0.0, 0])
|
||||
self.slots[name][slot] = [s + value, n + 1]
|
||||
|
||||
def mean(self, name: str, slot: int) -> float | None:
|
||||
s = self.slots[name].get(slot)
|
||||
return s[0] / s[1] if s and s[1] else None
|
||||
|
||||
def save(self, now: float):
|
||||
cut = now - HISTORY_S
|
||||
for k in self.slots:
|
||||
self.slots[k] = {t: v for t, v in self.slots[k].items() if t >= cut}
|
||||
tmp = self.path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(self.slots, f)
|
||||
os.replace(tmp, self.path)
|
||||
|
||||
|
||||
def _hourly(forecast: list[dict], key: str, start: int, steps: int) -> list[float] | None:
|
||||
"""A weather forecast's hourly value, held for each quarter hour."""
|
||||
pts = []
|
||||
for f in forecast or []:
|
||||
v = number(f.get(key))
|
||||
try:
|
||||
ts = datetime.fromisoformat(str(f["datetime"]).replace("Z", "+00:00")).timestamp()
|
||||
except (KeyError, ValueError):
|
||||
continue
|
||||
if v is not None:
|
||||
pts.append((ts, v))
|
||||
if not pts:
|
||||
return None
|
||||
pts.sort()
|
||||
out, j = [], 0
|
||||
for k in range(steps):
|
||||
t = start + k * STEP_S
|
||||
while j + 1 < len(pts) and pts[j + 1][0] <= t:
|
||||
j += 1
|
||||
out.append(pts[j][1])
|
||||
return out
|
||||
|
||||
|
||||
def _series(name, start, bundles, history, tz, now_value, default):
|
||||
s = bundles.forecast(name, start, STEP_S, STEPS, tz) if bundles else None
|
||||
if s is not None:
|
||||
return s, "model"
|
||||
out, have = [], 0
|
||||
for k in range(STEPS):
|
||||
t = start + k * STEP_S
|
||||
v = None
|
||||
for back in (86400, 2 * 86400): # the same quarter hour yesterday (or the day before)
|
||||
v = history.mean(name, t - back) if history else None
|
||||
if v is not None:
|
||||
break
|
||||
have += v is not None
|
||||
out.append(v if v is not None else (now_value if now_value is not None else default))
|
||||
return out, ("history" if have else ("now" if now_value is not None else "default"))
|
||||
|
||||
|
||||
def _hhmm(v: str, device_class) -> str | None:
|
||||
"""A departure as HH:MM: from "07:00(:00)" or a timestamp (local time
|
||||
of the timestamp as given)."""
|
||||
v = str(v)
|
||||
if len(v) in (5, 8) and v[2] == ":":
|
||||
return v[:5]
|
||||
try:
|
||||
d = datetime.fromisoformat(v.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
return d.strftime("%H:%M")
|
||||
|
||||
|
||||
def device_state(c, col: Collector, now: float) -> dict:
|
||||
"""What the optimiser needs to know about a control now."""
|
||||
e = c.entities
|
||||
st = {}
|
||||
if c.kind == "battery":
|
||||
soc = col.value(e.get("soc", ""))
|
||||
st["soc_pct"] = soc if soc is not None else float(c.p("soc_pct"))
|
||||
st["soc_estimated"] = soc is None
|
||||
st["charge_from_grid"] = col.state(e.get("charge_from_grid", "")) == "on"
|
||||
elif c.kind in ("heating", "cooling"):
|
||||
t = col.value(e.get("temp", ""))
|
||||
if t is None and e.get("climate"):
|
||||
t = number(col.attr(e["climate"], "current_temperature"))
|
||||
st["temp_c"] = t
|
||||
if e.get("climate"):
|
||||
st["target_c"] = number(col.attr(e["climate"], "temperature"))
|
||||
st["hvac"] = col.state(e["climate"])
|
||||
else:
|
||||
st["on"] = col.state(e.get("switch", "")) == "on"
|
||||
elif c.kind == "ev":
|
||||
conn = e.get("connected")
|
||||
st["connected"] = col.state(conn) == "on" if conn else True
|
||||
st["on"] = col.state(e.get("switch", "")) == "on"
|
||||
st["current_a"] = col.value(e.get("current", ""))
|
||||
st["soc_pct"] = col.value(e.get("soc", ""))
|
||||
need = col.value(e.get("energy_needed", ""))
|
||||
if need is not None:
|
||||
unit = col.attr(e["energy_needed"], "unit_of_measurement")
|
||||
st["need_wh"] = need * 1000.0 if unit == "kWh" else need
|
||||
dep = col.state(e.get("departure", "")) if e.get("departure") else None
|
||||
if dep:
|
||||
st["departure"] = _hhmm(dep, col.attr(e["departure"], "device_class"))
|
||||
elif c.kind == "cover":
|
||||
st["position_pct"] = cover_position(col, e["cover"])
|
||||
st["set_position"] = cover_positions(col, e["cover"])
|
||||
return st
|
||||
|
||||
|
||||
SET_POSITION = 4 # HA's CoverEntityFeature.SET_POSITION
|
||||
|
||||
|
||||
def cover_positions(col: Collector, ent: str) -> bool:
|
||||
"""Can the cover be set to a position (else only opened and closed)?
|
||||
True while HA has not said (the guard and the executor check again)."""
|
||||
f = number(col.attr(ent, "supported_features"))
|
||||
return True if f is None else bool(int(f) & SET_POSITION)
|
||||
|
||||
|
||||
def cover_position(col: Collector, ent: str) -> float | None:
|
||||
"""A cover's position (0 closed, 100 open): its current_position, else
|
||||
from its state (open 100, closed 0) for one that has no position."""
|
||||
v = number(col.attr(ent, "current_position"))
|
||||
if v is not None:
|
||||
return v
|
||||
return {"open": 100.0, "closed": 0.0}.get(col.state(ent))
|
||||
|
||||
|
||||
def model_state(now: float, controls, inputs, col: Collector, bundles, history, tz: str,
|
||||
weather_forecast: list[dict] | None, extra_limits: dict | None = None,
|
||||
occupied_hours=(6, 22), building: dict | None = None, location: dict | None = None,
|
||||
shade_ctx: dict | None = None, grid_order: dict | None = None) -> dict:
|
||||
"""The 48 h, 15-minute input for the optimiser (JSON: it runs in a
|
||||
subprocess). location: the site's latitude and longitude (HA's
|
||||
configuration); shade_ctx: per cover control its room (temp_c,
|
||||
setpoint_c, season: shades.py)."""
|
||||
start = int(now // STEP_S * STEP_S)
|
||||
zone = ZoneInfo(tz or "UTC")
|
||||
prices = bundles.prices(start, STEP_S, STEPS, now)
|
||||
load, load_src = _series("load_w", start, bundles, history, tz, col.total(inputs.load_power), 500.0)
|
||||
pv, pv_src = _series("pv_w", start, bundles, history, tz, None, 0.0)
|
||||
t_out = _hourly(weather_forecast or [], "temperature", start, STEPS)
|
||||
t_src = "weather forecast"
|
||||
measured = col.value(inputs.outside_temp) if inputs.outside_temp else None
|
||||
if t_out is not None and measured is not None:
|
||||
# a thermometer outside says better than the forecast what it is
|
||||
# now: the forecast moved by the difference, fading over 6 hours
|
||||
bias = measured - t_out[0]
|
||||
t_out = [v + bias * max(0.0, 1 - k / 24) for k, v in enumerate(t_out)]
|
||||
t_src = "weather forecast, from the outdoor sensor now"
|
||||
if t_out is None:
|
||||
now_out = col.value(inputs.outside_temp)
|
||||
if now_out is None and inputs.weather:
|
||||
now_out = number(col.attr(inputs.weather, "temperature"))
|
||||
t_out, t_src = [now_out if now_out is not None else 10.0] * STEPS, ("now" if now_out is not None else "default")
|
||||
peak = max(pv) if pv else 0.0
|
||||
if peak > 100:
|
||||
sun = [max(0.0, p / peak) for p in pv]
|
||||
else:
|
||||
# the sun's elevation now, held: a placeholder until a forecast says
|
||||
elev = number(col.attr(inputs.sun, "elevation")) if inputs.sun else None
|
||||
sun = [max(0.0, math.sin(math.radians(elev))) if elev is not None else 0.0] * STEPS
|
||||
present = None
|
||||
if inputs.presence:
|
||||
vals = [col.state(p) for p in inputs.presence]
|
||||
present = any(v in ("on", "home") for v in vals) if any(v is not None for v in vals) else None
|
||||
occupied = []
|
||||
for k in range(STEPS):
|
||||
if k < 4 and present is not None:
|
||||
occupied.append(1 if present else 0)
|
||||
continue
|
||||
h = datetime.fromtimestamp(start + k * STEP_S, timezone.utc).astimezone(zone).hour
|
||||
occupied.append(1 if occupied_hours[0] <= h < occupied_hours[1] else 0)
|
||||
devices = []
|
||||
for c in controls:
|
||||
if hasattr(c, "learn_range"):
|
||||
c.learn_range(col) # a climate's own min_temp..max_temp
|
||||
bounds = {}
|
||||
for q in _quantities(c):
|
||||
b = c.bounds(q, (extra_limits or {}).get(c.id))
|
||||
bounds[q] = [b.lo, b.hi, b.lo_by, b.hi_by]
|
||||
devices.append({"id": c.id, "kind": c.kind, "params": {k: c.p(k) for k in _param_names(c)},
|
||||
"state": device_state(c, col, now), "bounds": bounds,
|
||||
"channels": sorted(c.writable())})
|
||||
clouds = _hourly(weather_forecast or [], "cloud_coverage", start, STEPS)
|
||||
sky = [max(0.0, min(1.0, 1 - c / 100.0)) for c in clouds] if clouds else [1.0] * STEPS
|
||||
out = {"v": 1, "start": start, "step_s": STEP_S, "steps": STEPS, "tz": tz,
|
||||
"price_import": prices.import_ct, "price_export": prices.export_ct, "price_note": prices.note,
|
||||
"load_w": load, "pv_w": pv, "t_out": t_out, "sun": sun, "occupied": occupied, "sky": sky,
|
||||
"location": location or {},
|
||||
"sources": {"load": load_src, "pv": pv_src, "t_out": t_src, "model": bundles.model_id(),
|
||||
"sky": "weather forecast" if clouds else "clear"},
|
||||
"devices": devices, "building": building or {}, "grid_order": grid_order or {}}
|
||||
# a shade's moves by rules on the sun and its room (shades.py); the
|
||||
# optimiser takes them as they are
|
||||
from . import shades
|
||||
for d in devices:
|
||||
if d["kind"] == "cover":
|
||||
d["schedule"] = shades.schedule(d, out, (shade_ctx or {}).get(d["id"]))
|
||||
return out
|
||||
|
||||
|
||||
def _quantities(c) -> list[str]:
|
||||
return {"battery": ["soc_pct", "power_w"], "heating": ["temp_c"], "cooling": ["temp_c"],
|
||||
"ev": ["current_a"], "cover": ["position_pct"]}[c.kind]
|
||||
|
||||
|
||||
def _param_names(c) -> list[str]:
|
||||
from .controls import PARAMS
|
||||
return list(PARAMS[c.kind])
|
||||
@@ -0,0 +1,166 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The site's devices for the cloud: what each is (maker,
|
||||
model, firmware, the profile), its ratings (inverter kW, PV kWp, battery
|
||||
kWh and kW, heat pump kW, ...), what Cantabile reads and controls of it
|
||||
(asset and control ids) and its protection, for model training and the
|
||||
planners' capacity. Only with the owner's consent to share; never HA's
|
||||
entity ids or names (a device is its maker and model, its readings their
|
||||
asset ids). The box's own changes of protection go with it (the cloud's
|
||||
audit).
|
||||
|
||||
Sources: the mapping (assets, controls, mapping.d fragments), HA's device
|
||||
and entity registries (maker, model, firmware of the devices the mapped
|
||||
entities belong to), and on a Hub the devices tool's specs
|
||||
(devices-specs.json: profile, category, ratings, protection).
|
||||
|
||||
{"v":1, "made", "devices": [{"id", "source": "devices"|"ha",
|
||||
"manufacturer", "model", "model_id", "sw_version", "hw_version",
|
||||
"eebus_ski" (EEBUS devices), "category", "profile", "profile_version", "ratings": {...},
|
||||
"assets": [...], "assumed": [...], "controls": [...], "protection",
|
||||
"custodian"}],
|
||||
"protection": [{"target", "level", "custodian", "source", "set_by",
|
||||
"role", "at", "why"}]}
|
||||
Sent when it changed, and once a day.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
from .policy import Policy
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
RESEND_S = 24 * 3600
|
||||
MIN_GAP_S = 600 # the link passes one every 10 minutes
|
||||
VERSION_KEYS = ("manufacturer", "model", "model_id", "sw_version", "hw_version")
|
||||
|
||||
|
||||
def _eebus(d: dict) -> dict:
|
||||
"""An EEBUS device's SKI (the EEBUS bridge's devices: their serial
|
||||
number in HA): the cloud and the grid operator see which
|
||||
control box limits a site. Not a secret: a certificate's key hash."""
|
||||
if any(len(i) == 2 and i[0] == "mqtt" and str(i[1]).startswith("cantabile_eebus_") for i in d.get("identifiers") or []):
|
||||
ski = str(d.get("serial_number") or "").lower()
|
||||
if re.fullmatch(r"[0-9a-f]{40}", ski): # the platform refuses anything else
|
||||
return {"eebus_ski": ski}
|
||||
return {}
|
||||
|
||||
|
||||
def _hash(eid: str) -> str:
|
||||
return "h" + hashlib.sha256(eid.encode()).hexdigest()[:12]
|
||||
|
||||
|
||||
def build(mapping, registries: dict, specs: dict, policy: dict, now: float) -> dict:
|
||||
ents = {e["entity_id"]: e for e in registries.get("entities") or []}
|
||||
devs = {d["id"]: d for d in registries.get("devices") or []}
|
||||
asset_of = {a.entity: a.asset for a in mapping.assets}
|
||||
of_entity = {}
|
||||
for a in mapping.assets:
|
||||
of_entity.setdefault(a.entity, []).append(a)
|
||||
|
||||
def assumed_of(eids):
|
||||
"""The readings that are assumed, not measured (mapping.py)."""
|
||||
return sorted({a.asset for e in eids for a in of_entity.get(e, []) if getattr(a, "assumed", False)})
|
||||
control_of = {}
|
||||
for c in mapping.controls:
|
||||
for e in c.entities.values():
|
||||
control_of.setdefault(e, c.id)
|
||||
|
||||
def ha_device(entity_ids, hint=None):
|
||||
if hint and hint in devs:
|
||||
return devs[hint]
|
||||
for eid in entity_ids:
|
||||
d = devs.get((ents.get(eid) or {}).get("device_id"))
|
||||
if d:
|
||||
return d
|
||||
return {}
|
||||
|
||||
out, covered = [], set()
|
||||
for did, s in sorted((specs.get("devices") or {}).items()):
|
||||
mine = list(s.get("entities") or [])
|
||||
covered |= set(mine)
|
||||
hd = ha_device(mine, s.get("ha_device"))
|
||||
out.append({"id": did, "source": "devices",
|
||||
**{k: hd.get(k) or "" for k in VERSION_KEYS}, **_eebus(hd),
|
||||
# the profile's maker and model where HA has none
|
||||
"manufacturer": hd.get("manufacturer") or s.get("manufacturer", ""),
|
||||
"model": hd.get("model") or s.get("model", ""),
|
||||
"category": s.get("category", ""), "profile": s.get("profile", ""),
|
||||
"profile_version": s.get("profile_version", ""), "ratings": s.get("ratings") or {},
|
||||
"assets": sorted({asset_of[e] for e in mine if e in asset_of}),
|
||||
"assumed": assumed_of(mine),
|
||||
"controls": sorted(s.get("controls") or []),
|
||||
"protection": s.get("protection") or "none", "custodian": s.get("custodian")})
|
||||
# the mapping's own entities (an installer's mapping; an HA add-on site):
|
||||
# one entry per HA device they belong to
|
||||
groups: dict[str, list[str]] = {}
|
||||
for eid in list(asset_of) + list(control_of):
|
||||
if eid in covered:
|
||||
continue
|
||||
d = (ents.get(eid) or {}).get("device_id")
|
||||
groups.setdefault(d or "", []).append(eid)
|
||||
for d, eids in sorted(groups.items()):
|
||||
hd = devs.get(d) or {}
|
||||
if not d:
|
||||
continue # entities without a device: nothing to tell
|
||||
out.append({"id": "ha:" + hashlib.sha256(d.encode()).hexdigest()[:12], "source": "ha",
|
||||
**{k: hd.get(k) or "" for k in VERSION_KEYS}, **_eebus(hd),
|
||||
"category": "", "profile": "", "profile_version": "", "ratings": {},
|
||||
"assets": sorted({asset_of[e] for e in eids if e in asset_of}),
|
||||
"assumed": assumed_of(eids),
|
||||
"controls": sorted({control_of[e] for e in eids if e in control_of}),
|
||||
"protection": "none", "custodian": None})
|
||||
prot = []
|
||||
for t, e in sorted(policy.items()):
|
||||
if e.get("source") == "cloud":
|
||||
continue # the cloud has its own
|
||||
kind, _, name = t.partition(":")
|
||||
if kind == "entity":
|
||||
t = f"asset:{asset_of[name]}" if name in asset_of else f"entity:{_hash(name)}"
|
||||
prot.append({"target": t, **{k: e.get(k) for k in ("level", "custodian", "source", "set_by", "role", "at", "why")}})
|
||||
return {"v": 1, "made": int(now), "devices": out, "protection": prot}
|
||||
|
||||
|
||||
class Inventory:
|
||||
"""Sends the inventory through the sink (the link: op "inventory")."""
|
||||
|
||||
def __init__(self, cfg, mapping, consent, sink, policy: Policy | None = None, clock=time.time):
|
||||
self.cfg, self.mapping, self.consent, self.sink, self.clock = cfg, mapping, consent, sink, clock
|
||||
self.policy = policy or Policy(cfg.state_dir, cfg.site_id, clock)
|
||||
self.specs_path = os.path.join(cfg.state_dir, "devices-specs.json")
|
||||
self.sent_digest, self.sent_at = "", 0.0
|
||||
|
||||
def specs(self) -> dict:
|
||||
try:
|
||||
with open(self.specs_path) as f:
|
||||
d = json.load(f)
|
||||
return d if isinstance(d, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
async def maybe_send(self, client) -> bool:
|
||||
if not self.consent.share:
|
||||
return False
|
||||
pub = getattr(self.sink, "publish", None)
|
||||
if pub is None or client is None:
|
||||
return False
|
||||
try:
|
||||
reg = await client.registries()
|
||||
except Exception as e:
|
||||
log.info("inventory: HA's registries: %s", e)
|
||||
return False
|
||||
now = self.clock()
|
||||
if self.sent_at and now - self.sent_at < MIN_GAP_S:
|
||||
return False
|
||||
inv = build(self.mapping, reg, self.specs(), self.policy.entries(), now)
|
||||
body = {k: v for k, v in inv.items() if k != "made"}
|
||||
digest = hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
|
||||
if digest == self.sent_digest and now - self.sent_at < RESEND_S:
|
||||
return False
|
||||
await pub("inventory", inv)
|
||||
self.sent_digest, self.sent_at = digest, now
|
||||
log.info("inventory sent: %d devices", len(inv["devices"]))
|
||||
return True
|
||||
@@ -0,0 +1,603 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Joining a building or a community from Home Assistant ("Joining"), for sites that run the agent as an HA add-on: no Hub panel
|
||||
there, so the add-on's own page (HA's ingress: Settings, Add-ons, Cantabile,
|
||||
Open web UI, or the sidebar) offers what the Hub panel's Building or
|
||||
community section does: join with the operator's code (or a QR code's
|
||||
?code=), ask a building near Home Assistant's location to take the flat or
|
||||
an energy community to take the home (a villa), withdraw a request, leave.
|
||||
|
||||
The same requests as the Hub's /usr/lib/cantabile/building, to fleet's
|
||||
POST <devices>/api/devices/building, signed with the site's key by the
|
||||
link in this container (`cantabile-link sign "building:<site>:<time>:
|
||||
<sha256 of the request>"`). The result goes into the agent's state
|
||||
directory: joining.json (the last status, shown when Cantabile is out of
|
||||
reach) and membership.json (the buildings whose commands the agent takes:
|
||||
building.py). Fleet's status is synced every SYNC_S as well.
|
||||
|
||||
Only HA's ingress proxy (172.30.32.2) and this host may open the page:
|
||||
HA has signed the user in; the add-on's app (devpage.App) lets only HA's
|
||||
administrators in. The building's (or the community's) operator as
|
||||
a recipient of the home's data (every 15 minutes) is the owner's choice when
|
||||
joining, kept in consent.json's "recipients" ("building", "community") as the
|
||||
Hub panel keeps it.
|
||||
|
||||
After a reinstall Cantabile recognised (fleet reinstall.go), the page says
|
||||
"This looks like your earlier Cantabile box <name>" with what the cloud kept
|
||||
by itself, and offers the earlier consents for the building's and the
|
||||
community's operator, pre-ticked, given again only with the owner's yes.
|
||||
Cantabile keeps no backup: nothing else is restored here.
|
||||
|
||||
Not here: finding a building on the local network (an add-on has no mDNS
|
||||
of its own; the Hub's panel does it), the Hub-only parts (its own box)."""
|
||||
import asyncio
|
||||
import hashlib
|
||||
import html
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from . import i18n
|
||||
from .i18n import M, T, TN
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SYNC_S = 900
|
||||
INGRESS_PEERS = {"172.30.32.2", "127.0.0.1", "::1"}
|
||||
CODE_RE = re.compile(r"[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}")
|
||||
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||
E = html.escape
|
||||
|
||||
|
||||
class Fail(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _read(path: str) -> str:
|
||||
try:
|
||||
with open(path) as f:
|
||||
return f.read()
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def _write_json(path: str, d: dict, mode: int = 0o600):
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
tmp = path + ".tmp"
|
||||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
json.dump(d, f)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def member_ids(status: dict) -> list[str]:
|
||||
"""The buildings whose commands the agent takes (as the Hub's tool)."""
|
||||
ids = []
|
||||
m = status.get("membership")
|
||||
if m and m.get("state") == "active":
|
||||
ids.append(m["building"]["id"])
|
||||
ids += [c["id"] for c in status.get("communities") or []]
|
||||
ids += [o["id"] for o in status.get("own_site_of") or []]
|
||||
return sorted(set(ids))
|
||||
|
||||
|
||||
class Fleet:
|
||||
"""Fleet's building API for this site, signed by the link."""
|
||||
|
||||
def __init__(self, state_dir: str, link_state: str = "", devices_url: str = "",
|
||||
link_bin: str = "cantabile-link", site_id: str = ""):
|
||||
self.state_dir = state_dir
|
||||
self.link_state = link_state or os.environ.get("CANTABILE_LINK_STATE", "/data/link")
|
||||
self.url = (devices_url or os.environ.get("CANTABILE_DEVICES_URL", "https://devices.cantabile.cloud")).rstrip("/")
|
||||
self.link_bin, self._site = link_bin, site_id
|
||||
self.status_path = os.path.join(state_dir, "joining.json")
|
||||
self.membership_path = os.path.join(state_dir, "membership.json")
|
||||
self.consent_path = os.path.join(state_dir, "consent.json")
|
||||
|
||||
def site(self) -> str:
|
||||
s = self._site or _read(os.path.join(self.link_state, "site-id")).strip()
|
||||
if not re.fullmatch(r"[0-9a-f]{32}", s):
|
||||
raise Fail(T("this Home Assistant is not connected to Cantabile yet"))
|
||||
return s
|
||||
|
||||
def sign(self, text: str) -> str:
|
||||
try:
|
||||
r = subprocess.run([self.link_bin, "sign", text], capture_output=True, text=True, timeout=30,
|
||||
env={**os.environ, "CANTABILE_LINK_STATE": self.link_state})
|
||||
except (OSError, subprocess.SubprocessError) as e:
|
||||
raise Fail(T("cannot sign: {error}", error=e))
|
||||
sig = r.stdout.strip()
|
||||
if r.returncode != 0 or not re.fullmatch(r"[A-Za-z0-9+/=]{20,200}", sig):
|
||||
raise Fail(T("cannot sign: {error}", error=r.stderr.strip()[:200] or T("no key yet")))
|
||||
return sig
|
||||
|
||||
def ask(self, req: dict, timeout: float = 30) -> dict:
|
||||
site = self.site()
|
||||
body = json.dumps(req, separators=(",", ":"))
|
||||
ts = int(time.time())
|
||||
text = f"building:{site}:{ts}:{hashlib.sha256(body.encode()).hexdigest()}"
|
||||
data = json.dumps({"box": site, "ts": ts, "req": body, "sig": self.sign(text)}).encode()
|
||||
r = urllib.request.Request(self.url + "/api/devices/building", data=data, method="POST",
|
||||
headers={"Content-Type": "application/json", "User-Agent": "cantabile-edge"})
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=timeout) as resp:
|
||||
return json.loads(resp.read(1 << 20) or b"{}")
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
msg = json.loads(e.read(4096) or b"{}").get("error", "")
|
||||
except ValueError:
|
||||
msg = ""
|
||||
raise Fail(msg or T("Cantabile answered {code}", code=e.code))
|
||||
except (OSError, ValueError) as e:
|
||||
raise Fail(T("Cantabile cannot be reached: {error}", error=e))
|
||||
|
||||
def apply(self, status: dict) -> dict:
|
||||
status = dict(status, synced_at=int(time.time()))
|
||||
_write_json(self.status_path, status, 0o644)
|
||||
_write_json(self.membership_path, {"buildings": member_ids(status), "at": int(time.time())})
|
||||
return status
|
||||
|
||||
# -- the offer after a reinstall (the link keeps it: restore-offer.json)
|
||||
def offer(self) -> dict | None:
|
||||
try:
|
||||
o = json.loads(_read(os.path.join(self.link_state, "restore-offer.json")) or "{}")
|
||||
done = json.loads(_read(os.path.join(self.state_dir, "restore-answered.json")) or "{}")
|
||||
except ValueError:
|
||||
return None
|
||||
if not isinstance(o.get("from"), dict) or not o.get("received") or done.get("received") == o.get("received"):
|
||||
return None
|
||||
return o
|
||||
|
||||
def answer_offer(self, o: dict, f: dict) -> str:
|
||||
done = []
|
||||
c = o.get("consents") if isinstance(o.get("consents"), dict) else None
|
||||
if f.get("answer") == "yes" and c and f.get("consent_yes") == "1":
|
||||
for who in ("building", "community"):
|
||||
self.set_recipient_consent(who, f.get(f"c_r_{who}") == "1")
|
||||
done.append(M("consents given again"))
|
||||
_write_json(os.path.join(self.state_dir, "restore-answered.json"),
|
||||
{"received": o.get("received"), "at": int(time.time()), "done": done})
|
||||
return T("Restored: {what}.", what="; ".join(T(d) for d in done)) if done else T("Nothing restored.")
|
||||
|
||||
def kept(self) -> dict:
|
||||
try:
|
||||
return json.loads(_read(self.status_path) or "{}")
|
||||
except ValueError:
|
||||
return {}
|
||||
|
||||
# -- the owner's consent for the operator of what they join
|
||||
# ("building" or "community"; consent.json)
|
||||
def recipient_consent(self, who: str = "building") -> bool:
|
||||
try:
|
||||
r = json.loads(_read(self.consent_path) or "{}").get("recipients") or {}
|
||||
except ValueError:
|
||||
return False
|
||||
return isinstance(r.get(who), dict) and r[who].get("granted") is True
|
||||
|
||||
def building_consent(self) -> bool:
|
||||
return self.recipient_consent("building")
|
||||
|
||||
def set_building_consent(self, granted: bool):
|
||||
self.set_recipient_consent("building", granted)
|
||||
|
||||
def set_recipient_consent(self, who: str, granted: bool):
|
||||
try:
|
||||
d = json.loads(_read(self.consent_path) or "{}")
|
||||
except ValueError:
|
||||
d = {}
|
||||
now = int(time.time())
|
||||
rec = d.get("recipients") if isinstance(d.get("recipients"), dict) else {}
|
||||
rec[who] = {"granted": bool(granted), "at": now, "by": "ha-addon-page"}
|
||||
# the site's own consent (share, control: the add-on's configuration)
|
||||
# keeps its when and how
|
||||
d.update(recipients=rec)
|
||||
_write_json(self.consent_path, d)
|
||||
|
||||
|
||||
def ha_location(timeout: float = 10) -> tuple[float, float] | None:
|
||||
"""Home Assistant's home location (the Supervisor's proxy to Core)."""
|
||||
tok = os.environ.get("SUPERVISOR_TOKEN")
|
||||
if not tok:
|
||||
return None
|
||||
r = urllib.request.Request("http://supervisor/core/api/config", headers={"Authorization": f"Bearer {tok}"})
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=timeout) as resp:
|
||||
c = json.loads(resp.read(1 << 20))
|
||||
return float(c["latitude"]), float(c["longitude"])
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
# ---- the page ---------------------------------------------------------------
|
||||
|
||||
CONTROL_WORDS = {"load_limit": (M("a limit on what your home draws from the grid"), "W"),
|
||||
"shift_request": (M("requests to move some of your energy use to another time"), "kWh"),
|
||||
"thermostat_cap": (M("a cap on your heating's setpoints"), "°C")}
|
||||
# a community's penalties: the term's field and its words
|
||||
TERM_WORDS = (("guaranteed_kw", M("{v} kW guaranteed")), ("minimum_kwh", M("at least {v} kWh")),
|
||||
("max_kw", M("at most {v} kW")), ("deviation_ct", M("{v} ct/kWh for a deviation")),
|
||||
("override_ct", M("{v} ct/kWh for overriding a request")))
|
||||
PERIODS = {"month": M("month"), "quarter": M("quarter"), "year": M("year")}
|
||||
|
||||
CSS = """body{font-family:system-ui,sans-serif;margin:0;padding:16px;max-width:46rem;color:#1d2a24;background:#f6f8f7}
|
||||
h2{margin:.2rem 0 1rem}h3{margin:1.4rem 0 .5rem}.box{background:#fff;border:1px solid #d5ded9;border-radius:8px;padding:.8rem;margin:.6rem 0}
|
||||
.ok{background:#e3f4ea;border-color:#9fd3b4}.err{background:#fbe4e2;border-color:#e6a9a3}.note{color:#5a6b62}
|
||||
label{display:block;margin:.6rem 0 .2rem;font-size:.92rem}input:not([type=checkbox]){font:inherit;padding:.45rem .6rem;border:1px solid #b9c6bf;border-radius:6px;width:100%;box-sizing:border-box}
|
||||
label.check{display:flex;gap:.5rem;align-items:flex-start}button{font:inherit;padding:.45rem 1rem;border:0;border-radius:6px;background:#2f6f55;color:#fff;cursor:pointer;margin-top:.6rem}
|
||||
button.secondary{background:#e2e9e5;color:#1d2a24}form{margin:.4rem 0}
|
||||
@media (prefers-color-scheme:dark){body{background:#111915;color:#e3ebe6}.box{background:#18221d;border-color:#2b3a32}.note{color:#9fb0a6}
|
||||
input:not([type=checkbox]){background:#18221d;color:#e3ebe6;border-color:#3a4b42}.ok{background:#173326}.err{background:#3a1d1a}button.secondary{background:#2b3a32;color:#e3ebe6}}"""
|
||||
|
||||
N = i18n.number
|
||||
|
||||
|
||||
def community_terms_words(t):
|
||||
"""A community's terms in plain words: the price of shared
|
||||
energy (used now) and the amounts and penalties (recorded, not applied)."""
|
||||
if not t:
|
||||
return []
|
||||
ref = (f"{N(t.get('reference_ct', 0))} ct/kWh" if t.get("reference") == "fixed"
|
||||
else T("the day-ahead price (around {ct} ct/kWh)", ct=N(t.get("reference_ct", 0))))
|
||||
d = t.get("delta_ct", 0) or 0
|
||||
values = {"delta": N(abs(d)), "reference": ref, "feed_in": N(t.get("feed_in_ct", 0))}
|
||||
out = [T("Energy shared in the community: {delta} ct/kWh below {reference}; a surplus nobody in it takes goes to "
|
||||
"the grid at {feed_in} ct/kWh.", **values) if d < 0 else
|
||||
T("Energy shared in the community: {delta} ct/kWh above {reference}; a surplus nobody in it takes goes to "
|
||||
"the grid at {feed_in} ct/kWh.", **values)]
|
||||
extra = [T(w, v=N(t[k])) for k, w in TERM_WORDS if t.get(k)]
|
||||
if extra:
|
||||
period = t.get("period", "month")
|
||||
out.append(T("Per quarter-hour: {terms}, summed per {period} (Cantabile records these; it does not apply or "
|
||||
"bill them yet).", terms=", ".join(extra), period=T(PERIODS[period]) if period in PERIODS else period))
|
||||
return out
|
||||
|
||||
|
||||
def rules_html(r: dict | None, kind: str = "building") -> str:
|
||||
if not r:
|
||||
return ""
|
||||
community = kind == "community"
|
||||
if community:
|
||||
items = [T("The community sees your home's energy use every 15 minutes, if you allow it below.")
|
||||
if r.get("share") == "per_flat" else
|
||||
T("The community sees your energy use only summed up with its other members.")]
|
||||
items.append(T("Your 15-minute values are used to settle the energy shared in the community, never shown to its "
|
||||
"operator as a time series.") if r.get("billing", "per_flat") == "per_flat"
|
||||
else T("Cantabile settles nothing for this community."))
|
||||
else:
|
||||
items = [T("The building sees your flat's energy use every 15 minutes, if you allow it below.")
|
||||
if r.get("share") == "per_flat" else
|
||||
T("The building sees your energy use only summed up with the other flats.")]
|
||||
items.append(T("Your 15-minute consumption is used for the building's bills (for example shared solar power), "
|
||||
"never shown to the operator as a time series.") if r.get("billing", "per_flat") == "per_flat"
|
||||
else T("Cantabile makes no bills for this building."))
|
||||
allowed = [(k, b) for k, b in (r.get("controls") or {}).items() if b.get("allowed") and k in CONTROL_WORDS]
|
||||
if allowed:
|
||||
parts = []
|
||||
for k, b in allowed:
|
||||
what, unit = CONTROL_WORDS[k]
|
||||
lo, hi = b.get("min"), b.get("max")
|
||||
rng = (f" ({N(lo)}–{N(hi)} {unit})" if lo is not None and hi is not None
|
||||
else " (" + T("at least {v} {unit}", v=N(lo), unit=unit) + ")" if lo is not None
|
||||
else " (" + T("at most {v} {unit}", v=N(hi), unit=unit) + ")" if hi is not None else "")
|
||||
parts.append(T(what) + rng)
|
||||
how = (T("You can always override them.") if r.get("level") != "binding"
|
||||
else T("They apply until they end; your comfort settings always win."))
|
||||
items.append((T("The community may send {controls}.", controls="; ".join(parts)) if community else
|
||||
T("The building may send {controls}.", controls="; ".join(parts))) + " " + how)
|
||||
else:
|
||||
items.append(T("The community sends your home no requests.") if community
|
||||
else T("The building sends your home no requests."))
|
||||
if community:
|
||||
items += community_terms_words(r.get("community") or {})
|
||||
days = r.get("notice_days", 30)
|
||||
items.append(TN("Notice when the operator ends your membership or closes the community: {days} day.",
|
||||
"Notice when the operator ends your membership or closes the community: {days} days.", days, days=N(days))
|
||||
if community else
|
||||
TN("Notice when the operator ends your membership or closes the building: {days} day.",
|
||||
"Notice when the operator ends your membership or closes the building: {days} days.", days, days=N(days)))
|
||||
if r.get("pv_price_ct") and not community:
|
||||
items.append(T("Shared solar power: {pv} ct/kWh; grid power when no tariff covers you: {grid} ct/kWh.",
|
||||
pv=N(r["pv_price_ct"]), grid=N(r.get("grid_price_ct", 0))))
|
||||
return "<ul>" + "".join(f"<li>{E(i)}</li>" for i in items) + "</ul>"
|
||||
|
||||
|
||||
def card(c: dict) -> str:
|
||||
dist = " · " + T("{m} m away", m=f"{c['distance_m']:.0f}") if c.get("distance_m") is not None else ""
|
||||
return (f"<div class=\"box\"><b>{E(c.get('name', ''))}</b><br><small>{E(c.get('address', ''))}{E(dist)}"
|
||||
f"<br>{E(T('Run by {operator}', operator=c.get('operator', '')))}</small></div>")
|
||||
|
||||
|
||||
def when(s: str) -> str:
|
||||
return i18n.iso_date(s)
|
||||
|
||||
|
||||
def consent_box(checked: bool, kind: str = "building") -> str:
|
||||
if kind == "community":
|
||||
return (f'<label class="check"><input type="checkbox" name="consent_community" value="1"{" checked" if checked else ""}>'
|
||||
"<span>" + E(T("Share my home's energy data with the community's operator (every 15 minutes, if the "
|
||||
"community's rules ask for it).")) + "</span></label>")
|
||||
return (f'<label class="check"><input type="checkbox" name="consent_building" value="1"{" checked" if checked else ""}>'
|
||||
"<span>" + E(T("Share my flat's energy data with the building's operator (per flat, every 15 minutes, if the "
|
||||
"building's rules ask for it).")) + "</span></label>")
|
||||
|
||||
|
||||
def form(do: str, inner: str, button: str, cls: str = "") -> str:
|
||||
# action="": the same address, which is the ingress path HA gave the page
|
||||
return (f'<form method="post" action=""><input type="hidden" name="do" value="{E(do)}">{inner}'
|
||||
f'<button{f" class={chr(34)}{cls}{chr(34)}" if cls else ""}>{E(button)}</button></form>')
|
||||
|
||||
|
||||
KEPT_WORDS = {"name": M("Its name"), "tags": M("Its tags"), "building": M("Its building"),
|
||||
"communities": M("Its energy communities"), "tariffs": M("Its tariff"),
|
||||
"protection_entries": M("Its device protection"), "devices": M("Its devices' details")}
|
||||
RECIPIENT_WORDS = {"building": M("Your building's operator receives this home's energy data every 15 minutes"),
|
||||
"community": M("Your energy community's operator receives this home's energy data every 15 minutes")}
|
||||
|
||||
|
||||
def offer_html(o: dict) -> str:
|
||||
""""This looks like your earlier Cantabile box": what the cloud kept, and
|
||||
the earlier consents for the operators (only with the owner's yes)."""
|
||||
name = (o.get("from") or {}).get("name") or T("of this home")
|
||||
rows = []
|
||||
for k, words in KEPT_WORDS.items():
|
||||
v = (o.get("kept") or {}).get(k)
|
||||
if v in (None, "", [], 0):
|
||||
continue
|
||||
rows.append(f"<li>{E(T(words))}: {E(', '.join(map(str, v)) if isinstance(v, list) else str(v))}</li>")
|
||||
inner = f"<p>{E(T('Kept by Cantabile already:'))}</p><ul>{''.join(rows)}</ul>" if rows else ""
|
||||
c = o.get("consents") if isinstance(o.get("consents"), dict) else None
|
||||
if c:
|
||||
rec = set(c.get("recipients") or [])
|
||||
inner += (f'<p class="note">{E(T("Your earlier consents, as you gave them. They count only with your yes below."))}</p>'
|
||||
+ "".join(f'<label class="check"><input type="checkbox" name="c_r_{k}" value="1"{" checked" if k in rec else ""}>'
|
||||
f"<span>{E(T(w))}</span></label>" for k, w in RECIPIENT_WORDS.items())
|
||||
+ '<label class="check"><input type="checkbox" name="consent_yes" value="1">'
|
||||
f"<span><b>{E(T('Yes, I give these consents again.'))}</b></span></label>")
|
||||
inner += (f'<p class="note">{E(T("Cantabile keeps no backup of your home: which entities it may read, the devices and the add-on's options are set up again in Home Assistant."))}</p>')
|
||||
return (f'<div class="box">{T("This looks like your earlier Cantabile box {name}. Restore its settings?", name=f"<b>{E(name)}</b>")}</div>'
|
||||
f'<form method="post" action=""><input type="hidden" name="do" value="restore">{inner}'
|
||||
f'<button name="answer" value="no" class="secondary">{E(T("Not now"))}</button> '
|
||||
f'<button name="answer" value="yes">{E(T("Restore what is ticked"))}</button></form>')
|
||||
|
||||
|
||||
def check(name: str, text: str) -> str:
|
||||
return f'<label class="check"><input type="checkbox" name="{name}" value="1"><span>{E(text)}</span></label>'
|
||||
|
||||
|
||||
def page(st: dict, st_err: str, consent: bool, err: str = "", ok: str = "", preview: dict | None = None,
|
||||
code: str = "", found: list | None = None, consent_community: bool = False, offer: dict | None = None) -> str:
|
||||
body = [f"<h2>{E(T('Building or community'))}</h2>"]
|
||||
if offer:
|
||||
body.append(offer_html(offer))
|
||||
given = {"building": consent, "community": consent_community}
|
||||
state = {True: T("given"), False: T("not given")}
|
||||
if ok:
|
||||
body.append(f'<div class="box ok">{E(ok)}</div>')
|
||||
if err:
|
||||
body.append(f'<div class="box err">{E(err)}</div>')
|
||||
if st_err:
|
||||
body.append('<p class="note">' + E(T("Cantabile could not be reached ({error}); this is what it said last.", error=st_err)
|
||||
if st else T("Cantabile could not be reached ({error}).", error=st_err)) + "</p>")
|
||||
m = st.get("membership")
|
||||
if m:
|
||||
c = m["building"]
|
||||
ends = ('<div class="box err">' + E(T("The building's operator ended your membership: it ends on {date}.",
|
||||
date=when(m["ends_at"]))) + "</div>" if m.get("ends_at") else "")
|
||||
body.append("<p>" + T("Your flat is a member of this building (unit <b>{unit}</b>, since {since}).",
|
||||
unit=E(m.get("unit") or ""), since=E(when(m.get("joined_at") or ""))) + "</p>"
|
||||
+ card(c) + ends + "<h3>" + E(T("The building's rules")) + "</h3>" + rules_html(c.get("rules"))
|
||||
+ '<p class="note">' + E(T("Your consent for the building's operator: {state}.", state=state[consent])) + "</p>"
|
||||
+ form("leave", f'<input type="hidden" name="building" value="{E(c["id"])}">'
|
||||
+ check("sure", T("Leave this building. Its requests to your home end now; to join again you need "
|
||||
"a new code from the operator.")), T("Leave the building"), "secondary"))
|
||||
for cm in st.get("communities") or []:
|
||||
ends = ('<div class="box err">' + E(T("The community's operator ended your membership: it ends on {date}.",
|
||||
date=when(cm["ends_at"]))) + "</div>" if cm.get("ends_at") else "")
|
||||
values = {"name": E(cm["name"]), "operator": E(cm.get("operator", ""))}
|
||||
body.append("<p>" + (T("Your home is a member of the energy community <b>{name}</b> (run by {operator}, since {since}).",
|
||||
since=E(when(cm["joined_at"])), **values) if cm.get("joined_at") else
|
||||
T("Your home is a member of the energy community <b>{name}</b> (run by {operator}).", **values))
|
||||
+ "</p>" + ends + "<details><summary>" + E(T("The community's rules")) + "</summary>"
|
||||
+ f"{rules_html(cm.get('rules'), 'community')}</details>"
|
||||
+ '<p class="note">' + E(T("Your consent for the community's operator: {state}.",
|
||||
state=state[consent_community])) + "</p>"
|
||||
+ form("leave", f'<input type="hidden" name="building" value="{E(cm["id"])}">'
|
||||
+ check("sure", T("Leave this community. Its requests to your home end now; to join again you "
|
||||
"need a new code or its operator's yes.")), T("Leave the community"), "secondary"))
|
||||
if st.get("ended") and not m:
|
||||
e = st["ended"]
|
||||
body.append('<p class="note">' + E(T("Your membership of {name} ended on {date}: {reason}.", name=e.get("name", ""),
|
||||
date=when(e.get("at", "")), reason=e.get("reason", ""))) + "</p>")
|
||||
for r in st.get("requests") or []:
|
||||
if r.get("state") == "pending":
|
||||
name = f"<b>{E(r['name'])}</b>" + (" (" + E(T("unit {unit}", unit=r["unit_hint"])) + ")" if r.get("unit_hint") else "")
|
||||
body.append("<p>" + (T("You asked to join {name}: waiting for the community's operator.", name=name)
|
||||
if r.get("kind") == "community" else
|
||||
T("You asked to join {name}: waiting for the building's operator.", name=name)) + "</p>"
|
||||
+ form("cancel", f'<input type="hidden" name="request" value="{E(r["id"])}">',
|
||||
T("Withdraw the request"), "secondary"))
|
||||
elif r.get("state") == "declined":
|
||||
body.append('<p class="note">' + E(T("{name} declined your request: {reason}.", name=r["name"], reason=r["reason"])
|
||||
if r.get("reason") else
|
||||
T("{name} declined your request.", name=r["name"])) + "</p>")
|
||||
if preview:
|
||||
c, u = preview["building"], preview.get("unit")
|
||||
kind = "community" if c.get("kind") == "community" else "building"
|
||||
meter = (f'<label for="meter">{E(T("Your meter point (on your meter or your electricity bill)"))}</label>'
|
||||
'<input id="meter" name="meter_point" autocomplete="off" required>') if u and u.get("confirm_meter") else ""
|
||||
what = (T("Unit <b>{unit}</b> of this building:", unit=E(u["label"])) if u
|
||||
else E(T("This energy community (energy shared between buildings and homes):")))
|
||||
body.append(f"<h3>{E(T('Join'))}</h3><p>{what}</p>{card(c)}<h3>{E(T('Its rules'))}</h3>{rules_html(c.get('rules'), kind)}"
|
||||
+ form("join", f'<input type="hidden" name="code" value="{E(code)}"><input type="hidden" name="kind" value="{kind}">'
|
||||
f'<input type="hidden" name="rules_digest" value="{E(c.get("rules_digest", ""))}">{meter}'
|
||||
f'{consent_box(given[kind], kind)}', T("Join {name}", name=c.get("name", ""))))
|
||||
elif not m:
|
||||
body.append(f"<h3>{E(T('Join with a code'))}</h3><p class=\"note\">"
|
||||
+ E(T("A building's operator gives each flat a code; an energy community's operator gives each home a "
|
||||
"code (or a QR code: open its link here, or type the code).")) + "</p>"
|
||||
+ form("preview", f'<label for="code">{E(T("Join code"))}</label><input id="code" name="code" value="{E(code)}" '
|
||||
'autocapitalize="characters" autocomplete="off" placeholder="XXXX-XXXX-XXXX" required>', T("Continue")))
|
||||
if found is not None:
|
||||
if not found:
|
||||
body.append('<p class="note">' + E(T("No building or energy community using Cantabile was found near your "
|
||||
"home.")) + "</p>")
|
||||
for c in found:
|
||||
cid = E(c["id"])
|
||||
kind = "community" if c.get("kind") == "community" else "building"
|
||||
unit = ("" if kind == "community" else
|
||||
f'<label for="unit-{cid}">{E(T("Your flat (as on your door or contract)"))}</label><input id="unit-{cid}" '
|
||||
'name="unit_hint" maxlength="40" placeholder="3B">')
|
||||
body.append(card(c) + ('<p class="note">' + E(T("An energy community.")) + "</p>" if kind == "community" else "")
|
||||
+ f"<details><summary>{E(T('Its rules'))}</summary>{rules_html(c.get('rules'), kind)}</details>"
|
||||
+ form("request", f'<input type="hidden" name="building" value="{cid}"><input type="hidden" '
|
||||
f'name="kind" value="{kind}"><input type="hidden" name="rules_digest" '
|
||||
f'value="{E(c.get("rules_digest", ""))}">{unit}<label for="note-{cid}">'
|
||||
f'{E(T("A note for the operator (optional)"))}</label><input id="note-{cid}" name="note" maxlength="300">'
|
||||
f'{consent_box(given[kind], kind)}', T("Ask to join")))
|
||||
body.append(f"<h3>{E(T('No code?'))}</h3><p class=\"note\">"
|
||||
+ E(T("Look for buildings and energy communities using Cantabile near your home (Home Assistant's "
|
||||
"location goes to Cantabile only when you press this).")) + "</p>"
|
||||
+ form("find", "", T("Near my home"), "secondary"))
|
||||
return (f"<!doctype html><html lang=\"{i18n.current()}\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" "
|
||||
f"content=\"width=device-width,initial-scale=1\"><title>{E(T('Cantabile: building or community'))}</title>"
|
||||
f"<style>{CSS}</style></head><body>{''.join(body)}</body></html>")
|
||||
|
||||
|
||||
class JoinPage:
|
||||
"""The page and the status sync; `handle` is the HTTP part (tests)."""
|
||||
|
||||
def __init__(self, fleet: Fleet, location=ha_location):
|
||||
self.fleet, self.location = fleet, location
|
||||
|
||||
def _status(self) -> tuple[dict, str]:
|
||||
try:
|
||||
return self.fleet.apply(self.fleet.ask({"op": "status"})), ""
|
||||
except Fail as e:
|
||||
return self.fleet.kept(), str(e)
|
||||
|
||||
def get(self, query: dict) -> str:
|
||||
code = (query.get("code") or [""])[0].strip().upper()
|
||||
if code and CODE_RE.fullmatch(code):
|
||||
return self.post({"do": "preview", "code": code})
|
||||
st, err = self._status()
|
||||
return page(st, err, self.fleet.building_consent(), consent_community=self.fleet.recipient_consent("community"),
|
||||
offer=self.fleet.offer())
|
||||
|
||||
def post(self, f: dict) -> str:
|
||||
fl, do = self.fleet, f.get("do", "")
|
||||
|
||||
def show(err="", ok="", **kw):
|
||||
st, st_err = self._status()
|
||||
return page(st, st_err, fl.building_consent(), err=err, ok=ok, consent_community=fl.recipient_consent("community"),
|
||||
offer=fl.offer(), **kw)
|
||||
kind = "community" if f.get("kind") == "community" else "building"
|
||||
consent = f.get(f"consent_{kind}") == "1"
|
||||
given = {"building": f.get("consent_building") == "1", "community": f.get("consent_community") == "1"}
|
||||
try:
|
||||
if do == "restore":
|
||||
o = fl.offer()
|
||||
return show(ok=fl.answer_offer(o, f)) if o else show()
|
||||
if do == "preview":
|
||||
code = f.get("code", "").strip().upper()
|
||||
if not CODE_RE.fullmatch(code):
|
||||
return show(T("A join code has 12 letters and digits: XXXX-XXXX-XXXX."), code=code)
|
||||
return show(preview=fl.ask({"op": "preview", "code": code}), code=code)
|
||||
if do == "join":
|
||||
fl.apply(fl.ask({"op": "join", "code": f.get("code", "")[:20], "meter_point": f.get("meter_point", "")[:64],
|
||||
"rules_digest": f.get("rules_digest", "")[:80], "consent": given}))
|
||||
fl.set_recipient_consent(kind, consent)
|
||||
return show(ok=T("Welcome: your home is a member of the community now.") if kind == "community"
|
||||
else T("Welcome: your flat is a member now."))
|
||||
if do == "find":
|
||||
loc = self.location()
|
||||
if loc is None:
|
||||
return show(T("Home Assistant has no home location (Settings, System, General)."))
|
||||
out = fl.ask({"op": "nearby", "lat": loc[0], "lon": loc[1]})
|
||||
return show(found=out.get("buildings") or [])
|
||||
if do == "request":
|
||||
b = f.get("building", "")
|
||||
if not UUID_RE.fullmatch(b):
|
||||
return show(T("Which building or community?"))
|
||||
fl.apply(fl.ask({"op": "request", "building": b, "via": "address", "unit_hint": f.get("unit_hint", "")[:40],
|
||||
"note": f.get("note", "")[:300], "rules_digest": f.get("rules_digest", "")[:80],
|
||||
"consent": given}))
|
||||
fl.set_recipient_consent(kind, consent)
|
||||
return show(ok=T("Asked. The community's operator decides; this page shows the answer.") if kind == "community"
|
||||
else T("Asked. The building's operator decides; this page shows the answer."))
|
||||
if do == "cancel":
|
||||
fl.apply(fl.ask({"op": "cancel", "request": f.get("request", "")[:64]}))
|
||||
return show(ok=T("Your request was withdrawn."))
|
||||
if do == "leave":
|
||||
if f.get("sure") != "1":
|
||||
return show(T("Tick the box to leave."))
|
||||
fl.apply(fl.ask({"op": "leave", "building": f.get("building", "")[:64]}))
|
||||
return show(ok=T("You left."))
|
||||
except Fail as e:
|
||||
return show(str(e), code=f.get("code", ""))
|
||||
return show()
|
||||
|
||||
async def respond(self, method: str, url, hdr: dict, data: bytes, peer: str) -> tuple[int, str]:
|
||||
"""(status, page) for a request from HA's ingress (the add-on's
|
||||
pages: devpage.App)."""
|
||||
if method == "GET" and url.path in ("/", ""):
|
||||
return 200, await asyncio.to_thread(self.get, urllib.parse.parse_qs(url.query))
|
||||
if method == "POST" and url.path in ("/", ""):
|
||||
f = {k: v[0] for k, v in urllib.parse.parse_qs(data.decode("utf-8", "replace")).items()}
|
||||
return 200, await asyncio.to_thread(self.post, f)
|
||||
return 404, T("Not found")
|
||||
|
||||
async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
|
||||
peer = (writer.get_extra_info("peername") or ("",))[0]
|
||||
try:
|
||||
head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), 10)
|
||||
lines = head.decode("latin-1").split("\r\n")
|
||||
method, target = lines[0].split(" ")[:2]
|
||||
hdr = {k.strip().lower(): v.strip() for k, _, v in (ln.partition(":") for ln in lines[1:] if ln)}
|
||||
n = int(hdr.get("content-length") or 0)
|
||||
if n > 16384:
|
||||
raise ValueError("too large")
|
||||
data = await asyncio.wait_for(reader.readexactly(n), 10) if n else b""
|
||||
except (asyncio.TimeoutError, asyncio.IncompleteReadError, asyncio.LimitOverrunError, ValueError):
|
||||
writer.close()
|
||||
return
|
||||
url = urllib.parse.urlsplit(target)
|
||||
# the browser's language (HA's ingress passes the header on); this
|
||||
# task's context, carried into to_thread
|
||||
i18n.use(i18n.from_accept(hdr.get("accept-language")) or i18n.DEFAULT)
|
||||
if peer not in INGRESS_PEERS:
|
||||
status, out = 403, T("Open this page from Home Assistant.")
|
||||
else:
|
||||
status, out = await self.respond(method, url, hdr, data, peer)
|
||||
body = out.encode()
|
||||
ctype = "text/html; charset=utf-8" if status == 200 else "text/plain; charset=utf-8"
|
||||
writer.write(f"HTTP/1.1 {status} {'OK' if status == 200 else 'Error'}\r\nContent-Type: {ctype}\r\n"
|
||||
f"Content-Length: {len(body)}\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n"
|
||||
"Referrer-Policy: same-origin\r\nConnection: close\r\n\r\n".encode() + body)
|
||||
try:
|
||||
await writer.drain()
|
||||
finally:
|
||||
writer.close()
|
||||
|
||||
async def sync(self):
|
||||
try:
|
||||
await asyncio.to_thread(lambda: self.fleet.apply(self.fleet.ask({"op": "status"})))
|
||||
except Fail as e:
|
||||
log.info("building status: %s", e)
|
||||
|
||||
async def run(self, port: int, stop: asyncio.Event):
|
||||
server = await asyncio.start_server(self.handle, "0.0.0.0", port)
|
||||
log.info("building page on :%d (HA ingress)", port)
|
||||
try:
|
||||
while not stop.is_set():
|
||||
await self.sync()
|
||||
try:
|
||||
await asyncio.wait_for(stop.wait(), SYNC_S)
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
finally:
|
||||
server.close()
|
||||
@@ -0,0 +1,82 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Hard floors and limits, layered by who set them: every controlled value has a floor and a limit per level, and
|
||||
the edge enforces the effective one.
|
||||
|
||||
Levels, and who wins when a floor and a limit cross (higher rank wins):
|
||||
grid government / network operator (§14a): over everything 5
|
||||
owner the landlord: the comfort floor, the owner's limits 4
|
||||
building the building's coordinator 3
|
||||
cloud Cantabile's platform 2
|
||||
inhabitant the tenant: may raise the floor within the owner's limits 1
|
||||
|
||||
So a building limit never pushes a value below the owner's floor, a tenant's
|
||||
raised floor gives way to the owner's limit and to the building, and the
|
||||
grid operator's word overrides all. On top of all of them the device's own
|
||||
range (firmware safety: nothing disables it).
|
||||
|
||||
Quantities: temp_c (a room), soc_pct (a battery), power_w (a battery's or
|
||||
charger's power), current_a (an EV charger), position_pct (a cover).
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
|
||||
LEVELS = ("inhabitant", "cloud", "building", "owner", "grid")
|
||||
RANK = {lvl: i + 1 for i, lvl in enumerate(LEVELS)}
|
||||
QUANTITIES = ("temp_c", "soc_pct", "power_w", "current_a", "position_pct")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Bounds:
|
||||
lo: float
|
||||
hi: float
|
||||
lo_by: str # who set the effective floor ("device" if nobody)
|
||||
hi_by: str
|
||||
|
||||
def holds(self, v: float) -> bool:
|
||||
return self.lo - 1e-9 <= v <= self.hi + 1e-9
|
||||
|
||||
def clamp(self, v: float) -> float:
|
||||
return min(max(v, self.lo), self.hi)
|
||||
|
||||
|
||||
def parse(raw: dict | None) -> dict[str, dict[str, tuple[float | None, float | None]]]:
|
||||
"""{"temp_c": {"owner": [19, 26], "inhabitant": [21, null]}} -> checked."""
|
||||
out = {}
|
||||
for q, levels in (raw or {}).items():
|
||||
if q not in QUANTITIES:
|
||||
raise ValueError(f"limits: unknown quantity {q}")
|
||||
out[q] = {}
|
||||
for lvl, pair in (levels or {}).items():
|
||||
if lvl not in RANK:
|
||||
raise ValueError(f"limits: unknown level {lvl} (one of {', '.join(LEVELS)})")
|
||||
if not isinstance(pair, (list, tuple)) or len(pair) != 2:
|
||||
raise ValueError(f"limits {q}.{lvl}: [floor, limit] (either may be null)")
|
||||
lo, hi = (None if x is None else float(x) for x in pair)
|
||||
if lo is not None and hi is not None and lo > hi:
|
||||
raise ValueError(f"limits {q}.{lvl}: floor {lo} above limit {hi}")
|
||||
out[q][lvl] = (lo, hi)
|
||||
return out
|
||||
|
||||
|
||||
def effective(device: tuple[float, float], layers: dict[str, tuple[float | None, float | None]]) -> Bounds:
|
||||
"""The bounds that hold: the highest floor and the lowest limit; where
|
||||
they cross, the level with the higher rank wins; always inside the
|
||||
device's own range."""
|
||||
lo, lo_by, hi, hi_by = device[0], "device", device[1], "device"
|
||||
for lvl, (f, c) in layers.items():
|
||||
if f is not None and f > lo:
|
||||
lo, lo_by = f, lvl
|
||||
if c is not None and c < hi:
|
||||
hi, hi_by = c, lvl
|
||||
if lo > hi:
|
||||
if RANK.get(lo_by, 0) >= RANK.get(hi_by, 0):
|
||||
hi, hi_by = lo, lo_by
|
||||
else:
|
||||
lo, lo_by = hi, hi_by
|
||||
# the device's own range over every level (a floor above the device's
|
||||
# maximum becomes that maximum)
|
||||
d0, d1 = device
|
||||
if not d0 <= lo <= d1:
|
||||
lo, lo_by = min(max(lo, d0), d1), "device"
|
||||
if not d0 <= hi <= d1:
|
||||
hi, hi_by = min(max(hi, d0), d1), "device"
|
||||
return Bounds(lo, hi, lo_by, hi_by)
|
||||
@@ -0,0 +1,336 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Semantic mapping: HA entity -> Cantabile asset and role.
|
||||
|
||||
The mapping is a versioned YAML file an installer confirms. Only assets
|
||||
with consent: true ever leave the site, and only under their asset id
|
||||
(never the HA entity id or its friendly name). Values are converted to the
|
||||
canonical unit of their quantity: power W, energy Wh, temperature °C.
|
||||
|
||||
Devices added in the box's panel (Devices, from a device profile:
|
||||
/usr/lib/cantabile/devices) each bring a fragment next to the
|
||||
mapping: <mapping dir>/mapping.d/<device>.yaml, with assets, controls and
|
||||
inputs like the mapping's own. The mapping's own entries win: an entity or
|
||||
id it has already is left out of a fragment, and a fragment that does not
|
||||
parse is left out whole (logged), so one device cannot stop the agent.
|
||||
An asset's scale (default 1) multiplies its value after the unit's
|
||||
conversion: -1 for a device that counts the other way (a meter reading
|
||||
export as +, where Cantabile's grid power is import +).
|
||||
|
||||
Several devices of one kind (two inverters, two batteries, three chargers)
|
||||
are parts with an index: <system>.<n>.<quantity> (pv.1.power, pv.2.power,
|
||||
battery.1.soc). Their total (pv.power) is derived by the agent (sum; the
|
||||
mean for % and °C) and sent like a mapped value, so the cloud, the building
|
||||
and the optimiser read totals as before; a total mapped itself is never
|
||||
derived. Fragments of two or more devices with the same system (two
|
||||
inverters' pv.power) are indexed in fragment order (pv.1.power from the
|
||||
first file, pv.2.power from the second). A mapping without parts reads as
|
||||
before.
|
||||
|
||||
An asset may read one of the entity's attributes instead of its state
|
||||
(`attribute`, e.g. a climate's current_temperature, in HA's units: the
|
||||
asset's own unit), and with `equals` it is 1 while that value (state or
|
||||
attribute) is the given text and 0 otherwise: heating.state and
|
||||
cooling.state from a climate's hvac_action. One entity may feed several
|
||||
assets this way.
|
||||
|
||||
`assumed: true` marks a reading of a device that does not report back
|
||||
(HA's assumed state: an infrared thermostat, ESPHome's climate_ir): its
|
||||
value is what Home Assistant last sent, not measured (heating.state from
|
||||
the thermostat's mode, not its hvac_action). It is read and sent like any
|
||||
other value, flagged in the inventory; nothing may take it as feedback.
|
||||
"""
|
||||
import glob
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import yaml
|
||||
|
||||
from . import controls as controls_mod
|
||||
from .devprofiles import PART_RE, SUMMED, part_of # noqa: F401
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# unit -> (canonical unit, factor)
|
||||
UNITS = {
|
||||
"W": ("W", 1.0), "kW": ("W", 1e3), "MW": ("W", 1e6),
|
||||
"Wh": ("Wh", 1.0), "kWh": ("Wh", 1e3), "MWh": ("Wh", 1e6),
|
||||
"°C": ("°C", 1.0), "%": ("%", 1.0), "V": ("V", 1.0), "A": ("A", 1.0),
|
||||
"Hz": ("Hz", 1.0), "lx": ("lx", 1.0), "ppm": ("ppm", 1.0),
|
||||
}
|
||||
ROLE = {"power": "power", "energy": "energy", "temperature": "temp", "humidity": "humidity",
|
||||
"battery": "soc", "voltage": "voltage", "current": "current", "frequency": "frequency",
|
||||
"illuminance": "illuminance", "carbon_dioxide": "co2"}
|
||||
# Words in an entity's name that say which part of the system it measures.
|
||||
SYSTEMS = [("pv", ("pv", "solar", "photovoltaic")), ("battery", ("battery", "batt")),
|
||||
("grid", ("grid", "import", "export", "feed")), ("load", ("load", "consumption")),
|
||||
("heatpump", ("heat pump", "heatpump", "boiler", "combi")), ("ev", ("wallbox", "charger", "ev "))]
|
||||
|
||||
|
||||
# Systems whose quantities may come in parts: <system>.<n>.<quantity>
|
||||
# (part_of: pv.2.power -> ("pv.power", 2); devprofiles.py, shared with the Hub)
|
||||
MEAN_UNITS = ("%", "°C")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Total:
|
||||
"""A total derived from its parts' values (pv.power from pv.1.power, ...)."""
|
||||
asset: str
|
||||
parts: list[str]
|
||||
kind: str
|
||||
unit: str
|
||||
mean: bool = False
|
||||
entities: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Asset:
|
||||
entity: str
|
||||
asset: str
|
||||
kind: str # gauge (a level) | counter (a growing total)
|
||||
unit: str
|
||||
consent: bool = False
|
||||
scale: float = 1.0
|
||||
attribute: str = "" # read this attribute, not the state
|
||||
equals: str = "" # 1 while the value is this text, else 0
|
||||
assumed: bool = False # the device does not report back: what HA last sent, not measured
|
||||
fallback: bool = False # a stand-in (the weather service's outside.temp): a measured one takes its id
|
||||
|
||||
|
||||
class Mapping:
|
||||
"""v1/v2: assets to read. v3 adds `controls` (what the agent may act on,
|
||||
each with its own consent: controls.py) and `inputs` (sensors the
|
||||
optimiser reads, which never leave the site)."""
|
||||
|
||||
def __init__(self, version: int, assets: list[Asset], controls: list | None = None, inputs=None):
|
||||
self.version = version
|
||||
self.assets = assets
|
||||
self.by_entity = {} # entity -> its first asset
|
||||
self.of_entity: dict[str, list[Asset]] = {}
|
||||
for a in assets:
|
||||
self.by_entity.setdefault(a.entity, a)
|
||||
self.of_entity.setdefault(a.entity, []).append(a)
|
||||
self.by_asset = {a.asset: a for a in assets}
|
||||
self.controls = shared_writers(controls or [])
|
||||
self.inputs = inputs or controls_mod.Inputs()
|
||||
self.totals: dict[str, Total] = {}
|
||||
for a in assets:
|
||||
t = part_of(a.asset)
|
||||
if t and t[0] not in self.by_asset:
|
||||
tot = self.totals.setdefault(t[0], Total(t[0], [], a.kind, a.unit, a.unit in MEAN_UNITS))
|
||||
tot.parts.append(a.asset)
|
||||
tot.entities.append(a.entity)
|
||||
self.part_total = {p: t.asset for t in self.totals.values() for p in t.parts}
|
||||
# the optimiser's load and PV (history fallback): the parts' sum when
|
||||
# the mapping has parts and does not name them itself
|
||||
for key, total in (("pv_power", "pv.power"), ("load_power", "load.power")):
|
||||
if not getattr(self.inputs, key) and total in self.totals:
|
||||
setattr(self.inputs, key, list(self.totals[total].entities))
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: str) -> "Mapping":
|
||||
with open(path) as f:
|
||||
raw = yaml.safe_load(f) or {}
|
||||
assets = _assets(raw.get("assets", []))
|
||||
seen = {a.asset for a in assets}
|
||||
inputs = dict(raw.get("inputs") or {})
|
||||
version = int(raw.get("version", 1))
|
||||
frags = []
|
||||
for frag in sorted(glob.glob(os.path.join(os.path.dirname(path) or ".", "mapping.d", "*.yaml"))):
|
||||
try:
|
||||
with open(frag) as f:
|
||||
fr = yaml.safe_load(f) or {}
|
||||
if not isinstance(fr, dict) or not isinstance(fr.get("assets") or [], list):
|
||||
raise ValueError("not a mapping fragment")
|
||||
except (OSError, ValueError, yaml.YAMLError) as e:
|
||||
log.warning("%s left out: %s", frag, e)
|
||||
continue
|
||||
frags.append((frag, fr))
|
||||
index_fragments([fr for _, fr in frags])
|
||||
# the site's rooms (heating and cooling controls): a cover in one
|
||||
# device's fragment may shade a room another device heats
|
||||
rooms = {str(c.get("id")) for _, fr in frags for c in fr.get("controls") or []
|
||||
if isinstance(c, dict) and c.get("kind") in ("heating", "cooling")}
|
||||
controls = controls_mod.parse(raw.get("controls"), seen, rooms)
|
||||
rooms |= {c.id for c in controls if c.kind in ("heating", "cooling")}
|
||||
for frag, fr in frags:
|
||||
try:
|
||||
entities = {a.entity for a in assets}
|
||||
ids = seen | {c.id for c in controls}
|
||||
new = [a for a in _assets(fr.get("assets", [])) if a.entity not in entities and a.asset not in ids]
|
||||
new_ids = {a.asset for a in new}
|
||||
new_controls = [c for c in controls_mod.parse(fr.get("controls"), new_ids, rooms, strict=False)
|
||||
if c.id not in ids and c.id not in new_ids]
|
||||
for c in new_controls:
|
||||
c.device = str(fr.get("device") or "")
|
||||
for k, v in (fr.get("inputs") or {}).items():
|
||||
if k == "outside_temp" and fr.get("profile") == "ha-climate-sensor":
|
||||
# the owner's outdoor thermometer: over a helper or the weather's
|
||||
if inputs.get(k) and inputs[k] != v:
|
||||
log.info("inputs.outside_temp: %s (an outdoor sensor) over %s", v, inputs[k])
|
||||
inputs[k] = v
|
||||
continue
|
||||
if isinstance(inputs.get(k), list) or isinstance(v, list):
|
||||
have = inputs.get(k) or []
|
||||
have = [have] if isinstance(have, str) else list(have)
|
||||
inputs[k] = have + [x for x in ([v] if isinstance(v, str) else v) if x not in have]
|
||||
elif not inputs.get(k):
|
||||
inputs[k] = v
|
||||
controls_mod.parse_inputs(inputs)
|
||||
except (OSError, ValueError, TypeError, yaml.YAMLError) as e:
|
||||
log.warning("%s left out: %s", frag, e)
|
||||
continue
|
||||
assets += new
|
||||
seen |= new_ids
|
||||
controls += new_controls
|
||||
version = max(version, int(fr.get("version", 1)))
|
||||
prefer_measured(assets)
|
||||
return cls(version, assets, controls, controls_mod.parse_inputs(inputs))
|
||||
|
||||
def consented(self, entity_id: str) -> Asset | None:
|
||||
a = self.by_entity.get(entity_id)
|
||||
return a if a and a.consent else None
|
||||
|
||||
def consented_all(self, entity_id: str) -> list[Asset]:
|
||||
"""Every consented asset the entity feeds (its state, attributes)."""
|
||||
return [a for a in self.of_entity.get(entity_id, []) if a.consent]
|
||||
|
||||
|
||||
def prefer_measured(assets: list) -> None:
|
||||
"""A stand-in (fallback: the weather service's outside.temp) gives its id
|
||||
to a measured value of the same quantity (outside.temp_2 of an outdoor
|
||||
thermometer): the dashboards, the cloud and the optimiser read the
|
||||
measured one as outside.temp. In place."""
|
||||
groups: dict[str, list] = {}
|
||||
for a in assets:
|
||||
groups.setdefault(re.sub(r"_\d+$", "", a.asset), []).append(a)
|
||||
for base, group in groups.items():
|
||||
holder = next((a for a in group if a.asset == base), None)
|
||||
real = next((a for a in group if not a.fallback), None)
|
||||
if holder is not None and holder.fallback and real is not None:
|
||||
holder.asset, real.asset = real.asset, base
|
||||
|
||||
|
||||
def shared_writers(controls: list) -> list:
|
||||
"""Two controls never write one entity: a later one that would is left
|
||||
out, unless it and the one before are a heating and a cooling control on
|
||||
one climate, both with `switchover` (only one of them acts at a time:
|
||||
switchover.py)."""
|
||||
out, writers = [], {}
|
||||
|
||||
def pair(c, o):
|
||||
return set(c.writable()) == {"climate"} == set(o.writable()) and bool(c.switchover) and bool(o.switchover) \
|
||||
and {c.kind, o.kind} == {"heating", "cooling"}
|
||||
for c in controls:
|
||||
clash = {e: writers[e] for e in c.writable().values() if e in writers}
|
||||
if clash and not all(len(ws) == 1 and pair(c, ws[0]) for ws in clash.values()):
|
||||
log.warning("control %s left out: %s is written by %s already", c.id, ", ".join(clash),
|
||||
", ".join(sorted({o.id for ws in clash.values() for o in ws})))
|
||||
continue
|
||||
for e in c.writable().values():
|
||||
writers.setdefault(e, []).append(c)
|
||||
out.append(c)
|
||||
return out
|
||||
|
||||
|
||||
def index_fragments(frags: list[dict]):
|
||||
"""Two or more devices' fragments with the same system (pv.power from two
|
||||
inverters): each one's quantities of that system become parts, numbered
|
||||
in fragment order (pv.1.power, pv.1.energy; pv.2.power, ...). In place."""
|
||||
def systems(fr):
|
||||
return {a["asset"].split(".")[0] for a in fr.get("assets") or []
|
||||
if isinstance(a, dict) and str(a.get("asset", "")).count(".") == 1
|
||||
and a["asset"].split(".")[0] in SUMMED}
|
||||
have = [systems(fr) for fr in frags]
|
||||
for system in SUMMED:
|
||||
holders = [fr for fr, s in zip(frags, have) if system in s]
|
||||
if len(holders) < 2:
|
||||
continue
|
||||
for n, fr in enumerate(holders, 1):
|
||||
for a in fr["assets"]:
|
||||
head, _, tail = str(a.get("asset", "")).partition(".")
|
||||
if head == system and "." not in tail:
|
||||
a["asset"] = f"{system}.{n}.{tail}"
|
||||
|
||||
|
||||
def _assets(raw: list) -> list[Asset]:
|
||||
assets = [Asset(**a) for a in raw or []]
|
||||
seen = set()
|
||||
for a in assets:
|
||||
if a.kind not in ("gauge", "counter"):
|
||||
raise ValueError(f"{a.entity}: kind must be gauge or counter")
|
||||
if a.asset in seen:
|
||||
raise ValueError(f"asset id {a.asset} used twice")
|
||||
if not isinstance(a.scale, (int, float)) or a.scale == 0 or (a.kind == "counter" and a.scale < 0):
|
||||
raise ValueError(f"{a.entity}: scale is a number, not 0 (a counter's above 0)")
|
||||
if not isinstance(a.attribute, str) or not isinstance(a.equals, str) or (a.equals and a.kind != "gauge"):
|
||||
raise ValueError(f"{a.entity}: attribute and equals are text; equals only on a gauge")
|
||||
if not isinstance(a.assumed, bool):
|
||||
raise ValueError(f"{a.entity}: assumed is true or false")
|
||||
seen.add(a.asset)
|
||||
return assets
|
||||
|
||||
|
||||
def value_of(a: Asset, state, attrs: dict | None):
|
||||
"""The asset's raw value from the entity's state and attributes: a
|
||||
number, or 1/0 with `equals` (None: nothing to say yet)."""
|
||||
raw = (attrs or {}).get(a.attribute) if a.attribute else state
|
||||
if a.equals:
|
||||
return None if raw in (None, "unavailable", "unknown") else (1.0 if str(raw) == a.equals else 0.0)
|
||||
return raw
|
||||
|
||||
|
||||
def scaled(value: float | None, a: Asset) -> float | None:
|
||||
return None if value is None else value * a.scale
|
||||
|
||||
|
||||
def convert(value: float, unit: str | None, target: str) -> float | None:
|
||||
"""Value in the asset's canonical unit; None when the unit cannot be
|
||||
converted (a changed sensor must not send wrong numbers)."""
|
||||
if unit == "°F" and target == "°C":
|
||||
return (value - 32) * 5 / 9
|
||||
if unit == "K" and target == "°C":
|
||||
return value - 273.15
|
||||
canon = UNITS.get(unit or "")
|
||||
if canon is None:
|
||||
return value if (unit or "") == target else None
|
||||
return value * canon[1] if canon[0] == target else None
|
||||
|
||||
|
||||
def _slug(s: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "_", s.lower()).strip("_")
|
||||
|
||||
|
||||
def suggest(states: list[dict], registries: dict) -> dict:
|
||||
"""A mapping draft from device class, unit and area, for an installer to
|
||||
confirm: everything has consent: false until they do."""
|
||||
areas = {a["area_id"]: a["name"] for a in registries.get("areas", [])}
|
||||
devices = {d["id"]: d for d in registries.get("devices", [])}
|
||||
entities = {e["entity_id"]: e for e in registries.get("entities", [])}
|
||||
out, used = [], set()
|
||||
for st in sorted(states, key=lambda s: s["entity_id"]):
|
||||
eid, attrs = st["entity_id"], st.get("attributes", {})
|
||||
if not eid.startswith("sensor."):
|
||||
continue
|
||||
dc, unit = attrs.get("device_class"), attrs.get("unit_of_measurement")
|
||||
if dc not in ROLE or unit not in UNITS and unit not in ("°F", "K"):
|
||||
continue
|
||||
reg = entities.get(eid, {})
|
||||
area_id = reg.get("area_id") or devices.get(reg.get("device_id"), {}).get("area_id")
|
||||
name = (attrs.get("friendly_name") or eid).lower()
|
||||
system = next((s for s, words in SYSTEMS if any(w in name for w in words)), None)
|
||||
role = ROLE[dc]
|
||||
if system == "grid" and dc in ("power", "energy"):
|
||||
role = ("export_" if "export" in name or "feed" in name else "import_") + role
|
||||
prefix = system or (f"room.{_slug(areas[area_id])}" if area_id in areas else "site")
|
||||
asset = f"{prefix}.{role}"
|
||||
n = 2
|
||||
while asset in used:
|
||||
asset, n = f"{prefix}.{role}_{n}", n + 1
|
||||
used.add(asset)
|
||||
counter = attrs.get("state_class") in ("total", "total_increasing")
|
||||
target = "°C" if unit in ("°F", "K") else UNITS[unit][0]
|
||||
out.append({"entity": eid, "asset": asset, "kind": "counter" if counter else "gauge",
|
||||
"unit": target, "consent": False})
|
||||
return {"version": 1, "assets": out}
|
||||
@@ -0,0 +1,128 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""A small MQTT 3.1.1 client (asyncio), for Home Assistant's MQTT discovery
|
||||
(announce.py): connect with a last will, publish (QoS 0, retained or not),
|
||||
subscribe (QoS 0), keep-alive. Nothing else is needed, so no library: the
|
||||
agent's dependencies stay three (pyproject.toml)."""
|
||||
import asyncio
|
||||
import struct
|
||||
|
||||
|
||||
class MQTTError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _str(s: str) -> bytes:
|
||||
b = s.encode()
|
||||
return struct.pack("!H", len(b)) + b
|
||||
|
||||
|
||||
def _packet(kind: int, flags: int, body: bytes) -> bytes:
|
||||
n, length = len(body), b""
|
||||
while True:
|
||||
byte, n = n % 128, n // 128
|
||||
length += bytes([byte | (0x80 if n else 0)])
|
||||
if not n:
|
||||
break
|
||||
return bytes([kind << 4 | flags]) + length + body
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, host: str, port: int, client_id: str, keepalive: int = 60,
|
||||
username: str = "", password: str = ""):
|
||||
self.host, self.port, self.client_id, self.keepalive = host, port, client_id, keepalive
|
||||
self.username, self.password = username, password # the Hub's Mosquitto wants them
|
||||
self.r = self.w = None
|
||||
self.on_message = None # callback(topic, payload bytes)
|
||||
self._pid = 0
|
||||
self._suback: dict[int, asyncio.Future] = {}
|
||||
self._tasks: list[asyncio.Task] = []
|
||||
self.closed = asyncio.Event()
|
||||
|
||||
async def connect(self, will_topic: str, will_payload: bytes, timeout: float = 10):
|
||||
self.r, self.w = await asyncio.wait_for(asyncio.open_connection(self.host, self.port), timeout)
|
||||
flags = 0x02 | 0x04 | 0x20 # clean session, will, will retained (QoS 0)
|
||||
if self.username:
|
||||
flags |= 0x80 | (0x40 if self.password else 0)
|
||||
body = _str("MQTT") + bytes([4, flags]) + struct.pack("!H", self.keepalive) + \
|
||||
_str(self.client_id) + _str(will_topic) + struct.pack("!H", len(will_payload)) + will_payload
|
||||
if self.username:
|
||||
body += _str(self.username) + (_str(self.password) if self.password else b"")
|
||||
self.w.write(_packet(1, 0, body))
|
||||
await self.w.drain()
|
||||
head = await asyncio.wait_for(self.r.readexactly(4), timeout)
|
||||
if head[0] != 0x20 or head[3] != 0:
|
||||
raise MQTTError(f"connection refused (code {head[3]})")
|
||||
self.closed.clear()
|
||||
self._tasks = [asyncio.create_task(self._read()), asyncio.create_task(self._ping())]
|
||||
|
||||
async def _read_packet(self):
|
||||
first = (await self.r.readexactly(1))[0]
|
||||
n, mult = 0, 1
|
||||
while True:
|
||||
b = (await self.r.readexactly(1))[0]
|
||||
n += (b & 0x7F) * mult
|
||||
if not b & 0x80:
|
||||
break
|
||||
mult *= 128
|
||||
if mult > 128 ** 3:
|
||||
raise MQTTError("bad length")
|
||||
return first, await self.r.readexactly(n)
|
||||
|
||||
async def _read(self):
|
||||
try:
|
||||
while True:
|
||||
first, body = await self._read_packet()
|
||||
kind = first >> 4
|
||||
if kind == 3: # PUBLISH (we subscribe at QoS 0)
|
||||
tl = struct.unpack("!H", body[:2])[0]
|
||||
topic = body[2:2 + tl].decode(errors="replace")
|
||||
start = 2 + tl + (2 if first & 0x06 else 0)
|
||||
if self.on_message:
|
||||
self.on_message(topic, body[start:])
|
||||
elif kind == 9: # SUBACK
|
||||
pid = struct.unpack("!H", body[:2])[0]
|
||||
f = self._suback.pop(pid, None)
|
||||
if f and not f.done():
|
||||
f.set_result(body[2:])
|
||||
except (asyncio.IncompleteReadError, OSError, MQTTError):
|
||||
pass
|
||||
finally:
|
||||
self.closed.set()
|
||||
|
||||
async def _ping(self):
|
||||
try:
|
||||
while True:
|
||||
await asyncio.sleep(self.keepalive / 2)
|
||||
self.w.write(_packet(12, 0, b""))
|
||||
await self.w.drain()
|
||||
except (OSError, asyncio.CancelledError):
|
||||
pass
|
||||
|
||||
async def publish(self, topic: str, payload: bytes | str, retain: bool = False):
|
||||
if isinstance(payload, str):
|
||||
payload = payload.encode()
|
||||
self.w.write(_packet(3, 0x01 if retain else 0, _str(topic) + payload))
|
||||
await self.w.drain()
|
||||
|
||||
async def subscribe(self, topic: str, timeout: float = 10):
|
||||
self._pid = self._pid % 65535 + 1
|
||||
f = asyncio.get_running_loop().create_future()
|
||||
self._suback[self._pid] = f
|
||||
self.w.write(_packet(8, 0x02, struct.pack("!H", self._pid) + _str(topic) + b"\x00"))
|
||||
await self.w.drain()
|
||||
granted = await asyncio.wait_for(f, timeout)
|
||||
if granted[:1] == b"\x80":
|
||||
raise MQTTError(f"subscription to {topic} refused")
|
||||
|
||||
async def close(self):
|
||||
for t in self._tasks:
|
||||
t.cancel()
|
||||
if self.w is not None:
|
||||
try:
|
||||
self.w.write(_packet(14, 0, b"")) # DISCONNECT: no last will
|
||||
await self.w.drain()
|
||||
self.w.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.r = self.w = None
|
||||
self.closed.set()
|
||||
@@ -0,0 +1,142 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Names the agent gives itself in Home Assistant, in HA's language (its
|
||||
configuration's `language`, chosen in the Hub's setup; on any other HA the
|
||||
owner's). Areas in every language we know of; entity names where cheap (at
|
||||
least German). Anything missing: English. The Hub's ha-setup creates the
|
||||
areas with the same names (hub/.../cantabile/ha-setup: AREAS)."""
|
||||
|
||||
AREAS = {
|
||||
"cantabile": {"en": "Cantabile"},
|
||||
"flats": {"en": "Flats", "de": "Wohnungen", "ro": "Apartamente", "ru": "Квартиры", "fr": "Appartements",
|
||||
"it": "Appartamenti", "es": "Pisos", "nl": "Appartementen"},
|
||||
}
|
||||
|
||||
NAMES = {
|
||||
"cloud": {"de": "Cloud"},
|
||||
"mode": {"de": "Modus"},
|
||||
"next_action": {"en": "Next action", "de": "Nächste Aktion"},
|
||||
"plan": {"en": "{0}: plan", "de": "{0}: Plan"},
|
||||
"price_import_now": {"en": "Electricity price now", "de": "Strompreis jetzt"},
|
||||
"price_import_next": {"en": "Electricity price next", "de": "Strompreis als Nächstes"},
|
||||
"price_export_now": {"en": "Feed-in price now", "de": "Einspeisevergütung jetzt"},
|
||||
"price_other": {"en": "{0} price", "de": "Preis {0}"},
|
||||
"model": {"en": "Forecast model", "de": "Prognosemodell"},
|
||||
"commands": {"en": "Commands received", "de": "Empfangene Befehle"},
|
||||
"commanded": {"en": "{0}: setting", "de": "{0}: Vorgabe"},
|
||||
"received": {"en": "Commands received", "de": "Empfangene Befehle"},
|
||||
# a command in words ({0} the control's name, {1} its value, {2} a mode)
|
||||
"cmd_mode": {"en": "Mode: {2}", "de": "Modus: {2}"},
|
||||
"cmd_control": {"en": "{0}: set to {1}", "de": "{0}: auf {1}"},
|
||||
"cmd_release": {"en": "{0}: back to the plan", "de": "{0}: zurück zum Plan"},
|
||||
"cmd_limits": {"en": "{0}: new limits", "de": "{0}: neue Grenzen"},
|
||||
"cmd_tariff": {"en": "New tariff", "de": "Neuer Tarif"},
|
||||
"cmd_model": {"en": "New forecast model", "de": "Neues Prognosemodell"},
|
||||
"cmd_building": {"en": "Message from the building", "de": "Nachricht vom Gebäude"},
|
||||
"flat_grid": {"en": "Grid power", "de": "Netzbezug"},
|
||||
"flat_flex": {"en": "Flexibility", "de": "Flexibilität"},
|
||||
"flat_request": {"en": "Building's request", "de": "Anfrage des Gebäudes"},
|
||||
"flat_state": {"en": "State", "de": "Zustand"},
|
||||
# dashboards (dashboards.py)
|
||||
"dash_main": {"en": "Cantabile"},
|
||||
"dash_climate": {"en": "Heating & cooling", "de": "Heizung & Kühlung"},
|
||||
"card_plan": {"en": "Plan, next 48 h", "de": "Plan, nächste 48 h"},
|
||||
"card_prices": {"en": "Prices, next 48 h (ct/kWh)", "de": "Preise, nächste 48 h (ct/kWh)"},
|
||||
"card_devices": {"en": "What Cantabile sets", "de": "Was Cantabile vorgibt"},
|
||||
"card_power": {"en": "Power", "de": "Leistung"},
|
||||
"card_price": {"en": "Electricity price", "de": "Strompreis"},
|
||||
"card_daily": {"en": "Energy per day", "de": "Energie pro Tag"},
|
||||
"card_monthly": {"en": "Energy per month", "de": "Energie pro Monat"},
|
||||
"card_rooms": {"en": "Rooms", "de": "Räume"},
|
||||
"assumed_hint": {"en": "This thermostat does not report back (infrared): what it shows is what was last sent to "
|
||||
"it, not measured.",
|
||||
"de": "Dieses Thermostat meldet nichts zurück (Infrarot): Angezeigt wird, was zuletzt gesendet "
|
||||
"wurde, nicht gemessen."},
|
||||
"source": {"en": "{0}: from", "de": "{0}: von"},
|
||||
# the dashboard's views (dashboards.py)
|
||||
"view_energy": {"en": "Energy", "de": "Energie"},
|
||||
"view_building": {"en": "Building", "de": "Gebäude"},
|
||||
"devices_page": {"en": "Devices: use Home Assistant's devices with Cantabile",
|
||||
"de": "Geräte: Geräte aus Home Assistant mit Cantabile nutzen"},
|
||||
"card_cloud": {"en": "Cantabile Cloud", "de": "Cantabile Cloud"},
|
||||
"mode_off": {"en": "Off", "de": "Aus"},
|
||||
"mode_off_why": {"en": "Cantabile does not read your home.", "de": "Cantabile liest Ihr Zuhause nicht."},
|
||||
"mode_shadow": {"en": "Watching", "de": "Beobachten"},
|
||||
"mode_shadow_why": {"en": "Cantabile follows your home and changes nothing.",
|
||||
"de": "Cantabile verfolgt Ihr Zuhause und verändert nichts."},
|
||||
"mode_advisory": {"en": "Advising", "de": "Beraten"},
|
||||
"mode_advisory_why": {"en": "Cantabile plans and suggests; you decide.",
|
||||
"de": "Cantabile plant und schlägt vor; Sie entscheiden."},
|
||||
"mode_auto": {"en": "Automatic", "de": "Automatisch"},
|
||||
"mode_auto_why": {"en": "Cantabile runs the devices you allowed.",
|
||||
"de": "Cantabile steuert die Geräte, die Sie freigegeben haben."},
|
||||
"now": {"en": "Now", "de": "Jetzt"},
|
||||
"today": {"en": "Today", "de": "Heute"},
|
||||
"solar": {"en": "Solar", "de": "Solar"},
|
||||
"home": {"en": "Home", "de": "Haus"},
|
||||
"grid": {"en": "Grid", "de": "Netz"},
|
||||
"feed_in": {"en": "Feed-in", "de": "Einspeisung"},
|
||||
"battery": {"en": "Battery", "de": "Batterie"},
|
||||
"battery_soc": {"en": "Battery charge", "de": "Batterieladung"},
|
||||
"battery_in": {"en": "Battery charged", "de": "Batterie geladen"},
|
||||
"battery_out": {"en": "Battery discharged", "de": "Batterie entladen"},
|
||||
"from_grid": {"en": "From the grid", "de": "Aus dem Netz"},
|
||||
"to_grid": {"en": "To the grid", "de": "Ins Netz"},
|
||||
"heat_pump": {"en": "Heat pump", "de": "Wärmepumpe"},
|
||||
"ev": {"en": "Car", "de": "Auto"},
|
||||
"circuits": {"en": "Circuits", "de": "Stromkreise"},
|
||||
"of": {"en": "of", "de": "von"},
|
||||
"total": {"en": "Total", "de": "Gesamt"},
|
||||
"values": {"en": "Values", "de": "Werte"},
|
||||
"switched_on": {"en": "switched on", "de": "eingeschaltet"},
|
||||
"member_of": {"en": "Member of **{0}**, unit {1}.", "de": "Mitglied von **{0}**, Einheit {1}."},
|
||||
"community_of": {"en": "Member of the community **{0}**.", "de": "Mitglied der Gemeinschaft **{0}**."},
|
||||
"request_to": {"en": "Asked to join **{0}**: waiting for the operator.",
|
||||
"de": "Beitritt zu **{0}** angefragt: wartet auf den Betreiber."},
|
||||
"devices": {"en": "Devices", "de": "Geräte"},
|
||||
"fan": {"en": "fan", "de": "Lüfter"},
|
||||
"price_now": {"en": "Electricity now", "de": "Strom jetzt"},
|
||||
"feed_in_now": {"en": "feed-in", "de": "Einspeisung"},
|
||||
"cheapest": {"en": "Next 24 h: cheapest", "de": "Nächste 24 h: am günstigsten"},
|
||||
"dearest": {"en": "dearest", "de": "am teuersten"},
|
||||
"kind_heating": {"en": "heating", "de": "Heizen"},
|
||||
"kind_cooling": {"en": "cooling", "de": "Kühlen"},
|
||||
"coming": {"en": "Coming up", "de": "Als Nächstes"},
|
||||
"nothing_planned": {"en": "Nothing planned.", "de": "Nichts geplant."},
|
||||
"sets_release": {"en": "not controlling: your own settings apply",
|
||||
"de": "keine Vorgabe: Ihre eigenen Einstellungen gelten"},
|
||||
"your_settings": {"en": "your own settings", "de": "Ihre eigenen Einstellungen"},
|
||||
"sets_holds": {"en": "holds", "de": "hält"},
|
||||
"from_plan": {"en": "Following the plan.", "de": "Nach Plan."},
|
||||
"from_cloud": {"en": "Asked by Cantabile Cloud.", "de": "Von der Cantabile Cloud angefragt."},
|
||||
"from_building": {"en": "Asked by the building.", "de": "Vom Gebäude angefragt."},
|
||||
"from_owner": {"en": "You changed it by hand: Cantabile waits.",
|
||||
"de": "Von Ihnen von Hand geändert: Cantabile wartet."},
|
||||
"from_safe_default": {"en": "No current plan: your own settings until there is one.",
|
||||
"de": "Kein aktueller Plan: bis dahin Ihre eigenen Einstellungen."},
|
||||
"by_cloud": {"en": "Cantabile Cloud", "de": "Cantabile Cloud"},
|
||||
"by_building": {"en": "Building", "de": "Gebäude"},
|
||||
"by_grid": {"en": "Grid operator", "de": "Netzbetreiber"},
|
||||
"by_console": {"en": "Console", "de": "Konsole"},
|
||||
"what": {"en": "What", "de": "Was"},
|
||||
"from": {"en": "From", "de": "Von"},
|
||||
"time": {"en": "Time", "de": "Zeit"},
|
||||
"control": {"en": "Control", "de": "Gerät"},
|
||||
"value": {"en": "Value", "de": "Wert"},
|
||||
"why": {"en": "Why", "de": "Warum"},
|
||||
}
|
||||
|
||||
|
||||
def lang(code: str | None) -> str:
|
||||
"""HA's language ("de", "de-CH", "pt-BR") as our two-letter key."""
|
||||
return (code or "en").split("-")[0].split("_")[0].lower() or "en"
|
||||
|
||||
|
||||
def area(key: str, language: str | None) -> str:
|
||||
t = AREAS[key]
|
||||
return t.get(lang(language)) or t["en"]
|
||||
|
||||
|
||||
def name(key: str, language: str | None, *args) -> str:
|
||||
t = NAMES[key]
|
||||
text = t.get(lang(language)) or t.get("en") or key.replace("_", " ").capitalize()
|
||||
return text.format(*args)
|
||||
@@ -0,0 +1,490 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The plan: a MILP over the next 48 h in 15-minute steps (HiGHS), re-made
|
||||
every 15 minutes in a subprocess with a time limit (controller.py):
|
||||
|
||||
python -m cantabile_edge.optimizer < state.json > plan.json
|
||||
|
||||
Objective: the grid's cost (the tariff's import and export prices) plus
|
||||
penalties for comfort the plan gives up and for the floors and limits it
|
||||
would cross. Floors and limits are soft here, with a penalty far above any
|
||||
price, so there is always a plan (a room already below its floor must be
|
||||
able to come back); the executor's guard enforces them hard on every action.
|
||||
|
||||
Device models (one function each, small and replaceable):
|
||||
battery state of charge (estimated from params.soc_pct when no sensor),
|
||||
charge/discharge power, efficiency, never both at once (binary)
|
||||
heating a room's first-order thermal model (R in K/kW, C in kWh/K, the
|
||||
cooling outside temperature, heat from the device and from the sun
|
||||
through the room's covers); comfort target when occupied,
|
||||
setback/setup otherwise; a switched boiler is on/off (binary)
|
||||
ev the energy needed by the departure time, between min and max
|
||||
current (binary), only while connected
|
||||
cover the share of the sun's heat into its room (0 closed .. 1 open);
|
||||
a small penalty for closing it while someone is home in daylight.
|
||||
With a schedule (shades.py: rules on the sun on its facade, the
|
||||
season, quiet hours) its positions are fixed to it and its plan
|
||||
entries are the schedule's moves
|
||||
|
||||
The grid operator's limit (gridorder.py, state["grid_order"]: §14a through
|
||||
the EEBUS bridge): the controllable consumers may draw at most
|
||||
limit_w from the grid beyond the household's own net load, i.e. the import
|
||||
at most max(0, load - pv) + limit_w per step, with a penalty far above any
|
||||
building request (nobody overrides it).
|
||||
|
||||
The building's requests (building.py, state["building"]): a load limit on
|
||||
the grid import and a thermostat cap are constraints with a penalty (binding
|
||||
far above any price, flexible with a price), a shift request a soft target
|
||||
(the window's import lowered by its kWh against the house's own net load).
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import highspy
|
||||
from highspy.highs import highs_linear_expression as Lin
|
||||
|
||||
PENALTY_LIMIT = 5.0 # EUR per unit and step across a floor or limit (K, % of a battery, kWh)
|
||||
COMFORT_EUR_KH = 2.0 # EUR per K and hour below (heating) or above (cooling) the comfort target
|
||||
# while someone is home: above any price (0.30 let a room cool by 1.3 K
|
||||
# at a 40 ct peak); pre-heating in cheap hours still pays
|
||||
EV_SHORT_EUR_KWH = 1.0 # EUR per kWh the car lacks at departure
|
||||
LIGHT_EUR = 0.002 # EUR per step for a closed cover while someone is home in daylight
|
||||
CHANGE_EUR_KW = 0.002 # EUR per kW a device's power changes from one step to the next: smooth
|
||||
# plans (equal prices would otherwise give any order, and a charger or
|
||||
# boiler must not be switched back and forth)
|
||||
CLOSED_EUR = 0.00002 # EUR per step for a closed cover: open when nothing is at stake
|
||||
|
||||
|
||||
class Model:
|
||||
def __init__(self, s: dict):
|
||||
self.s = s
|
||||
self.T, self.dt = s["steps"], s["step_s"] / 3600.0
|
||||
self.h = highspy.Highs()
|
||||
self.h.setOptionValue("output_flag", False)
|
||||
self.flows = [[] for _ in range(self.T)] # (+1 into the house's balance | -1 out of it, var)
|
||||
self.cost = [] # (coef, var)
|
||||
self.devices = {} # id -> (kind, vars for the plan)
|
||||
|
||||
def var(self, lo=0.0, hi=highspy.kHighsInf, cost=0.0, integer=False):
|
||||
v = self.h.addVariable(lb=lo, ub=hi, type=highspy.HighsVarType.kInteger if integer else
|
||||
highspy.HighsVarType.kContinuous)
|
||||
if cost:
|
||||
self.cost.append((cost, v))
|
||||
return v
|
||||
|
||||
def smooth(self, series):
|
||||
"""The cost of every change in a power series (W variables or
|
||||
expressions), |p[t] - p[t-1]|."""
|
||||
for a, b in zip(series, series[1:]):
|
||||
d = self.var(cost=CHANGE_EUR_KW / 1000.0)
|
||||
self.h.addConstr(d - b + a >= 0)
|
||||
self.h.addConstr(d + b - a >= 0)
|
||||
|
||||
def eur_wh(self, t: int, price_ct: float) -> float:
|
||||
"""EUR for one W held for one step at this price."""
|
||||
return self.dt / 1000.0 * price_ct / 100.0
|
||||
|
||||
# -- the house -------------------------------------------------------
|
||||
def grid(self):
|
||||
s = self.s
|
||||
self.gin, self.gout = [], []
|
||||
for t in range(self.T):
|
||||
gi = self.var(cost=self.eur_wh(t, s["price_import"][t]))
|
||||
go = self.var(cost=-self.eur_wh(t, s["price_export"][t]))
|
||||
spill = self.var(0.0, max(0.0, s["pv_w"][t]))
|
||||
self.gin.append(gi)
|
||||
self.gout.append(go)
|
||||
self.flows[t] += [(1, gi), (-1, go), (-1, spill)]
|
||||
|
||||
def building(self):
|
||||
"""The building's load limit and shift request (on the grid import)."""
|
||||
req = self.s.get("building") or {}
|
||||
lim = req.get("load_limit")
|
||||
if lim:
|
||||
for t in range(lim["from_step"], lim["to_step"]):
|
||||
over = self.var(cost=lim["penalty"] * self.dt / 1000.0)
|
||||
self.h.addConstr(self.gin[t] - over <= lim["value"])
|
||||
sh = req.get("shift_request")
|
||||
if sh:
|
||||
a, b = sh["from_step"], sh["to_step"]
|
||||
base = sum(max(0.0, self.s["load_w"][t] - self.s["pv_w"][t]) * self.dt for t in range(a, b))
|
||||
target = max(0.0, base - sh["value"] * 1000.0)
|
||||
miss = self.var(cost=sh["penalty"] / 1000.0)
|
||||
imp = sum((self.dt * self.gin[t] for t in range(a, b)), start=Lin())
|
||||
self.h.addConstr(imp - miss <= target)
|
||||
|
||||
def grid_order(self):
|
||||
"""The grid operator's limit on the controllable consumers' draw."""
|
||||
o = self.s.get("grid_order") or {}
|
||||
if not o:
|
||||
return
|
||||
for t in range(o["from_step"], min(o["to_step"], self.T)):
|
||||
base = max(0.0, self.s["load_w"][t] - self.s["pv_w"][t])
|
||||
over = self.var(cost=o["penalty"] * self.dt / 1000.0)
|
||||
self.h.addConstr(self.gin[t] - over <= base + o["limit_w"])
|
||||
|
||||
def balance(self):
|
||||
s = self.s
|
||||
for t in range(self.T):
|
||||
expr = sum((sign * v for sign, v in self.flows[t]), start=Lin())
|
||||
self.h.addConstr(expr == s["load_w"][t] - s["pv_w"][t])
|
||||
|
||||
# -- devices ---------------------------------------------------------
|
||||
def battery(self, d):
|
||||
p, st, b = d["params"], d["state"], d["bounds"]
|
||||
cap = max(1.0, float(p["capacity_wh"]))
|
||||
eff = float(p["efficiency"])
|
||||
lo_pct, hi_pct = b["soc_pct"][0], b["soc_pct"][1]
|
||||
plo, phi = b["power_w"][0], b["power_w"][1]
|
||||
max_ch = max(0.0, min(float(p["max_charge_w"]), phi))
|
||||
max_dis = max(0.0, min(float(p["max_discharge_w"]), -plo))
|
||||
soc0 = cap * min(max(float(st["soc_pct"]), 0.0), 100.0) / 100.0
|
||||
mean_price = sum(self.s["price_import"]) / self.T
|
||||
soc, prev, ch, dis = [], soc0, [], []
|
||||
for t in range(self.T):
|
||||
c = self.var(0.0, max_ch)
|
||||
x = self.var(0.0, max_dis)
|
||||
z = self.var(0.0, 1.0, integer=True)
|
||||
self.h.addConstr(c - max_ch * z <= 0)
|
||||
self.h.addConstr(x + max_dis * z <= max_dis)
|
||||
e = self.var(0.0, cap)
|
||||
under = self.var(cost=PENALTY_LIMIT / cap * 100) # Wh below the floor, per % of the battery
|
||||
over = self.var(cost=PENALTY_LIMIT / cap * 100)
|
||||
self.h.addConstr(e - prev - self.dt * eff * c + self.dt / eff * x == 0)
|
||||
self.h.addConstr(e + under >= lo_pct / 100.0 * cap)
|
||||
self.h.addConstr(e - over <= hi_pct / 100.0 * cap)
|
||||
self.flows[t] += [(-1, c), (1, x)]
|
||||
soc.append(e)
|
||||
ch.append(c)
|
||||
dis.append(x)
|
||||
prev = e
|
||||
# energy left at the end is worth the mean price: no draining at the horizon
|
||||
short = self.var(cost=mean_price / 100.0 / 1000.0)
|
||||
self.h.addConstr(prev + short >= min(soc0, hi_pct / 100.0 * cap))
|
||||
self.smooth([c - x for c, x in zip(ch, dis)])
|
||||
self.devices[d["id"]] = ("battery", {"ch": ch, "dis": dis, "soc": soc, "cap": cap, "max_dis": max_dis,
|
||||
"floor_wh": lo_pct / 100.0 * cap})
|
||||
|
||||
def room(self, d, cooling: bool, gains):
|
||||
p, st, b = d["params"], d["state"], d["bounds"]
|
||||
r, c = float(p["r_k_per_kw"]), float(p["c_kwh_per_k"])
|
||||
pmax, cop = float(p["max_power_w"]), float(p["cop"])
|
||||
lo, hi = b["temp_c"][0], b["temp_c"][1]
|
||||
comfort = float(p["comfort_c"])
|
||||
other = float(p["setup_c"] if cooling else p["setback_c"])
|
||||
t0 = st.get("temp_c")
|
||||
t0 = float(t0) if t0 is not None else comfort
|
||||
switched = not cooling and "switch" in d["channels"] and "climate" not in d["channels"]
|
||||
temps, powers, prev = [], [], t0
|
||||
a = self.dt / (r * c)
|
||||
for t in range(self.T):
|
||||
if switched:
|
||||
u = self.var(0.0, 1.0, integer=True)
|
||||
pw = self.var(0.0, pmax)
|
||||
self.h.addConstr(pw - pmax * u == 0)
|
||||
else:
|
||||
pw = self.var(0.0, pmax)
|
||||
self.flows[t].append((-1, pw))
|
||||
tt = self.var(-50.0, 80.0)
|
||||
sign = -1.0 if cooling else 1.0
|
||||
gain = sum((g * gx for g, gx in gains(t)), start=Lin())
|
||||
# T[t+1] = T[t] (1 - a) + a T_out + dt/C (± cop P/1000 + sun gain/1000)
|
||||
self.h.addConstr(tt - (1 - a) * prev - sign * self.dt / c * cop / 1000.0 * pw
|
||||
- self.dt / c / 1000.0 * gain == a * self.s["t_out"][t])
|
||||
occ = self.s["occupied"][t + 1] if t + 1 < self.T else self.s["occupied"][t]
|
||||
target = min(max(comfort if occ else other, lo), hi)
|
||||
miss = self.var(cost=COMFORT_EUR_KH * self.dt)
|
||||
under = self.var(cost=PENALTY_LIMIT)
|
||||
over = self.var(cost=PENALTY_LIMIT)
|
||||
if cooling:
|
||||
self.h.addConstr(tt - miss <= target)
|
||||
else:
|
||||
self.h.addConstr(tt + miss >= target)
|
||||
self.h.addConstr(tt + under >= lo)
|
||||
self.h.addConstr(tt - over <= hi)
|
||||
cap = (self.s.get("building") or {}).get("thermostat_cap")
|
||||
if cap and cap["from_step"] <= t < cap["to_step"]:
|
||||
miss_cap = self.var(cost=cap["penalty"] * self.dt)
|
||||
if cooling:
|
||||
self.h.addConstr(tt + miss_cap >= cap["value"]) # cooling: not below the cap
|
||||
else:
|
||||
self.h.addConstr(tt - miss_cap <= cap["value"]) # heating: not above it
|
||||
temps.append(tt)
|
||||
powers.append(pw)
|
||||
prev = tt
|
||||
self.smooth(powers)
|
||||
self.devices[d["id"]] = ("cooling" if cooling else "heating",
|
||||
{"temp": temps, "power": powers, "pmax": pmax, "switched": switched})
|
||||
|
||||
def ev(self, d):
|
||||
p, st, b = d["params"], d["state"], d["bounds"]
|
||||
if not st.get("connected"):
|
||||
self.devices[d["id"]] = ("ev", None)
|
||||
return
|
||||
volts = float(p["voltage"]) * float(p["phases"])
|
||||
imax = min(float(p["max_current_a"]), b["current_a"][1])
|
||||
imin = max(float(p["min_current_a"]), b["current_a"][0])
|
||||
dep = departure_step(self.s, str(st.get("departure") or p["departure"]))
|
||||
need = float(st["need_wh"]) if st.get("need_wh") is not None else float(p["need_wh"])
|
||||
powers, total = [], Lin()
|
||||
for t in range(self.T):
|
||||
if t >= dep or imax < imin:
|
||||
powers.append(None)
|
||||
continue
|
||||
y = self.var(0.0, 1.0, integer=True)
|
||||
pw = self.var(0.0, imax * volts)
|
||||
self.h.addConstr(pw - imax * volts * y <= 0)
|
||||
self.h.addConstr(pw - imin * volts * y >= 0)
|
||||
self.flows[t].append((-1, pw))
|
||||
powers.append(pw)
|
||||
total += self.dt * pw
|
||||
short = self.var(cost=EV_SHORT_EUR_KWH / 1000.0)
|
||||
self.h.addConstr(total + short >= need)
|
||||
self.smooth([p for p in powers if p is not None])
|
||||
self.devices[d["id"]] = ("ev", {"power": powers, "volts": volts, "dep": dep})
|
||||
|
||||
def cover(self, d, room_ids):
|
||||
p, b = d["params"], d["bounds"]
|
||||
lo, hi = b["position_pct"][0] / 100.0, b["position_pct"][1] / 100.0
|
||||
sch = d.get("schedule")
|
||||
if sch:
|
||||
# the shade's moves by rules (shades.py): fixed here; the room
|
||||
# gets the sun on its facade through them
|
||||
room = p.get("room") if p.get("room") in room_ids else None
|
||||
xs = [self.var(min(max(x / 100.0, 0.0), 1.0), min(max(x / 100.0, 0.0), 1.0)) for x in sch["pos"]] \
|
||||
if room else []
|
||||
sun = sch["sun"] if sch.get("facade") else self.s["sun"]
|
||||
self.devices[d["id"]] = ("cover", {"pos": xs, "gain_w": float(p["gain_w"]), "room": room,
|
||||
"schedule": sch, "sun": sun})
|
||||
return
|
||||
if p.get("room") not in room_ids:
|
||||
self.devices[d["id"]] = ("cover", None)
|
||||
return
|
||||
xs = []
|
||||
for t in range(self.T):
|
||||
x = self.var(lo, hi)
|
||||
closed_any = self.var(cost=CLOSED_EUR)
|
||||
self.h.addConstr(closed_any + x >= hi)
|
||||
daylight = self.s["sun"][t] > 0.05 and self.s["occupied"][t]
|
||||
if daylight:
|
||||
closed = self.var(cost=LIGHT_EUR)
|
||||
self.h.addConstr(closed + x >= hi)
|
||||
xs.append(x)
|
||||
self.devices[d["id"]] = ("cover", {"pos": xs, "gain_w": float(p["gain_w"]), "room": p["room"]})
|
||||
|
||||
# -- solve -------------------------------------------------------------
|
||||
def solve(self, time_limit: float):
|
||||
s = self.s
|
||||
self.grid()
|
||||
covers = [d for d in s["devices"] if d["kind"] == "cover"]
|
||||
rooms = {d["id"] for d in s["devices"] if d["kind"] in ("heating", "cooling")}
|
||||
for d in covers:
|
||||
self.cover(d, rooms)
|
||||
for d in s["devices"]:
|
||||
k = d["kind"]
|
||||
if k == "battery":
|
||||
self.battery(d)
|
||||
elif k in ("heating", "cooling"):
|
||||
def gains(t, room=d["id"]):
|
||||
out = []
|
||||
for cid, (kind, v) in self.devices.items():
|
||||
if kind == "cover" and v and v["room"] == room:
|
||||
out.append((v["gain_w"] * v.get("sun", s["sun"])[t], v["pos"][t]))
|
||||
return out
|
||||
self.room(d, k == "cooling", gains)
|
||||
elif k == "ev":
|
||||
self.ev(d)
|
||||
self.building()
|
||||
self.grid_order()
|
||||
self.balance()
|
||||
obj = sum((c * v for c, v in self.cost), start=Lin())
|
||||
self.h.setOptionValue("time_limit", float(time_limit))
|
||||
# tight: the differences between good plans are cents, the total
|
||||
# cost euros (a 1 % gap left an EV charging at the evening price)
|
||||
self.h.setOptionValue("mip_rel_gap", 1e-4)
|
||||
self.h.setOptionValue("mip_abs_gap", 0.002)
|
||||
self.h.minimize(obj)
|
||||
status = self.h.getModelStatus()
|
||||
info = self.h.getInfo()
|
||||
if info.primal_solution_status != 2: # no feasible solution
|
||||
raise RuntimeError(f"no plan: {self.h.modelStatusToString(status)}")
|
||||
return self.h.modelStatusToString(status)
|
||||
|
||||
|
||||
def departure_step(s: dict, hhmm: str) -> int:
|
||||
"""The step of the next departure (local time), within the horizon."""
|
||||
zone = ZoneInfo(s.get("tz") or "UTC")
|
||||
start = datetime.fromtimestamp(s["start"], timezone.utc).astimezone(zone)
|
||||
h, m = (int(x) for x in hhmm.split(":"))
|
||||
dep = start.replace(hour=h, minute=m, second=0, microsecond=0)
|
||||
if dep <= start:
|
||||
dep += timedelta(days=1)
|
||||
return min(s["steps"], int((dep.timestamp() - s["start"]) // s["step_s"]))
|
||||
|
||||
|
||||
def _round(v: float, step: float) -> float:
|
||||
return round(v / step) * step
|
||||
|
||||
|
||||
def plan(s: dict, time_limit: float = 30.0) -> dict:
|
||||
t0 = time.time()
|
||||
m = Model(s)
|
||||
status = m.solve(time_limit)
|
||||
val = m.h.getSolution().col_value
|
||||
x = lambda v: val[v.index] # noqa: E731
|
||||
start, step, T = s["start"], s["step_s"], m.T
|
||||
pi = s["price_import"]
|
||||
devices = {}
|
||||
for d in s["devices"]:
|
||||
kind, v = m.devices.get(d["id"], (d["kind"], None))
|
||||
entries = []
|
||||
for t in range(T):
|
||||
e = _entry(d, kind, v, t, x, s, pi)
|
||||
if e is not None and (not entries or (entries[-1]["set"], entries[-1].get("grid")) !=
|
||||
(e["set"], e.get("grid"))):
|
||||
entries.append({"t": start + t * step, **e})
|
||||
devices[d["id"]] = entries
|
||||
energy = sum(m.eur_wh(t, pi[t]) * x(m.gin[t]) - m.eur_wh(t, s["price_export"][t]) * x(m.gout[t])
|
||||
for t in range(T))
|
||||
return {"v": 1, "made": int(time.time()), "start": start, "step_s": step, "status": status,
|
||||
"solve_s": round(time.time() - t0, 2), "devices": devices, "flex": flexibility(m, x),
|
||||
"cost_eur": round(energy, 2), "baseline_eur": round(baseline(s, m, x), 2),
|
||||
"price_note": s.get("price_note", ""), "sources": s.get("sources", {})}
|
||||
|
||||
|
||||
FLEX_STEPS = 96 # 24 h at 15 min: what a building plans with
|
||||
|
||||
|
||||
def flexibility(m, x) -> dict:
|
||||
"""What the flat could do for its building (the building
|
||||
asks for flexibility, it doesn't cap averages; building/README.md hole
|
||||
3), per step for the next 24 h: grid_w, the planned import; shed_w, how
|
||||
much of it the controllable devices (heating, cooling, EV, the battery's
|
||||
charging) could drop in that step, plus what the battery could still
|
||||
discharge (its spare power, bounded by the energy above its floor): what
|
||||
a load_limit can take away without touching the household's own use."""
|
||||
n = min(m.T, FLEX_STEPS)
|
||||
grid = [round(x(m.gin[t])) for t in range(n)]
|
||||
shed = [0.0] * n
|
||||
for kind, v in m.devices.values():
|
||||
if v is None:
|
||||
continue
|
||||
if kind == "battery":
|
||||
for t in range(min(n, len(v["dis"]))):
|
||||
stored = max(x(v["soc"][t - 1]) if t else x(v["soc"][0]), 0.0) - v["floor_wh"]
|
||||
spare = max(v["max_dis"] - x(v["dis"][t]), 0.0)
|
||||
shed[t] += max(min(spare, stored / m.dt if m.dt else 0.0), 0.0)
|
||||
cols = v.get("ch") if kind == "battery" else v.get("power")
|
||||
for t in range(min(n, len(cols or []))):
|
||||
if cols[t] is not None and hasattr(cols[t], "index"): # an EV's steps after departure are empty
|
||||
shed[t] += max(x(cols[t]), 0.0)
|
||||
return {"grid_w": grid, "shed_w": [round(min(sh, g)) for sh, g in zip(shed, grid)]}
|
||||
|
||||
|
||||
def _entry(d, kind, v, t, x, s, pi):
|
||||
"""What a device is to do in step t, and why (a few words)."""
|
||||
occ = s["occupied"][t]
|
||||
if v is None:
|
||||
return None
|
||||
if kind == "battery":
|
||||
net = x(v["ch"][t]) - x(v["dis"][t])
|
||||
net = _round(net, 50.0)
|
||||
surplus = s["pv_w"][t] - s["load_w"][t]
|
||||
grid = net > max(0.0, surplus) + 50
|
||||
if net > 0:
|
||||
why = f"cheap grid power ({pi[t]:.1f} ct)" if grid else "PV surplus"
|
||||
elif net < 0:
|
||||
mean = sum(pi) / len(pi)
|
||||
# "peak" only well above the horizon's average (Sim Munich: a plain
|
||||
# 28 ct hour was called a peak)
|
||||
why = (f"price peak ({pi[t]:.1f} ct)" if pi[t] >= 1.2 * mean else
|
||||
f"above the average price ({pi[t]:.1f} ct, average {mean:.1f})")
|
||||
else:
|
||||
why = "hold"
|
||||
return {"set": net, "grid": grid, "why": why}
|
||||
if kind in ("heating", "cooling"):
|
||||
temp = x(v["temp"][t])
|
||||
pw = x(v["power"][t])
|
||||
ahead = s["occupied"][min(t + 4, s["steps"] - 1)]
|
||||
if kind == "heating" and v["switched"]:
|
||||
on = pw > 0.5 * v["pmax"]
|
||||
why = ("pre-heat before someone is home" if on and not occ and ahead else
|
||||
"keep the room warm" if on else "off: warm enough or away")
|
||||
return {"set": "on" if on else "off", "why": why}
|
||||
# the room may dip below a floor in the model (soft, so there is always
|
||||
# a plan), but a setpoint never asks for it: clamped into the bounds
|
||||
# (the guard would refuse it; the sim's run showed 19.5 under a 20 floor)
|
||||
lo, hi = d["bounds"]["temp_c"][0], d["bounds"]["temp_c"][1]
|
||||
target = min(max(_round(temp, 0.5), math.ceil(lo * 2) / 2), math.floor(hi * 2) / 2)
|
||||
if kind == "cooling":
|
||||
if pw < 50:
|
||||
return {"set": "off", "why": "off: cool enough or away"}
|
||||
return {"set": target, "why": "pre-cool before someone is home" if not occ and ahead else "keep cool"}
|
||||
if pw < 50:
|
||||
return {"set": target, "why": "setback: away or night" if not occ else "warm enough"}
|
||||
return {"set": target, "why": f"pre-heat while power is cheap ({pi[t]:.1f} ct)" if not occ and ahead
|
||||
else "keep the room warm"}
|
||||
if kind == "ev":
|
||||
p = v["power"][t]
|
||||
if p is None:
|
||||
return {"set": "off", "why": "after departure"}
|
||||
amps = round(x(p) / v["volts"])
|
||||
if amps < 1:
|
||||
return {"set": "off", "why": "wait for cheaper hours"}
|
||||
return {"set": amps, "why": f"cheapest hours before departure ({pi[t]:.1f} ct)"}
|
||||
if kind == "cover" and v.get("schedule"):
|
||||
sch = v["schedule"]
|
||||
return {"set": sch["set"][t], "why": sch["why"][t] if sch["set"][t] is not None else ""}
|
||||
if kind == "cover":
|
||||
pos = _round(100 * x(v["pos"][t]), 10.0)
|
||||
sun = s["sun"][t]
|
||||
if pos < 100 and sun > 0.05:
|
||||
why = "shade: keep the sun's heat out"
|
||||
elif sun > 0.05:
|
||||
why = "open: daylight and the sun's heat"
|
||||
elif pos < 100:
|
||||
why = "closed: no sun"
|
||||
else:
|
||||
why = "open"
|
||||
return {"set": pos, "why": why}
|
||||
return None
|
||||
|
||||
|
||||
def baseline(s, m, x) -> float:
|
||||
"""An estimate of the cost without the plan: the house's net load at its
|
||||
prices, no battery, and the devices' energy (as the plan uses it) at the
|
||||
mean import price, the EV's as soon as it is plugged in."""
|
||||
T, pi, pe = m.T, s["price_import"], s["price_export"]
|
||||
cost = 0.0
|
||||
for t in range(T):
|
||||
net = s["load_w"][t] - s["pv_w"][t]
|
||||
cost += m.eur_wh(t, pi[t]) * max(net, 0) - m.eur_wh(t, pe[t]) * max(-net, 0)
|
||||
mean = sum(pi) / T
|
||||
for kind, v in m.devices.values():
|
||||
if not v:
|
||||
continue
|
||||
if kind in ("heating", "cooling"):
|
||||
cost += sum(m.eur_wh(t, mean) * x(v["power"][t]) for t in range(T))
|
||||
elif kind == "ev":
|
||||
wh = sum(m.dt * x(p) for p in v["power"] if p is not None)
|
||||
asap = pi[:max(1, math.ceil(wh / max(1.0, v["volts"] * 16) / m.dt))]
|
||||
cost += wh / 1000.0 * (sum(asap) / len(asap)) / 100.0
|
||||
return cost
|
||||
|
||||
|
||||
def main():
|
||||
s = json.load(sys.stdin)
|
||||
limit = float(sys.argv[1]) if len(sys.argv) > 1 else 30.0
|
||||
try:
|
||||
out = plan(s, limit)
|
||||
except Exception as e: # the caller keeps its last plan
|
||||
json.dump({"v": 1, "error": str(e)}, sys.stdout)
|
||||
sys.exit(1)
|
||||
json.dump(out, sys.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,122 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Protection of devices: what Cantabile may never do to a
|
||||
device, whatever a command's level.
|
||||
|
||||
none ordinary: consent and the guard decide
|
||||
protected never switched off or cut by Cantabile (plans, commands from
|
||||
the cloud, a building, a grid operator); the owner still can,
|
||||
by hand, and is the one who lifts it. A cover (blind, curtain)
|
||||
has no "off": protected, Cantabile does not move it at all
|
||||
(the profile ha-cover protects every shade until the owner
|
||||
lifts it)
|
||||
sealed tamper-proof: Cantabile does not act on it at all; only its
|
||||
custodian (an organisation: grid, metering or community
|
||||
operator, a building's operator) changes it, from the cloud
|
||||
|
||||
Two sources, both files in the agent's state directory:
|
||||
acl.json the cloud's signed policy (the link checked the bundle's
|
||||
signature; here its kind and site): {"v":1, "kind":"acl",
|
||||
"site", "issued", "expires": 0, "entries": [{"target",
|
||||
"level", "custodian", "set_by", "role", "at", "why"}]}
|
||||
protection.json the box's own (the panel's Devices: the owner's, a
|
||||
profile's defaults; /usr/lib/cantabile/devices):
|
||||
{"v":1, "entries": {target: {...}}}
|
||||
Targets: "device:<id on the box>", "control:<control id>", "entity:<HA
|
||||
entity id>". Per target a sealed entry from the cloud holds; the box's own
|
||||
never lowers it; otherwise the newer one (a custodian lifting a profile's
|
||||
seal is newer). A control is covered by its own target, its device's and
|
||||
each of its entities'.
|
||||
"""
|
||||
import time
|
||||
|
||||
from .bundles import _File
|
||||
|
||||
RANK = {"none": 0, "protected": 1, "sealed": 2}
|
||||
LEVELS = tuple(RANK)
|
||||
OFF_OPTIONS = {"off", "stop", "stopped", "disable", "disabled", "shutdown", "shut down", "standby"}
|
||||
|
||||
|
||||
def merge(cloud: dict, local: dict) -> dict:
|
||||
out = dict(cloud)
|
||||
for t, e in local.items():
|
||||
cur = out.get(t)
|
||||
if cur and cur["level"] == "sealed":
|
||||
continue
|
||||
if cur is None or float(e.get("at", 0)) > float(cur.get("at", 0)):
|
||||
out[t] = e
|
||||
return out
|
||||
|
||||
|
||||
def is_off(a) -> bool:
|
||||
"""Would this action switch a device off or cut it."""
|
||||
if a.service == "turn_off":
|
||||
return True
|
||||
if a.service in ("set_hvac_mode", "select_option"):
|
||||
return str(a.value).strip().lower() in OFF_OPTIONS
|
||||
if a.service == "set_value" and a.quantity == "current_a":
|
||||
try:
|
||||
return float(a.value) <= 0 # a charger at 0 A: stopped
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
class Policy:
|
||||
def __init__(self, state_dir: str, site_id: str, clock=time.time):
|
||||
self.site, self.clock = site_id, clock
|
||||
self.cloud = _File(f"{state_dir}/acl.json", self._check_acl)
|
||||
self.local = _File(f"{state_dir}/protection.json", self._check_local)
|
||||
|
||||
def _check_acl(self, d: dict):
|
||||
if d.get("v") != 1 or d.get("kind") != "acl":
|
||||
raise ValueError("not a v1 acl")
|
||||
if d.get("site") != self.site:
|
||||
raise ValueError("not this site's")
|
||||
for e in d.get("entries") or []:
|
||||
if not isinstance(e.get("target"), str) or e.get("level") not in LEVELS:
|
||||
raise ValueError("an entry needs target and level")
|
||||
|
||||
@staticmethod
|
||||
def _check_local(d: dict):
|
||||
if not isinstance(d.get("entries"), dict):
|
||||
raise ValueError("entries: {target: entry}")
|
||||
|
||||
def entries(self) -> dict:
|
||||
cloud = {e["target"]: dict(e, source="cloud") for e in (self.cloud.get() or {}).get("entries") or []}
|
||||
local = {t: e for t, e in ((self.local.get() or {}).get("entries") or {}).items()
|
||||
if isinstance(e, dict) and e.get("level") in LEVELS}
|
||||
return merge(cloud, local)
|
||||
|
||||
@staticmethod
|
||||
def targets(control, entity: str | None = None) -> list[str]:
|
||||
ts = [f"control:{control.id}"]
|
||||
if getattr(control, "device", ""):
|
||||
ts.append(f"device:{control.device}")
|
||||
ts += [f"entity:{e}" for e in ([entity] if entity else control.entities.values())]
|
||||
return ts
|
||||
|
||||
def level(self, targets) -> tuple[str, dict | None]:
|
||||
es = self.entries()
|
||||
best = ("none", None)
|
||||
for t in targets:
|
||||
e = es.get(t)
|
||||
if e and RANK[e["level"]] > RANK[best[0]]:
|
||||
best = (e["level"], e)
|
||||
return best
|
||||
|
||||
def refuses(self, a, control) -> str:
|
||||
"""Why the policy refuses this action ("" if it doesn't)."""
|
||||
lvl, e = self.level(self.targets(control, a.entity))
|
||||
if lvl == "sealed":
|
||||
who = (e or {}).get("custodian", "its custodian").replace("_", " ")
|
||||
return f"sealed by {who}: Cantabile does not act on it"
|
||||
if lvl == "protected" and a.domain == "cover":
|
||||
# a shade has no "off": protected, Cantabile does not move it at all
|
||||
return "protected: Cantabile does not move it until the owner allows it"
|
||||
if lvl == "protected" and is_off(a):
|
||||
return "protected: Cantabile never switches it off (only the owner, by hand)"
|
||||
return ""
|
||||
|
||||
def plannable(self, control) -> bool:
|
||||
"""Sealed controls are left out of the plans."""
|
||||
return self.level(self.targets(control))[0] != "sealed"
|
||||
@@ -0,0 +1,491 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""A mapping for a site that has none yet: part of installing Cantabile as
|
||||
an HA add-on and of moving a site onto it.
|
||||
|
||||
Two ways in, both with every consent off (reading and sharing stay the
|
||||
owner's choice):
|
||||
- **Import** a mapping an earlier install confirmed (the containers' agent's
|
||||
/root/cantabile-agent/mapping.yaml): addon-run copies the file the owner or
|
||||
support put in HA's share folder (/share/cantabile/mapping.yaml) to
|
||||
<mapping dir>/mapping-import.yaml; it is taken once per content, over an
|
||||
empty mapping or one this module wrote (never over one written by hand).
|
||||
Its entities, ids and units are kept; consent is not carried (a new site
|
||||
decides again). Where one of its entities measures nothing here
|
||||
(unavailable, unknown, gone) and one of Cantabile's own Modbus bridge
|
||||
devices gives the same quantity live, the bridge's entity takes its place.
|
||||
- **Propose** from HA's registries when the mapping is empty, or was
|
||||
proposed before and nobody changed it (`source: proposed`): new devices
|
||||
are taken in as they come. In order:
|
||||
1. Cantabile's Modbus bridge's devices (unique ids cantabile_modbus_*):
|
||||
their profile's register map says each value's quantity
|
||||
(the profiles ship in the add-on image);
|
||||
2. HA devices a profile recognises (manufacturer, model, integration):
|
||||
the profile's value matchers on their entities, as the Hub's devices
|
||||
tool does for "Use with Cantabile";
|
||||
3. the rest by name (mapping.suggest): only Cantabile's own quantities
|
||||
(pv, grid, battery, load, heat pump, EV) and one temperature and
|
||||
humidity per area, from sensors that have a value now; marked
|
||||
unverified by `source: proposed`.
|
||||
A bridge value read from another HA entity (an SPM's circuit through
|
||||
SonoffLAN) is that entity's mirror: the source entity is what is mapped.
|
||||
Two or more devices with the same system (two inverters' pv.power) are
|
||||
proposed as parts, numbered in HA's device order (pv.1.power, pv.2.power;
|
||||
the agent derives the total pv.power: mapping.py).
|
||||
|
||||
The owner's choice comes first. A proposal is a starting point: on the
|
||||
add-on's Devices page (devpage.py) the owner confirms a device with "Use
|
||||
with Cantabile", which writes its own fragment (<mapping dir>/mapping.d/
|
||||
<device>.yaml, as the Hub's devices tool does). From then on the proposal
|
||||
leaves that device alone: its HA device, entities, asset ids and the summed
|
||||
systems it gives (pv, battery, ...) are left out of the proposal, which is
|
||||
made again at once, so the device's values come only from its fragment.
|
||||
Removing the device on the page gives it back to the proposal. A mapping
|
||||
written by hand (no `source`) is never changed; there the mapping's own
|
||||
entries win and the page leaves them out of a device's fragment.
|
||||
|
||||
The file written says where it came from (`source`, `at`); the agent loads
|
||||
it again at once (agent.py). Controls are never proposed: acting needs the
|
||||
owner's own setup and consent."""
|
||||
import glob
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
import yaml
|
||||
|
||||
from .devprofiles import (BRIDGE, PER_PLACE, QUANTITIES, SUMMED, alternatives, assumed_state, by_priority, # noqa: F401
|
||||
entity_matches, fallback, glob_match, kinds_of, quantity_of, recognise, setup_for, slug)
|
||||
from .mapping import part_of, suggest
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
PROFILES_DIR = "/usr/share/cantabile/profiles"
|
||||
# Cantabile's quantities, profiles' matchers: devprofiles.py (shared with
|
||||
# the Hub's devices tool).
|
||||
EEBUS = "cantabile_eebus_" # Cantabile's EEBUS bridge
|
||||
BRIDGES = (BRIDGE, EEBUS)
|
||||
WRITTEN_BY_US = ("proposed", "imported")
|
||||
|
||||
|
||||
def indexed(vals: list[tuple]) -> list[tuple]:
|
||||
"""(quantity, entity, ...) of devices: a system that two or more devices
|
||||
give (pv.power of two inverters) becomes parts, numbered in the order
|
||||
the devices come (pv.1.power, pv.2.power)."""
|
||||
holders: dict[str, list] = {}
|
||||
for q, e, *_ in vals:
|
||||
head = q.split(".")[0]
|
||||
if head in SUMMED and q.count(".") == 1:
|
||||
devs = holders.setdefault(head, [])
|
||||
if e.get("device_id") not in devs:
|
||||
devs.append(e.get("device_id"))
|
||||
out = []
|
||||
for q, e, *rest in vals:
|
||||
head, _, tail = q.partition(".")
|
||||
devs = holders.get(head) or []
|
||||
if len(devs) > 1 and "." not in tail:
|
||||
q = f"{head}.{devs.index(e.get('device_id')) + 1}.{tail}"
|
||||
out.append((q, e, *rest))
|
||||
return out
|
||||
|
||||
|
||||
def live(state: dict | None) -> bool:
|
||||
"""The entity measures something now (a number)."""
|
||||
try:
|
||||
v = float((state or {}).get("state"))
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return v == v
|
||||
|
||||
|
||||
def load_profiles(path: str = "", extra=()) -> list[dict]:
|
||||
"""The profiles in path (CANTABILE_PROFILES, else the image's), then in
|
||||
the extra directories (one with the same id there wins)."""
|
||||
out = {}
|
||||
for d in [path or os.environ.get("CANTABILE_PROFILES", PROFILES_DIR), *extra]:
|
||||
for f in sorted(glob.glob(os.path.join(d, "*.json"))):
|
||||
try:
|
||||
with open(f) as fh:
|
||||
p = json.load(fh)
|
||||
if p.get("id") and p.get("name"):
|
||||
out[p["id"]] = p
|
||||
except (OSError, ValueError, AttributeError) as e:
|
||||
log.warning("profile %s left out: %s", f, e)
|
||||
return list(out.values())
|
||||
|
||||
|
||||
# -- registries -----------------------------------------------------------------
|
||||
|
||||
class Registry:
|
||||
"""HA's registries and states, the parts a proposal needs."""
|
||||
|
||||
def __init__(self, states: list[dict], reg: dict):
|
||||
self.states = {s["entity_id"]: s for s in states or []}
|
||||
self.areas = {a["area_id"]: a["name"] for a in reg.get("areas") or []}
|
||||
self.devices = {d["id"]: d for d in reg.get("devices") or []}
|
||||
self.entities = [e for e in reg.get("entities") or [] if not e.get("disabled_by")]
|
||||
self.by_device: dict[str, list[dict]] = {}
|
||||
for e in self.entities:
|
||||
if e.get("device_id"):
|
||||
self.by_device.setdefault(e["device_id"], []).append(e)
|
||||
|
||||
def domains(self, dev_id: str) -> list[str]:
|
||||
return sorted({e.get("platform") for e in self.by_device.get(dev_id, []) if e.get("platform")})
|
||||
|
||||
def entity_domains(self, dev_id: str) -> list[str]:
|
||||
"""Domains, and with the device class (cover.curtain, sensor.temperature)."""
|
||||
return sorted({k for e in self.by_device.get(dev_id, []) for k in kinds_of(e, self.attrs(e) or {})})
|
||||
|
||||
def attrs(self, e: dict) -> dict | None:
|
||||
"""HA's attributes of the entity now (None: no state known, or not
|
||||
available: then conditions on them hold)."""
|
||||
st = self.states.get(e["entity_id"])
|
||||
if not st or st.get("state") in ("unavailable", "unknown"):
|
||||
return None
|
||||
return st.get("attributes") or {}
|
||||
|
||||
def area_name(self, e: dict) -> str | None:
|
||||
a = e.get("area_id") or (self.devices.get(e.get("device_id")) or {}).get("area_id")
|
||||
return self.areas.get(a)
|
||||
|
||||
def name(self, e: dict) -> str:
|
||||
st = self.states.get(e["entity_id"]) or {}
|
||||
return (st.get("attributes") or {}).get("friendly_name") or e.get("original_name") or e["entity_id"]
|
||||
|
||||
|
||||
def bridge_device(d: dict) -> str | None:
|
||||
"""The device id of one of Cantabile's bridges (cantabile_modbus_<id>,
|
||||
cantabile_eebus_<id>), or None."""
|
||||
for i in d.get("identifiers") or []:
|
||||
for b in BRIDGES:
|
||||
if len(i) == 2 and i[0] == "mqtt" and str(i[1]).startswith(b):
|
||||
return str(i[1])[len(b):]
|
||||
return None
|
||||
|
||||
|
||||
def bridge_prefix(d: dict) -> str:
|
||||
"""The unique id prefix of the bridge a device is from ("" for none)."""
|
||||
for i in d.get("identifiers") or []:
|
||||
for b in BRIDGES:
|
||||
if len(i) == 2 and i[0] == "mqtt" and str(i[1]).startswith(b):
|
||||
return b
|
||||
return ""
|
||||
|
||||
|
||||
def bridge_values(p: dict) -> list[tuple[str, str]]:
|
||||
"""(quantity, key) of the values a bridge publishes for a profile: the
|
||||
Modbus bridge's registers (and split parts, derived values), the EEBUS
|
||||
bridge's eebus.values."""
|
||||
out = []
|
||||
mb = p.get("modbus") or {}
|
||||
for reg in (mb.get("registers") or []) + (mb.get("derived") or []):
|
||||
if reg.get("quantity"):
|
||||
out.append((reg["quantity"], reg["key"]))
|
||||
out += [(q, q.replace(".", "_")) for q in (reg.get("split") or {}).values()]
|
||||
for v in (p.get("eebus") or {}).get("values") or []:
|
||||
if v.get("quantity"):
|
||||
out.append((v["quantity"], v["key"]))
|
||||
return out
|
||||
|
||||
|
||||
class Taken:
|
||||
def __init__(self, assets=()):
|
||||
self.ids = {a["asset"] for a in assets}
|
||||
self.entities = {(a["entity"], a.get("attribute", ""), a.get("equals", ""))
|
||||
if a.get("attribute") or a.get("equals") or a.get("assumed") else a["entity"] for a in assets}
|
||||
|
||||
def add(self, entity: str, want: str, kind: str, unit: str, scale=1, unique=False, read=None) -> dict | None:
|
||||
"""read: how a value is read from the entity ({attribute, equals,
|
||||
assumed}); one entity may feed several assets that way (a climate:
|
||||
room temperature, setpoint, heating state)."""
|
||||
read = {k: v for k, v in (read or {}).items() if k in ("attribute", "equals", "assumed", "fallback") and v}
|
||||
key = entity if not read else (entity, read.get("attribute", ""), read.get("equals", ""))
|
||||
if key in self.entities or (not read and any(isinstance(k, tuple) and k[0] == entity for k in self.entities)) \
|
||||
or (unique and want in self.ids):
|
||||
return None
|
||||
out, n = want, 2
|
||||
while out in self.ids:
|
||||
out, n = f"{want}_{n}", n + 1
|
||||
self.ids.add(out)
|
||||
self.entities.add(key)
|
||||
a = {"entity": entity, "asset": out, "kind": kind, "unit": unit, "consent": False}
|
||||
if scale != 1:
|
||||
a["scale"] = scale
|
||||
a.update(read)
|
||||
return a
|
||||
|
||||
|
||||
# -- the three sources ------------------------------------------------------------
|
||||
|
||||
def from_bridge(r: Registry, profiles: list[dict]) -> list[tuple[str, dict]]:
|
||||
"""(quantity, entity) of Cantabile's Modbus bridge devices' values, by
|
||||
their profile's register map. Values the bridge reads from other HA
|
||||
entities (profiles with an "ha" map) are left to their source."""
|
||||
by_name = {p["name"]: p for p in profiles if (p.get("modbus") or {}).get("registers") or p.get("eebus")}
|
||||
uids = {e.get("unique_id"): e for e in r.entities if str(e.get("unique_id", "")).startswith(BRIDGES)}
|
||||
out = []
|
||||
for d in r.devices.values():
|
||||
dev, prefix = bridge_device(d), bridge_prefix(d)
|
||||
p = by_name.get(d.get("model") or "")
|
||||
if not dev or not p:
|
||||
continue
|
||||
for q, key in bridge_values(p): # derived values: computed by the bridge
|
||||
e = uids.get(f"{prefix}{dev}_{key}")
|
||||
if e is not None:
|
||||
out.append((q, e))
|
||||
return out
|
||||
|
||||
|
||||
def from_profiles(r: Registry, profiles: list[dict]) -> list[tuple[str, dict, float, dict]]:
|
||||
"""(quantity, entity, scale, read) of HA devices a profile recognises,
|
||||
by the value matchers of the setup path their integration has (else the
|
||||
profile's "existing" path); specific profiles before generic ones (any
|
||||
climate device: ha-thermostat)."""
|
||||
out = []
|
||||
for d in r.devices.values():
|
||||
if d.get("disabled_by") or bridge_device(d) or not (d.get("manufacturer") or d.get("model")):
|
||||
continue
|
||||
doms, edoms = r.domains(d["id"]), r.entity_domains(d["id"])
|
||||
for p in by_priority(profiles):
|
||||
if not recognise(p, d, doms, edoms):
|
||||
continue
|
||||
s = setup_for(p, doms)
|
||||
if not s or s["path"] == "modbus":
|
||||
continue
|
||||
ents = r.by_device.get(d["id"], [])
|
||||
for q, alts in (s.get("values") or {}).items():
|
||||
for m in alternatives(alts):
|
||||
hits = [e for e in ents if entity_matches(m, e, r.attrs(e))]
|
||||
read = {k: m[k] for k in ("attribute", "equals", "assumed", "fallback") if m.get(k)}
|
||||
for e in hits if "{area}" in q and not read else hits[:1]:
|
||||
out.append((q, e, m.get("scale", 1), read))
|
||||
if hits:
|
||||
break
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
def place(q: str, r: Registry, e: dict) -> str:
|
||||
"""room.{area}.temp -> room.kitchen.temp: the entity's area, else its name."""
|
||||
if "{area}" not in q:
|
||||
return q
|
||||
return q.replace("{area}", slug(r.area_name(e) or r.name(e)))
|
||||
|
||||
|
||||
def by_name(states: list[dict], reg: dict, r: Registry, taken: Taken, skip=()) -> list[dict]:
|
||||
"""mapping.suggest() kept to Cantabile's quantities, one per room; not
|
||||
the entities in skip."""
|
||||
out = []
|
||||
bridge = {e["entity_id"] for e in r.entities if str(e.get("unique_id", "")).startswith(BRIDGES)}
|
||||
for a in suggest(states, reg)["assets"]:
|
||||
q = a["asset"]
|
||||
head = q.split(".")[0]
|
||||
ok = q in QUANTITIES or (head == "room" and q.count(".") == 2 and q.rsplit(".", 1)[1] in ("temp", "humidity"))
|
||||
if not ok or a["entity"] in bridge or a["entity"] in skip or not live(r.states.get(a["entity"])):
|
||||
continue
|
||||
if any((part_of(i) or ("",))[0] == q for i in taken.ids):
|
||||
continue # its parts are mapped: the agent sums them
|
||||
got = taken.add(a["entity"], q, a["kind"], a["unit"], unique=True)
|
||||
if got:
|
||||
out.append(got)
|
||||
return out
|
||||
|
||||
|
||||
def propose(states: list[dict], reg: dict, profiles: list[dict], keep: list[dict] = (), used: list[dict] = ()) -> list[dict]:
|
||||
"""keep: an earlier proposal's entries, kept while their entity exists
|
||||
(a sensor without a value for a moment does not change the file).
|
||||
used: the owner's devices' fragments (mapping.d, the Devices page):
|
||||
the proposal leaves them their HA devices, entities and ids, and the
|
||||
summed systems they give (a second inverter is offered on the Devices
|
||||
page, not proposed: its pv.power and the owner's add up as parts)."""
|
||||
r = Registry(states, reg)
|
||||
known = {e["entity_id"] for e in r.entities} | set(r.states)
|
||||
u_assets = [a for fr in used for a in fr.get("assets") or [] if isinstance(a, dict) and a.get("entity")]
|
||||
u_ents = {a["entity"] for a in u_assets} | {e for fr in used for c in fr.get("controls") or []
|
||||
for e in (c.get("entities") or {}).values()}
|
||||
u_devs = {e.get("device_id") for e in r.entities if e["entity_id"] in u_ents and e.get("device_id")}
|
||||
u_systems = {str(a.get("asset", "")).split(".")[0] for a in u_assets} & set(SUMMED)
|
||||
|
||||
def yields(q: str, eid: str, dev) -> bool:
|
||||
return eid in u_ents or (dev is not None and dev in u_devs) or q.split(".")[0] in u_systems
|
||||
|
||||
devices = indexed([x for x in [(q, e, 1, True, None) for q, e in from_bridge(r, profiles)]
|
||||
+ [(q, e, scale, False, read) for q, e, scale, read in from_profiles(r, profiles)]
|
||||
if not yields(x[0], x[1]["entity_id"], x[1].get("device_id"))])
|
||||
fresh = {e["entity_id"] for _, e, *_ in devices}
|
||||
owner = {a.get("asset") for a in u_assets} | {c.get("id") for fr in used for c in fr.get("controls") or []}
|
||||
by_entity = {e["entity_id"]: e for e in r.entities}
|
||||
# an earlier proposal's entries; the devices' own ones as proposed now
|
||||
# (a second inverter turns pv.power into pv.1.power)
|
||||
kept = [a for a in keep if a.get("entity") in known and a.get("entity") not in fresh and a.get("asset") not in owner
|
||||
and not yields(str(a.get("asset", "")), a["entity"], (by_entity.get(a["entity"]) or {}).get("device_id"))]
|
||||
taken, out = Taken(kept + u_assets), []
|
||||
for q, e, scale, bridge, read in devices:
|
||||
qu = quantity_of(q)
|
||||
got = qu and taken.add(e["entity_id"], place(q, r, e), qu[1], qu[0], scale, unique=bridge, read=read)
|
||||
if got:
|
||||
out.append(got)
|
||||
skip = u_ents | {e["entity_id"] for e in r.entities if e.get("device_id") in u_devs}
|
||||
return out + kept + by_name(states, reg, r, taken, skip)
|
||||
|
||||
|
||||
def fragments(mapping_path: str) -> list[dict]:
|
||||
"""The owner's devices' fragments next to the mapping (mapping.d)."""
|
||||
out = []
|
||||
for f in sorted(glob.glob(os.path.join(os.path.dirname(mapping_path) or ".", "mapping.d", "*.yaml"))):
|
||||
try:
|
||||
with open(f) as fh:
|
||||
fr = yaml.safe_load(fh) or {}
|
||||
except (OSError, yaml.YAMLError):
|
||||
continue
|
||||
if isinstance(fr, dict):
|
||||
out.append(fr)
|
||||
return out
|
||||
|
||||
|
||||
def merge_import(raw: dict, states: list[dict], reg: dict, profiles: list[dict]) -> tuple[dict, list[str]]:
|
||||
"""An earlier install's mapping, consent off; its dead entities replaced
|
||||
by the bridge's live ones for the same quantity, the bridge's other
|
||||
values added. (mapping, notes)"""
|
||||
r = Registry(states, reg)
|
||||
assets = [dict(a, consent=False) for a in raw.get("assets") or []]
|
||||
controls = [dict(c, consent=False) for c in raw.get("controls") or []]
|
||||
by_id = {a["asset"]: a for a in assets}
|
||||
used = {a["entity"] for a in assets}
|
||||
notes = []
|
||||
for q, e in from_bridge(r, profiles):
|
||||
qu, eid = quantity_of(q), e["entity_id"]
|
||||
if not qu or eid in used or not live(r.states.get(eid)):
|
||||
continue
|
||||
q = place(q, r, e)
|
||||
cur = by_id.get(q)
|
||||
if cur is None:
|
||||
a = {"entity": eid, "asset": q, "kind": qu[1], "unit": qu[0], "consent": False}
|
||||
assets.append(a)
|
||||
by_id[q] = a
|
||||
notes.append(f"{q}: {eid} added (Cantabile's Modbus bridge)")
|
||||
elif not live(r.states.get(cur["entity"])):
|
||||
notes.append(f"{q}: {cur['entity']} has no value here; {eid} (Cantabile's Modbus bridge) instead")
|
||||
used.discard(cur["entity"])
|
||||
cur.update(entity=eid, kind=qu[1], unit=qu[0])
|
||||
cur.pop("scale", None)
|
||||
else:
|
||||
continue
|
||||
used.add(eid)
|
||||
out = {k: v for k, v in raw.items() if k not in ("assets", "controls", "source", "at", "from")}
|
||||
out.update(assets=assets)
|
||||
if controls:
|
||||
out["controls"] = controls
|
||||
return out, notes
|
||||
|
||||
|
||||
# -- the files ----------------------------------------------------------------------
|
||||
|
||||
def source_of(path: str) -> str | None:
|
||||
"""`source` of the mapping file: proposed / imported (ours), else None;
|
||||
"empty" for a mapping without assets or controls."""
|
||||
try:
|
||||
with open(path) as f:
|
||||
raw = yaml.safe_load(f) or {}
|
||||
except (OSError, yaml.YAMLError):
|
||||
return "empty"
|
||||
if raw.get("source") in WRITTEN_BY_US:
|
||||
return raw["source"]
|
||||
if not raw.get("assets") and not raw.get("controls"):
|
||||
return "empty"
|
||||
return None
|
||||
|
||||
|
||||
def write(path: str, data: dict, header: str):
|
||||
"""Only a file the agent's own parser takes (mapping.py) replaces the mapping."""
|
||||
from .mapping import Mapping
|
||||
tmp = path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
f.write(header + yaml.safe_dump(data, sort_keys=False, allow_unicode=True))
|
||||
os.chmod(tmp, 0o644)
|
||||
try:
|
||||
Mapping.load(tmp)
|
||||
except Exception:
|
||||
os.unlink(tmp)
|
||||
raise
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def import_file(mapping_path: str) -> str:
|
||||
return os.path.join(os.path.dirname(mapping_path) or ".", "mapping-import.yaml")
|
||||
|
||||
|
||||
def ensure(mapping_path: str, state_dir: str, states: list[dict], reg: dict,
|
||||
profiles: list[dict]) -> str | None:
|
||||
"""Import or propose when this site's mapping is ours to write; what was
|
||||
done ("imported" / "proposed") when the file changed, else None."""
|
||||
src = source_of(mapping_path)
|
||||
if src is None:
|
||||
return None # written by hand: never touched
|
||||
imp = import_file(mapping_path)
|
||||
done_path = os.path.join(state_dir, "mapping-import.json")
|
||||
try:
|
||||
with open(imp, "rb") as f:
|
||||
blob = f.read()
|
||||
except OSError:
|
||||
blob = None
|
||||
if blob is not None:
|
||||
digest = hashlib.sha256(blob).hexdigest()
|
||||
try:
|
||||
with open(done_path) as f:
|
||||
done = json.load(f).get("sha256")
|
||||
except (OSError, ValueError):
|
||||
done = None
|
||||
if digest != done:
|
||||
try:
|
||||
raw = yaml.safe_load(blob) or {}
|
||||
if not isinstance(raw, dict) or not isinstance(raw.get("assets", []), list):
|
||||
raise ValueError("not a mapping")
|
||||
data, notes = merge_import(raw, states, reg, profiles)
|
||||
except (ValueError, TypeError, KeyError, AttributeError, yaml.YAMLError) as e:
|
||||
log.warning("mapping import %s refused: %s", imp, e)
|
||||
return None
|
||||
data = {"version": int(data.get("version", 1)), "source": "imported",
|
||||
"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
**{k: v for k, v in data.items() if k != "version"}}
|
||||
note = "".join(f"# {n}\n" for n in notes)
|
||||
try:
|
||||
write(mapping_path, data, "# Imported from an earlier install's mapping (edge/cantabile_edge/propose.py).\n"
|
||||
"# Consent is not carried: every entry is off until the owner turns reading on.\n"
|
||||
+ ("# Changed on import:\n" + note if note else "")
|
||||
+ "# Edit freely; once `source` is removed Cantabile never writes this file again.\n")
|
||||
except (ValueError, TypeError, KeyError, AttributeError, yaml.YAMLError) as e:
|
||||
log.warning("mapping import %s refused: %s", imp, e)
|
||||
return None
|
||||
with open(done_path + ".tmp", "w") as f:
|
||||
json.dump({"sha256": digest, "at": int(time.time()), "assets": len(data["assets"])}, f)
|
||||
os.replace(done_path + ".tmp", done_path)
|
||||
log.info("mapping imported: %d entities, consent off (%d changed for this site)",
|
||||
len(data["assets"]), len(notes))
|
||||
for n in notes:
|
||||
log.info("mapping import: %s", n)
|
||||
return "imported"
|
||||
if src not in ("empty", "proposed"):
|
||||
return None
|
||||
try:
|
||||
with open(mapping_path) as f:
|
||||
old = (yaml.safe_load(f) or {}).get("assets") or []
|
||||
except (OSError, yaml.YAMLError):
|
||||
old = []
|
||||
assets = propose(states, reg, profiles, keep=old if src == "proposed" else (), used=fragments(mapping_path))
|
||||
if not assets and src == "empty":
|
||||
return None
|
||||
if not assets and not old:
|
||||
return None
|
||||
if old == assets:
|
||||
return None
|
||||
write(mapping_path, {"version": 2, "source": "proposed", "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"assets": assets},
|
||||
"# Proposed by Cantabile from Home Assistant's devices (edge/cantabile_edge/propose.py): unverified.\n"
|
||||
"# Nothing is read or sent until the owner turns consent on. Proposed again when devices change,\n"
|
||||
"# as long as `source: proposed` stays; remove that line to keep the file as it is.\n")
|
||||
log.info("mapping proposed: %d entities from Home Assistant's devices, consent off", len(assets))
|
||||
return "proposed"
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Shades (blinds, curtains, shutters, awnings): when the agent moves a
|
||||
cover control, by rules on the sun, the season and the room ("shades"). The plan's entries for a cover come from here, not from the
|
||||
optimiser's MILP: the rules are few, explainable in one line, and keep to
|
||||
the owner's quiet hours; the MILP takes the result as fixed and counts the
|
||||
sun's heat it lets into the room (optimizer.py).
|
||||
|
||||
Per 15-minute step of the plan, for a shade with its window's orientation
|
||||
(params.facing: degrees from north, -1 not known):
|
||||
|
||||
sun on the facade the sun above the horizon (> 2°) and in front of the
|
||||
window: cos(elevation) * cos(azimuth - facing) > 0.25,
|
||||
times the sky (1 - the weather forecast's cloud cover;
|
||||
clear without a forecast)
|
||||
cooling season the sun on the facade and the room warm (its
|
||||
temperature within 1 K of the setpoint, or outside
|
||||
24 °C or more) or the next 3 hours dear (their mean
|
||||
price 10 % above the horizon's): close to shade_pct
|
||||
(someone home: some daylight) or closed_pct (nobody
|
||||
home); open again (open_pct) when the sun has left
|
||||
heating season the sun on the facade (sunny, outside below 18 °C):
|
||||
open for its warmth; in the evening (the sun 2° below
|
||||
the horizon, after noon, outside below 12 °C): closed,
|
||||
to keep the warmth in (never closed before dawn: it
|
||||
opens again soon); in the morning (the sun up) open again.
|
||||
Never opened in the dark (privacy)
|
||||
quiet hours params.quiet_from..quiet_to (local): no move at all,
|
||||
unless params.night_moves is 1
|
||||
minimum interval params.min_move_s between two moves (the guard holds
|
||||
it too, against what was really done)
|
||||
not known without the facade: only the heating season's night
|
||||
and morning; without the site's location: nothing
|
||||
|
||||
The season: the room's heating or cooling control (params.room; of a
|
||||
thermostat that does both, its active side: switchover.py), else by month
|
||||
(heating October to April). An entry is a move: {"set": position %} in the
|
||||
step the shade is to move, then {"set": None} (hold: the executor leaves it
|
||||
alone), so a shade the owner moved by hand is never pushed back later; the
|
||||
guard's override pause (params.override_hold_s) keeps the agent off it.
|
||||
|
||||
HA's position: 0 closed, 100 open.
|
||||
"""
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
ORIENTATIONS = {"N": 0, "NE": 45, "E": 90, "SE": 135, "S": 180, "SW": 225, "W": 270, "NW": 315}
|
||||
WORDS = {"N": "north", "NE": "north-east", "E": "east", "SE": "south-east", "S": "south", "SW": "south-west",
|
||||
"W": "west", "NW": "north-west"}
|
||||
SUN_MIN = 0.25 # cos(elevation) * cos(azimuth - facing), times the sky: the sun counts
|
||||
HEAT_MONTHS = (10, 11, 12, 1, 2, 3, 4)
|
||||
|
||||
|
||||
def facing(v) -> float | None:
|
||||
"""A window's orientation: "N", "SW", ... or degrees (0 north, 90 east);
|
||||
None when not known (-1, empty, nonsense)."""
|
||||
if v is None:
|
||||
return None
|
||||
s = str(v).strip().upper()
|
||||
if s in ORIENTATIONS:
|
||||
return float(ORIENTATIONS[s])
|
||||
try:
|
||||
x = float(s)
|
||||
except ValueError:
|
||||
return None
|
||||
return x % 360 if 0 <= x <= 360 else None
|
||||
|
||||
|
||||
def compass(deg: float | None) -> str:
|
||||
"""The nearest of the eight directions ("SW")."""
|
||||
if deg is None:
|
||||
return ""
|
||||
return min(ORIENTATIONS, key=lambda k: abs((ORIENTATIONS[k] - deg + 180) % 360 - 180))
|
||||
|
||||
|
||||
def facade_words(deg: float | None) -> str:
|
||||
return WORDS.get(compass(deg), "")
|
||||
|
||||
|
||||
def sun_position(ts: float, lat: float, lon: float) -> tuple[float, float]:
|
||||
"""The sun's elevation and azimuth (degrees; azimuth from north,
|
||||
clockwise) at a unix time, to about a degree (the astronomical
|
||||
almanac's low-precision formulae): enough for which facade it is on."""
|
||||
d = ts / 86400.0 + 2440587.5 - 2451545.0 # days since J2000.0
|
||||
g = math.radians((357.529 + 0.98560028 * d) % 360)
|
||||
q = (280.459 + 0.98564736 * d) % 360
|
||||
lam = math.radians((q + 1.915 * math.sin(g) + 0.020 * math.sin(2 * g)) % 360)
|
||||
eps = math.radians(23.439 - 0.00000036 * d)
|
||||
ra = math.atan2(math.cos(eps) * math.sin(lam), math.cos(lam))
|
||||
dec = math.asin(math.sin(eps) * math.sin(lam))
|
||||
gmst = (18.697374558 + 24.06570982441908 * d) % 24
|
||||
h = math.radians(gmst * 15 + lon) - ra # hour angle (west +)
|
||||
phi = math.radians(lat)
|
||||
elev = math.asin(math.sin(phi) * math.sin(dec) + math.cos(phi) * math.cos(dec) * math.cos(h))
|
||||
az = math.atan2(-math.sin(h) * math.cos(dec),
|
||||
math.sin(dec) * math.cos(phi) - math.cos(dec) * math.sin(phi) * math.cos(h))
|
||||
return math.degrees(elev), math.degrees(az) % 360
|
||||
|
||||
|
||||
def on_facade(elev: float, az: float, face: float | None) -> float:
|
||||
"""How much of the sun falls on a vertical window facing `face` (0..1;
|
||||
0 below 2° or behind it, or the facade not known)."""
|
||||
if face is None or elev <= 2:
|
||||
return 0.0
|
||||
x = math.cos(math.radians(elev)) * math.cos(math.radians(az - face))
|
||||
return max(0.0, x)
|
||||
|
||||
|
||||
def _minutes(hhmm: str) -> int | None:
|
||||
try:
|
||||
h, m = (int(x) for x in str(hhmm).split(":"))
|
||||
except ValueError:
|
||||
return None
|
||||
return h * 60 + m if 0 <= h < 24 and 0 <= m < 60 else None
|
||||
|
||||
|
||||
def quiet(local: datetime, start: str, end: str) -> bool:
|
||||
"""In the owner's quiet hours (start..end, local; over midnight too)."""
|
||||
a, b, x = _minutes(start), _minutes(end), local.hour * 60 + local.minute
|
||||
if a is None or b is None or a == b:
|
||||
return False
|
||||
return a <= x < b if a < b else (x >= a or x < b)
|
||||
|
||||
|
||||
def season_of(month: int, room_kind: str | None = None) -> str:
|
||||
"""heating or cooling: the room's control's kind (a thermostat's active
|
||||
side), else by month."""
|
||||
if room_kind in ("heating", "cooling"):
|
||||
return room_kind
|
||||
return "heating" if month in HEAT_MONTHS else "cooling"
|
||||
|
||||
|
||||
def schedule(d: dict, s: dict, ctx: dict | None = None) -> dict:
|
||||
"""The shade's moves over the plan's horizon. d: the model state's
|
||||
device (params, state); s: the model state (start, step_s, steps, tz,
|
||||
t_out, occupied, price_import, sky?, location?); ctx: the room
|
||||
(temp_c, setpoint_c, season). Out: {"set": [position or None per step],
|
||||
"why": [...], "pos": [the position expected per step, 0..100], "sun":
|
||||
[the sun on the facade, 0..1]}."""
|
||||
ctx = ctx or {}
|
||||
p, st = d.get("params") or {}, d.get("state") or {}
|
||||
T, step = int(s["steps"]), int(s["step_s"])
|
||||
zone = ZoneInfo(s.get("tz") or "UTC")
|
||||
loc = s.get("location") or {}
|
||||
lat, lon = loc.get("latitude"), loc.get("longitude")
|
||||
face = facing(p.get("facing"))
|
||||
fw = facade_words(face)
|
||||
lo, hi = (d.get("bounds") or {}).get("position_pct", [0, 100])[:2]
|
||||
|
||||
def clamp(x):
|
||||
return int(round(min(max(float(x), lo), hi)))
|
||||
open_pct, shade_pct, closed_pct = clamp(p.get("open_pct", 100)), clamp(p.get("shade_pct", 30)), \
|
||||
clamp(p.get("closed_pct", 0))
|
||||
min_move = float(p.get("min_move_s", 1800))
|
||||
night_ok = bool(float(p.get("night_moves", 0) or 0))
|
||||
qf, qt = str(p.get("quiet_from", "22:00")), str(p.get("quiet_to", "07:00"))
|
||||
prices = s.get("price_import") or [0.0] * T
|
||||
mean = sum(prices) / len(prices) if prices else 0.0
|
||||
sky = s.get("sky") or [1.0] * T
|
||||
t_out = s.get("t_out") or [10.0] * T
|
||||
occupied = s.get("occupied") or [1] * T
|
||||
temp, setpoint = ctx.get("temp_c"), ctx.get("setpoint_c")
|
||||
pos0 = st.get("position_pct")
|
||||
pos = float(pos0) if pos0 is not None else float(open_pct)
|
||||
sets, whys, track, suns = [], [], [], []
|
||||
ours = None # what the last rule moved it for (shade, night)
|
||||
last_move = -math.inf
|
||||
for k in range(T):
|
||||
ts = s["start"] + k * step
|
||||
local = datetime.fromtimestamp(ts, timezone.utc).astimezone(zone)
|
||||
if lat is None or lon is None:
|
||||
sets.append(None)
|
||||
whys.append("no site location: the sun's position is not known")
|
||||
track.append(pos)
|
||||
suns.append(0.0)
|
||||
continue
|
||||
elev, az = sun_position(ts + step / 2, float(lat), float(lon))
|
||||
sun = on_facade(elev, az, face) * max(0.0, min(1.0, float(sky[k] if k < len(sky) else 1.0)))
|
||||
suns.append(round(sun, 3))
|
||||
season = ctx.get("season") or season_of(local.month)
|
||||
want, why, kind = None, "", None
|
||||
if season == "cooling":
|
||||
ahead = prices[k:k + 12]
|
||||
dear = bool(ahead) and mean > 0 and sum(ahead) / len(ahead) > 1.1 * mean
|
||||
warm = (temp is not None and setpoint is not None and temp >= setpoint - 1.0) or \
|
||||
(k < len(t_out) and t_out[k] >= 24.0)
|
||||
if sun >= SUN_MIN and (warm or dear):
|
||||
kind = "shade"
|
||||
want = shade_pct if occupied[k] else closed_pct
|
||||
why = f"sun on the {fw} facade" + ("" if warm else ": before the dear hours")
|
||||
elif ours == "shade" and sun < SUN_MIN * 0.6:
|
||||
kind, want, why = None, open_pct, f"the sun has left the {fw} facade"
|
||||
else:
|
||||
cold = k >= len(t_out) or t_out[k] < 18.0
|
||||
if sun >= SUN_MIN and cold:
|
||||
kind, want, why = "gain", open_pct, f"winter sun on the {fw} facade: its warmth in"
|
||||
elif elev < -2 and local.hour >= 12 and (k >= len(t_out) or t_out[k] < 12.0):
|
||||
kind, want, why = "night", closed_pct, "night: closed to keep the warmth in"
|
||||
elif ours == "night" and elev > 2:
|
||||
kind, want, why = None, open_pct, "morning: open again"
|
||||
if want is not None and want > pos + 0.5 and elev <= 0:
|
||||
want = None # never opened in the dark (privacy)
|
||||
hushed = quiet(local, qf, qt) and not night_ok
|
||||
move = want is not None and abs(want - pos) > 2 and not hushed and ts - last_move >= min_move
|
||||
if move:
|
||||
pos, last_move, ours = float(want), ts, kind
|
||||
sets.append(int(want))
|
||||
whys.append(why)
|
||||
else:
|
||||
if want is not None and abs(want - pos) <= 2 and kind is None:
|
||||
ours = None # back where it was before the rule: nothing of ours to undo
|
||||
sets.append(None)
|
||||
whys.append("quiet hours" if hushed and want is not None and abs(want - pos) > 2 else "")
|
||||
track.append(pos)
|
||||
return {"set": sets, "why": whys, "pos": track, "sun": suns, "facade": face is not None}
|
||||
|
||||
|
||||
def say(set_value, lang: str = "en") -> str:
|
||||
"""A shade's move in words: "close to 30 %", "open", "close"."""
|
||||
try:
|
||||
v = float(set_value)
|
||||
except (TypeError, ValueError):
|
||||
return str(set_value)
|
||||
de = lang.split("-")[0] == "de"
|
||||
if v >= 99.5:
|
||||
return "öffnen" if de else "open"
|
||||
if v <= 0.5:
|
||||
return "schließen" if de else "close"
|
||||
return (f"auf {v:.0f} % schließen" if de else f"close to {v:.0f} %")
|
||||
|
||||
|
||||
DE_SIDE = {"north": "Nord", "north-east": "Nordost", "east": "Ost", "south-east": "Südost", "south": "Süd",
|
||||
"south-west": "Südwest", "west": "West", "north-west": "Nordwest"}
|
||||
DE_WHY = [("winter sun on the {} facade: its warmth in", "Wintersonne auf der {}seite: ihre Wärme herein"),
|
||||
("the sun has left the {} facade", "die Sonne hat die {}seite verlassen"),
|
||||
("sun on the {} facade: before the dear hours", "Sonne auf der {}seite: vor den teuren Stunden"),
|
||||
("sun on the {} facade", "Sonne auf der {}seite"),
|
||||
("night: closed to keep the warmth in", "Nacht: geschlossen, damit die Wärme drinnen bleibt"),
|
||||
("morning: open again", "Morgen: wieder offen")]
|
||||
|
||||
|
||||
def why_words(why: str, lang: str = "en") -> str:
|
||||
"""A shade's reason in the owner's language (English and German)."""
|
||||
if lang.split("-")[0] != "de" or not why:
|
||||
return why
|
||||
for en, de in DE_WHY:
|
||||
for side, word in ([("", "")] if "{}" not in en else DE_SIDE.items()):
|
||||
if why == en.format(side):
|
||||
return de.format(word)
|
||||
return why
|
||||
@@ -0,0 +1,263 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Uplinks. send() returns True only when the batch is safely stored on the
|
||||
other side; only then the queue deletes it.
|
||||
|
||||
NATS: JetStream publish, whose acknowledgement means the stream stored the
|
||||
message. The message id (site and sequence number) lets JetStream drop a
|
||||
batch sent twice (a lost acknowledgement, then a replay). Subject:
|
||||
<prefix>.<site_id>.tel (the scheme: ctb.site.<site_id>.<kind>).
|
||||
JSON for v0; Protobuf later.
|
||||
|
||||
link: the site's link (edge/link) over a local socket; in production the
|
||||
agent's only uplink (the NATS sink is for tests without a link).
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
import nats
|
||||
from nats.js.api import StreamConfig
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
# nats-py logs a traceback for every refused connection; the uploader logs
|
||||
# one line per failed attempt instead.
|
||||
logging.getLogger("nats.aio.client").setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
async def _quiet(e):
|
||||
pass
|
||||
|
||||
|
||||
def _encode(site: str, seq: int, kind: str, payload: dict) -> bytes:
|
||||
return json.dumps({"v": 1, "site": site, "seq": seq, "type": kind, **payload},
|
||||
separators=(",", ":")).encode()
|
||||
|
||||
|
||||
class FileSink:
|
||||
"""JSON lines; fsync before the acknowledgement."""
|
||||
|
||||
def __init__(self, path: str, site: str):
|
||||
self.path, self.site = path, site
|
||||
|
||||
async def send(self, seq, kind, payload) -> bool:
|
||||
with open(self.path, "ab") as f:
|
||||
f.write(_encode(self.site, seq, kind, payload) + b"\n")
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
return True
|
||||
|
||||
async def publish(self, kind: str, data: dict) -> bool:
|
||||
"""A plan or an action (best effort: no queue, the next plan follows)."""
|
||||
with open(self.path, "ab") as f:
|
||||
f.write(json.dumps({"site": self.site, "type": kind, "data": data}, separators=(",", ":")).encode() + b"\n")
|
||||
return True
|
||||
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class StdoutSink:
|
||||
def __init__(self, site: str):
|
||||
self.site = site
|
||||
|
||||
async def send(self, seq, kind, payload) -> bool:
|
||||
sys.stdout.write(_encode(self.site, seq, kind, payload).decode() + "\n")
|
||||
sys.stdout.flush()
|
||||
return True
|
||||
|
||||
async def publish(self, kind: str, data: dict) -> bool:
|
||||
sys.stdout.write(json.dumps({"site": self.site, "type": kind, "data": data}) + "\n")
|
||||
sys.stdout.flush()
|
||||
return True
|
||||
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class NatsSink:
|
||||
def __init__(self, url: str, site: str, prefix: str, ensure_stream: bool = False):
|
||||
self.url, self.site, self.ensure = url, site, ensure_stream
|
||||
self.subject = f"{prefix}.{site}.tel"
|
||||
self.prefix = prefix
|
||||
self.nc = self.js = None
|
||||
|
||||
async def _connect(self):
|
||||
# No reconnect inside nats-py: the uploader retries with its own
|
||||
# backoff and a fresh connection, and keeps everything queued.
|
||||
# nats-py 2.10 retries a first connect forever even so (seen in
|
||||
# tests): the timeout turns that into a failure.
|
||||
self.nc = await asyncio.wait_for(
|
||||
nats.connect(self.url, allow_reconnect=False, connect_timeout=5, max_reconnect_attempts=0,
|
||||
error_cb=_quiet), 10)
|
||||
self.js = self.nc.jetstream(timeout=5)
|
||||
if self.ensure:
|
||||
await self.js.add_stream(StreamConfig(name="CTB_SITE_TEL", subjects=[f"{self.prefix}.*.tel"],
|
||||
duplicate_window=120))
|
||||
|
||||
async def send(self, seq, kind, payload) -> bool:
|
||||
try:
|
||||
if self.nc is None or not self.nc.is_connected:
|
||||
await self._connect()
|
||||
await self.js.publish(self.subject, _encode(self.site, seq, kind, payload),
|
||||
headers={"Nats-Msg-Id": f"{self.site}:{seq}"})
|
||||
return True
|
||||
except Exception as e: # any failure: keep the batch, try later
|
||||
log.warning("nats: batch %d not sent: %s", seq, str(e) or type(e).__name__)
|
||||
await self.close()
|
||||
return False
|
||||
|
||||
async def publish(self, kind: str, data: dict) -> bool:
|
||||
"""Plans and actions on <prefix>.<site>.<kind> (core NATS, no stream)."""
|
||||
try:
|
||||
if self.nc is None or not self.nc.is_connected:
|
||||
await self._connect()
|
||||
await self.nc.publish(f"{self.prefix}.{self.site}.{kind}", json.dumps(data).encode())
|
||||
return True
|
||||
except Exception as e:
|
||||
log.warning("nats: %s not published: %s", kind, str(e) or type(e).__name__)
|
||||
return False
|
||||
|
||||
async def close(self):
|
||||
if self.nc is not None:
|
||||
try:
|
||||
await self.nc.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.nc = self.js = None
|
||||
|
||||
|
||||
class LinkSink:
|
||||
"""The site's link (edge/link, Go) over its local socket: the link holds
|
||||
the site's key and NATS connection; a batch counts as sent once the link
|
||||
says JetStream stored it. Commands the link passes on (mode, control,
|
||||
limits, release; checked and signed by the link) go to on_command, an
|
||||
async (cmd, args) -> (ok, message) the agent sets; plans and actions go
|
||||
out with publish()."""
|
||||
|
||||
def __init__(self, path: str, site: str):
|
||||
self.path, self.site = path, site
|
||||
self.r = self.w = None
|
||||
self.reader = None
|
||||
self.waits: dict[int, asyncio.Future] = {}
|
||||
self.n = 0
|
||||
self.state_wait: asyncio.Future | None = None
|
||||
self.lock: asyncio.Lock | None = None
|
||||
self.on_command = None
|
||||
|
||||
async def _ensure(self):
|
||||
"""Connected, once: the uploader and the announcer (cloud()) share it."""
|
||||
if self.lock is None:
|
||||
self.lock = asyncio.Lock()
|
||||
async with self.lock:
|
||||
if self.w is None or self.w.is_closing() or (self.reader and self.reader.done()):
|
||||
await self.close()
|
||||
await self._connect()
|
||||
|
||||
async def _connect(self):
|
||||
self.r, self.w = await asyncio.wait_for(asyncio.open_unix_connection(self.path, limit=1 << 20), 5)
|
||||
self.w.write(b'{"op":"hello"}\n')
|
||||
await self.w.drain()
|
||||
hello = json.loads(await asyncio.wait_for(self.r.readline(), 5))
|
||||
if hello.get("op") != "hello" or hello.get("site") != self.site:
|
||||
raise RuntimeError(f"the link is for site {hello.get('site')!r}, this agent for {self.site!r}")
|
||||
self.reader = asyncio.create_task(self._read())
|
||||
|
||||
async def _read(self):
|
||||
try:
|
||||
while line := await self.r.readline():
|
||||
m = json.loads(line)
|
||||
if m.get("op") == "ack" and (f := self.waits.pop(m.get("id"), None)) and not f.done():
|
||||
f.set_result(m)
|
||||
elif m.get("op") == "state" and self.state_wait and not self.state_wait.done():
|
||||
self.state_wait.set_result(bool(m.get("ok")))
|
||||
elif m.get("op") == "command":
|
||||
asyncio.create_task(self._command(m))
|
||||
except Exception as e:
|
||||
log.warning("link: %s", str(e) or type(e).__name__)
|
||||
finally:
|
||||
for f in self.waits.values():
|
||||
if not f.done():
|
||||
f.set_exception(ConnectionError("link closed"))
|
||||
self.waits.clear()
|
||||
|
||||
async def _command(self, m: dict):
|
||||
ok, msg = False, "the agent takes no commands"
|
||||
if self.on_command is not None:
|
||||
try:
|
||||
ok, msg = await self.on_command(str(m.get("cmd", "")), dict(m.get("args") or {}))
|
||||
except Exception as e: # an answer always goes back
|
||||
ok, msg = False, f"failed: {e}"
|
||||
log.info("command %s (%s): %s %s", m.get("id"), m.get("cmd"), "done" if ok else "refused", msg)
|
||||
try:
|
||||
self.w.write(json.dumps({"op": "result", "id": m.get("id"), "ok": bool(ok),
|
||||
"message": str(msg)[:500]}).encode() + b"\n")
|
||||
await self.w.drain()
|
||||
except Exception as e:
|
||||
log.warning("link: result %s not sent: %s", m.get("id"), e)
|
||||
|
||||
async def publish(self, kind: str, data: dict) -> bool:
|
||||
"""A plan or an action: the link publishes it (ctb.site.<id>.<kind>),
|
||||
within its limits (a plan every 5 min, 120 actions an hour)."""
|
||||
try:
|
||||
await self._ensure()
|
||||
self.w.write(json.dumps({"op": kind, "data": data}, separators=(",", ":")).encode() + b"\n")
|
||||
await self.w.drain()
|
||||
return True
|
||||
except Exception as e:
|
||||
log.warning("link: %s not sent: %s", kind, str(e) or type(e).__name__)
|
||||
return False
|
||||
|
||||
async def cloud(self) -> bool:
|
||||
"""The link's NATS connection is up (the link's "state")."""
|
||||
try:
|
||||
await self._ensure()
|
||||
self.state_wait = asyncio.get_running_loop().create_future()
|
||||
self.w.write(b'{"op":"state"}\n')
|
||||
await self.w.drain()
|
||||
return await asyncio.wait_for(self.state_wait, 5)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
async def send(self, seq, kind, payload) -> bool:
|
||||
try:
|
||||
await self._ensure()
|
||||
self.n += 1
|
||||
n, f = self.n, asyncio.get_running_loop().create_future()
|
||||
self.waits[n] = f
|
||||
data = json.loads(_encode(self.site, seq, kind, payload))
|
||||
self.w.write(json.dumps({"op": "tel", "id": n, "msg_id": f"{self.site}:{seq}", "data": data},
|
||||
separators=(",", ":")).encode() + b"\n")
|
||||
await self.w.drain()
|
||||
ack = await asyncio.wait_for(f, 20)
|
||||
if not ack.get("ok"):
|
||||
log.warning("link: batch %d not stored: %s", seq, ack.get("error", "?"))
|
||||
return bool(ack.get("ok"))
|
||||
except Exception as e: # any failure: keep the batch, try later
|
||||
log.warning("link: batch %d not sent: %s", seq, str(e) or type(e).__name__)
|
||||
await self.close()
|
||||
return False
|
||||
|
||||
async def close(self):
|
||||
if self.reader is not None:
|
||||
self.reader.cancel()
|
||||
if self.w is not None:
|
||||
try:
|
||||
self.w.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.r = self.w = self.reader = None
|
||||
|
||||
|
||||
def make(cfg) -> object:
|
||||
s = cfg.sink
|
||||
if s.kind == "file":
|
||||
return FileSink(s.path, cfg.site_id)
|
||||
if s.kind == "stdout":
|
||||
return StdoutSink(cfg.site_id)
|
||||
if s.kind == "link":
|
||||
return LinkSink(s.path, cfg.site_id)
|
||||
if s.kind == "nats":
|
||||
return NatsSink(s.url, cfg.site_id, s.subject_prefix, s.ensure_stream)
|
||||
raise ValueError(f"unknown sink {s.kind}")
|
||||
@@ -0,0 +1,54 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Store-and-forward queue: SQLite in WAL mode (a power cut loses at most the
|
||||
batch being written). Batches get a sequence number that never repeats,
|
||||
leave in order, and are deleted only when the uplink acknowledged them.
|
||||
Bounded: when full, the oldest batches go first and the drop is counted, so
|
||||
the platform can see the gap."""
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
|
||||
|
||||
class Queue:
|
||||
def __init__(self, path: str, max_batches: int):
|
||||
self.max = max_batches
|
||||
self.db = sqlite3.connect(path, isolation_level=None)
|
||||
self.db.execute("PRAGMA journal_mode=WAL")
|
||||
self.db.execute("PRAGMA synchronous=NORMAL")
|
||||
# AUTOINCREMENT: a number is never reused, even after deletes
|
||||
self.db.execute("CREATE TABLE IF NOT EXISTS batches (seq INTEGER PRIMARY KEY AUTOINCREMENT, "
|
||||
"created REAL NOT NULL, kind TEXT NOT NULL, payload TEXT NOT NULL)")
|
||||
self.db.execute("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value INTEGER NOT NULL)")
|
||||
|
||||
def put(self, kind: str, payload: dict) -> int:
|
||||
cur = self.db.execute("INSERT INTO batches (created, kind, payload) VALUES (?, ?, ?)",
|
||||
(time.time(), kind, json.dumps(payload, separators=(",", ":"))))
|
||||
over = self.depth() - self.max
|
||||
if over > 0:
|
||||
self.db.execute("DELETE FROM batches WHERE seq IN (SELECT seq FROM batches ORDER BY seq LIMIT ?)",
|
||||
(over,))
|
||||
self.db.execute("INSERT INTO meta VALUES ('dropped', ?) ON CONFLICT(key) "
|
||||
"DO UPDATE SET value = value + excluded.value", (over,))
|
||||
return cur.lastrowid
|
||||
|
||||
def peek(self, n: int = 50) -> list[tuple[int, str, dict]]:
|
||||
rows = self.db.execute("SELECT seq, kind, payload FROM batches ORDER BY seq LIMIT ?", (n,))
|
||||
return [(s, k, json.loads(p)) for s, k, p in rows]
|
||||
|
||||
def ack(self, seq: int):
|
||||
"""Delete batches up to and including seq (they leave in order)."""
|
||||
self.db.execute("DELETE FROM batches WHERE seq <= ?", (seq,))
|
||||
|
||||
def clear(self):
|
||||
"""Delete every queued batch (consent withdrawn)."""
|
||||
self.db.execute("DELETE FROM batches")
|
||||
|
||||
def depth(self) -> int:
|
||||
return self.db.execute("SELECT count(*) FROM batches").fetchone()[0]
|
||||
|
||||
def dropped(self) -> int:
|
||||
row = self.db.execute("SELECT value FROM meta WHERE key = 'dropped'").fetchone()
|
||||
return row[0] if row else 0
|
||||
|
||||
def close(self):
|
||||
self.db.close()
|
||||
@@ -0,0 +1,132 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Heating or cooling: one thermostat that can do both (a reversible A/C,
|
||||
hub/profiles/ha-thermostat.json) has two controls on its climate entity,
|
||||
a heating and a cooling one, both with the same `switchover`; only one of
|
||||
them is active at a time. The inactive one is not planned, never acts (the
|
||||
guard refuses it too), and a command to it is refused: two controls never
|
||||
write the same climate entity.
|
||||
|
||||
switchover: {mode: heating | cooling | season | outdoor,
|
||||
heat_below_c: 15, cool_above_c: 22} # outdoor only
|
||||
|
||||
heating, cooling the owner's fixed choice
|
||||
season heating October to April, cooling May to September
|
||||
(the site's local month)
|
||||
outdoor by the outdoor temperature (inputs.outside_temp, else
|
||||
the mapped outside.temp): heating below heat_below_c,
|
||||
cooling above cool_above_c, and between them (or while
|
||||
there is no reading) the side it was on (hysteresis: no
|
||||
flipping on a mild day); by season when it had no side yet
|
||||
|
||||
The owner picks it on the Hub panel's Devices page (the devices tool
|
||||
writes it into both controls of the device's fragment); the default for a
|
||||
thermostat that can do both is `season`. The side in force is kept in
|
||||
<state dir>/switchover.json, so a restart in the band keeps it.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
MODES = ("heating", "cooling", "season", "outdoor")
|
||||
HEAT_MONTHS = (10, 11, 12, 1, 2, 3, 4)
|
||||
DEFAULT_HEAT_BELOW_C = 15.0
|
||||
DEFAULT_COOL_ABOVE_C = 22.0
|
||||
|
||||
|
||||
def check(sw) -> dict:
|
||||
"""A control's switchover, checked; ValueError otherwise."""
|
||||
if not isinstance(sw, dict) or sw.get("mode") not in MODES or set(sw) - {"mode", "heat_below_c", "cool_above_c"}:
|
||||
raise ValueError(f"switchover: {{mode: {'|'.join(MODES)}, heat_below_c?, cool_above_c?}}")
|
||||
out = {"mode": sw["mode"]}
|
||||
if sw["mode"] == "outdoor":
|
||||
try:
|
||||
lo = float(sw.get("heat_below_c", DEFAULT_HEAT_BELOW_C))
|
||||
hi = float(sw.get("cool_above_c", DEFAULT_COOL_ABOVE_C))
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("switchover: heat_below_c and cool_above_c are numbers") from None
|
||||
if not -30 <= lo < hi <= 45:
|
||||
raise ValueError("switchover: heat_below_c below cool_above_c (°C)")
|
||||
out.update(heat_below_c=lo, cool_above_c=hi)
|
||||
return out
|
||||
|
||||
|
||||
def by_season(month: int) -> str:
|
||||
return "heating" if month in HEAT_MONTHS else "cooling"
|
||||
|
||||
|
||||
def side(sw: dict, month: int, t_out: float | None, prev: str | None) -> str:
|
||||
"""heating or cooling, by the switchover's rule."""
|
||||
mode = sw.get("mode", "season")
|
||||
if mode in ("heating", "cooling"):
|
||||
return mode
|
||||
if mode == "outdoor":
|
||||
if t_out is not None and t_out < sw.get("heat_below_c", DEFAULT_HEAT_BELOW_C):
|
||||
return "heating"
|
||||
if t_out is not None and t_out > sw.get("cool_above_c", DEFAULT_COOL_ABOVE_C):
|
||||
return "cooling"
|
||||
if prev in ("heating", "cooling"):
|
||||
return prev # in the band (or no reading for now): stays
|
||||
return by_season(month)
|
||||
|
||||
|
||||
def groups(controls) -> dict[str, list]:
|
||||
"""climate entity -> its paired heating and cooling controls."""
|
||||
out: dict[str, list] = {}
|
||||
for c in controls:
|
||||
ent = c.entities.get("climate")
|
||||
if ent and getattr(c, "switchover", None) and c.kind in ("heating", "cooling"):
|
||||
out.setdefault(ent, []).append(c)
|
||||
return {e: cs for e, cs in out.items() if {c.kind for c in cs} == {"heating", "cooling"}}
|
||||
|
||||
|
||||
class Switchover:
|
||||
def __init__(self, state_dir: str | None = None):
|
||||
self.path = os.path.join(state_dir, "switchover.json") if state_dir else None
|
||||
self.sides: dict[str, str] = {} # climate entity -> heating | cooling
|
||||
if self.path:
|
||||
try:
|
||||
with open(self.path) as f:
|
||||
self.sides = {k: v for k, v in (json.load(f).get("sides") or {}).items()
|
||||
if v in ("heating", "cooling")}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
self.inactive: set[str] = set()
|
||||
|
||||
def update(self, controls, now: float, tz: str = "UTC", t_out: float | None = None) -> bool:
|
||||
"""Which control of each pair is active now; True when that changed."""
|
||||
try:
|
||||
month = datetime.fromtimestamp(now, ZoneInfo(tz)).month
|
||||
except Exception:
|
||||
month = datetime.fromtimestamp(now, timezone.utc).month
|
||||
inactive, sides = set(), {}
|
||||
for ent, cs in groups(controls).items():
|
||||
s = side(cs[0].switchover, month, t_out, self.sides.get(ent))
|
||||
sides[ent] = s
|
||||
inactive |= {c.id for c in cs if c.kind != s}
|
||||
changed = inactive != self.inactive or sides != self.sides
|
||||
if sides != self.sides:
|
||||
for ent, s in sides.items():
|
||||
if self.sides.get(ent) != s:
|
||||
log.info("switchover: %s now %s", ent, s)
|
||||
self.sides = sides
|
||||
self._save()
|
||||
self.inactive = inactive
|
||||
return changed
|
||||
|
||||
def active(self, c) -> bool:
|
||||
return c.id not in self.inactive
|
||||
|
||||
def _save(self):
|
||||
if not self.path:
|
||||
return
|
||||
try:
|
||||
tmp = self.path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump({"sides": self.sides}, f)
|
||||
os.replace(tmp, self.path)
|
||||
except OSError as e:
|
||||
log.warning("switchover: %s", e)
|
||||
@@ -0,0 +1,95 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""1-minute aggregates.
|
||||
|
||||
Gauges (a level: power, temperature): time-weighted mean, min, max and the
|
||||
last value. A sample mean would overweight bursts of fast updates, so each
|
||||
value counts for as long as it held. A gauge's last value carries into the
|
||||
next window, so a steady sensor that reports rarely still has a mean.
|
||||
|
||||
Counters (a growing total: energy): the delta over the window. A total
|
||||
that goes down is a meter reset or replacement: the new reading counts
|
||||
from zero instead of a negative delta.
|
||||
|
||||
Unavailable: seconds of the window without a valid value are reported, so
|
||||
the platform can tell "0 W" from "unknown".
|
||||
"""
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Gauge:
|
||||
value: float | None = None # the value holding since `since`
|
||||
since: float = 0.0
|
||||
area: float = 0.0 # value x seconds within the window
|
||||
valid_s: float = 0.0
|
||||
lo: float | None = None
|
||||
hi: float | None = None
|
||||
n: int = 0
|
||||
|
||||
def _hold(self, until: float):
|
||||
if self.value is not None and until > self.since:
|
||||
self.area += self.value * (until - self.since)
|
||||
self.valid_s += until - self.since
|
||||
self.since = until
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Counter:
|
||||
last: float | None = None
|
||||
delta: float = 0.0
|
||||
resets: int = 0
|
||||
n: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class Aggregator:
|
||||
interval: int = 60
|
||||
start: float = 0.0
|
||||
gauges: dict = field(default_factory=dict)
|
||||
counters: dict = field(default_factory=dict)
|
||||
|
||||
def begin(self, ts: float):
|
||||
self.start = ts - ts % self.interval
|
||||
|
||||
def sample(self, asset: str, kind: str, value: float | None, ts: float):
|
||||
"""value None = unavailable / unknown / not a number."""
|
||||
if kind == "counter":
|
||||
c = self.counters.setdefault(asset, _Counter())
|
||||
if value is None:
|
||||
return
|
||||
if c.last is not None:
|
||||
if value >= c.last:
|
||||
c.delta += value - c.last
|
||||
else:
|
||||
c.delta += value
|
||||
c.resets += 1
|
||||
c.last, c.n = value, c.n + 1
|
||||
return
|
||||
g = self.gauges.setdefault(asset, _Gauge(since=self.start))
|
||||
g._hold(max(ts, self.start))
|
||||
g.value = value
|
||||
if value is not None:
|
||||
g.lo = value if g.lo is None else min(g.lo, value)
|
||||
g.hi = value if g.hi is None else max(g.hi, value)
|
||||
g.n += 1
|
||||
|
||||
def flush(self, end: float) -> list[dict]:
|
||||
"""Records for [start, end); the next window starts at end."""
|
||||
span = end - self.start
|
||||
out = []
|
||||
for asset, g in sorted(self.gauges.items()):
|
||||
g._hold(end)
|
||||
rec = {"asset": asset, "kind": "gauge", "n": g.n,
|
||||
"unavailable_s": round(span - g.valid_s, 3)}
|
||||
if g.valid_s > 0:
|
||||
rec.update(mean=g.area / g.valid_s, min=g.lo if g.lo is not None else g.value,
|
||||
max=g.hi if g.hi is not None else g.value, last=g.value)
|
||||
out.append(rec)
|
||||
# carry the holding value; min/max start from it
|
||||
self.gauges[asset] = _Gauge(value=g.value, since=end, lo=g.value, hi=g.value)
|
||||
for asset, c in sorted(self.counters.items()):
|
||||
out.append({"asset": asset, "kind": "counter", "delta": c.delta, "last": c.last,
|
||||
"resets": c.resets, "n": c.n})
|
||||
self.counters[asset] = _Counter(last=c.last)
|
||||
self.start = end
|
||||
return out
|
||||
Reference in new issue
Block a user