cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1030: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-06 00:13:12 +02:00
1 parent e2c7085d2c
commit cddd34dcbc
30 files changed
+2141 -51

No files matched your search

+66 -7
View File
@@ -4,13 +4,25 @@
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"}
"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.
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
@@ -33,17 +45,23 @@ hard, flexible with a price) and a soft target (a shift). Results go out as
"building.<control>".
"""
import json
import math
import os
import time
CONTROLS = ("load_limit", "shift_request", "thermostat_cap")
CONTROLS = ("load_limit", "shift_request", "thermostat_cap", "battery_plan")
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},
# 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
# 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},
}
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:
@@ -94,6 +112,8 @@ class Building:
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)")
@@ -103,8 +123,32 @@ class Building:
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."""
@@ -131,10 +175,25 @@ class Building:
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."""
"""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."""
self.drop_ended()
out = {}
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: