cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.400: full source
This commit is contained in:
1 parent
343331d234
commit
d5fbcacaa4
176 files changed
+32511
-19
No files matched your search
@@ -0,0 +1,199 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from cantabile_edge import agent as agent_mod
|
||||
from cantabile_edge.config import Config
|
||||
from cantabile_edge.ha import HAClient, HAError, READ_ONLY
|
||||
from cantabile_edge.mapping import Mapping
|
||||
from cantabile_edge.store import Queue
|
||||
|
||||
SITE = "0123456789abcdef0123456789abcdef"
|
||||
|
||||
|
||||
class FlakySink:
|
||||
"""Fails while down; records what it accepted."""
|
||||
|
||||
def __init__(self):
|
||||
self.down, self.got = False, []
|
||||
|
||||
async def send(self, seq, kind, payload):
|
||||
if self.down:
|
||||
return False
|
||||
self.got.append(seq)
|
||||
return True
|
||||
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def make_agent(tmp_path, sink):
|
||||
m = tmp_path / "m.yaml"
|
||||
m.write_text(yaml.safe_dump({"version": 4, "assets": [
|
||||
{"entity": "sensor.pv", "asset": "pv.power", "kind": "gauge", "unit": "W", "consent": True},
|
||||
{"entity": "sensor.cam", "asset": "room.hall.power", "kind": "gauge", "unit": "W", "consent": False}]}))
|
||||
cfg = Config(site_id=SITE, interval_s=60, mapping=str(m), state_dir=str(tmp_path))
|
||||
a = agent_mod.Agent(cfg, Mapping.load(str(m)), Queue(str(tmp_path / "q.db"), 100), sink)
|
||||
a.consent.set(True, by="test")
|
||||
return a
|
||||
|
||||
|
||||
def test_consent_filter_and_units(tmp_path):
|
||||
a = make_agent(tmp_path, FlakySink())
|
||||
a.agg.begin(1000)
|
||||
a.clock = lambda: 1010.0
|
||||
a.on_entities({"a": {"sensor.pv": {"s": "1.2", "a": {"unit_of_measurement": "kW"}},
|
||||
"sensor.cam": {"s": "5", "a": {"unit_of_measurement": "W"}},
|
||||
"sensor.unmapped": {"s": "7", "a": {}}}})
|
||||
recs = a.agg.flush(1020)
|
||||
assert [r["asset"] for r in recs] == ["pv.power"] # no consent, unmapped: never leave
|
||||
assert recs[0]["last"] == 1200
|
||||
|
||||
|
||||
def test_unavailable_state_is_none(tmp_path):
|
||||
a = make_agent(tmp_path, FlakySink())
|
||||
a.agg.begin(1000)
|
||||
a.clock = lambda: 1010.0
|
||||
a.on_entities({"a": {"sensor.pv": {"s": "unavailable", "a": {"unit_of_measurement": "W"}}}})
|
||||
r = a.agg.flush(1020)[0]
|
||||
assert "mean" not in r and r["unavailable_s"] > 0
|
||||
|
||||
|
||||
def test_climate_feeds_heating_cooling_state_and_room_temp(tmp_path):
|
||||
"""One climate entity, three assets: heating.state and cooling.state from
|
||||
its hvac_action (1/0), the room's temperature from current_temperature;
|
||||
an attribute changing alone is news."""
|
||||
m = tmp_path / "m.yaml"
|
||||
c = "climate.livingroom_ac_thermostat"
|
||||
m.write_text(yaml.safe_dump({"version": 3, "assets": [
|
||||
{"entity": c, "asset": "heating.state", "kind": "gauge", "unit": "", "attribute": "hvac_action", "equals": "heating",
|
||||
"consent": True},
|
||||
{"entity": c, "asset": "cooling.state", "kind": "gauge", "unit": "", "attribute": "hvac_action", "equals": "cooling",
|
||||
"consent": True},
|
||||
{"entity": c, "asset": "room.living_room.temp_2", "kind": "gauge", "unit": "°C", "attribute": "current_temperature",
|
||||
"consent": True}]}))
|
||||
cfg = Config(site_id=SITE, interval_s=60, mapping=str(m), state_dir=str(tmp_path))
|
||||
a = agent_mod.Agent(cfg, Mapping.load(str(m)), Queue(str(tmp_path / "q.db"), 100), FlakySink())
|
||||
a.consent.set(True, by="test")
|
||||
a.agg.begin(1000)
|
||||
a.clock = lambda: 1010.0
|
||||
a.on_entities({"a": {c: {"s": "heat", "a": {"hvac_action": "heating", "current_temperature": 21.5}}}})
|
||||
a.clock = lambda: 1015.0
|
||||
a.on_entities({"c": {c: {"+": {"a": {"hvac_action": "idle"}, "lu": 1015.0}}}}) # the attribute alone
|
||||
recs = {r["asset"]: r for r in a.agg.flush(1020)}
|
||||
assert recs["heating.state"]["last"] == 0 and recs["heating.state"]["max"] == 1
|
||||
assert recs["cooling.state"]["last"] == 0
|
||||
assert recs["room.living_room.temp_2"]["last"] == 21.5 # kept: no new temperature
|
||||
assert Mapping.load(str(m)).by_entity[c].asset == "heating.state"
|
||||
|
||||
|
||||
def test_equals_needs_a_gauge(tmp_path):
|
||||
m = tmp_path / "m.yaml"
|
||||
m.write_text(yaml.safe_dump({"version": 3, "assets": [
|
||||
{"entity": "climate.x", "asset": "heating.state", "kind": "counter", "unit": "", "equals": "heating"}]}))
|
||||
with pytest.raises(ValueError):
|
||||
Mapping.load(str(m))
|
||||
|
||||
|
||||
async def test_outage_replays_in_order(tmp_path):
|
||||
sink = FlakySink()
|
||||
a = make_agent(tmp_path, sink)
|
||||
a.started = 0
|
||||
sink.down = True
|
||||
up = asyncio.create_task(a.uploader())
|
||||
for i in range(4):
|
||||
a.agg.begin(1000 + 60 * i)
|
||||
a.agg.sample("pv.power", "gauge", float(i), 1000 + 60 * i)
|
||||
a.close_window(1020 + 60 * i)
|
||||
await asyncio.sleep(1.5)
|
||||
assert sink.got == [] and a.queue.depth() == 4 # kept while down
|
||||
sink.down = False
|
||||
for _ in range(100):
|
||||
if not a.queue.depth():
|
||||
break
|
||||
await asyncio.sleep(0.1)
|
||||
a.stop.set()
|
||||
await up
|
||||
assert sink.got == sorted(sink.got) and len(sink.got) == 4 and a.queue.depth() == 0
|
||||
|
||||
|
||||
async def test_client_refuses_anything_but_reads():
|
||||
c = HAClient("ws://unused", "t")
|
||||
for t in ("call_service", "execute_script", "config/entity_registry/update", "fire_event"):
|
||||
with pytest.raises(HAError):
|
||||
await c.send(t)
|
||||
assert not any(t.startswith(("call", "execute", "fire")) for t in READ_ONLY)
|
||||
|
||||
|
||||
def test_parts_and_their_totals(tmp_path):
|
||||
"""Two inverters and two batteries (pv.1.power, pv.2.power, ...): each
|
||||
part is sent, and its total (pv.power: the sum; battery.soc: the mean)
|
||||
as if mapped, so the cloud and the optimiser read totals as before;
|
||||
a part without consent is not in it, a part without a value leaves a
|
||||
gauge's total unknown and a counter's waiting."""
|
||||
m = tmp_path / "m.yaml"
|
||||
a_ = lambda e, q, kind="gauge", unit="W", consent=True: {"entity": e, "asset": q, "kind": kind, "unit": unit, # noqa: E731
|
||||
"consent": consent}
|
||||
m.write_text(yaml.safe_dump({"version": 3, "assets": [
|
||||
a_("sensor.pv_a", "pv.1.power"), a_("sensor.pv_b", "pv.2.power"),
|
||||
a_("sensor.e_a", "pv.1.energy", "counter", "Wh"), a_("sensor.e_b", "pv.2.energy", "counter", "Wh"),
|
||||
a_("sensor.soc_a", "battery.1.soc", unit="%"), a_("sensor.soc_b", "battery.2.soc", unit="%"),
|
||||
a_("sensor.ev_a", "ev.1.power"), a_("sensor.ev_b", "ev.2.power", consent=False),
|
||||
a_("sensor.grid", "grid.power"), a_("sensor.grid_b", "grid.2.power")]}))
|
||||
mp = Mapping.load(str(m))
|
||||
assert sorted(mp.totals) == ["battery.soc", "ev.power", "pv.energy", "pv.power"] # grid.power is mapped
|
||||
assert mp.inputs.pv_power == ["sensor.pv_a", "sensor.pv_b"] and mp.inputs.load_power == ""
|
||||
cfg = Config(site_id=SITE, interval_s=60, mapping=str(m), state_dir=str(tmp_path))
|
||||
a = agent_mod.Agent(cfg, mp, Queue(str(tmp_path / "q.db"), 100), FlakySink())
|
||||
a.consent.set(True, by="test")
|
||||
a.agg.begin(1000)
|
||||
a.clock = lambda: 1001.0
|
||||
w, pct, wh = ({"unit_of_measurement": u} for u in ("W", "%", "Wh"))
|
||||
a.on_entities({"a": {"sensor.pv_a": {"s": "1000", "a": w}, "sensor.soc_a": {"s": "80", "a": pct},
|
||||
"sensor.e_a": {"s": "500", "a": wh}, "sensor.ev_a": {"s": "7000", "a": w},
|
||||
"sensor.ev_b": {"s": "3000", "a": w}}})
|
||||
a.clock = lambda: 1002.0
|
||||
a.on_entities({"a": {"sensor.pv_b": {"s": "2.5", "a": {"unit_of_measurement": "kW"}},
|
||||
"sensor.soc_b": {"s": "40", "a": pct}, "sensor.e_b": {"s": "700", "a": wh}}})
|
||||
a.clock = lambda: 1030.0
|
||||
a.on_entities({"c": {"sensor.e_a": {"+": {"s": "600", "lu": 1030}}}})
|
||||
recs = {r["asset"]: r for r in a.agg.flush(1060)}
|
||||
assert recs["pv.power"]["last"] == 3500 and recs["pv.1.power"]["last"] == 1000
|
||||
assert recs["battery.soc"]["last"] == 60
|
||||
assert recs["ev.power"]["last"] == 7000 # ev.2 has no consent
|
||||
assert recs["pv.energy"]["last"] == 1300 and recs["pv.energy"]["delta"] == 100
|
||||
a.on_entities({"c": {"sensor.pv_b": {"+": {"s": "unavailable", "lu": 1070}},
|
||||
"sensor.e_b": {"+": {"s": "unknown", "lu": 1070}}}})
|
||||
recs = {r["asset"]: r for r in a.agg.flush(1120)}
|
||||
assert recs["pv.power"].get("last") is None and recs["pv.power"]["unavailable_s"] == 60
|
||||
assert recs["pv.energy"]["delta"] == 0 and recs["pv.energy"]["resets"] == 0
|
||||
|
||||
|
||||
def test_devices_page_change_loads_the_mapping_again(tmp_path):
|
||||
"""The add-on's Devices page wrote a fragment: the agent reads it at once
|
||||
(devpage.py, agent.devices_changed), without a restart."""
|
||||
import json as _json
|
||||
a = make_agent(tmp_path, FlakySink())
|
||||
(tmp_path / "mapping.d").mkdir()
|
||||
(tmp_path / "mapping.d" / "ac-1.yaml").write_text(_json.dumps({"version": 3, "device": "ac-1", "assets": [
|
||||
{"entity": "climate.ac", "asset": "room.hall.temp", "kind": "gauge", "unit": "°C", "consent": False,
|
||||
"attribute": "current_temperature"}]}))
|
||||
assert "room.hall.temp" not in a.mapping.by_asset
|
||||
asyncio.run(a.devices_changed())
|
||||
assert "room.hall.temp" in a.mapping.by_asset and a.inventory.mapping is a.mapping and a.inventory_now.is_set()
|
||||
|
||||
|
||||
def test_restart_for_a_devices_consent(tmp_path, monkeypatch):
|
||||
"""A device's consent changed on the add-on's page: the agent stops with
|
||||
RESTART a moment later and addon-run starts it again (as the Hub's tool
|
||||
restarts it)."""
|
||||
a = make_agent(tmp_path, FlakySink())
|
||||
monkeypatch.setattr(agent_mod, "RESTART_DELAY_S", 0.01)
|
||||
|
||||
async def go():
|
||||
await a.devices_changed(restart=True)
|
||||
assert a.exit_code == agent_mod.RESTART and not a.stop.is_set() # the page answers first
|
||||
await asyncio.wait_for(a.stop.wait(), 1)
|
||||
asyncio.run(go())
|
||||
@@ -0,0 +1,191 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""What the agent shows in Home Assistant (announce.py): areas, the
|
||||
exchanged data, the commands received, the value per device, the flats of a
|
||||
building; MQTT credentials."""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import yaml
|
||||
|
||||
from cantabile_edge import agent as agent_mod
|
||||
from cantabile_edge import names
|
||||
from cantabile_edge.announce import Announcer
|
||||
from cantabile_edge.config import Config
|
||||
from cantabile_edge.controller import public_args, sender
|
||||
from cantabile_edge.mapping import Mapping
|
||||
from cantabile_edge.mqtt import Client
|
||||
from cantabile_edge.store import Queue
|
||||
|
||||
from test_agent import FlakySink
|
||||
from test_control_parts import MAPPING, SITE
|
||||
|
||||
|
||||
def make(tmp_path, mapping=MAPPING):
|
||||
m = tmp_path / "m.yaml"
|
||||
m.write_text(yaml.safe_dump(mapping))
|
||||
cfg = Config(site_id=SITE, mapping=str(m), state_dir=str(tmp_path))
|
||||
a = agent_mod.Agent(cfg, Mapping.load(str(m)), Queue(str(tmp_path / "q.db"), 100), FlakySink())
|
||||
return a, Announcer(a, "127.0.0.1", 1883)
|
||||
|
||||
|
||||
def put(path, data):
|
||||
"""As the link writes a bundle: a new file renamed into place."""
|
||||
tmp = str(path) + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(data, f)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def tariff(now, **kw):
|
||||
start = int(now // 900 * 900)
|
||||
return {"v": 1, "kind": "tariff", "id": "t1", "site": SITE, "issued": int(now), "start": start, "step_s": 900,
|
||||
"steps": 192, "expires": int(now) + 86400, "currency": "EUR", "unit": "ct/kWh",
|
||||
"import": [30.0 + i for i in range(192)], "export": [8.0] * 192, "estimated": [],
|
||||
"other": {"gas": 11.5}, "sources": ["awattar"], **kw}
|
||||
|
||||
|
||||
def test_device_in_the_cantabile_area(tmp_path):
|
||||
a, ann = make(tmp_path)
|
||||
dev = ann._configs()[("binary_sensor", "cloud")]["device"]
|
||||
assert dev["suggested_area"] == "Cantabile"
|
||||
a.ha_language = "de"
|
||||
assert names.area("flats", a.ha_language) == "Wohnungen"
|
||||
assert names.area("flats", "pt-BR") == "Flats" # unknown: English
|
||||
assert names.name("model", "de") == "Prognosemodell"
|
||||
assert names.name("cloud", "en") == "Cloud"
|
||||
|
||||
|
||||
def test_tariff_model_commands_and_devices(tmp_path):
|
||||
a, ann = make(tmp_path)
|
||||
now = time.time()
|
||||
put(tmp_path / "tariff.json", tariff(now))
|
||||
put(tmp_path / "model.json", {"v": 1, "kind": "model", "id": "m1", "site": "*",
|
||||
"issued": int(now), "source": "shared-v0",
|
||||
"forecasts": {"load_w": {"profile": "hour_of_week",
|
||||
"values": [500] * 168}}})
|
||||
objs = ann.objects()
|
||||
keys = {(c, o) for (_, c, o) in objs}
|
||||
for k in [("sensor", "price_import_now"), ("sensor", "price_import_next"), ("sensor", "price_export_now"),
|
||||
("sensor", "price_gas"), ("sensor", "model"), ("event", "commands"), ("sensor", "set_battery"),
|
||||
("sensor", "set_living"), ("binary_sensor", "cloud")]:
|
||||
assert k in keys, k
|
||||
assert ("sensor", "next_action") not in keys # shadow: no plan in HA
|
||||
p = objs[(ann.uid, "sensor", "price_import_now")]
|
||||
assert p["unit_of_measurement"] == "EUR/kWh" and p["suggested_display_precision"] == 3 # 0.167, not 0.16699…
|
||||
assert "round(4)" in p["value_template"]
|
||||
ev = objs[(ann.uid, "event", "commands")]
|
||||
assert set(ev["event_types"]) >= {"mode", "control", "release", "limits", "tariff", "model", "building"}
|
||||
t = a.control.bundles.tariff_now(now)
|
||||
assert t["import_now"] == 30.0 and t["import_next"] == 31.0 and t["export_now"] == 8.0
|
||||
assert t["curve"]["sources"] == ["awattar"] and len(t["curve"]["import"]) == 192
|
||||
assert a.control.bundles.model_info()["source"] == "shared-v0"
|
||||
# no tariff (expired): its sensors leave HA
|
||||
put(tmp_path / "tariff.json", tariff(now, expires=int(now) - 1))
|
||||
assert ("sensor", "price_import_now") not in {(c, o) for (_, c, o) in ann.objects()}
|
||||
|
||||
|
||||
def test_commands_received_and_actuators(tmp_path):
|
||||
a, ann = make(tmp_path)
|
||||
got = []
|
||||
|
||||
async def cb(ev):
|
||||
got.append(ev)
|
||||
a.control.on_received.append(cb)
|
||||
ok, _ = asyncio.run(a.control.command("control", {"asset": "battery", "set": "1500", "level": "flexible",
|
||||
"minutes": "30", "why": "test"}))
|
||||
assert ok and got[-1]["cmd"] == "control" and got[-1]["by"] == "cloud" and got[-1]["result"] == "applied"
|
||||
ok, _ = asyncio.run(a.control.command("limits", {"asset": "nope", "quantity": "temp_c", "level": "building"}))
|
||||
assert not ok and got[-1]["by"] == "building" and got[-1]["result"] == "refused"
|
||||
assert sender("building", {"level": "emergency"}) == "grid"
|
||||
assert "proof" not in public_args({"proof": "verified:x", "value": "3"})
|
||||
act = a.control.actuators()
|
||||
assert act["battery"]["source"] == "cloud" and act["battery"]["value"] == 1500.0
|
||||
assert act["battery"]["acting"] is False # shadow
|
||||
assert act["living"]["limits"]["temp_c"]["levels"]["owner"] == [19, 24]
|
||||
assert act["living"]["limits"]["temp_c"]["floor_by"] == "inhabitant"
|
||||
# the list HA shows (sensor received): newest first, in words, the control by name
|
||||
conf = ann.objects()[(ann.uid, "sensor", "received")]
|
||||
assert conf["state_topic"].endswith("/received") and "availability_topic" not in conf # kept across restarts
|
||||
rec = ann.received_list(a.control)
|
||||
assert [r["what"] for r in rec] == ["nope: new limits", "Battery: set to 1500"] # no such control: as sent
|
||||
assert rec[1]["by"] == "cloud" and rec[1]["result"] == "applied" and rec[0]["result"] == "refused"
|
||||
a.ha_language = "de"
|
||||
assert ann.received_list(a.control)[1]["what"] == "Battery: auf 1500"
|
||||
|
||||
|
||||
def test_controls_by_name(tmp_path):
|
||||
"""Controls in HA by the mapping's name, else their id in words, never
|
||||
the snake_case id ("Cantabile living_room_cooling: set by Cantab…")."""
|
||||
mapping = dict(MAPPING, controls=[dict(c, name="Living-room heating") if c["id"] == "living" else c
|
||||
for c in MAPPING["controls"]])
|
||||
a, ann = make(tmp_path, mapping)
|
||||
a.control.mode.set("auto", "test")
|
||||
objs = ann.objects()
|
||||
assert objs[(ann.uid, "sensor", "set_living")]["name"] == "Living-room heating: setting"
|
||||
assert objs[(ann.uid, "sensor", "set_battery")]["name"] == "Battery: setting"
|
||||
assert objs[(ann.uid, "sensor", "plan_living")]["name"] == "Living-room heating: plan"
|
||||
now = time.time()
|
||||
a.control.plan = {"made": now, "devices": {"living": [{"t": now + 600, "set": 21, "why": "cheap"}]}}
|
||||
st = ann._plan_state()
|
||||
assert st["next"].startswith("Living-room heating: 21 at ")
|
||||
assert st["attrs"]["next"][0]["name"] == "Living-room heating" and st["attrs"]["next"][0]["control"] == "living"
|
||||
|
||||
|
||||
def test_entity_ids_are_set(tmp_path):
|
||||
"""HA would make them from the names (0.3.0's check got
|
||||
binary_sensor.cantabile_cantabile_cloud); set, they don't depend on names."""
|
||||
a, ann = make(tmp_path)
|
||||
a.ha_language = "de"
|
||||
objs = ann.objects()
|
||||
assert objs[(ann.uid, "binary_sensor", "cloud")]["default_entity_id"] == "binary_sensor.cantabile_cloud"
|
||||
now = time.time()
|
||||
put(tmp_path / "flats.json", {"v": 1, "kind": "flats", "id": "f1", "site": SITE, "issued": int(now),
|
||||
"expires": int(now) + 3600, "flats": [{"id": "W-1", "label": "Wohnung 1"}]})
|
||||
assert ann.objects()[(f"{ann.uid}_flat_w_1", "sensor", "grid")]["default_entity_id"] == "sensor.cantabile_flat_w_1_grid"
|
||||
|
||||
|
||||
def test_flats_of_a_building(tmp_path):
|
||||
a, ann = make(tmp_path)
|
||||
a.ha_language = "de"
|
||||
now = time.time()
|
||||
put(tmp_path / "flats.json", {
|
||||
"v": 1, "kind": "flats", "id": "f1", "site": SITE, "issued": int(now), "expires": int(now) + 3600,
|
||||
"flats": [{"id": "W-1", "label": "Wohnung 1", "state": {"grid_w": 800},
|
||||
"flex": {"start": int(now // 900 * 900), "step_s": 900, "shed_w": [300, 200]},
|
||||
"commands": [{"control": "load_limit", "value": 2500, "level": "flexible",
|
||||
"until": int(now) + 600}]}]})
|
||||
objs = ann.objects()
|
||||
node = f"{ann.uid}_flat_w_1"
|
||||
grid = objs[(node, "sensor", "grid")]
|
||||
assert grid["device"]["via_device"] == ann.uid and grid["device"]["model"] == "Flat"
|
||||
assert grid["device"]["suggested_area"] == "Wohnungen" and grid["name"] == "Netzbezug"
|
||||
st = Announcer.flat_state(json.loads((tmp_path / "flats.json").read_text())["flats"][0], now)
|
||||
assert st["grid_w"] == 800 and st["flex_now"] == 300 and st["request"].startswith("load_limit 2500")
|
||||
# another site's flats: not shown
|
||||
d = json.loads((tmp_path / "flats.json").read_text())
|
||||
d["site"] = "cd" * 16
|
||||
put(tmp_path / "flats.json", d)
|
||||
assert not [k for k in ann.objects() if k[0] == node]
|
||||
|
||||
|
||||
def test_mqtt_connect_with_a_password():
|
||||
async def run():
|
||||
seen = {}
|
||||
|
||||
async def broker(r, w):
|
||||
first = await r.readexactly(2)
|
||||
seen["body"] = await r.readexactly(first[1])
|
||||
w.write(b"\x20\x02\x00\x00")
|
||||
await w.drain()
|
||||
srv = await asyncio.start_server(broker, "127.0.0.1", 0)
|
||||
port = srv.sockets[0].getsockname()[1]
|
||||
c = Client("127.0.0.1", port, "cid", username="cantabile-edge", password="pw")
|
||||
await c.connect("t/avail", b"offline")
|
||||
await c.close()
|
||||
srv.close()
|
||||
return seen["body"]
|
||||
body = asyncio.run(run())
|
||||
assert body[7] & 0xC0 == 0xC0 # user name and password flags
|
||||
assert body.endswith(b"\x00\x0ecantabile-edge\x00\x02pw")
|
||||
@@ -0,0 +1,56 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Cantabile's devices into the area "Cantabile" (areas.py) against a fake HA."""
|
||||
import asyncio
|
||||
|
||||
from cantabile_edge import areas
|
||||
|
||||
UID = "cantabile_s1"
|
||||
|
||||
|
||||
class FakeHA:
|
||||
def __init__(self, devices, area_list):
|
||||
self.devices, self.area_list, self.placed, self.made = devices, area_list, [], []
|
||||
|
||||
async def send(self, type_, **_):
|
||||
return {"config/device_registry/list": self.devices, "config/area_registry/list": self.area_list}[type_]
|
||||
|
||||
async def create_area(self, name, icon):
|
||||
self.made.append(name)
|
||||
return {"area_id": "cantabile", "name": name}
|
||||
|
||||
async def place_device(self, device_id, area_id):
|
||||
self.placed.append((device_id, area_id))
|
||||
|
||||
|
||||
def dev(id_, ident, area=None):
|
||||
return {"id": id_, "name": id_, "identifiers": [ident], "area_id": area}
|
||||
|
||||
|
||||
def test_ours_without_area_placed_and_area_made():
|
||||
ha = FakeHA([dev("agent", ["mqtt", UID]), dev("hm", ["mqtt", "cantabile_modbus_hm8042"]),
|
||||
dev("addon", ["hassio", "local_cantabile_modbus"]), dev("flat", ["mqtt", UID + "_flat_a"]),
|
||||
dev("mine", ["mqtt", "cantabile_modbus_spm_1"], area="kitchen"),
|
||||
dev("other", ["mqtt", "zigbee2mqtt_0x1"]), dev("hassio", ["hassio", "core_mosquitto"])], [])
|
||||
assert asyncio.run(areas.place(ha, UID, "de")) == 3
|
||||
assert ha.made == ["Cantabile"]
|
||||
assert ha.placed == [("agent", "cantabile"), ("hm", "cantabile"), ("addon", "cantabile")]
|
||||
|
||||
|
||||
def test_existing_area_used_nothing_to_do():
|
||||
ha = FakeHA([dev("agent", ["mqtt", UID], area="x")], [{"area_id": "x", "name": "Cantabile"}])
|
||||
assert asyncio.run(areas.place(ha, UID, "en")) == 0
|
||||
ha = FakeHA([dev("agent", ["mqtt", UID])], [{"area_id": "x", "name": "Cantabile"}])
|
||||
assert asyncio.run(areas.place(ha, UID, "en")) == 1 and ha.made == [] and ha.placed == [("agent", "x")]
|
||||
|
||||
|
||||
def test_devices_used_on_the_addon_page(tmp_path):
|
||||
"""A device the owner uses with Cantabile (devpage.py) goes to the area
|
||||
"Cantabile" when it has none; one in a room keeps its room."""
|
||||
import json as _json
|
||||
from cantabile_edge import areas as _areas
|
||||
(tmp_path / "devices.json").write_text(_json.dumps({"ha-thermostat-1": {"ha_device": "dev-ac"},
|
||||
"x": {"name": "no HA device"}}))
|
||||
used = _areas.used(str(tmp_path))
|
||||
assert used == {"dev-ac"} and _areas.used(str(tmp_path / "none")) == set()
|
||||
assert _areas.ours({"id": "dev-ac", "identifiers": [["esphome", "a"]]}, "cantabile_x", used)
|
||||
assert not _areas.ours({"id": "dev-lamp", "identifiers": [["zha", "b"]]}, "cantabile_x", used)
|
||||
@@ -0,0 +1,116 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The building's requests: parsing, the flat's floors, the plan, the cap
|
||||
on actions, binding and flexible overrides."""
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from cantabile_edge.building import Building
|
||||
from cantabile_edge.executor import Executor
|
||||
from cantabile_edge.inputs import Collector
|
||||
from test_control_parts import FakeHA, Clock, mapping, consent, mk_guard, states # noqa: F401 (fixtures)
|
||||
|
||||
highspy = pytest.importorskip("highspy")
|
||||
from cantabile_edge import optimizer # noqa: E402
|
||||
from test_optimizer import START, battery, heating, house, at # noqa: E402
|
||||
|
||||
|
||||
def cmd(control, value, level="binding", frm=START, until=START + 4 * 3600, cid="b1"):
|
||||
return {"v": "1", "id": cid, "building": "house-7", "level": level, "control": control, "value": str(value),
|
||||
"from": str(frm), "until": str(until), "why": "peak shaving"}
|
||||
|
||||
|
||||
def test_parse_and_rules(tmp_path):
|
||||
b = Building(str(tmp_path), Clock(START))
|
||||
with pytest.raises(ValueError, match="control one of"):
|
||||
b.parse(cmd("dim_lights", 1))
|
||||
with pytest.raises(ValueError, match="24 h"):
|
||||
b.parse(cmd("load_limit", 1000, until=START + 2 * 86400))
|
||||
# an emergency only as a grid operator's order the link verified (gridorder.go)
|
||||
with pytest.raises(ValueError, match="verified proof"):
|
||||
b.parse(cmd("load_limit", 1000, level="emergency"))
|
||||
with pytest.raises(ValueError, match="verified proof"):
|
||||
b.parse({**cmd("thermostat_cap", 18, level="emergency"), "proof": "verified:netz-berlin:o1"})
|
||||
assert b.parse({**cmd("load_limit", 1000, level="emergency"), "proof": "verified:netz-berlin:o1"})["level"] == "emergency"
|
||||
with pytest.raises(ValueError, match="level"):
|
||||
b.parse(cmd("load_limit", 1000, level="urgent"))
|
||||
floors = [("living", 20.5, 24, "heating")]
|
||||
ok, why = b.take(b.parse(cmd("thermostat_cap", 19)), floors)
|
||||
assert not ok and why.startswith("floor:") # below the tenant's comfort floor
|
||||
assert b.take(b.parse(cmd("thermostat_cap", 21)), floors)[0]
|
||||
ok, why = b.take(b.parse(cmd("thermostat_cap", 22, cid="b2")), floors)
|
||||
assert ok and "replaces b1" in why # a newer one replaces
|
||||
assert Building(str(tmp_path), Clock(START)).active["thermostat_cap"]["id"] == "b2" # kept on disk
|
||||
assert Building(str(tmp_path), Clock(START + 5 * 3600)).active == {} # dropped at until
|
||||
|
||||
|
||||
def test_membership(tmp_path):
|
||||
"""With the panel's membership.json only its buildings' commands count;
|
||||
without it, fleet's check alone decides (an HA add-on)."""
|
||||
b = Building(str(tmp_path), Clock(START))
|
||||
assert b.take(b.parse(cmd("load_limit", 3000)), [])[0] # no file: taken
|
||||
(tmp_path / "membership.json").write_text('{"buildings": ["other-house"]}')
|
||||
ok, why = b.take(b.parse(cmd("load_limit", 2500, cid="b2")), [])
|
||||
assert not ok and why == "not a member of that building"
|
||||
(tmp_path / "membership.json").write_text('{"buildings": ["other-house", "house-7"]}')
|
||||
assert b.take(b.parse(cmd("load_limit", 2500, cid="b3")), [])[0]
|
||||
(tmp_path / "membership.json").write_text('{"buildings": []}') # left: nothing more
|
||||
assert not b.take(b.parse(cmd("load_limit", 2000, cid="b4")), [])[0]
|
||||
|
||||
|
||||
def test_plan_keeps_the_load_limit():
|
||||
b = Building.__new__(Building)
|
||||
s = house([battery(soc=20, floor=10)])
|
||||
s["building"] = {"load_limit": {"value": 1000, "level": "binding", "from_step": 0, "to_step": 20,
|
||||
"penalty": 50.0, "id": "b1", "building": "house-7"}}
|
||||
p = optimizer.plan(s, 20)
|
||||
# without the limit the battery charges at 3 kW in the cheap night; with it, at most 600 W (1000 - 400 load)
|
||||
first = [e for e in p["devices"]["battery"] if e["t"] < START + 5 * 3600 and e["set"] > 0]
|
||||
assert first and all(e["set"] <= 600 for e in first), p["devices"]["battery"][:8]
|
||||
|
||||
|
||||
def test_plan_keeps_the_thermostat_cap():
|
||||
s = house([heating(temp=21.0)])
|
||||
s["building"] = {"thermostat_cap": {"value": 19.0, "level": "binding", "from_step": 20, "to_step": 40,
|
||||
"penalty": 50.0, "id": "b1", "building": "house-7"}}
|
||||
m = optimizer.Model(s)
|
||||
m.solve(20)
|
||||
v = m.h.getSolution().col_value
|
||||
temps = [v[x.index] for x in m.devices["heating"][1]["temp"]]
|
||||
assert max(temps[20:40]) <= 19.05
|
||||
|
||||
|
||||
def test_cap_on_actions_and_overrides(tmp_path, mapping, consent): # noqa: F811
|
||||
clk = Clock(START + 600)
|
||||
g = mk_guard(mapping, consent, clock=clk)
|
||||
col = Collector()
|
||||
col.observers.append(lambda eid, st, now: g.observe("living", eid, st["a"].get("temperature"), now)
|
||||
if eid == "climate.living" else None)
|
||||
states(col, climate__living=("heat", {"temperature": 21}))
|
||||
b = Building(str(tmp_path), clk)
|
||||
b.take(b.parse(cmd("thermostat_cap", 21.0, "binding", frm=START, until=START + 7200)),
|
||||
[("living", 20.5, 24, "heating")])
|
||||
sent = []
|
||||
|
||||
async def publish(kind, data):
|
||||
sent.append(data)
|
||||
ex = Executor(mapping.controls, g, col, publish, clock=clk, building=b)
|
||||
ex.plan = {"made": clk.t, "devices": {"living": [{"t": START, "set": 23.0, "why": "keep warm"}]}}
|
||||
ha = FakeHA()
|
||||
asyncio.run(ex.tick(ha, auto=True))
|
||||
assert not [c for c in ha.calls if c[2] == "climate.living"] # 23 capped to 21, which it is already
|
||||
# the owner turns it up by hand: a binding cap applies again
|
||||
clk.t += 300
|
||||
col.on_entities({"c": {"climate.living": {"+": {"a": {"temperature": 24}}}}}, clk.t)
|
||||
asyncio.run(ex.tick(ha, auto=True))
|
||||
assert ("climate", "set_temperature", "climate.living", {"temperature": 21.0}) in ha.calls
|
||||
assert any(m.get("entity") == "building:house-7" and m["result"] == "overridden" and "binding" in m["why"]
|
||||
for m in sent)
|
||||
# a flexible cap ends when the owner overrides
|
||||
b.take(b.parse(cmd("thermostat_cap", 21.0, "flexible", frm=START, until=START + 7200, cid="b2")),
|
||||
[("living", 20.5, 24, "heating")])
|
||||
clk.t += 300
|
||||
col.on_entities({"c": {"climate.living": {"+": {"a": {"temperature": 23.5}}}}}, clk.t)
|
||||
asyncio.run(ex.tick(ha, auto=True))
|
||||
assert "thermostat_cap" not in b.active
|
||||
assert any("flexible cap ended" in m["why"] for m in sent)
|
||||
@@ -0,0 +1,56 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from cantabile_edge.announce import Announcer
|
||||
from cantabile_edge.consent import Consent
|
||||
from cantabile_edge.mqtt import _packet
|
||||
|
||||
from test_agent import FlakySink, make_agent
|
||||
|
||||
|
||||
def test_off_by_default(tmp_path):
|
||||
assert Consent(str(tmp_path)).share is False
|
||||
|
||||
|
||||
def test_no_consent_collects_nothing(tmp_path):
|
||||
a = make_agent(tmp_path, FlakySink())
|
||||
a.set_consent(False, by="test")
|
||||
a.agg.begin(0)
|
||||
a.sample("sensor.pv", "100", 10)
|
||||
a.close_window(60)
|
||||
assert a.queue.depth() == 0
|
||||
|
||||
|
||||
def test_withdrawn_consent_deletes_the_queue(tmp_path):
|
||||
a = make_agent(tmp_path, FlakySink())
|
||||
a.agg.begin(0)
|
||||
a.sample("sensor.pv", "100", 10)
|
||||
a.close_window(60)
|
||||
assert a.queue.depth() == 1
|
||||
a.set_consent(False, by="test")
|
||||
assert a.queue.depth() == 0
|
||||
|
||||
|
||||
def test_another_writer_is_seen(tmp_path):
|
||||
# the box's panel writes the same file
|
||||
c = Consent(str(tmp_path))
|
||||
assert c.share is False
|
||||
(tmp_path / "consent.json").write_text(json.dumps({"share": True, "at": 1, "by": "panel"}))
|
||||
assert c.share is True
|
||||
|
||||
|
||||
def test_ha_sees_only_the_cloud_sensor(tmp_path):
|
||||
a = make_agent(tmp_path, FlakySink())
|
||||
ann = Announcer(a, "127.0.0.1", 1883)
|
||||
assert list(ann._configs()) == [("binary_sensor", "cloud")]
|
||||
assert not hasattr(ann, "_on_message") # nothing in HA changes the agent
|
||||
conf = ann._configs()[("binary_sensor", "cloud")]
|
||||
assert conf["device"]["identifiers"] == [f"cantabile_{a.cfg.site_id}"]
|
||||
assert "command_topic" not in conf
|
||||
|
||||
|
||||
def test_mqtt_length_encoding():
|
||||
assert _packet(3, 0, b"x" * 127)[1:2] == b"\x7f"
|
||||
assert _packet(3, 0, b"x" * 128)[1:3] == b"\x80\x01"
|
||||
assert _packet(3, 0, b"x" * 16384)[1:4] == b"\x80\x80\x01"
|
||||
@@ -0,0 +1,362 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""v1's parts without Home Assistant: limits, mapping v3, bundles, guard,
|
||||
executor, commands."""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from cantabile_edge import limits
|
||||
from cantabile_edge.bundles import Bundles
|
||||
from cantabile_edge.consent import Consent
|
||||
from cantabile_edge.executor import Executor, actions_for
|
||||
from cantabile_edge.guard import Action, Guard
|
||||
from cantabile_edge.inputs import Collector
|
||||
from cantabile_edge.mapping import Mapping
|
||||
|
||||
SITE = "ab" * 16
|
||||
MAPPING = {
|
||||
"version": 3,
|
||||
"assets": [{"entity": "sensor.load", "asset": "load.power", "kind": "gauge", "unit": "W", "consent": True}],
|
||||
"inputs": {"presence": "binary_sensor.home", "outside_temp": "sensor.outside", "weather": "weather.home",
|
||||
"load_power": "sensor.load"},
|
||||
"controls": [
|
||||
{"id": "battery", "kind": "battery", "consent": True,
|
||||
"entities": {"charge_from_grid": "switch.grid_charge", "setpoint": "number.batt_power",
|
||||
"soc": "sensor.batt_soc"},
|
||||
"params": {"capacity_wh": 10000, "max_charge_w": 3000, "max_discharge_w": 3000},
|
||||
"limits": {"soc_pct": {"owner": [20, 100]}, "power_w": {"owner": [-2000, 2500]}}},
|
||||
{"id": "living", "kind": "heating", "consent": True,
|
||||
"entities": {"climate": "climate.living", "temp": "sensor.living_temp"},
|
||||
"limits": {"temp_c": {"owner": [19, 24], "inhabitant": [20.5, None]}}},
|
||||
{"id": "boiler", "kind": "heating", "consent": False, "entities": {"switch": "switch.boiler"}},
|
||||
{"id": "car", "kind": "ev", "consent": True,
|
||||
"entities": {"switch": "switch.ev", "current": "number.ev_current", "connected": "binary_sensor.ev"}},
|
||||
{"id": "blind", "kind": "cover", "consent": True, "entities": {"cover": "cover.living"},
|
||||
"params": {"room": "living"}},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mapping(tmp_path):
|
||||
p = tmp_path / "mapping.yaml"
|
||||
p.write_text(yaml.safe_dump(MAPPING))
|
||||
return Mapping.load(str(p))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def consent(tmp_path):
|
||||
(tmp_path / "consent.json").write_text(json.dumps({"share": True, "control": True}))
|
||||
return Consent(str(tmp_path))
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self, t=1_800_000_000.0):
|
||||
self.t = t
|
||||
|
||||
def __call__(self):
|
||||
return self.t
|
||||
|
||||
|
||||
# -- limits ---------------------------------------------------------------
|
||||
def test_limits_layers():
|
||||
# tenant raises the floor within the owner's limits
|
||||
b = limits.effective((5, 30), {"owner": (19, 24), "inhabitant": (21, None)})
|
||||
assert (b.lo, b.hi, b.lo_by, b.hi_by) == (21, 24, "inhabitant", "owner")
|
||||
# a building limit never pushes below the owner's floor
|
||||
b = limits.effective((5, 30), {"owner": (19, 24), "building": (None, 18)})
|
||||
assert (b.lo, b.hi) == (19, 19) and b.hi_by == "owner"
|
||||
# the tenant's raised floor gives way to the building
|
||||
b = limits.effective((5, 30), {"inhabitant": (22, None), "building": (None, 20)})
|
||||
assert (b.lo, b.hi) == (20, 20)
|
||||
# the grid operator over everyone
|
||||
b = limits.effective((0, 100), {"owner": (30, None), "grid": (None, 10)})
|
||||
assert (b.lo, b.hi, b.hi_by) == (10, 10, "grid")
|
||||
# the device's range over every level
|
||||
b = limits.effective((5, 30), {"owner": (35, None)})
|
||||
assert (b.lo, b.hi, b.lo_by) == (30, 30, "device")
|
||||
with pytest.raises(ValueError):
|
||||
limits.parse({"temp_c": {"landlord": [1, 2]}})
|
||||
with pytest.raises(ValueError):
|
||||
limits.parse({"temp_c": {"owner": [25, 20]}})
|
||||
|
||||
|
||||
# -- mapping v3 -------------------------------------------------------------
|
||||
def test_mapping_v3(mapping):
|
||||
assert [c.id for c in mapping.controls] == ["battery", "living", "boiler", "car", "blind"]
|
||||
bat = mapping.controls[0]
|
||||
assert bat.writable() == {"charge_from_grid": "switch.grid_charge", "setpoint": "number.batt_power"}
|
||||
assert bat.bounds("power_w").lo == -2000 and bat.bounds("power_w").hi == 2500
|
||||
assert mapping.inputs.presence == ["binary_sensor.home"]
|
||||
assert not mapping.controls[2].consent # off by default unless given
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad, why", [
|
||||
({"id": "x", "kind": "toaster", "entities": {}}, "kind must be"),
|
||||
({"id": "x", "kind": "battery", "entities": {"soc": "sensor.s"}}, "needs charge_from_grid or setpoint"),
|
||||
({"id": "x", "kind": "cover", "entities": {"cover": "switch.c"}}, "must be a cover entity"),
|
||||
({"id": "load.power", "kind": "cover", "entities": {"cover": "cover.c"}}, "unique among"),
|
||||
({"id": "x", "kind": "cover", "entities": {"cover": "cover.c"}, "params": {"room": "nope"}}, "no heating"),
|
||||
({"id": "x", "kind": "ev", "entities": {"switch": "switch.e"}, "params": {"turbo": 1}}, "unknown params"),
|
||||
])
|
||||
def test_mapping_v3_refuses(tmp_path, bad, why):
|
||||
m = dict(MAPPING, controls=[bad])
|
||||
p = tmp_path / "m.yaml"
|
||||
p.write_text(yaml.safe_dump(m))
|
||||
with pytest.raises(ValueError, match=why):
|
||||
Mapping.load(str(p))
|
||||
|
||||
|
||||
# -- bundles ------------------------------------------------------------------
|
||||
def test_tariff_and_fallbacks(tmp_path):
|
||||
b = Bundles(str(tmp_path), SITE, default_price_ct=33)
|
||||
start = 1_800_000_000 // 900 * 900
|
||||
p = b.prices(start, 900, 4, start)
|
||||
assert p.import_ct == [33] * 4 and "default" in p.note
|
||||
t = {"v": 1, "kind": "tariff", "id": "t1", "site": SITE, "issued": start, "start": start, "step_s": 900,
|
||||
"steps": 2, "expires": start + 7200, "currency": "EUR", "unit": "ct/kWh",
|
||||
"import": [10, None], "export": [5, 5]}
|
||||
(tmp_path / "tariff.json").write_text(json.dumps(t))
|
||||
p = b.prices(start, 900, 4, start)
|
||||
assert p.import_ct == [10, 10, 10, 10] and p.export_ct == [5, 5, 0, 0] and "3 of 4" in p.note
|
||||
p = b.prices(start, 900, 2, start + 7200) # expired: the flat price, said
|
||||
assert p.import_ct == [10, 10] and "expired" in p.note
|
||||
os.remove(tmp_path / "tariff.json")
|
||||
assert "last known flat" in b.prices(start, 900, 1, start).note
|
||||
t["site"] = "cd" * 16 # another site's file: not taken
|
||||
(tmp_path / "tariff.json").write_text(json.dumps(t))
|
||||
assert b.prices(start, 900, 1, start).note.startswith("no tariff")
|
||||
|
||||
|
||||
def test_model_bundle(tmp_path):
|
||||
b = Bundles(str(tmp_path), SITE)
|
||||
m = {"v": 1, "kind": "model", "id": "m1", "site": "*", "issued": 1,
|
||||
"forecasts": {"load_w": {"profile": "hour_of_week", "values": list(range(168))}}}
|
||||
(tmp_path / "model.json").write_text(json.dumps(m))
|
||||
s = b.forecast("load_w", 1_800_000_000 // 3600 * 3600, 900, 8, "UTC") # a Friday
|
||||
assert len(s) == 8 and s[0] == s[3] and s[4] == s[0] + 1
|
||||
assert b.forecast("pv_w", 0, 900, 8, "UTC") is None
|
||||
m["forecasts"]["load_w"]["values"] = [1, 2] # malformed: refused, not used
|
||||
(tmp_path / "model.json").write_text(json.dumps(m))
|
||||
assert b.forecast("load_w", 0, 900, 8, "UTC") is None
|
||||
|
||||
|
||||
# -- the guard ----------------------------------------------------------------
|
||||
def mk_guard(mapping, consent, mode="auto", clock=None):
|
||||
return Guard(mapping.controls, consent, lambda: mode, clock=clock or Clock())
|
||||
|
||||
|
||||
def act(control="living", channel="climate", entity="climate.living", service="set_temperature", value=21.0,
|
||||
quantity="temp_c", level="plan"):
|
||||
return Action(control, channel, entity, entity.split(".")[0], service, {"temperature": value}, value, quantity,
|
||||
level)
|
||||
|
||||
|
||||
def test_guard_checks(mapping, consent):
|
||||
g = mk_guard(mapping, consent)
|
||||
assert g.check(act()) == (True, "")
|
||||
assert not g.check(act(value=25.0))[0] # above the owner's 24
|
||||
ok, why = g.check(act(value=20.0)) # below the tenant's raised floor 20.5
|
||||
assert not ok and "floor by inhabitant" in why
|
||||
assert "not this control's" in g.check(act(entity="climate.bedroom"))[1]
|
||||
assert "not allowed" in g.check(act(service="turn_off"))[1]
|
||||
assert "no consent" in g.check(act("boiler", "switch", "switch.boiler", "turn_on", "on", ""))[1]
|
||||
assert "does not act" in mk_guard(mapping, consent, "advisory").check(act())[1]
|
||||
|
||||
|
||||
def test_guard_needs_site_control_consent(mapping, tmp_path):
|
||||
(tmp_path / "consent.json").write_text(json.dumps({"share": True})) # data yes, control no
|
||||
g = mk_guard(mapping, Consent(str(tmp_path)))
|
||||
assert "has not allowed control" in g.check(act())[1]
|
||||
|
||||
|
||||
def test_guard_rate_cycling_override(mapping, consent):
|
||||
clk = Clock()
|
||||
mapping.controls[3].params["min_switch_s"] = 600 # this EV's mapping asks for anti-cycling
|
||||
g = mk_guard(mapping, consent, clock=clk)
|
||||
on = act("car", "switch", "switch.ev", "turn_on", "on", "")
|
||||
off = act("car", "switch", "switch.ev", "turn_off", "off", "")
|
||||
g.done(on)
|
||||
clk.t += 60
|
||||
ok, why = g.check(off)
|
||||
assert not ok and "minimum 600 s" in why # anti-cycling
|
||||
assert g.check(Action(**{**off.__dict__, "level": "emergency"}))[0] # an emergency may
|
||||
clk.t += 600
|
||||
assert g.check(off)[0]
|
||||
for _ in range(12): # per control: 12 an hour
|
||||
g.done(act(value=21.0))
|
||||
ok, why = g.check(act(value=21.5))
|
||||
assert not ok and "at most 12" in why # rate limit (12 an hour)
|
||||
clk.t += 3600
|
||||
assert g.check(act(value=21.5))[0]
|
||||
# the owner turns it by hand (after the settle time): hands off for flexible
|
||||
g.done(act(value=21.0))
|
||||
clk.t += 120
|
||||
g.observe("living", "climate.living", 23.0)
|
||||
ok, why = g.check(act(value=21.5))
|
||||
assert not ok and "by hand" in why and g.events
|
||||
assert g.check(act(value=21.5, level="binding"))[0] # a binding command still applies
|
||||
clk.t += 7200
|
||||
assert g.check(act(value=21.5))[0]
|
||||
|
||||
|
||||
def test_guard_ignores_the_agents_own_change(mapping, consent):
|
||||
clk = Clock()
|
||||
g = mk_guard(mapping, consent, clock=clk)
|
||||
g.done(act(value=21.0))
|
||||
clk.t += 10
|
||||
g.observe("living", "climate.living", 19.0) # still settling: not the owner
|
||||
clk.t += 200
|
||||
g.observe("living", "climate.living", 21.0) # what the agent set
|
||||
assert not g.overridden("living") and not g.events
|
||||
|
||||
|
||||
# -- the executor -------------------------------------------------------------
|
||||
class FakeHA:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
async def call_service(self, domain, service, entity, data, allowed):
|
||||
assert allowed(domain, service, entity)
|
||||
assert not allowed(domain, service, "switch.other")
|
||||
self.calls.append((domain, service, entity, data))
|
||||
|
||||
|
||||
def states(col, **kv):
|
||||
col.on_entities({"a": {k.replace("__", "."): {"s": v[0], "a": v[1] if len(v) > 1 else {}} for k, v in kv.items()}})
|
||||
|
||||
|
||||
def test_actions_only_where_the_device_differs(mapping):
|
||||
col = Collector()
|
||||
states(col, switch__grid_charge=("off",), number__batt_power=("0",), climate__living=("heat", {"temperature": 21}),
|
||||
switch__ev=("off",), number__ev_current=("6",), cover__living=("open", {"current_position": 100}))
|
||||
bat, living, _, car, blind = mapping.controls
|
||||
a = actions_for(bat, {"set": 2000.0, "grid": True}, col)
|
||||
assert [(x.service, x.value) for x in a] == [("set_value", 2000.0)] # a setpoint: no grid switch
|
||||
assert actions_for(living, {"set": 21.0}, col) == [] # already 21
|
||||
assert [x.service for x in actions_for(living, {"set": 22.5}, col)] == ["set_temperature"]
|
||||
assert [x.service for x in actions_for(car, {"set": 10}, col)] == ["set_value", "turn_on"]
|
||||
assert [x.value for x in actions_for(blind, {"set": 40.0}, col)] == [40.0]
|
||||
assert actions_for(blind, "release", col) == []
|
||||
|
||||
|
||||
def test_executor_plan_command_stale(mapping, consent):
|
||||
clk = Clock()
|
||||
g = mk_guard(mapping, consent, clock=clk)
|
||||
col = Collector()
|
||||
states(col, switch__grid_charge=("off",), number__batt_power=("0",), climate__living=("heat", {"temperature": 21}),
|
||||
switch__ev=("off",), number__ev_current=("6",), binary_sensor__ev=("on",),
|
||||
cover__living=("open", {"current_position": 100}))
|
||||
sent = []
|
||||
|
||||
async def publish(kind, data):
|
||||
sent.append((kind, data))
|
||||
ex = Executor(mapping.controls, g, col, publish, clock=clk)
|
||||
ex.plan = {"made": clk.t, "devices": {"living": [{"t": clk.t - 60, "set": 22.0, "why": "keep warm"}],
|
||||
"battery": [{"t": clk.t - 60, "set": 1500.0, "grid": True, "why": "cheap"}]}}
|
||||
ha = FakeHA()
|
||||
asyncio.run(ex.tick(ha, auto=True))
|
||||
assert ("climate", "set_temperature", "climate.living", {"temperature": 22.0}) in ha.calls
|
||||
# a battery with a setpoint: the power goes to the setpoint, the grid switch
|
||||
# stays off (it means "full power" on many inverters)
|
||||
assert ("number", "set_value", "number.batt_power", {"value": 1500.0}) in ha.calls
|
||||
assert not any(c[2] == "switch.grid_charge" for c in ha.calls)
|
||||
assert all(m["result"] == "done" for k, m in sent if k == "action")
|
||||
# a console command wins over the plan
|
||||
ok, _ = ex.command({"asset": "living", "set": "23", "level": "binding", "minutes": "30"}, clk.t)
|
||||
assert ok
|
||||
ha.calls.clear()
|
||||
asyncio.run(ex.tick(ha, auto=True))
|
||||
assert ("climate", "set_temperature", "climate.living", {"temperature": 23.0}) in ha.calls
|
||||
# out of bounds: refused and reported, not called
|
||||
ex.commands.clear()
|
||||
ex.command({"asset": "living", "set": "26", "level": "flexible"}, clk.t)
|
||||
ha.calls.clear()
|
||||
sent.clear()
|
||||
asyncio.run(ex.tick(ha, auto=True))
|
||||
assert not [c for c in ha.calls if c[2] == "climate.living"]
|
||||
assert any(m["result"] == "refused" and "outside" in m["why"] for k, m in sent)
|
||||
# a stale plan: the battery's safe default (no grid charging, power 0)
|
||||
ex.commands.clear()
|
||||
clk.t += 3600
|
||||
states(col, switch__grid_charge=("on",), number__batt_power=("1500",))
|
||||
ha.calls.clear()
|
||||
asyncio.run(ex.tick(ha, auto=True))
|
||||
assert ("switch", "turn_off", "switch.grid_charge", {}) in ha.calls
|
||||
assert ("number", "set_value", "number.batt_power", {"value": 0.0}) in ha.calls
|
||||
# nothing in advisory
|
||||
ha.calls.clear()
|
||||
asyncio.run(ex.tick(ha, auto=False))
|
||||
assert ha.calls == []
|
||||
|
||||
|
||||
def test_flexible_command_ends_when_the_owner_overrides(mapping, consent):
|
||||
clk = Clock()
|
||||
g = mk_guard(mapping, consent, clock=clk)
|
||||
col = Collector()
|
||||
col.observers.append(lambda eid, st, now: g.observe("living", eid, st["a"].get("temperature"), now)
|
||||
if eid == "climate.living" else None)
|
||||
states(col, climate__living=("heat", {"temperature": 21}))
|
||||
sent = []
|
||||
|
||||
async def publish(kind, data):
|
||||
sent.append(data)
|
||||
ex = Executor(mapping.controls, g, col, publish, clock=clk)
|
||||
ex.command({"asset": "living", "set": "22", "level": "flexible", "minutes": "120"}, clk.t)
|
||||
ha = FakeHA()
|
||||
asyncio.run(ex.tick(ha, auto=True))
|
||||
clk.t += 300
|
||||
col.on_entities({"c": {"climate.living": {"+": {"a": {"temperature": 19}}}}}, clk.t)
|
||||
asyncio.run(ex.tick(ha, auto=True))
|
||||
assert "living" not in ex.commands
|
||||
assert any(m["result"] == "overridden" and "flexible command" in m["why"] for m in sent)
|
||||
|
||||
|
||||
# -- end-to-end findings ----------------------------------
|
||||
def test_battery_without_setpoint_uses_the_grid_switch(mapping):
|
||||
"""A battery with the switch alone (an HM8042) is driven by it."""
|
||||
bat = mapping.controls[0]
|
||||
bat.entities = {"charge_from_grid": "switch.grid_charge", "soc": "sensor.batt_soc"}
|
||||
col = Collector()
|
||||
states(col, switch__grid_charge=("off",))
|
||||
acts = actions_for(bat, {"set": 1500.0, "grid": True}, col)
|
||||
assert [(a.entity, a.service) for a in acts] == [("switch.grid_charge", "turn_on")]
|
||||
|
||||
|
||||
def test_battery_with_setpoint_turns_a_stray_grid_switch_off(mapping):
|
||||
bat = mapping.controls[0]
|
||||
col = Collector()
|
||||
states(col, switch__grid_charge=("on",), number__batt_power=("0",))
|
||||
acts = [(a.entity, a.service) for a in actions_for(bat, {"set": 3000.0, "grid": True}, col)]
|
||||
assert ("switch.grid_charge", "turn_off") in acts
|
||||
assert ("number.batt_power", "set_value") in acts
|
||||
|
||||
|
||||
def test_anti_cycling_only_for_equipment(mapping, consent):
|
||||
clk = Clock()
|
||||
g = mk_guard(mapping, consent, clock=clk)
|
||||
on = act("car", "switch", "switch.ev", "turn_on", "on", "")
|
||||
off = act("car", "switch", "switch.ev", "turn_off", "off", "")
|
||||
g.done(on)
|
||||
clk.t += 5
|
||||
assert g.check(off)[0] # an EV charger may switch at once
|
||||
heat = act("living", "climate", "climate.living", "set_hvac_mode", "heat", "")
|
||||
stop = act("living", "climate", "climate.living", "set_hvac_mode", "off", "")
|
||||
g.done(heat)
|
||||
clk.t += 60
|
||||
ok, why = g.check(stop)
|
||||
assert not ok and "minimum 600 s" in why # a heat pump is held
|
||||
assert g.min_switch_for(mapping.controls[0]) == 0 # battery
|
||||
assert g.min_switch_for(mapping.controls[4]) == 0 # cover
|
||||
|
||||
|
||||
def test_bundle_stamps_change_with_a_new_file(tmp_path):
|
||||
b = Bundles(str(tmp_path), SITE)
|
||||
before = b.stamps()
|
||||
(tmp_path / "tariff.json").write_text("{}")
|
||||
assert b.stamps() != before
|
||||
|
||||
@@ -0,0 +1,505 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The dashboard (dashboards.py) for homes of every kind, from their HA
|
||||
registries and the device profiles' views (devview.py, hub/profiles): a flat
|
||||
with only a meter, a villa with PV, battery, heat pump and car charger, two
|
||||
inverters with two batteries (parts and totals), a relay board, a
|
||||
building's box with flats, a test home's shape. Each must give
|
||||
sensible sections: the right card per device, every entity it names in HA,
|
||||
nothing shown twice, HA's own cards only. With CANTABILE_FARM=<dir> (simulated
|
||||
flats: <flat>/ha/.storage/core.*, <flat>/agent/mapping.yaml)
|
||||
every flat there too."""
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from cantabile_edge import devview, propose
|
||||
from cantabile_edge.dashboards import Home, URL, dashboard, energy_prefs, shown_devices
|
||||
from cantabile_edge.mapping import Asset, Mapping
|
||||
|
||||
PROFILES = propose.load_profiles(str(pathlib.Path(__file__).resolve().parents[2] / "profiles"))
|
||||
P = {p["id"]: p for p in PROFILES}
|
||||
UID = "cantabile_site1"
|
||||
OURS = {f"{UID}_{k}": f"sensor.c_{k}" for k in ("cloud", "price_import_now", "price_export_now", "next_action")}
|
||||
LINKS = {"bridge": "/app/local_cantabile_modbus", "edge": "/app/local_cantabile_edge"}
|
||||
# HA's built-in cards (nothing to install)
|
||||
CORE = {"heading", "tile", "gauge", "distribution", "thermostat", "entities", "statistic", "statistics-graph",
|
||||
"history-graph", "markdown", "logbook", "vertical-stack", "grid"}
|
||||
|
||||
|
||||
class Reg:
|
||||
"""HA's registries and states, built device by device."""
|
||||
|
||||
def __init__(self):
|
||||
self.devices, self.entities, self.states = [], [], []
|
||||
self.areas = [{"area_id": "cantabile", "name": "Cantabile"}, {"area_id": "living_room", "name": "Living Room"},
|
||||
{"area_id": "flats", "name": "Flats"}]
|
||||
|
||||
def dev(self, id_, name, manufacturer="", model="", area=None, ident=None):
|
||||
self.devices.append({"id": id_, "name": name, "manufacturer": manufacturer, "model": model, "area_id": area,
|
||||
"identifiers": [ident or ["x", id_]]})
|
||||
return id_
|
||||
|
||||
def ent(self, dev, eid, uid, platform, dc=None, unit=None, state="1", name=None, tk=None, cat=None):
|
||||
self.entities.append({"entity_id": eid, "unique_id": uid, "device_id": dev, "platform": platform,
|
||||
"translation_key": tk, "entity_category": cat, "original_name": name})
|
||||
self.states.append({"entity_id": eid, "state": state, "attributes": {
|
||||
"device_class": dc, "unit_of_measurement": unit, "friendly_name": name or eid,
|
||||
"state_class": "total_increasing" if unit in ("Wh", "kWh") else "measurement"}})
|
||||
|
||||
def bridge(self, dev_id, name, profile, keys, area="cantabile"):
|
||||
"""A device of Cantabile's Modbus bridge: its register keys' entities."""
|
||||
p = P[profile]
|
||||
d = self.dev(f"b_{dev_id}", name, p["manufacturer"], p["name"], area, ["mqtt", f"cantabile_modbus_{dev_id}"])
|
||||
for key, (dom, dc, unit, state) in keys.items():
|
||||
self.ent(d, f"{dom}.{dev_id}_{key}", f"cantabile_modbus_{dev_id}_{key}", "mqtt", dc, unit, state,
|
||||
f"{name} {key.replace('_', ' ')}")
|
||||
return d
|
||||
|
||||
def agent(self):
|
||||
self.dev("agent", "Cantabile", "Cantabile", "Edge Agent", "cantabile", ["mqtt", UID])
|
||||
self.dev("addon", "Cantabile Modbus bridge", "Local apps", "Home Assistant App", "cantabile",
|
||||
["hassio", "local_cantabile_modbus"])
|
||||
|
||||
def reg(self):
|
||||
return {"devices": self.devices, "entities": self.entities, "areas": self.areas}
|
||||
|
||||
|
||||
def home(r: Reg, mapping=None, flats=(), lang="en") -> Home:
|
||||
if mapping is None: # proposed from the registries, as the add-on does
|
||||
mapping = Mapping(2, [Asset(**{k: v for k, v in a.items()})
|
||||
for a in propose.propose(r.states, r.reg(), PROFILES)])
|
||||
return Home(mapping, UID, OURS, list(flats), lang, reg=r.reg(), states=r.states, links=LINKS, profiles=PROFILES)
|
||||
|
||||
|
||||
def flat(cards) -> list[dict]:
|
||||
"""Cards with the stacks and grids opened (a device's card)."""
|
||||
out = []
|
||||
for c in cards:
|
||||
out.append(c)
|
||||
if c["type"] in ("vertical-stack", "grid"):
|
||||
out += flat(c["cards"])
|
||||
return out
|
||||
|
||||
|
||||
def sane(h: Home) -> dict:
|
||||
"""The dashboard, checked for what holds in every home; {path: view}."""
|
||||
cfg = dashboard(h)
|
||||
assert cfg is not None
|
||||
known = {e["entity_id"] for e in h.entities} | set(OURS.values())
|
||||
paths = [v["path"] for v in cfg["views"]]
|
||||
assert len(paths) == len(set(paths))
|
||||
for v in cfg["views"]:
|
||||
for s in v["sections"]:
|
||||
if v["path"] == "overview":
|
||||
# full-width bands (a device: half, two a row), no ragged columns; widths a phone
|
||||
# shows whole or half
|
||||
assert v["max_columns"] == 2 and v["dense_section_placement"] and s["column_span"] in (1, 2), s
|
||||
assert s["column_span"] == 2 or s["cards"][0]["heading_style"] == "title", s
|
||||
assert all(c.get("grid_options", {}).get("columns", 12) in (6, 12, 18, 24, "full")
|
||||
for c in s["cards"] if c["type"] != "heading"), s
|
||||
assert not any("_value" in c for c in s["cards"])
|
||||
else:
|
||||
assert s["cards"][0]["type"] == "heading" and len(s["cards"]) > 1, s
|
||||
for c in flat(s["cards"]):
|
||||
assert c["type"] in CORE, c["type"]
|
||||
for e in [c.get("entity")] + [x if isinstance(x, str) else x.get("entity")
|
||||
for x in c.get("entities") or [] if x]:
|
||||
assert e is None or e in known, (v["path"], c["type"], e)
|
||||
link = (c.get("tap_action") or {}).get("navigation_path", "")
|
||||
if link.startswith(f"/{URL}/"):
|
||||
assert link.split("/")[2] in paths, link # a device's sub-view exists
|
||||
ov = next(v for v in cfg["views"] if v["path"] == "overview")
|
||||
every = [e for s in ov["sections"] for c in flat(s["cards"]) for e in ents([c])]
|
||||
for s in ov["sections"]:
|
||||
for c in flat(s["cards"]):
|
||||
if c["type"] == "distribution": # circuits: once, in their device
|
||||
assert all(every.count(x["entity"]) == 1 for x in c["entities"]), c
|
||||
json.dumps(cfg)
|
||||
return {v["path"]: v for v in cfg["views"]}
|
||||
|
||||
|
||||
def _device_secs(view) -> list[dict]:
|
||||
"""The overview's devices: the sections with a heading linking a page."""
|
||||
return [s for s in view["sections"] if s["cards"][0].get("heading_style") == "title"
|
||||
and s["cards"][0].get("tap_action", {}).get("action") == "navigate"]
|
||||
|
||||
|
||||
def bands(view) -> dict[str, list]:
|
||||
"""The overview's bands by what they are: status, now, devices (the
|
||||
devices' sections), today, plan, building."""
|
||||
out = {}
|
||||
devs = _device_secs(view)
|
||||
for s in view["sections"]:
|
||||
if s in devs:
|
||||
continue
|
||||
head = s["cards"][0].get("heading") if s["cards"][0]["type"] == "heading" else None
|
||||
key = ("devices" if head and head.split(":")[0] in ("Devices", "Geräte") else None) \
|
||||
or {"Today": "today", "Heute": "today"}.get(head) \
|
||||
or ("plan" if head and head.startswith("Plan") else "building" if head else
|
||||
"status" if any(c.get("entity") == "sensor.c_cloud" for c in s["cards"]) else "now")
|
||||
out[key] = s["cards"][1:] if head else s["cards"]
|
||||
if devs:
|
||||
assert out.pop("devices") == [] # its heading alone, then the devices
|
||||
out["devices"] = devs
|
||||
return out
|
||||
|
||||
|
||||
def devices(view) -> dict[str, list]:
|
||||
"""Each device: {its name: its cards under its heading}."""
|
||||
return {s["cards"][0]["heading"]: s["cards"][1:] for s in _device_secs(view)}
|
||||
|
||||
|
||||
def links(view) -> dict[str, str]:
|
||||
return {s["cards"][0]["heading"]: s["cards"][0]["tap_action"]["navigation_path"] for s in _device_secs(view)}
|
||||
|
||||
|
||||
def sections(view) -> dict[str, list]:
|
||||
return {s["cards"][0]["heading"]: s["cards"][1:] for s in view["sections"]}
|
||||
|
||||
|
||||
def types(cards) -> list[str]:
|
||||
return [c["type"] for c in cards]
|
||||
|
||||
|
||||
def ents(cards) -> set[str]:
|
||||
out = set()
|
||||
for c in cards:
|
||||
out |= {c.get("entity")} | {x["entity"] if isinstance(x, dict) else x for x in c.get("entities") or []}
|
||||
return out - {None}
|
||||
|
||||
|
||||
# -- the homes -------------------------------------------------------------------------------
|
||||
|
||||
def test_flat_with_only_a_meter():
|
||||
"""A Shelly Pro 3EM through HA's shelly integration: the meter's card
|
||||
(grid power with its trend, the three phases as one bar, energy today),
|
||||
its own sub-view (no bridge page)."""
|
||||
r = Reg()
|
||||
d = r.dev("sh", "Shelly Pro 3EM", "Shelly", "Shelly Pro 3EM", "living_room")
|
||||
r.ent(d, "sensor.meter_power", "aabb-em:0-total_act_power", "shelly", "power", "W", "830", "Shelly Pro 3EM Power")
|
||||
for ph, w in zip("abc", ("300", "500", "30")):
|
||||
r.ent(d, f"sensor.meter_phase_{ph}_power", f"aabb-em:0-{ph}_act_power", "shelly", "power", "W", w,
|
||||
f"Shelly Pro 3EM Phase {ph.upper()} power")
|
||||
r.ent(d, f"sensor.meter_phase_{ph}_current", f"aabb-em:0-{ph}_current", "shelly", "current", "A", "1.2")
|
||||
r.ent(d, "sensor.meter_energy", "aabb-emdata:0-total_act", "shelly", "energy", "kWh", "1234")
|
||||
r.ent(d, "sensor.meter_returned", "aabb-emdata:0-total_act_ret", "shelly", "energy", "kWh", "56")
|
||||
r.ent(d, "sensor.meter_rssi", "aabb-wifi-rssi", "shelly", "signal_strength", "dBm", "-60", cat="diagnostic")
|
||||
h = home(r)
|
||||
assert {a.asset for a in h.m.assets} == {"grid.power", "grid.import_energy", "grid.export_energy"}
|
||||
v = sane(h)
|
||||
b = bands(v["overview"])
|
||||
assert b["now"][0]["entity"] == "sensor.meter_power" and b["now"][0]["features"][0]["type"] == "trend-graph"
|
||||
assert b["now"][0]["grid_options"] == {"columns": 24} # alone: the whole row
|
||||
sec = devices(v["overview"])["Shelly Pro 3EM"]
|
||||
assert types(sec) == ["tile", "markdown", "distribution"] # energy today: in Today
|
||||
assert sec[0]["entity"] == "sensor.meter_power"
|
||||
assert [e["entity"] for e in sec[2]["entities"]] == [f"sensor.meter_phase_{p}_power" for p in "abc"]
|
||||
assert [c["entity"] for c in b["today"]] == ["sensor.meter_energy", "sensor.meter_returned"]
|
||||
sub = links(v["overview"])["Shelly Pro 3EM"].split("/")[2]
|
||||
assert v[sub]["subview"] and "sensor.meter_phase_a_current" in str(v[sub]) # all its values there
|
||||
assert "sensor.meter_rssi" not in str(v[sub]) # not diagnostics
|
||||
assert h.view(r.devices[0]).profile == "shelly-pro-3em"
|
||||
assert "Grid" in str(b["now"])
|
||||
assert energy_prefs(h)["energy_sources"][0]["flow_from"][0]["stat_energy_from"] == "sensor.meter_energy"
|
||||
|
||||
|
||||
def villa() -> Reg:
|
||||
"""Huawei SUN2000 with LUNA2000 and DTSU666 (Huawei Solar: three HA
|
||||
devices), a Viessmann heat pump (ViCare), a go-eCharger, a SNZB-02."""
|
||||
r = Reg()
|
||||
r.agent()
|
||||
inv = r.dev("inv", "Inverter", "Huawei", "SUN2000-10KTL-M1")
|
||||
r.ent(inv, "sensor.inverter_input_power", "HV123_input_power", "huawei_solar", "power", "W", "4200", "Inverter Input power")
|
||||
r.ent(inv, "sensor.inverter_daily_yield", "HV123_daily_yield_energy", "huawei_solar", "energy", "kWh", "12")
|
||||
r.ent(inv, "sensor.inverter_total_yield", "HV123_accumulated_yield_energy", "huawei_solar", "energy", "kWh", "9000")
|
||||
bat = r.dev("bat", "Battery", "Huawei", "LUNA2000")
|
||||
r.ent(bat, "sensor.battery_soc", "HV123_storage_state_of_capacity", "huawei_solar", "battery", "%", "64", "Battery State of capacity")
|
||||
r.ent(bat, "sensor.battery_power", "HV123_storage_charge_discharge_power", "huawei_solar", "power", "W", "-900", "Battery Charge/Discharge power")
|
||||
r.ent(bat, "sensor.battery_charged", "HV123_storage_total_charge", "huawei_solar", "energy", "kWh", "800")
|
||||
r.ent(bat, "sensor.battery_discharged", "HV123_storage_total_discharge", "huawei_solar", "energy", "kWh", "700")
|
||||
met = r.dev("met", "Power meter", "Huawei", "DTSU666-H")
|
||||
r.ent(met, "sensor.power_meter_active_power", "HV123_power_meter_active_power", "huawei_solar", "power", "W", "-1500", "Power meter Active power")
|
||||
r.ent(met, "sensor.grid_exported", "HV123_grid_exported_energy", "huawei_solar", "energy", "kWh", "5000")
|
||||
r.ent(met, "sensor.grid_imported", "HV123_grid_accumulated_energy", "huawei_solar", "energy", "kWh", "3000")
|
||||
hp = r.dev("hp", "Vitocal 250-A", "Viessmann", "E3_Vitocal")
|
||||
r.entities.append({"entity_id": "climate.vicare_heating", "unique_id": "vc-heating-0", "device_id": hp,
|
||||
"platform": "vicare", "translation_key": "heating"})
|
||||
r.states.append({"entity_id": "climate.vicare_heating", "state": "heat", "attributes": {"friendly_name": "Heating"}})
|
||||
r.ent(hp, "sensor.vicare_supply", "vc-supply", "vicare", "temperature", "°C", "35", "Supply temperature", tk="supply_temperature")
|
||||
r.ent(hp, "sensor.vicare_return", "vc-return", "vicare", "temperature", "°C", "29", "Return temperature", tk="return_temperature")
|
||||
r.ent(hp, "sensor.vicare_outside", "vc-outside", "vicare", "temperature", "°C", "4", "Outside temperature", tk="outside_temperature")
|
||||
r.ent(hp, "sensor.vicare_dhw", "vc-dhw", "vicare", "temperature", "°C", "48", "Hot water storage temperature", tk="hotwater_storage_temperature")
|
||||
r.ent(hp, "sensor.vicare_spf", "vc-spf", "vicare", None, None, "3.9", "Seasonal performance factor", tk="spf_total")
|
||||
ev = r.dev("ev", "go-eCharger 123456", "go-e", "Gemini")
|
||||
r.ent(ev, "sensor.goe_123456_car", "goe_123456_car", "goecharger_api2", "enum", None, "charging", "Car state")
|
||||
r.ent(ev, "sensor.goe_123456_nrg_11", "goe_123456_nrg_11", "goecharger_api2", "power", "W", "7200", "Power total")
|
||||
r.ent(ev, "sensor.goe_123456_wh", "goe_123456_wh", "goecharger_api2", "energy", "Wh", "5400", "Charged since connected")
|
||||
r.ent(ev, "sensor.goe_123456_eto", "goe_123456_eto", "goecharger_api2", "energy", "Wh", "1200000", "Total energy")
|
||||
r.ent(ev, "switch.goe_123456_alw", "goe_123456_alw", "goecharger_api2", None, None, "on", "Allow charging")
|
||||
r.ent(ev, "number.goe_123456_amp", "goe_123456_amp", "goecharger_api2", "current", "A", "16", "Requested current")
|
||||
th = r.dev("th", "Temperature/Humidity Sensor", "SONOFF", "SNZB-02", "living_room")
|
||||
r.ent(th, "sensor.living_temperature", "00:11-1-1026", "zha", "temperature", "°C", "21.5", "Temperature")
|
||||
r.ent(th, "sensor.living_humidity", "00:11-1-1029", "zha", "humidity", "%", "45", "Humidity")
|
||||
return r
|
||||
|
||||
|
||||
def test_villa_pv_battery_heat_pump_charger():
|
||||
r = villa()
|
||||
h = home(r)
|
||||
q = {a.asset: a.entity for a in h.m.assets}
|
||||
assert q["pv.power"] == "sensor.inverter_input_power" and q["battery.soc"] == "sensor.battery_soc"
|
||||
assert q["grid.power"] == "sensor.power_meter_active_power" and q["ev.power"] == "sensor.goe_123456_nrg_11"
|
||||
assert q["room.living_room.temp"] == "sensor.living_temperature"
|
||||
assert {"heatpump.flow_temp", "outside.temp"} <= set(q)
|
||||
v = sane(h)
|
||||
b = bands(v["overview"])
|
||||
# energy now: solar, grid, the battery's charge as a bar (no lone gauge); no hole in the row
|
||||
assert [(c["entity"], c["grid_options"]["columns"]) for c in b["now"]] == [
|
||||
("sensor.inverter_input_power", 6), ("sensor.power_meter_active_power", 6), ("sensor.battery_soc", 12)]
|
||||
assert b["now"][2]["features"] == [{"type": "bar-gauge", "min": 0, "max": 100}]
|
||||
assert "gauge" not in types(flat(c for x in b.values() for c in x))
|
||||
s = devices(v["overview"])
|
||||
# each device by its kind, 2-4 values
|
||||
assert [c["entity"] for c in s["Battery"]] == ["sensor.battery_power", "sensor.battery_soc"]
|
||||
assert ents(s["Inverter"]) == {"sensor.inverter_input_power"}
|
||||
assert ents(s["Power meter"]) == {"sensor.power_meter_active_power"}
|
||||
hp = s["Vitocal 250-A"]
|
||||
assert hp[0]["type"] == "markdown" and "state_translated" in hp[0]["content"] # what it does, in words
|
||||
assert hp[1]["type"] == "tile" and hp[1]["entity"] == "climate.vicare_heating"
|
||||
assert hp[1]["features"] == [{"type": "target-temperature"}] # the thermostat: a tile with its setpoint
|
||||
assert [c["entity"] for c in hp[2:6]] == ["sensor.vicare_supply", "sensor.vicare_return", "sensor.vicare_outside",
|
||||
"sensor.vicare_dhw"]
|
||||
assert "sensor.vicare_spf" in str(v[links(v["overview"])["Vitocal 250-A"].split("/")[2]]) # COP: its page
|
||||
ev = s["go-eCharger 123456"]
|
||||
assert [c["entity"] for c in ev] == ["sensor.goe_123456_car", "sensor.goe_123456_nrg_11",
|
||||
"sensor.goe_123456_wh", "switch.goe_123456_alw"]
|
||||
assert ev[3]["icon_tap_action"] == {"action": "more-info"} # a tap never switches
|
||||
assert any(c["type"] == "statistic" and c["entity"] == "sensor.goe_123456_eto" for c in b["today"])
|
||||
assert [c["grid_options"]["columns"] for c in b["today"]] == [6, 6, 6, 6, 12, 12] # four a row, then halves
|
||||
# two a row, alike side by side (six: no whole row)
|
||||
assert [x["column_span"] for x in b["devices"]].count(2) == 0
|
||||
# a room's sensor: a compact card (temperature and humidity), and on the climate view
|
||||
assert [c["entity"] for c in s["Temperature/Humidity Sensor"]] == ["sensor.living_temperature", "sensor.living_humidity"]
|
||||
assert "sensor.living_temperature" in str(v["climate"])
|
||||
assert {"overview", "energy", "climate"} <= set(v)
|
||||
# not the add-on, not the agent
|
||||
assert "Cantabile Modbus bridge" not in s and "Cantabile" not in s
|
||||
prefs = energy_prefs(h)
|
||||
assert [x["type"] for x in prefs["energy_sources"]] == ["grid", "solar", "battery"]
|
||||
assert prefs["device_consumption"] == [{"stat_consumption": "sensor.goe_123456_eto"}]
|
||||
|
||||
|
||||
def hm(r, dev_id, name, pv="500", soc="80"):
|
||||
return r.bridge(dev_id, name, "hm8042-hybrid", {
|
||||
"pv_power": ("sensor", "power", "W", pv), "pv_energy": ("sensor", "energy", "kWh", "100"),
|
||||
"battery_soc": ("sensor", "battery", "%", soc), "battery_power": ("sensor", "power", "W", "-40"),
|
||||
"load_power": ("sensor", "power", "W", "600"), "grid_import_power": ("sensor", "power", "W", "0"),
|
||||
"load_energy": ("sensor", "energy", "kWh", "300"), "grid_energy": ("sensor", "energy", "kWh", "30"),
|
||||
"battery_voltage": ("sensor", "voltage", "V", "53"), "bypass": ("sensor", None, None, "0"),
|
||||
"charge_from_grid": ("select", None, None, "Solar priority")})
|
||||
|
||||
|
||||
def test_two_inverters_two_batteries_parts_and_totals(tmp_path):
|
||||
r = Reg()
|
||||
r.agent()
|
||||
hm(r, "hm_a", "Inverter A", "500", "80")
|
||||
hm(r, "hm_b", "Inverter B", "700", "60")
|
||||
assets = propose.propose(r.states, r.reg(), PROFILES)
|
||||
ids = {a["asset"]: a["entity"] for a in assets}
|
||||
assert ids["pv.1.power"] == "sensor.hm_a_pv_power" and ids["pv.2.power"] == "sensor.hm_b_pv_power"
|
||||
assert ids["battery.1.soc"] == "sensor.hm_a_battery_soc" and ids["battery.2.soc"] == "sensor.hm_b_battery_soc"
|
||||
assert "pv.power" not in ids # the agent derives it
|
||||
p = tmp_path / "mapping.yaml"
|
||||
p.write_text(yaml.safe_dump({"version": 2, "assets": assets}))
|
||||
m = Mapping.load(str(p))
|
||||
assert m.totals["pv.power"].parts == ["pv.1.power", "pv.2.power"] and not m.totals["pv.power"].mean
|
||||
assert m.totals["battery.soc"].mean # % : the mean
|
||||
assert m.inputs.pv_power == ["sensor.hm_a_pv_power", "sensor.hm_b_pv_power"] # the optimiser's: the sum
|
||||
h = home(r, m)
|
||||
v = sane(h)
|
||||
s = devices(v["overview"])
|
||||
for name in ("Inverter A", "Inverter B"): # what energy now does not show first
|
||||
assert [c["entity"].split("_", 2)[2] for c in s[name]] == ["battery_power", "battery_soc"]
|
||||
now = bands(v["overview"])["now"]
|
||||
assert [c["name"] for c in now] == ["Solar 1", "Solar 2", "Home 1", "Home 2", "Grid 1", "Grid 2",
|
||||
"Battery 1", "Battery 2"]
|
||||
assert all(c["grid_options"]["columns"] == 6 for c in now) # four a row
|
||||
assert [c["features"][0]["type"] for c in now] == ["trend-graph"] * 6 + ["bar-gauge"] * 2
|
||||
assert len([c for c in energy_prefs(h)["energy_sources"] if c["type"] == "solar"]) == 2
|
||||
# the bridge's devices open its page, not a sub-view
|
||||
assert links(v["overview"]) == {"Inverter A": "/app/local_cantabile_modbus#hm_a",
|
||||
"Inverter B": "/app/local_cantabile_modbus#hm_b"}
|
||||
assert not any(x.get("subview") for x in v.values())
|
||||
|
||||
|
||||
def test_relay_board_and_circuits_of_the_bridge():
|
||||
r = Reg()
|
||||
r.agent()
|
||||
r.bridge("relays", "Relays", "waveshare-relay-30ch",
|
||||
{f"relay_{n}": ("switch", None, None, "on" if n < 3 else "off") for n in range(1, 31)})
|
||||
r.bridge("spm_1", "SPM 1", "sonoff-spm", {
|
||||
**{f"power_{n}": ("sensor", "power", "W", str(10 * n)) for n in range(1, 5)},
|
||||
**{f"circuit_{n}": ("switch", None, None, "on") for n in range(1, 5)},
|
||||
**{f"energy_{n}": ("sensor", "energy", "kWh", "1") for n in range(1, 5)}})
|
||||
h = home(r)
|
||||
v = sane(h)
|
||||
s = devices(v["overview"])
|
||||
assert types(s["Relays"]) == ["markdown"] and "is_state" in s["Relays"][0]["content"]
|
||||
assert s["Relays"][0]["content"].count("switch.relays_relay_") == 30
|
||||
spm = s["SPM 1"]
|
||||
assert types(spm) == ["markdown", "distribution"] # the total, one bar
|
||||
assert [e["name"] for e in spm[1]["entities"]] == [f"Circuit {n}" for n in range(1, 5)] # the switches' names
|
||||
|
||||
|
||||
def test_building_box_with_flats():
|
||||
"""The building's own box: garage chargers without a profile (HA's
|
||||
device classes: a plug sensor makes a charger), the flats' view."""
|
||||
r = Reg()
|
||||
r.agent()
|
||||
for n in (1, 2):
|
||||
d = r.dev(f"ev{n}", f"Garage charger {n}", "Cantabile simulator", f"ev{n}")
|
||||
r.ent(d, f"binary_sensor.garage_charger_{n}_plugged_in", f"b_ev{n}_plugged", "mqtt", "plug", None, "on")
|
||||
r.ent(d, f"sensor.garage_charger_{n}_power", f"b_ev{n}_power", "mqtt", "power", "W", "3000")
|
||||
r.ent(d, f"switch.garage_charger_{n}_charging", f"b_ev{n}_switch", "mqtt", None, None, "on")
|
||||
g = r.dev("grid", "Grid meter", "Cantabile simulator", "grid")
|
||||
r.ent(g, "sensor.grid_meter_power", "b_grid_power", "mqtt", "power", "W", "9000")
|
||||
flats = [{"id": "f1", "label": "Flat 1"}, {"id": "f2", "label": "Flat 2"}]
|
||||
ours = dict(OURS, **{f"{UID}_flat_f{n}_grid": f"sensor.c_flat_f{n}_grid" for n in (1, 2)})
|
||||
m = Mapping(3, [Asset("sensor.grid_meter_power", "grid.power", "gauge", "W"),
|
||||
Asset("sensor.garage_charger_1_power", "ev.1.power", "gauge", "W"),
|
||||
Asset("sensor.garage_charger_2_power", "ev.2.power", "gauge", "W")])
|
||||
assert m.totals["ev.power"].parts == ["ev.1.power", "ev.2.power"]
|
||||
h = Home(m, UID, ours, flats, "de", reg=r.reg(), states=r.states, links=LINKS, profiles=PROFILES)
|
||||
cfg = dashboard(h)
|
||||
v = {x["path"]: x for x in cfg["views"]}
|
||||
assert "flats" in v and v["flats"]["title"] == "Wohnungen"
|
||||
s = devices(v["overview"])
|
||||
for n in (1, 2):
|
||||
c = s[f"Garage charger {n}"]
|
||||
assert c[0]["entity"] == f"binary_sensor.garage_charger_{n}_plugged_in"
|
||||
assert c[1]["entity"] == f"sensor.garage_charger_{n}_power"
|
||||
assert h.view(r.devices[2]).card == "charger"
|
||||
assert "Grid meter" in s
|
||||
|
||||
|
||||
def clone() -> Reg:
|
||||
"""A test home's shape: the bridge's HM8042, relays
|
||||
and SPM 1 (mirroring SonoffLAN's SPM 1, which is mapped), SonoffLAN's
|
||||
SPM-Main and curtain relays (domain sonoff too), a SNZB-02D on ZHA, the
|
||||
agent and the add-ons in "Cantabile"."""
|
||||
r = Reg()
|
||||
r.agent()
|
||||
r.dev("edge", "Cantabile Edge Agent", "Local apps", "Home Assistant App", "cantabile", ["hassio", "local_cantabile_edge"])
|
||||
hm(r, "hm8042", "HM8042")
|
||||
r.bridge("relays", "Relays", "waveshare-relay-30ch", {f"relay_{n}": ("switch", None, None, "off") for n in range(1, 31)})
|
||||
r.bridge("spm_1", "SPM 1", "sonoff-spm", {
|
||||
**{f"power_{n}": ("sensor", "power", "W", "5") for n in range(1, 5)},
|
||||
**{f"circuit_{n}": ("switch", None, None, "on") for n in range(1, 5)}})
|
||||
main = r.dev("spm_main", "SPM-Main", "SONOFF", "SPM-Main", "power_board", ["sonoff", "1000000003"])
|
||||
r.ent(main, "sensor.sonoff_1000000003_rssi", "1000000003_rssi", "sonoff", "signal_strength", "dBm", "-50", cat="diagnostic")
|
||||
spm = r.dev("spm_src", "SPM 1", "coolkit", "GD32-SM4(130)", "power_board", ["sonoff", "ab00000002"])
|
||||
for n, name in enumerate(("Bathroom and Shower", "Library and Guest", "Kitchen", "Master"), 1):
|
||||
r.ent(spm, f"switch.sonoff_ab00000002_{n}", f"ab00000002_{n}", "sonoff", None, None, "on", f"SPM-1 {name}")
|
||||
r.ent(spm, f"select.sonoff_ab00000002_{n}", f"ab00000002_{n}", "sonoff", None, None, "on", f"{name} config", cat="config")
|
||||
r.ent(spm, f"sensor.spm_1_{n}", f"ab00000002_power_{n}", "sonoff", "power", "W", "5", f"SPM-1 {name}")
|
||||
cur = r.dev("curtain", "Bedroom Curtain", "SONOFF", "DUALR3", "bedroom", ["sonoff", "1000000004"])
|
||||
for n in (1, 2):
|
||||
r.ent(cur, f"sensor.sonoff_1000000004_power_{n}", f"1000000004_power_{n}", "sonoff", "power", "W", "0")
|
||||
r.ent(cur, "cover.sonoff_1000000004", "1000000004", "sonoff", None, None, "open", "Bedroom Curtain")
|
||||
r.states[-1]["attributes"].update(current_position=100, supported_features=15, unit_of_measurement=None)
|
||||
zb = r.dev("snzb", "Temperature/Humidity Sensor", "SONOFF", "SNZB-02D", "living_room", ["zha", "08:dd"])
|
||||
r.ent(zb, "sensor.living_room_temperature", "08:dd-1-1026", "zha", "temperature", "°C", "22", "Temperature")
|
||||
return r
|
||||
|
||||
|
||||
def test_the_test_home():
|
||||
r = clone()
|
||||
h = home(r)
|
||||
v = sane(h)
|
||||
s = devices(v["overview"])
|
||||
heads = list(s)
|
||||
# the bridge's three, once each (SonoffLAN's SPM 1 is the bridge's mirror)
|
||||
assert heads.count("SPM 1") == 1 and "HM8042" in heads and "Relays" in heads
|
||||
assert "SPM-Main" not in heads # not an SPM-4Relay: no profile, not mapped
|
||||
assert [c["entity"] for c in s["Temperature/Humidity Sensor"]] == ["sensor.living_room_temperature"]
|
||||
# the curtain (DUALR3 in motor mode): HA's tile with its position slider (ha-cover)
|
||||
assert [(c["entity"], c["features"]) for c in s["Bedroom Curtain"]] == \
|
||||
[("cover.sonoff_1000000004", [{"type": "cover-position"}])]
|
||||
b = bands(v["overview"])
|
||||
assert [c["entity"] for c in b["now"]] == ["sensor.hm8042_pv_power", "sensor.hm8042_load_power",
|
||||
"sensor.hm8042_grid_import_power", "sensor.hm8042_battery_soc"]
|
||||
hm_cards = s["HM8042"] # not again what energy now shows
|
||||
assert [c["entity"] for c in hm_cards] == ["sensor.hm8042_battery_power", "sensor.hm8042_battery_soc"]
|
||||
assert "voltage" not in str(hm_cards)
|
||||
assert [c["entity"] for c in b["today"]] == ["sensor.hm8042_pv_energy", "sensor.hm8042_load_energy",
|
||||
"sensor.hm8042_grid_energy"]
|
||||
assert links(v["overview"])["SPM 1"] == "/app/local_cantabile_modbus#spm_1"
|
||||
# circuits once: in their meter, not again under energy now
|
||||
assert not [k for k, cards in b.items() if k != "devices" and "spm_1_power" in str(cards)]
|
||||
assert [c["type"] for x in b["devices"] for c in x["cards"] if "spm_1_power_1" in str(c)] \
|
||||
== ["markdown", "distribution"] # its total and its bar
|
||||
# SonoffLAN's SPM 1 by the profile's HA matchers: channels named after the switches
|
||||
dv = h.view(next(d for d in r.devices if d["id"] == "spm_src"))
|
||||
assert dv.profile == "sonoff-spm" and [c["n"] for c in dv.channels] == ["1", "2", "3", "4"]
|
||||
assert dv.channels[0] == {"n": "1", "power": "sensor.spm_1_1", "switch": "switch.sonoff_ab00000002_1"}
|
||||
curtain = h.view(next(d for d in r.devices if d["id"] == "curtain"))
|
||||
assert curtain.profile == "ha-cover" # the SPM's profile is not every Sonoff: the generic shade
|
||||
# what the agent maps: SonoffLAN's circuits (the mirror's source), the HM8042 through the bridge
|
||||
q = {a.asset for a in h.m.assets}
|
||||
assert {"pv.power", "battery.soc", "load.power"} <= q
|
||||
assert not any(a.entity.startswith("sensor.sonoff_1000000004") for a in h.m.assets)
|
||||
|
||||
|
||||
def test_views_for_every_profile_resolve():
|
||||
"""Each profile's view names something on a device made from its own
|
||||
register map (the bridge) or setup matchers: no profile whose view
|
||||
shows nothing."""
|
||||
for p in PROFILES:
|
||||
assert p.get("view", {}).get("card") in devview.CARDS, p["id"]
|
||||
|
||||
|
||||
# -- simulated flats (CANTABILE_FARM: a directory of them, read-only) ---------------------
|
||||
|
||||
FARM = os.environ.get("CANTABILE_FARM")
|
||||
|
||||
|
||||
@pytest.mark.skipif(not FARM, reason="CANTABILE_FARM not set (a directory of simulated flats)")
|
||||
@pytest.mark.parametrize("flat", sorted(os.listdir(FARM)) if FARM and os.path.isdir(FARM) else [])
|
||||
def test_sim_farm_flat(flat):
|
||||
base = pathlib.Path(FARM) / flat
|
||||
store = base / "ha" / ".storage"
|
||||
if not (store / "core.device_registry").exists():
|
||||
pytest.skip("no HA registries")
|
||||
reg = {"devices": json.loads((store / "core.device_registry").read_text())["data"]["devices"],
|
||||
"entities": json.loads((store / "core.entity_registry").read_text())["data"]["entities"],
|
||||
"areas": json.loads((store / "core.area_registry").read_text())["data"]["areas"]
|
||||
if (store / "core.area_registry").exists() else []}
|
||||
states = []
|
||||
if (store / "core.restore_state").exists():
|
||||
for x in json.loads((store / "core.restore_state").read_text())["data"]:
|
||||
states.append(x["state"])
|
||||
known = {s["entity_id"] for s in states}
|
||||
states += [{"entity_id": e["entity_id"], "state": "1", "attributes": {
|
||||
"device_class": e.get("device_class") or e.get("original_device_class"),
|
||||
"unit_of_measurement": e.get("unit_of_measurement"), "friendly_name": e.get("original_name")}}
|
||||
for e in reg["entities"] if e["entity_id"] not in known]
|
||||
m = Mapping.load(str(base / "agent" / "mapping.yaml"))
|
||||
uid = next((i[1] for d in reg["devices"] for i in d["identifiers"] if i[0] == "mqtt"
|
||||
and str(i[1]).startswith("cantabile_") and "_flat_" not in str(i[1])), UID)
|
||||
ours = {e["unique_id"]: e["entity_id"] for e in reg["entities"] if str(e.get("unique_id", "")).startswith(uid)}
|
||||
h = Home(m, uid, ours, [], "en", reg=reg, states=states, links={}, profiles=PROFILES)
|
||||
cfg = dashboard(h)
|
||||
assert cfg and cfg["views"][0]["path"] == "overview"
|
||||
known = {e["entity_id"] for e in reg["entities"]}
|
||||
for v in cfg["views"]:
|
||||
for s in v["sections"]:
|
||||
assert len(s["cards"]) > 1
|
||||
for c in s["cards"]:
|
||||
assert c["type"] in CORE
|
||||
assert c.get("entity") is None or c["entity"] in known
|
||||
devs = [d["name"] for d in shown_devices(h)]
|
||||
assert not [d for d in devs if d.startswith("Cantabile")]
|
||||
print(flat, devs)
|
||||
@@ -0,0 +1,280 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Cantabile's dashboard in HA (dashboards.py) against a fake HA: one
|
||||
"cantabile-main" with views for what the home has, the earlier dashboards
|
||||
removed, the owner's Energy preferences never overwritten."""
|
||||
import asyncio
|
||||
import dataclasses
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from cantabile_edge import agent as agent_mod
|
||||
from cantabile_edge.config import Config
|
||||
from cantabile_edge.dashboards import dashboard, energy_prefs
|
||||
from cantabile_edge.ha import HAClient, HAError
|
||||
from cantabile_edge.mapping import Mapping
|
||||
from cantabile_edge.store import Queue
|
||||
|
||||
from test_agent import FlakySink
|
||||
from test_control_parts import MAPPING, SITE
|
||||
|
||||
UID = f"cantabile_{SITE}"
|
||||
ASSETS = [
|
||||
{"entity": "sensor.grid_in", "asset": "grid.import_energy", "kind": "counter", "unit": "Wh", "consent": True},
|
||||
{"entity": "sensor.grid_out", "asset": "grid.export_energy", "kind": "counter", "unit": "Wh", "consent": True},
|
||||
{"entity": "sensor.grid_w", "asset": "grid.import_power", "kind": "gauge", "unit": "W", "consent": True},
|
||||
{"entity": "sensor.load", "asset": "load.power", "kind": "gauge", "unit": "W", "consent": True},
|
||||
]
|
||||
|
||||
|
||||
class FakeHA(HAClient):
|
||||
"""HAClient with HA's answers in memory (its own checks stay)."""
|
||||
|
||||
def __init__(self, prefs=None, boards_=None, devices=(), entities=(), areas=(), states=None, panels=("app",)):
|
||||
super().__init__("ws://fake", "t")
|
||||
self.prefs, self.boards, self.sent, self.configs = prefs, boards_ or [], [], {}
|
||||
self.devices, self.entities, self.areas, self.states = list(devices), list(entities), list(areas), states
|
||||
self.panels = {p: {} for p in panels}
|
||||
|
||||
async def _send(self, type_, timeout=60, _events=None, **f):
|
||||
self.sent.append((type_, f))
|
||||
if type_ == "config/entity_registry/list":
|
||||
return [{"platform": "mqtt", "unique_id": f"{UID}_{s}", "entity_id": f"sensor.c_{s}"}
|
||||
for s in ("cloud", "price_import_now", "price_export_now", "commands", "received", "set_battery",
|
||||
"set_living", "model", "next_action")] + self.entities
|
||||
if type_ == "config/device_registry/list":
|
||||
return self.devices
|
||||
if type_ == "config/area_registry/list":
|
||||
return self.areas
|
||||
if type_ == "get_states":
|
||||
return self.states
|
||||
if type_ == "get_panels":
|
||||
return self.panels
|
||||
if type_ == "energy/get_prefs":
|
||||
if self.prefs is None:
|
||||
raise HAError("not_found")
|
||||
return self.prefs
|
||||
if type_ == "energy/save_prefs":
|
||||
self.prefs = f
|
||||
return f
|
||||
if type_ == "lovelace/dashboards/list":
|
||||
return self.boards
|
||||
if type_ == "lovelace/dashboards/create":
|
||||
d = {"id": f["url_path"].replace("-", "_"), **f}
|
||||
self.boards.append(d)
|
||||
return d
|
||||
if type_ == "lovelace/dashboards/delete":
|
||||
self.boards = [b for b in self.boards if b["id"] != f["dashboard_id"]]
|
||||
return None
|
||||
if type_ == "lovelace/config/save":
|
||||
self.configs[f["url_path"]] = f["config"]
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def make(tmp_path, assets=ASSETS, controls=True):
|
||||
m = dict(MAPPING, assets=assets) if controls else {"version": 3, "assets": assets}
|
||||
p = tmp_path / "m.yaml"
|
||||
p.write_text(yaml.safe_dump(m))
|
||||
cfg = Config(site_id=SITE, mapping=str(p), state_dir=str(tmp_path))
|
||||
return agent_mod.Agent(cfg, Mapping.load(str(p)), Queue(str(tmp_path / "q.db"), 100), FlakySink())
|
||||
|
||||
|
||||
def views(ha):
|
||||
return {v["path"]: v for v in ha.configs["cantabile-main"]["views"]}
|
||||
|
||||
|
||||
def cards(view):
|
||||
return [c for s in view["sections"] for c in s["cards"]]
|
||||
|
||||
|
||||
def test_one_dashboard_with_views_from_what_the_home_has(tmp_path):
|
||||
a = make(tmp_path)
|
||||
ha = FakeHA(boards_=[{"id": "e", "url_path": "cantabile-electricity", "title": "Electricity"}])
|
||||
asyncio.run(a.dashboards.ensure(ha))
|
||||
assert [b["url_path"] for b in ha.boards] == ["cantabile-main"] # the earlier ones removed
|
||||
v = views(ha)
|
||||
assert list(v) == ["overview", "energy", "climate"] # no devices, not a building, no add-on
|
||||
ov = cards(v["overview"])
|
||||
# commands: the list the agent keeps (not the event's logbook: unknown at each restart), only when any
|
||||
rec = next(c for c in ov if c.get("title") == "Commands received")
|
||||
assert rec["type"] == "markdown" and "state_attr('sensor.c_received', 'commands')" in rec["content"]
|
||||
assert rec["visibility"] == [{"condition": "numeric_state", "entity": "sensor.c_received", "above": 0}]
|
||||
assert not any(c["type"] == "logbook" for c in ov)
|
||||
# the plan by the controls' names (never their ids), "nothing planned" when empty
|
||||
plan = next(c for c in ov if c.get("title") == "Coming up")
|
||||
assert '"living": "Living"' in plan["content"] and "Nothing planned." in plan["content"]
|
||||
assert "names.get(s.control)" in plan["content"]
|
||||
assert not any(c.get("title") == "What Cantabile sets" for c in ov) # shadow: it sets nothing
|
||||
# prices in ct/kWh with one decimal (the sensor is EUR/kWh for HA's Energy), no tile with a trend
|
||||
line = next(c for c in ov if c["type"] == "markdown" and "Electricity now" in c["content"])
|
||||
assert "ct/kWh" in line["content"] and "'%.1f' | format(n * 100)" in line["content"]
|
||||
assert "cheapest" in line["content"] and line["grid_options"] == {"columns": 24}
|
||||
assert not any(c.get("entity") == "sensor.c_price_import_now" for c in ov)
|
||||
assert any(c["type"] == "tile" and c["entity"] == "sensor.c_cloud" for c in ov)
|
||||
assert any(c["type"] == "tile" and c["entity"] == "sensor.load" and c["features"][0]["type"] == "trend-graph"
|
||||
for c in ov)
|
||||
assert any(c["type"] == "statistic" and c["entity"] == "sensor.grid_in" for c in ov)
|
||||
assert any(c["type"] == "markdown" and "Watching" in c["content"] for c in ov) # shadow, no mode entity
|
||||
assert {"type": "thermostat", "entity": "climate.living", "grid_options": {"columns": 6}} in cards(v["climate"])
|
||||
for view in v.values(): # no heading alone
|
||||
assert all(len(s["cards"]) > 1 or s["cards"][0]["type"] != "heading" for s in view["sections"])
|
||||
assert {s["column_span"] for s in v["overview"]["sections"]} == {2} # bands: the whole width
|
||||
# HA's Energy: grid with our price sensors
|
||||
grid = ha.prefs["energy_sources"][0]
|
||||
assert grid["flow_from"][0] == {"stat_energy_from": "sensor.grid_in", "stat_cost": None,
|
||||
"number_energy_price": None, "entity_energy_price": "sensor.c_price_import_now"}
|
||||
assert grid["flow_to"][0]["entity_energy_price"] == "sensor.c_price_export_now"
|
||||
# nothing changed: nothing saved again
|
||||
n = len([s for s in ha.sent if s[0] == "lovelace/config/save"])
|
||||
asyncio.run(a.dashboards.ensure(ha))
|
||||
assert len([s for s in ha.sent if s[0] == "lovelace/config/save"]) == n
|
||||
|
||||
|
||||
def test_devices_view_and_links(tmp_path):
|
||||
a = make(tmp_path, controls=False)
|
||||
a.cfg.join_page_port = 8099
|
||||
dev = lambda i, name, ident, area="cantabile", model="": {"id": i, "name": name, "identifiers": [ident],
|
||||
"area_id": area, "model": model}
|
||||
ent = lambda eid, dev_id, uid: {"entity_id": eid, "device_id": dev_id, "unique_id": uid, "platform": "mqtt"}
|
||||
sta = lambda eid, dc, name, state="1": {"entity_id": eid, "state": state,
|
||||
"attributes": {"device_class": dc, "friendly_name": name}}
|
||||
ha = FakeHA(
|
||||
areas=[{"area_id": "cantabile", "name": "Cantabile"}],
|
||||
devices=[dev("d1", "HM8042", ["mqtt", "cantabile_modbus_hm8042"]),
|
||||
dev("d2", "SPM 1", ["mqtt", "cantabile_modbus_spm_1"]),
|
||||
dev("d3", "Relays", ["mqtt", "cantabile_modbus_relays"]),
|
||||
dev("d4", "Cantabile Modbus bridge", ["hassio", "local_cantabile_modbus"]),
|
||||
dev("d5", "Cantabile Edge Agent", ["hassio", "local_cantabile_edge"]),
|
||||
dev("d6", "Cantabile", ["mqtt", UID]),
|
||||
dev("d7", "Lamp", ["zha", "x"], area="kitchen")],
|
||||
entities=[ent("sensor.hm8042_pv_power", "d1", "cantabile_modbus_hm8042_pv_power"),
|
||||
ent("sensor.hm8042_battery_charge", "d1", "cantabile_modbus_hm8042_battery_soc"),
|
||||
ent("sensor.hm8042_grid_voltage", "d1", "cantabile_modbus_hm8042_grid_voltage")]
|
||||
+ [ent(f"sensor.spm_1_power_{n}", "d2", f"cantabile_modbus_spm_1_power_{n}") for n in (1, 2, 3)]
|
||||
+ [ent(f"switch.spm_1_c{n}", "d2", f"cantabile_modbus_spm_1_circuit_{n}") for n in (1, 2, 3)]
|
||||
+ [ent(f"switch.relays_relay_{n}", "d3", f"cantabile_modbus_relays_relay_{n}") for n in (1, 2)],
|
||||
states=[sta("sensor.hm8042_pv_power", "power", "HM8042 PV power"),
|
||||
sta("sensor.hm8042_battery_charge", "battery", "HM8042 Battery charge"),
|
||||
sta("sensor.hm8042_grid_voltage", "voltage", "HM8042 Grid voltage")]
|
||||
+ [sta(f"sensor.spm_1_power_{n}", "power", f"SPM 1 Power {n}") for n in (1, 2, 3)]
|
||||
+ [sta(f"switch.spm_1_c{n}", None, f"SPM 1 Circuit {'ABC'[n - 1]}", "on") for n in (1, 2, 3)]
|
||||
+ [sta(f"switch.relays_relay_{n}", None, f"Relay {n}", "off") for n in (1, 2)])
|
||||
asyncio.run(a.dashboards.ensure(ha))
|
||||
v = views(ha)
|
||||
assert list(v) == ["overview", "energy"] # one view for status and devices
|
||||
secs = v["overview"]["sections"]
|
||||
assert secs[0]["cards"][0]["entity"] == "sensor.c_cloud" # the status on top
|
||||
assert secs[1]["cards"] == [{"type": "heading", "heading": "Devices: use Home Assistant's devices with Cantabile",
|
||||
"heading_style": "subtitle", "icon": "mdi:devices", "tap_action": {
|
||||
"action": "navigate", "navigation_path": "/app/local_cantabile_edge#devices"}}]
|
||||
# (no power mapped: no energy now; an add-on site: the heading opens the add-on's Devices page)
|
||||
stacks = {s["cards"][0]["heading"]: s["cards"] for s in secs[2:5]} # a section each: name over values
|
||||
assert set(stacks) == {"HM8042", "Relays", "SPM 1"} # not the add-ons, agent, lamp
|
||||
assert {k: c[0]["tap_action"]["navigation_path"] for k, c in stacks.items()} == {
|
||||
"HM8042": "/app/local_cantabile_modbus#hm8042", "Relays": "/app/local_cantabile_modbus#relays",
|
||||
"SPM 1": "/app/local_cantabile_modbus#spm_1"}
|
||||
hm = stacks["HM8042"]
|
||||
assert [(c["entity"], c["name"], c["grid_options"]["columns"]) for c in hm[1:]] == [
|
||||
("sensor.hm8042_battery_charge", "Battery charge", 6), ("sensor.hm8042_pv_power", "PV power", 6)]
|
||||
assert "voltage" not in str(hm)
|
||||
assert "is_state" in stacks["Relays"][1]["content"] # relays: how many are on
|
||||
spm = stacks["SPM 1"]
|
||||
assert "sum" in spm[1]["content"] and spm[2]["type"] == "distribution"
|
||||
assert [e["name"] for e in spm[2]["entities"]] == ["Circuit A", "Circuit B", "Circuit C"]
|
||||
# three devices, two a row: the one that pairs the others best the whole row
|
||||
assert sorted(s["column_span"] for s in secs[2:5]) == [1, 1, 2]
|
||||
assert not [s for s in secs if s["cards"][0].get("heading") == "Building"] # not in a building: no section
|
||||
# in a building, behind HA without the "app" panel: the older ingress route
|
||||
(tmp_path / "joining.json").write_text('{"membership": {"state": "active", "unit": "3B", '
|
||||
'"building": {"id": "b", "name": "Haus A"}}}')
|
||||
ha2 = FakeHA(panels=(), devices=ha.devices, entities=ha.entities, areas=ha.areas, states=ha.states)
|
||||
a.dashboards.saved = {}
|
||||
asyncio.run(a.dashboards.ensure(ha2))
|
||||
last = views(ha2)["overview"]["sections"][-1]["cards"]
|
||||
assert last[0]["tap_action"]["navigation_path"] == "/hassio/ingress/local_cantabile_edge#building"
|
||||
# the add-on's Devices page, from the devices' heading
|
||||
assert {"type": "heading", "heading": "Devices: use Home Assistant's devices with Cantabile", "heading_style": "subtitle",
|
||||
"icon": "mdi:devices", "tap_action": {"action": "navigate", "navigation_path":
|
||||
"/hassio/ingress/local_cantabile_edge#devices"}} in \
|
||||
views(ha2)["overview"]["sections"][1]["cards"]
|
||||
assert "Haus A" in last[1]["content"]
|
||||
assert "/hassio/ingress/local_cantabile_modbus#hm8042" in str(views(ha2)["overview"]["sections"][2:5])
|
||||
|
||||
|
||||
def test_auto_what_cantabile_sets_in_words(tmp_path):
|
||||
a = make(tmp_path)
|
||||
a.control.mode.set("auto", "test")
|
||||
h = a.dashboards.home({f"{UID}_{k}": f"sensor.c_{k}" for k in ("cloud", "set_living", "next_action")},
|
||||
states=[{"entity_id": "climate.living", "state": "heat",
|
||||
"attributes": {"friendly_name": "Living-room heating"}}])
|
||||
ov = [c for s in dashboard(h)["views"][0]["sections"] for c in s["cards"]]
|
||||
sets = next(c for c in ov if c.get("title") == "What Cantabile sets")
|
||||
assert "**Living-room heating**" in sets["content"] # HA's name for it, not "living"
|
||||
assert "not controlling: your own settings apply" in sets["content"]
|
||||
assert "No current plan" in sets["content"] # the safe default, in words
|
||||
assert "set by Cantabile" not in str(ov) and "living:" not in str(ov)
|
||||
plan = next(c for c in ov if c.get("title") == "Coming up")
|
||||
assert '"living": "Living-room heating"' in plan["content"]
|
||||
# a thermostat that heats and cools (two controls, one climate): told apart
|
||||
a.mapping.controls.append(dataclasses.replace(next(c for c in a.mapping.controls if c.id == "living"),
|
||||
id="living_cool", kind="cooling"))
|
||||
plan = next(c for s in dashboard(h)["views"][0]["sections"] for c in s["cards"] if c.get("title") == "Coming up")
|
||||
assert '"living": "Living-room heating (heating)"' in plan["content"]
|
||||
assert '"living_cool": "Living-room heating (cooling)"' in plan["content"]
|
||||
|
||||
|
||||
def test_nothing_to_show_no_dashboard(tmp_path):
|
||||
a = make(tmp_path, assets=[], controls=False)
|
||||
assert dashboard(a.dashboards.home({})) is None
|
||||
ha = FakeHA(boards_=[{"id": "m", "url_path": "cantabile-main", "title": "Cantabile"}])
|
||||
ha._send_orig = ha._send
|
||||
|
||||
async def no_ours(type_, timeout=60, _events=None, **f):
|
||||
if type_ == "config/entity_registry/list":
|
||||
return []
|
||||
return await ha._send_orig(type_, timeout, _events, **f)
|
||||
ha._send = no_ours
|
||||
asyncio.run(a.dashboards.ensure(ha))
|
||||
assert ha.boards == [] # an empty dashboard is removed
|
||||
|
||||
|
||||
def test_language(tmp_path):
|
||||
a = make(tmp_path, controls=False)
|
||||
a.ha_language = "de"
|
||||
ha = FakeHA()
|
||||
asyncio.run(a.dashboards.ensure(ha))
|
||||
v = views(ha)
|
||||
assert v["energy"]["title"] == "Energie"
|
||||
assert "Beobachten" in str(v["overview"])
|
||||
assert "replace('.', ',')" in str(v["overview"]) and "Strom jetzt" in str(v["overview"]) # 16,7 ct/kWh
|
||||
|
||||
|
||||
def test_owner_energy_prefs_kept_and_other_boards_untouched(tmp_path):
|
||||
a = make(tmp_path)
|
||||
owner = {"energy_sources": [{"type": "solar", "stat_energy_from": "sensor.mine"}], "device_consumption": []}
|
||||
ha = FakeHA(prefs=dict(owner), boards_=[{"id": "x", "url_path": "my-home", "title": "Mine"},
|
||||
{"id": "old", "url_path": "cantabile-flats", "title": "Flats"},
|
||||
{"id": "inv", "url_path": "cantabile-inverter", "title": "Inverter"}])
|
||||
asyncio.run(a.dashboards.ensure(ha))
|
||||
assert ha.prefs == owner # never overwritten
|
||||
assert not [s for s in ha.sent if s[0] == "energy/save_prefs"]
|
||||
ids = {b["id"] for b in ha.boards}
|
||||
assert {"x", "inv"} <= ids and "old" not in ids # our retired one removed, others kept
|
||||
|
||||
|
||||
def test_client_refuses_other_dashboards():
|
||||
ha = FakeHA()
|
||||
with pytest.raises(HAError):
|
||||
asyncio.run(ha.dashboard("lovelace/config/save", url_path="lovelace", config={}))
|
||||
with pytest.raises(HAError):
|
||||
asyncio.run(ha.dashboard("lovelace/dashboards/delete", dashboard_id="x")) # not listed as ours
|
||||
with pytest.raises(HAError):
|
||||
asyncio.run(ha.dashboard("lovelace/resources/create", url="/x.js")) # no custom cards
|
||||
|
||||
|
||||
def test_energy_prefs_none_without_counters(tmp_path):
|
||||
a = make(tmp_path, assets=[ASSETS[2]], controls=False)
|
||||
h = a.dashboards.home({})
|
||||
assert energy_prefs(h) is None
|
||||
assert dashboard(h)["views"][0]["path"] == "overview"
|
||||
@@ -0,0 +1,301 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The HA add-on's Devices page (devpage.py): HA's devices with the profile
|
||||
that fits, what each would give, "Use with Cantabile" writing the mapping
|
||||
fragment (consent off, protection defaults), the proposal yielding to it,
|
||||
one writer per entity, consent not given through HA, protection, heating or
|
||||
cooling, removing, owner only. HA is a fake; the profiles are the real ones."""
|
||||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
import urllib.parse
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from cantabile_edge import i18n, propose
|
||||
from cantabile_edge.devpage import App, Devices
|
||||
from cantabile_edge.joinpage import Fleet
|
||||
from cantabile_edge.mapping import Mapping
|
||||
|
||||
PROFILES = propose.load_profiles(str(pathlib.Path(__file__).resolve().parents[2] / "profiles"))
|
||||
INV, AC, LAMP = "dev-inverter", "dev-ac", "dev-lamp"
|
||||
|
||||
|
||||
def ent(eid, dev, uid, platform):
|
||||
return {"entity_id": eid, "device_id": dev, "unique_id": uid, "platform": platform}
|
||||
|
||||
|
||||
def st(eid, state, **attrs):
|
||||
return {"entity_id": eid, "state": state, "attributes": attrs}
|
||||
|
||||
|
||||
class FakeHA:
|
||||
def __init__(self, admins=("u-admin",)):
|
||||
self.admins = set(admins)
|
||||
self.reg = {
|
||||
"areas": [{"area_id": "living", "name": "Living room"}],
|
||||
"devices": [
|
||||
{"id": INV, "name": "Inverter", "manufacturer": "Huawei", "model": "SUN2000-10KTL", "config_entries": ["e1"]},
|
||||
{"id": AC, "name": "Living room A/C", "manufacturer": "Espressif", "model": "esp32", "area_id": "living",
|
||||
"config_entries": ["e2"]},
|
||||
{"id": LAMP, "name": "Lamp", "manufacturer": "IKEA", "model": "TRADFRI", "config_entries": ["e3"]}],
|
||||
"entities": [ent("sensor.inverter_input_power", INV, "x_input_power", "huawei_solar"),
|
||||
ent("sensor.inverter_yield", INV, "x_accumulated_yield_energy", "huawei_solar"),
|
||||
ent("sensor.battery_soc", INV, "x_storage_state_of_capacity", "huawei_solar"),
|
||||
ent("climate.living_ac", AC, "ac1", "esphome"),
|
||||
ent("light.lamp", LAMP, "l1", "zha")]}
|
||||
self.states = [st("sensor.inverter_input_power", "3200", device_class="power", unit_of_measurement="W",
|
||||
friendly_name="Inverter input power"),
|
||||
st("sensor.inverter_yield", "12000", device_class="energy", unit_of_measurement="kWh",
|
||||
state_class="total_increasing", friendly_name="Inverter yield"),
|
||||
st("sensor.battery_soc", "55", device_class="battery", unit_of_measurement="%",
|
||||
friendly_name="Battery state of capacity"),
|
||||
st("climate.living_ac", "heat", hvac_modes=["off", "heat", "cool"], hvac_action="idle",
|
||||
current_temperature=21.5, temperature=22, min_temp=16, max_temp=30, target_temp_step=0.5),
|
||||
st("light.lamp", "on")]
|
||||
|
||||
async def registries(self):
|
||||
return json.loads(json.dumps(self.reg))
|
||||
|
||||
async def send(self, type_, **kw):
|
||||
assert type_ == "get_states"
|
||||
return json.loads(json.dumps(self.states))
|
||||
|
||||
async def is_admin(self, user_id):
|
||||
return user_id in self.admins
|
||||
|
||||
|
||||
class Site:
|
||||
"""An add-on's /data: the mapping, its fragments, the state directory."""
|
||||
|
||||
def __init__(self, tmp, mapping=None):
|
||||
self.tmp, self.ha, self.changes, self.restarts = tmp, FakeHA(), 0, 0
|
||||
self.mapping = tmp / "mapping.yaml"
|
||||
self.state = tmp / "state"
|
||||
self.state.mkdir()
|
||||
if mapping is None:
|
||||
self.mapping.write_text("version: 1\nassets: []\n")
|
||||
self.propose() # what the add-on proposes at install
|
||||
else:
|
||||
self.mapping.write_text(yaml.safe_dump(mapping))
|
||||
self.dev = Devices(str(self.mapping), str(self.state), PROFILES, ha=lambda: self.ha, changed=self.changed)
|
||||
self.app = App(Fleet(str(self.state), site_id="ab" * 16), self.dev, location=lambda: None)
|
||||
|
||||
def propose(self):
|
||||
return propose.ensure(str(self.mapping), str(self.state), self.ha.states, self.ha.reg, PROFILES)
|
||||
|
||||
async def changed(self, restart=False):
|
||||
self.changes += 1
|
||||
self.restarts += restart # the agent starts again (agent.restart)
|
||||
self.propose() # as agent.devices_changed
|
||||
|
||||
def give_consent(self, share=True, control=False):
|
||||
"""The site's consent, as addon-run writes it from the configuration."""
|
||||
(self.state / "consent.json").write_text(json.dumps({"share": share, "control": control, "by": "ha-addon-config"}))
|
||||
|
||||
def frag(self, dev_id):
|
||||
return json.loads((self.tmp / "mapping.d" / f"{dev_id}.yaml").read_text())
|
||||
|
||||
def devices(self):
|
||||
return json.loads((self.state / "devices.json").read_text())
|
||||
|
||||
def req(self, method="GET", query="", form=None, hdr=None, peer="127.0.0.1"):
|
||||
url = urllib.parse.urlsplit("/" + (f"?{query}" if query else ""))
|
||||
data = urllib.parse.urlencode(form or {}).encode()
|
||||
return asyncio.run(self.app.respond(method, url, hdr or {}, data, peer))[1]
|
||||
|
||||
def post(self, **form):
|
||||
return self.req("POST", "p=devices", form)
|
||||
|
||||
|
||||
def test_page_shows_ha_devices_with_their_profile_and_what_they_would_give(tmp_path):
|
||||
s = Site(tmp_path)
|
||||
out = s.req()
|
||||
assert "<nav>" in out and "?p=building" in out and "Devices</h2>" in out
|
||||
assert out.count("Use with Cantabile</button>") == 2 # the inverter and the A/C
|
||||
assert "Cantabile would read: pv: power" in out and "battery: soc" in out
|
||||
assert "It could control: heating, cooling." in out and "generic profile" in out
|
||||
assert "room: living room.temp" in out
|
||||
assert "Proposed by Cantabile (not checked yet)" in out # the install's proposal
|
||||
assert "1 more in Home Assistant without a profile" in out and "Lamp" in out
|
||||
assert "Used with Cantabile" not in out
|
||||
|
||||
|
||||
def test_use_with_cantabile_writes_the_fragment_consent_off(tmp_path):
|
||||
s = Site(tmp_path)
|
||||
out = s.post(do="use", ha_device=AC, profile="ha-thermostat", name="Living room A/C")
|
||||
assert "is used with Cantabile now" in out and s.changes == 1
|
||||
dev = next(iter(s.devices().values()))
|
||||
assert dev["ha_device"] == AC and dev["profile"] == "ha-thermostat" and not dev["read"] and not dev["control"]
|
||||
frag = s.frag(dev["id"])
|
||||
assert frag["device"] == dev["id"] and frag["profile"] == "ha-thermostat"
|
||||
assert all(a["consent"] is False for a in frag["assets"]) and all(c["consent"] is False for c in frag["controls"])
|
||||
assert {a["asset"] for a in frag["assets"]} >= {"room.living_room.temp", "room.living_room.setpoint", "heating.state"}
|
||||
# a thermostat that heats and cools: both controls, paired, by season;
|
||||
# one climate entity, never two independent writers
|
||||
assert sorted(c["kind"] for c in frag["controls"]) == ["cooling", "heating"]
|
||||
assert all(c["switchover"] == {"mode": "season"} for c in frag["controls"])
|
||||
# the profile's protection (its controls are protected by default)
|
||||
prot = json.loads((s.state / "protection.json").read_text())["entries"]
|
||||
assert {t for t, e in prot.items() if e["level"] == "protected"} == {f"control:{c['id']}" for c in frag["controls"]}
|
||||
specs = json.loads((s.state / "devices-specs.json").read_text())["devices"]
|
||||
assert specs[dev["id"]]["profile"] == "ha-thermostat" and specs[dev["id"]]["ha_device"] == AC
|
||||
# the page: used, reading off, no second offer for it
|
||||
out = s.req()
|
||||
assert "Used with Cantabile" in out and "first give your consent in the add-on's configuration" in out
|
||||
assert 'name="read"' not in out
|
||||
assert out.count("Use with Cantabile</button>") == 1
|
||||
assert "This device is used with Cantabile already." in s.post(do="use", ha_device=AC, profile="ha-thermostat")
|
||||
assert len(s.devices()) == 1
|
||||
# the agent loads it: values and both controls, nothing consented
|
||||
m = Mapping.load(str(s.mapping))
|
||||
assert sum(1 for c in m.controls if c.entities.get("climate") == "climate.living_ac") == 2
|
||||
assert not any(a.consent for a in m.assets)
|
||||
|
||||
|
||||
def test_the_proposal_yields_to_the_owners_device(tmp_path):
|
||||
s = Site(tmp_path)
|
||||
before = yaml.safe_load(s.mapping.read_text())
|
||||
assert before["source"] == "proposed"
|
||||
assert "sensor.inverter_input_power" in {a["entity"] for a in before["assets"]}
|
||||
s.post(do="use", ha_device=INV, profile="huawei-sun2000")
|
||||
after = yaml.safe_load(s.mapping.read_text())
|
||||
assert after["source"] == "proposed"
|
||||
inv = {"sensor.inverter_input_power", "sensor.inverter_yield", "sensor.battery_soc"}
|
||||
assert not inv & {a["entity"] for a in after["assets"]} # the device's own fragment only
|
||||
assert not any(a["asset"].split(".")[0] in ("pv", "battery") for a in after["assets"])
|
||||
assert "climate.living_ac" in {a["entity"] for a in after["assets"]} # the rest stays proposed
|
||||
m = Mapping.load(str(s.mapping))
|
||||
ents = [a.entity for a in m.assets]
|
||||
assert len(ents) == len(set(a.asset for a in m.assets)) and m.by_asset["pv.power"].entity == "sensor.inverter_input_power"
|
||||
assert sorted(e for e in ents if e in inv) == sorted(inv) # each once
|
||||
# removing gives it back to the proposal
|
||||
dev_id = next(iter(s.devices()))
|
||||
assert "no longer uses it" in s.post(do="remove", id=dev_id)
|
||||
assert not (tmp_path / "mapping.d" / f"{dev_id}.yaml").exists() and s.devices() == {}
|
||||
assert inv <= {a["entity"] for a in yaml.safe_load(s.mapping.read_text())["assets"]}
|
||||
|
||||
|
||||
def test_a_hand_written_mapping_wins_and_one_writer_per_entity(tmp_path):
|
||||
hand = {"version": 3, "assets": [{"entity": "climate.living_ac", "asset": "room.living.temp", "kind": "gauge",
|
||||
"unit": "°C", "consent": True, "attribute": "current_temperature"}],
|
||||
"controls": [{"id": "heating", "kind": "heating", "consent": False, "entities": {"climate": "climate.living_ac"}}]}
|
||||
s = Site(tmp_path, mapping=hand)
|
||||
out = s.req()
|
||||
assert "In your own mapping: room: living.temp. Those stay as they are." in out
|
||||
# the climate entity is the hand mapping's (read and written there):
|
||||
# nothing is left for the thermostat's fragment, and the page says why
|
||||
assert "Read by your own mapping already, so left out here: room: living room.temp" in out
|
||||
assert "Another control writes to this device already, so Cantabile leaves out: heating, cooling." in out
|
||||
out = s.post(do="use", ha_device=AC, profile="ha-thermostat")
|
||||
assert "or your mapping has them all already" in out and not (tmp_path / "state" / "devices.json").exists()
|
||||
# the inverter is not in it: used as usual
|
||||
s.post(do="use", ha_device=INV, profile="huawei-sun2000")
|
||||
assert len(s.devices()) == 1
|
||||
assert yaml.safe_load(s.mapping.read_text()) == hand # never changed
|
||||
m = Mapping.load(str(s.mapping))
|
||||
assert [c.id for c in m.controls] == ["heating"]
|
||||
|
||||
|
||||
def test_reading_and_control_need_the_site_consent(tmp_path):
|
||||
s = Site(tmp_path)
|
||||
s.post(do="use", ha_device=AC, profile="ha-thermostat")
|
||||
dev_id = next(iter(s.devices()))
|
||||
# no consent in the add-on's configuration: refused, the page says where
|
||||
out = s.post(do="consent", id=dev_id, read="1")
|
||||
assert "First give your consent in the add-on" in out and not s.devices()[dev_id]["read"]
|
||||
assert not any(a["consent"] for a in s.frag(dev_id)["assets"]) and s.restarts == 0
|
||||
# with it: the switches, as on the Hub's Devices page
|
||||
s.give_consent(share=True, control=False)
|
||||
out = s.req()
|
||||
assert 'name="read"' in out and 'name="control"' in out
|
||||
assert "Cantabile may control it (heating, cooling), within your limits" in out
|
||||
assert "Control also needs your consent to control devices" in out
|
||||
out = s.post(do="consent", id=dev_id, read="1")
|
||||
assert "Cantabile starts again" in out and s.restarts == 1
|
||||
assert s.devices()[dev_id]["read"] and not s.devices()[dev_id]["control"]
|
||||
frag = s.frag(dev_id)
|
||||
assert all(a["consent"] for a in frag["assets"]) and not any(c["consent"] for c in frag["controls"])
|
||||
s.give_consent(share=True, control=True)
|
||||
out = s.post(do="consent", id=dev_id, read="1", control="1")
|
||||
assert all(c["consent"] for c in s.frag(dev_id)["controls"]) and "Control also needs" not in out
|
||||
# the agent loads it with consent: reading the thermostat, both controls
|
||||
m = Mapping.load(str(s.mapping))
|
||||
assert all(a.consent for a in m.assets if a.entity == "climate.living_ac")
|
||||
# removing a consented device starts the agent again too
|
||||
s.post(do="remove", id=dev_id)
|
||||
assert s.restarts == 3
|
||||
|
||||
|
||||
def test_protection_and_heating_or_cooling(tmp_path):
|
||||
s = Site(tmp_path)
|
||||
s.post(do="use", ha_device=AC, profile="ha-thermostat")
|
||||
dev_id = next(iter(s.devices()))
|
||||
heat = next(c["id"] for c in s.frag(dev_id)["controls"] if c["kind"] == "heating")
|
||||
out = s.req()
|
||||
assert "Allow switching off" in out
|
||||
out = s.req("POST", "p=devices", {"do": "protect", "id": dev_id, "target": f"control:{heat}", "level": "none"},
|
||||
hdr={"x-remote-user-display-name": "Ana"})
|
||||
entry = json.loads((s.state / "protection.json").read_text())["entries"][f"control:{heat}"]
|
||||
assert entry["level"] == "none" and entry["set_by"] == "Ana" and entry["source"] == "owner"
|
||||
assert "sealed is a custodian" in s.post(do="protect", id=dev_id, target=f"device:{dev_id}", level="sealed")
|
||||
# a seal from the cloud: shown locked, nothing to lift, not removable
|
||||
(s.state / "acl.json").write_text(json.dumps({"v": 1, "kind": "acl", "site": "ab" * 16, "entries": [
|
||||
{"target": f"device:{dev_id}", "level": "sealed", "custodian": "grid_operator", "at": 1}]}))
|
||||
out = s.req()
|
||||
assert "Sealed" in out and "only the grid operator can change it" in out
|
||||
assert "only they can change it" in s.post(do="protect", id=dev_id, target=f"device:{dev_id}", level="none")
|
||||
assert "Sealed: only the grid operator can remove it." in s.post(do="remove", id=dev_id)
|
||||
assert "Sealed: only the grid operator can change its control." in s.post(do="switchover", id=dev_id, mode="cooling")
|
||||
(s.state / "acl.json").unlink()
|
||||
# heating or cooling, into both controls
|
||||
s.post(do="switchover", id=dev_id, mode="outdoor", heat_below_c="14", cool_above_c="24")
|
||||
assert all(c["switchover"] == {"mode": "outdoor", "heat_below_c": 14.0, "cool_above_c": 24.0}
|
||||
for c in s.frag(dev_id)["controls"])
|
||||
assert "heat below a lower temperature" in s.post(do="switchover", id=dev_id, mode="outdoor", heat_below_c="25",
|
||||
cool_above_c="20")
|
||||
|
||||
|
||||
def test_owner_only(tmp_path):
|
||||
s = Site(tmp_path)
|
||||
ingress = "172.30.32.2"
|
||||
out = s.req(peer=ingress) # HA did not say who
|
||||
assert "Only an administrator of Home Assistant" in out and "Use with Cantabile" not in out
|
||||
out = s.req(peer=ingress, hdr={"x-remote-user-id": "u-guest"})
|
||||
assert "Only an administrator of Home Assistant" in out
|
||||
out = s.req("POST", "p=devices", {"do": "use", "ha_device": AC, "profile": "ha-thermostat"}, {"x-remote-user-id": "u-guest"},
|
||||
ingress)
|
||||
assert not (s.state / "devices.json").exists()
|
||||
assert "Use with Cantabile</button>" in s.req(peer=ingress, hdr={"x-remote-user-id": "u-admin"})
|
||||
# the building page is the same app's
|
||||
# the building page too: only administrators
|
||||
assert "Only an administrator of Home Assistant" in s.req(query="p=building", peer=ingress)
|
||||
assert "Only an administrator" in s.req("POST", "p=building", {"do": "find"}, {"x-remote-user-id": "u-guest"}, ingress)
|
||||
assert "Join with a code" in s.req(query="p=building", peer=ingress, hdr={"x-remote-user-id": "u-admin"})
|
||||
assert "<nav>" in s.req(query="p=building")
|
||||
|
||||
|
||||
def test_ha_not_connected(tmp_path):
|
||||
s = Site(tmp_path)
|
||||
s.ha = None
|
||||
out = s.req()
|
||||
assert "Home Assistant is not connected yet" in out
|
||||
assert "Home Assistant is not connected yet" in s.post(do="use", ha_device=AC, profile="ha-thermostat")
|
||||
|
||||
|
||||
def test_german(tmp_path):
|
||||
s = Site(tmp_path)
|
||||
|
||||
def run():
|
||||
i18n.use("de")
|
||||
return s.req()
|
||||
import contextvars
|
||||
out = contextvars.copy_context().run(run)
|
||||
assert '<html lang="de">' in out and "Geräte</h2>" in out and "Mit Cantabile nutzen" in out
|
||||
assert "Cantabile würde auslesen" in out and "Steuern könnte es: Heizen, Kühlen." in out
|
||||
assert "Use with Cantabile" not in out
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def english():
|
||||
i18n.use("en")
|
||||
@@ -0,0 +1,144 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The profile logic both callers share (devprofiles.py): the Hub's devices
|
||||
tool and the HA add-on (Devices page, proposal, dashboard). Where the
|
||||
repository's Hub tool is beside this package (a checkout; not in CI's edge
|
||||
container), it is checked to give the same fragment as the add-on does."""
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
from cantabile_edge import devprofiles as dp
|
||||
from cantabile_edge import devview, mapping, propose
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
PROFILES = {p["id"]: p for p in propose.load_profiles(str(ROOT / "profiles"))}
|
||||
TOOL = ROOT / "hub" / "mkosi" / "mkosi.extra" / "usr" / "lib" / "cantabile" / "devices"
|
||||
|
||||
|
||||
def climate(eid="climate.ac", **attrs):
|
||||
return {"entity_id": eid, "device_id": "d", "unique_id": eid, "attributes": attrs or None}
|
||||
|
||||
|
||||
def test_one_source_of_truth():
|
||||
assert propose.QUANTITIES is dp.QUANTITIES and propose.recognise is dp.recognise
|
||||
assert mapping.part_of is dp.part_of and mapping.SUMMED is dp.SUMMED
|
||||
assert devview.recognise is dp.recognise and devview.by_priority is dp.by_priority
|
||||
assert dp.quantity_of("pv.2.power") == ("W", "gauge") and dp.quantity_of("room.kitchen.temp") == ("°C", "gauge")
|
||||
assert dp.quantity_of("room.{area}.setpoint") == ("°C", "gauge") and dp.quantity_of("nope") is None
|
||||
|
||||
|
||||
def test_specific_profiles_before_generic():
|
||||
ps = list(PROFILES.values())
|
||||
huawei = {"manufacturer": "Huawei", "model": "SUN2000-10KTL"}
|
||||
assert [p["id"] for p in dp.fitting(ps, huawei, ["huawei_solar"], ["sensor"])] == ["huawei-sun2000"]
|
||||
any_ac = {"manufacturer": "Espressif", "model": "esp32"}
|
||||
assert [p["id"] for p in dp.fitting(ps, any_ac, ["esphome"], ["climate"])] == ["ha-thermostat"]
|
||||
assert dp.fitting(ps, any_ac, ["esphome"], ["light"]) == []
|
||||
|
||||
|
||||
def test_conditions_on_attributes():
|
||||
m = {"entity_id": "^climate\\.", "supports": "heat"}
|
||||
assert dp.entity_matches(m, climate(hvac_modes=["off", "heat"]))
|
||||
assert not dp.entity_matches(m, climate(hvac_modes=["off", "cool"]))
|
||||
assert dp.entity_matches(m, climate()) # not known: holds
|
||||
assert dp.entity_matches(m, climate(hvac_modes=["off", "cool"]), None) # the caller's word: not known
|
||||
infrared = climate(hvac_modes=["heat", "cool"])
|
||||
assert dp.assumed_state(infrared, infrared["attributes"]) is True
|
||||
assert dp.assumed_state(infrared, None) is None
|
||||
|
||||
|
||||
def test_fragment_heat_and_cool_paired_consent_off():
|
||||
p = PROFILES["ha-thermostat"]
|
||||
s = dp.setup_for(p, ["esphome"])
|
||||
ents = [climate(hvac_modes=["off", "heat", "cool"], hvac_action="idle", current_temperature=21, temperature=22)]
|
||||
frag, missing = dp.mapping_for("ac-1", p, s, ents, "Living room", set())
|
||||
assert [c["kind"] for c in frag["controls"]] == ["heating", "cooling"]
|
||||
assert all(c["switchover"] == dp.SWITCHOVER_DEFAULT for c in frag["controls"])
|
||||
assert not any(a["consent"] for a in frag["assets"]) and not any(c["consent"] for c in frag["controls"])
|
||||
assert "room.living_room.temp" in {a["asset"] for a in frag["assets"]}
|
||||
# a heat-only thermostat: one control
|
||||
frag2, _ = dp.mapping_for("ac-2", p, s, [climate(hvac_modes=["off", "heat"], hvac_action="idle")], None, set())
|
||||
assert [c["kind"] for c in frag2["controls"]] == ["heating"] and "switchover" not in frag2["controls"][0]
|
||||
assert dp.switchover_of(frag2) is None and dp.switchover_of(frag)["mode"] == "season"
|
||||
with pytest.raises(dp.Fail):
|
||||
dp.set_switchover(frag2, {"mode": "cooling"})
|
||||
assert dp.set_switchover(frag, {"mode": "cooling"}) == {"mode": "cooling"}
|
||||
dp.set_consent(frag, True, False)
|
||||
assert all(a["consent"] for a in frag["assets"]) and not any(c["consent"] for c in frag["controls"])
|
||||
|
||||
|
||||
def test_leave_out_keeps_one_writer():
|
||||
frag = {"assets": [{"entity": "sensor.a", "asset": "pv.power"}, {"entity": "sensor.b", "asset": "pv.energy"}],
|
||||
"controls": [{"id": "heating", "kind": "heating", "entities": {"climate": "climate.x"}},
|
||||
{"id": "ev", "kind": "ev", "entities": {"current": "number.y", "soc": "sensor.z"}}]}
|
||||
gone = dp.leave_out(frag, {"sensor.a"}, dp.control_writes([{"entities": {"climate": "climate.x"}}]))
|
||||
assert gone == (["pv.power"], ["heating"])
|
||||
assert [a["asset"] for a in frag["assets"]] == ["pv.energy"] and [c["id"] for c in frag["controls"]] == ["ev"]
|
||||
|
||||
|
||||
def test_protection_rules():
|
||||
dev, frag = {"id": "d"}, {"controls": [{"id": "heating", "entities": {"climate": "climate.x"}}], "assets": []}
|
||||
targets = dp.device_targets(dev, frag, {})
|
||||
assert targets == ["device:d", "control:heating", "entity:climate.x"]
|
||||
e = dp.owner_entry({}, targets, "d", "control:heating", "protected", "Ana", now=5)
|
||||
assert e["level"] == "protected" and e["set_by"] == "Ana" and e["source"] == "owner"
|
||||
for bad in ("sealed", "off"):
|
||||
with pytest.raises(dp.Fail):
|
||||
dp.owner_entry({}, targets, "d", "control:heating", bad)
|
||||
with pytest.raises(dp.Fail):
|
||||
dp.owner_entry({}, targets, "d", "control:other", "none")
|
||||
cloud = dp.acl_entries({"v": 1, "kind": "acl", "entries": [{"target": "device:d", "level": "sealed",
|
||||
"custodian": "grid_operator", "at": 1}]})
|
||||
policy = dp.merge_policy(cloud, {"device:d": {"level": "none", "at": 9}})
|
||||
assert policy["device:d"]["level"] == "sealed" # the box never lowers a cloud seal
|
||||
assert dp.sealed(policy, "d") and dp.level_of(policy, targets)[0] == "sealed"
|
||||
with pytest.raises(dp.Fail, match="grid operator"):
|
||||
dp.owner_entry(policy, targets, "d", "device:d", "none")
|
||||
|
||||
|
||||
def load_tool(root):
|
||||
os.environ["CANTABILE_DEVICES_ROOT"] = str(root)
|
||||
try:
|
||||
loader = importlib.machinery.SourceFileLoader("devices_tool_under_test", str(TOOL))
|
||||
d = importlib.util.module_from_spec(importlib.util.spec_from_loader(loader.name, loader))
|
||||
loader.exec_module(d)
|
||||
finally:
|
||||
os.environ.pop("CANTABILE_DEVICES_ROOT")
|
||||
d.BUILTIN = str(ROOT / "profiles")
|
||||
return d
|
||||
|
||||
|
||||
@pytest.mark.skipif(not (TOOL.exists() and (TOOL.parent / "python" / "cantabile_modbus.py").exists()),
|
||||
reason="the Hub's devices tool is not beside this package")
|
||||
def test_the_hub_tool_uses_the_same_logic(tmp_path):
|
||||
d = load_tool(tmp_path)
|
||||
assert d.Fail is d.dp.Fail and d.dp.mapping_for.__code__.co_filename.endswith("devprofiles.py")
|
||||
p = PROFILES["ha-thermostat"]
|
||||
s = dp.setup_for(p, ["esphome"])
|
||||
ents = [climate(hvac_modes=["off", "heat", "cool"], hvac_action="heating", current_temperature=20)]
|
||||
hub, _ = d.mapping_for("ac-1", p, s, ents, "Hall", set())
|
||||
addon, _ = dp.mapping_for("ac-1", p, s, ents, "Hall", set())
|
||||
assert json.dumps(hub, sort_keys=True) == json.dumps(addon, sort_keys=True)
|
||||
reg = {"devices": [{"id": "x", "manufacturer": "Espressif", "model": "esp32", "domains": ["esphome"]}],
|
||||
"entities": [{"entity_id": "climate.ac", "device_id": "x"}]}
|
||||
assert dp.offers(reg, PROFILES.values())[0]["profiles"] == ["ha-thermostat"]
|
||||
|
||||
|
||||
def test_services_and_cantabile_not_offered():
|
||||
"""HA's services (Backup, Google Translate), the Supervisor's apps and
|
||||
Cantabile's own agent are not devices: never in the Devices list."""
|
||||
reg = {"devices": [
|
||||
{"id": "b", "name": "Backup", "manufacturer": "Home Assistant", "model": "Home Assistant Backup",
|
||||
"entry_type": "service"},
|
||||
{"id": "g", "name": "Google Translate en com", "manufacturer": "Google", "model": "Google Translate TTS",
|
||||
"entry_type": "service"},
|
||||
{"id": "c", "name": "Cantabile", "manufacturer": "Cantabile", "model": "Edge Agent"},
|
||||
{"id": "a", "name": "Cantabile Edge Agent", "manufacturer": "Local apps", "model": "Home Assistant App",
|
||||
"domains": ["hassio"]},
|
||||
{"id": "t", "name": "MD Thermostat", "manufacturer": "Realtek", "model": "wr3", "domains": ["esphome"]}],
|
||||
"entities": []}
|
||||
assert [o["id"] for o in dp.offers(reg, [])] == ["t"]
|
||||
@@ -0,0 +1,45 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The flats bundle as fleet makes it (platform/services/fleet/flats.go):
|
||||
accepted by the agent and turned into each flat's values for HA."""
|
||||
import json
|
||||
import time
|
||||
|
||||
from cantabile_edge.announce import Announcer
|
||||
from cantabile_edge.bundles import Bundles
|
||||
|
||||
SITE = "cd" * 16
|
||||
|
||||
|
||||
def bundle(now):
|
||||
start = int(now // 900 * 900)
|
||||
return {"v": 1, "kind": "flats", "id": "b1", "site": SITE, "issued": int(now), "expires": int(now) + 48 * 3600,
|
||||
"building": {"id": "0d4b1f0e-1111-4222-8333-944455556666", "name": "Lindenstraße 4"},
|
||||
"flats": [
|
||||
{"id": "ab" * 16, "label": "Flat 1", "unit": "3B",
|
||||
"state": {"grid_w": 600, "use_w": 1000, "pv_share_w": 400, "slot": start - 900},
|
||||
"flex": {"start": start, "step_s": 900, "grid_w": [1000, 900], "shed_w": [300, 201]},
|
||||
"commands": [{"control": "load_limit", "value": 4000, "level": "flexible", "from": start,
|
||||
"until": start + 3600, "status": "sent"}]},
|
||||
{"id": "ef" * 16, "label": "Flat 2", "commands": []}]}
|
||||
|
||||
|
||||
def test_fleet_bundle_read(tmp_path):
|
||||
now = time.time()
|
||||
(tmp_path / "flats.json").write_text(json.dumps(bundle(now)))
|
||||
flats = Bundles(str(tmp_path), SITE).flat_list()
|
||||
assert [f["label"] for f in flats] == ["Flat 1", "Flat 2"]
|
||||
one = Announcer.flat_state(flats[0], now)
|
||||
assert one["grid_w"] == 600 and one["flex_now"] == 300 and one["request"] == "load_limit 4000 (flexible)"
|
||||
two = Announcer.flat_state(flats[1], now)
|
||||
assert two["grid_w"] is None and two["flex_now"] is None and two["request"] == "none"
|
||||
|
||||
|
||||
def test_other_site_or_expired(tmp_path):
|
||||
now = time.time()
|
||||
b = bundle(now)
|
||||
b["site"] = "00" * 16
|
||||
(tmp_path / "flats.json").write_text(json.dumps(b))
|
||||
assert Bundles(str(tmp_path), SITE).flat_list() == []
|
||||
b = bundle(now - 49 * 3600)
|
||||
(tmp_path / "flats.json").write_text(json.dumps(b))
|
||||
assert Bundles(str(tmp_path), SITE).flat_list() == []
|
||||
@@ -0,0 +1,183 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The grid operator's limit from the EEBUS bridge (gridorder.py): Ed25519 against RFC 8032's vectors, the bridge's key pinned on first
|
||||
use, orders checked, the controller's limits and the optimiser's
|
||||
constraint."""
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from cantabile_edge import gridorder
|
||||
from cantabile_edge.gridorder import GridOrders, verify
|
||||
|
||||
# RFC 8032, 7.1, tests 1 and 2
|
||||
VECTORS = [
|
||||
("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
|
||||
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "",
|
||||
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"),
|
||||
("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
|
||||
"3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", "72",
|
||||
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"),
|
||||
]
|
||||
|
||||
|
||||
def test_rfc8032_vectors():
|
||||
for _sk, pk, msg, sig in VECTORS:
|
||||
pk, msg, sig = bytes.fromhex(pk), bytes.fromhex(msg), bytes.fromhex(sig)
|
||||
assert verify(pk, msg, sig)
|
||||
assert not verify(pk, msg + b"x", sig)
|
||||
assert not verify(pk, msg, sig[:-1] + bytes([sig[-1] ^ 1]))
|
||||
assert not verify(b"\x00" * 31, b"", b"\x00" * 64)
|
||||
|
||||
|
||||
def _sign(seed: bytes, msg: bytes) -> tuple[bytes, bytes]:
|
||||
"""Ed25519 signing (RFC 8032, 5.1.6), for the tests only (the bridge
|
||||
signs in Go)."""
|
||||
h = hashlib.sha512(seed).digest()
|
||||
a = int.from_bytes(h[:32], "little")
|
||||
a &= (1 << 254) - 8
|
||||
a |= 1 << 254
|
||||
|
||||
def enc(p):
|
||||
x, y, z, _ = p
|
||||
zi = pow(z, gridorder._P - 2, gridorder._P)
|
||||
x, y = x * zi % gridorder._P, y * zi % gridorder._P
|
||||
return (y | ((x & 1) << 255)).to_bytes(32, "little")
|
||||
pub = enc(gridorder._mul(a, gridorder._G))
|
||||
r = int.from_bytes(hashlib.sha512(h[32:] + msg).digest(), "little") % gridorder._L
|
||||
R = enc(gridorder._mul(r, gridorder._G))
|
||||
k = int.from_bytes(hashlib.sha512(R + pub + msg).digest(), "little") % gridorder._L
|
||||
return pub, R + ((r + k * a) % gridorder._L).to_bytes(32, "little")
|
||||
|
||||
|
||||
def test_signing_helper_matches_rfc():
|
||||
sk, pk, _msg, sig = VECTORS[0]
|
||||
pub, s = _sign(bytes.fromhex(sk), b"")
|
||||
assert pub.hex() == pk and s.hex() == sig
|
||||
|
||||
|
||||
SEED = bytes(range(32))
|
||||
NOW = 1_800_000_000
|
||||
|
||||
|
||||
def message(seed=SEED, **o):
|
||||
order = {"v": 1, "kind": "eebus-lpc", "id": "cb01-1", "state": "limited", "active": True, "limit_w": 4200.0,
|
||||
"from": NOW, "until": NOW + 900, "failsafe_w": 4200.0, "failsafe_s": 7200.0, "scope": "controllable",
|
||||
"control_box": {"ski": "cb01", "device": "control_box_cb01"}, "issued": NOW}
|
||||
order.update(o)
|
||||
text = json.dumps(order)
|
||||
pub, sig = _sign(seed, text.encode())
|
||||
return json.dumps({"order": text, "sig": base64.b64encode(sig).decode(), "key": base64.b64encode(pub).decode()})
|
||||
|
||||
|
||||
def test_orders_pinned_and_checked(tmp_path):
|
||||
g = GridOrders(str(tmp_path), clock=lambda: NOW + 10)
|
||||
assert g.take(message()) == (True, "taken")
|
||||
assert (tmp_path / "eebus-bridge.key").exists()
|
||||
assert g.proof() == "verified:eebus-lpc:cb01:cb01-1"
|
||||
# another key: refused, the order stays
|
||||
assert g.take(message(seed=bytes(32), limit_w=99999.0))[1].startswith("signed by another key")
|
||||
assert g.active()["limit_w"] == 4200.0
|
||||
# a forged order with the right key but a changed text
|
||||
m = json.loads(message())
|
||||
m["order"] = m["order"].replace("4200.0", "42000.0", 1)
|
||||
assert g.take(json.dumps(m)) == (False, "bad signature")
|
||||
# active without a control box
|
||||
assert "control box" in g.take(message(control_box={}))[1]
|
||||
# the same order again: no change; its end
|
||||
assert g.take(message()) == (False, "taken")
|
||||
assert g.take(message(active=False, state="normal", limit_w=0.0)) == (True, "taken")
|
||||
assert g.active() is None and g.proof() == ""
|
||||
|
||||
|
||||
def test_stale_and_ended(tmp_path):
|
||||
t = [NOW]
|
||||
g = GridOrders(str(tmp_path), clock=lambda: t[0])
|
||||
g.take(message(until=0))
|
||||
assert g.active()
|
||||
t[0] += gridorder.STALE_S + 1
|
||||
assert g.active() is None # the bridge went quiet: its own failsafe holds
|
||||
t[0] = NOW
|
||||
g.take(message(until=NOW + 60))
|
||||
t[0] = NOW + 61
|
||||
assert g.active() is None
|
||||
|
||||
|
||||
def test_model_constraint_and_limits(tmp_path):
|
||||
g = GridOrders(str(tmp_path), clock=lambda: NOW)
|
||||
g.take(message())
|
||||
m = g.for_model(NOW - 900, 900, 192)
|
||||
assert m["limit_w"] == 4200.0 and m["from_step"] == 1 and m["to_step"] == 2 and m["proof"].startswith("verified:")
|
||||
|
||||
class C:
|
||||
def __init__(self, id, kind, params):
|
||||
self.id, self.kind, self.params = id, kind, params
|
||||
lim = g.limits([C("ev", "ev", {"phases": 3, "voltage": 230}), C("bat", "battery", {}), C("room", "heating", {})])
|
||||
assert lim == {"ev": {"current_a": (None, 6.1)}, "bat": {"power_w": (None, 4200.0)}}
|
||||
|
||||
|
||||
highspy = pytest.importorskip("highspy")
|
||||
|
||||
|
||||
def test_optimizer_keeps_the_controllable_draw_under_the_limit():
|
||||
from cantabile_edge import optimizer
|
||||
from test_optimizer import START, house
|
||||
ev = {"id": "ev", "kind": "ev", "channels": ["switch", "current"],
|
||||
"params": {"need_wh": 30000, "departure": "07:00", "min_current_a": 6, "max_current_a": 16,
|
||||
"phases": 3, "voltage": 230},
|
||||
"state": {"connected": True}, "bounds": {"current_a": [0, 16, "device", "device"]}}
|
||||
free = optimizer.plan(house([ev]), 20)
|
||||
s = house([ev])
|
||||
s["grid_order"] = {"limit_w": 4200.0, "from_step": 0, "to_step": 192, "penalty": 500.0}
|
||||
limited = optimizer.plan(s, 20)
|
||||
|
||||
def top(p):
|
||||
return max((e["set"] for e in p["devices"]["ev"] if e["set"] != "off"), default=0)
|
||||
assert top(free) > 6.1 # 30 kWh by 07:00 wants more than 4.2 kW
|
||||
assert 0 < top(limited) <= 6.1 + 1e-6, limited["devices"]["ev"] # 6 A x 3 x 230 V = 4.14 kW
|
||||
|
||||
|
||||
def test_controller_takes_an_order(tmp_path):
|
||||
"""The bridge's order through the controller: the guard's grid limits
|
||||
at once, merged with the console's, the owner told, gone again when it ends."""
|
||||
import os
|
||||
import yaml
|
||||
from cantabile_edge.config import Config
|
||||
from cantabile_edge.consent import Consent
|
||||
from cantabile_edge.controller import Controller
|
||||
from cantabile_edge.mapping import Mapping
|
||||
m = tmp_path / "mapping.yaml"
|
||||
m.write_text(yaml.safe_dump({"version": 3, "assets": [], "controls": [
|
||||
{"id": "car", "kind": "ev", "consent": True, "entities": {"switch": "switch.wb", "current": "number.wb_amps"},
|
||||
"params": {"phases": 3, "voltage": 230, "min_current_a": 6, "max_current_a": 16}}]}))
|
||||
t = [NOW]
|
||||
ctl = Controller(Config(site_id="ab" * 16, mapping=str(m), state_dir=str(tmp_path)), Mapping.load(str(m)),
|
||||
Consent(str(tmp_path)), sink=None, clock=lambda: t[0])
|
||||
ctl.saved_limits = {"car": {"current_a": {"cloud": (None, 10.0)}}}
|
||||
ctl._merge_limits()
|
||||
got = []
|
||||
ctl.on_received.append(lambda ev: _append(got, ev))
|
||||
assert asyncio.run(ctl.grid_order(message().encode()))
|
||||
assert ctl.guard.extra_limits["car"]["current_a"] == {"cloud": (None, 10.0), "grid": (None, 6.1)}
|
||||
assert got and got[0]["by"] == "grid" and got[0]["args"]["level"] == "emergency" and "proof" not in got[0]["args"]
|
||||
st = ctl.gridorders.for_model(NOW, 900, 192)
|
||||
assert st["limit_w"] == 4200.0
|
||||
# ended
|
||||
assert asyncio.run(ctl.grid_order(message(active=False, state="normal", limit_w=0.0, id="cb01-2").encode()))
|
||||
assert ctl.guard.extra_limits["car"]["current_a"] == {"cloud": (None, 10.0)}
|
||||
assert not os.path.exists(tmp_path / "limits.json") # the order's limits are never saved as the console's
|
||||
|
||||
|
||||
async def _append(lst, ev):
|
||||
lst.append(ev)
|
||||
|
||||
|
||||
def test_inventory_carries_the_eebus_ski():
|
||||
from cantabile_edge.inventory import _eebus
|
||||
ski = "C0B05C0A1B0C0DE000000000000000000000C0B0"
|
||||
assert _eebus({"identifiers": [["mqtt", "cantabile_eebus_cb_c0b05c"]], "serial_number": ski}) == {"eebus_ski": ski.lower()}
|
||||
# anything but a SKI is left out (the platform would refuse the inventory)
|
||||
assert _eebus({"identifiers": [["mqtt", "cantabile_eebus_cb_c0b05c"]], "serial_number": "c0b05c0a"}) == {}
|
||||
assert _eebus({"identifiers": [["mqtt", "cantabile_modbus_x"]], "serial_number": "1"}) == {}
|
||||
@@ -0,0 +1,87 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Against a real (throwaway) Home Assistant: set IT_HA_URL and
|
||||
IT_HA_TOKEN_FILE. Skipped
|
||||
otherwise. Read-only like the agent itself."""
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from cantabile_edge.ha import HAClient, HAError
|
||||
from cantabile_edge.mapping import suggest
|
||||
|
||||
URL, TOKEN_FILE = os.environ.get("IT_HA_URL"), os.environ.get("IT_HA_TOKEN_FILE")
|
||||
pytestmark = pytest.mark.skipif(not (URL and TOKEN_FILE), reason="no test Home Assistant configured")
|
||||
|
||||
|
||||
async def client():
|
||||
c = HAClient(URL, open(TOKEN_FILE).read().strip())
|
||||
await c.connect()
|
||||
return c
|
||||
|
||||
|
||||
async def test_registries_states_and_suggest():
|
||||
c = await client()
|
||||
try:
|
||||
reg = await c.registries()
|
||||
states = await c.send("get_states")
|
||||
draft = suggest(states, reg)["assets"]
|
||||
finally:
|
||||
await c.close()
|
||||
assert {"entities", "devices", "areas"} <= reg.keys()
|
||||
assert any(a["asset"] == "pv.power" for a in draft)
|
||||
assert any(a["kind"] == "counter" and a["unit"] == "Wh" for a in draft)
|
||||
|
||||
|
||||
async def test_subscribe_entities_streams_changes():
|
||||
c = await client()
|
||||
got = asyncio.Queue()
|
||||
try:
|
||||
ids = ["sensor.pv_power", "sensor.living_room_temperature"]
|
||||
await c.subscribe_entities(ids, got.put_nowait)
|
||||
first = await asyncio.wait_for(got.get(), 10)
|
||||
assert set(first["a"]) == set(ids) # only what was asked for
|
||||
change = await asyncio.wait_for(got.get(), 30) # the templates update every 10 s
|
||||
assert set(change["c"]) <= set(ids)
|
||||
finally:
|
||||
await c.close()
|
||||
|
||||
|
||||
async def test_backfill_queues_statistics(tmp_path):
|
||||
"""HA compiles 5-minute statistics every 5 minutes: a test HA a few
|
||||
minutes old has at least one row for the measurement sensors."""
|
||||
import yaml
|
||||
from cantabile_edge.backfill import backfill
|
||||
from cantabile_edge.mapping import Mapping
|
||||
from cantabile_edge.store import Queue
|
||||
|
||||
m = tmp_path / "m.yaml"
|
||||
m.write_text(yaml.safe_dump({"version": 1, "assets": [
|
||||
{"entity": "sensor.pv_power", "asset": "pv.power", "kind": "gauge", "unit": "W", "consent": True},
|
||||
{"entity": "sensor.grid_import_energy", "asset": "grid.import_energy", "kind": "counter",
|
||||
"unit": "Wh", "consent": True}]}))
|
||||
q = Queue(str(tmp_path / "q.db"), 100)
|
||||
c = await client()
|
||||
try:
|
||||
now = datetime.now(timezone.utc)
|
||||
n = await backfill(c, Mapping.load(str(m)), q, now - timedelta(days=1), now, "5minute")
|
||||
finally:
|
||||
await c.close()
|
||||
assert n >= 1
|
||||
recs = {r["asset"]: r for r in q.peek()[0][2]["records"]}
|
||||
assert recs["pv.power"]["rows"] and "mean" in recs["pv.power"]["rows"][0]
|
||||
|
||||
|
||||
async def test_statistics_and_read_only():
|
||||
c = await client()
|
||||
try:
|
||||
now = datetime.now(timezone.utc)
|
||||
res = await c.send("recorder/statistics_during_period", start_time=(now - timedelta(days=1)).isoformat(),
|
||||
end_time=now.isoformat(), statistic_ids=["sensor.pv_power"], period="5minute",
|
||||
types=["mean"])
|
||||
assert isinstance(res, dict)
|
||||
with pytest.raises(HAError):
|
||||
await c.send("call_service", domain="homeassistant", service="restart")
|
||||
finally:
|
||||
await c.close()
|
||||
@@ -0,0 +1,205 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
|
||||
from cantabile_edge import joinpage
|
||||
from cantabile_edge.building import Building
|
||||
from cantabile_edge.joinpage import Fail, Fleet, JoinPage
|
||||
|
||||
B = "0d4b1f0e-1111-4222-8333-944455556666"
|
||||
SITE = "ab" * 16
|
||||
RULES = {"share": "per_flat", "billing": "per_flat", "level": "flexible",
|
||||
"controls": {"load_limit": {"allowed": True, "min": 3000, "max": 8000}}, "pv_price_ct": 25, "grid_price_ct": 35}
|
||||
CARD = {"id": B, "name": "Lindenstraße 4", "address": "Berlin", "operator": "WEG Linden", "rules": RULES, "rules_digest": "d1"}
|
||||
|
||||
|
||||
class FakeFleet(Fleet):
|
||||
"""Fleet's answers without the network or the link."""
|
||||
|
||||
def __init__(self, tmp):
|
||||
super().__init__(str(tmp), link_state=str(tmp / "link"), devices_url="https://devices.test", site_id=SITE)
|
||||
self.asked, self.state, self.down = [], {}, False
|
||||
|
||||
def ask(self, req, timeout=30):
|
||||
self.asked.append(req)
|
||||
if self.down:
|
||||
raise Fail("Cantabile cannot be reached: test")
|
||||
op = req["op"]
|
||||
if op == "preview":
|
||||
if req["code"] != "ABCD-EFGH-JKLM":
|
||||
raise Fail("unknown or used code")
|
||||
return {"building": CARD, "unit": {"label": "3B", "confirm_meter": False}}
|
||||
if op == "join":
|
||||
self.state = {"membership": {"state": "active", "building": CARD, "unit": "3B", "joined_at": "2026-10-29T10:00:00Z"}}
|
||||
if op == "request":
|
||||
self.state = {"requests": [{"id": "r1", "state": "pending", "name": CARD["name"], "unit_hint": req["unit_hint"]}]}
|
||||
if op == "nearby":
|
||||
return {"buildings": [dict(CARD, distance_m=120)]}
|
||||
if op == "leave":
|
||||
self.state = {"ended": {"name": CARD["name"], "at": "2026-10-29T11:00:00Z", "reason": "left"}}
|
||||
return dict(self.state)
|
||||
|
||||
|
||||
def test_member_ids():
|
||||
st = {"membership": {"state": "active", "building": {"id": "a"}}, "communities": [{"id": "c"}], "own_site_of": [{"id": "o"}]}
|
||||
assert joinpage.member_ids(st) == ["a", "c", "o"]
|
||||
assert joinpage.member_ids({"membership": {"state": "pending", "building": {"id": "a"}}}) == []
|
||||
|
||||
|
||||
def test_join_by_code_writes_membership_and_consent(tmp_path):
|
||||
fl = FakeFleet(tmp_path)
|
||||
p = JoinPage(fl, location=lambda: None)
|
||||
out = p.get({"code": ["abcd-efgh-jklm"]}) # a QR code's link: straight to the preview
|
||||
assert "Unit <b>3B</b>" in out and "Lindenstraße 4" in out and "3000–8000 W" in out
|
||||
out = p.post({"do": "join", "code": "ABCD-EFGH-JKLM", "rules_digest": "d1", "consent_building": "1"})
|
||||
assert "member now" in out and "Leave the building" in out
|
||||
join = [a for a in fl.asked if a["op"] == "join"][0]
|
||||
assert join["consent"] == {"building": True, "community": False} and join["rules_digest"] == "d1"
|
||||
assert Building(str(tmp_path)).memberships() == {B}
|
||||
assert fl.building_consent()
|
||||
assert stat.S_IMODE(os.stat(tmp_path / "membership.json").st_mode) == 0o600
|
||||
# leaving: no membership any more, consent kept as the owner's choice
|
||||
out = p.post({"do": "leave", "building": B})
|
||||
assert "Tick the box" in out
|
||||
out = p.post({"do": "leave", "building": B, "sure": "1"})
|
||||
assert "You left" in out and Building(str(tmp_path)).memberships() == set()
|
||||
|
||||
|
||||
COMM = {"id": "1c4b1f0e-1111-4222-8333-944455556666", "kind": "community", "name": "Kiez eG", "address": "Berlin-Mitte",
|
||||
"operator": "Kiez Energie eG", "rules_digest": "c1",
|
||||
"rules": dict(RULES, community={"reference": "spot", "reference_ct": 30, "delta_ct": 1.5, "feed_in_ct": 8})}
|
||||
|
||||
|
||||
class CommunityFleet(FakeFleet):
|
||||
"""A villa: the code and the nearby answer are a community's."""
|
||||
|
||||
def ask(self, req, timeout=30):
|
||||
if req["op"] == "preview":
|
||||
self.asked.append(req)
|
||||
return {"building": COMM}
|
||||
if req["op"] == "nearby":
|
||||
self.asked.append(req)
|
||||
return {"buildings": [dict(COMM, distance_m=1800)]}
|
||||
if req["op"] == "join":
|
||||
self.asked.append(req)
|
||||
self.state = {"communities": [dict(COMM, joined_at="2026-10-29T10:00:00Z", ends_at="2026-11-28T10:00:00Z")]}
|
||||
return dict(self.state)
|
||||
return super().ask(req, timeout)
|
||||
|
||||
|
||||
def test_villa_joins_a_community(tmp_path):
|
||||
fl = CommunityFleet(tmp_path)
|
||||
p = JoinPage(fl, location=lambda: (52.52, 13.41))
|
||||
out = p.get({"code": ["abcd-efgh-jklm"]})
|
||||
assert "This energy community" in out and 'name="consent_community"' in out and 'name="consent_building"' not in out
|
||||
assert "The community may send" in out and "Shared solar power" not in out
|
||||
assert "1.5 ct/kWh above the day-ahead price (around 30 ct/kWh)" in out and "closes the community: 30 days" in out
|
||||
out = p.post({"do": "join", "kind": "community", "code": "ABCD-EFGH-JKLM", "rules_digest": "c1", "consent_community": "1"})
|
||||
assert "member of the community now" in out and "ends on 2026-11-28" in out and "Leave the community" in out
|
||||
join = [a for a in fl.asked if a["op"] == "join"][0]
|
||||
assert join["consent"] == {"building": False, "community": True}
|
||||
assert fl.recipient_consent("community") and not fl.building_consent()
|
||||
assert Building(str(tmp_path)).memberships() == {COMM["id"]}
|
||||
out = p.post({"do": "find"})
|
||||
assert "An energy community" in out and 'name="unit_hint"' not in out
|
||||
assert "Tick the box" in p.post({"do": "leave", "building": COMM["id"]})
|
||||
|
||||
|
||||
def test_bad_code_and_request_nearby(tmp_path):
|
||||
fl = FakeFleet(tmp_path)
|
||||
p = JoinPage(fl, location=lambda: (52.52, 13.41))
|
||||
assert "12 letters" in p.post({"do": "preview", "code": "nope"})
|
||||
assert "unknown or used code" in p.post({"do": "preview", "code": "ZZZZ-ZZZZ-ZZZZ"})
|
||||
out = p.post({"do": "find"})
|
||||
assert "120 m away" in out and "Ask to join" in out
|
||||
assert [a for a in fl.asked if a["op"] == "nearby"][0]["lat"] == 52.52
|
||||
out = p.post({"do": "request", "building": B, "unit_hint": "3B", "consent_building": ""})
|
||||
assert "waiting for the building" in out and not fl.building_consent()
|
||||
assert "Which building" in p.post({"do": "request", "building": "x"})
|
||||
|
||||
|
||||
def test_no_location_and_offline(tmp_path):
|
||||
fl = FakeFleet(tmp_path)
|
||||
p = JoinPage(fl, location=lambda: None)
|
||||
assert "no home location" in p.post({"do": "find"})
|
||||
p.post({"do": "join", "code": "ABCD-EFGH-JKLM", "consent_building": "1"})
|
||||
fl.down = True
|
||||
out = p.get({})
|
||||
assert "could not be reached" in out and "said last" in out and "Lindenstraße 4" in out
|
||||
|
||||
|
||||
def test_consent_keeps_other_keys(tmp_path):
|
||||
(tmp_path / "consent.json").write_text(json.dumps({"share": True, "control": True}))
|
||||
fl = FakeFleet(tmp_path)
|
||||
fl.set_building_consent(True)
|
||||
d = json.loads((tmp_path / "consent.json").read_text())
|
||||
assert d["share"] is True and d["control"] is True and d["recipients"]["building"]["granted"] is True
|
||||
|
||||
|
||||
async def test_http_ingress_only(tmp_path):
|
||||
fl = FakeFleet(tmp_path)
|
||||
p = JoinPage(fl, location=lambda: None)
|
||||
server = await asyncio.start_server(p.handle, "127.0.0.1", 0)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
|
||||
async def req(raw: bytes) -> bytes:
|
||||
r, w = await asyncio.open_connection("127.0.0.1", port)
|
||||
w.write(raw)
|
||||
await w.drain()
|
||||
out = await r.read()
|
||||
w.close()
|
||||
return out
|
||||
out = await req(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")
|
||||
assert out.startswith(b"HTTP/1.1 200") and b"Join with a code" in out
|
||||
body = b"do=preview&code=ABCD-EFGH-JKLM"
|
||||
out = await req(b"POST / HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: "
|
||||
+ str(len(body)).encode() + b"\r\n\r\n" + body)
|
||||
assert b"Unit <b>3B</b>" in out
|
||||
assert (await req(b"GET /etc/passwd HTTP/1.1\r\n\r\n")).startswith(b"HTTP/1.1 404")
|
||||
server.close()
|
||||
# any other peer: refused
|
||||
joinpage.INGRESS_PEERS.discard("127.0.0.1")
|
||||
try:
|
||||
server = await asyncio.start_server(p.handle, "127.0.0.1", 0)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
assert (await req(b"GET / HTTP/1.1\r\n\r\n")).startswith(b"HTTP/1.1 403")
|
||||
server.close()
|
||||
finally:
|
||||
joinpage.INGRESS_PEERS.add("127.0.0.1")
|
||||
|
||||
|
||||
def test_config_on_in_an_addon(monkeypatch):
|
||||
from cantabile_edge import config
|
||||
monkeypatch.setenv("SUPERVISOR_TOKEN", "t")
|
||||
monkeypatch.setenv("CANTABILE_SITE_ID", SITE)
|
||||
assert config.load(None).join_page_port == 8099
|
||||
monkeypatch.delenv("SUPERVISOR_TOKEN")
|
||||
monkeypatch.setenv("HA_TOKEN_FILE", "")
|
||||
assert config.load(None).join_page_port == 0
|
||||
|
||||
|
||||
def test_offer_after_reinstall(tmp_path):
|
||||
"""Cantabile recognised a reinstall: the page says so, shows what the cloud
|
||||
kept, and gives the earlier consents again only with the owner's yes."""
|
||||
fl = FakeFleet(tmp_path)
|
||||
p = JoinPage(fl, location=lambda: None)
|
||||
assert "earlier Cantabile box" not in p.get({})
|
||||
(tmp_path / "link").mkdir()
|
||||
offer = {"v": 1, "received": 1000, "from": {"id": SITE, "name": "Old-Office"},
|
||||
"kept": {"name": "Old-Office", "communities": ["Kiez eG"]},
|
||||
"consents": {"share": True, "control": False, "recipients": ["community"]}}
|
||||
(tmp_path / "link" / "restore-offer.json").write_text(json.dumps(offer))
|
||||
out = p.get({})
|
||||
assert "This looks like your earlier Cantabile box <b>Old-Office</b>" in out and "Kiez eG" in out
|
||||
assert 'name="c_r_community" value="1" checked' in out and 'name="consent_yes" value="1">' in out
|
||||
# ticked, but no yes: nothing given; the offer is answered
|
||||
out = p.post({"do": "restore", "answer": "yes", "c_r_community": "1"})
|
||||
assert "Nothing restored" in out and not fl.recipient_consent("community")
|
||||
assert "earlier Cantabile box" not in p.get({})
|
||||
# a new offer, with the yes
|
||||
(tmp_path / "link" / "restore-offer.json").write_text(json.dumps(dict(offer, received=2000)))
|
||||
out = p.post({"do": "restore", "answer": "yes", "c_r_community": "1", "consent_yes": "1"})
|
||||
assert "consents given again" in out
|
||||
assert fl.recipient_consent("community") and not fl.recipient_consent("building")
|
||||
@@ -0,0 +1,118 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The add-on's pages (Building or community, Devices) in German or English
|
||||
(the browser's Accept-Language)."""
|
||||
import ast
|
||||
import asyncio
|
||||
import contextvars
|
||||
import os
|
||||
import string
|
||||
|
||||
from cantabile_edge import devpage, i18n, i18n_de, joinpage
|
||||
from cantabile_edge.joinpage import JoinPage
|
||||
|
||||
from test_joinpage import COMM, CommunityFleet, FakeFleet
|
||||
|
||||
SOURCES = [os.path.join(os.path.dirname(joinpage.__file__), f) for f in ("joinpage.py", "devpage.py")]
|
||||
|
||||
|
||||
def german(fn, *args):
|
||||
"""fn(*args) rendered in German, in a context of its own."""
|
||||
def run():
|
||||
i18n.use("de")
|
||||
return fn(*args)
|
||||
return contextvars.copy_context().run(run)
|
||||
|
||||
|
||||
def test_from_accept():
|
||||
assert i18n.from_accept("de-DE,de;q=0.9,en;q=0.8") == "de"
|
||||
assert i18n.from_accept("en-US,en;q=0.9,de;q=0.8") == "en"
|
||||
assert i18n.from_accept("fr-FR,fr;q=0.9,de;q=0.7,en;q=0.5") == "de"
|
||||
assert i18n.from_accept("de;q=0.4, en;q=0.6") == "en"
|
||||
assert i18n.from_accept("de, en") == "de"
|
||||
assert i18n.from_accept("fr, ro") is None
|
||||
assert i18n.from_accept("") is None and i18n.from_accept(None) is None
|
||||
assert i18n.from_accept("de;q=bad, en;q=0.1") == "en"
|
||||
|
||||
|
||||
def test_default_is_english():
|
||||
assert i18n.current() == "en"
|
||||
assert i18n.T("Join") == "Join" and i18n.iso_date("2026-11-28T10:00:00Z") == "2026-11-28"
|
||||
assert german(i18n.T, "Join") == "Beitreten" and i18n.current() == "en"
|
||||
assert german(i18n.iso_date, "2026-11-28T10:00:00Z") == "28. Nov. 2026"
|
||||
assert german(i18n.number, 1.5) == "1,5"
|
||||
|
||||
|
||||
def test_german_page(tmp_path):
|
||||
fl = CommunityFleet(tmp_path)
|
||||
p = JoinPage(fl, location=lambda: (52.52, 13.41))
|
||||
out = german(p.get, {"code": ["abcd-efgh-jklm"]})
|
||||
assert '<html lang="de">' in out and "Gebäude oder Gemeinschaft" in out
|
||||
assert "Diese Energiegemeinschaft" in out and "Kündigungsfrist" in out and "30 Tage" in out
|
||||
assert "1,5 ct/kWh über dem Day-Ahead-Börsenpreis (etwa 30 ct/kWh)" in out
|
||||
assert "Building or community" not in out and "Its rules" not in out
|
||||
out = german(p.post, {"do": "join", "kind": "community", "code": "ABCD-EFGH-JKLM", "rules_digest": "c1",
|
||||
"consent_community": "1"})
|
||||
assert "jetzt Mitglied der Gemeinschaft" in out and "28. Nov. 2026" in out and "Aus der Gemeinschaft austreten" in out
|
||||
assert "Setzen Sie das Häkchen" in german(p.post, {"do": "leave", "building": COMM["id"]})
|
||||
|
||||
|
||||
async def test_http_german(tmp_path):
|
||||
fl = FakeFleet(tmp_path)
|
||||
p = JoinPage(fl, location=lambda: None)
|
||||
server = await asyncio.start_server(p.handle, "127.0.0.1", 0)
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
|
||||
async def req(raw: bytes) -> str:
|
||||
r, w = await asyncio.open_connection("127.0.0.1", port)
|
||||
w.write(raw)
|
||||
await w.drain()
|
||||
out = await r.read()
|
||||
w.close()
|
||||
return out.decode()
|
||||
try:
|
||||
out = await req(b"GET / HTTP/1.1\r\nAccept-Language: de-DE,de;q=0.9,en;q=0.8\r\n\r\n")
|
||||
assert '<html lang="de">' in out and "Mit einem Code beitreten" in out and "Beitrittscode" in out
|
||||
out = await req(b"GET / HTTP/1.1\r\nAccept-Language: fr-FR\r\n\r\n")
|
||||
assert '<html lang="en">' in out and "Join with a code" in out
|
||||
body = b"do=preview&code=ABCD-EFGH-JKLM"
|
||||
out = await req(b"POST / HTTP/1.1\r\nAccept-Language: de\r\nContent-Length: " + str(len(body)).encode()
|
||||
+ b"\r\n\r\n" + body)
|
||||
assert "Einheit <b>3B</b> in diesem Gebäude" in out and "3000–8000 W" in out
|
||||
assert i18n.current() == "en"
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def _texts():
|
||||
"""Every literal T/TN/M text of the pages."""
|
||||
out = []
|
||||
for n in (n for src in SOURCES for n in ast.walk(ast.parse(open(src).read()))):
|
||||
if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id in ("T", "TN", "M"):
|
||||
if not (n.args and isinstance(n.args[0], ast.Constant)):
|
||||
continue # T(table[k]): the table's M() texts
|
||||
if n.func.id == "TN":
|
||||
out.append((n.args[0].value, n.args[1].value))
|
||||
else:
|
||||
out.append(n.args[0].value)
|
||||
return out
|
||||
|
||||
|
||||
def _names(s):
|
||||
return {f for _, f, _, _ in string.Formatter().parse(s) if f is not None}
|
||||
|
||||
|
||||
def test_catalogue_complete():
|
||||
texts = _texts()
|
||||
assert len(texts) > 150
|
||||
missing = [t for t in texts if t not in i18n_de.MESSAGES]
|
||||
assert not missing, missing
|
||||
for t in texts:
|
||||
de = i18n_de.MESSAGES[t]
|
||||
if isinstance(t, tuple):
|
||||
assert isinstance(de, tuple) and len(de) == 2, t
|
||||
for en_form, de_form in zip(t, de):
|
||||
assert _names(en_form) == _names(de_form), t
|
||||
else:
|
||||
assert isinstance(de, str) and _names(t) == _names(de), t
|
||||
# nothing stale in the catalogue
|
||||
assert set(i18n_de.MESSAGES) <= set(texts), set(i18n_de.MESSAGES) - set(texts)
|
||||
@@ -0,0 +1,80 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The link sink against a fake link on a local socket: hello, a stored
|
||||
batch, a refused one, a wrong site, and a command answered as not taken."""
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from cantabile_edge.sinks import LinkSink
|
||||
|
||||
SITE = "ab" * 16
|
||||
|
||||
|
||||
async def fake_link(path, site=SITE, refuse=False, command=False):
|
||||
seen = []
|
||||
|
||||
async def handle(r, w):
|
||||
while line := await r.readline():
|
||||
m = json.loads(line)
|
||||
seen.append(m)
|
||||
if m["op"] == "hello":
|
||||
w.write(json.dumps({"op": "hello", "site": site}).encode() + b"\n")
|
||||
if command:
|
||||
w.write(b'{"op":"command","id":"c1","cmd":"mode","args":{"mode":"auto"}}\n')
|
||||
elif m["op"] == "tel":
|
||||
ans = {"op": "ack", "id": m["id"], "ok": not refuse}
|
||||
if refuse:
|
||||
ans["error"] = "not connected"
|
||||
w.write(json.dumps(ans).encode() + b"\n")
|
||||
await w.drain()
|
||||
|
||||
srv = await asyncio.start_unix_server(handle, path)
|
||||
return srv, seen
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stored_batch(tmp_path):
|
||||
p = str(tmp_path / "link.sock")
|
||||
srv, seen = await fake_link(p)
|
||||
s = LinkSink(p, SITE)
|
||||
assert await s.send(5, "tel", {"window": "x", "assets": {}})
|
||||
tel = [m for m in seen if m["op"] == "tel"][0]
|
||||
assert tel["msg_id"] == f"{SITE}:5" and tel["data"]["seq"] == 5 and tel["data"]["site"] == SITE
|
||||
await s.close()
|
||||
srv.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_refused_batch_is_kept(tmp_path):
|
||||
p = str(tmp_path / "link.sock")
|
||||
srv, _ = await fake_link(p, refuse=True)
|
||||
s = LinkSink(p, SITE)
|
||||
assert not await s.send(1, "tel", {})
|
||||
await s.close()
|
||||
srv.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wrong_site(tmp_path):
|
||||
p = str(tmp_path / "link.sock")
|
||||
srv, _ = await fake_link(p, site="cd" * 16)
|
||||
s = LinkSink(p, SITE)
|
||||
assert not await s.send(1, "tel", {})
|
||||
srv.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_command_not_taken(tmp_path):
|
||||
p = str(tmp_path / "link.sock")
|
||||
srv, seen = await fake_link(p, command=True)
|
||||
s = LinkSink(p, SITE)
|
||||
assert await s.send(1, "tel", {})
|
||||
for _ in range(50):
|
||||
if any(m["op"] == "result" for m in seen):
|
||||
break
|
||||
await asyncio.sleep(0.02)
|
||||
r = [m for m in seen if m["op"] == "result"][0]
|
||||
assert r["id"] == "c1" and r["ok"] is False
|
||||
await s.close()
|
||||
srv.close()
|
||||
@@ -0,0 +1,140 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from cantabile_edge.mapping import Mapping, convert, suggest
|
||||
|
||||
|
||||
def st(eid, dc, unit, name, state_class="measurement", state="1"):
|
||||
return {"entity_id": eid, "state": state, "attributes": {
|
||||
"device_class": dc, "unit_of_measurement": unit, "friendly_name": name, "state_class": state_class}}
|
||||
|
||||
|
||||
REG = {"areas": [{"area_id": "living_room", "name": "Living Room"}],
|
||||
"devices": [{"id": "d1", "area_id": "living_room"}],
|
||||
"entities": [{"entity_id": "sensor.living_temp", "device_id": "d1", "area_id": None},
|
||||
{"entity_id": "sensor.socket_power", "device_id": None, "area_id": "living_room"}]}
|
||||
|
||||
|
||||
def test_suggest_roles_areas_and_no_consent():
|
||||
states = [
|
||||
st("sensor.pv_power", "power", "kW", "PV power"),
|
||||
st("sensor.grid_total_energy", "energy", "kWh", "Grid import energy", "total_increasing"),
|
||||
st("sensor.grid_feed", "energy", "kWh", "Grid feed-in", "total_increasing"),
|
||||
st("sensor.living_temp", "temperature", "°C", "Living temperature"),
|
||||
st("sensor.socket_power", "power", "W", "Socket"),
|
||||
st("sensor.other_power", "power", "W", "Fridge"),
|
||||
st("sensor.other2_power", "power", "W", "Freezer"),
|
||||
st("sensor.weather", None, None, "Weather"), # no device class: skipped
|
||||
st("binary_sensor.door", "door", None, "Door"), # not a sensor: skipped
|
||||
]
|
||||
d = {a["entity"]: a for a in suggest(states, REG)["assets"]}
|
||||
assert d["sensor.pv_power"] == {"entity": "sensor.pv_power", "asset": "pv.power", "kind": "gauge",
|
||||
"unit": "W", "consent": False}
|
||||
assert d["sensor.grid_total_energy"]["asset"] == "grid.import_energy"
|
||||
assert d["sensor.grid_total_energy"]["kind"] == "counter"
|
||||
assert d["sensor.grid_total_energy"]["unit"] == "Wh"
|
||||
assert d["sensor.grid_feed"]["asset"] == "grid.export_energy"
|
||||
assert d["sensor.living_temp"]["asset"] == "room.living_room.temp" # area from the device
|
||||
assert d["sensor.socket_power"]["asset"] == "room.living_room.power" # area of the entity
|
||||
assert {d["sensor.other_power"]["asset"], d["sensor.other2_power"]["asset"]} == {"site.power", "site.power_2"}
|
||||
assert "sensor.weather" not in d and "binary_sensor.door" not in d
|
||||
assert not any(a["consent"] for a in d.values())
|
||||
|
||||
|
||||
def test_draft_loads_back(tmp_path):
|
||||
p = tmp_path / "m.yaml"
|
||||
p.write_text(yaml.safe_dump(suggest([st("sensor.pv_power", "power", "W", "PV")], REG)))
|
||||
m = Mapping.load(str(p))
|
||||
assert m.consented("sensor.pv_power") is None # draft: nothing leaves
|
||||
|
||||
|
||||
def test_load_rejects_duplicates(tmp_path):
|
||||
p = tmp_path / "m.yaml"
|
||||
p.write_text(yaml.safe_dump({"version": 2, "assets": [
|
||||
{"entity": "sensor.a", "asset": "pv.power", "kind": "gauge", "unit": "W", "consent": True},
|
||||
{"entity": "sensor.b", "asset": "pv.power", "kind": "gauge", "unit": "W", "consent": True}]}))
|
||||
with pytest.raises(ValueError):
|
||||
Mapping.load(str(p))
|
||||
|
||||
|
||||
def test_convert():
|
||||
assert convert(1.5, "kW", "W") == 1500
|
||||
assert convert(2, "kWh", "Wh") == 2000
|
||||
assert convert(212, "°F", "°C") == pytest.approx(100)
|
||||
assert convert(5, "W", "Wh") is None # wrong quantity: dropped, never guessed
|
||||
assert convert(5, "mystery", "mystery") == 5
|
||||
|
||||
|
||||
def _write(path, data):
|
||||
with open(path, "w") as f:
|
||||
yaml.safe_dump(data, f)
|
||||
|
||||
|
||||
def test_device_fragments_merge_and_main_wins(tmp_path):
|
||||
"""Devices added in the panel bring mapping.d/<device>.yaml; the
|
||||
mapping's own entries win, a broken fragment is left out whole."""
|
||||
main = tmp_path / "mapping.yaml"
|
||||
_write(main, {"version": 3, "assets": [
|
||||
{"entity": "sensor.pv", "asset": "pv.power", "kind": "gauge", "unit": "W", "consent": True}],
|
||||
"inputs": {"pv_power": "sensor.pv"}})
|
||||
(tmp_path / "mapping.d").mkdir()
|
||||
_write(tmp_path / "mapping.d" / "inverter.yaml", {"version": 3, "assets": [
|
||||
{"entity": "sensor.pv", "asset": "pv.power_2", "kind": "gauge", "unit": "W"}, # mapped already
|
||||
{"entity": "sensor.inv_pv", "asset": "pv.power", "kind": "gauge", "unit": "W"}, # id taken
|
||||
{"entity": "sensor.meter", "asset": "grid.power", "kind": "gauge", "unit": "W", "scale": -1},
|
||||
{"entity": "sensor.soc", "asset": "battery.soc", "kind": "gauge", "unit": "%"}],
|
||||
"controls": [{"id": "battery", "kind": "battery",
|
||||
"entities": {"setpoint": "number.batt_power", "soc": "sensor.soc"}}],
|
||||
"inputs": {"pv_power": "sensor.inv_pv", "load_power": "sensor.load"}})
|
||||
_write(tmp_path / "mapping.d" / "broken.yaml", {"assets": [
|
||||
{"entity": "sensor.x", "asset": "x.power", "kind": "level", "unit": "W"}]})
|
||||
m = Mapping.load(str(main))
|
||||
assert [a.entity for a in m.assets] == ["sensor.pv", "sensor.meter", "sensor.soc"]
|
||||
assert m.by_entity["sensor.meter"].scale == -1
|
||||
assert [c.id for c in m.controls] == ["battery"] and not m.controls[0].consent
|
||||
assert m.inputs.pv_power == "sensor.pv" and m.inputs.load_power == "sensor.load"
|
||||
assert "sensor.x" not in m.by_entity
|
||||
|
||||
|
||||
def test_scale_checked_and_applied(tmp_path):
|
||||
from cantabile_edge.mapping import scaled
|
||||
main = tmp_path / "mapping.yaml"
|
||||
_write(main, {"assets": [{"entity": "sensor.e", "asset": "grid.export_energy", "kind": "counter",
|
||||
"unit": "Wh", "scale": -1}]})
|
||||
with pytest.raises(ValueError, match="scale"):
|
||||
Mapping.load(str(main))
|
||||
_write(main, {"assets": [{"entity": "sensor.p", "asset": "grid.power", "kind": "gauge", "unit": "W",
|
||||
"scale": -1}]})
|
||||
a = Mapping.load(str(main)).assets[0]
|
||||
assert scaled(convert(1.5, "kW", "W"), a) == -1500
|
||||
assert scaled(None, a) is None
|
||||
|
||||
|
||||
def test_devices_of_one_kind_become_parts(tmp_path):
|
||||
"""Two inverters' fragments both with pv.power: numbered in file order
|
||||
(pv.1.*, pv.2.*), the total derived; one device's system stays as it is;
|
||||
an old mapping without parts reads as before (no totals)."""
|
||||
main = tmp_path / "mapping.yaml"
|
||||
_write(main, {"version": 3, "assets": [
|
||||
{"entity": "sensor.load", "asset": "load.power", "kind": "gauge", "unit": "W"}]})
|
||||
(tmp_path / "mapping.d").mkdir()
|
||||
for name, pre in (("a-inverter", "a"), ("b-inverter", "b")):
|
||||
_write(tmp_path / "mapping.d" / f"{name}.yaml", {"version": 3, "device": name, "assets": [
|
||||
{"entity": f"sensor.{pre}_pv", "asset": "pv.power", "kind": "gauge", "unit": "W"},
|
||||
{"entity": f"sensor.{pre}_pv_e", "asset": "pv.energy", "kind": "counter", "unit": "Wh"}]
|
||||
+ ([{"entity": "sensor.soc", "asset": "battery.soc", "kind": "gauge", "unit": "%"}] if pre == "a" else [])})
|
||||
m = Mapping.load(str(main))
|
||||
assert {a.entity: a.asset for a in m.assets} == {
|
||||
"sensor.load": "load.power", "sensor.a_pv": "pv.1.power", "sensor.a_pv_e": "pv.1.energy",
|
||||
"sensor.soc": "battery.soc", "sensor.b_pv": "pv.2.power", "sensor.b_pv_e": "pv.2.energy"}
|
||||
assert m.totals["pv.power"].entities == ["sensor.a_pv", "sensor.b_pv"] and m.totals["pv.energy"].kind == "counter"
|
||||
assert m.part_total["pv.2.energy"] == "pv.energy"
|
||||
_write(main, {"version": 2, "assets": [
|
||||
{"entity": "sensor.pv", "asset": "pv.power", "kind": "gauge", "unit": "W"},
|
||||
{"entity": "sensor.pv2", "asset": "pv.power_2", "kind": "gauge", "unit": "W"}]})
|
||||
(tmp_path / "mapping.d" / "a-inverter.yaml").unlink()
|
||||
(tmp_path / "mapping.d" / "b-inverter.yaml").unlink()
|
||||
old = Mapping.load(str(main))
|
||||
assert old.totals == {} and [a.asset for a in old.assets] == ["pv.power", "pv.power_2"]
|
||||
assert old.inputs.pv_power == ""
|
||||
@@ -0,0 +1,114 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""The optimiser on a synthetic house: cheap night, expensive evening."""
|
||||
import pytest
|
||||
|
||||
highspy = pytest.importorskip("highspy")
|
||||
|
||||
from cantabile_edge import optimizer # noqa: E402
|
||||
|
||||
START = 1793232000 # 2026-10-29 00:00 UTC (01:00 in Berlin)
|
||||
|
||||
|
||||
def house(devices, steps=192):
|
||||
hour = lambda k: (k // 4 + 1) % 24 # noqa: E731 (Berlin, winter)
|
||||
price = [12.0 if hour(k) < 6 else 40.0 if 17 <= hour(k) < 21 else 28.0 for k in range(steps)]
|
||||
return {"v": 1, "start": START, "step_s": 900, "steps": steps, "tz": "Europe/Berlin",
|
||||
"price_import": price, "price_export": [8.0] * steps, "price_note": "test",
|
||||
"load_w": [400.0] * steps, "pv_w": [0.0] * steps, "t_out": [5.0] * steps,
|
||||
"sun": [0.0] * steps, "occupied": [1 if 6 <= hour(k) < 22 else 0 for k in range(steps)],
|
||||
"devices": devices}
|
||||
|
||||
|
||||
def at(entries, t):
|
||||
"""The value in force at time t (a plan lists changes only)."""
|
||||
cur = None
|
||||
for e in entries:
|
||||
if e["t"] <= t:
|
||||
cur = e
|
||||
return cur
|
||||
|
||||
|
||||
def battery(soc=50, floor=20):
|
||||
return {"id": "battery", "kind": "battery", "channels": ["setpoint"],
|
||||
"params": {"capacity_wh": 10000, "max_charge_w": 3000, "max_discharge_w": 3000, "efficiency": 0.95,
|
||||
"soc_pct": soc},
|
||||
"state": {"soc_pct": soc}, "bounds": {"soc_pct": [floor, 100, "owner", "device"],
|
||||
"power_w": [-3000, 3000, "device", "device"]}}
|
||||
|
||||
|
||||
def heating(temp=19.0, switched=False, power=4000):
|
||||
return {"id": "heating", "kind": "heating", "channels": ["switch"] if switched else ["climate"],
|
||||
"params": {"r_k_per_kw": 10, "c_kwh_per_k": 3, "max_power_w": power, "comfort_c": 21, "setback_c": 17,
|
||||
"cop": 1.0},
|
||||
"state": {"temp_c": temp}, "bounds": {"temp_c": [16, 26, "owner", "owner"]}}
|
||||
|
||||
|
||||
def test_battery_charges_cheap_and_discharges_at_the_peak():
|
||||
p = optimizer.plan(house([battery()]), 20)
|
||||
steps = p["devices"]["battery"]
|
||||
first_night = [e for e in steps if e["t"] < START + 5 * 3600]
|
||||
assert any(e["set"] > 0 and e["grid"] for e in first_night), steps[:6]
|
||||
# 17:00-21:00 Berlin = 16:00-20:00 UTC: discharging at the peak
|
||||
assert any(at(steps, START + h * 3600)["set"] < 0 for h in (16, 17, 18, 19)), steps
|
||||
assert p["cost_eur"] < p["baseline_eur"]
|
||||
|
||||
|
||||
def test_battery_floor_respected():
|
||||
s = house([battery(soc=60, floor=55)])
|
||||
m = optimizer.Model(s)
|
||||
m.solve(20)
|
||||
val = m.h.getSolution().col_value
|
||||
soc = [val[v.index] for v in m.devices["battery"][1]["soc"]]
|
||||
assert min(soc) >= 0.55 * 10000 - 1
|
||||
|
||||
|
||||
def test_heating_reaches_comfort_when_occupied():
|
||||
s = house([heating(temp=17.0)])
|
||||
m = optimizer.Model(s)
|
||||
m.solve(20)
|
||||
val = m.h.getSolution().col_value
|
||||
temps = [val[v.index] for v in m.devices["heating"][1]["temp"]]
|
||||
# the second day (a 2 kW heater can't lift a 3 kWh/K room 4 K before the
|
||||
# first morning): warm whenever someone is home
|
||||
day2 = [t for t in range(100, 191) if s["occupied"][t + 1]]
|
||||
assert min(temps[t] for t in day2) >= 20.8 # comfort 21, within the solver's tolerance
|
||||
|
||||
|
||||
def test_switched_boiler_on_off():
|
||||
p = optimizer.plan(house([heating(temp=18.0, switched=True)]), 20)
|
||||
assert {e["set"] for e in p["devices"]["heating"]} <= {"on", "off"}
|
||||
assert any(e["set"] == "on" for e in p["devices"]["heating"])
|
||||
|
||||
|
||||
def test_ev_charges_in_cheap_hours_before_departure():
|
||||
ev = {"id": "ev", "kind": "ev", "channels": ["switch", "current"],
|
||||
"params": {"need_wh": 8000, "departure": "07:00", "min_current_a": 6, "max_current_a": 16,
|
||||
"phases": 1, "voltage": 230},
|
||||
"state": {"connected": True}, "bounds": {"current_a": [0, 16, "device", "device"]}}
|
||||
p = optimizer.plan(house([ev]), 20)
|
||||
on = [e for e in p["devices"]["ev"] if e["set"] != "off"]
|
||||
assert on and all(e["t"] < START + 5 * 3600 for e in on) # the cheap night, before 06:00 Berlin
|
||||
assert all(6 <= e["set"] <= 16 for e in on)
|
||||
assert len(p["devices"]["ev"]) <= 4, p["devices"]["ev"] # one charging block, not flapping
|
||||
|
||||
|
||||
def test_not_connected_ev_gets_no_plan():
|
||||
ev = {"id": "ev", "kind": "ev", "channels": ["switch"], "params": {"need_wh": 8000, "departure": "07:00",
|
||||
"min_current_a": 6, "max_current_a": 16, "phases": 1, "voltage": 230},
|
||||
"state": {"connected": False}, "bounds": {"current_a": [0, 16, "device", "device"]}}
|
||||
assert optimizer.plan(house([ev]), 20)["devices"]["ev"] == []
|
||||
|
||||
|
||||
def test_cover_shades_a_cooled_room_in_the_sun():
|
||||
s = house([{"id": "ac", "kind": "cooling", "channels": ["climate"],
|
||||
"params": {"r_k_per_kw": 10, "c_kwh_per_k": 3, "max_power_w": 1500, "comfort_c": 25, "setup_c": 28,
|
||||
"cop": 3.0},
|
||||
"state": {"temp_c": 26.0}, "bounds": {"temp_c": [18, 30, "owner", "owner"]}},
|
||||
{"id": "blind", "kind": "cover", "channels": ["cover"], "params": {"room": "ac", "gain_w": 3000},
|
||||
"state": {}, "bounds": {"position_pct": [0, 100, "device", "device"]}}])
|
||||
s["t_out"] = [30.0] * 192
|
||||
s["sun"] = [1.0 if 40 <= k < 64 else 0.0 for k in range(192)]
|
||||
p = optimizer.plan(s, 20)
|
||||
blind = p["devices"]["blind"]
|
||||
assert at(blind, START + 12 * 3600)["set"] < 100, blind # the sun on it: shaded
|
||||
assert at(blind, START + 3 * 3600)["set"] == 100, blind # night, nothing at stake: open
|
||||
@@ -0,0 +1,155 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Protection of devices (policy.py) in the guard and the
|
||||
plans, the mapping's fragments' devices, and the inventory for the cloud."""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
|
||||
import yaml
|
||||
|
||||
from cantabile_edge.controller import Controller
|
||||
from cantabile_edge.config import Config
|
||||
from cantabile_edge.inventory import Inventory, build
|
||||
from cantabile_edge.mapping import Mapping
|
||||
from cantabile_edge.policy import Policy, is_off, merge
|
||||
|
||||
from test_control_parts import MAPPING, SITE, Clock, act, consent, mapping, mk_guard # noqa: F401
|
||||
|
||||
|
||||
def put(path, data):
|
||||
"""As the link and the devices tool write: a new file renamed into place."""
|
||||
tmp = str(path) + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(data, f)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def acl(tmp_path, entries, site=SITE):
|
||||
put(tmp_path / "acl.json", {"v": 1, "kind": "acl", "id": "a", "site": site, "issued": 1, "expires": 0, "entries": entries})
|
||||
|
||||
|
||||
def local(tmp_path, entries):
|
||||
put(tmp_path / "protection.json", {"v": 1, "entries": entries})
|
||||
|
||||
|
||||
def guarded(mapping, consent, tmp_path):
|
||||
g = mk_guard(mapping, consent)
|
||||
g.policy = Policy(str(tmp_path), SITE)
|
||||
return g
|
||||
|
||||
|
||||
def test_merge():
|
||||
assert merge({"x": {"level": "sealed", "at": 1}}, {"x": {"level": "none", "at": 9}})["x"]["level"] == "sealed"
|
||||
assert merge({"x": {"level": "none", "at": 9}}, {"x": {"level": "sealed", "at": 1}})["x"]["level"] == "none"
|
||||
assert merge({"x": {"level": "protected", "at": 1}}, {"x": {"level": "none", "at": 2}})["x"]["level"] == "none"
|
||||
|
||||
|
||||
def test_protected_never_off(mapping, consent, tmp_path):
|
||||
g = guarded(mapping, consent, tmp_path)
|
||||
off = act("car", "switch", "switch.ev", "turn_off", "off", "")
|
||||
on = act("car", "switch", "switch.ev", "turn_on", "on", "")
|
||||
assert g.check(off)[0] and g.check(on)[0]
|
||||
local(tmp_path, {"entity:switch.ev": {"level": "protected", "at": 1, "source": "owner"}})
|
||||
ok, why = g.check(off)
|
||||
assert not ok and why.startswith("protected")
|
||||
assert g.check(on)[0] # on: fine
|
||||
stop = act("car", "current", "number.ev_current", "set_value", 0, "current_a", level="emergency")
|
||||
assert is_off(stop)
|
||||
local(tmp_path, {"control:car": {"level": "protected", "at": 2, "source": "owner"}})
|
||||
assert not g.check(stop)[0] # whatever the level
|
||||
|
||||
|
||||
def test_sealed_nothing(mapping, consent, tmp_path):
|
||||
g = guarded(mapping, consent, tmp_path)
|
||||
acl(tmp_path, [{"target": "control:living", "level": "sealed", "custodian": "grid_operator", "at": 1}])
|
||||
ok, why = g.check(act(level="emergency"))
|
||||
assert not ok and "grid operator" in why
|
||||
# the owner's own entry never lowers it
|
||||
local(tmp_path, {"control:living": {"level": "none", "at": 99, "source": "owner"}})
|
||||
assert not g.check(act())[0]
|
||||
# another site's policy: ignored
|
||||
acl(tmp_path, [{"target": "control:living", "level": "sealed", "custodian": "grid_operator", "at": 1}], site="cd" * 16)
|
||||
assert g.check(act())[0]
|
||||
|
||||
|
||||
def test_fragment_device_and_plans(tmp_path):
|
||||
m = tmp_path / "mapping.yaml"
|
||||
m.write_text(yaml.safe_dump({"version": 3, "assets": [], "controls": [MAPPING["controls"][0]]}))
|
||||
os.makedirs(tmp_path / "mapping.d")
|
||||
(tmp_path / "mapping.d" / "meter.yaml").write_text(json.dumps({
|
||||
"version": 3, "device": "victron-gx-1", "assets": [],
|
||||
"controls": [{"id": "battery_2", "kind": "battery", "consent": True,
|
||||
"entities": {"charge_from_grid": "switch.v_grid", "soc": "sensor.v_soc"},
|
||||
"params": {"capacity_wh": 5000, "max_charge_w": 2000, "max_discharge_w": 2000}}]}))
|
||||
mp = Mapping.load(str(m))
|
||||
assert {c.id: c.device for c in mp.controls} == {"battery": "", "battery_2": "victron-gx-1"}
|
||||
cfg = Config(site_id=SITE, mapping=str(m), state_dir=str(tmp_path))
|
||||
(tmp_path / "consent.json").write_text(json.dumps({"share": True, "control": True}))
|
||||
from cantabile_edge.consent import Consent
|
||||
ctl = Controller(cfg, mp, Consent(str(tmp_path)), sink=None, clock=Clock())
|
||||
assert ctl.guard.policy is ctl.policy
|
||||
acl(tmp_path, [{"target": "device:victron-gx-1", "level": "sealed", "custodian": "community_operator", "at": 1}])
|
||||
assert [c.id for c in mp.controls if ctl.policy.plannable(c)] == ["battery"]
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, reg):
|
||||
self.reg = reg
|
||||
|
||||
async def registries(self):
|
||||
return self.reg
|
||||
|
||||
|
||||
class Sink:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
async def publish(self, kind, data):
|
||||
self.sent.append((kind, data))
|
||||
|
||||
|
||||
REG = {"devices": [{"id": "d1", "manufacturer": "Victron", "model": "MultiPlus-II", "sw_version": "v3.14"},
|
||||
{"id": "d2", "manufacturer": "Shelly", "model": "Pro 3EM", "sw_version": "1.4.4", "name": "Meter"}],
|
||||
"entities": [{"entity_id": "switch.grid_charge", "device_id": "d1"},
|
||||
{"entity_id": "sensor.batt_soc", "device_id": "d1"},
|
||||
{"entity_id": "sensor.load", "device_id": "d2"}]}
|
||||
|
||||
|
||||
def test_inventory_build(mapping, tmp_path):
|
||||
specs = {"devices": {"victron-gx-1": {"profile": "victron-gx", "profile_version": "0.1.1", "category": "battery",
|
||||
"manufacturer": "Victron Energy", "model": "GX", "ratings": {"battery_kwh": 10},
|
||||
"entities": ["switch.grid_charge", "sensor.batt_soc"], "controls": ["battery"],
|
||||
"protection": "protected", "ha_device": None}}}
|
||||
pol = {"entity:sensor.load": {"level": "protected", "source": "owner", "at": 5, "set_by": "owner"},
|
||||
"entity:switch.secret_name": {"level": "protected", "source": "profile", "at": 1},
|
||||
"control:x": {"level": "sealed", "source": "cloud", "at": 1}}
|
||||
inv = build(mapping, REG, specs, pol, 100)
|
||||
v, ha = inv["devices"]
|
||||
assert (v["manufacturer"], v["model"], v["sw_version"], v["ratings"], v["controls"], v["protection"]) == \
|
||||
("Victron", "MultiPlus-II", "v3.14", {"battery_kwh": 10}, ["battery"], "protected")
|
||||
assert (ha["source"], ha["manufacturer"], ha["assets"]) == ("ha", "Shelly", ["load.power"])
|
||||
text = json.dumps(inv)
|
||||
for leak in ("sensor.", "switch.", "Meter", "secret_name"):
|
||||
assert leak not in text # no entity ids or names leave
|
||||
targets = {p["target"] for p in inv["protection"]}
|
||||
assert "asset:load.power" in targets and "control:x" not in targets
|
||||
|
||||
|
||||
def test_inventory_sent_with_consent_when_changed(mapping, consent, tmp_path):
|
||||
cfg = Config(site_id=SITE, mapping="", state_dir=str(tmp_path))
|
||||
clock = Clock()
|
||||
sink = Sink()
|
||||
inv = Inventory(cfg, mapping, consent, sink, clock=clock)
|
||||
client = FakeClient(REG)
|
||||
run = asyncio.run
|
||||
assert run(inv.maybe_send(client)) and sink.sent[0][0] == "inventory"
|
||||
clock.t += 700
|
||||
assert not run(inv.maybe_send(client)) # unchanged
|
||||
REG["devices"][0]["sw_version"] = "v3.15"
|
||||
assert run(inv.maybe_send(client)) # a firmware update
|
||||
clock.t += 100
|
||||
REG["devices"][0]["sw_version"] = "v3.16"
|
||||
assert not run(inv.maybe_send(client)) # within 10 min: later
|
||||
consent.set(False, "test")
|
||||
clock.t += 1000
|
||||
assert not run(inv.maybe_send(client))
|
||||
@@ -0,0 +1,220 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""A mapping for a site without one (propose.py): proposed from HA's
|
||||
registries and Cantabile's device profiles, or imported from an earlier
|
||||
install, always with consent off."""
|
||||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
import yaml
|
||||
|
||||
from cantabile_edge import agent as agent_mod
|
||||
from cantabile_edge import propose
|
||||
from cantabile_edge.config import Config
|
||||
from cantabile_edge.mapping import Mapping
|
||||
from cantabile_edge.store import Queue
|
||||
|
||||
from test_agent import FlakySink
|
||||
|
||||
PROFILES = propose.load_profiles(str(pathlib.Path(__file__).resolve().parents[2] / "profiles"))
|
||||
HM = next(p["name"] for p in PROFILES if p["id"] == "hm8042-hybrid")
|
||||
SPM = next(p["name"] for p in PROFILES if p["id"] == "sonoff-spm")
|
||||
|
||||
|
||||
def st(eid, state, dc=None, unit=None, name=None, sc="measurement"):
|
||||
return {"entity_id": eid, "state": state, "attributes": {"device_class": dc, "unit_of_measurement": unit,
|
||||
"friendly_name": name or eid, "state_class": sc}}
|
||||
|
||||
|
||||
def home():
|
||||
"""A test home, in small: the bridge's HM8042 (live), SPM 1 mirrored
|
||||
by the bridge, the old YAML modbus sensors (unavailable), a room."""
|
||||
devices = [{"id": "hm", "name": "HM8042", "model": HM, "manufacturer": "HM",
|
||||
"identifiers": [["mqtt", "cantabile_modbus_hm8042"]], "area_id": "cantabile"},
|
||||
{"id": "spmb", "name": "SPM 1", "model": SPM, "manufacturer": "SONOFF",
|
||||
"identifiers": [["mqtt", "cantabile_modbus_spm_1"]], "area_id": "cantabile"},
|
||||
{"id": "zha1", "name": "Thermo", "model": "TH01", "manufacturer": "Acme",
|
||||
"identifiers": [["zha", "x"]], "area_id": "living_room"}]
|
||||
ents = [{"entity_id": f"sensor.hm8042_{k}", "unique_id": f"cantabile_modbus_hm8042_{u}", "device_id": "hm",
|
||||
"platform": "mqtt"} for k, u in (("pv_power", "pv_power"), ("pv_energy", "pv_energy"),
|
||||
("grid_power", "grid_power"), ("grid_energy", "grid_energy"),
|
||||
("output_energy", "load_energy"), ("battery_charge", "battery_soc"),
|
||||
("grid_voltage", "grid_voltage"), ("battery_power", "battery_power"),
|
||||
("grid_power_estimated", "grid_import_power"))]
|
||||
ents += [{"entity_id": "sensor.spm_1_power_1", "unique_id": "cantabile_modbus_spm_1_power_1",
|
||||
"device_id": "spmb", "platform": "mqtt"},
|
||||
{"entity_id": "sensor.thermo_temperature", "unique_id": "t1", "device_id": "zha1", "platform": "zha"},
|
||||
{"entity_id": "sensor.pv_power", "unique_id": "pv_power", "platform": "modbus"},
|
||||
{"entity_id": "sensor.grid_total", "unique_id": "grid_total", "platform": "modbus"},
|
||||
{"entity_id": "sensor.load_power", "unique_id": "load", "platform": "template"}]
|
||||
states = [st("sensor.hm8042_pv_power", "120", "power", "W", "HM8042 PV power"),
|
||||
st("sensor.hm8042_pv_energy", "346930", "energy", "Wh", sc="total_increasing"),
|
||||
st("sensor.hm8042_grid_power", "0", "power", "W", "HM8042 Grid power"),
|
||||
st("sensor.hm8042_grid_energy", "35360", "energy", "Wh", sc="total_increasing"),
|
||||
st("sensor.hm8042_output_energy", "330300", "energy", "Wh", sc="total_increasing"),
|
||||
st("sensor.hm8042_battery_charge", "93", "battery", "%"),
|
||||
st("sensor.hm8042_grid_voltage", "227", "voltage", "V"),
|
||||
st("sensor.hm8042_battery_power", "-47.9", "power", "W", "HM8042 Battery power"),
|
||||
st("sensor.hm8042_grid_power_estimated", "567", "power", "W", "HM8042 Grid power (estimated)"),
|
||||
st("sensor.spm_1_power_1", "7", "power", "W", "SPM 1 Power 1"),
|
||||
st("sensor.thermo_temperature", "21.5", "temperature", "°C", "Thermo temperature"),
|
||||
st("sensor.pv_power", "unavailable", "power", "W", "PV power"),
|
||||
st("sensor.grid_total", "unavailable", "energy", "kWh", "Grid total", "total_increasing"),
|
||||
st("sensor.load_power", "300", "power", "W", "Load power"),
|
||||
st("sensor.fridge_power", "80", "power", "W", "Fridge")]
|
||||
reg = {"devices": devices, "entities": ents,
|
||||
"areas": [{"area_id": "living_room", "name": "Living Room"}, {"area_id": "cantabile", "name": "Cantabile"}]}
|
||||
return states, reg
|
||||
|
||||
|
||||
def test_proposal_from_the_bridge_profiles_and_names():
|
||||
states, reg = home()
|
||||
got = {a["asset"]: a for a in propose.propose(states, reg, PROFILES)}
|
||||
assert got["pv.power"]["entity"] == "sensor.hm8042_pv_power" # the bridge's profile, not the name
|
||||
assert got["pv.energy"] == {"entity": "sensor.hm8042_pv_energy", "asset": "pv.energy", "kind": "counter",
|
||||
"unit": "Wh", "consent": False}
|
||||
assert got["grid.import_energy"]["entity"] == "sensor.hm8042_grid_energy"
|
||||
assert got["load.energy"]["entity"] == "sensor.hm8042_output_energy"
|
||||
assert got["battery.soc"]["entity"] == "sensor.hm8042_battery_charge"
|
||||
assert got["load.power"]["entity"] == "sensor.load_power" # by name, live
|
||||
assert got["battery.power"]["entity"] == "sensor.hm8042_battery_power" # the bridge's derived values
|
||||
assert got["grid.import_power"]["entity"] == "sensor.hm8042_grid_power_estimated"
|
||||
assert got["room.living_room.temp"]["entity"] == "sensor.thermo_temperature"
|
||||
ents = {a["entity"] for a in got.values()}
|
||||
assert "sensor.spm_1_power_1" not in ents # a mirror: its source is mapped
|
||||
assert "sensor.fridge_power" not in ents and "sensor.hm8042_grid_voltage" not in ents
|
||||
assert "sensor.pv_power" not in ents # no value, and taken by the bridge
|
||||
assert not any(a["consent"] for a in got.values())
|
||||
|
||||
|
||||
def test_ensure_proposes_once_and_keeps_a_hand_written_mapping(tmp_path):
|
||||
states, reg = home()
|
||||
m = tmp_path / "mapping.yaml"
|
||||
m.write_text("version: 1\nassets: []\n")
|
||||
assert propose.ensure(str(m), str(tmp_path), states, reg, PROFILES) == "proposed"
|
||||
loaded = Mapping.load(str(m))
|
||||
assert loaded.by_entity["sensor.hm8042_pv_power"].asset == "pv.power"
|
||||
assert not any(a.consent for a in loaded.assets)
|
||||
assert propose.ensure(str(m), str(tmp_path), states, reg, PROFILES) is None # nothing new
|
||||
# a new device joins a proposed mapping; a value missing for a moment stays
|
||||
states = [s for s in states if s["entity_id"] != "sensor.load_power"] + \
|
||||
[st("sensor.load_power", "unavailable", "power", "W", "Load power")]
|
||||
reg["entities"].append({"entity_id": "sensor.ev_power", "unique_id": "ev", "platform": "x"})
|
||||
states.append(st("sensor.ev_power", "0", "power", "W", "Wallbox power"))
|
||||
assert propose.ensure(str(m), str(tmp_path), states, reg, PROFILES) == "proposed"
|
||||
loaded = Mapping.load(str(m))
|
||||
assert loaded.by_entity["sensor.ev_power"].asset == "ev.power"
|
||||
assert loaded.by_entity["sensor.load_power"].asset == "load.power"
|
||||
# written by hand (no `source`): never touched
|
||||
m.write_text(yaml.safe_dump({"version": 1, "assets": [
|
||||
{"entity": "sensor.x", "asset": "pv.power", "kind": "gauge", "unit": "W", "consent": True}]}))
|
||||
assert propose.ensure(str(m), str(tmp_path), states, reg, PROFILES) is None
|
||||
assert Mapping.load(str(m)).consented("sensor.x")
|
||||
|
||||
|
||||
OLD = {"version": 2, "assets": [
|
||||
{"entity": "sensor.pv_power", "asset": "pv.power", "kind": "gauge", "unit": "W", "consent": True},
|
||||
{"entity": "sensor.grid_total", "asset": "grid.import_energy", "kind": "counter", "unit": "Wh", "consent": True},
|
||||
{"entity": "sensor.load_power", "asset": "load.power", "kind": "gauge", "unit": "W", "consent": True},
|
||||
{"entity": "sensor.spm_1_kitchen", "asset": "circuit.kitchen.power", "kind": "gauge", "unit": "W",
|
||||
"consent": True},
|
||||
{"entity": "sensor.room_t", "asset": "room.living_room.temp", "kind": "gauge", "unit": "°C", "consent": True}]}
|
||||
|
||||
|
||||
def test_import_consent_off_dead_entities_replaced_once(tmp_path):
|
||||
states, reg = home()
|
||||
m = tmp_path / "mapping.yaml"
|
||||
m.write_text("version: 1\nassets: []\n")
|
||||
(tmp_path / "mapping-import.yaml").write_text(yaml.safe_dump(OLD))
|
||||
assert propose.ensure(str(m), str(tmp_path), states, reg, PROFILES) == "imported"
|
||||
raw = yaml.safe_load(m.read_text())
|
||||
assert raw["source"] == "imported" and "Consent is not carried" in m.read_text()
|
||||
got = {a["asset"]: a["entity"] for a in raw["assets"]}
|
||||
assert not any(a["consent"] for a in raw["assets"])
|
||||
assert got["pv.power"] == "sensor.hm8042_pv_power" # unavailable here: the bridge's
|
||||
assert got["grid.import_energy"] == "sensor.hm8042_grid_energy"
|
||||
assert got["load.power"] == "sensor.load_power" # live: kept
|
||||
assert got["circuit.kitchen.power"] == "sensor.spm_1_kitchen" # not measured by the bridge: kept
|
||||
assert got["battery.soc"] == "sensor.hm8042_battery_charge" # the bridge's other values added
|
||||
assert got["battery.power"] == "sensor.hm8042_battery_power" # derived by the bridge
|
||||
assert len(raw["assets"]) == len(OLD["assets"]) + 5 # + battery.soc, pv.energy, load.energy, grid, battery power
|
||||
assert "sensor.spm_1_power_1" not in got.values()
|
||||
assert json.loads((tmp_path / "mapping-import.json").read_text())["assets"] == len(raw["assets"])
|
||||
# once per file: not again, and no proposal over an import
|
||||
assert propose.ensure(str(m), str(tmp_path), states, reg, PROFILES) is None
|
||||
# a broken file is refused whole, the mapping stays
|
||||
(tmp_path / "mapping-import.yaml").write_text("assets: [{entity: x}]\n")
|
||||
assert propose.ensure(str(m), str(tmp_path), states, reg, PROFILES) is None
|
||||
assert yaml.safe_load(m.read_text())["source"] == "imported"
|
||||
|
||||
|
||||
class FakeHA:
|
||||
def __init__(self, states, reg):
|
||||
self.states, self.reg = states, reg
|
||||
|
||||
async def send(self, type_, **_):
|
||||
return self.states if type_ == "get_states" else None
|
||||
|
||||
async def registries(self):
|
||||
return self.reg
|
||||
|
||||
|
||||
def test_agent_loads_the_new_mapping(tmp_path):
|
||||
m = tmp_path / "mapping.yaml"
|
||||
m.write_text("version: 1\nassets: []\n")
|
||||
cfg = Config(site_id="ab" * 16, mapping=str(m), state_dir=str(tmp_path), propose=True, dashboards=False)
|
||||
a = agent_mod.Agent(cfg, Mapping.load(str(m)), Queue(str(tmp_path / "q.db"), 100), FlakySink())
|
||||
a.profiles = PROFILES
|
||||
assert asyncio.run(a.ensure_mapping(FakeHA(*home())))
|
||||
assert a.mapping.by_entity["sensor.hm8042_pv_power"].asset == "pv.power"
|
||||
assert a.inventory.mapping is a.mapping
|
||||
assert a.mapping.consented("sensor.hm8042_pv_power") is None # nothing is read for the cloud
|
||||
cfg.propose = False
|
||||
m.write_text("version: 1\nassets: []\n")
|
||||
assert not asyncio.run(a.ensure_mapping(FakeHA(*home()))) # the Hub: off
|
||||
|
||||
|
||||
def test_a_second_inverter_makes_parts():
|
||||
"""One bridge HM8042: pv.power; a second one comes: both are parts
|
||||
(pv.1.power, pv.2.power), the proposal written again with them."""
|
||||
states, reg = home()
|
||||
first = propose.propose(states, reg, PROFILES)
|
||||
assert {a["asset"] for a in first if a["entity"].startswith("sensor.hm8042_")} >= {"pv.power", "battery.soc"}
|
||||
reg["devices"].append({"id": "hm2", "name": "HM8042 B", "model": HM, "manufacturer": "HM",
|
||||
"identifiers": [["mqtt", "cantabile_modbus_hm8042_b"]], "area_id": "cantabile"})
|
||||
reg["entities"] += [{"entity_id": f"sensor.hm8042_b_{k}", "unique_id": f"cantabile_modbus_hm8042_b_{k}",
|
||||
"device_id": "hm2", "platform": "mqtt"} for k in ("pv_power", "battery_soc")]
|
||||
states += [st("sensor.hm8042_b_pv_power", "300", "power", "W"), st("sensor.hm8042_b_battery_soc", "50", "battery", "%")]
|
||||
second = {a["entity"]: a["asset"] for a in propose.propose(states, reg, PROFILES, keep=first)}
|
||||
assert second["sensor.hm8042_pv_power"] == "pv.1.power" and second["sensor.hm8042_b_pv_power"] == "pv.2.power"
|
||||
assert second["sensor.hm8042_battery_charge"] == "battery.1.soc"
|
||||
assert second["sensor.hm8042_b_battery_soc"] == "battery.2.soc"
|
||||
assert "pv.power" not in second.values()
|
||||
|
||||
|
||||
def test_eebus_bridge_devices_by_their_profiles():
|
||||
"""The EEBUS bridge's devices (cantabile_eebus_*): their
|
||||
profile's eebus.values say the quantities; the dashboard's view finds
|
||||
their values by key and the device opens the EEBUS bridge's page."""
|
||||
from cantabile_edge import dashboards, devview
|
||||
hp_model = next(p["name"] for p in PROFILES if p["id"] == "eebus-vaillant-arotherm")
|
||||
wb_model = next(p["name"] for p in PROFILES if p["id"] == "eebus-wallbox")
|
||||
reg = {"devices": [{"id": "hp", "name": "Heat pump", "model": hp_model, "manufacturer": "Vaillant",
|
||||
"identifiers": [["mqtt", "cantabile_eebus_vaillant_hp_ab12cd"]], "area_id": "cantabile"},
|
||||
{"id": "wb", "name": "Wallbox", "model": wb_model, "manufacturer": "Elli",
|
||||
"identifiers": [["mqtt", "cantabile_eebus_elli_wb_0f0f0f"]], "area_id": "cantabile"}],
|
||||
"entities": [{"entity_id": f"sensor.hp_{k}", "unique_id": f"cantabile_eebus_vaillant_hp_ab12cd_{k}", "device_id": "hp",
|
||||
"platform": "mqtt"} for k in ("power", "energy", "limit")] +
|
||||
[{"entity_id": f"sensor.wb_{k}", "unique_id": f"cantabile_eebus_elli_wb_0f0f0f_{k}", "device_id": "wb",
|
||||
"platform": "mqtt"} for k in ("charge_power", "charged_energy", "ev_connected", "current_limit")],
|
||||
"areas": [{"area_id": "cantabile", "name": "Cantabile"}]}
|
||||
states = [st("sensor.hp_power", "3200", "power", "W"), st("sensor.hp_energy", "5000", "energy", "kWh", sc="total_increasing"),
|
||||
st("sensor.wb_charge_power", "11000", "power", "W"),
|
||||
st("sensor.wb_charged_energy", "12", "energy", "kWh", sc="total_increasing")]
|
||||
got = {a["asset"]: a["entity"] for a in propose.propose(states, reg, PROFILES)}
|
||||
assert got["heatpump.power"] == "sensor.hp_power" and got["heatpump.energy"] == "sensor.hp_energy"
|
||||
assert got["ev.power"] == "sensor.wb_charge_power" and got["ev.energy"] == "sensor.wb_charged_energy"
|
||||
hp = reg["devices"][0]
|
||||
dv = devview.view_of(hp, [e for e in reg["entities"] if e["device_id"] == "hp"], {}, PROFILES)
|
||||
assert dv.profile == "eebus-vaillant-arotherm" and dv.headline[:2] == ["sensor.hp_power", "sensor.hp_limit"]
|
||||
assert dashboards._bridge_link(hp) == "eebus" and dashboards._bridge_link({"identifiers": [["mqtt", "cantabile_modbus_x"]]}) == "bridge"
|
||||
@@ -0,0 +1,441 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Shades (ha-cover, shades.py), temperature sensors (ha-climate-sensor) and
|
||||
weather services (ha-weather): which devices the profiles offer (never a
|
||||
garage door, never the box's own CPU temperature), their fragments and the
|
||||
owner's settings, the shade's rules on the sun, the guard around them, the
|
||||
dashboard and the plan in words."""
|
||||
import json
|
||||
import pathlib
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from cantabile_edge import dashboards, devprofiles as dp, propose, shades
|
||||
from cantabile_edge.consent import Consent
|
||||
from cantabile_edge.executor import actions_for
|
||||
from cantabile_edge.guard import Action, Guard
|
||||
from cantabile_edge.inputs import Collector, model_state
|
||||
from cantabile_edge.mapping import Mapping
|
||||
from cantabile_edge.policy import Policy
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
PROFILES = {p["id"]: p for p in propose.load_profiles(str(ROOT / "profiles"))}
|
||||
BERLIN = {"latitude": 52.52, "longitude": 13.40}
|
||||
|
||||
|
||||
# -- which profile, which device ---------------------------------------------------------------
|
||||
|
||||
def registry(*devices):
|
||||
"""devices: (id, manufacturer, model, platform, [(entity_id, device_class, category)], entry_type)."""
|
||||
reg = {"areas": [{"area_id": "bedroom", "name": "Bedroom"}], "devices": [], "entities": []}
|
||||
for dev_id, maker, model, platform, ents, *kind in devices:
|
||||
reg["devices"].append({"id": dev_id, "name": dev_id, "manufacturer": maker, "model": model,
|
||||
"domains": [platform], "area_id": "bedroom", "entry_type": kind[0] if kind else None})
|
||||
for eid, dc, *cat in ents:
|
||||
reg["entities"].append({"entity_id": eid, "device_id": dev_id, "unique_id": eid, "platform": platform,
|
||||
"device_class": dc, "entity_category": cat[0] if cat else None})
|
||||
return reg
|
||||
|
||||
|
||||
def offered(reg):
|
||||
return {o["id"]: o["profiles"] for o in dp.offers(reg, PROFILES.values())}
|
||||
|
||||
|
||||
def test_covers_offered_never_a_garage_door():
|
||||
reg = registry(
|
||||
("rbs", "SONOFF", "MINI-RBS", "sonoff", [("cover.left_curtain", None)]), # SonoffLAN: no class
|
||||
("blind", "Somfy", "RTS", "somfy", [("cover.kitchen_blind", "blind")]),
|
||||
("garage", "Meross", "MSG100", "meross", [("cover.garage", "garage")]),
|
||||
("gate", "Nice", "Gate", "nice", [("cover.gate", "gate")]),
|
||||
("both", "Shelly", "2PM", "shelly", [("cover.awning", "awning"), ("cover.door", "door")]),
|
||||
("damper", "Acme", "Vent", "acme", [("cover.vent", "damper")]),
|
||||
("window", "Velux", "Window", "velux", [("cover.roof_window", "window")]))
|
||||
got = offered(reg)
|
||||
assert got["rbs"] == ["ha-cover"] and got["blind"] == ["ha-cover"]
|
||||
for dev in ("garage", "gate", "both", "damper", "window"):
|
||||
assert got[dev] == [], dev # not even generic: never offered
|
||||
# a specific profile first: an SPM's sonoff device stays the SPM's
|
||||
spm = {"manufacturer": "SONOFF", "model": "SPM-Main"}
|
||||
fits = dp.fitting(PROFILES.values(), spm, ["sonoff"], ["cover", "sensor.power"])
|
||||
assert all(not dp.fallback(p) for p in fits) or fits == []
|
||||
|
||||
|
||||
def test_temperature_sensors_offered_not_system_or_device_internal():
|
||||
reg = registry(
|
||||
("esp", "Espressif", "esp32", "esphome", [("sensor.office_temp", "temperature"), ("sensor.office_hum", "humidity"),
|
||||
("sensor.esp_internal", "temperature", "diagnostic"),
|
||||
("sensor.esp_battery", "battery")]),
|
||||
("zb", "Xiaomi", "LYWSD03MMC", "zha", [("sensor.bath_temp", "temperature")]),
|
||||
("ble", "Govee", "H5075", "govee_ble", [("sensor.balcony_temp", "temperature")]),
|
||||
("snzb", "SONOFF", "SNZB-02D", "zha", [("sensor.living_temp", "temperature")]),
|
||||
("ac", "Espressif", "esp32", "esphome", [("climate.ac", None), ("sensor.ac_temp", "temperature")]),
|
||||
("sysmon", "Home Assistant", "System Monitor", "systemmonitor", [("sensor.processor_temperature", "temperature")]),
|
||||
("inverter", "Growatt", "MIN", "growatt", [("sensor.inv_temp", "temperature"), ("sensor.inv_power", "power")]),
|
||||
("diag", "Acme", "Router", "acme", [("sensor.router_temp", "temperature", "diagnostic")]),
|
||||
("met", "Met.no", "Forecast", "met", [("weather.home", None), ("sensor.met_temp", "temperature")], "service"),
|
||||
("backup", "Home Assistant", "Backup", "backup", [("sensor.backup_state", None)], "service"))
|
||||
got = offered(reg)
|
||||
assert got["esp"] == got["zb"] == got["ble"] == ["ha-climate-sensor"]
|
||||
assert got["snzb"] == ["sonoff-snzb-02"] # its own profile
|
||||
assert got["ac"] == ["ha-thermostat"] # a thermostat stays one
|
||||
assert got["sysmon"] == [] and got["inverter"] == [] and got["diag"] == []
|
||||
assert got["met"] == ["ha-weather"] # a weather service is offered
|
||||
assert "backup" not in got # other services are not
|
||||
|
||||
|
||||
# -- fragments and the owner's settings -------------------------------------------------------
|
||||
|
||||
def cover_ent(eid="cover.left_curtain", **attrs):
|
||||
return {"entity_id": eid, "device_id": "d", "unique_id": eid,
|
||||
"attributes": dict({"current_position": 100, "supported_features": 15}, **attrs)}
|
||||
|
||||
|
||||
def test_cover_fragment_protected_with_its_room():
|
||||
p = PROFILES["ha-cover"]
|
||||
s = dp.setup_for(p, ["sonoff"])
|
||||
frag, missing = dp.mapping_for("ha-cover-1", p, s, [cover_ent()], "Bedroom", set())
|
||||
(c,) = frag["controls"]
|
||||
assert c["kind"] == "cover" and c["entities"] == {"cover": "cover.left_curtain"} and c["consent"] is False
|
||||
assert c["params"]["area"] == "bedroom" and c["params"]["min_move_s"] == 1800
|
||||
assert [a["asset"] for a in frag["assets"]] == ["room.bedroom.shade_position"] and missing == ["room.{area}.shade_tilt"]
|
||||
prot = dp.profile_protection("ha-cover-1", p, s, [cover_ent()], frag, now=1)
|
||||
assert prot[f"control:{c['id']}"]["level"] == "protected"
|
||||
# the owner: room and window
|
||||
thermo = {"profile": "ha-thermostat", "assets": [{"asset": "room.living_room.temp"}],
|
||||
"controls": [{"id": "heating", "kind": "heating"}, {"id": "cooling", "kind": "cooling"}]}
|
||||
sh = dp.set_shade(frag, {"area": "Living room", "facing": "SW"}, [thermo])
|
||||
assert sh == {"area": "living_room", "facing": 225.0, "room": "heating"}
|
||||
assert dp.set_shade(frag, {"area": "", "facing": "275"}) == {"area": "", "facing": 275.0, "room": ""}
|
||||
with pytest.raises(dp.Fail):
|
||||
dp.set_shade(frag, {"facing": "up"})
|
||||
with pytest.raises(dp.Fail):
|
||||
dp.set_shade({"controls": [{"kind": "heating"}]}, {"facing": "N"})
|
||||
|
||||
|
||||
def test_sensor_indoor_outdoor_and_second_reading():
|
||||
p = PROFILES["ha-climate-sensor"]
|
||||
ents = [{"entity_id": "sensor.office_temp", "device_id": "d", "unique_id": "t", "device_class": "temperature"},
|
||||
{"entity_id": "sensor.office_hum", "device_id": "d", "unique_id": "h", "device_class": "humidity"},
|
||||
{"entity_id": "sensor.esp_internal", "device_id": "d", "unique_id": "i", "device_class": "temperature",
|
||||
"entity_category": "diagnostic"}]
|
||||
taken = {"room.office.temp"} # the room has a temperature already
|
||||
frag, _ = dp.mapping_for("ha-climate-sensor-1", p, dp.setup_for(p, ["esphome"]), ents, "Office", set(taken))
|
||||
assert {a["asset"]: a["entity"] for a in frag["assets"]} == {"room.office.temp_2": "sensor.office_temp",
|
||||
"room.office.humidity": "sensor.office_hum"}
|
||||
assert dp.place_of(frag) == {"place": "indoor", "area": "office"}
|
||||
dp.set_place(frag, {"place": "outdoor"}, taken)
|
||||
assert {a["asset"] for a in frag["assets"]} == {"outside.temp", "outside.humidity"}
|
||||
assert frag["inputs"] == {"outside_temp": "sensor.office_temp"} and dp.place_of(frag)["place"] == "outdoor"
|
||||
dp.set_place(frag, {"place": "indoor", "area": "Bedroom"}, taken)
|
||||
assert {a["asset"] for a in frag["assets"]} == {"room.bedroom.temp", "room.bedroom.humidity"} and "inputs" not in frag
|
||||
with pytest.raises(dp.Fail):
|
||||
dp.set_place(frag, {"place": "attic"})
|
||||
|
||||
|
||||
def test_one_weather_source_and_a_measured_outdoor_wins(tmp_path):
|
||||
p = PROFILES["ha-weather"]
|
||||
s = dp.setup_for(p, ["met"])
|
||||
w = {"entity_id": "weather.home", "device_id": "m", "unique_id": "w",
|
||||
"attributes": {"temperature": 8.0, "humidity": 70, "cloud_coverage": 40}}
|
||||
met, _ = dp.mapping_for("ha-weather-1", p, s, [w], None, set())
|
||||
assert met["inputs"] == {"weather": "weather.home"}
|
||||
assert {a["asset"] for a in met["assets"] if a.get("fallback")} == {"outside.temp", "outside.humidity"}
|
||||
owm, _ = dp.mapping_for("ha-weather-2", p, s, [dict(w, entity_id="weather.owm")], None,
|
||||
{"outside.temp", "outside.humidity"})
|
||||
dp.one_weather(owm, [met])
|
||||
assert "inputs" not in owm and dp.weather_of(owm) == {"active": False, "entity": "weather.owm"}
|
||||
frags = {"ha-weather-1": met, "ha-weather-2": owm}
|
||||
dp.set_weather(frags, "ha-weather-2")
|
||||
assert dp.weather_of(met)["active"] is False and owm["inputs"] == {"weather": "weather.owm"}
|
||||
dp.set_weather(frags, "ha-weather-1")
|
||||
assert dp.weather_of(met)["active"] is True and "inputs" not in owm
|
||||
# the agent: an outdoor thermometer takes outside.temp and the outside temperature
|
||||
sensor = {"version": 3, "device": "ha-climate-sensor-1", "profile": "ha-climate-sensor",
|
||||
"assets": [{"entity": "sensor.balcony_temp", "asset": "outside.temp_2", "kind": "gauge", "unit": "°C"}],
|
||||
"inputs": {"outside_temp": "sensor.balcony_temp"}}
|
||||
(tmp_path / "mapping.d").mkdir()
|
||||
(tmp_path / "mapping.yaml").write_text(yaml.safe_dump({"version": 3, "assets": [],
|
||||
"inputs": {"outside_temp": "sensor.forecast_helper"}}))
|
||||
for name, f in (("a-weather", met), ("b-sensor", sensor)):
|
||||
(tmp_path / "mapping.d" / f"{name}.yaml").write_text(json.dumps(f))
|
||||
m = Mapping.load(str(tmp_path / "mapping.yaml"))
|
||||
assert m.by_asset["outside.temp"].entity == "sensor.balcony_temp"
|
||||
assert m.by_asset["outside.temp_2"].entity == "weather.home" and m.by_asset["outside.temp_2"].fallback
|
||||
assert m.inputs.outside_temp == "sensor.balcony_temp" and m.inputs.weather == "weather.home"
|
||||
|
||||
|
||||
# -- the rules ----------------------------------------------------------------------------------
|
||||
|
||||
def ts(y, mo, d, h=0, tz="Europe/Berlin"):
|
||||
return int(datetime(y, mo, d, h, tzinfo=ZoneInfo(tz)).timestamp())
|
||||
|
||||
|
||||
def state(start, steps=96, t_out=30.0, occupied=1, prices=None, location=BERLIN):
|
||||
return {"start": start, "step_s": 900, "steps": steps, "tz": "Europe/Berlin", "t_out": [t_out] * steps,
|
||||
"occupied": [occupied] * steps if isinstance(occupied, int) else occupied,
|
||||
"price_import": prices or [30.0] * steps, "sky": [1.0] * steps, "location": location}
|
||||
|
||||
|
||||
def shade(facing=270, pos=100, **params):
|
||||
return {"id": "curtain", "kind": "cover", "params": dict({"facing": facing}, **params),
|
||||
"state": {"position_pct": pos}, "bounds": {"position_pct": [0, 100]}}
|
||||
|
||||
|
||||
def moves(sch, start):
|
||||
out = []
|
||||
for k, v in enumerate(sch["set"]):
|
||||
if v is not None:
|
||||
local = datetime.fromtimestamp(start + k * 900, timezone.utc).astimezone(ZoneInfo("Europe/Berlin"))
|
||||
out.append((local.strftime("%H:%M"), v, sch["why"][k]))
|
||||
return out
|
||||
|
||||
|
||||
def test_sun_position():
|
||||
# Berlin, midsummer: the sun in the south at about 13:10 CEST, 61° high; in the west in the evening
|
||||
el, az = shades.sun_position(ts(2026, 6, 21, 13) + 600, 52.52, 13.40)
|
||||
assert 59 < el < 62 and 170 < az < 190
|
||||
el, az = shades.sun_position(ts(2026, 6, 21, 19), 52.52, 13.40)
|
||||
assert 10 < el < 25 and 270 < az < 300
|
||||
assert shades.sun_position(ts(2026, 6, 21, 1), 52.52, 13.40)[0] < 0
|
||||
assert shades.facing("sw") == 225 and shades.facing(-1) is None and shades.compass(260) == "W"
|
||||
|
||||
|
||||
def test_summer_west_facade_closes_in_the_afternoon_sun():
|
||||
start = ts(2026, 7, 15)
|
||||
sch = shades.schedule(shade(270), state(start), {"temp_c": 26.0, "setpoint_c": 24.0})
|
||||
m = moves(sch, start)
|
||||
assert m[0][1] == 30 and m[0][2] == "sun on the west facade" and "13:00" <= m[0][0] <= "15:00", m
|
||||
assert m[1][1] == 100 and m[1][2] == "the sun has left the west facade" and "19:00" <= m[1][0] <= "21:30", m
|
||||
assert len(m) == 2
|
||||
# nobody home: closed all the way
|
||||
assert moves(shades.schedule(shade(270), state(start, occupied=0), {"temp_c": 26.0, "setpoint_c": 24.0}),
|
||||
start)[0][1] == 0
|
||||
# a cool room on a mild day: nothing at stake
|
||||
assert moves(shades.schedule(shade(270), state(start, t_out=20.0), {"temp_c": 21.0, "setpoint_c": 24.0}), start) == []
|
||||
# ... unless the evening is dear: shaded before it
|
||||
dear = [30.0] * 64 + [60.0] * 32
|
||||
m = moves(shades.schedule(shade(270), state(start, t_out=20.0, prices=dear), {"temp_c": 21.0, "setpoint_c": 24.0}),
|
||||
start)
|
||||
assert m and m[0][2] == "sun on the west facade: before the dear hours"
|
||||
# the morning sun is on the east facade, not on the west one
|
||||
m = moves(shades.schedule(shade(90), state(start), {"temp_c": 26.0, "setpoint_c": 24.0}), start)
|
||||
assert "07:00" <= m[0][0] <= "09:00" and m[0][2] == "sun on the east facade", m
|
||||
|
||||
|
||||
def test_winter_opens_in_the_sun_closes_at_night_never_in_quiet_hours():
|
||||
start = ts(2026, 1, 15)
|
||||
sch = shades.schedule(shade(180, pos=0), state(start, steps=192, t_out=2.0), {"season": "heating"})
|
||||
m = moves(sch, start)
|
||||
assert m[0][1] == 100 and m[0][2] == "winter sun on the south facade: its warmth in" and m[0][0] >= "08:00", m
|
||||
assert m[1][1] == 0 and m[1][2] == "night: closed to keep the warmth in" and "16:00" <= m[1][0] <= "18:00", m
|
||||
assert m[2][1] == 100 and m[2][0] >= "07:00", m # the next morning, after the quiet hours
|
||||
assert not any("22:00" <= t or t < "07:00" for t, _, _ in m)
|
||||
# quiet from 16:00: the night's closing waits for its end (and is never in the dark opened)
|
||||
noon = ts(2026, 1, 15, 12)
|
||||
m = moves(shades.schedule(shade(180, pos=100, quiet_from="16:00", quiet_to="23:00"),
|
||||
state(noon, steps=48, t_out=2.0), {"season": "heating"}), noon)
|
||||
assert m == [("23:00", 0, "night: closed to keep the warmth in")]
|
||||
# the owner allows moves at night
|
||||
m = moves(shades.schedule(shade(180, pos=100, quiet_from="16:00", quiet_to="23:00", night_moves=1),
|
||||
state(noon, steps=48, t_out=2.0), {"season": "heating"}), noon)
|
||||
assert m[0][1] == 0 and m[0][0] < "18:00"
|
||||
# the facade not known: only the night's closing and the morning's opening
|
||||
m = moves(shades.schedule(shade(-1, pos=100), state(start, steps=192, t_out=2.0), {"season": "heating"}), start)
|
||||
assert [v for _, v, _ in m] == [0, 100, 0] and m[1][2] == "morning: open again" # the evening, the morning, the evening
|
||||
# no location: nothing at all
|
||||
assert moves(shades.schedule(shade(180), state(start, location={}), {}), start) == []
|
||||
|
||||
|
||||
def test_minimum_interval_between_moves():
|
||||
start = ts(2026, 7, 15)
|
||||
flip = [k % 2 for k in range(96)] # occupancy changing every quarter hour
|
||||
sch = shades.schedule(shade(270, min_move_s=3600), state(start, occupied=flip), {"temp_c": 26.0, "setpoint_c": 24.0})
|
||||
at = [k for k, v in enumerate(sch["set"]) if v is not None]
|
||||
assert len(at) >= 2 and all(b - a >= 4 for a, b in zip(at, at[1:]))
|
||||
|
||||
|
||||
# -- the plan, the guard, the executor -----------------------------------------------------------
|
||||
|
||||
MAPPING = {"version": 3, "assets": [],
|
||||
"controls": [{"id": "curtain", "kind": "cover", "consent": True, "entities": {"cover": "cover.curtain"},
|
||||
"params": {"facing": 270, "area": "bedroom"}},
|
||||
{"id": "rbs", "kind": "cover", "consent": True, "entities": {"cover": "cover.rbs"}}]}
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self, t):
|
||||
self.t = t
|
||||
|
||||
def __call__(self):
|
||||
return self.t
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def site(tmp_path):
|
||||
(tmp_path / "mapping.yaml").write_text(yaml.safe_dump(MAPPING))
|
||||
(tmp_path / "consent.json").write_text(json.dumps({"share": True, "control": True}))
|
||||
return tmp_path
|
||||
|
||||
|
||||
def move(control="curtain", entity="cover.curtain", value=30.0, service="set_cover_position"):
|
||||
return Action(control, "cover", entity, "cover", service, {"position": int(value)}, value, "position_pct")
|
||||
|
||||
|
||||
def test_guard_override_pause_min_interval_shadow_and_protection(site):
|
||||
m = Mapping.load(str(site / "mapping.yaml"))
|
||||
clk = Clock(1_800_000_000.0)
|
||||
mode = ["auto"]
|
||||
g = Guard(m.controls, Consent(str(site)), lambda: mode[0], clock=clk)
|
||||
assert g.check(move()) == (True, "")
|
||||
g.done(move())
|
||||
clk.t += 600
|
||||
ok, why = g.check(move(value=100.0))
|
||||
assert not ok and "at most once in 1800" in why # the minimum interval
|
||||
# the owner moves it by hand: off it for 4 hours (not the 2 of a thermostat)
|
||||
g.observe("curtain", "cover.curtain", 31, clk.t) # where it was told: no override
|
||||
assert not g.overridden("curtain")
|
||||
g.observe("curtain", "cover.curtain", 80, clk.t)
|
||||
assert g.overridden("curtain") and g.events[-1]["until"] == int(clk.t + 14400)
|
||||
clk.t += 3 * 3600
|
||||
assert "by hand" in g.check(move(value=0.0))[1]
|
||||
clk.t += 3600 + 1
|
||||
assert g.check(move(value=0.0)) == (True, "")
|
||||
# never in shadow or advisory
|
||||
for mo in ("shadow", "advisory"):
|
||||
mode[0] = mo
|
||||
assert g.check(move(value=0.0))[1].startswith(f"mode {mo}")
|
||||
mode[0] = "auto"
|
||||
# protected: never moved at all (open as much as closed)
|
||||
(site / "protection.json").write_text(json.dumps({"v": 1, "entries": {"control:curtain": {"level": "protected", "at": 1}}}))
|
||||
g.policy = Policy(str(site), "ab" * 16, clk)
|
||||
for v, svc in ((100.0, "set_cover_position"), (0.0, "close_cover"), (100.0, "open_cover")):
|
||||
ok, why = g.check(move(value=v, service=svc))
|
||||
assert not ok and why.startswith("protected: Cantabile does not move it"), svc
|
||||
|
||||
|
||||
def test_executor_open_close_only_and_waits_while_moving(site):
|
||||
m = Mapping.load(str(site / "mapping.yaml"))
|
||||
curtain, rbs = m.controls
|
||||
col = Collector()
|
||||
col.on_entities({"a": {"cover.curtain": {"s": "open", "a": {"current_position": 100, "supported_features": 15}},
|
||||
"cover.rbs": {"s": "open", "a": {"supported_features": 11}}}})
|
||||
assert [(a.service, a.value) for a in actions_for(curtain, {"set": 30}, col)] == [("set_cover_position", 30.0)]
|
||||
assert [(a.service, a.value) for a in actions_for(rbs, {"set": 30}, col)] == [("close_cover", 0.0)]
|
||||
assert actions_for(rbs, {"set": 80}, col) == [] # open already
|
||||
assert actions_for(curtain, {"set": None}, col) == [] # a hold between moves
|
||||
col.on_entities({"c": {"cover.curtain": {"+": {"s": "closing"}}}})
|
||||
assert actions_for(curtain, {"set": 0}, col) == [] # moving: wait
|
||||
|
||||
|
||||
def test_model_state_gives_each_shade_its_schedule(site):
|
||||
m = Mapping.load(str(site / "mapping.yaml"))
|
||||
|
||||
class Bundles:
|
||||
def prices(self, *a):
|
||||
from types import SimpleNamespace
|
||||
return SimpleNamespace(import_ct=[30.0] * 192, export_ct=[8.0] * 192, note="t")
|
||||
|
||||
def forecast(self, *a):
|
||||
return None
|
||||
|
||||
def model_id(self):
|
||||
return ""
|
||||
col = Collector()
|
||||
col.on_entities({"a": {"cover.curtain": {"s": "open", "a": {"current_position": 100}},
|
||||
"sensor.out": {"s": "31"}}})
|
||||
m.inputs.outside_temp = "sensor.out"
|
||||
forecast = [{"datetime": datetime.fromtimestamp(ts(2026, 7, 15) + h * 3600, timezone.utc).isoformat(),
|
||||
"temperature": 25.0, "cloud_coverage": 0} for h in range(49)]
|
||||
s = model_state(ts(2026, 7, 15), m.controls, m.inputs, col, Bundles(), None, "Europe/Berlin", forecast,
|
||||
location=BERLIN, shade_ctx={"curtain": {"temp_c": 26.0, "setpoint_c": 24.0}})
|
||||
d = next(x for x in s["devices"] if x["id"] == "curtain")
|
||||
assert any(v == 30 for v in d["schedule"]["set"]) and s["sky"][0] == 1.0
|
||||
# a thermometer outside: the forecast moved to what it measures now
|
||||
assert s["t_out"][0] == 31.0 and s["t_out"][30] == 25.0 and "outdoor sensor" in s["sources"]["t_out"]
|
||||
|
||||
|
||||
def test_optimizer_takes_the_schedule():
|
||||
pytest.importorskip("highspy")
|
||||
from cantabile_edge import optimizer
|
||||
start = ts(2026, 7, 15)
|
||||
s = state(start, steps=96)
|
||||
s.update(price_export=[8.0] * 96, price_note="t", load_w=[400.0] * 96, pv_w=[0.0] * 96, sun=[0.5] * 96)
|
||||
room = {"id": "ac", "kind": "cooling", "channels": ["climate"],
|
||||
"params": {"r_k_per_kw": 10, "c_kwh_per_k": 3, "max_power_w": 1500, "comfort_c": 25, "setup_c": 28, "cop": 3},
|
||||
"state": {"temp_c": 26.0}, "bounds": {"temp_c": [18, 30, "owner", "owner"]}}
|
||||
d = dict(shade(270), params={"facing": 270, "room": "ac", "gain_w": 800}, channels=["cover"])
|
||||
d["schedule"] = shades.schedule(d, s, {"temp_c": 26.0, "setpoint_c": 24.0})
|
||||
s["devices"] = [room, d]
|
||||
p = optimizer.plan(s, 20)
|
||||
sets = [e for e in p["devices"]["curtain"] if e["set"] is not None]
|
||||
assert [e["set"] for e in sets] == [30, 100] and sets[0]["why"] == "sun on the west facade"
|
||||
|
||||
|
||||
# -- in words: the plan, the dashboard, the page ---------------------------------------------------
|
||||
|
||||
def test_words():
|
||||
assert shades.say(30) == "close to 30 %" and shades.say(100) == "open" and shades.say(0) == "close"
|
||||
assert shades.say(30, "de") == "auf 30 % schließen"
|
||||
assert shades.why_words("sun on the west facade", "de") == "Sonne auf der Westseite"
|
||||
assert shades.why_words("night: closed to keep the warmth in", "de").startswith("Nacht")
|
||||
|
||||
|
||||
def test_announce_coming_up_in_words(tmp_path):
|
||||
from test_announce import make
|
||||
from test_control_parts import MAPPING as BASE
|
||||
import time
|
||||
a, ann = make(tmp_path, dict(BASE, controls=BASE["controls"][:4] + [dict(BASE["controls"][4], name="Bedroom curtains")]))
|
||||
now = time.time()
|
||||
a.control.plan = {"made": now, "devices": {"blind": [{"t": now - 60, "set": None, "why": ""},
|
||||
{"t": now + 600, "set": 30, "why": "sun on the west facade"},
|
||||
{"t": now + 1500, "set": None, "why": ""}]}}
|
||||
st = ann._plan_state()
|
||||
assert st["next"].startswith("Bedroom curtains: close to 30 % at ") and st["next"].endswith("— sun on the west facade")
|
||||
assert [n["set"] for n in st["attrs"]["next"]] == ["close to 30 %"] # holds are not listed
|
||||
assert st["controls"]["blind"]["now"] == "-"
|
||||
|
||||
|
||||
def test_dashboard_cover_features():
|
||||
assert dashboards.cover_features({"supported_features": 15}) == [{"type": "cover-position"}]
|
||||
assert dashboards.cover_features({"supported_features": 11}) == [{"type": "cover-open-close"}]
|
||||
assert dashboards.cover_features({"supported_features": 15 | 128}) == [{"type": "cover-position"},
|
||||
{"type": "cover-tilt-position"}]
|
||||
|
||||
|
||||
def test_addon_devices_page_shade(tmp_path):
|
||||
import contextvars
|
||||
from cantabile_edge import i18n
|
||||
from test_devpage import Site, ent, st
|
||||
s = Site(tmp_path)
|
||||
s.ha.reg["areas"].append({"area_id": "bedroom", "name": "Bedroom"})
|
||||
s.ha.reg["devices"] += [
|
||||
{"id": "rbs", "name": "Left curtain", "manufacturer": "SONOFF", "model": "MINI-RBS", "area_id": "bedroom",
|
||||
"config_entries": ["e4"]},
|
||||
{"id": "garage", "name": "Garage", "manufacturer": "Meross", "model": "MSG100", "config_entries": ["e5"]}]
|
||||
s.ha.reg["entities"] += [ent("cover.left_curtain", "rbs", "c1", "sonoff"), ent("cover.garage", "garage", "g1", "meross")]
|
||||
s.ha.states += [st("cover.left_curtain", "unavailable", supported_features=15), # its class: none (SonoffLAN)
|
||||
st("cover.garage", "unavailable", device_class="garage")] # unavailable: still a garage
|
||||
out = s.req()
|
||||
assert 'name="ha_device" value="rbs"' in out and 'name="ha_device" value="garage"' not in out
|
||||
s.post(do="use", ha_device="rbs", profile="ha-cover", name="Left curtain")
|
||||
dev_id = next(i for i, d in s.devices().items() if d["profile"] == "ha-cover")
|
||||
out = s.req()
|
||||
assert "Room and window" in out and '<option value="Bedroom" selected>Bedroom</option>' in out
|
||||
assert "It may control: blinds and curtains." in out and "Allow Cantabile to move it" in out
|
||||
s.post(do="use", ha_device="dev-ac", profile="ha-thermostat") # the living room's A/C
|
||||
ac = next(i for i, d in s.devices().items() if d["profile"] == "ha-thermostat")
|
||||
s.post(do="shade", id=dev_id, area="Living room", facing="SE")
|
||||
p = next(c for c in s.frag(dev_id)["controls"] if c["kind"] == "cover")["params"]
|
||||
assert (p["area"], p["facing"]) == ("living_room", 135.0)
|
||||
assert p["room"] in {c["id"] for c in s.frag(ac)["controls"]} # its sun counts in the A/C's room
|
||||
m = Mapping.load(str(s.mapping)) # another device's room: kept
|
||||
assert next(c for c in m.controls if c.kind == "cover").p("room") == p["room"]
|
||||
assert "the window faces" in s.post(do="shade", id=dev_id, facing="up")
|
||||
|
||||
def run():
|
||||
i18n.use("de")
|
||||
return s.req()
|
||||
de = contextvars.copy_context().run(run)
|
||||
assert "Raum und Fenster" in de and "Südosten" in de and "Bewegen durch Cantabile erlauben" in de
|
||||
@@ -0,0 +1,32 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
from cantabile_edge.store import Queue
|
||||
|
||||
|
||||
def test_order_ack_and_no_reuse(tmp_path):
|
||||
q = Queue(str(tmp_path / "q.db"), 100)
|
||||
seqs = [q.put("tel", {"i": i}) for i in range(5)]
|
||||
assert seqs == sorted(seqs)
|
||||
assert [p["i"] for _, _, p in q.peek(3)] == [0, 1, 2]
|
||||
q.ack(seqs[1])
|
||||
assert [s for s, _, _ in q.peek()] == seqs[2:]
|
||||
q.ack(seqs[-1])
|
||||
assert q.depth() == 0
|
||||
assert q.put("tel", {}) > seqs[-1] # a number is never used twice
|
||||
|
||||
|
||||
def test_survives_reopen(tmp_path):
|
||||
p = str(tmp_path / "q.db")
|
||||
q = Queue(p, 100)
|
||||
q.put("tel", {"a": 1})
|
||||
q.put("stats", {"b": 2})
|
||||
q.close()
|
||||
q = Queue(p, 100)
|
||||
assert [(k, d) for _, k, d in q.peek()] == [("tel", {"a": 1}), ("stats", {"b": 2})]
|
||||
|
||||
|
||||
def test_bounded_drops_oldest_and_counts(tmp_path):
|
||||
q = Queue(str(tmp_path / "q.db"), 3)
|
||||
for i in range(5):
|
||||
q.put("tel", {"i": i})
|
||||
assert [p["i"] for _, _, p in q.peek()] == [2, 3, 4]
|
||||
assert q.dropped() == 2
|
||||
@@ -0,0 +1,162 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""A thermostat that heats and cools (switchover.py): heating or cooling by
|
||||
the owner's choice, by season (the boundary at the site's local month) or by
|
||||
the outdoor temperature with hysteresis; only one of its two controls is
|
||||
ever active (not planned, never acting, refused by the guard and for
|
||||
commands), and two controls that are no such pair never write one entity."""
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from cantabile_edge.config import Config
|
||||
from cantabile_edge.controller import Controller
|
||||
from cantabile_edge.executor import Executor
|
||||
from cantabile_edge.guard import Action
|
||||
from cantabile_edge.inputs import Collector
|
||||
from cantabile_edge.mapping import Mapping
|
||||
from cantabile_edge.switchover import Switchover, check, side
|
||||
|
||||
from test_control_parts import SITE, Clock, consent, mk_guard # noqa: F401
|
||||
|
||||
TZ = "Europe/Chisinau"
|
||||
|
||||
|
||||
def at(y, m, d, h=12, tz=TZ):
|
||||
return datetime(y, m, d, h, tzinfo=ZoneInfo(tz)).timestamp()
|
||||
|
||||
|
||||
def mapping_file(tmp_path, sw=None, outside=True):
|
||||
sw = sw or {"mode": "season"}
|
||||
m = {"version": 3,
|
||||
"assets": [{"entity": "sensor.outside", "asset": "outside.temp", "kind": "gauge", "unit": "°C", "consent": True}]
|
||||
if outside else [],
|
||||
"controls": [{"id": "heating", "kind": "heating", "consent": True, "entities": {"climate": "climate.ac"},
|
||||
"switchover": sw},
|
||||
{"id": "cooling", "kind": "cooling", "consent": True, "entities": {"climate": "climate.ac"},
|
||||
"switchover": sw}]}
|
||||
(tmp_path / "mapping.yaml").write_text(yaml.safe_dump(m, allow_unicode=True))
|
||||
return Mapping.load(str(tmp_path / "mapping.yaml"))
|
||||
|
||||
|
||||
def test_season_boundary():
|
||||
for when, want in ((at(2026, 4, 30, 23), "heating"), (at(2026, 5, 1, 0), "cooling"),
|
||||
(at(2026, 9, 30, 23), "cooling"), (at(2026, 10, 1, 0), "heating"),
|
||||
(at(2026, 1, 15), "heating"), (at(2026, 7, 15), "cooling")):
|
||||
assert side({"mode": "season"}, datetime.fromtimestamp(when, ZoneInfo(TZ)).month, None, None) == want
|
||||
# the site's own month: 1 May 00:00 in Chisinau is still 30 April in UTC
|
||||
assert side({"mode": "season"}, datetime.fromtimestamp(at(2026, 5, 1, 0), ZoneInfo("UTC")).month, None, None) \
|
||||
== "heating"
|
||||
# the owner's fixed choice, whatever the season or the weather
|
||||
assert side({"mode": "cooling"}, 1, -5, "heating") == "cooling"
|
||||
assert side({"mode": "heating"}, 7, 35, "cooling") == "heating"
|
||||
|
||||
|
||||
def test_season_boundary_in_the_agent(tmp_path):
|
||||
m = mapping_file(tmp_path)
|
||||
s = Switchover(str(tmp_path))
|
||||
s.update(m.controls, at(2026, 4, 30, 23), TZ)
|
||||
assert s.inactive == {"cooling"}
|
||||
assert s.update(m.controls, at(2026, 5, 1, 0), TZ) is True
|
||||
assert s.inactive == {"heating"}
|
||||
assert s.update(m.controls, at(2026, 5, 2), TZ) is False
|
||||
|
||||
|
||||
def test_outdoor_temperature_with_hysteresis(tmp_path):
|
||||
m = mapping_file(tmp_path, {"mode": "outdoor", "heat_below_c": 15, "cool_above_c": 22})
|
||||
s = Switchover(str(tmp_path))
|
||||
july = at(2026, 7, 10)
|
||||
seen = []
|
||||
for t in (10, 14.9, 18, 21.9, 22.1, 18, 15.5, 14, 18, None, 30):
|
||||
s.update(m.controls, july, TZ, t)
|
||||
seen.append(next(c.kind for c in m.controls if s.active(c)))
|
||||
# heating below 15 and on through the band; cooling above 22 and on
|
||||
# through the band; no reading: as it was
|
||||
assert seen == ["heating", "heating", "heating", "heating", "cooling", "cooling", "cooling", "heating",
|
||||
"heating", "heating", "cooling"]
|
||||
# a restart in the band keeps the side (switchover.json), not the season's
|
||||
s.update(m.controls, july, TZ, 14)
|
||||
again = Switchover(str(tmp_path))
|
||||
again.update(m.controls, july, TZ, 18)
|
||||
assert again.inactive == {"cooling"}
|
||||
# never had a side and no reading: by season
|
||||
fresh = Switchover()
|
||||
fresh.update(m.controls, july, TZ, None)
|
||||
assert fresh.inactive == {"heating"}
|
||||
|
||||
|
||||
def test_check():
|
||||
assert check({"mode": "outdoor"}) == {"mode": "outdoor", "heat_below_c": 15.0, "cool_above_c": 22.0}
|
||||
for bad in ({"mode": "both"}, {"mode": "outdoor", "heat_below_c": 25, "cool_above_c": 20}, {"mode": "season", "x": 1}):
|
||||
with pytest.raises(ValueError):
|
||||
check(bad)
|
||||
|
||||
|
||||
def test_never_both_controls_active(tmp_path, consent): # noqa: F811
|
||||
m = mapping_file(tmp_path)
|
||||
g = mk_guard(m, consent)
|
||||
s = Switchover()
|
||||
g.switchover = s
|
||||
s.update(m.controls, at(2026, 7, 10), TZ) # summer: cooling
|
||||
act = {k: Action(k, "climate", "climate.ac", "climate", "set_temperature", {"temperature": 22}, 22.0, "temp_c")
|
||||
for k in ("heating", "cooling")}
|
||||
assert g.check(act["cooling"])[0]
|
||||
ok, why = g.check(act["heating"])
|
||||
assert not ok and "not active" in why
|
||||
# the executor acts only for the active one; a command to the other is refused
|
||||
col = Collector()
|
||||
col.on_entities({"a": {"climate.ac": {"s": "off", "a": {"temperature": 25, "min_temp": 16, "max_temp": 30}}}}, now=0)
|
||||
ex = Executor(m.controls, g, col, None, clock=Clock(at(2026, 7, 10)))
|
||||
assert ex.command({"asset": "heating", "set": 21}, at(2026, 7, 10))[0] is False
|
||||
assert ex.command({"asset": "cooling", "set": 23}, at(2026, 7, 10))[0] is True
|
||||
done = []
|
||||
|
||||
async def run(_client, a, _now):
|
||||
done.append(a.control)
|
||||
ex._do = run
|
||||
asyncio.run(ex.tick(object(), True))
|
||||
assert done and set(done) == {"cooling"}
|
||||
# winter: the other way round, never both
|
||||
s.update(m.controls, at(2026, 1, 10), TZ)
|
||||
assert [c.id for c in m.controls if s.active(c)] == ["heating"]
|
||||
|
||||
|
||||
def test_controller_plans_only_the_active_side(tmp_path, consent): # noqa: F811
|
||||
m = mapping_file(tmp_path, {"mode": "outdoor", "heat_below_c": 15, "cool_above_c": 22})
|
||||
cfg = Config(site_id=SITE, mapping="", state_dir=str(tmp_path))
|
||||
ctl = Controller(cfg, m, consent, None, clock=Clock(at(2026, 1, 10)))
|
||||
assert "sensor.outside" in ctl.entities() # the mapped outside.temp
|
||||
ctl.col.on_entities({"a": {"sensor.outside": {"s": "28", "a": {}}}}, now=0)
|
||||
state = ctl.model_state()
|
||||
assert [d["id"] for d in state["devices"]] == ["cooling"] # 28 °C in January: cooling
|
||||
acts = ctl.actuators()
|
||||
assert acts["heating"]["switchover"]["active"] is False and acts["cooling"]["switchover"]["active"] is True
|
||||
assert json.dumps(acts)
|
||||
|
||||
|
||||
def test_unpaired_controls_never_share_an_entity(tmp_path):
|
||||
m = {"version": 3, "assets": [], "controls": [
|
||||
{"id": "a", "kind": "heating", "entities": {"climate": "climate.x"}},
|
||||
{"id": "b", "kind": "cooling", "entities": {"climate": "climate.x"}}, # no switchover
|
||||
{"id": "c", "kind": "heating", "entities": {"climate": "climate.y"}, "switchover": {"mode": "season"}},
|
||||
{"id": "d", "kind": "heating", "entities": {"climate": "climate.y"}, "switchover": {"mode": "season"}}, # same kind
|
||||
{"id": "e", "kind": "cooling", "entities": {"climate": "climate.y"}, "switchover": {"mode": "season"}},
|
||||
{"id": "f", "kind": "cooling", "entities": {"climate": "climate.y"}, "switchover": {"mode": "season"}}]} # a third
|
||||
(tmp_path / "mapping.yaml").write_text(yaml.safe_dump(m))
|
||||
assert [c.id for c in Mapping.load(str(tmp_path / "mapping.yaml")).controls] == ["a", "c", "e"]
|
||||
bad = dict(m, controls=[{"id": "s", "kind": "heating", "entities": {"switch": "switch.boiler"},
|
||||
"switchover": {"mode": "season"}}])
|
||||
(tmp_path / "mapping.yaml").write_text(yaml.safe_dump(bad))
|
||||
with pytest.raises(ValueError):
|
||||
Mapping.load(str(tmp_path / "mapping.yaml"))
|
||||
|
||||
|
||||
def test_one_thermostat_card_for_the_pair(tmp_path):
|
||||
from cantabile_edge.dashboards import Home, view_climate
|
||||
m = mapping_file(tmp_path)
|
||||
v = view_climate(Home(m, "u", {}, [], "en"))
|
||||
cards = [c for s in v["sections"] for c in s["cards"] if c["type"] == "thermostat"]
|
||||
assert [c["entity"] for c in cards] == ["climate.ac"]
|
||||
@@ -0,0 +1,73 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
import pytest
|
||||
|
||||
from cantabile_edge.telemetry import Aggregator
|
||||
|
||||
|
||||
def agg(start=1000.0):
|
||||
a = Aggregator(60)
|
||||
a.begin(start) # 1000 -> window starts at 960
|
||||
return a
|
||||
|
||||
|
||||
def rec(records, asset):
|
||||
return next(r for r in records if r["asset"] == asset)
|
||||
|
||||
|
||||
def test_gauge_time_weighted_mean():
|
||||
a = agg()
|
||||
a.sample("pv.power", "gauge", 100.0, 960)
|
||||
a.sample("pv.power", "gauge", 400.0, 1005) # 100 W for 45 s, 400 W for 15 s
|
||||
r = rec(a.flush(1020), "pv.power")
|
||||
assert r["mean"] == pytest.approx((100 * 45 + 400 * 15) / 60)
|
||||
assert (r["min"], r["max"], r["last"], r["n"], r["unavailable_s"]) == (100, 400, 400, 2, 0)
|
||||
|
||||
|
||||
def test_burst_does_not_skew_mean():
|
||||
a = agg()
|
||||
a.sample("load.power", "gauge", 1000.0, 960)
|
||||
for i in range(50): # a burst of zeros in one second
|
||||
a.sample("load.power", "gauge", 0.0, 1019 + i / 100)
|
||||
a.sample("load.power", "gauge", 1000.0, 1019.5)
|
||||
assert rec(a.flush(1020), "load.power")["mean"] == pytest.approx(1000 * 59.5 / 60, rel=1e-3)
|
||||
|
||||
|
||||
def test_gauge_carries_into_next_window():
|
||||
a = agg()
|
||||
a.sample("room.living.temp", "gauge", 21.5, 970)
|
||||
a.flush(1020)
|
||||
r = rec(a.flush(1080), "room.living.temp") # no new sample: still 21.5
|
||||
assert (r["mean"], r["min"], r["max"], r["n"], r["unavailable_s"]) == (21.5, 21.5, 21.5, 0, 0)
|
||||
|
||||
|
||||
def test_unavailable_seconds():
|
||||
a = agg()
|
||||
a.sample("pv.power", "gauge", 200.0, 960)
|
||||
a.sample("pv.power", "gauge", None, 990) # unavailable for the second half
|
||||
r = rec(a.flush(1020), "pv.power")
|
||||
assert r["unavailable_s"] == 30
|
||||
assert r["mean"] == 200
|
||||
r = rec(a.flush(1080), "pv.power") # still unavailable: no values at all
|
||||
assert r["unavailable_s"] == 60 and "mean" not in r
|
||||
|
||||
|
||||
def test_counter_delta_and_reset():
|
||||
a = agg()
|
||||
a.sample("grid.import_energy", "counter", 1000.0, 961) # baseline
|
||||
a.sample("grid.import_energy", "counter", 1500.0, 990)
|
||||
r = rec(a.flush(1020), "grid.import_energy")
|
||||
assert (r["delta"], r["resets"]) == (500, 0)
|
||||
a.sample("grid.import_energy", "counter", 1700.0, 1030)
|
||||
a.sample("grid.import_energy", "counter", 50.0, 1040) # meter reset to 0, then 50
|
||||
a.sample("grid.import_energy", "counter", None, 1050) # unavailable: ignored
|
||||
a.sample("grid.import_energy", "counter", 80.0, 1060)
|
||||
r = rec(a.flush(1080), "grid.import_energy")
|
||||
assert (r["delta"], r["resets"], r["last"]) == (200 + 50 + 30, 1, 80)
|
||||
|
||||
|
||||
def test_counter_without_samples_is_zero():
|
||||
a = agg()
|
||||
a.sample("grid.import_energy", "counter", 10.0, 970)
|
||||
a.flush(1020)
|
||||
r = rec(a.flush(1080), "grid.import_energy")
|
||||
assert (r["delta"], r["n"], r["last"]) == (0, 0, 10)
|
||||
@@ -0,0 +1,161 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Any thermostat in Home Assistant (hub/profiles/ha-thermostat.json): a
|
||||
climate device no specific profile knows is proposed and shown by the
|
||||
generic profile; an ESPHome thermostat (feedback) gives room temperature,
|
||||
setpoint and heating/cooling state from hvac_action; an infrared one
|
||||
(ESPHome climate_ir: no hvac_action) gives them from its mode, flagged
|
||||
assumed. The setpoint stays inside the thermostat's own range and step,
|
||||
and a protected thermostat is never set off."""
|
||||
import json
|
||||
|
||||
from cantabile_edge import controls as controls_mod
|
||||
from cantabile_edge import propose
|
||||
from cantabile_edge.executor import actions_for
|
||||
from cantabile_edge.guard import Action
|
||||
from cantabile_edge.inputs import Collector
|
||||
from cantabile_edge.inventory import build
|
||||
from cantabile_edge.mapping import Asset, Mapping
|
||||
from cantabile_edge.policy import Policy
|
||||
|
||||
from test_control_parts import SITE, consent, mk_guard # noqa: F401
|
||||
from test_dashboard_homes import PROFILES, Reg, devices, home, sane
|
||||
|
||||
|
||||
def climate(r, dev, eid, state, attrs, manufacturer="Espressif", model="esp32", platform="esphome",
|
||||
area="living_room", name=None):
|
||||
d = r.dev(dev, name or dev, manufacturer, model, area)
|
||||
r.entities.append({"entity_id": eid, "unique_id": f"{dev}-climate", "device_id": d, "platform": platform})
|
||||
r.states.append({"entity_id": eid, "state": state, "attributes": dict(attrs, friendly_name=name or dev)})
|
||||
return d
|
||||
|
||||
|
||||
def ac_home(r):
|
||||
"""A test home's A/C thermostat (ESPHome's thermostat: feedback) and
|
||||
an infrared split in the bedroom (climate_ir coolix: assumed)."""
|
||||
climate(r, "ac", "climate.livingroom_ac_thermostat", "cool",
|
||||
{"hvac_modes": ["off", "cool"], "hvac_action": "cooling", "current_temperature": 26.4,
|
||||
"temperature": 24, "min_temp": 18, "max_temp": 30, "target_temp_step": 0.5, "fan_mode": "auto"},
|
||||
name="Living room A/C")
|
||||
r.areas.append({"area_id": "bedroom", "name": "Bedroom"})
|
||||
climate(r, "ir", "climate.bedroom_split", "heat",
|
||||
{"hvac_modes": ["off", "heat", "cool", "dry"], "current_temperature": None, "temperature": 22,
|
||||
"min_temp": 17, "max_temp": 30, "target_temp_step": 1}, area="bedroom", name="Bedroom split")
|
||||
|
||||
|
||||
def test_proposed_from_any_climate_device():
|
||||
r = Reg()
|
||||
ac_home(r)
|
||||
got = {a["asset"]: a for a in propose.propose(r.states, r.reg(), PROFILES)}
|
||||
t = got["room.living_room.temp"]
|
||||
assert (t["entity"], t["attribute"], t["unit"]) == ("climate.livingroom_ac_thermostat", "current_temperature", "°C")
|
||||
assert got["room.living_room.setpoint"]["attribute"] == "temperature"
|
||||
assert got["cooling.state"] == {"entity": "climate.livingroom_ac_thermostat", "asset": "cooling.state",
|
||||
"kind": "gauge", "unit": "", "consent": False,
|
||||
"attribute": "hvac_action", "equals": "cooling"}
|
||||
# the infrared one: no room temperature (no sensor), its state from its mode, assumed
|
||||
assert "room.bedroom.temp" not in got
|
||||
ir = [a for a in got.values() if a["entity"] == "climate.bedroom_split"]
|
||||
states = {a["equals"]: a for a in ir if a.get("equals")}
|
||||
assert states["heat"]["assumed"] is True and "attribute" not in states["heat"]
|
||||
assert states["cool"]["assumed"] is True
|
||||
assert got["room.bedroom.setpoint"]["entity"] == "climate.bedroom_split"
|
||||
# the agent takes the proposal
|
||||
m = Mapping(2, [Asset(**a) for a in got.values()])
|
||||
assert {a.asset for a in m.assets if a.assumed} == {a["asset"] for a in ir if a.get("equals")}
|
||||
|
||||
|
||||
def test_a_specific_profile_wins():
|
||||
"""ViCare's heat pump has a climate entity too: its own profile, not the generic one."""
|
||||
r = Reg()
|
||||
climate(r, "hp", "climate.vicare_heating", "heat", {"hvac_modes": ["heat"], "hvac_action": "heating",
|
||||
"current_temperature": 21},
|
||||
manufacturer="Viessmann", model="E3_Vitocal", platform="vicare")
|
||||
got = propose.propose(r.states, r.reg(), PROFILES)
|
||||
assert not any(a["asset"].startswith("room.") and a["entity"] == "climate.vicare_heating" for a in got)
|
||||
h = home(r)
|
||||
assert h.view(r.devices[0]).profile == "viessmann-vicare"
|
||||
|
||||
|
||||
def test_dashboard_section():
|
||||
r = Reg()
|
||||
ac_home(r)
|
||||
h = home(r)
|
||||
assert h.view(r.devices[0]).profile == "ha-thermostat"
|
||||
s = devices(sane(h)["overview"])
|
||||
ac = s["Living room A/C"]
|
||||
# what it does in words under its name ("Off · fan low": its action only when it says more than
|
||||
# its mode), then one tile: the room's temperature and its setpoint to change
|
||||
line = ac[0]
|
||||
assert line["type"] == "markdown" and "state_attr_translated(e, 'fan_mode')" in line["content"]
|
||||
assert "fan {{" in line["content"] and "startswith(s)" in line["content"]
|
||||
assert ac[1]["type"] == "tile" and ac[1]["entity"] == "climate.livingroom_ac_thermostat"
|
||||
assert ac[1]["features"] == [{"type": "target-temperature"}]
|
||||
assert not any("does not report back" in c.get("content", "") for c in ac) # it reports back
|
||||
ir = s["Bedroom split"]
|
||||
assert ir[1]["entity"] == "climate.bedroom_split"
|
||||
assert any(c["type"] == "markdown" and "does not report back" in c["content"] for c in ir)
|
||||
de = devices(sane(home(r, lang="de"))["overview"])
|
||||
assert any("meldet nichts zurück" in c.get("content", "") for c in de["Bedroom split"])
|
||||
|
||||
|
||||
FRAGMENT = {"version": 3, "device": "ha-thermostat-1", "profile": "ha-thermostat",
|
||||
"assets": [{"entity": "climate.split", "asset": "cooling.state", "kind": "gauge", "unit": "",
|
||||
"equals": "cool", "assumed": True, "consent": True},
|
||||
{"entity": "climate.split", "asset": "room.bedroom.setpoint", "kind": "gauge", "unit": "°C",
|
||||
"attribute": "temperature", "consent": True}],
|
||||
"controls": [{"id": "cooling", "kind": "cooling", "consent": True, "entities": {"climate": "climate.split"},
|
||||
"params": {"min_switch_s": 900}}]}
|
||||
|
||||
|
||||
def load(tmp_path):
|
||||
(tmp_path / "mapping.yaml").write_text("version: 3\nassets: []\n")
|
||||
(tmp_path / "mapping.d").mkdir()
|
||||
(tmp_path / "mapping.d" / "ha-thermostat-1.yaml").write_text(json.dumps(FRAGMENT))
|
||||
return Mapping.load(str(tmp_path / "mapping.yaml"))
|
||||
|
||||
|
||||
def test_fragment_assumed_and_inventory(tmp_path):
|
||||
m = load(tmp_path)
|
||||
a = m.by_asset["cooling.state"]
|
||||
assert (a.equals, a.assumed) == ("cool", True) and not m.by_asset["room.bedroom.setpoint"].assumed
|
||||
reg = {"devices": [{"id": "d", "manufacturer": "Espressif", "model": "esp32"}],
|
||||
"entities": [{"entity_id": "climate.split", "device_id": "d"}]}
|
||||
inv = build(m, reg, {}, {}, 1)
|
||||
assert inv["devices"][0]["assumed"] == ["cooling.state"]
|
||||
bad = dict(FRAGMENT, assets=[dict(FRAGMENT["assets"][0], assumed="yes")])
|
||||
(tmp_path / "mapping.d" / "ha-thermostat-1.yaml").write_text(json.dumps(bad))
|
||||
assert "cooling.state" not in Mapping.load(str(tmp_path / "mapping.yaml")).by_asset # left out whole
|
||||
|
||||
|
||||
def col_with(attrs, state="cool"):
|
||||
col = Collector()
|
||||
col.on_entities({"a": {"climate.split": {"s": state, "a": attrs}}}, now=0)
|
||||
return col
|
||||
|
||||
|
||||
def test_setpoint_in_the_thermostats_range_and_step(tmp_path):
|
||||
c = load(tmp_path).controls[0]
|
||||
col = col_with({"temperature": 24, "min_temp": 18, "max_temp": 26, "target_temp_step": 0.5})
|
||||
acts = actions_for(c, 23.3, col)
|
||||
assert [(a.service, a.value) for a in acts] == [("set_temperature", 23.5)]
|
||||
assert c.bounds("temp_c").lo == 18 and c.bounds("temp_c").hi == 26 # cooling 16..32 narrowed
|
||||
# a step of 1 that rounds below the range goes up into it
|
||||
col = col_with({"temperature": 24, "min_temp": 18.5, "max_temp": 26, "target_temp_step": 1})
|
||||
assert actions_for(c, 18.5, col)[0].value == 19.0
|
||||
# a range that does not overlap the kind's is ignored
|
||||
c.entity_range.clear()
|
||||
c.learn_range(col_with({"min_temp": 40, "max_temp": 50}))
|
||||
assert c.device_range("temp_c") == controls_mod.RANGE["cooling"]["temp_c"]
|
||||
|
||||
|
||||
def test_protected_thermostat_never_off(tmp_path, consent): # noqa: F811
|
||||
m = load(tmp_path)
|
||||
g = mk_guard(m, consent)
|
||||
g.policy = Policy(str(tmp_path), SITE)
|
||||
(tmp_path / "protection.json").write_text(json.dumps({"v": 1, "entries": {"control:cooling": {
|
||||
"level": "protected", "at": 1, "source": "profile", "device": "ha-thermostat-1"}}}))
|
||||
off = Action("cooling", "climate", "climate.split", "climate", "set_hvac_mode", {"hvac_mode": "off"}, "off")
|
||||
ok, why = g.check(off)
|
||||
assert not ok and why.startswith("protected")
|
||||
cool = Action("cooling", "climate", "climate.split", "climate", "set_temperature", {"temperature": 24}, 24.0, "temp_c")
|
||||
assert g.policy.refuses(cool, g.controls["cooling"]) == ""
|
||||
Reference in new issue
Block a user