Files
cantabile-ha-addons/src/edge/tests/test_devprofiles.py
T

289 lines
18 KiB
Python

# 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"]
# --- storage with losses (docs/design/storage-losses.md 10.1-10.3) ------------------------
def water_heater(eid="water_heater.tank", **attrs):
return {"entity_id": eid, "device_id": "d", "unique_id": eid,
"attributes": dict({"current_temperature": 52, "temperature": 55, "min_temp": 35, "max_temp": 65}, **attrs)}
def test_storage_quantities_write_roles_and_ratings():
for q, want in (("battery.standby_power", ("W", "gauge")), ("dhw.temp_top", ("°C", "gauge")),
("dhw.temp_bottom", ("°C", "gauge")), ("dhw.heater_power", ("W", "gauge")),
("dhw.tank_energy", ("Wh", "gauge")), ("dhw.energy", ("Wh", "counter"))):
assert dp.quantity_of(q) == want, q
assert {"water_heater", "sg_ready", "switch"} <= dp.WRITE_ROLES
# a tank's power is a diverter's watts (written); a battery's or a car's power is a reading
assert dp.is_write("dhw_tank", "power") and not dp.is_write("battery", "power") and not dp.is_write("ev", "power")
assert not dp.is_write("dhw_tank", "temp_top") and not dp.is_write("battery", "standby")
new = ("battery_standby_w", "battery_self_discharge_pct_month", "tank_volume_l", "tank_heater_kw", "tank_cop",
"tank_standby_w", "tank_erp_class", "tank_max_c", "tank_room_c", "tank_grossanlage")
assert all(k in dp.RATINGS for k in new) and len(dp.ERP_CLASSES) == 7 and dp.ERP_CLASSES[4] == "D"
assert dp.HEATERS == ("element", "heat_pump", "boiler", "district")
def test_battery_profiles_ask_for_the_idle_loss():
for pid in ("hm8042-hybrid", "solaredge-sunspec", "huawei-sun2000", "victron-gx", "sma-sunny-boy", "fronius-gen24"):
rated = {f["rating"]: f for f in PROFILES[pid]["fields"] if f.get("rating")}
assert {"battery_standby_w", "battery_self_discharge_pct_month"} <= set(rated), pid
assert rated["battery_standby_w"]["optional"] and rated["battery_standby_w"]["min"] > 0, pid
assert "learns" in rated["battery_standby_w"]["label"], pid
def test_water_heater_fragment_consent_off_heater_chosen_after():
"""Any HA water_heater (ha-water-heater): a dhw_tank control on it,
consent off; its current temperature as the tank's; optional roles only
where the device has them; the heater the installer's choice."""
p = PROFILES["ha-water-heater"]
ps = list(PROFILES.values())
assert [x["id"] for x in dp.fitting(ps, {"manufacturer": "Stiebel", "model": "WWK"}, ["mqtt"], ["water_heater"])] \
== ["ha-water-heater"]
s = dp.setup_for(p, ["mqtt"])
power = {"entity_id": "sensor.tank_heater_power", "device_id": "d", "unique_id": "p", "device_class": "power"}
frag, missing = dp.mapping_for("tank-1", p, s, [water_heater(), power], "Cellar", set())
tank = frag["controls"][0]
assert (tank["kind"], tank["consent"]) == ("dhw_tank", False)
assert tank["entities"] == {"water_heater": "water_heater.tank", "heater_power": "sensor.tank_heater_power"}
assert "heater" not in (tank.get("params") or {}) # never a guess
got = {a["asset"]: a for a in frag["assets"]}
assert got["dhw.temp_top"]["attribute"] == "current_temperature" and got["dhw.temp_top"]["unit"] == "°C"
assert got["dhw.heater_power"]["entity"] == "sensor.tank_heater_power"
assert "dhw.temp_bottom" in missing and not any("control" in m for m in missing)
assert not any(a["consent"] for a in frag["assets"])
assert dp.tank_of(frag) == {"heater": ""}
assert dp.set_tank_heater(frag, {"heater": "heat_pump"}) == {"heater": "heat_pump"}
assert frag["controls"][0]["params"]["heater"] == "heat_pump"
for bad in ({"heater": "gas"}, {}):
with pytest.raises(dp.Fail):
dp.set_tank_heater(frag, bad)
with pytest.raises(dp.Fail):
dp.set_tank_heater({"controls": [{"kind": "battery"}]}, {"heater": "element"})
# one writer per entity: the water heater's control writes it, not its power sensor
assert "water_heater.tank" in dp.control_writes(frag["controls"])
assert "sensor.tank_heater_power" not in dp.control_writes(frag["controls"])
def test_immersion_heater_on_a_relay_with_tank_sensors():
"""A tank without a water_heater entity: a relay and its sensors, found
by their names across HA (ha-immersion-heater; never offered by itself)."""
p = PROFILES["ha-immersion-heater"]
assert dp.fitting([p], {"manufacturer": "Shelly", "model": "Plus 1PM"}, ["shelly"], ["switch", "sensor.temperature"]) == []
s = dp.setup_for(p, [])
ents = [{"entity_id": "switch.keller_heizstab", "unique_id": "r"},
{"entity_id": "sensor.speicher_oben", "unique_id": "t1", "device_class": "temperature"},
{"entity_id": "sensor.speicher_unten", "unique_id": "t2", "device_class": "temperature"},
{"entity_id": "sensor.heizstab_power", "unique_id": "w", "device_class": "power"},
{"entity_id": "switch.fridge", "unique_id": "f"}]
frag, missing = dp.mapping_for("tank-2", p, s, ents, None, set())
c = frag["controls"][0]
assert c["kind"] == "dhw_tank" and c["params"] == {"heater": "element"}
assert c["entities"] == {"switch": "switch.keller_heizstab", "temp_top": "sensor.speicher_oben",
"temp_bottom": "sensor.speicher_unten", "heater_power": "sensor.heizstab_power"}
assert {a["asset"] for a in frag["assets"]} == {"dhw.temp_top", "dhw.temp_bottom", "dhw.heater_power"}
assert missing == []
# without the bottom sensor and the power sensor: the control still, those roles left out
frag2, _ = dp.mapping_for("tank-3", p, s, ents[:2], None, set())
assert frag2["controls"][0]["entities"] == {"switch": "switch.keller_heizstab", "temp_top": "sensor.speicher_oben"}
# without the top sensor: no control (a tank temperature is needed), reported
frag3, missing3 = dp.mapping_for("tank-4", p, s, ents[:1], None, set())
assert frag3["controls"] == [] and "dhw_tank control (temp_top)" in missing3
def test_rating_values_above_zero():
p = PROFILES["ha-water-heater"]
got = dp.rating_values(p, {"rated_tank_volume_l": "300", "rated_tank_erp_class": "3", "rated_tank_cop": " ",
"nope": "5"})
assert got == {"rated_tank_volume_l": 300.0, "rated_tank_erp_class": 3}
assert dp.ratings_of(p, got) == {"tank_volume_l": 300.0, "tank_erp_class": 3}
for bad in ({"rated_tank_volume_l": "0"}, {"rated_tank_volume_l": "-5"}, {"rated_tank_erp_class": "8"},
{"rated_tank_cop": "abc"}, {"rated_tank_grossanlage": "0"}):
with pytest.raises(dp.Fail):
dp.rating_values(p, bad)
f = {"name": "x", "label": "X", "type": "number", "rating": "battery_kwh", "min": 0}
with pytest.raises(dp.Fail, match="above 0"):
dp.rating_value(f, "0")
fields = dp.rating_fields(p, {"ratings": {"tank_volume_l": 300.0}})
assert next(x["value"] for x in fields if x["rating"] == "tank_volume_l") == 300.0
assert next(x["value"] for x in fields if x["rating"] == "tank_cop") is None
def test_storage_from_the_plan():
"""Both Devices pages: a battery's idle loss with its source, a tank's
facts, what it is not planned without (design 10.5)."""
frag = {"controls": [{"id": "battery", "kind": "battery", "entities": {"charge_from_grid": "switch.x"}},
{"id": "dhw_tank", "kind": "dhw_tank", "entities": {"water_heater": "water_heater.t"},
"params": {"heater": "heat_pump"}},
{"id": "heating", "kind": "heating", "entities": {"climate": "climate.y"}}]}
# no plan yet: the tank's gaps from what the installer and the owner gave
out = dp.storage_of(frag, {"tank_volume_l": 300}, {})
assert [x["kind"] for x in out] == ["battery", "dhw_tank"]
assert out[0] == {"id": "battery", "kind": "battery", "planned": False}
assert out[1]["missing"] == ["max_power_w", "cop"] and out[1]["volume_l"] == 300 and not out[1]["planned"]
out = dp.storage_of(frag, {"tank_volume_l": 300, "tank_heater_kw": 1.2, "tank_cop": 2.8}, None)
assert out[1]["missing"] == [] and out[1]["heater_kw"] == 1.2 and out[1]["cop"] == 2.8
# the plan's word
planning = {"storage": {"battery": {"kind": "battery", "standby_w": 49.0, "standby_src": "learnt",
"self_discharge_pct_month": 2.0, "self_discharge_src": "parameter",
"idle_loss_kwh_24h": 1.18, "standby_in_load": None},
"dhw_tank": {"kind": "dhw_tank", "heater": "heat_pump", "volume_l": 300, "standby_w": 122.0,
"loss_src": "assumed", "erp_class": "D", "temp_c": 51.5, "usable_kwh": 2.2}},
"refused": {}}
bat, tank = dp.storage_of(frag, {}, planning)
assert bat == {"id": "battery", "kind": "battery", "planned": True, "standby_w": 49.0, "standby_src": "learnt",
"self_discharge_pct_month": 2.0, "self_discharge_src": "parameter", "idle_loss_kwh_24h": 1.18}
assert tank["planned"] and tank["missing"] == [] and (tank["loss_src"], tank["erp_class"]) == ("assumed", "D")
# refused by the plan: its missing facts
planning = {"storage": {}, "refused": {"dhw_tank": {"why": "tank volume unknown", "missing": ["volume_l"]}}}
tank = dp.storage_of(frag, {}, planning)[1]
assert tank["refused"] and tank["missing"] == ["volume_l"] and not tank["planned"]
# a mapping's facts count as given; a device's volume entity too
frag["controls"][1]["params"] = {"heater": "element", "max_power_w": 3000}
frag["controls"][1]["entities"]["volume"] = "sensor.v"
assert dp.storage_of(frag, {}, {})[1]["missing"] == [] and dp.storage_of(frag, {}, {})[1]["heater_kw"] == 3.0
frag["controls"][1]["entities"] = {"switch": "switch.r"}
assert dp.storage_of(frag, {"tank_volume_l": 200}, {})[1]["missing"] == ["temp_sensor"]