Files
cantabile-ha-addons/src/edge/cantabile_edge/steady.py
T

273 lines
12 KiB
Python

# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""A steady plan: no command for a change that does not matter (sim-munich-1
in auto, 2026-11-03: a battery set 4.7 times an hour in steps of 50-150 W,
its mode switched 2.9 times an hour, a heat pump's setpoint 20.5 and back to
20.0 every quarter hour).
The optimiser's plan is exact to the watt and the tenth of a kelvin; every
small difference became a command. Here, after the solve (controller.py
make_plan), each control's plan entries are walked in time order from what
the device is set to now, and a change is kept out of the plan (the entry
keeps the value in force, its why says so) unless all hold:
deadband it changes enough: a battery's power by max(300 W, 10 % of its
max), a setpoint by 0.5 K, an EV's current by 2 A (any change
of on/off or mode counts: a battery's self-consumption is no
power of its own, it follows the house)
lasts a temperature: the plan keeps the new value for 30 minutes
(a one-step blip is no command)
hold the control's last change of the same kind is older than its
hold: a mode (a battery's manual/self-consumption, a climate's
off/heat, an EV's on/off) params.hold_mode_s (30 min), a
setpoint params.hold_set_s (15 min); the first from the agent's
last command (the guard's record), later ones from the plan
gain a battery's setpoint: the energy the change moves over its
hold, valued at the most a kWh can be worth moved in the
horizon (its dearest import price less the lower of its
cheapest import and feed-in price), at least
params.min_gain_ct (1 ct): an upper bound, so only changes that
cannot be worth a cent are kept
Not here, so never held back: the console's and the building's commands,
the safe defaults, the grid operator's order (the plan is made again at
once within its bounds; a kept value outside the bounds in force is never
kept), the owner's own changes (the guard's hands off; and the owner's
preferences, preferences.py: the first plan after a change of a control's
preferences or overrides, `free`, is taken as it is for that control) and
the guard's floors. The entry the plan made is kept in the entry as
"planned".
"""
import math
MIN_BATTERY_W = 300.0
BATTERY_SHARE = 0.10
TEMP_K = 0.5
EV_A = 2.0
LASTS_S = 1800.0
SAME_K = 0.25
AUTO = "auto" # a battery in its own self-consumption mode (a plan entry's "auto")
def _num(v):
try:
x = float(v)
except (TypeError, ValueError):
return None
return x if math.isfinite(x) else None
def current(c, col):
"""What the device is set to now, in a plan entry's terms (None:
unknown, the plan is followed as it is)."""
e = c.entities
if c.kind == "battery":
if "setpoint" not in e:
return None
if "mode" in e and col.state(e["mode"]) == str(c.p("auto_option")):
return AUTO
return _num(col.state(e["setpoint"]))
if c.kind in ("heating", "cooling"):
if "climate" in e:
if col.state(e["climate"]) in ("off", None):
return "off" if col.state(e["climate"]) == "off" else None
return _num(col.attr(e["climate"], "temperature"))
if "switch" in e:
s = col.state(e["switch"])
return s if s in ("on", "off") else None
return None
if c.kind == "ev":
if col.state(e.get("switch", "")) == "off":
return "off"
return _num(col.state(e["current"])) if "current" in e else None
return None
def _val(c, e):
"""A plan entry's value: its set, or a battery's AUTO."""
return AUTO if c.kind == "battery" and e.get("auto") else e["set"]
def _big(c, old, new) -> bool:
if c.kind == "battery":
f, _, _ = c.battery_facts()
top = max(f.get("max_charge_w") or 0.0, f.get("max_discharge_w") or 0.0)
return abs(new - old) >= max(MIN_BATTERY_W, BATTERY_SHARE * top) - 1e-9
if c.kind in ("heating", "cooling"):
return abs(new - old) >= TEMP_K - 1e-9
if c.kind == "ev":
return abs(new - old) >= EV_A - 1e-9
return True
def _same(a, b) -> bool:
if isinstance(a, str) or isinstance(b, str):
return a == b
return abs(a - b) < SAME_K
def _lasts(c, entries, i, end) -> float:
"""How long the plan keeps entry i's value (s)."""
v = _val(c, entries[i])
for e in entries[i + 1:]:
if not _same(_val(c, e), v):
return e["t"] - entries[i]["t"]
return end - entries[i]["t"]
def _within(bounds, v) -> bool:
if not bounds or isinstance(v, str):
return True
lo, hi = bounds[0], bounds[1]
return (lo is None or v >= lo - 1e-9) and (hi is None or v <= hi + 1e-9)
def stabilise(plan: dict, state: dict, controls, col, last_set=None, now: float | None = None,
free: set | None = None) -> dict:
"""The plan with changes that do not matter kept out (module
docstring). last_set(control id, kind "mode"|"set") -> when the agent
last changed that (None: not known). free: control ids (or "*": all)
whose preferences the owner just changed: their entries as planned.
In place; returns the plan."""
now = plan.get("made", 0) if now is None else now
step = plan.get("step_s", 900)
end = plan.get("start", now) + step * plan.get("steps", state.get("steps", 192))
# the prices the plan had (none without a tariff: no gain to weigh then)
prices = [x for x in state.get("price_import") or [] if x is not None]
feed = [x for x in state.get("price_export") or [] if x is not None]
spread = (max(prices) - min(prices + feed)) if prices else 0.0 # ct per kWh, at most
devs = {d["id"]: d for d in state.get("devices") or []}
kept_n = 0
for c in controls:
entries = (plan.get("devices") or {}).get(c.id)
if not entries or c.kind not in ("battery", "heating", "cooling", "ev"):
continue
if free and (c.id in free or "*" in free):
continue # the owner's change: not held back
cur = current(c, col)
if cur is None:
continue
p = devs.get(c.id, {}).get("params") or {}
hold = {"mode": float(p.get("hold_mode_s", c.p("hold_mode_s"))),
"set": float(p.get("hold_set_s", c.p("hold_set_s")))}
min_gain = float(p.get("min_gain_ct", c.p("min_gain_ct")))
bq = {"battery": "power_w", "heating": "temp_c", "cooling": "temp_c", "ev": "current_a"}[c.kind]
bounds = (devs.get(c.id, {}).get("bounds") or {}).get(bq)
changed = {}
for k in ("mode", "set"):
t = last_set(c.id, k) if last_set else None
changed[k] = t if t is not None else -1e18
raw = [dict(e) for e in entries]
out = []
for i, e in enumerate(raw):
new = _val(c, e)
if new == "release":
out.append(e) # nothing written (a room's fallback: its own setpoint)
continue
if _same(cur, new):
kind = None
elif isinstance(cur, str) or isinstance(new, str):
kind = "mode" # on/off, a climate's off, a battery's auto
else:
kind = "set"
if kind is None:
out.append(e)
continue
if kind == "mode" and c.kind in ("heating", "cooling") and "climate" not in c.entities:
kind = "set" # a boiler's on/off is its setpoint
t = max(e["t"], now)
why = ""
if not _within(bounds, cur):
why = "" # what is set now is outside the bounds: change
elif kind == "set" and not isinstance(new, str) and not _big(c, cur, new):
why = f"kept: a change of {_amount(c, cur, new)} is below the deadband"
elif c.kind in ("heating", "cooling") and _lasts(c, raw, i, end) < LASTS_S:
why = f"kept: the plan holds {new:g} for less than {LASTS_S / 60:.0f} min" if not isinstance(new, str) \
else f"kept: the plan is {new} for less than {LASTS_S / 60:.0f} min"
elif t - changed[kind] < hold[kind]:
why = f"kept: changed {int((t - changed[kind]) // 60)} min ago (hold {hold[kind] / 60:.0f} min)"
elif c.kind == "battery" and kind == "set" and prices:
gain = abs(new - cur) * hold["set"] / 3600 / 1000 * spread
if gain < min_gain:
why = f"kept: gain below {min_gain:g} ct ({gain:.2f} ct)"
if why:
kept_n += 1
ke = {"t": e["t"], "set": cur, "why": why, "planned": e["set"]}
if c.kind == "battery":
ke["grid"] = bool(out[-1].get("grid")) if out and "grid" in out[-1] else cur != AUTO and cur > 0
if cur == AUTO:
ke.update(set=e["set"], auto=True)
out.append(ke)
continue
out.append(e)
cur = new
changed[kind] = t
if kind == "mode" and c.kind != "battery":
changed["set"] = t
_hold_source(c, out, col, hold["mode"], last_set, now)
# a plan lists changes only
merged = []
for e in out:
if merged and _same(_val(c, merged[-1]), _val(c, e)) and \
(merged[-1].get("grid") == e.get("grid") or _val(c, e) == AUTO) and \
merged[-1].get("source") == e.get("source"):
continue
merged.append(e)
plan["devices"][c.id] = merged
plan["kept"] = kept_n
return plan
def _hold_source(c, entries, col, hold_s, last_set, now):
"""A hybrid's heat source (a plan entry's "source") changes only after
the hold of a mode (params.hold_mode_s) since its last change: from the
agent's last command (the guard's record, kind "source"), then from the
plan's own changes. A held entry keeps the source in force, its why
says so. In place."""
if c.kind != "heating" or "source" not in c.entities:
return
opts = {str(v): k for k, v in (c.p("source_options") or {}).items()}
cur = opts.get(str(col.state(c.entities["source"])))
t_last = last_set(c.id, "source") if last_set else None
t_last = t_last if t_last is not None else -1e18
for e in entries:
new = e.get("source")
if new is None or new == cur:
continue
t = max(e["t"], now)
if cur is not None and t - t_last < hold_s:
e["planned_source"], e["source"] = new, cur
e["why"] = (e.get("why", "") + "; " if e.get("why") else "") + \
f"source kept: changed {int((t - t_last) // 60)} min ago (hold {hold_s / 60:.0f} min)"
continue
cur, t_last = new, t
def _amount(c, a, b) -> str:
unit = {"battery": "W", "heating": "K", "cooling": "K", "ev": "A"}[c.kind]
d = abs(b - a)
return f"{d:.0f} {unit}" if unit == "W" else f"{d:.1f} {unit}"
def carry_quarter(plan: dict, old: dict | None, now: float) -> dict:
"""A plan made in the middle of a quarter hour for no urgent reason (a
tariff or model bundle came): the quarter under way keeps the values of
the plan in force; the new plan decides from the next quarter on. Each
plan reckons the quarter from its own start with the room as it is when
it is made, and two plans in one quarter set a heat pump to 20.5 and
back to 20.0 (sim-munich-1). In place; returns the plan."""
if not old or old.get("start") != plan.get("start"):
return plan
nxt = plan["start"] + plan["step_s"]
for cid, entries in (plan.get("devices") or {}).items():
prev = [e for e in (old.get("devices") or {}).get(cid) or [] if e["t"] <= now]
if not prev or not entries:
continue
keep = dict(prev[-1], t=plan["start"])
rest = [e for e in entries if e["t"] >= nxt]
if not rest or rest[0]["t"] > nxt:
at = [e for e in entries if e["t"] < nxt]
if at:
rest.insert(0, dict(at[-1], t=nxt)) # the new plan's value from the next quarter
plan["devices"][cid] = [keep] + rest
return plan