cantabile_edge, cantabile_modbus, cantabile_eebus 0.1.629: full source

This commit is contained in:
Setti Solutions S.R.L committed 2026-11-03 23:26:41 +02:00
1 parent d5fbcacaa4
commit 85edd56ec8
46 files changed
+3518 -267

No files matched your search

+77 -8
View File
@@ -35,6 +35,7 @@ import time
from . import inputs as inputs_mod
from .building import Building
from .bundles import Bundles
from .evphases import EvPhases
from .executor import Executor, building_msg
from .gridorder import GridOrders
from .guard import Guard
@@ -81,6 +82,7 @@ class Controller:
min_switch_s=cfg.min_switch_s, max_actions_per_hour=cfg.max_actions_per_hour, clock=clock)
self.saved_limits = self._load_limits() # the console's (limits.json)
self.gridorders = GridOrders(cfg.state_dir, clock) # the grid operator's, from the EEBUS bridge (3q)
self.evphases = EvPhases(cfg.state_dir) # each charger's phase count and its source
self.guard.extra_limits = self.saved_limits
self.policy = Policy(cfg.state_dir, cfg.site_id, clock)
self.guard.policy = self.policy
@@ -180,6 +182,7 @@ class Controller:
lat, lon = (cfg or {}).get("latitude"), (cfg or {}).get("longitude")
if isinstance(lat, (int, float)) and isinstance(lon, (int, float)):
self.location = {"latitude": float(lat), "longitude": float(lon)}
write_cell(self.cfg.state_dir, float(lat), float(lon))
except Exception as e:
log.warning("get_config: %s", e)
ids = self.entities()
@@ -222,7 +225,9 @@ class Controller:
self.history, self.tz, self.forecast, self.guard.extra_limits,
building=self.building.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS),
location=self.location, shade_ctx=self.shade_ctx(),
grid_order=self.gridorders.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS))
grid_order=self.gridorders.for_model(start, inputs_mod.STEP_S, inputs_mod.STEPS),
grid_max_w=getattr(self.cfg, "grid_max_w", None),
ev_phases=self.ev_phases())
async def make_plan(self) -> dict | None:
self.forecast = []
@@ -261,15 +266,20 @@ class Controller:
"prices": plan.get("price_note", ""), "model": plan.get("model", ""),
"sources": plan.get("sources", {}),
# for the building (shed_w/grid_w per step, 24 h): absent from older agents
"flex": plan.get("flex", {})}
"flex": plan.get("flex", {}),
# the market's contracts in the plan (shadow): planned kWh and saving vs the grid
"market": plan.get("market", [])}
def inputs_fresh(self) -> bool:
"""The plan's room temperatures and the battery's state are not older
than an hour (a sensor that stopped must not steer)."""
now = self.clock()
"""The plan's room temperatures and the battery's state have a value
(a sensor that stopped must not steer). HA marks a device that went
away unavailable; a value that holds steady is not stale (the clone,
2026-10-30: a room at 23.5 °C for hours and a full battery held every
control at its safe default), and HA sends no update for an
unchanged value, so its age says nothing."""
for c in self.controls:
for role in ("temp", "soc"):
if role in c.entities and self.col.age(c.entities[role], now) > 3600:
if role in c.entities and self.col.value(c.entities[role]) is None:
return False
return True
@@ -378,8 +388,10 @@ class Controller:
async def _actor(self, stop):
while not stop.is_set():
now = self.clock()
self.history.add("load_w", self.col.total(self.inputs.load_power), now)
self.history.add("load_w", inputs_mod.base_load(self.col, self.inputs), now)
self.history.add("pv_w", self.col.total(self.inputs.pv_power), now)
if self.sample_ev_phases(now) and self.gridorders.active():
self._merge_limits() # a learned count: the order's current bound again
if int(now) % 900 < 60:
try:
self.history.save(now)
@@ -387,6 +399,10 @@ class Controller:
log.warning("history: %s", e)
self.executor.inputs_ok = self.inputs_fresh()
self.grid_tick()
try:
await self.grid_report()
except Exception as e:
log.warning("grid order report: %s", e)
if self.switch_sides():
self.wake.set() # heating <-> cooling: a plan for the new side
try:
@@ -506,12 +522,34 @@ class Controller:
os.replace(p + ".tmp", p)
# -- the chargers' phases (evphases.py) ------------------------------------
def ev_phases(self) -> dict:
"""{control id: {"phases", "source", "plan", "order"}} for the EV controls."""
return self.evphases.all(self.controls, self.col)
def sample_ev_phases(self, now: float) -> bool:
"""A reading per charger for learning its phases: its power (its own
`power` sensor, else the site's ev.power where it is the only
charger) and current (measured, else its setpoint). True when a
learned count changed."""
evs = [c for c in self.controls if c.kind == "ev"]
site_ev = self.mapping.by_asset.get("ev.power") if len(evs) == 1 and hasattr(self.mapping, "by_asset") else None
changed = False
for c in evs:
pw = c.entities.get("power") or (site_ev.entity if site_ev else "")
cur = c.entities.get("current_measured") or c.entities.get("current") or ""
p = inputs_mod.watts(self.col, pw) if pw else None
a = self.col.value(cur) if cur else None
changed |= self.evphases.sample(c.id, p, a, float(c.p("voltage")), now)
return changed
# -- the grid operator's limit (EEBUS LPC, gridorder.py) -----------------
def _merge_limits(self):
"""The guard's limits: the console's, and over them the grid order's
at level grid (the lower limit of the two holds)."""
merged = {c: {q: dict(lv) for q, lv in qs.items()} for c, qs in self.saved_limits.items()}
for cid, qs in self.gridorders.limits(self.controls).items():
phases = {cid: v["phases"] for cid, v in self.ev_phases().items()}
for cid, qs in self.gridorders.limits(self.controls, phases).items():
for q, (f, lim) in qs.items():
per = merged.setdefault(cid, {}).setdefault(q, {})
old = per.get("grid")
@@ -538,10 +576,18 @@ class Controller:
args.update(value="", state="normal")
log.info("grid operator's limit ended")
await self._received("grid", args, "grid", True, "limited" if o else "ended")
await self.grid_report()
self.wake.set()
self.act_now.set()
return True
async def grid_report(self):
"""The order to the cloud as an action (gridorder.py action()): each
quarter-hour it holds, and its end."""
a = self.gridorders.action()
if a is not None:
await self._publish("action", a)
def grid_tick(self):
"""An order that went stale or ended takes its limits away."""
if self.gridorders.order and not self.gridorders.active() and any(
@@ -562,6 +608,29 @@ def sender(cmd: str, args: dict) -> str:
return "cloud"
def write_cell(state_dir: str, lat: float, lon: float) -> bool:
"""The site's weather cell (0.1°, ~10 km) for the link: site_cell.json
in the state directory; the heartbeat carries it to the cloud only with
the owner's share consent (edge/link). Written when it changed."""
cell = {"lat": round(lat, 1), "lon": round(lon, 1)}
path = os.path.join(state_dir, "site_cell.json")
try:
with open(path) as f:
if json.load(f) == cell:
return False
except (OSError, ValueError):
pass
try:
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(cell, f)
os.replace(tmp, path)
except OSError as e:
log.warning("site cell: %s", e)
return False
return True
SECRET_ARGS = ("proof", "sig", "bundle", "token", "password")