# 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("93 %" in lst and "PV power 1.52 kW" in lst assert "1 of 30 on" in lst and "Total 412 W" 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("
")[1].split("
")[0] assert "charging<" not in hm # -0.9 A: discharging assert "≈ 568 W" in hm and "via bypass, estimated" in hm # bypass: grid ≈ output assert " inverter assert "Battery · 93 %" in hm and "width=89.3" in hm # SoC bar in its box assert "Battery state (bits)<" in hm and "Details" in hm # non-zero: shown assert hm.index("Battery state (bits)") < hm.index("Details") spm = page.split("
")[1].split("
")[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("
")[1].split("
")[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 "