EV-04 round 3: undo restores the current in shadow mode too, energy rule catches a frozen 6 A figure, settle after a refused select
checks / unit (pull_request) Failing after 21m10s
infra-pin / fresh (pull_request) Successful in 1s

N1 the undo gives the old current back (clamped) in shadow mode; DECISIONS records it as the one write shadow mode allows.
N2 the corroboration looks back to a stretch with at least 40 Wh expected (60 s at 2.4 kW and up, 104 s at 1.38 kW).
L4 the current comes back 10 s after the phase select returned, also when it was refused.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
glenn schrooyen
2026-11-16 07:59:15 +01:00
co-authored by Claude
parent 661a3b009a
commit f31dcb62b6
4 changed files with 162 additions and 35 deletions
@@ -68,17 +68,33 @@ unavailable reading None at once), not stuck after a write (SAFETY-37's shape),
never above what the read-back allows, and CORROBORATED by the charger's energy
meter (round 2). The rule (`CarTracker.corroborated`, constants `CORR_*` in
`chargers.py`): the charger reports charging (mode3 C) and has an energy entity,
and over the last 60 s of unbroken charging readings the meter has gained at
least 50 % of what the reported power adds up to, less 15 Wh (the meter shows
10 Wh steps). A gap, a state other than C or a meter that goes back starts the
window again. With less than a window of readings (a session just began, or
the add-on just started) the figure is believed, so a charge does not raise the
false alarms for its first minute; a frozen figure is believed for that minute
only. No energy entity: never corroborated, so the normal alarms stand. The
tolerance is loose on purpose (ramps, 10 Wh steps, the sampling) and tight
enough that a frozen power figure on a car that has stopped, or everything
frozen together, fails inside a window. Below about 0.5 kW the rule passes by
itself; such a figure cannot hide an overload that matters.
and, looking back over unbroken charging readings to the shortest stretch that
is at least 55 s long and over which the reported power adds up to at least
40 Wh, the meter has gained at least 50 % of that, less 15 Wh (the meter shows
10 Wh steps, so at 40 Wh it must show one step; an honest car can fall one step
short and still passes). Readings are kept 180 s. A gap, a state other than C or
a meter that goes back starts the history again. With no such stretch yet (a
session just began, or the add-on just started) the figure is believed, so a
charge does not raise false alarms for its first minute; a frozen figure is
believed for that long only. No energy entity: never corroborated, so the normal
alarms stand. **Bound:** a frozen figure of P watts on a car that has really
stopped is caught within max(60 s, 40 Wh / P): 60 s from 2.4 kW up, 104 s at
1.38 kW (6 A, 1 phase, the lowest charge), plus the alarms' own 10 s hold. Below
about 0.8 kW (40 Wh over the 180 s kept) the figure is believed; it cannot hide
an overload that matters. (Round 2 had a 15 Wh slack that cancelled the 50 % rule
up to 1.8 kW; the 40 Wh floor fixes that.)
## The one write shadow mode allows
When the add-on has paused the car (0 A) for a phase change and has not yet
selected the phases, Off, a stop of control, a safety latch or shadow mode ends
the change. The old current is given back (clamped, `_restore_a`) in every one of
those cases, shadow mode included. With the shipped `shadow_mode: auto`, stopping
control turns shadow on, so without this the car would stay at 0 A for as long
as control is stopped, while the design's Manual column says the current
stands. Undoing our own half-done change is not a new command; it is the same
write the shutdown restore makes. Nothing else is written in shadow mode: no
phase switch, and no write afterwards.
## Decision 1 (`ev_batt_cover`)
+8 -6
View File
@@ -274,11 +274,13 @@ class ManualWriter:
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."""
(clamped), in shadow mode too: it undoes the add-on's own half-done
change (as the shutdown restore does) and is the one write shadow mode
allows. Nothing else is written afterwards."""
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)
a = self._restore_a(q.get("prev"), clamp)
if a is not None:
await self._write(drv, a, 0.0, now, tracker)
@@ -327,13 +329,13 @@ class ManualWriter:
self._stamp(now)
self.last_switch = now
self.log.append(("phases", q["n"], now, ok))
q["stage"], q["t1"] = "settle", now
q["stage"], q["t1"] = "settle", self.last_done # from its return
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.
# on the old phases after the same SETTLE_S as a taken select
# (HA may have taken it and only the read-back be late), and
# the change is tried again after PHASE_GAP_S, MAX_TRIES times.
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 "
+20 -12
View File
@@ -75,14 +75,22 @@ OWN_WRITE_MUTE_S = 15.0 # the tracker's two-writer detector ignores our own
# 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.
# while the charger's energy meter CORROBORATES it. Looking back over readings
# (all in mode3 C, no gap) to the shortest stretch that is at least CORR_WINDOW_S
# long AND over which the reported power adds up to at least CORR_MIN_WH, the
# meter must have advanced by at least CORR_RATIO of that, less CORR_SLACK_WH (the
# meter shows 10 Wh steps, so at 40 Wh expected it must show one step). Readings
# are kept for CORR_KEEP_S. Until such a stretch exists (a session just began, or
# the add-on just started) the figure is believed, as it was before. A frozen
# figure of P watts on a car that has really stopped is caught within
# max(CORR_WINDOW_S, CORR_MIN_WH / P) seconds: 60 s at 2.4 kW and up, 104 s at
# 1.38 kW (6 A, 1 phase). Below CORR_MIN_WH over CORR_KEEP_S (about 0.8 kW) the
# figure is believed; it cannot hide an overload that matters.
CORR_WINDOW_S = 60.0
CORR_RATIO = 0.5
CORR_SLACK_WH = 15.0
CORR_MIN_WH = 40.0
CORR_KEEP_S = 180.0
# role -> (entity domain, suffix after `<x>_`). `current` is the setpoint, the
# one the installer names; the rest are derived by swapping its suffix.
@@ -746,7 +754,7 @@ class CarTracker:
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:
while len(h) > 2 and now - h[1][0] >= CORR_KEEP_S:
h.pop(0)
def corroborated(self, now: float) -> bool:
@@ -762,14 +770,14 @@ class CarTracker:
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:]):
for k in range(len(h) - 1, 0, -1):
(t0, p0, e0), (t1, _p1, _e1) = h[k - 1], h[k]
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
if h[-1][0] - t0 >= CORR_WINDOW_S - 5.0 and exp_wh >= CORR_MIN_WH:
got_wh = h[-1][2] - e0
return got_wh >= CORR_RATIO * exp_wh - CORR_SLACK_WH
return True
def stuck(self, now: float) -> bool:
"""Power and read-back unchanged `STUCK_S` after a write that moved the
+107 -6
View File
@@ -766,8 +766,46 @@ check("...until the user changes something: then it tries again",
m2["after_user"] == 1)
async def m3(trigger):
async def l4_late():
# Home Assistant takes the select but the read-back is late: the current
# must not come back before SETTLE_S has passed
w = World(setpoint=10, phases=1)
await w.step(8)
await w.act("car_mode", "manual")
await w.act("car_current", 10)
await w.step(5)
sim = w.sim
def slow(n):
sim.log.append((sim.t, "phases", n, sim.power_w, sim.setpoint_a))
sim._pending.append((sim.t + 12.0, "phases", n))
return True
sim.request_phases = slow
ret = []
real = w.drv.write_phases
async def spy(n):
r = await real(n)
ret.append((sim.t, r)) # model time the select call returned
return r
w.drv.write_phases = spy
n0 = len(w.writes())
await w.act("car_phases", 3)
await w.step(60)
ws = w.writes()[n0:]
t_back = next(x[0] for x in ws if x[1] == "current" and x[0] > ret[0][0] - 1)
return ret[0][1], t_back - ret[0][0]
took_l4, gap_l4 = run(l4_late())
check(f"L4: after a phase select the charger did not take in time (read-back "
f"12 s late), the current comes back only 10 s after the select call "
f"returned ({gap_l4:.0f} s)", took_l4 is False and gap_l4 >= 10.0)
async def m3(trigger):
# the shipped shadow_mode: auto (shadow is on whenever control is stopped)
w = World(dict(CAR, shadow_mode="auto"), setpoint=10, phases=1)
w.sim.ramp_w_s = 50.0
w.sim.stop_delay_s = 40.0
await w.step(60)
@@ -784,22 +822,23 @@ async def m3(trigger):
w.c.o["shadow_mode"] = "on"
elif trigger == "stop":
await w.c.handle_action("auto_toggle")
w.c.o["shadow_mode"] = "off"
elif trigger == "safety":
w.c.inverters[0].sign_wd.tripped = True
await w.step(80)
return w, mid, [(x[1], x[2]) for x in w.writes()[n0:]]
for _trig, _want in (("off", [("current", 10.0)]), ("shadow", []),
for _trig, _want in (("off", [("current", 10.0)]),
("shadow", [("current", 10.0)]),
("stop", [("current", 10.0)]),
("safety", [("current", 10.0)])):
w_m3, mid_m3, wr_m3 = run(m3(_trig))
check(f"M3 ({_trig} mid-sequence, before the select): no phase switch, "
+ ("nothing is written further" if not _want else
"the old 10 A comes back") + f" ({wr_m3})",
+ "the old 10 A comes back, and nothing is written after it "
+ f"(N1, shipped shadow_mode auto; {wr_m3})",
mid_m3[0] == 0.0 and wr_m3 == _want and w_m3.writes("phases") == []
and w_m3.sim.phases_allowed == 1 and w_m3.c.car_writer.seq is None)
and w_m3.sim.readback_a == 10.0 and w_m3.sim.phases_allowed == 1
and w_m3.c.car_writer.seq is None)
async def m4():
@@ -1381,6 +1420,46 @@ t_end = feed(tr, 80, lambda i: 1000.0 + i * 11000.0 / 3.6e6, t0=t_end + 1)
check("a car that really ramps up (5 kW to 11 kW) stays corroborated",
corr(tr, t_end))
# N2: the lowest charge, 6 A on 1 phase (1380 W), honest and frozen
def honest_1380(tr, secs, t0=100.0, e0=1000.0, step_wh=10.0):
"""An honest 1380 W car whose meter shows `step_wh` steps."""
for i in range(secs):
wh = 1380.0 * i / 3600.0
tr.observe(charging_reading((e0 + (wh // step_wh) * step_wh) / 1000.0,
1380.0), t0 + i,
datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16")
return t0 + secs - 1
tr = CH.CarTracker()
t_end = honest_1380(tr, 400)
check("N2: an honest 6 A, 1 phase car (1380 W) with a meter that shows 10 Wh "
"steps is believed, minute after minute",
corr(tr, t_end) and tr.car_w_trusted(t_end) is not None
and all(corr(tr, t) for t in (t_end - 3, t_end - 17)))
ok_all = True
tr = CH.CarTracker()
for i in range(500): # step sizes and phases of the meter vary
wh = 1380.0 * i / 3600.0
step_wh = (10.0, 5.0, 20.0)[i // 170]
tr.observe(charging_reading((1000.0 + (wh // step_wh) * step_wh) / 1000.0,
1380.0), 100.0 + i,
datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16")
ok_all &= corr(tr, 100.0 + i)
check("...at every second of a 500 s charge with 5, 10 and 20 Wh meter steps",
ok_all)
tr = CH.CarTracker()
t_end = honest_1380(tr, 200)
frozen_at, caught = t_end, None
for i in range(1, 200): # now the figure and the meter freeze
tr.observe(charging_reading(tr.reading.energy_kwh, 1380.0), t_end + i,
datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16")
if caught is None and not corr(tr, t_end + i):
caught = i
check(f"N2: a frozen 1380 W figure is caught {caught} s after the freeze "
"(bound: 40 Wh / 1.38 kW = 104 s, and not sooner than the honest run "
"allows)", caught is not None and 60 <= caught <= 110)
# --- M5 end to end: the meter, the plant and the real controller ------------- #
def freeze_all(plant, c):
plant.ch.freeze() # every reading sticks
@@ -1409,6 +1488,28 @@ for _name, _r, _t0 in (("a freeze in the middle of a session (everything "
f"normal alarm fires ({_al})",
[n for _t, n in _al] == ["goodwe_peak_saturated"]
and _t0 < _al[0][0] < _t0 + 60 + 25)
def freeze_1380(plant, c):
plant.ch.freeze()
plant.ch.set_current(0) # the car really stops
plant.load = lambda at: 9000.0 + plant.ch.power_w
_s6 = SimCharger(setpoint_a=6)
_s6.phases_allowed = 1
r_fz_6a = P.drive(HOUSE, dur=500, sim=_s6, user_a=6, setpoint=6, phases=1,
events={150: freeze_1380})
_al6 = alarms(r_fz_6a)
check("N2 (probe G): a frozen 6 A, 1 phase figure (1380 W) after the car "
"really stops, and the house steps to 9 kW: the normal alarm fires "
f"within the stated bound ({_al6})",
[n for _t, n in _al6] == ["goodwe_peak_saturated"]
and 150 < _al6[0][0] < 150 + 104 + 10 + 25)
_s6h = SimCharger(setpoint_a=6)
r_6_honest = P.drive(HOUSE, dur=500, sim=_s6h, user_a=6, setpoint=6, phases=1,
opts={"peak_cap_w": 1500})
check("an honest 6 A, 1 phase car on the real controller: the corroboration "
"never turns the figure off (the car stays trusted to the end)",
r_6_honest["c"].car_alarm_w() is not None)
r_honest = P.drive(HOUSE, dur=400)
check("M5: an honest charging car still suppresses the alarms for the whole "
"run, meter and all", alarms(r_honest) == []