cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1789: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-12 06:28:42 +02:00
1 parent 94f46db8f8
commit b24675fe9c
25 files changed
+766 -40

No files matched your search

+8
View File
@@ -92,6 +92,14 @@ class Building:
self.bound = b if isinstance(b, dict) and b.get("building") else None
except (OSError, ValueError, AttributeError):
pass
c = self.active.get("battery_plan")
if c and not self.bound:
# a plan taken by an agent before the binding existed (2026-11-09, the farm's upgrade to 0.1.0-dev.db2193861454:
# Berlin's and Durlach's plans of the night carried no binding, so A9.4b did not hold and the owner's 10 % floor
# was refilled from the grid against the building's 0 W): the plan in force binds as if taken now
self.bound = {"building": c["building"], "level": c.get("level", "binding"), "since": int(self.clock()),
"until": c["until"], "id": c["id"]}
self._save()
self.drop_ended()
def memberships(self) -> set[str] | None:
+22 -4
View File
@@ -51,7 +51,7 @@ from . import shades, steady
from .evphases import EvPhases
from .executor import Executor, building_msg
from .gridorder import GridOrders
from .guard import Guard
from .guard import Guard, changed_by
from .policy import Policy
from .preferences import Preferences
from .switchover import Switchover
@@ -284,7 +284,7 @@ class Controller:
value = st.get("s") # the agent last set the mode
else:
value = st.get("s")
self.guard.observe(c.id, eid, value, now)
self.guard.observe(c.id, eid, value, now, by=changed_by(st.get("c")))
def planned_kinds(self) -> set[str]:
"""The kinds of the devices the box plans whose power is inside the
@@ -411,6 +411,8 @@ class Controller:
"sources": plan.get("sources", {}),
# for the building (shed_w/grid_w per step, 24 h): absent from older agents
"flex": plan.get("flex", {}),
# the energy picture per step, 24 h (optimizer.plan_series; the console's plan chart): absent from older agents
**({"series": plan["series"]} if plan.get("series") else {}),
# 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
@@ -843,7 +845,8 @@ class Controller:
at level grid (the lower limit of the two holds)."""
merged = {c: {q: dict(lv) for q, lv in qs.items()} for c, qs in self.saved_limits.items()}
phases = {cid: v["phases"] for cid, v in self.ev_phases().items()}
for cid, qs in self.gridorders.limits(self.controls, phases).items():
self._grid_connected = self.ev_connected()
for cid, qs in self.gridorders.limits(self.controls, phases, self._grid_connected).items():
for q, (f, lim) in qs.items():
per = merged.setdefault(cid, {}).setdefault(q, {})
old = per.get("grid")
@@ -882,8 +885,23 @@ class Controller:
if a is not None:
await self._publish("action", a)
def ev_connected(self) -> dict:
"""Each charger's car: plugged in (True), not (False), unknown (None: no connected entity or no
state yet), for the order's shares (gridorder.limits)."""
out = {}
for c in self.controls:
if c.kind == "ev":
st = self.col.state(c.entities["connected"]) if "connected" in c.entities else None
out[c.id] = True if st == "on" else False if st == "off" else None
return out
def grid_tick(self):
"""An order that went stale or ended takes its limits away."""
"""An order that went stale or ended takes its limits away; while one holds, a car plugged in or out
gets its share again (the chargers share the one limit, gridorder.limits)."""
if self.gridorders.active() and self.ev_connected() != getattr(self, "_grid_connected", None):
self._merge_limits()
self.wake.set()
return
if self.gridorders.order and not self.gridorders.active() and any(
"grid" in lv for qs in self.guard.extra_limits.values() for lv in qs.values()) \
and not any("grid" in lv for qs in self.saved_limits.values() for lv in qs.values()):
+5 -1
View File
@@ -205,7 +205,10 @@ PARAMS = {
# a hot-water tank's choices (its facts: FACTS, no default): the legionella run left to the
# device's own program unless the installer says "plan" (or "none"); a heating control whose
# compressor it shares; the SG-Ready select's option per state "1".."4"; anti-cycling as heating
"dhw_tank": {"legionella": "device", "shares_with": "", "sg_options": {}, "cop_curve": [],
# a boiler-heated tank: the burner's part load as a heating control's (boiler_type, part_load_curve: the data
# sheet's; inputs.tank_inputs passes them to the plan; 2026-11-09: refused as unknown before)
"dhw_tank": {"legionella": "device", "shares_with": "", "sg_options": {}, "cop_curve": [], "boiler_type": "",
"part_load_curve": [],
"min_switch_s": 600.0, "hold_mode_s": 1800.0, "hold_set_s": 900.0, "min_gain_ct": 1.0},
}
@@ -750,6 +753,7 @@ def _check_tank(cid: str, p: dict):
SG-Ready options for states "1".."4", a COP curve as heating's."""
if "heater" in p and p["heater"] not in TANK_HEATERS:
raise ValueError(f"control {cid}: heater is one of {', '.join(TANK_HEATERS)}")
_check_part_load(cid, p)
if "erp_class" in p and p["erp_class"] not in ERP_CLASSES:
raise ValueError(f"control {cid}: erp_class is one of {', '.join(ERP_CLASSES)}")
if "top_share" in p and not 0 < float(p["top_share"]) <= 1:
+71 -4
View File
@@ -183,7 +183,38 @@ class Executor:
# -- what is wanted ------------------------------------------------------
def wanted(self, c, now):
want, level, why = self._wanted(c, now)
return self._capped(c, want, level, why, now)
return self._grid_bound(c, *self._capped(c, want, level, why, now))
def _grid_bound(self, c, want, level, why):
"""The grid operator's order (gridorder.limits, at level grid in the guard's limits) on every
controllable consumer, whatever its plan says: a charger the plan leaves as it is (a building's garage
charger: no session to plan) or plans above its share is set to its share, or paused where its share is
below its minimum current; a battery charges at most its share. Before 2026-11-09 only the plan kept
the order and the guard checked commands, so a charger nobody commanded kept drawing (Sim Durlach's
garage, feeder 6, 2026-11-08 16:32-17:32 at 30-37 kW under a 4.2 kW order)."""
q = "current_a" if c.kind == "ev" else "power_w" if c.kind in ("battery", "dhw_tank") else ""
lims = getattr(self.guard, "extra_limits", None) or {}
g = ((lims.get(c.id) or {}).get(q) or {}).get("grid") if q else None
if not g or g[1] is None:
return want, level, why
cap = float(g[1])
tag = f"the grid operator's limit: {cap:g} {'A' if q == 'current_a' else 'W'} (its share of the order)"
v = want.get("set") if isinstance(want, dict) else want
if c.kind == "ev":
if v == "off":
return want, level, why
lo = float(c.p("min_current_a") or 0)
n = number(v)
if cap < lo or cap <= 0:
return "off", "emergency", tag
if n is None or n > cap:
return cap, "emergency", tag
return want, level, why
if c.kind == "battery" and isinstance(want, dict) and number(v) is not None and float(v) > cap:
return {**want, "set": cap}, "emergency", tag
if c.kind == "dhw_tank" and number(v) is not None and "power" in c.entities and float(v) > cap:
return ({**want, "set": cap} if isinstance(want, dict) else cap), "emergency", tag
return want, level, why
def _wanted(self, c, now):
cmd = self.commands.get(c.id)
@@ -273,25 +304,47 @@ class Executor:
return lambda d, s, ent: (d, s, ent) == (a.domain, a.service, a.entity)
async def _overrides(self, now):
"""Each change by hand the guard saw: reported as an `overridden`
action with what the agent had set, who changed it (guard.changed_by:
resident, automation, device), until when the agent keeps off it, and
what it overrode (the level: plan, a command's level; its id), for the
console's overrides and deviations report."""
while self.guard.events:
ev = self.guard.events.pop(0)
c = self.controls.get(ev["control"])
cap, bcmd = self.building.cap(c.kind, now) if self.building is not None and c else (None, None)
if bcmd is not None and "climate" in c.entities and ev["entity"] == c.entities["climate"]:
await self._building_override(bcmd, ev)
bplan = self._battery_plan(c, now)
if bplan is not None:
await self._battery_plan_override(bplan, ev)
cmd = self.commands.get(ev["control"])
until, level = ev["until"], "plan"
if cmd and cmd["level"] == "flexible":
self.commands.pop(ev["control"], None) # the owner wins over a flexible command
why = f"the owner changed it by hand: flexible command {cmd.get('id', '')} ended"
level = "flexible"
elif cmd:
why = f"the owner changed it by hand: {cmd['level']} command applied again"
until, level = int(now), cmd["level"] # applied again at once: no hands-off time
else:
why = f"the owner changed it by hand: hands off until {time.strftime('%H:%M UTC', time.gmtime(ev['until']))}"
await self.publish("action", {"v": 1, "at": ev["at"], "asset": ev["control"], "entity": ev["entity"],
"service": "", "value": ev["value"], "result": "overridden", "why": why})
msg = {"v": 1, "at": ev["at"], "asset": ev["control"], "entity": ev["entity"],
"service": "", "value": ev["value"], "result": "overridden", "why": why,
"level": level, "by": ev.get("by", ""), "until": int(until), "agent_set": ev.get("agent_set")}
if cmd and cmd.get("id"):
msg["id"] = cmd["id"]
await self.publish("action", msg)
log.info("override: %s %s=%s (%s)", ev["control"], ev["entity"], ev["value"], why)
self.log.append({"result": "overridden", **ev})
def _battery_plan(self, c, now):
"""The building's battery_plan in force for this battery, or None."""
if self.building is None or c is None or c.kind != "battery":
return None
bp = self.building.active.get("battery_plan")
return bp if bp and bp["from"] <= now < bp["until"] else None
async def _building_override(self, bcmd, ev):
"""The owner changed a room the building's cap holds: a flexible cap
ends, a binding one stays (applied again)."""
@@ -300,7 +353,21 @@ class Executor:
why = "the owner changed it by hand: the flexible cap ended"
else:
why = "the owner changed it by hand: the binding cap applied again"
await self.publish("action", building_msg(bcmd, "overridden", why, ev["at"]))
msg = building_msg(bcmd, "overridden", why, ev["at"])
msg.update({"by": ev.get("by", ""), "asset": ev["control"], "agent_set": ev.get("agent_set"), "set": ev["value"],
"until": int(bcmd["until"]) if bcmd["level"] == "flexible" else int(ev["at"])})
await self.publish("action", msg)
async def _battery_plan_override(self, bp, ev):
"""The owner changed a battery the building's battery_plan holds: told
to the building as an override of that plan (reported only; whether a
flexible plan is lifted then is still open: until then the
plan stays, the guard's hands-off time holds the battery)."""
why = f"the owner changed the battery by hand: the building's {bp['level']} battery plan overridden"
msg = building_msg(bp, "overridden", why, ev["at"])
msg.update({"by": ev.get("by", ""), "asset": ev["control"], "agent_set": ev.get("agent_set"), "set": ev["value"],
"until": int(ev["until"])})
await self.publish("action", msg)
async def _report(self, a: Action, result, why, now):
msg = {"v": 1, "at": int(now), "asset": a.control, "entity": a.entity,
+33 -15
View File
@@ -48,7 +48,7 @@ import math
import os
import time
from .controls import ev_volts
from .controls import PARAMS, ev_volts
log = logging.getLogger(__name__)
@@ -242,24 +242,42 @@ class GridOrders:
return {"limit_w": float(o["limit_w"]), "from_step": int(a), "to_step": int(b), "penalty": PENALTY_EUR_KWH,
"id": o["id"], "proof": self.proof(), "state": o.get("state", "")}
def limits(self, controls, phases: dict | None = None) -> dict:
"""Grid-level bounds per controllable device (§14a: chargers,
batteries' charging; heat pumps are held by the bridge itself): no
single one above the whole limit. phases: {control id: count} from
evphases (else the mapping's; unknown: 3, never above the ordered
power). {control id: {quantity: (floor, limit)}}."""
def limits(self, controls, phases: dict | None = None, connected: dict | None = None) -> dict:
"""Grid-level bounds per controllable device (§14a with an energy
management system: the controllable consumers' sum at most the
limit; heat pumps are held by the bridge itself). The one limit is
shared, not given whole to each (before 2026-11-09 each charger and
the battery got all of it: three garage chargers could draw three
times the order): the chargers first, in turn, each its share down to
0.1 A (never above the order's power) or 0 where less than its
minimum current is left (it pauses: a car charging at its minimum
and another paused is the redistribution, not every car below its
minimum); a car known not plugged in takes nothing (connected:
{control id: bool}); then a battery's charging and a tank's stepless
element get what is left (no battery reserve is kept for orders: the
owner, 2026-11-09). phases: {control id: count} from evphases (else
the mapping's; unknown: 3, never above the ordered power).
{control id: {quantity: (floor, limit)}}."""
o = self.active()
if not o:
return {}
w = float(o["limit_w"])
left = float(o["limit_w"])
out = {}
con = connected or {}
evs = sorted((c for c in controls if c.kind == "ev"), key=lambda c: con.get(c.id) is False)
for c in evs:
n = (phases or {}).get(c.id) or c.params.get("phases")
volts = ev_volts({**c.params, "phases": n}, "order")
lo = float(c.params.get("min_current_a") or PARAMS["ev"]["min_current_a"])
hi = float(c.params.get("max_current_a") or PARAMS["ev"]["max_current_a"])
# down to 0.1 A: never above the power left (6.1 A x 690 V = 4209 W)
amps = math.floor(max(left, 0.0) / volts * 10 + 1e-9) / 10
if con.get(c.id) is False or amps < lo:
amps = 0.0
out[c.id] = {"current_a": (None, amps)}
left -= min(amps, hi) * volts
for c in controls:
if c.kind == "ev":
n = (phases or {}).get(c.id) or c.params.get("phases")
volts = ev_volts({**c.params, "phases": n}, "order")
# down to 0.1 A: never above the ordered power (6.1 A x 690 V = 4209 W)
out[c.id] = {"current_a": (None, math.floor(w / volts * 10 + 1e-9) / 10)}
elif c.kind == "battery" or c.kind == "dhw_tank" and "power" in c.entities:
if c.kind == "battery" or c.kind == "dhw_tank" and "power" in c.entities:
# a battery's charging; a tank's stepless element (its relay: the plan's limit on the meter)
out[c.id] = {"power_w": (None, w)}
out[c.id] = {"power_w": (None, max(0.0, round(left, 1)))}
return out
+28 -3
View File
@@ -172,10 +172,11 @@ class Guard:
if entity not in tr.commanded:
tr.commanded[entity] = (self.clock() - self.settle, value)
def observe(self, control_id: str, entity: str, value, now: float | None = None):
def observe(self, control_id: str, entity: str, value, now: float | None = None, by: str = ""):
"""A state change of a control's entity: if it differs from what the
agent set, and not right after the agent set it, the owner changed
it by hand."""
it by hand. by: who changed it (changed_by), reported with the
override."""
now = self.clock() if now is None else now
tr = self._t(control_id)
cmd = tr.commanded.get(entity)
@@ -191,7 +192,7 @@ class Guard:
tr.override_entity = entity
tr.commanded.pop(entity, None)
self.events.append({"control": control_id, "entity": entity, "value": value, "agent_set": want,
"until": int(tr.override_until), "at": int(now)})
"until": int(tr.override_until), "at": int(now), "by": by})
def last_change(self, control_id: str, kind: str) -> float | None:
"""When the agent last changed a control's mode or setpoint (kind
@@ -202,6 +203,30 @@ class Guard:
return self.clock() < self._t(control_id).override_until
def changed_by(ctx) -> str:
"""Who changed an entity, from Home Assistant's context of the new state
(subscribe_entities sends it as "c": the context's id alone when it has
no user and no parent, else {"id", "user_id", "parent_id"}):
resident a person signed in to HA (its app or dashboard, the box's
panel through HA): the context has a user
automation an automation or script in HA: a parent context, no user
device neither: the device or its integration reported the change
itself (a button or dial on the device, its own app, its
manual mode)
"" no context reported (an older HA, a test)
The agent's own calls never reach here as overrides: the guard skips a
value it set itself."""
if isinstance(ctx, str) and ctx:
return "device"
if isinstance(ctx, dict):
if ctx.get("user_id"):
return "resident"
if ctx.get("parent_id"):
return "automation"
return "device" if ctx.get("id") else ""
return ""
def _same(a, b, tol: float = 0.26) -> bool:
try:
return abs(float(a) - float(b)) < tol
+3 -1
View File
@@ -55,12 +55,14 @@ class Collector:
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}
self.states[eid] = {"s": s.get("s"), "a": dict(s.get("a") or {}), "t": s.get("lc") or now, "c": s.get("c")}
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"]
# the change's context (HA: an id alone, or {"id", "user_id", "parent_id"}): who made it (guard.changed_by)
cur["c"] = plus.get("c")
cur["a"].update(plus.get("a") or {})
for k in minus.get("a") or []:
cur["a"].pop(k, None)
+70
View File
@@ -946,6 +946,8 @@ class Model:
"lo_c": lo_c, "hi_c": hi_c, "heater": heater, "pmax": pmax, "cops": cops, "switched": switched,
"eff": sup.curve["full"] if heater == "boiler" else None, "e_leg": e_leg, "window": window,
"qmax": sup.qmax if sup else None,
# a boiler-heated tank's fuel (gas or heating oil: the plan's series, plan_series)
"fuel": sup.carrier if heater == "boiler" and sup else None,
"src": "electric" if heater in ("element", "heat_pump") else heater})
def cover(self, d, room_ids):
@@ -1307,6 +1309,10 @@ def plan(s: dict, time_limit: float = 30.0) -> dict:
notes += m.notes
if notes:
out["notes"] = notes
# the site's energy per carrier and use, per step for 24 h (the console's plan chart; methods A2.17)
series = plan_series(s, m, x, outlook)
if series:
out["series"] = series
steps_eur = step_costs(s, m, x)
if steps_eur is not None:
out["steps_eur"] = steps_eur # per step and carrier: with and without the plan (costs.py)
@@ -1619,6 +1625,70 @@ def flexibility(m, x) -> dict:
return out
def plan_series(s, m, x, outlook) -> dict:
"""The plan's energy picture per step for the next 24 h (FLEX_STEPS; W,
the mean power in the step: docs/methods.md A2.17), for the console's
plan chart: electricity's sources (import_w, pv_w: the forecast, the
battery's discharge) and uses (load_w: the house's own forecast,
heating_w / cooling_w: electric heat and cooling, ev_w, dhw_element_w:
a tank's electric heater, the battery's charge, export_w), and the other
carriers' inputs: gas_w and oil_w (a boiler's fuel, Hi), heat_w (heat
bought from a district or the building), dhw_w (hot water's heat drawn,
where forecast); per hot-water tank its planned temperature
("tank_c:<id>", °C). Only what the site has (a key absent: not in the plan,
never 0 for it); the heat outlook (A2.16) adds its fixed heat as drawn."""
n = min(m.T, FLEX_STEPS)
out: dict[str, list] = {}
def add(key, t, w):
out.setdefault(key, [0.0] * n)[t] += w
for t in range(n):
add("import_w", t, x(m.gin[t]) + sum((x(v) for v in m.buy[t]), 0.0))
add("export_w", t, x(m.gout[t]) + sum((x(v) for v in m.sell[t]), 0.0))
add("load_w", t, max(0.0, float(s["load_w"][t])))
if any(float(v) > 0 for v in s["pv_w"][:n]):
out["pv_w"] = [max(0.0, float(v)) for v in s["pv_w"][:n]]
temps = {}
for did, (kind, v) in m.devices.items():
if not v:
continue
if kind == "battery":
for t in range(min(n, len(v["ch"]))):
add("battery_charge_w", t, _x(x, v["ch"][t]))
add("battery_discharge_w", t, _x(x, v["dis"][t]))
continue
if kind == "ev":
for t in range(min(n, len(v["power"]))):
add("ev_w", t, _x(x, v["power"][t]))
continue
if kind not in ("heating", "cooling", "dhw_tank"):
continue
el = "dhw_element_w" if kind == "dhw_tank" else kind + "_w"
fuel = (v.get("fuel") or "gas") + "_w"
for col, key in (("power", el), ("gas", fuel), ("district", "heat_w")):
xs = v.get(col) or []
if not any(c is not None and hasattr(c, "index") for c in xs[:n]):
continue
for t in range(min(n, len(xs))):
add(key, t, _x(x, xs[t]))
if kind == "dhw_tank":
# its planned mean temperature at each step's end (°C, not W: "tank_c:<id>")
temps["tank_c:" + did] = [round(tank_temp(v, t, x), 1) for t in range(min(n, len(v["e"])))]
for t in range(min(n, len(v.get("draw") or []))):
d = v["draw"][t]
add("dhw_w", t, float(d) if isinstance(d, (int, float)) else _x(x, d))
if outlook:
key = {"gas": "gas_w", "oil": "oil_w", "heat": "heat_w"}.get(outlook.get("carrier"))
for kind, ln in (outlook.get("lines") or {}).items():
for t in range(min(n, len(ln["input_w"]))):
if key:
add(key, t, float(ln["input_w"][t]))
if kind == "dhw":
add("dhw_w", t, float(ln["heat_w"][t]))
return {**{k: [round(w) for w in v] for k, v in out.items()}, **temps}
def _x(x, v) -> float:
"""A step's value: a variable's, or 0 where there is none (an EV's steps after departure)."""
return x(v) if v is not None and hasattr(v, "index") else 0.0
+52
View File
@@ -30,6 +30,19 @@ owner: "we still have no saving from gas/oil?"; methods E14):
not_planned the heating or tank on it was refused (its refusal's why: e.g.
no gas price); 0 in plan and base, nothing of it is planned
Electricity whose saving rounds to 0.00 EUR carries why and note too (audit
2026-11-09: 28 homes showed electricity 0 without a reason):
no_lever the plan moves no electricity: no battery, no car plugged in
or expected, no electric heating (heat pump, heater) and no
electric hot water; the household's own use is a fixed term
(a district-heat or gas flat, a car away)
flat_price it has a lever, but one import price at every step and no
battery: the lever's draw costs the same whenever it runs
not_shifted the price varies (or a battery could store), but the plan
found nothing cheaper than the baseline: the draw already lies
in the cheapest hours, or nothing is due in the horizon
The levers found are in the note.
base_eur − plan_eur summed over the carriers is the plan's own saving,
baseline_eur − cost_eur: the plan's electricity carries the market's
contracts (a tenant-power flat's energy bought from its building at the
@@ -56,6 +69,10 @@ def saving_parts(s: dict, m, x, steps: dict | None) -> dict | None:
if p is not None:
heating += m.eur_wh(t, mean - pi[t]) * x(p)
out["electricity"]["heating_eur"] = round(heating, 4)
if "electricity" in out:
why = electricity_zero_why(s, m, out["electricity"])
if why is not None:
out["electricity"].update(why)
for carrier in HEAT_CARRIERS:
why = zero_why(s, m, carrier, out.get(carrier))
if why is not None:
@@ -95,3 +112,38 @@ def zero_why(s: dict, m, carrier: str, part: dict | None) -> dict | None:
+ ("; a lower room temperature is not counted as a saving" if rooms else "")
+ tail}
return {"why": "not_shifted", "note": f"the {words} price varies, but the heat was needed when it was made" + tail}
def electric_levers(m) -> list[str]:
"""What in this plan can move electricity in time (its words)."""
out = []
for kind, v in m.devices.values():
if not v:
continue # e.g. a car not plugged in and none expected
if kind == "battery" and float(v.get("cap") or 0) > 0:
out.append("battery")
elif kind == "ev":
out.append("car")
elif kind in ("heating", "cooling") and v.get("src") in ("electric", "heat_pump", "hybrid"):
out.append({"heat_pump": "heat pump", "hybrid": "hybrid's heat pump"}.get(v["src"], "electric heating")
if kind == "heating" else "cooling")
elif kind == "dhw_tank" and v.get("src") == "electric":
out.append("electric hot water")
return sorted(set(out))
def electricity_zero_why(s: dict, m, part: dict) -> dict | None:
"""Why the electricity saving is 0 in this plan ({why, note}; module docstring), None where it has one."""
if abs(part["base_eur"] - part["plan_eur"]) >= ZERO_EUR:
return None
levers = electric_levers(m)
if not levers:
return {"why": "no_lever", "note": "nothing in this plan moves electricity in time (no battery, no car plugged in "
"or expected, no heat pump or electric heating, no electric hot water): "
"the household's own use is the same with and without the plan"}
ps = [p for p in (s.get("price_import") or [])[:m.T] if p is not None]
if ps and max(ps) - min(ps) < 1e-9 and "battery" not in levers:
return {"why": "flat_price", "note": f"one electricity price ({ps[0]:.2f} ct/kWh) at every hour of the plan: "
f"the {', '.join(levers)} costs the same whenever it runs"}
return {"why": "not_shifted", "note": f"the {', '.join(levers)} found nothing cheaper in this plan: its draw "
"already lies in the cheapest hours, or nothing is due in the horizon"}
+16 -2
View File
@@ -8,7 +8,16 @@ next window, so a steady sensor that reports rarely still has a mean.
Counters (a growing total: energy): the delta over the window. A total
that goes down is a meter reset or replacement: the new reading counts
from zero instead of a negative delta.
from zero instead of a negative delta. A drop is judged by the reading after
it: Home Assistant reports 0 for a moment while it restarts, and after a
restart it may show the total it had saved minutes before until the device
reports again, so a return to at least the previous total means the drop
was "unavailable" (the increase since the last real reading counts, no
reset); a reading below it means the meter really started again (a reset).
Before, the 0 was a reset, and the meter's whole total became one minute's
increase (a test site 2026-11-08 11:21 UTC: 2 124 kWh of load in a minute); the
stale total too (Sim Berlin 1 2026-11-08 14:44 UTC: heat.energy 462 477 →
461 809 Wh after the farm's reboot, back at 462 4xx with its simulator).
Unavailable: seconds of the window without a valid value are reported, so
the platform can tell "0 W" from "unknown".
@@ -39,6 +48,7 @@ class _Counter:
delta: float = 0.0
resets: int = 0
n: int = 0
drop: float | None = None # a reading below the total, judged by the next different one
@dataclass
@@ -58,11 +68,15 @@ class Aggregator:
if value is None:
return
if c.last is not None:
if value < c.last and (c.drop is None or value == c.drop or value == 0):
c.drop = value # unavailable until a different reading says otherwise
return
if value >= c.last:
c.delta += value - c.last
else:
c.delta += value
c.resets += 1
c.drop = None
c.last, c.n = value, c.n + 1
return
g = self.gauges.setdefault(asset, _Gauge(since=self.start))
@@ -90,6 +104,6 @@ class Aggregator:
for asset, c in sorted(self.counters.items()):
out.append({"asset": asset, "kind": "counter", "delta": c.delta, "last": c.last,
"resets": c.resets, "n": c.n})
self.counters[asset] = _Counter(last=c.last)
self.counters[asset] = _Counter(last=c.last, drop=c.drop)
self.start = end
return out