cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.400: full source
This commit is contained in:
1 parent
343331d234
commit
d5fbcacaa4
176 files changed
+32511
-19
No files matched your search
@@ -0,0 +1,309 @@
|
||||
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
|
||||
"""Inputs for the optimiser: the latest states of the controls' and the
|
||||
inputs' entities (presence, temperatures, humidity, outside temperature,
|
||||
sun, weather), a short local history of load and PV (the fallback when no
|
||||
model bundle says), and the 15-minute model state for the horizon.
|
||||
|
||||
None of this leaves the site; only the plan does (controller.py).
|
||||
|
||||
Placeholders (quality is not a goal yet):
|
||||
- occupancy beyond the next hour: the presence now for one hour, then
|
||||
06:00-22:00 local as "occupied" (a learned schedule comes later);
|
||||
- sun: the PV forecast scaled to its peak, else the sun's elevation.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
STEP_S = 900
|
||||
STEPS = 192 # 48 h
|
||||
HISTORY_S = 3 * 86400
|
||||
|
||||
|
||||
def number(v) -> float | None:
|
||||
try:
|
||||
x = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return x if x == x and abs(x) != math.inf else None
|
||||
|
||||
|
||||
class Collector:
|
||||
"""States of the entities the agent watches, in HA's compact
|
||||
subscribe_entities form. Observers (the guard) see every change."""
|
||||
|
||||
def __init__(self):
|
||||
self.states: dict[str, dict] = {}
|
||||
self.observers = []
|
||||
|
||||
def on_entities(self, ev: dict, now: float | None = None):
|
||||
now = time.time() if now is None else now
|
||||
for eid, s in (ev.get("a") or {}).items():
|
||||
self.states[eid] = {"s": s.get("s"), "a": dict(s.get("a") or {}), "t": s.get("lc") or now}
|
||||
for eid, c in (ev.get("c") or {}).items():
|
||||
cur = self.states.setdefault(eid, {"s": None, "a": {}, "t": now})
|
||||
plus, minus = c.get("+") or {}, c.get("-") or {}
|
||||
if "s" in plus:
|
||||
cur["s"] = plus["s"]
|
||||
cur["a"].update(plus.get("a") or {})
|
||||
for k in minus.get("a") or []:
|
||||
cur["a"].pop(k, None)
|
||||
cur["t"] = plus.get("lc") or plus.get("lu") or now
|
||||
for obs in self.observers:
|
||||
obs(eid, cur, now)
|
||||
|
||||
def state(self, eid: str):
|
||||
return (self.states.get(eid) or {}).get("s")
|
||||
|
||||
def attr(self, eid: str, name: str):
|
||||
return ((self.states.get(eid) or {}).get("a") or {}).get(name)
|
||||
|
||||
def value(self, eid: str) -> float | None:
|
||||
return number(self.state(eid)) if eid else None
|
||||
|
||||
def total(self, eids: str | list) -> float | None:
|
||||
"""One entity's value, or the sum of several (parts: pv.1.power, ...);
|
||||
None while any of them has none."""
|
||||
if isinstance(eids, str):
|
||||
return self.value(eids)
|
||||
vals = [self.value(e) for e in eids or []]
|
||||
return None if not vals or None in vals else sum(vals)
|
||||
|
||||
def age(self, eid: str, now: float) -> float:
|
||||
st = self.states.get(eid)
|
||||
return now - float(st["t"]) if st and st.get("t") else math.inf
|
||||
|
||||
|
||||
class History:
|
||||
"""Quarter-hour means of load and PV (W) for the last 3 days, kept on
|
||||
disk, for "the same quarter hour yesterday"."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self.path = path
|
||||
self.slots: dict[str, dict[int, list[float]]] = {"load_w": {}, "pv_w": {}}
|
||||
try:
|
||||
with open(path) as f:
|
||||
raw = json.load(f)
|
||||
self.slots = {k: {int(t): v for t, v in raw.get(k, {}).items()} for k in self.slots}
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
def add(self, name: str, value: float | None, now: float):
|
||||
if value is None:
|
||||
return
|
||||
slot = int(now // STEP_S * STEP_S)
|
||||
s, n = self.slots[name].get(slot, [0.0, 0])
|
||||
self.slots[name][slot] = [s + value, n + 1]
|
||||
|
||||
def mean(self, name: str, slot: int) -> float | None:
|
||||
s = self.slots[name].get(slot)
|
||||
return s[0] / s[1] if s and s[1] else None
|
||||
|
||||
def save(self, now: float):
|
||||
cut = now - HISTORY_S
|
||||
for k in self.slots:
|
||||
self.slots[k] = {t: v for t, v in self.slots[k].items() if t >= cut}
|
||||
tmp = self.path + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(self.slots, f)
|
||||
os.replace(tmp, self.path)
|
||||
|
||||
|
||||
def _hourly(forecast: list[dict], key: str, start: int, steps: int) -> list[float] | None:
|
||||
"""A weather forecast's hourly value, held for each quarter hour."""
|
||||
pts = []
|
||||
for f in forecast or []:
|
||||
v = number(f.get(key))
|
||||
try:
|
||||
ts = datetime.fromisoformat(str(f["datetime"]).replace("Z", "+00:00")).timestamp()
|
||||
except (KeyError, ValueError):
|
||||
continue
|
||||
if v is not None:
|
||||
pts.append((ts, v))
|
||||
if not pts:
|
||||
return None
|
||||
pts.sort()
|
||||
out, j = [], 0
|
||||
for k in range(steps):
|
||||
t = start + k * STEP_S
|
||||
while j + 1 < len(pts) and pts[j + 1][0] <= t:
|
||||
j += 1
|
||||
out.append(pts[j][1])
|
||||
return out
|
||||
|
||||
|
||||
def _series(name, start, bundles, history, tz, now_value, default):
|
||||
s = bundles.forecast(name, start, STEP_S, STEPS, tz) if bundles else None
|
||||
if s is not None:
|
||||
return s, "model"
|
||||
out, have = [], 0
|
||||
for k in range(STEPS):
|
||||
t = start + k * STEP_S
|
||||
v = None
|
||||
for back in (86400, 2 * 86400): # the same quarter hour yesterday (or the day before)
|
||||
v = history.mean(name, t - back) if history else None
|
||||
if v is not None:
|
||||
break
|
||||
have += v is not None
|
||||
out.append(v if v is not None else (now_value if now_value is not None else default))
|
||||
return out, ("history" if have else ("now" if now_value is not None else "default"))
|
||||
|
||||
|
||||
def _hhmm(v: str, device_class) -> str | None:
|
||||
"""A departure as HH:MM: from "07:00(:00)" or a timestamp (local time
|
||||
of the timestamp as given)."""
|
||||
v = str(v)
|
||||
if len(v) in (5, 8) and v[2] == ":":
|
||||
return v[:5]
|
||||
try:
|
||||
d = datetime.fromisoformat(v.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
return d.strftime("%H:%M")
|
||||
|
||||
|
||||
def device_state(c, col: Collector, now: float) -> dict:
|
||||
"""What the optimiser needs to know about a control now."""
|
||||
e = c.entities
|
||||
st = {}
|
||||
if c.kind == "battery":
|
||||
soc = col.value(e.get("soc", ""))
|
||||
st["soc_pct"] = soc if soc is not None else float(c.p("soc_pct"))
|
||||
st["soc_estimated"] = soc is None
|
||||
st["charge_from_grid"] = col.state(e.get("charge_from_grid", "")) == "on"
|
||||
elif c.kind in ("heating", "cooling"):
|
||||
t = col.value(e.get("temp", ""))
|
||||
if t is None and e.get("climate"):
|
||||
t = number(col.attr(e["climate"], "current_temperature"))
|
||||
st["temp_c"] = t
|
||||
if e.get("climate"):
|
||||
st["target_c"] = number(col.attr(e["climate"], "temperature"))
|
||||
st["hvac"] = col.state(e["climate"])
|
||||
else:
|
||||
st["on"] = col.state(e.get("switch", "")) == "on"
|
||||
elif c.kind == "ev":
|
||||
conn = e.get("connected")
|
||||
st["connected"] = col.state(conn) == "on" if conn else True
|
||||
st["on"] = col.state(e.get("switch", "")) == "on"
|
||||
st["current_a"] = col.value(e.get("current", ""))
|
||||
st["soc_pct"] = col.value(e.get("soc", ""))
|
||||
need = col.value(e.get("energy_needed", ""))
|
||||
if need is not None:
|
||||
unit = col.attr(e["energy_needed"], "unit_of_measurement")
|
||||
st["need_wh"] = need * 1000.0 if unit == "kWh" else need
|
||||
dep = col.state(e.get("departure", "")) if e.get("departure") else None
|
||||
if dep:
|
||||
st["departure"] = _hhmm(dep, col.attr(e["departure"], "device_class"))
|
||||
elif c.kind == "cover":
|
||||
st["position_pct"] = cover_position(col, e["cover"])
|
||||
st["set_position"] = cover_positions(col, e["cover"])
|
||||
return st
|
||||
|
||||
|
||||
SET_POSITION = 4 # HA's CoverEntityFeature.SET_POSITION
|
||||
|
||||
|
||||
def cover_positions(col: Collector, ent: str) -> bool:
|
||||
"""Can the cover be set to a position (else only opened and closed)?
|
||||
True while HA has not said (the guard and the executor check again)."""
|
||||
f = number(col.attr(ent, "supported_features"))
|
||||
return True if f is None else bool(int(f) & SET_POSITION)
|
||||
|
||||
|
||||
def cover_position(col: Collector, ent: str) -> float | None:
|
||||
"""A cover's position (0 closed, 100 open): its current_position, else
|
||||
from its state (open 100, closed 0) for one that has no position."""
|
||||
v = number(col.attr(ent, "current_position"))
|
||||
if v is not None:
|
||||
return v
|
||||
return {"open": 100.0, "closed": 0.0}.get(col.state(ent))
|
||||
|
||||
|
||||
def model_state(now: float, controls, inputs, col: Collector, bundles, history, tz: str,
|
||||
weather_forecast: list[dict] | None, extra_limits: dict | None = None,
|
||||
occupied_hours=(6, 22), building: dict | None = None, location: dict | None = None,
|
||||
shade_ctx: dict | None = None, grid_order: dict | None = None) -> dict:
|
||||
"""The 48 h, 15-minute input for the optimiser (JSON: it runs in a
|
||||
subprocess). location: the site's latitude and longitude (HA's
|
||||
configuration); shade_ctx: per cover control its room (temp_c,
|
||||
setpoint_c, season: shades.py)."""
|
||||
start = int(now // STEP_S * STEP_S)
|
||||
zone = ZoneInfo(tz or "UTC")
|
||||
prices = bundles.prices(start, STEP_S, STEPS, now)
|
||||
load, load_src = _series("load_w", start, bundles, history, tz, col.total(inputs.load_power), 500.0)
|
||||
pv, pv_src = _series("pv_w", start, bundles, history, tz, None, 0.0)
|
||||
t_out = _hourly(weather_forecast or [], "temperature", start, STEPS)
|
||||
t_src = "weather forecast"
|
||||
measured = col.value(inputs.outside_temp) if inputs.outside_temp else None
|
||||
if t_out is not None and measured is not None:
|
||||
# a thermometer outside says better than the forecast what it is
|
||||
# now: the forecast moved by the difference, fading over 6 hours
|
||||
bias = measured - t_out[0]
|
||||
t_out = [v + bias * max(0.0, 1 - k / 24) for k, v in enumerate(t_out)]
|
||||
t_src = "weather forecast, from the outdoor sensor now"
|
||||
if t_out is None:
|
||||
now_out = col.value(inputs.outside_temp)
|
||||
if now_out is None and inputs.weather:
|
||||
now_out = number(col.attr(inputs.weather, "temperature"))
|
||||
t_out, t_src = [now_out if now_out is not None else 10.0] * STEPS, ("now" if now_out is not None else "default")
|
||||
peak = max(pv) if pv else 0.0
|
||||
if peak > 100:
|
||||
sun = [max(0.0, p / peak) for p in pv]
|
||||
else:
|
||||
# the sun's elevation now, held: a placeholder until a forecast says
|
||||
elev = number(col.attr(inputs.sun, "elevation")) if inputs.sun else None
|
||||
sun = [max(0.0, math.sin(math.radians(elev))) if elev is not None else 0.0] * STEPS
|
||||
present = None
|
||||
if inputs.presence:
|
||||
vals = [col.state(p) for p in inputs.presence]
|
||||
present = any(v in ("on", "home") for v in vals) if any(v is not None for v in vals) else None
|
||||
occupied = []
|
||||
for k in range(STEPS):
|
||||
if k < 4 and present is not None:
|
||||
occupied.append(1 if present else 0)
|
||||
continue
|
||||
h = datetime.fromtimestamp(start + k * STEP_S, timezone.utc).astimezone(zone).hour
|
||||
occupied.append(1 if occupied_hours[0] <= h < occupied_hours[1] else 0)
|
||||
devices = []
|
||||
for c in controls:
|
||||
if hasattr(c, "learn_range"):
|
||||
c.learn_range(col) # a climate's own min_temp..max_temp
|
||||
bounds = {}
|
||||
for q in _quantities(c):
|
||||
b = c.bounds(q, (extra_limits or {}).get(c.id))
|
||||
bounds[q] = [b.lo, b.hi, b.lo_by, b.hi_by]
|
||||
devices.append({"id": c.id, "kind": c.kind, "params": {k: c.p(k) for k in _param_names(c)},
|
||||
"state": device_state(c, col, now), "bounds": bounds,
|
||||
"channels": sorted(c.writable())})
|
||||
clouds = _hourly(weather_forecast or [], "cloud_coverage", start, STEPS)
|
||||
sky = [max(0.0, min(1.0, 1 - c / 100.0)) for c in clouds] if clouds else [1.0] * STEPS
|
||||
out = {"v": 1, "start": start, "step_s": STEP_S, "steps": STEPS, "tz": tz,
|
||||
"price_import": prices.import_ct, "price_export": prices.export_ct, "price_note": prices.note,
|
||||
"load_w": load, "pv_w": pv, "t_out": t_out, "sun": sun, "occupied": occupied, "sky": sky,
|
||||
"location": location or {},
|
||||
"sources": {"load": load_src, "pv": pv_src, "t_out": t_src, "model": bundles.model_id(),
|
||||
"sky": "weather forecast" if clouds else "clear"},
|
||||
"devices": devices, "building": building or {}, "grid_order": grid_order or {}}
|
||||
# a shade's moves by rules on the sun and its room (shades.py); the
|
||||
# optimiser takes them as they are
|
||||
from . import shades
|
||||
for d in devices:
|
||||
if d["kind"] == "cover":
|
||||
d["schedule"] = shades.schedule(d, out, (shade_ctx or {}).get(d["id"]))
|
||||
return out
|
||||
|
||||
|
||||
def _quantities(c) -> list[str]:
|
||||
return {"battery": ["soc_pct", "power_w"], "heating": ["temp_c"], "cooling": ["temp_c"],
|
||||
"ev": ["current_a"], "cover": ["position_pct"]}[c.kind]
|
||||
|
||||
|
||||
def _param_names(c) -> list[str]:
|
||||
from .controls import PARAMS
|
||||
return list(PARAMS[c.kind])
|
||||
Reference in new issue
Block a user