# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. """Shades (ha-cover, shades.py), temperature sensors (ha-climate-sensor) and weather services (ha-weather): which devices the profiles offer (never a garage door, never the box's own CPU temperature), their fragments and the owner's settings, the shade's rules on the sun, the guard around them, the dashboard and the plan in words.""" import json import pathlib from datetime import datetime, timezone from zoneinfo import ZoneInfo import pytest import yaml from cantabile_edge import dashboards, devprofiles as dp, propose, shades from cantabile_edge.consent import Consent from cantabile_edge.executor import actions_for from cantabile_edge.guard import Action, Guard from cantabile_edge.inputs import Collector, model_state from cantabile_edge.mapping import Mapping from cantabile_edge.policy import Policy ROOT = pathlib.Path(__file__).resolve().parents[2] PROFILES = {p["id"]: p for p in propose.load_profiles(str(ROOT / "profiles"))} BERLIN = {"latitude": 52.52, "longitude": 13.40} # -- which profile, which device --------------------------------------------------------------- def registry(*devices): """devices: (id, manufacturer, model, platform, [(entity_id, device_class, category)], entry_type).""" reg = {"areas": [{"area_id": "bedroom", "name": "Bedroom"}], "devices": [], "entities": []} for dev_id, maker, model, platform, ents, *kind in devices: reg["devices"].append({"id": dev_id, "name": dev_id, "manufacturer": maker, "model": model, "domains": [platform], "area_id": "bedroom", "entry_type": kind[0] if kind else None}) for eid, dc, *cat in ents: reg["entities"].append({"entity_id": eid, "device_id": dev_id, "unique_id": eid, "platform": platform, "device_class": dc, "entity_category": cat[0] if cat else None}) return reg def offered(reg): return {o["id"]: o["profiles"] for o in dp.offers(reg, PROFILES.values())} def test_covers_offered_never_a_garage_door(): reg = registry( ("rbs", "SONOFF", "MINI-RBS", "sonoff", [("cover.left_curtain", None)]), # SonoffLAN: no class ("blind", "Somfy", "RTS", "somfy", [("cover.kitchen_blind", "blind")]), ("garage", "Meross", "MSG100", "meross", [("cover.garage", "garage")]), ("gate", "Nice", "Gate", "nice", [("cover.gate", "gate")]), ("both", "Shelly", "2PM", "shelly", [("cover.awning", "awning"), ("cover.door", "door")]), ("damper", "Acme", "Vent", "acme", [("cover.vent", "damper")]), ("window", "Velux", "Window", "velux", [("cover.roof_window", "window")])) got = offered(reg) assert got["rbs"] == ["ha-cover"] and got["blind"] == ["ha-cover"] for dev in ("garage", "gate", "both", "damper", "window"): assert got[dev] == [], dev # not even generic: never offered # a specific profile first: an SPM's sonoff device stays the SPM's spm = {"manufacturer": "SONOFF", "model": "SPM-Main"} fits = dp.fitting(PROFILES.values(), spm, ["sonoff"], ["cover", "sensor.power"]) assert all(not dp.fallback(p) for p in fits) or fits == [] def test_temperature_sensors_offered_not_system_or_device_internal(): reg = registry( ("esp", "Espressif", "esp32", "esphome", [("sensor.office_temp", "temperature"), ("sensor.office_hum", "humidity"), ("sensor.esp_internal", "temperature", "diagnostic"), ("sensor.esp_battery", "battery")]), ("zb", "Xiaomi", "LYWSD03MMC", "zha", [("sensor.bath_temp", "temperature")]), ("ble", "Govee", "H5075", "govee_ble", [("sensor.balcony_temp", "temperature")]), ("snzb", "SONOFF", "SNZB-02D", "zha", [("sensor.living_temp", "temperature")]), ("ac", "Espressif", "esp32", "esphome", [("climate.ac", None), ("sensor.ac_temp", "temperature")]), ("sysmon", "Home Assistant", "System Monitor", "systemmonitor", [("sensor.processor_temperature", "temperature")]), ("inverter", "Growatt", "MIN", "growatt", [("sensor.inv_temp", "temperature"), ("sensor.inv_power", "power")]), ("diag", "Acme", "Router", "acme", [("sensor.router_temp", "temperature", "diagnostic")]), ("met", "Met.no", "Forecast", "met", [("weather.home", None), ("sensor.met_temp", "temperature")], "service"), ("backup", "Home Assistant", "Backup", "backup", [("sensor.backup_state", None)], "service")) got = offered(reg) assert got["esp"] == got["zb"] == got["ble"] == ["ha-climate-sensor"] assert got["snzb"] == ["sonoff-snzb-02"] # its own profile assert got["ac"] == ["ha-thermostat"] # a thermostat stays one assert got["sysmon"] == [] and got["inverter"] == [] and got["diag"] == [] assert got["met"] == ["ha-weather"] # a weather service is offered assert "backup" not in got # other services are not # -- fragments and the owner's settings ------------------------------------------------------- def cover_ent(eid="cover.left_curtain", **attrs): return {"entity_id": eid, "device_id": "d", "unique_id": eid, "attributes": dict({"current_position": 100, "supported_features": 15}, **attrs)} def test_cover_fragment_protected_with_its_room(): p = PROFILES["ha-cover"] s = dp.setup_for(p, ["sonoff"]) frag, missing = dp.mapping_for("ha-cover-1", p, s, [cover_ent()], "Bedroom", set()) (c,) = frag["controls"] assert c["kind"] == "cover" and c["entities"] == {"cover": "cover.left_curtain"} and c["consent"] is False assert c["params"]["area"] == "bedroom" and c["params"]["min_move_s"] == 1800 assert [a["asset"] for a in frag["assets"]] == ["room.bedroom.shade_position"] and missing == ["room.{area}.shade_tilt"] prot = dp.profile_protection("ha-cover-1", p, s, [cover_ent()], frag, now=1) assert prot[f"control:{c['id']}"]["level"] == "protected" # the owner: room and window thermo = {"profile": "ha-thermostat", "assets": [{"asset": "room.living_room.temp"}], "controls": [{"id": "heating", "kind": "heating"}, {"id": "cooling", "kind": "cooling"}]} sh = dp.set_shade(frag, {"area": "Living room", "facing": "SW"}, [thermo]) assert sh == {"area": "living_room", "facing": 225.0, "room": "heating"} assert dp.set_shade(frag, {"area": "", "facing": "275"}) == {"area": "", "facing": 275.0, "room": ""} with pytest.raises(dp.Fail): dp.set_shade(frag, {"facing": "up"}) with pytest.raises(dp.Fail): dp.set_shade({"controls": [{"kind": "heating"}]}, {"facing": "N"}) def test_sensor_indoor_outdoor_and_second_reading(): p = PROFILES["ha-climate-sensor"] ents = [{"entity_id": "sensor.office_temp", "device_id": "d", "unique_id": "t", "device_class": "temperature"}, {"entity_id": "sensor.office_hum", "device_id": "d", "unique_id": "h", "device_class": "humidity"}, {"entity_id": "sensor.esp_internal", "device_id": "d", "unique_id": "i", "device_class": "temperature", "entity_category": "diagnostic"}] taken = {"room.office.temp"} # the room has a temperature already frag, _ = dp.mapping_for("ha-climate-sensor-1", p, dp.setup_for(p, ["esphome"]), ents, "Office", set(taken)) assert {a["asset"]: a["entity"] for a in frag["assets"]} == {"room.office.temp_2": "sensor.office_temp", "room.office.humidity": "sensor.office_hum"} assert dp.place_of(frag) == {"place": "indoor", "area": "office"} dp.set_place(frag, {"place": "outdoor"}, taken) assert {a["asset"] for a in frag["assets"]} == {"outside.temp", "outside.humidity"} assert frag["inputs"] == {"outside_temp": "sensor.office_temp"} and dp.place_of(frag)["place"] == "outdoor" dp.set_place(frag, {"place": "indoor", "area": "Bedroom"}, taken) assert {a["asset"] for a in frag["assets"]} == {"room.bedroom.temp", "room.bedroom.humidity"} and "inputs" not in frag with pytest.raises(dp.Fail): dp.set_place(frag, {"place": "attic"}) def test_one_weather_source_and_a_measured_outdoor_wins(tmp_path): p = PROFILES["ha-weather"] s = dp.setup_for(p, ["met"]) w = {"entity_id": "weather.home", "device_id": "m", "unique_id": "w", "attributes": {"temperature": 8.0, "humidity": 70, "cloud_coverage": 40}} met, _ = dp.mapping_for("ha-weather-1", p, s, [w], None, set()) assert met["inputs"] == {"weather": "weather.home"} assert {a["asset"] for a in met["assets"] if a.get("fallback")} == {"outside.temp", "outside.humidity"} owm, _ = dp.mapping_for("ha-weather-2", p, s, [dict(w, entity_id="weather.owm")], None, {"outside.temp", "outside.humidity"}) dp.one_weather(owm, [met]) assert "inputs" not in owm and dp.weather_of(owm) == {"active": False, "entity": "weather.owm"} frags = {"ha-weather-1": met, "ha-weather-2": owm} dp.set_weather(frags, "ha-weather-2") assert dp.weather_of(met)["active"] is False and owm["inputs"] == {"weather": "weather.owm"} dp.set_weather(frags, "ha-weather-1") assert dp.weather_of(met)["active"] is True and "inputs" not in owm # the agent: an outdoor thermometer takes outside.temp and the outside temperature sensor = {"version": 3, "device": "ha-climate-sensor-1", "profile": "ha-climate-sensor", "assets": [{"entity": "sensor.balcony_temp", "asset": "outside.temp_2", "kind": "gauge", "unit": "°C"}], "inputs": {"outside_temp": "sensor.balcony_temp"}} (tmp_path / "mapping.d").mkdir() (tmp_path / "mapping.yaml").write_text(yaml.safe_dump({"version": 3, "assets": [], "inputs": {"outside_temp": "sensor.forecast_helper"}})) for name, f in (("a-weather", met), ("b-sensor", sensor)): (tmp_path / "mapping.d" / f"{name}.yaml").write_text(json.dumps(f)) m = Mapping.load(str(tmp_path / "mapping.yaml")) assert m.by_asset["outside.temp"].entity == "sensor.balcony_temp" assert m.by_asset["outside.temp_2"].entity == "weather.home" and m.by_asset["outside.temp_2"].fallback assert m.inputs.outside_temp == "sensor.balcony_temp" and m.inputs.weather == "weather.home" # -- the rules ---------------------------------------------------------------------------------- def ts(y, mo, d, h=0, tz="Europe/Berlin"): return int(datetime(y, mo, d, h, tzinfo=ZoneInfo(tz)).timestamp()) def state(start, steps=96, t_out=30.0, occupied=1, prices=None, location=BERLIN): return {"start": start, "step_s": 900, "steps": steps, "tz": "Europe/Berlin", "t_out": [t_out] * steps, "occupied": [occupied] * steps if isinstance(occupied, int) else occupied, "price_import": prices or [30.0] * steps, "sky": [1.0] * steps, "location": location} def shade(facing=270, pos=100, **params): return {"id": "curtain", "kind": "cover", "params": dict({"facing": facing}, **params), "state": {"position_pct": pos}, "bounds": {"position_pct": [0, 100]}} def moves(sch, start): out = [] for k, v in enumerate(sch["set"]): if v is not None: local = datetime.fromtimestamp(start + k * 900, timezone.utc).astimezone(ZoneInfo("Europe/Berlin")) out.append((local.strftime("%H:%M"), v, sch["why"][k])) return out def test_sun_position(): # Berlin, midsummer: the sun in the south at about 13:10 CEST, 61° high; in the west in the evening el, az = shades.sun_position(ts(2026, 6, 21, 13) + 600, 52.52, 13.40) assert 59 < el < 62 and 170 < az < 190 el, az = shades.sun_position(ts(2026, 6, 21, 19), 52.52, 13.40) assert 10 < el < 25 and 270 < az < 300 assert shades.sun_position(ts(2026, 6, 21, 1), 52.52, 13.40)[0] < 0 assert shades.facing("sw") == 225 and shades.facing(-1) is None and shades.compass(260) == "W" def test_summer_west_facade_closes_in_the_afternoon_sun(): start = ts(2026, 7, 15) sch = shades.schedule(shade(270), state(start), {"temp_c": 26.0, "setpoint_c": 24.0}) m = moves(sch, start) assert m[0][1] == 30 and m[0][2] == "sun on the west facade" and "13:00" <= m[0][0] <= "15:00", m assert m[1][1] == 100 and m[1][2] == "the sun has left the west facade" and "19:00" <= m[1][0] <= "21:30", m assert len(m) == 2 # nobody home: closed all the way assert moves(shades.schedule(shade(270), state(start, occupied=0), {"temp_c": 26.0, "setpoint_c": 24.0}), start)[0][1] == 0 # a cool room on a mild day: nothing at stake assert moves(shades.schedule(shade(270), state(start, t_out=20.0), {"temp_c": 21.0, "setpoint_c": 24.0}), start) == [] # ... unless the evening is dear: shaded before it dear = [30.0] * 64 + [60.0] * 32 m = moves(shades.schedule(shade(270), state(start, t_out=20.0, prices=dear), {"temp_c": 21.0, "setpoint_c": 24.0}), start) assert m and m[0][2] == "sun on the west facade: before the dear hours" # the morning sun is on the east facade, not on the west one m = moves(shades.schedule(shade(90), state(start), {"temp_c": 26.0, "setpoint_c": 24.0}), start) assert "07:00" <= m[0][0] <= "09:00" and m[0][2] == "sun on the east facade", m def test_winter_opens_in_the_sun_closes_at_night_never_in_quiet_hours(): start = ts(2026, 1, 15) sch = shades.schedule(shade(180, pos=0), state(start, steps=192, t_out=2.0), {"season": "heating"}) m = moves(sch, start) assert m[0][1] == 100 and m[0][2] == "winter sun on the south facade: its warmth in" and m[0][0] >= "08:00", m assert m[1][1] == 0 and m[1][2] == "night: closed to keep the warmth in" and "16:00" <= m[1][0] <= "18:00", m assert m[2][1] == 100 and m[2][0] >= "07:00", m # the next morning, after the quiet hours assert not any("22:00" <= t or t < "07:00" for t, _, _ in m) # quiet from 16:00: the night's closing waits for its end (and is never in the dark opened) noon = ts(2026, 1, 15, 12) m = moves(shades.schedule(shade(180, pos=100, quiet_from="16:00", quiet_to="23:00"), state(noon, steps=48, t_out=2.0), {"season": "heating"}), noon) assert m == [("23:00", 0, "night: closed to keep the warmth in")] # the owner allows moves at night m = moves(shades.schedule(shade(180, pos=100, quiet_from="16:00", quiet_to="23:00", night_moves=1), state(noon, steps=48, t_out=2.0), {"season": "heating"}), noon) assert m[0][1] == 0 and m[0][0] < "18:00" # the facade not known: only the night's closing and the morning's opening m = moves(shades.schedule(shade(-1, pos=100), state(start, steps=192, t_out=2.0), {"season": "heating"}), start) assert [v for _, v, _ in m] == [0, 100, 0] and m[1][2] == "morning: open again" # the evening, the morning, the evening # no location: nothing at all assert moves(shades.schedule(shade(180), state(start, location={}), {}), start) == [] def test_unpriced_steps_are_no_dear_hours(): # the tariff's prices end before the horizon (None after: bundles.prices), or there is none at all # (2026-11-05: every plan of a flat with a shade failed summing them) start = ts(2026, 7, 15) cool = {"temp_c": 21.0, "setpoint_c": 24.0} dear = [30.0] * 64 + [60.0] * 16 + [None] * 16 m = moves(shades.schedule(shade(270), state(start, t_out=20.0, prices=dear), cool), start) assert m and m[0][2] == "sun on the west facade: before the dear hours" # no prices: no dear hours (no stand-in price); the warm room still shaded assert moves(shades.schedule(shade(270), state(start, t_out=20.0, prices=[None] * 96), cool), start) == [] m = moves(shades.schedule(shade(270), state(start, prices=[None] * 96), {"temp_c": 26.0, "setpoint_c": 24.0}), start) assert m[0][2] == "sun on the west facade" # the winter's rules use no price: the same moves with the tail unpriced jan = ts(2026, 1, 15) full = shades.schedule(shade(180, pos=0), state(jan, t_out=2.0), {"season": "heating"}) part = shades.schedule(shade(180, pos=0), state(jan, t_out=2.0, prices=[30.0] * 90 + [None] * 6), {"season": "heating"}) assert part["set"] == full["set"] def test_minimum_interval_between_moves(): start = ts(2026, 7, 15) flip = [k % 2 for k in range(96)] # occupancy changing every quarter hour sch = shades.schedule(shade(270, min_move_s=3600), state(start, occupied=flip), {"temp_c": 26.0, "setpoint_c": 24.0}) at = [k for k, v in enumerate(sch["set"]) if v is not None] assert len(at) >= 2 and all(b - a >= 4 for a, b in zip(at, at[1:])) def test_a_shade_the_agent_moved_moves_back_in_the_next_plans(): # 2026-11-05: Munich 1's shade closed for the night on 30 October and stayed # closed: every plan after the move started from the closed shade and no # longer knew why it was closed, so the morning's opening was never planned evening = ts(2026, 1, 15, 17) night = {"season": "heating"} assert moves(shades.schedule(shade(-1, pos=0), state(evening, t_out=2.0), night), evening) == [] m = moves(shades.schedule(shade(-1, pos=0), state(evening, t_out=2.0), dict(night, ours="night")), evening) assert m[0][1:] == (100, "morning: open again") and m[0][0] >= "07:00", m # summer: shaded from the sun, opened again when the sun has left noon = ts(2026, 7, 15, 16) warm = {"temp_c": 26.0, "setpoint_c": 24.0} sch = shades.schedule(shade(270, pos=30), state(noon, steps=32), dict(warm, ours="shade")) assert moves(sch, noon)[0][1:] == (100, "the sun has left the west facade") # the rule each move is for, into the plan's entry start = ts(2026, 1, 15) sch = shades.schedule(shade(-1, pos=100), state(start, steps=192, t_out=2.0), night) assert [r for r, v in zip(sch["rule"], sch["set"]) if v is not None] == ["night", "", "night"] def test_moves_kept_while_the_shade_is_where_the_agent_put_it(tmp_path): mv = shades.Moves(str(tmp_path)) assert mv.ours("curtain", 0.0) is None mv.record("curtain", "night", 0.0, 1_800_000_000) assert mv.ours("curtain", 2.0) == "night" assert mv.ours("curtain", 40.0) is None # moved by hand: the owner's position stays assert mv.ours("curtain", None) is None again = shades.Moves(str(tmp_path)) # across a restart assert again.ours("curtain", 0.0) == "night" again.record("curtain", "", 100.0, 1_800_050_000) # opened again: nothing of ours assert again.ours("curtain", 100.0) is None # -- the plan, the guard, the executor ----------------------------------------------------------- MAPPING = {"version": 3, "assets": [], "controls": [{"id": "curtain", "kind": "cover", "consent": True, "entities": {"cover": "cover.curtain"}, "params": {"facing": 270, "area": "bedroom"}}, {"id": "rbs", "kind": "cover", "consent": True, "entities": {"cover": "cover.rbs"}}]} class Clock: def __init__(self, t): self.t = t def __call__(self): return self.t @pytest.fixture def site(tmp_path): (tmp_path / "mapping.yaml").write_text(yaml.safe_dump(MAPPING)) (tmp_path / "consent.json").write_text(json.dumps({"share": True, "control": True})) return tmp_path def move(control="curtain", entity="cover.curtain", value=30.0, service="set_cover_position"): return Action(control, "cover", entity, "cover", service, {"position": int(value)}, value, "position_pct") def test_guard_override_pause_min_interval_shadow_and_protection(site): m = Mapping.load(str(site / "mapping.yaml")) clk = Clock(1_800_000_000.0) mode = ["auto"] g = Guard(m.controls, Consent(str(site)), lambda: mode[0], clock=clk) assert g.check(move()) == (True, "") g.done(move()) clk.t += 600 ok, why = g.check(move(value=100.0)) assert not ok and "at most once in 1800" in why # the minimum interval # the owner moves it by hand: off it for 4 hours (not the 2 of a thermostat) g.observe("curtain", "cover.curtain", 31, clk.t) # where it was told: no override assert not g.overridden("curtain") g.observe("curtain", "cover.curtain", 80, clk.t) assert g.overridden("curtain") and g.events[-1]["until"] == int(clk.t + 14400) clk.t += 3 * 3600 assert "by hand" in g.check(move(value=0.0))[1] clk.t += 3600 + 1 assert g.check(move(value=0.0)) == (True, "") # never in shadow or advisory for mo in ("shadow", "advisory"): mode[0] = mo assert g.check(move(value=0.0))[1].startswith(f"mode {mo}") mode[0] = "auto" # protected: never moved at all (open as much as closed) (site / "protection.json").write_text(json.dumps({"v": 1, "entries": {"control:curtain": {"level": "protected", "at": 1}}})) g.policy = Policy(str(site), "ab" * 16, clk) for v, svc in ((100.0, "set_cover_position"), (0.0, "close_cover"), (100.0, "open_cover")): ok, why = g.check(move(value=v, service=svc)) assert not ok and why.startswith("protected: Cantabile does not move it"), svc def test_executor_open_close_only_and_waits_while_moving(site): m = Mapping.load(str(site / "mapping.yaml")) curtain, rbs = m.controls col = Collector() col.on_entities({"a": {"cover.curtain": {"s": "open", "a": {"current_position": 100, "supported_features": 15}}, "cover.rbs": {"s": "open", "a": {"supported_features": 11}}}}) assert [(a.service, a.value) for a in actions_for(curtain, {"set": 30}, col)] == [("set_cover_position", 30.0)] assert [(a.service, a.value) for a in actions_for(rbs, {"set": 30}, col)] == [("close_cover", 0.0)] assert actions_for(rbs, {"set": 80}, col) == [] # open already assert actions_for(curtain, {"set": None}, col) == [] # a hold between moves col.on_entities({"c": {"cover.curtain": {"+": {"s": "closing"}}}}) assert actions_for(curtain, {"set": 0}, col) == [] # moving: wait def test_model_state_gives_each_shade_its_schedule(site): m = Mapping.load(str(site / "mapping.yaml")) class Bundles: def prices(self, *a): from types import SimpleNamespace return SimpleNamespace(import_ct=[30.0] * 192, export_ct=[8.0] * 192, note="t") def forecast(self, *a): return None def model_id(self): return "" col = Collector() col.on_entities({"a": {"cover.curtain": {"s": "open", "a": {"current_position": 100}}, "sensor.out": {"s": "31"}}}) m.inputs.outside_temp = "sensor.out" forecast = [{"datetime": datetime.fromtimestamp(ts(2026, 7, 15) + h * 3600, timezone.utc).isoformat(), "temperature": 25.0, "cloud_coverage": 0} for h in range(49)] s = model_state(ts(2026, 7, 15), m.controls, m.inputs, col, Bundles(), None, "Europe/Berlin", forecast, location=BERLIN, shade_ctx={"curtain": {"temp_c": 26.0, "setpoint_c": 24.0}}) d = next(x for x in s["devices"] if x["id"] == "curtain") assert any(v == 30 for v in d["schedule"]["set"]) and s["sky"][0] == 1.0 # a thermometer outside: the forecast moved to what it measures now assert s["t_out"][0] == 31.0 and s["t_out"][30] == 25.0 and "outdoor sensor" in s["sources"]["t_out"] def test_optimizer_takes_the_schedule(): pytest.importorskip("highspy") from cantabile_edge import optimizer start = ts(2026, 7, 15) s = state(start, steps=96) s.update(price_export=[8.0] * 96, price_note="t", load_w=[400.0] * 96, pv_w=[0.0] * 96, sun=[0.5] * 96) room = {"id": "ac", "kind": "cooling", "channels": ["climate"], "params": {"r_k_per_kw": 10, "c_kwh_per_k": 3, "max_power_w": 1500, "comfort_c": 25, "setup_c": 28, "cop": 3}, "state": {"temp_c": 26.0}, "bounds": {"temp_c": [18, 30, "owner", "owner"]}} d = dict(shade(270), params={"facing": 270, "room": "ac", "gain_w": 800}, channels=["cover"]) d["schedule"] = shades.schedule(d, s, {"temp_c": 26.0, "setpoint_c": 24.0}) s["devices"] = [room, d] p = optimizer.plan(s, 20) sets = [e for e in p["devices"]["curtain"] if e["set"] is not None] assert [e["set"] for e in sets] == [30, 100] and sets[0]["why"] == "sun on the west facade" # -- in words: the plan, the dashboard, the page --------------------------------------------------- def test_words(): assert shades.say(30) == "close to 30 %" and shades.say(100) == "open" and shades.say(0) == "close" assert shades.say(30, "de") == "auf 30 % schließen" assert shades.why_words("sun on the west facade", "de") == "Sonne auf der Westseite" assert shades.why_words("night: closed to keep the warmth in", "de").startswith("Nacht") def test_announce_coming_up_in_words(tmp_path): from test_announce import make from test_control_parts import MAPPING as BASE import time a, ann = make(tmp_path, dict(BASE, controls=BASE["controls"][:4] + [dict(BASE["controls"][4], name="Bedroom curtains")])) now = time.time() a.control.plan = {"made": now, "devices": {"blind": [{"t": now - 60, "set": None, "why": ""}, {"t": now + 600, "set": 30, "why": "sun on the west facade"}, {"t": now + 1500, "set": None, "why": ""}]}} st = ann._plan_state() assert st["next"].startswith("Bedroom curtains: close to 30 % at ") and st["next"].endswith("— sun on the west facade") assert [n["set"] for n in st["attrs"]["next"]] == ["close to 30 %"] # holds are not listed assert st["controls"]["blind"]["now"] == "-" def test_dashboard_cover_features(): assert dashboards.cover_features({"supported_features": 15}) == [{"type": "cover-position"}] assert dashboards.cover_features({"supported_features": 11}) == [{"type": "cover-open-close"}] assert dashboards.cover_features({"supported_features": 15 | 128}) == [{"type": "cover-position"}, {"type": "cover-tilt-position"}] def test_addon_devices_page_shade(tmp_path): import contextvars from cantabile_edge import i18n from test_devpage import Site, ent, st s = Site(tmp_path) s.ha.reg["areas"].append({"area_id": "bedroom", "name": "Bedroom"}) s.ha.reg["devices"] += [ {"id": "rbs", "name": "Left curtain", "manufacturer": "SONOFF", "model": "MINI-RBS", "area_id": "bedroom", "config_entries": ["e4"]}, {"id": "garage", "name": "Garage", "manufacturer": "Meross", "model": "MSG100", "config_entries": ["e5"]}] s.ha.reg["entities"] += [ent("cover.left_curtain", "rbs", "c1", "sonoff"), ent("cover.garage", "garage", "g1", "meross")] s.ha.states += [st("cover.left_curtain", "unavailable", supported_features=15), # its class: none (SonoffLAN) st("cover.garage", "unavailable", device_class="garage")] # unavailable: still a garage out = s.req() assert 'name="ha_device" value="rbs"' in out and 'name="ha_device" value="garage"' not in out s.post(do="use", ha_device="rbs", profile="ha-cover", name="Left curtain") dev_id = next(i for i, d in s.devices().items() if d["profile"] == "ha-cover") out = s.req(query=f"p=devices&d={dev_id}") assert "Room and window" in out and '' in out assert "Controls: blinds and curtains" in out and "Allow Cantabile to move it" in out s.post(do="use", ha_device="dev-ac", profile="ha-thermostat") # the living room's A/C ac = next(i for i, d in s.devices().items() if d["profile"] == "ha-thermostat") s.post(do="shade", id=dev_id, area="Living room", facing="SE") p = next(c for c in s.frag(dev_id)["controls"] if c["kind"] == "cover")["params"] assert (p["area"], p["facing"]) == ("living_room", 135.0) assert p["room"] in {c["id"] for c in s.frag(ac)["controls"]} # its sun counts in the A/C's room m = Mapping.load(str(s.mapping)) # another device's room: kept assert next(c for c in m.controls if c.kind == "cover").p("room") == p["room"] assert "the window faces" in s.post(do="shade", id=dev_id, facing="up") def run(): i18n.use("de") return s.req(query=f"p=devices&d={dev_id}") de = contextvars.copy_context().run(run) assert "Raum und Fenster" in de and "Südosten" in de and "Bewegen durch Cantabile erlauben" in de def test_executor_keeps_what_a_planned_move_was_for(site): import asyncio from cantabile_edge.controller import Controller from cantabile_edge.config import Config m = Mapping.load(str(site / "mapping.yaml")) clk = Clock(float(ts(2026, 1, 15, 17))) cfg = Config(site_id="ab" * 16, mapping=str(site / "mapping.yaml"), state_dir=str(site)) ctl = Controller(cfg, m, Consent(str(site)), sink=None, clock=clk) ctl.mode.set("auto", "test") ctl.col.on_entities({"a": {"cover.curtain": {"s": "open", "a": {"current_position": 100, "supported_features": 15}}, "cover.rbs": {"s": "open", "a": {"supported_features": 11}}}}) called = [] class Client: async def call_service(self, domain, service, entity, data, allowed): called.append((service, entity, data)) t = int(clk.t) ctl.executor.plan = {"made": t, "devices": { "curtain": [{"t": t, "set": 0, "why": "night: closed to keep the warmth in", "rule": "night"}], "rbs": [{"t": t, "set": None, "why": ""}]}} asyncio.run(ctl.executor.tick(Client(), True)) assert called == [("set_cover_position", "cover.curtain", {"position": 0})] ctl.col.on_entities({"c": {"cover.curtain": {"+": {"s": "closed", "a": {"current_position": 0}}}}}) assert ctl.shade_ctx()["curtain"]["ours"] == "night" and "ours" not in ctl.shade_ctx()["rbs"] # kept across a restart: the next morning's plan opens it again = Controller(cfg, m, Consent(str(site)), sink=None, clock=clk) again.col.on_entities({"a": {"cover.curtain": {"s": "closed", "a": {"current_position": 0}}}}) assert again.shade_ctx()["curtain"]["ours"] == "night" assert again.mode() == "auto" and again.mode.source().startswith("set by test at ")