cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.1030: full source
This commit is contained in:
1 parent
e2c7085d2c
commit
cddd34dcbc
30 files changed
+2141
-51
No files matched your search
@@ -15,8 +15,9 @@ import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
from . import areas, ha, propose, sinks, trainhist
|
||||
from . import areas, costs, ha, propose, sinks, trainhist
|
||||
from .announce import Announcer
|
||||
from .bundles import Bundles
|
||||
from .consent import Consent
|
||||
from .controller import Controller
|
||||
from .inventory import Inventory
|
||||
@@ -57,6 +58,7 @@ class Agent:
|
||||
self.started = 0.0
|
||||
self.clock = time.time # tests set their own
|
||||
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
|
||||
# v1: plans and actions for the mapping's controls (controller.py)
|
||||
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)
|
||||
if self.control is not None:
|
||||
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.exit_code = 0 # RESTART: start again (restart())
|
||||
# A mapping for a site without one (propose.py): the HA add-on
|
||||
@@ -177,15 +197,24 @@ class Agent:
|
||||
return await q()
|
||||
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):
|
||||
share = self.consent.share # without it nothing is collected to send
|
||||
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
|
||||
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
|
||||
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
|
||||
raw = value_of(a, state, self.attrs.get(entity_id))
|
||||
v = number(raw)
|
||||
@@ -195,6 +224,8 @@ class Agent:
|
||||
v = scaled(convert(v, unit, a.unit), a)
|
||||
if v is None:
|
||||
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)
|
||||
if up:
|
||||
self.agg.sample(a.asset, a.kind, v, ts)
|
||||
@@ -245,7 +276,9 @@ class Agent:
|
||||
|
||||
async def on_connect(self, client: ha.HAClient):
|
||||
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:
|
||||
log.info("get_config: %s", e)
|
||||
try:
|
||||
@@ -256,6 +289,8 @@ class Agent:
|
||||
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)
|
||||
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)
|
||||
log.info("subscribed to %d consented entities (mapping v%d)", len(ids), self.mapping.version)
|
||||
if self.control is not None:
|
||||
@@ -292,6 +327,16 @@ class Agent:
|
||||
self.control.boxml.store.add_window(tstart, trecs)
|
||||
except Exception as 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:
|
||||
return
|
||||
seq = self.queue.put("tel", {
|
||||
@@ -363,6 +408,8 @@ class Agent:
|
||||
self.agg.begin(self.started)
|
||||
if self.train_agg is not None:
|
||||
self.train_agg.begin(self.started)
|
||||
if self.cost_agg is not None:
|
||||
self.cost_agg.begin(self.started)
|
||||
if self.cfg.mode == "off":
|
||||
log.info("mode off: not reading Home Assistant")
|
||||
await self.stop.wait()
|
||||
|
||||
@@ -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>
|
||||
the tariff in force, its 48 h curve as attributes
|
||||
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,
|
||||
release, limits, tariff, model, building; who
|
||||
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.
|
||||
"""
|
||||
import asyncio
|
||||
import html
|
||||
import time
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from . import costs as costs_mod
|
||||
from . import gridorder
|
||||
from . import __version__
|
||||
from . import names, shades
|
||||
@@ -603,6 +614,87 @@ class Announcer:
|
||||
return {"kind": "boost", "control": cid, "c": p.ha.get(f"boost_c:{cid}", default),
|
||||
"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:
|
||||
"""Every discovery config HA should have now: (node, component,
|
||||
object) -> config; node is the site's or a flat's."""
|
||||
@@ -611,6 +703,7 @@ class Announcer:
|
||||
out = {}
|
||||
for (comp, obj), conf in {**self._configs(), **self._plan_objects(),
|
||||
**self._exchange_objects(tariff, model), **self._prefs_objects(),
|
||||
**self._cost_objects(),
|
||||
**self._market_objects(self.bundles.market_now(now))}.items():
|
||||
out[(self.uid, comp, obj)] = conf
|
||||
out.update(self._flat_objects(self.bundles.flat_list()))
|
||||
@@ -712,6 +805,12 @@ class Announcer:
|
||||
if ctl is not None and ctl.received:
|
||||
# kept (retained) across restarts until new ones come
|
||||
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)
|
||||
if market is not None:
|
||||
await c.publish(f"{self.base}/market/availability", "offline" if market["stale"] else "online", retain=True)
|
||||
|
||||
@@ -4,13 +4,25 @@
|
||||
like every command) with string args:
|
||||
|
||||
{"v": "1", "id", "building", "level": "flexible|binding",
|
||||
"control": "load_limit|shift_request|thermostat_cap", "value",
|
||||
"from": unix, "until": unix (<= from + 24 h), "why"}
|
||||
"control": "load_limit|shift_request|thermostat_cap|battery_plan",
|
||||
"value", "from": unix, "until": unix (<= from + 24 h), "why"}
|
||||
|
||||
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
|
||||
optimiser decides how and where (a soft target)
|
||||
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
|
||||
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>".
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
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
|
||||
"binding": {"load_limit": 50.0, "shift_request": 5.0, "thermostat_cap": 50.0}, # per kWh, per kWh, per K·h
|
||||
"flexible": {"load_limit": 1.0, "shift_request": 0.5, "thermostat_cap": 2.0},
|
||||
# per kWh, per kWh, per K·h; battery_plan per kWh of the battery's deviation from the building's
|
||||
# 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
|
||||
# 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},
|
||||
}
|
||||
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:
|
||||
@@ -94,6 +112,8 @@ class Building:
|
||||
raise ValueError("building: v 1 only")
|
||||
if c["level"] not in ("flexible", "binding", "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"):
|
||||
# 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)")
|
||||
@@ -103,8 +123,32 @@ class Building:
|
||||
raise ValueError("building: from < until <= from + 24 h")
|
||||
if c["control"] in ("load_limit", "shift_request") and c["value"] < 0:
|
||||
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
|
||||
|
||||
@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]:
|
||||
"""A parsed command. floors: (control id, the flat's floor, the
|
||||
flat's limit, kind) of each heating/cooling room, for the cap."""
|
||||
@@ -131,10 +175,25 @@ class Building:
|
||||
self._save()
|
||||
|
||||
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()
|
||||
out = {}
|
||||
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)
|
||||
b = min(steps, -(-(c["until"] - start) // step_s))
|
||||
if a >= b:
|
||||
|
||||
@@ -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)})"
|
||||
|
||||
|
||||
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:
|
||||
"""A contract's coming slots (fleet marketbundle.go "ahead": windows of
|
||||
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)])
|
||||
if est:
|
||||
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)
|
||||
|
||||
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")
|
||||
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:
|
||||
"""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)."""
|
||||
@@ -379,6 +477,10 @@ class Bundles:
|
||||
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),
|
||||
"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,
|
||||
"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")}}
|
||||
|
||||
@@ -36,12 +36,23 @@ def _logging():
|
||||
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):
|
||||
a = agent.build(cfg)
|
||||
loop = asyncio.get_running_loop()
|
||||
for s in (signal.SIGTERM, signal.SIGINT):
|
||||
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()
|
||||
return a.exit_code
|
||||
|
||||
@@ -80,7 +91,7 @@ def main():
|
||||
p = argparse.ArgumentParser(prog="cantabile-edge")
|
||||
p.add_argument("--config", "-c", help="YAML config file")
|
||||
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")
|
||||
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")
|
||||
|
||||
@@ -40,6 +40,7 @@ class Config:
|
||||
mqtt_password: str = field(default="", repr=False)
|
||||
mqtt_password_file: str = "" # read at each connection (it may come later)
|
||||
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 Hub's panel has its own); 0 = off. On by default in an add-on.
|
||||
join_page_port: int = 0
|
||||
|
||||
@@ -23,7 +23,10 @@ Commands (from the console through the link, which checked the signature):
|
||||
limits {"asset", "quantity", "level": "cloud|building|grid",
|
||||
"floor"?, "limit"? (empty: none), "until"?}
|
||||
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",
|
||||
"value"}}, "level": "installer|operator", "by"}: an installer's or
|
||||
Cantabile's setting within the owner's limits (preferences.py);
|
||||
@@ -44,7 +47,7 @@ import time
|
||||
from . import inputs as inputs_mod
|
||||
from .building import Building
|
||||
from .bundles import Bundles
|
||||
from . import steady
|
||||
from . import shades, steady
|
||||
from .evphases import EvPhases
|
||||
from .executor import Executor, building_msg
|
||||
from .gridorder import GridOrders
|
||||
@@ -63,19 +66,33 @@ MODES = ("off", "shadow", "advisory", "auto")
|
||||
class Mode:
|
||||
def __init__(self, state_dir: str, default: str):
|
||||
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:
|
||||
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
|
||||
if m in MODES:
|
||||
self.at, self.by = d.get("at"), str(d.get("by") or "")
|
||||
except (OSError, ValueError, AttributeError):
|
||||
self.current = default
|
||||
|
||||
def set(self, mode: str, by: str):
|
||||
tmp = self.path + ".tmp"
|
||||
now = int(time.time())
|
||||
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)
|
||||
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:
|
||||
return self.current
|
||||
@@ -107,6 +124,7 @@ class Controller:
|
||||
self.building = Building(cfg.state_dir, clock)
|
||||
self.executor = Executor(self.controls, self.guard, self.col, self._publish, stale_s=cfg.plan_stale_s,
|
||||
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.client = None
|
||||
self.tz = "UTC"
|
||||
@@ -204,6 +222,12 @@ class Controller:
|
||||
ctx["temp_c"] = self._asset_value(ta)
|
||||
if ctx.get("setpoint_c") is None:
|
||||
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
|
||||
return out
|
||||
|
||||
@@ -353,6 +377,8 @@ class Controller:
|
||||
# without a tariff: priced false, cost and baseline null (U1); controls not
|
||||
# planned and why (U2); absent from older agents
|
||||
"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", {}),
|
||||
# for the building (shed_w/grid_w per step, 24 h): absent from older agents
|
||||
"flex": plan.get("flex", {}),
|
||||
|
||||
@@ -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
|
||||
@@ -38,6 +38,14 @@
|
||||
actuators' contract target against their state); the building
|
||||
the home is in or asked to join
|
||||
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)
|
||||
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
|
||||
@@ -582,6 +590,52 @@ def view_climate(h: Home) -> dict | None:
|
||||
_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:
|
||||
""""HM8042 PV power" on the device HM8042: "PV power"."""
|
||||
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:
|
||||
"""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"):
|
||||
views.append(view_climate(h))
|
||||
if h.flats:
|
||||
|
||||
@@ -159,6 +159,7 @@ class Executor:
|
||||
self.commands: dict[str, dict] = {} # control -> {"set", "level", "until", "id", "why"}
|
||||
self._refused: dict[tuple, float] = {}
|
||||
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 ------------------------------------------------------
|
||||
def wanted(self, c, now):
|
||||
@@ -222,23 +223,28 @@ class Executor:
|
||||
# hand still counts as an override of the cap
|
||||
self.guard.expect(c.id, c.entities["climate"], want["set"])
|
||||
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)
|
||||
if not ok:
|
||||
key = (a.control, reason.split(" ")[0] + reason[-12:])
|
||||
if now - self._refused.get(key, 0) >= 3600:
|
||||
self._refused[key] = now
|
||||
await self._report(a, "refused", reason, now)
|
||||
return
|
||||
return False
|
||||
try:
|
||||
await client.call_service(a.domain, a.service, a.entity, a.data, self._allowed(a))
|
||||
except Exception as e:
|
||||
await self._report(a, "failed", str(e)[:200], now)
|
||||
return
|
||||
return False
|
||||
self.guard.done(a)
|
||||
await self._report(a, "done", a.why, now)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _allowed(a: Action):
|
||||
|
||||
@@ -56,6 +56,15 @@ MESSAGES = {
|
||||
"This energy community (energy shared between buildings and homes):":
|
||||
"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)",
|
||||
"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",
|
||||
"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).":
|
||||
|
||||
@@ -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}
|
||||
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}
|
||||
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}
|
||||
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>")
|
||||
|
||||
|
||||
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
|
||||
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>')
|
||||
|
||||
|
||||
@@ -365,12 +366,36 @@ def offer_html(o: dict) -> str:
|
||||
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:
|
||||
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,
|
||||
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>"]
|
||||
if 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
|
||||
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)}"
|
||||
+ 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'{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\">"
|
||||
+ 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>"
|
||||
@@ -502,17 +532,32 @@ class JoinPage:
|
||||
if do == "restore":
|
||||
o = fl.offer()
|
||||
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":
|
||||
code = f.get("code", "").strip().upper()
|
||||
if not CODE_RE.fullmatch(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)
|
||||
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}))
|
||||
fl.set_recipient_consent(kind, consent)
|
||||
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."))
|
||||
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":
|
||||
loc = self.location()
|
||||
if loc is None:
|
||||
|
||||
@@ -186,6 +186,94 @@ NAMES = {
|
||||
"pref_reserve_blocks": {"en": "{0}: reserve by time", "de": "{0}: Reserve nach Uhrzeit"},
|
||||
"pref_result": {"en": "Preferences", "de": "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"},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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):
|
||||
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
|
||||
cooling outside temperature, heat from the device, from the 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
|
||||
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).
|
||||
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
|
||||
target per step from its schedule (in place of the occupied hours) at the
|
||||
@@ -139,7 +149,11 @@ 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)
|
||||
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)
|
||||
GRID_MAX_W = 43470.0 # W: the site's connection when the state does not say (state["grid_max_w"],
|
||||
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"],
|
||||
# config grid_max_w): a German house connection's usual 63 A main fuse,
|
||||
# 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())
|
||||
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):
|
||||
"""The grid operator's limit on the controllable consumers' draw."""
|
||||
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])
|
||||
|
||||
# -- 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):
|
||||
p, st, b = d["params"], d["state"], d["bounds"]
|
||||
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_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
|
||||
mean_price = sum(self.s["price_import"]) / self.T if self.priced else None
|
||||
soc, prev, ch, dis = [], soc0, [], []
|
||||
pref = d.get("pref") # the owner's reserve per step (preferences.py)
|
||||
floors = []
|
||||
@@ -355,11 +423,12 @@ class Model:
|
||||
ch.append(c)
|
||||
dis.append(x)
|
||||
prev = e
|
||||
# energy left at the end is worth the mean price: no draining at the
|
||||
# horizon (without a tariff nothing is drained for a price anyway)
|
||||
if mean_price is not None:
|
||||
short = self.var(cost=mean_price / 100.0 / 1000.0)
|
||||
self.h.addConstr(prev + short >= min(soc0, hi_pct / 100.0 * cap))
|
||||
# the end value (docs/methods.md A2.5, as the building's D5.17): the
|
||||
# last charge is free within its bounds, each kWh left in it worth V
|
||||
# (without a tariff nothing is drained for a price anyway: V 0)
|
||||
v_ct = self.end_value()
|
||||
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.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,
|
||||
@@ -611,6 +680,7 @@ class Model:
|
||||
elif k == "ev":
|
||||
self.ev(d)
|
||||
self.building()
|
||||
self.battery_plan()
|
||||
self.grid_order()
|
||||
self.balance()
|
||||
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,
|
||||
"priced": m.priced, "steps": T, "price_state": s.get("prices") or {},
|
||||
"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"]:
|
||||
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
|
||||
@@ -1039,7 +1120,8 @@ def shift_envelope(m, x) -> dict | None:
|
||||
battery base_w (the planned grid-side power: charge > 0, discharge
|
||||
< 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
|
||||
(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)
|
||||
ev, heating, cooling
|
||||
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)]
|
||||
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)],
|
||||
"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]))})
|
||||
elif kind == "ev":
|
||||
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)
|
||||
surplus = s["pv_w"][t] - s["load_w"][t]
|
||||
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):
|
||||
# no tariff: the battery in its own mode, unless the owner's
|
||||
# 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}"}
|
||||
if kind == "cover" and v.get("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":
|
||||
pos = _round(100 * x(v["pos"][t]), 10.0)
|
||||
sun = s["sun"][t]
|
||||
@@ -1384,6 +1479,64 @@ def baseline(s, m, x) -> float:
|
||||
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():
|
||||
s = json.load(sys.stdin)
|
||||
limit = float(sys.argv[1]) if len(sys.argv) > 1 else 30.0
|
||||
|
||||
@@ -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
|
||||
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
|
||||
step the shade is to move, then {"set": None} (hold: the executor leaves it
|
||||
alone), so a shade the owner moved by hand is never pushed back later; the
|
||||
(heating October to April). An entry is a move: {"set": position %, "rule": "shade" | "night" | ""} in
|
||||
the step the shade is to move, then {"set": None} (hold: the executor leaves
|
||||
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.
|
||||
|
||||
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.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
@@ -168,13 +178,17 @@ def schedule(d: dict, s: dict, ctx: dict | None = None) -> dict:
|
||||
pos0 = st.get("position_pct")
|
||||
pos = float(pos0) if pos0 is not None else float(open_pct)
|
||||
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
|
||||
for k in range(T):
|
||||
ts = s["start"] + k * step
|
||||
local = datetime.fromtimestamp(ts, timezone.utc).astimezone(zone)
|
||||
if lat is None or lon is None:
|
||||
sets.append(None)
|
||||
rules.append("")
|
||||
whys.append("no site location: the sun's position is not known")
|
||||
track.append(pos)
|
||||
suns.append(0.0)
|
||||
@@ -210,14 +224,56 @@ def schedule(d: dict, s: dict, ctx: dict | None = None) -> dict:
|
||||
if move:
|
||||
pos, last_move, ours = float(want), ts, kind
|
||||
sets.append(int(want))
|
||||
rules.append(kind or "")
|
||||
whys.append(why)
|
||||
else:
|
||||
rules.append("")
|
||||
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
|
||||
sets.append(None)
|
||||
whys.append("quiet hours" if hushed and want is not None and abs(want - pos) > 2 else "")
|
||||
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:
|
||||
|
||||
Reference in new issue
Block a user