194 lines
8.9 KiB
Python
194 lines
8.9 KiB
Python
# 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 ""))
|