cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.400: full source
This commit is contained in:
1 parent
343331d234
commit
d5fbcacaa4
176 files changed
+32511
-19
No files matched your search
@@ -0,0 +1,151 @@
|
||||
# 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", "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)
|
||||
|
||||
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 <state dir>/building.json across restarts.
|
||||
|
||||
Membership (2026-10-29, joining a building): the Hub's panel writes
|
||||
<state dir>/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:<id>", service
|
||||
"building.<control>".
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
CONTROLS = ("load_limit", "shift_request", "thermostat_cap")
|
||||
PENALTY = { # EUR per unit across a building's request in the plan
|
||||
"binding": {"load_limit": 50.0, "shift_request": 5.0, "thermostat_cap": 50.0}, # per kWh, per kWh, per K·h
|
||||
"flexible": {"load_limit": 1.0, "shift_request": 0.5, "thermostat_cap": 2.0},
|
||||
# a grid operator's order relayed by the building (§14a), with proof the
|
||||
# link checked (edge/link/gridorder.go): nobody overrides it
|
||||
"emergency": {"load_limit": 500.0, "shift_request": 50.0, "thermostat_cap": 500.0},
|
||||
}
|
||||
|
||||
|
||||
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)
|
||||
try:
|
||||
with open(self.path) as f:
|
||||
self.active = {k: v for k, v in json.load(f).items() if k in CONTROLS}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
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, f)
|
||||
os.replace(tmp, self.path)
|
||||
|
||||
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["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")
|
||||
return c
|
||||
|
||||
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
|
||||
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."""
|
||||
if self.active.pop(control, None) is not 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."""
|
||||
self.drop_ended()
|
||||
out = {}
|
||||
for ctl, c in self.active.items():
|
||||
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
|
||||
Reference in new issue
Block a user