# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. """From what is wanted to Home Assistant service calls, through the guard. Each control has one wanted value at a time, from (highest first): 1. a command from the console (`control`, with its level: flexible, binding, emergency), until it ends or is released; 2. the current plan's step, while the plan is fresh (made in the last stale_s) and its inputs were fresh; 3. the control's safe defaults (mapping `safe:`), when the plan or its data is stale; a battery's default is no grid charging and power 0. The wanted value becomes actions on the control's channels, but only where the device differs from it (no repeated calls), each checked by the guard. Every action, refusal and owner override is reported (`action` messages: ctb.site..action) and logged; a refusal once per control and reason per hour. A flexible command the owner overrides by hand ends (reported "overridden"); binding and emergency commands are applied again (the flat cannot lift them). """ import logging import time from .guard import Action from .inputs import cover_position, cover_positions, number log = logging.getLogger(__name__) RELEASE = "release" # a safe value meaning: leave the device as it is def _plan_value(plan: dict, cid: str, now: float): cur = None for e in (plan or {}).get("devices", {}).get(cid, []): if e["t"] <= now: cur = e return cur def actions_for(c, want, col, level="plan", why="") -> list[Action]: """The actions that bring control c to `want` (a plan entry's set, a command's set, or a safe value), only where the device differs.""" e = c.entities out = [] def act(channel, service, data, value, quantity=""): ent = e[channel] out.append(Action(c.id, channel, ent, ent.split(".", 1)[0], service, data, value, quantity, level, why)) def switch(channel, on: bool): if channel in e and (col.state(e[channel]) == "on") != on: act(channel, "turn_on" if on else "turn_off", {}, "on" if on else "off") def setnum(channel, v: float, quantity: str): if channel in e and (number(col.state(e[channel])) is None or abs(number(col.state(e[channel])) - v) > 0.5): act(channel, "set_value", {"value": v}, v, quantity) if want is None or want == RELEASE: return out if c.kind == "battery": if isinstance(want, dict): # a plan entry: power and whether from the grid power, grid = float(want.get("set", 0)), bool(want.get("grid")) auto = bool(want.get("auto")) # the inverter's own self-consumption (optimizer._entry) else: power, grid = float(want), float(want) > 0 auto = abs(power) < 50 # a command: about 0 is the inverter's own mode # With a setpoint the power is set there and the grid switch stays # off (it means "full power" on many inverters and would override # the setpoint); a battery with the switch alone is driven by it. switch("charge_from_grid", grid and "setpoint" not in e) if "mode" in e: # the inverter's own mode: its self-consumption where the plan's # battery balances the house, else manual at the plan's power (0: # hold, the self-consumption mode would discharge); the setpoint # counts in manual only opt = str(c.p("auto_option") if auto else c.p("manual_option")) if col.state(e["mode"]) != opt: act("mode", "select_option", {"option": opt}, opt) if opt == str(c.p("auto_option")): return out # the setpoint counts in manual only: not touched setnum("setpoint", power, "power_w") elif c.kind in ("heating", "cooling"): v = want.get("set") if isinstance(want, dict) else want if "climate" in e: c.learn_range(col) step = c.temp_step(col) if number(v) is not None and step: # the thermostat's step (0.5, 1): a value it can take lo, hi = c.device_range("temp_c") r = round(float(v) / step) * step r = r + step if r < lo - 1e-9 else r - step if r > hi + 1e-9 else r v = round(r, 3) state = col.state(e["climate"]) mode = "cool" if c.kind == "cooling" else "heat" if v == "off": if state not in ("off", None): act("climate", "set_hvac_mode", {"hvac_mode": "off"}, "off") elif number(v) is not None: if state != mode: act("climate", "set_hvac_mode", {"hvac_mode": mode}, mode) cur = number(col.attr(e["climate"], "temperature")) if cur is None or abs(cur - float(v)) > 0.25: act("climate", "set_temperature", {"temperature": float(v)}, float(v), "temp_c") elif v in ("on", "off"): switch("switch", v == "on") elif c.kind == "ev": v = want.get("set") if isinstance(want, dict) else want if v == "off": switch("switch", False) elif number(v) is not None: setnum("current", float(v), "current_a") switch("switch", True) elif c.kind == "cover": v = number(want.get("set") if isinstance(want, dict) else want) if v is not None: if col.state(e["cover"]) in ("opening", "closing"): return out # moving: wait for it to stop cur = cover_position(col, e["cover"]) if cover_positions(col, e["cover"]): if cur is None or abs(cur - v) > 2: act("cover", "set_cover_position", {"position": int(round(v))}, v, "position_pct") elif v >= 50 and cur != 100.0: # open and close only: halfway or more is open act("cover", "open_cover", {}, 100.0, "position_pct") elif v < 50 and cur != 0.0: act("cover", "close_cover", {}, 0.0, "position_pct") return out def building_msg(c: dict, result: str, why: str, at: float) -> dict: """An `action` message about a building request (agreed form).""" return {"v": 1, "at": int(at), "asset": "", "entity": f"building:{c['building']}", "service": f"building.{c['control']}", "value": c["value"], "result": result, "why": why, "level": c["level"], "id": c["id"]} def safe_want(c): """The control's safe value when plans or data are stale.""" if c.kind == "battery": s = c.safe or {} sp = float(s.get("setpoint", 0)) return {"set": sp, "grid": bool(s.get("charge_from_grid", False)), "auto": abs(sp) < 50} v = (c.safe or {}).get(next(iter(c.writable()), ""), RELEASE) return v class Executor: def __init__(self, controls, guard, col, publish, *, stale_s=1800, clock=time.time, building=None): self.building = building # the building's requests (building.py), or None self.controls = {c.id: c for c in controls} self.guard, self.col, self.publish, self.stale, self.clock = guard, col, publish, stale_s, clock self.plan: dict | None = None self.inputs_ok = True self.commands: dict[str, dict] = {} # control -> {"set", "level", "until", "id", "why"} self._refused: dict[tuple, float] = {} self.log: list[dict] = [] # the last actions (tests, status) # -- what is wanted ------------------------------------------------------ def wanted(self, c, now): want, level, why = self._wanted(c, now) return self._capped(c, want, level, why, now) def _wanted(self, c, now): cmd = self.commands.get(c.id) if cmd and now < cmd["until"]: return cmd["set"], cmd["level"], cmd.get("why") or f"{cmd['level']} command" if cmd: self.commands.pop(c.id, None) fresh = self.plan is not None and now - self.plan.get("made", 0) <= self.stale and self.inputs_ok if fresh: e = _plan_value(self.plan, c.id, now) return e, "plan", (e or {}).get("why", "") return safe_want(c), "plan", "safe default: the plan or its data is stale" def _capped(self, c, want, level, why, now): """The building's thermostat cap on a climate's setpoint (heating: at most, cooling: at least), at the cap's level: a binding cap applies again when the owner changes it by hand.""" if self.building is None or "climate" not in c.entities: return want, level, why cap, cmd = self.building.cap(c.kind, now) if cap is None: return want, level, why v = want.get("set") if isinstance(want, dict) else want if number(v) is None: return want, level, why v = float(v) capped = min(v, cap) if c.kind == "heating" else max(v, cap) if capped == v and level != "plan": return want, level, why lvl = cmd["level"] if level in ("plan", "flexible") else level return {"set": capped}, lvl, f"building {cmd['building']}: {cmd['why'] or 'thermostat cap'} ({cap:g} °C)" # -- one round --------------------------------------------------------------- async def tick(self, client, auto: bool): """One round: overrides seen since the last, then each control. With auto False only overrides are reported (the guard refuses anyway).""" now = self.clock() await self._overrides(now) if not auto or client is None: return sw = self.guard.switchover for c in self.controls.values(): if sw is not None and not sw.active(c): continue # the thermostat's other control acts (switchover.py) want, level, why = self.wanted(c, now) acts = actions_for(c, want, self.col, level, why) if why.startswith("building") and not any(a.channel == "climate" for a in acts): # the room is within the building's cap already: a change by # hand still counts as an override of the cap self.guard.expect(c.id, c.entities["climate"], want["set"]) for a in acts: await self._do(client, a, now) async def _do(self, client, a: Action, now): ok, reason = self.guard.check(a) if not ok: key = (a.control, reason.split(" ")[0] + reason[-12:]) if now - self._refused.get(key, 0) >= 3600: self._refused[key] = now await self._report(a, "refused", reason, now) return try: await client.call_service(a.domain, a.service, a.entity, a.data, self._allowed(a)) except Exception as e: await self._report(a, "failed", str(e)[:200], now) return self.guard.done(a) await self._report(a, "done", a.why, now) @staticmethod def _allowed(a: Action): """The HA client's check: exactly this action and nothing else.""" return lambda d, s, ent: (d, s, ent) == (a.domain, a.service, a.entity) async def _overrides(self, now): while self.guard.events: ev = self.guard.events.pop(0) c = self.controls.get(ev["control"]) cap, bcmd = self.building.cap(c.kind, now) if self.building is not None and c else (None, None) if bcmd is not None and "climate" in c.entities and ev["entity"] == c.entities["climate"]: await self._building_override(bcmd, ev) cmd = self.commands.get(ev["control"]) if cmd and cmd["level"] == "flexible": self.commands.pop(ev["control"], None) # the owner wins over a flexible command why = f"the owner changed it by hand: flexible command {cmd.get('id', '')} ended" elif cmd: why = f"the owner changed it by hand: {cmd['level']} command applied again" else: why = f"the owner changed it by hand: hands off until {time.strftime('%H:%M UTC', time.gmtime(ev['until']))}" await self.publish("action", {"v": 1, "at": ev["at"], "asset": ev["control"], "entity": ev["entity"], "service": "", "value": ev["value"], "result": "overridden", "why": why}) log.info("override: %s %s=%s (%s)", ev["control"], ev["entity"], ev["value"], why) self.log.append({"result": "overridden", **ev}) async def _building_override(self, bcmd, ev): """The owner changed a room the building's cap holds: a flexible cap ends, a binding one stays (applied again).""" if bcmd["level"] == "flexible": self.building.lift("thermostat_cap") why = "the owner changed it by hand: the flexible cap ended" else: why = "the owner changed it by hand: the binding cap applied again" await self.publish("action", building_msg(bcmd, "overridden", why, ev["at"])) async def _report(self, a: Action, result, why, now): msg = {"v": 1, "at": int(now), "asset": a.control, "entity": a.entity, "service": f"{a.domain}.{a.service}", "value": a.value, "result": result, "why": why, "level": a.level} self.log.append(msg) self.log = self.log[-200:] log.info("action %s: %s %s %s=%s (%s)", result, a.control, msg["service"], a.entity, a.value, why) await self.publish("action", msg) # -- commands from the console ------------------------------------------ def command(self, args: dict, now: float) -> tuple[bool, str]: cid = args.get("asset", "") c = self.controls.get(cid) if c is None: return False, f"no control {cid!r}" sw = self.guard.switchover if sw is not None and not sw.active(c): return False, f"{cid}: not active now (the thermostat is on its other side: switchover)" level = args.get("level", "flexible") if level not in ("flexible", "binding", "emergency"): return False, "level: flexible, binding or emergency" try: until = float(args["until"]) if args.get("until") else now + 60 * float(args.get("minutes", 60)) except ValueError: return False, "until: unix time, or minutes" if until <= now: return False, "already over" v = args.get("set", "") want = float(v) if number(v) is not None else v if want in ("", None): return False, "set: a value" self.commands[cid] = {"set": want, "level": level, "until": until, "id": args.get("id", ""), "why": args.get("why") or f"{level} command"} return True, f"{cid}: {want} ({level}) until {time.strftime('%H:%M UTC', time.gmtime(until))}" def release(self, cid: str) -> tuple[bool, str]: if self.commands.pop(cid, None) is None: return False, f"no command for {cid!r}" return True, f"{cid}: back to the plan"