cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.2080: full source
This commit is contained in:
1 parent
5168a4a590
commit
b3dfc9bb68
22 files changed
+865
-43
No files matched your search
@@ -22,7 +22,7 @@ Settings → Add-ons → Add-on store → ⋮ → Repositories, add
|
|||||||
`https://git.setti.solutions/Daniel/cantabile-ha-addons`, then install the
|
`https://git.setti.solutions/Daniel/cantabile-ha-addons`, then install the
|
||||||
add-on. The Supervisor pulls the prebuilt images
|
add-on. The Supervisor pulls the prebuilt images
|
||||||
(`git.setti.solutions/daniel/cantabile-ha-<edge|modbus|eebus>-<arch>:<version>`,
|
(`git.setti.solutions/daniel/cantabile-ha-<edge|modbus|eebus>-<arch>:<version>`,
|
||||||
named by `image:` in each `config.yaml`); this version: `0.1.2019`, arch amd64.
|
named by `image:` in each `config.yaml`); this version: `0.1.2080`, arch amd64.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
# the Hub's, wrapped by addon-run (Dockerfile). The image is prebuilt,
|
# the Hub's, wrapped by addon-run (Dockerfile). The image is prebuilt,
|
||||||
# per arch (README.md: building it from src/).
|
# per arch (README.md: building it from src/).
|
||||||
name: Cantabile Edge Agent
|
name: Cantabile Edge Agent
|
||||||
version: "0.1.2019"
|
version: "0.1.2080"
|
||||||
slug: cantabile_edge
|
slug: cantabile_edge
|
||||||
description: Plans your home's energy with Cantabile and, with your consent, runs the devices you choose.
|
description: Plans your home's energy with Cantabile and, with your consent, runs the devices you choose.
|
||||||
url: https://cantabile.cloud
|
url: https://cantabile.cloud
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
# Assistant that isn't a Cantabile Hub. Devices are paired on its page
|
# Assistant that isn't a Cantabile Hub. Devices are paired on its page
|
||||||
# (ingress), by their SKI.
|
# (ingress), by their SKI.
|
||||||
name: Cantabile EEBUS
|
name: Cantabile EEBUS
|
||||||
version: "0.1.2019"
|
version: "0.1.2080"
|
||||||
slug: cantabile_eebus
|
slug: cantabile_eebus
|
||||||
description: Pairs with EEBUS devices (the grid operator's control box, heat pumps, wallboxes, inverters), shows them in Home Assistant under Cantabile's names and hands the grid operator's §14a limit to the Cantabile agent; every control with its protection.
|
description: Pairs with EEBUS devices (the grid operator's control box, heat pumps, wallboxes, inverters), shows them in Home Assistant under Cantabile's names and hands the grid operator's §14a limit to the Cantabile agent; every control with its protection.
|
||||||
url: https://cantabile.cloud
|
url: https://cantabile.cloud
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
# Home Assistant that isn't a Cantabile Hub. Devices come from the options;
|
# Home Assistant that isn't a Cantabile Hub. Devices come from the options;
|
||||||
# the page (ingress) shows them and each control's protection.
|
# the page (ingress) shows them and each control's protection.
|
||||||
name: Cantabile Modbus bridge
|
name: Cantabile Modbus bridge
|
||||||
version: "0.1.2019"
|
version: "0.1.2080"
|
||||||
slug: cantabile_modbus
|
slug: cantabile_modbus
|
||||||
description: Reads inverters, meters, relays and circuits by Cantabile's device profiles (Modbus, or Home Assistant's own entities) and shows them in Home Assistant, each control with its protection.
|
description: Reads inverters, meters, relays and circuits by Cantabile's device profiles (Modbus, or Home Assistant's own entities) and shows them in Home Assistant, each control with its protection.
|
||||||
url: https://cantabile.cloud
|
url: https://cantabile.cloud
|
||||||
|
|||||||
@@ -56,6 +56,11 @@ building and the home, and what the agent does to each device):
|
|||||||
text pref_<car>_ready "Mo-Fr 08:00 100% must; Sa,Su 10:00 20kWh max 25ct"
|
text pref_<car>_ready "Mo-Fr 08:00 100% must; Sa,Su 10:00 20kWh max 25ct"
|
||||||
number pref_<car>_capacity (kWh, for %), text pref_<car>_needed (one-off)
|
number pref_<car>_capacity (kWh, for %), text pref_<car>_needed (one-off)
|
||||||
number pref_<battery>_reserve (%), text pref_<battery>_reserve_blocks
|
number pref_<battery>_reserve (%), text pref_<battery>_reserve_blocks
|
||||||
|
select pref_comfort the home's comfort choice (Comfort / Balanced / Saving;
|
||||||
|
with a heating or cooling room; methods.md G5)
|
||||||
|
text pref_<tank>_hotwater the hot-water times, as a room's schedule: "Mo-Fr 06:00-08:00 55 must"
|
||||||
|
(a hot-water tank: the least temperature in the hours; methods.md G7)
|
||||||
|
sensor pref_last_change applied or refused, and why, for the last setting made here
|
||||||
sensor pref_<control>_result, preferences (advisory and auto, with the
|
sensor pref_<control>_result, preferences (advisory and auto, with the
|
||||||
plan): per preference met or not and each must's cost
|
plan): per preference met or not and each must's cost
|
||||||
Commands on cantabile/<site>/prefs/<object>/set (the owner's, "Home
|
Commands on cantabile/<site>/prefs/<object>/set (the owner's, "Home
|
||||||
@@ -83,6 +88,7 @@ from . import costs as costs_mod
|
|||||||
from . import gridorder
|
from . import gridorder
|
||||||
from . import __version__
|
from . import __version__
|
||||||
from . import names, shades
|
from . import names, shades
|
||||||
|
from .preferences import COMFORT_MODES
|
||||||
from .bundles import Bundles
|
from .bundles import Bundles
|
||||||
from .mqtt import Client
|
from .mqtt import Client
|
||||||
|
|
||||||
@@ -114,6 +120,7 @@ class Announcer:
|
|||||||
ctl = getattr(agent, "control", None)
|
ctl = getattr(agent, "control", None)
|
||||||
self.bundles = ctl.bundles if ctl is not None else Bundles(agent.cfg.state_dir, site)
|
self.bundles = ctl.bundles if ctl is not None else Bundles(agent.cfg.state_dir, site)
|
||||||
self.pref_cmds: dict[str, tuple[str, str]] = {} # object -> (control id, what): the commands HA may send
|
self.pref_cmds: dict[str, tuple[str, str]] = {} # object -> (control id, what): the commands HA may send
|
||||||
|
self.pref_last: dict | None = None # the last setting made in HA: {at, ok, why}
|
||||||
if ctl is not None:
|
if ctl is not None:
|
||||||
ctl.on_plan.append(self._planned)
|
ctl.on_plan.append(self._planned)
|
||||||
ctl.on_received.append(self._received)
|
ctl.on_received.append(self._received)
|
||||||
@@ -432,7 +439,7 @@ class Announcer:
|
|||||||
ctl = getattr(self.agent, "control", None)
|
ctl = getattr(self.agent, "control", None)
|
||||||
if ctl is None or not hasattr(ctl, "prefs") or ctl.mode() == "off":
|
if ctl is None or not hasattr(ctl, "prefs") or ctl.mode() == "off":
|
||||||
return None, []
|
return None, []
|
||||||
return ctl, [c for c in ctl.controls if c.kind in ("heating", "cooling", "ev", "battery")]
|
return ctl, [c for c in ctl.controls if c.kind in ("heating", "cooling", "ev", "battery", "dhw_tank")]
|
||||||
|
|
||||||
def _prefs_objects(self) -> dict:
|
def _prefs_objects(self) -> dict:
|
||||||
"""The preferences' entities: settings in every mode but off, their
|
"""The preferences' entities: settings in every mode but off, their
|
||||||
@@ -467,6 +474,8 @@ class Announcer:
|
|||||||
payload_on="ON", payload_off="OFF", state_on="ON", state_off="OFF", icon="mdi:home-export-outline")
|
payload_on="ON", payload_off="OFF", state_on="ON", state_off="OFF", icon="mdi:home-export-outline")
|
||||||
add("text", "pref_away_until", "", "away_until", names.name("pref_away_until", lang), max=40, mode="text",
|
add("text", "pref_away_until", "", "away_until", names.name("pref_away_until", lang), max=40, mode="text",
|
||||||
icon="mdi:calendar-arrow-right")
|
icon="mdi:calendar-arrow-right")
|
||||||
|
add("select", "pref_comfort", "", "comfort", names.name("pref_comfort", lang),
|
||||||
|
options=[names.name(f"comfort_{m}", lang) for m in COMFORT_MODES], icon="mdi:thermometer-check")
|
||||||
for c in cs:
|
for c in cs:
|
||||||
k, n = _slug(c.id), c.label()
|
k, n = _slug(c.id), c.label()
|
||||||
if c.kind == "ev":
|
if c.kind == "ev":
|
||||||
@@ -476,12 +485,20 @@ class Announcer:
|
|||||||
max=250, step=0.5, mode="box", unit_of_measurement="kWh", icon="mdi:car-battery")
|
max=250, step=0.5, mode="box", unit_of_measurement="kWh", icon="mdi:car-battery")
|
||||||
add("text", f"pref_{k}_needed", c.id, "needed", names.name("pref_needed", lang, n), max=80, mode="text",
|
add("text", f"pref_{k}_needed", c.id, "needed", names.name("pref_needed", lang, n), max=80, mode="text",
|
||||||
icon="mdi:car-arrow-right")
|
icon="mdi:car-arrow-right")
|
||||||
|
elif c.kind == "dhw_tank":
|
||||||
|
add("text", f"pref_{k}_hotwater", c.id, "hotwater", names.name("pref_hotwater", lang, n), max=255,
|
||||||
|
mode="text", icon="mdi:water-boiler")
|
||||||
elif c.kind == "battery":
|
elif c.kind == "battery":
|
||||||
add("number", f"pref_{k}_reserve", c.id, "reserve", names.name("pref_reserve", lang, n), min=0, max=100,
|
add("number", f"pref_{k}_reserve", c.id, "reserve", names.name("pref_reserve", lang, n), min=0, max=100,
|
||||||
step=1, mode="box", unit_of_measurement="%", icon="mdi:battery-lock")
|
step=1, mode="box", unit_of_measurement="%", icon="mdi:battery-lock")
|
||||||
add("text", f"pref_{k}_reserve_blocks", c.id, "reserve_blocks", names.name("pref_reserve_blocks", lang, n),
|
add("text", f"pref_{k}_reserve_blocks", c.id, "reserve_blocks", names.name("pref_reserve_blocks", lang, n),
|
||||||
max=255, mode="text", icon="mdi:battery-clock")
|
max=255, mode="text", icon="mdi:battery-clock")
|
||||||
self.pref_cmds = cmds
|
self.pref_cmds = cmds
|
||||||
|
last = {"state_topic": f"{top}/result", "json_attributes_topic": f"{top}/result", **self._avail(), "device": dev}
|
||||||
|
out[("sensor", "pref_last_change")] = {
|
||||||
|
"name": names.name("pref_last_change", lang), "unique_id": f"{self.uid}_pref_last_change",
|
||||||
|
"icon": "mdi:check-circle-outline", "entity_category": "diagnostic",
|
||||||
|
"value_template": "{{ value_json.last_change or '-' }}", **last}
|
||||||
if ctl.mode() in ("advisory", "auto"):
|
if ctl.mode() in ("advisory", "auto"):
|
||||||
res = {"state_topic": f"{top}/result", "json_attributes_topic": f"{top}/result", **self._avail(), "device": dev}
|
res = {"state_topic": f"{top}/result", "json_attributes_topic": f"{top}/result", **self._avail(), "device": dev}
|
||||||
out[("sensor", "preferences")] = {
|
out[("sensor", "preferences")] = {
|
||||||
@@ -520,6 +537,8 @@ class Announcer:
|
|||||||
out[f"pref_{k}_capacity"] = v.get("capacity_kwh")
|
out[f"pref_{k}_capacity"] = v.get("capacity_kwh")
|
||||||
car = next((o for o in act if o["kind"] == "car" and o.get("control") == c.id), None)
|
car = next((o for o in act if o["kind"] == "car" and o.get("control") == c.id), None)
|
||||||
out[f"pref_{k}_needed"] = pm.car_text(car, p.tz) if car else ""
|
out[f"pref_{k}_needed"] = pm.car_text(car, p.tz) if car else ""
|
||||||
|
elif c.kind == "dhw_tank":
|
||||||
|
out[f"pref_{k}_hotwater"] = pm.room_text(p.value(f"tank:{c.id}"))
|
||||||
elif c.kind == "battery":
|
elif c.kind == "battery":
|
||||||
v = p.value(f"battery:{c.id}") or {}
|
v = p.value(f"battery:{c.id}") or {}
|
||||||
out[f"pref_{k}_reserve"] = v.get("reserve_pct", 0.0)
|
out[f"pref_{k}_reserve"] = v.get("reserve_pct", 0.0)
|
||||||
@@ -528,8 +547,21 @@ class Announcer:
|
|||||||
away = next((o for o in act if o["kind"] == "away"), None)
|
away = next((o for o in act if o["kind"] == "away"), None)
|
||||||
out["pref_away"] = "ON" if away else "OFF"
|
out["pref_away"] = "ON" if away else "OFF"
|
||||||
out["pref_away_until"] = p.ha.get("away_until", "")
|
out["pref_away_until"] = p.ha.get("away_until", "")
|
||||||
|
out["pref_comfort"] = names.name(f"comfort_{self._comfort_now(p)}", self.lang)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
def _comfort_now(self, p) -> str:
|
||||||
|
"""The home's comfort choice in force: the household's, else the Parameters page's default."""
|
||||||
|
from . import comfort
|
||||||
|
mode = p.comfort_mode()
|
||||||
|
if mode is None:
|
||||||
|
try:
|
||||||
|
bp = self.bundles.box_params(time.time()) if hasattr(self.bundles, "box_params") else {}
|
||||||
|
except Exception:
|
||||||
|
bp = {}
|
||||||
|
mode = comfort.rows(bp)[0]["comfort.default_mode"]
|
||||||
|
return mode
|
||||||
|
|
||||||
def prefs_result(self) -> dict:
|
def prefs_result(self) -> dict:
|
||||||
"""The plan's feedback per control (cantabile/<site>/prefs/result)."""
|
"""The plan's feedback per control (cantabile/<site>/prefs/result)."""
|
||||||
ctl, cs = self._pref_controls()
|
ctl, cs = self._pref_controls()
|
||||||
@@ -546,7 +578,9 @@ class Announcer:
|
|||||||
"results": mine}
|
"results": mine}
|
||||||
bad = [f for f in fb if f.get("met") is False]
|
bad = [f for f in fb if f.get("met") is False]
|
||||||
last = (p.errors[-1] if p is not None and p.errors else None)
|
last = (p.errors[-1] if p is not None and p.errors else None)
|
||||||
|
lc = self.pref_last
|
||||||
return {"summary": "none" if not fb else f"{len(bad)} not met" if bad else "met",
|
return {"summary": "none" if not fb else f"{len(bad)} not met" if bad else "met",
|
||||||
|
"last_change": f"{'applied' if lc['ok'] else 'refused'}: {lc['why']}" if lc else "",
|
||||||
"lines": [f["text"] for f in fb], "controls": per,
|
"lines": [f["text"] for f in fb], "controls": per,
|
||||||
"last_error": f"{last['item']}: {last['why']}" if last else ""}
|
"last_error": f"{last['item']}: {last['why']}" if last else ""}
|
||||||
|
|
||||||
@@ -559,7 +593,11 @@ class Announcer:
|
|||||||
text = payload.decode(errors="replace").strip()
|
text = payload.decode(errors="replace").strip()
|
||||||
p, by = ctl.prefs, "Home Assistant"
|
p, by = ctl.prefs, "Home Assistant"
|
||||||
msg = None
|
msg = None
|
||||||
if what == "schedule":
|
if what == "comfort":
|
||||||
|
msg = {"set": {"item": "comfort", "value": {"mode": text}}}
|
||||||
|
elif what == "hotwater":
|
||||||
|
msg = {"set": {"item": f"tank:{cid}", "value": text or None}}
|
||||||
|
elif what == "schedule":
|
||||||
msg = {"set": {"item": f"room:{cid}", "value": text or None}}
|
msg = {"set": {"item": f"room:{cid}", "value": text or None}}
|
||||||
elif what in ("boost_c", "boost_h"):
|
elif what in ("boost_c", "boost_h"):
|
||||||
try:
|
try:
|
||||||
@@ -603,7 +641,8 @@ class Announcer:
|
|||||||
msg = {"set": {"item": f"battery:{cid}", "value": text}} if text else \
|
msg = {"set": {"item": f"battery:{cid}", "value": text}} if text else \
|
||||||
{"set": {"item": f"battery:{cid}", "value": dict(v, blocks=[])}}
|
{"set": {"item": f"battery:{cid}", "value": dict(v, blocks=[])}}
|
||||||
if msg is not None:
|
if msg is not None:
|
||||||
await ctl.prefs_change(msg, "owner", by)
|
ok, why = await ctl.prefs_change(msg, "owner", by)
|
||||||
|
self.pref_last = {"at": int(time.time()), "ok": ok, "why": why}
|
||||||
self.changed.set()
|
self.changed.set()
|
||||||
|
|
||||||
def _boost(self, p, cid) -> dict:
|
def _boost(self, p, cid) -> dict:
|
||||||
@@ -800,8 +839,7 @@ class Announcer:
|
|||||||
prefs = self.prefs_state()
|
prefs = self.prefs_state()
|
||||||
if prefs:
|
if prefs:
|
||||||
await c.publish(f"{self.base}/prefs", json.dumps(prefs, default=str), retain=True)
|
await c.publish(f"{self.base}/prefs", json.dumps(prefs, default=str), retain=True)
|
||||||
if ctl.mode() in ("advisory", "auto"):
|
await c.publish(f"{self.base}/prefs/result", json.dumps(self.prefs_result(), default=str), retain=True)
|
||||||
await c.publish(f"{self.base}/prefs/result", json.dumps(self.prefs_result(), default=str), retain=True)
|
|
||||||
if ctl is not None and ctl.received:
|
if ctl is not None and ctl.received:
|
||||||
# kept (retained) across restarts until new ones come
|
# kept (retained) across restarts until new ones come
|
||||||
await c.publish(f"{self.base}/received", json.dumps({"commands": self.received_list(ctl)}), retain=True)
|
await c.publish(f"{self.base}/received", json.dumps({"commands": self.received_list(ctl)}), retain=True)
|
||||||
|
|||||||
@@ -19,7 +19,9 @@ rules (window, discharge_kw) and the check of its own MILP against plan() (A2.3a
|
|||||||
nothing assumes a flat price.
|
nothing assumes a flat price.
|
||||||
4. Wear (Parameters battery.wear_ct, per kWh cycled) on every kWh discharged, whatever it serves; the idle loss
|
4. Wear (Parameters battery.wear_ct, per kWh cycled) on every kWh discharged, whatever it serves; the idle loss
|
||||||
(standby P⁰ and self-discharge λ, design storage-losses.md S.2) in the charge balance; what of it the grid supplies
|
(standby P⁰ and self-discharge λ, design storage-losses.md S.2) in the charge balance; what of it the grid supplies
|
||||||
(the BMS's valves) is money in plan() at the slot's purchase.
|
(the BMS's valves) is money in plan() at the slot's purchase. Each kW the battery's power changes
|
||||||
|
from one slot to the next at battery.ramp_ct: a tie-break against flicker (charge, discharge, charge again), small
|
||||||
|
against a real cycle (2026-11-13); an LP term, no binaries.
|
||||||
5. The window: the floor (the battery's own minimum, its box's published floor, and the building's reserve
|
5. The window: the floor (the battery's own minimum, its box's published floor, and the building's reserve
|
||||||
battery.plan_reserve_pct) and the top (the battery's maximum and battery.plan_max_soc_pct); the charge and the
|
battery.plan_reserve_pct) and the top (the battery's maximum and battery.plan_max_soc_pct); the charge and the
|
||||||
discharge each at their own power (the battery's facts; where they give one power, the discharge at
|
discharge each at their own power (the battery's facts; where they give one power, the discharge at
|
||||||
@@ -29,7 +31,11 @@ rules (window, discharge_kw) and the check of its own MILP against plan() (A2.3a
|
|||||||
7. Grid orders: a binding limit on the import is a constraint of the plan (the caller's import-limit row; the
|
7. Grid orders: a binding limit on the import is a constraint of the plan (the caller's import-limit row; the
|
||||||
battery's grid kWh count on it, and none are bought while a §14a order dims): it overrides the prices and may
|
battery's grid kWh count on it, and none are bought while a §14a order dims): it overrides the prices and may
|
||||||
force a discharge.
|
force a discharge.
|
||||||
8. A flat's own battery (and a house's) is its box's (edge optimizer, for the household's money, with the same rules:
|
8. Flats first (the proposal's simplification, D5.19): the PV the battery takes where the flats could use it now
|
||||||
|
(room_flats) carries that rule with it: it goes to the flats later (the time shift), is fed in or kept, never to the
|
||||||
|
plant's own use (2026-11-13, Durlach: PV taken from the flats at 14:00 and sent to the own use at 14:15, around the
|
||||||
|
flats-first bound on PV to the own use). The surplus and the PV the own use could take stay free.
|
||||||
|
9. A flat's own battery (and a house's) is its box's (edge optimizer, for the household's money, with the same rules:
|
||||||
wear, reserve and top, the discharge power; not the PV share, a building's concept); the plan sees it in the
|
wear, reserve and top, the discharge power; not the PV share, a building's concept); the plan sees it in the
|
||||||
flat's published plan (its import after its own battery) and the building battery never charges it (the caller's
|
flat's published plan (its import after its own battery) and the building battery never charges it (the caller's
|
||||||
caps).
|
caps).
|
||||||
@@ -51,7 +57,7 @@ END_GRID_GAP = 1e-3 # ENG: the grid pool's end value this share below the horiz
|
|||||||
# they match). Used only where a row did not arrive (the owner, 2026-11-12: "fall back to suggested, with alarm"):
|
# they match). Used only where a row did not arrive (the owner, 2026-11-12: "fall back to suggested, with alarm"):
|
||||||
# the plan goes on with these and the missing row is reported as a data gap naming it.
|
# the plan goes on with these and the missing row is reported as a data gap naming it.
|
||||||
SUGGESTED_ROWS = {"battery.wear_ct": 3.0, "battery.pv_share_pct": 50.0, "battery.discharge_ratio_pct": 65.0,
|
SUGGESTED_ROWS = {"battery.wear_ct": 3.0, "battery.pv_share_pct": 50.0, "battery.discharge_ratio_pct": 65.0,
|
||||||
"battery.plan_reserve_pct": 10.0, "battery.plan_max_soc_pct": 95.0}
|
"battery.plan_reserve_pct": 10.0, "battery.plan_max_soc_pct": 95.0, "battery.ramp_ct": 0.2}
|
||||||
|
|
||||||
|
|
||||||
def suggested_gap(missing: list) -> dict:
|
def suggested_gap(missing: list) -> dict:
|
||||||
@@ -132,6 +138,9 @@ class Block:
|
|||||||
# integer: integers()). Without it an LP may pass PV through the battery in one slot
|
# integer: integers()). Without it an LP may pass PV through the battery in one slot
|
||||||
# (found 2026-11-12 on a GGV test building: PV charged and the plant's own use served from the
|
# (found 2026-11-12 on a GGV test building: PV charged and the plant's own use served from the
|
||||||
# battery at once in 50 quarter-hours, around the flats-first bound of the PV to the own use)
|
# battery at once in 50 quarter-hours, around the flats-first bound of the PV to the own use)
|
||||||
|
ramp_eur_kw: float = 0.0 # per kW the battery's power changes from one slot to the next (battery.ramp_ct / 100)
|
||||||
|
room_flats: list | None = None # the PV the flats leave per slot (kWh; the own use's PV bound, flats first): the PV
|
||||||
|
# charged beyond it (CF) is held in its own stock S, out only to the flats or fed in
|
||||||
CH: list = field(default_factory=list)
|
CH: list = field(default_factory=list)
|
||||||
DI: list = field(default_factory=list)
|
DI: list = field(default_factory=list)
|
||||||
CT: list = field(default_factory=list)
|
CT: list = field(default_factory=list)
|
||||||
@@ -148,6 +157,12 @@ class Block:
|
|||||||
LBq: list = field(default_factory=list)
|
LBq: list = field(default_factory=list)
|
||||||
LQ: list = field(default_factory=list)
|
LQ: list = field(default_factory=list)
|
||||||
Z: list = field(default_factory=list) # 1: the slot may charge, 0: discharge (exclusive)
|
Z: list = field(default_factory=list) # 1: the slot may charge, 0: discharge (exclusive)
|
||||||
|
RC: list = field(default_factory=list) # |charge_t − charge_{t−1}| (kWh per slot), t ≥ 1: the ramp
|
||||||
|
RD: list = field(default_factory=list) # |discharge_t − discharge_{t−1}|
|
||||||
|
CF: list = field(default_factory=list) # the PV charged that the flats could have used (flats first)
|
||||||
|
S: list = field(default_factory=list) # its stock in the battery (part of E above the floor)
|
||||||
|
DS: list = field(default_factory=list) # its discharge (to the flats or fed in)
|
||||||
|
LS: list = field(default_factory=list) # its share of the standby loss
|
||||||
lo: dict = field(default_factory=dict) # column -> a new lower bound (the caller applies: set_bounds)
|
lo: dict = field(default_factory=dict) # column -> a new lower bound (the caller applies: set_bounds)
|
||||||
hi: dict = field(default_factory=dict)
|
hi: dict = field(default_factory=dict)
|
||||||
const_eur: float = 0.0 # the start's charge at the end value (taken off: the gain counts the change)
|
const_eur: float = 0.0 # the start's charge at the end value (taken off: the gain counts the change)
|
||||||
@@ -204,6 +219,19 @@ class Block:
|
|||||||
self.g0 = b.start
|
self.g0 = b.start
|
||||||
if self.exclusive:
|
if self.exclusive:
|
||||||
self.Z = [add(0, 1) for t in range(n)]
|
self.Z = [add(0, 1) for t in range(n)]
|
||||||
|
if self.ramp_eur_kw > 0:
|
||||||
|
# the ramp (rule 4): each kW the charge, and each kW the discharge, changes from one slot to the next, at
|
||||||
|
# battery.ramp_ct (per kWh of change in a slot: the € per kW over the slot's length)
|
||||||
|
r = -self.ramp_eur_kw / getattr(b, "slot_h", 0.25)
|
||||||
|
self.RC = [add(0, INF, r) for t in range(1, n)]
|
||||||
|
self.RD = [add(0, INF, r) for t in range(1, n)]
|
||||||
|
if self.room_flats is not None and self.CT and self.DO:
|
||||||
|
# flats first (rule 8): the PV charged where the flats could use it, its own stock, out only to them
|
||||||
|
self.CF = [add(0, pch) for t in range(n)]
|
||||||
|
self.S = [add(0, b.hi) for t in range(n)]
|
||||||
|
self.DS = [add(0, pdis) for t in range(n)]
|
||||||
|
if self.p0 > 0:
|
||||||
|
self.LS = [add(0, self.p0) for t in range(n)]
|
||||||
if self.Q: # the start's PV part where known, else none of it (never shared as PV): D5.19
|
if self.Q: # the start's PV part where known, else none of it (never shared as PV): D5.19
|
||||||
self.g0 = min(b.start, max(0.0, self.green_start or 0.0))
|
self.g0 = min(b.start, max(0.0, self.green_start or 0.0))
|
||||||
|
|
||||||
@@ -309,12 +337,44 @@ class Block:
|
|||||||
ins = [self.CH[t]] + ([self.CQ[t]] if self.CQ else [])
|
ins = [self.CH[t]] + ([self.CQ[t]] if self.CQ else [])
|
||||||
row(-INF, 0.0, ins + [self.Z[t]], [1.0] * len(ins) + [-self.pch])
|
row(-INF, 0.0, ins + [self.Z[t]], [1.0] * len(ins) + [-self.pch])
|
||||||
row(-INF, self.pdis, outs + [self.Z[t]], [1.0] * len(outs) + [self.pdis])
|
row(-INF, self.pdis, outs + [self.Z[t]], [1.0] * len(outs) + [self.pdis])
|
||||||
|
if self.RC and t > 0:
|
||||||
|
# the ramp: rᶜ_t ≥ |Σ charge_t − Σ charge_{t−1}|, rᵈ_t the same for the discharges (each flow apart: an LP
|
||||||
|
# term as tight as its relaxation; on the net power the MILP took 30x longer, a cost per change of direction
|
||||||
|
# on the binaries as long: 2026-11-13)
|
||||||
|
i1 = [self.CH[t]] + ([self.CQ[t]] if self.CQ else [])
|
||||||
|
i0 = [self.CH[t - 1]] + ([self.CQ[t - 1]] if self.CQ else [])
|
||||||
|
for r, a1, a0 in ((self.RC[t - 1], i1, i0), (self.RD[t - 1], self.outs(t), self.outs(t - 1))):
|
||||||
|
row(0.0, INF, [r] + a1 + a0, [1.0] + [-1.0] * len(a1) + [1.0] * len(a0))
|
||||||
|
row(0.0, INF, [r] + a1 + a0, [1.0] + [1.0] * len(a1) + [-1.0] * len(a0))
|
||||||
|
if self.S:
|
||||||
|
# flats first (rule 8): CF_t ≥ CH_t − room_flats⁺_t; S_t = φ S_{t−1} + ηc CF_t − DS_t/ηd − ℓˢ_t (from 0: the
|
||||||
|
# start's charge is free), DS_t ≤ DI_t + XB_t, ℓˢ_t ≤ ℓᵇ_t, S_t ≤ E_t − its floor: the own use never reaches it
|
||||||
|
row(-max(0.0, self.room_flats[t]), INF, [self.CF[t], self.CH[t]], [1.0, -1.0])
|
||||||
|
c4, v4 = [self.S[t], self.CF[t], self.DS[t]], [1.0, -ec, 1.0 / ec]
|
||||||
|
if t > 0:
|
||||||
|
c4.append(self.S[t - 1])
|
||||||
|
v4.append(-phi)
|
||||||
|
if self.LS:
|
||||||
|
c4.append(self.LS[t])
|
||||||
|
v4.append(1.0)
|
||||||
|
row(-INF, 0.0, [self.LS[t], self.LB[t]], [1.0, -1.0])
|
||||||
|
row(0.0, 0.0, c4, v4)
|
||||||
|
to = [self.DI[t]] + ([self.XB[t]] if self.XB else [])
|
||||||
|
row(-INF, 0.0, [self.DS[t]] + to, [1.0] + [-1.0] * len(to))
|
||||||
|
row(-INF, -self.lo.get(self.E[t], self.base_lo(t)), [self.S[t], self.E[t]], [1.0, -1.0])
|
||||||
|
if self.Q: # with grid kWh the floor holds for both pools: S above it there too (never holding it for q)
|
||||||
|
row(-INF, -self.floor_at(t), [self.S[t], self.E[t], self.Q[t]], [1.0, -1.0, -1.0])
|
||||||
|
|
||||||
def idle_grid(self, x: list, t: int) -> float:
|
def idle_grid(self, x: list, t: int) -> float:
|
||||||
"""The idle loss the grid supplies in slot t (kWh, the valves LG and LQ: the standby and the self-discharge the
|
"""The idle loss the grid supplies in slot t (kWh, the valves LG and LQ: the standby and the self-discharge the
|
||||||
BMS draws while the cells are at the floor), from a solution x. plan() counts it at the slot's purchase, and prices the valves at it in the objective too (idle_eur), so the dispatch avoids what it costs."""
|
BMS draws while the cells are at the floor), from a solution x. plan() counts it at the slot's purchase, and prices the valves at it in the objective too (idle_eur), so the dispatch avoids what it costs."""
|
||||||
return sum(max(0.0, x[cs[t]]) for cs in (self.LG, self.LQ) if cs)
|
return sum(max(0.0, x[cs[t]]) for cs in (self.LG, self.LQ) if cs)
|
||||||
|
|
||||||
|
def switches(self, x: list) -> int:
|
||||||
|
"""The changes of direction in a solution x (charging to discharging or back, idle slots between kept)."""
|
||||||
|
return switches([sum(max(0.0, x[c]) for c in ([self.CH[t]] + ([self.CQ[t]] if self.CQ else []))) for t in range(self.n)],
|
||||||
|
[sum(max(0.0, x[c]) for c in self.outs(t)) for t in range(self.n)])
|
||||||
|
|
||||||
def integers(self) -> list[int]:
|
def integers(self) -> list[int]:
|
||||||
"""The columns the caller makes integer (the exclusivity's binaries)."""
|
"""The columns the caller makes integer (the exclusivity's binaries)."""
|
||||||
return list(self.Z)
|
return list(self.Z)
|
||||||
@@ -341,6 +401,17 @@ class Block:
|
|||||||
self.row(-INF, max(0.0, cap), [EX[t], self.XB[t]], [1.0, 1.0])
|
self.row(-INF, max(0.0, cap), [EX[t], self.XB[t]], [1.0, 1.0])
|
||||||
|
|
||||||
|
|
||||||
|
def switches(charge: list, discharge: list, eps: float = 1e-6) -> int:
|
||||||
|
"""The changes of direction in a dispatch (kWh per slot): charging to discharging or back, idle slots between kept."""
|
||||||
|
n, last = 0, 0
|
||||||
|
for c, d in zip(charge, discharge):
|
||||||
|
cur = 1 if c > eps and c >= d else (-1 if d > eps else 0)
|
||||||
|
if cur and last and cur != last:
|
||||||
|
n += 1
|
||||||
|
last = cur or last
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
def charge_slot_kwh(b, slot_h: float = 0.25) -> float:
|
def charge_slot_kwh(b, slot_h: float = 0.25) -> float:
|
||||||
"""The charge power over one slot (kWh)."""
|
"""The charge power over one slot (kWh)."""
|
||||||
return max(0.0, b.kw) * getattr(b, "slot_h", slot_h)
|
return max(0.0, b.kw) * getattr(b, "slot_h", slot_h)
|
||||||
@@ -427,17 +498,24 @@ class Lp:
|
|||||||
|
|
||||||
|
|
||||||
def plan(hz: Horizon, bat=None, *, wear_ct: float = 0.0, share: float | None = None, end_ct: float = 0.0,
|
def plan(hz: Horizon, bat=None, *, wear_ct: float = 0.0, share: float | None = None, end_ct: float = 0.0,
|
||||||
grey_to_loads: bool = True, surplus_only: bool = False, battery_feed: bool = True, z_ct: float = 0.0) -> dict:
|
grey_to_loads: bool = True, surplus_only: bool = False, battery_feed: bool = True, z_ct: float = 0.0,
|
||||||
|
ramp_ct: float = 0.0, flats_first: bool = True) -> dict:
|
||||||
"""The owner's dispatch over one horizon at fixed prices (the same Block and terms as the plan's MILP at its fixed
|
"""The owner's dispatch over one horizon at fixed prices (the same Block and terms as the plan's MILP at its fixed
|
||||||
prices): per slot the PV used directly (DU ≤ the load), by the own use (PO), fed in (EX), curtailed (CU), charged
|
prices): per slot the PV used directly (DU ≤ the load), by the own use (PO), fed in (EX), curtailed (CU), charged
|
||||||
(CH), the battery's discharges and grid kWh; the owner's money (€) over the horizon without the end value, and the
|
(CH), the battery's discharges and grid kWh; the owner's money (€) over the horizon without the end value, and the
|
||||||
series. bat None: no battery. wear_ct only labels the battery's (bat.wear_ct is used)."""
|
series. bat None: no battery. wear_ct only labels the battery's (bat.wear_ct is used). ramp_ct: per kW the
|
||||||
|
battery's power changes from one slot to the next (battery.ramp_ct; a tie-break, no money in eur). flats_first
|
||||||
|
(with an own use): the plan's rule, the PV to the own use only what the loads leave (PO ≤ PV − load) and the PV the
|
||||||
|
battery takes from the loads never to the own use (rule 8); False: the own use first (§42c: the plant's own use
|
||||||
|
before the members)."""
|
||||||
n = len(hz.pv)
|
n = len(hz.pv)
|
||||||
lp = Lp()
|
lp = Lp()
|
||||||
own = hz.own if hz.own is not None and hz.own_ct is not None else None
|
own = hz.own if hz.own is not None and hz.own_ct is not None else None
|
||||||
direct = hz.direct_ct or [0.0] * n
|
direct = hz.direct_ct or [0.0] * n
|
||||||
DU = [lp.add(0, max(0.0, hz.load[t]), (hz.value_ct[t] + direct[t]) / 100) for t in range(n)]
|
DU = [lp.add(0, max(0.0, hz.load[t]), (hz.value_ct[t] + direct[t]) / 100) for t in range(n)]
|
||||||
PO = [lp.add(0, max(0.0, own[t]), hz.own_ct[t] / 100) for t in range(n)] if own else []
|
po_cap = [max(0.0, own[t]) if not flats_first else min(max(0.0, own[t]), max(0.0, hz.pv[t] - hz.load[t]))
|
||||||
|
for t in range(n)] if own else []
|
||||||
|
PO = [lp.add(0, po_cap[t], hz.own_ct[t] / 100) for t in range(n)] if own else []
|
||||||
EX = [lp.add(0, max(0.0, hz.pv[t]), (hz.feed_ct[t] - (0.01 if hz.unpaid and hz.unpaid[t] else 0.0)) / 100) for t in range(n)]
|
EX = [lp.add(0, max(0.0, hz.pv[t]), (hz.feed_ct[t] - (0.01 if hz.unpaid and hz.unpaid[t] else 0.0)) / 100) for t in range(n)]
|
||||||
CU = [lp.add(0, max(0.0, hz.pv[t])) for t in range(n)]
|
CU = [lp.add(0, max(0.0, hz.pv[t])) for t in range(n)]
|
||||||
blk = None
|
blk = None
|
||||||
@@ -451,7 +529,8 @@ def plan(hz: Horizon, bat=None, *, wear_ct: float = 0.0, share: float | None = N
|
|||||||
feed_eur=[(hz.feed_ct[t] - bat.wear_ct - (0.01 if hz.unpaid and hz.unpaid[t] else 0.0)) / 100 for t in range(n)]
|
feed_eur=[(hz.feed_ct[t] - bat.wear_ct - (0.01 if hz.unpaid and hz.unpaid[t] else 0.0)) / 100 for t in range(n)]
|
||||||
if battery_feed else None,
|
if battery_feed else None,
|
||||||
own_load=list(own) if own else None, own_eur=[hz.own_ct[t] / 100 for t in range(n)] if own else None,
|
own_load=list(own) if own else None, own_eur=[hz.own_ct[t] / 100 for t in range(n)] if own else None,
|
||||||
end_eur=end_ct / 100, green_start=bat.start,
|
end_eur=end_ct / 100, green_start=bat.start, ramp_eur_kw=max(0.0, ramp_ct) / 100,
|
||||||
|
room_flats=[hz.pv[t] - hz.load[t] for t in range(n)] if own and flats_first else None,
|
||||||
idle_eur=[v / 100 for v in (hz.buy_ct or hz.grid_ct or hz.own_ct or hz.value_ct)],
|
idle_eur=[v / 100 for v in (hz.buy_ct or hz.grid_ct or hz.own_ct or hz.value_ct)],
|
||||||
valve=(lambda base: base if g_min is None else min(base, max(0.0, g_min) * (1 - VALVE_UNDER))))
|
valve=(lambda base: base if g_min is None else min(base, max(0.0, g_min) * (1 - VALVE_UNDER))))
|
||||||
# the battery's money on the delivered kWh: the loads' value (DI, DQ), the own use's (DO, DOq: in Block)
|
# the battery's money on the delivered kWh: the loads' value (DI, DQ), the own use's (DO, DOq: in Block)
|
||||||
@@ -491,7 +570,7 @@ def plan(hz: Horizon, bat=None, *, wear_ct: float = 0.0, share: float | None = N
|
|||||||
if blk:
|
if blk:
|
||||||
out.update(charge=v(blk.CH), discharge=v(blk.DI), grid_charge=v(blk.CQ), grey_discharge=v(blk.DQ), own_discharge=v(blk.DO),
|
out.update(charge=v(blk.CH), discharge=v(blk.DI), grid_charge=v(blk.CQ), grey_discharge=v(blk.DQ), own_discharge=v(blk.DO),
|
||||||
own_grey=v(blk.DOq), battery_export=v(blk.XB),
|
own_grey=v(blk.DOq), battery_export=v(blk.XB),
|
||||||
soc=[x[blk.E[t]] + (x[blk.Q[t]] if blk.Q else 0.0) for t in range(n)])
|
soc=[x[blk.E[t]] + (x[blk.Q[t]] if blk.Q else 0.0) for t in range(n)], switches=blk.switches(x))
|
||||||
groups += [blk.CH, blk.DI, blk.CQ, blk.DQ, blk.DO, blk.DOq, blk.XB]
|
groups += [blk.CH, blk.DI, blk.CQ, blk.DQ, blk.DO, blk.DOq, blk.XB]
|
||||||
# the owner's money per slot (€; the end value is no money); the idle loss the grid supplies (the valves) at the
|
# the owner's money per slot (€; the end value is no money); the idle loss the grid supplies (the valves) at the
|
||||||
# slot's purchase (before 2026-11-12 at no money, the ROI ~3 % optimistic with a 20 W, 0.3 %/h battery)
|
# slot's purchase (before 2026-11-12 at no money, the ROI ~3 % optimistic with a 20 W, 0.3 %/h battery)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
like every command) with string args:
|
like every command) with string args:
|
||||||
|
|
||||||
{"v": "1", "id", "building", "level": "flexible|binding",
|
{"v": "1", "id", "building", "level": "flexible|binding",
|
||||||
"control": "load_limit|shift_request|thermostat_cap|battery_plan",
|
"control": "load_limit|shift_request|thermostat_cap|battery_plan|sg_ready",
|
||||||
"value", "from": unix, "until": unix (<= from + 24 h), "why"}
|
"value", "from": unix, "until": unix (<= from + 24 h), "why"}
|
||||||
|
|
||||||
load_limit the flat's highest grid import, W, in [from, until)
|
load_limit the flat's highest grid import, W, in [from, until)
|
||||||
@@ -23,6 +23,14 @@ like every command) with string args:
|
|||||||
any electricity price, far below the owner's floors and
|
any electricity price, far below the owner's floors and
|
||||||
the battery's SoC bounds, which win (optimizer.py
|
the battery's SoC bounds, which win (optimizer.py
|
||||||
Model.battery_plan). Kept with its schedule.
|
Model.battery_plan). Kept with its schedule.
|
||||||
|
sg_ready the building plan's SG Ready states for the building's
|
||||||
|
own heat pump (methods C2.9.3): "schedule": "s0,s1,..."
|
||||||
|
one state 1-4 per step from `from` (as battery_plan's,
|
||||||
|
step_s "900"), "value" the first; "mode": "active" (the
|
||||||
|
building's consent to act: fleet sends none in shadow, a
|
||||||
|
command without it is refused). Never an emergency, never
|
||||||
|
in the box's own plan: the box's heat_pump_sg control
|
||||||
|
sets it through sgready.py's rules and the guard.
|
||||||
|
|
||||||
The binding (2026-11-09): a box that took a battery_plan stays bound to
|
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
|
that building after the plan ends ("battery_bound" in building.json: the
|
||||||
@@ -61,7 +69,8 @@ import math
|
|||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
|
||||||
CONTROLS = ("load_limit", "shift_request", "thermostat_cap", "battery_plan")
|
CONTROLS = ("load_limit", "shift_request", "thermostat_cap", "battery_plan", "sg_ready")
|
||||||
|
SCHEDULED = ("battery_plan", "sg_ready") # the controls with a schedule per step
|
||||||
PENALTY = { # EUR per unit across a building's request in the 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
|
# 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
|
# plan: above any electricity price (the box follows rather than re-plans at its own price), far
|
||||||
@@ -150,8 +159,8 @@ class Building:
|
|||||||
raise ValueError("building: v 1 only")
|
raise ValueError("building: v 1 only")
|
||||||
if c["level"] not in ("flexible", "binding", "emergency"):
|
if c["level"] not in ("flexible", "binding", "emergency"):
|
||||||
raise ValueError("building: level flexible, binding or emergency")
|
raise ValueError("building: level flexible, binding or emergency")
|
||||||
if c["control"] == "battery_plan" and c["level"] == "emergency":
|
if c["control"] in SCHEDULED and c["level"] == "emergency":
|
||||||
raise ValueError("building: a battery_plan is flexible or binding, never an emergency")
|
raise ValueError(f"building: a {c['control']} is flexible or binding, never an emergency")
|
||||||
if c["level"] == "emergency" and not (c["proof"].startswith("verified:") and c["control"] == "load_limit"):
|
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)
|
# 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)")
|
raise ValueError("building: an emergency needs the grid operator's verified proof (a relayed load_limit)")
|
||||||
@@ -163,28 +172,36 @@ class Building:
|
|||||||
raise ValueError(f"building: {c['control']} must not be negative")
|
raise ValueError(f"building: {c['control']} must not be negative")
|
||||||
if c["control"] == "battery_plan":
|
if c["control"] == "battery_plan":
|
||||||
c["step_s"], c["schedule"] = Building.schedule(a, c["from"], c["until"])
|
c["step_s"], c["schedule"] = Building.schedule(a, c["from"], c["until"])
|
||||||
|
if c["control"] == "sg_ready":
|
||||||
|
if str(a.get("mode", "")) != "active":
|
||||||
|
raise ValueError("building: sg_ready only from a building in active mode (mode: active)")
|
||||||
|
c["step_s"], ws = Building.schedule(a, c["from"], c["until"], "sg_ready")
|
||||||
|
if not all(w in (1.0, 2.0, 3.0, 4.0) for w in ws):
|
||||||
|
raise ValueError("building: sg_ready schedule: every value an SG Ready state 1, 2, 3 or 4")
|
||||||
|
c["schedule"] = [int(w) for w in ws]
|
||||||
|
c["mode"] = "active"
|
||||||
return c
|
return c
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def schedule(a: dict, frm: int, until: int) -> tuple[int, list[float]]:
|
def schedule(a: dict, frm: int, until: int, control: str = "battery_plan") -> tuple[int, list[float]]:
|
||||||
"""A battery_plan's step and its W per step from `from`."""
|
"""A schedule's step and its value per step from `from` (a battery_plan's W, an sg_ready's state)."""
|
||||||
try:
|
try:
|
||||||
step = int(str(a.get("step_s", "")).strip())
|
step = int(str(a.get("step_s", "")).strip())
|
||||||
except ValueError:
|
except ValueError:
|
||||||
step = 0
|
step = 0
|
||||||
if step != SCHEDULE_STEP_S:
|
if step != SCHEDULE_STEP_S:
|
||||||
raise ValueError(f"building: battery_plan step_s {SCHEDULE_STEP_S}")
|
raise ValueError(f"building: {control} step_s {SCHEDULE_STEP_S}")
|
||||||
raw = a.get("schedule")
|
raw = a.get("schedule")
|
||||||
try:
|
try:
|
||||||
ws = [float(w) for w in (raw.split(",") if isinstance(raw, str) else raw)]
|
ws = [float(w) for w in (raw.split(",") if isinstance(raw, str) else raw)]
|
||||||
except (AttributeError, TypeError, ValueError):
|
except (AttributeError, TypeError, ValueError):
|
||||||
raise ValueError('building: battery_plan schedule "w0,w1,..." (W per step)')
|
raise ValueError(f'building: {control} schedule "v0,v1,..." (one value per step)')
|
||||||
n, rest = divmod(until - frm, step)
|
n, rest = divmod(until - frm, step)
|
||||||
if rest or len(ws) != n:
|
if rest or len(ws) != n:
|
||||||
raise ValueError(f"building: battery_plan schedule has {len(ws)} values, "
|
raise ValueError(f"building: {control} schedule has {len(ws)} values, "
|
||||||
f"(until - from) / step_s is {(until - frm) / step:g}")
|
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):
|
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")
|
raise ValueError(f"building: {control} schedule: every value finite, |v| <= 1e6")
|
||||||
return step, ws
|
return step, ws
|
||||||
|
|
||||||
def take(self, c: dict, floors: list[tuple[str, float, float, str]]) -> tuple[bool, str]:
|
def take(self, c: dict, floors: list[tuple[str, float, float, str]]) -> tuple[bool, str]:
|
||||||
@@ -235,6 +252,8 @@ class Building:
|
|||||||
"until": int(bound.get("until") or 0),
|
"until": int(bound.get("until") or 0),
|
||||||
"lapsed": "battery_plan" not in self.active}
|
"lapsed": "battery_plan" not in self.active}
|
||||||
for ctl, c in self.active.items():
|
for ctl, c in self.active.items():
|
||||||
|
if ctl == "sg_ready":
|
||||||
|
continue # the heat pump's SG Ready: set by the executor (sg_state), not planned
|
||||||
if ctl == "battery_plan":
|
if ctl == "battery_plan":
|
||||||
ws, k_s = c.get("schedule") or [], int(c.get("step_s") or SCHEDULE_STEP_S)
|
ws, k_s = c.get("schedule") or [], int(c.get("step_s") or SCHEDULE_STEP_S)
|
||||||
sched = []
|
sched = []
|
||||||
@@ -255,6 +274,16 @@ class Building:
|
|||||||
"penalty": PENALTY[c["level"]][ctl], "id": c["id"], "building": c["building"]}
|
"penalty": PENALTY[c["level"]][ctl], "id": c["id"], "building": c["building"]}
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
def sg_state(self, now: float) -> tuple[int | None, dict | None]:
|
||||||
|
"""The building's SG Ready state for now (its step of the sg_ready
|
||||||
|
command in force) and the command; (None, None) without one."""
|
||||||
|
c = self.active.get("sg_ready")
|
||||||
|
if not c or not c["from"] <= now < c["until"]:
|
||||||
|
return None, None
|
||||||
|
k = int((now - c["from"]) // int(c.get("step_s") or SCHEDULE_STEP_S))
|
||||||
|
ws = c.get("schedule") or []
|
||||||
|
return (int(ws[k]), c) if 0 <= k < len(ws) else (None, c)
|
||||||
|
|
||||||
def cap(self, kind: str, now: float) -> tuple[float | None, dict | None]:
|
def cap(self, kind: str, now: float) -> tuple[float | None, dict | None]:
|
||||||
"""The thermostat cap in force now for a heating/cooling room."""
|
"""The thermostat cap in force now for a heating/cooling room."""
|
||||||
c = self.active.get("thermostat_cap")
|
c = self.active.get("thermostat_cap")
|
||||||
|
|||||||
@@ -132,6 +132,10 @@ class Controller:
|
|||||||
# the household's tolerance learnt from its changes by hand (comfort.py, methods.md G5)
|
# the household's tolerance learnt from its changes by hand (comfort.py, methods.md G5)
|
||||||
self.tolerance = comfort.Tolerance(cfg.state_dir)
|
self.tolerance = comfort.Tolerance(cfg.state_dir)
|
||||||
self.executor.on_override = self._learn_override
|
self.executor.on_override = self._learn_override
|
||||||
|
# a heat pump's SG Ready (sgready.py): the lock's Parameters rows from the tariff bundle, and whether a
|
||||||
|
# grid operator's order is in force (no increased operation against it)
|
||||||
|
self.executor.box_params = self.bundles.box_params
|
||||||
|
self.executor.grid_order = self.grid_order_in_force
|
||||||
self.col.observers.append(self._observe)
|
self.col.observers.append(self._observe)
|
||||||
self.client = None
|
self.client = None
|
||||||
self.tz = "UTC"
|
self.tz = "UTC"
|
||||||
@@ -731,10 +735,24 @@ class Controller:
|
|||||||
return False, f"unknown command {cmd!r}"
|
return False, f"unknown command {cmd!r}"
|
||||||
|
|
||||||
async def building_command(self, args: dict, now: float) -> tuple[bool, str]:
|
async def building_command(self, args: dict, now: float) -> tuple[bool, str]:
|
||||||
|
if args.get("control") == "sg_ready" and args.get("mode") == "shadow":
|
||||||
|
# the building went back to shadow: its SG Ready schedule ends here, the heat pump back to 2 (normal)
|
||||||
|
old = self.building.active.get("sg_ready")
|
||||||
|
if not old or str(old["building"]) != str(args.get("building")):
|
||||||
|
return True, "sg_ready: nothing to release"
|
||||||
|
self.building.lift("sg_ready")
|
||||||
|
self.act_now.set()
|
||||||
|
msg = "sg_ready released: the building is in shadow mode (SG Ready 2, normal)"
|
||||||
|
await self._publish("action", building_msg(old, "done", msg, now))
|
||||||
|
return True, msg
|
||||||
try:
|
try:
|
||||||
c = Building.parse(args)
|
c = Building.parse(args)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
|
if c["control"] == "sg_ready" and not any(x.kind == "heat_pump_sg" for x in self.controls):
|
||||||
|
why = "no SG Ready control on this box (a heat_pump_sg control in the mapping)"
|
||||||
|
await self._publish("action", building_msg(c, "refused", why, now))
|
||||||
|
return False, why
|
||||||
floors = []
|
floors = []
|
||||||
for ctl in self.controls:
|
for ctl in self.controls:
|
||||||
if ctl.kind in ("heating", "cooling"):
|
if ctl.kind in ("heating", "cooling"):
|
||||||
@@ -742,10 +760,22 @@ class Controller:
|
|||||||
floors.append((ctl.id, b.lo, b.hi, ctl.kind))
|
floors.append((ctl.id, b.lo, b.hi, ctl.kind))
|
||||||
ok, msg = self.building.take(c, floors)
|
ok, msg = self.building.take(c, floors)
|
||||||
await self._publish("action", building_msg(c, "done" if ok else "refused", msg if ok else msg, now))
|
await self._publish("action", building_msg(c, "done" if ok else "refused", msg if ok else msg, now))
|
||||||
if ok:
|
if ok and c["control"] == "sg_ready":
|
||||||
|
self.act_now.set() # the heat pump's state now (the executor; not a plan input)
|
||||||
|
elif ok:
|
||||||
self.wake.set() # a plan with it now
|
self.wake.set() # a plan with it now
|
||||||
return ok, msg
|
return ok, msg
|
||||||
|
|
||||||
|
def grid_order_in_force(self, now: float) -> str:
|
||||||
|
"""The grid operator's order in force now, in words ("" none): one from the EEBUS bridge (§14a EnWG
|
||||||
|
dimming), or a load limit the building relayed as an emergency with the operator's proof."""
|
||||||
|
if self.gridorders.active():
|
||||||
|
return "the grid operator's order (§14a EnWG)"
|
||||||
|
ll = self.building.active.get("load_limit")
|
||||||
|
if ll and ll.get("level") == "emergency" and ll["from"] <= now < ll["until"]:
|
||||||
|
return "the grid operator's relayed order"
|
||||||
|
return ""
|
||||||
|
|
||||||
def set_limit(self, a: dict, now: float) -> tuple[bool, str]:
|
def set_limit(self, a: dict, now: float) -> tuple[bool, str]:
|
||||||
from .limits import QUANTITIES
|
from .limits import QUANTITIES
|
||||||
c = {c.id: c for c in self.controls}.get(a.get("asset", ""))
|
c = {c.id: c for c in self.controls}.get(a.get("asset", ""))
|
||||||
|
|||||||
@@ -93,6 +93,12 @@ Kinds, their entities (* needed) and what the executor sets (channels):
|
|||||||
the owner's, else class D's limit (assumed); temperatures and
|
the owner's, else class D's limit (assumed); temperatures and
|
||||||
shares the mapping's, else the Parameters page's dhw.* rows;
|
shares the mapping's, else the Parameters page's dhw.* rows;
|
||||||
legionella plan | device (default: its own program) | none
|
legionella plan | device (default: its own program) | none
|
||||||
|
heat_pump_sg a heat pump's SG Ready input, set from its building's
|
||||||
|
schedule (the `sg_ready` command; sgready.py), never planned by
|
||||||
|
the box itself: sg_lock and sg_boost (switches: the label's two
|
||||||
|
relay contacts) or sg_ready (select, its options per state in
|
||||||
|
params.sg_options) *; power, buffer_temp (sensors, read only);
|
||||||
|
params.min_buffer_c (°C, the installer's): no lock at or below it
|
||||||
battery's idle loss (battery_idle_facts, S.2): standby_w and
|
battery's idle loss (battery_idle_facts, S.2): standby_w and
|
||||||
self_discharge_pct_month from the mapping, the device's standby
|
self_discharge_pct_month from the mapping, the device's standby
|
||||||
entity, the box's fit (storefit.py), the owner's ratings
|
entity, the box's fit (storefit.py), the owner's ratings
|
||||||
@@ -156,12 +162,17 @@ ENTITIES = {
|
|||||||
"temp_top": ("sensor",), "temp_bottom": ("sensor",), "heater_power": ("sensor",),
|
"temp_top": ("sensor",), "temp_bottom": ("sensor",), "heater_power": ("sensor",),
|
||||||
"room_temp": ("sensor",), "volume": ("sensor", "input_number"),
|
"room_temp": ("sensor",), "volume": ("sensor", "input_number"),
|
||||||
"standby_loss": ("sensor", "input_number")},
|
"standby_loss": ("sensor", "input_number")},
|
||||||
|
# a heat pump driven through its SG Ready input by its building's schedule (sgready.py): two relay contacts
|
||||||
|
# (the lock and the boost) or the device's own SG Ready select; read only: its power, its buffer's temperature
|
||||||
|
"heat_pump_sg": {"sg_ready": ("select", "input_select"), "sg_lock": ("switch", "input_boolean"),
|
||||||
|
"sg_boost": ("switch", "input_boolean"), "power": ("sensor",), "buffer_temp": ("sensor",)},
|
||||||
}
|
}
|
||||||
WRITES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover", "source",
|
WRITES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover", "source",
|
||||||
"water_heater", "power", "sg_ready", "dhw_comfort"}
|
"water_heater", "power", "sg_ready", "dhw_comfort", "sg_lock", "sg_boost"}
|
||||||
NEEDED = {"battery": (("charge_from_grid", "setpoint"),), "heating": (("climate", "switch"),),
|
NEEDED = {"battery": (("charge_from_grid", "setpoint"),), "heating": (("climate", "switch"),),
|
||||||
"cooling": (("climate",),), "ev": (("switch",),), "cover": (("cover",),),
|
"cooling": (("climate",),), "ev": (("switch",),), "cover": (("cover",),),
|
||||||
"dhw_tank": (("water_heater", "switch", "power", "sg_ready"),)}
|
"dhw_tank": (("water_heater", "switch", "power", "sg_ready"),),
|
||||||
|
"heat_pump_sg": (("sg_ready", "sg_lock", "sg_boost"),)}
|
||||||
# defaults per kind (params may override each)
|
# defaults per kind (params may override each)
|
||||||
PARAMS = {
|
PARAMS = {
|
||||||
# capacity_wh, max_charge_w, max_discharge_w, efficiency (one way, 0-1):
|
# capacity_wh, max_charge_w, max_discharge_w, efficiency (one way, 0-1):
|
||||||
@@ -226,6 +237,10 @@ PARAMS = {
|
|||||||
# data sheet; methods.md G7): else the Parameters page's dhw.hp_cop_drop_pct_per_k
|
# data sheet; methods.md G7): else the Parameters page's dhw.hp_cop_drop_pct_per_k
|
||||||
"cop_tank_curve": [],
|
"cop_tank_curve": [],
|
||||||
"min_switch_s": 600.0, "hold_mode_s": 1800.0, "hold_set_s": 900.0, "min_gain_ct": 1.0},
|
"min_switch_s": 600.0, "hold_mode_s": 1800.0, "hold_set_s": 900.0, "min_gain_ct": 1.0},
|
||||||
|
# a heat pump on SG Ready (sgready.py): the select's option per state "1".."4"; its contacts switch when the
|
||||||
|
# building's schedule moves (the schedule keeps the compressor's minimum run and off times: methods C2.9.5,
|
||||||
|
# the device's own controller its own)
|
||||||
|
"heat_pump_sg": {"sg_options": {}, "min_switch_s": 0.0},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -248,7 +263,9 @@ FACTS = {"battery": ("capacity_wh", "max_charge_w", "max_discharge_w", "efficien
|
|||||||
# a window's facts behind a cover (methods.md G3 in the plan; the installer's, the device's or the
|
# a window's facts behind a cover (methods.md G3 in the plan; the installer's, the device's or the
|
||||||
# owner's, never assumed): its glass area (m²), g-value (0-1), the share of the sun the closed cover
|
# owner's, never assumed): its glass area (m²), g-value (0-1), the share of the sun the closed cover
|
||||||
# keeps out (0-1), the window's U (W/m²K) and the factor a closed shutter leaves of it (0-1)
|
# keeps out (0-1), the window's U (W/m²K) and the factor a closed shutter leaves of it (0-1)
|
||||||
"cover": ("window_m2", "g_value", "shade_factor", "window_u", "closed_u_factor")}
|
"cover": ("window_m2", "g_value", "shade_factor", "window_u", "closed_u_factor"),
|
||||||
|
# the buffer's lowest usable temperature (°C, the installer's): no lock (SG Ready 1) at or below it
|
||||||
|
"heat_pump_sg": ("min_buffer_c",)}
|
||||||
# facts that may be 0 (a battery without idle loss), facts that are no numbers
|
# facts that may be 0 (a battery without idle loss), facts that are no numbers
|
||||||
ZERO_OK = {"standby_w", "self_discharge_pct_month"}
|
ZERO_OK = {"standby_w", "self_discharge_pct_month"}
|
||||||
TEXT_FACTS = {"heater", "erp_class", "grossanlage"}
|
TEXT_FACTS = {"heater", "erp_class", "grossanlage"}
|
||||||
@@ -862,6 +879,14 @@ def parse(raw: list | None, reading_assets: set[str], rooms: set[str] | None = N
|
|||||||
_check_heat(cid, params, ents)
|
_check_heat(cid, params, ents)
|
||||||
if kind == "dhw_tank":
|
if kind == "dhw_tank":
|
||||||
_check_tank(cid, params)
|
_check_tank(cid, params)
|
||||||
|
if kind == "heat_pump_sg":
|
||||||
|
opts = params.get("sg_options") or {}
|
||||||
|
if not isinstance(opts, dict) or set(map(str, opts)) - {"1", "2", "3", "4"}:
|
||||||
|
raise ValueError(f"control {cid}: sg_options names the select's option for the SG-Ready states 1-4")
|
||||||
|
if "sg_ready" in ents and "2" not in map(str, opts):
|
||||||
|
raise ValueError(f"control {cid}: an SG Ready select needs params.sg_options, at least state 2 (normal)")
|
||||||
|
if "sg_ready" in ents and ({"sg_lock", "sg_boost"} & set(ents)):
|
||||||
|
raise ValueError(f"control {cid}: an SG Ready select or the relay contacts, not both")
|
||||||
sw = {}
|
sw = {}
|
||||||
if c.get("switchover") is not None:
|
if c.get("switchover") is not None:
|
||||||
if kind not in ("heating", "cooling") or "climate" not in ents:
|
if kind not in ("heating", "cooling") or "climate" not in ents:
|
||||||
|
|||||||
@@ -102,7 +102,8 @@ PROFILE_STATUS = {"verified": (M("checked"), "ok", M("Checked on a device: its v
|
|||||||
"device. Look at its values before you turn reading on.")),
|
"device. Look at its values before you turn reading on.")),
|
||||||
"draft": (M("draft"), "warn", M("A draft profile: check the values before you turn reading on."))}
|
"draft": (M("draft"), "warn", M("A draft profile: check the values before you turn reading on."))}
|
||||||
CONTROL_WORDS = {"battery": M("battery"), "heating": M("heating"), "cooling": M("cooling"), "ev": M("charging"),
|
CONTROL_WORDS = {"battery": M("battery"), "heating": M("heating"), "cooling": M("cooling"), "ev": M("charging"),
|
||||||
"cover": M("blinds and curtains"), "dhw_tank": M("hot-water tank")}
|
"cover": M("blinds and curtains"), "dhw_tank": M("hot-water tank"),
|
||||||
|
"heat_pump_sg": M("heat pump (SG Ready)")}
|
||||||
# What a device reads, by meaning (the devices tool gives the keys:
|
# What a device reads, by meaning (the devices tool gives the keys:
|
||||||
# devprofiles.reads); never the asset ids.
|
# devprofiles.reads); never the asset ids.
|
||||||
QUANTITY_WORDS = {
|
QUANTITY_WORDS = {
|
||||||
|
|||||||
@@ -68,7 +68,9 @@ PART_RE = re.compile(r"^(" + "|".join(SUMMED) + r")\.(\d{1,3})\.([a-z_]+)$")
|
|||||||
WRITE_ROLES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover", "water_heater", "sg_ready"}
|
WRITE_ROLES = {"charge_from_grid", "setpoint", "mode", "climate", "switch", "current", "cover", "water_heater", "sg_ready"}
|
||||||
# Roles that write only on some kinds: a tank's "power" is a stepless
|
# Roles that write only on some kinds: a tank's "power" is a stepless
|
||||||
# heater's watts (a number); a battery's or a car's "power" is a reading.
|
# heater's watts (a number); a battery's or a car's "power" is a reading.
|
||||||
KIND_WRITE_ROLES = {"dhw_tank": {"power"}}
|
KIND_WRITE_ROLES = {"dhw_tank": {"power"},
|
||||||
|
# a heat pump's SG Ready contacts (sgready.py): the lock and the boost relay
|
||||||
|
"heat_pump_sg": {"sg_lock", "sg_boost"}}
|
||||||
|
|
||||||
|
|
||||||
def is_write(kind, role) -> bool:
|
def is_write(kind, role) -> bool:
|
||||||
|
|||||||
@@ -18,8 +18,10 @@ A flexible command the owner overrides by hand ends (reported "overridden");
|
|||||||
binding and emergency commands are applied again (the flat cannot lift them).
|
binding and emergency commands are applied again (the flat cannot lift them).
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
from . import sgready
|
||||||
from .guard import Action
|
from .guard import Action
|
||||||
from .inputs import cover_position, cover_positions, number
|
from .inputs import cover_position, cover_positions, number
|
||||||
|
|
||||||
@@ -143,6 +145,25 @@ def actions_for(c, want, col, level="plan", why="") -> list[Action]:
|
|||||||
setnum("power", float(v), "power_w")
|
setnum("power", float(v), "power_w")
|
||||||
elif number(v) is not None and "switch" in e:
|
elif number(v) is not None and "switch" in e:
|
||||||
switch("switch", float(v) > 0)
|
switch("switch", float(v) > 0)
|
||||||
|
elif c.kind == "heat_pump_sg":
|
||||||
|
# a heat pump's SG Ready input (sgready.py): "sg:3" as its select's option, or as the label's two contacts
|
||||||
|
# (the ones to open first, then the boost, then the lock: never a lock and a boost together on the way)
|
||||||
|
v = want.get("set") if isinstance(want, dict) else want
|
||||||
|
if not (isinstance(v, str) and v.startswith("sg:") and v[3:] in ("1", "2", "3", "4")):
|
||||||
|
return out
|
||||||
|
if "sg_ready" in e:
|
||||||
|
opt = (c.p("sg_options") or {}).get(v[3:])
|
||||||
|
if opt is not None and col.state(e["sg_ready"]) != str(opt):
|
||||||
|
act("sg_ready", "select_option", {"option": str(opt)}, str(opt))
|
||||||
|
else:
|
||||||
|
from .sgready import RELAYS
|
||||||
|
lock, boost = RELAYS[int(v[3:])]
|
||||||
|
for ch, on in (("sg_lock", lock), ("sg_boost", boost)):
|
||||||
|
if not on:
|
||||||
|
switch(ch, False)
|
||||||
|
for ch, on in (("sg_boost", boost), ("sg_lock", lock)):
|
||||||
|
if on:
|
||||||
|
switch(ch, True)
|
||||||
elif c.kind == "cover":
|
elif c.kind == "cover":
|
||||||
v = number(want.get("set") if isinstance(want, dict) else want)
|
v = number(want.get("set") if isinstance(want, dict) else want)
|
||||||
if v is not None:
|
if v is not None:
|
||||||
@@ -189,6 +210,13 @@ class Executor:
|
|||||||
self.log: list[dict] = [] # the last actions (tests, status)
|
self.log: list[dict] = [] # the last actions (tests, status)
|
||||||
self.shade_moves = None # shades.Moves: what each shade was last moved for
|
self.shade_moves = None # shades.Moves: what each shade was last moved for
|
||||||
self.on_override = None # a callable(ev): each change by hand (comfort.Tolerance)
|
self.on_override = None # a callable(ev): each change by hand (comfort.Tolerance)
|
||||||
|
# a heat pump's SG Ready from its building's schedule (sgready.py): the locks it had, the Parameters rows
|
||||||
|
# (the tariff bundle's), the grid operator's order in force ("" none), the last feedback per control
|
||||||
|
self.sg_log = sgready.LockLog(os.path.dirname(building.path), clock) if building is not None else None
|
||||||
|
self.box_params = lambda now: {}
|
||||||
|
self.grid_order = lambda now: ""
|
||||||
|
self._sg_told: dict[str, tuple] = {}
|
||||||
|
self._last_refusal = ""
|
||||||
|
|
||||||
# -- what is wanted ------------------------------------------------------
|
# -- what is wanted ------------------------------------------------------
|
||||||
def wanted(self, c, now):
|
def wanted(self, c, now):
|
||||||
@@ -227,6 +255,8 @@ class Executor:
|
|||||||
return want, level, why
|
return want, level, why
|
||||||
|
|
||||||
def _wanted(self, c, now):
|
def _wanted(self, c, now):
|
||||||
|
if c.kind == "heat_pump_sg":
|
||||||
|
return self._sg_wanted(c, now)
|
||||||
cmd = self.commands.get(c.id)
|
cmd = self.commands.get(c.id)
|
||||||
if cmd and now < cmd["until"]:
|
if cmd and now < cmd["until"]:
|
||||||
return cmd["set"], cmd["level"], cmd.get("why") or f"{cmd['level']} command"
|
return cmd["set"], cmd["level"], cmd.get("why") or f"{cmd['level']} command"
|
||||||
@@ -245,6 +275,41 @@ class Executor:
|
|||||||
return e, "plan", (e or {}).get("why", "")
|
return e, "plan", (e or {}).get("why", "")
|
||||||
return safe_want(c), "plan", "safe default: the plan or its data is stale"
|
return safe_want(c), "plan", "safe default: the plan or its data is stale"
|
||||||
|
|
||||||
|
def _sg_wanted(self, c, now):
|
||||||
|
"""A heat pump's SG Ready now: its building's state through sgready.decide (the lock's limits, the grid
|
||||||
|
operator's order, the buffer), at the command's level; the device's state read back first (its locks)."""
|
||||||
|
if self.sg_log is not None:
|
||||||
|
self.sg_log.note(sgready.read_state(c, self.col), now)
|
||||||
|
state, cmd = self.building.sg_state(now) if self.building is not None else (None, None)
|
||||||
|
buf = self.col.value(c.entities["buffer_temp"]) if c.entities.get("buffer_temp") else None
|
||||||
|
got, why = sgready.decide(c, state, now, self.sg_log or sgready.LockLog("/nonexistent"), self.box_params(now) or {},
|
||||||
|
grid_order=self.grid_order(now), buffer_c=buf)
|
||||||
|
if cmd is None:
|
||||||
|
return {"set": f"sg:{got}", "sg": (None, got, why, None)}, "plan", why
|
||||||
|
return ({"set": f"sg:{got}", "sg": (state, got, why, cmd)}, cmd["level"],
|
||||||
|
f"building {cmd['building']}: {why}")
|
||||||
|
|
||||||
|
async def _sg_feedback(self, c, want, acts_ok: bool, refusal: str, now):
|
||||||
|
"""The building's answer per SG Ready command (an `action` about the command, building_msg): done when
|
||||||
|
the device is at the schedule's state, refused with why (a rule of sgready.py, the guard's refusal);
|
||||||
|
sent when it changes, not every round."""
|
||||||
|
state, got, why, cmd = want["sg"]
|
||||||
|
if cmd is None:
|
||||||
|
return
|
||||||
|
if got != state:
|
||||||
|
result, text = "refused", why
|
||||||
|
elif not acts_ok:
|
||||||
|
result, text = "refused", f"SG Ready {state} not set: {refusal}"
|
||||||
|
else:
|
||||||
|
result, text = "done", f"SG Ready {state} set"
|
||||||
|
key = (cmd["id"], state, got, result, text if result == "refused" else "")
|
||||||
|
if self._sg_told.get(c.id) == key:
|
||||||
|
return
|
||||||
|
self._sg_told[c.id] = key
|
||||||
|
msg = building_msg(cmd, result, text, now)
|
||||||
|
msg.update({"asset": c.id, "value": got, "set": state})
|
||||||
|
await self.publish("action", msg)
|
||||||
|
|
||||||
def _capped(self, c, want, level, why, now):
|
def _capped(self, c, want, level, why, now):
|
||||||
"""The building's thermostat cap on a climate's setpoint (heating: at
|
"""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
|
most, cooling: at least), at the cap's level: a binding cap applies
|
||||||
@@ -271,6 +336,11 @@ class Executor:
|
|||||||
now = self.clock()
|
now = self.clock()
|
||||||
await self._overrides(now)
|
await self._overrides(now)
|
||||||
if not auto or client is None:
|
if not auto or client is None:
|
||||||
|
# a heat pump's SG Ready command: the building hears that this box does not act now
|
||||||
|
for c in self.controls.values():
|
||||||
|
if c.kind == "heat_pump_sg":
|
||||||
|
want, _, _ = self.wanted(c, now)
|
||||||
|
await self._sg_feedback(c, want, False, f"mode {self.guard.mode()}: the box does not act", now)
|
||||||
return
|
return
|
||||||
sw = self.guard.switchover
|
sw = self.guard.switchover
|
||||||
for c in self.controls.values():
|
for c in self.controls.values():
|
||||||
@@ -278,6 +348,14 @@ class Executor:
|
|||||||
continue # the thermostat's other control acts (switchover.py)
|
continue # the thermostat's other control acts (switchover.py)
|
||||||
want, level, why = self.wanted(c, now)
|
want, level, why = self.wanted(c, now)
|
||||||
acts = actions_for(c, want, self.col, level, why)
|
acts = actions_for(c, want, self.col, level, why)
|
||||||
|
if c.kind == "heat_pump_sg":
|
||||||
|
ok, refusal = True, ""
|
||||||
|
for a in acts:
|
||||||
|
if not await self._do(client, a, now):
|
||||||
|
ok, refusal = False, self._last_refusal
|
||||||
|
break # never a lock and a boost half-set: the rest waits
|
||||||
|
await self._sg_feedback(c, want, ok, refusal, now)
|
||||||
|
continue
|
||||||
if why.startswith("building") and "climate" in c.entities and not any(a.channel == "climate" for a in acts):
|
if why.startswith("building") and "climate" in c.entities and not any(a.channel == "climate" for a in acts):
|
||||||
# the room is within the building's cap already: a change by
|
# the room is within the building's cap already: a change by
|
||||||
# hand still counts as an override of the cap (a room only: a
|
# hand still counts as an override of the cap (a room only: a
|
||||||
@@ -293,6 +371,7 @@ class Executor:
|
|||||||
|
|
||||||
async def _do(self, client, a: Action, now) -> bool:
|
async def _do(self, client, a: Action, now) -> bool:
|
||||||
ok, reason = self.guard.check(a)
|
ok, reason = self.guard.check(a)
|
||||||
|
self._last_refusal = reason
|
||||||
if not ok:
|
if not ok:
|
||||||
key = (a.control, reason.split(" ")[0] + reason[-12:])
|
key = (a.control, reason.split(" ")[0] + reason[-12:])
|
||||||
if now - self._refused.get(key, 0) >= 3600:
|
if now - self._refused.get(key, 0) >= 3600:
|
||||||
@@ -302,6 +381,7 @@ class Executor:
|
|||||||
try:
|
try:
|
||||||
await client.call_service(a.domain, a.service, a.entity, a.data, self._allowed(a))
|
await client.call_service(a.domain, a.service, a.entity, a.data, self._allowed(a))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
self._last_refusal = "failed: " + str(e)[:200]
|
||||||
await self._report(a, "failed", str(e)[:200], now)
|
await self._report(a, "failed", str(e)[:200], now)
|
||||||
return False
|
return False
|
||||||
self.guard.done(a)
|
self.guard.done(a)
|
||||||
@@ -400,6 +480,8 @@ class Executor:
|
|||||||
c = self.controls.get(cid)
|
c = self.controls.get(cid)
|
||||||
if c is None:
|
if c is None:
|
||||||
return False, f"no control {cid!r}"
|
return False, f"no control {cid!r}"
|
||||||
|
if c.kind == "heat_pump_sg":
|
||||||
|
return False, f"{cid}: set by its building's SG Ready schedule only"
|
||||||
sw = self.guard.switchover
|
sw = self.guard.switchover
|
||||||
if sw is not None and not sw.active(c):
|
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)"
|
return False, f"{cid}: not active now (the thermostat is on its other side: switchover)"
|
||||||
|
|||||||
@@ -99,10 +99,23 @@ def feature_names(series: str) -> list[str]:
|
|||||||
return list(SERIES_FEATURES.get(series, LOAD_FEATURES))
|
return list(SERIES_FEATURES.get(series, LOAD_FEATURES))
|
||||||
|
|
||||||
|
|
||||||
def level_floor(series: str) -> float:
|
# nMAE is not given where the held-out window's metered mean is under this share
|
||||||
|
# of the training window's (a short history's 6 h night: a mean near zero made
|
||||||
|
# nMAE thousands of percent; the cloud's value: Parameters forecast.trainer.
|
||||||
|
# min_level_share, trainlib.Selection; the box has no Parameters: this one)
|
||||||
|
MIN_LEVEL_SHARE = 0.25
|
||||||
|
|
||||||
|
|
||||||
|
def level_floor(series: str, y_train: np.ndarray | None = None, share: float = 0.0) -> float:
|
||||||
"""The metered mean under which nMAE is not given (metrics): 1 W for
|
"""The metered mean under which nMAE is not given (metrics): 1 W for
|
||||||
a power, 0.01 for a share (FRACTION_SERIES)."""
|
a power, 0.01 for a share (FRACTION_SERIES); with y_train, at least
|
||||||
return 0.01 if series in FRACTION_SERIES else 1.0
|
`share` of the training window's mean level (the held-out window is
|
||||||
|
then not a night against a day)."""
|
||||||
|
base = 0.01 if series in FRACTION_SERIES else 1.0
|
||||||
|
if y_train is None or share <= 0:
|
||||||
|
return base
|
||||||
|
ok = y_train[~np.isnan(y_train)]
|
||||||
|
return max(base, share * float(np.abs(ok).mean())) if len(ok) else base
|
||||||
|
|
||||||
|
|
||||||
def digits(series: str) -> int:
|
def digits(series: str) -> int:
|
||||||
|
|||||||
@@ -462,6 +462,7 @@ MESSAGES = {
|
|||||||
"Saved. The next plan uses them.": "Gespeichert. Der nächste Plan verwendet sie.",
|
"Saved. The next plan uses them.": "Gespeichert. Der nächste Plan verwendet sie.",
|
||||||
"hot-water tank": "Warmwasserspeicher",
|
"hot-water tank": "Warmwasserspeicher",
|
||||||
"Hot-water tank": "Warmwasserspeicher",
|
"Hot-water tank": "Warmwasserspeicher",
|
||||||
|
"heat pump (SG Ready)": "Wärmepumpe (SG Ready)",
|
||||||
"battery idle use": "Eigenverbrauch des Speichers",
|
"battery idle use": "Eigenverbrauch des Speichers",
|
||||||
"tank temperature (top)": "Speichertemperatur (oben)",
|
"tank temperature (top)": "Speichertemperatur (oben)",
|
||||||
"tank temperature (bottom)": "Speichertemperatur (unten)",
|
"tank temperature (bottom)": "Speichertemperatur (unten)",
|
||||||
|
|||||||
@@ -1075,6 +1075,8 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
|
|||||||
cop_src, band_src, fallback, zone_src = {}, {}, [], {}
|
cop_src, band_src, fallback, zone_src = {}, {}, [], {}
|
||||||
one_room = sum(c.kind in ("heating", "cooling") for c in controls) == 1
|
one_room = sum(c.kind in ("heating", "cooling") for c in controls) == 1
|
||||||
for c in controls:
|
for c in controls:
|
||||||
|
if c.kind == "heat_pump_sg":
|
||||||
|
continue # its building's schedule sets it (sgready.py), not this plan
|
||||||
if hasattr(c, "learn_range"):
|
if hasattr(c, "learn_range"):
|
||||||
c.learn_range(col) # a climate's own min_temp..max_temp
|
c.learn_range(col) # a climate's own min_temp..max_temp
|
||||||
bounds = {}
|
bounds = {}
|
||||||
@@ -1544,7 +1546,7 @@ def room_refusal(c, st: dict, rc: str, power: str, source: str = "electric", cop
|
|||||||
|
|
||||||
def _quantities(c) -> list[str]:
|
def _quantities(c) -> list[str]:
|
||||||
return {"battery": ["soc_pct", "power_w"], "heating": ["temp_c"], "cooling": ["temp_c"],
|
return {"battery": ["soc_pct", "power_w"], "heating": ["temp_c"], "cooling": ["temp_c"],
|
||||||
"ev": ["current_a"], "cover": ["position_pct"], "dhw_tank": ["temp_c"]}[c.kind]
|
"ev": ["current_a"], "cover": ["position_pct"], "dhw_tank": ["temp_c"]}.get(c.kind, [])
|
||||||
|
|
||||||
|
|
||||||
def _param_names(c) -> list[str]:
|
def _param_names(c) -> list[str]:
|
||||||
|
|||||||
@@ -184,6 +184,12 @@ NAMES = {
|
|||||||
"pref_needed": {"en": "{0}: needed once at", "de": "{0}: einmalig gebraucht um"},
|
"pref_needed": {"en": "{0}: needed once at", "de": "{0}: einmalig gebraucht um"},
|
||||||
"pref_reserve": {"en": "{0}: reserve", "de": "{0}: Reserve"},
|
"pref_reserve": {"en": "{0}: reserve", "de": "{0}: Reserve"},
|
||||||
"pref_reserve_blocks": {"en": "{0}: reserve by time", "de": "{0}: Reserve nach Uhrzeit"},
|
"pref_reserve_blocks": {"en": "{0}: reserve by time", "de": "{0}: Reserve nach Uhrzeit"},
|
||||||
|
"pref_comfort": {"en": "Comfort", "de": "Komfort"},
|
||||||
|
"comfort_comfort": {"en": "Comfort", "de": "Komfort"},
|
||||||
|
"comfort_balanced": {"en": "Balanced", "de": "Ausgewogen"},
|
||||||
|
"comfort_saving": {"en": "Saving", "de": "Sparsam"},
|
||||||
|
"pref_hotwater": {"en": "{0}: hot-water times", "de": "{0}: Warmwasserzeiten"},
|
||||||
|
"pref_last_change": {"en": "Last setting made here", "de": "Letzte Einstellung hier"},
|
||||||
"pref_result": {"en": "Preferences", "de": "Präferenzen"},
|
"pref_result": {"en": "Preferences", "de": "Präferenzen"},
|
||||||
"pref_result_of": {"en": "{0}: preferences", "de": "{0}: Präferenzen"},
|
"pref_result_of": {"en": "{0}: preferences", "de": "{0}: Präferenzen"},
|
||||||
# the household's own costs (costs.py; announce.py, dashboards.py view "costs")
|
# the household's own costs (costs.py; announce.py, dashboards.py view "costs")
|
||||||
|
|||||||
@@ -840,6 +840,8 @@ class Preferences:
|
|||||||
b = {"kind": "car", "need_kwh": round(need / 1000.0, 2) if need is not None else None,
|
b = {"kind": "car", "need_kwh": round(need / 1000.0, 2) if need is not None else None,
|
||||||
"ready_by": str(c.p("departure") or ""),
|
"ready_by": str(c.p("departure") or ""),
|
||||||
"car": [r for r in ("departure", "energy_needed") if c.entities.get(r)]}
|
"car": [r for r in ("departure", "energy_needed") if c.entities.get(r)]}
|
||||||
|
elif c.kind == "dhw_tank":
|
||||||
|
continue # a tank's own minimum is a Parameters row (dhw.min_temp_c), not a target here
|
||||||
else:
|
else:
|
||||||
if v and (float(v.get("reserve_pct") or 0) > 0 or v.get("blocks")):
|
if v and (float(v.get("reserve_pct") or 0) > 0 or v.get("blocks")):
|
||||||
continue
|
continue
|
||||||
@@ -855,7 +857,8 @@ class Preferences:
|
|||||||
for c in controls:
|
for c in controls:
|
||||||
if c.kind not in KINDS:
|
if c.kind not in KINDS:
|
||||||
continue
|
continue
|
||||||
q = {"heating": "temp_c", "cooling": "temp_c", "battery": "soc_pct", "ev": "current_a"}[c.kind]
|
q = {"heating": "temp_c", "cooling": "temp_c", "battery": "soc_pct", "ev": "current_a",
|
||||||
|
"dhw_tank": "temp_c"}[c.kind]
|
||||||
b = c.bounds(q)
|
b = c.bounds(q)
|
||||||
cl.append({"id": c.id, "kind": c.kind, "name": c.label(), "bounds": [b.lo, b.hi],
|
cl.append({"id": c.id, "kind": c.kind, "name": c.label(), "bounds": [b.lo, b.hi],
|
||||||
"setback_c": _p(c, "setback_c"), "setup_c": _p(c, "setup_c"), "comfort_c": _p(c, "comfort_c")})
|
"setback_c": _p(c, "setback_c"), "setup_c": _p(c, "setup_c"), "comfort_c": _p(c, "comfort_c")})
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||||
|
"""A heat pump's SG Ready input, driven by its building's schedule.
|
||||||
|
|
||||||
|
The building plan sets the building heat pump's SG Ready state per
|
||||||
|
quarter-hour (a `building` command, control `sg_ready`: building.py); the
|
||||||
|
box's control of kind `heat_pump_sg` (controls.py) carries it out on the
|
||||||
|
device's SG Ready input:
|
||||||
|
|
||||||
|
- two relay contacts (switch entities `sg_lock`, `sg_boost`), as the SG
|
||||||
|
Ready label (Bundesverband Waermepumpe) wires them:
|
||||||
|
state 1 lock on, boost off blocked (the utility's lock)
|
||||||
|
state 2 lock off, boost off normal
|
||||||
|
state 3 lock off, boost on on, recommended
|
||||||
|
state 4 lock on, boost on forced on
|
||||||
|
A device with one contact only takes what that contact can say (a lock
|
||||||
|
contact: 1 and 2; a boost contact: 2 and 3, 4 as 3).
|
||||||
|
- or a select entity (`sg_ready`) the device or its integration exposes,
|
||||||
|
its option per state in params.sg_options {"1": ..., "4": ...}.
|
||||||
|
|
||||||
|
What the box sets is the schedule's state through these rules (decide),
|
||||||
|
in this order, each refusal named:
|
||||||
|
|
||||||
|
1. no command in force (none taken, or it ended): 2, normal; the device's
|
||||||
|
own control runs it;
|
||||||
|
2. a grid operator's order in force (§14a EnWG dimming, a relayed
|
||||||
|
emergency limit): never 3 or 4 (no increased operation against it);
|
||||||
|
3. state 1 (the lock) only within the grid contract's limits, the
|
||||||
|
Parameters rows from the tariff bundle (never a value of the box's
|
||||||
|
own; a row missing: no lock, named):
|
||||||
|
heat.sg_ready_block_max_h one lock at most this long
|
||||||
|
heat.sg_ready_lock_max_h_day locked at most this long in any
|
||||||
|
24 h (stricter than per day)
|
||||||
|
heat.sg_ready_lock_min_release_h released at least this long
|
||||||
|
between two locks
|
||||||
|
and only while the buffer covers: where the control maps the buffer's
|
||||||
|
temperature (`buffer_temp`) and gives its floor (params.min_buffer_c,
|
||||||
|
the installer's fact), not at or below it;
|
||||||
|
4. a state the device's contacts cannot say: the nearest it can.
|
||||||
|
|
||||||
|
Then the guard (guard.py) as for every action: the device's protection,
|
||||||
|
the box's mode (only auto acts), the owner's consent for the site and for
|
||||||
|
the control, the allow-list, the rate. The locks the device actually had
|
||||||
|
(its read-back state, whoever set it) are kept in <state dir>/sgready.json
|
||||||
|
for rule 3.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
STATES = (1, 2, 3, 4)
|
||||||
|
NORMAL = 2
|
||||||
|
# the SG Ready label's contacts per state: (lock, boost)
|
||||||
|
RELAYS = {1: (True, False), 2: (False, False), 3: (False, True), 4: (True, True)}
|
||||||
|
BLOCK_KEY = "heat.sg_ready_block_max_h"
|
||||||
|
LOCK_DAY_KEY = "heat.sg_ready_lock_max_h_day"
|
||||||
|
RELEASE_KEY = "heat.sg_ready_lock_min_release_h"
|
||||||
|
PARAM_KEYS = (BLOCK_KEY, LOCK_DAY_KEY, RELEASE_KEY)
|
||||||
|
WINDOW_S = 86400 # the lock's budget: any 24 h (a day's limit, held over every day)
|
||||||
|
KEEP_S = 2 * 86400 # locks older than this are forgotten
|
||||||
|
|
||||||
|
|
||||||
|
def _num(v) -> float | None:
|
||||||
|
try:
|
||||||
|
x = float(v)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
return x if x == x and abs(x) != float("inf") else None
|
||||||
|
|
||||||
|
|
||||||
|
def read_state(c, col) -> int | None:
|
||||||
|
"""The device's SG Ready state now: its select's option (params.sg_options
|
||||||
|
reversed), else its contacts; None where unknown."""
|
||||||
|
e = c.entities
|
||||||
|
if e.get("sg_ready"):
|
||||||
|
opts = {str(v): int(k) for k, v in (c.p("sg_options") or {}).items() if str(k).isdigit()}
|
||||||
|
return opts.get(str(col.state(e["sg_ready"])))
|
||||||
|
lock = col.state(e["sg_lock"]) if e.get("sg_lock") else "off"
|
||||||
|
boost = col.state(e["sg_boost"]) if e.get("sg_boost") else "off"
|
||||||
|
if lock not in ("on", "off") or boost not in ("on", "off"):
|
||||||
|
return None
|
||||||
|
return {v: k for k, v in RELAYS.items()}[(lock == "on", boost == "on")]
|
||||||
|
|
||||||
|
|
||||||
|
def expressible(c, state: int) -> tuple[int, str]:
|
||||||
|
"""The nearest state the control's entities can say, and why it differs."""
|
||||||
|
e = c.entities
|
||||||
|
if e.get("sg_ready"):
|
||||||
|
opts = c.p("sg_options") or {}
|
||||||
|
if str(state) in opts:
|
||||||
|
return state, ""
|
||||||
|
return NORMAL, f"the select has no option for SG Ready {state} (params.sg_options)"
|
||||||
|
lock, boost = bool(e.get("sg_lock")), bool(e.get("sg_boost"))
|
||||||
|
need_lock, need_boost = RELAYS[state]
|
||||||
|
if (lock or not need_lock) and (boost or not need_boost):
|
||||||
|
return state, ""
|
||||||
|
if state == 4 and boost:
|
||||||
|
return 3, "no lock contact (sg_lock): SG Ready 4 as 3"
|
||||||
|
return NORMAL, f"no {'lock (sg_lock)' if need_lock and not lock else 'boost (sg_boost)'} contact for SG Ready {state}"
|
||||||
|
|
||||||
|
|
||||||
|
class LockLog:
|
||||||
|
"""The device's locks (state 1) as read back: [start, end or None]."""
|
||||||
|
|
||||||
|
def __init__(self, state_dir: str, clock=time.time):
|
||||||
|
self.path, self.clock = os.path.join(state_dir, "sgready.json"), clock
|
||||||
|
self.locks: list[list] = []
|
||||||
|
try:
|
||||||
|
with open(self.path) as f:
|
||||||
|
self.locks = [[float(a), None if b is None else float(b)] for a, b in json.load(f).get("locks", [])]
|
||||||
|
except (OSError, ValueError, TypeError, AttributeError):
|
||||||
|
self.locks = []
|
||||||
|
|
||||||
|
def _save(self):
|
||||||
|
tmp = self.path + ".tmp"
|
||||||
|
with open(tmp, "w") as f:
|
||||||
|
json.dump({"locks": self.locks}, f)
|
||||||
|
os.replace(tmp, self.path)
|
||||||
|
|
||||||
|
def note(self, state: int | None, now: float):
|
||||||
|
"""The device's state now: a lock opens at a 1, closes at anything else known."""
|
||||||
|
if state is None:
|
||||||
|
return
|
||||||
|
open_ = bool(self.locks) and self.locks[-1][1] is None
|
||||||
|
changed = False
|
||||||
|
if state == 1 and not open_:
|
||||||
|
self.locks.append([now, None])
|
||||||
|
changed = True
|
||||||
|
elif state != 1 and open_:
|
||||||
|
self.locks[-1][1] = now
|
||||||
|
changed = True
|
||||||
|
old = len(self.locks)
|
||||||
|
self.locks = [x for x in self.locks if x[1] is None or now - x[1] < KEEP_S]
|
||||||
|
if changed or len(self.locks) != old:
|
||||||
|
self._save()
|
||||||
|
|
||||||
|
def block_s(self, now: float) -> float:
|
||||||
|
"""How long the lock in force has lasted (0: none)."""
|
||||||
|
return now - self.locks[-1][0] if self.locks and self.locks[-1][1] is None else 0.0
|
||||||
|
|
||||||
|
def locked_s(self, now: float, window: float = WINDOW_S) -> float:
|
||||||
|
"""Seconds locked within the last window."""
|
||||||
|
return sum(max(0.0, (now if b is None else b) - max(a, now - window)) for a, b in self.locks)
|
||||||
|
|
||||||
|
def released_s(self, now: float) -> float | None:
|
||||||
|
"""Seconds since the last lock ended (None: no lock ended, or one is in force)."""
|
||||||
|
if not self.locks or self.locks[-1][1] is None:
|
||||||
|
return None
|
||||||
|
return now - self.locks[-1][1]
|
||||||
|
|
||||||
|
|
||||||
|
def lock_rows(box_params: dict) -> tuple[dict[str, float], list[str]]:
|
||||||
|
"""The lock's Parameters rows (hours) and the ones missing."""
|
||||||
|
got, missing = {}, []
|
||||||
|
for k in PARAM_KEYS:
|
||||||
|
v = _num(box_params.get(k))
|
||||||
|
if v is None or v < 0:
|
||||||
|
missing.append(k)
|
||||||
|
else:
|
||||||
|
got[k] = v
|
||||||
|
return got, missing
|
||||||
|
|
||||||
|
|
||||||
|
def decide(c, want: int | None, now: float, log: LockLog, box_params: dict, *, grid_order: str = "",
|
||||||
|
buffer_c: float | None = None) -> tuple[int, str]:
|
||||||
|
"""The state to set and why (the rules of the module's doc, in order)."""
|
||||||
|
if want not in STATES:
|
||||||
|
return NORMAL, "no SG Ready command in force: 2, normal (the heat pump's own control)"
|
||||||
|
if want in (3, 4) and grid_order:
|
||||||
|
return NORMAL, f"SG Ready {want} refused: {grid_order} in force (no increased operation): 2"
|
||||||
|
if want == 1:
|
||||||
|
rows, missing = lock_rows(box_params)
|
||||||
|
floor = _num(c.p("min_buffer_c"))
|
||||||
|
if missing:
|
||||||
|
return NORMAL, "SG Ready 1 refused: Parameters row" + ("s " if len(missing) > 1 else " ") + \
|
||||||
|
", ".join(missing) + " missing (the tariff bundle): 2"
|
||||||
|
block, day, rel = rows[BLOCK_KEY] * 3600, rows[LOCK_DAY_KEY] * 3600, rows[RELEASE_KEY] * 3600
|
||||||
|
cur = log.block_s(now)
|
||||||
|
if cur and cur >= block:
|
||||||
|
return NORMAL, f"SG Ready 1 refused: locked {cur / 3600:.2f} h, one lock at most {rows[BLOCK_KEY]:g} h ({BLOCK_KEY}): 2"
|
||||||
|
if log.locked_s(now) >= day:
|
||||||
|
return NORMAL, (f"SG Ready 1 refused: locked {log.locked_s(now) / 3600:.2f} h in the last 24 h, at most "
|
||||||
|
f"{rows[LOCK_DAY_KEY]:g} h ({LOCK_DAY_KEY}): 2")
|
||||||
|
r = log.released_s(now)
|
||||||
|
if not cur and r is not None and r < rel:
|
||||||
|
return NORMAL, (f"SG Ready 1 refused: released {r / 3600:.2f} h ago, at least {rows[RELEASE_KEY]:g} h between "
|
||||||
|
f"two locks ({RELEASE_KEY}): 2")
|
||||||
|
if floor is not None and c.entities.get("buffer_temp"):
|
||||||
|
if buffer_c is None:
|
||||||
|
return NORMAL, "SG Ready 1 refused: the buffer's temperature is unknown now: 2"
|
||||||
|
if buffer_c <= floor:
|
||||||
|
return NORMAL, f"SG Ready 1 refused: the buffer at {buffer_c:.1f} °C, at most its floor {floor:g} °C: 2"
|
||||||
|
got, why = expressible(c, want)
|
||||||
|
return got, (f"SG Ready {want}" + (f" as {got}: {why}" if got != want else ""))
|
||||||
@@ -66,10 +66,14 @@ class Selection:
|
|||||||
prior: a shorter window starves it less)
|
prior: a shorter window starves it less)
|
||||||
baseline_margin a model other than the hour-of-week goes in force
|
baseline_margin a model other than the hour-of-week goes in force
|
||||||
(and stays there) only when its held-out score is
|
(and stays there) only when its held-out score is
|
||||||
below the baseline's by this fraction"""
|
below the baseline's by this fraction
|
||||||
|
min_level_share nMAE is given only where the held-out window's metered
|
||||||
|
mean is at least this share of the training window's
|
||||||
|
(else MAE: a night against a day)"""
|
||||||
min_holdout_days: float
|
min_holdout_days: float
|
||||||
min_holdout_days_pv: float
|
min_holdout_days_pv: float
|
||||||
baseline_margin: float
|
baseline_margin: float
|
||||||
|
min_level_share: float
|
||||||
|
|
||||||
def min_days(self, series: str) -> float:
|
def min_days(self, series: str) -> float:
|
||||||
return self.min_holdout_days_pv if series in PV_SERIES else self.min_holdout_days
|
return self.min_holdout_days_pv if series in PV_SERIES else self.min_holdout_days
|
||||||
@@ -88,6 +92,13 @@ def cut_for(t: np.ndarray, y: np.ndarray, sel: Selection | None = None, series:
|
|||||||
return fcmodels.holdout(t, y), True
|
return fcmodels.holdout(t, y), True
|
||||||
|
|
||||||
|
|
||||||
|
def floor_for(series: str, y_train: np.ndarray, sel: Selection | None) -> float:
|
||||||
|
"""The level under which the held-out window's nMAE is not given:
|
||||||
|
fcmodels.level_floor with the share of the training mean (sel.min_level_share;
|
||||||
|
without a Selection, the box: fcmodels.MIN_LEVEL_SHARE)."""
|
||||||
|
return fcmodels.level_floor(series, y_train, sel.min_level_share if sel else fcmodels.MIN_LEVEL_SHARE)
|
||||||
|
|
||||||
|
|
||||||
def floored(scores: dict, champ: float | None, champ_kind: str | None, sel: Selection | None
|
def floored(scores: dict, champ: float | None, champ_kind: str | None, sel: Selection | None
|
||||||
) -> tuple[dict, float | None, str]:
|
) -> tuple[dict, float | None, str]:
|
||||||
"""The baseline as a floor (methods.md B5.2): of the challengers'
|
"""The baseline as a floor (methods.md B5.2): of the challengers'
|
||||||
@@ -207,13 +218,13 @@ def train_series(series: str, t: np.ndarray, y: np.ndarray, w: fcmodels.Weather,
|
|||||||
res.runs.append(Run(series, kind, {}, None, note=f"not trained: {why}"))
|
res.runs.append(Run(series, kind, {}, None, note=f"not trained: {why}"))
|
||||||
continue
|
continue
|
||||||
pred = fcmodels.predict(p, series, t[te], wslice(wt, te), site, hist_t, hist_y)
|
pred = fcmodels.predict(p, series, t[te], wslice(wt, te), site, hist_t, hist_y)
|
||||||
res.runs.append(Run(series, kind, fcmodels.metrics(y[te], pred, fcmodels.level_floor(series)), p))
|
res.runs.append(Run(series, kind, fcmodels.metrics(y[te], pred, floor_for(series, y[tr], sel)), p))
|
||||||
base = next((r for r in res.runs if r.kind == "how" and r.params), None)
|
base = next((r for r in res.runs if r.kind == "how" and r.params), None)
|
||||||
res.baseline = base.metrics if base else None
|
res.baseline = base.metrics if base else None
|
||||||
if champion is not None:
|
if champion is not None:
|
||||||
try:
|
try:
|
||||||
pred = fcmodels.predict(champion, series, t[te], wslice(wt, te), site, hist_t, hist_y)
|
pred = fcmodels.predict(champion, series, t[te], wslice(wt, te), site, hist_t, hist_y)
|
||||||
res.champion = fcmodels.metrics(y[te], pred, fcmodels.level_floor(series))
|
res.champion = fcmodels.metrics(y[te], pred, floor_for(series, y[tr], sel))
|
||||||
except Exception as e: # a champion that can no longer run is replaced
|
except Exception as e: # a champion that can no longer run is replaced
|
||||||
res.champion = None
|
res.champion = None
|
||||||
res.note = f"the model in force could not be scored ({e}): replaced"
|
res.note = f"the model in force could not be scored ({e}): replaced"
|
||||||
@@ -273,12 +284,13 @@ def score_params(params: dict, series: str, t: np.ndarray, y: np.ndarray, w: fcm
|
|||||||
cut = cut_for(t, y, sel, series)[0]
|
cut = cut_for(t, y, sel, series)[0]
|
||||||
wt = w_test if w_test is not None else w
|
wt = w_test if w_test is not None else w
|
||||||
te = slice(cut, len(t))
|
te = slice(cut, len(t))
|
||||||
|
first = int(have[0])
|
||||||
try:
|
try:
|
||||||
pred = fcmodels.predict(params, series, t[te], wslice(wt, te), site, t[:cut], y[:cut])
|
pred = fcmodels.predict(params, series, t[te], wslice(wt, te), site, t[:cut], y[:cut])
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log.warning("benchmark %s: %s", series, e)
|
log.warning("benchmark %s: %s", series, e)
|
||||||
return None
|
return None
|
||||||
return fcmodels.metrics(y[te], pred, fcmodels.level_floor(series))
|
return fcmodels.metrics(y[te], pred, floor_for(series, y[first:cut], sel))
|
||||||
|
|
||||||
|
|
||||||
# ---- the rooms ---------------------------------------------------------------------
|
# ---- the rooms ---------------------------------------------------------------------
|
||||||
|
|||||||
@@ -519,3 +519,50 @@ def test_console_command_sets_an_installers_level(tmp_path):
|
|||||||
assert pr["items"]["room:living"]["in_force"] == "installer"
|
assert pr["items"]["room:living"]["in_force"] == "installer"
|
||||||
assert pr["items"]["room:living"]["levels"]["installer"]["text"] == "daily 22:00-06:00 22"
|
assert pr["items"]["room:living"]["levels"]["installer"]["text"] == "daily 22:00-06:00 22"
|
||||||
assert pr["log"][-1]["by"] == "installer:bob"
|
assert pr["log"][-1]["by"] == "installer:bob"
|
||||||
|
|
||||||
|
|
||||||
|
def test_ha_comfort_select_and_hot_water_times(tmp_path):
|
||||||
|
"""Backlog 521: the home's comfort choice (a select) and a tank's hot-water times (a text), as the
|
||||||
|
owner's changes with applied/refused feedback, through the same path as the other settings."""
|
||||||
|
import copy
|
||||||
|
from test_announce import make
|
||||||
|
from test_control_parts import MAPPING
|
||||||
|
m = copy.deepcopy(MAPPING)
|
||||||
|
m["controls"].append({"id": "tank", "kind": "dhw_tank", "consent": True, "entities": {"switch": "switch.heizstab"}})
|
||||||
|
a, ann = make(tmp_path, m)
|
||||||
|
ctl = a.control
|
||||||
|
ctl.tz = ctl.prefs.tz = "Europe/Berlin"
|
||||||
|
objs = ann.objects()
|
||||||
|
sel = objs[(ann.uid, "select", "pref_comfort")]
|
||||||
|
assert sel["options"] == ["Comfort", "Balanced", "Saving"] and sel["command_topic"].endswith("/pref_comfort/set")
|
||||||
|
assert sel["entity_category"] == "config"
|
||||||
|
assert objs[(ann.uid, "text", "pref_tank_hotwater")]["max"] == 255
|
||||||
|
assert (ann.uid, "sensor", "pref_last_change") in objs
|
||||||
|
|
||||||
|
def send(obj, text):
|
||||||
|
asyncio.run(ann.pref_message(obj, text.encode()))
|
||||||
|
assert ann.prefs_state()["pref_comfort"] == "Balanced" # not set: the default
|
||||||
|
assert ctl.prefs.comfort_mode() is None
|
||||||
|
send("pref_comfort", "Saving")
|
||||||
|
assert ctl.prefs.comfort_mode() == "saving" and ann.prefs_state()["pref_comfort"] == "Saving"
|
||||||
|
assert ctl.prefs.effective("comfort")["by"] == "Home Assistant"
|
||||||
|
assert ann.prefs_result()["last_change"].startswith("applied: comfort")
|
||||||
|
send("pref_comfort", "Wild") # refused: as it was
|
||||||
|
assert ctl.prefs.comfort_mode() == "saving"
|
||||||
|
assert ann.prefs_result()["last_change"].startswith("refused: comfort")
|
||||||
|
assert ann.prefs_state()["pref_tank_hotwater"] == ""
|
||||||
|
send("pref_tank_hotwater", "mo-fr 6-8 55 must; sa,su 7-9 50")
|
||||||
|
assert ctl.prefs.value("tank:tank")["blocks"][0]["how"] == "must"
|
||||||
|
assert ann.prefs_state()["pref_tank_hotwater"] == "Mo-Fr 06:00-08:00 55 must; Sa,Su 07:00-09:00 50"
|
||||||
|
send("pref_tank_hotwater", "daily 06:00-08:00 95") # above the range: refused, as it was
|
||||||
|
assert ann.prefs_result()["last_change"].startswith("refused:")
|
||||||
|
assert ann.prefs_state()["pref_tank_hotwater"].startswith("Mo-Fr 06:00-08:00 55 must")
|
||||||
|
ctl.prefs.write_view(ctl.controls, "shadow") # the panel's view with a tank in it
|
||||||
|
v = json.load(open(ctl.prefs.view_path))
|
||||||
|
assert any(c["kind"] == "dhw_tank" for c in v["controls"]) and v["items"]["comfort"]["in_force"] == "owner"
|
||||||
|
send("pref_tank_hotwater", "")
|
||||||
|
assert ctl.prefs.value("tank:tank") is None
|
||||||
|
a.ha_language = "de"
|
||||||
|
assert ann.prefs_state()["pref_comfort"] == "Sparsam"
|
||||||
|
send("pref_comfort", "Komfort")
|
||||||
|
assert ctl.prefs.comfort_mode() == "comfort"
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||||
|
"""A heat pump's SG Ready from its building's schedule (sgready.py): the
|
||||||
|
command, the mapping (relays or a select), the lock's limits, the grid
|
||||||
|
operator's order, the buffer, the guard and the feedback per command."""
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from cantabile_edge import sgready
|
||||||
|
from cantabile_edge.building import Building
|
||||||
|
from cantabile_edge.consent import Consent
|
||||||
|
from cantabile_edge.controls import parse
|
||||||
|
from cantabile_edge.executor import Executor, actions_for
|
||||||
|
from cantabile_edge.guard import Guard
|
||||||
|
from cantabile_edge.inputs import Collector
|
||||||
|
from test_control_parts import Clock, FakeHA, states
|
||||||
|
|
||||||
|
T0 = 1_800_000_000 # a quarter-hour's start
|
||||||
|
ROWS = {sgready.BLOCK_KEY: 2, sgready.LOCK_DAY_KEY: 6, sgready.RELEASE_KEY: 2}
|
||||||
|
RELAY = {"id": "hp", "kind": "heat_pump_sg", "consent": True,
|
||||||
|
"entities": {"sg_lock": "switch.hp_lock", "sg_boost": "switch.hp_boost", "buffer_temp": "sensor.buffer"},
|
||||||
|
"params": {"min_buffer_c": 30}}
|
||||||
|
SELECT = {"id": "hp", "kind": "heat_pump_sg", "consent": True, "entities": {"sg_ready": "select.hp_sg"},
|
||||||
|
"params": {"sg_options": {"1": "1 blocked", "2": "2 normal", "3": "3 boost", "4": "4 forced"}}}
|
||||||
|
|
||||||
|
|
||||||
|
def ctl(raw):
|
||||||
|
return parse([raw], set())[0]
|
||||||
|
|
||||||
|
|
||||||
|
def cmd(states_, cid="s1", frm=T0, mode="active", level="binding"):
|
||||||
|
return {"v": "1", "id": cid, "building": "house-7", "level": level, "control": "sg_ready", "value": str(states_[0]),
|
||||||
|
"from": str(frm), "until": str(frm + 900 * len(states_)), "why": "the building plan's SG Ready",
|
||||||
|
"schedule": ",".join(map(str, states_)), "step_s": "900", "mode": mode}
|
||||||
|
|
||||||
|
|
||||||
|
def test_mapping_relays_or_select():
|
||||||
|
assert ctl(RELAY).writable() == {"sg_lock": "switch.hp_lock", "sg_boost": "switch.hp_boost"}
|
||||||
|
assert ctl(SELECT).writable() == {"sg_ready": "select.hp_sg"}
|
||||||
|
with pytest.raises(ValueError, match="needs sg_ready or sg_lock or sg_boost"):
|
||||||
|
ctl({**RELAY, "entities": {"power": "sensor.hp_power"}})
|
||||||
|
with pytest.raises(ValueError, match="sg_options"):
|
||||||
|
ctl({**SELECT, "params": {}}) # a select without its options
|
||||||
|
with pytest.raises(ValueError, match="not both"):
|
||||||
|
ctl({**SELECT, "entities": {"sg_ready": "select.hp_sg", "sg_lock": "switch.hp_lock"}})
|
||||||
|
with pytest.raises(ValueError, match="min_buffer_c"):
|
||||||
|
ctl({**RELAY, "params": {"min_buffer_c": "warm"}})
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_command(tmp_path):
|
||||||
|
b = Building(str(tmp_path), Clock(T0))
|
||||||
|
c = b.parse(cmd([3, 3, 1, 2]))
|
||||||
|
assert c["schedule"] == [3, 3, 1, 2] and c["step_s"] == 900
|
||||||
|
with pytest.raises(ValueError, match="state 1, 2, 3 or 4"):
|
||||||
|
b.parse(cmd([3, 5]))
|
||||||
|
with pytest.raises(ValueError, match="active mode"):
|
||||||
|
b.parse(cmd([3], mode="shadow")) # never from a building in shadow
|
||||||
|
with pytest.raises(ValueError, match="never an emergency"):
|
||||||
|
b.parse(cmd([3], level="emergency"))
|
||||||
|
with pytest.raises(ValueError, match="schedule has 2 values"):
|
||||||
|
b.parse({**cmd([3, 3]), "until": str(T0 + 2700)})
|
||||||
|
assert b.take(c, [])[0]
|
||||||
|
assert b.sg_state(T0 + 10) == (3, b.active["sg_ready"])
|
||||||
|
assert b.sg_state(T0 + 1800)[0] == 1
|
||||||
|
assert b.sg_state(T0 + 3600) == (None, None) # over
|
||||||
|
assert "sg_ready" not in b.for_model(T0, 900, 8) # never in the box's own plan
|
||||||
|
|
||||||
|
|
||||||
|
def test_relays_per_state_never_lock_and_boost_on_the_way():
|
||||||
|
c, col = ctl(RELAY), Collector()
|
||||||
|
states(col, switch__hp_lock=("off",), switch__hp_boost=("off",))
|
||||||
|
assert [(a.channel, a.service) for a in actions_for(c, {"set": "sg:1"}, col)] == [("sg_lock", "turn_on")]
|
||||||
|
assert actions_for(c, {"set": "sg:2"}, col) == []
|
||||||
|
assert [(a.channel, a.service) for a in actions_for(c, {"set": "sg:3"}, col)] == [("sg_boost", "turn_on")]
|
||||||
|
assert [(a.channel, a.service) for a in actions_for(c, {"set": "sg:4"}, col)] == [("sg_boost", "turn_on"), ("sg_lock", "turn_on")]
|
||||||
|
states(col, switch__hp_lock=("off",), switch__hp_boost=("on",)) # 3 -> 1: the boost off first
|
||||||
|
assert [(a.channel, a.service) for a in actions_for(c, {"set": "sg:1"}, col)] == [("sg_boost", "turn_off"), ("sg_lock", "turn_on")]
|
||||||
|
assert sgready.read_state(c, col) == 3
|
||||||
|
s = ctl(SELECT)
|
||||||
|
states(col, select__hp_sg=("2 normal",))
|
||||||
|
a = actions_for(s, {"set": "sg:3"}, col)
|
||||||
|
assert [(x.service, x.data) for x in a] == [("select_option", {"option": "3 boost"})]
|
||||||
|
assert sgready.read_state(s, col) == 2
|
||||||
|
# one contact only: what it can say
|
||||||
|
lock_only = ctl({**RELAY, "entities": {"sg_lock": "switch.hp_lock"}})
|
||||||
|
assert sgready.expressible(lock_only, 3)[0] == 2 and sgready.expressible(lock_only, 1)[0] == 1
|
||||||
|
boost_only = ctl({**RELAY, "entities": {"sg_boost": "switch.hp_boost"}})
|
||||||
|
assert sgready.expressible(boost_only, 4)[0] == 3 and sgready.expressible(boost_only, 1)[0] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_lock_limits(tmp_path):
|
||||||
|
c = ctl(RELAY)
|
||||||
|
log = sgready.LockLog(str(tmp_path))
|
||||||
|
decide = lambda t, want=1, rows=ROWS, **kw: sgready.decide(c, want, t, log, rows, buffer_c=kw.get("buf", 45.0), # noqa: E731
|
||||||
|
grid_order=kw.get("order", ""))
|
||||||
|
assert decide(T0) == (1, "SG Ready 1")
|
||||||
|
# a Parameters row missing: no lock, named (never a value of the box's own)
|
||||||
|
got, why = decide(T0, rows={sgready.BLOCK_KEY: 2})
|
||||||
|
assert got == 2 and sgready.LOCK_DAY_KEY in why and sgready.RELEASE_KEY in why
|
||||||
|
# one lock at most 2 h
|
||||||
|
log.note(1, T0)
|
||||||
|
assert decide(T0 + 7199)[0] == 1
|
||||||
|
got, why = decide(T0 + 7200)
|
||||||
|
assert got == 2 and "one lock at most 2 h" in why
|
||||||
|
log.note(2, T0 + 7200)
|
||||||
|
# released at least 2 h between two locks
|
||||||
|
got, why = decide(T0 + 7200 + 3600)
|
||||||
|
assert got == 2 and "released 1.00 h ago" in why
|
||||||
|
assert decide(T0 + 4 * 3600)[0] == 1
|
||||||
|
# at most 6 h in any 24 h: two more locks of 2 h
|
||||||
|
for k in (1, 2):
|
||||||
|
log.note(1, T0 + k * 4 * 3600)
|
||||||
|
log.note(2, T0 + k * 4 * 3600 + 7200)
|
||||||
|
got, why = decide(T0 + 12 * 3600)
|
||||||
|
assert got == 2 and "6.00 h in the last 24 h" in why
|
||||||
|
assert decide(T0 + 24 * 3600 + 1)[0] == 1 # the first lock out of the window
|
||||||
|
assert sgready.LockLog(str(tmp_path)).locked_s(T0 + 12 * 3600) == 6 * 3600 # kept on disk
|
||||||
|
# the buffer: no lock at or below its floor, none while its temperature is unknown
|
||||||
|
assert decide(T0 + 30 * 3600, buf=30.0)[0] == 2
|
||||||
|
assert "unknown" in decide(T0 + 30 * 3600, buf=None)[1]
|
||||||
|
# the grid operator's order: no increased operation
|
||||||
|
got, why = decide(T0, want=4, order="the grid operator's order (§14a EnWG)")
|
||||||
|
assert got == 2 and "§14a" in why
|
||||||
|
assert decide(T0, want=4)[0] == 4
|
||||||
|
assert decide(T0, want=None)[0] == 2 # no command: normal
|
||||||
|
|
||||||
|
|
||||||
|
def run_tick(ex, ha, auto=True):
|
||||||
|
asyncio.run(ex.tick(ha, auto=auto))
|
||||||
|
|
||||||
|
|
||||||
|
def mk(tmp_path, raw, mode="auto", t=T0 + 60):
|
||||||
|
(tmp_path / "consent.json").write_text(json.dumps({"share": True, "control": True}))
|
||||||
|
clk = Clock(t)
|
||||||
|
c = ctl(raw)
|
||||||
|
g = Guard([c], Consent(str(tmp_path)), lambda: mode, clock=clk)
|
||||||
|
col = Collector()
|
||||||
|
sent = []
|
||||||
|
|
||||||
|
async def publish(kind, msg):
|
||||||
|
sent.append((kind, msg))
|
||||||
|
b = Building(str(tmp_path), clk)
|
||||||
|
ex = Executor([c], g, col, publish, clock=clk, building=b)
|
||||||
|
ex.box_params = lambda now: dict(ROWS)
|
||||||
|
return ex, b, col, clk, sent
|
||||||
|
|
||||||
|
|
||||||
|
def test_executor_sets_the_schedule_and_answers(tmp_path):
|
||||||
|
ex, b, col, clk, sent = mk(tmp_path, RELAY)
|
||||||
|
states(col, switch__hp_lock=("off",), switch__hp_boost=("off",), sensor__buffer=("45",))
|
||||||
|
assert b.take(b.parse(cmd([3, 1, 1, 2])), [])[0]
|
||||||
|
ha = FakeHA()
|
||||||
|
run_tick(ex, ha)
|
||||||
|
assert ha.calls == [("switch", "turn_on", "switch.hp_boost", {})]
|
||||||
|
fb = [m for k, m in sent if m.get("service") == "building.sg_ready"]
|
||||||
|
assert fb[-1]["result"] == "done" and fb[-1]["id"] == "s1" and fb[-1]["value"] == 3
|
||||||
|
n = len(fb)
|
||||||
|
run_tick(ex, FakeHA()) # the same: no new answer
|
||||||
|
assert len([m for k, m in sent if m.get("service") == "building.sg_ready"]) == n
|
||||||
|
# the next quarter-hour: 1, the lock (the boost off first)
|
||||||
|
clk.t = T0 + 900 + 60
|
||||||
|
states(col, switch__hp_lock=("off",), switch__hp_boost=("on",), sensor__buffer=("45",))
|
||||||
|
ha = FakeHA()
|
||||||
|
run_tick(ex, ha)
|
||||||
|
assert ha.calls == [("switch", "turn_off", "switch.hp_boost", {}), ("switch", "turn_on", "switch.hp_lock", {})]
|
||||||
|
# the buffer at its floor: no lock, the building told why
|
||||||
|
clk.t = T0 + 1800 + 60
|
||||||
|
states(col, switch__hp_lock=("on",), switch__hp_boost=("off",), sensor__buffer=("29.5",))
|
||||||
|
ha = FakeHA()
|
||||||
|
run_tick(ex, ha)
|
||||||
|
assert ha.calls == [("switch", "turn_off", "switch.hp_lock", {})]
|
||||||
|
last = [m for k, m in sent if m.get("service") == "building.sg_ready"][-1]
|
||||||
|
assert last["result"] == "refused" and "floor 30" in last["why"] and last["value"] == 2
|
||||||
|
# after the command: 2, normal
|
||||||
|
clk.t = T0 + 3600 + 60
|
||||||
|
states(col, switch__hp_lock=("off",), switch__hp_boost=("on",))
|
||||||
|
ha = FakeHA()
|
||||||
|
run_tick(ex, ha)
|
||||||
|
assert ha.calls == [("switch", "turn_off", "switch.hp_boost", {})]
|
||||||
|
# a console command never sets it
|
||||||
|
assert not ex.command({"asset": "hp", "set": "sg:4"}, clk.t)[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_shadow_box_and_no_consent_answer_refused(tmp_path):
|
||||||
|
ex, b, col, clk, sent = mk(tmp_path, SELECT, mode="shadow")
|
||||||
|
states(col, select__hp_sg=("2 normal",))
|
||||||
|
assert b.take(b.parse(cmd([4, 4])), [])[0]
|
||||||
|
ha = FakeHA()
|
||||||
|
run_tick(ex, ha, auto=False)
|
||||||
|
assert ha.calls == []
|
||||||
|
last = [m for k, m in sent if m.get("service") == "building.sg_ready"][-1]
|
||||||
|
assert last["result"] == "refused" and "mode shadow" in last["why"]
|
||||||
|
(tmp_path / "x").mkdir()
|
||||||
|
ex2, b2, col2, _, sent2 = mk(tmp_path / "x", {**SELECT, "consent": False})
|
||||||
|
states(col2, select__hp_sg=("2 normal",))
|
||||||
|
assert b2.take(b2.parse(cmd([3, 3])), [])[0]
|
||||||
|
run_tick(ex2, FakeHA())
|
||||||
|
last = [m for k, m in sent2 if m.get("service") == "building.sg_ready"][-1]
|
||||||
|
assert last["result"] == "refused" and "no consent" in last["why"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_select_lock_cap_from_the_bundle(tmp_path):
|
||||||
|
"""The lock's rows come from the tariff bundle: without them the lock is refused, the rest is set."""
|
||||||
|
ex, b, col, clk, sent = mk(tmp_path, SELECT)
|
||||||
|
ex.box_params = lambda now: {}
|
||||||
|
states(col, select__hp_sg=("2 normal",))
|
||||||
|
assert b.take(b.parse(cmd([1, 3])), [])[0]
|
||||||
|
ha = FakeHA()
|
||||||
|
run_tick(ex, ha)
|
||||||
|
assert ha.calls == []
|
||||||
|
last = [m for k, m in sent if m.get("service") == "building.sg_ready"][-1]
|
||||||
|
assert last["result"] == "refused" and "missing" in last["why"]
|
||||||
|
clk.t += 900
|
||||||
|
run_tick(ex, ha)
|
||||||
|
assert ha.calls == [("select", "select_option", "select.hp_sg", {"option": "3 boost"})]
|
||||||
|
|
||||||
|
|
||||||
|
def controller(tmp_path, controls):
|
||||||
|
import yaml
|
||||||
|
from cantabile_edge.config import Config
|
||||||
|
from cantabile_edge.controller import Controller
|
||||||
|
from cantabile_edge.mapping import Mapping
|
||||||
|
m = tmp_path / "mapping.yaml"
|
||||||
|
m.write_text(yaml.safe_dump({"version": 3, "assets": [], "controls": controls}))
|
||||||
|
t = [T0 + 60]
|
||||||
|
ctl = Controller(Config(site_id="ab" * 16, mapping=str(m), state_dir=str(tmp_path)), Mapping.load(str(m)),
|
||||||
|
Consent(str(tmp_path)), sink=None, clock=lambda: t[0])
|
||||||
|
sent = []
|
||||||
|
|
||||||
|
async def publish(kind, data):
|
||||||
|
sent.append((kind, data))
|
||||||
|
ctl._publish = publish
|
||||||
|
return ctl, sent
|
||||||
|
|
||||||
|
|
||||||
|
def test_controller_takes_releases_and_refuses(tmp_path):
|
||||||
|
(tmp_path / "a").mkdir()
|
||||||
|
ctl, sent = controller(tmp_path / "a", [RELAY])
|
||||||
|
ok, why = asyncio.run(ctl.command("building", cmd([3, 3])))
|
||||||
|
assert ok and ctl.building.active["sg_ready"]["schedule"] == [3, 3]
|
||||||
|
assert sent[-1][1]["service"] == "building.sg_ready" and sent[-1][1]["result"] == "done"
|
||||||
|
assert ctl.received[-1]["result"] == "applied"
|
||||||
|
# the building went back to shadow: the schedule ends here
|
||||||
|
ok, why = asyncio.run(ctl.command("building", {"v": "1", "id": "s2", "building": "house-7", "control": "sg_ready",
|
||||||
|
"mode": "shadow"}))
|
||||||
|
assert ok and "released" in why and "sg_ready" not in ctl.building.active
|
||||||
|
ok, why = asyncio.run(ctl.command("building", cmd([3], mode="")))
|
||||||
|
assert not ok and "active mode" in why
|
||||||
|
# the grid operator's relayed order: no increased operation
|
||||||
|
assert ctl.grid_order_in_force(T0) == ""
|
||||||
|
ctl.building.active["load_limit"] = {"id": "g1", "building": "house-7", "level": "emergency", "control": "load_limit",
|
||||||
|
"value": 4200.0, "from": T0, "until": T0 + 3600}
|
||||||
|
assert "order" in ctl.grid_order_in_force(T0 + 60)
|
||||||
|
# a box without an SG Ready control refuses the command, and says so
|
||||||
|
(tmp_path / "b").mkdir()
|
||||||
|
ctl2, sent2 = controller(tmp_path / "b", [{"id": "car", "kind": "ev", "consent": True, "entities": {"switch": "switch.wb"}}])
|
||||||
|
ok, why = asyncio.run(ctl2.command("building", cmd([3])))
|
||||||
|
assert not ok and "no SG Ready control" in why and sent2[-1][1]["result"] == "refused"
|
||||||
@@ -52,7 +52,7 @@ Each path: `{"path", "fields": [field names], "note", ...}`.
|
|||||||
- **`fallback`**: `true` marks a stand-in (the weather service's `outside.temp`): the agent gives its id to a measured value of the same quantity (an outdoor thermometer's `outside.temp_2` becomes `outside.temp`).
|
- **`fallback`**: `true` marks a stand-in (the weather service's `outside.temp`): the agent gives its id to a measured value of the same quantity (an outdoor thermometer's `outside.temp_2` becomes `outside.temp`).
|
||||||
- **inputs** (a setup path, the HA paths): `{"weather" | "outside_temp": matcher}`, the agent's mapping inputs the device gives (`ha-weather`: `inputs.weather`, its hourly forecast). One weather service plans: a second one's is kept unused until the owner picks it (`devices weather ID`).
|
- **inputs** (a setup path, the HA paths): `{"weather" | "outside_temp": matcher}`, the agent's mapping inputs the device gives (`ha-weather`: `inputs.weather`, its hourly forecast). One weather service plans: a second one's is kept unused until the owner picks it (`devices weather ID`).
|
||||||
- **Assumed state:** a device without feedback (HA's `assumed_state`, or a climate without `hvac_action`: ESPHome's infrared climates, `climate_ir`: coolix, daikin, mitsubishi, heatpumpir, ...) shows what HA last sent it. A value found by a matcher with `"assumed": true` is marked `assumed` in the agent's mapping: read and sent like any other, listed as assumed in the inventory and on the panel ("Assumed, not measured"), and never feedback. The thermostat profile reads such a device's heating and cooling state from its mode (`equals` `heat` / `cool`), never from `hvac_action`.
|
- **Assumed state:** a device without feedback (HA's `assumed_state`, or a climate without `hvac_action`: ESPHome's infrared climates, `climate_ir`: coolix, daikin, mitsubishi, heatpumpir, ...) shows what HA last sent it. A value found by a matcher with `"assumed": true` is marked `assumed` in the agent's mapping: read and sent like any other, listed as assumed in the inventory and on the panel ("Assumed, not measured"), and never feedback. The thermostat profile reads such a device's heating and cooling state from its mode (`equals` `heat` / `cool`), never from `hvac_action`.
|
||||||
- **controls**: `[{"kind": "battery|heating|cooling|ev|cover|dhw_tank", "entities": {role: matcher}, "params": {...}, "safe": {...}}]`, the roles and params of the agent's mapping v3 (`edge/cantabile_edge/controls.py`; `dhw_tank`: docs/design/storage-losses.md 10.1). A control's entity matcher (the HA paths) may say **`"optional": true`**: a role the control has where the device has it (a tank's bottom sensor, its heater's power, a battery's own `standby` report), left out without a word where it has not; every other role must be found, else the control is reported missing; at least one role is not optional. The roles that write (one writer per entity, below): `charge_from_grid`, `setpoint`, `mode`, `climate`, `switch`, `current`, `cover`, `water_heater`, `sg_ready`, and a tank's `power` (a stepless heater's W; a battery's or a car's `power` is a reading). One control per entity: a later control that would write an entity an earlier one writes is left out, with one exception: a heating and a cooling control on one climate (a thermostat that heats and cools) are both mapped as a pair with `"switchover": {"mode": "season"}`, and the agent uses only one of them at a time (`edge/cantabile_edge/switchover.py`). The owner chooses on the Devices page (`devices switchover ID`): **Heating**, **Cooling**, **By season** (the default: heating October to April, cooling May to September, the site's local month) or **By outdoor temperature** (`heat_below_c`, `cool_above_c`: heating below the first, cooling above the second, and between them the side it was on, so a mild day does not flip it; the outdoor temperature is the mapping's `inputs.outside_temp`, else its `outside.temp`; without a reading it stays, and by season when it never had a side). The inactive control is not planned, never acts (the guard refuses it), and a command to it is refused; protection is per control, as before. A control whose matcher's `supports` the device lacks is left out, not reported missing. A climate control's setpoint stays inside the thermostat's own `min_temp`..`max_temp` (with the kind's range) and is rounded to its `target_temp_step` by the agent.
|
- **controls**: `[{"kind": "battery|heating|cooling|ev|cover|dhw_tank|heat_pump_sg", "entities": {role: matcher}, "params": {...}, "safe": {...}}]`, the roles and params of the agent's mapping v3 (`edge/cantabile_edge/controls.py`; `dhw_tank`: docs/design/storage-losses.md 10.1; `heat_pump_sg`: a heat pump's SG Ready input set from its building's schedule, its two relay contacts `sg_lock`, `sg_boost` or its select `sg_ready`, docs/methods.md A9.5). A control's entity matcher (the HA paths) may say **`"optional": true`**: a role the control has where the device has it (a tank's bottom sensor, its heater's power, a battery's own `standby` report), left out without a word where it has not; every other role must be found, else the control is reported missing; at least one role is not optional. The roles that write (one writer per entity, below): `charge_from_grid`, `setpoint`, `mode`, `climate`, `switch`, `current`, `cover`, `water_heater`, `sg_ready`, a heat pump's SG Ready contacts `sg_lock` and `sg_boost`, and a tank's `power` (a stepless heater's W; a battery's or a car's `power` is a reading). One control per entity: a later control that would write an entity an earlier one writes is left out, with one exception: a heating and a cooling control on one climate (a thermostat that heats and cools) are both mapped as a pair with `"switchover": {"mode": "season"}`, and the agent uses only one of them at a time (`edge/cantabile_edge/switchover.py`). The owner chooses on the Devices page (`devices switchover ID`): **Heating**, **Cooling**, **By season** (the default: heating October to April, cooling May to September, the site's local month) or **By outdoor temperature** (`heat_below_c`, `cool_above_c`: heating below the first, cooling above the second, and between them the side it was on, so a mild day does not flip it; the outdoor temperature is the mapping's `inputs.outside_temp`, else its `outside.temp`; without a reading it stays, and by season when it never had a side). The inactive control is not planned, never acts (the guard refuses it), and a command to it is refused; protection is per control, as before. A control whose matcher's `supports` the device lacks is left out, not reported missing. A climate control's setpoint stays inside the thermostat's own `min_temp`..`max_temp` (with the kind's range) and is rounded to its `target_temp_step` by the agent.
|
||||||
|
|
||||||
### Shades, temperature sensors, weather (the generic profiles)
|
### Shades, temperature sensors, weather (the generic profiles)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user