# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. """No command flapping (sim-munich-1 in auto, 2026-11-03): plans at the quarter hour, the quarter under way kept by a bundle's plan, a deadband, a hold and a least gain per change (steady.py), the battery's self-consumption mode where the plan's battery balances the house, a thermostat at its target while no heat is planned, honest labels.""" import pytest from cantabile_edge import steady from cantabile_edge.controller import plan_wait from cantabile_edge.controls import Control from cantabile_edge.executor import actions_for from cantabile_edge.inputs import Collector T0 = 1_800_000_000 // 900 * 900 # a quarter hour def bat(): return Control("battery", "battery", {"setpoint": "number.bp", "mode": "select.bm"}, True, {"capacity_wh": 10000, "max_charge_w": 2500, "max_discharge_w": 2500}) def hp(**params): return Control("hp", "heating", {"climate": "climate.hp"}, True, dict({"cop": 3.0}, **params)) def car(): return Control("car", "ev", {"switch": "switch.wb", "current": "number.wb_a"}, True, {}) def col_with(**kv): col = Collector() col.on_entities({"a": {k.replace("__", "."): {"s": v[0], "a": v[1] if len(v) > 1 else {}} for k, v in kv.items()}}) return col def plan_of(cid, entries, steps=8): return {"made": T0, "start": T0, "step_s": 900, "devices": {cid: [dict({"t": T0 + 900 * k, "why": "plan"}, **e) for k, e in entries]}} def state(steps=8, price=None, devices=(), export=8.0): return {"steps": steps, "price_import": price or [30.0] * steps, "price_export": [export] * steps, "devices": list(devices)} # -- 1. the cause: plans at the quarter hour ------------------------------------------------ def test_plans_at_the_quarter_hour(): assert plan_wait(T0 + 12 * 60, 900) == pytest.approx(3 * 60 + 5) # made at :12: the next at :15:05 assert plan_wait(T0 + 5, 900) == pytest.approx(900) # made at :00:05: the next at :15:05 assert plan_wait(T0 + 4, 900) == pytest.approx(1) # just before: at once (at least 1 s) assert plan_wait(T0 + 60, 900) == pytest.approx(845) def test_a_bundles_plan_keeps_the_quarter_under_way(): old = plan_of("hp", [(0, {"set": 20.5}), (1, {"set": 20.0})]) new = plan_of("hp", [(0, {"set": 20.0}), (2, {"set": 21.0})]) steady.carry_quarter(new, old, T0 + 12 * 60) assert [(e["t"] - T0, e["set"]) for e in new["devices"]["hp"]] == [(0, 20.5), (900, 20.0), (1800, 21.0)] # a plan of the next quarter: as it is nxt = plan_of("hp", [(0, {"set": 20.0})]) nxt["start"] = T0 + 900 assert steady.carry_quarter(nxt, old, T0 + 960)["devices"]["hp"][0]["set"] == 20.0 # -- 2. deadband ---------------------------------------------------------------------------- def test_battery_deadband_and_its_mode(): col = col_with(number__bp=("1200",), select__bm=("manual",)) p = plan_of("battery", [(0, {"set": 1350.0, "grid": True}), (1, {"set": 200.0, "grid": True}), (2, {"set": 150.0, "grid": True})]) steady.stabilise(p, state(), [bat()], col, None, T0) got = [(e["t"] - T0, e["set"], e["why"][:30]) for e in p["devices"]["battery"]] # 150 W off 1200: kept (deadband 300 W); 1000 W off: done; 50 W off that: kept assert got[0][1] == 1200.0 and got[0][2].startswith("kept: a change of 150 W") assert got[1][:2] == (900, 200.0) assert len(got) == 2 and p["kept"] == 2 def test_temperature_needs_half_a_kelvin_and_half_an_hour(): col = col_with(climate__hp=("heat", {"temperature": 20.0})) # the see-saw: 20.5 for one quarter, then 20.0 again: no command p = plan_of("hp", [(0, {"set": 20.5}), (1, {"set": 20.0}), (2, {"set": 20.5}), (3, {"set": 20.0})]) steady.stabilise(p, state(), [hp()], col, None, T0) assert [e["set"] for e in p["devices"]["hp"]] == [20.0] assert "less than 30 min" in p["devices"]["hp"][0]["why"] # 21 for an hour: done p = plan_of("hp", [(0, {"set": 21.0}), (4, {"set": 20.0})]) steady.stabilise(p, state(), [hp()], col, None, T0) assert [e["set"] for e in p["devices"]["hp"]] == [21.0, 20.0] def test_ev_current_two_amps(): col = col_with(switch__wb=("on",), number__wb_a=("10",)) p = plan_of("car", [(0, {"set": 11}), (1, {"set": 13})]) steady.stabilise(p, state(), [car()], col, None, T0) assert [e["set"] for e in p["devices"]["car"]] == [10.0, 13] # -- 3. hold ---------------------------------------------------------------------------------- def test_hold_per_kind_and_configurable(): col = col_with(number__bp=("1500",), select__bm=("manual",)) last = {("battery", "mode"): T0 - 600, ("battery", "set"): T0 - 300} p = plan_of("battery", [(0, {"set": 0.0, "grid": False, "auto": True})]) steady.stabilise(p, state(), [bat()], col, lambda c, k: last.get((c, k)), T0) e = p["devices"]["battery"][0] assert e["set"] == 1500.0 and "changed 10 min ago (hold 30 min)" in e["why"] # the same with a 5-minute hold for modes (params.hold_mode_s) b = bat() b.params["hold_mode_s"] = 300 p = plan_of("battery", [(0, {"set": 0.0, "grid": False, "auto": True})]) steady.stabilise(p, state(), [b], col, lambda c, k: last.get((c, k)), T0) assert p["devices"]["battery"][0].get("auto") is True # a setpoint 5 minutes after the last: held for 15 minutes, then done p = plan_of("battery", [(0, {"set": 2500.0, "grid": True}), (1, {"set": 2500.0, "grid": True})]) steady.stabilise(p, state(price=[10.0] + [40.0] * 7), [bat()], col, lambda c, k: last.get((c, k)), T0) assert [(e["t"] - T0, e["set"]) for e in p["devices"]["battery"]] == [(0, 1500.0), (900, 2500.0)] # -- 4. gain ---------------------------------------------------------------------------------- def test_least_gain(): col = col_with(number__bp=("1000",), select__bm=("manual",)) # 1000 -> 1500 W where a kWh is worth nothing moved (one price, feed-in at it): kept p = plan_of("battery", [(0, {"set": 1500.0, "grid": True})]) steady.stabilise(p, state(export=30.0), [bat()], col, None, T0) assert p["devices"]["battery"][0]["set"] == 1000.0 and "gain below 1 ct" in p["devices"]["battery"][0]["why"] p = plan_of("battery", [(0, {"set": 1500.0, "grid": True})]) steady.stabilise(p, state(price=[10.0] + [40.0] * 7), [bat()], col, None, T0) assert p["devices"]["battery"][0]["set"] == 1500.0 # 0.5 kW x 15 min x 32 ct = 4 ct p = plan_of("battery", [(0, {"set": 1500.0, "grid": True})]) b = bat() b.params["min_gain_ct"] = 5.0 steady.stabilise(p, state(price=[10.0] + [40.0] * 7), [b], col, None, T0) assert p["devices"]["battery"][0]["set"] == 1000.0 # -- exceptions ------------------------------------------------------------------------------- def test_a_value_outside_the_bounds_is_never_kept(): """The grid operator's order (or a new limit) lowered the bound under what is set: the plan's value goes, deadband or not.""" col = col_with(switch__wb=("on",), number__wb_a=("16",)) p = plan_of("car", [(0, {"set": 15})]) d = {"id": "car", "params": {}, "bounds": {"current_a": [0, 15.0, "device", "grid"]}} steady.stabilise(p, state(devices=[d]), [car()], col, None, T0) assert p["devices"]["car"][0]["set"] == 15 def test_guard_records_the_changes(): from cantabile_edge.consent import Consent from cantabile_edge.guard import Action, Guard import tempfile with tempfile.TemporaryDirectory() as d: g = Guard([bat(), hp(), Control("boiler", "heating", {"switch": "switch.b"}, True, {})], Consent(d), clock=lambda: T0) g.done(Action("battery", "mode", "select.bm", "select", "select_option", {}, "manual")) g.done(Action("battery", "setpoint", "number.bp", "number", "set_value", {}, 100.0, "power_w")) g.done(Action("boiler", "switch", "switch.b", "switch", "turn_on", {}, "on")) assert g.last_change("battery", "mode") == T0 and g.last_change("battery", "set") == T0 assert g.last_change("boiler", "set") == T0 and g.last_change("boiler", "mode") is None # -- the battery's own mode, the thermostat, the labels ------------------------------------------ def test_battery_self_consumption_and_hold(): pytest.importorskip("highspy") from cantabile_edge import optimizer from test_optimizer import battery, house s = house([battery(soc=50, floor=10)], steps=16) s["price_import"] = [40.0] * 8 + [20.0] * 8 # dear now, cheap later: cover the house now p = optimizer.plan(s, 10) first = p["devices"]["battery"][0] assert first.get("auto") is True and first["why"].startswith("self-consumption") col = col_with(number__bp=("700",), select__bm=("manual",)) acts = actions_for(bat(), first, col) assert [(a.service, a.value) for a in acts] == [("select_option", "self-consumption")] # no setpoint # hold (0 W while the grid supplies the house): manual at 0, not self-consumption (it would discharge) acts = actions_for(bat(), {"set": 0.0, "grid": False}, col) assert [(a.service, a.value) for a in acts] == [("set_value", 0.0)] def test_thermostat_at_its_target_without_heat(): pytest.importorskip("highspy") from cantabile_edge import optimizer from test_optimizer import heating, house d = heating(temp=24.0) # a warm room: no heat for hours s = house([d], steps=16) p = optimizer.plan(s, 10) first = p["devices"]["heating"][0] # not the predicted 23.x (a thermostat would hold it by heating): the target, 17 at night, 21 by day assert first["set"] in (17.0, 21.0) and first["set"] < 23.0 def test_cheap_only_in_the_cheapest_quarter(): from cantabile_edge.optimizer import _charge_why pi = [30.0] * 24 + [47.6] * 8 + [50.0] * 16 assert _charge_why(pi, 0).startswith("cheap grid power") assert _charge_why(pi, 24).startswith("charge for dearer hours later (47.6 ct now, 50.0 ct") assert _charge_why([50.0] * 4, 3) == "charge from the grid (50.0 ct)" def test_a_replayed_morning_is_quiet(): """A replay (replay_flapping.py) of three hours: at most 2 commands an hour, the heat pump not every quarter hour.""" pytest.importorskip("highspy") import replay_flapping per, total, _eur, _kh = replay_flapping.run(hours=3, steps=48, how="after") assert total <= 2.0, per assert per.get(("heat_pump", "set_temperature"), 0) <= 1.0, per