cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.400: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-10-30 08:26:45 +02:00
1 parent 343331d234
commit d5fbcacaa4
176 files changed
+32511 -19

No files matched your search

+144
View File
@@ -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"]