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,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")
|
||||
Reference in new issue
Block a user