EV-04 round 2: race-free another-writer check, refused phase select, undo before the select, clamped restore, energy-corroborated car figure
checks / unit (pull_request) Successful in 21m14s
infra-pin / fresh (pull_request) Successful in 1s

M1 the writer ignores a reading taken before its latest confirmed write.
M2 a refused phase select gives the current back and stops after 3 tries (amber row).
M3 Off, shadow mode or a control/safety stop before the select undoes the change.
M4 the restore on shutdown (and the undo) is clamped.
M5 the car's power reaches the alarm path only while the charger's energy meter agrees with it.
L1 fuzz other-writer branch reachable and shown to run. L2 one wording. L3 Batteries-help-off text.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
glenn schrooyen
2026-11-16 06:51:15 +01:00
co-authored by Claude
parent 0c92239a63
commit 661a3b009a
11 changed files with 493 additions and 68 deletions
+64 -8
View File
@@ -120,6 +120,11 @@ class ManualWriter:
self.blocked = False # a phase change waits for PHASE_GAP_S
self.would = None # (amps, phases): what it would set
self.log = [] # (kind, value, now, ok), for the checks
self.last_done = None # when our latest write was confirmed
self._clock = None
self.phase_fails = 0 # phase selects the charger did not take
self.phases_gave_up = False
self.undone = 0 # sequences undone before the select
# ------------------------------------------------------------------ user
def user_changed(self) -> None:
@@ -129,22 +134,35 @@ class ManualWriter:
self.hold = self.other = False
self.mismatch_since = None
self.fails, self.fail_at, self.gave_up = 0, None, False
self.phase_fails, self.phases_gave_up = 0, False
self.attempted_a = self.prior_a = None
# ------------------------------------------------------------------ step
async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp,
now, tracker, writing, status):
now, tracker, writing, status, shadow=False, clock=None):
"""One cycle. `r` is the latest `ChargerReading`; `writing` is False in
shadow mode and while control is stopped (the step then only works out
what it WOULD set, in `self.would`)."""
self._clock = clock or (lambda: now)
if r is None or not r.available:
self.was_available = False
return
# A reading taken before our latest write was confirmed says nothing
# about it (the writer runs beside the cycle and can finish between a
# read and the step that follows): wait for one taken after.
if self.last_done is not None and tracker is not None \
and tracker.obs_at is not None \
and tracker.obs_at <= self.last_done:
return
if not self.was_available:
self.was_available = True
self.reapply = True # on return: only if it differs
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
if self.seq is not None:
if self.seq["stage"] in ("zero", "select") \
and (mode != MANUAL or not writing):
await self._undo(drv, now, tracker, clamp, shadow)
return
await self._advance(drv, r, cur, now, tracker, want_a, clamp, rev)
return
self.would = None
@@ -166,7 +184,8 @@ class ManualWriter:
if self.hold:
return
phases_need = (r.phases_allowed is not None
and r.phases_allowed != n_eff)
and r.phases_allowed != n_eff
and not self.phases_gave_up)
cur_need = cur is None or abs(cur - target) > TOL_A
need_user = rev != self.rev_applied
if not (phases_need or cur_need):
@@ -230,6 +249,7 @@ class ManualWriter:
async def _write(self, drv, a, was, now, tracker) -> bool:
ok = await drv.write_current(a)
self._stamp(now)
tracker.note_write(now, was, a)
self.log.append(("current", a, now, ok))
if ok:
@@ -239,6 +259,29 @@ class ManualWriter:
self.attempted_a, self.prior_a = a, was
return ok
def _stamp(self, now) -> None:
self.last_done = (self._clock or (lambda: now))()
@staticmethod
def _restore_a(prev, clamp):
"""The current to give back: what it was, never above the clamp."""
if prev is None:
return None
hi = CH.ENTITY_MAX_A if clamp is None else float(clamp)
a = min(float(prev), hi)
return a if a >= CH.MIN_A else None
async def _undo(self, drv, now, tracker, clamp, shadow) -> None:
"""Off, shadow mode or a stopped control while the car is paused and the
phases have NOT been selected: no switch. The old current comes back
(clamped), except in shadow mode, which writes nothing further."""
q, self.seq = self.seq, None
self.undone += 1
self.rev_applied, self.reapply = None, True
a = None if shadow else self._restore_a(q.get("prev"), clamp)
if a is not None:
await self._write(drv, a, 0.0, now, tracker)
async def _begin(self, drv, r, cur, n, now, tracker) -> None:
"""Step 1 of the safe sequence: 0 A. A charger that does not take it
stops the sequence before the phases are touched."""
@@ -249,14 +292,15 @@ class ManualWriter:
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
"prev": cur}
async def abandon(self, drv, now, tracker) -> None:
async def abandon(self, drv, now, tracker, clamp=None) -> None:
"""The add-on is stopping in the middle of a phase change: give the car
its current back (a stopped add-on must not leave it at 0 A). The
phases stay as the select left them."""
its current back (a stopped add-on must not leave it at 0 A), clamped
like every write. The phases stay as the select left them."""
q, self.seq = self.seq, None
if q is not None and q.get("prev") is not None \
and q["prev"] >= CH.MIN_A:
await self._write(drv, float(q["prev"]), 0.0, now, tracker)
a = None if q is None else self._restore_a(q.get("prev"), clamp)
if a is not None:
self._clock = self._clock or (lambda: now)
await self._write(drv, a, 0.0, now, tracker)
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
q = self.seq
@@ -280,9 +324,21 @@ class ManualWriter:
q["stage"] = "select"
if q["stage"] == "select":
ok = await drv.write_phases(q["n"])
self._stamp(now)
self.last_switch = now
self.log.append(("phases", q["n"], now, ok))
q["stage"], q["t1"] = "settle", now
if not ok:
# The charger did not take it: the car gets its current back
# on the old phases at once, and the change is tried again
# after PHASE_GAP_S, MAX_TRIES times in all.
self.phase_fails += 1
q["t1"] = now - SETTLE_S
if self.phase_fails >= MAX_TRIES:
self.phases_gave_up = True
_LOG.warning("The charger did not take the phases, so the "
"add-on stops trying until you change "
"something: CHARGER_PHASES.")
return
if now - q["t1"] < SETTLE_S:
return
+55 -4
View File
@@ -26,7 +26,7 @@ import asyncio
import logging
import re
import time
from dataclasses import dataclass
from dataclasses import dataclass, field
from .hass import BAD_STATES
from .solarfc import KWH_PER
@@ -74,6 +74,15 @@ OWN_WRITE_MUTE_S = 15.0 # the tracker's two-writer detector ignores our own
# Volts used to bound a car figure by what the read-back allows (a physical
# ceiling for the alarm path, never a setpoint).
CEILING_V = 253.0
# EV-04 round 2: the car's power may be used by the peak guard's alarm path only
# while the charger's energy meter CORROBORATES it. Over the last CORR_WINDOW_S
# seconds of readings (all in mode3 C, no gap) the meter must have advanced by at
# least CORR_RATIO of what the reported power adds up to, less CORR_SLACK_WH (the
# meter shows 10 Wh steps). Until a window of CORR_WINDOW_S exists (a session just
# began, or the add-on just started) the figure is believed, as it was before.
CORR_WINDOW_S = 60.0
CORR_RATIO = 0.5
CORR_SLACK_WH = 15.0
# role -> (entity domain, suffix after `<x>_`). `current` is the setpoint, the
# one the installer names; the rest are derived by swapping its suffix.
@@ -645,6 +654,8 @@ class CarTracker:
armed_sig: tuple | None = None
sig: tuple | None = None
stuck_now: bool = False
obs_at: float | None = None # monotonic second of the latest reading
_hist: list = field(default_factory=list) # (t, power W, energy Wh)
# today's energy
day: str | None = None
today_kwh: float | None = None
@@ -653,6 +664,8 @@ class CarTracker:
def observe(self, r: ChargerReading, now: float, now_utc, day: str):
self.reading = r
self.obs_at = now
self._corr_note(r, now)
usable = r.available and r.power_w is not None
if r.available:
self.bad_since = None
@@ -721,6 +734,43 @@ class CarTracker:
if self.armed_at is not None and now - self.armed_at >= STUCK_S:
self.stuck_now = True
def _corr_note(self, r, now: float) -> None:
"""Keep the last `CORR_WINDOW_S` of (power, energy) while the charger is
charging. Any gap, a car that is not in mode3 C, a reading without
power or energy, or a meter that goes back starts the window again."""
h = self._hist
ok = (r.available and r.charging is True and r.power_w is not None
and r.energy_kwh is not None)
if not ok or (h and r.energy_kwh * 1000.0 < h[-1][2] - 0.5):
h.clear()
if not ok:
return
h.append((now, float(r.power_w), r.energy_kwh * 1000.0))
while len(h) > 2 and now - h[1][0] >= CORR_WINDOW_S:
h.pop(0)
def corroborated(self, now: float) -> bool:
"""Does the charger's energy meter agree with the power it reports? No
energy entity, or not charging: no. Less than a window of readings: yes
(the first minute of a session is believed). Otherwise the energy the
meter gained over the window must be at least `CORR_RATIO` of what the
power adds up to, less `CORR_SLACK_WH`. A frozen power figure on a car
that has stopped fails this within a window, and so does everything
frozen together."""
r = self.reading
h = self._hist
if r is None or not r.available or r.charging is not True \
or r.energy_kwh is None or not h:
return False
span = h[-1][0] - h[0][0]
if span < CORR_WINDOW_S - 5.0:
return True
exp_wh = 0.0
for (t0, p0, _e0), (t1, _p1, _e1) in zip(h, h[1:]):
exp_wh += p0 * (t1 - t0) / 3600.0
got_wh = h[-1][2] - h[0][2]
return got_wh >= CORR_RATIO * exp_wh - CORR_SLACK_WH
def stuck(self, now: float) -> bool:
"""Power and read-back unchanged `STUCK_S` after a write that moved the
setpoint. Cleared the moment either moves."""
@@ -728,10 +778,11 @@ class CarTracker:
def car_w_trusted(self, now: float):
"""The car's power for the peak guard's ALARM PATH, or None. Fresh (the
EV-03 rules), not stuck, and never above what the read-back allows the
car to draw: an old or stuck figure must not hide a house overload."""
EV-03 rules), not stuck after a write, corroborated by the energy meter
(`corroborated`), and never above what the read-back allows the car to
draw: an old or frozen figure must not hide a house overload."""
w = self.car_w(now)
if w is None or self.stuck(now):
if w is None or self.stuck(now) or not self.corroborated(now):
return None
r = self.reading
a = r.allowed_a if r.allowed_a is not None else r.setpoint_a
+8 -5
View File
@@ -71,9 +71,11 @@ class CarMixin:
def car_writing(self) -> bool:
"""May the add-on write to the charger now? Control runs, shadow mode is
off, and the add-on is not shutting down. Shadow mode gates charger
off, no safety stop is latched and the add-on is not shutting down. Shadow mode gates charger
writes exactly as it gates inverter writes."""
return bool(self.auto and not self.shadow
latched = (any(i.sign_wd.tripped for i in self.inverters)
or self.site_sign_wd.tripped or self.circ_wd.tripped)
return bool(self.auto and not self.shadow and not latched
and not getattr(self, "stopping", False))
# ---------------------------------------------------------------- actions
@@ -168,7 +170,8 @@ class CarMixin:
return
try:
await asyncio.wait_for(self.car_writer.abandon(
self.charger, self.car_now(), self.car), 15.0)
self.charger, self.car_now(), self.car, self.car_clamp()),
15.0)
except Exception: # noqa: BLE001
_LOG.warning("The car could not be given its current back "
"before the add-on stopped: CHARGER_RESTORE.")
@@ -183,8 +186,8 @@ class CarMixin:
self.charger, self.car.reading, mode=self.car_mode,
want_a=self.car_a, want_phases=self.car_n, rev=self.car_rev,
clamp=self.car_clamp(), now=now, tracker=self.car,
writing=self.car_writing(),
status=self.car.status(now, True))
writing=self.car_writing(), shadow=bool(self.shadow),
status=self.car.status(now, True), clock=self.car_now)
# ------------------------------------------- the car and the peak guard
def car_alarm_w(self):
+3
View File
@@ -215,6 +215,9 @@ class StatusMixin:
if w.gave_up:
out.append({"ok": False, "warn": True, "id": "charger_refused",
"text": messages.row_charger_refused()})
if w.phases_gave_up:
out.append({"ok": False, "warn": True, "id": "charger_phases",
"text": messages.row_charger_phases()})
elif self.car.other_writer(datetime.now(timezone.utc)):
out.append({"ok": True, "warn": True, "id": "charger_writer",
"text": messages.row_charger_writer()})
+10 -2
View File
@@ -520,9 +520,9 @@ def row_car_over() -> str:
def row_charger_other() -> str:
"""EV-04: the grey row, in Manual, while something else sets the current."""
return Bi("Something else changed the charger, so the add-on writes "
return Bi("Something else changes the charger, so the add-on writes "
"nothing until you change it.",
"Iets anders wijzigde de laadpaal, dus de add-on schrijft niets "
"Iets anders wijzigt de laadpaal, dus de add-on schrijft niets "
"tot u iets wijzigt.")
@@ -540,6 +540,13 @@ def row_charger_refused() -> str:
"laadpaal.")
def row_charger_phases() -> str:
"""EV-04: the amber row when the charger does not take the phases."""
return Bi("The charger did not take the phases, so check the charger.",
"De laadpaal nam de fasen niet over, dus controleer de "
"laadpaal.")
def row_charger_error(text) -> str:
"""EV-04: the grey row while the charger reports an error. Writes go on."""
t = " ".join(str(text or "").split())[:60]
@@ -1776,6 +1783,7 @@ def status_samples() -> list:
("row_charger_error", GREEN, row_charger_error("Socket error")),
("row_charger_stuck", AMBER, row_charger_stuck()),
("row_charger_refused", AMBER, row_charger_refused()),
("row_charger_phases", AMBER, row_charger_phases()),
("row_charger_setup", AMBER, row_charger_setup()),
]
+3 -2
View File
@@ -325,7 +325,7 @@
"manual_cover": "You set {a} A. The batteries give {kw} and help down to {pct}.",
"manual_over": "You set {a} A. The batteries are at {pct}, so this charge sets the peak.",
"manual_full": "You set {a} A. The batteries give all they can, so this charge sets the peak.",
"manual_nocover": "You set {a} A. The batteries keep their charge, so this charge sets the peak.",
"manual_nocover": "You set {a} A. The guard ignores the car, so this charge can set the peak.",
"manual_wait": "You set {a} A. It is set when a car is connected.",
"manual_would": "Shadow mode: the add-on would set {a} A, {phases}.",
"manual_stopped": "Control is stopped. The charger keeps its last setting.",
@@ -541,7 +541,8 @@
"solar_forecast": "Solar forecast",
"charger": "Charger not reachable",
"charger_writer": "Something else changes the charger",
"charger_other": "Something else changed the charger",
"charger_other": "Something else changes the charger",
"charger_phases": "Charger did not take phases",
"charger_stuck": "Charger reading may be stuck",
"charger_refused": "Charger did not take it",
"charger_error": "The charger reports an error",
+3 -2
View File
@@ -279,7 +279,7 @@
"manual_cover": "U stelde {a} A in. De batterijen leveren {kw} en helpen tot {pct}.",
"manual_over": "U stelde {a} A in. De batterijen staan op {pct}, dus deze lading bepaalt de piek.",
"manual_full": "U stelde {a} A in. De batterijen geven alles, dus deze lading bepaalt de piek.",
"manual_nocover": "U stelde {a} A in. De batterijen houden hun lading, dus deze lading bepaalt de piek.",
"manual_nocover": "U stelde {a} A in. De bewaking negeert de auto, dus deze lading kan de piek bepalen.",
"manual_wait": "U stelde {a} A in. Het wordt ingesteld zodra een auto is aangesloten.",
"manual_would": "Schaduwmodus: de add-on zou {a} A instellen, {phases}.",
"manual_stopped": "De regeling is gestopt. De laadpaal houdt haar laatste instelling.",
@@ -462,7 +462,8 @@
"solar_forecast": "Zonneprognose",
"charger": "Laadpaal onbereikbaar",
"charger_writer": "Iets anders wijzigt de laadpaal",
"charger_other": "Iets anders wijzigde de laadpaal",
"charger_other": "Iets anders wijzigt de laadpaal",
"charger_phases": "Laadpaal nam fasen niet over",
"charger_stuck": "Laadpaalmeting staat mogelijk vast",
"charger_refused": "Laadpaal nam het niet over",
"charger_error": "De laadpaal meldt een fout",