From 85edd56ec84f07edf9323b39e9265101ac7fe9b3 Mon Sep 17 00:00:00 2001
From: "Setti Solutions S.R.L"
Date: Tue, 3 Nov 2026 23:26:41 +0200
Subject: [PATCH] cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.629:
full source
---
README.md | 2 +-
cantabile_edge/CHANGELOG.md | 16 +
cantabile_edge/config.yaml | 2 +-
cantabile_eebus/config.yaml | 2 +-
cantabile_modbus/config.yaml | 2 +-
src/edge/cantabile_edge/agent.py | 36 +-
src/edge/cantabile_edge/announce.py | 178 +++++++++-
src/edge/cantabile_edge/bundles.py | 253 +++++++++++++-
src/edge/cantabile_edge/config.py | 4 +
src/edge/cantabile_edge/controller.py | 85 ++++-
src/edge/cantabile_edge/controls.py | 37 +-
src/edge/cantabile_edge/dashboards.py | 189 +++++++++--
src/edge/cantabile_edge/devpage.py | 453 ++++++++++++++++++-------
src/edge/cantabile_edge/devprofiles.py | 99 ++++++
src/edge/cantabile_edge/evphases.py | 165 +++++++++
src/edge/cantabile_edge/gridorder.py | 43 ++-
src/edge/cantabile_edge/i18n_de.py | 111 +++++-
src/edge/cantabile_edge/inputs.py | 136 +++++++-
src/edge/cantabile_edge/inventory.py | 54 ++-
src/edge/cantabile_edge/mapping.py | 31 ++
src/edge/cantabile_edge/names.py | 57 ++++
src/edge/cantabile_edge/optimizer.py | 208 ++++++++++--
src/edge/link/bundles.go | 8 +-
src/edge/link/bundles_test.go | 24 ++
src/edge/link/hub.go | 23 ++
src/edge/link/hub_setup_test.go | 21 ++
src/edge/link/main.go | 35 +-
src/edge/link/main_test.go | 34 ++
src/edge/link/netstate.go | 86 +++++
src/edge/link/netstate_test.go | 42 +++
src/edge/tests/test_agent.py | 25 ++
src/edge/tests/test_base_load.py | 185 ++++++++++
src/edge/tests/test_control_parts.py | 21 ++
src/edge/tests/test_dashboard_heat.py | 74 ++++
src/edge/tests/test_dashboard_homes.py | 2 +-
src/edge/tests/test_dashboards.py | 76 ++++-
src/edge/tests/test_devpage.py | 34 +-
src/edge/tests/test_evphases.py | 184 ++++++++++
src/edge/tests/test_gridorder.py | 48 ++-
src/edge/tests/test_inputs_fresh.py | 25 ++
src/edge/tests/test_market_bundle.py | 184 ++++++++++
src/edge/tests/test_market_plan.py | 221 ++++++++++++
src/edge/tests/test_model_series.py | 199 +++++++++++
src/edge/tests/test_optimizer.py | 35 ++
src/edge/tests/test_policy.py | 30 ++
src/edge/tests/test_shades.py | 6 +-
46 files changed, 3518 insertions(+), 267 deletions(-)
create mode 100644 src/edge/cantabile_edge/evphases.py
create mode 100644 src/edge/link/netstate.go
create mode 100644 src/edge/link/netstate_test.go
create mode 100644 src/edge/tests/test_base_load.py
create mode 100644 src/edge/tests/test_dashboard_heat.py
create mode 100644 src/edge/tests/test_evphases.py
create mode 100644 src/edge/tests/test_inputs_fresh.py
create mode 100644 src/edge/tests/test_market_bundle.py
create mode 100644 src/edge/tests/test_market_plan.py
create mode 100644 src/edge/tests/test_model_series.py
diff --git a/README.md b/README.md
index 1b86262..237fa50 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,7 @@ Settings → Add-ons → Add-on store → ⋮ → Repositories, add
`https://git.setti.solutions/Daniel/cantabile-ha-addons`, then install the
add-on. The Supervisor pulls the prebuilt images
(`git.setti.solutions/daniel/cantabile-ha--:`,
-named by `image:` in each `config.yaml`); this version: `0.1.400`, arch amd64.
+named by `image:` in each `config.yaml`); this version: `0.1.629`, arch amd64.
## Layout
diff --git a/cantabile_edge/CHANGELOG.md b/cantabile_edge/CHANGELOG.md
index 6483093..f506e29 100644
--- a/cantabile_edge/CHANGELOG.md
+++ b/cantabile_edge/CHANGELOG.md
@@ -6,6 +6,22 @@ names the commit; the agent inside is the Edge Agent image of that commit.
## 0.1.x
+- The Devices page is clearer: the devices you use with Cantabile are a
+ short list, each with its state in words ("In use · reading on · control
+ on" or "Added · reading off"), its main values now ("21.5 °C, set to
+ 22 °C, heating") and whether it is protected. Open a device to change it:
+ reading and control switch at once, what it reads is said in plain words
+ ("room temperature (Living room), setpoint, heating/cooling state"), and
+ heating or cooling, room and window, indoor or outdoor and protection
+ each save on their own (Save shows once you change something). Removing
+ asks you to confirm. "Untested" profiles are marked with a small badge and
+ an "i" that explains it. Devices you can still add are listed apart,
+ below; a device in use is never offered again.
+- Heat is shown as heat: a heat meter's or heat pump's heat is "Heat from
+ the building (thermal)" or "Heat delivered (thermal)", in kW and kWh, in
+ its own band below solar, home, grid and battery, never added to the
+ electricity. With your own heat pump its electric power and its COP are
+ shown beside the heat.
- Blinds, curtains, shutters and awnings: the Devices page offers any of
Home Assistant's covers (never a garage door, gate, door, damper or
window). You set the room it shades and which way the window faces.
diff --git a/cantabile_edge/config.yaml b/cantabile_edge/config.yaml
index 8f583b9..92bff3e 100644
--- a/cantabile_edge/config.yaml
+++ b/cantabile_edge/config.yaml
@@ -3,7 +3,7 @@
# the Hub's, wrapped by addon-run (Dockerfile). The image is prebuilt,
# per arch (README.md: building it from src/).
name: Cantabile Edge Agent
-version: "0.1.400"
+version: "0.1.629"
slug: cantabile_edge
description: Plans your home's energy with Cantabile and, with your consent, runs the devices you choose.
url: https://cantabile.cloud
diff --git a/cantabile_eebus/config.yaml b/cantabile_eebus/config.yaml
index 7b18671..c597e6d 100644
--- a/cantabile_eebus/config.yaml
+++ b/cantabile_eebus/config.yaml
@@ -4,7 +4,7 @@
# Assistant that isn't a Cantabile Hub. Devices are paired on its page
# (ingress), by their SKI.
name: Cantabile EEBUS
-version: "0.1.400"
+version: "0.1.629"
slug: cantabile_eebus
description: Pairs with EEBUS devices (the grid operator's control box, heat pumps, wallboxes, inverters), shows them in Home Assistant under Cantabile's names and hands the grid operator's §14a limit to the Cantabile agent; every control with its protection.
url: https://cantabile.cloud
diff --git a/cantabile_modbus/config.yaml b/cantabile_modbus/config.yaml
index c016290..7512fc7 100644
--- a/cantabile_modbus/config.yaml
+++ b/cantabile_modbus/config.yaml
@@ -4,7 +4,7 @@
# Home Assistant that isn't a Cantabile Hub. Devices come from the options;
# the page (ingress) shows them and each control's protection.
name: Cantabile Modbus bridge
-version: "0.1.400"
+version: "0.1.629"
slug: cantabile_modbus
description: Reads inverters, meters, relays and circuits by Cantabile's device profiles (Modbus, or Home Assistant's own entities) and shows them in Home Assistant, each control with its protection.
url: https://cantabile.cloud
diff --git a/src/edge/cantabile_edge/agent.py b/src/edge/cantabile_edge/agent.py
index ecb9908..21b07fd 100644
--- a/src/edge/cantabile_edge/agent.py
+++ b/src/edge/cantabile_edge/agent.py
@@ -21,6 +21,7 @@ from .consent import Consent
from .controller import Controller
from .inventory import Inventory
from .dashboards import Dashboards
+from .gridorder import GridOrders
from .devpage import App, Devices
from .joinpage import Fleet
from .mapping import Mapping, convert, scaled, value_of
@@ -61,9 +62,14 @@ class Agent:
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 grid operator's orders (EEBUS LPC, gridorder.py): the controller's,
+ # or, on a site without controls, checked and told to the cloud only
+ self.gridorders = self.control.gridorders if self.control is not None else GridOrders(cfg.state_dir)
# 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)
+ if self.control is not None:
+ self.inventory.ev_phases = self.control.ev_phases
self.client = None
self.exit_code = 0 # RESTART: start again (restart())
# A mapping for a site without one (propose.py): the HA add-on
@@ -234,10 +240,10 @@ class Agent:
async def inventory_loop(self):
"""The inventory at connecting, then every 30 minutes if it changed
- (and once a day anyway)."""
+ (and once a day anyway); every minute while the link is not connected."""
while not self.stop.is_set():
try:
- await asyncio.wait_for(self.inventory_now.wait(), 1800)
+ await asyncio.wait_for(self.inventory_now.wait(), 60 if self.inventory.waiting else 1800)
except asyncio.TimeoutError:
pass
self.inventory_now.clear()
@@ -263,6 +269,27 @@ class Agent:
time.strftime("%H:%M", time.gmtime(start)), seq, len(records),
self.queue.depth(), self.queue.dropped())
+ async def grid_order(self, payload) -> bool:
+ """A message on cantabile-eebus/gridorder (announce.py): the
+ controller's when there is one (limits and a plan within them);
+ otherwise only checked and told to the cloud (nothing to limit)."""
+ if self.control is not None:
+ return await self.control.grid_order(payload)
+ changed, _ = self.gridorders.take(payload)
+ await self.grid_report()
+ return changed
+
+ async def grid_report(self):
+ """The grid operator's order to the cloud as an action per
+ quarter-hour (gridorder.py action()): fleet's market ledger exempts
+ those slots."""
+ if self.control is not None:
+ return await self.control.grid_report()
+ a = self.gridorders.action()
+ pub = getattr(self.sink, "publish", None)
+ if a is not None and pub is not None:
+ await pub("action", a)
+
async def ticker(self):
i = self.cfg.interval_s
while not self.stop.is_set():
@@ -271,6 +298,11 @@ class Agent:
await asyncio.wait_for(self.stop.wait(), max(0.0, end - time.time()))
except asyncio.TimeoutError:
self.close_window(end)
+ if self.control is None: # the controller's own loop reports otherwise
+ try:
+ await self.grid_report()
+ except Exception as e:
+ log.warning("grid order report: %s", e)
async def uploader(self):
wait = 1.0
diff --git a/src/edge/cantabile_edge/announce.py b/src/edge/cantabile_edge/announce.py
index 56cae8a..15e535b 100644
--- a/src/edge/cantabile_edge/announce.py
+++ b/src/edge/cantabile_edge/announce.py
@@ -27,6 +27,15 @@ building and the home, and what the agent does to each device):
sensor set_ 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
+ sensor market_, market_position[_building], market_price, market_actuator_
+ the shadow market (market.json, a signed `market`
+ bundle): per contract the exchange with its
+ counterpart (kW in the last settled quarter-hour,
+ a sentence in plain words, the period), the net
+ position, the shared energy's price, per border
+ actuator its contract target vs its state now;
+ sensors only, unavailable when the bundle is
+ stale (cantabile//market/availability)
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
@@ -229,6 +238,162 @@ class Announcer:
"json_attributes_template": "{{ {'commands': value_json.commands} | tojson }}", **common}
return out
+ # -- the shadow market (a `market` bundle: bundles.py) -------------------
+ def _market_avail(self) -> dict:
+ """Unavailable when the agent is offline or the bundle is stale."""
+ return {"availability": [{"topic": f"{self.base}/availability"}, {"topic": f"{self.base}/market/availability"}],
+ "availability_mode": "all"}
+
+ @staticmethod
+ def _party(c: dict, lang: str) -> str:
+ p = c.get("counterpart") or {}
+ if p.get("type") == "homes":
+ return names.name("mk_flats", lang, p.get("count") or "")
+ return p.get("name") or p.get("type") or "?"
+
+ def _market_objects(self, m: dict | None) -> dict:
+ """Per contract the exchange with its counterpart, the net position
+ of each of the box's nodes, the shared energy's price, per border
+ actuator its contract target: sensors only (never a control: the
+ actuators keep their own entities and protection)."""
+ ctl = getattr(self.agent, "control", None)
+ if m is None or (ctl is not None and ctl.mode() == "off"):
+ return {}
+ dev, out, lang = self._device(), {}, self.lang
+ common = {"state_topic": f"{self.base}/market", "json_attributes_topic": f"{self.base}/market",
+ **self._market_avail(), "device": dev}
+ for c in m.get("contracts") or []:
+ k = _slug(c["id"])
+ out[("sensor", f"market_{k}")] = {
+ "name": names.name("market_exchange", lang, self._party(c, lang)), "unique_id": f"{self.uid}_market_{k}",
+ "unit_of_measurement": "kW", "device_class": "power", "state_class": "measurement", "icon": "mdi:swap-horizontal",
+ "value_template": "{%% set v = value_json.contracts['%s'].kw %%}{{ v if v is not none else none }}" % k,
+ "json_attributes_template": "{{ value_json.contracts['%s'] | tojson }}" % k, **common}
+ nodes = {n.get("id"): n.get("name") for n in m.get("nodes") or []}
+ for p in m.get("positions") or []:
+ kind = str(p.get("node", "")).split(":")[0]
+ obj = "market_position" if kind == "site" else f"market_position_{_slug(kind)}"
+ out[("sensor", obj)] = {
+ "name": names.name("market_position", lang) if kind == "site" else
+ names.name("market_position_of", lang, nodes.get(p.get("node")) or kind),
+ "unique_id": f"{self.uid}_{obj}", "unit_of_measurement": "kWh", "state_class": "measurement",
+ "icon": "mdi:scale-balance",
+ "value_template": "{{ value_json.positions['%s'].net_kwh }}" % obj,
+ "json_attributes_template": "{{ value_json.positions['%s'] | tojson }}" % obj, **common}
+ if m.get("contracts"):
+ out[("sensor", "market_price")] = {
+ "name": names.name("market_price", lang), "unique_id": f"{self.uid}_market_price",
+ "unit_of_measurement": "EUR/kWh", "suggested_display_precision": 3, "state_class": "measurement",
+ "icon": "mdi:cash-multiple",
+ "value_template": "{% set v = value_json.price.now %}{{ (v / 100) | round(4) if v is not none else none }}",
+ "json_attributes_template": "{{ value_json.price | tojson }}", **common}
+ for a in m.get("actuators") or []:
+ k = _slug(a["device"])
+ out[("sensor", f"market_actuator_{k}")] = {
+ "name": names.name("market_actuator", lang, a.get("name") or a["device"]),
+ "unique_id": f"{self.uid}_market_actuator_{k}", "icon": "mdi:electric-switch",
+ "value_template": "{{ value_json.actuators['%s'].target }}" % k,
+ "json_attributes_template": "{{ value_json.actuators['%s'] | tojson }}" % k, **common}
+ return out
+
+ def _actual(self, device: str):
+ """A border actuator's state in HA now, from the agent's own view of
+ the device's controls (None: not one the agent watches)."""
+ ctl = getattr(self.agent, "control", None)
+ col = getattr(ctl, "col", None)
+ if ctl is None or col is None:
+ return None
+ for c in ctl.controls:
+ if getattr(c, "device", "") == device:
+ for eid in (c.entities or {}).values():
+ st = col.state(eid)
+ if st is not None:
+ return st
+ return None
+
+ def market_state(self, m: dict) -> dict:
+ """The market's values for HA: per contract (kW in the last settled
+ quarter-hour, a sentence in plain words, the details), positions,
+ the price now, the actuators' target and actual state."""
+ lang = self.lang
+ num = names.number
+ out = {"contracts": {}, "positions": {}, "actuators": {}, "price": {}, "shadow": True, "stale": bool(m.get("stale")),
+ "note": names.name("mk_shadow_note", lang), "issued": m.get("issued"), "slot": m.get("slot")}
+ links = {lk.get("id"): lk for lk in m.get("links") or []}
+ prices, applying = {}, []
+ for c in m.get("contracts") or []:
+ k = _slug(c["id"])
+ last, slot, per = c.get("last") or None, c.get("slot") or {}, c.get("period") or {}
+ party = self._party(c, lang)
+ head = names.name("mk_sells" if c["direction"] == "sells" else "mk_buys", lang, party)
+ kw = None
+ if last and last.get("measured"):
+ d = float(last.get("delivered_kwh") or 0)
+ kw = round(d * 4, 3)
+ amount = float(last.get("max_kwh") or 0) or float(last.get("guaranteed_kwh") or 0)
+ part = names.name("mk_slot", lang, num(d, lang, 2), num(amount, lang, 2)) if amount > 0 else \
+ names.name("mk_slot_open", lang, num(d, lang, 2))
+ else:
+ part = names.name("mk_no_value", lang)
+ price = slot.get("price_ct")
+ bits = [f"{head}: {part}"]
+ if price is not None:
+ bits.append(f"{num(float(price), lang)} ct/kWh")
+ prices[k] = price
+ if slot.get("applies"):
+ applying.append(float(price))
+ if not slot.get("applies"):
+ bits.append(names.name("mk_not_now", lang))
+ bits.append(names.name("mk_shadow", lang))
+ details = []
+ if last and last.get("kind") and last.get("deviation_kwh"):
+ dev = num(abs(float(last["deviation_kwh"])), lang, 2)
+ details.append(names.name("mk_deviation_self" if last.get("cause") == "self" else "mk_deviation_other", lang, dev))
+ if last.get("exempt"):
+ details.append(names.name("mk_exempt", lang, last.get("exempt_why") or ""))
+ pname = names.name("mk_" + (per.get("period") or "month"), lang) if ("mk_" + (per.get("period") or "month")) in names.NAMES \
+ else per.get("period", "")
+ period = names.name("mk_period", lang, pname, num(float(per.get("delivered_kwh") or 0), lang),
+ num(float(per.get("amount_eur") or 0), lang, 2))
+ if per.get("penalties_paid_eur") or per.get("penalties_received_eur"):
+ period += " · " + names.name("mk_penalties", lang, num(float(per.get("penalties_paid_eur") or 0), lang, 2),
+ num(float(per.get("penalties_received_eur") or 0), lang, 2))
+ meas = (links.get(c.get("link")) or {}).get("measurement") or {}
+ out["contracts"][k] = {
+ "kw": kw, "summary": " · ".join(bits), "details": "; ".join(details), "period_words": period,
+ "contract": c["id"], "name": c.get("name", ""), "direction": c["direction"], "counterpart": party,
+ "counterpart_type": (c.get("counterpart") or {}).get("type", ""), "link_kind": c.get("link_kind", ""),
+ "slot": slot, "last": last, "period": per, "kwh_period": per.get("delivered_kwh"), "price_ct": price,
+ "penalty_last_eur": (last or {}).get("penalty_eur"), "measurement": meas.get("kind", ""),
+ "trust": meas.get("trust", ""), "shadow": True}
+ out["price"] = {"now": round(sum(applying) / len(applying), 3) if applying else None, "unit": "ct/kWh",
+ "per_contract": prices}
+ for p in m.get("positions") or []:
+ kind = str(p.get("node", "")).split(":")[0]
+ obj = "market_position" if kind == "site" else f"market_position_{_slug(kind)}"
+ out["positions"][obj] = dict(p)
+ for a in m.get("actuators") or []:
+ k = _slug(a["device"])
+ tgt = a.get("target") or {}
+ actual = self._actual(a["device"])
+ if actual is None and a.get("last"):
+ actual = a["last"].get("value")
+
+ def say(x):
+ return names.name(f"mk_state_{x}", lang) if f"mk_state_{x}" in names.NAMES else \
+ (str(x) if x not in (None, "") else names.name("mk_unknown", lang))
+ kwb = f" ({num(float(tgt['kw']), lang)} kW)" if tgt.get("kw") is not None else ""
+ words = (f"{names.name('mk_target', lang)}: **{say(tgt.get('state'))}**{kwb} · {names.name('mk_actual', lang)}: "
+ f"**{say(actual)}** · {names.name('mk_protection', lang, a.get('protection') or 'none')} · "
+ + names.name("mk_default", lang, say(a.get("default_state")), int((a.get("fallback_s") or 0) // 60)))
+ out["actuators"][k] = {"target": tgt.get("state"), "target_kw": tgt.get("kw"), "why": tgt.get("why", ""),
+ "actual": actual, "agrees": actual is not None and str(actual) == str(tgt.get("state")),
+ "words": words, "device": a["device"], "name": a.get("name", ""), "link": a.get("link"),
+ "protection": a.get("protection"), "default_state": a.get("default_state"),
+ "default_set": a.get("default_set"), "fallback_s": a.get("fallback_s"),
+ "last": a.get("last"), "shadow": True}
+ 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."""
@@ -236,7 +401,8 @@ class Announcer:
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():
+ **self._exchange_objects(tariff, model),
+ **self._market_objects(self.bundles.market_now(now))}.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
@@ -332,6 +498,10 @@ class Announcer:
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)
+ market = self.bundles.market_now(now)
+ if market is not None:
+ await c.publish(f"{self.base}/market/availability", "offline" if market["stale"] else "online", retain=True)
+ await c.publish(f"{self.base}/market", json.dumps(self.market_state(market), default=str), 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)
@@ -371,13 +541,13 @@ class Announcer:
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:
+ take = getattr(self.agent, "grid_order", None)
+ if take is None:
return
def on(topic, payload):
if topic == gridorder.TOPIC and payload:
- asyncio.ensure_future(ctl.grid_order(payload))
+ asyncio.ensure_future(take(payload))
c.on_message = on
try:
await c.subscribe(gridorder.TOPIC)
diff --git a/src/edge/cantabile_edge/bundles.py b/src/edge/cantabile_edge/bundles.py
index 73db879..d6bea7d 100644
--- a/src/edge/cantabile_edge/bundles.py
+++ b/src/edge/cantabile_edge/bundles.py
@@ -1,5 +1,6 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
-"""Data bundles the optimiser reads: tariffs and the forecast model.
+"""Data bundles the optimiser reads: tariffs and the forecast model (and,
+for Home Assistant only, a building's flats and the shadow market).
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
@@ -24,10 +25,35 @@ Model v1 (the forecasts' data; the ML in ml/ is a placeholder, 2026-10-28):
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.
+ Optional (2026-10-30; an older agent ignores them):
+ - per series "series": {"start": , "step_s": 900,
+ "values": [at most 400 numbers]}: the cloud's trained forecast (W) for
+ the next ~48 h; where it covers a step it is taken, elsewhere the
+ hour_of_week profile.
+ - "rooms": {"": {"r_k_per_kw": 0.5-200, "c_kwh_per_k": 0.1-100,
+ "power": "thermal"|"electric" (default thermal), ...}}: a room's R and C
+ identified in the cloud from its history (electric: fitted against the
+ heating's electric power; inputs.model_state converts with the cop).
+ Only from a model for this site (not "*"). A heating or cooling control
+ takes its room by its id, its id without _heating/_cooling/_heat/_cool,
+ its area, or, as the site's only such control, the model's only room
+ (room_rc). The mapping's own r_k_per_kw/c_kwh_per_k win.
+ - forecasts "base_load_w" (2026-11-03, Finding A2-a): the load without the
+ devices the box plans (load.power less heatpump.power, ac.power and
+ ev.power where the site has those controls); the plan's load. A model
+ without it: its load_w only where the box has no meter of a planned
+ device inside the load (inputs.model_state), else the box's history.
+ - per room "gain_w" (a constant internal gain, W of heat, or 24 values by
+ local hour) and "solar_w_per_kw" (W of heat per kW/m² of global
+ irradiance) (2026-11-03, Finding B6-a): the fit's other terms, taken
+ into the room's model with R and C (room_rc). Absent: 0, as before.
+ A malformed series or room refuses the whole bundle.
"""
import json
import logging
+import math
import os
+import re
import time
from dataclasses import dataclass
from datetime import datetime, timezone
@@ -85,14 +111,60 @@ def _check_tariff(d: dict):
raise ValueError("no import price")
+SERIES_MAX = 400 # a model's series: steps of 900 s (~4 days)
+ROOM_R = (0.5, 200.0) # K/kW
+ROOM_C = (0.1, 100.0) # kWh/K
+ROOM_SUFFIX = re.compile(r"_(heating|cooling|heat|cool)$")
+# a room's fitted gains (Finding B6-a), as the planner takes them: outside
+# these the fit's artefact (a negative sun, a gain above any home's) is cut
+ROOM_GAIN_W = (-2000.0, 5000.0) # W of heat, internal (people, appliances)
+ROOM_SOLAR_M2 = (0.0, 50.0) # W of heat per W/m² of global irradiance
+
+
+def _clip(x: float, lo_hi) -> float:
+ return min(max(float(x), lo_hi[0]), lo_hi[1])
+
+
+def _finite(x) -> bool:
+ return isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x)
+
+
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:
+ if not isinstance(f, dict) or 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")
+ s = f.get("series")
+ if s is None:
+ continue
+ if not isinstance(s, dict) or s.get("step_s") != 900 or not _finite(s.get("start")) or s["start"] % 900:
+ raise ValueError(f"{name}: a series in steps of 900 s from a quarter hour")
+ v = s.get("values")
+ if not isinstance(v, list) or len(v) > SERIES_MAX or not all(_finite(x) for x in v):
+ raise ValueError(f"{name}: a series of at most {SERIES_MAX} numbers")
+ rooms = d.get("rooms")
+ if rooms is None:
+ return
+ if not isinstance(rooms, dict):
+ raise ValueError("rooms: an object")
+ for key, r in rooms.items():
+ if not isinstance(r, dict):
+ raise ValueError(f"room {key}: an object")
+ rk, ck = r.get("r_k_per_kw"), r.get("c_kwh_per_k")
+ if not _finite(rk) or not ROOM_R[0] <= rk <= ROOM_R[1]:
+ raise ValueError(f"room {key}: r_k_per_kw {ROOM_R[0]}-{ROOM_R[1]}")
+ if not _finite(ck) or not ROOM_C[0] <= ck <= ROOM_C[1]:
+ raise ValueError(f"room {key}: c_kwh_per_k {ROOM_C[0]}-{ROOM_C[1]}")
+ if r.get("power", "thermal") not in ("thermal", "electric"):
+ raise ValueError(f"room {key}: power thermal or electric")
+ g = r.get("gain_w")
+ if g is not None and not (_finite(g) or (isinstance(g, list) and len(g) == 24 and all(_finite(x) for x in g))):
+ raise ValueError(f"room {key}: gain_w a number or 24 numbers (by local hour)")
+ if r.get("solar_m2") is not None and not _finite(r["solar_m2"]):
+ raise ValueError(f"room {key}: solar_m2 a number")
def _check_flats(d: dict):
@@ -108,6 +180,32 @@ def _check_flats(d: dict):
raise ValueError("flat label: a string")
+MARKET_STALE_S = 4 * 900 # without stale_after_s in the bundle: four slots
+
+
+def _check_market(d: dict):
+ """The shadow market's values for this box's own nodes (fleet's
+ marketbundle.go, the market's step 1.5). Written by the link from a
+ signed `market` bundle; shown in HA (announce.py, dashboards.py), never
+ acted on: a bundle that is not marked shadow-only is refused."""
+ if d.get("v") != 1 or d.get("kind") != "market":
+ raise ValueError("not a v1 market bundle")
+ if d.get("shadow") is not True or d.get("commands") != "none":
+ raise ValueError("a market bundle is shadow only (commands: none)")
+ for key, most in (("contracts", 200), ("links", 200), ("actuators", 100), ("positions", 10), ("nodes", 10)):
+ v = d.get(key) or []
+ if not isinstance(v, list) or len(v) > most:
+ raise ValueError(f"{key}: a list of at most {most}")
+ for c in d.get("contracts") or []:
+ if not isinstance(c.get("id"), str) or not c["id"] or len(c["id"]) > 80:
+ raise ValueError("contract id: a string")
+ if c.get("direction") not in ("sells", "buys"):
+ raise ValueError("contract direction: sells or buys")
+ for a in d.get("actuators") or []:
+ if not isinstance(a.get("device"), str) or not a["device"] or len(a["device"]) > 80:
+ raise ValueError("actuator device: a string")
+
+
@dataclass
class Prices:
import_ct: list[float]
@@ -115,12 +213,49 @@ class Prices:
note: str # what the prices are ("tariff ", "flat fallback ...")
+def _ahead_terms(ah, start: int, step_s: int, steps: int, terms) -> list | None:
+ """A contract's coming slots (fleet marketbundle.go "ahead": windows of
+ slot indices with their amounts, the price as [count, ct] runs) as the
+ plan's steps: per step None (outside its windows or the slots told) or
+ terms(price, guaranteed_kwh, minimum_kwh, max_kwh). None when the
+ contract has no usable "ahead" (the caller then holds its slot's terms)."""
+ if not isinstance(ah, dict):
+ return None
+ try:
+ a0, astep, n = int(ah["start"]), int(ah.get("step_s") or 900), int(ah.get("slots") or 0)
+ prices = []
+ for cnt, ct in ah.get("price_ct") or []:
+ prices += [float(ct)] * int(cnt)
+ wins = [(int(w["from"]), int(w["to"]), w) for w in ah.get("windows") or []]
+ except (KeyError, TypeError, ValueError):
+ return None
+ if astep <= 0 or n <= 0 or n > 2000 or len(prices) < n:
+ return None
+ by_slot: dict[int, dict] = {}
+ for f, t, w in wins:
+ for i in range(max(0, f), min(n, t)):
+ by_slot[i] = w
+ out = []
+ for k in range(steps):
+ i = (start + k * step_s - a0) // astep
+ w = by_slot.get(i) if 0 <= i < n else None
+ if w is None:
+ out.append(None)
+ continue
+ try:
+ out.append(terms(prices[i], w.get("guaranteed_kwh"), w.get("minimum_kwh"), w.get("max_kwh")))
+ except (TypeError, ValueError):
+ out.append(None)
+ return out
+
+
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.market = _File(os.path.join(state_dir, "market.json"), _check_market)
self.flat: float | None = None # the last known tariff's mean import price
def stamps(self):
@@ -136,16 +271,19 @@ class Bundles:
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
+ # feed-in without a price is counted at 0 ct: the plan then values PV
+ # export at nothing (it may curtail or self-consume more), so its note says so
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)
+ return Prices([flat] * steps, [0.0] * steps, note + "; feed-in at 0 ct/kWh")
expired = now >= t.get("expires", 0)
- out_i, out_e, outside = [], [], 0
+ out_i, out_e, outside, no_export = [], [], 0, 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
+ no_export += pe 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:
@@ -154,6 +292,10 @@ class Bundles:
note = f"tariff {t.get('id')}; {outside} of {steps} steps at the flat {flat:.1f} ct/kWh"
else:
note = f"tariff {t.get('id')}"
+ if no_export == steps:
+ note += "; feed-in at 0 ct/kWh"
+ elif no_export:
+ note += f"; feed-in at 0 ct/kWh in {no_export} of {steps} steps (no export price)"
return Prices(out_i, out_e, note)
def tariff_now(self, now: float) -> dict | None:
@@ -178,7 +320,8 @@ class Bundles:
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 {}))}
+ "expires": m.get("expires"), "series": sorted((m.get("forecasts") or {})),
+ "rooms": sorted(m.get("rooms") or {}) if m.get("site") == self.site else []}
def flat_list(self) -> list[dict]:
d = self.flats.get()
@@ -188,6 +331,69 @@ class Bundles:
return []
return list(d.get("flats") or [])
+ def market_now(self, now: float) -> dict | None:
+ """The market bundle for HA, or None (none, another site's, expired,
+ or nothing in it). "stale": older than its stale_after_s (the
+ entities go unavailable then)."""
+ d = self.market.get()
+ if d is None or d.get("site") not in (self.site,) or (d.get("expires") and d["expires"] <= now):
+ return None
+ if not (d.get("contracts") or d.get("actuators")):
+ return None
+ age = now - max(d.get("issued") or 0, d.get("slot") or 0)
+ return dict(d, stale=age > float(d.get("stale_after_s") or MARKET_STALE_S), age_s=int(age))
+
+ def market_for_model(self, start: int, step_s: int, steps: int, now: float) -> list[dict]:
+ """The contracts in force as energy sources and sinks for the plan
+ (the market's step 2; shadow: the plan only, no commands). Per
+ contract: id, name, direction (buys: an import source, sells: an
+ export sink), price_ct, guaranteed_w (firm), minimum_wh (take-or-pay,
+ per step), max_w (0: none), from_step, to_step (the plan's steps it
+ applies in) and, from a bundle with the coming slots, terms: per plan
+ step None (it does not apply) or {price_ct, guaranteed_w, minimum_wh,
+ max_w}; the scalars are then those of its first step.
+
+ The coming slots (a contract's "ahead", fleet marketbundle.go since
+ market-polish): each step gets its own slot's terms (window, amounts,
+ price) as far as the bundle tells them, while the bundle is fresh.
+ A bundle without them (an older fleet) carries one slot's terms; they
+ are held for the steps while the bundle is fresh (its slot .. slot +
+ stale_after_s), nothing beyond: the plan never assumes a contract it
+ hasn't been told of."""
+ d = self.market_now(now)
+ if d is None or d.get("stale"):
+ return []
+ slot = int(d.get("slot") or 0)
+ h = int(d.get("step_s") or 900) / 3600.0 # the bundle's slot in hours: kWh per slot -> W
+
+ def terms(price, g_kwh, min_kwh, max_kwh):
+ return {"price_ct": float(price),
+ "guaranteed_w": max(0.0, float(g_kwh or 0)) * 1000.0 / h,
+ "minimum_wh": max(0.0, float(min_kwh or 0)) * 1000.0 * (step_s / 3600.0) / h,
+ "max_w": max(0.0, float(max_kwh or 0)) * 1000.0 / h}
+
+ until = slot + int(float(d.get("stale_after_s") or MARKET_STALE_S))
+ a = max(0, -(-(slot - start) // step_s))
+ b = min(steps, -(-(until - start) // step_s))
+ out = []
+ for c in d.get("contracts") or []:
+ head = {"id": c["id"], "name": str(c.get("name") or "")[:200], "direction": c["direction"]}
+ per = _ahead_terms(c.get("ahead"), start, step_s, steps, terms)
+ if per is not None:
+ on = [t for t, x in enumerate(per) if x is not None]
+ if on:
+ out.append({**head, **per[on[0]], "from_step": on[0], "to_step": on[-1] + 1, "terms": per})
+ continue
+ sl = c.get("slot") or {}
+ if b <= a or not sl.get("applies"):
+ continue
+ try:
+ x = terms(sl.get("price_ct"), sl.get("guaranteed_kwh"), sl.get("minimum_kwh"), sl.get("max_kwh"))
+ except (TypeError, ValueError):
+ continue
+ out.append({**head, **x, "from_step": a, "to_step": b})
+ return out
+
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)."""
@@ -198,12 +404,47 @@ class Bundles:
if f is None:
return None
zone = ZoneInfo(tz or "UTC")
+ ser = f.get("series") or {}
+ s0, sv = ser.get("start"), ser.get("values") or []
out = []
for k in range(steps):
- d = datetime.fromtimestamp(start + k * step_s, timezone.utc).astimezone(zone)
+ t = start + k * step_s
+ i = int((t - s0) // 900) if sv else -1
+ if 0 <= i < len(sv):
+ out.append(float(sv[i])) # the trained series where it covers
+ continue
+ d = datetime.fromtimestamp(t, timezone.utc).astimezone(zone)
out.append(float(f["values"][d.weekday() * 24 + d.hour]))
return out
+ def room_rc(self, control_id: str, area: str = "", only_one: bool = False,
+ now: float | None = None) -> dict | None:
+ """A heating or cooling control's room in the model (R and C fitted
+ in the cloud): by its id, its id without _heating/_cooling/_heat/
+ _cool, its area; else, when the caller says it is the site's only
+ such control (only_one), the model's only room. None without a
+ model for this site (a shared "*" model has no rooms), expired, or
+ no match. {"r_k_per_kw", "c_kwh_per_k", "power", "gain_w" (W, a
+ number or 24 by local hour; 0 when the model has none),
+ "solar_m2"}."""
+ m = self.model.get()
+ now = time.time() if now is None else now
+ if m is None or m.get("site") != self.site or (m.get("expires") and m["expires"] <= now):
+ return None
+ rooms = m.get("rooms") or {}
+ key = next((k for k in (control_id, ROOM_SUFFIX.sub("", control_id or ""), area or "")
+ if k and k in rooms), None)
+ if key is None and only_one and len(rooms) == 1:
+ key = next(iter(rooms))
+ if key is None:
+ return None
+ r = rooms[key]
+ g = r.get("gain_w") or 0.0
+ return {"r_k_per_kw": float(r["r_k_per_kw"]), "c_kwh_per_k": float(r["c_kwh_per_k"]),
+ "power": r.get("power") or "thermal",
+ "gain_w": [_clip(x, ROOM_GAIN_W) for x in g] if isinstance(g, list) else _clip(g, ROOM_GAIN_W),
+ "solar_m2": _clip(r.get("solar_m2") or 0.0, ROOM_SOLAR_M2)}
+
def model_id(self) -> str:
m = self.model.get()
return m.get("id", "") if m else ""
diff --git a/src/edge/cantabile_edge/config.py b/src/edge/cantabile_edge/config.py
index 9121b23..1d3d623 100644
--- a/src/edge/cantabile_edge/config.py
+++ b/src/edge/cantabile_edge/config.py
@@ -55,6 +55,10 @@ class Config:
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
+ # The site's grid connection (W): the plan's import and export are at most
+ # this. 3 x 230 V x 63 A, a German house connection's usual main fuse;
+ # a site with a smaller fuse (or a building's larger one) sets its own.
+ grid_max_w: float = 43470.0
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
diff --git a/src/edge/cantabile_edge/controller.py b/src/edge/cantabile_edge/controller.py
index 5ce7b44..aad01b5 100644
--- a/src/edge/cantabile_edge/controller.py
+++ b/src/edge/cantabile_edge/controller.py
@@ -35,6 +35,7 @@ import time
from . import inputs as inputs_mod
from .building import Building
from .bundles import Bundles
+from .evphases import EvPhases
from .executor import Executor, building_msg
from .gridorder import GridOrders
from .guard import Guard
@@ -81,6 +82,7 @@ class Controller:
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.evphases = EvPhases(cfg.state_dir) # each charger's phase count and its source
self.guard.extra_limits = self.saved_limits
self.policy = Policy(cfg.state_dir, cfg.site_id, clock)
self.guard.policy = self.policy
@@ -180,6 +182,7 @@ class Controller:
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)}
+ write_cell(self.cfg.state_dir, float(lat), float(lon))
except Exception as e:
log.warning("get_config: %s", e)
ids = self.entities()
@@ -222,7 +225,9 @@ class Controller:
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))
+ grid_order=self.gridorders.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS),
+ grid_max_w=getattr(self.cfg, "grid_max_w", None),
+ ev_phases=self.ev_phases())
async def make_plan(self) -> dict | None:
self.forecast = []
@@ -261,15 +266,20 @@ class Controller:
"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", {})}
+ "flex": plan.get("flex", {}),
+ # the market's contracts in the plan (shadow): planned kWh and saving vs the grid
+ "market": plan.get("market", [])}
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()
+ """The plan's room temperatures and the battery's state have a value
+ (a sensor that stopped must not steer). HA marks a device that went
+ away unavailable; a value that holds steady is not stale (the clone,
+ 2026-10-30: a room at 23.5 °C for hours and a full battery held every
+ control at its safe default), and HA sends no update for an
+ unchanged value, so its age says nothing."""
for c in self.controls:
for role in ("temp", "soc"):
- if role in c.entities and self.col.age(c.entities[role], now) > 3600:
+ if role in c.entities and self.col.value(c.entities[role]) is None:
return False
return True
@@ -378,8 +388,10 @@ class Controller:
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("load_w", inputs_mod.base_load(self.col, self.inputs), now)
self.history.add("pv_w", self.col.total(self.inputs.pv_power), now)
+ if self.sample_ev_phases(now) and self.gridorders.active():
+ self._merge_limits() # a learned count: the order's current bound again
if int(now) % 900 < 60:
try:
self.history.save(now)
@@ -387,6 +399,10 @@ class Controller:
log.warning("history: %s", e)
self.executor.inputs_ok = self.inputs_fresh()
self.grid_tick()
+ try:
+ await self.grid_report()
+ except Exception as e:
+ log.warning("grid order report: %s", e)
if self.switch_sides():
self.wake.set() # heating <-> cooling: a plan for the new side
try:
@@ -506,12 +522,34 @@ class Controller:
os.replace(p + ".tmp", p)
+ # -- the chargers' phases (evphases.py) ------------------------------------
+ def ev_phases(self) -> dict:
+ """{control id: {"phases", "source", "plan", "order"}} for the EV controls."""
+ return self.evphases.all(self.controls, self.col)
+
+ def sample_ev_phases(self, now: float) -> bool:
+ """A reading per charger for learning its phases: its power (its own
+ `power` sensor, else the site's ev.power where it is the only
+ charger) and current (measured, else its setpoint). True when a
+ learned count changed."""
+ evs = [c for c in self.controls if c.kind == "ev"]
+ site_ev = self.mapping.by_asset.get("ev.power") if len(evs) == 1 and hasattr(self.mapping, "by_asset") else None
+ changed = False
+ for c in evs:
+ pw = c.entities.get("power") or (site_ev.entity if site_ev else "")
+ cur = c.entities.get("current_measured") or c.entities.get("current") or ""
+ p = inputs_mod.watts(self.col, pw) if pw else None
+ a = self.col.value(cur) if cur else None
+ changed |= self.evphases.sample(c.id, p, a, float(c.p("voltage")), now)
+ return changed
+
# -- 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():
+ phases = {cid: v["phases"] for cid, v in self.ev_phases().items()}
+ for cid, qs in self.gridorders.limits(self.controls, phases).items():
for q, (f, lim) in qs.items():
per = merged.setdefault(cid, {}).setdefault(q, {})
old = per.get("grid")
@@ -538,10 +576,18 @@ class Controller:
args.update(value="", state="normal")
log.info("grid operator's limit ended")
await self._received("grid", args, "grid", True, "limited" if o else "ended")
+ await self.grid_report()
self.wake.set()
self.act_now.set()
return True
+ async def grid_report(self):
+ """The order to the cloud as an action (gridorder.py action()): each
+ quarter-hour it holds, and its end."""
+ a = self.gridorders.action()
+ if a is not None:
+ await self._publish("action", a)
+
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(
@@ -562,6 +608,29 @@ def sender(cmd: str, args: dict) -> str:
return "cloud"
+def write_cell(state_dir: str, lat: float, lon: float) -> bool:
+ """The site's weather cell (0.1°, ~10 km) for the link: site_cell.json
+ in the state directory; the heartbeat carries it to the cloud only with
+ the owner's share consent (edge/link). Written when it changed."""
+ cell = {"lat": round(lat, 1), "lon": round(lon, 1)}
+ path = os.path.join(state_dir, "site_cell.json")
+ try:
+ with open(path) as f:
+ if json.load(f) == cell:
+ return False
+ except (OSError, ValueError):
+ pass
+ try:
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(cell, f)
+ os.replace(tmp, path)
+ except OSError as e:
+ log.warning("site cell: %s", e)
+ return False
+ return True
+
+
SECRET_ARGS = ("proof", "sig", "bundle", "token", "password")
diff --git a/src/edge/cantabile_edge/controls.py b/src/edge/cantabile_edge/controls.py
index 31ba841..49d0fa4 100644
--- a/src/edge/cantabile_edge/controls.py
+++ b/src/edge/cantabile_edge/controls.py
@@ -67,6 +67,7 @@ from dataclasses import dataclass, field
from . import limits as limits_mod
from . import switchover as switchover_mod
+from .evphases import ASSUMED
log = logging.getLogger(__name__)
@@ -78,7 +79,9 @@ ENTITIES = {
"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")},
+ "energy_needed": ("sensor",), "departure": ("sensor", "input_datetime"),
+ # read only, for its phase count (evphases.py): reported, or learned from power and current
+ "phases": ("sensor",), "power": ("sensor",), "current_measured": ("sensor",)},
"cover": {"cover": ("cover",)},
}
WRITES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover"}
@@ -91,15 +94,31 @@ PARAMS = {
"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},
+ "min_switch_s": 600.0,
+ # the room's other heat (W; the model's fit, inputs._room_rc): internal
+ # (a number, or 24 by local hour) and the sun's per W/m² of irradiance
+ "internal_gain_w": 0.0, "solar_m2": 0.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},
+ "setup_c": 28.0, "cop": 3.0, "min_switch_s": 600.0, "internal_gain_w": 0.0, "solar_m2": 0.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},
+ "phases": None, "voltage": 230.0, "min_switch_s": 0.0}, # phases: None, not said (evphases.py)
"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},
}
+
+
+def ev_volts(params: dict, purpose: str) -> float:
+ """A charger's volts x phases (W per A) for a purpose: "plan" (the
+ plan's power per A) or "order" (the grid order's current bound,
+ gridorder.limits). params["phases"]: the count from the best evidence
+ (evphases.py: mapping, device, learned); without it each purpose takes
+ its own safe side (evphases.ASSUMED: the order 3, the plan 1)."""
+
+ v = float(params.get("voltage") or PARAMS["ev"]["voltage"])
+ return v * float(params.get("phases") or ASSUMED[purpose])
+
+
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 = {
@@ -254,16 +273,22 @@ class Inputs:
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)
+ # sensors W of the planned devices' own draw inside load_power (heat pump,
+ # A/C, charger): taken off it, so the plan's base load is the house
+ # without the devices it plans itself (inputs.base_load). None: from the
+ # mapping's assets (mapping.controlled_power); an empty list: load_power
+ # has none of them in it.
+ controlled_power: list[str] | None = None
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]
+ return [e for e in self.presence + self.humidity + one + summed + list(self.controlled_power or []) if e]
def parse_inputs(raw: dict | None) -> Inputs:
raw = dict(raw or {})
- for k in ("presence", "humidity"):
+ for k in ("presence", "humidity", "controlled_power"):
if isinstance(raw.get(k), str):
raw[k] = [raw[k]]
unknown = set(raw) - set(Inputs.__dataclass_fields__)
diff --git a/src/edge/cantabile_edge/dashboards.py b/src/edge/cantabile_edge/dashboards.py
index 2d8f5bb..ac68a5b 100644
--- a/src/edge/cantabile_edge/dashboards.py
+++ b/src/edge/cantabile_edge/dashboards.py
@@ -32,7 +32,10 @@
and dearest hour of the next 24; the coming actions by
the controls' names or "nothing planned", the prices of 48 h
as a table, what Cantabile sets in words: only in auto, the
- commands received: only when there are any); the building
+ commands received: only when there are any); the market
+ (shadow; only when the site has contracts: positions, the
+ price, a card per contract in plain words, the border
+ actuators' contract target against their state); the building
the home is in or asked to join
energy power and price over time, energy per day and month (if mapped)
climate rooms, thermostats, heat pump (if mapped)
@@ -81,8 +84,9 @@ class Home:
def __init__(self, mapping, uid: str, ours: dict[str, str], flats: list[dict], lang: str,
mode: str = "shadow", reg: dict | None = None, states: list[dict] | None = None,
links: dict[str, str] | None = None, joining: dict | None = None,
- profiles: list[dict] | None = None):
+ profiles: list[dict] | None = None, market: dict | None = None):
self.m, self.uid, self.ours, self.flats, self.lang = mapping, uid, ours, flats, lang
+ self.market = market # the shadow market's bundle (bundles.market_now), or None
self.mode, self.links, self.joining, self.profiles = mode, links or {}, joining, profiles or []
self._views: dict[str, devview.DeviceView] = {}
self.assets = {a.asset: a for a in mapping.assets}
@@ -146,6 +150,17 @@ class Home:
return [a.entity for a in self.m.assets
if a.kind == "counter" and a.asset.startswith(prefix) and self.alive(a.entity)]
+ def thermal(self) -> set[str]:
+ """The entities of heat (heat.power, heat.energy and their parts):
+ thermal, never shown or summed as electricity."""
+ return {a.entity for a in self.m.assets
+ if a.asset.split(".")[0] == "heat" and a.asset.rsplit(".", 1)[-1] in ("power", "energy")}
+
+ def heat_label(self) -> str:
+ """Heat delivered by a heat pump of this site, else heat from the
+ building (a heat meter: district heat, the building's heat pump)."""
+ return self.n("heat_delivered" if self.each("heatpump.power") else "heat_building")
+
def our(self, suffix: str) -> str | None:
return self.ours.get(f"{self.uid}_{suffix}")
@@ -300,6 +315,48 @@ def energy_now(h: "Home") -> list[dict]:
return now
+def _kilo(e: str, unit: str, dec: str) -> str:
+ """A jinja expression of a heat sensor in kW or kWh (from W/Wh too)."""
+ return ("{% set u = state_attr('" + e + "', 'unit_of_measurement') %}{% set v = states('" + e + "') | float(none) %}"
+ "{% if v is none %}–{% else %}{{ ('%.1f' | format(v / 1000 if u in ['W', 'Wh'] else v))"
+ " | replace('.', '" + dec + "') }} " + unit + "{% endif %}")
+
+
+def _thermal(h: "Home", e: str, label: str, cols=6, value: bool = False) -> dict:
+ """A heat value (thermal) as its label and kW or kWh: never a tile that
+ could pass for electricity. value: one of a device's values."""
+ a = next((a for a in h.m.assets if a.entity == e), None)
+ unit = "kWh" if a is not None and a.kind == "counter" else "kW"
+ dec = "," if h.lang.split("-")[0] in DECIMAL_COMMA else "."
+ c = {"type": "markdown", "text_only": True, "grid_options": {"columns": cols}, "entity_id": e,
+ "content": f" {label} \n**{_kilo(e, unit, dec)}**"}
+ return dict(c, _value=True) if value else c
+
+
+def heat_band(h: "Home") -> list[dict]:
+ """Heat now and today, thermal, in a band of its own below the
+ electricity: from the building (district heat, a heat meter) or
+ delivered by the site's heat pump, then with its electric power and the
+ COP (heat ÷ electricity). Never summed with electric power."""
+ heat, hp = h.each("heat.power"), h.each("heatpump.power")
+ if not heat and not h.each("heat.energy"):
+ return []
+ label = h.heat_label()
+ out = [_thermal(h, e, f"{label} {n}".strip()) for n, e in heat]
+ out += [_today(e, f"{h.n('heat_today')} {n}".strip(), "mdi:radiator") for n, e in h.each("heat.energy")]
+ if hp:
+ out += [_tile(e, f"{h.n('heat_pump_electric')} {n}".strip(), "mdi:heat-pump", "deep-purple")
+ for n, e in hp]
+ if len(heat) == 1 and len(hp) == 1:
+ q, w = heat[0][1], hp[0][1]
+ dec = "," if h.lang.split("-")[0] in DECIMAL_COMMA else "."
+ out.append(_md("{% set q = states('" + q + "') | float(none) %}{% set w = states('" + w + "') | float(none) %}"
+ + h.n("cop") + " \n**{% if q is not none and w %}{{ ('%.1f' | format(q / w)) | replace('.', '"
+ + dec + "') }}{% else %}–{% endif %}**", 6, text_only=True))
+ out.append(_md("ⓘ " + h.n("heat_not_electric") + " ", text_only=True))
+ return out
+
+
def _label(h: "Home", c) -> str:
"""A control as people call it: the mapping's name, else the name HA
shows for its device's main entity, else its id in words."""
@@ -408,6 +465,46 @@ def plan_cards(h: "Home") -> list[dict]:
return out[:1 if price else 0] + _fill(out[1 if price else 0:])
+def market_band(h: "Home") -> dict | None:
+ """The shadow market, only when the site has contracts (a `market`
+ bundle): the net position(s) and the shared energy's price (quarters),
+ per contract a card in plain words (halves: "Sells to Home B: 1.2 kWh
+ last quarter-hour (contract 1.5) · 16.4 ct/kWh · shadow", the period
+ below), the border actuators' contract target against their state now,
+ and what shadow means. HA's core cards only."""
+ m = h.market
+ if not m or not m.get("contracts"):
+ return None
+ top = []
+ for p in m.get("positions") or []:
+ kind = str(p.get("node", "")).split(":")[0]
+ top.append(_tile(h.our("market_position" if kind == "site" else f"market_position_{_slug(kind)}"),
+ icon="mdi:scale-balance", cols=6))
+ top.append(_tile(h.our("market_price"), h.n("market_price"), "mdi:cash-multiple", cols=6))
+ stale = "" + h.n("mk_stale") + " "
+ deals = []
+ for c in m.get("contracts") or []:
+ e = h.our(f"market_{_slug(c['id'])}")
+ if not e:
+ continue
+ deals.append(_md(
+ "{% set e = '" + e + "' %}{% if states(e) == 'unavailable' or not state_attr(e, 'summary') %}" + stale
+ + "{% else %}**{{ state_attr(e, 'summary') }}**{% set d = state_attr(e, 'details') %}"
+ "{% if d %} \n{{ d }} {% endif %} \n{{ state_attr(e, 'period_words') }} {% endif %}",
+ 12))
+ rows = []
+ for a in m.get("actuators") or []:
+ e = h.our(f"market_actuator_{_slug(a['device'])}")
+ if e:
+ rows.append("**" + (a.get("name") or a["device"]).replace("*", "") + "**: {% set e = '" + e + "' %}"
+ "{% if states(e) == 'unavailable' %}" + stale + "{% else %}{{ state_attr(e, 'words') }}{% endif %}")
+ acts = _md(" \n".join(rows)) if rows else None
+ if not deals and not acts:
+ return None
+ note = _md("ⓘ " + h.n("mk_shadow_note") + " ")
+ return _band(*_fill([c for c in top if c]), *_fill(deals), acts, note, heading=h.n("card_market"), icon="mdi:handshake-outline")
+
+
# -- the views ----------------------------------------------------------------------
def view_overview(h: Home) -> dict | None:
@@ -444,10 +541,11 @@ def view_overview(h: Home) -> dict | None:
return _view(h.n("dash_main"), "overview", "mdi:leaf",
_band(*status), _band(*now),
+ _band(*_fill(heat_band(h)), heading=h.n("heat"), icon="mdi:radiator"),
devices_heading(h, bool(devices)), *devices,
_band(*today, heading=h.n("today"), icon="mdi:calendar-today"),
_band(*plan_cards(h), heading=h.n("card_plan"), icon="mdi:chart-timeline-variant"),
- building_section(h), columns=WIDE)
+ market_band(h), building_section(h), columns=WIDE)
def view_energy(h: Home) -> dict | None:
@@ -475,9 +573,13 @@ def view_climate(h: Home) -> dict | None:
for e in dict.fromkeys(c.entities["climate"] for c in rooms if "climate" in c.entities)],
_history(h.n("card_rooms"), list(dict.fromkeys(e for e in temps if e))
+ [h.our(f"set_{c.id}") for c in rooms] + [h.asset("outside.temp")])),
+ # electric and thermal apart, never in one graph
_section(_heading(h.n("heat_pump"), "mdi:heat-pump"),
- _history(h.n("card_power"), h.all("heatpump.power", "heat.power")),
- _stats(h.n("card_daily"), h.all("heatpump.energy", "heat.energy"))))
+ _history(h.n("electric_power"), h.all("heatpump.power")),
+ _stats(h.n("card_daily"), h.all("heatpump.energy"))),
+ _section(_heading(h.n("heat"), "mdi:radiator"),
+ _history(h.heat_label(), h.all("heat.power")),
+ _stats(h.n("heat_today"), h.all("heat.energy"))))
def _short(name: str, device: str) -> str:
@@ -560,9 +662,15 @@ def device_cards(h: Home, d: dict, detail: bool = False) -> list[dict]:
cards, used = [], set()
+ thermal = h.thermal()
+
def tile(eid, trend=None, cols=6):
if eid and eid not in used:
used.add(eid)
+ if eid in thermal: # heat: thermal, never like electricity
+ label = h.heat_label() if eid in h.all("heat.power") else h.n("heat_today")
+ cards.append(_thermal(h, eid, label, cols))
+ return
cards.append(_tile(eid, nm(eid), trend=power(eid) if trend is None else trend, cols=cols))
soc = dv.flow.get("soc") or next((e for e in dv.headline if st(e).get("device_class") == "battery"), None)
if dv.card in ("flow", "gauge") and soc:
@@ -592,7 +700,7 @@ def device_cards(h: Home, d: dict, detail: bool = False) -> list[dict]:
for e in dv.headline:
tile(e, None if dv.card in ("flow", "meter", "charger") or detail else False)
if dv.channels:
- power_ch = [c for c in dv.channels if c.get("power")]
+ power_ch = [c for c in dv.channels if c.get("power") and c["power"] not in thermal] # never heat
if power_ch:
cards.append(_sum(h.n("total"), [c["power"] for c in power_ch]))
cards.append({"type": "distribution", "grid_options": {"columns": "full"},
@@ -735,10 +843,13 @@ def device_card(h: Home, d: dict, skip: set[str] = frozenset()) -> dict | None:
picked.append(e)
picked = picked[:HEADLINE]
used |= set(picked)
- cards += [{"type": "tile", "entity": e, "name": nm(e), "_value": True,
+ thermal = h.thermal()
+ cards += [_thermal(h, e, h.heat_label() if e in h.all("heat.power") else h.n("heat_today"), value=True)
+ if e in thermal else
+ {"type": "tile", "entity": e, "name": nm(e), "_value": True,
**({"icon_tap_action": {"action": "more-info"}}
if e.split(".")[0] in ("switch", "light", "fan", "input_boolean") else {})} for e in picked]
- power_ch = [c for c in dv.channels if c.get("power") and c["power"] not in skip]
+ power_ch = [c for c in dv.channels if c.get("power") and c["power"] not in skip and c["power"] not in thermal]
if power_ch:
cards.append({"type": "markdown", "text_only": True, "content":
"{% set e = " + json.dumps([c["power"] for c in power_ch]) + " %}" + h.n("total")
@@ -798,18 +909,22 @@ def device_subview(h: Home, d: dict) -> dict | None:
value it has (not diagnostic), and its power over the last day."""
dv = h.view(d)
cards = device_cards(h, d, detail=True)
- shown = {x if isinstance(x, str) else x.get("entity") for c in cards for x in [c, *(c.get("entities") or [])]}
+ shown = {x if isinstance(x, str) else x.get("entity") or x.get("entity_id")
+ for c in cards for x in [c, *(c.get("entities") or [])]}
shown |= set(dv.switches)
+ thermal = h.thermal()
rest = [e["entity_id"] for e in h.ents_of(d) if not e.get("entity_category") and e["entity_id"] not in shown
and e["entity_id"].split(".")[0] in VALUES and h.alive(e["entity_id"])]
powers = [e for e in dv.entities() | set(rest) if (((h.states or {}).get(e) or {}).get("attributes") or {})
- .get("device_class") == "power"]
+ .get("device_class") == "power" and e not in thermal]
+ heat = sorted(e for e in dv.entities() | set(rest) | shown if e in thermal and e in h.all("heat.power"))
return {"type": "sections", "title": _name(d), "path": _subpath(d), "subview": True,
"back_path": f"/{URL}/overview", "max_columns": 3, "sections": [x for x in (
_section(_heading(_name(d), "mdi:information-outline"), *cards),
_section(_heading(h.n("values"), "mdi:format-list-bulleted"),
{"type": "entities", "entities": rest, "grid_options": {"columns": "full"}} if rest else None),
- _section(_heading(h.n("card_power"), "mdi:flash"), _history(h.n("card_power"), sorted(powers))))
+ _section(_heading(h.n("card_power"), "mdi:flash"), _history(h.n("card_power"), sorted(powers))),
+ _section(_heading(h.n("heat"), "mdi:radiator"), _history(h.heat_label(), heat)))
if x]}
@@ -858,15 +973,19 @@ def dashboard(h: Home) -> dict | None:
def energy_prefs(h: Home) -> dict | None:
"""HA's Energy preferences from the mapping, or None (nothing to show).
- Parts (two inverters, two batteries) are each a source of their own."""
+ Parts (two inverters, two batteries) are each a source of their own.
+ The grid in HA's current form (energy storage 1.3, in HA 2026.10): a
+ source per grid connection with its import and export meter side by
+ side (parts paired in order); legacy_grid() gives the older form."""
src = []
imp, exp = h.all("grid.import_energy"), h.all("grid.export_energy")
- if imp or exp:
+ for i in range(max(len(imp), len(exp))):
+ e_in, e_out = (imp[i] if i < len(imp) else None), (exp[i] if i < len(exp) else None)
src.append({"type": "grid", "cost_adjustment_day": 0,
- "flow_from": [{"stat_energy_from": e, "stat_cost": None, "number_energy_price": None,
- "entity_energy_price": h.our("price_import_now")} for e in imp],
- "flow_to": [{"stat_energy_to": e, "stat_compensation": None, "number_energy_price": None,
- "entity_energy_price": h.our("price_export_now")} for e in exp]})
+ "stat_energy_from": e_in, "stat_cost": None, "number_energy_price": None,
+ "entity_energy_price": h.our("price_import_now") if e_in else None,
+ "stat_energy_to": e_out, "stat_compensation": None, "number_energy_price_export": None,
+ "entity_energy_price_export": h.our("price_export_now") if e_out else None})
for e in h.all("pv.energy"):
src.append({"type": "solar", "stat_energy_from": e, "config_entry_solar_forecast": None})
ins, outs = dict(h.each("battery.charge_energy")), dict(h.each("battery.discharge_energy"))
@@ -883,6 +1002,23 @@ def energy_prefs(h: Home) -> dict | None:
return {"energy_sources": src, "device_consumption": devices}
+def legacy_grid(prefs: dict) -> dict:
+ """The preferences in HA's older grid form (energy storage before 1.3):
+ one grid source, its import and export meters in flow_from / flow_to.
+ The same dict when there is no grid."""
+ grids = [s for s in prefs["energy_sources"] if s["type"] == "grid"]
+ if not grids:
+ return prefs
+ one = {"type": "grid", "cost_adjustment_day": 0,
+ "flow_from": [{"stat_energy_from": g["stat_energy_from"], "stat_cost": None, "number_energy_price": None,
+ "entity_energy_price": g["entity_energy_price"]}
+ for g in grids if g["stat_energy_from"]],
+ "flow_to": [{"stat_energy_to": g["stat_energy_to"], "stat_compensation": None, "number_energy_price": None,
+ "entity_energy_price": g["entity_energy_price_export"]}
+ for g in grids if g["stat_energy_to"]]}
+ return dict(prefs, energy_sources=[one] + [s for s in prefs["energy_sources"] if s["type"] != "grid"])
+
+
class Dashboards:
def __init__(self, agent):
self.agent = agent
@@ -918,9 +1054,10 @@ class Dashboards:
links: dict[str, str] | None = None) -> Home:
ctl = getattr(self.agent, "control", None)
flats = ctl.bundles.flat_list() if ctl is not None else []
+ market = ctl.bundles.market_now(time.time()) if ctl is not None else None
return Home(self.agent.mapping, f"cantabile_{self.agent.cfg.site_id}", ours, flats,
getattr(self.agent, "ha_language", "en"), self.mode(), reg, states, links,
- self.joining() if self.agent.cfg.join_page_port else None, self.profiles)
+ self.joining() if self.agent.cfg.join_page_port else None, self.profiles, market)
@staticmethod
async def links(client, devices: list[dict]) -> dict[str, str]:
@@ -985,9 +1122,21 @@ class Dashboards:
if prefs and (prefs.get("energy_sources") or prefs.get("device_consumption")):
return # the owner's: never overwritten
want = energy_prefs(h)
- if want is not None:
+ if want is None:
+ return
+ try:
await client.dashboard("energy/save_prefs", **want)
- log.info("HA's Energy dashboard set up from the mapping")
+ except HAError as e:
+ # an HA from before the unified grid (energy storage 1.3) takes
+ # only flow_from / flow_to: the same preferences in that form
+ old = legacy_grid(want)
+ if old is want or "invalid_format" not in str(e):
+ raise
+ await client.dashboard("energy/save_prefs", **old)
+ log.info("HA's Energy dashboard set up from the mapping (HA %s: the older grid form)",
+ getattr(client, "version", None))
+ return
+ log.info("HA's Energy dashboard set up from the mapping")
async def run(self, stop: asyncio.Event):
while not stop.is_set():
diff --git a/src/edge/cantabile_edge/devpage.py b/src/edge/cantabile_edge/devpage.py
index 00611a0..de09a60 100644
--- a/src/edge/cantabile_edge/devpage.py
+++ b/src/edge/cantabile_edge/devpage.py
@@ -66,16 +66,67 @@ SWITCHOVER_WORDS = {"heating": M("Heating"), "cooling": M("Cooling"),
"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")}
+PROFILE_STATUS = {"verified": (M("checked"), "ok", M("Checked on a device: its values are known to be right.")),
+ "documented": (M("untested"), "quiet", M("Made from the maker's documentation, not yet checked on a "
+ "device. Look at its values before you turn reading on.")),
+ "draft": (M("draft"), "warn", M("A draft profile: 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")}
+# What a device reads, by meaning (the devices tool gives the keys:
+# devprofiles.reads); never the asset ids.
+QUANTITY_WORDS = {
+ "room.temp": M("room temperature"), "room.humidity": M("humidity"), "room.setpoint": M("setpoint"),
+ "room.setpoint_range": M("heat/cool range"), "heating_cooling.state": M("heating/cooling state"),
+ "heating.state": M("heating state"), "cooling.state": M("cooling state"),
+ "room.setpoint_low": M("heat/cool range"), "room.setpoint_high": M("heat/cool range"),
+ "room.shade_position": M("position"), "room.shade_tilt": M("tilt"),
+ "pv.power": M("solar power"), "pv.energy": M("solar energy"), "grid.power": M("grid power"),
+ "grid.import_power": M("power from the grid"), "grid.export_power": M("power to the grid"),
+ "grid.import_energy": M("energy from the grid"), "grid.export_energy": M("energy to the grid"),
+ "battery.power": M("battery power"), "battery.soc": M("battery charge"),
+ "battery.charge_energy": M("energy charged"), "battery.discharge_energy": M("energy discharged"),
+ "load.power": M("home consumption"), "load.energy": M("home energy"),
+ "heatpump.power": M("heat pump power"), "heatpump.energy": M("heat pump energy"),
+ "heat.power": M("heat delivered (thermal)"), "heat.energy": M("heat energy (thermal)"), "heatpump.flow_temp": M("flow temperature"),
+ "heatpump.dhw_temp": M("hot water temperature"), "outside.temp": M("outdoor temperature"),
+ "outside.humidity": M("outdoor humidity"), "gas.energy": M("gas"), "ev.power": M("charging power"),
+ "ev.energy": M("energy charged"), "circuit.power": M("power"), "circuit.energy": M("energy")}
+# A device's main values now (devprofiles.live) on the list.
+LIVE_WORDS = {"room.setpoint": M("set to {v}"), "room.setpoint_range": M("set to {low}–{high}"),
+ "pv.power": M("solar {v}"), "battery.soc": M("battery {v}"), "battery.power": M("battery {v}"),
+ "grid.power": M("grid {v}"), "load.power": M("home {v}"), "ev.power": M("charging {v}"),
+ "heatpump.power": M("heat pump {v}"), "heat.power": M("heat {v} (thermal)"), "heatpump.flow_temp": M("flow {v}"),
+ "outside.temp": M("outside {v}"), "room.humidity": M("humidity {v}"), "room.shade_position": M("{v} open")}
+HVAC_WORDS = {"heating": M("heating"), "cooling": M("cooling"), "idle": M("idle")}
+LIVE_UNITS = {"room.temp": "°C", "room.setpoint": "°C", "room.setpoint_range": "°C", "heatpump.flow_temp": "°C",
+ "outside.temp": "°C", "battery.soc": "%", "room.humidity": "%", "room.shade_position": "%"}
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}}"""
+a{color:#2f6f55}.muted,.model{color:#5a6b62;font-size:.85rem}
+.badge{display:inline-block;font-size:.75rem;padding:0 .45rem;border-radius:1rem;background:#e2e9e5;margin-left:.3rem;vertical-align:.1em}
+.badge.quiet{background:none;box-shadow:inset 0 0 0 1px #d5ded9;color:#5a6b62}.badge.warn{background:#fbe9c9;color:#7a4b00}
+ul.plain{list-style:none;margin:.3rem 0;padding:0}input[type=radio]{width:auto}select{font:inherit;padding:.45rem .6rem;border-radius:6px;width:100%}
+a.box.dev{display:flex;gap:.8rem;align-items:center;color:inherit;text-decoration:none}a.box.dev:hover{border-color:#2f6f55}
+.grow{flex:1;min-width:0}.grow>span{display:block}.grow>span.name{display:inline;font-weight:600}.grow>span.badge{display:inline-block}
+.chev{color:#5a6b62;font-size:1.4rem}.state{font-size:.9rem}.values{font-size:1.05rem;font-weight:600}.box.now>span{display:block}
+.dot{display:inline-block;width:.55rem;height:.55rem;border-radius:50%;margin-right:.45rem;background:#9fb0a6}.dot.on{background:#2f9e6e}
+.offer .top{display:flex;gap:.8rem;align-items:center}.offer .top form{margin:0}.offer .top button{margin:0;white-space:nowrap}.offer p.note{margin:.4rem 0 0;font-size:.9rem}
+.add{margin-top:2rem;border-top:2px solid #d5ded9}a.back{text-decoration:none;font-size:.9rem}.model.head{margin:-.6rem 0 .6rem}
+section.set{border-top:1px solid #d5ded9;margin-top:1rem}section.set h3{margin:.9rem 0 .4rem}section.set p{margin:.35rem 0}
+.switch{display:flex;align-items:center;justify-content:space-between;gap:.8rem;padding:.3rem 0}.switch form{margin:0}.switch button{margin:0;white-space:nowrap}
+.pill{display:inline-block;font-size:.75rem;padding:0 .5rem;border-radius:1rem;background:#e2e9e5;color:#5a6b62;font-weight:600}.pill.on{background:#e3f4ea;color:#1f5d3a}
+.row{display:flex;gap:.6rem}.row>div{flex:1}.right{text-align:right}
+details.remove summary{color:#b3261e;cursor:pointer;padding:.8rem 0 .2rem}button.danger{background:none;color:#b3261e;box-shadow:inset 0 0 0 2px #b3261e}
+details.more summary{cursor:pointer;margin:.6rem 0}
+details.info{display:inline;position:relative}details.info>summary{display:inline-flex;align-items:center;justify-content:center;width:1.2rem;height:1.2rem;margin:0 .35rem;vertical-align:.1em;list-style:none;border:1px solid #5a6b62;border-radius:50%;color:#5a6b62;font:italic 600 .72rem/1 Georgia,serif;cursor:pointer}
+details.info>summary::-webkit-details-marker{display:none}details.info>.info-body{position:absolute;left:0;z-index:3;width:min(22rem,80vw);margin-top:.4rem;padding:.7rem .9rem;background:#fff;color:#1d2a24;border:1px solid #d5ded9;border-radius:8px;box-shadow:0 6px 24px rgba(0,0,0,.18);font-size:.9rem;font-weight:normal}
+@supports selector(:has(a)){form.changes .save{display:none}form.changes:has(input:default:not(:checked),input:checked:not(:default),option:checked:not(:default),input[value=outdoor]:checked) .save{display:inline-block}
+form.changes:not(:has(input[value=outdoor]:checked)) .outdoor{display:none}}
+@media (prefers-color-scheme:dark){nav{border-color:#2b3a32}a{color:#5cc493}.badge,.pill{background:#2b3a32}.muted,.model,.chev{color:#9fb0a6}
+.badge.quiet{background:none;box-shadow:inset 0 0 0 1px #2b3a32;color:#9fb0a6}.badge.warn{background:#3a2c12;color:#f3c77e}.pill.on{background:#19302a;color:#a6e0bf}
+.dot.on{background:#5cc493}.add,section.set{border-color:#2b3a32}a.box.dev:hover{border-color:#5cc493}select{background:#18221d;color:#e3ebe6;border:1px solid #3a4b42}
+details.remove summary{color:#f08a80}button.danger{background:none;color:#f08a80;box-shadow:inset 0 0 0 2px #f08a80}
+details.info>.info-body{background:#18221d;color:#e3ebe6;border-color:#2b3a32}details.info>summary{border-color:#9fb0a6;color:#9fb0a6}}"""
# 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])}"
@@ -101,10 +152,6 @@ def _write_json(path: str, data, mode: int = 0o644):
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)."""
@@ -235,19 +282,25 @@ class Devices:
"""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()
+ try:
+ reg, states = await self.snapshot()
+ ha_error = ""
+ except Exception as e:
+ reg, states, ha_error = {}, {}, str(e)
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())
+ assets = frag.get("assets", [])
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", []),
+ status=p.get("status", ""), generic=bool(p) and dp.fallback(p), assets=assets,
+ controls=frag.get("controls", []), reads=dp.reads(assets), live=dp.live(assets, states),
+ assumed=dp.reads([a for a in assets if a.get("assumed")]), lacks=dp.lacks(d.get("missing")),
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": []}
+ if ha_error:
+ return {"devices": used, "offers": [], "rest": [], "ha_error": ha_error, "site": self.site(), "rooms": []}
main = self.main()
src = main.get("source")
mapped = {}
@@ -445,8 +498,9 @@ def custodian(e: dict | None) -> str:
# ---- the page -----------------------------------------------------------------------------
-def form(do: str, inner: str, button: str, cls: str = "", inline: bool = False) -> str:
- return (f'')
@@ -455,55 +509,163 @@ def hidden(**kw) -> str:
return "".join(f' ' 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'{E(out)}
'
+def info(body: str) -> str:
+ """An "i": its explanation (escaped HTML) opens below on a click or tap."""
+ name = E(T("More information"))
+ return (f'i '
+ f'{body}
')
-def notes(d: dict) -> str:
+def quantity_words(q: str) -> str:
+ """A quantity without words of its own: room.living_room.x -> room: living room.x."""
+ return q.replace("_", " ").replace(".", ": ", 1)
+
+
+def room_name(place: str, rooms) -> str:
+ """An asset's place (an area's slug) as HA names it: living_room -> Living room."""
+ return next((r for r in rooms or [] if dp.slug(r) == place), place.replace("_", " ").capitalize())
+
+
+def reads_words(keys, rooms=()) -> str:
+ """[(key, place)] (devprofiles.reads) in words: room temperature
+ (Living room), setpoint, heating/cooling state; a room named once."""
+ named, out = set(), []
+ for k, place in keys or []:
+ w = T(QUANTITY_WORDS[k]) if k in QUANTITY_WORDS else quantity_words(k)
+ if place and place not in named:
+ named.add(place)
+ w = T("{what} ({room})", what=w, room=room_name(place, rooms))
+ out.append(w)
+ return ", ".join(dict.fromkeys(out))
+
+
+def ids_words(ids, rooms=()) -> str:
+ return reads_words(dp.reads(list(ids)), rooms)
+
+
+def control_words(controls) -> str:
+ return ", ".join(dict.fromkeys(T(CONTROL_WORDS.get(c["kind"], c["kind"])) for c in controls or []))
+
+
+def _num(v, digits: int = 1) -> str:
+ v = round(float(v), digits)
+ return i18n.number(int(v) if v == int(v) else v)
+
+
+def live_words(k: str, v) -> str:
+ """One of a device's values now (devprofiles.live): 21.5 °C, set to 22 °C, heating."""
+ if k == dp.HVAC:
+ return T(HVAC_WORDS.get(v, HVAC_WORDS["idle"]))
+ if k in ("heating.state", "cooling.state"):
+ return T(HVAC_WORDS[k.split(".")[0] if v else "idle"])
+ if k == dp.RANGE:
+ return T(LIVE_WORDS[k], low=_num(v[0]), high=_num(v[1])) + " °C"
+ unit = LIVE_UNITS.get(k)
+ s = f"{_num(v)} {unit}" if unit else f"{_num(v / 1000)} kW" if abs(v) >= 1000 or k == "heat.power" else f"{_num(v, 0)} W"
+ return T(LIVE_WORDS[k], v=s) if k in LIVE_WORDS else s
+
+
+def device_values(d: dict) -> str:
+ return ", ".join(live_words(k, v) for k, v in d.get("live") or [])
+
+
+def device_state(d: dict) -> str:
+ """In use · reading on · control off / Added · reading off, with a dot."""
+ on = bool(d.get("read"))
+ parts = [T("In use"), T("reading on")] if on else [T("Added"), T("reading off")]
+ if d.get("controls"):
+ parts.append(T("control on") if d.get("control") else T("control off"))
+ return f' ' + E(" · ".join(parts))
+
+
+def model_line(d: dict) -> str:
+ if d.get("generic"):
+ return E(d.get("model", "").split(" (")[0]) + f' · {E(T("generic profile"))} '
+ return E(f"{d.get('manufacturer', '')} {d.get('model', '')}".strip())
+
+
+def status_badge(status, explain: bool = True) -> str:
+ """A profile's status as a small badge, its explanation behind an "i"."""
+ if status not in PROFILE_STATUS:
+ return ""
+ word, cls, why = PROFILE_STATUS[status]
+ return f'{E(T(word))} ' + (info(E(T(why))) if explain else "")
+
+
+def protection_badge(d: dict) -> str:
+ if d.get("protection") == "sealed":
+ return f'{E(T("sealed"))} '
+ if any((e or {}).get("level") == "protected" for e in (d.get("policy") or {}).values()):
+ return f'{E(T("protected"))} '
+ return ""
+
+
+def section(title: str, body: str, extra: str = "") -> str:
+ return f''
+
+
+def save_button() -> str:
+ """Save, shown only once something changed (by CSS)."""
+ return f'{E(T("Save"))}
'
+
+
+def notes(d: dict, rooms=(), values: bool = True) -> str:
+ """What a device lacks or leaves to others, in words (quietly); the
+ values it does not report only on its own page (values)."""
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"):
+ lacks = dp.lacks(d.get("missing"))
+ if lacks["values"] and values:
+ out.append(T("This device does not report: {values}.", values=reads_words([(k, "") for k in lacks["values"]])))
+ gone = [T("{control} control", control=T(CONTROL_WORDS.get(k, k))) for k in lacks["controls"]] + lacks["other"]
+ if gone:
+ out.append(T("Not found in Home Assistant: {entities}.", entities=", ".join(gone)))
+ left = d.get("left_out") or {}
+ if left.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"):
+ values=ids_words(left["values"], rooms)))
+ if left.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")]
+ controls=", ".join(T(CONTROL_WORDS.get(k, k)) for k in left["controls"])))
+ assumed = d.get("assumed") if "assumed" in d else dp.reads([a 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)))
+ "what was last sent to it and never takes it as feedback.", values=reads_words(assumed)))
return "".join(f'{E(x)}
' 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 []))
+ """Reading and control, each a switch that takes effect at once, as on
+ the Hub's Devices page; only with the site's consent (the add-on's
+ configuration)."""
+ kinds = control_words(d.get("controls"))
if not site.get("share"):
- return ('' + 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)."))
- + "
")
- ctl = ('" + E(T("Cantabile may control it ({controls}), within your limits", controls=kinds))
- + " ") if kinds else ""
- note = ('' + E(T("Control also needs your consent to control devices in the add-on's configuration."))
- + "
") if kinds and not site.get("control") else ""
- return form("consent", hidden(id=d["id"]) + '" + E(T("Cantabile may read these values"))
- + f" {ctl}", T("Save")) + note
+ return section(T("Reading and control"), '' + 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).")) + "
")
+ read, control = bool(d.get("read")), bool(d.get("control"))
+
+ def row(title, note, on, values):
+ pill = f'{E(T("On") if on else T("Off"))} '
+ inner = hidden(id=d["id"]) + "".join(f' '
+ for k, v in values.items())
+ return (f'{E(title)} {pill}{E(note)}
'
+ + form("consent", inner, T("Turn off") if on else T("Turn on"), "secondary") + "
")
+ rows = row(T("Reading"), T("Cantabile may read these values."), read, {"read": not read, "control": control and not read})
+ if kinds:
+ rows += row(T("Control"), T("Cantabile may control it ({controls}), within your limits.", controls=kinds), control,
+ {"read": read or not control, "control": not control})
+ if not site.get("control"):
+ rows += '' + E(T("Control also needs your consent to control devices in the add-on's "
+ "configuration.")) + "
"
+ return section(T("Reading and control"), rows)
+
+
+def reads_html(d: dict, rooms=()) -> str:
+ lines = [f'{E(T("Reads: {values}", values=reads_words(d.get("reads"), rooms) or T("nothing")))}
']
+ kinds = control_words(d.get("controls"))
+ if kinds:
+ lines.append(f'{E(T("Controls: {controls}", controls=kinds))}
')
+ return section(T("What Cantabile reads"), "".join(lines) + notes(d, rooms))
def switchover_html(d: dict) -> str:
@@ -514,14 +676,14 @@ def switchover_html(d: dict) -> str:
lo, hi = sw.get("heat_below_c", 15), sw.get("cool_above_c", 22)
radios = "".join(f' '
f"{E(T(w))} " for k, w in SWITCHOVER_WORDS.items())
- inner = (hidden(id=d["id"]) + f'{E(T("This thermostat can heat and cool. Cantabile uses one at a time; the other is never touched."))}
'
- + radios
- + f'{E(T("By outdoor temperature: heat below (°C)"))} '
- f' '
- f'{E(T("cool above (°C)"))} '
- f' '
- f'{E(T("Between the two it stays as it is, so it does not switch back and forth on a mild day."))}
')
- return f"{E(T('Heating or cooling'))} {form('switchover', inner, T('Save'))} "
+ inner = (hidden(id=d["id"]) + radios + ''
+ f'{E(T("Between the two it stays as it is, so it does not switch back and forth on a mild day."))}
')
+ about = info(E(T("This thermostat can heat and cool. Cantabile uses one at a time; the other is never touched.")))
+ return section(T("Heating or cooling"), form("switchover", inner, T("Save"), "save", form_cls="changes"), about)
FACING_WORDS = {"": M("Not known"), "N": M("North"), "NE": M("North-east"), "E": M("East"), "SE": M("South-east"),
@@ -532,7 +694,7 @@ 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'{E(T("No room"))} ' + "".join(
+ return f'{E(T("No room"))} ' + "".join(
f'{E(r)} ' for r in names)
@@ -546,15 +708,16 @@ def shade_html(d: dict, rooms) -> str:
opts = "".join(f'{E(T(w))} ' for k, w in FACING_WORDS.items())
if cur is None:
opts += f'{face:g}° '
- inner = (hidden(id=d["id"]) + '' + E(T(
+ inner = (hidden(id=d["id"]) + '
'
+ f'
{E(T("Room it shades"))} '
+ f'{_room_options(rooms, sh.get("area") or "")}
'
+ f'
{E(T("The window faces"))} {opts}
'
+ '' + E(T("Without the window's direction Cantabile only closes it at night in winter.")) + "
")
+ about = info(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.")) + "
"
- f'{E(T("Room it shades"))} '
- f'{_room_options(rooms, sh.get("area") or "")} '
- f'{E(T("The window faces"))} {opts} '
- '' + E(T("Without the window's direction Cantabile only closes it at night in winter.")) + "
")
- return f"{E(T('Room and window'))} {form('shade', inner, T('Save'))} "
+ "move it by hand it waits 4 hours.")))
+ return section(T("Room and window"), form("shade", inner, T("Save"), "save", form_cls="changes"), about)
def place_html(d: dict, rooms) -> str:
@@ -566,9 +729,9 @@ def place_html(d: dict, rooms) -> str:
inner = (hidden(id=d["id"])
+ f'{E(T("Indoor, in the room:"))} '
+ f'{_room_options(rooms, pl.get("area") or "")} '
- + f'{E(T("Outdoor: Cantabile's outside temperature"))} '
- + '' + E(T("An outdoor sensor counts before the weather service's temperature.")) + "
")
- return f"{E(T('Indoor or outdoor'))} {form('place', inner, T('Save'))} "
+ + f'{E(T("Outdoor: Cantabile's outside temperature"))} ')
+ about = info(E(T("An outdoor sensor counts before the weather service's temperature.")))
+ return section(T("Indoor or outdoor"), form("place", inner, T("Save"), "save", form_cls="changes"), about)
def weather_html(d: dict) -> str:
@@ -577,9 +740,11 @@ def weather_html(d: dict) -> str:
if not w:
return ""
if w.get("active"):
- return '' + E(T("Cantabile plans with this forecast: solar, heating, cooling and the shades.")) + "
"
- return ('' + E(T("Not used for planning: Cantabile plans with one weather forecast, another one's."))
- + "
" + form("weather", hidden(id=d["id"]), T("Plan with this forecast"), "secondary"))
+ return section(T("Forecast"), '' + E(T(
+ "Cantabile plans with this forecast: solar, heating, cooling and the shades.")) + "
")
+ return section(T("Forecast"), '' + E(T(
+ "Not used for planning: Cantabile plans with one weather forecast, another one's.")) + "
"
+ + form("weather", hidden(id=d["id"]), T("Plan with this forecast"), "secondary"))
def protection_html(d: dict) -> str:
@@ -589,11 +754,15 @@ def protection_html(d: dict) -> str:
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
+ profile_name = f"{d.get('manufacturer', '')} {d.get('model', '')}".strip()
rows = []
- covers = {f"control:{c['id']}" for c in d.get("controls") or [] if c.get("kind") == "cover" and c.get("id")}
+ kinds = {f"control:{c['id']}": c.get("kind") for c in d.get("controls") or [] if c.get("id")}
+ covers = {t for t, k in kinds.items() if k == "cover"}
for t in targets:
e = pol.get(t) or {}
kind, _, name = t.partition(":")
+ if kind == "control" and kinds.get(t) in CONTROL_WORDS:
+ name = T(CONTROL_WORDS[kinds[t]])
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")
@@ -602,54 +771,61 @@ def protection_html(d: dict) -> str:
rows.append(f'{E(what)}: {E(T("Sealed"))} · {E(T("only {who} can change it", who=custodian(seal or e)))}'
f'{": " + E(why) if why else ""} ')
continue
- why = f" ({E(e['why'])})" if e.get("why") and lvl == "protected" else ""
+ # the profile's default says only the profile's name: not repeated
+ why = f" ({E(e['why'])})" if e.get("why") and e["why"] != profile_name and lvl == "protected" else ""
state = f"{E(T('protected'))} " if lvl == "protected" else E(T("not protected"))
- rows.append(f"{E(what)}: {state}{why} "
+ rows.append(f' {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)
+ lift if lvl == "protected" else T("Protect"), "secondary")
+ " ")
- return (f"{E(T('Protection'))} "
- + 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'
')
+ about = 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 " " + T(
+ "A protected blind or curtain is not moved by Cantabile at all.")))
+ return section(T("Protection"), f'', info(about))
-def badges(d: dict) -> str:
- st = PROFILE_STATUS.get(d.get("status"))
- out = f'{E(d.get("manufacturer", ""))} {E(d.get("model", ""))} '
- if d.get("generic"):
- out += f'{E(T("generic profile"))} '
- if st:
- out += f'{E(T(st))} '
- return out
+def remove_html(d: dict) -> str:
+ return ('' + E(T("Remove from Cantabile")) + " "
+ + '' + E(T("Cantabile stops using it. Home Assistant keeps the device as it is.")) + "
"
+ + form("remove", hidden(id=d["id"]), T("Yes, remove it"), "danger") + " ")
-def device_card(d: dict, site: dict, rooms=()) -> str:
- return (f'{E(d["name"])} {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"
{E(T('Remove'))} "
- + E(T("Cantabile stops using it. Home Assistant keeps the device as it is."))
- + "
" + form("remove", hidden(id=d["id"]), T("Stop using it with Cantabile"), "secondary") + " ")
+def device_row(d: dict) -> str:
+ """A device in use on the list: name, state in words, main values now,
+ protection; its settings on its own page."""
+ vals = device_values(d)
+ return (f''
+ f'{E(d["name"])} {protection_badge(d)}'
+ f'{model_line(d)} {device_state(d)} '
+ + (f'{E(vals)} ' if vals else "")
+ + ' › ')
-def offer_card(h: dict) -> str:
+def offer_card(h: dict, rooms=()) -> str:
+ """A device HA has that a profile knows, not used yet: what it would
+ give, "Use with Cantabile"."""
p = h["profile"]
name = h["name"] or h["model"]
+ generic = f' · {E(T("generic profile"))} ' if h.get("generic") else ""
+ would = T("Cantabile would read: {values}.", values=reads_words(dp.reads(h["assets"]), rooms) or T("nothing"))
+ kinds = control_words(h["controls"])
+ if kinds:
+ would += " " + T("It could control: {controls}.", controls=kinds)
proposed = ""
if h.get("in_mapping"):
- ids = ", ".join(quantity_words(i) for i in h["in_mapping"])
+ ids = ids_words(h["in_mapping"], rooms)
proposed = '' + 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)) + "
"
- body = what_lines(h["assets"], h["controls"], True) + notes(h) + proposed
- view = dict(h, status=p.get("status"))
+ head = (f'{E(name)} {status_badge(p.get("status"), False)}'
+ f'{E((h.get("manufacturer", "") + " " + h.get("model", "")).strip())}{generic} ')
+ body = f'{E(would)}
' + notes(h, rooms, False) + proposed
if not h["assets"] and not h["controls"]:
- return f'{E(name)} {badges(view)}{body}
'
- return (f'{E(name)} {badges(view)}{body}'
- + form("use", hidden(ha_device=h["id"], profile=p["id"], name=name), T("Use with Cantabile")) + "
")
+ return f''
+ return (f'{head}'
+ + form("use", hidden(ha_device=h["id"], profile=p["id"], name=name), T("Use with Cantabile"), "secondary")
+ + f"
{body}
")
def nav(page: str) -> str:
@@ -664,32 +840,55 @@ def html(title: str, body: str, page: str) -> str:
f"{nav(page)}{body}