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

+362
View File
@@ -0,0 +1,362 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""v1's parts without Home Assistant: limits, mapping v3, bundles, guard,
executor, commands."""
import asyncio
import json
import os
import time
import pytest
import yaml
from cantabile_edge import limits
from cantabile_edge.bundles import Bundles
from cantabile_edge.consent import Consent
from cantabile_edge.executor import Executor, actions_for
from cantabile_edge.guard import Action, Guard
from cantabile_edge.inputs import Collector
from cantabile_edge.mapping import Mapping
SITE = "ab" * 16
MAPPING = {
"version": 3,
"assets": [{"entity": "sensor.load", "asset": "load.power", "kind": "gauge", "unit": "W", "consent": True}],
"inputs": {"presence": "binary_sensor.home", "outside_temp": "sensor.outside", "weather": "weather.home",
"load_power": "sensor.load"},
"controls": [
{"id": "battery", "kind": "battery", "consent": True,
"entities": {"charge_from_grid": "switch.grid_charge", "setpoint": "number.batt_power",
"soc": "sensor.batt_soc"},
"params": {"capacity_wh": 10000, "max_charge_w": 3000, "max_discharge_w": 3000},
"limits": {"soc_pct": {"owner": [20, 100]}, "power_w": {"owner": [-2000, 2500]}}},
{"id": "living", "kind": "heating", "consent": True,
"entities": {"climate": "climate.living", "temp": "sensor.living_temp"},
"limits": {"temp_c": {"owner": [19, 24], "inhabitant": [20.5, None]}}},
{"id": "boiler", "kind": "heating", "consent": False, "entities": {"switch": "switch.boiler"}},
{"id": "car", "kind": "ev", "consent": True,
"entities": {"switch": "switch.ev", "current": "number.ev_current", "connected": "binary_sensor.ev"}},
{"id": "blind", "kind": "cover", "consent": True, "entities": {"cover": "cover.living"},
"params": {"room": "living"}},
],
}
@pytest.fixture
def mapping(tmp_path):
p = tmp_path / "mapping.yaml"
p.write_text(yaml.safe_dump(MAPPING))
return Mapping.load(str(p))
@pytest.fixture
def consent(tmp_path):
(tmp_path / "consent.json").write_text(json.dumps({"share": True, "control": True}))
return Consent(str(tmp_path))
class Clock:
def __init__(self, t=1_800_000_000.0):
self.t = t
def __call__(self):
return self.t
# -- limits ---------------------------------------------------------------
def test_limits_layers():
# tenant raises the floor within the owner's limits
b = limits.effective((5, 30), {"owner": (19, 24), "inhabitant": (21, None)})
assert (b.lo, b.hi, b.lo_by, b.hi_by) == (21, 24, "inhabitant", "owner")
# a building limit never pushes below the owner's floor
b = limits.effective((5, 30), {"owner": (19, 24), "building": (None, 18)})
assert (b.lo, b.hi) == (19, 19) and b.hi_by == "owner"
# the tenant's raised floor gives way to the building
b = limits.effective((5, 30), {"inhabitant": (22, None), "building": (None, 20)})
assert (b.lo, b.hi) == (20, 20)
# the grid operator over everyone
b = limits.effective((0, 100), {"owner": (30, None), "grid": (None, 10)})
assert (b.lo, b.hi, b.hi_by) == (10, 10, "grid")
# the device's range over every level
b = limits.effective((5, 30), {"owner": (35, None)})
assert (b.lo, b.hi, b.lo_by) == (30, 30, "device")
with pytest.raises(ValueError):
limits.parse({"temp_c": {"landlord": [1, 2]}})
with pytest.raises(ValueError):
limits.parse({"temp_c": {"owner": [25, 20]}})
# -- mapping v3 -------------------------------------------------------------
def test_mapping_v3(mapping):
assert [c.id for c in mapping.controls] == ["battery", "living", "boiler", "car", "blind"]
bat = mapping.controls[0]
assert bat.writable() == {"charge_from_grid": "switch.grid_charge", "setpoint": "number.batt_power"}
assert bat.bounds("power_w").lo == -2000 and bat.bounds("power_w").hi == 2500
assert mapping.inputs.presence == ["binary_sensor.home"]
assert not mapping.controls[2].consent # off by default unless given
@pytest.mark.parametrize("bad, why", [
({"id": "x", "kind": "toaster", "entities": {}}, "kind must be"),
({"id": "x", "kind": "battery", "entities": {"soc": "sensor.s"}}, "needs charge_from_grid or setpoint"),
({"id": "x", "kind": "cover", "entities": {"cover": "switch.c"}}, "must be a cover entity"),
({"id": "load.power", "kind": "cover", "entities": {"cover": "cover.c"}}, "unique among"),
({"id": "x", "kind": "cover", "entities": {"cover": "cover.c"}, "params": {"room": "nope"}}, "no heating"),
({"id": "x", "kind": "ev", "entities": {"switch": "switch.e"}, "params": {"turbo": 1}}, "unknown params"),
])
def test_mapping_v3_refuses(tmp_path, bad, why):
m = dict(MAPPING, controls=[bad])
p = tmp_path / "m.yaml"
p.write_text(yaml.safe_dump(m))
with pytest.raises(ValueError, match=why):
Mapping.load(str(p))
# -- bundles ------------------------------------------------------------------
def test_tariff_and_fallbacks(tmp_path):
b = Bundles(str(tmp_path), SITE, default_price_ct=33)
start = 1_800_000_000 // 900 * 900
p = b.prices(start, 900, 4, start)
assert p.import_ct == [33] * 4 and "default" in p.note
t = {"v": 1, "kind": "tariff", "id": "t1", "site": SITE, "issued": start, "start": start, "step_s": 900,
"steps": 2, "expires": start + 7200, "currency": "EUR", "unit": "ct/kWh",
"import": [10, None], "export": [5, 5]}
(tmp_path / "tariff.json").write_text(json.dumps(t))
p = b.prices(start, 900, 4, start)
assert p.import_ct == [10, 10, 10, 10] and p.export_ct == [5, 5, 0, 0] and "3 of 4" in p.note
p = b.prices(start, 900, 2, start + 7200) # expired: the flat price, said
assert p.import_ct == [10, 10] and "expired" in p.note
os.remove(tmp_path / "tariff.json")
assert "last known flat" in b.prices(start, 900, 1, start).note
t["site"] = "cd" * 16 # another site's file: not taken
(tmp_path / "tariff.json").write_text(json.dumps(t))
assert b.prices(start, 900, 1, start).note.startswith("no tariff")
def test_model_bundle(tmp_path):
b = Bundles(str(tmp_path), SITE)
m = {"v": 1, "kind": "model", "id": "m1", "site": "*", "issued": 1,
"forecasts": {"load_w": {"profile": "hour_of_week", "values": list(range(168))}}}
(tmp_path / "model.json").write_text(json.dumps(m))
s = b.forecast("load_w", 1_800_000_000 // 3600 * 3600, 900, 8, "UTC") # a Friday
assert len(s) == 8 and s[0] == s[3] and s[4] == s[0] + 1
assert b.forecast("pv_w", 0, 900, 8, "UTC") is None
m["forecasts"]["load_w"]["values"] = [1, 2] # malformed: refused, not used
(tmp_path / "model.json").write_text(json.dumps(m))
assert b.forecast("load_w", 0, 900, 8, "UTC") is None
# -- the guard ----------------------------------------------------------------
def mk_guard(mapping, consent, mode="auto", clock=None):
return Guard(mapping.controls, consent, lambda: mode, clock=clock or Clock())
def act(control="living", channel="climate", entity="climate.living", service="set_temperature", value=21.0,
quantity="temp_c", level="plan"):
return Action(control, channel, entity, entity.split(".")[0], service, {"temperature": value}, value, quantity,
level)
def test_guard_checks(mapping, consent):
g = mk_guard(mapping, consent)
assert g.check(act()) == (True, "")
assert not g.check(act(value=25.0))[0] # above the owner's 24
ok, why = g.check(act(value=20.0)) # below the tenant's raised floor 20.5
assert not ok and "floor by inhabitant" in why
assert "not this control's" in g.check(act(entity="climate.bedroom"))[1]
assert "not allowed" in g.check(act(service="turn_off"))[1]
assert "no consent" in g.check(act("boiler", "switch", "switch.boiler", "turn_on", "on", ""))[1]
assert "does not act" in mk_guard(mapping, consent, "advisory").check(act())[1]
def test_guard_needs_site_control_consent(mapping, tmp_path):
(tmp_path / "consent.json").write_text(json.dumps({"share": True})) # data yes, control no
g = mk_guard(mapping, Consent(str(tmp_path)))
assert "has not allowed control" in g.check(act())[1]
def test_guard_rate_cycling_override(mapping, consent):
clk = Clock()
mapping.controls[3].params["min_switch_s"] = 600 # this EV's mapping asks for anti-cycling
g = mk_guard(mapping, consent, clock=clk)
on = act("car", "switch", "switch.ev", "turn_on", "on", "")
off = act("car", "switch", "switch.ev", "turn_off", "off", "")
g.done(on)
clk.t += 60
ok, why = g.check(off)
assert not ok and "minimum 600 s" in why # anti-cycling
assert g.check(Action(**{**off.__dict__, "level": "emergency"}))[0] # an emergency may
clk.t += 600
assert g.check(off)[0]
for _ in range(12): # per control: 12 an hour
g.done(act(value=21.0))
ok, why = g.check(act(value=21.5))
assert not ok and "at most 12" in why # rate limit (12 an hour)
clk.t += 3600
assert g.check(act(value=21.5))[0]
# the owner turns it by hand (after the settle time): hands off for flexible
g.done(act(value=21.0))
clk.t += 120
g.observe("living", "climate.living", 23.0)
ok, why = g.check(act(value=21.5))
assert not ok and "by hand" in why and g.events
assert g.check(act(value=21.5, level="binding"))[0] # a binding command still applies
clk.t += 7200
assert g.check(act(value=21.5))[0]
def test_guard_ignores_the_agents_own_change(mapping, consent):
clk = Clock()
g = mk_guard(mapping, consent, clock=clk)
g.done(act(value=21.0))
clk.t += 10
g.observe("living", "climate.living", 19.0) # still settling: not the owner
clk.t += 200
g.observe("living", "climate.living", 21.0) # what the agent set
assert not g.overridden("living") and not g.events
# -- the executor -------------------------------------------------------------
class FakeHA:
def __init__(self):
self.calls = []
async def call_service(self, domain, service, entity, data, allowed):
assert allowed(domain, service, entity)
assert not allowed(domain, service, "switch.other")
self.calls.append((domain, service, entity, data))
def states(col, **kv):
col.on_entities({"a": {k.replace("__", "."): {"s": v[0], "a": v[1] if len(v) > 1 else {}} for k, v in kv.items()}})
def test_actions_only_where_the_device_differs(mapping):
col = Collector()
states(col, switch__grid_charge=("off",), number__batt_power=("0",), climate__living=("heat", {"temperature": 21}),
switch__ev=("off",), number__ev_current=("6",), cover__living=("open", {"current_position": 100}))
bat, living, _, car, blind = mapping.controls
a = actions_for(bat, {"set": 2000.0, "grid": True}, col)
assert [(x.service, x.value) for x in a] == [("set_value", 2000.0)] # a setpoint: no grid switch
assert actions_for(living, {"set": 21.0}, col) == [] # already 21
assert [x.service for x in actions_for(living, {"set": 22.5}, col)] == ["set_temperature"]
assert [x.service for x in actions_for(car, {"set": 10}, col)] == ["set_value", "turn_on"]
assert [x.value for x in actions_for(blind, {"set": 40.0}, col)] == [40.0]
assert actions_for(blind, "release", col) == []
def test_executor_plan_command_stale(mapping, consent):
clk = Clock()
g = mk_guard(mapping, consent, clock=clk)
col = Collector()
states(col, switch__grid_charge=("off",), number__batt_power=("0",), climate__living=("heat", {"temperature": 21}),
switch__ev=("off",), number__ev_current=("6",), binary_sensor__ev=("on",),
cover__living=("open", {"current_position": 100}))
sent = []
async def publish(kind, data):
sent.append((kind, data))
ex = Executor(mapping.controls, g, col, publish, clock=clk)
ex.plan = {"made": clk.t, "devices": {"living": [{"t": clk.t - 60, "set": 22.0, "why": "keep warm"}],
"battery": [{"t": clk.t - 60, "set": 1500.0, "grid": True, "why": "cheap"}]}}
ha = FakeHA()
asyncio.run(ex.tick(ha, auto=True))
assert ("climate", "set_temperature", "climate.living", {"temperature": 22.0}) in ha.calls
# a battery with a setpoint: the power goes to the setpoint, the grid switch
# stays off (it means "full power" on many inverters)
assert ("number", "set_value", "number.batt_power", {"value": 1500.0}) in ha.calls
assert not any(c[2] == "switch.grid_charge" for c in ha.calls)
assert all(m["result"] == "done" for k, m in sent if k == "action")
# a console command wins over the plan
ok, _ = ex.command({"asset": "living", "set": "23", "level": "binding", "minutes": "30"}, clk.t)
assert ok
ha.calls.clear()
asyncio.run(ex.tick(ha, auto=True))
assert ("climate", "set_temperature", "climate.living", {"temperature": 23.0}) in ha.calls
# out of bounds: refused and reported, not called
ex.commands.clear()
ex.command({"asset": "living", "set": "26", "level": "flexible"}, clk.t)
ha.calls.clear()
sent.clear()
asyncio.run(ex.tick(ha, auto=True))
assert not [c for c in ha.calls if c[2] == "climate.living"]
assert any(m["result"] == "refused" and "outside" in m["why"] for k, m in sent)
# a stale plan: the battery's safe default (no grid charging, power 0)
ex.commands.clear()
clk.t += 3600
states(col, switch__grid_charge=("on",), number__batt_power=("1500",))
ha.calls.clear()
asyncio.run(ex.tick(ha, auto=True))
assert ("switch", "turn_off", "switch.grid_charge", {}) in ha.calls
assert ("number", "set_value", "number.batt_power", {"value": 0.0}) in ha.calls
# nothing in advisory
ha.calls.clear()
asyncio.run(ex.tick(ha, auto=False))
assert ha.calls == []
def test_flexible_command_ends_when_the_owner_overrides(mapping, consent):
clk = Clock()
g = mk_guard(mapping, consent, clock=clk)
col = Collector()
col.observers.append(lambda eid, st, now: g.observe("living", eid, st["a"].get("temperature"), now)
if eid == "climate.living" else None)
states(col, climate__living=("heat", {"temperature": 21}))
sent = []
async def publish(kind, data):
sent.append(data)
ex = Executor(mapping.controls, g, col, publish, clock=clk)
ex.command({"asset": "living", "set": "22", "level": "flexible", "minutes": "120"}, clk.t)
ha = FakeHA()
asyncio.run(ex.tick(ha, auto=True))
clk.t += 300
col.on_entities({"c": {"climate.living": {"+": {"a": {"temperature": 19}}}}}, clk.t)
asyncio.run(ex.tick(ha, auto=True))
assert "living" not in ex.commands
assert any(m["result"] == "overridden" and "flexible command" in m["why"] for m in sent)
# -- end-to-end findings ----------------------------------
def test_battery_without_setpoint_uses_the_grid_switch(mapping):
"""A battery with the switch alone (an HM8042) is driven by it."""
bat = mapping.controls[0]
bat.entities = {"charge_from_grid": "switch.grid_charge", "soc": "sensor.batt_soc"}
col = Collector()
states(col, switch__grid_charge=("off",))
acts = actions_for(bat, {"set": 1500.0, "grid": True}, col)
assert [(a.entity, a.service) for a in acts] == [("switch.grid_charge", "turn_on")]
def test_battery_with_setpoint_turns_a_stray_grid_switch_off(mapping):
bat = mapping.controls[0]
col = Collector()
states(col, switch__grid_charge=("on",), number__batt_power=("0",))
acts = [(a.entity, a.service) for a in actions_for(bat, {"set": 3000.0, "grid": True}, col)]
assert ("switch.grid_charge", "turn_off") in acts
assert ("number.batt_power", "set_value") in acts
def test_anti_cycling_only_for_equipment(mapping, consent):
clk = Clock()
g = mk_guard(mapping, consent, clock=clk)
on = act("car", "switch", "switch.ev", "turn_on", "on", "")
off = act("car", "switch", "switch.ev", "turn_off", "off", "")
g.done(on)
clk.t += 5
assert g.check(off)[0] # an EV charger may switch at once
heat = act("living", "climate", "climate.living", "set_hvac_mode", "heat", "")
stop = act("living", "climate", "climate.living", "set_hvac_mode", "off", "")
g.done(heat)
clk.t += 60
ok, why = g.check(stop)
assert not ok and "minimum 600 s" in why # a heat pump is held
assert g.min_switch_for(mapping.controls[0]) == 0 # battery
assert g.min_switch_for(mapping.controls[4]) == 0 # cover
def test_bundle_stamps_change_with_a_new_file(tmp_path):
b = Bundles(str(tmp_path), SITE)
before = b.stamps()
(tmp_path / "tariff.json").write_text("{}")
assert b.stamps() != before