cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1030: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-06 00:13:12 +02:00
1 parent e2c7085d2c
commit cddd34dcbc
30 files changed
+2140 -50

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@ Settings → Add-ons → Add-on store → ⋮ → Repositories, add
`https://git.setti.solutions/Daniel/cantabile-ha-addons`, then install the `https://git.setti.solutions/Daniel/cantabile-ha-addons`, then install the
add-on. The Supervisor pulls the prebuilt images add-on. The Supervisor pulls the prebuilt images
(`git.setti.solutions/daniel/cantabile-ha-<edge|modbus|eebus>-<arch>:<version>`, (`git.setti.solutions/daniel/cantabile-ha-<edge|modbus|eebus>-<arch>:<version>`,
named by `image:` in each `config.yaml`); this version: `0.1.901`, arch amd64. named by `image:` in each `config.yaml`); this version: `0.1.1030`, arch amd64.
## Layout ## Layout
+19
View File
@@ -6,6 +6,25 @@ names the commit; the agent inside is the Edge Agent image of that commit.
## 0.1.x ## 0.1.x
- Invitations: when a building or an energy community invites your home,
the add-on's page shows the invitation with three buttons: Look at it
(what joining means for you), Join and Decline. Until now an invitation
waited unseen until it expired.
- My energy costs: a new view on the Cantabile dashboard with your own
prices, what the plan saved and your monthly cost so far; where a figure
is missing (for example fixed charges), a notice at the top says what is
missing instead of a guess.
- Shades the agent closed are opened again later (in the morning, or when
the sun has left the window); before, they stayed where the agent left
them.
- A building's battery follows the building's plan when the building sends
one; your own battery is planned with the value of the energy it still
holds at the plan's end, instead of always ending at least as full as it
started.
- In a building or community with tenant power, your home plans with the
price of the building's current offer for your flat (planned with, not
billed).
- The Devices page is clearer: the devices you use with Cantabile are a - The Devices page is clearer: the devices you use with Cantabile are a
short list, each with its state in words ("In use · reading on · control short list, each with its state in words ("In use · reading on · control
on" or "Added · reading off"), its main values now ("21.5 °C, set to on" or "Added · reading off"), its main values now ("21.5 °C, set to
+1 -1
View File
@@ -3,7 +3,7 @@
# the Hub's, wrapped by addon-run (Dockerfile). The image is prebuilt, # the Hub's, wrapped by addon-run (Dockerfile). The image is prebuilt,
# per arch (README.md: building it from src/). # per arch (README.md: building it from src/).
name: Cantabile Edge Agent name: Cantabile Edge Agent
version: "0.1.901" version: "0.1.1030"
slug: cantabile_edge slug: cantabile_edge
description: Plans your home's energy with Cantabile and, with your consent, runs the devices you choose. description: Plans your home's energy with Cantabile and, with your consent, runs the devices you choose.
url: https://cantabile.cloud url: https://cantabile.cloud
+1 -1
View File
@@ -4,7 +4,7 @@
# Assistant that isn't a Cantabile Hub. Devices are paired on its page # Assistant that isn't a Cantabile Hub. Devices are paired on its page
# (ingress), by their SKI. # (ingress), by their SKI.
name: Cantabile EEBUS name: Cantabile EEBUS
version: "0.1.901" version: "0.1.1030"
slug: cantabile_eebus slug: cantabile_eebus
description: Pairs with EEBUS devices (the grid operator's control box, heat pumps, wallboxes, inverters), shows them in Home Assistant under Cantabile's names and hands the grid operator's §14a limit to the Cantabile agent; every control with its protection. description: Pairs with EEBUS devices (the grid operator's control box, heat pumps, wallboxes, inverters), shows them in Home Assistant under Cantabile's names and hands the grid operator's §14a limit to the Cantabile agent; every control with its protection.
url: https://cantabile.cloud url: https://cantabile.cloud
+1 -1
View File
@@ -4,7 +4,7 @@
# Home Assistant that isn't a Cantabile Hub. Devices come from the options; # Home Assistant that isn't a Cantabile Hub. Devices come from the options;
# the page (ingress) shows them and each control's protection. # the page (ingress) shows them and each control's protection.
name: Cantabile Modbus bridge name: Cantabile Modbus bridge
version: "0.1.901" version: "0.1.1030"
slug: cantabile_modbus slug: cantabile_modbus
description: Reads inverters, meters, relays and circuits by Cantabile's device profiles (Modbus, or Home Assistant's own entities) and shows them in Home Assistant, each control with its protection. description: Reads inverters, meters, relays and circuits by Cantabile's device profiles (Modbus, or Home Assistant's own entities) and shows them in Home Assistant, each control with its protection.
url: https://cantabile.cloud url: https://cantabile.cloud
+51 -4
View File
@@ -15,8 +15,9 @@ import logging
import os import os
import time import time
from . import areas, ha, propose, sinks, trainhist from . import areas, costs, ha, propose, sinks, trainhist
from .announce import Announcer from .announce import Announcer
from .bundles import Bundles
from .consent import Consent from .consent import Consent
from .controller import Controller from .controller import Controller
from .inventory import Inventory from .inventory import Inventory
@@ -57,6 +58,7 @@ class Agent:
self.started = 0.0 self.started = 0.0
self.clock = time.time # tests set their own self.clock = time.time # tests set their own
self.ha_language = "en" # HA's language (its config): names in HA (names.py) self.ha_language = "en" # HA's language (its config): names in HA (names.py)
self.ha_tz = "UTC" # HA's time zone (its config): the costs' months and days
self.dashboards = Dashboards(self) if cfg.dashboards else None self.dashboards = Dashboards(self) if cfg.dashboards else None
# v1: plans and actions for the mapping's controls (controller.py) # v1: plans and actions for the mapping's controls (controller.py)
self.control = Controller(cfg, mapping, self.consent, sink) if mapping.controls else None self.control = Controller(cfg, mapping, self.consent, sink) if mapping.controls else None
@@ -79,6 +81,24 @@ class Agent:
self.control.policy if self.control is not None else None) self.control.policy if self.control is not None else None)
if self.control is not None: if self.control is not None:
self.inventory.ev_phases = self.control.ev_phases self.inventory.ev_phases = self.control.ev_phases
# the household's own costs (costs.py, methods.md A12): its meters at the
# prices that applied, kept on the box, shown in HA only; with or
# without the share consent (nothing of it leaves the box)
self.costs, self.cost_agg = None, None
if getattr(cfg, "costs", True):
try:
ctl = self.control
self.costs = costs.Ledger(cfg.state_dir, ctl.bundles if ctl is not None else
Bundles(cfg.state_dir, cfg.site_id),
mode=ctl.mode if ctl is not None else (lambda: None),
tz=lambda: self.ha_tz)
self.cost_agg = Aggregator(cfg.interval_s)
if ctl is not None:
ctl.on_plan.append(self._cost_plan)
except Exception as e: # never keeps the agent from running
log.warning("costs: not kept: %s", e)
self.costs, self.cost_agg = None, None
self._cost_pruned = 0.0
self.client = None self.client = None
self.exit_code = 0 # RESTART: start again (restart()) self.exit_code = 0 # RESTART: start again (restart())
# A mapping for a site without one (propose.py): the HA add-on # A mapping for a site without one (propose.py): the HA add-on
@@ -177,15 +197,24 @@ class Agent:
return await q() return await q()
return self.last_sent > 0 return self.last_sent > 0
async def _cost_plan(self, plan):
"""A new plan: its estimate for the quarter-hour under way (costs.py)."""
try:
self.costs.take_plan(plan)
except Exception as e:
log.warning("costs: the plan's estimate: %s", e)
def sample(self, entity_id: str, state: str | None, ts: float): def sample(self, entity_id: str, state: str | None, ts: float):
share = self.consent.share # without it nothing is collected to send share = self.consent.share # without it nothing is collected to send
local = self.train_agg is not None local = self.train_agg is not None
if not share and not local: cost = self.cost_agg is not None
if not share and not local and not cost:
return # the owner has not (or no longer) agreed return # the owner has not (or no longer) agreed
for a in self.mapping.of_entity.get(entity_id, []): for a in self.mapping.of_entity.get(entity_id, []):
up = share and a.consent # to the cloud: the site's and the asset's consent up = share and a.consent # to the cloud: the site's and the asset's consent
mine = local and trainhist.wanted(a.asset) # the box's own training: never leaves the box mine = local and trainhist.wanted(a.asset) # the box's own training: never leaves the box
if not (up or mine): costs_ = cost and costs.wanted(a.asset) # the household's costs: never leave the box
if not (up or mine or costs_):
continue continue
raw = value_of(a, state, self.attrs.get(entity_id)) raw = value_of(a, state, self.attrs.get(entity_id))
v = number(raw) v = number(raw)
@@ -195,6 +224,8 @@ class Agent:
v = scaled(convert(v, unit, a.unit), a) v = scaled(convert(v, unit, a.unit), a)
if v is None: if v is None:
log.warning("%s: unit %s cannot become %s; value dropped", a.asset, unit, a.unit) log.warning("%s: unit %s cannot become %s; value dropped", a.asset, unit, a.unit)
if costs_:
self.cost_agg.sample(a.asset, a.kind, v, ts)
total = self.mapping.part_total.get(a.asset) total = self.mapping.part_total.get(a.asset)
if up: if up:
self.agg.sample(a.asset, a.kind, v, ts) self.agg.sample(a.asset, a.kind, v, ts)
@@ -245,7 +276,9 @@ class Agent:
async def on_connect(self, client: ha.HAClient): async def on_connect(self, client: ha.HAClient):
try: try:
self.ha_language = (await client.send("get_config") or {}).get("language") or "en" hc = await client.send("get_config") or {}
self.ha_language = hc.get("language") or "en"
self.ha_tz = hc.get("time_zone") or self.ha_tz
except Exception as e: except Exception as e:
log.info("get_config: %s", e) log.info("get_config: %s", e)
try: try:
@@ -256,6 +289,8 @@ class Agent:
if self.train_agg is not None: # and the box's own training's (never sent: sample()) if self.train_agg is not None: # and the box's own training's (never sent: sample())
ids = list(dict.fromkeys(ids + [a.entity for a in self.mapping.assets if trainhist.wanted(a.asset) ids = list(dict.fromkeys(ids + [a.entity for a in self.mapping.assets if trainhist.wanted(a.asset)
or trainhist.wanted(self.mapping.part_total.get(a.asset, ""))])) or trainhist.wanted(self.mapping.part_total.get(a.asset, ""))]))
if self.cost_agg is not None: # the household's costs' meters (never sent: sample())
ids = list(dict.fromkeys(ids + [a.entity for a in self.mapping.assets if costs.wanted(a.asset)]))
await client.subscribe_entities(ids, self.on_entities) await client.subscribe_entities(ids, self.on_entities)
log.info("subscribed to %d consented entities (mapping v%d)", len(ids), self.mapping.version) log.info("subscribed to %d consented entities (mapping v%d)", len(ids), self.mapping.version)
if self.control is not None: if self.control is not None:
@@ -292,6 +327,16 @@ class Agent:
self.control.boxml.store.add_window(tstart, trecs) self.control.boxml.store.add_window(tstart, trecs)
except Exception as e: except Exception as e:
log.warning("training history: %s", e) log.warning("training history: %s", e)
if self.cost_agg is not None:
cstart, crecs = self.cost_agg.start, self.cost_agg.flush(end)
try: # the household's costs (costs.py): kept on the box, shown in HA
if crecs:
self.costs.add_window(cstart, end, crecs)
if end - self._cost_pruned > 86400:
self.costs.prune(end)
self._cost_pruned = end
except Exception as e:
log.warning("costs: %s", e)
if not records: if not records:
return return
seq = self.queue.put("tel", { seq = self.queue.put("tel", {
@@ -363,6 +408,8 @@ class Agent:
self.agg.begin(self.started) self.agg.begin(self.started)
if self.train_agg is not None: if self.train_agg is not None:
self.train_agg.begin(self.started) self.train_agg.begin(self.started)
if self.cost_agg is not None:
self.cost_agg.begin(self.started)
if self.cfg.mode == "off": if self.cfg.mode == "off":
log.info("mode off: not reading Home Assistant") log.info("mode off: not reading Home Assistant")
await self.stop.wait() await self.stop.wait()
+99
View File
@@ -19,6 +19,15 @@ building and the home, and what the agent does to each device):
sensor price_import_now, price_import_next, price_export_now, price_<carrier> sensor price_import_now, price_import_next, price_export_now, price_<carrier>
the tariff in force, its 48 h curve as attributes the tariff in force, its 48 h curve as attributes
sensor model the forecast model (source, issued, expires) sensor model the forecast model (source, issued, expires)
sensor costs, costs_prices, cost_<carrier>, saving_<carrier>
the household's own costs (costs.py): the gaps
(missing data and why: the dashboard's alarm box)
and the month's tables; the price's source now
and today's and tomorrow's prices per hour; this
month's cost so far (forecast, last month as
attributes); this month's savings (the building's
offer vs the own supplier, the plan's; saved or
would-have in shadow)
event commands each command or bundle received: mode, control, event commands each command or bundle received: mode, control,
release, limits, tariff, model, building; who release, limits, tariff, model, building; who
sent it (cloud, building, grid), its arguments sent it (cloud, building, grid), its arguments
@@ -64,11 +73,13 @@ On the Cantabile Hub the broker is Mosquitto on the box (127.0.0.1:1883, with
the agent's own user: hub mqtt-users); without a broker this does nothing. the agent's own user: hub mqtt-users); without a broker this does nothing.
""" """
import asyncio import asyncio
import html
import time import time
import json import json
import logging import logging
import re import re
from . import costs as costs_mod
from . import gridorder from . import gridorder
from . import __version__ from . import __version__
from . import names, shades from . import names, shades
@@ -603,6 +614,87 @@ class Announcer:
return {"kind": "boost", "control": cid, "c": p.ha.get(f"boost_c:{cid}", default), return {"kind": "boost", "control": cid, "c": p.ha.get(f"boost_c:{cid}", default),
"hours": p.ha.get(f"boost_h:{cid}", 2.0)} "hours": p.ha.get(f"boost_h:{cid}", 2.0)}
# -- the household's costs (costs.py) ---------------------------------------
def costs_report(self, now: float | None = None) -> dict | None:
"""The costs view's figures (costs.report), at most once a minute;
None without a ledger. A failure is logged and gives None (the
dashboard then says the figures are not available)."""
ledger = getattr(self.agent, "costs", None)
if ledger is None:
return None
now = time.time() if now is None else now
cached = getattr(self, "_costs_cache", None)
if cached is not None and now - cached[0] < costs_mod.REPORT_EVERY_S and cached[2] == self.lang:
return cached[1]
try:
meters = costs_mod.meters_of(self.agent.mapping)
ctl = getattr(self.agent, "control", None)
rep = costs_mod.report(ledger, now, self.lang, meters, ctl is not None and bool(ctl.controls))
except Exception as e:
log.warning("costs: %s", e)
rep = None
self._costs_cache = (now, rep, self.lang)
return rep
def _cost_objects(self) -> dict:
"""sensor costs (the gaps: the alarm box; the tables), costs_prices
(the source of the price now; today's and tomorrow's prices),
cost_<carrier> (€ this month so far), saving_<carrier> (€ this
month: the offer's and the plan's, saved or would-have)."""
rep = self.costs_report()
if rep is None:
return {}
dev, topic = self._device(), f"{self.base}/costs"
common = {"state_topic": topic, "json_attributes_topic": topic, **self._avail(), "device": dev}
out = {("sensor", "costs"): {"name": names.name("costs_status", self.lang), "unique_id": f"{self.uid}_costs",
"icon": "mdi:cash-multiple", "value_template": "{{ value_json.status.n }}",
"json_attributes_template": "{{ value_json.status | tojson }}", **common},
("sensor", "costs_prices"): {"name": names.name("costs_prices", self.lang),
"unique_id": f"{self.uid}_costs_prices", "icon": "mdi:cash-clock",
"value_template": "{{ value_json.prices.source }}",
"json_attributes_template": "{{ value_json.prices | tojson }}", **common}}
money = {"unit_of_measurement": "EUR", "device_class": "monetary", "state_class": "total",
"suggested_display_precision": 2}
for c in (rep.get("costs") or {}).get("carriers") or {}:
label = names.name("carrier_" + c, self.lang)
out[("sensor", f"cost_{c}")] = {
"name": names.name("cost_of", self.lang, label), "unique_id": f"{self.uid}_cost_{c}", "icon": "mdi:cash",
"value_template": "{{ value_json.cost['%s'].so_far }}" % c,
"json_attributes_template": "{{ value_json.cost['%s'] | tojson }}" % c, **money, **common}
out[("sensor", f"saving_{c}")] = {
"name": names.name("saving_of", self.lang, label), "unique_id": f"{self.uid}_saving_{c}",
"icon": "mdi:piggy-bank-outline", "value_template": "{{ value_json.saving['%s'].total }}" % c,
"json_attributes_template": "{{ value_json.saving['%s'] | tojson }}" % c,
**{k: v for k, v in money.items() if k != "state_class"}, **common}
return out
def costs_state(self, rep: dict) -> dict:
"""The costs topic's payload (one JSON for the costs' sensors)."""
pr = rep.get("prices") or {}
days = {d["key"]: d for d in pr.get("days") or []}
sp = self.bundles.slot_prices(time.time())
el = (sp or {}).get("electricity") or {}
source = None if el.get("price") is None else "offer" if el.get("offer") else "own"
status = {"n": len(rep["gaps"]), "gaps": rep["gaps"], "md": rep.get("md_gaps", ""),
"alert": "<br>".join(f"<b>{html.escape(names.name('cs_' + g['section'], self.lang))}</b>: "
f"{html.escape(g['why'])}" for g in rep["gaps"]),
"md_costs": (rep.get("costs") or {}).get("md"), "md_savings": (rep.get("savings") or {}).get("md"),
"month": (rep.get("costs") or {}).get("month"), "made": rep.get("made")}
prices = {"source": source, "now_md": pr.get("now_md"), "today_md": (days.get("today") or {}).get("md"),
"tomorrow_md": (days.get("tomorrow") or {}).get("md"), "tenant": pr.get("tenant"),
"today": (days.get("today") or {}).get("hours"), "tomorrow": (days.get("tomorrow") or {}).get("hours")}
cost, saving = {}, {}
for c, r in ((rep.get("costs") or {}).get("carriers") or {}).items():
cost[c] = r
for c, r in ((rep.get("savings") or {}).get("carriers") or {}).items():
off, plan = r.get("offer") or {}, r.get("plan") or {}
vals = [v for v in (off.get("month"), plan.get("saved"), plan.get("would")) if v is not None]
saving[c] = dict(r, total=round(sum(vals), 2) if vals else None,
shadow=bool((off and not off.get("billed")) or plan.get("would")))
for c in cost:
saving.setdefault(c, {"total": None})
return {"status": status, "prices": prices, "cost": cost, "saving": saving}
def objects(self) -> dict: def objects(self) -> dict:
"""Every discovery config HA should have now: (node, component, """Every discovery config HA should have now: (node, component,
object) -> config; node is the site's or a flat's.""" object) -> config; node is the site's or a flat's."""
@@ -611,6 +703,7 @@ class Announcer:
out = {} out = {}
for (comp, obj), conf in {**self._configs(), **self._plan_objects(), for (comp, obj), conf in {**self._configs(), **self._plan_objects(),
**self._exchange_objects(tariff, model), **self._prefs_objects(), **self._exchange_objects(tariff, model), **self._prefs_objects(),
**self._cost_objects(),
**self._market_objects(self.bundles.market_now(now))}.items(): **self._market_objects(self.bundles.market_now(now))}.items():
out[(self.uid, comp, obj)] = conf out[(self.uid, comp, obj)] = conf
out.update(self._flat_objects(self.bundles.flat_list())) out.update(self._flat_objects(self.bundles.flat_list()))
@@ -712,6 +805,12 @@ class Announcer:
if ctl is not None and ctl.received: if ctl is not None and ctl.received:
# kept (retained) across restarts until new ones come # kept (retained) across restarts until new ones come
await c.publish(f"{self.base}/received", json.dumps({"commands": self.received_list(ctl)}), retain=True) await c.publish(f"{self.base}/received", json.dumps({"commands": self.received_list(ctl)}), retain=True)
rep = self.costs_report(now)
if rep is not None:
try:
await c.publish(f"{self.base}/costs", json.dumps(self.costs_state(rep), default=str), retain=True)
except (TypeError, ValueError, KeyError) as e:
log.warning("costs: not shown: %s", e)
market = self.bundles.market_now(now) market = self.bundles.market_now(now)
if market is not None: if market is not None:
await c.publish(f"{self.base}/market/availability", "offline" if market["stale"] else "online", retain=True) await c.publish(f"{self.base}/market/availability", "offline" if market["stale"] else "online", retain=True)
+66 -7
View File
@@ -4,13 +4,25 @@
like every command) with string args: like every command) with string args:
{"v": "1", "id", "building", "level": "flexible|binding", {"v": "1", "id", "building", "level": "flexible|binding",
"control": "load_limit|shift_request|thermostat_cap", "value", "control": "load_limit|shift_request|thermostat_cap|battery_plan",
"from": unix, "until": unix (<= from + 24 h), "why"} "value", "from": unix, "until": unix (<= from + 24 h), "why"}
load_limit the flat's highest grid import, W, in [from, until) load_limit the flat's highest grid import, W, in [from, until)
shift_request kWh the flat is asked to move out of [from, until): the shift_request kWh the flat is asked to move out of [from, until): the
optimiser decides how and where (a soft target) optimiser decides how and where (a soft target)
thermostat_cap the highest heating setpoint, °C (cooling: the lowest) thermostat_cap the highest heating setpoint, °C (cooling: the lowest)
battery_plan the building's one plan for its battery (2026-11-05: the
coordinator plans the building's battery; the building's
own box follows it instead of planning it again at its
own tariff). Two more args: "schedule": "w0,w1,..." the
battery's grid-side power per step from `from`, W
(+ charge, - discharge), exactly (until - from) / step_s
values, each finite and |w| <= 1e6; "step_s": "900" (only
900). "value" is the first slot's W. Never an emergency.
The plan tracks it at a price per kWh of deviation: above
any electricity price, far below the owner's floors and
the battery's SoC bounds, which win (optimizer.py
Model.battery_plan). Kept with its schedule.
Rules: always within the flat's own floors (a cap below the comfort floor Rules: always within the flat's own floors (a cap below the comfort floor
of the owner or the tenant is refused: "floor"); a newer command for the of the owner or the tenant is refused: "floor"); a newer command for the
@@ -33,17 +45,23 @@ hard, flexible with a price) and a soft target (a shift). Results go out as
"building.<control>". "building.<control>".
""" """
import json import json
import math
import os import os
import time import time
CONTROLS = ("load_limit", "shift_request", "thermostat_cap") CONTROLS = ("load_limit", "shift_request", "thermostat_cap", "battery_plan")
PENALTY = { # EUR per unit across a building's request in the plan PENALTY = { # EUR per unit across a building's request in the plan
"binding": {"load_limit": 50.0, "shift_request": 5.0, "thermostat_cap": 50.0}, # per kWh, per kWh, per K·h # per kWh, per kWh, per K·h; battery_plan per kWh of the battery's deviation from the building's
"flexible": {"load_limit": 1.0, "shift_request": 0.5, "thermostat_cap": 2.0}, # plan: above any electricity price (the box follows rather than re-plans at its own price), far
# below the owner's floors (optimizer.PENALTY_LIMIT, 5 EUR per % of capacity and step)
"binding": {"load_limit": 50.0, "shift_request": 5.0, "thermostat_cap": 50.0, "battery_plan": 5.0},
"flexible": {"load_limit": 1.0, "shift_request": 0.5, "thermostat_cap": 2.0, "battery_plan": 0.5},
# a grid operator's order relayed by the building (§14a), with proof the # a grid operator's order relayed by the building (§14a), with proof the
# link checked (edge/link/gridorder.go): nobody overrides it # link checked (edge/link/gridorder.go): nobody overrides it; never a battery_plan
"emergency": {"load_limit": 500.0, "shift_request": 50.0, "thermostat_cap": 500.0}, "emergency": {"load_limit": 500.0, "shift_request": 50.0, "thermostat_cap": 500.0},
} }
SCHEDULE_STEP_S = 900 # a battery_plan's step: the plans' 15 minutes
SCHEDULE_MAX_W = 1e6 # |W| per step at most: a sanity bound on the numbers, not a battery's rating
class Building: class Building:
@@ -94,6 +112,8 @@ class Building:
raise ValueError("building: v 1 only") raise ValueError("building: v 1 only")
if c["level"] not in ("flexible", "binding", "emergency"): if c["level"] not in ("flexible", "binding", "emergency"):
raise ValueError("building: level flexible, binding or emergency") raise ValueError("building: level flexible, binding or emergency")
if c["control"] == "battery_plan" and c["level"] == "emergency":
raise ValueError("building: a battery_plan is flexible or binding, never an emergency")
if c["level"] == "emergency" and not (c["proof"].startswith("verified:") and c["control"] == "load_limit"): if c["level"] == "emergency" and not (c["proof"].startswith("verified:") and c["control"] == "load_limit"):
# only a grid operator's order the link verified (2026-10-29) # only a grid operator's order the link verified (2026-10-29)
raise ValueError("building: an emergency needs the grid operator's verified proof (a relayed load_limit)") raise ValueError("building: an emergency needs the grid operator's verified proof (a relayed load_limit)")
@@ -103,8 +123,32 @@ class Building:
raise ValueError("building: from < until <= from + 24 h") raise ValueError("building: from < until <= from + 24 h")
if c["control"] in ("load_limit", "shift_request") and c["value"] < 0: if c["control"] in ("load_limit", "shift_request") and c["value"] < 0:
raise ValueError(f"building: {c['control']} must not be negative") raise ValueError(f"building: {c['control']} must not be negative")
if c["control"] == "battery_plan":
c["step_s"], c["schedule"] = Building.schedule(a, c["from"], c["until"])
return c return c
@staticmethod
def schedule(a: dict, frm: int, until: int) -> tuple[int, list[float]]:
"""A battery_plan's step and its W per step from `from`."""
try:
step = int(str(a.get("step_s", "")).strip())
except ValueError:
step = 0
if step != SCHEDULE_STEP_S:
raise ValueError(f"building: battery_plan step_s {SCHEDULE_STEP_S}")
raw = a.get("schedule")
try:
ws = [float(w) for w in (raw.split(",") if isinstance(raw, str) else raw)]
except (AttributeError, TypeError, ValueError):
raise ValueError('building: battery_plan schedule "w0,w1,..." (W per step)')
n, rest = divmod(until - frm, step)
if rest or len(ws) != n:
raise ValueError(f"building: battery_plan schedule has {len(ws)} values, "
f"(until - from) / step_s is {(until - frm) / step:g}")
if not all(math.isfinite(w) and abs(w) <= SCHEDULE_MAX_W for w in ws):
raise ValueError("building: battery_plan schedule: every value finite, |w| <= 1e6 W")
return step, ws
def take(self, c: dict, floors: list[tuple[str, float, float, str]]) -> tuple[bool, str]: def take(self, c: dict, floors: list[tuple[str, float, float, str]]) -> tuple[bool, str]:
"""A parsed command. floors: (control id, the flat's floor, the """A parsed command. floors: (control id, the flat's floor, the
flat's limit, kind) of each heating/cooling room, for the cap.""" flat's limit, kind) of each heating/cooling room, for the cap."""
@@ -131,10 +175,25 @@ class Building:
self._save() self._save()
def for_model(self, start: int, step_s: int, steps: int) -> dict: def for_model(self, start: int, step_s: int, steps: int) -> dict:
"""The requests as the optimiser takes them: per step, or a window.""" """The requests as the optimiser takes them: per step, or a window.
A battery_plan per model step (the slot at the step's middle; the
model may start after `from`: past slots skipped), None where the
command doesn't cover the step; from_step/to_step its covered span."""
self.drop_ended() self.drop_ended()
out = {} out = {}
for ctl, c in self.active.items(): for ctl, c in self.active.items():
if ctl == "battery_plan":
ws, k_s = c.get("schedule") or [], int(c.get("step_s") or SCHEDULE_STEP_S)
sched = []
for t in range(steps):
k = (start + t * step_s + step_s // 2 - c["from"]) // k_s
sched.append(float(ws[k]) if 0 <= k < len(ws) else None)
covered = [t for t, w in enumerate(sched) if w is not None]
if covered:
out[ctl] = {"schedule_w": sched, "from_step": covered[0], "to_step": covered[-1] + 1,
"penalty": PENALTY[c["level"]][ctl], "level": c["level"], "id": c["id"],
"building": c["building"]}
continue
a = max(0, (c["from"] - start) // step_s) a = max(0, (c["from"] - start) // step_s)
b = min(steps, -(-(c["until"] - start) // step_s)) b = min(steps, -(-(c["until"] - start) // step_s))
if a >= b: if a >= b:
+102
View File
@@ -253,6 +253,29 @@ def no_tariff_note(reason: str, tariff_id: str = "", expired_at: int = 0) -> str
return f"{NO_TARIFF} ({NO_TARIFF_WHY.get(reason, reason).format(id=tariff_id, at=at)})" return f"{NO_TARIFF} ({NO_TARIFF_WHY.get(reason, reason).format(id=tariff_id, at=at)})"
TENANT_MODEL = {"mieterstrom": "Mieterstrom", "ggv": "GGV", "sharing": "Energy Sharing"}
def tenant_info(t: dict) -> dict | None:
"""The bundle's "tenant" (fleet tenantprice.go, 2026-11-05): its import
price is a building's or community's tenant price (Mieterstrom, GGV,
Energy Sharing), shadow: planned with and shown, not billed. None
without one (or not a table). The price itself is in "import" as it is;
this only says where it comes from."""
m = t.get("tenant")
if not isinstance(m, dict) or m.get("model") not in TENANT_MODEL:
return None
return {k: m.get(k) for k in ("model", "plant", "name", "shadow", "billed", "schema", "proposal", "made_at",
"valid_until", "steps")}
def tenant_note(m: dict | None) -> str:
if not m:
return ""
state = "shadow: planned with, not billed" if not m.get("billed") else "billed"
return f"; tenant price: {TENANT_MODEL[m['model']]} {m.get('name') or m.get('plant') or ''} ({state})".replace(" ", " ")
def _ahead_terms(ah, start: int, step_s: int, steps: int, terms) -> list | None: def _ahead_terms(ah, start: int, step_s: int, steps: int, terms) -> list | None:
"""A contract's coming slots (fleet marketbundle.go "ahead": windows of """A contract's coming slots (fleet marketbundle.go "ahead": windows of
slot indices with their amounts, the price as [count, ct] runs) as the slot indices with their amounts, the price as [count, ct] runs) as the
@@ -339,6 +362,7 @@ class Bundles:
est = len([x for x in t.get("estimated") or [] if isinstance(x, int)]) est = len([x for x in t.get("estimated") or [] if isinstance(x, int)])
if est: if est:
note += f"; {est} steps estimated by the platform" note += f"; {est} steps estimated by the platform"
note += tenant_note(tenant_info(t))
return Prices(out_i, out_e, note, "tariff", "", tid, exp, n) return Prices(out_i, out_e, note, "tariff", "", tid, exp, n)
def carrier_prices(self, carrier: str, start: int, step_s: int, steps: int, now: float) -> list: def carrier_prices(self, carrier: str, start: int, step_s: int, steps: int, now: float) -> list:
@@ -366,6 +390,80 @@ class Bundles:
p = t.get("params") p = t.get("params")
return {k: v for k, v in p.items() if isinstance(k, str)} if isinstance(p, dict) else {} return {k: v for k, v in p.items() if isinstance(k, str)} if isinstance(p, dict) else {}
def _valid(self, now: float) -> dict | None:
t = self.tariff.get()
if t is None or t.get("site") not in (self.site, None, "") or now >= int(t.get("expires", 0) or 0):
return None
return t
def slot_prices(self, ts: float, now: float | None = None) -> dict | None:
"""The prices of the quarter-hour at ts as the bundle in force now
says (the household's costs, costs.py): per carrier {price (ct/kWh
gross, None: none), own (the own supplier's: the tenant block's
own_import where a tenant price is in the bundle, else the price
itself), offer (the slot is priced by the building's or community's
offer), billed (that price is billed; shadow: false)}. A slot is the
offer's where the bundle's "tenant" has a per-slot "slots" list
saying so ("offer"), else where its price differs from own_import
(fleet tenantTariff keeps the own price where there is no offer).
None: no valid bundle for this site, or ts outside it."""
t = self._valid(time.time() if now is None else now)
if t is None:
return None
i = int((ts - t["start"]) // 900)
if i < 0 or ts >= int(t.get("expires", 0) or 0):
return None
def at(v):
return v[i] if isinstance(v, list) and 0 <= i < len(v) and _finite(v[i]) else None
imp = at(t.get("import"))
ten = t.get("tenant") if isinstance(t.get("tenant"), dict) and tenant_info(t) else None
el = {"price": imp, "own": imp, "offer": False, "billed": True}
if ten is not None:
own = at(ten.get("own_import"))
slots = ten.get("slots")
el["own"] = own
if isinstance(slots, list):
el["offer"] = 0 <= i < len(slots) and slots[i] == "offer"
else:
el["offer"] = imp is not None and own is not None and abs(imp - own) > 1e-6
if not el["offer"] and own is None:
el["own"] = imp
el["billed"] = bool(ten.get("billed"))
out = {"electricity": el}
for c in ("gas", "heat"):
p = at(t.get(c))
if p is not None:
out[c] = {"price": p, "own": p, "offer": False, "billed": True}
return out
def tenant_now(self, now: float) -> dict | None:
"""The tenant price's source in the bundle in force (tenant_info),
with own_known: whether it carries the own supplier's curve."""
t = self._valid(now)
m = tenant_info(t) if t is not None else None
if m is None:
return None
own = (t.get("tenant") or {}).get("own_import")
return dict(m, own_known=isinstance(own, list) and any(_finite(x) for x in own))
def fixed_charges(self, now: float) -> dict | None:
"""The fixed charges per carrier the bundle carries (optional
"fixed": {"electricity": {"eur_month": gross €/month, "incomplete":
bool, "missing": [...]}, "gas": {...}}; fleet fixedcharges.go
composes them, not yet sent). None: the
bundle has none (or no valid bundle)."""
t = self._valid(now)
f = t.get("fixed") if t is not None else None
if not isinstance(f, dict):
return None
out = {}
for c, v in f.items():
if isinstance(v, dict) and _finite(v.get("eur_month")) and v["eur_month"] >= 0:
out[c] = {"eur_month": float(v["eur_month"]), "incomplete": bool(v.get("incomplete")),
"missing": [str(x) for x in v.get("missing") or []][:10]}
return out
def tariff_now(self, now: float) -> dict | None: def tariff_now(self, now: float) -> dict | None:
"""The tariff in force for HA: import now and next step, export now, """The tariff in force for HA: import now and next step, export now,
the curves and where they come from; None without one (or expired).""" the curves and where they come from; None without one (or expired)."""
@@ -379,6 +477,10 @@ class Bundles:
return v[k] if 0 <= k < len(v) else None return v[k] if 0 <= k < len(v) else None
return {"import_now": at(imp, i), "import_next": at(imp, i + 1), "export_now": at(exp, i), return {"import_now": at(imp, i), "import_next": at(imp, i + 1), "export_now": at(exp, i),
"other": dict(t.get("other") or {}), "currency": t.get("currency") or "EUR", "other": dict(t.get("other") or {}), "currency": t.get("currency") or "EUR",
# a tenant price (Mieterstrom, GGV, §42c; shadow: not billed): where it comes from, and the
# own supplier's price now, the reference the tenant's saving is measured against
"tenant": tenant_info(t), "own_import_now": at((t.get("tenant") or {}).get("own_import") or []
if isinstance(t.get("tenant"), dict) else [], i),
"curve": {"id": t.get("id"), "start": t["start"], "step_s": t["step_s"], "import": imp, "curve": {"id": t.get("id"), "start": t["start"], "step_s": t["step_s"], "import": imp,
"export": exp, "estimated": t.get("estimated") or [], "sources": t.get("sources") or [], "export": exp, "estimated": t.get("estimated") or [], "sources": t.get("sources") or [],
"issued": t.get("issued"), "expires": t.get("expires"), "unit": t.get("unit", "ct/kWh")}} "issued": t.get("issued"), "expires": t.get("expires"), "unit": t.get("unit", "ct/kWh")}}
+13 -2
View File
@@ -36,12 +36,23 @@ def _logging():
logging.getLogger("websockets").setLevel(logging.WARNING) logging.getLogger("websockets").setLevel(logging.WARNING)
def mode_words(a, cfg) -> str:
"""The mode in force and where it comes from: the console's (kept in
the state dir's mode.json) wins over the configuration's off|shadow
(2026-11-05: "mode shadow" logged on a box acting in auto)."""
m = getattr(a, "control", None)
if cfg.mode == "off" or m is None:
why = "from the configuration" + ("" if m is not None or cfg.mode == "off" else "; no controls in the mapping")
return f"mode {cfg.mode} ({why})"
return f"mode {m.mode()} ({m.mode.source()})"
async def _run(cfg): async def _run(cfg):
a = agent.build(cfg) a = agent.build(cfg)
loop = asyncio.get_running_loop() loop = asyncio.get_running_loop()
for s in (signal.SIGTERM, signal.SIGINT): for s in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(s, a.stop.set) loop.add_signal_handler(s, a.stop.set)
logging.info("cantabile-edge %s site %s mode %s", __version__, cfg.site_id, cfg.mode) logging.info("cantabile-edge %s site %s %s", __version__, cfg.site_id, mode_words(a, cfg))
await a.run() await a.run()
return a.exit_code return a.exit_code
@@ -80,7 +91,7 @@ def main():
p = argparse.ArgumentParser(prog="cantabile-edge") p = argparse.ArgumentParser(prog="cantabile-edge")
p.add_argument("--config", "-c", help="YAML config file") p.add_argument("--config", "-c", help="YAML config file")
sub = p.add_subparsers(dest="cmd", required=True) sub = p.add_subparsers(dest="cmd", required=True)
sub.add_parser("run", help="read HA, aggregate, send (shadow mode: never acts)") sub.add_parser("run", help="read HA, aggregate, send; plan and act (acts only in auto, set from the console)")
sub.add_parser("suggest-mapping", help="print a mapping draft from HA's entities") sub.add_parser("suggest-mapping", help="print a mapping draft from HA's entities")
b = sub.add_parser("backfill", help="send HA's long-term statistics") b = sub.add_parser("backfill", help="send HA's long-term statistics")
b.add_argument("--since", required=True, help="ISO date/time or e.g. 30d") b.add_argument("--since", required=True, help="ISO date/time or e.g. 30d")
+1
View File
@@ -40,6 +40,7 @@ class Config:
mqtt_password: str = field(default="", repr=False) mqtt_password: str = field(default="", repr=False)
mqtt_password_file: str = "" # read at each connection (it may come later) mqtt_password_file: str = "" # read at each connection (it may come later)
dashboards: bool = True # Cantabile's dashboards in HA (dashboards.py) dashboards: bool = True # Cantabile's dashboards in HA (dashboards.py)
costs: bool = True # the household's own costs, kept on the box (costs.py)
# The Building page for HA's ingress (joinpage.py): HA add-on sites only # The Building page for HA's ingress (joinpage.py): HA add-on sites only
# (the Hub's panel has its own); 0 = off. On by default in an add-on. # (the Hub's panel has its own); 0 = off. On by default in an add-on.
join_page_port: int = 0 join_page_port: int = 0
+31 -5
View File
@@ -23,7 +23,10 @@ Commands (from the console through the link, which checked the signature):
limits {"asset", "quantity", "level": "cloud|building|grid", limits {"asset", "quantity", "level": "cloud|building|grid",
"floor"?, "limit"? (empty: none), "until"?} "floor"?, "limit"? (empty: none), "until"?}
building {"v", "id", "building", "level", "control", "value", "from", building {"v", "id", "building", "level", "control", "value", "from",
"until", "why"}: the building's requests (building.py) "until", "why"}: the building's requests (building.py:
load_limit, shift_request, thermostat_cap, battery_plan; a
battery_plan also "schedule": "w0,w1,..." W per step and
"step_s": "900", the building's plan its battery follows)
preferences {"msg": JSON of preferences.apply_msg's {"set": {"item", preferences {"msg": JSON of preferences.apply_msg's {"set": {"item",
"value"}}, "level": "installer|operator", "by"}: an installer's or "value"}}, "level": "installer|operator", "by"}: an installer's or
Cantabile's setting within the owner's limits (preferences.py); Cantabile's setting within the owner's limits (preferences.py);
@@ -44,7 +47,7 @@ import time
from . import inputs as inputs_mod from . import inputs as inputs_mod
from .building import Building from .building import Building
from .bundles import Bundles from .bundles import Bundles
from . import steady from . import shades, steady
from .evphases import EvPhases from .evphases import EvPhases
from .executor import Executor, building_msg from .executor import Executor, building_msg
from .gridorder import GridOrders from .gridorder import GridOrders
@@ -63,19 +66,33 @@ MODES = ("off", "shadow", "advisory", "auto")
class Mode: class Mode:
def __init__(self, state_dir: str, default: str): def __init__(self, state_dir: str, default: str):
self.path, self.default = os.path.join(state_dir, "mode.json"), default self.path, self.default = os.path.join(state_dir, "mode.json"), default
self.at, self.by = None, "" # when and by whom the kept mode was set
try: try:
with open(self.path) as f: with open(self.path) as f:
m = json.load(f).get("mode") d = json.load(f)
m = d.get("mode")
self.current = m if m in MODES else default self.current = m if m in MODES else default
if m in MODES:
self.at, self.by = d.get("at"), str(d.get("by") or "")
except (OSError, ValueError, AttributeError): except (OSError, ValueError, AttributeError):
self.current = default self.current = default
def set(self, mode: str, by: str): def set(self, mode: str, by: str):
tmp = self.path + ".tmp" tmp = self.path + ".tmp"
now = int(time.time())
with open(tmp, "w") as f: with open(tmp, "w") as f:
json.dump({"mode": mode, "at": int(time.time()), "by": by}, f) json.dump({"mode": mode, "at": now, "by": by}, f)
os.replace(tmp, self.path) os.replace(tmp, self.path)
self.current = mode self.current, self.at, self.by = mode, now, by
def source(self) -> str:
"""Where the mode in force comes from, in words (the startup log):
the console's command kept in mode.json, or the configuration."""
if self.at is None:
return "from the configuration"
when = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(self.at)) if isinstance(self.at, (int, float)) else "?"
cfg = f"; the configuration says {self.default}" if self.default != self.current else ""
return f"set by {self.by or 'the console'} at {when}, kept in {self.path}{cfg}"
def __call__(self) -> str: def __call__(self) -> str:
return self.current return self.current
@@ -107,6 +124,7 @@ class Controller:
self.building = Building(cfg.state_dir, clock) self.building = Building(cfg.state_dir, clock)
self.executor = Executor(self.controls, self.guard, self.col, self._publish, stale_s=cfg.plan_stale_s, self.executor = Executor(self.controls, self.guard, self.col, self._publish, stale_s=cfg.plan_stale_s,
clock=clock, building=self.building) clock=clock, building=self.building)
self.executor.shade_moves = shades.Moves(cfg.state_dir) # what each shade was last moved for
self.col.observers.append(self._observe) self.col.observers.append(self._observe)
self.client = None self.client = None
self.tz = "UTC" self.tz = "UTC"
@@ -204,6 +222,12 @@ class Controller:
ctx["temp_c"] = self._asset_value(ta) ctx["temp_c"] = self._asset_value(ta)
if ctx.get("setpoint_c") is None: if ctx.get("setpoint_c") is None:
ctx["setpoint_c"] = self._asset_value(sa) ctx["setpoint_c"] = self._asset_value(sa)
# what the agent last moved it for, while it is still there (shades.Moves)
moves = getattr(self.executor, "shade_moves", None)
if moves is not None and "cover" in c.entities:
ours = moves.ours(c.id, inputs_mod.cover_position(self.col, c.entities["cover"]))
if ours:
ctx["ours"] = ours
out[c.id] = ctx out[c.id] = ctx
return out return out
@@ -353,6 +377,8 @@ class Controller:
# without a tariff: priced false, cost and baseline null (U1); controls not # without a tariff: priced false, cost and baseline null (U1); controls not
# planned and why (U2); absent from older agents # planned and why (U2); absent from older agents
"priced": plan.get("priced", True), "refused": plan.get("refused", {}), "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", []),
"sources": plan.get("sources", {}), "sources": plan.get("sources", {}),
# for the building (shed_w/grid_w per step, 24 h): absent from older agents # for the building (shed_w/grid_w per step, 24 h): absent from older agents
"flex": plan.get("flex", {}), "flex": plan.get("flex", {}),
+567
View File
@@ -0,0 +1,567 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The household's own energy costs on the box (docs/methods.md A12; the
owner, 2026-11-05: a tenant/inhabitant-facing "My energy costs" view on the
box's own Home Assistant dashboard; the console is staff-only).
Only the household's own figures: its meter, the prices of its own tariff
bundle and its own plan. Never the building operator's margin, other flats
or building totals (the box has none of them: the bundle carries only this
site's prices).
What is kept (<state dir>/costs.db, SQLite; survives restarts):
slots per quarter-hour and carrier (electricity, gas, heat): the metered
kWh (from the agent's own 1-minute windows: a counter's delta,
else a power's mean), what they cost at the price that applied
(the tariff bundle in force at the minute), the kWh without a
price, the same kWh at the own supplier's price, the kWh, cost and
own-supplier cost of slots priced by a building's or community's
offer (Mieterstrom, GGV, §42c), and the plan's estimate for the
slot (optimizer.step_costs: with and without the plan, the same
prices) as saved (mode auto, a billed price) or would-have-saved
(shadow, advisory, or an unbilled tenant price). 400 days.
months the same sums per local month (the site's time zone): the
monthly accumulators, plus the fixed charges per month the bundle
said (when it carries them).
prices per quarter-hour the import price, the own supplier's and whether
the offer priced it, as the bundle said (today's past hours after
the bundle has moved on). 3 days.
Nothing here is ever sent anywhere: it is shown in HA only (announce.py,
dashboards.py). Missing data is never a 0: each figure is None with the
reason in report()["gaps"] (the dashboard's alarm box)."""
from __future__ import annotations
import html
import logging
import math
import os
import sqlite3
import threading
import time
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from . import names
from .devprofiles import part_of
log = logging.getLogger(__name__)
SLOT_S = 900
KEEP_DAYS = 400 # slots: this month and last, and a year back for a later view
KEEP_PRICE_DAYS = 3
CARRIERS = ("electricity", "gas", "heat")
# the meters the costs are read from: carrier, kind (a part, grid.1.import_energy, counts as its quantity)
ASSETS = {"grid.import_energy": ("electricity", "counter"), "grid.import_power": ("electricity", "gauge"),
"grid.power": ("electricity", "gauge"), # signed (import +): its positive part
"gas.energy": ("gas", "counter"), "heat.energy": ("heat", "counter")}
PREFER = ("grid.import_energy", "grid.import_power", "grid.power") # electricity: the counter first
PARAM_FORECAST = "costs.forecast_days" # the Parameters page (fleet), in the tariff bundle's params
FORECAST_DAYS = (1, 62) # the parameter's valid range
REPORT_EVERY_S = 60 # HA's figures made again at most this often (announce.py)
COLS = ("kwh", "cost_eur", "unpriced_kwh", "own_eur", "offer_kwh", "offer_eur", "offer_own_eur",
"plan_eur", "base_eur", "saved_eur", "would_eur", "plan_slots", "minutes")
def quantity(asset: str) -> str:
p = part_of(asset)
return p[0] if p else asset
def wanted(asset: str) -> bool:
return quantity(asset) in ASSETS
def meters_of(mapping) -> dict[str, bool]:
"""Per carrier whether the mapping has a meter for it."""
out = {c: False for c in CARRIERS}
for a in mapping.assets:
q = quantity(a.asset)
if q in ASSETS:
out[ASSETS[q][0]] = True
return out
def _finite(v) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
def amounts(records: list[dict], span_s: float) -> dict[str, float | None]:
"""A closed window's kWh per carrier from the cost aggregator's records
(telemetry.Aggregator): the counters' deltas (Wh) where the carrier has
a counter that has a reading, else its power's mean (W) over the
window; None: no meter value for the carrier in this window. Parts
(two meters) add up."""
by: dict[str, dict[str, list]] = {}
for r in records:
q = quantity(r.get("asset", ""))
if q not in ASSETS:
continue
carrier, kind = ASSETS[q]
if kind == "counter":
v = r.get("delta") if r.get("last") is not None else None
v = v / 1000.0 if _finite(v) else None
else:
m = r.get("mean")
v = (max(m, 0.0) if q == "grid.power" else m) * span_s / 3600.0 / 1000.0 if _finite(m) else None
by.setdefault(carrier, {}).setdefault(q, []).append(v)
out = {}
for carrier, qs in by.items():
order = [q for q in PREFER if q in qs] if carrier == "electricity" else list(qs)
got = None
for q in order:
vals = qs[q]
if vals and all(v is not None for v in vals):
got = sum(vals)
break
out[carrier] = got
return out
class Ledger:
"""The household's costs. bundles: the agent's tariff bundle reader
(bundles.Bundles); mode: the control mode now (None: no planner on this
box); tz: the site's time zone now (HA's)."""
def __init__(self, state_dir: str, bundles, mode=lambda: None, tz=lambda: "UTC", clock=time.time):
self.bundles, self.mode, self.tz, self.clock = bundles, mode, tz, clock
self.lock = threading.Lock()
self.path = os.path.join(state_dir, "costs.db")
self.db = sqlite3.connect(self.path, isolation_level=None, check_same_thread=False)
self.db.execute("PRAGMA journal_mode=WAL")
self.db.execute("PRAGMA synchronous=NORMAL")
cols = ", ".join(f"{c} REAL NOT NULL DEFAULT 0" for c in COLS)
self.db.execute(f"CREATE TABLE IF NOT EXISTS slots (slot INTEGER NOT NULL, carrier TEXT NOT NULL, {cols}, "
"billed INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (slot, carrier)) WITHOUT ROWID")
self.db.execute(f"CREATE TABLE IF NOT EXISTS months (month TEXT NOT NULL, carrier TEXT NOT NULL, {cols}, "
"fixed_eur REAL, fixed_incomplete INTEGER NOT NULL DEFAULT 0, unbilled_kwh REAL NOT NULL DEFAULT 0, "
"PRIMARY KEY (month, carrier)) WITHOUT ROWID")
self.db.execute("CREATE TABLE IF NOT EXISTS prices (slot INTEGER PRIMARY KEY, price_ct REAL, own_ct REAL, "
"offer INTEGER NOT NULL DEFAULT 0) WITHOUT ROWID")
self.pending: dict[int, dict] = {} # slot -> the latest plan's estimate for it (step 0)
self._booked = 0 # the last slot whose plan estimate is booked
def close(self):
with self.lock:
self.db.close()
# -- time -------------------------------------------------------------------
def zone(self) -> ZoneInfo:
try:
return ZoneInfo(self.tz() or "UTC")
except Exception: # an unknown zone: UTC, said in the report
return ZoneInfo("UTC")
def month_of(self, ts: float) -> str:
return datetime.fromtimestamp(ts, timezone.utc).astimezone(self.zone()).strftime("%Y-%m")
def month_bounds(self, ts: float) -> tuple[int, int]:
d = datetime.fromtimestamp(ts, timezone.utc).astimezone(self.zone())
a = d.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
b = (a + timedelta(days=32)).replace(day=1)
# a new datetime at midnight in the zone (DST: the offset of that day)
a = datetime(a.year, a.month, 1, tzinfo=self.zone())
b = datetime(b.year, b.month, 1, tzinfo=self.zone())
return int(a.timestamp()), int(b.timestamp())
# -- writing ----------------------------------------------------------------
def _add(self, slot: int, carrier: str, vals: dict, billed: bool | None = None, month_extra: dict | None = None):
keys = [k for k in COLS if k in vals]
month = self.month_of(slot)
if keys:
sets = ", ".join(f"{k} = {k} + excluded.{k}" for k in keys)
q = ", ".join("?" for _ in keys)
self.db.execute(f"INSERT INTO slots (slot, carrier, {', '.join(keys)}{', billed' if billed is not None else ''}) "
f"VALUES (?, ?, {q}{', ?' if billed is not None else ''}) ON CONFLICT (slot, carrier) DO UPDATE SET "
f"{sets}{', billed = excluded.billed' if billed is not None else ''}",
[slot, carrier] + [vals[k] for k in keys] + ([int(billed)] if billed is not None else []))
self.db.execute(f"INSERT INTO months (month, carrier, {', '.join(keys)}) VALUES (?, ?, {q}) "
f"ON CONFLICT (month, carrier) DO UPDATE SET {sets}", [month, carrier] + [vals[k] for k in keys])
for k, v in (month_extra or {}).items():
self.db.execute("INSERT INTO months (month, carrier) VALUES (?, ?) ON CONFLICT DO NOTHING", (month, carrier))
if k == "unbilled_kwh":
self.db.execute("UPDATE months SET unbilled_kwh = unbilled_kwh + ? WHERE month = ? AND carrier = ?",
(v, month, carrier))
else:
self.db.execute(f"UPDATE months SET {k} = ? WHERE month = ? AND carrier = ?", (v, month, carrier))
def add_window(self, start: float, end: float, records: list[dict]) -> dict:
"""A closed window of the cost aggregator: its kWh per carrier at the
prices in force at its start, into its slot and month; the plan's
estimate of slots that ended. Returns the kWh booked per carrier."""
span = max(0.0, end - start)
slot = int(start // SLOT_S * SLOT_S)
got = amounts(records, span)
sp = self.bundles.slot_prices(start, self.clock())
fixed = self.bundles.fixed_charges(start)
with self.lock:
self.db.execute("BEGIN")
try:
self._book_plans(slot)
el = (sp or {}).get("electricity") or {}
if el:
self.db.execute("INSERT OR REPLACE INTO prices (slot, price_ct, own_ct, offer) VALUES (?, ?, ?, ?)",
(slot, el.get("price"), el.get("own"), int(bool(el.get("offer")))))
for carrier, kwh in got.items():
if kwh is None or kwh < 0:
continue
p = (sp or {}).get(carrier) or {}
price, own = p.get("price"), p.get("own")
v = {"kwh": kwh, "minutes": span / 60.0}
if price is None:
v["unpriced_kwh"] = kwh
else:
v["cost_eur"] = kwh * price / 100.0
if own is not None:
v["own_eur"] = kwh * own / 100.0
if p.get("offer") and price is not None and own is not None:
v.update(offer_kwh=kwh, offer_eur=kwh * price / 100.0, offer_own_eur=kwh * own / 100.0)
extra = {}
f = (fixed or {}).get(carrier)
if f is not None:
extra.update(fixed_eur=f["eur_month"], fixed_incomplete=int(bool(f.get("incomplete"))))
if p.get("offer") and not p.get("billed"):
extra["unbilled_kwh"] = kwh
self._add(slot, carrier, v, None if not p else bool(p.get("billed", True)), extra)
self.db.execute("COMMIT")
except Exception:
self.db.execute("ROLLBACK")
raise
return got
def take_plan(self, plan: dict):
"""A new plan: its estimate for the quarter-hour under way (step 0,
optimizer.step_costs), booked when the quarter-hour ends; a later
plan in the same quarter-hour replaces it."""
se, start, step = plan.get("steps_eur"), plan.get("start"), plan.get("step_s") or SLOT_S
if not isinstance(se, dict) or not _finite(start):
return
now = self.clock()
k = int((now - start) // step)
if k < 0:
return
slot = int(start + k * step)
est = {}
for carrier, d in se.items():
try:
est[carrier] = (float(d["plan"][k]), float(d["base"][k]))
except (KeyError, IndexError, TypeError, ValueError):
continue
if est:
self.pending[slot] = {"est": est, "mode": self.mode() or ""}
def _book_plans(self, now_slot: int):
for slot in sorted(s for s in self.pending if s < now_slot):
p = self.pending.pop(slot)
if slot <= self._booked:
continue
sp = self.bundles.slot_prices(slot, self.clock()) or {}
for carrier, (plan_eur, base_eur) in p["est"].items():
saving = base_eur - plan_eur
billed = carrier != "electricity" or not (sp.get("electricity") or {}).get("offer") or \
bool((sp.get("electricity") or {}).get("billed"))
acted = p["mode"] == "auto" and billed
self._add(slot, carrier, {"plan_eur": plan_eur, "base_eur": base_eur,
"saved_eur" if acted else "would_eur": saving, "plan_slots": 1})
self._booked = slot
def prune(self, now: float | None = None):
now = self.clock() if now is None else now
with self.lock:
self.db.execute("DELETE FROM slots WHERE slot < ?", (int(now) - KEEP_DAYS * 86400,))
self.db.execute("DELETE FROM prices WHERE slot < ?", (int(now) - KEEP_PRICE_DAYS * 86400,))
# -- reading ----------------------------------------------------------------
def month_row(self, month: str, carrier: str) -> dict | None:
with self.lock:
cur = self.db.execute(f"SELECT {', '.join(COLS)}, fixed_eur, fixed_incomplete, unbilled_kwh FROM months "
"WHERE month = ? AND carrier = ?", (month, carrier))
row = cur.fetchone()
if row is None:
return None
return dict(zip(COLS + ("fixed_eur", "fixed_incomplete", "unbilled_kwh"), row))
def window(self, carrier: str, since: int, until: int) -> dict:
with self.lock:
row = self.db.execute("SELECT count(*), sum(cost_eur), sum(unpriced_kwh), sum(minutes) FROM slots "
"WHERE carrier = ? AND slot >= ? AND slot < ? AND minutes > 0",
(carrier, since, until)).fetchone()
return {"slots": row[0] or 0, "cost_eur": row[1] or 0.0, "unpriced_kwh": row[2] or 0.0, "minutes": row[3] or 0.0}
def stored_prices(self, since: int, until: int) -> dict[int, tuple]:
with self.lock:
rows = self.db.execute("SELECT slot, price_ct, own_ct, offer FROM prices WHERE slot >= ? AND slot < ?",
(since, until)).fetchall()
return {int(s): (p, o, bool(f)) for s, p, o, f in rows}
def carriers(self, now: float) -> list[str]:
"""The carriers this home has: electricity always; gas and heat with
a meter value kept or a price in the bundle."""
out = ["electricity"]
with self.lock:
kept = {c for (c,) in self.db.execute("SELECT DISTINCT carrier FROM months")}
sp = self.bundles.slot_prices(now, now) or {}
for c in ("gas", "heat"):
if c in kept or (sp.get(c) or {}).get("price") is not None:
out.append(c)
return out
# -- the report HA shows ------------------------------------------------------------
def _eur(v: float | None, lang: str) -> str:
return "–" if v is None else f"{names.number(v, lang, 2)} €"
def _ct(v: float | None, lang: str) -> str:
return "–" if v is None else names.number(v, lang, 1)
def report(ledger: Ledger, now: float | None, lang: str, meters: dict[str, bool], has_plan: bool) -> dict:
"""What the dashboard shows, in HA's language (names.py): per section
its figures and markdown, and the gaps (missing data: a figure is None
and why). meters: per carrier whether the mapping has a meter for it.
A section that fails is a gap of its own; the others stay."""
now = ledger.clock() if now is None else now
out = {"gaps": [], "made": int(now)}
def gap(section: str, why: str):
out["gaps"].append({"section": section, "why": why})
for key, fn in (("prices", lambda: prices_section(ledger, now, lang, gap)),
("costs", lambda: costs_section(ledger, now, lang, meters, gap)),
("savings", lambda: savings_section(ledger, now, lang, has_plan, gap))):
try:
out[key] = fn()
except Exception as e: # one section's failure never takes the others with it
log.warning("costs: the %s section: %s", key, e)
out[key] = None
gap(key, names.name("cg_failed", lang, str(e)[:120]))
out["md_gaps"] = "\n".join(f"- **{names.name('cs_' + g['section'], lang)}**: {g['why']}" for g in out["gaps"])
return out
def prices_section(ledger: Ledger, now: float, lang: str, gap) -> dict:
"""Today and tomorrow per hour (local): the price (mean of its
quarter-hours), where it came from (the building's or community's offer,
or the own supplier) and, where an offer exists, the own supplier's
price beside it."""
zone = ledger.zone()
b = ledger.bundles
tenant = b.tenant_now(now)
d0 = datetime.fromtimestamp(now, timezone.utc).astimezone(zone).replace(hour=0, minute=0, second=0, microsecond=0)
d0 = datetime(d0.year, d0.month, d0.day, tzinfo=zone)
days = []
stored = ledger.stored_prices(int(d0.timestamp()), int(d0.timestamp()) + 2 * 86400 + 7200)
for di, key in ((0, "today"), (1, "tomorrow")):
day = (d0 + timedelta(days=di))
day = datetime(day.year, day.month, day.day, tzinfo=zone)
nxt = day + timedelta(days=1)
nxt = datetime(nxt.year, nxt.month, nxt.day, tzinfo=zone)
hours = []
t = int(day.timestamp())
while t < int(nxt.timestamp()):
qs = []
for q in range(4):
s = t + q * SLOT_S
sp = (b.slot_prices(s, now) or {}).get("electricity")
if sp and sp.get("price") is not None:
qs.append((sp["price"], sp.get("own"), bool(sp.get("offer"))))
elif s in stored and stored[s][0] is not None:
qs.append(stored[s])
local = datetime.fromtimestamp(t, timezone.utc).astimezone(zone)
if qs:
own = [o for _, o, _ in qs if o is not None]
hours.append({"h": local.strftime("%H"), "t": t, "ct": round(sum(p for p, _, _ in qs) / len(qs), 2),
"own": round(sum(own) / len(own), 2) if len(own) == len(qs) else None,
"offer": sum(1 for *_, f in qs if f), "of": len(qs)})
else:
hours.append({"h": local.strftime("%H"), "t": t, "ct": None, "own": None, "offer": 0, "of": 0})
t += 3600
days.append({"key": key, "date": day.strftime("%Y-%m-%d"), "hours": hours})
any_offer = tenant is not None or any(h["offer"] for d in days for h in d["hours"])
who = names.name("cs_offer_of", lang, tenant_label(tenant)) if tenant else names.name("cs_offer", lang)
for d in days:
priced = [h for h in d["hours"] if h["ct"] is not None]
label = names.name("cs_" + d["key"], lang)
if not priced:
d["md"] = f"**{label}**: {names.name('cg_no_prices_day', lang)}"
if d["key"] == "today":
gap("prices", names.name("cg_no_prices_today", lang))
continue
lo, hi = min(h["ct"] for h in priced), max(h["ct"] for h in priced)
n_off = sum(1 for h in priced if h["offer"])
head = f"<b>{label}</b>: {_ct(lo, lang)}–{_ct(hi, lang)} ct/kWh" # HTML: a summary is no markdown
if any_offer:
head += " · " + html.escape(names.name("cs_hours_offer", lang, n_off, who))
rows = []
hdr = f"| {names.name('cs_hour', lang)} | ct/kWh | {names.name('cs_from', lang)} |"
sep = "|---|---:|---|"
if any_offer:
hdr += f" {names.name('cs_own', lang)} |"
sep += "---:|"
for h in d["hours"]:
src = "–" if h["ct"] is None else (names.name("cs_src_offer", lang) if h["offer"] == h["of"] and h["of"]
else names.name("cs_src_part", lang) if h["offer"]
else names.name("cs_src_own", lang))
row = f"| {h['h']} | {_ct(h['ct'], lang)} | {src} |"
if any_offer:
row += f" {_ct(h['own'], lang) if h['offer'] else ''} |"
rows.append(row)
d["md"] = (f"<details><summary>{head}</summary>\n\n{hdr}\n{sep}\n" + "\n".join(rows) + "\n\n</details>")
# now: the price, its source and the own supplier's beside it
sp = (b.slot_prices(now, now) or {}).get("electricity") or {}
now_md = ""
if sp.get("price") is not None:
now_md = f"{names.name('price_now', lang)} **{_ct(sp['price'], lang)} ct/kWh**"
if sp.get("offer"):
now_md += " · " + who
if sp.get("own") is not None:
now_md += f" · {names.name('cs_own_now', lang)} {_ct(sp['own'], lang)} ct/kWh"
else:
now_md += " · " + names.name("cs_src_own_long", lang)
if tenant and not tenant.get("billed"):
now_md += f" \n<small>{names.name('cs_offer_shadow', lang)}</small>"
else:
gap("prices", names.name("cg_no_price_now", lang))
if tenant and not tenant.get("own_known"):
gap("prices", names.name("cg_no_own_curve", lang))
return {"now_md": now_md, "days": days, "tenant": tenant, "offer": any_offer}
def tenant_label(t: dict | None) -> str:
if not t:
return ""
model = {"mieterstrom": "Mieterstrom", "ggv": "GGV", "sharing": "§42c"}.get(t.get("model"), t.get("model") or "")
return f"{t.get('name') or t.get('plant') or ''} ({model})".strip()
def costs_section(ledger: Ledger, now: float, lang: str, meters: dict[str, bool], gap) -> dict:
"""Per carrier: this month so far, the forecast to its end, last month;
each with the fixed charges where the bundle carries them."""
month = ledger.month_of(now)
a, b = ledger.month_bounds(now)
last = ledger.month_of(a - 1)
params = ledger.bundles.box_params(now)
days = params.get(PARAM_FORECAST)
if not _finite(days) or not FORECAST_DAYS[0] <= days <= FORECAST_DAYS[1]:
days = None
gap("costs", names.name("cg_no_forecast_param", lang, PARAM_FORECAST))
fixed_now = ledger.bundles.fixed_charges(now)
if fixed_now is None:
gap("costs", names.name("cg_no_fixed", lang))
out = {"month": month, "last_month": last, "carriers": {}}
rows = []
for c in ledger.carriers(now):
cur, prev = ledger.month_row(month, c), ledger.month_row(last, c)
r = {"so_far": None, "forecast": None, "last": None, "kwh": None, "fixed_month": None, "why": []}
fx = (fixed_now or {}).get(c)
if fx is not None:
r["fixed_month"] = round(fx["eur_month"], 2)
if not meters.get(c) and not (cur and cur["kwh"]):
r["why"].append(names.name("cg_no_meter_" + c, lang))
gap("costs", names.name("cg_no_meter_" + c, lang))
elif cur is None or not cur["minutes"]:
r["why"].append(names.name("cg_no_meter_data", lang))
else:
elapsed = max(0.0, min(1.0, (now - a) / (b - a)))
fixed_so_far = fx["eur_month"] * elapsed if fx else 0.0
r["kwh"] = round(cur["kwh"], 2)
r["so_far"] = round(cur["cost_eur"] + fixed_so_far, 2)
if cur["unpriced_kwh"] > 0.0005:
r["why"].append(names.name("cg_unpriced", lang, names.number(cur["unpriced_kwh"], lang, 1)))
gap("costs", names.name("cg_unpriced_of", lang, names.name("carrier_" + c, lang),
names.number(cur["unpriced_kwh"], lang, 1)))
if days is not None:
w = ledger.window(c, int(now - days * 86400), int(now))
if w["minutes"] >= 60:
per_min = w["cost_eur"] / w["minutes"]
rest = max(0.0, (b - now) / 60.0)
r["forecast"] = round(cur["cost_eur"] + per_min * rest + (fx["eur_month"] if fx else 0.0), 2)
r["forecast_basis_h"] = round(w["minutes"] / 60.0, 1)
else:
r["why"].append(names.name("cg_forecast_short", lang))
if prev is not None and prev["minutes"]:
pf = prev.get("fixed_eur")
r["last"] = round(prev["cost_eur"] + (pf or 0.0), 2)
r["last_kwh"] = round(prev["kwh"], 2)
if cur and cur.get("unbilled_kwh", 0) > 0.0005:
r["own_eur"] = round(cur["own_eur"], 2)
r["note"] = names.name("cs_unbilled_note", lang, _eur(cur["own_eur"], lang))
r["incomplete"] = bool(cur and (cur["unpriced_kwh"] > 0.0005 or cur.get("fixed_incomplete")))
out["carriers"][c] = r
star = "*" if r["incomplete"] else ""
rows.append(f"| {names.name('carrier_' + c, lang)} | {_eur(r['so_far'], lang)}{star} | "
f"{_eur(r['forecast'], lang)} | {_eur(r['last'], lang)} |")
hdr = (f"| | {names.name('cs_so_far', lang)} | {names.name('cs_forecast', lang)} | "
f"{names.name('cs_last_month', lang)} |\n|---|---:|---:|---:|\n")
notes = []
if fixed_now is not None:
notes.append(names.name("cs_fixed_in", lang))
else:
notes.append(names.name("cs_fixed_out", lang))
if any(r["incomplete"] for r in out["carriers"].values()):
notes.append(names.name("cs_incomplete", lang))
notes += [r["note"] for r in out["carriers"].values() if r.get("note")]
if days is not None:
notes.append(names.name("cs_forecast_how", lang, int(days)))
out["md"] = hdr + "\n".join(rows) + "\n\n<small>" + " ".join(notes) + "</small>"
return out
def savings_section(ledger: Ledger, now: float, lang: str, has_plan: bool, gap) -> dict:
"""Per carrier, this month and last: (a) where the household buys: the
building's or community's offer against its own supplier for the same
kWh (electricity only: there is no tenant gas or heat); (b) the plan's
actions: with against without the plan, the same prices (its estimate).
Shadow (control mode shadow or advisory, or a tenant price not billed):
"would have saved", never money saved."""
month = ledger.month_of(now)
a, _ = ledger.month_bounds(now)
last = ledger.month_of(a - 1)
tenant = ledger.bundles.tenant_now(now)
out = {"carriers": {}}
lines = []
for c in ledger.carriers(now):
cur, prev = ledger.month_row(month, c) or {}, ledger.month_row(last, c) or {}
r = {}
if c == "electricity":
if cur.get("offer_kwh") or prev.get("offer_kwh") or tenant:
billed = not cur.get("unbilled_kwh") and bool(cur.get("offer_kwh"))
r["offer"] = {"month": round(cur.get("offer_own_eur", 0) - cur.get("offer_eur", 0), 2) if cur.get("offer_kwh") else None,
"last": round(prev.get("offer_own_eur", 0) - prev.get("offer_eur", 0), 2) if prev.get("offer_kwh") else None,
"kwh": round(cur.get("offer_kwh", 0), 2), "billed": billed}
key = "cs_offer_saved" if billed else "cs_offer_would"
if r["offer"]["month"] is None:
lines.append(f"- {names.name('cs_offer_none_yet', lang, tenant_label(tenant))}")
else:
lines.append(f"- {names.name(key, lang, _eur(r['offer']['month'], lang), names.number(r['offer']['kwh'], lang, 1))}"
+ (f" · {names.name('cs_last_month', lang)} {_eur(r['offer']['last'], lang)}"
if r["offer"]["last"] is not None else ""))
else:
lines.append(f"- {names.name('cs_offer_no', lang)}")
p_cur = (cur.get("saved_eur", 0), cur.get("would_eur", 0), cur.get("plan_slots", 0))
p_prev = (prev.get("saved_eur", 0), prev.get("would_eur", 0), prev.get("plan_slots", 0))
if p_cur[2] or p_prev[2]:
r["plan"] = {"saved": round(p_cur[0], 2) if p_cur[2] else None, "would": round(p_cur[1], 2) if p_cur[2] else None,
"hours": round(p_cur[2] / 4.0, 1),
"last_saved": round(p_prev[0], 2) if p_prev[2] else None,
"last_would": round(p_prev[1], 2) if p_prev[2] else None}
parts = []
if p_cur[2] and abs(p_cur[0]) >= 0.005:
parts.append(names.name("cs_plan_saved", lang, _eur(p_cur[0], lang)))
if p_cur[2] and (abs(p_cur[1]) >= 0.005 or not parts):
parts.append(names.name("cs_plan_would", lang, _eur(p_cur[1], lang)))
if not p_cur[2]:
parts.append(names.name("cs_plan_none_month", lang))
tail = ""
if p_prev[2]:
tail = f" · {names.name('cs_last_month', lang)} {_eur(p_prev[0] + p_prev[1], lang)}"
lines.append(f"- {names.name('cs_plan_of', lang, names.name('carrier_' + c, lang))}: " + ", ".join(parts) + tail)
elif c == "electricity" or has_plan:
why = names.name("cg_no_plan" if not has_plan else "cg_no_plan_yet", lang)
lines.append(f"- {names.name('cs_plan_of', lang, names.name('carrier_' + c, lang))}: {why}")
if c == "electricity":
gap("savings", why)
out["carriers"][c] = r
out["md"] = "\n".join(lines) + "\n\n<small>" + names.name("cs_savings_how", lang) + "</small>"
return out
+55 -1
View File
@@ -38,6 +38,14 @@
actuators' contract target against their state); the building actuators' contract target against their state); the building
the home is in or asked to join the home is in or asked to join
energy power and price over time, energy per day and month (if mapped) energy power and price over time, energy per day and month (if mapped)
costs "My energy costs" (costs.py, the household's own figures,
for the inhabitant): an alarm box with what cannot be
computed and why; the price now and its source (the
building's offer or the own supplier, the own supplier's
beside it), today and tomorrow per hour (folded); savings
per carrier (the offer vs the own supplier, the plan's;
"would have saved" in shadow); the month's cost per carrier
(so far, forecast, last month, fixed charges where known)
climate rooms, thermostats, heat pump (if mapped) climate rooms, thermostats, heat pump (if mapped)
flats a building's flats (only on a building's own box) flats a building's flats (only on a building's own box)
Sensors gone or unavailable for an hour are left out. The add-ons' pages Sensors gone or unavailable for an hour are left out. The add-ons' pages
@@ -582,6 +590,52 @@ def view_climate(h: Home) -> dict | None:
_stats(h.n("heat_today"), h.all("heat.energy")))) _stats(h.n("heat_today"), h.all("heat.energy"))))
def view_costs(h: Home) -> dict | None:
"""My energy costs (costs.py; the household's own figures only, for
the inhabitant: the console is staff's): on top an alarm box with what
cannot be computed and why (only when there is something); the prices
(the price now and its source, the own supplier's beside a building's
offer; today and tomorrow per hour, folded); the savings per carrier
(the building's offer vs the own supplier, the plan's: saved, or would
have saved in shadow); the month's cost per carrier (so far, forecast,
last month). Each card shows its attribute, or that it is not there yet:
a missing figure never breaks the view. None without the sensors."""
st, pr = h.our("costs"), h.our("costs_prices")
if not st and not pr:
return None
none = h.n("cs_unavailable")
def attr(e, key):
return ("{% set m = state_attr('" + e + "', '" + key + "') %}{% if m %}{{ m }}{% else %}<small>"
+ none + "</small>{% endif %}") if e else None
alarm = _md("<ha-alert alert-type=\"warning\" title=\"" + h.n("cs_alarm") + "\">{{ state_attr('" + st
+ "', 'alert') }}</ha-alert>", visibility=[{"condition": "numeric_state", "entity": st, "above": 0}]
) if st else None
prices = _md(attr(pr, "now_md") + "\n\n" + attr(pr, "today_md") + "\n\n"
"{% set m = state_attr('" + pr + "', 'tomorrow_md') %}{% if m %}{{ m }}{% endif %}") if pr else None
savings = _md(attr(st, "md_savings")) if st else None
month = _md(attr(st, "md_costs")) if st else None
tiles = [_tile(h.our(f"cost_{c}"), h.n("carrier_" + c), icon, cols=6)
for c, icon in (("electricity", "mdi:flash"), ("gas", "mdi:fire"), ("heat", "mdi:radiator"))]
return _view(h.n("view_costs"), "costs", "mdi:cash-multiple",
_band(alarm), _band(prices, heading=h.n("cs_prices"), icon="mdi:cash-clock"),
_band(savings, heading=h.n("cs_savings"), icon="mdi:piggy-bank-outline"),
_band(*_fill([t for t in tiles if t]), month, heading=h.n("cs_costs"), icon="mdi:calendar-month"),
columns=WIDE)
def _safe_view(make, h: Home, path: str, title_key: str) -> dict | None:
"""A view that failed to build: one card that says so, the other views
stay (a failing section never takes the dashboard with it)."""
try:
return make(h)
except Exception as e:
log.warning("dashboards: the %s view: %s", path, e)
return _view(h.n(title_key), path, "mdi:alert-outline",
_band(_md("<ha-alert alert-type=\"error\">" + h.n("cg_failed", type(e).__name__) + "</ha-alert>")),
columns=WIDE)
def _short(name: str, device: str) -> str: def _short(name: str, device: str) -> str:
""""HM8042 PV power" on the device HM8042: "PV power".""" """"HM8042 PV power" on the device HM8042: "PV power"."""
if device and name.lower().startswith(device.lower() + " "): if device and name.lower().startswith(device.lower() + " "):
@@ -959,7 +1013,7 @@ def building_section(h: Home) -> dict | None:
def dashboard(h: Home) -> dict | None: def dashboard(h: Home) -> dict | None:
"""The dashboard's config, or None: nothing to show.""" """The dashboard's config, or None: nothing to show."""
views = [view_overview(h), view_energy(h)] views = [view_overview(h), view_energy(h), _safe_view(view_costs, h, "costs", "view_costs")]
if h.controls("heating", "cooling") or h.each("heatpump.power") or h.prefixed("room", "temp"): if h.controls("heating", "cooling") or h.each("heatpump.power") or h.prefixed("room", "temp"):
views.append(view_climate(h)) views.append(view_climate(h))
if h.flats: if h.flats:
+10 -4
View File
@@ -159,6 +159,7 @@ class Executor:
self.commands: dict[str, dict] = {} # control -> {"set", "level", "until", "id", "why"} self.commands: dict[str, dict] = {} # control -> {"set", "level", "until", "id", "why"}
self._refused: dict[tuple, float] = {} self._refused: dict[tuple, float] = {}
self.log: list[dict] = [] # the last actions (tests, status) self.log: list[dict] = [] # the last actions (tests, status)
self.shade_moves = None # shades.Moves: what each shade was last moved for
# -- what is wanted ------------------------------------------------------ # -- what is wanted ------------------------------------------------------
def wanted(self, c, now): def wanted(self, c, now):
@@ -222,23 +223,28 @@ class Executor:
# hand still counts as an override of the cap # hand still counts as an override of the cap
self.guard.expect(c.id, c.entities["climate"], want["set"]) self.guard.expect(c.id, c.entities["climate"], want["set"])
for a in acts: for a in acts:
await self._do(client, a, now) done = await self._do(client, a, now)
if done and c.kind == "cover" and self.shade_moves is not None:
# what it moved for: the next plans open it again (shades.Moves)
rule = want.get("rule", "") if isinstance(want, dict) and level == "plan" else ""
self.shade_moves.record(c.id, rule, float(a.value), now)
async def _do(self, client, a: Action, now): async def _do(self, client, a: Action, now) -> bool:
ok, reason = self.guard.check(a) ok, reason = self.guard.check(a)
if not ok: if not ok:
key = (a.control, reason.split(" ")[0] + reason[-12:]) key = (a.control, reason.split(" ")[0] + reason[-12:])
if now - self._refused.get(key, 0) >= 3600: if now - self._refused.get(key, 0) >= 3600:
self._refused[key] = now self._refused[key] = now
await self._report(a, "refused", reason, now) await self._report(a, "refused", reason, now)
return return False
try: try:
await client.call_service(a.domain, a.service, a.entity, a.data, self._allowed(a)) await client.call_service(a.domain, a.service, a.entity, a.data, self._allowed(a))
except Exception as e: except Exception as e:
await self._report(a, "failed", str(e)[:200], now) await self._report(a, "failed", str(e)[:200], now)
return return False
self.guard.done(a) self.guard.done(a)
await self._report(a, "done", a.why, now) await self._report(a, "done", a.why, now)
return True
@staticmethod @staticmethod
def _allowed(a: Action): def _allowed(a: Action):
+9
View File
@@ -56,6 +56,15 @@ MESSAGES = {
"This energy community (energy shared between buildings and homes):": "This energy community (energy shared between buildings and homes):":
"Diese Energiegemeinschaft (Energie, die zwischen Gebäuden und Häusern geteilt wird):", "Diese Energiegemeinschaft (Energie, die zwischen Gebäuden und Häusern geteilt wird):",
"Your meter point (on your meter or your electricity bill)": "Ihr Zählpunkt (auf Ihrem Zähler oder Ihrer Stromrechnung)", "Your meter point (on your meter or your electricity bill)": "Ihr Zählpunkt (auf Ihrem Zähler oder Ihrer Stromrechnung)",
"Invitations": "Einladungen",
"{operator} invites your home to join {name} (unit {unit}), until {date}.":
"{operator} lädt Ihr Zuhause ein, {name} beizutreten (Einheit {unit}), bis {date}.",
"{operator} invites your home to join {name}, until {date}.":
"{operator} lädt Ihr Zuhause ein, {name} beizutreten, bis {date}.",
"Look at it": "Ansehen",
"Decline": "Ablehnen",
"Which invitation?": "Welche Einladung?",
"You declined the invitation.": "Sie haben die Einladung abgelehnt.",
"Join with a code": "Mit einem Code beitreten", "Join with a code": "Mit einem Code beitreten",
"A building's operator gives each flat a code; an energy community's operator gives each home a code (or a QR code: " "A building's operator gives each flat a code; an energy community's operator gives each home a code (or a QR code: "
"open its link here, or type the code).": "open its link here, or type the code).":
+52 -7
View File
@@ -229,7 +229,7 @@ h2{margin:.2rem 0 1rem}h3{margin:1.4rem 0 .5rem}.box{background:#fff;border:1px
.ok{background:#e3f4ea;border-color:#9fd3b4}.err{background:#fbe4e2;border-color:#e6a9a3}.note{color:#5a6b62} .ok{background:#e3f4ea;border-color:#9fd3b4}.err{background:#fbe4e2;border-color:#e6a9a3}.note{color:#5a6b62}
label{display:block;margin:.6rem 0 .2rem;font-size:.92rem}input:not([type=checkbox]){font:inherit;padding:.45rem .6rem;border:1px solid #b9c6bf;border-radius:6px;width:100%;box-sizing:border-box} label{display:block;margin:.6rem 0 .2rem;font-size:.92rem}input:not([type=checkbox]){font:inherit;padding:.45rem .6rem;border:1px solid #b9c6bf;border-radius:6px;width:100%;box-sizing:border-box}
label.check{display:flex;gap:.5rem;align-items:flex-start}button{font:inherit;padding:.45rem 1rem;border:0;border-radius:6px;background:#2f6f55;color:#fff;cursor:pointer;margin-top:.6rem} label.check{display:flex;gap:.5rem;align-items:flex-start}button{font:inherit;padding:.45rem 1rem;border:0;border-radius:6px;background:#2f6f55;color:#fff;cursor:pointer;margin-top:.6rem}
button.secondary{background:#e2e9e5;color:#1d2a24}form{margin:.4rem 0} button.secondary{background:#e2e9e5;color:#1d2a24}form{margin:.4rem 0}form.inline{display:inline-block;margin:0 .4rem 0 0}
@media (prefers-color-scheme:dark){body{background:#111915;color:#e3ebe6}.box{background:#18221d;border-color:#2b3a32}.note{color:#9fb0a6} @media (prefers-color-scheme:dark){body{background:#111915;color:#e3ebe6}.box{background:#18221d;border-color:#2b3a32}.note{color:#9fb0a6}
input:not([type=checkbox]){background:#18221d;color:#e3ebe6;border-color:#3a4b42}.ok{background:#173326}.err{background:#3a1d1a}button.secondary{background:#2b3a32;color:#e3ebe6}}""" input:not([type=checkbox]){background:#18221d;color:#e3ebe6;border-color:#3a4b42}.ok{background:#173326}.err{background:#3a1d1a}button.secondary{background:#2b3a32;color:#e3ebe6}}"""
@@ -326,9 +326,10 @@ def consent_box(checked: bool, kind: str = "building") -> str:
"building's rules ask for it).")) + "</span></label>") "building's rules ask for it).")) + "</span></label>")
def form(do: str, inner: str, button: str, cls: str = "") -> str: def form(do: str, inner: str, button: str, cls: str = "", inline: bool = False) -> str:
# action="": the same address, which is the ingress path HA gave the page # action="": the same address, which is the ingress path HA gave the page
return (f'<form method="post" action=""><input type="hidden" name="do" value="{E(do)}">{inner}' return (f'<form method="post" action=""{" class=" + chr(34) + "inline" + chr(34) if inline else ""}>'
f'<input type="hidden" name="do" value="{E(do)}">{inner}'
f'<button{f" class={chr(34)}{cls}{chr(34)}" if cls else ""}>{E(button)}</button></form>') f'<button{f" class={chr(34)}{cls}{chr(34)}" if cls else ""}>{E(button)}</button></form>')
@@ -365,12 +366,36 @@ def offer_html(o: dict) -> str:
f'<button name="answer" value="yes">{E(T("Restore what is ticked"))}</button></form>') f'<button name="answer" value="yes">{E(T("Restore what is ticked"))}</button></form>')
def invitations_html(offers: list) -> str:
"""Invitations an operator addressed to this box: one line each, the card
and the rules behind a details, "Look at it" (the preview) or "Decline"."""
out = []
for o in offers or []:
c, inv = o.get("building") or {}, str(o.get("invite", ""))
if not UUID_RE.fullmatch(inv):
continue
kind = "community" if c.get("kind") == "community" else "building"
values = {"operator": c.get("operator") or o.get("from") or "", "name": c.get("name", ""),
"date": when(o.get("expires_at") or "")}
u = o.get("unit")
line = (T("{operator} invites your home to join {name} (unit {unit}), until {date}.", unit=u.get("label", ""),
**values) if u and u.get("label") else
T("{operator} invites your home to join {name}, until {date}.", **values))
hidden = f'<input type="hidden" name="invite" value="{E(inv)}">'
out.append(f'<div class="box"><p>{E(line)}</p><details><summary>{E(T("Its rules"))}</summary>{card(c)}'
f'{rules_html(c.get("rules"), kind)}</details>'
+ form("preview", hidden, T("Look at it"), inline=True)
+ form("decline", hidden, T("Decline"), "secondary", inline=True) + "</div>")
return f"<h3>{E(T('Invitations'))}</h3>" + "".join(out) if out else ""
def check(name: str, text: str) -> str: def check(name: str, text: str) -> str:
return f'<label class="check"><input type="checkbox" name="{name}" value="1"><span>{E(text)}</span></label>' return f'<label class="check"><input type="checkbox" name="{name}" value="1"><span>{E(text)}</span></label>'
def page(st: dict, st_err: str, consent: bool, err: str = "", ok: str = "", preview: dict | None = None, def page(st: dict, st_err: str, consent: bool, err: str = "", ok: str = "", preview: dict | None = None,
code: str = "", found: list | None = None, consent_community: bool = False, offer: dict | None = None) -> str: code: str = "", found: list | None = None, consent_community: bool = False, offer: dict | None = None,
invite: str = "") -> str:
body = [f"<h2>{E(T('Building or community'))}</h2>"] body = [f"<h2>{E(T('Building or community'))}</h2>"]
if offer: if offer:
body.append(offer_html(offer)) body.append(offer_html(offer))
@@ -433,10 +458,15 @@ def page(st: dict, st_err: str, consent: bool, err: str = "", ok: str = "", prev
what = (T("Unit <b>{unit}</b> of this building:", unit=E(u["label"])) if u what = (T("Unit <b>{unit}</b> of this building:", unit=E(u["label"])) if u
else E(T("This energy community (energy shared between buildings and homes):"))) else E(T("This energy community (energy shared between buildings and homes):")))
body.append(f"<h3>{E(T('Join'))}</h3><p>{what}</p>{card(c)}<h3>{E(T('Its rules'))}</h3>{rules_html(c.get('rules'), kind)}" body.append(f"<h3>{E(T('Join'))}</h3><p>{what}</p>{card(c)}<h3>{E(T('Its rules'))}</h3>{rules_html(c.get('rules'), kind)}"
+ form("join", f'<input type="hidden" name="code" value="{E(code)}"><input type="hidden" name="kind" value="{kind}">' + form("join", (f'<input type="hidden" name="invite" value="{E(invite)}">' if invite else
f'<input type="hidden" name="code" value="{E(code)}">')
+ f'<input type="hidden" name="kind" value="{kind}">'
f'<input type="hidden" name="rules_digest" value="{E(c.get("rules_digest", ""))}">{meter}' f'<input type="hidden" name="rules_digest" value="{E(c.get("rules_digest", ""))}">{meter}'
f'{consent_box(given[kind], kind)}', T("Join {name}", name=c.get("name", "")))) f'{consent_box(given[kind], kind)}', T("Join {name}", name=c.get("name", ""))))
elif not m: else:
# invitations: also next to a flat's building membership (a community may invite the home)
body.append(invitations_html(st.get("offers")))
if not preview and not m:
body.append(f"<h3>{E(T('Join with a code'))}</h3><p class=\"note\">" body.append(f"<h3>{E(T('Join with a code'))}</h3><p class=\"note\">"
+ E(T("A building's operator gives each flat a code; an energy community's operator gives each home a " + E(T("A building's operator gives each flat a code; an energy community's operator gives each home a "
"code (or a QR code: open its link here, or type the code).")) + "</p>" "code (or a QR code: open its link here, or type the code).")) + "</p>"
@@ -502,17 +532,32 @@ class JoinPage:
if do == "restore": if do == "restore":
o = fl.offer() o = fl.offer()
return show(ok=fl.answer_offer(o, f)) if o else show() return show(ok=fl.answer_offer(o, f)) if o else show()
if do == "preview" and f.get("invite"):
inv = f.get("invite", "").strip().lower()
if not UUID_RE.fullmatch(inv):
return show(T("Which invitation?"))
return show(preview=fl.ask({"op": "preview", "invite": inv}), invite=inv)
if do == "preview": if do == "preview":
code = f.get("code", "").strip().upper() code = f.get("code", "").strip().upper()
if not CODE_RE.fullmatch(code): if not CODE_RE.fullmatch(code):
return show(T("A join code has 12 letters and digits: XXXX-XXXX-XXXX."), code=code) return show(T("A join code has 12 letters and digits: XXXX-XXXX-XXXX."), code=code)
return show(preview=fl.ask({"op": "preview", "code": code}), code=code) return show(preview=fl.ask({"op": "preview", "code": code}), code=code)
if do == "join": if do == "join":
fl.apply(fl.ask({"op": "join", "code": f.get("code", "")[:20], "meter_point": f.get("meter_point", "")[:64], inv = f.get("invite", "").strip().lower()
if inv and not UUID_RE.fullmatch(inv):
return show(T("Which invitation?"))
fl.apply(fl.ask({"op": "join", **({"invite": inv} if inv else {"code": f.get("code", "")[:20]}),
"meter_point": f.get("meter_point", "")[:64],
"rules_digest": f.get("rules_digest", "")[:80], "consent": given})) "rules_digest": f.get("rules_digest", "")[:80], "consent": given}))
fl.set_recipient_consent(kind, consent) fl.set_recipient_consent(kind, consent)
return show(ok=T("Welcome: your home is a member of the community now.") if kind == "community" return show(ok=T("Welcome: your home is a member of the community now.") if kind == "community"
else T("Welcome: your flat is a member now.")) else T("Welcome: your flat is a member now."))
if do == "decline":
inv = f.get("invite", "").strip().lower()
if not UUID_RE.fullmatch(inv):
return show(T("Which invitation?"))
fl.apply(fl.ask({"op": "decline", "invite": inv}))
return show(ok=T("You declined the invitation."))
if do == "find": if do == "find":
loc = self.location() loc = self.location()
if loc is None: if loc is None:
+88
View File
@@ -186,6 +186,94 @@ NAMES = {
"pref_reserve_blocks": {"en": "{0}: reserve by time", "de": "{0}: Reserve nach Uhrzeit"}, "pref_reserve_blocks": {"en": "{0}: reserve by time", "de": "{0}: Reserve nach Uhrzeit"},
"pref_result": {"en": "Preferences", "de": "Präferenzen"}, "pref_result": {"en": "Preferences", "de": "Präferenzen"},
"pref_result_of": {"en": "{0}: preferences", "de": "{0}: Präferenzen"}, "pref_result_of": {"en": "{0}: preferences", "de": "{0}: Präferenzen"},
# the household's own costs (costs.py; announce.py, dashboards.py view "costs")
"view_costs": {"en": "My energy costs", "de": "Meine Energiekosten"},
"costs_status": {"en": "Energy costs: missing data", "de": "Energiekosten: fehlende Daten"},
"costs_prices": {"en": "Electricity price source now", "de": "Strompreis: Quelle jetzt"},
"cost_of": {"en": "{0}: cost this month", "de": "{0}: Kosten diesen Monat"},
"saving_of": {"en": "{0}: savings this month", "de": "{0}: Ersparnis diesen Monat"},
"carrier_electricity": {"en": "Electricity", "de": "Strom"},
"carrier_gas": {"en": "Gas", "de": "Gas"},
"carrier_heat": {"en": "Heat", "de": "Wärme"},
"cs_prices": {"en": "Prices", "de": "Preise"},
"cs_costs": {"en": "Monthly cost", "de": "Monatskosten"},
"cs_savings": {"en": "Savings", "de": "Ersparnis"},
"cs_alarm": {"en": "Some figures cannot be shown", "de": "Einige Werte können nicht angezeigt werden"},
"cs_unavailable": {"en": "Not available yet: the agent has not sent these figures.",
"de": "Noch nicht verfügbar: der Agent hat diese Werte nicht gesendet."},
"cs_today": {"en": "Today", "de": "Heute"},
"cs_tomorrow": {"en": "Tomorrow", "de": "Morgen"},
"cs_hour": {"en": "Hour", "de": "Stunde"},
"cs_from": {"en": "From", "de": "Von"},
"cs_own": {"en": "Own supplier", "de": "Eigener Lieferant"},
"cs_own_now": {"en": "own supplier", "de": "eigener Lieferant"},
"cs_offer": {"en": "the building's offer", "de": "Angebot des Gebäudes"},
"cs_offer_of": {"en": "{0}", "de": "{0}"},
"cs_src_offer": {"en": "building", "de": "Gebäude"},
"cs_src_part": {"en": "partly building", "de": "teils Gebäude"},
"cs_src_own": {"en": "supplier", "de": "Lieferant"},
"cs_src_own_long": {"en": "your own supplier", "de": "Ihr eigener Lieferant"},
"cs_hours_offer": {"en": "{0} h from {1}", "de": "{0} h von {1}"},
"cs_offer_shadow": {"en": "The building's price is shown and planned with but not billed yet (shadow): "
"your own supplier still bills you.",
"de": "Der Preis des Gebäudes wird angezeigt und eingeplant, aber noch nicht abgerechnet "
"(Schattenbetrieb): Ihr eigener Lieferant rechnet weiter ab."},
"cs_so_far": {"en": "So far", "de": "Bisher"},
"cs_forecast": {"en": "Month end (forecast)", "de": "Monatsende (Prognose)"},
"cs_last_month": {"en": "last month", "de": "Vormonat"},
"cs_fixed_in": {"en": "Fixed charges included.", "de": "Grundpreise eingerechnet."},
"cs_fixed_out": {"en": "Without fixed charges (not known to the box).",
"de": "Ohne Grundpreise (der Box nicht bekannt)."},
"cs_incomplete": {"en": "* at least: some kWh had no price.", "de": "* mindestens: einige kWh hatten keinen Preis."},
"cs_forecast_how": {"en": "Forecast: the cost per hour of the last {0} days for the rest of the month.",
"de": "Prognose: die Kosten je Stunde der letzten {0} Tage für den Rest des Monats."},
"cs_unbilled_note": {"en": "At your own supplier's price (what is billed now): {0}.",
"de": "Zum Preis Ihres eigenen Lieferanten (was jetzt abgerechnet wird): {0}."},
"cs_offer_saved": {"en": "Building offer vs your own supplier: **{0} saved** this month ({1} kWh)",
"de": "Angebot des Gebäudes statt eigenem Lieferanten: **{0} gespart** diesen Monat ({1} kWh)"},
"cs_offer_would": {"en": "Building offer vs your own supplier: **would have saved {0}** this month ({1} kWh; not billed)",
"de": "Angebot des Gebäudes statt eigenem Lieferanten: **hätte {0} gespart** diesen Monat "
"({1} kWh; nicht abgerechnet)"},
"cs_offer_none_yet": {"en": "Building offer {0}: no metered kWh at its price this month yet.",
"de": "Angebot des Gebäudes {0}: diesen Monat noch keine gemessenen kWh zu seinem Preis."},
"cs_offer_no": {"en": "You buy from your own supplier: no building offer.",
"de": "Sie beziehen von Ihrem eigenen Lieferanten: kein Angebot des Gebäudes."},
"cs_plan_of": {"en": "{0}, Cantabile's plan", "de": "{0}, Plan von Cantabile"},
"cs_plan_saved": {"en": "**{0} saved** (estimated)", "de": "**{0} gespart** (geschätzt)"},
"cs_plan_would": {"en": "**would have saved {0}** (not acted on, or at a price not billed)",
"de": "**hätte {0} gespart** (nicht ausgeführt oder zu einem nicht abgerechneten Preis)"},
"cs_plan_none_month": {"en": "no plan this month yet", "de": "diesen Monat noch kein Plan"},
"cs_savings_how": {"en": "Building offer: the same metered kWh at your own supplier's price. Plan: the plan's "
"estimate of each quarter-hour with and without its actions, at the same prices.",
"de": "Angebot des Gebäudes: dieselben gemessenen kWh zum Preis Ihres eigenen Lieferanten. "
"Plan: die Schätzung des Plans je Viertelstunde mit und ohne seine Aktionen, zu "
"denselben Preisen."},
"cg_failed": {"en": "could not be computed ({0})", "de": "konnte nicht berechnet werden ({0})"},
"cg_no_prices_day": {"en": "no prices yet", "de": "noch keine Preise"},
"cg_no_prices_today": {"en": "no prices for today: no tariff received, or it has expired",
"de": "keine Preise für heute: kein Tarif empfangen oder abgelaufen"},
"cg_no_price_now": {"en": "no electricity price for now in the tariff", "de": "kein Strompreis für jetzt im Tarif"},
"cg_no_own_curve": {"en": "the tariff names a building offer but not your own supplier's price: "
"its saving cannot be computed",
"de": "der Tarif nennt ein Angebot des Gebäudes, aber nicht den Preis Ihres eigenen "
"Lieferanten: dessen Ersparnis ist nicht berechenbar"},
"cg_no_forecast_param": {"en": "no forecast: the parameter {0} is not in the tariff (Parameters page)",
"de": "keine Prognose: der Parameter {0} fehlt im Tarif (Parameter-Seite)"},
"cg_no_fixed": {"en": "fixed charges unknown: the tariff does not carry them yet",
"de": "Grundpreise unbekannt: der Tarif enthält sie noch nicht"},
"cg_no_meter_electricity": {"en": "no grid meter mapped (energy from the grid or grid power)",
"de": "kein Netzzähler zugeordnet (Energie aus dem Netz oder Netzleistung)"},
"cg_no_meter_gas": {"en": "gas is priced but no gas meter is mapped", "de": "Gas hat einen Preis, aber kein Gaszähler ist zugeordnet"},
"cg_no_meter_heat": {"en": "heat is priced but no heat meter is mapped",
"de": "Wärme hat einen Preis, aber kein Wärmezähler ist zugeordnet"},
"cg_no_meter_data": {"en": "no metered values this month yet", "de": "diesen Monat noch keine Messwerte"},
"cg_unpriced": {"en": "{0} kWh without a price", "de": "{0} kWh ohne Preis"},
"cg_unpriced_of": {"en": "{0}: {1} kWh this month had no price (no tariff then): the cost is at least the figure shown",
"de": "{0}: {1} kWh diesen Monat hatten keinen Preis (damals kein Tarif): die Kosten sind mindestens der gezeigte Wert"},
"cg_forecast_short": {"en": "less than an hour metered: no forecast yet",
"de": "weniger als eine Stunde gemessen: noch keine Prognose"},
"cg_no_plan": {"en": "no plan: Cantabile controls no device here", "de": "kein Plan: Cantabile steuert hier kein Gerät"},
"cg_no_plan_yet": {"en": "no plan with prices this month yet", "de": "diesen Monat noch kein Plan mit Preisen"},
} }
+163 -10
View File
@@ -34,7 +34,11 @@ able to come back); the executor's guard enforces them hard on every action.
Device models (one function each, small and replaceable): Device models (one function each, small and replaceable):
battery state of charge (estimated from params.soc_pct when no sensor), battery state of charge (estimated from params.soc_pct when no sensor),
charge/discharge power, efficiency, never both at once (binary) charge/discharge power, efficiency, never both at once (binary);
the last charge free within its bounds, each kWh left worth V
(end_value: the Parameters page's battery.end_value_pct of the
mean feed-in price, under the cheapest import price; missing:
0, noted in the plan's "notes")
heating a room's first-order thermal model (R in K/kW, C in kWh/K, the heating a room's first-order thermal model (R in K/kW, C in kWh/K, the
cooling outside temperature, heat from the device, from the sun cooling outside temperature, heat from the device, from the sun
through the room's covers, and the fit's internal gain and sun through the room's covers, and the fit's internal gain and sun
@@ -92,6 +96,12 @@ The building's requests (building.py, state["building"]): a load limit on
the grid import and a thermostat cap are constraints with a penalty (binding the grid import and a thermostat cap are constraints with a penalty (binding
far above any price, flexible with a price), a shift request a soft target far above any price, flexible with a price), a shift request a soft target
(the window's import lowered by its kWh against the house's own net load). (the window's import lowered by its kWh against the house's own net load).
A battery plan (the building's one plan for its battery, its own box
following it) is a tracking target per step: the batteries' grid-side power
(their sum) at the building's W, each kWh off it at the request's penalty
(above any price, below the owner's floors and the SoC bounds, which win:
battery_plan). The battery's plan entries then say "building <id>: ..." and
stay setpoints (not the inverter's own self-consumption mode).
The owner's preferences (preferences.py, a device's "pref"): a room's The owner's preferences (preferences.py, a device's "pref"): a room's
target per step from its schedule (in place of the occupied hours) at the target per step from its schedule (in place of the occupied hours) at the
@@ -139,6 +149,10 @@ NO_PRICE_EUR_KWH = 1e-4 # EUR per kWh through the meter and per kWh a device u
# only (ENG: a tie-break toward the least energy, not a price) # only (ENG: a tie-break toward the least energy, not a price)
SPILL_EUR_KWH = 1e-3 # EUR per kWh of PV curtailed (ENG: never curtail while the meter takes it; SPILL_EUR_KWH = 1e-3 # EUR per kWh of PV curtailed (ENG: never curtail while the meter takes it;
# above NO_PRICE_EUR_KWH so export wins over spill without a tariff) # above NO_PRICE_EUR_KWH so export wins over spill without a tariff)
END_VALUE_KEY = "battery.end_value_pct" # the Parameters page's (via the tariff bundle's params): % of the
# mean feed-in price a kWh left in the battery at the end is worth
END_VALUE_GAP_CT = 0.5 # ct/kWh: the end value at least this far below the cheapest import price (ENG: never
# buy grid energy into the battery only to keep it; building/mieterstrom.py's twin)
GRID_MAX_W = 43470.0 # W: the site's connection when the state does not say (state["grid_max_w"], GRID_MAX_W = 43470.0 # W: the site's connection when the state does not say (state["grid_max_w"],
# config grid_max_w): a German house connection's usual 63 A main fuse, # config grid_max_w): a German house connection's usual 63 A main fuse,
# 3 x 230 V x 63 A # 3 x 230 V x 63 A
@@ -304,6 +318,27 @@ class Model:
imp = sum((self.dt * self.meter_in(t) for t in range(a, b)), start=Lin()) imp = sum((self.dt * self.meter_in(t) for t in range(a, b)), start=Lin())
self.h.addConstr(imp - miss <= target) self.h.addConstr(imp - miss <= target)
def battery_plan(self):
"""The building's plan for its battery (state["building"]
["battery_plan"], building.py; docs/methods.md A9.3): per step it
covers, the battery's grid-side power (charge - discharge) tracks
the target, each W off it costing penalty x dt / 1000 (EUR per kWh
of deviation). A site with several batteries: their sum tracks it.
The SoC bounds and the owner's reserve (PENALTY_LIMIT, per % and
step) cost far more, so they win; no battery planned: nothing."""
bp = (self.s.get("building") or {}).get("battery_plan")
bats = [v for kind, v in self.devices.values() if kind == "battery" and v]
if not bp or not bats:
return
ws = bp["schedule_w"]
for t in range(max(0, bp["from_step"]), min(self.T, bp["to_step"], len(ws))):
if ws[t] is None:
continue
pos = self.var(cost=bp["penalty"] * self.dt / 1000.0)
neg = self.var(cost=bp["penalty"] * self.dt / 1000.0)
net = sum((v["ch"][t] - v["dis"][t] for v in bats), start=Lin())
self.h.addConstr(net - pos + neg == float(ws[t]))
def grid_order(self): def grid_order(self):
"""The grid operator's limit on the controllable consumers' draw.""" """The grid operator's limit on the controllable consumers' draw."""
o = self.s.get("grid_order") or {} o = self.s.get("grid_order") or {}
@@ -321,6 +356,40 @@ class Model:
self.h.addConstr(expr == s["load_w"][t] - s["pv_w"][t]) self.h.addConstr(expr == s["load_w"][t] - s["pv_w"][t])
# -- devices --------------------------------------------------------- # -- devices ---------------------------------------------------------
def end_value(self) -> float:
"""V, ct per kWh left in a battery at the plan's end (docs/methods.md
A2.5, as the building's D5.17): the Parameters page's
battery.end_value_pct (state["params"], the tariff bundle's) of the
horizon's mean export price, at most END_VALUE_GAP_CT below its
cheapest import price (never grid energy bought only to keep it),
never below 0. 0 without a tariff, without an export price or
without the parameter (noted: self.end_note)."""
if hasattr(self, "_end_v"):
return self._end_v
self._end_v, self.end_note = 0.0, ""
if not self.priced:
return 0.0
raw = (self.s.get("params") or {}).get(END_VALUE_KEY)
try:
pct = float(raw)
except (TypeError, ValueError):
pct = None
if pct is None or not math.isfinite(pct):
self.end_note = f"{END_VALUE_KEY} missing: the battery's charge at the end valued at 0"
return 0.0
pe = [p for p in (self.s.get("price_export") or [])[:self.T] if p is not None]
if not pe:
self.end_note = "no export price: the battery's charge at the end valued at 0"
return 0.0
v = pct / 100.0 * sum(pe) / len(pe)
cheapest = min(self.s["price_import"][:self.T])
if v > cheapest - END_VALUE_GAP_CT:
v = cheapest - END_VALUE_GAP_CT
self.end_note = (f"the battery's end value capped at {max(0.0, v):.1f} ct/kWh, "
f"{END_VALUE_GAP_CT:g} ct below the cheapest import price")
self._end_v = max(0.0, v)
return self._end_v
def battery(self, d): def battery(self, d):
p, st, b = d["params"], d["state"], d["bounds"] p, st, b = d["params"], d["state"], d["bounds"]
cap = max(1.0, float(p["capacity_wh"])) cap = max(1.0, float(p["capacity_wh"]))
@@ -330,7 +399,6 @@ class Model:
max_ch = max(0.0, min(float(p["max_charge_w"]), phi)) max_ch = max(0.0, min(float(p["max_charge_w"]), phi))
max_dis = max(0.0, min(float(p["max_discharge_w"]), -plo)) max_dis = max(0.0, min(float(p["max_discharge_w"]), -plo))
soc0 = cap * min(max(float(st["soc_pct"]), 0.0), 100.0) / 100.0 soc0 = cap * min(max(float(st["soc_pct"]), 0.0), 100.0) / 100.0
mean_price = sum(self.s["price_import"]) / self.T if self.priced else None
soc, prev, ch, dis = [], soc0, [], [] soc, prev, ch, dis = [], soc0, [], []
pref = d.get("pref") # the owner's reserve per step (preferences.py) pref = d.get("pref") # the owner's reserve per step (preferences.py)
floors = [] floors = []
@@ -355,11 +423,12 @@ class Model:
ch.append(c) ch.append(c)
dis.append(x) dis.append(x)
prev = e prev = e
# energy left at the end is worth the mean price: no draining at the # the end value (docs/methods.md A2.5, as the building's D5.17): the
# horizon (without a tariff nothing is drained for a price anyway) # last charge is free within its bounds, each kWh left in it worth V
if mean_price is not None: # (without a tariff nothing is drained for a price anyway: V 0)
short = self.var(cost=mean_price / 100.0 / 1000.0) v_ct = self.end_value()
self.h.addConstr(prev + short >= min(soc0, hi_pct / 100.0 * cap)) if v_ct:
self.cost.append((-v_ct / 100.0 / 1000.0, prev))
self.smooth([c - x for c, x in zip(ch, dis)]) self.smooth([c - x for c, x in zip(ch, dis)])
self.devices[d["id"]] = ("battery", {"ch": ch, "dis": dis, "soc": soc, "cap": cap, "max_dis": max_dis, self.devices[d["id"]] = ("battery", {"ch": ch, "dis": dis, "soc": soc, "cap": cap, "max_dis": max_dis,
"floor_wh": lo_pct / 100.0 * cap, "floors": floors, "floor_wh": lo_pct / 100.0 * cap, "floors": floors,
@@ -611,6 +680,7 @@ class Model:
elif k == "ev": elif k == "ev":
self.ev(d) self.ev(d)
self.building() self.building()
self.battery_plan()
self.grid_order() self.grid_order()
self.balance() self.balance()
obj = sum((c * v for c, v in self.cost), start=Lin()) obj = sum((c * v for c, v in self.cost), start=Lin())
@@ -732,6 +802,17 @@ def plan(s: dict, time_limit: float = 30.0) -> dict:
"baseline_eur": round(base, 2) if base is not None else None, "baseline_eur": round(base, 2) if base is not None else None,
"priced": m.priced, "steps": T, "price_state": s.get("prices") or {}, "priced": m.priced, "steps": T, "price_state": s.get("prices") or {},
"price_note": s.get("price_note", ""), "sources": s.get("sources", {})} "price_note": s.get("price_note", ""), "sources": s.get("sources", {})}
bats = [v for kind, v in m.devices.values() if kind == "battery" and v]
if bats and m.priced:
# the batteries' end value (A2.5): V and the change of their charge at it, not in cost_eur
v_ct = m.end_value()
out["battery_end"] = {"value_ct": round(v_ct, 2), "store_eur": round(sum(
v_ct / 100.0 * (x(b["soc"][-1]) - b["soc0"]) / 1000.0 for b in bats), 2)}
if getattr(m, "end_note", ""):
out["notes"] = [m.end_note] # what the plan assumed for want of a fact (also published)
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)
if heat_cost["gas_eur"] or heat_cost["heat_eur"]: if heat_cost["gas_eur"] or heat_cost["heat_eur"]:
out["gas_eur"], out["heat_eur"] = round(heat_cost["gas_eur"], 2), round(heat_cost["heat_eur"], 2) out["gas_eur"], out["heat_eur"] = round(heat_cost["gas_eur"], 2), round(heat_cost["heat_eur"], 2)
# rooms not planned (inputs.room_refusal): the thermostat's # rooms not planned (inputs.room_refusal): the thermostat's
@@ -1039,7 +1120,8 @@ def shift_envelope(m, x) -> dict | None:
battery base_w (the planned grid-side power: charge > 0, discharge battery base_w (the planned grid-side power: charge > 0, discharge
< 0), soc_wh (the state of charge at the start), lo_wh per < 0), soc_wh (the state of charge at the start), lo_wh per
step (its floor: the bounds and the owner's reserve), max_wh step (its floor: the bounds and the owner's reserve), max_wh
(its ceiling), ch_w, dis_w (its power), eta (one way), end_wh (the planned (its ceiling), cap_wh (its capacity: a metered % in Wh for
the building's coordinator), ch_w, dis_w (its power), eta (one way), end_wh (the planned
last state of charge: the building keeps at least it) last state of charge: the building keeps at least it)
ev, heating, cooling ev, heating, cooling
base_w (planned), up_w / down_w (the most it can draw above / base_w (planned), up_w / down_w (the most it can draw above /
@@ -1071,7 +1153,8 @@ def shift_envelope(m, x) -> dict | None:
base = [_x(x, v["ch"][t]) - _x(x, v["dis"][t]) for t in range(n)] base = [_x(x, v["ch"][t]) - _x(x, v["dis"][t]) for t in range(n)]
out.append({"id": d["id"], "kind": "battery", "base_w": [round(b) for b in base], out.append({"id": d["id"], "kind": "battery", "base_w": [round(b) for b in base],
"soc_wh": round(v["soc0"]), "lo_wh": [round(v["floors"][t] / 100.0 * v["cap"]) for t in range(n)], "soc_wh": round(v["soc0"]), "lo_wh": [round(v["floors"][t] / 100.0 * v["cap"]) for t in range(n)],
"max_wh": round(v["hi_wh"]), "ch_w": round(v["max_ch"]), "dis_w": round(v["max_dis"]), "max_wh": round(v["hi_wh"]), "cap_wh": round(v["cap"]),
"ch_w": round(v["max_ch"]), "dis_w": round(v["max_dis"]),
"eta": round(v["eff"], 4), "end_wh": round(_x(x, v["soc"][n - 1]))}) "eta": round(v["eff"], 4), "end_wh": round(_x(x, v["soc"][n - 1]))})
elif kind == "ev": elif kind == "ev":
if not v.get("known") or v["pmax"] <= 0: if not v.get("known") or v["pmax"] <= 0:
@@ -1239,6 +1322,14 @@ def _entry(d, kind, v, t, x, s, pi, grid_w=(1e9, 1e9)):
net = _round(net, 50.0) net = _round(net, 50.0)
surplus = s["pv_w"][t] - s["load_w"][t] surplus = s["pv_w"][t] - s["load_w"][t]
grid = net > max(0.0, surplus) + 50 grid = net > max(0.0, surplus) + 50
bp = (s.get("building") or {}).get("battery_plan")
target = bp["schedule_w"][t] if bp and t < len(bp["schedule_w"]) else None
if target is not None:
# the building's plan for its battery (Model.battery_plan): a setpoint, not the own mode
why = f"building {bp['building']}: its battery plan ({target:+.0f} W)"
if abs(net - target) > GRID_ZERO_W:
why += ", within your battery's limits and reserve"
return {"set": net, "grid": grid, "why": why}
if not s.get("priced", True): if not s.get("priced", True):
# no tariff: the battery in its own mode, unless the owner's # no tariff: the battery in its own mode, unless the owner's
# reserve needs charging from the grid # reserve needs charging from the grid
@@ -1337,7 +1428,11 @@ def _entry(d, kind, v, t, x, s, pi, grid_w=(1e9, 1e9)):
return {"set": amps, "why": f"cheapest hours before departure ({pi[t]:.1f} ct){ph}"} return {"set": amps, "why": f"cheapest hours before departure ({pi[t]:.1f} ct){ph}"}
if kind == "cover" and v.get("schedule"): if kind == "cover" and v.get("schedule"):
sch = v["schedule"] sch = v["schedule"]
return {"set": sch["set"][t], "why": sch["why"][t] if sch["set"][t] is not None else ""} if sch["set"][t] is None:
return {"set": None, "why": ""}
rule = (sch.get("rule") or [""] * (t + 1))[t]
# the rule it moves for: the executor keeps it for the next plans (shades.Moves)
return {"set": sch["set"][t], "why": sch["why"][t], **({"rule": rule} if rule else {})}
if kind == "cover": if kind == "cover":
pos = _round(100 * x(v["pos"][t]), 10.0) pos = _round(100 * x(v["pos"][t]), 10.0)
sun = s["sun"][t] sun = s["sun"][t]
@@ -1384,6 +1479,64 @@ def baseline(s, m, x) -> float:
return cost return cost
def step_costs(s, m, x) -> dict | None:
"""Per step and carrier what the plan costs and what the same step
would cost without it, at the same prices (EUR; costs.py books the step
of each quarter-hour as the household's saving by the plan, methods.md
A12):
electricity plan: the meter's import less its feed-in at the step's
prices; without: the house's net load at those prices (no
battery) and the planned devices' electric energy of the
step at the horizon's mean import price (a car's at the
mean of its as-soon-as-possible steps), as baseline()
gas, heat the heating's gas or district heat of the step at its
price, against the same energy at the horizon's mean price
A step's saving can be negative (a battery charging now for later). The
market's contracts are not in it. None without a tariff."""
if not m.priced:
return None
T, pi, pe = m.T, s["price_import"], s["price_export"]
el_plan = [m.eur_wh(t, pi[t]) * x(m.gin[t]) - m.eur_wh(t, pe[t]) * x(m.gout[t]) for t in range(T)]
el_base = []
for t in range(T):
net = s["load_w"][t] - s["pv_w"][t]
el_base.append(m.eur_wh(t, pi[t]) * max(net, 0) - m.eur_wh(t, pe[t]) * max(-net, 0))
mean = sum(pi) / T
out = {"electricity": {"plan": el_plan, "base": el_base}}
for carrier, col, key in (("gas", "gas", "price_gas"), ("heat", "district", "price_heat")):
prices = (s.get(key) or [])[:T]
ps = [p for p in prices if p is not None]
if not ps:
continue
mp = sum(ps) / len(ps)
plan_c, base_c, used = [0.0] * T, [0.0] * T, False
for kind, v in m.devices.values():
if kind != "heating" or not v:
continue
for t, var in enumerate(v.get(col) or []):
if var is not None and t < len(prices) and prices[t] is not None:
used = True
plan_c[t] += m.eur_wh(t, prices[t]) * x(var)
base_c[t] += m.eur_wh(t, mp) * x(var)
if used:
out[carrier] = {"plan": plan_c, "base": base_c}
for kind, v in m.devices.values():
if not v:
continue
if kind in ("heating", "cooling"):
for t in range(T):
if v["power"][t] is not None:
el_base[t] += m.eur_wh(t, mean) * x(v["power"][t])
elif kind == "ev":
wh = sum(m.dt * x(p) for p in v["power"] if p is not None)
asap = pi[:max(1, math.ceil(wh / max(1.0, v["volts"] * 16) / m.dt))]
amean = sum(asap) / len(asap)
for t, p in enumerate(v["power"]):
if p is not None:
el_base[t] += m.eur_wh(t, amean) * x(p)
return {c: {k: [round(y, 5) for y in ys] for k, ys in d.items()} for c, d in out.items()}
def main(): def main():
s = json.load(sys.stdin) s = json.load(sys.stdin)
limit = float(sys.argv[1]) if len(sys.argv) > 1 else 30.0 limit = float(sys.argv[1]) if len(sys.argv) > 1 else 30.0
+61 -5
View File
@@ -34,14 +34,24 @@ Per 15-minute step of the plan, for a shade with its window's orientation
The season: the room's heating or cooling control (params.room; of a The season: the room's heating or cooling control (params.room; of a
thermostat that does both, its active side: switchover.py), else by month thermostat that does both, its active side: switchover.py), else by month
(heating October to April). An entry is a move: {"set": position %} in the (heating October to April). An entry is a move: {"set": position %, "rule": "shade" | "night" | ""} in
step the shade is to move, then {"set": None} (hold: the executor leaves it the step the shade is to move, then {"set": None} (hold: the executor leaves
alone), so a shade the owner moved by hand is never pushed back later; the it alone), so a shade the owner moved by hand is never pushed back later; the
guard's override pause (params.override_hold_s) keeps the agent off it. guard's override pause (params.override_hold_s) keeps the agent off it.
What the agent's last move was for (Moves, <state dir>/shades.json: the rule,
the position, when) carries into the next plans while the shade is still
where the agent put it: a shade closed for the night opens in the morning,
one shaded from the sun opens when the sun has left, though every plan after
the move starts from the shade as it is (2026-11-05: Munich 1's shade closed
on 30 October and stayed closed; each plan forgot why it was closed).
HA's position: 0 closed, 100 open. HA's position: 0 closed, 100 open.
""" """
import json
import math import math
import os
import time
from datetime import datetime, timezone from datetime import datetime, timezone
from zoneinfo import ZoneInfo from zoneinfo import ZoneInfo
@@ -168,13 +178,17 @@ def schedule(d: dict, s: dict, ctx: dict | None = None) -> dict:
pos0 = st.get("position_pct") pos0 = st.get("position_pct")
pos = float(pos0) if pos0 is not None else float(open_pct) pos = float(pos0) if pos0 is not None else float(open_pct)
sets, whys, track, suns = [], [], [], [] sets, whys, track, suns = [], [], [], []
ours = None # what the last rule moved it for (shade, night) # what the last rule moved it for (shade, night): the agent's last move
# (Moves.ours) while the shade is still where it put it
ours = ctx.get("ours") if ctx.get("ours") in ("shade", "night") else None
rules = []
last_move = -math.inf last_move = -math.inf
for k in range(T): for k in range(T):
ts = s["start"] + k * step ts = s["start"] + k * step
local = datetime.fromtimestamp(ts, timezone.utc).astimezone(zone) local = datetime.fromtimestamp(ts, timezone.utc).astimezone(zone)
if lat is None or lon is None: if lat is None or lon is None:
sets.append(None) sets.append(None)
rules.append("")
whys.append("no site location: the sun's position is not known") whys.append("no site location: the sun's position is not known")
track.append(pos) track.append(pos)
suns.append(0.0) suns.append(0.0)
@@ -210,14 +224,56 @@ def schedule(d: dict, s: dict, ctx: dict | None = None) -> dict:
if move: if move:
pos, last_move, ours = float(want), ts, kind pos, last_move, ours = float(want), ts, kind
sets.append(int(want)) sets.append(int(want))
rules.append(kind or "")
whys.append(why) whys.append(why)
else: else:
rules.append("")
if want is not None and abs(want - pos) <= 2 and kind is None: if want is not None and abs(want - pos) <= 2 and kind is None:
ours = None # back where it was before the rule: nothing of ours to undo ours = None # back where it was before the rule: nothing of ours to undo
sets.append(None) sets.append(None)
whys.append("quiet hours" if hushed and want is not None and abs(want - pos) > 2 else "") whys.append("quiet hours" if hushed and want is not None and abs(want - pos) > 2 else "")
track.append(pos) track.append(pos)
return {"set": sets, "why": whys, "pos": track, "sun": suns, "facade": face is not None} return {"set": sets, "why": whys, "rule": rules, "pos": track, "sun": suns, "facade": face is not None}
class Moves:
"""The agent's last move per shade (<state dir>/shades.json): the rule it
was for ("shade", "night", "" for the rest: a command, a reopening), the
position and when. Kept across restarts: a box started again at night
still opens the shade it closed in the morning."""
TOL = 3.0 # % : still where the agent put it (the guard's own tolerance)
def __init__(self, state_dir: str):
self.path = os.path.join(state_dir, "shades.json")
try:
with open(self.path) as f:
d = json.load(f)
self.moves = d if isinstance(d, dict) else {}
except (OSError, ValueError):
self.moves = {}
def record(self, cid: str, rule: str, pos: float, at: float | None = None):
self.moves[cid] = {"rule": rule if rule in ("shade", "night") else "", "pos": float(pos),
"at": int(time.time() if at is None else at)}
tmp = self.path + ".tmp"
try:
with open(tmp, "w") as f:
json.dump(self.moves, f)
os.replace(tmp, self.path)
except OSError:
pass # kept in memory: the next move tries again
def ours(self, cid: str, pos_now) -> str | None:
"""The rule the agent last moved the shade for, while it is still
there (moved by hand: none, the owner's position stays)."""
m = self.moves.get(cid)
if not isinstance(m, dict) or not m.get("rule") or pos_now is None:
return None
try:
return m["rule"] if abs(float(pos_now) - float(m["pos"])) <= self.TOL else None
except (TypeError, ValueError, KeyError):
return None
def say(set_value, lang: str = "en") -> str: def say(set_value, lang: str = "en") -> str:
+66
View File
@@ -0,0 +1,66 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The battery's end value on the box (optimizer.py Model.end_value;
docs/methods.md A2.5, as the building's D5.17): the last charge free
within its bounds, each kWh left worth battery.end_value_pct of the mean
feed-in price, capped below the cheapest import price; missing facts: 0
and a note, the battery still planned."""
import pytest
highspy = pytest.importorskip("highspy")
from cantabile_edge import optimizer # noqa: E402
from test_optimizer import battery, house # noqa: E402
def solve(s):
m = optimizer.Model(optimizer._prepare(s))
m.solve(20)
v = m.h.getSolution().col_value
d = m.devices["battery"][1]
return m, [v[e.index] for e in d["soc"]], d["soc0"]
def test_a_full_battery_discharges_into_the_dear_evening():
s = house([battery(soc=100)])
s["params"] = {"battery.end_value_pct": 100}
m, soc, soc0 = solve(s)
assert m.end_value() == pytest.approx(8.0) # 100 % of the 8 ct feed-in
assert soc[-1] < soc0 - 1000 # no longer held at its start
p = optimizer.plan(s, 20)
assert p["battery_end"]["value_ct"] == 8.0 and p["battery_end"]["store_eur"] < 0
assert "notes" not in p
def test_an_empty_battery_is_not_filled_for_the_end():
s = house([battery(soc=20)])
s["price_import"] = [30.0] * s["steps"] # a flat price: nothing to shift
s["params"] = {"battery.end_value_pct": 100}
_, soc, soc0 = solve(s)
assert max(soc) <= soc0 + 50
def test_the_end_value_capped_below_the_cheapest_import():
s = house([battery(soc=20)])
s["price_export"] = [20.0] * s["steps"] # a feed-in above the night's 12 ct import
s["params"] = {"battery.end_value_pct": 100}
m, soc, soc0 = solve(s)
assert m.end_value() == pytest.approx(11.5) # 0.5 ct below the cheapest import
assert "capped" in m.end_note
assert soc[-1] <= soc0 + 50 # no grid energy bought only to keep it
assert any("capped" in n for n in optimizer.plan(s, 20)["notes"])
def test_a_missing_parameter_is_noted_and_the_battery_still_planned():
s = house([battery(soc=60)])
p = optimizer.plan(s, 20)
assert p["devices"]["battery"] and "battery" not in (p.get("refused") or {})
assert p["notes"] == ["battery.end_value_pct missing: the battery's charge at the end valued at 0"]
assert p["battery_end"]["value_ct"] == 0
def test_no_export_price_values_the_end_at_zero():
s = house([battery(soc=60)])
s["price_export"] = [None] * s["steps"]
s["params"] = {"battery.end_value_pct": 100}
m, _, _ = solve(s)
assert m.end_value() == 0 and m.end_note.startswith("no export price")
+108
View File
@@ -0,0 +1,108 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The building's plan for its battery (building.py battery_plan,
optimizer.py Model.battery_plan; docs/methods.md A9.3): the box's plan
follows the building's schedule within the battery's power and SoC limits,
the owner's floor wins over it, nothing changes without it, and the shift
envelope carries the battery's capacity."""
import pytest
highspy = pytest.importorskip("highspy")
from cantabile_edge import optimizer # noqa: E402
from cantabile_edge.building import Building # noqa: E402
from test_control_parts import Clock # noqa: E402
from test_optimizer import START, battery, house as _house # noqa: E402
def house(devices):
s = _house(devices)
s["params"] = {"battery.end_value_pct": 100} # the end value (A2.5) as the Parameters page's
return s
def with_plan(s, tmp_path, ws, frm=START, level="binding"):
"""The state with a battery_plan taken as the controller takes it (Building.for_model)."""
b = Building(str(tmp_path), Clock(START))
ok, why = b.take(b.parse({"v": "1", "id": "p1", "building": "house-7", "level": level,
"control": "battery_plan", "value": str(ws[0]), "from": str(frm),
"until": str(frm + 900 * len(ws)), "why": "the building's plan",
"schedule": ",".join(str(w) for w in ws), "step_s": "900"}), [])
assert ok, why
s["building"] = b.for_model(START, 900, s["steps"])
return s
def solved(s):
m = optimizer.Model(s)
m.solve(20)
v = m.h.getSolution().col_value
out = {}
for did, (kind, d) in m.devices.items():
if kind == "battery":
out[did] = ([v[c.index] - v[x.index] for c, x in zip(d["ch"], d["dis"])], [v[e.index] for e in d["soc"]])
return out
def test_follows_the_schedule_within_power_and_soc(tmp_path):
# at night (cheap, 12 ct) the box alone would never discharge; the building asks 3 kW for an hour,
# then 5 kW for 30 min (more than the battery's 3 kW)
alone, _ = solved(house([battery(soc=80)]))["battery"]
assert all(p > -100 for p in alone[4:10])
s = with_plan(house([battery(soc=80)]), tmp_path, [-3000] * 4 + [-5000] * 2, frm=START + 4 * 900)
p, soc = solved(s)["battery"]
assert p[4:8] == pytest.approx([-3000] * 4, abs=1)
assert p[8:10] == pytest.approx([-3000] * 2, abs=1) # its power limit, not the building's 5 kW
assert min(soc) >= 2000 - 1 # its floor (20 %)
# the plan's entries say so, as setpoints (not the inverter's own mode)
e = [x for x in optimizer.plan(s, 20)["devices"]["battery"] if START + 4 * 900 <= x["t"] < START + 10 * 900]
assert e and all(x["why"].startswith("building house-7: its battery plan") and not x.get("auto") for x in e)
m = optimizer.Model(s)
m.solve(20)
v = m.h.getSolution().col_value
x = lambda var: v[var.index] # noqa: E731
d = m.devices["battery"][1]
e8 = optimizer._entry(s["devices"][0], "battery", d, 8, x, s, s["price_import"])
assert e8["why"] == "building house-7: its battery plan (-5000 W), within your battery's limits and reserve"
def test_flexible_still_follows_against_the_price(tmp_path):
s = with_plan(house([battery(soc=80)]), tmp_path, [-3000] * 4, frm=START + 4 * 900, level="flexible")
p, _ = solved(s)["battery"]
assert p[4:8] == pytest.approx([-3000] * 4, abs=1)
def test_the_owners_floor_wins(tmp_path):
# 80 % with the owner's floor at 70 %, from the plan's first step (no time to charge first):
# 4 x 3 kW would leave about 48 %; the floor holds
s = with_plan(house([battery(soc=80, floor=70)]), tmp_path, [-3000] * 4)
p, soc = solved(s)["battery"]
assert min(soc) >= 7000 - 1
assert sum(p[0:4]) > -4 * 3000 + 1000 # it did not follow all the way
def test_several_batteries_track_the_sum(tmp_path):
b2 = dict(battery(soc=80), id="battery2")
s = with_plan(house([battery(soc=80), b2]), tmp_path, [-4000] * 4, frm=START + 4 * 900)
r = solved(s)
total = [a + b for a, b in zip(r["battery"][0], r["battery2"][0])]
assert total[4:8] == pytest.approx([-4000] * 4, abs=1)
def test_nothing_changes_without_it(tmp_path):
plain = optimizer.plan(house([battery(soc=80)]), 20)["devices"]["battery"]
s = house([battery(soc=80)])
s["building"] = {}
assert optimizer.plan(s, 20)["devices"]["battery"] == plain
# a plan that covers no step of this window: nothing either
s = house([battery(soc=80)])
s["building"] = {"battery_plan": {"schedule_w": [None] * s["steps"], "from_step": 0, "to_step": 0,
"penalty": 5.0, "level": "binding", "id": "p1", "building": "house-7"}}
assert optimizer.plan(s, 20)["devices"]["battery"] == plain
def test_shift_envelope_has_the_capacity():
b = battery(soc=50)
b["bounds"]["soc_pct"][1] = 90
sh = optimizer.plan(house([b]), 20)["flex"]["shift"]
d = next(x for x in sh["devices"] if x["kind"] == "battery")
assert d["cap_wh"] == 10000 and d["max_wh"] == 9000
+66
View File
@@ -114,3 +114,69 @@ def test_cap_on_actions_and_overrides(tmp_path, mapping, consent): # no
asyncio.run(ex.tick(ha, auto=True)) asyncio.run(ex.tick(ha, auto=True))
assert "thermostat_cap" not in b.active assert "thermostat_cap" not in b.active
assert any("flexible cap ended" in m["why"] for m in sent) assert any("flexible cap ended" in m["why"] for m in sent)
def bplan(ws, level="binding", frm=START, step_s="900", cid="p1", until=None):
"""A battery_plan command as fleet sends it (string args)."""
until = frm + 900 * len(ws) if until is None else until
return {"v": "1", "id": cid, "building": "house-7", "level": level, "control": "battery_plan",
"value": str(ws[0] if ws else 0), "from": str(frm), "until": str(until), "why": "the building's plan",
"schedule": ",".join(str(w) for w in ws), "step_s": step_s}
def test_battery_plan_parse(tmp_path):
b = Building(str(tmp_path), Clock(START))
c = b.parse(bplan([-3000, -3000, 1500.5, 0]))
assert c["control"] == "battery_plan" and c["schedule"] == [-3000.0, -3000.0, 1500.5, 0.0] and c["step_s"] == 900
assert c["value"] == -3000.0 # the first slot; a discharge is not refused
with pytest.raises(ValueError, match="schedule has 3 values"):
b.parse(bplan([1, 2, 3], until=START + 4 * 900)) # wrong length
with pytest.raises(ValueError, match="schedule has"):
b.parse(bplan([1, 2], until=START + 2 * 900 + 300)) # not a whole number of steps
with pytest.raises(ValueError, match="step_s 900"):
b.parse(bplan([1, 2], step_s="300"))
with pytest.raises(ValueError, match="step_s 900"):
b.parse({k: v for k, v in bplan([1, 2]).items() if k != "step_s"})
with pytest.raises(ValueError, match="finite"):
b.parse(bplan([1, float("nan")]))
with pytest.raises(ValueError, match="finite"):
b.parse(bplan([1, "inf"]))
with pytest.raises(ValueError, match="finite"):
b.parse(bplan([1, 2e6]))
with pytest.raises(ValueError, match="schedule"):
b.parse(bplan([1, "x"]))
with pytest.raises(ValueError, match="schedule"):
b.parse({k: v for k, v in bplan([1, 2]).items() if k != "schedule"})
with pytest.raises(ValueError, match="never an emergency"):
b.parse({**bplan([1, 2], level="emergency"), "proof": "verified:netz-berlin:o1"})
with pytest.raises(ValueError, match="24 h"):
b.parse(bplan([0] * 97)) # more than 24 h
def test_battery_plan_kept_replaced_and_dropped(tmp_path):
b = Building(str(tmp_path), Clock(START))
assert b.take(b.parse(bplan([-1000] * 8)), [])[0]
ok, why = b.take(b.parse(bplan([500] * 8, cid="p2")), [])
assert ok and "replaces p1" in why # a newer one replaces
again = Building(str(tmp_path), Clock(START + 600)) # a restart: kept with its schedule
assert again.active["battery_plan"]["id"] == "p2" and again.active["battery_plan"]["schedule"] == [500.0] * 8
assert again.for_model(START, 900, 192)["battery_plan"]["schedule_w"][:8] == [500.0] * 8
assert Building(str(tmp_path), Clock(START + 8 * 900)).active == {} # dropped at until
def test_battery_plan_for_model_alignment(tmp_path):
# the command from START, the model starting 2 steps later: past slots skipped
b = Building(str(tmp_path), Clock(START + 1800))
b.take(b.parse(bplan([10, 20, 30, 40, 50, 60], level="flexible")), [])
r = b.for_model(START + 1800, 900, 10)["battery_plan"]
assert r["schedule_w"] == [30.0, 40.0, 50.0, 60.0] + [None] * 6
assert (r["from_step"], r["to_step"], r["level"], r["penalty"]) == (0, 4, "flexible", 0.5)
assert (r["id"], r["building"]) == ("p1", "house-7")
# a command starting after the model's start: None before it
(tmp_path / "later").mkdir()
b2 = Building(str(tmp_path / "later"), Clock(START))
b2.take(b2.parse(bplan([-3000] * 4, frm=START + 3 * 900, cid="p3")), [])
r = b2.for_model(START, 900, 10)["battery_plan"]
assert r["schedule_w"] == [None] * 3 + [-3000.0] * 4 + [None] * 3
assert (r["from_step"], r["to_step"], r["penalty"]) == (3, 7, 5.0)
assert b2.for_model(START + 7 * 900, 900, 10) == {} # nothing of it left in this window
+297
View File
@@ -0,0 +1,297 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""The household's own costs (costs.py, methods.md A12): the metered kWh
at the price that applied, the building's offer against the own supplier,
the plan's estimate (saved or would-have in shadow), the month's cost, kept
across restarts; missing data as a gap with its reason, never a 0; the
sensors in HA and the "My energy costs" view."""
import json
import time
import pytest
import yaml
from cantabile_edge import agent as agent_mod
from cantabile_edge import costs, names
from cantabile_edge.announce import Announcer
from cantabile_edge.bundles import Bundles
from cantabile_edge.config import Config
from cantabile_edge.dashboards import Home, dashboard, view_costs
from cantabile_edge.mapping import Mapping
from cantabile_edge.store import Queue
from test_agent import FlakySink
from test_control_parts import MAPPING, SITE
START = 1793865600 # 2026-11-05 08:00 UTC (09:00 in Berlin), a quarter hour
OWN, TENANT = 36.4, 28.0 # ct/kWh gross: the own supplier's and the building's (Mieterstrom)
TZ = "Europe/Berlin"
def tariff(tmp_path, tenant=True, params=None, fixed=None, gas=None, steps=192, billed=False, start=START):
imp = [TENANT if tenant and k < 96 else OWN for k in range(steps)] # the offer the first 24 h
t = {"v": 1, "kind": "tariff", "id": "t-1", "site": SITE, "issued": start, "start": start, "step_s": 900,
"steps": steps, "expires": start + 2 * 86400, "currency": "EUR", "unit": "ct/kWh", "import": imp,
"export": [7.8] * steps, "sources": ["product:own"] + (["mieterstrom:b-1"] if tenant else [])}
if tenant:
t["tenant"] = {"model": "mieterstrom", "plant": "b-1", "name": "Haus Sonne", "shadow": not billed,
"billed": billed, "schema": "", "proposal": "p-1", "made_at": start,
"valid_until": start + 21600, "steps": 96, "own_import": [OWN] * steps}
if params is not None:
t["params"] = params
if fixed is not None:
t["fixed"] = fixed
if gas is not None:
t["gas"] = [gas] * steps
(tmp_path / "tariff.json").write_text(json.dumps(t))
return Bundles(str(tmp_path), SITE)
class Clock:
def __init__(self, t):
self.t = t
def __call__(self):
return self.t
def ledger(tmp_path, bundles, mode="shadow", t=START):
clock = Clock(t)
return costs.Ledger(str(tmp_path), bundles, mode=lambda: mode, tz=lambda: TZ, clock=clock), clock
def counter(asset, wh, last=1000.0):
return {"asset": asset, "kind": "counter", "delta": wh, "last": last, "resets": 0, "n": 1}
def test_amounts_counter_first_then_power_parts_add_and_none_is_no_value():
recs = [counter("grid.import_energy", 250.0), {"asset": "grid.import_power", "kind": "gauge", "mean": 6000.0}]
assert costs.amounts(recs, 60) == {"electricity": 0.25} # the counter wins over the power
assert costs.amounts([{"asset": "grid.import_power", "kind": "gauge", "mean": 6000.0}], 60) == {"electricity": 0.1}
assert costs.amounts([{"asset": "grid.power", "kind": "gauge", "mean": -500.0}], 60) == {"electricity": 0.0}
two = [counter("grid.1.import_energy", 100.0), counter("grid.2.import_energy", 50.0)]
assert costs.amounts(two, 60)["electricity"] == pytest.approx(0.15)
# a counter never read yet: no value (not 0 kWh)
assert costs.amounts([{"asset": "gas.energy", "kind": "counter", "delta": 0.0, "last": None, "n": 0}], 60) == {"gas": None}
assert costs.amounts([{"asset": "load.power", "kind": "gauge", "mean": 5.0}], 60) == {}
def test_slot_prices_offer_own_and_shadow(tmp_path):
b = tariff(tmp_path)
sp = b.slot_prices(START, START)
assert sp["electricity"] == {"price": TENANT, "own": OWN, "offer": True, "billed": False}
late = b.slot_prices(START + 30 * 3600, START) # beyond the offer: the own price
assert late["electricity"]["offer"] is False and late["electricity"]["price"] == OWN
assert b.slot_prices(START - 900, START) is None # before the bundle: not known
assert b.tenant_now(START)["own_known"] is True
d = tmp_path / "own"
d.mkdir()
b2 = tariff(d, tenant=False)
assert b2.slot_prices(START, START)["electricity"] == {"price": OWN, "own": OWN, "offer": False, "billed": True}
assert b2.tenant_now(START) is None
def test_metered_kwh_at_the_price_that_applied_and_the_offer_would_have_saved(tmp_path):
b = tariff(tmp_path, params={costs.PARAM_FORECAST: 7})
lg, clock = ledger(tmp_path, b)
for k in range(60): # an hour, 50 Wh a minute: 3 kWh
clock.t = START + 60 * (k + 1)
lg.add_window(START + 60 * k, START + 60 * (k + 1), [counter("grid.import_energy", 50.0)])
row = lg.month_row("2026-11", "electricity")
assert row["kwh"] == pytest.approx(3.0)
assert row["cost_eur"] == pytest.approx(3.0 * TENANT / 100)
assert row["offer_own_eur"] - row["offer_eur"] == pytest.approx(3.0 * (OWN - TENANT) / 100)
assert row["unbilled_kwh"] == pytest.approx(3.0) # shadow: not billed
rep = costs.report(lg, clock.t, "en", {"electricity": True}, has_plan=False)
sav = rep["savings"]["carriers"]["electricity"]["offer"]
assert sav["month"] == pytest.approx(0.25) and sav["billed"] is False
assert "would have saved 0.25 €" in rep["savings"]["md"] # never "saved" in shadow
c = rep["costs"]["carriers"]["electricity"]
assert c["so_far"] == pytest.approx(0.84) and c["forecast"] > c["so_far"]
assert "own supplier" in c["note"] and c["own_eur"] == pytest.approx(1.09)
# the price table: today per hour, the offer's hours marked, the own supplier's beside them
today = next(d for d in rep["prices"]["days"] if d["key"] == "today")
h07 = next(h for h in today["hours"] if h["h"] == "09")
assert h07["ct"] == TENANT and h07["own"] == OWN and h07["offer"] == 4
assert "<details>" in today["md"] and "Haus Sonne (Mieterstrom)" in today["md"]
assert "Haus Sonne (Mieterstrom)" in rep["prices"]["now_md"] and "not billed" in rep["prices"]["now_md"]
# only the household's own figures: nothing of the building or other flats in what HA gets
assert "b-1" not in json.dumps({k: v for k, v in rep.items() if k != "prices"})
def test_billed_offer_is_saved_and_no_offer_says_so(tmp_path):
b = tariff(tmp_path, billed=True)
lg, clock = ledger(tmp_path, b)
clock.t = START + 60
lg.add_window(START, START + 60, [counter("grid.import_energy", 1000.0)])
rep = costs.report(lg, clock.t, "en", {"electricity": True}, has_plan=False)
assert "0.08 € saved" in rep["savings"]["md"]
d = tmp_path / "own"
d.mkdir()
b2 = tariff(d, tenant=False)
lg2, clock2 = ledger(d, b2)
clock2.t = START + 60
lg2.add_window(START, START + 60, [counter("grid.import_energy", 1000.0)])
rep2 = costs.report(lg2, clock2.t, "de", {"electricity": True}, has_plan=False)
assert names.name("cs_offer_no", "de") in rep2["savings"]["md"]
assert rep2["savings"]["carriers"]["electricity"] == {}
def test_plan_estimate_saved_in_auto_would_in_shadow(tmp_path):
b = tariff(tmp_path, tenant=False)
mode = {"m": "auto"}
clock = Clock(START + 120)
lg = costs.Ledger(str(tmp_path), b, mode=lambda: mode["m"], tz=lambda: TZ, clock=clock)
plan = {"start": START, "step_s": 900, "steps_eur": {"electricity": {"plan": [0.10, 0.2], "base": [0.15, 0.2]},
"gas": {"plan": [0.05], "base": [0.07]}}}
lg.take_plan(plan)
clock.t = START + 900 + 60
lg.add_window(START + 900, START + 960, [counter("grid.import_energy", 10.0)]) # the next slot: booked
row = lg.month_row("2026-11", "electricity")
assert row["saved_eur"] == pytest.approx(0.05) and row["would_eur"] == 0 and row["plan_slots"] == 1
assert lg.month_row("2026-11", "gas")["saved_eur"] == pytest.approx(0.02)
mode["m"] = "shadow"
lg.take_plan(dict(plan, start=START + 900))
clock.t = START + 1800 + 60
lg.add_window(START + 1800, START + 1860, [counter("grid.import_energy", 10.0)])
row = lg.month_row("2026-11", "electricity")
assert row["would_eur"] == pytest.approx(0.05) and row["plan_slots"] == 2
rep = costs.report(lg, clock.t, "en", {"electricity": True, "gas": False}, has_plan=True)
assert "0.05 € saved** (estimated)" in rep["savings"]["md"] and "would have saved 0.05 €" in rep["savings"]["md"]
assert rep["costs"]["carriers"]["gas"]["so_far"] is None # no gas meter: no cost, a reason
assert any(g["why"] == names.name("cg_no_meter_gas", "en") for g in rep["gaps"]) # the plan heats with gas
def test_kept_across_restarts(tmp_path):
b = tariff(tmp_path, tenant=False)
lg, clock = ledger(tmp_path, b)
clock.t = START + 60
lg.add_window(START, START + 60, [counter("grid.import_energy", 500.0)])
lg.close()
lg2, _ = ledger(tmp_path, b, t=START + 120)
assert lg2.month_row("2026-11", "electricity")["kwh"] == pytest.approx(0.5)
def test_gaps_say_why_and_last_month_and_fixed_charges(tmp_path):
# no tariff at all: no price, nothing made up
lg, clock = ledger(tmp_path, Bundles(str(tmp_path), SITE))
clock.t = START + 60
lg.add_window(START, START + 60, [counter("grid.import_energy", 500.0)])
rep = costs.report(lg, clock.t, "en", {"electricity": True}, has_plan=False)
whys = [g["why"] for g in rep["gaps"]]
assert names.name("cg_no_prices_today", "en") in whys and names.name("cg_no_fixed", "en") in whys
assert names.name("cg_no_forecast_param", "en", costs.PARAM_FORECAST) in whys
el = rep["costs"]["carriers"]["electricity"]
assert el["so_far"] == 0.0 and el["incomplete"] is True # at least: 0.5 kWh without a price
assert el["forecast"] is None
# a gas price, but no gas meter: a gap, no cost
d, o = tmp_path / "gas", tmp_path / "october"
d.mkdir()
o.mkdir()
fixed = {"electricity": {"eur_month": 12.4, "incomplete": False}}
b = tariff(d, tenant=False, gas=11.5, params={costs.PARAM_FORECAST: 7}, fixed=fixed)
oct_ = START - 10 * 86400
lg, clock = ledger(d, tariff(o, tenant=False, fixed=fixed, start=oct_), t=oct_ + 60)
# last month (October): 2 kWh at the bundle then in force
lg.add_window(oct_, oct_ + 60, [counter("grid.import_energy", 2000.0)])
lg.bundles = b
for k in range(60):
clock.t = START + 60 * (k + 1)
lg.add_window(START + 60 * k, START + 60 * (k + 1), [counter("grid.import_energy", 20.0)])
rep = costs.report(lg, clock.t, "en", {"electricity": True, "gas": False}, has_plan=False)
assert names.name("cg_no_meter_gas", "en") in [g["why"] for g in rep["gaps"]]
el = rep["costs"]["carriers"]["electricity"]
assert el["fixed_month"] == 12.4 and el["forecast"] > 12.4 # the month's fixed charges in it
assert el["last"] == pytest.approx(2.0 * OWN / 100 + 12.4, abs=0.006)
assert "Fixed charges included." in rep["costs"]["md"]
def test_a_failing_section_is_a_gap_the_others_stay(tmp_path, monkeypatch):
b = tariff(tmp_path, tenant=False)
lg, clock = ledger(tmp_path, b, t=START + 60)
def boom(*a, **k):
raise RuntimeError("broken")
monkeypatch.setattr(costs, "prices_section", boom)
rep = costs.report(lg, clock.t, "en", {"electricity": True}, has_plan=False)
assert rep["prices"] is None and rep["costs"] is not None and rep["savings"] is not None
assert {"section": "prices", "why": "could not be computed (broken)"} in rep["gaps"]
# -- in HA -----------------------------------------------------------------------------
def make_agent(tmp_path):
mp = dict(MAPPING, assets=MAPPING["assets"] + [
{"entity": "sensor.grid_in", "asset": "grid.import_energy", "kind": "counter", "unit": "Wh", "consent": False}])
m = tmp_path / "m.yaml"
m.write_text(yaml.safe_dump(mp))
cfg = Config(site_id=SITE, mapping=str(m), state_dir=str(tmp_path))
a = agent_mod.Agent(cfg, Mapping.load(str(m)), Queue(str(tmp_path / "q.db"), 100), FlakySink())
return a, Announcer(a, "127.0.0.1", 1883)
def test_agent_meters_without_consent_and_ha_sensors(tmp_path):
now = time.time()
tariff(tmp_path, start=int((now - 900) // 900 * 900))
a, ann = make_agent(tmp_path)
assert a.costs is not None and not a.consent.share # no consent: kept on the box all the same, never sent
t0 = a.cost_agg.start = now - 60
a.on_entities({"a": {"sensor.grid_in": {"s": "1000", "a": {"unit_of_measurement": "Wh"}}}})
a.on_entities({"c": {"sensor.grid_in": {"+": {"s": "1400", "lc": now - 1}}}})
a.close_window(now)
assert a.queue.depth() == 0 # nothing queued for the cloud
month = a.costs.month_of(t0)
assert a.costs.month_row(month, "electricity")["kwh"] == pytest.approx(0.4)
objs = ann.objects()
keys = {o for (_, c, o) in objs if c == "sensor"}
assert {"costs", "costs_prices", "cost_electricity", "saving_electricity"} <= keys
conf = objs[(ann.uid, "sensor", "cost_electricity")]
assert conf["default_entity_id"] == "sensor.cantabile_cost_electricity" and conf["device_class"] == "monetary"
st = ann.costs_state(ann.costs_report())
assert st["prices"]["source"] == "offer" and st["cost"]["electricity"]["kwh"] == pytest.approx(0.4)
assert st["saving"]["electricity"]["shadow"] is True
assert "<b>" in st["status"]["alert"] and st["status"]["n"] == len(st["status"]["gaps"])
def test_the_view(tmp_path):
a, _ = make_agent(tmp_path)
uid = f"cantabile_{SITE}"
ours = {f"{uid}_{s}": f"sensor.cantabile_{s}" for s in ("costs", "costs_prices", "cost_electricity",
"saving_electricity", "price_import_now")}
h = Home(a.mapping, uid, ours, [], "de")
v = view_costs(h)
assert v["path"] == "costs" and v["title"] == "Meine Energiekosten"
cards = [c for s in v["sections"] for c in s["cards"]]
alarm = cards[0]
assert "ha-alert" in alarm["content"] and alarm["visibility"][0]["entity"] == "sensor.cantabile_costs"
text = json.dumps(v, ensure_ascii=False)
assert "md_savings" in text and "md_costs" in text and "today_md" in text
assert names.name("cs_unavailable", "de") in text # a missing figure: said, not an error
assert "costs" in [x["path"] for x in dashboard(h)["views"]]
# without the sensors: no view
assert view_costs(Home(a.mapping, uid, {}, [], "en")) is None
def test_plan_step_costs_add_up_to_the_plan_and_its_baseline():
pytest.importorskip("highspy")
from cantabile_edge import optimizer
from test_optimizer import battery, house
p = optimizer.plan(house([battery()]), 20)
se = p["steps_eur"]["electricity"]
assert len(se["plan"]) == p["steps"] == len(se["base"])
assert sum(se["plan"]) == pytest.approx(p["cost_eur"], abs=0.02)
assert sum(se["base"]) == pytest.approx(p["baseline_eur"], abs=0.02)
assert "gas" not in p["steps_eur"]
def test_a_failing_view_leaves_the_dashboard(tmp_path, monkeypatch):
from cantabile_edge import dashboards
a, _ = make_agent(tmp_path)
uid = f"cantabile_{SITE}"
h = Home(a.mapping, uid, {f"{uid}_costs": "sensor.cantabile_costs"}, [], "en")
def boom(h):
raise KeyError("x")
monkeypatch.setattr(dashboards, "view_costs", boom)
views = dashboards.dashboard(h)["views"]
bad = next(v for v in views if v["path"] == "costs")
assert "ha-alert" in json.dumps(bad) and "overview" in [v["path"] for v in views]
+63
View File
@@ -203,3 +203,66 @@ def test_offer_after_reinstall(tmp_path):
out = p.post({"do": "restore", "answer": "yes", "c_r_community": "1", "consent_yes": "1"}) out = p.post({"do": "restore", "answer": "yes", "c_r_community": "1", "consent_yes": "1"})
assert "consents given again" in out assert "consents given again" in out
assert fl.recipient_consent("community") and not fl.recipient_consent("building") assert fl.recipient_consent("community") and not fl.recipient_consent("building")
INV = "7e1a2b3c-1111-4222-8333-944455556666"
OFFER = {"invite": INV, "building": CARD, "unit": {"label": "3B", "confirm_meter": False},
"expires_at": "2026-11-30T10:00:00Z", "from": "Cantabile"}
class InviteFleet(FakeFleet):
"""An operator's invitation addressed to this box (status "offers")."""
def __init__(self, tmp):
super().__init__(tmp)
self.state = {"offers": [OFFER]}
def ask(self, req, timeout=30):
if req["op"] == "preview" and "invite" in req:
self.asked.append(req)
if req["invite"] != INV:
raise Fail("unknown invitation")
return {"building": CARD, "unit": OFFER["unit"]}
if req["op"] == "decline":
self.asked.append(req)
self.state = {}
return {}
return super().ask(req, timeout)
def test_invitation_shown_previewed_and_joined(tmp_path):
fl = InviteFleet(tmp_path)
p = JoinPage(fl, location=lambda: None)
out = p.get({})
assert "WEG Linden invites your home to join Lindenstraße 4 (unit 3B), until 2026-11-30." in out
assert f'name="invite" value="{INV}"' in out and "Look at it" in out and "Decline" in out
assert out.index("Invitations") < out.index("Join with a code")
out = p.post({"do": "preview", "invite": INV})
assert "Unit <b>3B</b>" in out and f'<input type="hidden" name="invite" value="{INV}">' in out
assert 'name="code"' not in out
assert [a for a in fl.asked if a["op"] == "preview"][-1] == {"op": "preview", "invite": INV}
out = p.post({"do": "join", "invite": INV, "rules_digest": "d1", "consent_building": "1"})
assert "member now" in out
join = [a for a in fl.asked if a["op"] == "join"][0]
assert join["invite"] == INV and "code" not in join and join["consent"] == {"building": True, "community": False}
assert Building(str(tmp_path)).memberships() == {B}
def test_invitation_declined_and_bad_ids(tmp_path):
fl = InviteFleet(tmp_path)
p = JoinPage(fl, location=lambda: None)
assert "Which invitation?" in p.post({"do": "preview", "invite": "nope"})
assert "Which invitation?" in p.post({"do": "decline", "invite": "../x"})
assert "Which invitation?" in p.post({"do": "join", "invite": "x"})
assert not [a for a in fl.asked if a["op"] in ("preview", "decline", "join")]
out = p.post({"do": "decline", "invite": INV})
assert "You declined the invitation." in out and "invites your home" not in out
assert [a for a in fl.asked if a["op"] == "decline"] == [{"op": "decline", "invite": INV}]
def test_community_invitation_next_to_a_building(tmp_path):
fl = InviteFleet(tmp_path)
fl.state = {"membership": {"state": "active", "building": CARD, "unit": "3B", "joined_at": "2026-10-29T10:00:00Z"},
"offers": [dict(OFFER, building=COMM, unit=None)]}
out = JoinPage(fl, location=lambda: None).get({})
assert "Kiez Energie eG invites your home to join Kiez eG, until 2026-11-30." in out and "Join with a code" not in out
+7
View File
@@ -83,6 +83,13 @@ async def test_http_german(tmp_path):
server.close() server.close()
def test_german_invitation(tmp_path):
from test_joinpage import InviteFleet
out = german(JoinPage(InviteFleet(tmp_path), location=lambda: None).get, {})
assert "WEG Linden lädt Ihr Zuhause ein, Lindenstraße 4 beizutreten (Einheit 3B), bis 30. Nov. 2026." in out
assert "Einladungen" in out and "Ansehen" in out and "Ablehnen" in out
def _texts(): def _texts():
"""Every literal T/TN/M text of the pages.""" """Every literal T/TN/M text of the pages."""
out = [] out = []
+64
View File
@@ -277,6 +277,39 @@ def test_minimum_interval_between_moves():
assert len(at) >= 2 and all(b - a >= 4 for a, b in zip(at, at[1:])) assert len(at) >= 2 and all(b - a >= 4 for a, b in zip(at, at[1:]))
def test_a_shade_the_agent_moved_moves_back_in_the_next_plans():
# 2026-11-05: Munich 1's shade closed for the night on 30 October and stayed
# closed: every plan after the move started from the closed shade and no
# longer knew why it was closed, so the morning's opening was never planned
evening = ts(2026, 1, 15, 17)
night = {"season": "heating"}
assert moves(shades.schedule(shade(-1, pos=0), state(evening, t_out=2.0), night), evening) == []
m = moves(shades.schedule(shade(-1, pos=0), state(evening, t_out=2.0), dict(night, ours="night")), evening)
assert m[0][1:] == (100, "morning: open again") and m[0][0] >= "07:00", m
# summer: shaded from the sun, opened again when the sun has left
noon = ts(2026, 7, 15, 16)
warm = {"temp_c": 26.0, "setpoint_c": 24.0}
sch = shades.schedule(shade(270, pos=30), state(noon, steps=32), dict(warm, ours="shade"))
assert moves(sch, noon)[0][1:] == (100, "the sun has left the west facade")
# the rule each move is for, into the plan's entry
start = ts(2026, 1, 15)
sch = shades.schedule(shade(-1, pos=100), state(start, steps=192, t_out=2.0), night)
assert [r for r, v in zip(sch["rule"], sch["set"]) if v is not None] == ["night", "", "night"]
def test_moves_kept_while_the_shade_is_where_the_agent_put_it(tmp_path):
mv = shades.Moves(str(tmp_path))
assert mv.ours("curtain", 0.0) is None
mv.record("curtain", "night", 0.0, 1_800_000_000)
assert mv.ours("curtain", 2.0) == "night"
assert mv.ours("curtain", 40.0) is None # moved by hand: the owner's position stays
assert mv.ours("curtain", None) is None
again = shades.Moves(str(tmp_path)) # across a restart
assert again.ours("curtain", 0.0) == "night"
again.record("curtain", "", 100.0, 1_800_050_000) # opened again: nothing of ours
assert again.ours("curtain", 100.0) is None
# -- the plan, the guard, the executor ----------------------------------------------------------- # -- the plan, the guard, the executor -----------------------------------------------------------
MAPPING = {"version": 3, "assets": [], MAPPING = {"version": 3, "assets": [],
@@ -460,3 +493,34 @@ def test_addon_devices_page_shade(tmp_path):
return s.req(query=f"p=devices&d={dev_id}") return s.req(query=f"p=devices&d={dev_id}")
de = contextvars.copy_context().run(run) de = contextvars.copy_context().run(run)
assert "Raum und Fenster" in de and "Südosten" in de and "Bewegen durch Cantabile erlauben" in de assert "Raum und Fenster" in de and "Südosten" in de and "Bewegen durch Cantabile erlauben" in de
def test_executor_keeps_what_a_planned_move_was_for(site):
import asyncio
from cantabile_edge.controller import Controller
from cantabile_edge.config import Config
m = Mapping.load(str(site / "mapping.yaml"))
clk = Clock(float(ts(2026, 1, 15, 17)))
cfg = Config(site_id="ab" * 16, mapping=str(site / "mapping.yaml"), state_dir=str(site))
ctl = Controller(cfg, m, Consent(str(site)), sink=None, clock=clk)
ctl.mode.set("auto", "test")
ctl.col.on_entities({"a": {"cover.curtain": {"s": "open", "a": {"current_position": 100, "supported_features": 15}},
"cover.rbs": {"s": "open", "a": {"supported_features": 11}}}})
called = []
class Client:
async def call_service(self, domain, service, entity, data, allowed):
called.append((service, entity, data))
t = int(clk.t)
ctl.executor.plan = {"made": t, "devices": {
"curtain": [{"t": t, "set": 0, "why": "night: closed to keep the warmth in", "rule": "night"}],
"rbs": [{"t": t, "set": None, "why": ""}]}}
asyncio.run(ctl.executor.tick(Client(), True))
assert called == [("set_cover_position", "cover.curtain", {"position": 0})]
ctl.col.on_entities({"c": {"cover.curtain": {"+": {"s": "closed", "a": {"current_position": 0}}}}})
assert ctl.shade_ctx()["curtain"]["ours"] == "night" and "ours" not in ctl.shade_ctx()["rbs"]
# kept across a restart: the next morning's plan opens it
again = Controller(cfg, m, Consent(str(site)), sink=None, clock=clk)
again.col.on_entities({"a": {"cover.curtain": {"s": "closed", "a": {"current_position": 0}}}})
assert again.shade_ctx()["curtain"]["ours"] == "night"
assert again.mode() == "auto" and again.mode.source().startswith("set by test at ")
+4 -1
View File
@@ -141,5 +141,8 @@ def test_import_through_a_contract_counts():
c = {"id": "pool", "name": "pool", "direction": "buys", "price_ct": 10.0, "max_w": 0.0, "guaranteed_w": 0.0, c = {"id": "pool", "name": "pool", "direction": "buys", "price_ct": 10.0, "max_w": 0.0, "guaranteed_w": 0.0,
"minimum_wh": 0.0, "from_step": 0, "to_step": 192} "minimum_wh": 0.0, "from_step": 0, "to_step": 192}
p = optimizer.plan(house([battery()], market=[c]), 20) p = optimizer.plan(house([battery()], market=[c]), 20)
assert min(p["flex"]["grid_w"]) >= 390 # the house's 400 W at least # the house's 400 W less what the battery covers (its end value, A2.5, lets it discharge)
base = shift(p, "battery")["base_w"]
assert min(p["flex"]["grid_w"]) > 0
assert all(g >= 400 + min(0, b) - 10 for g, b in zip(p["flex"]["grid_w"], base))
assert sum(p["flex"]["shed_w"]) > 0 assert sum(p["flex"]["shed_w"]) > 0
+1
View File
@@ -165,6 +165,7 @@ def test_battery_self_consumption_and_hold():
from test_optimizer import battery, house from test_optimizer import battery, house
s = house([battery(soc=50, floor=10)], steps=16) s = house([battery(soc=50, floor=10)], steps=16)
s["price_import"] = [40.0] * 8 + [20.0] * 8 # dear now, cheap later: cover the house now s["price_import"] = [40.0] * 8 + [20.0] * 8 # dear now, cheap later: cover the house now
s["params"] = {"battery.end_value_pct": 100} # what is left is worth the feed-in (A2.5): no export
p = optimizer.plan(s, 10) p = optimizer.plan(s, 10)
first = p["devices"]["battery"][0] first = p["devices"]["battery"][0]
assert first.get("auto") is True and first["why"].startswith("self-consumption") assert first.get("auto") is True and first["why"].startswith("self-consumption")
+73
View File
@@ -0,0 +1,73 @@
# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
"""A flat under a building's GGV schema or a community's §42c sharing,
where the plan has no offer in some quarter-hours (no PV or battery to
share there, 2026-11-05): fleet composes the flat's tariff bundle from its
own supplier's prices and lays the tenant price only on the slots with an
offer (tenantTariff); a slot without one keeps the own supplier's price.
The box takes the bundle as it is: the own supplier's price there, never
0 ct and never the neighbouring tenant price; a step with no price at all
(null) stays without one (the plan covers the priced steps), never a
guess."""
import json
from cantabile_edge.bundles import Bundles
SITE = "cd" * 16
START = 1793865600 # 2026-11-05 06:00 UTC, a quarter hour
OWN = 36.4 # the flat's own supplier (gross ct/kWh)
TENANT = 31.2 # own − share·(own − offer) where there is an offer
def write(tmp_path, imp):
t = {"v": 1, "kind": "tariff", "id": "t-1", "site": SITE, "issued": START, "start": START, "step_s": 900,
"steps": len(imp), "expires": START + 86400, "currency": "EUR", "unit": "ct/kWh", "import": imp,
"export": [7.8] * len(imp), "sources": ["product:own", "mieterstrom:schema-1"]}
(tmp_path / "tariff.json").write_text(json.dumps(t))
return Bundles(str(tmp_path), SITE)
def test_no_offer_slots_keep_the_own_supplier(tmp_path):
# night: no offer (fleet left the own price), day: the tenant price on the share
imp = [OWN] * 8 + [TENANT] * 8 + [OWN] * 8
p = write(tmp_path, imp).prices(START, 900, 24, START + 60)
assert p.status == "tariff"
assert p.import_ct == imp # taken as it is
assert all(v == OWN for v in p.import_ct[:8]) # the own supplier's where there is no offer
assert 0 not in p.import_ct and None not in p.import_ct
assert p.priced_steps == 24
def test_a_gap_is_no_price_never_zero_or_held(tmp_path):
# a step with no price at all (no own price known there either): None, the plan covers the steps before it
imp = [TENANT] * 4 + [None] + [OWN] * 4
p = write(tmp_path, imp).prices(START, 900, 9, START + 60)
assert p.import_ct[4] is None # neither 0 nor the last price held
assert p.import_ct[:4] == [TENANT] * 4 and p.import_ct[5:] == [OWN] * 4
assert p.priced_steps == 4
assert "the plan covers those" in p.note
def test_a_shadow_tenant_price_is_planned_with_and_named(tmp_path):
# a Mieterstrom building in shadow (2026-11-05): fleet sends the tenant price in every slot, with "tenant"
# saying where it comes from (not billed) and the own supplier's curve as the reference
imp = [TENANT] * 8
t = {"v": 1, "kind": "tariff", "id": "t-2", "site": SITE, "issued": START, "start": START, "step_s": 900,
"steps": 8, "expires": START + 86400, "currency": "EUR", "unit": "ct/kWh", "import": imp,
"export": [7.8] * 8, "sources": ["product:own", "mieterstrom:b-1"],
"tenant": {"model": "mieterstrom", "plant": "b-1", "name": "Haus Sonne", "shadow": True, "billed": False,
"schema": "", "proposal": "p-1", "made_at": START, "valid_until": START + 21600, "steps": 8,
"own_import": [OWN] * 8}}
(tmp_path / "tariff.json").write_text(json.dumps(t))
b = Bundles(str(tmp_path), SITE)
p = b.prices(START, 900, 8, START + 60)
assert p.import_ct == imp # the tenant price as it is: what the plan and its baseline use
assert "tenant price: Mieterstrom Haus Sonne (shadow: planned with, not billed)" in p.note
now = b.tariff_now(START + 60)
assert now["import_now"] == TENANT and now["own_import_now"] == OWN
assert now["tenant"]["model"] == "mieterstrom" and now["tenant"]["billed"] is False
def test_no_tenant_block_no_tenant_note(tmp_path):
b = write(tmp_path, [OWN] * 4)
assert "tenant price" not in b.prices(START, 900, 4, START + 60).note
assert b.tariff_now(START + 60)["tenant"] is None