cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1289: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-08 16:35:35 +02:00
1 parent 165dda4479
commit 05802d6f87
57 files changed
+5928 -232

No files matched your search

+79 -5
View File
@@ -55,6 +55,8 @@ from .guard import Guard
from .policy import Policy
from .preferences import Preferences
from .switchover import Switchover
from . import storefit as storefit_mod
from .storefit import StoreFit
from .inputs import Collector, History
from . import localml
@@ -113,6 +115,8 @@ class Controller:
self.saved_limits = self._load_limits() # the console's (limits.json)
self.gridorders = GridOrders(cfg.state_dir, clock) # the grid operator's, from the EEBUS bridge (3q)
self.evphases = EvPhases(cfg.state_dir) # each charger's phase count and its source
# what the box learns of its stores: a battery's idle loss, a tank's draw, UA, legionella (storefit.py)
self.storefit = StoreFit(os.path.join(cfg.state_dir, "storefit.json"), clock)
self.guard.extra_limits = self.saved_limits
self.policy = Policy(cfg.state_dir, cfg.site_id, clock)
self.guard.policy = self.policy
@@ -174,8 +178,19 @@ class Controller:
t_out = self.col.value(ent) if ent else None
return self.switchover.update(self.controls, self.clock(), self.tz, t_out)
def presence_entities(self) -> list[str]:
"""The presence sources (methods.md A1, B16): the inputs' presence
and the mapped presence assets (room.<r>.occupied, person.<slug>.home:
inputs.presence_asset), each once."""
out = list(getattr(self.inputs, "presence", None) or [])
for a in getattr(self.mapping, "assets", None) or []:
if inputs_mod.presence_asset(getattr(a, "asset", "")) and a.entity not in out:
out.append(a.entity)
return out
def entities(self) -> list[str]:
out = set(self.inputs.entities())
out.update(self.presence_entities())
if self.outside_entity() and any(c.switchover or c.kind == "cover" for c in self.controls):
out.add(self.outside_entity())
for c in self.controls:
@@ -277,7 +292,7 @@ class Controller:
metered (inputs.controlled_power), as the planner uses it."""
if not (getattr(self.inputs, "controlled_power", None) or []):
return set()
return {c.kind for c in self.controls if c.kind in ("heating", "cooling", "ev")}
return {c.kind for c in self.controls if c.kind in ("heating", "cooling", "ev", "dhw_tank")}
# -- plans ---------------------------------------------------------------
def owner_ratings(self):
@@ -313,7 +328,8 @@ class Controller:
location=self.location, shade_ctx=self.shade_ctx(),
grid_order=self.gridorders.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS),
grid_max_w=getattr(self.cfg, "grid_max_w", None),
ev_phases=self.ev_phases())
ev_phases=self.ev_phases(), presence=self.presence_entities(),
storefit=self.storefit)
# the owner's preferences per step (preferences.py)
return self.prefs.apply(state, {c.id: c for c in controls}, self.col, now)
@@ -379,14 +395,21 @@ class Controller:
"priced": plan.get("priced", True), "refused": plan.get("refused", {}),
# what the plan assumed for want of a fact (e.g. battery.end_value_pct missing)
"notes": plan.get("notes", []),
# cost_eur by carrier (its heat outlook a fixed term: the heat no room model plans),
# the plan's CO2 and its basis (methods A2): absent from older agents
**{k: plan[k] for k in ("cost_parts", "heat_outlook", "co2_kg", "co2_basis", "storage") if k in plan},
# the saving by carrier and lever (plansplit.py; the console's Savings page): absent from older agents
**({"saving_parts": plan["saving_parts"]} if plan.get("saving_parts") else {}),
"sources": plan.get("sources", {}),
# for the building (shed_w/grid_w per step, 24 h): absent from older agents
"flex": plan.get("flex", {}),
# the market's contracts in the plan (shadow): planned kWh and saving vs the grid
"market": plan.get("market", []),
# the owner's preferences: per level who set what and when, the
# overrides, and per preference met or not and each must's cost
"preferences": self.prefs.public(),
# overrides, and per preference met or not and each must's cost;
# builtin: the agent's own targets where none is set
"preferences": self.prefs.public(self.controls, bool(self.presence_entities()),
(plan.get("sources") or {}).get("occupancy")),
# the box's own models (boxtrain.py): held-out and live errors per source,
# hourly the forecasts it planned on; absent from older agents
**({"ml": plan["ml"]} if plan.get("ml") else {})}
@@ -437,7 +460,9 @@ class Controller:
b, now, start = self.boxml, self.clock(), int(state["start"])
st = b.store
if self.forecast:
st.put_weather("forecast", "ha", localml.ha_hours(self.forecast), now)
# with the wind in m/s where the weather entity says its unit (localml.ha_hours)
unit = self.col.attr(self.inputs.weather, "wind_speed_unit") if self.inputs.weather else None
st.put_weather("forecast", "ha", localml.ha_hours(self.forecast, unit), now)
m = self.bundles.model.get()
if isinstance(m, dict) and m.get("site") == self.cfg.site_id:
if m.get("weather"):
@@ -447,6 +472,9 @@ class Controller:
for key, series in (("load", "plan"), ("pv", "pv")):
if cands.get(key):
b.record(series, start, cands[key], now)
for key, c in cands.items(): # the carriers' (occupancy): under their own names
if key not in ("load", "pv") and c:
b.record(key, start, c, now)
auto = plan.get("mode") == "auto"
net = (plan.get("flex") or {}).get("net_w") if auto else \
([round(lo - pv) for lo, pv in zip(net_load, state["pv_w"])] if net_load else None)
@@ -592,6 +620,10 @@ class Controller:
self.history.add("pv_w", self.col.total(self.inputs.pv_power), now)
if self.sample_ev_phases(now) and self.gridorders.active():
self._merge_limits() # a learned count: the order's current bound again
try:
self.sample_stores(now)
except Exception as e: # never stops the actions
log.warning("stores: %s", e)
if int(now) % 900 < 60:
try:
self.history.save(now)
@@ -755,6 +787,48 @@ class Controller:
changed |= self.evphases.sample(c.id, p, a, float(c.p("voltage")), now)
return changed
# -- what the box learns of its stores (storefit.py) ---------------------------
def sample_stores(self, now: float):
"""A reading of each battery (its SoC, its own power, the PV, its
grid charging) and each tank (its mean temperature, the room, its
heater's heat) for the idle-loss fit, the tank's draw (S.7), UA and
legionella time; the fits once a day, saved each quarter-hour."""
bp = self.bundles.box_params(now) if hasattr(self.bundles, "box_params") else {}
caps = {}
bats = [c for c in self.controls if c.kind == "battery"]
for c in self.controls:
if c.kind == "battery":
e = c.entities
pw = inputs_mod.watts(self.col, e["power"]) if e.get("power") else None
if pw is None and len(bats) == 1 and hasattr(self.mapping, "by_asset"):
a = self.mapping.by_asset.get("battery.power")
pw = inputs_mod.watts(self.col, a.entity) if a else None
pv = self.col.total(self.inputs.pv_power) if self.inputs.pv_power else None
self.storefit.sample_battery(c.id, now, self.col.value(e.get("soc", "")), pw, pv,
self.col.state(e.get("charge_from_grid", "")) == "on")
f, _, _ = c.battery_facts()
if f.get("capacity_wh"):
caps[c.id] = f["capacity_wh"]
elif c.kind == "dhw_tank" and c.resolved:
st = inputs_mod.device_state(c, self.col, now)
f = c.resolved
temp = storefit_mod.mean_temp(st.get("temp_top"), st.get("temp_bottom"),
float(f.get("top_share") or 1.0))
room = st.get("room_c") if st.get("room_c") is not None else f.get("room_temp_c")
heat = st.get("heater_w")
if heat is not None and f.get("heater") == "heat_pump":
# its heat by its COP (a COP curve's is not known here: no heat, no draw then)
heat = heat * float(f["cop"]) if f.get("cop") else None
facts = dict(f, draw_detect_k=bp.get("dhw.draw_detect_k_per_15min"))
if room is not None:
self.storefit.sample_tank(c.id, now, temp, float(room), heat, facts)
if int(now) % 900 < 60:
self.storefit.fit_batteries(caps, bp, now)
for c in self.controls:
if c.kind == "dhw_tank" and c.resolved:
self.storefit.fit_tank(c.id, dict(c.resolved, label_ua_w_k=c.resolved.get("ua_w_k")), bp)
self.storefit.save()
# -- the grid operator's limit (EEBUS LPC, gridorder.py) -----------------
def _merge_limits(self):
"""The guard's limits: the console's, and over them the grid order's