464 lines
27 KiB
Python
464 lines
27 KiB
Python
# 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, SupportSessions
|
||
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<details" in out
|
||
assert out.count("Use with Cantabile</button>") == 2 # the inverter and the A/C
|
||
assert "Cantabile would read: solar power" in out and "battery charge" in out
|
||
assert "It could control: heating, cooling." in out and "generic profile" in out
|
||
assert "room temperature (Living room), setpoint, heating/cooling state" in out # words, never asset ids
|
||
assert "room: " not in out and "Devices in Home Assistant you can add" 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 "in use 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
|
||
assert "Reading and control" in out and "‹ Devices" in out # its own page
|
||
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 list: in use, reading off, in words, no second offer for it
|
||
out = s.req()
|
||
assert "1 device in use with Cantabile" in out and "Added · reading off · control off" in out
|
||
assert f'href="?p=devices&d={dev["id"]}"' in out and "21.5 °C, set to 22 °C, idle" in out
|
||
assert out.count("Use with Cantabile</button>") == 1
|
||
out = s.req(query=f"p=devices&d={dev['id']}")
|
||
assert "first give your consent in the add-on's configuration" in out and 'name="read"' not in out
|
||
assert '<span class="badge quiet">untested</span>' in out
|
||
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 temperature (Living). 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 temperature (Living room)" 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(query=f"p=devices&d={dev_id}")
|
||
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 and "In use · reading on · control off" in out
|
||
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(query=f"p=devices&d={dev_id}")
|
||
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(query=f"p=devices&d={dev_id}")
|
||
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<details" in out and "Mit Cantabile nutzen" in out
|
||
assert "Raumtemperatur (Living room)" in out and "Geräte in Home Assistant, die Sie hinzufügen können" 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
|
||
|
||
|
||
def test_support_session_banner_end_and_owners_choices(tmp_path):
|
||
"""Remote HA for support on an add-on site: while the link says support
|
||
has this Home Assistant open, both pages show it with End now (SIGUSR1
|
||
to the link, only to the link); the support user cannot change what is
|
||
the owner's (as on the Hub's panel)."""
|
||
import signal
|
||
import time
|
||
s = Site(tmp_path)
|
||
link, proc, killed = tmp_path / "link", tmp_path / "proc", []
|
||
link.mkdir()
|
||
(proc / "4242").mkdir(parents=True)
|
||
(proc / "4242" / "cmdline").write_bytes(b"cantabile-link\0")
|
||
(proc / "77").mkdir()
|
||
(proc / "77" / "cmdline").write_bytes(b"python3\0-m\0cantabile_edge\0")
|
||
s.app.support = SupportSessions(str(link), proc=str(proc), kill=lambda pid, sig: killed.append((pid, sig)))
|
||
state = link / "support-ha.json"
|
||
assert "Cantabile support has this Home Assistant open" not in s.req() # no file: none
|
||
state.write_text(json.dumps({"pid": 4242, "sessions": []}))
|
||
assert "Cantabile support has this Home Assistant open" not in s.req()
|
||
state.write_text(json.dumps({"pid": 4242, "user": "Cantabile support", "sessions": [
|
||
{"by": "Ana (Cantabile)", "since": int(time.time()) - 300, "consent": "", "kind": "ha"}]}))
|
||
out = s.req()
|
||
assert "Cantabile support has this Home Assistant open" in out and "Ana (Cantabile), for 5 minutes" in out
|
||
assert 'value="end-support"' in out and "End now" in out
|
||
assert "Cantabile support has this Home Assistant open" in s.req(query="p=building")
|
||
|
||
def german():
|
||
i18n.use("de")
|
||
return s.req()
|
||
import contextvars
|
||
out = contextvars.copy_context().run(german)
|
||
assert "Der Cantabile-Support hat dieses Home Assistant geöffnet" in out and "seit 5 Minuten" in out
|
||
assert "Jetzt beenden" in out
|
||
# the owner's End now (any administrator): the link gets SIGUSR1
|
||
out = s.req("POST", "p=devices", {"do": "end-support"})
|
||
assert "Ended. Cantabile support's session is closed" in out and killed == [(4242, signal.SIGUSR1)]
|
||
out = s.req("POST", "p=building", {"do": "end-support"})
|
||
assert "Ended." in out and "<nav>" in out and len(killed) == 2
|
||
# never another process: a pid that is not the link
|
||
state.write_text(json.dumps({"pid": 77, "sessions": [{"by": "Ana", "since": 1, "kind": "ha"}]}))
|
||
assert "No session to end" in s.req("POST", "p=devices", {"do": "end-support"}) and len(killed) == 2
|
||
state.write_text(json.dumps({"pid": 4242, "sessions": [{"by": "Ana", "since": 1, "kind": "ha"}]}))
|
||
# the support user (an HA administrator) may look and add, not decide what is the owner's
|
||
s.give_consent(share=True, control=True)
|
||
s.post(do="use", ha_device=AC, profile="ha-thermostat")
|
||
dev_id = next(iter(s.devices()))
|
||
sup = {"x-remote-user-id": "u-support", "x-remote-user-name": "cantabile-support",
|
||
"x-remote-user-display-name": "Cantabile support"}
|
||
s.ha.admins.add("u-support")
|
||
ingress = "172.30.32.2"
|
||
frag = s.tmp / "mapping.d" / f"{dev_id}.yaml"
|
||
for form, why in (({"do": "consent", "id": dev_id, "read": "1", "control": "1"}, "Reading and control are the owner"),
|
||
({"do": "protect", "id": dev_id, "target": f"device:{dev_id}", "level": "none"}, "Protection is the owner"),
|
||
({"do": "switchover", "id": dev_id, "mode": "cooling"}, "Heating or cooling is the owner"),
|
||
({"do": "weather", "id": dev_id}, "The weather forecast is the owner")):
|
||
before = (s.state / "devices.json").read_text(), frag.read_text()
|
||
out = s.req("POST", f"p=devices&d={dev_id}", form, sup, ingress)
|
||
assert why in out and "Cantabile support has this Home Assistant open" in out, form
|
||
assert before == ((s.state / "devices.json").read_text(), frag.read_text()), form
|
||
# the owner still can
|
||
s.req("POST", f"p=devices&d={dev_id}", {"do": "consent", "id": dev_id, "read": "1", "control": "0"})
|
||
assert s.devices()[dev_id] != json.loads(before[0])[dev_id]
|
||
# known by its id too while a session is open (the link names it)
|
||
state.write_text(json.dumps({"pid": 4242, "sessions": [{"by": "Ana", "since": 1, "kind": "ha", "ha_user": "u-support"}]}))
|
||
out = s.req("POST", f"p=devices&d={dev_id}", {"do": "protect", "id": dev_id, "target": f"device:{dev_id}", "level": "none"},
|
||
{"x-remote-user-id": "u-support"}, ingress)
|
||
assert "Protection is the owner" in out
|
||
# and End now is theirs too
|
||
assert "Ended." in s.req("POST", "p=devices", {"do": "end-support"}, sup, ingress)
|
||
|
||
|
||
def test_hot_water_tank_ratings_and_idle_loss(tmp_path):
|
||
"""Backlog 329 (docs/design/storage-losses.md): any HA water heater
|
||
used as a hot-water tank (control dhw_tank, consent off); its heater the
|
||
owner's choice; its ratings entered here as on the Hub (each above 0);
|
||
what it is not planned without as a warning; the loss's and a battery's
|
||
idle loss's source from the agent's latest plan; support may not change
|
||
them."""
|
||
s = Site(tmp_path)
|
||
s.ha.reg["devices"].append({"id": "dev-tank", "name": "Tank", "manufacturer": "Stiebel Eltron", "model": "WWK 300",
|
||
"config_entries": ["e4"]})
|
||
s.ha.reg["entities"].append(ent("water_heater.tank", "dev-tank", "wh1", "stiebel"))
|
||
s.ha.states.append(st("water_heater.tank", "eco", current_temperature=51.5, temperature=55, min_temp=35, max_temp=65))
|
||
out = s.req()
|
||
assert "It could control: hot-water tank." in out
|
||
out = s.post(do="use", ha_device="dev-tank", profile="ha-water-heater", name="Tank")
|
||
dev_id = next(i for i, d in s.devices().items() if d["profile"] == "ha-water-heater")
|
||
tank = s.frag(dev_id)["controls"][0]
|
||
assert (tank["kind"], tank["consent"], tank["entities"]) == ("dhw_tank", False, {"water_heater": "water_heater.tank"})
|
||
page = s.req(query=f"p=devices&d={dev_id}")
|
||
assert "Hot-water tank" in page and 'name="heater"' in page and "Choose its heater" in page
|
||
assert "Needed: the tank is not planned without it." in page
|
||
assert "the tank's volume (Ratings), its heater (above)" in page
|
||
assert 'name="f_rated_tank_volume_l"' in page and 'value="ratings"' in page and "tank 51.5 °C" in page
|
||
# the heater and the ratings: the owner's
|
||
assert "Saved." in s.post(do="tank", id=dev_id, heater="heat_pump")
|
||
assert s.frag(dev_id)["controls"][0]["params"]["heater"] == "heat_pump"
|
||
assert "the heater is one of" in s.post(do="tank", id=dev_id, heater="gas")
|
||
s.post(do="ratings", id=dev_id, f_rated_tank_volume_l="300", f_rated_tank_heater_kw="0.6", f_rated_tank_cop="")
|
||
assert s.devices()[dev_id]["ratings"] == {"tank_volume_l": 300.0, "tank_heater_kw": 0.6}
|
||
specs = json.loads((s.state / "devices-specs.json").read_text())["devices"][dev_id]
|
||
assert specs["ratings"]["tank_volume_l"] == 300.0 and specs["controls"] == [tank["id"]]
|
||
assert "0.01 to 1000" in s.post(do="ratings", id=dev_id, f_rated_tank_heater_kw="0", f_rated_tank_volume_l="300")
|
||
assert s.devices()[dev_id]["ratings"]["tank_heater_kw"] == 0.6 # refused: kept as it was
|
||
page = s.req(query=f"p=devices&d={dev_id}")
|
||
assert "the heat pump's COP (Ratings)" in page and "300 L · heater 0.6 kW" in page
|
||
assert 'value="300"' in page
|
||
# the agent's plan: the loss assumed at class D's limit (quiet, no alarm)
|
||
(s.state / "preferences-view.json").write_text(json.dumps({"v": 1, "planning": {"refused": {}, "storage": {
|
||
tank["id"]: {"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}}}}))
|
||
page = s.req(query=f"p=devices&d={dev_id}")
|
||
assert "Needed:" not in page and "now 51.5 °C · 2.2 kWh usable" in page
|
||
assert "Standing loss 122 W assumed: class D's limit (Parameters). Enter the label's value below." in page
|
||
# support may not change what is the owner's
|
||
sup = {"x-remote-user-name": "cantabile-support"}
|
||
for form, why in (({"do": "tank", "id": dev_id, "heater": "element"}, "The tank's heater is the owner"),
|
||
({"do": "ratings", "id": dev_id, "f_rated_tank_volume_l": "200"}, "The ratings are the owner")):
|
||
out = s.req("POST", f"p=devices&d={dev_id}", form, sup)
|
||
assert why in out, form
|
||
assert s.devices()[dev_id]["ratings"]["tank_volume_l"] == 300.0
|
||
assert s.frag(dev_id)["controls"][0]["params"]["heater"] == "heat_pump"
|
||
|
||
def german():
|
||
i18n.use("de")
|
||
return s.req(query=f"p=devices&d={dev_id}")
|
||
import contextvars
|
||
out = contextvars.copy_context().run(german)
|
||
assert "Warmwasserspeicher" in out and "Warmhalteverlust 122 W angenommen" in out and "Nenndaten" in out
|
||
|
||
|
||
def test_battery_idle_loss_line():
|
||
"""A battery's idle loss with its source (design 2.3): learnt, the
|
||
owner's, assumed (a quiet line with what to do, never an alarm)."""
|
||
from cantabile_edge.devpage import battery_store_lines, ratings_html
|
||
assert battery_store_lines({"standby_w": 49.2, "standby_src": "learnt", "idle_loss_kwh_24h": 1.18,
|
||
"self_discharge_pct_month": 2, "self_discharge_src": "parameter"}) == [
|
||
"Idle loss 49 W (learnt by the box) · about 1.18 kWh a day", "Self-discharge 2 %/month assumed (Parameters)"]
|
||
assert battery_store_lines({"standby_w": 13, "standby_src": "parameter"}) == [
|
||
"Idle loss 13 W assumed (Parameters): enter the datasheet's value below."]
|
||
assert battery_store_lines({"standby_w": 30, "standby_src": "owner"}) == ["Idle loss 30 W (your rating)"]
|
||
assert battery_store_lines({"planned": False}) == []
|
||
d = {"id": "hm8042-hybrid-1", "rating_fields": [
|
||
{"name": "rated_battery_standby_w", "label": "x", "rating": "battery_standby_w", "value": None}],
|
||
"storage": [{"id": "battery", "kind": "battery", "standby_w": 13, "standby_src": "assumed"}]}
|
||
out = ratings_html(d)
|
||
assert out.index("Idle loss 13 W assumed") < out.index('name="f_rated_battery_standby_w"')
|
||
assert "box warn" not in out and "leave empty and the box learns it" in out
|
||
# a hot-water meter's ratings too (the add-on had no form for them)
|
||
out = ratings_html({"id": "ha-water-meter-1", "rating_fields": [
|
||
{"name": "rated_dhw_kwh_per_m3", "label": "x", "rating": "dhw_kwh_per_m3", "value": 58.2}]})
|
||
assert "From the meter and the installation" in out and 'value="58.2"' in out
|
||
assert "Hot water: kWh of heat per m³ drawn" in out
|
||
assert ratings_html({"id": "x", "rating_fields": []}) == ""
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def english():
|
||
i18n.use("en")
|