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
@@ -62,13 +62,23 @@ stops holding late in a period that the car already pushed over, because
`excess_w` grows as the seconds run out; the average form does not, and it is the
same test for a steady car.
**A stale or stuck car figure must never hide a real overload.** Only
**A stale, stuck or frozen car figure must never hide a real overload.** Only
`CarTracker.car_w_trusted` is used: fresh (the EV-03 rules, which also make an
unavailable reading None at once), not stuck (power and read-back unchanged 60 s
after a write that moved the setpoint by 1 A or more, SAFETY-37's shape), and never
above what the read-back allows the car to draw. A figure that is stuck from the
start with no write is not caught by the stuck rule; it is bounded by the
read-back and is the one hole this card leaves (the design's own rule).
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.
## Decision 1 (`ev_batt_cover`)
+12 -5
View File
@@ -3328,10 +3328,15 @@ what the car drew. When the car alone is why the batteries cannot hold the
period, the add-on does **not** raise *Battery stopped limiting the peak* or
*Load too high for battery*. It shows a grey note *Car over the peak
limit* once per charging session, a grey row, and says so in the car's *Why*.
This holds only while the car's reading is fresh: a stale or stuck reading
never hides a real overload of the house. With `ev_batt_cover` off, the peak
guard protects the house without the car, so it does not force the batteries to
discharge for it, and the period goes over by the car alone. When the month's peak was set by a car
This holds only while the car's reading is fresh and the charger's energy
meter confirms it (the meter must have gained at least half of what the power
adds up to over the last minute). A stale, stuck or frozen reading, or a
charger with no energy entity, never hides a real overload of the house: the
normal alarms stand. With `ev_batt_cover` off, the peak
guard protects the house without the car, so it does not spend the batteries on
it. Normal zero-grid control can still discharge them for the car, and a grid
charge of the batteries can bring the period to the peak limit plus the car.
The period can go over by the car alone. When the month's peak was set by a car
charge, Home's peak line says so.
**When the charger does not answer.** After 30 seconds the card says *Charger
@@ -3340,7 +3345,9 @@ follows. While the car reading is older than 15 seconds the House tile shows no
reading, and that moment is left out of the house profile, rather than guessing
how much the car took. A reading that does not move for a minute after the
add-on changed the current shows the amber row *Charger reading may be stuck*;
the add-on goes on writing.
the add-on goes on writing. If the charger does not take a phase change three
times, an amber row says so and the add-on stops trying until you change
something; the car gets its current back each time.
**Another writer.** In Manual, if the charger shows a different current than the
add-on set, for 30 seconds, something else is setting it, usually your own
+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",
+306 -32
View File
@@ -186,6 +186,18 @@ class World:
await self.c.cycle()
await self.c.car_settle()
async def step_race(self, n=1, dt=1.0):
"""The production order: the writer task can finish AFTER the cycle's
read and BEFORE that cycle's kick (read -> task settles -> cycle), so
the step that follows sees a reading older than the write."""
for _ in range(n):
self.sim.tick(dt)
self.t += dt
CLOCK[0] = self.t
await self.c.read_inputs(now_mono=self.t)
await self.c.car_settle()
await self.c.cycle()
async def act(self, what, value):
return await self.c.handle_action(what, value=value)
@@ -682,6 +694,134 @@ async def phases_in_off():
check("in Off a phase change writes nothing either",
run(phases_in_off()).writes() == [])
print("\n5b. ROUND 2: THE SEQUENCE UNDER A RACING WRITER, A REFUSED SELECT, "
"A MODE CHANGE, THE CLAMP")
async def m1_race(lag):
# the writer task finishes between a cycle's read and that cycle's kick
w = World(setpoint=10, phases=1)
w.sim.lag_s = lag
await w.step(8)
await w.act("car_mode", "manual")
await w.act("car_current", 10)
await w.step(10)
n0 = len(w.writes())
await w.act("car_phases", 3)
await w.step_race(60)
seq = [(x[1], x[2]) for x in w.writes()[n0:]]
await w.step_race(300)
return w, seq
for _lag in (0.0, 3.0):
w_m1, seq_m1 = run(m1_race(_lag))
check(f"M1 (read -> writer settles -> cycle, read-back lag {_lag:.0f} s): "
"the phases are selected and the car gets its 10 A back, with no "
f"false 'something else changed the charger' ({seq_m1})",
seq_m1 == [("current", 0.0), ("phases", 3), ("current", 10.0)]
and w_m1.sim.readback_a == 10 and w_m1.sim.phases_allowed == 3
and not w_m1.c.car_writer.hold and "charger_other" not in w_m1.rows()
and w_m1.sim.power_w > 6000)
async def m2_refused():
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 deaf(n): # Home Assistant says yes, nothing moves
sim.log.append((sim.t, "phases", n, sim.power_w, sim.setpoint_a))
return True
sim.request_phases = deaf
n0 = len(w.writes())
await w.act("car_phases", 3)
await w.step(3700)
mid = [x for x in w.writes()[n0:]]
ph = [x for x in mid if x[1] == "phases"]
zeros = [x for x in mid if x[1] == "current" and x[2] == 0.0]
out = dict(ph=len(ph), zeros=len(zeros), rb=sim.readback_a,
gave=getattr(w.c.car_writer, "phases_gave_up", None), row=w.rows().get(
"charger_phases"), power=sim.power_w)
await w.act("car_phases", 3) # the user asks again: tried again
await w.step(60)
out["after_user"] = len([x for x in w.writes() if x[1] == "phases"]) - len(ph)
return out
m2 = run(m2_refused())
check("M2: a phase select the charger never takes is tried 3 times (10 minutes "
"apart), not for ever", m2["ph"] == 3 and m2["zeros"] == 3)
check("...each time the car gets its current back on the old phases (10 A, "
"drawing), and at the end it is not left paused", m2["rb"] == 10
and m2["power"] > 2000)
check("...then an amber row says the charger did not take the phases, and "
"the add-on stops trying", m2["gave"] is True
and m2["row"]["ok"] is False and m2["row"]["warn"] is True)
check("...until the user changes something: then it tries again",
m2["after_user"] == 1)
async def m3(trigger):
w = World(setpoint=10, phases=1)
w.sim.ramp_w_s = 50.0
w.sim.stop_delay_s = 40.0
await w.step(60)
await w.act("car_mode", "manual")
await w.act("car_current", 10)
await w.step(3)
await w.act("car_phases", 3)
await w.step(3) # 0 A written, the select not yet
n0 = len(w.writes())
mid = (w.sim.readback_a, w.c.car_writer.seq["stage"])
if trigger == "off":
await w.act("car_mode", "off")
elif trigger == "shadow":
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", []),
("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})",
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)
async def m4():
w = World(dict(CAR, ev_max_a=10), setpoint=16, phases=1)
w.sim.ramp_w_s = 50.0
w.sim.stop_delay_s = 40.0
await w.step(60)
await w.act("car_mode", "manual")
await w.act("car_phases", 3)
await w.step(4)
prev = w.c.car_writer.seq["prev"]
await w.c.car_shutdown()
return w, prev
w_m4, prev_m4 = run(m4())
check("M4: the old read-back was 16 A (another writer's) against ev_max_a 10; "
"the restore on shutdown is clamped: the car gets 10 A back, no "
"software fault is logged",
prev_m4 == 16.0 and w_m4.sim.readback_a == 10.0
and w_m4.drv.clamp_faults == [] and w_m4.drv.sent[-1] == 10.0)
# --- every write path: who calls the seam, and a fuzz over the lot --------- #
def seam_callers():
"""(file, name) of every call of the charger's write methods in app/."""
@@ -712,47 +852,71 @@ async def fuzz(seed):
rnd = random.Random(seed)
w = World(setpoint=rnd.choice([6, 10, 16]), phases=rnd.choice([1, 3]))
w.sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0])
bad = []
seen = 0
race = seed % 2 == 1 # half the sites run read -> settle -> cycle
bad, seen, others, holds, undos = [], 0, 0, 0, 0
last_switch = None
if rnd.random() < 0.8:
await w.act("car_mode", "manual")
for step in range(400):
c, sim = w.c, w.sim
seq = c.car_writer.seq is not None
wr = c.car_writer
stage = wr.seq["stage"] if wr.seq is not None else None
seq = stage is not None
r = rnd.random()
if r < 0.02:
if stage in ("zero", "select") and rnd.random() < 0.15:
# the user, a stop or shadow mode arrives mid-sequence
pick = rnd.choice(["off", "stop", "shadow"])
if pick == "off":
await w.act("car_mode", "off")
elif pick == "stop":
c.auto = False
else:
c.o["shadow_mode"] = "on"
elif r < 0.02:
await w.act("car_mode", rnd.choice(["off", "manual", "manual"]))
elif r < 0.07:
await w.act("car_current", rnd.randint(6, 16))
elif r < 0.09:
await w.act("car_phases", rnd.choice([1, 3]))
elif r < 0.095 and not seq:
elif r < 0.093 and not seq:
sim.go_unavailable(rnd.random() < 0.5)
elif r < 0.10 and not seq:
elif r < 0.096 and not seq:
sim.station_a = float(rnd.choice([10, 13, 16]))
elif r < 0.105 and not seq:
elif r < 0.099 and not seq:
(sim.unplug if sim.state != "A" else sim.plug_in)()
elif r < 0.103 and rnd.random() < 0.5:
elif r < 0.108:
sim.set_current(rnd.randint(0, 16)) # another writer
elif r < 0.115:
others += 1
elif r < 0.112:
sim.refuse = rnd.choice([None, None, "ignore", "error"])
elif r < 0.12:
elif r < 0.116:
c.auto = rnd.random() < 0.8
mode_now, auto_now = c.car_mode, c.auto
n0 = len(sim.log)
await w.step(1)
elif r < 0.12:
c.o["shadow_mode"] = rnd.choice(["on", "off", "off"])
mode_now, auto_now, shadow_now = c.car_mode, c.auto, c.shadow
n0, u0 = len(sim.log), getattr(wr, "undone", 0)
await (w.step_race(1) if race else w.step(1))
undone = getattr(wr, "undone", 0) > u0
undos += undone
holds += bool(wr.hold)
for t, what, v, power, sp in sim.log[n0:]:
clamp = min(16.0, sim.station_a)
# a sequence whose select has gone out is finished whatever the
# mode says; one undone before it gives the old current back
exempt = stage == "settle" or undone
if what == "current" and not 0.0 <= v <= clamp + 1e-9:
bad.append((seed, step, "over the clamp", v, clamp))
if what == "current" and (mode_now != "manual" and not seq):
if what == "current" and mode_now != "manual" and not exempt:
bad.append((seed, step, "written outside Manual", mode_now))
if what in ("current", "phases") and not auto_now and not seq:
if what in ("current", "phases") and not auto_now and not exempt:
bad.append((seed, step, "written with control stopped"))
if what in ("current", "phases") and shadow_now and not exempt:
bad.append((seed, step, "written in shadow mode"))
if what == "current" and sim.state == "A" and not seq:
bad.append((seed, step, "written with no car"))
if what == "phases":
if mode_now != "manual" or not auto_now or shadow_now:
bad.append((seed, step, "phases selected outside Manual"))
if sp != 0.0:
bad.append((seed, step, "phases with the setpoint up", sp))
if last_switch is not None and t - last_switch < 600.0:
@@ -760,19 +924,26 @@ async def fuzz(seed):
t - last_switch))
last_switch = t
seen += len(sim.log) - n0
return bad, seen
return bad, seen, others, holds, undos
fz_bad, fz_n = [], 0
fz_bad, fz_n, fz_o, fz_h, fz_u = [], 0, 0, 0, 0
for _seed in range(14):
_b, _n = run(fuzz(_seed))
_b, _n, _o, _h, _u = run(fuzz(_seed))
fz_bad += _b
fz_n += _n
fz_o += _o
fz_h += _h
fz_u += _u
check(f"fuzz: {fz_n} charger writes over 14 random sites and 5600 steps of "
f"random user changes, outages, unplugs, refusals and other writers: "
f"none over the clamp, none outside Manual, none with control stopped "
f"or no car, the phases never moved with the car drawing, one switch "
f"per 10 minutes ({fz_bad[:3]})", not fz_bad and fz_n > 100)
f"random user changes, outages, unplugs, refusals, shadow and control "
f"stops, in both cycle orders: none over the clamp, none outside "
f"Manual, none with control stopped, in shadow mode or with no car, the "
f"phases never selected outside Manual or with the car drawing, one "
f"switch per 10 minutes ({fz_bad[:3]})", not fz_bad and fz_n > 100)
check(f"fuzz: the other-writer branch runs ({fz_o} other writers made, "
f"{fz_h} steps with the add-on holding off one, {fz_u} sequences undone)",
fz_o > 30 and fz_h > 5 and fz_u > 0)
# =========================================================================== #
print("\n6. SHADOW MODE AND A STOPPED CONTROL WRITE NOTHING")
@@ -1160,16 +1331,101 @@ w_ = r_stuck["c"]
check("...while stuck, the car figure is not used by the alarm path",
w_.car.stuck(w_.car_now()) and w_.car_alarm_w() is None)
# a plausible figure is bounded by what the read-back allows
# a plausible figure is bounded by what the read-back allows (and needs an
# energy meter that agrees with it)
def corr(tr, t):
f = getattr(tr, "corroborated", None)
return f(t) if f else True # an old tree has no such rule
def charging_reading(e_kwh, w=11000.0, a=6.0):
return CH.ChargerReading(available=True, state="C", charging=True,
power_w=w, allowed_a=a, setpoint_a=a,
phases_allowed=1, energy_kwh=e_kwh)
def feed(tr, secs, e_of, w=11000.0, t0=100.0):
for i in range(secs):
tr.observe(charging_reading(e_of(i), w), t0 + i,
datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16")
return t0 + secs - 1
tr = CH.CarTracker()
tr.observe(CH.ChargerReading(available=True, state="C", power_w=11000.0,
allowed_a=6.0, setpoint_a=6.0,
phases_allowed=1), 100.0,
datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16")
check("a car figure of 11 kW on a 6 A, 1 phase read-back counts for no more "
t_end = feed(tr, 80, lambda i: 1000.0 + i * 11000.0 / 3.6e6)
check("an honest 11 kW figure on a 6 A, 1 phase read-back counts for no more "
"than that allows (1.5 kW), so an old figure cannot cover a house "
"overload", abs(tr.car_w_trusted(100.0) - 6 * 253) < 1)
check("...and None when it is not fresh", tr.car_w_trusted(100.0 + 16) is None)
"overload", abs(tr.car_w_trusted(t_end) - 6 * 253) < 1
and corr(tr, t_end))
check("...and None when it is not fresh", tr.car_w_trusted(t_end + 16) is None)
tr = CH.CarTracker()
t_end = feed(tr, 20, lambda i: 1000.0)
check("the first minute of readings is believed (a session just began): no "
"false alarm while the meter has had no time to show it",
corr(tr, t_end) and tr.car_w_trusted(t_end) is not None)
t_end = feed(tr, 80, lambda i: 1000.0, t0=t_end + 1)
check("M5: a power figure of 11 kW with an energy meter that does not move "
"is not corroborated after a window: no car figure for the alarms",
not corr(tr, t_end) and tr.car_w_trusted(t_end) is None)
tr = CH.CarTracker()
t_end = feed(tr, 80, lambda i: 1000.0 + i * 1500.0 / 3.6e6)
check("M5: a meter that gains 1.5 kW while the power says 11 kW is not "
"corroborated either", not corr(tr, t_end))
tr = CH.CarTracker()
t_end = feed(tr, 80, lambda i: None)
check("M5: no energy entity: never corroborated, so never used",
not corr(tr, t_end) and tr.car_w_trusted(t_end) is None)
tr = CH.CarTracker()
t_end = feed(tr, 80, lambda i: 1000.0 + i * 5000.0 / 3.6e6, w=5000.0)
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))
# --- M5 end to end: the meter, the plant and the real controller ------------- #
def freeze_all(plant, c):
plant.ch.freeze() # every reading sticks
plant.ch.set_current(0) # the car really stops
plant.load = lambda at: 9000.0 + plant.ch.power_w
def freeze_power_only(plant, c):
plant.ch.freeze_power() # only the power sensor sticks
plant.ch.set_current(6) # the car really draws 1.4 kW
plant.ch.set_phases(1)
plant.load = lambda at: 9000.0 + plant.ch.power_w
r_fz_mid = P.drive(HOUSE, dur=400, events={120: freeze_all})
r_fz_pw = P.drive(HOUSE, dur=400, events={120: freeze_power_only})
r_fz_0 = P.drive(HOUSE, dur=400, events={5: freeze_all})
r_noe = P.drive(HOUSE, dur=240, sim=SimCharger(setpoint_a=16))
for _name, _r, _t0 in (("a freeze in the middle of a session (everything "
"stuck, the car stops)", r_fz_mid, 120),
("only the power sensor sticks while the car draws "
"1.4 kW", r_fz_pw, 120),
("a freeze from the start", r_fz_0, 5)):
_al = alarms(_r)
check(f"M5: {_name} and the house steps to 9 kW: after a window the "
f"normal alarm fires ({_al})",
[n for _t, n in _al] == ["goodwe_peak_saturated"]
and _t0 < _al[0][0] < _t0 + 60 + 25)
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) == []
and len(P.ids(r_honest, P.OVER)) == 1)
class _NoE(SimCharger):
pass
_sim_noe = SimCharger(setpoint_a=16)
_sim_noe.no_energy = True
r_noe = P.drive(HOUSE, dur=240, sim=_sim_noe)
check("M5: a charger with no energy entity does not suppress: the normal "
"alarm fires and there is no car notice",
[n for _t, n in alarms(r_noe)] == ["goodwe_peak_saturated"]
and P.ids(r_noe, P.OVER) == [])
# =========================================================================== #
print("\n10. DECISION 1: BATTERIES HELP WITH THE PEAK, ON AND OFF")
@@ -1187,8 +1443,9 @@ check("off: the guard sees the house without the car, is not engaged, and the "
check("off: the quarter goes over by the car alone, and the add-on says so "
"(one grey notice), with no alarm",
alarms(r_no) == [] and len(P.ids(r_no, P.OVER)) == 1)
check("off: the Why says the batteries keep their charge",
"keep their charge" in cardwhy(r_no))
check("off: the Why says the guard ignores the car (and promises nothing "
"about the batteries)", "guard ignores the car" in cardwhy(r_no)
and "keep their charge" not in cardwhy(r_no))
check("either way the car is never throttled",
r_on["sim"].writes() == [] and r_no["sim"].writes() == []
and r_no["sim"].setpoint_a == 16 and r_no["sim"].power_w > 10000)
@@ -1445,6 +1702,23 @@ check("the Dutch is not the English for the sentences",
for k in ("manual_set", "manual_cover", "manual_over", "manual_full",
"manual_nocover", "manual_wait", "manual_would",
"manual_stopped", "manual_blocked")))
check("L2: one wording for 'something else changes the charger', in Off and "
"Manual, English and Dutch",
en["home_words"]["attn"]["charger_other"]
== en["home_words"]["attn"]["charger_writer"]
and nl["home_words"]["attn"]["charger_other"]
== nl["home_words"]["attn"]["charger_writer"]
and "changes the charger" in str(messages.row_charger_other())
and "wijzigt de laadpaal" in messages.row_charger_other().nl
and "changed" not in str(messages.row_charger_other()))
check("L3: with Batteries help off the Why promises nothing about the "
"batteries, and DOCS says what it does",
"keep their charge" not in json.dumps(en) + json.dumps(nl)
.replace("houden hun lading", "keep their charge")
and "zero-grid control can still discharge them for the car"
in io.open(os.path.join(HERE, "DOCS.md"), encoding="utf-8").read()
.replace("\n", " ").replace("Normal zero-grid control can still",
"zero-grid control can still"))
check("every new row, notice and refusal is bilingual",
all(getattr(f, "nl", None) for f in (
messages.row_car_over(), messages.row_charger_other(),
+13 -2
View File
@@ -64,6 +64,8 @@ class SimCharger:
self.lag_s = 0.0 # a write shows in the read-back this late
self.refuse = None # None | "ignore" | "error"
self._snap = None # `freeze()`: the readings stop moving
self._frozen_w = None # `freeze_power()`: only the power does
self.no_energy = False # a charger with no energy entity
self.ramp_w_s = RAMP_W_S # how fast the power follows its target
self.stop_delay_s = 0.0 # mode3 stays C this long after 0 A
self._c_hold = 0.0
@@ -183,6 +185,11 @@ class SimCharger:
moment, whatever the charger does after it."""
self._snap = self._build() if on else None
def freeze_power(self, on=True):
"""Only the power sensor sticks, at what it reads now; the energy meter
and the rest go on telling the truth."""
self._frozen_w = self.power_w if on else None
def states(self) -> dict:
return self._snap if self._snap is not None else self._build()
@@ -207,7 +214,8 @@ class SimCharger:
{"A": "Available", "B": "EV Connected",
"C": "Charging Normal"}.get(self.state, "Error")),
st(f"sensor.{x}_active_power_total_socket_1",
f"{self.power_w:.0f}", "W"),
f"{self.power_w if self._frozen_w is None else self._frozen_w:.0f}",
"W"),
st(f"sensor.{x}_meter_reading_socket_1", f"{self.kwh:.2f}",
"kWh"),
st(f"sensor.{x}_current_l1_socket_1", f"{amps[0]:.1f}", "A"),
@@ -226,7 +234,10 @@ class SimCharger:
"state": bad or ("on" if self.login_on else "off"),
"attributes": {"device_class": "connectivity"}}),
]
return dict(rows)
out = dict(rows)
if self.no_energy:
out.pop(f"sensor.{x}_meter_reading_socket_1", None)
return out
class FakeHa: