From 2cfbc4aec87ab443504313e7d03d323267224a52 Mon Sep 17 00:00:00 2001 From: glenn schrooyen Date: Tue, 17 Nov 2026 13:26:56 +0100 Subject: [PATCH 1/4] EV-15: the add-on's own phase change at the peak reserve raises no false alarm While the add-on holds the car at 0 A for its own phase change, the car's figure had no corroboration (not charging), so nothing was explained and the peak-floor alarm fired once. For grading only, the car's fresh, not stuck figure now stands in for that sequence (bounded: its own waits plus one corroboration window), ending at once on Off, Stop, shadow, unplug, another writer or a refused write. car_exclude, the claim, floor and writes unchanged. Co-Authored-By: Claude --- goodwe_controller/CHANGELOG.md | 4 + .../DECISIONS/EV-04-manual-mode.md | 15 + goodwe_controller/app/carmode.py | 6 + goodwe_controller/app/chargers.py | 14 +- goodwe_controller/app/ctl_car.py | 63 ++++- goodwe_controller/test_ev15.py | 265 ++++++++++++++++++ 6 files changed, 355 insertions(+), 12 deletions(-) create mode 100644 goodwe_controller/test_ev15.py diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index 88a23a2..0d68c33 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +### Not in a release yet + +- 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]]). + ## 0.24.0 **A minor bump: the add-on can now charge the car (Manual mode), and a car that alone takes the batteries to the peak reserve no longer raises a false peak alarm. Two new options were added, both with defaults, and none needs setting.** diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index 24ceea8..1d85320 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -120,6 +120,21 @@ up to 1.8 kW; the 40 Wh floor fixes that.) the gaps seen on the rig, 150 to 250 s at 50 s sampling, and shorter than a quarter) and a gap does not restart the 10 s on-count. `car_explains`, which the alarms read, has no hold. +- **Our own phase change is not a reason to alarm** (EV-15). Rig, twice: at the + reserve, with the car covering, the add-on's 3 -> 1 switch set the car to 0 A. + A car that is not charging has no corroboration (`CarTracker._corr_note` clears + the window, `corroborated` is False), so `car_alarm_w()` was None, the car + explained nothing and `_car_need_excl` latched for the quarter: one + PEAK_GUARD_FLOOR_LIMITED and one `goodwe_peak_soc_floor`. Now, only for grading + (`car_cycle`), `ctl_car._car_own_pause` lets the car's fresh, not stuck figure + (`CarTracker.car_w_paused`, 0 W while paused) stand in without corroboration: + from our 0 A write (`seq` exists) until the current is set again, at most + `OWN_PAUSE_MAX_S` (85 s, the sequence's own waits), then at most one + corroboration window (60 s). It ends at once on Off, Stop, shadow, unplug, + another writer, or a refused select or write (`seq["failed"]`). The energy it + drew in the pause is kept apart (`ws_p`), so `car_exclude`, the guard's + input, the claim, floor and writes are unchanged. A house overload still fails + the test without the car, so it alarms as on Off. - **Our own write is ours until its mute ends** (EV-12). The mute of the tracker's own detector opens before the write and runs 15 s from when it returns, because the read-back reaches the cycle while the write still waits for it. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 0284b15..38e19e4 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -125,6 +125,7 @@ class ManualWriter: self.phase_fails = 0 # phase selects the charger did not take self.phases_gave_up = False self.undone = 0 # sequences undone before the select + self.phase_done_at = None # EV-15: our phase change ended well then # ------------------------------------------------------------------ user def user_changed(self) -> None: @@ -296,6 +297,7 @@ class ManualWriter: if not ok: self._failed(now) return + self.phase_done_at = None self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, "prev": cur} @@ -336,6 +338,7 @@ class ManualWriter: self.log.append(("phases", q["n"], now, ok)) q["stage"], q["t1"] = "settle", self.last_done # from its return if not ok: + q["failed"] = True # EV-15: no grace for the alarm # The charger did not take it: the car gets its current back # 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 @@ -356,7 +359,10 @@ class ManualWriter: # still wanted, and one that is in place is adopted. self.seq, self.rev_applied, self.reapply = None, None, False self.fails, self.blocked = 0, False + if not q.get("failed"): + self.phase_done_at = self.last_done # EV-15 return + q["failed"] = True # EV-15: a refused write ends it q["tries"] += 1 if q["tries"] >= MAX_TRIES: # Left at 0 A is the safe side; the next reading re-applies. diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index ed62829..caa6618 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -800,8 +800,20 @@ class CarTracker: 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.""" + return self._capped_w(now, True) + + def car_w_paused(self, now: float): + """EV-15: the same figure as `car_w_trusted` without the energy-meter + corroboration, which a car held at 0 A by the add-on's own phase change + cannot give (the meter's window restarts when it stops charging). Fresh, + not stuck, and capped by the read-back. Only for grading the alarm + during that sequence (`ctl_car._car_own_pause`).""" + return self._capped_w(now, False) + + def _capped_w(self, now: float, corroborate: bool): w = self.car_w(now) - if w is None or self.stuck(now) or not self.corroborated(now): + if w is None or self.stuck(now) \ + or (corroborate and not self.corroborated(now)): return None r = self.reading a = r.allowed_a if r.allowed_a is not None else r.setpoint_a diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 9534160..8e11071 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -24,6 +24,13 @@ OVER_HOLD_S = peakguard.ALARM_HOLD_S # the cause: longer than the gaps seen on the rig (150 to 250 s at 50 s # sampling) and shorter than a quarter, or until the session really ends. OVER_OFF_HOLD_S = 180.0 +# EV-15: the longest our own phase change can take (0 A wait, settle, three +# tries of a write at 5 s apart and up to 10 s each, the select's own wait); +# the grace for the alarm never outlasts it, and after the current is set +# again it lasts at most one corroboration window. +OWN_PAUSE_MAX_S = (carmode.ZERO_WAIT_S + carmode.SETTLE_S + + carmode.MAX_TRIES * 15.0 + 10.0) +OWN_PAUSE_TAIL_S = chargers.CORR_WINDOW_S class CarMixin: @@ -57,7 +64,7 @@ class CarMixin: self._car_over_notified = None # the session a notice was raised for self._car_session = 0 self._car_prev_state = None - self._carq = {"key": None, "ws": 0.0, "mono": None} + self._carq = {"key": None, "ws": 0.0, "ws_p": 0.0, "mono": None} self._peak_proj_real = None saved = data.get(CAR_PEAK_KEY) self.car_peak_q = dict(saved) if isinstance(saved, dict) else {} @@ -206,17 +213,42 @@ class CarMixin: return None return self.car.car_w_trusted(self.car_now()) - def _car_quarter(self, proj, w, mono) -> None: + def _car_own_pause(self, mono) -> bool: + """EV-15: is the car held at 0 A by the add-on's OWN phase change (its + 0 A write until the current is set again, then at most one + corroboration window)? No when it was aborted (Off, Stop, shadow, + unplug, another writer), a write was refused, or it ran past its own + maximum.""" + wr = getattr(self, "car_writer", None) + if wr is None or (wr.seq is None and wr.phase_done_at is None): + return False + r = self.car.reading + if not (self.car_manual() and self.car_writing() + and r is not None and r.available and r.state != "A"): + return False + q = wr.seq + if q is not None: + return not q.get("failed") and 0.0 <= mono - q["t0"] \ + <= OWN_PAUSE_MAX_S + return 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S + + def _car_quarter(self, proj, w, mono, wg=None) -> None: """The car's energy in the open quarter, for the average the guard's - house leaves out and for the peak line.""" + house leaves out and for the peak line. `wg` (EV-15) is the figure for + grading during our own pause; its energy is kept apart (`ws_p`) so the + guard's input is unchanged.""" q = self._carq key = None if proj is None else proj.block_start last = q["mono"] if key != q["key"]: self._car_bank(q) - q["key"], q["ws"] = key, 0.0 - if key is not None and w is not None and last is not None: - q["ws"] += float(w) * min(max(mono - last, 0.0), 5.0) + q["key"], q["ws"], q["ws_p"] = key, 0.0, 0.0 + if key is not None and last is not None: + dt = min(max(mono - last, 0.0), 5.0) + if w is not None: + q["ws"] += float(w) * dt + elif wg is not None: + q["ws_p"] = q.get("ws_p", 0.0) + float(wg) * dt q["mono"] = mono def _car_bank(self, q) -> None: @@ -233,14 +265,17 @@ class CarMixin: del self.car_peak_q[k] self.store.set(CAR_PEAK_KEY, dict(self.car_peak_q)) - def car_avg_w(self, proj, w) -> float: + def car_avg_w(self, proj, w, graded=False) -> float: """The car's average over the whole open quarter: what it drew so far - and `w` for the rest.""" + and `w` for the rest. `graded` (EV-15) adds what it drew during our + own pause.""" if proj is None or w is None: return 0.0 left = max(0.0, QUARTER_S - float(proj.elapsed_s)) so_far = self._carq["ws"] if self._carq["key"] == proj.block_start \ else 0.0 + if graded and self._carq["key"] == proj.block_start: + so_far += self._carq.get("ws_p", 0.0) return (so_far + float(w) * left) / QUARTER_S def car_exclude(self, proj, w): @@ -264,7 +299,7 @@ class CarMixin: the car asked for. Unchanged without a fresh car reading.""" if proj is None or w is None or proj.block_start is None: return proj - avg = self.car_avg_w(proj, w) + avg = self.car_avg_w(proj, w, graded=True) left = max(0.0, QUARTER_S - float(proj.elapsed_s)) held = float(proj.held_w) done_ws = QUARTER_S * float(proj.projected_w) - max(held, 0.0) * left @@ -280,13 +315,19 @@ class CarMixin: `real_proj` is the projection WITH the car, whatever the guard saw.""" mono = self.car_now() w = self.car_alarm_w() - self._car_quarter(real_proj, w, mono) + # EV-15: the figure for grading only. Our own phase change holds the + # car at 0 A and the energy meter cannot corroborate it then, so for + # that bounded time its fresh, not stuck figure stands in. + wg = w + if w is None and self._car_own_pause(mono): + wg = self.car.car_w_paused(mono) + self._car_quarter(real_proj, w, mono, wg) self._car_session_tick(mono) explains = over = False if real_proj is not None and target_w is not None \ and real_proj.block_start is not None: # EV-10: every cycle, so the latches do not depend on the option. - graded = self._car_explains_alarm(real_proj, guard, target_w, w) + graded = self._car_explains_alarm(real_proj, guard, target_w, wg) if self.car_cover: explains = over = graded elif w is not None: diff --git a/goodwe_controller/test_ev15.py b/goodwe_controller/test_ev15.py new file mode 100644 index 0000000..6713371 --- /dev/null +++ b/goodwe_controller/test_ev15.py @@ -0,0 +1,265 @@ +"""EV-15: the add-on's own phase change at the peak reserve raises no alarm. +`python3 -B test_ev15.py` + +The rig (EV-10 and EV-10b, F-2): cover on, the batteries at the reserve, the car +charging and explaining the excess. The add-on's own 3 -> 1 phase switch sets +the car to 0 A; with the car not charging its figure is no longer corroborated +(`CarTracker.corroborated`), so `car_alarm_w()` is None, nothing is explained, +and PEAK_GUARD_FLOOR_LIMITED plus `goodwe_peak_soc_floor` fire. The rule: for +the add-on's own sequence only (`ctl_car._car_own_pause`, bounded) the car's +fresh, not stuck figure stands in for grading. + +1. The rig shapes end to end through the car cycle: 3 -> 1 and 1 -> 3. +2. A house overload that starts during the sequence still alarms, as on Off. +3. Aborted (Off, Stop, unplug), refused, an outside writer: no grace. +4. The bounds, and the figure that stands in (stale, stuck: nothing). +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import logging +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import ctl_car, carmode, chargers as CH # noqa: E402 +import ev04_peak as P # noqa: E402 +import safety81_sim as s81 # noqa: E402 + +logging.disable(logging.CRITICAL) +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +def at(t, fn): + return {"t": t, "fn": fn} + + +def run(house, cap, t_res, t_sw, new, *, extra=None, mode="manual", + sim_fn=None, dur=895, plug=True): + """Reserve at `t_res`, our phase change to `new` at `t_sw`. Returns the + run, a per-second trace (second, own-pause, explains, red rows) and the + alarms.""" + tr = [] + + def note(plant, c): + red = [x["id"] for x in c.checks() + if x["ok"] is False and not x["warn"]] \ + if t_sw - 5 <= plant.t <= t_sw + 90 else [] + g = c.peak_guard + lim = bool(g is not None and (g.floor_limited or g.saturated)) + tr.append((plant.t, getattr(c, "_car_own_pause", lambda _t: False)(c.car_now()), c.car_explains, + red, plant.ch.power_w, plant.ch.state, lim)) + + def reserve(plant, c): + plant.soc = 19.0 + plant.load = lambda t: house + plant.ch.power_w + + def switch(plant, c): + asyncio.get_event_loop().create_task( + c.handle_action("car_phases", value=new)) + + ev = {t: note for t in range(0, dur)} + ev[t_res] = lambda p, c: (reserve(p, c), note(p, c)) + ev[t_sw] = lambda p, c: (switch(p, c), note(p, c)) + for t, fn in (extra or {}).items(): + prev = ev.get(t, note) + ev[t] = (lambda p, c, prev=prev, fn=fn: (fn(p, c), prev(p, c))) + sim = None + if sim_fn is not None: + from chargersim import SimCharger + sim = SimCharger(setpoint_a=16) + sim_fn(sim) + r = P.drive(s81.constant(house), dur=dur, rating=12000.0, soc=60.0, + cap=cap, phases=(3 if new == 1 else 1), user_a=16, setpoint=16, + mode=mode, events=ev, sim=sim, plug=plug) + return r, tr, P.ids(r, *P.ALARMS) + + +def reds(tr): + return [x for x in tr if x[3]] + + +# =========================================================================== # +print("1. THE RIG SHAPES THROUGH THE CAR CYCLE") +# =========================================================================== # +SHAPES = ( + ("EV-10 shape: house 3 kW, car 11 kW, aim 6 kW, 3 -> 1", + 3000.0, 6050.0, 300, 600, 1), + ("EV-10b shape: a 9411 W limit, 3 -> 1", 2000.0, 9461.0, 300, 600, 1), + ("1 -> 3 (the car 3.7 kW, then 11 kW), aim 5 kW", 2500.0, 5050.0, + 100, 600, 3), +) +for name, house, cap, t_res, t_sw, new in SHAPES: + r, tr, al = run(house, cap, t_res, t_sw, new) + c, sim = r["c"], r["sim"] + sw = [x for x in sim.writes() if x[1] == "phases"] + check(f"{name}: the car at the reserve covers, and the add-on's own " + f"sequence ran (0 A, select, the current back)", + len(sw) == 1 and [x[2] for x in sim.writes("current")][-2:] + == [0.0, 16.0] and sim.phases_allowed == new) + pause = [x for x in tr if x[1]] + check(f"{name}: the own-pause grace was on during it, and ended", + len(pause) >= 10 and not tr[-1][1] + and (pause[-1][0] - pause[0][0]) + <= getattr(ctl_car, "OWN_PAUSE_MAX_S", 0) + + getattr(ctl_car, "OWN_PAUSE_TAIL_S", 0)) + check(f"{name}: no PEAK_GUARD_FLOOR_LIMITED / saturated, no " + f"goodwe_peak_soc_floor notification", al == []) + check(f"{name}: no red row in any sample around the switch", + reds(tr) == []) + limited = [x for x in tr if x[1] and x[6]] + check(f"{name}: in every cycle of the sequence in which the guard is " + f"limited (the cycle of the rig's alarm among them) the car " + f"explains it", len(limited) >= 1 and all(x[2] for x in limited) + and any(x[2] for x in tr if x[0] == t_sw + 1)) + check(f"{name}: and in every limited cycle after it, to the quarter's end", + all(x[2] for x in tr if x[0] >= t_sw and x[6])) + +# =========================================================================== # +print("\n2. A HOUSE OVERLOAD DURING THE SEQUENCE STILL ALARMS") +# =========================================================================== # +def overload(plant, c): + plant.load = lambda t: 25000.0 + plant.ch.power_w + + +r, tr, al = run(3000.0, 6050.0, 300, 600, 1, extra={606: overload}) +ro, tro, alo = run(3000.0, 6050.0, 300, 600, 1, extra={606: overload}, + mode="off", plug=False) +rn, trn, aln = run(3000.0, 6050.0, 300, 900, 1, extra={606: overload}) +check("PRECONDITION: on Off (no car) the same load alarms, and in Manual " + "with no phase change", alo != [] and aln != []) +check("a 25 kW house overload that starts 6 s into the sequence (the car " + "paused): the alarm fires", al != []) +print(f" alarm seconds: in the sequence {[t for t, _ in al]}, Off without " + f"the car {[t for t, _ in alo]}, Manual with no phase change " + f"{[t for t, _ in aln]}") +check("...at the same second as on Off and as in Manual with no phase change", + bool(al) and bool(alo) and bool(aln) + and al[0][0] == alo[0][0] == aln[0][0]) +check("...and the car does not explain it (during the sequence too)", + not any(x[2] for x in tr if 640 <= x[0] <= 660)) + +# =========================================================================== # +print("\n3. ABORTED, REFUSED, OUTSIDE: NO GRACE AFTER IT") +# =========================================================================== # +def hit(res, t0, secs): + return [x for x in res if t0 <= x[0] <= t0 + secs and x[1]] + + +def off_now(plant, c): + asyncio.get_event_loop().create_task(c.handle_action("car_mode", + value="off")) + + +def stop_now(plant, c): + c.auto = False + + +def unplug(plant, c): + plant.ch.unplug() + + +slow = lambda s: setattr(s, "stop_delay_s", 8.0) # noqa: E731 +for what, fn in (("Off", off_now), ("Stop", stop_now), ("unplug", unplug)): + r, tr, al = run(3000.0, 6050.0, 300, 600, 1, extra={602: fn}, + sim_fn=slow) + check(f"{what} 2 s into the sequence: the grace is off from the next " + f"cycle on", not hit(tr, 604, 200) + and any(x[1] for x in tr if 600 <= x[0] <= 602)) + +def refuse_phases(sim): + sim.request_phases = lambda n: False + + +r, tr, al = run(3000.0, 6050.0, 300, 600, 1, sim_fn=refuse_phases) +check("the select is refused: the grace ends at once (no cycle of it after " + "the refusal), the current comes back", + len([x for x in r["sim"].writes("current")]) >= 2 + and not hit(tr, 606, 200)) + +def outside_zero(plant, c): + plant.ch.set_current(0.0) + + +r2, tr2, al2 = run(3000.0, 6050.0, 300, 900, 1, extra={602: outside_zero}) +check("an outside writer's 0 A: no grace, and the normal grading (no car " + "power: nothing explained) raises the alarm as before", + not any(x[1] for x in tr2) and not any(x[2] for x in tr2 + if 610 <= x[0] <= 700) + and al2 != []) + +# =========================================================================== # +print("\n4. THE BOUNDS AND THE FIGURE THAT STANDS IN") +# =========================================================================== # +class _C(ctl_car.CarMixin): + """The mixin with just what `_car_own_pause` reads.""" + def __init__(self): + self.o = {} + self.car_init({}, type("S", (), {"data": {}, "set": lambda s, k, v: 0})()) + self.car_mode = carmode.MANUAL + self.auto, self.shadow = True, False + self.inverters, self.site_sign_wd = [], type("W", (), {"tripped": False})() + self.circ_wd = type("W", (), {"tripped": False})() + self.charger = type("H", (), {"configured": lambda s: True})() + self.car = CH.CarTracker() + self.car.reading = CH.ChargerReading(available=True, state="B") + + +c = _C() +c.car_writer.seq = {"stage": "settle", "t0": 100.0, "n": 1, "tries": 0, + "prev": 16.0} +M = ctl_car.OWN_PAUSE_MAX_S +check("bound: the sequence's own maximum is its waits (0 A wait, settle, " + "three tries at 15 s, the select) and no more", + M == carmode.ZERO_WAIT_S + carmode.SETTLE_S + carmode.MAX_TRIES * 15.0 + + 10.0 and ctl_car.OWN_PAUSE_TAIL_S == CH.CORR_WINDOW_S) +check("bound: on at the 0 A write and up to the maximum", + c._car_own_pause(100.0) and c._car_own_pause(100.0 + M)) +check("bound: off one second past it", not c._car_own_pause(101.0 + M)) +c.car_writer.seq = None +c.car_writer.phase_done_at = 200.0 +T = ctl_car.OWN_PAUSE_TAIL_S +check("bound: after the current is set again it lasts one corroboration " + "window", c._car_own_pause(200.0 + T) and not c._car_own_pause(201.0 + T)) +c.car_writer.phase_done_at = None +check("no sequence and none just done: no grace", not c._car_own_pause(100.0)) +c.car_writer.seq = {"stage": "settle", "t0": 100.0, "failed": True} +check("a refused write marks the sequence: no grace", not c._car_own_pause(110.0)) +c.car_writer.seq = {"stage": "settle", "t0": 100.0} +c.car_mode = carmode.OFF +check("Off: no grace", not c._car_own_pause(110.0)) +c.car_mode, c.shadow = carmode.MANUAL, True +check("shadow mode: no grace", not c._car_own_pause(110.0)) +c.shadow, c.auto = False, False +check("control stopped: no grace", not c._car_own_pause(110.0)) +c.auto = True +c.car.reading = CH.ChargerReading(available=True, state="A") +check("unplugged: no grace", not c._car_own_pause(110.0)) +c.car.reading = CH.ChargerReading(available=True, state="B") +check("PRECONDITION: the same state is on", c._car_own_pause(110.0)) + +tk = CH.CarTracker() +tk.reading = CH.ChargerReading(available=True, state="B", power_w=500.0, + allowed_a=16.0, phases_allowed=1) +tk.last_ok = 0.0 +check("the stand-in figure is the fresh reading, capped by the read-back", + tk.car_w_paused(5.0) == 500.0 and tk.car_w_trusted(5.0) is None) +check("a stale reading stands in for nothing", tk.car_w_paused(100.0) is None) +tk.stuck_now = True +check("a stuck reading stands in for nothing", tk.car_w_paused(5.0) is None) + +print() +if fails: + print(f"FAIL: {len(fails)} check(s)") + for f in fails: + print(" -", f) + sys.exit(1) +print("ok: EV-15") -- 2.54.0 From 07f703d1bc4956dceec9185a57e8106ebcfdc7c8 Mon Sep 17 00:00:00 2001 From: glenn schrooyen Date: Tue, 17 Nov 2026 13:39:11 +0100 Subject: [PATCH 2/4] EV-15: test_ev15 guards its own indexing (named absence) Co-Authored-By: Claude --- goodwe_controller/test_ev15.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/goodwe_controller/test_ev15.py b/goodwe_controller/test_ev15.py index 6713371..1b9ac32 100644 --- a/goodwe_controller/test_ev15.py +++ b/goodwe_controller/test_ev15.py @@ -107,7 +107,7 @@ for name, house, cap, t_res, t_sw, new in SHAPES: == [0.0, 16.0] and sim.phases_allowed == new) pause = [x for x in tr if x[1]] check(f"{name}: the own-pause grace was on during it, and ended", - len(pause) >= 10 and not tr[-1][1] + len(pause) >= 10 and not any(x[1] for x in tr[-1:]) and (pause[-1][0] - pause[0][0]) <= getattr(ctl_car, "OWN_PAUSE_MAX_S", 0) + getattr(ctl_car, "OWN_PAUSE_TAIL_S", 0)) -- 2.54.0 From 6d7046fc4590938186193a1193d9e0b322ce38ea Mon Sep 17 00:00:00 2001 From: glenn schrooyen Date: Tue, 17 Nov 2026 15:24:30 +0100 Subject: [PATCH 3/4] EV-15 round 2: the grace opens when the 0 A write is sent The writer runs beside the cycle and the car can stop before the write returns, so no sequence existed yet and the latch set. Window now opens at send (zero_sent_at), cleared on return; ends on another writer in the tail too. Co-Authored-By: Claude --- .../DECISIONS/EV-04-manual-mode.md | 4 +- goodwe_controller/app/carmode.py | 11 ++- goodwe_controller/app/ctl_car.py | 11 ++- goodwe_controller/test_ev15.py | 83 ++++++++++++++++++- 4 files changed, 100 insertions(+), 9 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index 1d85320..bfa3e39 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -128,7 +128,9 @@ up to 1.8 kW; the 40 Wh floor fixes that.) PEAK_GUARD_FLOOR_LIMITED and one `goodwe_peak_soc_floor`. Now, only for grading (`car_cycle`), `ctl_car._car_own_pause` lets the car's fresh, not stuck figure (`CarTracker.car_w_paused`, 0 W while paused) stand in without corroboration: - from our 0 A write (`seq` exists) until the current is set again, at most + from the moment our 0 A write is SENT (`zero_sent_at`: the cycle runs beside + the writer and the car stops before the write returns), until the current is + set again, at most `OWN_PAUSE_MAX_S` (85 s, the sequence's own waits), then at most one corroboration window (60 s). It ends at once on Off, Stop, shadow, unplug, another writer, or a refused select or write (`seq["failed"]`). The energy it diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 38e19e4..39bf326 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -126,6 +126,7 @@ class ManualWriter: self.phases_gave_up = False self.undone = 0 # sequences undone before the select self.phase_done_at = None # EV-15: our phase change ended well then + self.zero_sent_at = None # EV-15: our 0 A write is out, not yet back # ------------------------------------------------------------------ user def user_changed(self) -> None: @@ -293,11 +294,17 @@ class ManualWriter: 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.""" - ok = await self._write(drv, 0.0, cur, now, tracker) + self.phase_done_at = None + # EV-15: the car stops while the write waits for its read-back, and the + # cycle runs beside it: the window opens when the write is SENT. + self.zero_sent_at = now + try: + ok = await self._write(drv, 0.0, cur, now, tracker) + finally: + self.zero_sent_at = None if not ok: self._failed(now) return - self.phase_done_at = None self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, "prev": cur} diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 8e11071..4114b8b 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -214,19 +214,22 @@ class CarMixin: return self.car.car_w_trusted(self.car_now()) def _car_own_pause(self, mono) -> bool: - """EV-15: is the car held at 0 A by the add-on's OWN phase change (its - 0 A write until the current is set again, then at most one - corroboration window)? No when it was aborted (Off, Stop, shadow, + """EV-15: is the car held at 0 A by the add-on's OWN phase change (from + the moment its 0 A write is SENT, the cycle runs beside the write, + until the current is set again, then at most one corroboration window)? No when it was aborted (Off, Stop, shadow, unplug, another writer), a write was refused, or it ran past its own maximum.""" wr = getattr(self, "car_writer", None) - if wr is None or (wr.seq is None and wr.phase_done_at is None): + if wr is None or (wr.seq is None and wr.phase_done_at is None + and wr.zero_sent_at is None) or wr.hold: return False r = self.car.reading if not (self.car_manual() and self.car_writing() and r is not None and r.available and r.state != "A"): return False q = wr.seq + if q is None and wr.zero_sent_at is not None: # sent, not yet back + return 0.0 <= mono - wr.zero_sent_at <= OWN_PAUSE_MAX_S if q is not None: return not q.get("failed") and 0.0 <= mono - q["t0"] \ <= OWN_PAUSE_MAX_S diff --git a/goodwe_controller/test_ev15.py b/goodwe_controller/test_ev15.py index 1b9ac32..d875e98 100644 --- a/goodwe_controller/test_ev15.py +++ b/goodwe_controller/test_ev15.py @@ -42,8 +42,26 @@ def at(t, fn): return {"t": t, "fn": fn} +def beside(plant, c): + """The writer runs BESIDE the cycle, as in production (`car_kick`): its 1 s + poll for the read-back lands after the cycle's own read, and the cycle does + not wait for the writer (`ev04_peak.drive` does).""" + gate = asyncio.Event() + + async def sleep(_s): + gate.clear() + await gate.wait() + + async def settle(): + gate.set() + for _ in range(5): + await asyncio.sleep(0) + c.charger._sleep = sleep + c.car_settle = settle + + def run(house, cap, t_res, t_sw, new, *, extra=None, mode="manual", - sim_fn=None, dur=895, plug=True): + sim_fn=None, dur=895, plug=True, side=False): """Reserve at `t_res`, our phase change to `new` at `t_sw`. Returns the run, a per-second trace (second, own-pause, explains, red rows) and the alarms.""" @@ -69,13 +87,16 @@ def run(house, cap, t_res, t_sw, new, *, extra=None, mode="manual", ev = {t: note for t in range(0, dur)} ev[t_res] = lambda p, c: (reserve(p, c), note(p, c)) ev[t_sw] = lambda p, c: (switch(p, c), note(p, c)) + if side: + ev[t_sw - 2] = lambda p, c: (beside(p, c), note(p, c)) for t, fn in (extra or {}).items(): prev = ev.get(t, note) ev[t] = (lambda p, c, prev=prev, fn=fn: (fn(p, c), prev(p, c))) sim = None - if sim_fn is not None: + if sim_fn is not None or side: from chargersim import SimCharger sim = SimCharger(setpoint_a=16) + sim_fn = sim_fn or (lambda s: None) sim_fn(sim) r = P.drive(s81.constant(house), dur=dur, rating=12000.0, soc=60.0, cap=cap, phases=(3 if new == 1 else 1), user_a=16, setpoint=16, @@ -241,6 +262,20 @@ check("shadow mode: no grace", not c._car_own_pause(110.0)) c.shadow, c.auto = False, False check("control stopped: no grace", not c._car_own_pause(110.0)) c.auto = True +c.car_writer.hold = True +check("another writer (hold): no grace", not c._car_own_pause(110.0)) +c.car_writer.hold = False +c.car_writer.seq, c.car_writer.zero_sent_at = None, 100.0 +check("0 A sent, not yet back: grace from the send, to the maximum, no more", + c._car_own_pause(100.0) and c._car_own_pause(100.0 + M) + and not c._car_own_pause(101.0 + M)) +c.car_writer.zero_sent_at = None +c.car_writer.phase_done_at = 200.0 +c.car_writer.hold = True +check("another writer in the 60 s after the current is set: no grace", + not c._car_own_pause(210.0)) +c.car_writer.hold, c.car_writer.phase_done_at = False, None +c.car_writer.seq = {"stage": "settle", "t0": 100.0} c.car.reading = CH.ChargerReading(available=True, state="A") check("unplugged: no grace", not c._car_own_pause(110.0)) c.car.reading = CH.ChargerReading(available=True, state="B") @@ -256,6 +291,50 @@ check("a stale reading stands in for nothing", tk.car_w_paused(100.0) is None) tk.stuck_now = True check("a stuck reading stands in for nothing", tk.car_w_paused(5.0) is None) +# =========================================================================== # +print("\n5. THE WRITER RUNS BESIDE THE CYCLE (review F-1)") +# =========================================================================== # +# The car stops (state B) in the same Home Assistant update as the 0 A +# read-back; the write has not returned yet, so no sequence exists. The window +# opens when the write is SENT (`ManualWriter.zero_sent_at`). +def lagged(lag, delay): + def f(s): + s.lag_s, s.stop_delay_s = lag, delay + return f + + +for lag, delay in ((2, 0), (0, 0), (2, 3), (5, 2)): + r, tr, al = run(3000.0, 6050.0, 300, 600, 1, side=True, + sim_fn=lagged(lag, delay)) + nm = f"beside the cycle, lag {lag} s, stop delay {delay} s" + limited = [x for x in tr if x[0] >= 600 and x[6]] + check(f"{nm}: our sequence ran (select once, then 16 A again)", + len([x for x in r["sim"].writes("phases")]) == 1 + and r["sim"].phases_allowed == 1 + and [x[2] for x in r["sim"].writes("current")][-2:] == [0.0, 16.0]) + check(f"{nm}: no PEAK_GUARD_FLOOR_LIMITED, no goodwe_peak_soc_floor", + al == []) + check(f"{nm}: no red row, and the car explains every limited cycle", + reds(tr) == [] and all(x[2] for x in limited)) + + +def not_taken(plant, c): + plant.ch.refuse = "ignore" # HA accepts, the charger does nothing + + +r, tr, al = run(3000.0, 6050.0, 300, 600, 1, side=True, + sim_fn=lagged(0, 0), extra={600: not_taken}) +check("the 0 A write is not taken (read-back never follows): the window was " + "open while it waited", any(x[1] for x in tr if 600 <= x[0] <= 606)) +own = [x[0] for x in tr if x[1]] +runs = 1 + len([1 for a, b in zip(own, own[1:]) if b - a > 1]) +check("...and no grace after the refusal (the retry, RETRY_S later, opens it " + "again only while that write waits: at most 3 runs of 11 s), no " + "sequence made", not hit(tr, 613, 40) and r["c"].car_writer.seq is None + and 1 <= runs <= 3 and len(own) <= 3 * 11) +check("...the car went on charging and nothing was written but the 0 A", + r["sim"].power_w > 5000.0 and not r["sim"].writes("phases")) + print() if fails: print(f"FAIL: {len(fails)} check(s)") -- 2.54.0 From 7788543e09dc360d04a86f532f21e413d20cd4b1 Mon Sep 17 00:00:00 2001 From: glenn schrooyen Date: Tue, 17 Nov 2026 16:51:41 +0100 Subject: [PATCH 4/4] EV-15 review: reflow the _car_own_pause docstring (one 123-char line) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Bdqr7PiaHcBnzPituu2yTC --- goodwe_controller/app/ctl_car.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 4114b8b..41615da 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -214,11 +214,11 @@ class CarMixin: return self.car.car_w_trusted(self.car_now()) def _car_own_pause(self, mono) -> bool: - """EV-15: is the car held at 0 A by the add-on's OWN phase change (from - the moment its 0 A write is SENT, the cycle runs beside the write, - until the current is set again, then at most one corroboration window)? No when it was aborted (Off, Stop, shadow, - unplug, another writer), a write was refused, or it ran past its own - maximum.""" + """EV-15: is the car held at 0 A by the add-on's OWN phase change? From + the moment its 0 A write is SENT (the cycle runs beside the write) + until the current is set again, then at most one corroboration window. + No when it was aborted (Off, Stop, shadow, unplug, another writer), a + write was refused, or it ran past its own maximum.""" wr = getattr(self, "car_writer", None) if wr is None or (wr.seq is None and wr.phase_done_at is None and wr.zero_sent_at is None) or wr.hold: -- 2.54.0