# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. """The building's requests to this flat (agreed with the building side, 2026-10-28). Fleet sends a signed command `building` (the link checks it like every command) with string args: {"v": "1", "id", "building", "level": "flexible|binding", "control": "load_limit|shift_request|thermostat_cap|battery_plan", "value", "from": unix, "until": unix (<= from + 24 h), "why"} load_limit the flat's highest grid import, W, in [from, until) shift_request kWh the flat is asked to move out of [from, until): the optimiser decides how and where (a soft target) thermostat_cap the highest heating setpoint, °C (cooling: the lowest) battery_plan the building's one plan for its battery (2026-11-05: the coordinator plans the building's battery; the building's own box follows it instead of planning it again at its own tariff). Two more args: "schedule": "w0,w1,..." the battery's grid-side power per step from `from`, W (+ charge, - discharge), exactly (until - from) / step_s values, each finite and |w| <= 1e6; "step_s": "900" (only 900). "value" is the first slot's W. Never an emergency. The plan tracks it at a price per kWh of deviation: above any electricity price, far below the owner's floors and the battery's SoC bounds, which win (optimizer.py Model.battery_plan). Kept with its schedule. The binding (2026-11-09): a box that took a battery_plan stays bound to that building after the plan ends ("battery_bound" in building.json: the building, the level, since, the last plan's until). A bound battery's step that no plan covers (the plan lapsed: the coordinator sent no renewal; or beyond its 24 h within the box's 48 h) is self-consumption only: charged from the house's PV surplus, discharged for the house's own use, never charged from the grid or discharged into it for the box's own tariff (optimizer.py Model.battery_plan, docs/methods.md A9.4). The battery serves the building's flats, which the box's own plan cannot see. Ended only when the box leaves that building (membership.json without it) or the owner lifts a flexible battery plan by hand. Rules: always within the flat's own floors (a cap below the comfort floor of the owner or the tenant is refused: "floor"); a newer command for the same control replaces the older; each is dropped at `until`. The level sits in the 3b ladder: binding, the flat's owner cannot lift it (applied again); flexible, the owner's change by hand ends it. Everything else is in each command. Kept in /building.json across restarts. Membership (2026-10-29, joining a building): the Hub's panel writes /membership.json {"buildings": [ids]} after the owner joined or left (the buildings and communities this site belongs to, and the building whose own box it is; /usr/lib/cantabile/building). With it, a command from any other building is refused ("not a member"), besides fleet's own check. Without it (an HA add-on, an older panel), fleet's check alone decides. The optimiser takes them as constraints (a cap, a limit: binding nearly hard, flexible with a price) and a soft target (a shift). Results go out as `action` messages with entity "building:", service "building.". """ import json import math import os import time CONTROLS = ("load_limit", "shift_request", "thermostat_cap", "battery_plan") PENALTY = { # EUR per unit across a building's request in the plan # per kWh, per kWh, per K·h; battery_plan per kWh of the battery's deviation from the building's # plan: above any electricity price (the box follows rather than re-plans at its own price), far # below the owner's floors (optimizer.PENALTY_LIMIT, 5 EUR per % of capacity and step) "binding": {"load_limit": 50.0, "shift_request": 5.0, "thermostat_cap": 50.0, "battery_plan": 5.0}, "flexible": {"load_limit": 1.0, "shift_request": 0.5, "thermostat_cap": 2.0, "battery_plan": 0.5}, # a grid operator's order relayed by the building (§14a), with proof the # link checked (edge/link/gridorder.go): nobody overrides it; never a battery_plan "emergency": {"load_limit": 500.0, "shift_request": 50.0, "thermostat_cap": 500.0}, } BOUND_KEY = "battery_bound" # building.json: the binding of the battery to a building (kept after its plan ends) SCHEDULE_STEP_S = 900 # a battery_plan's step: the plans' 15 minutes SCHEDULE_MAX_W = 1e6 # |W| per step at most: a sanity bound on the numbers, not a battery's rating class Building: def __init__(self, state_dir: str, clock=time.time): self.path, self.clock = os.path.join(state_dir, "building.json"), clock self.membership_path = os.path.join(state_dir, "membership.json") self.active: dict[str, dict] = {} # control -> the command's args (parsed) # the building the battery is bound to (a battery_plan taken; kept after it ends: the module's doc) self.bound: dict | None = None try: with open(self.path) as f: raw = json.load(f) self.active = {k: v for k, v in raw.items() if k in CONTROLS} b = raw.get(BOUND_KEY) self.bound = b if isinstance(b, dict) and b.get("building") else None except (OSError, ValueError, AttributeError): pass c = self.active.get("battery_plan") if c and not self.bound: # a plan taken by an agent before the binding existed (2026-11-09, the farm's upgrade to 0.1.0-dev.db2193861454: # Berlin's and Durlach's plans of the night carried no binding, so A9.4b did not hold and the owner's 10 % floor # was refilled from the grid against the building's 0 W): the plan in force binds as if taken now self.bound = {"building": c["building"], "level": c.get("level", "binding"), "since": int(self.clock()), "until": c["until"], "id": c["id"]} self._save() self.drop_ended() def memberships(self) -> set[str] | None: """The buildings this site belongs to (membership.json), or None when the panel wrote none.""" try: with open(self.membership_path) as f: ids = json.load(f).get("buildings") except (OSError, ValueError, AttributeError): return None return {str(i) for i in ids} if isinstance(ids, list) else None def _save(self): tmp = self.path + ".tmp" with open(tmp, "w") as f: json.dump({**self.active, **({BOUND_KEY: self.bound} if self.bound else {})}, f) os.replace(tmp, self.path) def battery_bound(self) -> dict | None: """The building the battery is bound to, or None (never bound, or the box left that building: membership.json without it ends the binding).""" if not self.bound: return None members = self.memberships() if members is not None and str(self.bound["building"]) not in members: self.bound = None self._save() return None return self.bound def drop_ended(self) -> list[dict]: now = self.clock() ended = [c for c in self.active.values() if now >= c["until"]] if ended: self.active = {k: c for k, c in self.active.items() if now < c["until"]} self._save() return ended @staticmethod def parse(a: dict) -> dict: try: c = {"id": a["id"], "building": a["building"], "level": a.get("level", "flexible"), "control": a["control"], "value": float(a["value"]), "from": int(float(a["from"])), "until": int(float(a["until"])), "why": a.get("why", "")[:120], "proof": a.get("proof", "")} except (KeyError, ValueError, TypeError) as e: raise ValueError(f"building: {e} (id, building, control, value, from, until needed)") if str(a.get("v", "1")) != "1": raise ValueError("building: v 1 only") if c["level"] not in ("flexible", "binding", "emergency"): raise ValueError("building: level flexible, binding or emergency") if c["control"] == "battery_plan" and c["level"] == "emergency": raise ValueError("building: a battery_plan is flexible or binding, never an emergency") if c["level"] == "emergency" and not (c["proof"].startswith("verified:") and c["control"] == "load_limit"): # only a grid operator's order the link verified (2026-10-29) raise ValueError("building: an emergency needs the grid operator's verified proof (a relayed load_limit)") if c["control"] not in CONTROLS: raise ValueError(f"building: control one of {', '.join(CONTROLS)}") if not c["from"] < c["until"] <= c["from"] + 86400: raise ValueError("building: from < until <= from + 24 h") if c["control"] in ("load_limit", "shift_request") and c["value"] < 0: raise ValueError(f"building: {c['control']} must not be negative") if c["control"] == "battery_plan": c["step_s"], c["schedule"] = Building.schedule(a, c["from"], c["until"]) return c @staticmethod def schedule(a: dict, frm: int, until: int) -> tuple[int, list[float]]: """A battery_plan's step and its W per step from `from`.""" try: step = int(str(a.get("step_s", "")).strip()) except ValueError: step = 0 if step != SCHEDULE_STEP_S: raise ValueError(f"building: battery_plan step_s {SCHEDULE_STEP_S}") raw = a.get("schedule") try: ws = [float(w) for w in (raw.split(",") if isinstance(raw, str) else raw)] except (AttributeError, TypeError, ValueError): raise ValueError('building: battery_plan schedule "w0,w1,..." (W per step)') n, rest = divmod(until - frm, step) if rest or len(ws) != n: raise ValueError(f"building: battery_plan schedule has {len(ws)} values, " f"(until - from) / step_s is {(until - frm) / step:g}") if not all(math.isfinite(w) and abs(w) <= SCHEDULE_MAX_W for w in ws): raise ValueError("building: battery_plan schedule: every value finite, |w| <= 1e6 W") return step, ws def take(self, c: dict, floors: list[tuple[str, float, float, str]]) -> tuple[bool, str]: """A parsed command. floors: (control id, the flat's floor, the flat's limit, kind) of each heating/cooling room, for the cap.""" if self.clock() >= c["until"]: return False, "already over" members = self.memberships() if members is not None and c["building"] not in members: return False, "not a member of that building" if c["control"] == "thermostat_cap": for cid, lo, hi, kind in floors: if kind == "heating" and c["value"] < lo: return False, f"floor: {cid}'s comfort floor is {lo:g} °C, the cap {c['value']:g} °C" if kind == "cooling" and c["value"] > hi: return False, f"floor: {cid}'s limit is {hi:g} °C, the cap {c['value']:g} °C" old = self.active.get(c["control"]) self.active[c["control"]] = c if c["control"] == "battery_plan": b = self.bound if self.bound and self.bound.get("building") == c["building"] else {} self.bound = {"building": c["building"], "level": c["level"], "since": b.get("since", int(self.clock())), "until": c["until"], "id": c["id"]} self._save() replaced = f" (replaces {old['id']})" if old and old["id"] != c["id"] else "" return True, f"{c['control']} {c['value']:g} {c['level']} until {time.strftime('%H:%M UTC', time.gmtime(c['until']))}{replaced}" def lift(self, control: str): """The owner overrode a flexible request: it ends (a battery plan's binding with it: the owner took the battery back).""" if self.active.pop(control, None) is not None: if control == "battery_plan": self.bound = None self._save() def for_model(self, start: int, step_s: int, steps: int) -> dict: """The requests as the optimiser takes them: per step, or a window. A battery_plan per model step (the slot at the step's middle; the model may start after `from`: past slots skipped), None where the command doesn't cover the step; from_step/to_step its covered span. A bound battery (battery_bound) adds "battery_bound": {building, level, until (the last plan's end), lapsed (no plan in force: it ended)}: the steps no plan covers are self-consumption only.""" self.drop_ended() out = {} bound = self.battery_bound() if bound: out["battery_bound"] = {"building": bound["building"], "level": bound.get("level", "binding"), "until": int(bound.get("until") or 0), "lapsed": "battery_plan" not in self.active} for ctl, c in self.active.items(): if ctl == "battery_plan": ws, k_s = c.get("schedule") or [], int(c.get("step_s") or SCHEDULE_STEP_S) sched = [] for t in range(steps): k = (start + t * step_s + step_s // 2 - c["from"]) // k_s sched.append(float(ws[k]) if 0 <= k < len(ws) else None) covered = [t for t, w in enumerate(sched) if w is not None] if covered: out[ctl] = {"schedule_w": sched, "from_step": covered[0], "to_step": covered[-1] + 1, "penalty": PENALTY[c["level"]][ctl], "level": c["level"], "id": c["id"], "building": c["building"]} continue a = max(0, (c["from"] - start) // step_s) b = min(steps, -(-(c["until"] - start) // step_s)) if a >= b: continue out[ctl] = {"value": c["value"], "level": c["level"], "from_step": int(a), "to_step": int(b), "penalty": PENALTY[c["level"]][ctl], "id": c["id"], "building": c["building"]} return out def cap(self, kind: str, now: float) -> tuple[float | None, dict | None]: """The thermostat cap in force now for a heating/cooling room.""" c = self.active.get("thermostat_cap") if c and c["from"] <= now < c["until"] and kind in ("heating", "cooling"): return c["value"], c return None, None