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

+249
View File
@@ -0,0 +1,249 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The add-on's manifest (what the Supervisor checks, and what keeps the
system "supported") and addon-run's start, with a fake Supervisor."""
import http.server
import json
import os
import subprocess
import sys
import threading
from pathlib import Path
import pytest
import yaml
ADDON = Path(__file__).resolve().parent.parent / "cantabile_edge"
RUN = ADDON / "addon-run"
def manifest():
return yaml.safe_load((ADDON / "config.yaml").read_text())
def test_manifest_has_what_the_supervisor_needs():
m = manifest()
for k in ("name", "version", "slug", "description", "arch"):
assert m.get(k), k
assert m["slug"] == ADDON.name
assert set(m["arch"]) <= {"amd64", "aarch64", "armv7", "armhf", "i386"}
assert "{arch}" in m["image"]
assert isinstance(m["version"], str)
def test_manifest_asks_for_no_more_than_it_needs():
m = manifest()
for k in ("host_network", "privileged", "full_access", "host_pid", "docker_api", "apparmor"):
assert k not in m, k
assert m["map"] == [{"type": "homeassistant_config", "read_only": True}, {"type": "share", "read_only": True}]
assert m.get("hassio_role", "default") == "default"
def test_options_schema_and_translations_agree():
m = manifest()
assert set(m["options"]) == set(m["schema"])
assert m["schema"]["mode"] == "list(off|shadow)" # advisory and auto only from the console
assert m["options"]["mode"] in ("off", "shadow")
for lang in ("en", "de"):
t = yaml.safe_load((ADDON / "translations" / f"{lang}.yaml").read_text())
assert set(t["configuration"]) == set(m["schema"]), lang
def test_icons_exist():
for n in ("icon.png", "logo.png"):
assert (ADDON / n).read_bytes()[:8] == b"\x89PNG\r\n\x1a\n"
class Supervisor(http.server.BaseHTTPRequestHandler):
mqtt = None
seen = []
def do_GET(self):
Supervisor.seen.append((self.path, self.headers.get("Authorization")))
if self.path == "/services/mqtt" and Supervisor.mqtt:
body = json.dumps({"result": "ok", "data": Supervisor.mqtt}).encode()
self.send_response(200)
else:
body = b'{"result": "error", "message": "Service not enabled"}'
self.send_response(400)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
def log_message(self, *a):
pass
@pytest.fixture
def box(tmp_path):
srv = http.server.HTTPServer(("127.0.0.1", 0), Supervisor)
threading.Thread(target=srv.serve_forever, daemon=True).start()
data, ha, etc, share = tmp_path / "data", tmp_path / "ha", tmp_path / "etc", tmp_path / "share"
data.mkdir(), (ha / ".storage").mkdir(parents=True), etc.mkdir(), share.mkdir()
(ha / ".storage" / "core.uuid").write_text('{"version":1,"key":"core.uuid","data":{"uuid":"8b7c0f9e5a1d4c2b9e3f0a1b2c3d4e5f"}}')
(etc / "addon.env").write_text("# the platform\nCANTABILE_DEVICES_URL=https://devices.example.org\n")
(etc / "commands.pem").write_text("cert")
(data / "options.json").write_text(json.dumps({"consent_data": True, "consent_control": False, "mode": "shadow",
"claim_code": " ABCD-EFGH-JKLM ", "dashboards": False}))
Supervisor.seen.clear()
def run():
env = {"PATH": os.environ["PATH"], "ADDON_DRY_RUN": "1", "ADDON_DATA": str(data), "ADDON_HA_CONFIG": str(ha),
"ADDON_ETC": str(etc), "ADDON_SHARE": str(share), "SUPERVISOR_URL": f"http://127.0.0.1:{srv.server_port}", "SUPERVISOR_TOKEN": "tok"}
p = subprocess.run([sys.executable, str(RUN)], env=env, capture_output=True, text=True, check=True)
return json.loads(p.stdout.strip().splitlines()[-1])
yield run, data, etc
srv.shutdown()
def test_start_with_the_mosquitto_add_on(box):
run, data, etc = box
Supervisor.mqtt = {"host": "core-mosquitto", "port": 1883, "ssl": False, "username": "addons", "password": "pw"}
out = run()
env = out["env"]
assert out["cmd"][-1] == "run" and out["cmd"][0] == "cantabile-run"
assert env["CANTABILE_DEVICES_URL"] == "https://devices.example.org"
assert env["CANTABILE_COMMAND_CERT"] == f"{etc}/commands.pem"
assert "CANTABILE_BUNDLE_CERT" not in env # no bundle certificate in this build
assert env["CANTABILE_HA_UUID_FILE"] == f"{data}/ha-core.uuid"
assert "8b7c0f9e5a1d4c2b9e3f0a1b2c3d4e5f" in (data / "ha-core.uuid").read_text()
assert (data / "ha-core.uuid").stat().st_mode & 0o077 == 0
assert (data / "claim-code").read_text() == "ABCD-EFGH-JKLM\n"
assert env["CANTABILE_MODE"] == "shadow" and env["CANTABILE_DASHBOARDS"] == "0"
assert (env["CANTABILE_MQTT_HOST"], env["CANTABILE_MQTT_PORT"], env["CANTABILE_MQTT_USER"]) == ("core-mosquitto", "1883", "addons")
assert (data / "mqtt-password").read_text() == "pw"
assert Supervisor.seen == [("/services/mqtt", "Bearer tok")]
assert "sink: {kind: link" in (data / "config.yaml").read_text()
assert "assets: []" in (data / "mapping.yaml").read_text()
assert env["CANTABILE_PROPOSE"] == "1" # the agent proposes one, consent off
assert not (data / "mapping-import.yaml").exists()
def test_start_without_a_broker_and_keeps_the_installers_files(box):
run, data, etc = box
Supervisor.mqtt = None
(data / "mapping.yaml").write_text("version: 3\nassets: [mine]\n")
(data / "config.yaml").write_text("mode: shadow\n# mine\n")
(etc / "bundles.pem").write_text("cert")
env = run()["env"]
assert not any(k.startswith("CANTABILE_MQTT") for k in env)
assert env["CANTABILE_BUNDLE_CERT"] == f"{etc}/bundles.pem"
assert (data / "mapping.yaml").read_text() == "version: 3\nassets: [mine]\n"
assert (data / "config.yaml").read_text() == "mode: shadow\n# mine\n"
def test_no_claim_code_writes_none(box):
run, data, etc = box
(data / "options.json").write_text(json.dumps({"consent_data": True, "mode": "off", "claim_code": "", "dashboards": True}))
env = run()["env"]
assert not (data / "claim-code").exists()
assert env["CANTABILE_MODE"] == "off" and env["CANTABILE_DASHBOARDS"] == "1"
def test_an_earlier_installs_mapping_is_handed_to_the_agent(box):
run, data, etc = box
share = data.parent / "share" / "cantabile"
share.mkdir()
(share / "mapping.yaml").write_text("version: 2\nassets: []\n")
run()
assert (data / "mapping-import.yaml").read_text() == "version: 2\nassets: []\n"
assert (data / "mapping-import.yaml").stat().st_mode & 0o077 == 0
HUB_WEB = ADDON.parent.parent / "hub" / "mkosi" / "mkosi.extra" / "usr" / "lib" / "cantabile" / "web"
def addon_run_constants():
import ast
tree = ast.parse(RUN.read_text())
want = ("CONSENT_TEXT", "CONTROL_TEXT", "CONSENT_VERSION", "CONSENT_SOURCE")
return {n.targets[0].id: ast.literal_eval(n.value) for n in tree.body
if isinstance(n, ast.Assign) and isinstance(n.targets[0], ast.Name) and n.targets[0].id in want}
def test_consent_is_asked_in_the_configuration():
m = manifest()
assert m["options"]["consent_data"] is False and m["options"]["consent_control"] is False # off until the owner says yes
assert m["schema"]["consent_data"] == "bool" and m["schema"]["consent_control"] == "bool"
c = addon_run_constants()
en = yaml.safe_load((ADDON / "translations" / "en.yaml").read_text())["configuration"]
assert c["CONSENT_TEXT"] in " ".join(en["consent_data"]["description"].split())
assert c["CONTROL_TEXT"][len("Allow Cantabile"):] in " ".join(en["consent_control"]["description"].split())
@pytest.mark.skipif(not HUB_WEB.exists(), reason="the Hub's panel is not beside the add-on")
def test_consent_texts_and_version_are_the_hubs():
import re
web = HUB_WEB.read_text()
c = addon_run_constants()
assert f'CONSENT_VERSION = "{c["CONSENT_VERSION"]}"' in web
hub_text = re.search(r'CONSENT_TEXT = M\("([^"]+)"\)', web).group(1)
hub_control = "".join(re.findall(r'"([^"]*)"', re.search(r"CONTROL_TEXT = M\((.*?)\)\n", web, re.S).group(1)))
assert (c["CONSENT_TEXT"], c["CONTROL_TEXT"]) == (hub_text, hub_control)
def test_no_consent_no_connection(box):
run, data, etc = box
(data / "options.json").write_text(json.dumps({"consent_data": False, "consent_control": True, "mode": "shadow",
"claim_code": "ABCD-EFGH-JKLM", "dashboards": True}))
assert run() == {"consent": False} # no link, no agent
assert not (data / "claim-code").exists() and Supervisor.seen == []
c = json.loads((data / "state" / "consent.json").read_text())
assert c["share"] is False and c["control"] is False # control needs sharing too
assert c["by"] == "ha-addon-config"
def test_consent_recorded_and_kept(box):
run, data, etc = box
state = data / "state"
state.mkdir()
(state / "consent.json").write_text(json.dumps({"recipients": {"building": {"granted": True, "at": 5}}}))
assert run()["cmd"][0] == "cantabile-run"
c = json.loads((state / "consent.json").read_text())
assert (c["share"], c["control"], c["by"]) == (True, False, "ha-addon-config")
assert c["source"] == "given at installation in the add-on's configuration"
assert c["text_version"] == addon_run_constants()["CONSENT_VERSION"]
assert c["texts"]["share"].startswith("Cantabile may receive") and c["recipients"]["building"]["granted"]
assert (state / "consent.json").stat().st_mode & 0o077 == 0
# unchanged: when it was given stays
c["at"] = 1000
(state / "consent.json").write_text(json.dumps(c))
run()
assert json.loads((state / "consent.json").read_text())["at"] == 1000
# control given later, then sharing taken back
opts = json.loads((data / "options.json").read_text())
(data / "options.json").write_text(json.dumps(dict(opts, consent_control=True)))
run()
c = json.loads((state / "consent.json").read_text())
assert c["control"] is True and c["at"] > 1000
(data / "options.json").write_text(json.dumps(dict(opts, consent_data=False, consent_control=True)))
assert run() == {"consent": False}
c = json.loads((state / "consent.json").read_text())
assert (c["share"], c["control"]) == (False, False) and c["recipients"]["building"]["granted"]
def test_the_page_says_why_it_is_not_connected():
import importlib.machinery
import importlib.util
loader = importlib.machinery.SourceFileLoader("addon_run", str(RUN))
m = importlib.util.module_from_spec(importlib.util.spec_from_loader("addon_run", loader))
loader.exec_module(m)
en, de = m.waiting_html("en-US,en;q=0.9"), m.waiting_html("de-DE,de;q=0.9")
assert "Cantabile is not connected" in en and "Share energy data with Cantabile" in en and 'lang="en"' in en
assert "Cantabile ist nicht verbunden" in de and "Energiedaten mit Cantabile teilen" in de
# the names it points to are the configuration's
for lang, page in (("en", en), ("de", de)):
t = yaml.safe_load((ADDON / "translations" / f"{lang}.yaml").read_text())["configuration"]
assert t["consent_data"]["name"] in page and t["consent_control"]["name"] in page
def test_the_page_links_to_the_configuration():
import importlib.machinery
import importlib.util
loader = importlib.machinery.SourceFileLoader("addon_run", str(RUN))
m = importlib.util.module_from_spec(importlib.util.spec_from_loader("addon_run", loader))
loader.exec_module(m)
page = m.waiting_html("en", "local_cantabile_edge")
assert 'href="/hassio/addon/local_cantabile_edge/config"' in page and 'target="_top"' in page
assert "prefers-color-scheme:dark" in page
assert "href=" not in m.waiting_html("en", "") and "href=" not in m.waiting_html("en", "x/../y")
+90
View File
@@ -0,0 +1,90 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The EEBUS add-on's manifest: what the Supervisor needs, no more rights
than EEBUS needs (the host's network, nothing else), options = schema =
translations in English and German, the image built from the bridge and
the profiles, and the public repository's rules for its files."""
import re
from pathlib import Path
import pytest
import yaml
ROOT = Path(__file__).resolve().parents[1]
ADDON = ROOT / "cantabile_eebus"
HUB_WEB = ROOT / "hub/mkosi/mkosi.extra/usr/lib/cantabile/web"
def manifest():
return yaml.safe_load((ADDON / "config.yaml").read_text())
def test_manifest():
m = manifest()
assert m["slug"] == ADDON.name and "{arch}" in m["image"] and isinstance(m["version"], str)
assert set(m["arch"]) <= {"amd64", "aarch64"}
assert "mqtt:need" in m["services"]
assert m["ingress"] is True and m["ingress_port"] == 8099 and m["panel_admin"] is True
def test_no_more_rights_than_eebus_needs():
m = manifest()
assert m["host_network"] is True # mDNS and SHIP's announced address
for k in ("privileged", "full_access", "host_pid", "docker_api", "hassio_api", "auth_api", "homeassistant_api",
"devices", "map", "ports"):
assert k not in m, k
assert m.get("hassio_role", "default") == "default"
def test_options_schema_and_translations_agree():
m = manifest()
assert set(m["options"]) <= set(m["schema"])
assert m["options"]["pass_on_limits"] is True and m["options"]["simulate"] is False
for lang in ("en", "de"):
t = yaml.safe_load((ADDON / "translations" / f"{lang}.yaml").read_text())
assert set(t["configuration"]) == set(m["schema"]), lang
for k, v in t["configuration"].items():
assert v["name"] and v["description"], (lang, k)
def test_the_bridge_reads_these_options():
main = (ROOT / "src" / "eebus-bridge" / "main.go").read_text()
for k in manifest()["schema"]:
assert f'json:"{k}"' in main, k
def test_image_and_icons():
d = (ADDON / "Dockerfile").read_text()
assert "src/eebus-bridge/*.go" in d and "src/profiles/*.json" in d and '"-ha"' in d
assert "THIRD-PARTY-NOTICES.md" in d and (ROOT / "src/eebus-bridge/THIRD-PARTY-NOTICES.md").exists()
for n in ("icon.png", "logo.png"):
assert (ADDON / n).read_bytes()[:8] == b"\x89PNG\r\n\x1a\n"
def test_public_repository_rules():
"""Setti Solutions' copyright on every text file."""
for f in ADDON.rglob("*"):
if f.is_dir() or f.suffix == ".png":
continue
text = f.read_text()
assert "Setti Solutions S.R.L" in text and "www.setti.md" in text, f
@pytest.mark.skipif(not HUB_WEB.exists(), reason="the Hub's panel is not in this repository")
def test_consent_to_control_as_the_hubs():
"""consent_control: off until the owner gives it; the bridge records the
Hub's control text and version (hub/.../cantabile/web), as the Cantabile
add-on does; no data consent (nothing leaves the home)."""
m = manifest()
assert m["options"]["consent_control"] is False and m["schema"]["consent_control"] == "bool"
assert "consent_data" not in m["schema"]
go = (ROOT / "src" / "eebus-bridge" / "consent.go").read_text()
text = re.search(r'ControlText\s*=\s*"([^"]+)"', go).group(1)
version = re.search(r'ConsentVersion\s*=\s*"([^"]+)"', go).group(1)
web = HUB_WEB.read_text()
hub_control = "".join(re.findall(r'"([^"]*)"', re.search(r"CONTROL_TEXT = M\((.*?)\)\n", web, re.S).group(1)))
assert text == hub_control
assert f'CONSENT_VERSION = "{version}"' in web
en = yaml.safe_load((ADDON / "translations" / "en.yaml").read_text())["configuration"]
assert text[len("Allow Cantabile"):-1] in " ".join(en["consent_control"]["description"].split())
docs = (ADDON / "DOCS.md").read_text()
assert "## Your consent" in docs and (ADDON / "CHANGELOG.md").exists()
+307
View File
@@ -0,0 +1,307 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The Modbus bridge add-on: its manifest, its devices from the options and
the profiles, the simulator, protection changes on its page, relays (coils),
circuits from Home Assistant's entities, and read-only devices."""
import itertools
import json
import sys
from pathlib import Path
import pytest
import yaml
ROOT = Path(__file__).resolve().parents[1]
ADDON = ROOT / "cantabile_modbus"
sys.path[:0] = [str(ROOT / "src/modbus-bridge"), str(ADDON)]
import bridge # noqa: E402
import cantabile_modbus as mb # noqa: E402
import run # noqa: E402
def test_manifest():
m = yaml.safe_load((ADDON / "config.yaml").read_text())
assert m["slug"] == ADDON.name and "{arch}" in m["image"]
for k in ("host_network", "privileged", "full_access", "docker_api", "hassio_api", "auth_api"):
assert k not in m, k
assert m["homeassistant_api"] is True # circuits from HA's own entities
assert m["map"] == [{"type": "share", "read_only": True}]
assert "mqtt:need" in m["services"]
t = yaml.safe_load((ADDON / "translations/en.yaml").read_text())
assert set(t["configuration"]) == set(m["schema"])
PORTS = itertools.count(25120, 10)
@pytest.fixture
def addon(tmp_path, monkeypatch):
monkeypatch.setattr(run, "PROFILES", str(ROOT / "src/profiles"))
monkeypatch.setattr(run, "DEVICES", str(tmp_path / "devices.json"))
monkeypatch.setattr(run, "POLICY", str(tmp_path / "policy.json"))
monkeypatch.setattr(run, "PLOG", str(tmp_path / "protection.log"))
monkeypatch.setattr(run, "SIM_PORT", next(PORTS)) # a test's simulators stay up
monkeypatch.setattr(bridge, "POLICY", str(tmp_path / "policy.json"))
return tmp_path
def test_devices_from_options_and_simulator(addon):
opts = {"simulate": True, "devices": [{"profile": "hm8042-hybrid", "name": "HM8042", "host": "192.0.2.9", "port": 10000, "unit_id": 10},
{"profile": "no-such", "name": "X", "host": "h", "port": 1, "unit_id": 1}]}
devs = run.make_devices(opts, run.profiles())
assert [d["id"] for d in devs] == ["hm8042"]
d = devs[0]
assert (d["host"], d["port"], d["unit_id"]) == ("127.0.0.1", run.SIM_PORT, 10)
assert json.loads(Path(run.DEVICES).read_text())["devices"][0]["profile"] == "hm8042-hybrid"
values, errors = mb.read_values(mb.Client(d["host"], d["port"], 10), d["registers"])
assert not errors and values["battery_soc"] == 0
def test_protection_changes_are_the_owners_and_logged(addon):
dev = {"id": "spm", "name": "SPM", "registers": [{"key": "relay_2", "table": "holding", "address": 1, "type": "u16",
"write": {"options": {"0": "Off", "1": "On"}}}],
"protection": {"relay_2": {"level": "protected", "refuse": ["0"]}}}
assert run.level_of(dev, "relay_2") == "protected"
assert run.set_level(dev, "relay_2", "none", "Owner")
assert run.level_of(dev, "relay_2") == "none"
log = Path(run.PLOG).read_text()
assert "SPM / relay_2: protected -> none, by Owner" in log
assert not run.set_level(dev, "relay_2", "sealed", "Owner") # sealed never from here
dev["protection"]["relay_2"]["level"] = "sealed"
assert not run.set_level(dev, "relay_2", "none", "Owner")
assert run.level_of(dev, "relay_2") == "sealed"
def test_page_shows_protection(addon):
dev = {"id": "spm", "name": "SPM", "manufacturer": "SONOFF", "model": "SPM", "host": "h", "port": 1, "unit_id": 1,
"registers": [{"key": "relay_2", "name": "SPM-2 LIVINGROOM", "table": "holding", "address": 1, "type": "u16",
"write": {"options": {"0": "Off", "1": "On"}}}],
"protection": {"relay_2": {"level": "protected", "refuse": ["0"]}}}
page = run.page([dev]).decode()
assert "protected · Off refused" in page and ">Lift<" in page and "confirm(" in page # lifting asks first
assert "1 of 1 controls protected" in page and "href='#spm'" in page and "id='spm'" in page
class FakeMQTT:
def __init__(self):
self.sent = {}
def publish(self, topic, payload, retain=False):
self.sent[topic] = payload
def test_inverter_writes_protected_and_no_ac_output(addon):
"""HM8042: only charging source and output source are written, both
refused until the owner lifts them; nothing else (the AC output) can be."""
opts = {"simulate": True, "devices": [{"profile": "hm8042-hybrid", "name": "HM8042", "host": "192.0.2.9", "port": 10000, "unit_id": 10}]}
dev = run.make_devices(opts, run.profiles())[0]
assert {r["key"] for r in dev["registers"] if r.get("write")} == {"charge_from_grid", "output_mode"}
assert all(r["table"] in ("input", "holding", "discrete") for r in dev["registers"]) # discrete: the bypass, read only
b = bridge.Bridge([dev], FakeMQTT())
for key, value in (("charge_from_grid", "Utility & solar"), ("output_mode", "Inverter first"), ("output_mode", "Utility first")):
assert run.level_of(dev, key) == "protected"
assert not b.command(f"cantabile-modbus/hm8042/{key}/set", value.encode())
assert not b.command("cantabile-modbus/hm8042/ac_output/set", b"0")
assert not b.command("cantabile-modbus/hm8042/load_output_status/set", b"0") # a value, never written
# the owner lifts the charging source: written (the simulator) and read back
assert run.set_level(dev, "charge_from_grid", "none", "Owner")
assert b.command("cantabile-modbus/hm8042/charge_from_grid/set", b"Utility & solar")
assert b.mqtt.sent["cantabile-modbus/hm8042/charge_from_grid"] == "Utility & solar"
def test_relays_coils_switches_and_protection(addon):
opts = {"devices": [{"profile": "waveshare-relay-30ch", "name": "Relays", "host": "192.0.2.8", "port": 502, "unit_id": 1,
"simulate": True, "poll_s": 5}]}
dev = run.make_devices(opts, run.profiles())[0]
assert dev["poll_s"] == 10 and dev.get("simulated") and len(dev["registers"]) == 30
c = mb.Client(dev["host"], dev["port"], 1)
values, errors = mb.read_values(c, dev["registers"])
assert not errors and values["relay_1"] == 0 and len(values) == 30
comp, cfg = bridge.entity_config(dev, dev["registers"][16])
assert comp == "switch" and cfg["payload_on"] == "On" and cfg["command_topic"].endswith("/relay_17/set")
b = bridge.Bridge([dev], FakeMQTT())
assert not b.command("cantabile-modbus/relays/relay_3/set", b"Off") # protected: Off refused
assert b.command("cantabile-modbus/relays/relay_3/set", b"On") # On is not refused
assert mb.read_values(c, dev["registers"][2:3])[0] == {"relay_3": 1}
assert run.set_level(dev, "relay_3", "none", "Owner")
assert b.command("cantabile-modbus/relays/relay_3/set", b"Off")
assert mb.read_values(c, dev["registers"][2:3])[0] == {"relay_3": 0}
assert run.level_of(dev, "relay_4") == "protected" # the others stay
def test_read_only_is_a_dry_run(addon):
opts = {"devices": [{"profile": "waveshare-relay-30ch", "name": "Relays", "host": "192.0.2.8", "port": 502, "unit_id": 1,
"simulate": True, "read_only": True}]}
dev = run.make_devices(opts, run.profiles())[0]
b = bridge.Bridge([dev], FakeMQTT())
run.set_level(dev, "relay_5", "none", "Owner")
assert not b.command("cantabile-modbus/relays/relay_5/set", b"On") # allowed, but not written
assert mb.read_values(mb.Client(dev["host"], dev["port"], 1), dev["registers"][4:5])[0] == {"relay_5": 0}
assert "read only" in run.page([dev]).decode()
SPM_STATES = [{"entity_id": "switch.sonoff_ab00000001_1", "state": "on", "attributes": {"friendly_name": "SPM-2 Livingroom"}},
{"entity_id": "switch.sonoff_ab00000001_2", "state": "off", "attributes": {"friendly_name": "SPM-2 Split"}},
{"entity_id": "sensor.spm_2_livingroom", "state": "120.5", "attributes": {}}, # renamed in HA
{"entity_id": "sensor.sonoff_ab00000001_power_2", "state": "unavailable", "attributes": {}},
{"entity_id": "sensor.sonoff_ab00000001_voltage_1", "state": "229.1", "attributes": {}}]
def test_spm_circuits_from_home_assistant(addon, monkeypatch):
import ha_source
opts = {"devices": [{"profile": "sonoff-spm", "name": "SPM 2", "device": "ab00000001"},
{"profile": "sonoff-spm", "name": "No id"}]}
names = {s["entity_id"]: s["attributes"].get("friendly_name") for s in SPM_STATES}
ids = {("sensor", "sonoff", "ab00000001_power_1"): "sensor.spm_2_livingroom",
("select", "sonoff", "ab00000001_2"): "select.sonoff_ab00000001_2"} # the power-on select: same unique id
devs = run.make_devices(opts, run.profiles(), names, ids)
assert [d["id"] for d in devs] == ["spm_2"]
dev = devs[0]
assert dev["source"] == "ha" and len(dev["registers"]) == 20
regs = {r["key"]: r for r in dev["registers"]}
assert regs["circuit_1"]["name"] == "SPM-2 Livingroom" and regs["circuit_3"]["name"] == "Circuit 3"
assert regs["circuit_2"]["entity"] == "switch.sonoff_ab00000001_2"
assert regs["power_1"]["entity"] == "sensor.spm_2_livingroom" and regs["power_2"]["entity"] == "sensor.sonoff_ab00000001_power_2"
calls = []
src = ha_source.HASource(dev, states=lambda: SPM_STATES, service=lambda *a: calls.append(a),
energy=str(addon / "energy.json"))
values, errors = src.read_values(dev["registers"], now=1000)
assert values["circuit_1"] == 1 and values["circuit_2"] == 0 and values["power_1"] == 120.5
assert "power_2" in errors and "energy_1" not in values
monkeypatch.setattr(ha_source, "GAP_S", 3600)
values, _ = src.read_values(dev["registers"], now=1000 + 3600)
assert values["energy_1"] == 120.5 # 1 h at 120.5 W
values, _ = src.read_values(dev["registers"], now=1000 + 3600 + 3601)
assert values["energy_1"] == 120.5 # a gap is not counted
assert ha_source.HASource(dev, states=lambda: SPM_STATES, energy=str(addon / "energy.json")).energy["spm_2/energy_1"] == 120.5
monkeypatch.setattr(ha_source, "ENERGY", str(addon / "energy-{}.json")) # the default: one file per device
other = ha_source.HASource(dict(dev, id="spm_1"), states=lambda: SPM_STATES)
assert other.energy == {} and other.path.endswith("energy-spm_1.json")
# every circuit protected: Off refused, nothing sent to HA
monkeypatch.setitem(bridge.SOURCES, "ha", lambda d: src)
b = bridge.Bridge([dev], FakeMQTT())
for n in range(1, 5):
assert run.level_of(dev, f"circuit_{n}") == "protected"
assert not b.command(f"cantabile-modbus/spm_2/circuit_{n}/set", b"Off")
assert calls == []
disc = bridge.discovery(dev)
sw = disc["homeassistant/switch/cantabile_modbus/spm_2_circuit_1/config"]
assert sw["name"] == "SPM-2 Livingroom" and sw["payload_off"] == "Off"
assert disc["homeassistant/sensor/cantabile_modbus/spm_2_energy_1/config"]["state_class"] == "total_increasing"
# a lifted circuit is switched through HA (another circuit than the livingroom's)
assert run.set_level(dev, "circuit_2", "none", "Owner")
assert b.command("cantabile-modbus/spm_2/circuit_2/set", b"On")
assert calls == [("switch", "turn_on", {"entity_id": "switch.sonoff_ab00000001_2"})]
page = run.page([dev]).decode()
assert "Home Assistant (ab00000001)" in page and "protected · Off refused" in page
def test_page_list_and_device_views(addon, monkeypatch):
"""A list of devices; per device its sets, channels as tiles, the
inverter's flow, the controls with a shared note once; German too."""
monkeypatch.setattr(run, "values", {}); monkeypatch.setattr(run, "statuses", {}); monkeypatch.setattr(run, "hist", {})
opts = {"devices": [{"profile": "hm8042-hybrid", "name": "HM8042", "host": "192.0.2.9", "port": 10000, "unit_id": 10, "simulate": True},
{"profile": "waveshare-relay-30ch", "name": "Relays", "host": "192.0.2.8", "port": 502, "unit_id": 1,
"simulate": True, "read_only": True},
{"profile": "sonoff-spm", "name": "SPM 2", "device": "ab00000001"}]}
names = {s["entity_id"]: s["attributes"].get("friendly_name") for s in SPM_STATES}
devs = run.make_devices(opts, run.profiles(), names, {})
now = 100 * 60
run.record("hm8042", "pv_power", "1400", now - 120)
regs = {"battery_soc": 93, "pv_power": 1520, "load_voltage": 227, "load_current": 2.5, "battery_voltage": 53.2,
"battery_current": -0.9, "grid_power": 0, "bypass": 1, "pv_energy": 346930, "grid_state": 0, "battery_state": 4}
hm = next(d for d in devs if d["id"] == "hm8042")
for topic, v in bridge.states(hm, bridge.derive(hm, regs)).items(): # what the bridge publishes
run.record("hm8042", topic.split("/")[2], v, now)
run.record("hm8042", "status", "online")
for n, (pw, v) in enumerate([("300", "226.1"), ("100", "226.5"), ("0", "226.4"), ("11.5", "226.6")], 1):
run.record("spm_2", f"power_{n}", pw, now); run.record("spm_2", f"voltage_{n}", v, now)
run.record("spm_2", f"energy_{n}", "1.5", now) # kWh, as published; run.record("spm_2", f"circuit_{n}", "On", now)
run.record("relays", "relay_3", "On", now)
monkeypatch.setattr(run.view.time, "time", lambda: now + 30) # seconds, as record()
page = run.page(devs).decode()
lst = page.split("<section")[0]
assert lst.count("class=card href=") == 3 and "Battery charge <b>93 %</b>" in lst and "PV power <b>1.52 kW</b>" in lst
assert "1 of 30 on" in lst and "Total <b>412 W</b>" in lst and "30 of 30 controls protected" in lst
assert "2 of 2 controls protected" in lst and "simulated" in lst and "read only" in lst
assert lst.count(">online<") == 1 and ">offline<" not in lst # no status yet: no badge
hm = page.split("<section class=dev id='hm8042'>")[1].split("</section>")[0]
assert "<svg viewBox='0 0 360 316'" in hm and "568 W" in hm # output
assert "47.9 W" in hm and "discharging" in hm and ">charging<" not in hm # -0.9 A: discharging
assert "≈ 568 W" in hm and "via bypass, estimated" in hm # bypass: grid ≈ output
assert "<line x1=180 y1=246 x2=180 y2=176" in hm # battery -> inverter
assert "Battery · 93 %" in hm and "width=89.3" in hm # SoC bar in its box
assert "<polyline class=spark" in hm and "346.9 kWh" in hm
assert ">Battery state (bits)<" in hm and "Details" in hm # non-zero: shown
assert hm.index("Battery state (bits)") < hm.index("<summary>Details")
spm = page.split("<section class=dev id='spm_2'>")[1].split("</section>")[0]
assert "SPM-2 Livingroom" in spm and "width:73%" in spm and "Voltage 226.4 V" in spm and spm.count("1.5 kWh") == 4
assert spm.count("Off is refused until the owner lifts it") == 1 # the shared note once
rel = page.split("<section class=dev id='relays'>")[1].split("</section>")[0]
assert rel.count("What each relay feeds") == 1 and rel.count("class='grid tiles'") == 1 and rel.count(">Lift<") == 30 and rel.count("· Off refused<") == 1
assert "Protect all" not in rel and "Lift all" not in page
de = run.page(devs, "de").decode()
assert "Alle Geräte" in de and "30 von 30 Steuerungen geschützt" in de
def test_protect_all_never_lifts(addon):
opts = {"devices": [{"profile": "waveshare-relay-30ch", "name": "Relays", "host": "192.0.2.8", "port": 502, "unit_id": 1, "simulate": True}]}
dev = run.make_devices(opts, run.profiles())[0]
for k in ("relay_1", "relay_2"):
assert run.set_level(dev, k, "none", "Owner")
assert "Protect all" in run.page([dev]).decode()
assert run.protect_all(dev, "Owner") == ["relay_1", "relay_2"]
assert all(run.level_of(dev, r["key"]) == "protected" for r in dev["registers"])
assert run.protect_all(dev, "Owner") == []
def test_circuit_names_from_the_registry_when_disabled(monkeypatch):
"""A disabled entity (a circuit's switch) has no
state: its name comes from HA's entity registry."""
import ha_source
monkeypatch.setattr(ha_source, "registry", lambda: ({("switch", "sonoff", "ab00000001_1"): "switch.sonoff_ab00000001_1"},
{"switch.sonoff_ab00000001_1": "SPM-2 Livingroom", "switch.x": None}))
monkeypatch.setattr(ha_source, "call", lambda *a: [{"entity_id": "switch.sonoff_ab00000001_2", "attributes": {"friendly_name": "SPM-2 Split"}}])
names, ids = run.ha_names()
assert names == {"switch.sonoff_ab00000001_1": "SPM-2 Livingroom", "switch.sonoff_ab00000001_2": "SPM-2 Split"}
assert ids[("switch", "sonoff", "ab00000001_1")] == "switch.sonoff_ab00000001_1"
def test_flow_charging_without_bypass():
"""Daytime (03:00 UTC): grid charging, +17.8 A into the battery."""
import page as pg
dev = {"id": "inv", "name": "Inv", "registers": [{"key": k} for k in ("pv", "grid", "soc", "bypass")],
"derived": [{"key": "load"}, {"key": "bat"}],
"view": {"flow": {"pv": "pv", "grid": "grid", "load": "load", "battery": "bat", "soc": "soc", "bypass": "bypass"}}}
vals = {"inv/pv": "106", "inv/grid": "1517", "inv/load": "565", "inv/bat": "961.2", "inv/soc": "92", "inv/bypass": "0"}
vw = pg.View(dev, vals, {})
p = pg.flow(vw)
assert (p["grid"], p["bypass"], round(p["battery"])) == (1517, False, 961)
svg = pg.flow_svg(vw, pg.T["en"])
assert ">charging<" in svg and "≈" not in svg and "estimated" not in svg
assert "<line x1=180 y1=176 x2=180 y2=246" in svg and "<line x1=112 y1=150 x2=130 y2=150" in svg # into battery; grid in
def test_bridge_derived_values_and_kwh(addon):
"""The HM8042's derived values (published as entities with their
quantities) and energy in kWh for HA's statistics."""
opts = {"devices": [{"profile": "hm8042-hybrid", "name": "HM8042", "host": "192.0.2.9", "port": 10000, "unit_id": 10, "simulate": True}]}
dev = run.make_devices(opts, run.profiles())[0]
night = {"load_voltage": 227.0, "load_current": 2.5, "battery_voltage": 53.2, "battery_current": -0.9, "grid_power": 0.0, "bypass": 1,
"pv_energy": 346930}
v = bridge.derive(dev, night)
assert (v["load_power"], v["battery_power"], v["grid_import_power"]) == (567.5, -47.88, 567.5) # bypass: grid feeds the output
day = dict(night, bypass=0, grid_power=1517.4, battery_current=17.8)
v = bridge.derive(dev, day)
assert (v["battery_power"], v["grid_import_power"]) == (946.96, 1517.4)
assert bridge.derive(dev, {"grid_power": 0.0})["grid_import_power"] is None # bypass unknown: no figure
st = bridge.states(dev, bridge.derive(dev, night))
assert st["cantabile-modbus/hm8042/pv_energy"] == "346.93" and st["cantabile-modbus/hm8042/battery_power"] == "-47.88"
disc = bridge.discovery(dev)
e = disc["homeassistant/sensor/cantabile_modbus/hm8042_pv_energy/config"]
assert (e["unit_of_measurement"], e["device_class"], e["state_class"]) == ("kWh", "energy", "total_increasing")
b = disc["homeassistant/sensor/cantabile_modbus/hm8042_battery_power/config"]
assert (b["unit_of_measurement"], b["device_class"], b["unique_id"]) == ("W", "power", "cantabile_modbus_hm8042_battery_power")
assert "homeassistant/sensor/cantabile_modbus/hm8042_grid_import_power/config" in disc