cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.901: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-05 13:14:49 +02:00
1 parent d48b9aff87
commit e2c7085d2c
76 files changed
+5380 -330

No files matched your search

+255 -19
View File
@@ -3,8 +3,9 @@
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. A
room's R and C: the mapping's, else the model bundle's (its rooms), else
the defaults; sources.rooms says which per control.
room's R and C: the mapping's, else the box's or the cloud's fit (the
model bundle's rooms); none: the room is not planned (room_refusal) and keeps a fallback schedule; sources.rooms says which per
control.
None of this leaves the site; only the plan does (controller.py).
@@ -284,10 +285,11 @@ def device_state(c, col: Collector, now: float) -> dict:
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
# the state of charge from its sensor only (no estimate: docs/parameters.md U2)
st["soc_pct"] = col.value(e.get("soc", ""))
st["charge_from_grid"] = col.state(e.get("charge_from_grid", "")) == "on"
if hasattr(c, "reported"):
c.reported = battery_reported(c, col)
elif c.kind in ("heating", "cooling"):
t = col.value(e.get("temp", ""))
if t is None and e.get("climate"):
@@ -298,6 +300,12 @@ def device_state(c, col: Collector, now: float) -> dict:
st["hvac"] = col.state(e["climate"])
else:
st["on"] = col.state(e.get("switch", "")) == "on"
if c.kind == "heating" and e.get("source"):
# a hybrid's source now, in the plan's words (heat_pump | boiler)
opts = {str(v): k for k, v in (c.p("source_options") or {}).items()}
st["source"] = opts.get(str(col.state(e["source"])))
if c.kind == "heating" and e.get("efficiency") and hasattr(c, "reported"):
c.reported = {"efficiency_pct": col.value(e["efficiency"])}
elif c.kind == "ev":
conn = e.get("connected")
st["connected"] = col.state(conn) == "on" if conn else True
@@ -317,6 +325,105 @@ def device_state(c, col: Collector, now: float) -> dict:
return st
def _scaled(col: Collector, eid: str, units: dict) -> float | None:
"""An entity's value converted by its unit (units: unit -> factor; a
unit not in it: None, never a guess at the scale)."""
v = col.value(eid) if eid else None
if v is None:
return None
f = units.get(col.attr(eid, "unit_of_measurement"))
return v * f if f is not None else None
def battery_reported(c, col: Collector) -> dict:
"""The battery's own ratings where its device reports them (the
control's capacity, rated_power and efficiency entities): capacity_wh,
rated_power_w, efficiency_pct (round trip); absent where it does not."""
e, out = c.entities, {}
cap = _scaled(col, e.get("capacity", ""), {"kWh": 1000.0, "Wh": 1.0})
pw = _scaled(col, e.get("rated_power", ""), {"kW": 1000.0, "W": 1.0})
eff = _scaled(col, e.get("efficiency", ""), {"%": 1.0})
for k, v in (("capacity_wh", cap), ("rated_power_w", pw), ("efficiency_pct", eff)):
if v is not None and v > 0:
out[k] = v
return out
def battery_refusal(c, st: dict) -> dict | None:
"""Why a battery is not planned (docs/parameters.md U2), or None: its
capacity, power or efficiency unknown (the mapping, the device and its
owner's ratings have none), or no state of charge from its sensor.
{"why": the reasons, "where": where to enter what is missing,
"missing": [...]}."""
from .controls import BATTERY_RATINGS
_, missing, _ = c.battery_facts()
why = [f"battery {m} unknown" for m in missing]
if st.get("soc_pct") is None:
why.append("SoC unknown (no state-of-charge sensor)" if not c.entities.get("soc")
else "SoC unknown (the state-of-charge sensor has no value)")
if not why:
return None
where = ""
if missing:
labels = ", ".join(BATTERY_RATINGS[m][1] for m in missing)
params = ", ".join(BATTERY_RATINGS[m][2] for m in missing)
dev = getattr(c, "rated_device", "") or ""
where = (f"on the panel: Devices, {dev}, Ratings ({labels})" if dev else
f"on the panel: Devices, the battery's device, Ratings ({labels}); or in the mapping's params ({params})")
if st.get("soc_pct") is None:
where = (where + "; " if where else "") + "map the battery's state-of-charge sensor (soc)"
return {"why": "; ".join(why), "where": where, "missing": missing + (["soc"] if st.get("soc_pct") is None else [])}
HYBRID_SWITCH_KEY = "heat.hybrid_switch_eur" # the Parameters page's (via the tariff bundle)
def heating_refusal(c, params: dict, price_gas: list, price_heat: list, prices_status: str,
box_params: dict | None = None) -> dict | None:
"""Why a heating control is not planned (docs/methods.md E6, the
owner's rule: refuse, never guess), or None: a boiler's efficiency or
a boiler's / heat station's most heat unknown, no gas price (boiler,
hybrid) or heat price (district) for now, a hybrid without an
electricity price to compare with. {"why", "where", "missing"}."""
from .controls import HEAT_RATINGS
src = str(params.get("heat_source") or "electric")
if src == "electric":
return None
_, missing, _ = c.heat_facts()
why = [f"{HEAT_RATINGS[m][1].split(',')[0].lower()} unknown" for m in missing]
where = []
if src in ("heat_pump", "hybrid") and "cop" not in (c.params or {}) and not (c.params or {}).get("cop_curve"):
# a heat pump's COP is the device's (its datasheet): no default stands in
why.append("heat pump COP unknown")
where.append("the mapping's params: cop_curve (the datasheet's COP by outside temperature) or cop")
missing = missing + ["cop"]
if src == "hybrid" and (box_params or {}).get(HYBRID_SWITCH_KEY) is None:
why.append(f"parameter {HYBRID_SWITCH_KEY} not received")
where.append("the admin Parameters page (Gas and heat); it reaches the box with its tariff")
missing = missing + [HYBRID_SWITCH_KEY]
rated = [m for m in missing if m in HEAT_RATINGS]
if rated:
labels = ", ".join(HEAT_RATINGS[m][1] for m in rated)
dev = getattr(c, "rated_device", "") or ""
where.append(f"on the panel: Devices, {dev or 'the heating device'}, Ratings ({labels}); or in the mapping's params "
f"({', '.join(rated)})" + ("; or map the boiler's efficiency sensor" if "boiler_efficiency" in rated else ""))
if src in ("boiler", "hybrid") and (not price_gas or price_gas[0] is None):
why.append("no gas price for now")
where.append("the site's gas tariff (console: the site's tariff, Gas)")
missing = missing + ["gas_price"]
if src == "district" and (not price_heat or price_heat[0] is None):
why.append("no heat price for now")
where.append("the site's heat tariff, or its building's heat price (console: Buildings, rules)")
missing = missing + ["heat_price"]
if src == "hybrid" and prices_status == "none":
why.append("no electricity price to compare the heat pump with")
where.append("the site's electricity tariff")
missing = missing + ["electricity_price"]
if not why:
return None
return {"why": "; ".join(why), "where": "; ".join(where), "missing": missing}
SET_POSITION = 4 # HA's CoverEntityFeature.SET_POSITION
@@ -350,6 +457,12 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
start = int(now // STEP_S * STEP_S)
zone = ZoneInfo(tz or "UTC")
prices = bundles.prices(start, STEP_S, STEPS, now)
# gas and heat per step (fleet heatprice.go): what a boiler's and district heat cost
cp = getattr(bundles, "carrier_prices", None)
price_gas = cp("gas", start, STEP_S, STEPS, now) if cp else [None] * STEPS
price_heat = cp("heat", start, STEP_S, STEPS, now) if cp else [None] * STEPS
bp = getattr(bundles, "box_params", None)
box_params = bp(now) if bp else {}
# the base load: the house without the planned devices (Finding A2-a), so
# the plan, the building's shift and the grid order's base (optimizer)
# do not count them twice. The model's base_load_w is that; its load_w
@@ -431,7 +544,11 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
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, rooms_src, phases_src = [], {}, {}
devices, rooms_src, phases_src, refused, battery_src, heat_src = [], {}, {}, {}, {}, {}
# a room's COP and comfort temperatures: the mapping's (the device's facts, the owner's), or the
# defaults (optimizer.shift_envelope publishes no shift from defaults); rooms not planned
# (room_refusal) with what their fallback schedule needs
cop_src, band_src, fallback = {}, {}, []
one_room = sum(c.kind in ("heating", "cooling") for c in controls) == 1
for c in controls:
if hasattr(c, "learn_range"):
@@ -448,26 +565,87 @@ def model_state(now: float, controls, inputs, col: Collector, bundles, history,
{"phases": None, "source": "assumed"})
params["phases"] = info["phases"]
phases_src[c.id] = {"phases": info["phases"], "source": info["source"]}
st = device_state(c, col, now)
if c.kind in ("heating", "cooling"):
rooms_src[c.id] = _room_rc(c, params, bundles, one_room, now)
# the room's and the device's facts the mapping gives (no defaults: controls.FACTS)
params.update({k: float(c.params[k]) for k in ("r_k_per_kw", "c_kwh_per_k", "max_power_w", "cop")
if k in c.params})
source = "electric" if c.kind == "cooling" else str(params.get("heat_source") or "electric")
if c.kind == "heating" and source == "electric" and "cop" not in params:
params["cop"] = 1.0 # a resistive heater: all its electricity becomes heat (physics)
src, power = _room_rc(c, params, bundles, one_room, now)
rooms_src[c.id] = src
# an electric fit runs in electric equivalents: the COP cancels (_room_rc)
cop_src[c.id] = ("mapping" if "cop" in c.params or c.params.get("cop_curve") else
"electric heater" if c.kind == "heating" and source == "electric" else
"electric fit" if power == "electric" and "cop" in params else "none")
# comfort/setback/setup: the mapping's, else the box's copy of the Parameters rows
# comfort.heating_setpoints / comfort.cooling_setpoints (docs/parameters.md C7)
band_src[c.id] = "mapping" if any(k in c.params for k in ("comfort_c", "setback_c", "setup_c")) else "defaults"
# what is missing for the room and for its heat source (methods E6)
nos = [room_refusal(c, st, src, power, source)]
if c.kind == "heating":
nos.append(heating_refusal(c, params, price_gas, price_heat, getattr(prices, "status", "tariff"),
box_params))
nos = [n for n in nos if n is not None]
if nos:
# not planned: its limits and a fallback schedule (the owner's or
# installer's preferences: optimizer.fallback_entries)
no = {"why": "; ".join(n["why"] for n in nos if n.get("why")),
"where": "; ".join(n["where"] for n in nos if n.get("where")),
"missing": [m for n in nos for m in n.get("missing") or []]}
refused[c.id] = dict(no, kind=c.kind, name=c.label() if hasattr(c, "label") else c.id)
fallback.append({"id": c.id, "kind": c.kind, "params": params, "state": st, "bounds": bounds,
"channels": sorted(c.writable())})
continue
if c.kind == "heating" and hasattr(c, "heat_facts"):
facts, _, fsrc = c.heat_facts()
params.update(facts)
if facts:
heat_src[c.id] = fsrc
if c.kind == "battery":
no = battery_refusal(c, st)
if no is not None:
refused[c.id] = dict(no, kind="battery", name=c.label() if hasattr(c, "label") else c.id)
continue
facts, _, fsrc = c.battery_facts()
params.update(facts)
battery_src[c.id] = fsrc
# the battery's power from its facts (device_range ran before them in bounds)
b = c.bounds("power_w", (extra_limits or {}).get(c.id))
bounds["power_w"] = [b.lo, b.hi, b.lo_by, b.hi_by]
devices.append({"id": c.id, "kind": c.kind, "params": params,
"state": device_state(c, col, now), "bounds": bounds,
"state": st, "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
ghi, ghi_src = irradiance(start, location, sky, sun if peak > 100 else None)
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,
"price_gas": price_gas, "price_heat": price_heat, "params": box_params,
# the tariff's state (bundles.Prices): status tariff | none, why none, the steps it prices
"prices": {"status": getattr(prices, "status", "tariff"), "reason": getattr(prices, "reason", ""),
"tariff": getattr(prices, "tariff_id", ""), "expired_at": getattr(prices, "expired_at", 0),
"priced_steps": getattr(prices, "priced_steps", STEPS)},
"load_w": load, "pv_w": pv, "t_out": t_out, "sun": sun, "occupied": occupied, "sky": sky,
"ghi_w_m2": ghi, "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", "rooms": rooms_src, "ghi": ghi_src,
"rooms_cop": cop_src, "rooms_band": band_src,
"ev_phases": phases_src,
**({"battery": battery_src} if battery_src else {}),
**({"heating": heat_src} if heat_src else {}),
**({"intraday": intraday} if intraday else {}),
# per series the steps from the cloud's forecast, the box's own model
# (its kind and weather) and the hour-of-week profile (methods.md B9)
"forecast": {k: v for k, v in fc_src.items() if v}},
"devices": devices, "building": building or {}, "grid_order": grid_order or {},
# controls not planned and why (docs/parameters.md U2: a battery without its facts;
# a room without its R/C fit, power, COP or temperature)
"refused": refused,
# the rooms among them: their limits and params for a fallback schedule
# (preferences.apply gives their schedule, optimizer.fallback_entries the setpoints)
"fallback": fallback,
# the market's contracts in force as sources and sinks (shadow, the market's step 2)
"market": bundles.market_for_model(start, STEP_S, STEPS, now) if hasattr(bundles, "market_for_model") else []}
if grid_max_w:
@@ -508,12 +686,21 @@ def irradiance(start: int, location: dict | None, sky: list[float],
def _room_rc(c, params: dict, bundles, only_one: bool, now: float) -> str:
"""A heating or cooling control's R and C: the mapping's own, else the
model's room (bundles.room_rc), else the defaults. A room fitted against
the electric power: C * cop and R / cop (the same RC; the optimiser's
heat is cop * P). Into params; where they came from."""
if "r_k_per_kw" in c.params or "c_kwh_per_k" in c.params:
return "mapping"
"""A heating or cooling control's R and C: the mapping's own (both), else
the model's room (the box's fit in force, else the cloud's:
bundles.room_rc), else none (never the built-in defaults: the room is
not planned, room_refusal). A room fitted against the
electric power: C * cop and R / cop (the same RC; the optimiser's heat
is cop * P): the COP cancels, so without the mapping's cop the model
runs in electric equivalents (cop 1 by construction, not a default).
Into params; (where they came from: mapping | box model | model |
partial (the mapping sets one of the two) | none, the power the fit is
against: thermal | electric | "")."""
has = [k for k in ("r_k_per_kw", "c_kwh_per_k") if k in c.params]
if len(has) == 2:
return "mapping", "thermal"
if has:
return "partial", ""
# the box's own fit where it is in force (boxtrain.py), else the cloud's
own = getattr(bundles, "own", None)
rc = own.room_rc(c.id, str(c.params.get("area") or ""), only_one) if own is not None else None
@@ -522,12 +709,17 @@ def _room_rc(c, params: dict, bundles, only_one: bool, now: float) -> str:
get = getattr(bundles, "room_rc", None)
rc = get(c.id, str(c.params.get("area") or ""), only_one, now) if get else None
if rc is None:
return "defaults"
return "none", ""
r, cap = rc["r_k_per_kw"], rc["c_kwh_per_k"]
gain, solar = rc.get("gain_w") or 0.0, rc.get("solar_m2") or 0.0
cop = number(params.get("cop")) or 1.0
if rc.get("power") == "electric" and cop > 0:
# fitted in electric equivalents: the heat is cop times (like C)
electric = str(params.get("heat_source") or "electric") in ("electric", "heat_pump")
if rc.get("power") == "electric" and electric:
# fitted in electric equivalents: the heat is cop times (like C); without
# the mapping's COP (a cooler, or a heat pump with its curve alone) the
# model stays in electric equivalents (cop 1)
cop = number(params.get("cop")) or 1.0
if c.kind == "cooling" or "cop" in params:
params["cop"] = cop
r, cap = r / cop, cap * cop
gain = [g * cop for g in gain] if isinstance(gain, list) else gain * cop
solar *= cop
@@ -538,7 +730,51 @@ def _room_rc(c, params: dict, bundles, only_one: bool, now: float) -> str:
params["internal_gain_w"] = gain
if "solar_m2" not in c.params:
params["solar_m2"] = solar
return src
return src, ("electric" if rc.get("power") == "electric" else "thermal")
def room_refusal(c, st: dict, rc: str, power: str, source: str = "electric") -> dict | None:
"""Why a heating or cooling room is not planned (docs/parameters.md E3: R/C measured, power and COP the device's), or
None: no R/C (no fit, the mapping sets neither, or only one of the
two), the heater's or cooler's electric power unknown (max_power_w),
the COP unknown where the model needs it (the mapping's R/C or a fit
against the heat; an electric fit needs none), or no room temperature
now. {"why", "where", "missing": [...]} (the plan adds "fallback":
schedule | own | none). The room keeps its limits, and its thermostat
follows the owner's or installer's schedule (preferences) meanwhile,
else its own setpoint (optimizer.fallback_entries)."""
why, where, missing = [], [], []
if rc == "partial":
have = "r_k_per_kw" if "r_k_per_kw" in c.params else "c_kwh_per_k"
lack = "c_kwh_per_k" if have == "r_k_per_kw" else "r_k_per_kw"
why.append(f"the mapping sets {have} but not {lack}")
where.append("the mapping's params: both r_k_per_kw and c_kwh_per_k, or neither (the room's fit is used)")
missing.append(lack)
elif rc == "none":
why.append("no R/C fit for this room yet (no room model)")
where.append("nothing to do: the box fits the room from its measured temperature and heating (nightly, once "
"there are a few days of history); or the installer enters r_k_per_kw and c_kwh_per_k in the "
"mapping's params")
missing += ["r_k_per_kw", "c_kwh_per_k"]
# the electric power: a cooler's, and a heater's that runs on electricity (a boiler's or a heat
# station's heat is its max_heat_w: heating_refusal)
if "max_power_w" not in c.params and (c.kind == "cooling" or source in ("electric", "heat_pump", "hybrid")):
why.append(f"the {'heating' if c.kind == 'heating' else 'cooling'}'s electric power unknown")
where.append("the mapping's params (max_power_w, W)")
missing.append("max_power_w")
# a cooler's COP (a heater's: electric 1, a heat pump's or hybrid's: heating_refusal)
if c.kind == "cooling" and rc in ("mapping", "model", "box model") and power != "electric" and "cop" not in c.params:
why.append("COP unknown (heat per kWh of electricity)")
where.append("the mapping's params (cop)")
missing.append("cop")
if st.get("temp_c") is None:
why.append("room temperature unknown" + (" (no temperature sensor)" if not c.entities.get("temp") and
not c.entities.get("climate") else " (no value now)"))
where.append("map the room's temperature sensor (temp), or a thermostat that reports its temperature")
missing.append("temp")
if not why:
return None
return {"why": "; ".join(why), "where": "; ".join(where), "missing": missing}
def _quantities(c) -> list[str]: