# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. """The actuation guard: every action the agent would take goes through check() first, and only an allowed one becomes a Home Assistant service call (executor.py). In this order: 0. policy the device's protection (policy.py): never anything on a sealed device, never off on a protected one, whatever the command's level 0b. switchover a thermostat that heats and cools: only its active control (heating or cooling, switchover.py) may act 1. mode only in `auto` (shadow and advisory never act) 2. consent the owner's for the site ("control" in consent.json) and the control's own (mapping v3), both off by default 3. allow-list the control's own entities, with the service its kind uses 4. bounds inside the effective floors and limits (limits.py: the device's range, the owner's, the building's, the cloud's, the grid operator's) 5. override the owner changed it by hand: the agent keeps off it for override_hold_s (flexible), unless a binding or emergency command says otherwise (3b command levels) 6. cycling a switch stays on/off for its minimum time (anti-cycling; only for equipment that wears from short cycles: heating, cooling) 7. rate at most max_actions_per_hour per control; a cover moves at most once in its params.min_move_s (default 30 min) Emergency commands skip 5-7 (nobody overrides them; device safety and the bounds still hold). Binding ones skip 5: the flat cannot lift them, only the building or the cloud. Every refusal has a reason, and is reported once per control and reason per hour (not every minute). """ import time from dataclasses import dataclass, field LEVELS = ("plan", "flexible", "binding", "emergency") # plan: the optimiser's own @dataclass class Action: control: str channel: str # the entity role (charge_from_grid, setpoint, climate, switch, current, cover) entity: str domain: str service: str data: dict value: float | str # what is set (W, °C, A, %, "on"/"off"/"cool"/...) quantity: str = "" # what bounds it (temp_c, power_w, current_a, position_pct; "" for on/off) level: str = "plan" why: str = "" @dataclass class _Track: times: list = field(default_factory=list) # when actions were taken (rate limit) switched: dict = field(default_factory=dict) # channel -> (time, value) of the last on/off change commanded: dict = field(default_factory=dict) # entity -> (time, value) the agent last set override_until: float = 0.0 override_entity: str = "" moved: float = -1e18 # when a cover was last moved by the agent changed: dict = field(default_factory=dict) # "mode" | "set" -> when the agent last changed it (steady.py) # The service each channel uses, by domain: nothing else can be called. SERVICES = { "switch": {"turn_on", "turn_off"}, "input_boolean": {"turn_on", "turn_off"}, "number": {"set_value"}, "input_number": {"set_value"}, "climate": {"set_temperature", "set_hvac_mode"}, "cover": {"set_cover_position", "open_cover", "close_cover"}, "select": {"select_option"}, "input_select": {"select_option"}, "water_heater": {"set_temperature"}, } class Guard: def __init__(self, controls, consent, mode=lambda: "shadow", *, override_hold_s=7200, min_switch_s=600, max_actions_per_hour=12, settle_s=90, clock=time.time): self.controls = {c.id: c for c in controls} self.consent, self.mode, self.clock = consent, mode, clock self.hold, self.min_switch, self.max_rate, self.settle = override_hold_s, min_switch_s, max_actions_per_hour, settle_s self.extra_limits: dict = {} # control -> quantity -> level -> (floor, limit), from commands self.policy = None # policy.Policy: the devices' protection self.switchover = None # switchover.Switchover: heating or cooling now self.track: dict[str, _Track] = {} self.events: list[dict] = [] # overrides seen (the executor reports them) def min_switch_for(self, c) -> float: """Anti-cycling time for this control: the mapping's params.min_switch_s if set; else the guard's min_switch_s for kinds whose equipment wears from short cycles (heating, cooling: their default is > 0), and 0 for batteries, EV chargers and covers.""" if "min_switch_s" in (c.params or {}): return float(c.params["min_switch_s"]) from .controls import PARAMS return float(self.min_switch) if PARAMS.get(c.kind, {}).get("min_switch_s", 0) > 0 else 0.0 def _t(self, cid) -> _Track: return self.track.setdefault(cid, _Track()) def bounds(self, c, q): return c.bounds(q, self.extra_limits.get(c.id)) def check(self, a: Action) -> tuple[bool, str]: now = self.clock() c = self.controls.get(a.control) if c is None: return False, "no such control" if self.policy is not None: why = self.policy.refuses(a, c) if why: return False, why if self.switchover is not None and not self.switchover.active(c): return False, f"{c.kind} is not active now (switchover: the thermostat's other control is)" if self.mode() != "auto": return False, f"mode {self.mode()}: the agent does not act" if not self.consent.control: return False, "the owner has not allowed control (site consent)" if not c.consent: return False, "no consent for this control" if c.writable().get(a.channel) != a.entity: return False, f"{a.entity} is not this control's {a.channel}" if a.service not in SERVICES.get(a.domain, ()) or a.entity.split(".", 1)[0] != a.domain: return False, f"{a.domain}.{a.service} is not allowed for {a.entity}" if a.quantity: b = self.bounds(c, a.quantity) try: v = float(a.value) except (TypeError, ValueError): return False, f"{a.value!r} is not a number" if not b.holds(v): return False, (f"{v:g} outside {b.lo:g}..{b.hi:g} {a.quantity} " f"(floor by {b.lo_by}, limit by {b.hi_by})") tr = self._t(c.id) urgent = a.level == "emergency" if now < tr.override_until and a.level not in ("binding", "emergency"): return False, f"the owner changed {tr.override_entity} by hand: hands off until {_hhmm(tr.override_until)}" min_switch = self.min_switch_for(c) if not urgent and min_switch > 0 and a.quantity == "" and a.channel in tr.switched: when, last = tr.switched[a.channel] if last != a.value and now - when < min_switch: return False, f"switched {last} {int(now - when)} s ago (minimum {min_switch:g} s)" tr.times = [t for t in tr.times if now - t < 3600] if not urgent and c.kind == "cover" and now - tr.moved < float(c.p("min_move_s")): return False, (f"moved {int(now - tr.moved)} s ago (at most once in {float(c.p('min_move_s')):g} s)") if not urgent and len(tr.times) >= self.max_rate: return False, f"{len(tr.times)} actions in the last hour (at most {self.max_rate})" return True, "" def done(self, a: Action): """An action was carried out: count it, remember what was set.""" now = self.clock() tr = self._t(a.control) tr.times.append(now) tr.commanded[a.entity] = (now, a.value) c = self.controls.get(a.control) boiler = c is not None and c.kind in ("heating", "cooling") and a.channel == "switch" # a hybrid's heat source: its own hold (steady.py _hold_source) tr.changed["source" if a.channel == "source" else "set" if a.quantity or boiler else "mode"] = now if a.domain == "cover": tr.moved = now if a.quantity == "": prev = tr.switched.get(a.channel) if prev is None or prev[1] != a.value: tr.switched[a.channel] = (now, a.value) def expect(self, control_id: str, entity: str, value): """The agent wants this value and the device already has it (no action needed): a later change by hand counts as an override, as if the agent had set it (not counted as an action).""" tr = self._t(control_id) if entity not in tr.commanded: tr.commanded[entity] = (self.clock() - self.settle, value) def observe(self, control_id: str, entity: str, value, now: float | None = None, by: str = ""): """A state change of a control's entity: if it differs from what the agent set, and not right after the agent set it, the owner changed it by hand. by: who changed it (changed_by), reported with the override.""" now = self.clock() if now is None else now tr = self._t(control_id) cmd = tr.commanded.get(entity) if cmd is None: return when, want = cmd c = self.controls.get(control_id) cover = c is not None and c.kind == "cover" if now - when < self.settle or _same(value, want, 3.0 if cover else 0.26): return # a shade the owner moved: off it for its own pause (params.override_hold_s) tr.override_until = now + (float(c.p("override_hold_s")) if cover else self.hold) tr.override_entity = entity tr.commanded.pop(entity, None) self.events.append({"control": control_id, "entity": entity, "value": value, "agent_set": want, "until": int(tr.override_until), "at": int(now), "by": by}) def last_change(self, control_id: str, kind: str) -> float | None: """When the agent last changed a control's mode or setpoint (kind "mode" | "set"; a boiler's on/off is its setpoint), or None.""" return self._t(control_id).changed.get(kind) def overridden(self, control_id: str) -> bool: return self.clock() < self._t(control_id).override_until def changed_by(ctx) -> str: """Who changed an entity, from Home Assistant's context of the new state (subscribe_entities sends it as "c": the context's id alone when it has no user and no parent, else {"id", "user_id", "parent_id"}): resident a person signed in to HA (its app or dashboard, the box's panel through HA): the context has a user automation an automation or script in HA: a parent context, no user device neither: the device or its integration reported the change itself (a button or dial on the device, its own app, its manual mode) "" no context reported (an older HA, a test) The agent's own calls never reach here as overrides: the guard skips a value it set itself.""" if isinstance(ctx, str) and ctx: return "device" if isinstance(ctx, dict): if ctx.get("user_id"): return "resident" if ctx.get("parent_id"): return "automation" return "device" if ctx.get("id") else "" return "" def _same(a, b, tol: float = 0.26) -> bool: try: return abs(float(a) - float(b)) < tol except (TypeError, ValueError): return str(a) == str(b) def _hhmm(t: float) -> str: return time.strftime("%H:%M UTC", time.gmtime(t))