Merge pull request 'EV-13: a refused current write shows one amber row' (#269) from EV-13 into release/1.0
infra-pin / fresh (push) Successful in 2s

This commit was merged in pull request #269.
This commit is contained in:
2026-11-22 12:09:19 +01:00
5 changed files with 1418 additions and 8 deletions
+1
View File
@@ -2,6 +2,7 @@
### Not in a release yet
- When the car charger does not take a current setting but is plainly working, you now see one amber row ("did not take the setting"), not a second "reading may be stuck" ([[EV-13]]).
- The add-on no longer changes the car's phases while the car still draws: it waits until the charger reads under 100 W, and if the car is still drawing after 20 s it gives the current back and tries again after 10 minutes ([[EV-28]]).
- When the add-on changes the car's phases while the batteries are at the peak reserve, there is no longer a false "Battery stopped limiting the peak" for a moment ([[EV-15]]).
@@ -64,6 +64,16 @@ 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 refused write arms the stuck check only when the charger shows no life
(EV-13).** A charger that ignores a write keeps its old read-back, so the
check would read it as stuck 60 s later and show a second amber row beside
"did not take the setting". A refused write now arms only if, within `TOOK_S`
of the send, the energy, a phase current or the power changed in a sample taken
after the send, against the last value before (`CarTracker.note_write`,
`_alive`). Unchanged, absent before, or taken before the send is no life. No
life arms as before, dated the send. A write that raised, or was accepted, is
unchanged. A frozen charger (every write looks refused) still arms.
**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 after a write (SAFETY-37's shape),
+1 -1
View File
@@ -257,7 +257,7 @@ class ManualWriter:
finally:
self._stamp(now)
tracker.end_write(self.last_done)
tracker.note_write(now, was, a)
tracker.note_write(now, was, a, ok, getattr(drv, "polls", ()))
tracker.end_write(self.last_done)
self.log.append(("current", a, now, ok))
if ok:
+120 -7
View File
@@ -70,6 +70,7 @@ TOOK_S = 10.0 # a write is "taken" when the read-back follows by t
TOOK_TOL_A = 0.5 # ... to within this
STUCK_S = 60.0 # EV-04: power and read-back unchanged after a write
STUCK_MIN_A = 1.0 # ... that moved the setpoint by at least this
LIFE_KEEP_S = 40.0 # EV-13: samples kept to date a refused write's life
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).
@@ -120,6 +121,7 @@ REQUIRED = ("current", "readback", "state", "power")
_SETPOINT_RE = re.compile(r"^number\.(?P<x>.+)_" + SETPOINT_SUFFIX + "$")
_ROLE_ORDER = tuple(ROLES)
_LIFE_ROLES = ("power", "energy", "l1", "l2", "l3") # EV-13
#: power unit -> W. The probe and the reading both use this one table.
_W_PER = {"mW": 0.001, "W": 1.0, "kW": 1000.0, "MW": 1000000.0}
POWER_UNITS = tuple(_W_PER)
@@ -161,6 +163,10 @@ class ChargerReading:
error: str | None = None # None: no error (or not read)
display: str | None = None
why: str = "" # for the log only, "" when available
# EV-13: when the sample was TAKEN, on the tracker's clock. None: the
# caller's `now` (in the cycle that is the read's start, `now_mono`).
taken_at: float | None = None
phase_a: tuple = () # EV-13: L1, L2, L3 each, None if not read
def _state_obj(obj):
@@ -280,6 +286,7 @@ def reading_from_states(states: dict) -> ChargerReading:
available=True, state=letter, connected=connected, charging=charging,
power_w=power, energy_kwh=_kwh(states.get("energy")),
current_a=currents, setpoint_a=_amps(states.get("current")),
phase_a=tuple(_amps(states.get(k)) for k in ("l1", "l2", "l3")),
allowed_a=_amps(states.get("readback")),
phases_allowed=_phases(states.get("phases_read")),
station_a=_first(_amps(states.get("station_active")),
@@ -420,6 +427,9 @@ class AlfenHaDriver(ChargerDriver):
self._clock = time.monotonic
self.clamp_faults = [] # (asked, clamp), newest last, for the log
self.sent = [] # every number value actually sent
# EV-13: what the latest write saw while it waited for the read-back,
# [(time, ChargerReading)]: the cycle's reads do not run inside it.
self.polls = []
@classmethod
def from_options(cls, opts: dict) -> "AlfenHaDriver":
@@ -498,6 +508,7 @@ class AlfenHaDriver(ChargerDriver):
read-back followed within `TOOK_S`. A value above `clamp_a()` is a
SOFTWARE FAULT: nothing is sent, it is logged (the clamp watchdog's
shape) and the answer is False."""
self.polls = []
try:
a = float(a)
except (TypeError, ValueError):
@@ -522,7 +533,8 @@ class AlfenHaDriver(ChargerDriver):
"""Did the read-back follow the write, within `TOOK_S`?"""
t0 = self._clock()
while True:
st = await self._states(("readback", "current"))
st = await self._states(("readback", "current") + _LIFE_ROLES)
self._poll(st)
seen = _first(_amps(st["readback"]), _amps(st["current"]))
if seen is not None and abs(seen - a) <= TOOK_TOL_A:
return True
@@ -530,6 +542,17 @@ class AlfenHaDriver(ChargerDriver):
return False
await self._sleep(1.0)
def _poll(self, st: dict) -> None:
"""EV-13: keep what this wait saw of energy, power and phase currents
(never raises: a write does not depend on it)."""
try:
self.polls.append((self._clock(), ChargerReading(
available=True, power_w=_watts(st.get("power")),
energy_kwh=_kwh(st.get("energy")),
phase_a=tuple(_amps(st.get(k)) for k in ("l1", "l2", "l3")))))
except Exception: # noqa: BLE001
pass
async def write_phases(self, n: int) -> bool:
"""Select 1 or 3 phases. ONLY THROUGH `carmode`'s safe sequence: the
setting moves the contactors, so it is touched with the car paused."""
@@ -631,6 +654,31 @@ CHARGING, WAITING, NONE_, FULL, UNREACH, SETUP, FAULT = (
"charging", "waiting", "none", "full", "unreach", "setup", "fault")
def _life_vals(r) -> tuple:
"""EV-13: what shows a charger is alive: energy, power, three phase
currents. None is "not read"."""
cur = tuple(r.phase_a or ())
if len(cur) != 3:
# Only `current_a`, which leaves out a phase that is not read: which
# phase is which is then known only when all three are there.
cur = tuple(r.current_a or ())
cur = cur if len(cur) == 3 else (None,) * 3
return (r.energy_kwh, r.power_w) + cur
def _alive(vals: tuple, pre: list) -> bool:
"""A value that is present now, was present before the write, and differs
from every value before it. Present but unchanged, or not there before, is
no life."""
for i, v in enumerate(vals):
if v is None:
continue
old = [p[i] for p in pre if p[i] is not None]
if old and all(v != o for o in old):
return True
return False
@dataclass
class CarTracker:
"""What the cycle learns about the car from the readings. Pure, clocked by
@@ -663,6 +711,9 @@ class CarTracker:
sig: tuple | None = None
stuck_now: bool = False
obs_at: float | None = None # monotonic second of the latest reading
# EV-13: a REFUSED write waits to see if the charger shows life (below)
_pend: dict | None = None
_ring: list = field(default_factory=list) # (taken-at, life values)
_hist: list = field(default_factory=list) # (t, power W, energy Wh)
# today's energy
day: str | None = None
@@ -683,7 +734,10 @@ class CarTracker:
if usable:
self.last_ok = now
self.last_good, self.last_good_utc = r, now_utc
if not r.available:
self._pend_lapse(now)
if r.available:
self._life(r, now)
self._sig(r, now)
self._writer(r, now_utc, now)
self._energy(r, day)
@@ -727,19 +781,78 @@ class CarTracker:
`OWN_WRITE_MUTE_S` from now, not from before the write."""
self.mute_until = now + OWN_WRITE_MUTE_S
def note_write(self, now: float, was_a, to_a) -> None:
"""The add-on wrote the current. Its own change is not "another
writer" for `OWN_WRITE_MUTE_S`, and a write that moved the setpoint by
`STUCK_MIN_A` or more arms the stuck check: power and read-back that
have not changed `STUCK_S` later are a stuck reading, not a car."""
def note_write(self, now: float, was_a, to_a, ok: bool = True,
polls=()) -> None:
"""The add-on wrote the current at `now`. Its own change is not
"another writer" for `OWN_WRITE_MUTE_S`, and a write that moved the
setpoint by `STUCK_MIN_A` or more arms the stuck check: power and
read-back that have not changed `STUCK_S` later are a stuck reading,
not a car.
EV-13: a write the charger REFUSED (`ok` False) arms it only when the
charger shows no life: the energy, a phase current or the power
changed in a sample taken after `now` and within `TOOK_S` of it,
against the last values before. A refused write on a charger that is
plainly alive is not a stuck reading. `polls` are the samples the
write itself saw while it waited, `[(time, ChargerReading)]`."""
self.mute_until = now + OWN_WRITE_MUTE_S
try:
moved = was_a is None or abs(float(to_a) - float(was_a)) \
>= STUCK_MIN_A
except (TypeError, ValueError):
moved = False
if moved and self.armed_at is None:
if self._pend is not None and now > self._pend["t"] + TOOK_S:
self._pend_arm() # the old window ran out
if not moved or self.armed_at is not None:
return
if ok:
self._pend = None
self.armed_at, self.armed_sig = now, self.sig
return
if self._pend is not None:
return # an earlier refusal's window
before = [x for x in self._ring if x[0] <= now]
pre = [max(before, key=lambda x: x[0])[1]] if before else []
self._pend = {"t": now, "pre": pre, "sig": self.sig}
later = [(t, _life_vals(r)) for t, r in polls]
later += [(t, v) for t, v in self._ring if t > now]
for t, v in sorted(later, key=lambda x: x[0]):
self._pend_feed(t, v, t)
def _life(self, r, now: float) -> None:
"""EV-13: file this sample (by when it was TAKEN) and let a refused
write's open window look at it."""
t = now if r.taken_at is None else r.taken_at
v = _life_vals(r)
self._ring.append((t, v))
top = max(x[0] for x in self._ring)
self._ring = [x for x in self._ring if top - x[0] <= LIFE_KEEP_S]
self._pend_feed(t, v, now)
def _pend_feed(self, t: float, vals: tuple, arrival: float) -> None:
p = self._pend
if p is None:
return
if t <= p["t"]:
p["pre"] = (p["pre"] + [vals])[-8:] # taken before the send
elif t <= p["t"] + TOOK_S and _alive(vals, p["pre"]):
self._pend = None # life: nothing to arm
return
if max(t, arrival) > p["t"] + TOOK_S:
self._pend_arm()
def _pend_lapse(self, now: float) -> None:
"""A reading that did not answer shows no life either: once the window
has run out the refusal arms, dated the send, as it did before."""
p = self._pend
if p is not None and now > p["t"] + TOOK_S:
self._pend_arm()
def _pend_arm(self) -> None:
"""No life in the window: arm as the write would have, dated its send."""
p, self._pend = self._pend, None
if p is not None and self.armed_at is None:
self.armed_at, self.armed_sig = p["t"], p["sig"]
def _sig(self, r, now: float) -> None:
sig = (r.power_w, r.allowed_a)
File diff suppressed because it is too large Load Diff