From 2cfbc4aec87ab443504313e7d03d323267224a52 Mon Sep 17 00:00:00 2001 From: glenn schrooyen Date: Tue, 17 Nov 2026 13:26:56 +0100 Subject: [PATCH 01/55] 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 02/55] 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 03/55] 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 04/55] 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 From 12c97b56f44553ee69ef5c4ab3bd221bc96d4dcc Mon Sep 17 00:00:00 2001 From: ems-agent Date: Thu, 19 Nov 2026 02:59:50 +0100 Subject: [PATCH 05/55] EV-18: no floor alarm at a quarter's start while the car explains the excess EV-15 rig F-A: with both batteries at the peak reserve and the car charging, PEAK_GUARD_FLOOR_LIMITED and goodwe_peak_soc_floor fired at a quarter's start and stayed red for the quarter, the excess smaller than the car. Two causes, both held by the per-quarter latch `_car_need_excl`: - C2: "without the car" assumed the batteries give 0 W from now on, so what the loop still gives below the reserve counted as house (T2 red on base); - C1: one cycle with no trusted car figure latched it for the quarter (T1). Owner 2026-11-19 (Q1-Q3): without the car the batteries keep giving what they give now (lower of two readings, every cycle); a house need seen with a trusted car figure stays latched to the quarter's end (`_car_need_house`); an unknown car figure keeps the alarm only while it is unknown. A car known to draw nothing (fresh reading, not charging) still grades the house's own need. After a restart or a gap only the rest of the quarter is graded without the car. A 0 W figure explains nothing outside our own pause (EV-15). The guard's claim, floor, setpoints and charger writes are unchanged (N4: 41 runs, same command digests as base). test_ev18.py: the test plan's T1-T18, T2b, T2c, N2-N5 (tools/ev18_peak.py: the real Controller across one quarter edge, N=2 at the reserve). Co-Authored-By: Claude --- .../DECISIONS/EV-04-manual-mode.md | 20 +- goodwe_controller/app/ctl_car.py | 94 ++- goodwe_controller/test_ev18.py | 681 ++++++++++++++++++ goodwe_controller/tools/ev18_peak.py | 207 ++++++ 4 files changed, 975 insertions(+), 27 deletions(-) create mode 100644 goodwe_controller/test_ev18.py create mode 100644 goodwe_controller/tools/ev18_peak.py diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index bfa3e39..e49e675 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -97,10 +97,10 @@ up to 1.8 kW; the 40 Wh floor fixes that.) that latch twice, with and without the car, from the same readings. Both reset at a new quarter and when the guard stops wanting power, and they run every cycle, so the cover option does not touch them. This holds with the projection - still under the aim (rig: 5888 W against 6000 W). A car of 0 W makes the two the - same, so it explains nothing; a stale, stuck or uncorroborated figure is `None`, - sets the latch without the car, and the normal alarms stand. There is no minimum - car power: the comparison itself is what separates car from house. + still under the aim (rig: 5888 W against 6000 W). A car of 0 W explains + nothing; a stale, stuck or uncorroborated figure is `None` and the normal + alarms stand while it is (EV-18 below). There is no minimum car power: the + comparison itself is what separates car from house. - **The period without the car is not clipped at 0 W** (EV-10b). The rig showed EV-10 failing: house 3 kW, car 11 kW, batteries 8.1 kW, aim 6 kW. The batteries give more than the house uses, so the house alone is an export; `car_exclude` @@ -137,6 +137,18 @@ up to 1.8 kW; the 40 Wh floor fixes that.) 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. +- **The batteries as they give now, and no latch from an unknown** (EV-18, EV-15 + rig F-A). At the reserve the loop still gives some battery power; "without the + car, batteries at 0 W" counted it as house, `_car_need_excl` latched at the + quarter's start and the floor alarm stood for the quarter with the excess + smaller than the car. Owner 2026-11-19: without the car the batteries keep + giving what they give now (the lower of two readings, every cycle); a miss so + (`_car_need_house`) seen with a trusted car figure stays latched to the + quarter's end. The car explains where the period with it misses on the same + batteries (`_car_over_now`), or by the EV-10 test above. A `None` car figure + or battery reading explains nothing in that cycle and latches nothing. After + a restart or a gap the car's share of what is done is unknown (`_carq` + `whole`), so only the rest of the period is graded without the car. - **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/ctl_car.py b/goodwe_controller/app/ctl_car.py index 41615da..726173a 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -60,6 +60,7 @@ class CarMixin: self._car_over_gone = None self._car_batt_prev = None self._car_need_real = self._car_need_excl = False # EV-10 latches + self._car_need_house = self._car_over_now = False # EV-18 latches self._car_latch_block = None self._car_over_notified = None # the session a notice was raised for self._car_session = 0 @@ -235,6 +236,16 @@ class CarMixin: <= OWN_PAUSE_MAX_S return 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S + def _car_idle(self, mono) -> bool: + """EV-18: is the car known to draw nothing? A fresh reading that says + it is not charging (mode3 A or B) at under `CAR_PEAK_MIN_W`. Not an + unknown figure: the house's own need is graded in such a cycle.""" + r = getattr(self.car, "reading", None) + if r is None or not r.available or r.charging is not False: + return False + p = self.car.car_w(mono) + return p is not None and p < CAR_PEAK_MIN_W + 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. `wg` (EV-15) is the figure for @@ -244,8 +255,16 @@ class CarMixin: key = None if proj is None else proj.block_start last = q["mono"] if key != q["key"]: + # EV-18: `whole` when the count covers the block: it follows on + # from the block before, or starts in its first seconds (not + # after a restart or a gap). + whole = key is not None and ( + float(proj.elapsed_s) <= 5.0 or ( + last is not None and q["key"] is not None + and (key - q["key"]).total_seconds() == QUARTER_S)) self._car_bank(q) q["key"], q["ws"], q["ws_p"] = key, 0.0, 0.0 + q["whole"] = whole if key is not None and last is not None: dt = min(max(mono - last, 0.0), 5.0) if w is not None: @@ -322,7 +341,8 @@ class CarMixin: # 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): + own = (w is None or float(w) <= 0.0) and self._car_own_pause(mono) + if w is None and own: wg = self.car.car_w_paused(mono) self._car_quarter(real_proj, w, mono, wg) self._car_session_tick(mono) @@ -330,7 +350,14 @@ class CarMixin: 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, wg) + # EV-18: a car known to draw nothing counts as 0 W for the latches + # (the house's own need); it and a 0 W figure explain nothing, + # but in our own pause (EV-15). + idle = wg is None and self._car_idle(mono) + graded = self._car_explains_alarm(real_proj, guard, target_w, + 0.0 if idle else wg) + if idle or (w is not None and float(w) <= 0.0 and not own): + graded = False if self.car_cover: explains = over = graded elif w is not None: @@ -360,35 +387,41 @@ class CarMixin: batteries left are graded by `load_too_high` on where the period lands (SAFETY-81 / 87); a floor that leaves nothing is graded by SAFETY-126's `misses_aim` (the batteries at 0 W from now on), latched for the - quarter. That latch is kept here twice, on the period as it is - (`_car_need_real`) and without the car (`_car_need_excl`), from the - same `misses_aim` and the same batteries reading. Both reset at a new - quarter and when the guard no longer wants power, whatever the cover - option says (this runs every cycle). A car that is 0 W, or untrusted - (`w` None sets the second latch), makes the two equal and explains - nothing.""" - batt, prev = self.site_batt_w, self._car_batt_prev - self._car_batt_prev = batt + quarter (`_car_need_real`, and `_car_need_excl` without the car). + EV-18 (owner 2026-11-19): without the car, the batteries keep giving + what they give now (the lower of two readings), re-checked every cycle; + a miss seen so (`_car_need_house`) never lets the car explain for the + rest of the quarter. The car also explains where the period with it, + on the same batteries, misses (`_car_over_now`). Only a trusted figure + latches: an untrusted car (`w` None) or an unknown battery reading + explains nothing in that cycle only. All reset at a new quarter and + when the guard no longer wants power, whatever the cover option says + (this runs every cycle). DECISIONS/EV-04-manual-mode.md (EV-18).""" + now, prev = self.site_batt_w, self._car_batt_prev + self._car_batt_prev = now wants = bool(guard is not None and guard.engaged and guard.blind is None and (guard.wanted_w or 0.0) > 0.0) - if real_proj.block_start != self._car_latch_block: + if real_proj.block_start != self._car_latch_block or not wants: self._car_latch_block = real_proj.block_start self._car_need_real = self._car_need_excl = False - if not wants: - self._car_need_real = self._car_need_excl = False + self._car_need_house = self._car_over_now = False + batt = now if batt is not None and prev is not None: batt = min(float(batt), float(prev)) excl = self.car_exclude_alarm(real_proj, w) - if wants: - if batt is None: - self._car_need_real = self._car_need_excl = True - else: - self._car_need_real = self._car_need_real or \ - peakguard.misses_aim(real_proj, batt_w=batt, - target_w=target_w) - self._car_need_excl = self._car_need_excl or w is None or \ + if wants and batt is not None: + self._car_need_real = self._car_need_real or \ + peakguard.misses_aim(real_proj, batt_w=batt, + target_w=target_w) + self._car_over_now = self._car_over_now or \ + self._car_lands_over(real_proj, now, batt, target_w) + if w is not None: + whole = self._carq.get("whole", True) + self._car_need_excl = self._car_need_excl or \ peakguard.misses_aim(excl, batt_w=batt, target_w=target_w) + self._car_need_house = self._car_need_house or \ + self._car_lands_over(excl, now, batt, target_w, whole) if w is None or batt is None or not wants \ or not (guard.saturated or guard.floor_limited): return False @@ -398,7 +431,8 @@ class CarMixin: rating = guard.able_w else: return bool(not guard.within_aim and self._car_need_real - and not self._car_need_excl) + and not self._car_need_house + and (self._car_over_now or not self._car_need_excl)) def high(p): return peakguard.load_too_high( @@ -406,6 +440,20 @@ class CarMixin: achievable_w=rating) return bool(high(real_proj) and not high(excl)) + @staticmethod + def _car_lands_over(p, now, gives, target_w, whole=True) -> bool: + """EV-18: does the period end more than `ALARM_MISS_W` over the aim + with the batteries giving `gives` W from now on (`now`: what they gave + in the meter's figure)? Not `whole`: the car's share of what is done + is not known (a restart, a gap), so only the rest is graded.""" + if whole: + return peakguard.load_too_high(p, batt_w=now, ceiling_w=target_w, + achievable_w=gives) + if QUARTER_S - float(p.elapsed_s) <= 0.0: + return False + rest = float(p.held_w) + float(now) - float(gives) + return rest - float(target_w) > peakguard.ALARM_MISS_W + def _car_session_tick(self, mono) -> None: """A charging session is a plug-in: the state goes from no car to a car. The notice is raised once per session.""" diff --git a/goodwe_controller/test_ev18.py b/goodwe_controller/test_ev18.py new file mode 100644 index 0000000..01c3853 --- /dev/null +++ b/goodwe_controller/test_ev18.py @@ -0,0 +1,681 @@ +"""EV-18: no floor alarm at a quarter's start while the car explains the excess +(EV-15 rig F-A). `python3 -B test_ev18.py` + +The rig: both batteries at the peak reserve, the car charging, and +PEAK_GUARD_FLOOR_LIMITED + `goodwe_peak_soc_floor` at a quarter's start, red +for most of the quarter, while the grid excess was smaller than the car. Two +causes, both latched for the quarter by `_car_need_excl`: + C1 one cycle with no trusted car figure set the latch (T1); + C2 "without the car" assumed the batteries give 0 W from now on, so what + the loop still gives below the reserve counted as house (T2). +The rule now (owner 2026-11-19, Q1-Q3): without the car the batteries keep +giving what they give now (the lower of the last two readings, re-checked +every cycle); a house need seen with a trusted car figure stays latched to the +quarter's end; an unknown car figure keeps the alarm only while it is unknown. + +T-ids are the test plan's (reports/EV-18-test-plan.md). "base" is 9fdce02. +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import os +import sys +from datetime import datetime, timedelta, timezone + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import chargers as CH, ctl_car, tariff # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from named_absence import first, nth, present # noqa: E402 +import ev04_peak as P # noqa: E402 +import ev18_peak as H # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +AIM = H.AIM +CAR = 1380.0 +E = H.E +# Measured on base 9fdce02 with this file's own runs: the seconds of +# goodwe_peak_soc_floor in the honest shapes, which must not come later now. An +# honest shape steps the house at E, and the meter shows it at E+1. +T5_BASE = [E + 1] # also T6 (T5 shape), T8, T9(a), T10(b) T5 +T7_BASE = E + 72 +T9B_BASE = [] # 400 W real: never uncorroborated (Findings) +T9C_BASE = E + 1 # 100 W real: never trusted at the edge +T10A_T5_BASE = [E + 2] # the guard disengages at E+1 (no battery reading) +T11_BASE = [E + 13] # SAFETY-87: ALARM_HOLD_S after the step +T13_BASE = [E + 301] +T15_T5_BASE = [E + 10] # x10: one cycle + +# =========================================================================== # +print("1. UNIT: car_cycle ACROSS A QUARTER EDGE (a real `_carq`, not preset)") +# =========================================================================== # +BS = datetime(2026, 11, 17, 21, 15, tzinfo=timezone.utc) # the edge E + + +class _Car(ctl_car.CarMixin): + def __init__(self): + self.o = {"ev_batt_cover": True} + self.w = CAR + self._now = 0.0 + self.site_batt_w, self.site_rating_w = 0.0, 9600.0 + self.store = type("S", (), {"data": {}, "set": lambda s, k, v: 0})() + self.car_init({}, self.store) + + def car_now(self): + return self._now + + def car_alarm_w(self): + return self.w + + class car: # noqa: N801 + @staticmethod + def status(*_a): + return "charging" + + +class _G: + """Floor-limited, the floor leaves nothing (floor_w 0), wants power.""" + def __init__(self, wants=True, within_aim=False): + self.floor_limited, self.saturated = True, False + self.floor_w, self.able_w, self.ceiling_w = 0.0, None, AIM + 50.0 + self.engaged, self.blind = True, None + self.wanted_w = 300.0 if wants else 0.0 + self.within_aim = within_aim + + +def urun(secs, grid, batt, w, *, x=1, mono_x=None, c=None, guard=None): + """`car_cycle` once per entry of `secs` (seconds from the edge E, `x` fake + seconds apart). `grid(t)` is the meter (house + car - batteries), + `batt(t)` the site battery reading, `w(t)` the trusted car figure. Returns + (car, {t: car_explains}).""" + c = c or _Car() + mono_x = x if mono_x is None else mono_x + done, out = {}, {} + for t in secs: + q = t // 900 + bs, el = BS + timedelta(seconds=900 * q), t - 900 * q + g = float(grid(t)) + d = done.get(bs, g * el) + p = tariff.Projection( + projected_w=(d + g * (900 - el)) / 900.0, + elapsed_w=(d / el if el else g), elapsed_s=float(el), + covered_frac=1.0, complete=False, block_start=bs, held_w=g) + done[bs] = d + g * x + c._now = 10000.0 + t * mono_x / x + c.w, c.site_batt_w = w(t), batt(t) + c.car_cycle(p, guard(t) if guard else _G(), AIM, None) + out[t] = c.car_explains + return c, out + + +def const(v): + return lambda t: v + + +def run_of(d, t0, t1): + return [d[t] for t in sorted(d) if t0 <= t <= t1] + + +# --- T1: the car figure untrusted for the edge's first cycles --------------- # +def t1(x=1, mono_x=None): + _c, ex = urun(range(-30, 121, x), const(13000.0 + CAR), const(0.0), + lambda t: None if 0 <= t <= 2 * x else CAR, x=x, + mono_x=mono_x) + return ex + + +ex = t1() +print(f" T1 explains E-1..E+5: {run_of(ex, -1, 5)}") +check("T1 PRECONDITION: before the edge the car (trusted) explains the " + "excess (house 13 000 W, car 1 380 W, grid 14 380 W)", + all(run_of(ex, -30, -1)) and len(run_of(ex, -30, -1)) == 30) +check("T1 (Expected 5): while the car figure is unknown (E+0..E+2) it " + "explains nothing, so the alarm stands", not any(run_of(ex, 0, 2))) +_c1b, ex1b = urun(range(-30, 121), const(12500.0 + CAR - 800.0), const(800.0), + lambda t: None if 0 <= t <= 2 else CAR) +check("T1b (the EV-10 path: the grid lands under the aim, the batteries at " + "0 W would miss; house 12 500 W, b 800 W): unknown E+0..E+2, released " + "at E+3 and explained to E+120", + not any(run_of(ex1b, 0, 2)) and all(run_of(ex1b, 3, 120)) + and len(run_of(ex1b, 3, 120)) == 118) +check("T1 (Expected 3): released at the first trusted cycle (E+3) and " + "explained to E+120 (base: latched False to E+120)", + all(run_of(ex, 3, 120)) and len(run_of(ex, 3, 120)) == 118) + +# --- T2c: the battery W boundary, graded on the lower of two readings ------- # +def t2c(b_of): + _c, ex = urun(range(0, 6), lambda t: 14000.0 + CAR - b_of(t), b_of, + const(CAR)) + return run_of(ex, 0, 5) + + +e391, e389 = t2c(const(391.0)), t2c(const(389.0)) +e395 = t2c(lambda t: 395.0 if t == 0 else 385.0) +print(f" T2c 391 W {e391}, 389 W {e389}, 395 then 385 W {e395}") +check("T2c: b steady at 391 W (house alone with the real batteries lands " + "13 609 W, aim + 9 W): the car explains from E+0", all(e391) + and len(e391) == 6) +check("T2c: b at 389 W (13 611 W, aim + 11 W): it does not, from E+0", + not any(e389) and len(e389) == 6) +check("T2c: readings 395 then 385 W: graded on 385 W, no explanation from " + "the second cycle on", not any(e395[1:]) and len(e395) == 6) + +# --- T4: ALARM_MISS_W, batteries at 0 W -------------------------------------- # +e09 = run_of(urun(range(0, 6), const(13609.0 + CAR), const(0.0), + const(CAR))[1], 0, 5) +e11 = run_of(urun(range(0, 6), const(13611.0 + CAR), const(0.0), + const(CAR))[1], 0, 5) +check("T4 unit: the house alone at aim + 9 W: the car explains from E+0; at " + "aim + 11 W it does not", all(e09) and len(e09) == 6 and not any(e11)) + +# --- T8 / N2: 0 W and tiny cars ---------------------------------------------- # +e0 = run_of(urun(range(-5, 30), const(14000.0 - 800.0), const(800.0), + const(0.0))[1], -5, 29) +e50 = run_of(urun(range(-5, 30), const(14090.0 + 50.0), const(0.0), + const(50.0))[1], -5, 29) +check("T8 unit: a 0 W car never explains, whatever the batteries give (T2 " + "shape, b 800 W)", not any(e0) and len(e0) == 35) +check("T8 unit: a 50 W car with the house at 14 090 W never explains", + not any(e50) and len(e50) == 35) +# N2: a car that drew 11 kW earlier in the quarter and now reports 0 W +c0, ex0 = urun(range(0, 400), lambda t: 2600.0 + (11040.0 if t < 300 else 0.0), + const(0.0), lambda t: 11040.0 if t < 300 else 0.0) +check("N2: a trusted 0 W figure explains nothing, also after the car drew " + "earlier in the quarter", not any(run_of(ex0, 300, 399))) + +# --- T8 unit: a car known to draw nothing is not an unknown car ------------- # +class _Tracker: + """The two things `_car_idle` reads: the reading, and its fresh power.""" + def __init__(self, available): + self.reading = CH.ChargerReading(available=available, state="B", + charging=False, power_w=0.0) + + def car_w(self, _now): + return 0.0 if self.reading.available else None + + @staticmethod + def status(*_a): + return "charging" + + +def idle_then_charging(available): + c = _Car() + c.car = _Tracker(available) + _c, ex = urun(range(0, 900), + lambda t: 14090.0 if t < 60 else 13000.0 + CAR, const(0.0), + lambda t: None if t < 60 else CAR, c=c) + return ex + + +exi, exu = idle_then_charging(True), idle_then_charging(False) +check("T8 unit: a car known idle (mode3 B, 0 W, fresh) while the house alone " + "misses (14 090 W): that house need is latched, so the car charging " + "from E+60 does not explain the quarter (test_ev10's `swapped` case)", + not any(run_of(exi, 0, 899))) +check("T8 unit: the same with the charger unavailable (unknown car): the " + "alarm stands while unknown and is released at E+60 (Expected 5)", + not any(run_of(exu, 0, 59)) and all(run_of(exu, 60, 899))) + +# --- T10(a) unit: the battery reading lost for one cycle --------------------- # +cA, eA = urun(range(-3, 10), const(14000.0 + CAR - 800.0), + lambda t: None if t == 1 else 800.0, const(CAR)) +check("T10(a) unit, T2 shape: the cycle with no battery reading explains " + "nothing (no last-known W credited); the next ones do", + eA.get(1) is False and eA.get(0) is True and all(run_of(eA, 2, 9)) + and len(run_of(eA, 2, 9)) == 8) + +# --- T13 unit: a house need seen with a trusted car stays latched ----------- # +c13, e13 = urun(range(-5, 1000), + lambda t: (15500.0 if 300 <= t < 360 else 13000.0) + CAR, + const(0.0), const(CAR)) +check("T13 unit: the house steps to 15 500 W at E+300 for 60 s (landing " + "without the car 14 667 W): not explained from E+300 to the quarter's " + "end, though the house is back at 13 000 W from E+360", + all(run_of(e13, 0, 299)) and not any(run_of(e13, 300, 899)) + and len(run_of(e13, 300, 899)) == 600) +check("T13 unit: ...and released by the new quarter", all(run_of(e13, 900, 999))) +c13g, e13g = urun(range(0, 400), + lambda t: (15500.0 if 100 <= t < 160 else 13000.0) + CAR, + const(0.0), const(CAR), + guard=lambda t: _G(wants=not (t == 250))) +check("T13 unit: ...or by the guard no longer wanting power (EV-10)", + not any(run_of(e13g, 100, 249)) and all(run_of(e13g, 251, 399))) + +# --- T14: no flicker --------------------------------------------------------- # +def floor_edges(ex): + """Per quarter, False -> True edges of the floor alarm the stub implies + (floor-limited, within_aim False, not explained).""" + out, was = {}, False + for t in sorted(ex): + al = not ex[t] + if al and not was: + out[t // 900] = out.get(t // 900, 0) + 1 + was = al + return out + + +_ca, eta = urun(range(0, 1200), + lambda t: 13610.0 + (40.0 if int(t // 7) % 2 else -40.0) + CAR, + const(0.0), const(CAR)) +_cb, etb = urun(range(0, 1200), + lambda t: 14000.0 + CAR - (400.0 if int(t // 7) % 2 else 800.0), + lambda t: 400.0 if int(t // 7) % 2 else 800.0, const(CAR)) +fa, fb = floor_edges(eta), floor_edges(etb) +print(f" T14 alarm edges per quarter: (a) {fa} (b) {fb}") +check("T14(a): the house alone straddles aim + 10 W by 40 W every 7 s: at " + "most one alarm edge per quarter", all(v <= 1 for v in fa.values())) +check("T14(b): T2 shape with b alternating 400 / 800 W every 7 s: no alarm " + "edge at all (base: one per quarter)", fb == {}) + +# --- T15 unit: x10 ------------------------------------------------------------ # +ex10 = t1(x=10) +check("T15 unit x10 (wall and mono 10 s a cycle): T1 the same; released " + "within 1 cycle (E+30, the first trusted cycle)", + not any(run_of(ex10, 0, 20)) and all(run_of(ex10, 30, 120)) + and all(run_of(ex10, -30, -10))) +ex10m = t1(x=10, mono_x=1) +check("T15 unit, mono x1 and wall x10: the same verdicts (the edge comes from " + "the projection's block_start, not from mono)", + not any(run_of(ex10m, 0, 20)) and all(run_of(ex10m, 30, 120))) + +# =========================================================================== # +print("\n2. THE REAL CONTROLLER ACROSS THE EDGE (N=2, both at the reserve)") +# =========================================================================== # + + +RUNS = [] # (name, alarm edges) of every run, for N5 + + +def summary(name, r, tr): + RUNS.append((name, H.edges(tr))) + w = H.window(tr, E - 120, E + 900) + lim = [x for x in w if x["lim"]] + print(f" {name}: alarms {[t - E for t in H.alarms(r)]} edges " + f"{[t - E for t in H.edges(tr)]} red {len(H.red_secs(tr))} s " + f"(first {[t - E for t in H.red_secs(tr)[:1]]}) errors " + f"{len(H.errors(tr))} limited {len(lim)} explained " + f"{sum(1 for x in lim if x['explains'])} cmd {H.commands(r, tr)}") + return w, lim + + +def quiet(r, tr): + """No floor notification, no ERROR, no red peak_guard row, E-120..E+900.""" + return H.alarms(r) == [] and H.red_secs(tr) == [] and H.errors(tr) == [] + + +def all_explained(lim, t0=E - 120): + return bool(lim) and all(x["explains"] for x in lim if x["t"] >= t0) + + +ZERO = const(0.0) + + +def honest(w): + """An honest shape steps at the edge, so Off has no alarm before it.""" + return H.shape(w, at=E) + +# --- T2: the rig F-A shape ---------------------------------------------------- # +r2, tr2 = H.run(H.shape(14000.0), a=ZERO, b=const(800.0)) +w2, lim2 = summary("T2", r2, tr2) +check("T2 PRECONDITION: limited at the reserve from the edge, the car trusted, " + "b 800 W, grid excess 980 W < car", + present(first(x for x in w2 if x["t"] == E and x["lim"])) + and all(x["w"] == CAR and x["batt"] == 800.0 for x in lim2)) +check("T2: no goodwe_peak_soc_floor, no PEAK_GUARD_FLOOR_LIMITED ERROR, no " + "red peak_guard row in E-120..E+900 (base: alarm at E+0, red to E+900)", + quiet(r2, tr2)) +check("T2: the car explains every floor-limited cycle, E+0..E+10 among them", + all_explained(lim2) and len([x for x in lim2 if x["t"] <= E + 10]) == 11) + +# --- T2b: the batteries give less later --------------------------------------- # +r2i, tr2i = H.run(H.shape(14000.0), a=ZERO, + b=lambda t: 800.0 if t < E + 300 else 0.0) +summary("T2b(i)", r2i, tr2i) +a2i = H.alarms(r2i) +check("T2b(i): b drops to 0 W at E+300 (landing without the car 13 733 W): " + "the alarm fires within 1 cycle of E+300", + len(a2i) == 1 and E + 300 <= nth(a2i, 0) <= E + 301) +check("T2b(i): ...and stays to the quarter's end (a house need with a " + "trusted car is latched)", all(x["alarm"] and x["red"] for x in + H.window(tr2i, E + 302, E + 899))) +r2ii, tr2ii = H.run(H.shape(14000.0), a=ZERO, + b=lambda t: 800.0 if t < E + 300 else 400.0) +summary("T2b(ii)", r2ii, tr2ii) +check("T2b(ii): b drops to 400 W (landing 13 467 W): no alarm to E+900", + quiet(r2ii, tr2ii)) + +# --- T3: batteries at 0 W, and the 11 kW car ---------------------------------- # +r3, tr3 = H.run(H.shape(13000.0), a=ZERO, b=ZERO) +w3, lim3 = summary("T3", r3, tr3) +check("T3: batteries 0 W, house 13 000 W, car 1 380 W: no alarm, no red row, " + "the car explains every limited cycle incl. E+0..E+10, one car notice", + quiet(r3, tr3) and all_explained(lim3) + and len(P.ids(r3, P.OVER)) == 1 + and all(x["explains"] for x in lim3 if x["t"] <= E + 10)) + + +def plug_at(t0): + return {t0: lambda p, c: p.ch.plug_in()} + + +r3k, tr3k = H.run(H.shape(2600.0, before=2600.0), a=ZERO, b=ZERO, car_a=16, + phases=3, aim=6344.0, plug=False, extra=plug_at(E - 120)) +w3k, lim3k = summary("T3 11 kW", r3k, tr3k) +check("T3 11 kW: house 2 600 W, car 11 kW, aim 6 344 W (base P 21:30): no " + "alarm, the car explains every limited cycle", + quiet(r3k, tr3k) and all_explained(lim3k) + and len(P.ids(r3k, P.OVER)) == 1) + +# --- T4 controller ------------------------------------------------------------ # +r409, tr409 = H.run(H.shape(13609.0), a=ZERO, b=ZERO) +summary("T4 13 609", r409, tr409) +check("T4: the house alone at aim + 9 W: no alarm", quiet(r409, tr409)) +r411, tr411 = H.run(H.shape(13611.0), a=ZERO, b=ZERO) +r411o, tr411o = H.run(H.shape(13611.0), a=ZERO, b=ZERO, mode="off") +summary("T4 13 611", r411, tr411) +summary("T4 13 611 Off", r411o, tr411o) +check("T4: at aim + 11 W the alarm at the same cycle as Off (and as base, " + "E+0)", H.alarms(r411) == H.alarms(r411o) == [E]) + +# --- T5: an honest alarm ------------------------------------------------------ # +r5, tr5 = H.run(honest(14090.0), a=ZERO, b=ZERO) +r5o, tr5o = H.run(honest(14090.0), a=ZERO, b=ZERO, mode="off") +summary("T5", r5, tr5) +summary("T5 Off", r5o, tr5o) +check("T5: grid excess 1 870 W > car 1 380 W: the alarm and the ERROR at the " + "same second as Off and as base (E+1, the step's first sample)", + H.alarms(r5) == H.alarms(r5o) == T5_BASE + and nth(H.errors(tr5), 0) == nth(H.errors(tr5o), 0) == E + 1) +check("T5: the car explains no cycle", not any(x["explains"] for x in tr5)) + + +# --- T6: the car figure unknown across the edge ------------------------------- # +def unavailable(t0, t1): + return {t0: lambda p, c: p.ch.go_unavailable(True), + t1: lambda p, c: p.ch.go_unavailable(False)} + + +r6, tr6 = H.run(H.shape(13000.0), a=ZERO, b=ZERO, + extra=unavailable(E - 20, E + 60)) +summary("T6 T3 shape", r6, tr6) +back = first(x["t"] for x in tr6 if x["t"] >= E + 60 and x["w"] is not None) +check("T6 T3 shape: while unknown the car explains nothing and the alarm " + "stands from E+0, as base", + H.alarms(r6) == [E] and not any( + x["explains"] for x in H.window(tr6, E - 5, E + 59)) + and all(x["alarm"] for x in H.window(tr6, E, E + 59))) +check("T6 T3 shape: released within 1 cycle of the first trusted cycle after " + "E+60, no new alarm edge to E+900 (base: red to E+900)", + present(back) and all(not x["alarm"] and x["explains"] for x in + H.window(tr6, back + 1, E + 899)) + and H.edges(tr6) == [E]) +r6h, tr6h = H.run(honest(14090.0), a=ZERO, b=ZERO, + extra=unavailable(E - 20, E + 60)) +summary("T6 T5 shape", r6h, tr6h) +check("T6 T5 shape: the alarm at the base second and it stands throughout", + H.alarms(r6h) == T5_BASE and all(x["alarm"] for x in + H.window(tr6h, E + 1, E + 899))) + + +# --- T7: a frozen car figure, the car really stops ---------------------------- # +def frozen_stop(p, c): + p.ch.freeze() + p.ch.car_full() + + +r7, tr7 = H.run(honest(14090.0), a=ZERO, b=ZERO, extra={E - 30: frozen_stop}) +summary("T7", r7, tr7) +first7 = nth(H.alarms(r7), 0) +untr = first(x["t"] for x in tr7 if x["t"] >= E - 30 and x["w"] is None) +check("T7: the alarm within 114 s of the stop (max(60, 40 Wh / 1.38 kW) " + "+ 10), no later than base", + present(first7) and first7 <= E - 30 + 114 and first7 <= T7_BASE) +check("T7: never explained after the figure goes untrusted", + present(untr) and not any(x["explains"] for x in tr7 if x["t"] >= untr)) + + +# --- T8: a car at 0 W, and a 50 W car ----------------------------------------- # +class Draw(SimCharger): + """A charger that draws `real_w` while charging and reports `say_w`.""" + def __init__(self, real_w, say_w, **kw): + super().__init__(**kw) + self.real_w, self.say_w = real_w, say_w + + def target_w(self): + return 0.0 if super().target_w() <= 0.0 else self.real_w + + def _build(self): + keep, self._frozen_w = self._frozen_w, self.say_w + try: + return super()._build() + finally: + self._frozen_w = keep + + +def full(p, c): + p.ch.car_full() + + +for nm, kw in (("house 14 090 W", dict(house=honest(14090.0), b=ZERO)), + ("T2 shape", dict(house=honest(14000.0), b=const(800.0)))): + r8, tr8 = H.run(a=ZERO, extra={1: full}, **kw) + r8o, tr8o = H.run(a=ZERO, extra={1: full}, mode="off", **kw) + summary(f"T8 0 W, {nm}", r8, tr8) + summary(f"T8 0 W, {nm}, Off", r8o, tr8o) + check(f"T8: a car plugged at 0 W, {nm}: the alarm at the same second as " + f"Off, nothing explained", H.alarms(r8) == H.alarms(r8o) + and H.alarms(r8) != [] and not any(x["explains"] for x in tr8)) +r8s, tr8s = H.run(honest(14090.0), a=ZERO, b=ZERO, + sim=Draw(50.0, 50.0, setpoint_a=6)) +r8so, tr8so = H.run(honest(14090.0), a=ZERO, b=ZERO, mode="off", + sim=Draw(50.0, 50.0, setpoint_a=6)) +summary("T8 50 W", r8s, tr8s) +check("T8: a 50 W car, house 14 090 W: the alarm at the same second as Off, " + "nothing explained", H.alarms(r8s) == H.alarms(r8so) == T5_BASE + and not any(x["explains"] for x in tr8s)) + +# --- T9: a wrong charger reply ------------------------------------------------ # +r9a, tr9a = H.run(honest(13900.0), a=ZERO, b=ZERO, + sim=Draw(1380.0, 11000.0, setpoint_a=6)) +summary("T9(a)", r9a, tr9a) +check("T9(a): reports 11 kW, read-back 6 A 1-ph (cap 1 518 W): the house " + "alone misses, the alarm at the base second", + H.alarms(r9a) == T5_BASE and all(x["w"] is None or x["w"] <= 1518.0 + for x in tr9a)) +r9b, tr9b = H.run(honest(13900.0), a=ZERO, b=ZERO, + sim=Draw(400.0, 1380.0, setpoint_a=6)) +summary("T9(b)", r9b, tr9b) +check("T9(b): reports 1 380 W, draws 400 W: the same alarms as base (none: " + "400 W corroborates a 1 380 W figure, CORR_RATIO 0.5; see the dev " + "report's Findings)", H.alarms(r9b) == T9B_BASE) +r9c, tr9c = H.run(honest(13900.0), a=ZERO, b=ZERO, + sim=Draw(100.0, 1380.0, setpoint_a=6)) +summary("T9(c)", r9c, tr9c) +a9c = nth(H.alarms(r9c), 0) +check("T9(c): reports 1 380 W, draws 100 W: the first alarm once the figure " + "is uncorroborated, at most 104 s + 10 s after the edge, no later than " + "base", present(a9c) and a9c <= E + 114 and a9c <= T9C_BASE) +print(f" T9(c) alarm edges {[t - E for t in H.edges(tr9c)]} (base: one; " + f"the meter's 10 Wh step re-corroborates the figure every 360 s and " + f"Expected 3/5 release the alarm then: see the dev report)") + +# --- T10: a lost battery reading, an unavailable charger ---------------------- # +for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), + ("T5", dict(house=honest(14090.0), b=ZERO))): + r10, tr10 = H.run(a=ZERO, lost={"b": {E + 1}}, **kw) + summary(f"T10(a) {nm}", r10, tr10) + gap = first(x for x in tr10 if x["t"] == E + 1) + nxt = first(x for x in tr10 if x["t"] == E + 2) + check(f"T10(a) {nm}: inverter-b's reading lost at E+1: that cycle grades " + f"nothing (P_SAFETY owns a missing input), the next one grades on " + f"what is measured", present(gap, nxt) and gap["batt"] is None + and nxt["batt"] == (800.0 if nm == "T2" else 0.0)) + if nm == "T2": + check("T10(a) T2: no alarm edge (base: E+0)", quiet(r10, tr10)) + else: + check("T10(a) T5: the same alarm seconds as base", + H.alarms(r10) == T10A_T5_BASE) + r10b, tr10b = H.run(a=ZERO, extra=unavailable(E + 1, E + 2), **kw) + summary(f"T10(b) {nm}", r10b, tr10b) + if nm == "T2": + check("T10(b) T2: the charger unavailable for one cycle (E+1): the " + "alarm stands for that cycle only (Expected 5)", + H.edges(tr10b) == [E + 1] + and all(not x["alarm"] for x in H.window(tr10b, E + 2, E + 899)) + and all(x["explains"] for x in H.window(tr10b, E + 2, E + 899) + if x["lim"])) + else: + check("T10(b) T5: the alarm at the base second and it stands", + H.alarms(r10b) == T5_BASE and all( + x["alarm"] for x in H.window(tr10b, E + 1, E + 899))) + +# --- T11: one battery first (SAFETY-87) --------------------------------------- # +for nm, house in (("(i) 17 500 W", 17500.0), ("(ii) 19 000 W", 19000.0)): + r11, tr11 = H.run(honest(house), soc={"a": 19.0, "b": 35.0}) + summary(f"T11{nm}", r11, tr11) + if house < 18000.0: + check("T11(i): b able, house 17 500 W, car 1 380 W: no alarm across E", + H.alarms(r11) == [] and P.ids(r11, *P.ALARMS) == []) + else: + check("T11(ii): house 19 000 W: the alarm at the base second", + [t for t, _n in P.ids(r11, *P.ALARMS)] == T11_BASE) + +# --- T12 (record only): plug-in at E+0, the reserve at E+180 ------------------ # +def reserve_at(p, c): + p.socs.update({"a": 19.0, "b": 19.0}) + + +r12, tr12 = H.run(H.shape(13000.0), soc={"a": 40.0, "b": 40.0}, plug=False, + extra={E: lambda p, c: p.ch.plug_in(), E + 180: reserve_at}) +summary("T12 (record, F-B)", r12, tr12) + +# --- T13 controller: the latch is kept ---------------------------------------- # +r13, tr13 = H.run(H.shape(lambda t: 15500.0 if E + 300 <= t < E + 360 + else 13000.0), a=ZERO, b=ZERO) +summary("T13", r13, tr13) +check("T13: the house steps to 15 500 W at E+300 for 60 s: the alarm at " + "the base second (E+301, the step's first sample), and red to the " + "quarter's end", H.alarms(r13) == T13_BASE and all( + x["alarm"] and x["red"] for x in H.window(tr13, E + 301, E + 899))) + +# --- T16: the edge paths ------------------------------------------------------ # +for nm, kw in (("(a)(b)(c) SAFETY-91 roll, modes on", {}), + ("(d) the guard not wanting at the edge", + dict(lost={"b": {E}}))): + r16, tr16 = H.run(H.shape(13000.0), a=ZERO, b=ZERO, **kw) + w16, lim16 = summary(f"T16{nm}", r16, tr16) + f16 = first(x for x in tr16 if x["t"] >= E and x["lim"]) + pre = first(x for x in tr16 if x["t"] == E - 1) + check(f"T16{nm}: the car explains from the first limited cycle of the " + f"new block, no alarm, no red row, `_carq` key = block_start", + present(f16) and quiet(r16, tr16) and all( + x["explains"] and x["key"] == x["block"] + for x in tr16 if x["t"] >= f16["t"] and x["lim"])) + if not kw: + print(f" T16(c): within_aim at E-1 {pre['within_aim'] if present(pre) else pre}" + " (SAFETY-126's latch carried; not asserted)") + else: + g0 = first(x for x in tr16 if x["t"] == E) + check("T16(d) PRECONDITION: the guard did not want power at E+0", + present(g0) and not g0["wants"]) + + +# --- T17: a restart ----------------------------------------------------------- # +def restart_at(t0): + return {t0: lambda p, c: H.restart(c)} + + +for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), + ("T3", dict(house=H.shape(13000.0), b=ZERO)), + ("T5", dict(house=honest(14090.0), b=ZERO))): + rr0, tr0 = H.run(a=ZERO, **kw) + for at in (E + 2, E + 300): + rr, trr = H.run(a=ZERO, extra=restart_at(at), **kw) + summary(f"T17 {nm} restart at E+{at - E}", rr, trr) + if nm == "T5": + check(f"T17 T5, restart at E+{at - E}: the alarm at the base " + f"second and again on the first cycle after the restart, " + f"as base; red throughout", + H.alarms(rr) == T5_BASE + [at] and len(H.red_secs(trr)) + == len(H.red_secs(tr0))) + else: + check(f"T17 {nm}, restart at E+{at - E}: the same as without " + f"(no floor notice, no ERROR, no red row)", + quiet(rr, trr) and quiet(rr0, tr0)) + print(f" T17 {nm} car-over notices: twin " + f"{[t - E for t, _n in P.ids(rr0, P.OVER)]}, restarted " + f"{[t - E for t, _n in P.ids(rr, P.OVER)]} (EV-11's " + f"once-per-session state does not survive a restart, as on " + f"base)") + +# --- T15 controller: x10 ------------------------------------------------------ # +# F2 (out of scope, filed apart): `_car_quarter` caps a cycle's dt at 5 s, so at +# 10 s a cycle half the car's energy is counted, and late in the quarter the +# house alone seems to miss the aim (T2 from about E+540, T3 E+820, as on base +# for T3). The x10 verdicts are graded to E+500; what comes after is printed. +F2_FROM = E + 500 +for nm, kw, want in ( + ("T2", dict(house=H.shape(14000.0), b=const(800.0)), "quiet"), + ("T3", dict(house=H.shape(13000.0), b=ZERO), "quiet"), + ("T5", dict(house=honest(14090.0), b=ZERO), "alarm"), + ("T6", dict(house=H.shape(13000.0), b=ZERO, + extra=unavailable(E - 20, E + 60)), "release")): + rx, trx = H.run(a=ZERO, x=10, **kw) + summary(f"T15 x10 {nm}", rx, trx) + early = [x for x in trx if x["t"] < F2_FROM] + print(f" T15 x10 {nm}: alarms after E+500 (F2) " + f"{[t - E for t in H.alarms(rx) if t >= F2_FROM]}") + if want == "quiet": + check(f"T15 x10 {nm}: no alarm, no red row, every limited cycle " + f"explained, E-120..E+500", + not [t for t in H.alarms(rx) if t < F2_FROM] + and H.red_secs(trx, t1=F2_FROM - 1) == [] + and all_explained([x for x in early if x["lim"]])) + elif want == "alarm": + check("T15 x10 T5: the alarm at the base second (E+10, one cycle)", + H.alarms(rx) == T15_T5_BASE) + else: + bk = first(x["t"] for x in trx if x["t"] >= E + 60 + and x["w"] is not None) + check("T15 x10 T6: the alarm while unknown, released within 1 cycle " + "(10 fake s) of the first trusted one, no new edge to E+500", + present(bk) and bk <= E + 70 + and all(not x["alarm"] for x in H.window(trx, bk, F2_FROM - 1)) + and [t for t in H.edges(trx) if t < F2_FROM] == [E]) + +# --- N4: the alarm decision changes no command -------------------------------- # +for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), + ("T5", dict(house=honest(14090.0), b=ZERO))): + ra, tra = H.run(a=ZERO, **kw) + rb, trb = H.run(a=ZERO, explain_off=True, **kw) + check(f"N4 {nm}: the claim, the floor, the battery setpoints and the " + f"charger writes are identical whether the car explains or not", + H.commands(ra, tra) == H.commands(rb, trb)) + +# --- N5: at most one floor-alarm edge per quarter ---------------------------- # +def per_quarter(ts): + out = {} + for t in ts: + out[(t - E) // 900] = out.get((t - E) // 900, 0) + 1 + return out + + +many = [(nm, ts) for nm, ts in RUNS + if not nm.startswith("T9(c)") + and any(v > 1 for v in per_quarter( + [t for t in ts if not nm.startswith("T15 x10") or t < F2_FROM]) + .values())] +check(f"N5: at most one floor-alarm edge per quarter in every run " + f"({len(RUNS)} runs; T9(c) apart, x10 to E+500): {many}", many == []) + +print() +print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") +sys.exit(1 if fails else 0) diff --git a/goodwe_controller/tools/ev18_peak.py b/goodwe_controller/tools/ev18_peak.py new file mode 100644 index 0000000..b104d66 --- /dev/null +++ b/goodwe_controller/tools/ev18_peak.py @@ -0,0 +1,207 @@ +"""EV-18: the real Controller across one quarter edge `E`, N=2, both units at +the peak reserve and the car charging (`ev04_peak.drive`). Used by test_ev18.py. + +The run starts `E` s before an edge (rig.BASE is moved back for the run), with +a light house so the first quarter does not raise the month's peak (the aim +stays `AIM`). At `E - 120` the house steps to the shape, so the guard first +wants power at the edge, as on the rig (EV-15 F-A). `force` makes a unit give +what the loop gives below the reserve whatever it is told; `lost` drops its +reading for some seconds (the grid still sees it). The trace is one dict per +cycle, taken after it. +""" + +import hashlib +import logging +import os +import sys +from datetime import timedelta + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import ev04_peak as P # noqa: E402 +import opt11_identity as rig # noqa: E402 +import safety81_sim as s81 # noqa: E402 +from app import peakguard # noqa: E402 + +E = 150 # the edge, in run seconds +AIM = 13600.0 +MARGIN = 50.0 +PRE_W = 5000.0 # the first quarter's house: under the cap +FLOOR = "goodwe_peak_soc_floor" +OPTS = {"peak_soc_floor": 20, "inverters": [ + {"name": "inverter-a", "setpoint_entity": "number.sp_a", + "soc_entity": "sensor.soc_a", "batt_entity": "sensor.batt_a", + "max_w": 5000, "bms_soc_floor": 10}, + {"name": "inverter-b", "setpoint_entity": "number.sp_b", + "soc_entity": "sensor.soc_b", "batt_entity": "sensor.batt_b", + "max_w": 4600, "bms_soc_floor": 10}]} + + +class _Errors(logging.Handler): + def __init__(self): + super().__init__(logging.ERROR) + self.rec = [] + + def emit(self, r): + self.rec.append(r.getMessage()) + + +ERR = _Errors() +_lg = logging.getLogger("goodwe") +_lg.addHandler(ERR) +_lg.setLevel(logging.ERROR) +_lg.propagate = False + + +class Plant(P.CarPlantN): + force = {} + lost = {} + + def batt_of(self, u, at): + f = self.force.get(u) + if f is not None: + return float(f(at)) + return super().batt_of(u, at) + + async def number(self, e, invert=False): + for u, secs in self.lost.items(): + if e == "sensor.batt_" + u and int(self.t) in secs: + return None + return await super().number(e, invert) + + +def shape(after, before=PRE_W, at=None): + """The house: `before` until `at` (E - 120), then `after` (W or fn(t)).""" + at = E - 120 if at is None else at + return lambda t: before if t < at else (after(t) if callable(after) + else after) + + +def run(house, *, a=None, b=None, lost=None, car_a=6, phases=1, aim=AIM, + mode="manual", dur=None, extra=None, sim=None, soc=None, plug=True, + x=1, mono_x=None, explain_off=False): + """One run; returns (run, trace). `x`: fake seconds per cycle (wall and + monotonic both; `mono_x` sets the monotonic rate apart). `explain_off`: + the car never explains (for the control-identity check).""" + force = {} + if a is not None: + force["a"] = a + if b is not None: + force["b"] = b + cls = type("Plant", (Plant,), {"force": force, "lost": lost or {}}) + tr = [] + n_err = [len(ERR.rec)] + dur = E + 900 if dur is None else dur + + def hook(plant, c): + orig = c.car_settle + if explain_off: + c._car_explains_alarm = lambda *a_, **k_: False + if mono_x is not None and mono_x != x: + c.car_now = (lambda f=c.car_now: f() * mono_x / x) + + async def settle(): + await orig() + g = c.peak_guard + red = [] + if plant.t >= E - 130: + red = [r_["id"] for r_ in c.checks() + if r_["ok"] is False and not r_["warn"] + and r_["id"] == "peak_guard"] + errs = [m for m in ERR.rec[n_err[0]:] + if "may not draw the battery lower" in m] + n_err[0] = len(ERR.rec) + cl = peakguard.claim(g) if g is not None else None + tr.append({ + "t": plant.t, "explains": c.car_explains, + "lim": bool(g is not None and (g.floor_limited + or g.saturated)), + "within_aim": bool(g is not None and g.within_aim), + "wants": bool(g is not None and g.engaged + and (g.wanted_w or 0.0) > 0.0), + "alarm": c._peak_floor_limited, "red": red, "err": errs, + "w": c.car_alarm_w(), "batt": c.site_batt_w, + "key": c._carq["key"], + "block": (c._peak_proj_real.block_start + if c._peak_proj_real is not None else None), + "floor_w": g.floor_w if g is not None else None, + "lo": getattr(cl, "lo", None), + "sp": tuple(i.last_write for i in c.inverters)}) + c.car_settle = settle + + ev = {0: hook} + for t, fn in (extra or {}).items(): + if t == 0: + ev[0] = (lambda p, c, fn=fn: (hook(p, c), fn(p, c))) + else: + ev[t] = fn + socs = soc or {"a": 19.0, "b": 19.0} + s = sim + if s is None: + from chargersim import SimCharger + s = SimCharger(setpoint_a=car_a) + if x != 1: + tick = s.tick + s.tick = lambda secs=1.0: tick(secs * x) + base, step = rig.BASE, s81.TICK + rig.BASE, s81.TICK = base - timedelta(seconds=E), float(x) + try: + r = P.drive(house, dur=dur, rating=5000.0, soc=socs, + cap=aim + MARGIN, phases=phases, n=2, plant_cls=cls, + opts=OPTS, dev_w=5000.0, setpoint=car_a, user_a=car_a, + mode=mode, events=ev, sim=s, plug=plug) + finally: + rig.BASE, s81.TICK = base, step + return r, tr + + +def alarms(r): + """Seconds of each goodwe_peak_soc_floor notification.""" + return [t for t, n in r["raised"] if n == FLOOR] + + +def window(tr, t0, t1): + return [x for x in tr if t0 <= x["t"] <= t1] + + +def edges(tr): + """Seconds at which the floor alarm goes False -> True.""" + out, was = [], False + for x in tr: + if x["alarm"] and not was: + out.append(x["t"]) + was = x["alarm"] + return out + + +def red_secs(tr, t0=None, t1=None): + t0 = E - 120 if t0 is None else t0 + t1 = E + 900 if t1 is None else t1 + return [x["t"] for x in window(tr, t0, t1) if x["red"]] + + +def errors(tr): + return [x["t"] for x in tr if x["err"]] + + +def commands(r, tr): + """A digest of every command: the units' setpoints, the charger's writes, + and the guard's floor and claim per cycle (N4).""" + h = hashlib.sha256() + for u in sorted(r["plant"].hists): + h.update(repr((u, r["plant"].hists[u])).encode()) + h.update(repr(r["sim"].writes()).encode()) + h.update(repr([(x["t"], x["floor_w"], x["lo"], x["sp"]) + for x in tr]).encode()) + return h.hexdigest()[:16] + + +def restart(c): + """A restart as the car side sees it: a fresh `car_init` and an empty + corroboration history, and no floor alarm standing.""" + mode, n, a = c.car_mode, c.car_n, c.car_a + c.car_init(c.o, c.store) + c.car_mode, c.car_n, c.car_a = mode, n, a + c.car._hist.clear() + c._peak_floor_limited = False -- 2.54.0 From 5db56b5f28ab544ac973308870ae15a217026be8 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Thu, 19 Nov 2026 11:28:04 +0100 Subject: [PATCH 06/55] EV-18 review round 1: restart keeps the house's done part; contradicted figure untrusted to the quarter's end - [Critical] After a restart or a gap only the rest of the quarter was graded without the car (`_carq["whole"]`), which dropped the house's own energy from before it and hid an honest alarm (review repro: house 18 kW then 12 kW, restart at E+310). The rest-only grading is gone: the car is credited only with energy counted since the start, the rest of what is done counts as house (base's side). T17b covers it; T17 T2 at E+300 now alarms from the restart (the conservative side). - [Major] Owner 2026-11-19: a figure the energy meter contradicted (fresh, charging, not corroborated) stays untrusted to the quarter's end, also as the EV-15 stand-in. T9(c): one alarm edge, red to the end; T9(c) is back in the N5 check. - [Major] T2c lagging-meter variant (readings 389 W then 800 W, the meter at 800 W): the house latch grades on the lower reading. - Unit stub: a run that starts mid-quarter has the car counted since the quarter's start (no restart). Co-Authored-By: Claude --- .../DECISIONS/EV-04-manual-mode.md | 8 ++- goodwe_controller/app/ctl_car.py | 48 ++++++++------- goodwe_controller/test_ev18.py | 60 +++++++++++++++++-- 3 files changed, 86 insertions(+), 30 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index e49e675..3a45fb7 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -146,9 +146,11 @@ up to 1.8 kW; the 40 Wh floor fixes that.) (`_car_need_house`) seen with a trusted car figure stays latched to the quarter's end. The car explains where the period with it misses on the same batteries (`_car_over_now`), or by the EV-10 test above. A `None` car figure - or battery reading explains nothing in that cycle and latches nothing. After - a restart or a gap the car's share of what is done is unknown (`_carq` - `whole`), so only the rest of the period is graded without the car. + or battery reading explains nothing in that cycle and latches nothing; a car + known to draw nothing (fresh, not charging) still grades the house's need. + Owner 2026-11-19: a figure the energy meter contradicted (fresh, charging, + not corroborated) stays untrusted to the quarter's end. After a restart or a + gap the car's earlier energy is not known, so it counts as house. - **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/ctl_car.py b/goodwe_controller/app/ctl_car.py index 726173a..53bfa88 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -62,6 +62,7 @@ class CarMixin: self._car_need_real = self._car_need_excl = False # EV-10 latches self._car_need_house = self._car_over_now = False # EV-18 latches self._car_latch_block = None + self._car_contra_block = None # EV-18: the quarter it was contradicted self._car_over_notified = None # the session a notice was raised for self._car_session = 0 self._car_prev_state = None @@ -236,6 +237,17 @@ class CarMixin: <= OWN_PAUSE_MAX_S return 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S + def _car_contradicted(self, mono) -> bool: + """EV-18 (owner 2026-11-19): does the charger's energy meter + contradict a fresh, not stuck figure of a charging car? Then that + figure stays untrusted to the quarter's end (`car_cycle`).""" + r = getattr(self.car, "reading", None) + if r is None or not r.available or r.charging is not True \ + or not self.car_manual(): + return False + return (self.car.car_w(mono) is not None and not self.car.stuck(mono) + and not self.car.corroborated(mono)) + def _car_idle(self, mono) -> bool: """EV-18: is the car known to draw nothing? A fresh reading that says it is not charging (mode3 A or B) at under `CAR_PEAK_MIN_W`. Not an @@ -255,16 +267,8 @@ class CarMixin: key = None if proj is None else proj.block_start last = q["mono"] if key != q["key"]: - # EV-18: `whole` when the count covers the block: it follows on - # from the block before, or starts in its first seconds (not - # after a restart or a gap). - whole = key is not None and ( - float(proj.elapsed_s) <= 5.0 or ( - last is not None and q["key"] is not None - and (key - q["key"]).total_seconds() == QUARTER_S)) self._car_bank(q) q["key"], q["ws"], q["ws_p"] = key, 0.0, 0.0 - q["whole"] = whole if key is not None and last is not None: dt = min(max(mono - last, 0.0), 5.0) if w is not None: @@ -340,8 +344,15 @@ class CarMixin: # 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 own = (w is None or float(w) <= 0.0) and self._car_own_pause(mono) + # EV-18: a figure the meter contradicted is not trusted again in + # that quarter, not even as the stand-in for our own pause. + key = None if real_proj is None else real_proj.block_start + if key is not None and not own and self._car_contradicted(mono): + self._car_contra_block = key + if key is not None and key == self._car_contra_block: + w, own = None, False + wg = w if w is None and own: wg = self.car.car_w_paused(mono) self._car_quarter(real_proj, w, mono, wg) @@ -417,11 +428,10 @@ class CarMixin: self._car_over_now = self._car_over_now or \ self._car_lands_over(real_proj, now, batt, target_w) if w is not None: - whole = self._carq.get("whole", True) self._car_need_excl = self._car_need_excl or \ peakguard.misses_aim(excl, batt_w=batt, target_w=target_w) self._car_need_house = self._car_need_house or \ - self._car_lands_over(excl, now, batt, target_w, whole) + self._car_lands_over(excl, now, batt, target_w) if w is None or batt is None or not wants \ or not (guard.saturated or guard.floor_limited): return False @@ -441,18 +451,14 @@ class CarMixin: return bool(high(real_proj) and not high(excl)) @staticmethod - def _car_lands_over(p, now, gives, target_w, whole=True) -> bool: + def _car_lands_over(p, now, gives, target_w) -> bool: """EV-18: does the period end more than `ALARM_MISS_W` over the aim with the batteries giving `gives` W from now on (`now`: what they gave - in the meter's figure)? Not `whole`: the car's share of what is done - is not known (a restart, a gap), so only the rest is graded.""" - if whole: - return peakguard.load_too_high(p, batt_w=now, ceiling_w=target_w, - achievable_w=gives) - if QUARTER_S - float(p.elapsed_s) <= 0.0: - return False - rest = float(p.held_w) + float(now) - float(gives) - return rest - float(target_w) > peakguard.ALARM_MISS_W + in the meter's figure)? Of what is done, only the car's energy counted + since the add-on started is the car's (a restart or a gap leaves the + rest with the house).""" + return peakguard.load_too_high(p, batt_w=now, ceiling_w=target_w, + achievable_w=gives) def _car_session_tick(self, mono) -> None: """A charging session is a plug-in: the state goes from no car to a diff --git a/goodwe_controller/test_ev18.py b/goodwe_controller/test_ev18.py index 01c3853..a18ffd9 100644 --- a/goodwe_controller/test_ev18.py +++ b/goodwe_controller/test_ev18.py @@ -99,6 +99,11 @@ def urun(secs, grid, batt, w, *, x=1, mono_x=None, c=None, guard=None): c = c or _Car() mono_x = x if mono_x is None else mono_x done, out = {}, {} + t0 = nth(list(secs), 0) + if c._carq["key"] is None and present(t0) and t0 % 900: + # started mid-quarter: the car was counted since its start (no restart) + c._carq.update(key=BS + timedelta(seconds=900 * (t0 // 900)), + ws=float(w(t0) or 0.0) * (t0 % 900), ws_p=0.0) for t in secs: q = t // 900 bs, el = BS + timedelta(seconds=900 * q), t - 900 * q @@ -167,6 +172,18 @@ check("T2c: b at 389 W (13 611 W, aim + 11 W): it does not, from E+0", not any(e389) and len(e389) == 6) check("T2c: readings 395 then 385 W: graded on 385 W, no explanation from " "the second cycle on", not any(e395[1:]) and len(e395) == 6) +# review round 1 (MD): the meter shows the higher output while the readings +# are 389 W then 800 W. b gives 800 W; one reading of 389 W at E+3, the meter +# still at 800 W. House 14 005 W: at E+4 the house latch grades on the lower +# reading (389 W), rest 13 616 W, landing 13 614 W > aim + 10 W; on the +# current one (800 W) it would be 13 205 W. +_cl, elag = urun(range(0, 12), const(14005.0 + CAR - 800.0), + lambda t: 389.0 if t == 3 else 800.0, const(CAR)) +print(f" T2c lagging meter E+0..E+11: {run_of(elag, 0, 11)}") +check("T2c (meter lags, readings 389 then 800 W): explained before, the " + "house latch sets on the lower reading at E+4 and holds to E+11", + all(run_of(elag, 0, 3)) and not any(run_of(elag, 4, 11)) + and len(run_of(elag, 4, 11)) == 8) # --- T4: ALARM_MISS_W, batteries at 0 W -------------------------------------- # e09 = run_of(urun(range(0, 6), const(13609.0 + CAR), const(0.0), @@ -503,9 +520,12 @@ a9c = nth(H.alarms(r9c), 0) check("T9(c): reports 1 380 W, draws 100 W: the first alarm once the figure " "is uncorroborated, at most 104 s + 10 s after the edge, no later than " "base", present(a9c) and a9c <= E + 114 and a9c <= T9C_BASE) -print(f" T9(c) alarm edges {[t - E for t in H.edges(tr9c)]} (base: one; " - f"the meter's 10 Wh step re-corroborates the figure every 360 s and " - f"Expected 3/5 release the alarm then: see the dev report)") +check("T9(c) (owner 2026-11-19): the meter contradicted the figure, so it " + "stays untrusted to the quarter's end: one alarm edge, red and never " + "explained to E+899 (the meter's 10 Wh step re-corroborates it every " + "360 s)", H.edges(tr9c) == [a9c] and all( + x["alarm"] and x["red"] and not x["explains"] + for x in H.window(tr9c, a9c, E + 899))) # --- T10: a lost battery reading, an unavailable charger ---------------------- # for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), @@ -606,6 +626,16 @@ for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), f"as base; red throughout", H.alarms(rr) == T5_BASE + [at] and len(H.red_secs(trr)) == len(H.red_secs(tr0))) + elif nm == "T2" and at == E + 300: + # review round 1: the car's energy before a restart is not known, + # so it counts as house (never credited to the car). Here that + # tips the house alone over the aim: the alarm stands from the + # restart, the conservative side (base: red from E+0). + check("T17 T2, restart at E+300: quiet before the restart; after " + "it the car's unknown earlier share counts as house, so at " + "most one alarm edge, at the restart", + quiet(rr0, tr0) and H.red_secs(trr, t1=at - 1) == [] + and H.edges(trr) in ([], [at])) else: check(f"T17 {nm}, restart at E+{at - E}: the same as without " f"(no floor notice, no ERROR, no red row)", @@ -616,6 +646,25 @@ for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), f"once-per-session state does not survive a restart, as on " f"base)") +# --- T17b (review round 1): a house need only the done part shows ----------- # +def heavy_then_light(t): + """House 18 000 W for E..E+300, then 12 000 W: alone it lands 14 000 W.""" + if t < E: + return H.PRE_W if t < E - 120 else 12000.0 + return 18000.0 if t < E + 300 else 12000.0 + + +r17b0, tr17b0 = H.run(heavy_then_light, a=ZERO, b=ZERO) +r17b, tr17b = H.run(heavy_then_light, a=ZERO, b=ZERO, + extra=restart_at(E + 310)) +summary("T17b no restart", r17b0, tr17b0) +summary("T17b restart at E+310", r17b, tr17b) +check("T17b: the house heavy before a restart at E+310 (alone it lands " + "14 000 W, excess 1 780 W > car): red to the quarter's end and never " + "explained, as without the restart (and as base and Off)", + len(H.red_secs(tr17b, E, E + 899)) == len(H.red_secs(tr17b0, E, E + 899)) + == 899 and not any(x["explains"] for x in H.window(tr17b, E, E + 899))) + # --- T15 controller: x10 ------------------------------------------------------ # # F2 (out of scope, filed apart): `_car_quarter` caps a cycle's dt at 5 s, so at # 10 s a cycle half the car's energy is counted, and late in the quarter the @@ -669,12 +718,11 @@ def per_quarter(ts): many = [(nm, ts) for nm, ts in RUNS - if not nm.startswith("T9(c)") - and any(v > 1 for v in per_quarter( + if any(v > 1 for v in per_quarter( [t for t in ts if not nm.startswith("T15 x10") or t < F2_FROM]) .values())] check(f"N5: at most one floor-alarm edge per quarter in every run " - f"({len(RUNS)} runs; T9(c) apart, x10 to E+500): {many}", many == []) + f"({len(RUNS)} runs; x10 to E+500): {many}", many == []) print() print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") -- 2.54.0 From 93c6628eca94a77656cebb5125b57a8038d45329 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Thu, 19 Nov 2026 12:18:06 +0100 Subject: [PATCH 07/55] EV-18 review round 2: the contradiction latch touches only the alarm; an unknown energy reading is not a contradiction - [Critical] The latch set `w = None` before `_car_quarter`, so with cover off the guard's input (`car_exclude`) counted the car as house and the batteries discharged. The latch now changes only the figure graded for the alarm; the car's energy count, the guard's input and the car-over row keep the unlatched `car_alarm_w()`. Cover-off N4 twins (energy gap, T9(c) liar, SoC 60 % and at the reserve) give the same commands as without the latch. - [Major] `corroborated()` is False for an unknown energy reading, so one missing reading latched a correct figure for the quarter. New `CarTracker.contradicted()`: only a meter that answered over a whole window and fell short. R1 (energy entity unknown 1 s at E+200, T2 and T3 shapes): red for that cycle only, explained from the next. - Minors: unit checks that a contradiction in our own pause latches nothing (MF) and that the latch ends with the quarter (MG). Co-Authored-By: Claude --- goodwe_controller/app/chargers.py | 11 +++ goodwe_controller/app/ctl_car.py | 33 +++++---- goodwe_controller/test_ev18.py | 107 ++++++++++++++++++++++++++- goodwe_controller/tools/ev18_peak.py | 20 ++++- 4 files changed, 153 insertions(+), 18 deletions(-) diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index caa6618..7c96512 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -790,6 +790,17 @@ class CarTracker: return got_wh >= CORR_RATIO * exp_wh - CORR_SLACK_WH return True + def contradicted(self, now: float) -> bool: + """EV-18: did the energy meter answer over a whole window and fall + short (`corroborated` compared and failed)? Not when the energy + reading is unknown, the window is empty or still short, or the car is + not charging: those are unknown, not contradicted.""" + r = self.reading + if r is None or not r.available or r.charging is not True \ + or r.energy_kwh is None or not self._hist: + return False + return not self.corroborated(now) + 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.""" diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 53bfa88..d3f86a2 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -238,15 +238,17 @@ class CarMixin: return 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S def _car_contradicted(self, mono) -> bool: - """EV-18 (owner 2026-11-19): does the charger's energy meter - contradict a fresh, not stuck figure of a charging car? Then that - figure stays untrusted to the quarter's end (`car_cycle`).""" + """EV-18 (owner 2026-11-19): did the charger's energy meter answer + and fall short of a fresh, not stuck figure of a charging car + (`CarTracker.contradicted`)? Then that figure stays untrusted for the + alarm to the quarter's end (`car_cycle`). An unknown energy reading + contradicts nothing.""" r = getattr(self.car, "reading", None) if r is None or not r.available or r.charging is not True \ or not self.car_manual(): return False return (self.car.car_w(mono) is not None and not self.car.stuck(mono) - and not self.car.corroborated(mono)) + and self.car.contradicted(mono)) def _car_idle(self, mono) -> bool: """EV-18: is the car known to draw nothing? A fresh reading that says @@ -345,18 +347,19 @@ class CarMixin: # car at 0 A and the energy meter cannot corroborate it then, so for # that bounded time its fresh, not stuck figure stands in. own = (w is None or float(w) <= 0.0) and self._car_own_pause(mono) - # EV-18: a figure the meter contradicted is not trusted again in - # that quarter, not even as the stand-in for our own pause. - key = None if real_proj is None else real_proj.block_start - if key is not None and not own and self._car_contradicted(mono): - self._car_contra_block = key - if key is not None and key == self._car_contra_block: - w, own = None, False wg = w if w is None and own: wg = self.car.car_w_paused(mono) self._car_quarter(real_proj, w, mono, wg) self._car_session_tick(mono) + # EV-18 (owner 2026-11-19): a figure the meter contradicted grades no + # alarm again in that quarter, not even as our own pause's stand-in. + # The alarm decision only: the car's energy count, the guard's input + # (`car_exclude`) and the car-over row keep the figure. + key = None if real_proj is None else real_proj.block_start + if key is not None and not own and self._car_contradicted(mono): + self._car_contra_block = key + contra = key is not None and key == self._car_contra_block explains = over = False if real_proj is not None and target_w is not None \ and real_proj.block_start is not None: @@ -365,9 +368,11 @@ class CarMixin: # (the house's own need); it and a 0 W figure explain nothing, # but in our own pause (EV-15). idle = wg is None and self._car_idle(mono) - graded = self._car_explains_alarm(real_proj, guard, target_w, - 0.0 if idle else wg) - if idle or (w is not None and float(w) <= 0.0 and not own): + graded = self._car_explains_alarm( + real_proj, guard, target_w, + None if contra else 0.0 if idle else wg) + if contra or idle or (w is not None and float(w) <= 0.0 + and not own): graded = False if self.car_cover: explains = over = graded diff --git a/goodwe_controller/test_ev18.py b/goodwe_controller/test_ev18.py index a18ffd9..9737c5c 100644 --- a/goodwe_controller/test_ev18.py +++ b/goodwe_controller/test_ev18.py @@ -241,6 +241,65 @@ check("T8 unit: the same with the charger unavailable (unknown car): the " "alarm stands while unknown and is released at E+60 (Expected 5)", not any(run_of(exu, 0, 59)) and all(run_of(exu, 60, 899))) +# --- the contradiction latch (owner 2026-11-19), unit ----------------------- # +class _TrackerC: + """A charging car whose energy meter contradicts it when `contra(t)`.""" + def __init__(self, contra): + self.contra = contra + self.reading = CH.ChargerReading(available=True, state="C", + charging=True, power_w=CAR) + + def car_w(self, _now): + return CAR + + def stuck(self, _now): + return False + + def contradicted(self, now): + return self.contra(now - 10000.0) + + def car_w_paused(self, _now): + return CAR + + @staticmethod + def status(*_a): + return "charging" + + +class _CarC(_Car): + def __init__(self, contra, own): + super().__init__() + self.car, self.own = _TrackerC(contra), own + + def car_manual(self): + return True + + def _car_own_pause(self, mono): + return self.own(mono - 10000.0) + + +def contra_run(contra, own, secs): + c = _CarC(contra, own) + _c, ex = urun(secs, const(13000.0 + CAR), const(0.0), + lambda t: None if contra(t) or own(t) else CAR, c=c) + return ex + + +never = lambda t: False # noqa: E731 +exg = contra_run(lambda t: 300 <= t < 306, never, range(0, 1100)) +check("contradiction (T3 shape): the meter contradicts the figure at E+300: " + "not explained from E+300 to the quarter's end, though trusted again " + "from E+306", all(run_of(exg, 0, 299)) and not any(run_of(exg, 300, 899)) + and len(run_of(exg, 300, 899)) == 600) +check("contradiction: released by the next quarter (review MG): explained " + "again from E+900", all(run_of(exg, 900, 1099)) + and len(run_of(exg, 900, 1099)) == 200) +exf = contra_run(lambda t: 100 <= t < 130, lambda t: 100 <= t < 130, + range(0, 400)) +check("contradiction during our own pause (EV-15) latches nothing (review " + "MF): the stand-in explains in it, the trusted figure after it", + all(run_of(exf, 0, 399)) and len(run_of(exf, 0, 399)) == 400) + # --- T10(a) unit: the battery reading lost for one cycle --------------------- # cA, eA = urun(range(-3, 10), const(14000.0 + CAR - 800.0), lambda t: None if t == 1 else 800.0, const(CAR)) @@ -557,6 +616,18 @@ for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), H.alarms(r10b) == T5_BASE and all( x["alarm"] for x in H.window(tr10b, E + 1, E + 899))) +# --- R1 (review round 2): the energy reading unknown for one cycle ----------- # +for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), + ("T3", dict(house=H.shape(13000.0), b=ZERO))): + rg, trg = H.run(a=ZERO, extra=H.energy_gap(E + 200), **kw) + summary(f"R1 {nm} energy gap at E+200", rg, trg) + check(f"R1 {nm}: the charger's energy entity unknown for one cycle " + f"(E+200) on a correct car: unknown, not contradicted, so red for " + f"that cycle only and explained from the next (Expected 5)", + H.red_secs(trg) == [E + 200] and H.edges(trg) == [E + 200] + and all(x["explains"] for x in H.window(trg, E + 201, E + 899) + if x["lim"])) + # --- T11: one battery first (SAFETY-87) --------------------------------------- # for nm, house in (("(i) 17 500 W", 17500.0), ("(ii) 19 000 W", 19000.0)): r11, tr11 = H.run(honest(house), soc={"a": 19.0, "b": 35.0}) @@ -709,6 +780,31 @@ for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), f"charger writes are identical whether the car explains or not", H.commands(ra, tra) == H.commands(rb, trb)) +# N4 with "Batteries help with the peak" off (review round 2): the guard's +# input is `car_exclude`, which reads the car's energy count. The +# contradiction latch must not touch it: the same commands with the latch off. +for nm, kw in ( + ("SoC 60 %, energy gap at E+200", + dict(house=H.shape(13000.0), soc={"a": 60.0, "b": 60.0}, + extra=H.energy_gap(E + 200))), + ("at the reserve, energy gap at E+200", + dict(house=H.shape(13000.0), a=ZERO, b=ZERO, + extra=H.energy_gap(E + 200))), + ("SoC 60 %, the T9(c) liar", + dict(house=honest(13900.0), soc={"a": 60.0, "b": 60.0}, + sim=Draw(100.0, 1380.0, setpoint_a=6))), + ("at the reserve, the T9(c) liar", + dict(house=honest(13900.0), a=ZERO, b=ZERO, + sim=Draw(100.0, 1380.0, setpoint_a=6)))): + ra, tra = H.run(cover=False, **kw) + if "sim" in kw: + kw = dict(kw, sim=Draw(100.0, 1380.0, setpoint_a=6)) + rb, trb = H.run(cover=False, latch_off=True, **kw) + summary(f"N4 cover off, {nm}", ra, tra) + check(f"N4 cover off, {nm}: the claim, the floor, the setpoints and the " + f"charger writes are those of the same run without the " + f"contradiction latch", H.commands(ra, tra) == H.commands(rb, trb)) + # --- N5: at most one floor-alarm edge per quarter ---------------------------- # def per_quarter(ts): out = {} @@ -717,12 +813,19 @@ def per_quarter(ts): return out +# Cover off, the T9(c) liar at the reserve: the guard's own engagement flips +# as the liar's figure is corroborated now and then (its input is +# `car_exclude`), pre-existing (base: 4 edges). Printed, not graded here. +LIAR_OFF = "N4 cover off, at the reserve, the T9(c) liar" +print(f" {LIAR_OFF}: alarm edges " + f"{[[t - E for t in ts] for nm, ts in RUNS if nm == LIAR_OFF]}") many = [(nm, ts) for nm, ts in RUNS - if any(v > 1 for v in per_quarter( + if nm != LIAR_OFF and any(v > 1 for v in per_quarter( [t for t in ts if not nm.startswith("T15 x10") or t < F2_FROM]) .values())] check(f"N5: at most one floor-alarm edge per quarter in every run " - f"({len(RUNS)} runs; x10 to E+500): {many}", many == []) + f"({len(RUNS)} runs; x10 to E+500; the cover-off liar apart): " + f"{many}", many == []) print() print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") diff --git a/goodwe_controller/tools/ev18_peak.py b/goodwe_controller/tools/ev18_peak.py index b104d66..9d3f38c 100644 --- a/goodwe_controller/tools/ev18_peak.py +++ b/goodwe_controller/tools/ev18_peak.py @@ -80,10 +80,12 @@ def shape(after, before=PRE_W, at=None): def run(house, *, a=None, b=None, lost=None, car_a=6, phases=1, aim=AIM, mode="manual", dur=None, extra=None, sim=None, soc=None, plug=True, - x=1, mono_x=None, explain_off=False): + x=1, mono_x=None, explain_off=False, latch_off=False, + cover=True): """One run; returns (run, trace). `x`: fake seconds per cycle (wall and monotonic both; `mono_x` sets the monotonic rate apart). `explain_off`: - the car never explains (for the control-identity check).""" + the car never explains, `latch_off`: no contradiction latch (both for the + control-identity check). `cover`: the option `ev_batt_cover`.""" force = {} if a is not None: force["a"] = a @@ -98,6 +100,10 @@ def run(house, *, a=None, b=None, lost=None, car_a=6, phases=1, aim=AIM, orig = c.car_settle if explain_off: c._car_explains_alarm = lambda *a_, **k_: False + if latch_off: + c._car_contradicted = lambda *a_, **k_: False + if not cover: + c.o["ev_batt_cover"] = False if mono_x is not None and mono_x != x: c.car_now = (lambda f=c.car_now: f() * mono_x / x) @@ -197,6 +203,16 @@ def commands(r, tr): return h.hexdigest()[:16] +def energy_gap(at, secs=1): + """The charger's energy entity is missing (unknown) for `secs` from `at`.""" + def on(p, c): + p.ch.no_energy = True + + def off(p, c): + p.ch.no_energy = False + return {at: on, at + secs: off} + + def restart(c): """A restart as the car side sees it: a fresh `car_init` and an empty corroboration history, and no floor alarm standing.""" -- 2.54.0 From ef8c5dcf627ba7ad18bfac14ee2e982dec6e63ae Mon Sep 17 00:00:00 2001 From: ems-agent Date: Thu, 19 Nov 2026 13:02:02 +0100 Subject: [PATCH 08/55] EV-18 review round 3: the DECISIONS line and a comment say what the contradiction latch does Wording only. DECISIONS/EV-04: a contradiction is a meter that answered and fell short (an unknown reading is none), and it grades no alarm while the guard's input keeps the figure. ctl_car.car_cycle: the car-over row keeps the figure only with the cover off. Co-Authored-By: Claude --- goodwe_controller/DECISIONS/EV-04-manual-mode.md | 7 ++++--- goodwe_controller/app/ctl_car.py | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index 3a45fb7..2c2b9e3 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -148,9 +148,10 @@ up to 1.8 kW; the 40 Wh floor fixes that.) batteries (`_car_over_now`), or by the EV-10 test above. A `None` car figure or battery reading explains nothing in that cycle and latches nothing; a car known to draw nothing (fresh, not charging) still grades the house's need. - Owner 2026-11-19: a figure the energy meter contradicted (fresh, charging, - not corroborated) stays untrusted to the quarter's end. After a restart or a - gap the car's earlier energy is not known, so it counts as house. + Owner 2026-11-19: a figure the energy meter contradicted (it answered over a + whole window and fell short; an unknown reading is no contradiction) grades + no alarm to the quarter's end; the guard's input keeps it. After a restart + or a gap the car's earlier energy is not known, so it counts as house. - **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/ctl_car.py b/goodwe_controller/app/ctl_car.py index d3f86a2..479f737 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -355,7 +355,7 @@ class CarMixin: # EV-18 (owner 2026-11-19): a figure the meter contradicted grades no # alarm again in that quarter, not even as our own pause's stand-in. # The alarm decision only: the car's energy count, the guard's input - # (`car_exclude`) and the car-over row keep the figure. + # (`car_exclude`) and, with the cover off, the car-over row keep it. key = None if real_proj is None else real_proj.block_start if key is not None and not own and self._car_contradicted(mono): self._car_contra_block = key -- 2.54.0 From 4950a2374f22828e11e36023dbb6385bb0060f5c Mon Sep 17 00:00:00 2001 From: ems-agent Date: Fri, 20 Nov 2026 20:16:25 +0100 Subject: [PATCH 09/55] EV-19: no floor alarm when the batteries first reach the reserve early in a Manual car session EV-15 rig F-B, reproduced on 43b0db7 (tools/ev19_reserve.py, T1 grid). At the reserve inverter-b goes on following the house, so its output rises in that cycle. The battery reading shows the rise one cycle before the P1 sample does, and EV-18's house figure (held - car + now - min(now, prev)) counted the new battery power as house load. `_car_need_house` latched: one PEAK_GUARD_FLOOR_LIMITED ERROR and goodwe_peak_soc_floor at R+1, red until the guard stopped wanting power. ctl_car._car_explains_alarm: for the house latch only, a reading above both earlier readings counts as house only up to the higher of them. The credit stays the lower of the last two readings. The claim, floor, setpoints and charger writes are unchanged (342 runs, same digests). test_ev19.py: T1-T17, T20, N1-N6 of reports/EV-19-test-plan.md; 49 checks red on 43b0db7, 124 of 124 green here. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-04-manual-mode.md | 7 + goodwe_controller/app/ctl_car.py | 11 +- goodwe_controller/test_ev19.py | 564 +++++++++++++ goodwe_controller/tools/ev19_reserve.py | 752 ++++++++++++++++++ 4 files changed, 1332 insertions(+), 2 deletions(-) create mode 100644 goodwe_controller/test_ev19.py create mode 100644 goodwe_controller/tools/ev19_reserve.py diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index 2c2b9e3..6f0e852 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -152,6 +152,13 @@ up to 1.8 kW; the 40 Wh floor fixes that.) whole window and fell short; an unknown reading is no contradiction) grades no alarm to the quarter's end; the guard's input keeps it. After a restart or a gap the car's earlier energy is not known, so it counts as house. +- **A battery rise is house only once a second reading shows it** (EV-19, EV-15 + rig F-B). At the reserve inverter-b goes on following the house, so its + output rises; the reading shows it one cycle before P1 does, and the house + figure (meter + battery) counted that power as house. `_car_need_house` + latched and the alarm stood. For the house figure, a reading above both + earlier ones counts only up to the higher of them; the credit stays the lower + of the last two readings. - **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/ctl_car.py b/goodwe_controller/app/ctl_car.py index 479f737..da37a70 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -58,7 +58,7 @@ class CarMixin: self.car_over = False # ... held: the card and row say so self._car_over_since = None self._car_over_gone = None - self._car_batt_prev = None + self._car_batt_prev = self._car_batt_prev2 = None self._car_need_real = self._car_need_excl = False # EV-10 latches self._car_need_house = self._car_over_now = False # EV-18 latches self._car_latch_block = None @@ -414,7 +414,14 @@ class CarMixin: when the guard no longer wants power, whatever the cover option says (this runs every cycle). DECISIONS/EV-04-manual-mode.md (EV-18).""" now, prev = self.site_batt_w, self._car_batt_prev + prev2, self._car_batt_prev2 = self._car_batt_prev2, prev self._car_batt_prev = now + # EV-19: the reading can show a rise one cycle before the meter does + # (the batteries pick up the house at the reserve), so a reading above + # both earlier ones is not yet counted as house. + seen = now + if now is not None and prev is not None and prev2 is not None: + seen = min(float(now), max(float(prev), float(prev2))) wants = bool(guard is not None and guard.engaged and guard.blind is None and (guard.wanted_w or 0.0) > 0.0) @@ -436,7 +443,7 @@ class CarMixin: self._car_need_excl = self._car_need_excl or \ peakguard.misses_aim(excl, batt_w=batt, target_w=target_w) self._car_need_house = self._car_need_house or \ - self._car_lands_over(excl, now, batt, target_w) + self._car_lands_over(excl, seen, batt, target_w) if w is None or batt is None or not wants \ or not (guard.saturated or guard.floor_limited): return False diff --git a/goodwe_controller/test_ev19.py b/goodwe_controller/test_ev19.py new file mode 100644 index 0000000..bf4077c --- /dev/null +++ b/goodwe_controller/test_ev19.py @@ -0,0 +1,564 @@ +"""EV-19: no floor alarm when the batteries first reach the peak reserve early +in a Manual car session (EV-15 rig F-B). `python3 -B test_ev19.py` + +The rig: one PEAK_GUARD_FLOOR_LIMITED ERROR, one `goodwe_peak_soc_floor` and +one red sample the moment the batteries reached the reserve, while the excess +was smaller than the car. Reproduced (T1): at the reserve inverter-b goes on +following the house, so its output RISES in that cycle. The battery reading +shows the rise one cycle before the P1 sample does, and EV-18's "house" +(meter + what the batteries give now) counted the new battery power as house +load. That latched `_car_need_house` for the quarter: the alarm stood until +the guard stopped wanting power. Now a rise the reading shows above both +earlier readings is not counted as house until a second reading confirms it. +The credit stays the lower of the last two readings. + +T-ids are the test plan's (reports/EV-19-test-plan.md). "base" is 43b0db7. +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import os +import sys +from datetime import datetime, timedelta, timezone + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import ctl_car, tariff # noqa: E402 +from named_absence import first, nth, present # noqa: E402 +import ev19_reserve as V # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +AIM = V.AIM +CAR = V.CAR + +# =========================================================================== # +print("1. UNIT: car_cycle in the reserve cycle (a real `_carq`)") +# =========================================================================== # +BS = datetime(2026, 11, 20, 20, 30, tzinfo=timezone.utc) # a quarter edge + + +class _Car(ctl_car.CarMixin): + def __init__(self): + self.o = {"ev_batt_cover": True} + self.w = CAR + self._now = 0.0 + self.site_batt_w, self.site_rating_w = 0.0, 9600.0 + self.store = type("S", (), {"data": {}, "set": lambda s, k, v: 0})() + self.car_init({}, self.store) + + def car_now(self): + return self._now + + def car_alarm_w(self): + return self.w + + class car: # noqa: N801 + @staticmethod + def status(*_a): + return "charging" + + +class _G: + """Floor-limited, the floor leaves nothing (floor_w 0), wants power.""" + floor_limited, saturated = True, False + floor_w, able_w, ceiling_w = 0.0, None, AIM + 50.0 + engaged, blind, wanted_w, within_aim = True, None, 300.0, False + + +def urun(secs, grid, batt, w=lambda t: CAR): + """`car_cycle` once per second of `secs` (seconds from the edge). `grid(t)` + is the meter, `batt(t)` the site battery reading. {t: car_explains}.""" + c = _Car() + done, out = {}, {} + for t in secs: + q = t // 900 + bs, el = BS + timedelta(seconds=900 * q), t - 900 * q + g = float(grid(t)) + d = done.get(bs, g * el) + p = tariff.Projection( + projected_w=(d + g * (900 - el)) / 900.0, + elapsed_w=(d / el if el else g), elapsed_s=float(el), + covered_frac=1.0, complete=False, block_start=bs, held_w=g) + done[bs] = d + g + c._now = 10000.0 + t + c.w, c.site_batt_w = w(t), batt(t) + c.car_cycle(p, _G(), AIM, None) + out[t] = c.car_explains + return out + + +def run_of(d, t0, t1): + return [d[t] for t in sorted(d) if t0 <= t <= t1] + + +def rise(at, lo, hi): + """A battery reading that steps from `lo` to `hi` at `at`.""" + return lambda t: lo if t < at else hi + + +def meter(house, b, lag=1): + """The P1 figure: house + car - what the batteries gave `lag` cycles ago + (the reading leads the meter by that much).""" + return lambda t: house + CAR - b(t - lag) + + +HB = AIM + 520.0 - CAR # F-B: house + car at batteries 0 W = aim + 520 +b2 = rise(1, 0.0, 4600.0) +u2 = urun(range(-5, 61), meter(HB, b2), b2) +print(f" T2 unit E-1..E+3: {run_of(u2, -1, 3)}") +check("T2 unit: b starts following the house at the reserve (0 -> 4 600 W) " + "and the reading shows it one cycle before the meter: the car explains " + "every cycle, the rise cycle E+1 among them (base: not from E+1)", + all(run_of(u2, 0, 60)) and len(run_of(u2, 0, 60)) == 61) +u2s = urun(range(-5, 61), meter(HB, b2, lag=0), b2) +check("T2 unit: the same rise with the meter in step: explained every cycle", + all(run_of(u2s, 0, 60)) and len(run_of(u2s, 0, 60)) == 61) + +# T4: the landing without the car at aim + 9 / + 11 W in the rise cycle. The +# rise is at the edge, so with the lower reading credited (0 W) the house +# alone lands at exactly `house`. +b4 = rise(0, 0.0, 800.0) +u409 = urun(range(-3, 10), meter(AIM + 9.0, b4), b4) +u411 = urun(range(-3, 10), meter(AIM + 11.0, b4), b4) +print(f" T4 unit +9 {run_of(u409, 0, 3)} +11 {run_of(u411, 0, 3)}") +check("T4 unit: the house alone at aim + 9 W in the rise cycle: the car " + "explains from E+0 (base: no)", all(run_of(u409, 0, 9)) + and len(run_of(u409, 0, 9)) == 10) +check("T4 unit: at aim + 11 W it does not, from E+0 (as base)", + not any(run_of(u411, 0, 9)) and len(run_of(u411, 0, 9)) == 10) + +# N6 / T7(a): an unknown reading credits nothing; the lower reading is +# credited, not the higher or the last known one. +b7 = lambda t: None if t == 1 else b2(t) # noqa: E731 +u7 = urun(range(-5, 30), meter(HB, b2), b7) +check("T7(a) unit: the battery reading unknown in the rise cycle: nothing " + "explained in that cycle (no last-known W), explained from the next", + u7.get(1) is False and u7.get(0) is True and all(run_of(u7, 2, 29))) +u6 = urun(range(-5, 30), meter(AIM + 11.0 + 400.0, lambda t: 400.0, lag=0), + lambda t: 800.0 if t == 3 else 400.0) +check("N6 unit: b at 400 W, the house alone with it at aim + 11 W, one " + "reading of 800 W at E+3: not explained in any cycle", + not any(run_of(u6, 0, 29))) +# The rise counts as house once a second reading confirms it: b steps to +# 800 W and the meter, one cycle late, shows a house of aim + 811 W (the +# house steps with it), so with b's 800 W the house alone misses by 11 W. +b8 = rise(5, 0.0, 800.0) +u8 = urun(range(0, 30), lambda t: (AIM - 500.0 if t < 5 else AIM + 811.0) + + CAR - b8(t - 1), b8) +print(f" N6 unit house step with a rise E+4..E+8: {run_of(u8, 4, 8)}") +check("N6 unit: a house step that comes with a battery rise is latched at " + "most one cycle after the rise (E+6), and stays latched", + all(run_of(u8, 0, 4)) and not any(run_of(u8, 6, 29))) + +# =========================================================================== # +print("\n2. THE REAL CONTROLLER AT THE RESERVE (N=2, tools/ev19_reserve.py)") +# =========================================================================== # +JOBS = V.jobs() +RES = V.run_many(JOBS) + + +def res(name): + return RES[name] + + +def trusted(x): + return x["w"] is not None and x["w"] > 0.0 and not x["contra"] + + +def bad(x): + return bool(x["alarm"] or x["red"] or x["err"]) + + +def hits(r, t0=-10, t1=60): + """T1's reproduction: an alarm, red sample or ERROR in R-10..R+60 in a + cycle where the car figure is trusted (every T1 shape lands under the aim + without the car, so the car explains there).""" + return [int(x["t"] - r.R) for x in r.win(t0, t1) if bad(x) and trusted(x)] + + +def show(name): + r = res(name) + print(f" {name}: alarms {r.rel_alarms()} edges {r.edges()} errors " + f"{r.errors()} red {len(r.red())} s cmd {r.cmd}") + + +# Measured on base 43b0db7 with this file's own runs: the seconds from R of +# goodwe_peak_soc_floor in the honest shapes, which must not come later now. +BASE_ALARMS = { + "T4 +11 manual": [0, 857], "T5 t1 manual": [2], "T5 t4 manual": [11], + "T5 tau5 manual": [2], "T6 step R+0 manual": [2], + "T6 step R+1 manual": [2], "T6 step R+5 manual": [6], + "T7(a) T5": [2], "T7(b) T5": [2], "T8(c) frozen, the car stops": [2], + "T9(a) T5 b lost at R": [2], "T9(a) T5 b lost at R-1": [2], + "T9(b) T5 P1 5 s late at R": [5], "T10 T5 twin": [2], + "T10 T5 restart R-2": [2], "T10 T5 restart R+2": [2], + "T11 T5 R=E-1": [2], "T11 T5 R=E+0": [0, 2], "T11 T5 R=E+1": [0, 2], + "T11 T5 R=E+43": [2], "T12 T5 1->3 at R-15": [2], + "T12 T5 1->3 at R+5": [2], "T13(a) draws 100 W manual": [0, 857], + "T14(c) N=1 T5": [2], "T15 honest manual": [13], + "T16 x10 T5 manual": [20], "T16 x10 T6 manual": [20], + "T16 mono1 T5 manual": [20], "T16 mono1 T6 manual": [20], + "T16 x10 T11 T5 R=E-10": [20], "T16 x10 T11 T5 R=E+0": [0, 20], + "T16 x10 T11 T5 R=E+10": [0, 20], "T16 x10 T11 T5 R=E+40": [20], + "T16 mono1 T11 T5 R=E-10": [20], "T16 mono1 T11 T5 R=E+0": [0, 20], + "T16 mono1 T11 T5 R=E+10": [0, 20], "T16 mono1 T11 T5 R=E+40": [20], + "T16 mono1 T3 t1 bw=0": [600], "T16 mono1 T3 t1 bw=2000": [700], + "T16 mono1 T3 t1 bw=4250": [800], "T16 mono1 T3 t4 bw=0": [600], + "T16 mono1 T3 t4 bw=2000": [700], "T16 mono1 T3 t4 bw=4250": [800], +} +# The T1 cells that reproduce F-B on base (G0): b following the house from R. +BASE_REPRO = [f"T1 core bw={bw} t2 rp={rp}" for bw in (0, 400, 800) + for rp in (30, 100, 110, 180, 600)] + [ + "T1 d: x10 wall+mono t2 bw=1200", "T1 d: x10 wall, mono x1 t2 bw=1200"] + + +def as_base(k): + """The same alarm seconds as base.""" + return res(k).rel_alarms() == BASE_ALARMS[k] + +# --- T1: the reproduction grid ------------------------------------------------ # +T1 = sorted(k for k in JOBS if k.startswith("T1 ")) +C5 = [k for k in T1 if k.startswith("T1 b: energy")] +rep = {k: hits(res(k)) for k in T1} +print(f" T1 cells {len(T1)}; reproducing on this tree: " + f"{sorted(k for k in T1 if rep[k])}") +check("T1: no grid cell reproduces F-B: no notice, ERROR or red sample in " + "R-10..R+60 while the car figure is trusted (base: the " + f"{len(BASE_REPRO)} tau2 cells with b at 0-800 W at R)", + not [k for k in T1 if rep[k]]) +for k in C5: + show(k) +check("T1 C5 cells (the energy meter late or never stepping): the figure is " + "untrusted (contradicted or unknown) wherever the alarm stands, as EV-18 " + "Expected 5 wants", all(not trusted(x) for k in C5 + for x in res(k).win(-10, 60) if bad(x))) + +# --- T2: THE red-before test -------------------------------------------------- # +T2 = BASE_REPRO +for k in T2: + r = res(k) + lim = [x for x in r.win(0, 60) if x["floor_lim"]] + check(f"T2 {k[3:]}: no notice, no ERROR, no red sample R-60..R+900; the " + f"car explains every floor-limited cycle of R..R+60", + r.quiet(-60, 900) and bool(lim) and all(x["explains"] for x in lim)) +check("T2 PRECONDITION: every reproducing cell is in the grid (b at 0, 400, " + "800 W x 5 plug-in times; x10 and mono x1 with b at 1 200 W)", + len(T2) == 17 and all(k in RES for k in T2)) +r2 = res("T1 core bw=0 t2 rp=180") +x1 = r2.at(1) +check("T2 PRECONDITION: in the rise cycle the reading shows b's 4 600 W, the " + "guard is floor-limited and wants power", + present(x1) and x1["batt"] == 4600.0 and x1["floor_lim"] + and x1["wants"]) + +# --- T3: the battery W sweep --------------------------------------------------- # +T3 = sorted(k for k in JOBS if k.startswith("T3 ")) +loud = [k for k in T3 if not res(k).quiet(-60, 900)] +print(f" T3 cells {len(T3)}, with an alarm or red sample: {loud}") +check("T3: tau1 and tau2, b at R 0..4 600 W in 200 W steps and 9 600 W " + "(tau5): no alarm and no red sample in any cell", loud == []) + +# --- T4 controller ------------------------------------------------------------- # +for k in ("T4 +9 manual", "T4 +11 manual", "T4 +11 off"): + show(k) +check("T4: the house alone at aim + 9 W, b following the house from R: no " + "alarm (base: R+1)", res("T4 +9 manual").quiet(-60, 900)) +check("T4: at aim + 11 W the alarm in the same cycle as base and as Off " + "(R+0)", as_base("T4 +11 manual") + and res("T4 +11 manual").rel_alarms()[:1] + == res("T4 +11 off").rel_alarms()[:1] == [0]) + + +# --- T5 / T6: honest alarms ---------------------------------------------------- # +def same_as_off(k): + on, off = res(f"{k} manual"), res(f"{k} off") + show(f"{k} manual") + show(f"{k} off") + a = on.rel_alarms() + return (bool(a) and a == off.rel_alarms() + and on.errors() == off.errors()) + + +for k in ("T5 t1", "T5 t4", "T5 tau5"): + check(f"{k}: the excess is more than the car: PEAK_GUARD_FLOOR_LIMITED, " + f"the ERROR and the notice at the same second as Off and as base", + same_as_off(k) and as_base(f"{k} manual")) + check(f"{k}: the car explains no cycle", + not any(x["explains"] for x in res(f"{k} manual").tr)) +for n in (0, 1, 5): + k = f"T6 step R+{n}" + show(f"{k} manual") + check(f"{k}: the house steps to aim + 1 900 W at R+{n}: the alarm and " + f"the ERROR at the same second as base, R+{BASE_ALARMS[k + ' manual'][0]}" + f" (no grace, no hold; Off alarms from R+0, where the car explains)", + as_base(f"{k} manual") and res(f"{k} manual").errors() + == BASE_ALARMS[f"{k} manual"]) + + +# --- T7: unknown values -------------------------------------------------------- # +def only_while_unknown(r, t0=-60, t1=900): + """Every alarm / red cycle has an untrusted car figure in it or in the + cycle before (the alarm clears within 1 cycle of the first trusted one).""" + prev = None + for x in r.win(t0, t1): + if bad(x) and trusted(x) and (prev is None or trusted(prev)): + return False + prev = x + return True + + +show("T7(a) T2") +check("T7(a) T2: inverter-a's reading unknown at R and R+1: no alarm", + res("T7(a) T2").quiet(-60, 900)) +check("T7(a) T5: the alarm at the same second as base and as Off (the " + "guard grades nothing without the reading)", as_base("T7(a) T5") + and res("T7(a) T5").rel_alarms() == res("T7(a) T5 off").rel_alarms()) +show("T7(b) T2") +check("T7(b) T2: the charger unavailable at R: an alarm only while the " + "figure is unknown, cleared within 1 cycle of the first trusted one", + only_while_unknown(res("T7(b) T2"))) +check("T7(b) T5: the alarm at the same second as base and as Off", + as_base("T7(b) T5") + and res("T7(b) T5").rel_alarms() == res("T7(b) T5 off").rel_alarms()) + +# --- T8: a stale car figure ---------------------------------------------------- # +r8a = res("T8(a) Off 120 s, Manual R-5") +show("T8(a) Off 120 s, Manual R-5") +check("T8(a): nothing before Manual is trusted (car_alarm_w None)", + all(x["w"] is None for x in r8a.tr if x["t"] < r8a.R - 5)) +check("T8(a): after Manual, as T2: no alarm R-60..R+900", + r8a.quiet(-60, 900)) +r8b = res("T8(b) stale R-5..R+20") +show("T8(b) stale R-5..R+20") +check("T8(b) PRECONDITION: the figure goes untrusted (older than 15 s)", + any(x["w"] is None for x in r8b.win(0, 25))) +check("T8(b): the alarm only while the figure is stale, cleared within 1 " + "cycle of the first fresh one", only_while_unknown(r8b)) +r8c, r8co = res("T8(c) frozen, the car stops"), res("T8(c) off") +show("T8(c) frozen, the car stops") +a8 = nth(r8c.rel_alarms(), 0) +untr = first(int(x["t"] - r8c.R) for x in r8c.tr + if x["t"] >= r8c.R - 30 and not trusted(x)) +check("T8(c): the alarm at base's second, as Off, within 114 s of the stop", + present(a8) and a8 <= -30 + 114 + and as_base("T8(c) frozen, the car stops") + and r8c.rel_alarms() == r8co.rel_alarms()) +check("T8(c): never explained after the figure goes untrusted", + present(untr) and not any(x["explains"] for x in r8c.tr + if x["t"] >= r8c.R + untr)) + +# --- T9: comms ------------------------------------------------------------------ # +for nm in ("T2", "T5"): + for k in (f"T9(a) {nm} b lost at R", f"T9(a) {nm} b lost at R-1", + f"T9(b) {nm} P1 5 s late at R"): + show(k) + r = res(k) + if nm == "T2": + check(f"{k}: no alarm edge", r.edges() == []) + else: + check(f"{k}: the alarm at the base second " + f"(R+{BASE_ALARMS[k][0]})", as_base(k)) + +# --- T10: a restart ------------------------------------------------------------ # +for nm in ("T2", "T5"): + tw = res(f"T10 {nm} twin") + for k in (-2, 2): + r = res(f"T10 {nm} restart R{k:+d}") + show(f"T10 {nm} restart R{k:+d}") + if nm == "T2": + check(f"T10 T2 restart at R{k:+d}: no notice, no red sample, as " + f"the unrestarted twin", r.quiet(-60, 900) + and tw.quiet(-60, 900)) + else: + check(f"T10 T5 restart at R{k:+d}: the alarm at the base second " + f"and the twin's, red as the twin", + as_base(f"T10 T5 restart R{k:+d}") and as_base("T10 T5 twin") + and len(r.red()) == len(tw.red())) + +# --- T11: the quarter edge ------------------------------------------------------ # +for rr in (-1, 0, 1, 43): + r = res(f"T11 T2 R=E{rr:+d}") + show(f"T11 T2 R=E{rr:+d}") + wa = [(int(x["t"] - r.E), x["within_aim"]) for x in r.tr + if r.E - 1 <= x["t"] <= r.E] + print(f" T11 T2 R=E{rr:+d}: within_aim at E-1/E+0 {wa} (F1, not " + f"asserted)") + check(f"T11 T2 R=E{rr:+d}: no alarm across the edge", r.quiet(-60, 900)) + check(f"T11 T5 R=E{rr:+d}: the alarm at the same seconds as base and " + f"as Off", as_base(f"T11 T5 R=E{rr:+d}") + and res(f"T11 T5 R=E{rr:+d}").rel_alarms() + == res(f"T11 T5 R=E{rr:+d} off").rel_alarms()) +pre = res("T11 C4 T2 R=E+1") +show("T11 C4 T2 R=E+1") +wa = [(int(x["t"] - pre.E), x["within_aim"]) for x in pre.tr + if pre.E - 1 <= x["t"] <= pre.E] +print(f" T11 C4: within_aim at E-1/E+0 {wa} (F1, not asserted)") +check("T11 C4 PRECONDITION: the guard wants power in the last 60 s of the " + "old quarter (house 13 350 W all along, car 1 380 W)", + all(x["wants"] for x in pre.tr if pre.E - 60 <= x["t"] < pre.E)) +sat = [x for x in pre.win(-60, -1) if x["red"]] +print(f" T11 C4: red before R {[int(x['t'] - pre.R) for x in sat]} (near " + f"the old quarter's end, the guard saturated: SAFETY-81's row)") +check("T11 C4: SAFETY-126's latch carried over the edge, the reserve at " + "E+1: no floor notice or ERROR R-60..R+900, no red sample from R; " + "before R red only where the guard is saturated (not the floor alarm)", + pre.quiet(0, 900) and not [t for t in pre.rel_alarms() if t >= -60] + and all(x["lim"] and not x["floor_lim"] and not x["alarm"] + for x in sat)) + +# --- T12: our own phase change -------------------------------------------------- # +for k in (-15, 5): + r = res(f"T12 T2 1->3 at R{k:+d}") + show(f"T12 T2 1->3 at R{k:+d}") + check(f"T12 T2, 1->3 at R{k:+d}: no alarm during our own pause or after", + r.quiet(-60, 900)) + on, off = res(f"T12 T5 1->3 at R{k:+d}"), res(f"T12 T5 1->3 at R{k:+d} off") + show(f"T12 T5 1->3 at R{k:+d}") + a, ao = nth(on.rel_alarms(), 0), nth(off.rel_alarms(), 0) + check(f"T12 T5, 1->3 at R{k:+d}: the alarm at base's second, no later " + f"than Off's and within OWN_PAUSE_MAX_S " + f"({ctl_car.OWN_PAUSE_MAX_S:.0f} s) of the request", + present(a, ao) and a <= ao and as_base(f"T12 T5 1->3 at R{k:+d}") + and a <= max(k, 0) + ctl_car.OWN_PAUSE_MAX_S) + +# --- T13: a wrong charger reply ------------------------------------------------- # +r13 = res("T13(a) draws 400 W manual") +show("T13(a) draws 400 W manual") +check("T13(a) 400 W: the energy meter never contradicts a 1 380 W figure " + "when 400 W is drawn (CORR_RATIO 0.5 and its slack; EV-18 T9(b)), so " + "nothing is uncorroborated and the figure explains; base's R+1 alarm " + "was F-B", not any(x["contra"] for x in r13.tr) + and all(x["w"] == CAR for x in r13.win(-60, 60))) +r13c = res("T13(a) draws 100 W manual") +show("T13(a) draws 100 W manual") +show("T13(a) draws 100 W off") +c0 = first(x["t"] for x in r13c.tr if x["contra"]) +a13 = nth(r13c.rel_alarms(), 0) +check("T13(a) 100 W PRECONDITION: the energy meter contradicts the figure " + "within 104 + 10 s of the plug-in (R-180)", + present(c0) and c0 <= r13c.R - 180 + 114) +check("T13(a) 100 W: the alarm at base's second and Off's, and never " + "explained after the contradiction in that quarter", + present(a13) and as_base("T13(a) draws 100 W manual") + and r13c.rel_alarms() == res("T13(a) draws 100 W off").rel_alarms() + and not any(x["explains"] for x in r13c.tr + if present(c0) and x["t"] >= c0 + and x["block"] == r13c.at(0)["block"])) +for k in ("T13(b) the write ignored, 0 A", "T14(a) 0 W in C", + "T14(a) idle B"): + show(f"{k} manual") + check(f"{k}: the car at 0 W explains nothing: the alarm as Off", + same_as_off(k) and not any( + x["explains"] for x in res(f"{k} manual").tr)) + +# --- T14: configuration -------------------------------------------------------- # +show("T14(b) ev_charger off") +check("T14(b) ev_charger off: no explanation, the alarm as Off", + res("T14(b) ev_charger off").rel_alarms() + == res("T14(b) off").rel_alarms() != [] + and not any(x["explains"] for x in res("T14(b) ev_charger off").tr)) +for tj in ("t1", "t4"): + show(f"T14(c) N=1 anchor {tj}") + check(f"T14(c) N=1 anchor {tj}: no alarm", + res(f"T14(c) N=1 anchor {tj}").quiet(-60, 900)) +check("T14(c) N=1 T5: the alarm at the same second as base and as Off", + as_base("T14(c) N=1 T5") and res("T14(c) N=1 T5").rel_alarms() + == res("T14(c) N=1 T5 off").rel_alarms()) + +# --- T15: one battery first ----------------------------------------------------- # +for k in ("T15 anchor manual", "T15 honest manual", "T15 honest off"): + show(k) +check("T15 anchor: a at the reserve at R, b at R+360: no alarm", + res("T15 anchor manual").quiet(-60, 900)) +check("T15 honest (house 19 000 W): the alarm after ALARM_HOLD_S at the " + "base second (R+13; Off R+11, as base)", as_base("T15 honest manual")) + +# --- T16: x10 -------------------------------------------------------------------- # +for xn in ("x10", "mono1"): + r = res(f"T16 {xn} T2") + show(f"T16 {xn} T2") + check(f"T16 {xn} T2 PRECONDITION: the rise cycle reads b's 4 600 W", + present(r.at(10)) and r.at(10)["batt"] == 4600.0) + check(f"T16 {xn} T2: no alarm (base: R+10, 10 red cycles)", + r.quiet(-60, 900)) + t3 = sorted(k for k in JOBS if k.startswith(f"T16 {xn} T3 ")) + print(f" T16 {xn} T3 alarms " + f"{[(k[10:], res(k).rel_alarms()) for k in t3]}") + check(f"T16 {xn} T3 ({len(t3)} cells): no alarm R-60..R+300", + all(res(k).quiet(-60, 300) for k in t3)) + # mono x1 / wall x10: the car's energy is counted on the monotonic clock, + # a tenth of the wall's, so its share of the quarter is short and the + # house latch sets late in the quarter (EV-18 F2, out of scope), as base. + check(f"T16 {xn} T3: any later alarm at base's second (EV-18 F2)", + all(as_base(k) if k in BASE_ALARMS else res(k).quiet(-60, 900) + for k in t3)) + for k in ("T5", "T6"): + show(f"T16 {xn} {k} manual") + check(f"T16 {xn} {k}: the alarm at the base second", + as_base(f"T16 {xn} {k} manual")) + check(f"T16 {xn} T7(b) T2: an alarm only while the figure is unknown", + only_while_unknown(res(f"T16 {xn} T7(b) T2"))) + for rr in (-10, 0, 10, 40): + check(f"T16 {xn} T11 T2 R=E{rr:+d}: no alarm", + res(f"T16 {xn} T11 T2 R=E{rr:+d}").quiet(-60, 900)) + check(f"T16 {xn} T11 T5 R=E{rr:+d}: the alarm at the base seconds", + as_base(f"T16 {xn} T11 T5 R=E{rr:+d}")) + +# --- T17: no flicker -------------------------------------------------------------- # +r17 = res("T17 flicker") +print(f" T17 alarm edges per quarter {r17.edges_per_quarter()}") +check("T17: the house alone straddles aim + 10 W, the batteries cross the " + "reserve 3 times: at most one alarm edge per quarter", + all(v <= 1 for v in r17.edges_per_quarter().values())) + +# --- N2: the car explains only with a trusted, non-zero figure ----------------- # +bad2 = sorted(k for k, r in RES.items() + if any(x["explains"] and not trusted(x) for x in r.tr)) +check(f"N2: car_explains never True with car_alarm_w None, 0 W or " + f"contradicted, in any of the {len(RES)} runs: {bad2}", bad2 == []) + +for k in ("N2 no energy entity", "N2 reports 11 kW at 6 A"): + show(f"{k} manual") + check(f"{k}: the figure is not trusted for the alarm (no corroboration, " + f"or capped by the read-back): nothing explained, the alarm as Off", + same_as_off(k) and not any( + x["explains"] for x in res(f"{k} manual").tr)) +check("N2 PRECONDITION: the charger without an energy entity reports a " + "fresh 1 380 W", all(x["car_raw"] == CAR for x in + res("N2 no energy entity manual").win(-60, 60))) + +# --- N4 / T20: no control change --------------------------------------------- # +for nm in ("T2", "T5"): + a = res("T1 core bw=0 t2 rp=180") if nm == "T2" else res("T10 T5 twin") + check(f"N4 {nm}: the claim, the floor, the setpoints and the charger " + f"writes are those of the same run with the car never explaining", + a.cmd == res(f"N4 {nm} explain off").cmd) + +# --- N5: at most one floor-alarm edge per quarter ------------------------------ # +# Base 43b0db7 has 2 edges in the first quarter of these runs: the guard lets +# go for one cycle at R+1 (the battery reads 0 W, the meter does not show it +# yet), in Off and in the C5 cells too. Not EV-19's; head must not add one. +BASE_TWO = ["T1 b: energy first step late", "T1 b: energy never steps", + "T11 T5 R=E+0", "T11 T5 R=E+0 off", "T11 T5 R=E+1", + "T11 T5 R=E+1 off", "T16 mono1 T11 T5 R=E+0", + "T16 mono1 T11 T5 R=E+10", "T16 mono1 T6 off", + "T16 x10 T11 T5 R=E+0", "T16 x10 T11 T5 R=E+10", "T16 x10 T6 off", + "T6 step R+0 off", "T6 step R+1 off", "T6 step R+5 off"] +many = sorted(k for k, r in RES.items() + if any(v > (2 if k in BASE_TWO and q == 0 else 1) + for q, v in r.edges_per_quarter().items())) +check(f"N5: at most one floor-alarm edge per quarter in every run, and no " + f"more than base where base has two ({len(RES)} runs): {many}", + many == []) + +print() +print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") +sys.exit(1 if fails else 0) diff --git a/goodwe_controller/tools/ev19_reserve.py b/goodwe_controller/tools/ev19_reserve.py new file mode 100644 index 0000000..319c5b4 --- /dev/null +++ b/goodwe_controller/tools/ev19_reserve.py @@ -0,0 +1,752 @@ +"""EV-19: the real Controller, N=2, when the batteries first reach the peak +reserve `R` early in a Manual car session (EV-15 F-B). Used by test_ev19.py. + + python3 tools/ev19_reserve.py # the T1 grid, one row per cell + +The units stand at 21 % and give `bw` W (`force`) until `R`, where both read +19 %; after `R` they follow the trajectory `traj`. The house is set so that +house + car with the batteries at 0 W lands at aim + `over` W (F-B: +520 W, +less than the 1 380 W car). Manual is set, then the car plugs in, `rp` s +before `R`. The run starts `E` s before a quarter edge (rig.BASE moved back), +so `R = E + r_rel`. One dict per cycle, taken after it. + +Trajectories after R: t1 both 0 W; t2 a 0 W, b follows the house (the loop +below the reserve covers house + car, up to b's rating); t3 both ramp to 0 W +over 3 cycles; t4 as t1, but every battery reading is 10 s old (the rig reads +battery W every 10 fake s, P1 every 5) while P1 is fresh; t4r as t1, but P1 +is 5 s late while the battery reading is fresh. +""" + +import hashlib +import os +import sys +from datetime import timedelta + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import ev04_peak as P # noqa: E402 +import ev18_peak as H # noqa: E402 +import opt11_identity as rig # noqa: E402 +import safety81_sim as s81 # noqa: E402 +from app import peakguard # noqa: E402 +from chargersim import SimCharger # noqa: E402 + +AIM = H.AIM +CAR = 1380.0 +FLOOR = H.FLOOR +RATE = {"a": 5000.0, "b": 4600.0} +OPTS = H.OPTS +OPTS1 = {"peak_soc_floor": 20, "inverters": [OPTS["inverters"][0]]} + + +class Meter(SimCharger): + """A charger whose energy meter shows no 10 Wh step until `hold_until` + (sim seconds; None: always live, float('inf'): never).""" + + hold_until = None + _held = None + + def _build(self): + if self.hold_until is None or self.t >= self.hold_until: + self._held = None + return super()._build() + if self._held is None: + self._held = self.kwh + keep, self.kwh = self.kwh, self._held + try: + return super()._build() + finally: + self.kwh = keep + + +class Draw(Meter): + """A charger that draws `real_w` while charging and reports `say_w` + (as test_ev18's). `c_at_0`: it stays in mode3 C while drawing 0 W.""" + + def __init__(self, real_w, say_w, c_at_0=False, **kw): + super().__init__(**kw) + self.real_w, self.say_w, self.c_at_0 = real_w, say_w, c_at_0 + + def target_w(self): + if super().target_w() <= 0.0: + return 0.0 + return self.real_w + + def tick(self, seconds=1.0): + super().tick(seconds) + if self.c_at_0 and self.state == "B" and not self.full: + self.state = "C" + + def _build(self): + keep, self._frozen_w = self._frozen_w, self.say_w + try: + return super()._build() + finally: + self._frozen_w = keep + + +class Plant(H.Plant): + """`batt_lag`: every battery reading is that many s old. `p1_lag` with + `p1_from`: P1 that many s late from that second on.""" + + batt_lag = 0.0 + p1_lag = 0.0 + p1_from = 0.0 + house = None + + def batt_of(self, u, at): + f = self.force.get(u) + if f is not None: + return float(f(at, self)) + return P.CarPlantN.batt_of(self, u, at) + + def grid(self, at): + if self.p1_lag and at >= self.p1_from: + at = at - self.p1_lag + return super().grid(at) + + async def number(self, e, invert=False): + for u, secs in self.lost.items(): + if e == "sensor.batt_" + u and int(self.t) in secs: + return None + if self.batt_lag and e.startswith("sensor.batt_") \ + and e[-1] in self.socs: + return self.batt_of(e[-1], self.t - self.batt_lag) + return await P.CarPlantN.number(self, e, invert) + + +def split(bw, units="ab"): + """`bw` over the units, each capped at its rating.""" + if len(units) == 1: + return {units: min(bw, RATE[units])} + a = min(RATE["a"], bw / 2.0) + b = min(RATE["b"], bw - a) + a = min(RATE["a"], bw - b) + return {"a": a, "b": b} + + +def traj_fn(u, traj, before, R, house, step=1): + """Unit `u`'s W at time `at`: `before` until the first cycle after R + (R + `step`), then the trajectory. P1 is sampled 0.3 s before each cycle, + so the battery reading shows a change one cycle before the meter does.""" + def f(at, plant): + if at < R + step: + return before + if traj in ("t1", "t4", "t4r"): + return 0.0 + if traj == "t2": + if u == "a": + return 0.0 + return min(RATE["b"], house(at) + plant.ch.power_w) + if traj == "t3": + k = int((at - R) // step) + return before * max(0.0, (3 - k) / 3.0) + if traj == "keep": + return before + raise ValueError(traj) + return f + + +def run(*, bw=4250.0, traj="t1", rp=180, r_rel=43, order="manual", + energy="ok", x=1, mono_x=None, aim=AIM, over=520.0, house_w=None, + house_fn=None, car_a=6, n=2, extra=None, rel=None, lost=None, + after=900, + soc_after=None, soc0=21.0, mode="manual", sim=None, + explain_off=False, latch_off=False, force=None, plug_at=None, + man_at=None, opts=None, pre_w=H.PRE_W): + """One run; returns (run, trace, meta). `over`: house + car at batteries + 0 W lands at aim + `over` W (ignored with `house_w`). `order`: 'manual' + (Manual at plug-in - 3 s), 'plug' (plug-in at R-185, Manual at R-180), + 'off120' (plug-in and charging in Off from R-180, Manual at R-60). + `energy`: 'ok', 'late' (first 10 Wh step at plug-in + 150 s), 'never'. + `mode`: 'manual' or 'off' (Off throughout: the base for honest alarms). + `house_fn`: fn(t, R) for the house after the step. `extra`: events at + run seconds, `rel`: at seconds from R. `lost`: {unit: seconds from R}. + `plug_at` / `man_at`: plug-in / Manual at these seconds from R (override + `order`). `force`: {unit: fn(at, plant) or None (the unit obeys)}. + `opts`: added to the options. `pre_w`: the house before its step.""" + units = "ab" if n == 2 else "a" + step = int(x) + if order == "plug": + lead = 185 + elif order == "off120": + lead = 180 + else: + lead = rp + 3 + if plug_at is not None or man_at is not None: + lead = -min(v for v in (plug_at, man_at) if v is not None) + E = 150 + while E + r_rel - lead - 2 * step < 10: + E += 150 + E = int(-(-E // step) * step) + R = E + r_rel + if x != 1: + R = int(-(-R // step) * step) + hw = (aim + over - CAR) if house_w is None else house_w + t_house = min(E - 120, R - lead - step) + if x != 1: + t_house = int(t_house // step * step) + + def house(t): + if t < t_house: + return pre_w + if house_fn is not None: + return house_fn(t, R) + return hw + + sp = split(bw, units) + frc = {u: traj_fn(u, traj, sp[u], R, house, step) for u in units} + frc.update(force or {}) + soc_after = soc_after or {u: 19.0 for u in units} + lagb = 10.0 if traj == "t4" else 0.0 + cls = type("Plant", (Plant,), { + "force": frc, "batt_lag": lagb, + "lost": {u: {R + k for k in v} for u, v in (lost or {}).items()}, + "p1_lag": 5.0 if traj == "t4r" else 0.0, "p1_from": float(R)}) + + s = sim or Meter(setpoint_a=car_a) + if energy == "never": + s.hold_until = float("inf") + if x != 1: + tick = s.tick + s.tick = lambda secs=1.0: tick(secs * x) + + if order == "plug": + t_plug, t_man = R - 185, R - 180 + elif order == "off120": + t_plug, t_man = R - 180, R - 60 + else: + t_plug, t_man = R - rp, R - rp - 3 + if plug_at is not None: + t_plug = R + plug_at + if man_at is not None: + t_man = R + man_at + if x != 1: + t_plug = int(t_plug // step * step) + t_man = int(t_man // step * step) + if t_man == t_plug and order != "plug": + t_man -= step + + tr = [] + n_err = [len(H.ERR.rec)] + + def hook(plant, c): + orig = c.car_settle + if explain_off: + c._car_explains_alarm = lambda *a_, **k_: False + if latch_off: + c._car_contradicted = lambda *a_, **k_: False + if mono_x is not None and mono_x != x: + c.car_now = (lambda f=c.car_now: f() * mono_x / x) + + async def settle(): + await orig() + g = c.peak_guard + red = [r_["id"] for r_ in c.checks() + if r_["ok"] is False and not r_["warn"] + and r_["id"] == "peak_guard"] + errs = [m for m in H.ERR.rec[n_err[0]:] + if "may not draw the battery lower" in m] + n_err[0] = len(H.ERR.rec) + cl = peakguard.claim(g) if g is not None else None + mono = c.car_now() + tr.append({ + "t": plant.t, "explains": c.car_explains, + "lim": bool(g is not None and (g.floor_limited + or g.saturated)), + "floor_lim": bool(g is not None and g.floor_limited), + "within_aim": bool(g is not None and g.within_aim), + "wants": bool(g is not None and g.engaged + and (g.wanted_w or 0.0) > 0.0), + "wanted": None if g is None else g.wanted_w, + "target": None if g is None else g.target_w, + "alarm": c._peak_floor_limited, "red": red, "err": errs, + "w": c.car_alarm_w(), "car_raw": c.car.car_w(mono), + "batt": c.site_batt_w, + "true_batt": plant.batt(plant.t), + "need_real": c._car_need_real, "need_excl": c._car_need_excl, + "need_house": c._car_need_house, "over_now": c._car_over_now, + "contra": c._car_contra_block is not None and ( + c._peak_proj_real is not None + and c._car_contra_block + == c._peak_proj_real.block_start), + "idle": c._car_idle(mono), "peak_needed": c._peak_needed, + "key": c._carq["key"], + "block": (c._peak_proj_real.block_start + if c._peak_proj_real is not None else None), + "floor_w": g.floor_w if g is not None else None, + "lo": getattr(cl, "lo", None), + "sp": tuple(i.last_write for i in c.inverters)}) + c.car_settle = settle + + def set_manual(p, c): + c._car_action("car_mode", "manual", c.car_now()) + + def plug(p, c): + p.ch.plug_in() + if energy == "late": + p.ch.hold_until = p.ch.t + 150.0 + + def reserve(p, c): + p.socs.update(soc_after) + + ev = {} + + def add(t, fn): + t = int(t) + old = ev.get(t) + ev[t] = fn if old is None else ( + lambda p, c, a_=old, b_=fn: (a_(p, c), b_(p, c))) + + add(0, hook) + add(t_plug, plug) + if mode == "manual": + add(t_man, set_manual) + add(R, reserve) + for t, fn in (extra or {}).items(): + add(t, fn) + for t, fn in (rel or {}).items(): + add(R + t, fn) + base, tick0 = rig.BASE, s81.TICK + rig.BASE, s81.TICK = base - timedelta(seconds=E), float(x) + o = dict(OPTS if n == 2 else OPTS1, **(opts or {})) + try: + r = P.drive(house, dur=R + after + step, rating=5000.0, + soc={u: soc0 for u in units}, cap=aim + H.MARGIN, + phases=1, n=n, plant_cls=cls, opts=o, dev_w=5000.0, + setpoint=car_a, user_a=car_a, mode="off", events=ev, + sim=s, plug=False) + finally: + rig.BASE, s81.TICK = base, tick0 + meta = {"E": E, "R": R, "t_plug": t_plug, "t_man": t_man, + "t_house": t_house, "house_w": hw, "step": step} + return r, tr, meta + + +# ---------------------------------------------------------- event helpers +# For `rel` (seconds from R) or `extra` (run seconds). +def p1_gap(t0, secs): + """No P1 sample reaches the add-on for `secs` from `t0` (it is late).""" + def off(p, c): + c.p1._ev19_submit = c.p1.submit + c.p1.submit = lambda *a, **k: None + + def on(p, c): + c.p1.submit = c.p1._ev19_submit + return {t0: off, t0 + secs: on} + + +def stale(t0, t1): + """The charger's readings stop reaching the car tracker from t0 to t1: + its figure ages past `stale_s`.""" + def off(p, c): + c.car._ev19_observe = c.car.observe + c.car.observe = lambda *a, **k: None + + def on(p, c): + c.car.observe = c.car._ev19_observe + return {t0: off, t1: on} + + +def unavailable(t0, t1): + return {t0: lambda p, c: p.ch.go_unavailable(True), + t1: lambda p, c: p.ch.go_unavailable(False)} + + +def restart(t0): + return {t0: lambda p, c: H.restart(c)} + + +def phases(t0, n=3): + """The user asks for `n` phases (the add-on's own 0 A pause follows).""" + return {t0: lambda p, c: c._car_action("car_phases", n, c.car_now())} + + +def socs(t0, **s): + return {t0: lambda p, c: p.socs.update(s)} + + +def merge(*evs): + out = {} + for e in evs: + for t, fn in e.items(): + old = out.get(t) + out[t] = fn if old is None else ( + lambda p, c, a_=old, b_=fn: (a_(p, c), b_(p, c))) + return out + + +# --------------------------------------------------------------- grading +def window(tr, t0, t1): + return [x for x in tr if t0 <= x["t"] <= t1] + + +def alarms(r): + return H.alarms(r) + + +def edges(tr): + return H.edges(tr) + + +def bad(x): + """An alarm, red sample or ERROR in this cycle.""" + return bool(x["alarm"] or x["red"] or x["err"]) + + +def repro(r, tr, meta, t0=-10, t1=60): + """T1's definition: a floor notice, ERROR or red sample in R-10..R+60 in + a cycle where the car figure is trusted (the shape lands under the aim + without the car, so the car explains). Returns (cycles, C5-only cycles).""" + R = meta["R"] + w = window(tr, R + t0, R + t1) + notes = [t for t in alarms(r) if R + t0 <= t <= R + t1] + hit = [x["t"] for x in w if bad(x) and x["w"] is not None + and x["w"] > 0.0] + c5 = [x["t"] for x in w if bad(x) and not (x["w"] is not None + and x["w"] > 0.0)] + return hit, c5, notes + + +def quiet(r, tr, t0, t1): + return (not [t for t in alarms(r) if t0 <= t <= t1] + and not any(bad(x) for x in window(tr, t0, t1))) + + +def commands(r, tr): + h = hashlib.sha256() + for u in sorted(r["plant"].hists): + h.update(repr((u, r["plant"].hists[u])).encode()) + h.update(repr(r["sim"].writes()).encode()) + h.update(repr([(x["t"], x["floor_w"], x["lo"], x["sp"]) + for x in tr]).encode()) + return h.hexdigest()[:16] + + +def row(name, r, tr, meta): + hit, c5, notes = repro(r, tr, meta) + R = meta["R"] + first = hit[:1] + cause = "" + if first: + x = next(y for y in tr if y["t"] == first[0]) + cause = (f"w={x['w']:.0f} batt={x['batt']} true={x['true_batt']:.0f}" + f" real={x['need_real']:d} excl={x['need_excl']:d} " + f"house={x['need_house']:d} over={x['over_now']:d} " + f"contra={x['contra']:d} pn={x['peak_needed']:d} " + f"wa={x['within_aim']:d} wanted={x['wanted']:.0f}") + return (f"{name:42s} R={R:5d} notes {[t - R for t in notes]} " + f"hit {[t - R for t in hit][:6]}{'...' if len(hit) > 6 else ''}" + f" n={len(hit)} c5 {len(c5)} err " + f"{len([x for x in window(tr, R - 10, R + 60) if x['err']])} " + f"red900 {len([x for x in window(tr, R - 60, R + 900) if x['red']])}" + f" {cause}") + + +def t2_shape(**kw): + """The reproducing shape (T2): b follows the house from R, 0 W before.""" + return dict(dict(bw=0.0, traj="t2"), **kw) + + +def t5_shape(**kw): + """The honest shape (T5): the house alone misses the aim by 1 680 W, more + than the 1 380 W car; the batteries give 4 250 W until R.""" + return dict(dict(bw=4250.0, traj="t1", house_w=AIM + 1680.0), **kw) + + +def flicker_force(bw=2000.0): + """T17: each unit gives bw/2 above its reserve and ramps to 0 W over 3 + cycles once at it (tau3); back above it, it gives bw/2 again at once.""" + def mk(u): + st = {"since": None} + + def f(at, plant): + if plant.socs[u] >= 20.0: + st["since"] = None + return bw / 2.0 + if st["since"] is None: + st["since"] = at + k = int(at - st["since"]) + return bw / 2.0 * max(0.0, (3 - k) / 3.0) + return f + return {"a": mk("a"), "b": mk("b")} + + +def _step_house(k, lo=AIM + 520.0 - CAR, hi=AIM + 1900.0): + return lambda t, R: lo if t < R + k else hi + + +def _ignoring(): + """The charger accepts the 6 A write and ignores it: the car stays at + 0 A.""" + s = Meter(setpoint_a=0) + s.refuse = "ignore" + return s + + +def _full_at_plug(p, c): + """The car is full (after the plug-in at R-180): mode3 B, 0 W.""" + p.ch.car_full() + + +def _no_energy(p, c): + """The charger has no energy entity.""" + p.ch.no_energy = True + + +def _freeze_stop(p, c): + p.ch.freeze() + p.ch.car_full() + + +def jobs(): + """Every controller run test_ev19.py grades: {name: kwargs}.""" + j = {} + for name, kw in grid(): + j["T1 " + name] = kw + # T3: the battery W sweep + for tj in ("t1", "t2"): + for bw in range(0, 4601, 200): + j[f"T3 {tj} bw={bw}"] = dict(bw=float(bw), traj=tj) + j[f"T3 {tj} tau5"] = dict(bw=9600.0, traj=tj, aim=6000.0, + house_w=5200.0) + # T4: the landing without the car at aim + 9 / + 11 W + for d in (9, 11): + for md in ("manual", "off"): + j[f"T4 +{d} {md}"] = t2_shape(house_w=AIM + d, mode=md) + # T5: honest at the reserve + for tj in ("t1", "t4"): + for md in ("manual", "off"): + j[f"T5 {tj} {md}"] = t5_shape(traj=tj, mode=md) + for md in ("manual", "off"): + j[f"T5 tau5 {md}"] = dict(bw=9600.0, traj="t1", aim=6000.0, + house_w=7700.0, mode=md) + # T6: the honest step in the reserve cycle + for k in (0, 1, 5): + for md in ("manual", "off"): + j[f"T6 step R+{k} {md}"] = dict(bw=4250.0, traj="t1", mode=md, + house_fn=_step_house(k)) + # T7: unknown values + for nm, sh in (("T2", t2_shape), ("T5", t5_shape)): + j[f"T7(a) {nm}"] = sh(lost={"a": {0, 1}}) + j[f"T7(b) {nm}"] = sh(rel=unavailable(0, 1)) + j["T7(a) T5 off"] = t5_shape(lost={"a": {0, 1}}, mode="off") + j["T7(b) T5 off"] = t5_shape(rel=unavailable(0, 1), mode="off") + # T8: a stale car figure + j["T8(a) Off 120 s, Manual R-5"] = t2_shape(plug_at=-125, man_at=-5) + j["T8(b) stale R-5..R+20"] = t2_shape(rel=stale(-5, 20)) + j["T8(c) frozen, the car stops"] = t5_shape(rel={-30: _freeze_stop}) + j["T8(c) off"] = t5_shape(rel={-30: _freeze_stop}, mode="off") + # T9: comms + for nm, sh in (("T2", t2_shape), ("T5", t5_shape)): + j[f"T9(a) {nm} b lost at R"] = sh(lost={"b": {0}}) + j[f"T9(a) {nm} b lost at R-1"] = sh(lost={"b": {-1}}) + j[f"T9(b) {nm} P1 5 s late at R"] = sh(rel=p1_gap(0, 5)) + # T10: a restart + for nm, sh in (("T2", t2_shape), ("T5", t5_shape)): + j[f"T10 {nm} twin"] = sh() + for k in (-2, 2): + j[f"T10 {nm} restart R{k:+d}"] = sh(rel=restart(k)) + # T11: the quarter edge + for rr in (-1, 0, 1, 43): + j[f"T11 T2 R=E{rr:+d}"] = t2_shape(r_rel=rr) + j[f"T11 T5 R=E{rr:+d}"] = t5_shape(r_rel=rr) + j[f"T11 T5 R=E{rr:+d} off"] = t5_shape(r_rel=rr, mode="off") + # C4: the old quarter heads over the aim (the house high all along), so the + # guard wants power in its last 60 s and SAFETY-126's latch is carried + j["T11 C4 T2 R=E+1"] = t2_shape(r_rel=1, house_w=13350.0, pre_w=13350.0) + # T12: our own phase change + for k in (-15, 5): + j[f"T12 T2 1->3 at R{k:+d}"] = t2_shape(rel=phases(k)) + j[f"T12 T5 1->3 at R{k:+d}"] = t5_shape(rel=phases(k)) + j[f"T12 T5 1->3 at R{k:+d} off"] = t5_shape(rel=phases(k), + mode="off") + # T13: a wrong charger reply + # (a): the house + the 400 W it really draws lands at aim + 520 W, so the + # house alone misses by 120 W; (b) and T14(a): the car draws 0 W and the + # house alone lands at aim + 520 W. An alarm is due in each. + for md in ("manual", "off"): + j[f"T13(a) draws 400 W {md}"] = t2_shape( + sim=Draw(400.0, CAR, setpoint_a=6), house_w=AIM + 120.0, mode=md) + j[f"T13(a) draws 100 W {md}"] = t2_shape( + sim=Draw(100.0, CAR, setpoint_a=6), house_w=AIM + 420.0, mode=md) + j[f"T13(b) the write ignored, 0 A {md}"] = t2_shape( + sim=_ignoring(), house_w=AIM + 520.0, mode=md) + # T14: configuration + j[f"T14(a) 0 W in C {md}"] = t2_shape( + sim=Draw(0.0, 0.0, c_at_0=True, setpoint_a=6), + house_w=AIM + 520.0, mode=md) + j[f"T14(a) idle B {md}"] = t2_shape( + house_w=AIM + 520.0, mode=md, rel={-179: _full_at_plug}) + j["T14(b) ev_charger off"] = t2_shape(opts={"ev_charger": "off"}) + j["T14(b) off"] = t2_shape(mode="off") + for tj in ("t1", "t4"): + j[f"T14(c) N=1 anchor {tj}"] = dict(n=1, bw=4250.0, traj=tj) + j["T14(c) N=1 T5"] = t5_shape(n=1) + j["T14(c) N=1 T5 off"] = t5_shape(n=1, mode="off") + # T15: one battery first (SAFETY-87) + for nm, hw in (("anchor", AIM + 520.0 - CAR), ("honest", 19000.0)): + for md in ("manual", "off"): + j[f"T15 {nm} {md}"] = dict( + bw=4250.0, traj="t1", house_w=hw, mode=md, + force={"b": None}, soc_after={"a": 19.0, "b": 35.0}, + rel=socs(360, b=19.0)) + # T16: x10 (wall and mono), and mono x1 / wall x10 + for xn, xk in (("x10", dict(x=10)), ("mono1", dict(x=10, mono_x=1))): + xk = dict(xk, r_rel=40) + # x10: b at 1 200 W before R (at 0 W, which the forced unit holds + # against the guard's floor, SAFETY-37's gate reads it as frozen) + xk2 = dict(xk, bw=1200.0) + j[f"T16 {xn} T2"] = t2_shape(**xk2) + for tj in ("t1", "t4"): + for bw in (0.0, 2000.0, 4250.0): + j[f"T16 {xn} T3 {tj} bw={bw:.0f}"] = dict(bw=bw, traj=tj, + **xk) + for md in ("manual", "off"): + j[f"T16 {xn} T5 {md}"] = t5_shape(mode=md, **xk) + j[f"T16 {xn} T6 {md}"] = dict(bw=4250.0, traj="t1", mode=md, + house_fn=_step_house(0), **xk) + j[f"T16 {xn} T7(b) T2"] = t2_shape(rel=unavailable(0, 10), **xk2) + for rr in (-10, 0, 10, 40): + j[f"T16 {xn} T11 T2 R=E{rr:+d}"] = t2_shape( + **dict(xk2, r_rel=rr)) + j[f"T16 {xn} T11 T5 R=E{rr:+d}"] = t5_shape(**dict(xk, r_rel=rr)) + # T17: no flicker + j["T17 flicker"] = dict( + force=flicker_force(), after=1200, + rel=merge(socs(300, a=21.0, b=21.0), socs(600, a=19.0, b=19.0)), + house_fn=lambda t, R: AIM + 10.0 + (40.0 if int(t // 7) % 2 + else -40.0)) + # N2: figures only `car_w_trusted` keeps out of the alarm path: no energy + # entity (never corroborated, never contradicted) and 11 kW reported at + # a 6 A read-back (capped at 1 518 W; the house alone misses by 1 680 W) + for md in ("manual", "off"): + j[f"N2 no energy entity {md}"] = t2_shape(extra={0: _no_energy}, + mode=md) + j[f"N2 reports 11 kW at 6 A {md}"] = t5_shape( + sim=Draw(CAR, 11000.0, setpoint_a=6), mode=md) + # T20 / N4: the same runs with the car never explaining + j["N4 T2 explain off"] = t2_shape(explain_off=True) + j["N4 T5 explain off"] = t5_shape(explain_off=True) + return j + + +def grid(): + """The T1 cells: (name, kwargs).""" + cells = [] + for bw in (0.0, 400.0, 800.0, 2000.0, 4250.0, 9600.0): + for tj in ("t1", "t2", "t3", "t4", "t4r"): + for rp in (30, 100, 110, 180, 600): + kw = dict(bw=bw, traj=tj, rp=rp) + if bw == 9600.0: + kw.update(aim=6000.0, house_w=5200.0) + cells.append((f"core bw={bw:.0f} {tj} rp={rp}", kw)) + cells.append(("a: plug R-185, Manual R-180", dict(order="plug"))) + cells.append(("a: Off 120 s, Manual R-60", dict(order="off120"))) + cells.append(("b: energy first step late", dict(energy="late"))) + cells.append(("b: energy never steps", dict(energy="never"))) + for rr in (-60, 0, 1, 43, 450, 890): + cells.append((f"c: R=E{rr:+d}", dict(r_rel=rr))) + cells.append(("d: x10 wall+mono", dict(x=10, r_rel=40))) + cells.append(("d: x10 wall, mono x1", dict(x=10, mono_x=1, r_rel=40))) + for tj, bw in (("t4", 4250.0), ("t2", 4250.0), ("t2", 1200.0)): + cells.append((f"d: x10 wall+mono {tj} bw={bw:.0f}", + dict(x=10, r_rel=40, traj=tj, bw=bw))) + cells.append((f"d: x10 wall, mono x1 {tj} bw={bw:.0f}", + dict(x=10, mono_x=1, r_rel=40, traj=tj, bw=bw))) + return cells + + +class Res: + """What a check needs from one run, picklable: the notices (`raised`, + seconds and ids), the trace, the command digest and the run's times.""" + + def __init__(self, r, tr, meta): + self.raised = list(r["raised"]) + self.tr, self.meta = tr, meta + self.cmd = commands(r, tr) + self.R, self.E = meta["R"], meta["E"] + + def alarms(self): + return [t for t, n in self.raised if n == FLOOR] + + def rel_alarms(self): + return [int(t - self.R) for t in self.alarms()] + + def edges(self): + return [int(t - self.R) for t in edges(self.tr)] + + def errors(self): + return [int(x["t"] - self.R) for x in self.tr if x["err"]] + + def red(self, t0=-60, t1=900): + return [int(x["t"] - self.R) for x in + window(self.tr, self.R + t0, self.R + t1) if x["red"]] + + def at(self, k): + return next((x for x in self.tr if x["t"] == self.R + k), None) + + def win(self, t0, t1): + return window(self.tr, self.R + t0, self.R + t1) + + def quiet(self, t0=-60, t1=900): + return quiet({"raised": self.raised}, self.tr, + self.R + t0, self.R + t1) + + def edges_per_quarter(self): + """False -> True edges of the floor alarm per quarter (N5).""" + out = {} + for t in edges(self.tr): + q = int((t - self.E) // 900) + out[q] = out.get(q, 0) + 1 + return out + + def summary(self): + return {"alarms": self.rel_alarms(), "edges": self.edges(), + "errors": self.errors(), "red": len(self.red()), + "cmd": self.cmd} + + +_JOBS = {} + + +def _job(name): + import logging + logging.disable(logging.WARNING) + return name, Res(*run(**_JOBS[name])) + + +def run_many(jobs, procs=None): + """{name: kwargs} -> {name: Res}, `procs` runs at a time (fork: the + kwargs may hold functions).""" + import multiprocessing + _JOBS.clear() + _JOBS.update(jobs) + procs = procs or int(os.environ.get("EV19_JOBS", "0")) \ + or min(8, os.cpu_count() or 1) + ctx = multiprocessing.get_context("fork") + with ctx.Pool(procs) as pool: + return dict(pool.imap_unordered(_job, list(jobs), chunksize=1)) + + +def _one(cell): + import logging + logging.disable(logging.WARNING) + name, kw = cell + try: + r, tr, meta = run(**kw) + except Exception as e: # noqa: BLE001 + import traceback + return name, f"{name:42s} Traceback {e!r}\n{traceback.format_exc()}" + return name, row(name, r, tr, meta) + + +if __name__ == "__main__": + import multiprocessing + cells = grid() + if len(sys.argv) > 1: + cells = [c for c in cells if any(a in c[0] for a in sys.argv[1:])] + with multiprocessing.Pool(int(os.environ.get("EV19_JOBS", "8"))) as pool: + for _name, line in pool.imap(_one, cells): + print(line, flush=True) -- 2.54.0 From c2bb32ec932db9e428b33efb505d6752d20c4912 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Fri, 20 Nov 2026 22:13:19 +0100 Subject: [PATCH 10/55] EV-19 review round 1: discount a battery rise only while the meter has not moved [Major] The rise discount applied to any rise, also one the meter already shows, so an honest house step answered by one cycle of battery power alarmed one cycle after base (review repro: T6 step + burst, R+6 instead of R+5). Now a reading above both earlier ones is discounted only while the meter's house side (held - car; held alone when a car figure is unknown) moved no more than RISE_STILL_W (50 W) since the last cycle. Tests: the burst shapes (unit, meter in step and one cycle late; controller, step at R+5 and R+30, 3 000 / 4 600 W) at base's second; the "N6 unit" check tightened to the rise cycle; the RISE_STILL_W boundary; a pin on EV-18's `_car_over_now` (mC); T10 restarts at R-1 and R (mE). test_ev19: 144 of 144 here, 52 red on 43b0db7. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-04-manual-mode.md | 12 ++- goodwe_controller/app/ctl_car.py | 27 +++++-- goodwe_controller/test_ev19.py | 79 ++++++++++++++++--- goodwe_controller/tools/ev19_reserve.py | 29 ++++++- 4 files changed, 127 insertions(+), 20 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index 6f0e852..4fb034b 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -152,13 +152,17 @@ up to 1.8 kW; the 40 Wh floor fixes that.) whole window and fell short; an unknown reading is no contradiction) grades no alarm to the quarter's end; the guard's input keeps it. After a restart or a gap the car's earlier energy is not known, so it counts as house. -- **A battery rise is house only once a second reading shows it** (EV-19, EV-15 +- **A battery rise the meter has not shown is not house yet** (EV-19, EV-15 rig F-B). At the reserve inverter-b goes on following the house, so its output rises; the reading shows it one cycle before P1 does, and the house figure (meter + battery) counted that power as house. `_car_need_house` - latched and the alarm stood. For the house figure, a reading above both - earlier ones counts only up to the higher of them; the credit stays the lower - of the last two readings. + latched and the alarm stood. Now, while the meter's house side (held - car) + moved no more than `RISE_STILL_W` since the last cycle, a reading above both + earlier ones counts only up to the higher of them. A meter that moved shows + the rise (an honest step with a battery burst alarms at once, as before). A + rise the meter does not move with at all is graded as F-B: the one case the + readings cannot tell apart. The credit stays the lower of the last two + readings; `_car_over_now` is unchanged. - **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/ctl_car.py b/goodwe_controller/app/ctl_car.py index da37a70..d87d1bc 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -31,6 +31,9 @@ OVER_OFF_HOLD_S = 180.0 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 +# EV-19: the meter's house side (held - car) moved no more than this since the +# last cycle: it has not shown a battery rise the reading already shows. +RISE_STILL_W = 50.0 class CarMixin: @@ -59,6 +62,7 @@ class CarMixin: self._car_over_since = None self._car_over_gone = None self._car_batt_prev = self._car_batt_prev2 = None + self._car_hx_prev = None # EV-19: last cycle's (held, car W) self._car_need_real = self._car_need_excl = False # EV-10 latches self._car_need_house = self._car_over_now = False # EV-18 latches self._car_latch_block = None @@ -416,12 +420,6 @@ class CarMixin: now, prev = self.site_batt_w, self._car_batt_prev prev2, self._car_batt_prev2 = self._car_batt_prev2, prev self._car_batt_prev = now - # EV-19: the reading can show a rise one cycle before the meter does - # (the batteries pick up the house at the reserve), so a reading above - # both earlier ones is not yet counted as house. - seen = now - if now is not None and prev is not None and prev2 is not None: - seen = min(float(now), max(float(prev), float(prev2))) wants = bool(guard is not None and guard.engaged and guard.blind is None and (guard.wanted_w or 0.0) > 0.0) @@ -433,6 +431,23 @@ class CarMixin: if batt is not None and prev is not None: batt = min(float(batt), float(prev)) excl = self.car_exclude_alarm(real_proj, w) + # EV-19: the reading can show a rise one cycle before the meter does + # (the batteries pick up the house at the reserve). While the meter's + # house side (held - car; held alone when a car figure is unknown) has + # not moved, a reading above both earlier ones is not yet counted as + # house; a meter that moved shows it (no discount). + held = float(real_proj.held_w) + hp, self._car_hx_prev = self._car_hx_prev, (held, w) + still = False + if hp is not None: + moved = held - hp[0] + if w is not None and hp[1] is not None: + moved -= float(w) - float(hp[1]) + still = abs(moved) <= RISE_STILL_W + seen = now + if still and now is not None and prev is not None \ + and prev2 is not None: + seen = min(float(now), max(float(prev), float(prev2))) if wants and batt is not None: self._car_need_real = self._car_need_real or \ peakguard.misses_aim(real_proj, batt_w=batt, diff --git a/goodwe_controller/test_ev19.py b/goodwe_controller/test_ev19.py index bf4077c..57ca96e 100644 --- a/goodwe_controller/test_ev19.py +++ b/goodwe_controller/test_ev19.py @@ -147,16 +147,55 @@ u6 = urun(range(-5, 30), meter(AIM + 11.0 + 400.0, lambda t: 400.0, lag=0), check("N6 unit: b at 400 W, the house alone with it at aim + 11 W, one " "reading of 800 W at E+3: not explained in any cycle", not any(run_of(u6, 0, 29))) -# The rise counts as house once a second reading confirms it: b steps to -# 800 W and the meter, one cycle late, shows a house of aim + 811 W (the -# house steps with it), so with b's 800 W the house alone misses by 11 W. +# A house step that comes with a battery rise: b steps to 800 W and the +# meter, one cycle late, shows a house of aim + 811 W, so with b's 800 W the +# house alone misses by 11 W. The meter moved, so nothing is discounted. b8 = rise(5, 0.0, 800.0) u8 = urun(range(0, 30), lambda t: (AIM - 500.0 if t < 5 else AIM + 811.0) + CAR - b8(t - 1), b8) print(f" N6 unit house step with a rise E+4..E+8: {run_of(u8, 4, 8)}") -check("N6 unit: a house step that comes with a battery rise is latched at " - "most one cycle after the rise (E+6), and stays latched", - all(run_of(u8, 0, 4)) and not any(run_of(u8, 6, 29))) +check("N6 unit: a house step that comes with a battery rise is latched in " + "the rise cycle (E+5, as base), and stays latched", + all(run_of(u8, 0, 4)) and not any(run_of(u8, 5, 29))) + +# Review round 1 (Major): an honest house step at E+5 answered by ONE reading +# of battery power, the meter in step (it shows the burst too) or one cycle +# late. Not explained from E+5, the step's own cycle, as base. +for H, burst, lag in ((2000.0, 4600.0, 0), (1900.0, 3000.0, 0), + (5000.0, 4600.0, 0), (2000.0, 4600.0, 1), + (1900.0, 3000.0, 1)): + hs = (lambda t, H=H: AIM - 500.0 if t < 5 else AIM + H) + bb = (lambda t, burst=burst: burst if t == 5 else 0.0) + ub = urun(range(0, 15), lambda t, hs=hs, bb=bb, lag=lag: + hs(t) + CAR - bb(t - lag), bb) + check(f"RB unit: house -> aim + {H:.0f} W at E+5 with one {burst:.0f} W " + f"reading, meter {'in step' if lag == 0 else 'one cycle late'}: " + f"explained to E+4, not from E+5 (base: the same)", + ub.get(4) is True and not any(run_of(ub, 5, 14)) + and len(run_of(ub, 5, 14)) == 10) + +# The discount needs a still meter: the F-B rise (T2 unit) with the house +# side of the meter moving by RISE_STILL_W -/+ 10 W in the rise cycle. +STILL = getattr(ctl_car, "RISE_STILL_W", 50.0) # 43b0db7 has none +for d, want in ((STILL - 10.0, True), (STILL + 10.0, False)): + ud = urun(range(-5, 10), lambda t, d=d: HB + (d if t >= 1 else 0.0) + + CAR - b2(t - 1), b2) + check(f"RISE_STILL_W: the meter's house side moves {d:.0f} W in the rise " + f"cycle: {'still, the rise is not yet house (explained)' if want else 'moved, the rise counts as house (not explained, as base)'}", + ud.get(1) is want and ud.get(0) is True) + +# Review round 1 (mC): EV-18's `_car_over_now` keeps the reading as it is. b +# gives 2 000 W, the house alone with it lands under the aim and the period +# with the car too, so nothing explains; b rises to 4 000 W at E+5 one cycle +# before the meter: the period with the car on the reading as it is lands +# over, so the car explains from E+5. +bc = rise(5, 2000.0, 4000.0) +uc = urun(range(0, 15), lambda t: AIM + 500.0 + CAR - bc(t - 1), bc) +print(f" over_now unit E+3..E+7: {run_of(uc, 3, 7)}") +check("over_now unit: `_car_over_now` grades the undiscounted reading: not " + "explained E+0..E+4, explained from the rise cycle E+5", + not any(run_of(uc, 0, 4)) and all(run_of(uc, 5, 14)) + and len(run_of(uc, 5, 14)) == 10) # =========================================================================== # print("\n2. THE REAL CONTROLLER AT THE RESERVE (N=2, tools/ev19_reserve.py)") @@ -200,6 +239,8 @@ BASE_ALARMS = { "T9(a) T5 b lost at R": [2], "T9(a) T5 b lost at R-1": [2], "T9(b) T5 P1 5 s late at R": [5], "T10 T5 twin": [2], "T10 T5 restart R-2": [2], "T10 T5 restart R+2": [2], + "T10 T5 restart R-1": [2], "T10 T5 restart R+0": [2], + "T10 T2 restart R+0": [1], "T11 T5 R=E-1": [2], "T11 T5 R=E+0": [0, 2], "T11 T5 R=E+1": [0, 2], "T11 T5 R=E+43": [2], "T12 T5 1->3 at R-15": [2], "T12 T5 1->3 at R+5": [2], "T13(a) draws 100 W manual": [0, 857], @@ -370,10 +411,16 @@ for nm in ("T2", "T5"): # --- T10: a restart ------------------------------------------------------------ # for nm in ("T2", "T5"): tw = res(f"T10 {nm} twin") - for k in (-2, 2): + for k in (-2, -1, 0, 2): r = res(f"T10 {nm} restart R{k:+d}") show(f"T10 {nm} restart R{k:+d}") - if nm == "T2": + if nm == "T2" and k == 0: + # the rise cycle R+1 has no reading from two cycles back: nothing + # is discounted (the old behaviour), so the alarm is base's + check("T10 T2 restart at R+0: no reading two cycles back in the " + "rise cycle, so no discount: the alarm as base (R+1)", + as_base("T10 T2 restart R+0")) + elif nm == "T2": check(f"T10 T2 restart at R{k:+d}: no notice, no red sample, as " f"the unrestarted twin", r.quiet(-60, 900) and tw.quiet(-60, 900)) @@ -383,6 +430,18 @@ for nm in ("T2", "T5"): as_base(f"T10 T5 restart R{k:+d}") and as_base("T10 T5 twin") and len(r.red()) == len(tw.red())) +# --- Review round 1 (Major), controller: the T6 step with a one-cycle burst ---- # +for k in (5, 30): + for hi in (1900, 2500): + for burst in ("3000", "4600"): + nm = f"RB step R+{k} aim+{hi} burst {burst} manual" + r = res(nm) + show(nm) + check(f"{nm[:-7]}: P1 and the reading both show the burst: the " + f"notice, the ERROR and the first red sample at the step, " + f"R+{k}, as base", r.rel_alarms() == [k] + and r.errors() == [k] and r.red()[:1] == [k]) + # --- T11: the quarter edge ------------------------------------------------------ # for rr in (-1, 0, 1, 43): r = res(f"T11 T2 R=E{rr:+d}") @@ -551,7 +610,9 @@ BASE_TWO = ["T1 b: energy first step late", "T1 b: energy never steps", "T11 T5 R=E+1 off", "T16 mono1 T11 T5 R=E+0", "T16 mono1 T11 T5 R=E+10", "T16 mono1 T6 off", "T16 x10 T11 T5 R=E+0", "T16 x10 T11 T5 R=E+10", "T16 x10 T6 off", - "T6 step R+0 off", "T6 step R+1 off", "T6 step R+5 off"] + "T6 step R+0 off", "T6 step R+1 off", "T6 step R+5 off"] + [ + f"RB step R+{k} aim+{hi} burst {b} off" for k in (5, 30) + for hi in (1900, 2500) for b in (3000, 4600)] many = sorted(k for k, r in RES.items() if any(v > (2 if k in BASE_TWO and q == 0 else 1) for q, v in r.edges_per_quarter().items())) diff --git a/goodwe_controller/tools/ev19_reserve.py b/goodwe_controller/tools/ev19_reserve.py index 319c5b4..bce4918 100644 --- a/goodwe_controller/tools/ev19_reserve.py +++ b/goodwe_controller/tools/ev19_reserve.py @@ -201,7 +201,7 @@ def run(*, bw=4250.0, traj="t1", rp=180, r_rel=43, order="manual", soc_after = soc_after or {u: 19.0 for u in units} lagb = 10.0 if traj == "t4" else 0.0 cls = type("Plant", (Plant,), { - "force": frc, "batt_lag": lagb, + "force": frc, "batt_lag": lagb, "R": R, "lost": {u: {R + k for k in v} for u, v in (lost or {}).items()}, "p1_lag": 5.0 if traj == "t4r" else 0.0, "p1_from": float(R)}) @@ -477,6 +477,17 @@ def _step_house(k, lo=AIM + 520.0 - CAR, hi=AIM + 1900.0): return lambda t, R: lo if t < R + k else hi +def _burst(k, w): + """Inverter-b: 2 125 W until R+1, then `w` for 0.5 s before the cycle at + R+k (P1, sampled 0.3 s before it, and the reading both show it), else + 0 W.""" + def f(at, plant): + if at < plant.R + 1: + return 4250.0 / 2.0 + return w if plant.R + k - 0.5 <= at <= plant.R + k else 0.0 + return f + + def _ignoring(): """The charger accepts the 6 A write and ignores it: the car stays at 0 A.""" @@ -626,6 +637,22 @@ def jobs(): mode=md) j[f"N2 reports 11 kW at 6 A {md}"] = t5_shape( sim=Draw(CAR, 11000.0, setpoint_a=6), mode=md) + # Review round 1: an honest house step answered by ONE cycle of inverter-b + # power that P1 and the reading both show (the meter in step), after the + # T6 shape (4 250 W until R, then 0 W). + for k in (5, 30): + for hi in (1900, 2500): + for burst in (3000.0, 4600.0): + for md in ("manual", "off"): + j[f"RB step R+{k} aim+{hi} burst {burst:.0f} {md}"] = dict( + bw=4250.0, traj="t1", mode=md, + house_fn=_step_house(k - 0.5, hi=AIM + hi), + force={"b": _burst(k, burst)}) + # T10 (mE): restarts at R-1 and R, so the rise cycle has no reading from + # two cycles back + for nm, sh in (("T2", t2_shape), ("T5", t5_shape)): + for k in (-1, 0): + j[f"T10 {nm} restart R{k:+d}"] = sh(rel=restart(k)) # T20 / N4: the same runs with the car never explaining j["N4 T2 explain off"] = t2_shape(explain_off=True) j["N4 T5 explain off"] = t5_shape(explain_off=True) -- 2.54.0 From 77684ecfadc0feccf83b6c5db17a2562e500b885 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Fri, 20 Nov 2026 23:14:09 +0100 Subject: [PATCH 11/55] EV-19 review round 2: pin the 50 W blind band and the car term of the stillness test Test-only. Two unit checks in test_ev19.py: an honest step with a burst that moves the meter's house side +/-60 W alarms in base's cycle, and inside the band (0 W) the car explains at most the step's own cycle; a car step offset by a burst at the meter is not discounted. They kill RISE_STILL_W = 500 W and a stillness test without the car term. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/test_ev19.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/goodwe_controller/test_ev19.py b/goodwe_controller/test_ev19.py index 57ca96e..5aaa015 100644 --- a/goodwe_controller/test_ev19.py +++ b/goodwe_controller/test_ev19.py @@ -184,6 +184,35 @@ for d, want in ((STILL - 10.0, True), (STILL + 10.0, False)): f"cycle: {'still, the rise is not yet house (explained)' if want else 'moved, the rise counts as house (not explained, as base)'}", ud.get(1) is want and ud.get(0) is True) +# Review round 2: the blind band in absolute W (the owner's 50 W; change this +# check with the owner). An honest step at E+5 (house aim - 500 -> aim + 1 900 +# W, more than the car) with one burst that leaves the meter's house side +# moving d W: at |d| = 60 the alarm cycle is base's (E+5); inside the band +# (d = 0) the car explains at most the step's own cycle, never from E+6. +for dd in (60.0, -60.0, 0.0): + hb = (lambda t: AIM - 500.0 if t < 5 else AIM + 1900.0) + bd = (lambda t, B=2400.0 - dd: B if t == 5 else 0.0) + ubd = urun(range(0, 15), lambda t, hb=hb, bd=bd: hb(t) + CAR - bd(t), bd) + print(f" band d={dd:+.0f} W E+4..E+8: {run_of(ubd, 4, 8)}") + t0 = 5 if dd else 6 + check(f"band: an honest step whose burst moves the meter's house side " + f"{dd:+.0f} W: not explained from E+{t0}", + ubd.get(4) is True and not any(run_of(ubd, t0, 14)) + and len(run_of(ubd, t0, 14)) == 15 - t0) + +# Review round 2: the stillness test uses the house side (held - car). The car +# steps 1 380 -> 2 760 W, the house aim - 500 -> aim + 3 000 W (more than the +# car) and b gives one reading of 4 880 W, all at E+5, meter in step: the +# meter's total stays, its house side drops 1 380 W, so nothing is discounted. +hc = (lambda t: AIM - 500.0 if t < 5 else AIM + 3000.0) +wc = (lambda t: CAR if t < 5 else 2 * CAR) +bc5 = (lambda t: 4880.0 if t == 5 else 0.0) +ucw = urun(range(0, 15), lambda t: hc(t) + wc(t) - bc5(t), bc5, w=wc) +check("car term: the car steps up with the house and a burst, the meter's " + "total still: not explained from E+5 (as base)", + ucw.get(4) is True and not any(run_of(ucw, 5, 14)) + and len(run_of(ucw, 5, 14)) == 10) + # Review round 1 (mC): EV-18's `_car_over_now` keeps the reading as it is. b # gives 2 000 W, the house alone with it lands under the aim and the period # with the car too, so nothing explains; b rises to 4 000 W at E+5 one cycle -- 2.54.0 From 3b1189cdbf69a6ba7883b7fac1da4867174df81b Mon Sep 17 00:00:00 2001 From: "Claude (dev)" Date: Sat, 21 Nov 2026 08:54:04 +0100 Subject: [PATCH 12/55] EV-16: hold the Car Why text while car_over holds and the guard floor flag toggles Display only: the 'are at' / 'give all they can' text changes only when the other state has stood for 180 s (the car_over off hold); SoC unread is never 'are at'. Cleared when car_over drops, on unplug and with cover off. Co-Authored-By: Claude --- goodwe_controller/app/ctl_car.py | 3 + goodwe_controller/app/homeview.py | 30 ++- goodwe_controller/test_ev16.py | 355 ++++++++++++++++++++++++++++++ 3 files changed, 387 insertions(+), 1 deletion(-) create mode 100644 goodwe_controller/test_ev16.py diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index d87d1bc..cd5ac56 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -61,6 +61,7 @@ class CarMixin: self.car_over = False # ... held: the card and row say so self._car_over_since = None self._car_over_gone = None + self._car_why_hold = None # EV-16: the held Car Why (display) self._car_batt_prev = self._car_batt_prev2 = None self._car_hx_prev = None # EV-19: last cycle's (held, car W) self._car_need_real = self._car_need_excl = False # EV-10 latches @@ -398,6 +399,7 @@ class CarMixin: self._car_over_gone = mono if mono - self._car_over_gone >= OVER_OFF_HOLD_S: self.car_over, self._car_over_since = False, None + self._car_why_hold = None # EV-16: display only self._car_over_gone = None def _car_explains_alarm(self, real_proj, guard, target_w, w) -> bool: @@ -497,6 +499,7 @@ class CarMixin: # The session is over: that is a real end, with no hold. self.car_over = False self._car_over_since = self._car_over_gone = None + self._car_why_hold = None # EV-16: display only if s not in (chargers.NONE_, None) and self._car_prev_state in ( chargers.NONE_, None): self._car_session += 1 diff --git a/goodwe_controller/app/homeview.py b/goodwe_controller/app/homeview.py index 941e941..c9e4fc8 100644 --- a/goodwe_controller/app/homeview.py +++ b/goodwe_controller/app/homeview.py @@ -1301,6 +1301,32 @@ def _car_why(key, c, good): return _t("car.why." + (key if key else "wait")) +# EV-16: the Why of "car over the limit" follows the guard's floor flag, which +# toggles cycle by cycle at the reserve. The text is held: it changes only when +# the other state has stood for as long as the car_over row's own hold. +WHY_HOLD_S = 180.0 # = ctl_car.OVER_OFF_HOLD_S (tested) + + +def _over_why_is_floor(c, pg) -> bool: + """True: "are at {pct}"; False: "give all they can". Display only: the + state lives in `c._car_why_hold` and nothing in control reads it.""" + mono = c.car_now() + cand = (pg.floor_limited and pg.soc is not None) if pg is not None \ + else None + h = getattr(c, "_car_why_hold", None) + if h is None: + h = [bool(cand), None] # shown, since when cand differs + elif cand is None or cand == h[0]: + h[1] = None + else: + if h[1] is None: + h[1] = mono + if mono - h[1] >= WHY_HOLD_S: + h = [cand, None] + c._car_why_hold = h + return h[0] + + def _car_manual_why(c, key): """The Why of Manual: what you set, and what the peak limit does about it. Plan lines: two sentences of at most 12 words.""" @@ -1311,9 +1337,11 @@ def _car_manual_why(c, key): if c.car_over: pg = getattr(c, "peak_guard", None) if not c.car_cover: + c._car_why_hold = None return _t("car.why.manual_nocover", a=a) - return _t("car.why.manual_over" if pg is not None and pg.floor_limited + return _t("car.why.manual_over" if _over_why_is_floor(c, pg) else "car.why.manual_full", a=a, pct=pct) + c._car_why_hold = None if c.shadow: t, n = w.would if w.would is not None else (c.car_a, c.car_n) return _t("car.why.manual_would", a=f"{float(t):.0f}", diff --git a/goodwe_controller/test_ev16.py b/goodwe_controller/test_ev16.py new file mode 100644 index 0000000..64a8d84 --- /dev/null +++ b/goodwe_controller/test_ev16.py @@ -0,0 +1,355 @@ +"""EV-16: the Car Why does not alternate between "are at {pct}" and "give all +they can" while the car-over row holds and the guard's floor flag toggles. +`python3 -B test_ev16.py` + +Display only: the text is held in `c._car_why_hold`; control never reads it. +Mutant: pick the text from the live `floor_limited` again (T1, T2, T7, T8, T9 +go red). +Mutating a module this file grades? Read MUTATION.md first. +""" + +import dataclasses +import hashlib +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, homeview, chargers as CH # noqa: E402 +import ev04_peak as P # noqa: E402 +import safety81_sim as s81 # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +OVER = "are at" +FULL = "give all they can" +Q = 900.0 +STEP = 5.0 + + +@dataclasses.dataclass +class G: + floor_limited: bool = True + soc: object = 20.0 + saturated: bool = False + floor_w: float = 0.0 + able_w: object = None + ceiling_w: float = 4500.0 + engaged: bool = True + blind: object = None + wanted_w: float = 300.0 + within_aim: bool = False + + +class Proj: + projected_w = 14500.0 + held_w = 14500.0 + elapsed_s = 400.0 + block_start = None + + +class S(ctl_car.CarMixin): + def __init__(self, cover=True): + self.o = {"ev_batt_cover": cover} + self._now = 0.0 + self.w = 11000.0 + self.site_batt_w, self.site_rating_w = 8100.0, 9600.0 + self.shadow, self.auto, self.peak_guard = False, True, None + self.state = "charging" + self.car_init({}, type("St", (), {"data": {}, "set": lambda s, k, v: 0})()) + self.car_over = True + + def car_now(self): + return self._now + + def car_alarm_w(self): + return self.w + + @property + def car(self): + me = self + + class _C: + @staticmethod + def status(*_a): + return me.state + return _C + + +def why(c): + return homeview._car_manual_why(c, "charging") + + +def kind(t): + return "over" if OVER in t else "full" if FULL in t else t + + +def run(c, secs, g_of, t0=0.0): + """Read the Why once per 5 s cycle; returns [(t, kind)].""" + out = [] + t = t0 + while t < t0 + secs: + c._now = t + c.peak_guard = g_of(t - t0) + out.append((t, kind(why(c)))) + t += STEP + return out + + +def changes(seq): + return [i for i in range(1, len(seq)) if seq[i][1] != seq[i - 1][1]] + + +def toggle(period, first=True): + return lambda t: G(floor_limited=(int(t // period) % 2 == 0) == first) + + +HOUSE = s81.constant(1100.0) + + +def real_run(read, eventful=True): + """The T1 shape through the real controller: the batteries toggle across + the reserve every 10 s. Returns the control digest, the per-cycle rows and + flags, and the Why texts read (if `read`).""" + texts, rows, flags = [], [], [] + + def ev(plant, c): + plant.soc = 19.0 if int(plant.t // 10) % 2 == 0 else 60.0 + pg = c.peak_guard + flags.append(None if pg is None else pg.floor_limited) + rows.append(tuple((x["id"], x["ok"], x["warn"]) for x in c.checks() + if x["id"] in ("peak_guard", "car_over"))) + if read and c.car_over: + texts.append(homeview.car_block(c, None)["why"]) + r = P.drive(HOUSE, dur=900, events={k: ev for k in range(0, 900)}, + cap=3500.0) + ctl = ([s[1:] for s in r["snaps"]], list(r["raised"]), + r["sim"].writes(), r["sim"].setpoint_a) + return ctl, rows, flags, texts + + +def digest(x): + return hashlib.sha256(repr(x).encode()).hexdigest()[:16] + + +if "--digest" in sys.argv: + ctl, rows, flags, _t = real_run(False) + print("DIGEST control", digest(ctl), "rows", digest(rows), + "flags", digest(flags)) + sys.exit(0) + +print("1. the hold: a toggling flag shows one text") +c = S() +a = run(c, Q, toggle(10.0, True)) +check("T1 quarter starts floor-limited, toggles every 10 s: one distinct text", + len({k for _, k in a}) == 1 and a[0][1] == "over") +for per in (20.0, 30.0, 10.0): + c = S() + a = run(c, Q, toggle(per, False)) + check(f"T2 starts not limited, toggles every {per:.0f} s: at most one " + f"change, none back", len(changes(a)) <= 1) +c = S() +a = run(c, Q, lambda t: G(floor_limited=False, soc=38.0)) +check("T3 never limited: 'give all they can' every cycle, never 'are at'", + {k for _, k in a} == {"full"}) +c = S() +a = run(c, Q, lambda t: G()) +check("T4 limited and steady: 'are at' 20 % from the first cycle", + {k for _, k in a} == {"over"} + and "20 %" in why(c)) + +print("\n2. real changes still show") +c = S() +a = run(c, 300.0, lambda t: G(floor_limited=False, soc=30.0)) +a += run(c, 600.0, lambda t: G(), t0=300.0) +ch = changes(a) +check("T5 full for 300 s then steady limited: one change, full -> over, " + "within 185 s", len(ch) == 1 and a[ch[0]][1] == "over" + and a[ch[0]][0] - 300.0 <= 185.0) +c = S() +a = run(c, 300.0, lambda t: G()) +a += run(c, 600.0, lambda t: G(floor_limited=False, soc=30.0), t0=300.0) +ch = changes(a) +check("T6 limited for 300 s then steady not limited: one change back to " + "'give all they can' within 185 s", len(ch) == 1 + and a[ch[0]][1] == "full" and a[ch[0]][0] - 300.0 <= 185.0) +for steady_false in (True, False): + c = S() + a = run(c, Q, toggle(10.0, True)) + a += run(c, Q, (lambda t: G(floor_limited=False, soc=30.0)) + if steady_false else (lambda t: G()), t0=Q) + ch = changes(a) + first_q = {k for t, k in a if t < Q} + check(f"T7 toggling across the edge, new quarter steady " + f"{'False' if steady_false else 'True'}: nothing before the edge, " + f"at most one change near it, to the new state", + len(first_q) == 1 and len(ch) <= 1 + and all(a[i][0] >= Q for i in ch) + and len(a) > 0 and a[-1][1] == ("full" if steady_false else "over")) + near = [i for i in ch if abs(a[i][0] - Q) <= 60.0] + check("T7 (cont.) at most one change in the 60 s around the edge", + len(near) <= 1) + +print("\n3. failure modes") +c = S() +a = run(c, Q, lambda t: G(soc=None)) +check("T8 SoC unread, guard limited: never 'are at', one text", + {k for _, k in a} == {"full"}) +c = S() +a = run(c, Q, lambda t: G(soc=None if int(t // 10) % 2 == 0 else 20.0)) +check("T8 SoC toggling None / 20 % every 10 s, starting unread: one text, " + "never 'are at'", {k for _, k in a} == {"full"}) +c = S() +seq = [] +for t in range(0, 900, 5): + c._now = float(t) + c.peak_guard = None if 400 <= t < 410 else G(floor_limited=(t // 10) % 2 + == 0) + try: + seq.append((t, kind(why(c)))) + except Exception as e: # noqa: BLE001 + seq.append((t, "TRACE " + repr(e))) +check("T9 guard None for a cycle: no Traceback, one text through it", + not any("TRACE" in k for _, k in seq) and len({k for _, k in seq}) == 1) +c = S() +c.peak_guard = None +c._now = 0.0 +check("T9 (cont.) guard None from the very first read: a text, no Traceback", + kind(why(c)) in ("full", "over")) + +# T10: the car stops, car_over drops after 180 s, a later episode +c = S() +run(c, 100.0, lambda t: G()) +check("T10 held 'are at' to start", kind(why(c)) == "over") +for k in range(0, 200): + c._now = 100.0 + k + c.w = None + c.car_cycle(Proj(), G(), 14000.0, None) +check("T10 car_over dropped after the stop", c.car_over is False) +check("T10 the Why left the over wording", OVER not in why(c) + and FULL not in why(c)) +c.car_over = True # a new episode, later, SoC 60 % +c._now = 5000.0 +c.peak_guard = G(floor_limited=False, soc=60.0) +check("T10 the new episode shows 'give all they can' from its first cycle", + kind(why(c)) == "full") + +# T10b: no read between the drop and the new episode (the hold is cleared at +# the drop, not at a read) +c = S() +run(c, 100.0, lambda t: G()) +for k in range(0, 200): + c._now = 100.0 + k + c.w = None + c.car_cycle(Proj(), G(), 14000.0, None) +c.car_over = True +c._now = 9000.0 +c.peak_guard = G(floor_limited=False, soc=60.0) +check("T10 no /status between the drop and the new episode: still 'full'", + kind(why(c)) == "full") + +# T11: unplug +c = S() +run(c, 100.0, lambda t: G()) +c._car_prev_state = "charging" +c.state = CH.NONE_ +c._now = 105.0 +c.car_cycle(Proj(), G(), 14000.0, None) +c.car_over = False +check("T11 after the unplug cycle there is no over wording", + OVER not in homeview._car_manual_why(c, "none") + and FULL not in homeview._car_manual_why(c, "none") + and "set when a car is connected" in homeview._car_manual_why(c, "none")) +c.state = "charging" +c.car_over = True +c.peak_guard = G(floor_limited=False, soc=60.0) +c._now = 400.0 +check("T11 a replug starts with no held text", kind(why(c)) == "full") +# the hold is also gone when the unplug itself ends car_over (no read between) +c = S() +run(c, 100.0, lambda t: G()) +c._car_prev_state = "charging" +c.state = CH.NONE_ +c._now = 105.0 +c.car_cycle(Proj(), G(), 14000.0, None) +check("T11 (cont.) the unplug clears the hold itself", + c.car_over is False and getattr(c, "_car_why_hold", "x") is None) + +# T12: cover off while car_over holds +c = S() +run(c, 100.0, lambda t: G()) +c.o["ev_batt_cover"] = False +c._now = 105.0 +check("T12 cover off: 'ignores the car' at the next read", + "ignores the car" in why(c)) +c.o["ev_batt_cover"] = True +c.peak_guard = G(floor_limited=False, soc=60.0) +c._now = 110.0 +check("T12 cover on again, steady not limited: 'give all they can', not " + "the old 'are at'", kind(why(c)) == "full") + +# T13: restart +c = S() +a = run(c, 450.0, toggle(10.0, True)) +c2 = S() +b = run(c2, 450.0, toggle(10.0, True), t0=450.0) +check("T13 restart mid-quarter: no Traceback, a text, at most one change " + "after", kind(why(c2)) in ("full", "over") and len(changes(b)) <= 1) + +print("\n4. control unchanged; the rows follow the live flag") +ctl1, rows1, flags1, sts = real_run(True) +ctl0, rows0, flags0, _t = real_run(False) +check("T14 reading the Why every cycle changes no command, alarm or row", + ctl1 == ctl0 and rows1 == rows0 and flags1 == flags0) +shown = [t for t in sts if OVER in t or FULL in t] +flips = sum(1 for a, b in zip(flags1, flags1[1:]) if a != b) +BASE_8150608 = ("e6034b0c78f23776", "5ffb80fa428cd6ee", "689a5b0e4bf7c897") +check("T14/T15 commands, alarms, charger writes and the peak_guard/car_over " + "rows equal those of base 8150608 (digests taken there with --digest)", + (digest(ctl1), digest(rows1), digest(flags1)) == BASE_8150608) +check("PRECONDITION: the real guard's floor flag toggles many times and " + "car_over is on for most of the run", flips > 20 and len(shown) > 200) +check("T1/T2 through the real guard: at most one Why change in the quarter", + sum(1 for a, b in zip(shown, shown[1:]) if a != b) <= 1) +check("T15 the peak_guard row follows the live flag (it changes as often as " + "the flag), the hold is only in the Why", + sum(1 for a, b in zip(rows1, rows1[1:]) if a != b) >= 1 + and len({r for r in rows1 if r}) >= 1) +print(" DIGEST control", digest(ctl1), "rows", digest(rows1), + "flags", digest(flags1)) + +print("\n5. text, hold and wiring") +check("the hold equals the car_over row's own off hold", + homeview.WHY_HOLD_S == ctl_car.OVER_OFF_HOLD_S) +src = open(os.path.join(HERE, "app", "homeview.py")).read() +check("the live flag is read only by the hold helper, not by the Why branch", + 'pg.floor_limited else' not in src) +import json +for lang, over, full in ( + ("en", "You set {a} A. The batteries are at {pct}, so this charge " + "sets the peak.", + "You set {a} A. The batteries give all they can, so this charge " + "sets the peak."), + ("nl", "U stelde {a} A in. De batterijen staan op {pct}, dus deze " + "lading bepaalt de piek.", + "U stelde {a} A in. De batterijen geven alles, dus deze lading " + "bepaalt de piek.")): + d = json.load(open(os.path.join(HERE, "app", "ui_text", lang + ".json"))) + d = d["home_words"]["car"]["why"] + check(f"T17 {lang}.json wording of manual_over / manual_full unchanged", + d["manual_over"] == over and d["manual_full"] == full) +check("a held peak_guard row is not touched: the module still has no hold " + "in ctl_status", "_car_why_hold" not in open(os.path.join( + HERE, "app", "ctl_status.py")).read()) + +print() +print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") +sys.exit(1 if fails else 0) -- 2.54.0 From b662d7171b75177506f096c9f996c1dd2c80393e Mon Sep 17 00:00:00 2001 From: "Claude (dev)" Date: Sat, 21 Nov 2026 10:04:00 +0100 Subject: [PATCH 13/55] EV-16: key the held Car Why to the car_over episode; add T16, T18 and N-id checks Control bumps _car_over_ep at each start and end of car_over; the display ignores a hold of another episode, so a read overlapping the end cannot bring a stale text back. Co-Authored-By: Claude --- goodwe_controller/app/ctl_car.py | 7 +- goodwe_controller/app/homeview.py | 11 +++- goodwe_controller/test_ev16.py | 105 +++++++++++++++++++++++++++++- 3 files changed, 115 insertions(+), 8 deletions(-) diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index cd5ac56..391fae2 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -62,6 +62,7 @@ class CarMixin: self._car_over_since = None self._car_over_gone = None self._car_why_hold = None # EV-16: the held Car Why (display) + self._car_over_ep = 0 # EV-16: bumped by control at each start/end of car_over; the hold is valid for one value self._car_batt_prev = self._car_batt_prev2 = None self._car_hx_prev = None # EV-19: last cycle's (held, car W) self._car_need_real = self._car_need_excl = False # EV-10 latches @@ -393,13 +394,15 @@ class CarMixin: if self._car_over_since is None: self._car_over_since = mono if mono - self._car_over_since >= OVER_HOLD_S: + if not self.car_over: + self._car_over_ep += 1 # EV-16: a new episode self.car_over = True else: if self._car_over_gone is None: self._car_over_gone = mono if mono - self._car_over_gone >= OVER_OFF_HOLD_S: self.car_over, self._car_over_since = False, None - self._car_why_hold = None # EV-16: display only + self._car_over_ep += 1 # EV-16: ends the held Why self._car_over_gone = None def _car_explains_alarm(self, real_proj, guard, target_w, w) -> bool: @@ -499,7 +502,7 @@ class CarMixin: # The session is over: that is a real end, with no hold. self.car_over = False self._car_over_since = self._car_over_gone = None - self._car_why_hold = None # EV-16: display only + self._car_over_ep += 1 # EV-16: ends the held Why if s not in (chargers.NONE_, None) and self._car_prev_state in ( chargers.NONE_, None): self._car_session += 1 diff --git a/goodwe_controller/app/homeview.py b/goodwe_controller/app/homeview.py index c9e4fc8..8c317c0 100644 --- a/goodwe_controller/app/homeview.py +++ b/goodwe_controller/app/homeview.py @@ -1309,20 +1309,25 @@ WHY_HOLD_S = 180.0 # = ctl_car.OVER_OFF_HOLD_S (tested) def _over_why_is_floor(c, pg) -> bool: """True: "are at {pct}"; False: "give all they can". Display only: the - state lives in `c._car_why_hold` and nothing in control reads it.""" + state lives in `c._car_why_hold`, stamped with the episode `c._car_over_ep` + that control bumps; a hold of another episode is never used, so a read + overlapping the end of car_over cannot bring a stale text back.""" mono = c.car_now() cand = (pg.floor_limited and pg.soc is not None) if pg is not None \ else None + ep = getattr(c, "_car_over_ep", 0) # owned by the control loop h = getattr(c, "_car_why_hold", None) + if h is not None and h[2] != ep: # a hold of an ended episode + h = None if h is None: - h = [bool(cand), None] # shown, since when cand differs + h = [bool(cand), None, ep] # shown, since when, episode elif cand is None or cand == h[0]: h[1] = None else: if h[1] is None: h[1] = mono if mono - h[1] >= WHY_HOLD_S: - h = [cand, None] + h = [cand, None, ep] c._car_why_hold = h return h[0] diff --git a/goodwe_controller/test_ev16.py b/goodwe_controller/test_ev16.py index 64a8d84..22ed817 100644 --- a/goodwe_controller/test_ev16.py +++ b/goodwe_controller/test_ev16.py @@ -2,7 +2,9 @@ they can" while the car-over row holds and the guard's floor flag toggles. `python3 -B test_ev16.py` -Display only: the text is held in `c._car_why_hold`; control never reads it. +Display only: the text is held in `c._car_why_hold`; control never reads it. Control owns +`c._car_over_ep` (bumped at each start and end of car_over); a hold of +another episode is never used. Mutant: pick the text from the live `floor_limited` again (T1, T2, T7, T8, T9 go red). Mutating a module this file grades? Read MUTATION.md first. @@ -279,9 +281,10 @@ run(c, 100.0, lambda t: G()) c._car_prev_state = "charging" c.state = CH.NONE_ c._now = 105.0 +ep_before = c._car_over_ep c.car_cycle(Proj(), G(), 14000.0, None) -check("T11 (cont.) the unplug clears the hold itself", - c.car_over is False and getattr(c, "_car_why_hold", "x") is None) +check("T11 (cont.) the unplug ends the episode (control bumps it)", + c.car_over is False and c._car_over_ep > ep_before) # T12: cover off while car_over holds c = S() @@ -350,6 +353,102 @@ check("a held peak_guard row is not touched: the module still has no hold " "in ctl_status", "_car_why_hold" not in open(os.path.join( HERE, "app", "ctl_status.py")).read()) +print("\n6. EV-16 review round 1: the race, T16, T18, the N-ids") +# the race: a read takes the hold, control ends the episode, the read writes +# its old hold back; the next episode must not show it +c = S() +run(c, 100.0, lambda t: G()) +stale = c._car_why_hold +check("race: the read holds 'are at' before the end", kind(why(c)) == "over") +for k in range(0, 200): + c._now = 100.0 + k + c.w = None + c.car_cycle(Proj(), G(), 14000.0, None) +c._car_why_hold = stale # the late write-back +c.car_over = True +c._car_over_ep += 1 # what control does on a start +c._now = 6000.0 +c.peak_guard = G(floor_limited=False, soc=60.0) +check("N4 race: a read interleaved with the clear cannot bring the old " + "'are at' into the next episode", kind(why(c)) == "full") +c = S() +run(c, 100.0, lambda t: G()) +stale = c._car_why_hold +c._car_prev_state = "charging" +c.state = CH.NONE_ +c._now = 105.0 +c.car_cycle(Proj(), G(), 14000.0, None) +c._car_why_hold = stale # write-back after an unplug +c.state = "charging" +c.car_over = True +c.peak_guard = G(floor_limited=False, soc=60.0) +c._now = 110.0 +check("N4 race (unplug): a stale write-back after the unplug is not used", + kind(why(c)) == "full") + +# T16: the existing checks this one must leave alone are present and run in CI +for f in ("test_ev04.py", "test_ev10.py", "test_ev10b.py", "test_ev18.py", + "test_ev19.py", "test_home.py", "test_named_absence.py", + "test_bytecode.py"): + check(f"T16 {f} exists (run unchanged by CI's run-tests.sh)", + os.path.exists(os.path.join(HERE, f))) +t04 = open(os.path.join(HERE, "test_ev04.py")).read() +check("T16 test_ev04's Manual Why assertion 'batteries give all they can' " + "is still there", 'batteries give all they can" in cardwhy' in t04) + +# T18: the mutant, in process: the live flag picks the text again +real = homeview._over_why_is_floor +homeview._over_why_is_floor = lambda c, pg: bool( + pg is not None and pg.floor_limited) +try: + m = run(S(), Q, toggle(10.0, True)) + m8 = run(S(), Q, lambda t: G(soc=None)) +finally: + homeview._over_why_is_floor = real +check("T18 mutant (live flag): T1 shape alternates and T8 shows 'are at', so " + "T1, T2, T7 and T8 would go red", len(changes(m)) > 20 + and any(k == "over" for _, k in m8)) + +# the N-ids, by name +a = run(S(), Q, toggle(10.0, True)) +check("N1 control: batteries, charger writes and setpoint equal base " + "(digests, section 4)", (digest(ctl1), digest(rows1), digest(flags1)) + == BASE_8150608) +check("N2 `floor_limited`, `car_explains`, `car_over`, the peak_guard row " + "are not changed by the hold: the guard flag toggles as in base " + "(flags digest) and the rows digest equals base", + digest(flags1) == BASE_8150608[2] and digest(rows1) == BASE_8150608[1]) +n3 = run(S(), Q, lambda t: G(soc=None)) + run( + S(), Q, lambda t: G(floor_limited=False, soc=40.0)) +check("N3 never 'are at' with SoC unread or with the guard never limited", + {k for _, k in n3} == {"full"}) +c = S() +run(c, 100.0, lambda t: G()) +c.car_over = False +n4 = homeview._car_manual_why(c, "charging") +check("N4 no over wording once car_over is off", OVER not in n4 + and FULL not in n4) +check("N5 at most one Why change in a quarter while the guard toggles", + len(changes(a)) <= 1) +try: + for g in (None, G(soc=None), G(), G(floor_limited=False, soc=1.0)): + c = S() + c.peak_guard = g + why(c) + n6 = True +except Exception: # noqa: BLE001 + n6 = False +check("N6 no Traceback for a guard of None, SoC unread, limited, not " + "limited", n6) +en = open(os.path.join(HERE, "app", "ui_text", "en.json")).read() +nl = open(os.path.join(HERE, "app", "ui_text", "nl.json")).read() +check("N7 wording unchanged: the four texts are in the files verbatim", + "The batteries are at {pct}, so this charge sets the peak." in en + and "The batteries give all they can, so this charge sets the peak." + in en and "De batterijen staan op {pct}, dus deze lading bepaalt de " + "piek." in nl and "De batterijen geven alles, dus deze lading bepaalt " + "de piek." in nl) + print() print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") sys.exit(1 if fails else 0) -- 2.54.0 From c707eb47764ab7b4bba878ed313ca7f3a019514e Mon Sep 17 00:00:00 2001 From: "Claude (dev)" Date: Sat, 21 Nov 2026 11:23:13 +0100 Subject: [PATCH 14/55] EV-16: time the Car Why hold on the control cycle, not on page reads car_cycle ends with _car_why_tick (display only: control writes, never reads); the Why reads the record. Adds read-gap tests (A, B, cover off/on), a long guard-None test and a lower bound for the hold. Co-Authored-By: Claude --- goodwe_controller/app/ctl_car.py | 36 +++++++-- goodwe_controller/app/homeview.py | 36 +++------ goodwe_controller/test_ev16.py | 117 ++++++++++++++++++++++++------ 3 files changed, 134 insertions(+), 55 deletions(-) diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 391fae2..eeb660c 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -61,8 +61,8 @@ class CarMixin: self.car_over = False # ... held: the card and row say so self._car_over_since = None self._car_over_gone = None - self._car_why_hold = None # EV-16: the held Car Why (display) - self._car_over_ep = 0 # EV-16: bumped by control at each start/end of car_over; the hold is valid for one value + self._car_why_rec = None # EV-16: [shown over, since, episode] + self._car_over_ep = 0 # EV-16: bumped when car_over ends self._car_batt_prev = self._car_batt_prev2 = None self._car_hx_prev = None # EV-19: last cycle's (held, car W) self._car_need_real = self._car_need_excl = False # EV-10 latches @@ -394,16 +394,40 @@ class CarMixin: if self._car_over_since is None: self._car_over_since = mono if mono - self._car_over_since >= OVER_HOLD_S: - if not self.car_over: - self._car_over_ep += 1 # EV-16: a new episode self.car_over = True else: if self._car_over_gone is None: self._car_over_gone = mono if mono - self._car_over_gone >= OVER_OFF_HOLD_S: self.car_over, self._car_over_since = False, None - self._car_over_ep += 1 # EV-16: ends the held Why + self._car_over_ep += 1 # EV-16: an episode ends self._car_over_gone = None + self._car_why_tick(guard, mono) + + def _car_why_tick(self, guard, mono) -> None: + """EV-16, display only: control writes `_car_why_rec`, never reads it. + The Car Why text ("are at" / "give all they can") is held: it changes + only when the other state has stood for `OVER_OFF_HOLD_S` of THIS + cycle's clock (so reads of /status do not matter). State: floor-limited + with the SoC read; a guard of None, or unread SoC, never counts as + floor. Cleared when car_over is off or the cover is off.""" + if not (self.car_over and self.car_cover): + self._car_why_rec = None + return + cand = None if guard is None else bool( + getattr(guard, "floor_limited", False) + and getattr(guard, "soc", None) is not None) + ep = self._car_over_ep + r = self._car_why_rec + if r is None or r[2] != ep: + self._car_why_rec = [bool(cand), None, ep] + elif cand is None or cand == r[0]: + r[1] = None + else: + if r[1] is None: + r[1] = mono + if mono - r[1] >= OVER_OFF_HOLD_S: + self._car_why_rec = [cand, None, ep] def _car_explains_alarm(self, real_proj, guard, target_w, w) -> bool: """EV-10: is the alarm's own test true with the car and false without @@ -502,7 +526,7 @@ class CarMixin: # The session is over: that is a real end, with no hold. self.car_over = False self._car_over_since = self._car_over_gone = None - self._car_over_ep += 1 # EV-16: ends the held Why + self._car_over_ep += 1 # EV-16: an episode ends if s not in (chargers.NONE_, None) and self._car_prev_state in ( chargers.NONE_, None): self._car_session += 1 diff --git a/goodwe_controller/app/homeview.py b/goodwe_controller/app/homeview.py index 8c317c0..4774469 100644 --- a/goodwe_controller/app/homeview.py +++ b/goodwe_controller/app/homeview.py @@ -1302,34 +1302,20 @@ def _car_why(key, c, good): # EV-16: the Why of "car over the limit" follows the guard's floor flag, which -# toggles cycle by cycle at the reserve. The text is held: it changes only when -# the other state has stood for as long as the car_over row's own hold. +# toggles cycle by cycle at the reserve. The text is held, on the control +# cycle's clock (`ctl_car.CarMixin._car_why_tick`, display only: control writes +# `_car_why_rec`, never reads it). The Why only reads it. WHY_HOLD_S = 180.0 # = ctl_car.OVER_OFF_HOLD_S (tested) def _over_why_is_floor(c, pg) -> bool: - """True: "are at {pct}"; False: "give all they can". Display only: the - state lives in `c._car_why_hold`, stamped with the episode `c._car_over_ep` - that control bumps; a hold of another episode is never used, so a read - overlapping the end of car_over cannot bring a stale text back.""" - mono = c.car_now() - cand = (pg.floor_limited and pg.soc is not None) if pg is not None \ - else None - ep = getattr(c, "_car_over_ep", 0) # owned by the control loop - h = getattr(c, "_car_why_hold", None) - if h is not None and h[2] != ep: # a hold of an ended episode - h = None - if h is None: - h = [bool(cand), None, ep] # shown, since when, episode - elif cand is None or cand == h[0]: - h[1] = None - else: - if h[1] is None: - h[1] = mono - if mono - h[1] >= WHY_HOLD_S: - h = [cand, None, ep] - c._car_why_hold = h - return h[0] + """True: "are at {pct}"; False: "give all they can". With no valid held + record (not yet ticked, or of an ended episode) the live state, written + nowhere.""" + rec = getattr(c, "_car_why_rec", None) + if rec is not None and rec[2] == getattr(c, "_car_over_ep", 0): + return rec[0] + return bool(pg is not None and pg.floor_limited and pg.soc is not None) def _car_manual_why(c, key): @@ -1342,11 +1328,9 @@ def _car_manual_why(c, key): if c.car_over: pg = getattr(c, "peak_guard", None) if not c.car_cover: - c._car_why_hold = None return _t("car.why.manual_nocover", a=a) return _t("car.why.manual_over" if _over_why_is_floor(c, pg) else "car.why.manual_full", a=a, pct=pct) - c._car_why_hold = None if c.shadow: t, n = w.would if w.would is not None else (c.car_a, c.car_n) return _t("car.why.manual_would", a=f"{float(t):.0f}", diff --git a/goodwe_controller/test_ev16.py b/goodwe_controller/test_ev16.py index 22ed817..dab89da 100644 --- a/goodwe_controller/test_ev16.py +++ b/goodwe_controller/test_ev16.py @@ -2,8 +2,9 @@ they can" while the car-over row holds and the guard's floor flag toggles. `python3 -B test_ev16.py` -Display only: the text is held in `c._car_why_hold`; control never reads it. Control owns -`c._car_over_ep` (bumped at each start and end of car_over); a hold of +Display only: the text is held by `ctl_car._car_why_tick` on the control +cycle's clock (control writes `_car_why_rec`, never reads it; /status reads do +not move it). `c._car_over_ep` is bumped when car_over ends; a record of another episode is never used. Mutant: pick the text from the live `floor_limited` again (T1, T2, T7, T8, T9 go red). @@ -94,13 +95,19 @@ def kind(t): return "over" if OVER in t else "full" if FULL in t else t +def tick(c, g, t): + """One control cycle's display tick (what car_cycle ends with).""" + c._now = t + c.peak_guard = g + c._car_why_tick(g, t) + + def run(c, secs, g_of, t0=0.0): """Read the Why once per 5 s cycle; returns [(t, kind)].""" out = [] t = t0 while t < t0 + secs: - c._now = t - c.peak_guard = g_of(t - t0) + tick(c, g_of(t - t0), t) out.append((t, kind(why(c)))) t += STEP return out @@ -212,9 +219,8 @@ check("T8 SoC toggling None / 20 % every 10 s, starting unread: one text, " c = S() seq = [] for t in range(0, 900, 5): - c._now = float(t) - c.peak_guard = None if 400 <= t < 410 else G(floor_limited=(t // 10) % 2 - == 0) + tick(c, None if 400 <= t < 410 else G(floor_limited=(t // 10) % 2 + == 0), float(t)) try: seq.append((t, kind(why(c)))) except Exception as e: # noqa: BLE001 @@ -222,8 +228,7 @@ for t in range(0, 900, 5): check("T9 guard None for a cycle: no Traceback, one text through it", not any("TRACE" in k for _, k in seq) and len({k for _, k in seq}) == 1) c = S() -c.peak_guard = None -c._now = 0.0 +tick(c, None, 0.0) check("T9 (cont.) guard None from the very first read: a text, no Traceback", kind(why(c)) in ("full", "over")) @@ -239,8 +244,7 @@ check("T10 car_over dropped after the stop", c.car_over is False) check("T10 the Why left the over wording", OVER not in why(c) and FULL not in why(c)) c.car_over = True # a new episode, later, SoC 60 % -c._now = 5000.0 -c.peak_guard = G(floor_limited=False, soc=60.0) +tick(c, G(floor_limited=False, soc=60.0), 5000.0) check("T10 the new episode shows 'give all they can' from its first cycle", kind(why(c)) == "full") @@ -253,8 +257,8 @@ for k in range(0, 200): c.w = None c.car_cycle(Proj(), G(), 14000.0, None) c.car_over = True -c._now = 9000.0 c.peak_guard = G(floor_limited=False, soc=60.0) +c._now = 9000.0 check("T10 no /status between the drop and the new episode: still 'full'", kind(why(c)) == "full") @@ -272,8 +276,7 @@ check("T11 after the unplug cycle there is no over wording", and "set when a car is connected" in homeview._car_manual_why(c, "none")) c.state = "charging" c.car_over = True -c.peak_guard = G(floor_limited=False, soc=60.0) -c._now = 400.0 +tick(c, G(floor_limited=False, soc=60.0), 400.0) check("T11 a replug starts with no held text", kind(why(c)) == "full") # the hold is also gone when the unplug itself ends car_over (no read between) c = S() @@ -290,12 +293,11 @@ check("T11 (cont.) the unplug ends the episode (control bumps it)", c = S() run(c, 100.0, lambda t: G()) c.o["ev_batt_cover"] = False -c._now = 105.0 +tick(c, G(), 105.0) check("T12 cover off: 'ignores the car' at the next read", "ignores the car" in why(c)) c.o["ev_batt_cover"] = True -c.peak_guard = G(floor_limited=False, soc=60.0) -c._now = 110.0 +tick(c, G(floor_limited=False, soc=60.0), 110.0) check("T12 cover on again, steady not limited: 'give all they can', not " "the old 'are at'", kind(why(c)) == "full") @@ -350,7 +352,7 @@ for lang, over, full in ( check(f"T17 {lang}.json wording of manual_over / manual_full unchanged", d["manual_over"] == over and d["manual_full"] == full) check("a held peak_guard row is not touched: the module still has no hold " - "in ctl_status", "_car_why_hold" not in open(os.path.join( + "in ctl_status", "_car_why_rec" not in open(os.path.join( HERE, "app", "ctl_status.py")).read()) print("\n6. EV-16 review round 1: the race, T16, T18, the N-ids") @@ -358,27 +360,26 @@ print("\n6. EV-16 review round 1: the race, T16, T18, the N-ids") # its old hold back; the next episode must not show it c = S() run(c, 100.0, lambda t: G()) -stale = c._car_why_hold +stale = c._car_why_rec check("race: the read holds 'are at' before the end", kind(why(c)) == "over") for k in range(0, 200): c._now = 100.0 + k c.w = None c.car_cycle(Proj(), G(), 14000.0, None) -c._car_why_hold = stale # the late write-back +c._car_why_rec = stale # the late write-back c.car_over = True -c._car_over_ep += 1 # what control does on a start c._now = 6000.0 c.peak_guard = G(floor_limited=False, soc=60.0) check("N4 race: a read interleaved with the clear cannot bring the old " "'are at' into the next episode", kind(why(c)) == "full") c = S() run(c, 100.0, lambda t: G()) -stale = c._car_why_hold +stale = c._car_why_rec c._car_prev_state = "charging" c.state = CH.NONE_ c._now = 105.0 c.car_cycle(Proj(), G(), 14000.0, None) -c._car_why_hold = stale # write-back after an unplug +c._car_why_rec = stale # write-back after an unplug c.state = "charging" c.car_over = True c.peak_guard = G(floor_limited=False, soc=60.0) @@ -449,6 +450,76 @@ check("N7 wording unchanged: the four texts are in the files verbatim", "piek." in nl and "De batterijen geven alles, dus deze lading bepaalt " "de piek." in nl) +print("\n7. EV-16 review round 2: the hold runs on the control clock") + + +def gap_run(c, g_of, read_at, end=2300.0): + """Control cycles every 5 s; the Why is read only at the `read_at` times.""" + out = [] + t = 0.0 + while t < end: + tick(c, g_of(t), t) + if any(a <= t < b for a, b in read_at): + out.append((t, kind(why(c)))) + t += STEP + return out + + +pages = ((0, 60), (2000, 2300)) +c = S() +r = gap_run(c, lambda t: G(floor_limited=t >= 300.0, soc=20.0), pages) +late = [(t, k) for t, k in r if t >= 2000] +check("review A: drained to the reserve while the page was closed: the " + "first read at t=2000 already shows 'are at'", + len(late) > 0 and late[0][1] == "over" and {k for _, k in late} == {"over"}) +c = S() +r = gap_run(c, lambda t: G(floor_limited=t < 300.0, + soc=20.0 if t < 300.0 else 45.0), pages) +late = [(t, k) for t, k in r if t >= 2000] +check("review B: off the reserve while the page was closed: the first " + "read at t=2000 shows 'give all they can', never a false 'are at'", + len(late) > 0 and late[0][1] == "full" and {k for _, k in late} == {"full"}) +c = S() +r = [] +for t in range(0, 400, 5): + cov = not (100 <= t < 200) + c.o["ev_batt_cover"] = cov + tick(c, G(floor_limited=t < 100, soc=20.0 if t < 100 else 45.0), + float(t)) + if t in (95, 205): + r.append(kind(why(c))) +check("review: cover off and on with no read between: back on, the state " + "now not limited shows 'give all they can' at the first read", + r == ["over", "full"]) +# lower bound of the hold: a real change is NOT shown before the hold ends +c = S() +r = [] +for t in range(0, 600, 5): + tick(c, G(floor_limited=t >= 300.0, soc=20.0), float(t)) + r.append((t, kind(why(c)))) +check("review: a real change is held for the full 180 s: still the old " + "text 170 s after it, the new one by 185 s", + dict(r)[470] == "full" and dict(r)[485] == "over") +# M7: guard None for 180 s or more under car_over +for steady, want in ((True, "over"), (False, "full")): + c = S() + seq = [] + for t in range(0, 1200, 5): + g = G(floor_limited=steady, soc=20.0 if steady else 45.0) \ + if t < 100 else None + tick(c, g, float(t)) + seq.append(kind(why(c))) + check(f"T9 (long) guard None for 1100 s after a steady " + f"{'limited' if steady else 'not limited'} state: the text stays " + f"'{want}', no flip", set(seq) == {want}) +c = S() +seq = [] +for t in range(0, 1200, 5): + tick(c, None, float(t)) + seq.append(kind(why(c))) +check("T9 (long) guard None from the start for 1200 s: one text, 'full'", + set(seq) == {"full"}) + print() print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") sys.exit(1 if fails else 0) -- 2.54.0 From 91cbdf2f43d4b0641b8a10d1ad70b5efd8b89c79 Mon Sep 17 00:00:00 2001 From: EV-16 reviewer Date: Sat, 21 Nov 2026 12:37:06 +0100 Subject: [PATCH 15/55] EV-16 review round 2: pin the unread-SoC rule on the Why's live fallback The fallback (no record yet, or a record of an ended episode) had no check; reading floor_limited alone there survived test_ev16. Test only. Co-Authored-By: Claude --- goodwe_controller/test_ev16.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/goodwe_controller/test_ev16.py b/goodwe_controller/test_ev16.py index dab89da..0d865a6 100644 --- a/goodwe_controller/test_ev16.py +++ b/goodwe_controller/test_ev16.py @@ -519,6 +519,19 @@ for t in range(0, 1200, 5): seq.append(kind(why(c))) check("T9 (long) guard None from the start for 1200 s: one text, 'full'", set(seq) == {"full"}) +# review round 2: the live fallback (no record yet, or one of an ended +# episode) keeps the unread-SoC rule too +for label, rec in (("no record yet", None), + ("a record of an ended episode", [True, None, -1])): + c = S() + c._now = 0.0 + c._car_why_rec = rec + c.peak_guard = G(soc=None) + check(f"N3 {label}: limited with SoC unread is not 'are at'", + kind(why(c)) == "full") + c.peak_guard = G() + check(f"N3 {label}: limited with SoC read shows 'are at' (live state)", + kind(why(c)) == "over") print() print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed") -- 2.54.0 From af374026b1beb51883f66e2558c14df0269100ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 18:33:08 +0100 Subject: [PATCH 16/55] CI-20: bump infra-pin to admin/goodwe release/1.0 f884612 Co-Authored-By: Claude --- .gitea/infra-pin | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitea/infra-pin b/.gitea/infra-pin index f01d2b5..1bdc5ea 100644 --- a/.gitea/infra-pin +++ b/.gitea/infra-pin @@ -1,2 +1,2 @@ # The admin/goodwe commit CI tests against. Bump: set to the full SHA of admin/goodwe release/1.0 HEAD (README.md, "CI and the infra pin"). -3b4ff84757f9c2c5b63a4b4a53e593ccaeafb847 +f88461234f3a7d53c025a68beda4cb6e4384cebf -- 2.54.0 From 83f114fe084dda08904098a2c267b3234063f831 Mon Sep 17 00:00:00 2001 From: "Claude (dev agent)" Date: Sat, 21 Nov 2026 21:04:13 +0100 Subject: [PATCH 17/55] EV-28: never select the phases while the car still draws Stage zero counted mode3 B as quiet whatever the power and selected at the 20 s timeout under load. A power reading now decides (under 100 W); mode3 (not C, not D) only without one. Still drawing at 20 s: no select, the current comes back at once, one failed try, next try PHASE_GAP_S later. Co-Authored-By: Claude --- goodwe_controller/CHANGELOG.md | 1 + .../DECISIONS/EV-04-manual-mode.md | 8 +- goodwe_controller/app/carmode.py | 33 +- goodwe_controller/test_ev04.py | 30 +- goodwe_controller/test_ev28.py | 936 ++++++++++++++++++ 5 files changed, 992 insertions(+), 16 deletions(-) create mode 100644 goodwe_controller/test_ev28.py diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index 0d68c33..bf5a514 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -2,6 +2,7 @@ ### Not in a release yet +- 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]]). ## 0.24.0 diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index 4fb034b..607569f 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -30,9 +30,11 @@ code had to decide that the design left open. ## The phase sequence -0 A, wait until the charger reports under 100 W or mode3 leaves C (20 s at most), -select the phases, wait 10 s, write the current. One switch per 10 minutes. A -charger that does not take the 0 A never gets the phases select. A sequence that +0 A, wait until the charger reports under 100 W (mode3 leaving C counts only +when there is no power reading; 20 s at most), select the phases, wait 10 s, write the current. One switch per 10 minutes. A +charger that does not take the 0 A never gets the phases select. A car still +drawing after 20 s gets no select: its current comes back and it counts as a +failed try (EV-28). A sequence that has begun is finished whatever the mode, because it leaves the car at 0 A otherwise; a stop of the add-on in the middle gives the car its current back (`car_shutdown`). diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 39bf326..dbaafb0 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -15,8 +15,9 @@ THE RULES, each tested in test_ev04.py: reports, the entity's own range)`. The driver refuses anything above it; this module never asks for more. * Phases change only through the SAFE SEQUENCE: 0 A, wait until the charger - reports under `QUIET_W` or mode3 leaves C (at most `ZERO_WAIT_S`), select the - phases, wait `SETTLE_S`, write the current again. At most one switch per + reports under `QUIET_W` (mode3 leaving C only without a power reading; at + most `ZERO_WAIT_S`, then the current comes back and it counts as a failed + try), select the phases, wait `SETTLE_S`, write the current again. At most one switch per `PHASE_GAP_S`. A sequence that has begun is always finished, because it leaves the car at 0 A otherwise. * A read-back that differs from the add-on's own last write for `WRITER_S` is @@ -333,11 +334,29 @@ class ManualWriter: "phase change, so the phases were not touched.") return if q["stage"] == "zero": - quiet = ((r.power_w is not None and r.power_w < QUIET_W) - or (r.state is not None and r.state != "C")) - if not quiet and now - q["t0"] < ZERO_WAIT_S: - return - q["stage"] = "select" + # A power reading decides; only without one does mode3 (not C, + # not D) say the car is quiet. Still drawing at the timeout: no + # select, the current comes back (EV-28). + if r.power_w is not None: + quiet = r.power_w < QUIET_W + else: + quiet = r.state is not None and r.state not in ("C", "D") + if not quiet: + if now - q["t0"] < ZERO_WAIT_S: + return + self.last_switch = now + self.phase_fails += 1 + q["failed"] = True # EV-15: no grace for the alarm + q["stage"], q["t1"] = "settle", now - SETTLE_S # restore now + _LOG.warning("The car kept drawing, so the phases were not " + "changed.") + 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.") + else: + q["stage"] = "select" if q["stage"] == "select": ok = await drv.write_phases(q["n"]) self._stamp(now) diff --git a/goodwe_controller/test_ev04.py b/goodwe_controller/test_ev04.py index 1b28031..fdc83e7 100644 --- a/goodwe_controller/test_ev04.py +++ b/goodwe_controller/test_ev04.py @@ -613,10 +613,15 @@ async def slow_stop(): w5s, n05s = run(slow_stop()) seq5s = w5s.writes()[n05s:] -check("a car that is slow to stop: the phases are selected after 20 s at most " - f"({seq5s[1][0] - seq5s[0][0]:.0f} s after the 0 A)", - [x[1] for x in seq5s][:2] == ["current", "phases"] - and 19.0 <= seq5s[1][0] - seq5s[0][0] <= 22.0) +# EV-28: a car still drawing at 20 s gets no select; the current comes back +rest5s = [x for x in seq5s if x[1] == "current" and x[2] == 10.0] +check("a car that is slow to stop (about 1300 W after 20 s): the phases are " + "NOT selected, the add-on gives up at 20 s, the 10 A come back at once " + f"({[(x[1], x[2]) for x in seq5s]}), one failed try", + [x[1] for x in seq5s].count("phases") == 0 + and [x[2] for x in seq5s if x[1] == "current"][:2] == [0.0, 10.0] + and rest5s and 20.0 <= rest5s[0][0] - seq5s[0][0] <= 21.0 + and w5s.sim.phases_allowed == 1 and w5s.c.car_writer.phase_fails == 1) async def zero_refused(): @@ -890,9 +895,11 @@ check("the write paths are exactly these (all in carmode.py): the current " ("carmode.py", "write_phases")]) -async def fuzz(seed): +async def fuzz(seed, slow=False): rnd = random.Random(seed) w = World(setpoint=rnd.choice([6, 10, 16]), phases=rnd.choice([1, 3])) + if slow: # EV-28: the car's power ramps down slowly + w.sim.ramp_w_s, w.sim.stop_delay_s = 200.0, float(seed % 2) w.sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0]) race = seed % 2 == 1 # half the sites run read -> settle -> cycle bad, seen, others, holds, undos = [], 0, 0, 0, 0 @@ -961,6 +968,9 @@ async def fuzz(seed): bad.append((seed, step, "phases selected outside Manual")) if sp != 0.0: bad.append((seed, step, "phases with the setpoint up", sp)) + if power >= carmode.QUIET_W: # EV-28 (N1) + bad.append((seed, step, "phases selected under load", + power)) if last_switch is not None and t - last_switch < 600.0: bad.append((seed, step, "two switches inside 10 min", t - last_switch)) @@ -977,7 +987,15 @@ for _seed in range(14): fz_o += _o fz_h += _h fz_u += _u -check(f"fuzz: {fz_n} charger writes over 14 random sites and 5600 steps of " +for _seed in range(100, 104): # EV-28: ramp 200 W/s, B after 0 or 1 s + _b, _n, _o, _h, _u = run(fuzz(_seed, slow=True)) + fz_bad += _b + fz_n += _n + fz_o += _o + fz_h += _h + fz_u += _u +check(f"fuzz: {fz_n} charger writes over 18 random sites (4 of them with a " + f"car that stops at 200 W/s) and 7200 steps of " 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 " diff --git a/goodwe_controller/test_ev28.py b/goodwe_controller/test_ev28.py new file mode 100644 index 0000000..378c3a1 --- /dev/null +++ b/goodwe_controller/test_ev28.py @@ -0,0 +1,936 @@ +"""EV-28: the phases are never selected while the car still draws. +`python3 -B test_ev28.py` + +The stage "zero" of the phase sequence counted mode3 B as quiet whatever the +power, and selected anyway after ZERO_WAIT_S. Now: a power reading decides +(under QUIET_W); mode3 (not C, not D) only without one; a car still drawing at +the timeout gets NO select, its current back at once, and one failed try. + +U = the ManualWriter on a stub driver (exact seconds). W = the real Controller +on the charger model (`chargersim`, power ramps down at `ramp_w_s`). + +1. U: what counts as quiet (T1, T3, T4, T6, T7, T8). +2. W: the rig shapes (T2, T5, T9, T10, T16, T17). +3. W: tries, the amber row, the log (T11, T12, T13). +4. W: the other ends of a sequence and the alarm (T14, T15, T18-T21). +5. W: the digests of the quiet shapes, from 4eba2d9 (T22). +6. Docs and the module docstring (T25). T23 is in test_ev04 (slow_stop), T24 + its fuzz. Mutants (T26): see the dev report. +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import hashlib +import logging +import os +import sys +from datetime import datetime + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode, chargers as CH, ctl_car # noqa: E402 +from app.carmode import ManualWriter, QUIET_W, ZERO_WAIT_S # noqa: E402 +from app.carmode import SETTLE_S, PHASE_GAP_S, MAX_TRIES # noqa: E402 +from app.main import Controller # noqa: E402 +from app import freshness # noqa: E402 +from named_absence import nth # noqa: E402 +from chargersim import FakeHa, SimCharger # noqa: E402 +import ev04_peak as P # noqa: E402 +import safety81_sim as s81 # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +class _Cap(logging.Handler): + def __init__(self): + super().__init__(logging.DEBUG) + self.rec = [] + + def emit(self, r): + self.rec.append((r.levelno, r.getMessage())) + + def loud(self, since=0): + """INFO and above from `since` on.""" + return [m for lv, m in self.rec[since:] if lv >= logging.INFO] + + +CAP = _Cap() +logging.getLogger("goodwe").addHandler(CAP) +logging.getLogger("goodwe").setLevel(logging.DEBUG) + + +def run(coro): + return asyncio.run(coro) + + +# =========================================================================== # +# U: the writer on a stub driver +# =========================================================================== # +class Drv: + def __init__(self, phases=1, a=10.0, ok_phases=True): + self.log, self.now, self.phases, self.a = [], 0.0, phases, a + self.ok_phases = ok_phases + + async def write_current(self, a): + self.log.append((self.now, "current", float(a))) + self.a = float(a) + return True + + async def write_phases(self, n): + self.log.append((self.now, "phases", n)) + if self.ok_phases: + self.phases = n + return self.ok_phases + + +class Trk: + obs_at = None + + def begin_write(self): + pass + + def end_write(self, *_a): + pass + + def note_write(self, *_a): + pass + + +async def unit(fn, times=None, want_phases=3, want_a=10.0, clamp_fn=None, + n_phases=1, a0=10.0, ok_phases=True): + """0 A is written at t=0. `fn(dt)` is (mode3, power_w) `dt` s later, or None + (unavailable). Returns (writer, driver, abandon time or None).""" + w, d = ManualWriter(), Drv(phases=n_phases, a=a0, ok_phases=ok_phases) + trk = Trk() + + async def step(t, state, power): + d.now = float(t) + a = d.a + r = CH.ChargerReading(available=state is not None, state=state, + power_w=power, setpoint_a=a, allowed_a=a, + phases_allowed=d.phases) + await w.step(d, r, mode="manual", want_a=want_a, + want_phases=want_phases, rev=1, + clamp=clamp_fn(t) if clamp_fn else 16.0, now=float(t), + tracker=trk, writing=True, status="charging", + clock=lambda: float(t)) + await step(0.0, "C", 2300.0) + aband = None + for t in (times if times is not None else range(1, 41)): + x = fn(t) + if x is None: + await step(t, None, None) + else: + await step(t, x[0], x[1]) + if aband is None and w.seq is not None \ + and w.seq["stage"] == "settle" and w.seq.get("failed") \ + and not d.log[-1][1] == "phases": + aband = t + if aband is None and w.seq is None and w.phase_fails: + aband = t + return w, d, aband + + +def phases_at(d): + return [x for x in d.log if x[1] == "phases"] + + +print("1. U: WHAT COUNTS AS QUIET") +for p in (600.0, 1200.0, 2152.0, 2200.0): + w, d, ab = run(unit(lambda t, p=p: ("B", p), range(1, 20))) + check(f"T1: B with {p:.0f} W for 19 s: no select ({d.log})", + not phases_at(d) and w.seq is not None + and w.seq["stage"] == "zero") + +w, d, ab = run(unit(lambda t: ("B", 40.0 if t >= 10 else 2152.0), + range(1, 15))) +sel = [x[0] for x in phases_at(d)] +check(f"T3: the live Alfen shape (B, 2152 W to t0+9, 40 W at t0+10): select " + f"at t0+10 and not before ({sel})", sel == [10.0]) + +w, d, ab = run(unit(lambda t: ("B", 100.0), range(1, 20))) +check("T4: exactly 100.0 W with B: not quiet, no select (strict <)", + not phases_at(d)) +for p, st in ((99.9, "C"), (0.0, "B"), (-5.0, "C")): + w, d, ab = run(unit(lambda t, p=p, st=st: (st, p), range(1, 4))) + check(f"T4: {p} W with {st}: select on the first step ({d.log})", + [x[0] for x in phases_at(d)] == [1.0]) + +w, d, ab = run(unit(lambda t: ("B", 30.0) if t >= 20 else ("C", 2000.0), + [19.9, 20.0, 21.0])) +check(f"T6: quiet first seen at exactly t0+20: select at 20 ({d.log})", + [x[0] for x in phases_at(d)] == [20.0]) +w, d, ab = run(unit(lambda t: ("B", 500.0), [19.9, 20.0, 21.0])) +check("T6: still drawing at 19.9: waits; at 20.0: no select, abandoned " + f"({d.log}, abandon {ab})", + not phases_at(d) and ab == 20.0 and w.phase_fails == 1 + and d.log[-1] == (20.0, "current", 10.0)) +w, d, ab = run(unit(lambda t: ("B", 500.0), [19.9])) +check("T6: at 19.9 s the sequence still waits", + w.seq is not None and w.seq["stage"] == "zero" and w.phase_fails == 0) + +w, d, ab = run(unit(lambda t: ("B", None), range(1, 4))) +check("T7: no power reading and B: select on the first step, as before", + [x[0] for x in phases_at(d)] == [1.0]) +w, d, ab = run(unit(lambda t: ("D", None), range(1, 30))) +check("T7/Expected 2: no power reading and D (charging with ventilation) is " + "not quiet: no select", not phases_at(d)) +# state None needs an available reading with state None: own helper +async def unit_blind(state): + w, d = ManualWriter(), Drv() + trk = Trk() + for t in range(0, 26): + d.now = float(t) + a = d.a + r = CH.ChargerReading(available=True, state=("C" if t == 0 else state), + power_w=2300.0 if t == 0 else None, + setpoint_a=a, allowed_a=a, + phases_allowed=d.phases) + await w.step(d, r, mode="manual", want_a=10.0, want_phases=3, rev=1, + clamp=16.0, now=float(t), tracker=trk, writing=True, + status="charging", clock=lambda: float(t)) + return w, d + + +for st in ("C", None): + w, d = run(unit_blind(st)) + check(f"T8: no power reading, state {st}: no select ever, abandon at " + f"t0+20, one restore, one failed try ({d.log})", + not phases_at(d) and w.phase_fails == 1 and w.seq is None + and d.log == [(0.0, "current", 0.0), (20.0, "current", 10.0)]) + +# the abandon is immediate: no SETTLE_S wait (brief answer 1) +w, d, ab = run(unit(lambda t: ("C", 900.0), range(1, 26))) +check(f"Expected 3: the current comes back at the abandon step itself, not " + f"after SETTLE_S ({d.log})", + d.log == [(0.0, "current", 0.0), (20.0, "current", 10.0)] + and w.last_switch == 20.0) +w, d, ab = run(unit(lambda t: ("C", 900.0), range(1, 26), + clamp_fn=lambda t: 16.0 if t < 10 else 8.0, want_a=16.0)) +check(f"N2: the restore is clamped at the abandon ({d.log[-1]})", + d.log[-1] == (20.0, "current", 8.0)) + +# =========================================================================== # +# W: the real Controller on the charger model +# =========================================================================== # +freshness.monotonic = lambda: CLOCK[0] +CLOCK = [1000.0] +SET = "number.wallbox_power_connector_max_current_socket_1" +BASE = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid", + "soc_entity": "sensor.soc", "batt_entity": "sensor.batt", + "meter_source": "off", "max_w": 5000, "gain": 0.6, "slew_w": 500, + "deadband_w": 15, "target_grid_w": 0, "step_w": 10, "heartbeat_s": 10, + "stale_input_s": 15, "shadow_mode": "off", "peak_cap_w": 3500, + "pv_entities": ["sensor.pv"]} +CAR = dict(BASE, ev_charger="alfen_ha", ev_max_a=16, ev_phases="auto", + ev_current_entity=SET) + + +class _Store: + def __init__(self): + self.data = {} + + def set(self, k, v): + self.data[k] = v + + def get(self, k, d=None): + return self.data.get(k, d) + + def set_time(self, k, v): + self.data[k] = v.isoformat() + + def get_time(self, k): + v = self.data.get(k) + return None if v is None else datetime.fromisoformat(v) + + +class _Pub: + enabled = False + + def publish(self, v): + pass + + def close(self): + pass + + +class Site(FakeHa): + def __init__(self, charger, grid=500.0, batt=0.0, pv=2000.0): + super().__init__(charger, None) + self.grid, self.batt, self.pv = grid, batt, pv + + async def limits(self, _e): + return (-5000.0, 5000.0, 1.0) + + def _all(self): + out = super()._all() + for eid, val, unit_ in (("sensor.grid", self.grid, "W"), + ("sensor.soc", 50.0, "%"), + ("sensor.batt", self.batt, "W"), + ("sensor.pv", self.pv, "W")): + out[eid] = {"entity_id": eid, "state": str(val), + "attributes": {"unit_of_measurement": unit_}} + return out + + async def number(self, entity_id, invert=False): + s = self._all().get(entity_id) + try: + v = float(s["state"]) + except (TypeError, ValueError, KeyError): + return None + return -v if invert else v + + async def set_number(self, entity_id, value): + if entity_id == "number.sp": + self.sets.append((entity_id, float(value))) + self.batt = float(value) + return True + return await super().set_number(entity_id, float(value)) + + +class World: + def __init__(self, opts=CAR, sim=None, store=None, setpoint=10, grid=800.0, + phases=1): + self.sim = sim or SimCharger(setpoint_a=setpoint) + self.sim.plug_in() + self.sim.phases_allowed = phases + self.site = Site(self.sim, grid=grid) + self.store = store or _Store() + self.t = 1000.0 + CLOCK[0] = self.t + self.make(opts) + + def make(self, opts): + self.opts = dict(opts) + self.c = Controller(dict(opts), self.site, self.store, _Pub(), + stop=asyncio.Event()) + self.c.auto = True + self.c.dev_min, self.c.dev_max = -5000.0, 5000.0 + self.drv = self.c.charger + if hasattr(self.drv, "_sleep"): + self.drv._sleep = self.sleep + self.drv._clock = lambda: CLOCK[0] + + async def sleep(self, s): + self.sim.tick(s) + self.t += s + CLOCK[0] = self.t + + async def step(self, n=1, dt=1.0): + 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.cycle() + await self.c.car_settle() + + async def step_race(self, n=1, dt=1.0): + 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) + + def writes(self, what=None): + return self.sim.writes(what) + + def rows(self): + return {r["id"]: r for r in self.c.checks()} + + @property + def wr(self): + return self.c.car_writer + + +async def ready(phases=1, a=10, to=3, ramp=200.0, delay=1.0, opts=CAR, + station=None): + """The car draws `a` A on `phases`; the add-on is in Manual at `a`; the + sim's power then falls at `ramp` W/s and B comes `delay` s after 0 A.""" + w = World(opts, setpoint=a, phases=phases) + if station: + w.sim.station_a = float(station) + await w.step(8) + await w.act("car_phases", phases) # the wish is what the car has + await w.act("car_mode", "manual") + await w.act("car_current", a) + await w.step(8) + w.sim.ramp_w_s, w.sim.stop_delay_s = ramp, delay + w.n0 = len(w.writes()) + MARK[0] = len(CAP.rec) + await w.act("car_phases", to) + return w + + +def t_zero(w): + z = [x for x in w.writes("current")[w.n0 // 1:] if x[2] == 0.0] + z = [x for x in w.writes("current") if x[2] == 0.0] + return z[-1][0] if z else None + + +def seqw(w): + return [(x[1], x[2]) for x in w.writes()[w.n0:]] + + +print("\n2. W: THE RIG SHAPES") + + +MARK = [0] + + +async def t2(): + w = await ready(1, 10, 3) + await w.step(60) + return w + + +w = run(t2()) +t0 = t_zero(w) +ph = w.writes("phases") +check(f"T2: 1 ph 10 A at 2300 W -> 3 ph: writes are exactly [0, phases 3, " + f"10] ({seqw(w)})", seqw(w) == [("current", 0.0), ("phases", 3), + ("current", 10.0)]) +check(f"T2: select with power under 100 W ({ph[0][3]:.0f}) and the setpoint " + f"at 0 A, at t0+{ph[0][0] - t0:.0f} s", + ph[0][3] < QUIET_W and ph[0][4] == 0.0 and 11 <= ph[0][0] - t0 <= 15) +check("T2: ends on 3 phases, 10 A, the car draws", + w.sim.phases_allowed == 3 and w.sim.readback_a == 10 + and w.sim.power_w > 6000) +check(f"T13: a clean change logs nothing at INFO or above ({CAP.loud(MARK[0])})", + CAP.loud(MARK[0]) == []) + + +async def t5a(): + w = await ready(1, 16, 3) + await w.step(60) + return w + + +w = run(t5a()) +t0, ph = t_zero(w), w.writes("phases") +check(f"T5a: 1 ph 16 A 3680 W -> 3 ph: select at t0+{ph[0][0] - t0:.0f} s " + f"with {ph[0][3]:.0f} W, then 16 A ({seqw(w)})", + 17 <= ph[0][0] - t0 <= 20 and ph[0][3] < QUIET_W + and seqw(w)[-1] == ("current", 16.0) and w.sim.phases_allowed == 3) + + +async def t5b(): + w = await ready(3, 6, 1) + await w.step(60) + return w + + +w = run(t5b()) +t0 = t_zero(w) +rest = [x for x in w.writes("current") if x[2] == 6.0 and x[0] > t0] +check(f"T5b: 3 ph 6 A 4140 W -> 1 ph: still 140 W at t0+20: no select, " + f"abandon at t0+{nth(rest)[0] - t0:.0f}, restore to 6 A", + not w.writes("phases") and 20 <= nth(rest)[0] - t0 <= 21 + and w.sim.readback_a == 6 and w.wr.phase_fails == 1) + + +async def t9(extra=None, steps=70, **kw): + w = await ready(3, 16, 1, **kw) + await w.step(steps) + return w + + +w9 = run(t9()) +t0 = t_zero(w9) +cw = [x for x in w9.writes("current")] +rest = [x for x in cw if x[0] > t0] +check(f"T9: 3 ph 16 A -> 1 ph, car still ~7 kW at t0+20: no phases write, " + f"abandon at t0+{nth(rest)[0] - t0:.0f}, one restore of 16 A " + f"({seqw(w9)})", + not w9.writes("phases") and 20 <= nth(rest)[0] - t0 <= 21 + and seqw(w9) == [("current", 0.0), ("current", 16.0)] + and nth(rest)[0] <= t0 + 20 + SETTLE_S + 2) +check("T9: phases stay 3, the car draws again, one failed try, not given up, " + "no amber row, sequence over", + w9.sim.phases_allowed == 3 and w9.sim.power_w > 6000 + and w9.wr.phase_fails == 1 and not w9.wr.phases_gave_up + and "charger_phases" not in w9.rows() and w9.wr.seq is None) +check("Expected 3: the next try counts PHASE_GAP_S from the abandon", + w9.wr.last_switch is not None + and abs(w9.wr.last_switch - (nth(rest)[0] + w9.t - w9.sim.t)) <= 1.5) + + +async def t10(): + w = await ready(3, 16, 1) + await w.step(10) + w.sim.station_a = 10.0 + await w.step(60) + return w + + +w = run(t10()) +t0 = t_zero(w) +after = [x for x in w.writes("current") if x[0] > t0] +check(f"T10/N2: the station limit drops to 10 A during zero: the restore is " + f"10 A and nothing above it ({[x[2] for x in after]})", + after and after[0][2] == 10.0 and all(x[2] <= 10.0 for x in after) + and not w.writes("phases")) + + +async def t16(): + w = await ready(1, 10, 3) + await w.step(1) # 0 A is written, the car at 2300 W + w.sim.freeze_power() + await w.step(60) + return w + + +w = run(t16()) +t0 = t_zero(w) +rest = [x for x in w.writes("current") if x[0] > t0] +check(f"T16/N5: the power sensor stuck at 2300 W while the car stops: no " + f"select, abandon at t0+{nth(rest)[0] - t0:.0f}, restore 10 A", + not w.writes("phases") and 20 <= nth(rest)[0] - t0 <= 21 + and nth(rest)[2] == 10.0 and w.wr.phase_fails == 1) + + +async def t17(ramp): + w = await ready(1, 10, 3, ramp=ramp, delay=1.0) + await w.step(1) + w.sim.go_unavailable() + n = len(w.sim.log) + await w.step(28) # t0+2 .. t0+30 + during = len(w.sim.log) - n + w.sim.go_unavailable(False) + n1 = len(w.writes()) + await w.step(3) + first = w.writes()[n1:] + await w.step(40) + return w, during, first + + +w, during, first = run(t17(50.0)) +check(f"T17a: back after 30 s at ~800 W: no write while unavailable, no " + f"select, then the restore ({[x[1:3] for x in first]})", + during == 0 and not w.writes("phases") and w.sim.readback_a == 10 + and w.wr.phase_fails == 1) +w, during, first = run(t17(200.0)) +ph = w.writes("phases") +check(f"T17b: back at 0 W: the select at the first available step " + f"({first[0][1:3] if first else None}), power {ph[0][3]:.0f} W", + during == 0 and first and first[0][1] == "phases" + and ph[0][3] < QUIET_W and w.sim.phases_allowed == 3) + +print("\n3. W: TRIES, THE AMBER ROW, THE LOG") + + +async def t11(): + w = await ready(3, 16, 1) + mark = len(CAP.rec) + await w.step(1900) + zeros = [x[0] for x in w.writes("current") if x[2] == 0.0] + rests = [x[0] for x in w.writes("current") if x[2] == 16.0 + and x[0] > nth(zeros)] + out = dict(zeros=zeros, rests=rests, ph=len(w.writes("phases")), + gave=w.wr.phases_gave_up, row=w.rows().get("charger_phases"), + loud=CAP.loud(mark), w=w) + await w.step(1200) + out["more"] = len([x for x in w.writes("current") if x[2] == 0.0]) + n = len([x for x in w.writes("current") if x[2] == 0.0]) + await w.act("car_phases", 1) # same wish, a user change + await w.act("car_phases", 3) + await w.act("car_phases", 1) + await w.step(60) + out["after_user"] = len([x for x in w.writes("current") + if x[2] == 0.0]) - n + return out + + +o = run(t11()) +z, rs = o["zeros"], o["rests"] +check(f"T11: 3 zero writes, 0 phases writes, 3 restores ({len(z)}, {o['ph']}," + f" {len(rs)})", len(z) == 3 and o["ph"] == 0 and len(rs) == 3) +check("T11: the 2nd and 3rd 0 A come PHASE_GAP_S after the abandon of the " + "one before", + len(z) == 3 and len(rs) == 3 and all(z[i] - z[i - 1] >= PHASE_GAP_S + and z[i] <= rs[i - 1] + PHASE_GAP_S + SETTLE_S + 2 + for i in (1, 2))) +check("T11: after the 3rd the add-on gives up: amber row, no 4th 0 A in " + "1200 s", o["gave"] and o["row"] is not None and o["row"]["ok"] is False + and o["row"]["warn"] is True and o["more"] == 3) +check("T11: a user change after the give-up tries again at once (one 0 A)", + o["after_user"] == 1) +check(f"T13: one 'kept drawing' line per abandon (3) plus the one " + f"CHARGER_PHASES warning, nothing else, no ERROR ({o['loud']})", + len(o["loud"]) == 4 and sum("CHARGER_PHASES" in m for m in o["loud"]) == 1 + and not [1 for lv, _m in CAP.rec if lv >= logging.ERROR]) + + +async def t12(): + w = await ready(3, 16, 1) + await w.step(40) # try 1: abandoned + real = w.sim.request_phases + w.sim.ramp_w_s = 3000.0 + w.sim.request_phases = lambda n: False # refused select + await w.step(int(PHASE_GAP_S) + 60) # try 2 + mid = w.wr.phase_fails + w.sim.request_phases = real + w.sim.ramp_w_s = 200.0 + await w.step(int(PHASE_GAP_S) + 60) # try 3: abandoned + n = len(w.writes("current")) + await w.step(1500) + return w, mid, len(w.writes("current")) - n + + +w, mid, extra = run(t12()) +check(f"T12: abandon, refused select, abandon share one count: 2 after try 2 " + f"({mid}), given up after try 3, amber row, no 4th try", + mid == 2 and w.wr.phases_gave_up and w.wr.phase_fails == 3 + and "charger_phases" in w.rows() and extra == 0) + +print("\n4. W: THE OTHER ENDS OF A SEQUENCE, THE ALARM") + + +async def t18(): + w = await ready(3, 16, 1) + await w.step(5) + await w.c.car_shutdown() + n = len(w.writes()) + mark = w.writes()[w.n0:] + st = (w.wr.seq, w.wr.phase_fails, w.sim.readback_a) + w.make(w.opts) + await w.step(60) + return w, st, mark, w.writes()[n:] + + +w, st, mark, later = run(t18()) +check(f"T18: shutdown at t0+5 with the car drawing: one clamped restore (16 " + f"A), no select, sequence over, no failed try ({mark})", + [(x[1], x[2]) for x in mark] == [("current", 0.0), ("current", 16.0)] + and st == (None, 0, 16.0)) +ok = True +for i, x in enumerate(later): + if x[1] == "phases": + ok = ok and any(y[1] == "current" and y[2] == 0.0 + for y in later[:i]) and x[3] < QUIET_W +check(f"T18: after the restart no select unless a new 0 A came first and the " + f"car was quiet ({[x[1:3] for x in later]})", ok) + + +async def t19(how): + w = await ready(3, 16, 1) + await w.step(5) + n = len(w.writes()) + mark = len(CAP.rec) + if how == "off": + await w.act("car_mode", "off") + elif how == "stop": + w.c.auto = False + else: + w.c.o["shadow_mode"] = "on" + await w.step(80) + return w, w.writes()[n:], CAP.loud(mark) + + +for how in ("off", "stop", "shadow"): + w, after, loud = run(t19(how)) + check(f"T19: {how} at t0+5 with the car drawing: `_undo` as before: one " + f"restore, no select, nothing after it, not a failed try " + f"({[x[1:3] for x in after]})", + [(x[1], x[2]) for x in after] == [("current", 16.0)] + and not w.writes("phases") and w.wr.phase_fails == 0 + and not [m for m in loud if "drawing" in m.lower()]) + + +async def t20(): + w = await ready(3, 16, 1) + await w.step(5) + mark = len(CAP.rec) + n = len(w.writes()) + w.sim.set_current(9) + await w.step(80) + return w, w.writes()[n:], CAP.loud(mark) + + +w, after, loud = run(t20()) +check(f"T20: another writer sets 9 A at t0+5: hold, grey row, no select, no " + f"restore by the add-on, no failed try, no abandon line ({after})", + not w.writes("phases") and after == [] and w.wr.hold + and "charger_other" in w.rows() and w.wr.phase_fails == 0 + and not [m for m in loud if "drawing" in m.lower()]) + + +async def t21(): + w = await ready(3, 16, 1) + await w.step(5) + await w.act("car_phases", 3) # back to what the car has + await w.act("car_current", 12) + await w.step(80) + return w + + +w = run(t21()) +bad = [x for x in w.writes("phases") if x[3] >= QUIET_W] +check(f"T21: the user changes phases back and the current at t0+5: no select " + f"under load, the new current ends up, nothing above the clamp " + f"({seqw(w)})", + not bad and w.sim.readback_a == 12 and w.sim.phases_allowed == 3 + and all(x[2] <= 16.0 for x in w.writes("current")) and w.wr.seq is None) + + +async def t15(): + w = await ready(3, 16, 1) + calls = [] + real = w.drv.write_current + + async def spy(a): + r = await real(a) + calls.append((w.sim.t, a, r)) + return r + w.drv.write_current = spy + await w.step(19) + w.sim.refuse = "error" + await w.step(40) + mid = (list(calls), w.wr.seq is None, bool(w.writes("phases"))) + w.sim.refuse = None + await w.step(int(carmode.RETRY_S) + 10) + return w, mid + + +w, (calls, over, anyph) = run(t15()) +tries = [c for c in calls if c[1] == 16.0] +gaps = [round(b[0] - a[0]) for a, b in zip(tries, tries[1:])] +check(f"T15: the restore is refused: tried {len(tries)} times ~5 s apart " + f"({gaps}), no select, sequence ends", + len(tries) == MAX_TRIES and all(4 <= g <= 6 for g in gaps) and over + and not anyph and not w.writes("phases")) +check("T15: after the refusal ends the current is back at 16 A, never a " + "select", w.sim.readback_a == 16 and not w.writes("phases")) + + +# --- T14: the controller level (the EV-15 harness) ------------------------- # +def ctl(extra=None, t_sw=600, new=1): + tr = [] + + def note(plant, c): + tr.append((plant.t, c._car_own_pause(c.car_now()), c.car_explains, + c.car_writer.phase_done_at, plant.ch.power_w, + c.car_writer.phase_fails)) + + def reserve(plant, c): + plant.soc = 19.0 + plant.load = lambda t: 3000.0 + 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, 720)} + ev[300] = 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 = SimCharger(setpoint_a=16) + sim.ramp_w_s, sim.stop_delay_s = 200.0, 1.0 + r = P.drive(s81.constant(3000.0), dur=720, rating=12000.0, soc=60.0, + cap=6050.0, phases=3, user_a=16, setpoint=16, mode="manual", + events=ev, sim=sim) + return r, tr, P.ids(r, *P.ALARMS) + + +logging.disable(logging.CRITICAL) +r, tr, al = ctl() +logging.disable(logging.NOTSET) +ab = [x[0] for x in tr if x[0] > 600 and x[5] == 1] +a0 = ab[0] if ab else None +check(f"T14: the car keeps drawing: abandon at {a0}; the own-pause grace is " + f"on before it and off from the abandon step on, phase_done_at stays " + f"None", a0 is not None and any(x[1] for x in tr if 602 <= x[0] < a0) + and not any(x[1] for x in tr if x[0] >= a0) + and all(x[3] is None for x in tr) and not r["sim"].writes("phases")) + + +def overload(plant, c): + plant.load = lambda t: 25000.0 + plant.ch.power_w + + +logging.disable(logging.CRITICAL) +r2, tr2, al2 = ctl(extra={640: overload}) +r3, tr3, al3 = ctl(extra={640: overload}, t_sw=900) # no phase change +logging.disable(logging.NOTSET) +check(f"T14: a house overload after the abandon alarms, as with no car " + f"change ({[t for t, _ in al2]} vs {[t for t, _ in al3]}), and the car " + f"does not explain it", + bool(al2) and bool(al3) and al2[0][0] == al3[0][0] + and not any(x[2] for x in tr2 if x[0] >= 642)) + +# =========================================================================== # +print("\n5. W: THE DIGESTS OF THE QUIET SHAPES, PINNED FROM 4eba2d9") +# =========================================================================== # + + +async def d_story(lag=0.0, race=False): + 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(5) + await w.act("car_phases", 3) + await (w.step_race(60) if race else w.step(60)) + return w + + +async def d_gap(): + w = await d_story() + await w.act("car_phases", 1) + await w.step(620) + return w + + +async def d_zero_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(3) + w.sim.refuse = "ignore" + await w.act("car_phases", 3) + await w.step(80) + return w + + +async def d_m2(): + 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): + sim.log.append((sim.t, "phases", n, sim.power_w, sim.setpoint_a)) + return True + sim.request_phases = deaf + await w.act("car_phases", 3) + await w.step(3700) + return w + + +async def d_l4(): + 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 + await w.act("car_phases", 3) + await w.step(60) + return w + + +async def d_mid(kind): + """The slow-stop car (ramp 50 W/s, C held 40 s) cut short before 20 s.""" + w = World(dict(CAR, shadow_mode="auto"), setpoint=10, phases=1) + w.sim.ramp_w_s, w.sim.stop_delay_s = 50.0, 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) + if kind == "off": + await w.act("car_mode", "off") + elif kind == "shadow": + w.c.o["shadow_mode"] = "on" + elif kind == "stop": + await w.c.handle_action("auto_toggle") + elif kind == "shutdown": + await w.c.car_shutdown() + elif kind == "other": + w.sim.set_current(9) + await w.step(80) + return w + + +async def d_off(): + w = World(setpoint=10, phases=1) + await w.step(5) + await w.act("car_phases", 3) + await w.step(60) + return w + + +def digest(w): + s = repr([(x[0], x[1], x[2]) for x in w.sim.log]) + return hashlib.sha256(s.encode()).hexdigest()[:12] + + +SHAPES = [("phase_story", lambda: d_story()), + ("phase_story lag 3", lambda: d_story(lag=3.0)), + ("m1 race", lambda: d_story(race=True)), + ("phase_gap", d_gap), ("zero_refused", d_zero_refused), + ("m2_refused", d_m2), ("l4_late", d_l4), ("phases_in_off", d_off)] \ + + [(f"mid {k}", (lambda k=k: d_mid(k))) + for k in ("off", "shadow", "stop", "shutdown", "other")] +# Pinned from 4eba2d9 (python3 -B on the base tree). Two shapes CHANGE by +# design, because the base selected under load in them: `phase_gap` (second +# switch: base selected at t0+1 with 3900 W, now t0+3 under 100 W, the same +# writes otherwise) and `mid shutdown` (the restarted sequence met a car at +# 1250 W: base selected at the timeout, now abandons and restores). Their pins +# are the new digests; the facts are asserted below. +PINS = {"phase_story": "9e7d818e1304", "phase_story lag 3": "13bba7ca8427", + "m1 race": "0f845c466111", "phase_gap": "467fad0b4ebe", + "zero_refused": "041e96466f8e", "m2_refused": "5ea1b28f8c3a", + "l4_late": "50248d297e1d", "phases_in_off": "4f53cda18c2b", + "mid off": "b62df7ce65eb", "mid shadow": "b62df7ce65eb", + "mid stop": "b62df7ce65eb", "mid shutdown": "5cae419f3e9f", + "mid other": "0f43ad8a061a"} +got = {name: digest(run(fn())) for name, fn in SHAPES} +_g = run(d_gap()) +_p = _g.writes("phases") +check("T22: the changed shapes are changed only where base selected under " + f"load: phase_gap's 2nd select is under 100 W ({_p[1][3]:.0f} W)", + len(_p) == 2 and _p[1][3] < QUIET_W) +check("T22: digests: " + ", ".join(f"{k}={v}" for k, v in got.items()), + all(PINS.get(k) == v for k, v in got.items()) and set(PINS) == set(got)) + +# =========================================================================== # +print("\n6. DOCS (T25)") +# =========================================================================== # +doc = open(os.path.join(HERE, "DECISIONS", "EV-04-manual-mode.md"), + encoding="utf-8").read() +phase = doc.split("## The phase sequence")[1].split("\n## ")[0] +flat = " ".join(phase.split()) +check("T25: DECISIONS says: under 100 W with a power reading, mode3 leaving C " + "only without one, still drawing at 20 s gives the current back and " + "counts as a failed try", + "under 100 W" in flat and "no power reading" in flat + and "failed try" in flat and "current comes back" in flat + and "or mode3 leaves C (20 s at most)" not in flat) +src = carmode.__doc__ +check("T25: the module docstring matches (power reading first, then mode3, " + "then the failed try)", + "without a power reading" in " ".join(src.split()) + and "failed" in src and "or mode3 leaves C" not in src) + +print() +if fails: + print(f"FAIL: {len(fails)} check(s)") + for f in fails: + print(" -", f) + sys.exit(1) +print("ok: EV-28") -- 2.54.0 From 4b4a4c10535353c6156a04d886566c0343afa711 Mon Sep 17 00:00:00 2001 From: "Claude (review agent)" Date: Sat, 21 Nov 2026 22:58:56 +0100 Subject: [PATCH 18/55] EV-28 review: pin the restore step in T17a and the counted failure in T15 Review fixes, no logic change: - T17a now asserts the restore is the first write once the charger is back (it was only checked to happen at some point); mutant M3 (restore after SETTLE_S) now turns T17a red. - T15 now asserts the refused restore is counted once (`fails == 1`); a mutant without `_failed` there now turns T15 red. - DECISIONS "The phase sequence" and the carmode docstring reflowed to 79 columns; DECISIONS says D counts as drawing too, as the code does. Co-Authored-By: Claude --- goodwe_controller/DECISIONS/EV-04-manual-mode.md | 16 ++++++++-------- goodwe_controller/app/carmode.py | 6 +++--- goodwe_controller/test_ev28.py | 11 +++++++---- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index 607569f..39c2fa1 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -30,14 +30,14 @@ code had to decide that the design left open. ## The phase sequence -0 A, wait until the charger reports under 100 W (mode3 leaving C counts only -when there is no power reading; 20 s at most), select the phases, wait 10 s, write the current. One switch per 10 minutes. A -charger that does not take the 0 A never gets the phases select. A car still -drawing after 20 s gets no select: its current comes back and it counts as a -failed try (EV-28). A sequence that -has begun is finished whatever the mode, because it leaves the car at 0 A -otherwise; a stop of the add-on in the middle gives the car its current back -(`car_shutdown`). +0 A, wait until the charger reports under 100 W (mode3 leaving C and D counts +only when there is no power reading; 20 s at most), select the phases, wait +10 s, write the current. One switch per 10 minutes. A charger that does not +take the 0 A never gets the phases select. A car still drawing after 20 s gets +no select: its current comes back and it counts as a failed try (EV-28). A +sequence that has begun is finished whatever the mode, because it leaves the +car at 0 A otherwise; a stop of the add-on in the middle gives the car its +current back (`car_shutdown`). ## Another writer diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index dbaafb0..af18a32 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -17,9 +17,9 @@ THE RULES, each tested in test_ev04.py: * Phases change only through the SAFE SEQUENCE: 0 A, wait until the charger reports under `QUIET_W` (mode3 leaving C only without a power reading; at most `ZERO_WAIT_S`, then the current comes back and it counts as a failed - try), select the phases, wait `SETTLE_S`, write the current again. At most one switch per - `PHASE_GAP_S`. A sequence that has begun is always finished, because it - leaves the car at 0 A otherwise. + try), select the phases, wait `SETTLE_S`, write the current again. At most + one switch per `PHASE_GAP_S`. A sequence that has begun is always finished, + because it leaves the car at 0 A otherwise. * A read-back that differs from the add-on's own last write for `WRITER_S` is ANOTHER WRITER: an info row, and no write over it until the user changes the mode or a value again. diff --git a/goodwe_controller/test_ev28.py b/goodwe_controller/test_ev28.py index 378c3a1..710537e 100644 --- a/goodwe_controller/test_ev28.py +++ b/goodwe_controller/test_ev28.py @@ -518,9 +518,11 @@ async def t17(ramp): w, during, first = run(t17(50.0)) check(f"T17a: back after 30 s at ~800 W: no write while unavailable, no " - f"select, then the restore ({[x[1:3] for x in first]})", + f"select, the restore on the first available step " + f"({[x[1:3] for x in first]})", during == 0 and not w.writes("phases") and w.sim.readback_a == 10 - and w.wr.phase_fails == 1) + and w.wr.phase_fails == 1 + and [x[1:3] for x in first][:1] == [("current", 10.0)]) w, during, first = run(t17(200.0)) ph = w.writes("phases") check(f"T17b: back at 0 W: the select at the first available step " @@ -698,7 +700,8 @@ async def t15(): await w.step(19) w.sim.refuse = "error" await w.step(40) - mid = (list(calls), w.wr.seq is None, bool(w.writes("phases"))) + mid = (list(calls), w.wr.seq is None and w.wr.fails == 1, + bool(w.writes("phases"))) w.sim.refuse = None await w.step(int(carmode.RETRY_S) + 10) return w, mid @@ -708,7 +711,7 @@ w, (calls, over, anyph) = run(t15()) tries = [c for c in calls if c[1] == 16.0] gaps = [round(b[0] - a[0]) for a, b in zip(tries, tries[1:])] check(f"T15: the restore is refused: tried {len(tries)} times ~5 s apart " - f"({gaps}), no select, sequence ends", + f"({gaps}), no select, sequence ends, one failed write counted", len(tries) == MAX_TRIES and all(4 <= g <= 6 for g in gaps) and over and not anyph and not w.writes("phases")) check("T15: after the refusal ends the current is back at 16 A, never a " -- 2.54.0 From c25877fea4b7eb201130188b9bcc23c7db97bb54 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 01:50:44 +0100 Subject: [PATCH 19/55] EV-13: a refused current write arms the stuck check only when the charger shows no life A refused write on a live charger no longer reads as a stuck reading 60 s later, so a refused write shows one amber row (charger_refused). A frozen charger still arms and is still caught. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/app/carmode.py | 2 +- goodwe_controller/app/chargers.py | 112 +++- goodwe_controller/test_ev13.py | 972 ++++++++++++++++++++++++++++++ 3 files changed, 1078 insertions(+), 8 deletions(-) create mode 100644 goodwe_controller/test_ev13.py diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index af18a32..32a65a1 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -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: diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index 7c96512..228b09f 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -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.+)_" + 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,9 @@ 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 def _state_obj(obj): @@ -420,6 +425,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 +506,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 +531,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 +540,18 @@ 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: + cur = tuple(a for a in (_amps(st.get(k)) for k in ("l1", "l2", "l3")) + if a is not None) + self.polls.append((self._clock(), ChargerReading( + available=True, power_w=_watts(st.get("power")), + energy_kwh=_kwh(st.get("energy")), current_a=cur))) + 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 +653,26 @@ 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.current_a or ())[:3] + return (r.energy_kwh, r.power_w) + cur + (None,) * (3 - len(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 +705,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 @@ -684,6 +729,7 @@ class CarTracker: self.last_ok = now self.last_good, self.last_good_utc = r, now_utc if r.available: + self._life(r, now) self._sig(r, now) self._writer(r, now_utc, now) self._energy(r, day) @@ -727,19 +773,71 @@ 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_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) diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py new file mode 100644 index 0000000..ecab25b --- /dev/null +++ b/goodwe_controller/test_ev13.py @@ -0,0 +1,972 @@ +"""EV-13: a refused current write shows ONE amber row, not two. +`python3 -B test_ev13.py` + +The bug: `ManualWriter._write` armed the stuck-reading check on every write, +refused or not. A charger that ignores the write keeps its old setpoint, so the +read-back does not move, and 60 s later "Charger reading may be stuck" showed +beside "The charger did not take the setting", and the car figure was not +trusted (EV-15 rig: it latched the quarter). + +The rule (owner's delegate, decision (b)): a refused write skips the arm ONLY +when the charger shows life: a change in the energy counter, a phase current or +the power, in a sample taken after the write was sent and within `TOOK_S` of it, +against the last value before. Present but unchanged, absent before, a stale +sample (taken before the send): not life. No life: it arms as before, dated the +send. A frozen charger (every write looks refused) is still caught. + +Shapes: S = a tracker fed by a script (the test chooses each sample's values, +taken-at and arrival), W = the real Controller on `chargersim.SimCharger`, C = +`ev04_peak.drive` (the SAFETY-81 plant). Times are model seconds. +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). + + 1. S: what counts as life (T3-T10, T12, T15) + 2. W: live refusals, one amber row (T1, T2, T19) + 3. W: no life, accepted writes, transitions (T11, T14, T17, T18, T20, T21) + 4. W: errors, restart (T13, T25) + 5. C: the peak guard (T16, T22-T24) + 6. Writes, as on the base (T26) +""" + +import asyncio +import dataclasses +import hashlib +import logging +import os +import sys +from datetime import datetime, timezone + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode, chargers as CH, freshness # noqa: E402 +from app.main import Controller # noqa: E402 +from chargersim import FakeHa, SimCharger # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +class _Log(logging.Handler): + def __init__(self): + super().__init__(logging.DEBUG) + self.rec = [] + + def emit(self, r): + self.rec.append((r.levelname, r.getMessage())) + + def text(self, level=None): + return "\n".join(m for lv, m in self.rec if level in (None, lv)) + + +LOG = _Log() +logging.getLogger("goodwe").addHandler(LOG) +logging.getLogger("goodwe").setLevel(logging.DEBUG) +logging.getLogger("goodwe").propagate = False + +UTC = datetime(2026, 11, 22, tzinfo=timezone.utc) +DAY = "2026-11-22" +TS = 1000.0 # t_s in the S shape +TOOK_S, STUCK_S = CH.TOOK_S, CH.STUCK_S + + +# =========================================================================== # +print("1. S: WHAT COUNTS AS LIFE") +# =========================================================================== # +def rd(e=1.000, p=11040.0, cur=(16.0, 15.9, 16.0), a=16.0, taken=None, + state="C"): + return CH.ChargerReading( + available=True, state=state, charging=state == "C", power_w=p, + energy_kwh=e, current_a=cur, allowed_a=a, setpoint_a=a, + phases_allowed=3, taken_at=taken) + + +def steady(changes=None, start=1, end=130, **base): + """One sample a second from TS+start to TS+end, taken on arrival. `changes` + is {second after TS: kwargs}; each change stays.""" + out, kw = [], dict(base) + for s in range(start, end + 1): + kw.update((changes or {}).get(s, {})) + out.append((TS + s, rd(**kw))) + return out + + +def play(timeline, mode="live", ok=False, was=16.0, to=10.0, pre_end=0, + pre=None, end=TS + 130): + """The tracker sees the pre-write samples, then the write (refused unless + `ok`), then `timeline` = [(arrival, ChargerReading)]. + live: the write returns at once (HA said no), samples come after it. + ring: the write waited TOOK_S; the cycle's samples came meanwhile. + polls: the write waited and saw the samples itself (nothing else did). + Returns (tracker, first second `stuck()` was True, armed_at ever set).""" + tr = CH.CarTracker() + seen = {"armed": False, "first": None} + + def obs(at, r): + tr.observe(r, at, UTC, DAY) + seen["armed"] |= tr.armed_at is not None + if seen["first"] is None and tr.stuck(at): + seen["first"] = at + + for i in range(-20, pre_end + 1): + obs(TS + i, rd(**(pre or {}))) + inside = [x for x in timeline if x[0] <= TS + TOOK_S] + outside = [x for x in timeline if x[0] > TS + TOOK_S] + if mode == "live": + tr.note_write(TS, was, to, ok) + rest = timeline + elif mode == "ring": + for at, r in inside: + obs(at, r) + tr.note_write(TS, was, to, ok) + rest = outside + else: + tr.note_write(TS, was, to, ok, [ + (r.taken_at if r.taken_at is not None else at, r) + for at, r in inside]) + rest = outside + seen["armed"] |= tr.armed_at is not None + for at, r in sorted(rest, key=lambda x: x[0]): + if at <= end: + obs(at, r) + return tr, seen["first"], seen["armed"] + + +MODES = ("live", "ring", "polls") + + +def pend(tr): + """The refusal window a tracker keeps open (None: none).""" + return getattr(tr, "_pend", None) + + +def life(name, changes, **kw): + for m in MODES: + tr, first, armed = play(steady(changes), m, **kw) + check(f"{name} [{m}]: not armed, never stuck to TS+130", + tr.armed_at is None and first is None and not armed + and not tr.stuck_now) + + +def armed(name, tl, at=TS, **kw): + for m in MODES: + tr, first, ever = play(tl, m, **kw) + check(f"{name} [{m}]: armed at the send, stuck at TS+60 (+-1), " + f"not before TS+59 (first {first})", + first is not None and TS + 59 <= first <= TS + 61 + and tr.armed_at == at and tr.stuck_now) + + +life("T3 energy alone steps 10 Wh at +4", {4: dict(e=1.010)}) +life("T4 one phase current alone (L2 15.9 -> 16.0) at +4", + {4: dict(cur=(16.0, 16.0, 16.0))}) +life("T5 power alone (11040 -> 11080 W) at +4", {4: dict(p=11080.0)}) +life("T9 the step at +9, inside the window", {9: dict(e=1.010)}) +life("T9 the step exactly at +10 (the edge counts)", {10: dict(e=1.010)}) +life("T12(a) power None, state C, energy rising", {4: dict(e=1.010)}, + pre=dict(p=None)) +armed("T6 present but unchanged: every sample repeats the pre-write values", + steady()) +armed("T9 the step at +11 is outside the window; armed_at is the send, not " + "+10 or +11", steady({11: dict(e=1.010)})) +armed("T10 energy absent before, present after: no change against a last " + "value", steady({4: dict(e=1.010)}), pre=dict(e=None)) +armed("T12(b) power None, nothing else changes", steady(p=None), + pre=dict(p=None)) + +# T7: a stale sample: the pre-write sample again, the same taken-at time +for what, e in (("the same values", 1.000), ("changed values", 1.010)): + tl = [(TS + s, rd(e=e, taken=TS - 1.0)) for s in range(1, 131)] + armed(f"T7 stale sample ({what}, taken-at TS-1 again and again)", tl) + +# T8: the late pre-write sample (EV-12 ordering): taken TS-1, arrives TS+2 +late = [(TS + s, rd(e=1.010, taken=TS - 1.0) if s == 2 else rd(e=1.010)) + for s in range(2, 131)] +armed("T8 a sample taken at TS-1 (+10 Wh) arrives at TS+2, nothing changes " + "after it", late, pre_end=-3) + +# T15: the STUCK_MIN_A edge is as before +t15 = CH.CarTracker() +t15.observe(rd(), TS, UTC, DAY) +t15.note_write(TS, 10, 10.9) +a09 = t15.armed_at +t15.note_write(TS, 10, 11) +a10 = t15.armed_at +t15b = CH.CarTracker() +t15b.observe(rd(), TS, UTC, DAY) +t15b.note_write(TS, None, 10) +check("T15 a 0.9 A move does not arm, 1.0 A does, an unknown `was` does", + a09 is None and a10 == TS and t15b.armed_at == TS) +t15c = CH.CarTracker() +t15c.observe(rd(), TS, UTC, DAY) +t15c.note_write(TS, 10, 10.9, False) +t15d = CH.CarTracker() +t15d.observe(rd(), TS, UTC, DAY) +t15d.note_write(TS, 10, 11, False) +for i in range(1, 80): + t15d.observe(rd(), TS + i, UTC, DAY) +check("T15 a refused 0.9 A move arms nothing and leaves nothing waiting; a " + "refused 1.0 A move with no life arms", + t15c.armed_at is None and pend(t15c) is None and t15d.armed_at == TS + and t15d.stuck_now) + +# the details the plan implies +tr = CH.CarTracker() +tr.observe(rd(), TS, UTC, DAY) +tr.note_write(TS, 16, 10, True) +check("E3: an accepted write arms at once, at the send", tr.armed_at == TS + and pend(tr) is None) +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(), TS + i, UTC, DAY) +tr.note_write(TS, 16, 10, False) +tr.observe(rd(), TS + 3, UTC, DAY) +tr.note_write(TS + 5, 10, 8, True) +check("an accepted write while a refusal's window is open arms at the " + "accepted write, and the window is dropped", + tr.armed_at == TS + 5 and pend(tr) is None) +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(), TS + i, UTC, DAY) +tr.note_write(TS, 16, 10, False) +tr.note_write(TS + 5, 10, 6, False) +tr.note_write(TS + 10, 6, 5, False) +for i in range(1, 70): + tr.observe(rd(), TS + i, UTC, DAY) +check("T20 shape: refusals 5 s apart with nothing changing arm once, dated " + "the FIRST", tr.armed_at == TS and tr.stuck_now) +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(), TS + i, UTC, DAY) +tr.note_write(TS, 16, 10, False) +for i in range(1, 5): + tr.observe(rd(e=1.010), TS + i, UTC, DAY) +tr.note_write(TS + 20, 10, 8, False) +check("a refusal that showed life leaves no window; a later refusal gets " + "its own", pend(tr) is not None and pend(tr)["t"] == TS + 20 + and tr.armed_at is None) + +# T18 (tracker): an armed check is neither cleared nor delayed by a refusal +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(), TS + i, UTC, DAY) +tr.note_write(TS, 16, 10, True) +for i in range(1, 20): + tr.observe(rd(), TS + i, UTC, DAY) +tr.note_write(TS + 20, 10, 8, False) +for i in range(20, 61): + tr.observe(rd(e=1.0 + i / 1000.0), TS + i, UTC, DAY) +check("T18 (tracker) an accepted write armed at TS; a live refusal at TS+20 " + "neither clears nor delays it: stuck at TS+60", + tr.armed_at == TS and tr.stuck_now and pend(tr) is None) + + +# =========================================================================== # +# W: the real Controller on the charger model +# =========================================================================== # +class _Store: + def __init__(self): + self.data = {} + + def set(self, k, v): + self.data[k] = v + + def get(self, k, d=None): + return self.data.get(k, d) + + def set_time(self, k, v): + self.data[k] = v.isoformat() + + def get_time(self, k): + v = self.data.get(k) + return None if v is None else datetime.fromisoformat(v) + + +class _Pub: + enabled = False + + def __init__(self): + self.values = [] + + def publish(self, v): + self.values.append(dict(v)) + + def close(self): + pass + + +class Site(FakeHa): + def __init__(self, charger, grid=500.0, batt=0.0, pv=2000.0): + super().__init__(charger, None) + self.grid, self.batt, self.pv = grid, batt, pv + + async def limits(self, _e): + return (-5000.0, 5000.0, 1.0) + + def _all(self): + out = super()._all() + for eid, val, unit in (("sensor.grid", self.grid, "W"), + ("sensor.soc", 50.0, "%"), + ("sensor.batt", self.batt, "W"), + ("sensor.pv", self.pv, "W")): + out[eid] = {"entity_id": eid, "state": str(val), + "attributes": {"unit_of_measurement": unit}} + return out + + async def number(self, entity_id, invert=False): + s = self._all().get(entity_id) + try: + v = float(s["state"]) + except (TypeError, ValueError, KeyError): + return None + return -v if invert else v + + async def set_number(self, entity_id, value): + if entity_id == "number.sp": + self.sets.append((entity_id, float(value))) + self.batt = float(value) + return True + return await super().set_number(entity_id, float(value)) + + +BASE = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid", + "soc_entity": "sensor.soc", "batt_entity": "sensor.batt", + "meter_source": "off", "max_w": 5000, "gain": 0.6, "slew_w": 500, + "deadband_w": 15, "target_grid_w": 0, "step_w": 10, "heartbeat_s": 10, + "stale_input_s": 15, "shadow_mode": "off", "peak_cap_w": 3500, + "pv_entities": ["sensor.pv"]} +SET = "number.wallbox_power_connector_max_current_socket_1" +CAR = dict(BASE, ev_charger="alfen_ha", ev_max_a=16, ev_phases="auto", + ev_current_entity=SET) +CLOCK = [1000.0] +freshness.monotonic = lambda: CLOCK[0] + + +class World: + """A real Controller on the charger model, one clock for all of it.""" + + def __init__(self, opts=CAR, sim=None, store=None, setpoint=16, phases=3, + grid=800.0, beside=False): + self.sim = sim or SimCharger(setpoint_a=setpoint) + self.sim.plug_in() + self.sim.phases_allowed = phases + self.site = Site(self.sim, grid=grid) + self.store = store or _Store() + self.t = 1000.0 + CLOCK[0] = self.t + self.off = self.t - self.sim.t # sim time + off = this clock + self.make(opts) + if beside: + self.beside() + + def beside(self): + """The writer runs BESIDE the cycle, as in production: the cycle reads + (and the tracker sees) the charger while a write waits for its + read-back, one poll per cycle.""" + 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) + self.drv._sleep = sleep + self.c.car_settle = settle + + def make(self, opts): + self.c = Controller(dict(opts), self.site, self.store, _Pub(), + stop=asyncio.Event()) + self.c.auto = True + self.c.dev_min, self.c.dev_max = -5000.0, 5000.0 + self.drv = self.c.charger + self.drv._sleep = self.sleep + self.drv._clock = lambda: CLOCK[0] + + async def sleep(self, s): + self.sim.tick(s) + self.t += s + CLOCK[0] = self.t + + async def step(self, n=1, dt=1.0): + out = [] + 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.cycle() + await self.c.car_settle() + tk = self.c.car + out.append((tk.obs_at, tk.armed_at, tk.stuck(self.t))) + return out + + async def act(self, what, value): + return await self.c.handle_action(what, value=value) + + def rows(self): + return {r["id"]: r for r in self.c.checks()} + + def amber(self): + """The charger's amber rows: not ok, warn.""" + return sorted(i for i, r in self.rows().items() + if r["warn"] and not r["ok"] and i.startswith("charger")) + + def sends(self): + """The model seconds (this clock) of every current write received.""" + return [x[0] + self.off for x in self.sim.writes("current")] + + +def run(coro): + return asyncio.run(coro) + + +SEND = {} # T26: what the charger was sent, per shape + + +def keep(key, w, res): + """The writes of one run: the driver's calls (second, value, taken) and + what the model received (model second, kind, value).""" + SEND[key] = ([(round(t), a, r) for t, a, r in res], + [(round(x[0]), x[1], x[2]) for x in w.sim.writes()]) + + +async def live_car(setpoint=16, phases=3, **kw): + """Manual, the car charging `setpoint` A on `phases`, ramped up.""" + w = World(setpoint=setpoint, phases=phases, **kw) + await w.step(6) + await w.act("car_phases", phases) # the wish is what the car has + await w.act("car_mode", "manual") + await w.act("car_current", setpoint) + await w.step(4) + return w + + +def spy_on(w): + """[(send time, current, ok)] of every `write_current`.""" + res, real = [], w.drv.write_current + + async def spy(a): + t = w.t + r = await real(a) + res.append((t, a, r)) + return r + w.drv.write_current = spy + return res + + +def never_stuck(tr, lo=0): + return all(a is None and not s for _t, a, s in tr[lo:]) + + +def first_stuck(tr): + return next((t for t, _a, s in tr if s), None) + + + + +# =========================================================================== # +print("\n2. W: LIVE REFUSALS SHOW ONE AMBER ROW") +# =========================================================================== # +# Each W shape runs twice: the writer inside the cycle (the model's own +# waits), and BESIDE it as in production (the cycle reads while a write waits). +SIDES = ((False, "inside"), (True, "beside")) + + +async def t1(kind, beside): + w = await live_car(beside=beside) + w.sim.refuse = kind + res = spy_on(w) + await w.act("car_current", 10) + tr = await w.step(400) + return w, res, tr + + +for beside, side in SIDES: + for kind, nm in (("ignore", "T1 the charger ignores it (HA says yes)"), + ("error", "T2 HA refuses at once (False at +0)")): + LOG.rec.clear() + w, res, tr = run(t1(kind, beside)) + ts = [t for t, _a, _r in res] + keep(f"{nm[:2]}-{kind}-{side}", w, res) + nm = f"{nm} [{side}]" + check(f"{nm}: three tries about a minute apart, all refused, then " + f"it gives up ({[round(x - ts[0]) for x in ts]})", + len(res) == 3 and not any(r for _t, _a, r in res) + and all(55 <= b - a <= 75 for a, b in zip(ts, ts[1:])) + and w.c.car_writer.gave_up) + check(f"{nm}: the car shows life inside each window: never armed, " + "never stuck, to 400 s", never_stuck(tr)) + check(f"{nm}: after the 3rd try exactly ONE amber charger row, " + f"charger_refused ({w.amber()})", + w.amber() == ["charger_refused"]) + check(f"{nm}: the car figure is still used by the alarm path", + w.c.car_alarm_w() is not None) + check(f"{nm}: N8 one CHARGER_REFUSED warning, no Traceback; N7 no " + "'another writer' row", + LOG.text("WARNING").count("CHARGER_REFUSED") == 1 + and "Traceback" not in LOG.text() + and "charger_other" not in w.rows() + and "charger_writer" not in w.rows()) + + +async def t19(beside): + w = await live_car(16, 3, beside=beside) + w.sim.refuse = "ignore" + res = spy_on(w) + await w.act("car_phases", 1) + tr = await w.step(400) + return w, res, tr + + +for beside, side in SIDES: + LOG.rec.clear() + w, res, tr = run(t19(beside)) + keep(f"T19-{side}", w, res) + check(f"T19 [{side}] the 0 A of a phase change is ignored and the car " + "keeps drawing: tried MAX_TRIES times, no select, never armed or " + "stuck", len(res) == carmode.MAX_TRIES + and not any(r for _t, _a, r in res) + and all(a == 0.0 for _t, a, _r in res) + and not w.sim.writes("phases") and never_stuck(tr)) + check(f"T19 [{side}] ...and no charger_stuck row; charger_refused shows " + f"({w.amber()})", "charger_refused" in w.amber() + and "charger_stuck" not in w.amber()) + + +# =========================================================================== # +print("\n3. W: NO LIFE, ACCEPTED WRITES, TRANSITIONS") +# =========================================================================== # +async def t11(beside): + w = await live_car(beside=beside) + w.sim.set_current(5) # under 6 A: B, exactly 0 W, waiting + await w.step(8) + w.sim.refuse = "ignore" + res = spy_on(w) + await w.act("car_current", 10) + tr = await w.step(300) + return w, res, tr + + +for beside, side in SIDES: + LOG.rec.clear() + w, res, tr = run(t11(beside)) + keep(f"T11-{side}", w, res) + t_s = res[0][0] + fs = first_stuck(tr) + check(f"T11 [{side}] a paused car (B, 0 W) shows no life: it arms as " + f"today, stuck at t_s+60 ({fs - t_s if fs else None})", + w.sim.state == "B" and w.sim.power_w == 0.0 and fs is not None + and 59 <= fs - t_s <= 61) + check(f"T11 [{side}] ...and after the 3rd try both amber rows show: " + f"{w.amber()}", w.amber() == ["charger_refused", "charger_stuck"]) + + +async def t14(): + w = await live_car(beside=True) + w.sim.lag_s = 3.0 # the read-back is seen by the cycle + w.sim.freeze_power() # the power sticks, the rest is live + res = spy_on(w) + await w.act("car_current", 8) + tr = await w.step(100) + return w, res, tr + + +LOG.rec.clear() +w, res, tr = run(t14()) +t_s = res[0][0] +fs = first_stuck(tr) +check(f"T14 an ACCEPTED write (read-back 3 s late) under a frozen power: " + f"stuck at t_s+60 (+-1), as before ({fs - t_s if fs else None})", + res[0][2] is True and fs is not None and 59 <= fs - t_s <= 61 + and w.c.car.armed_at == t_s) +check("T14 ...the amber row 'charger_stuck' shows, and the car figure is not " + "trusted while stuck (N4)", "charger_stuck" in w.amber() + and w.c.car.car_w_trusted(w.t) is None and w.c.car_alarm_w() is None) + + +async def t17(): + w = await live_car(beside=True) + w.sim.refuse = "ignore" + res = spy_on(w) + await w.act("car_current", 10) + tr = await w.step(70) # tries at t_s and t_s+60: live + w.sim.refuse = None + w.sim.lag_s = 3.0 + w.sim.freeze_power() + await w.act("car_current", 12) + tr += await w.step(120) + return w, res, tr + + +LOG.rec.clear() +w, res, tr = run(t17()) +t_s, t_acc = res[0][0], res[-1][0] +fs = first_stuck(tr) +check(f"T17 live refusals (not armed), then an accepted write at t_s+" + f"{t_acc - t_s:.0f}: not armed before it, stuck at ITS +60 (+-1) " + f"({fs - t_acc if fs else None})", + res[-1][2] is True and t_acc - t_s > 61 and fs is not None + and 59 <= fs - t_acc <= 61 + and all(a is None for t, a, _s in tr if t < t_acc)) + + +async def t18(): + w = await live_car(beside=True) + w.sim.lag_s = 3.0 + w.sim.freeze_power() + res = spy_on(w) + await w.act("car_current", 12) # accepted: arms + tr = await w.step(19) + w.sim.lag_s = 0.0 + w.sim.refuse = "ignore" + await w.act("car_current", 10) # a live refusal 20 s later + tr += await w.step(100) + return w, res, tr + + +LOG.rec.clear() +w, res, tr = run(t18()) +t0 = res[0][0] +fs = first_stuck(tr) +check(f"T18 an accepted write armed at t0; a live refusal at t0+" + f"{res[1][0] - t0:.0f} neither clears nor delays it: stuck at t0+60 " + f"({fs - t0 if fs else None}), still dated t0", + len(res) >= 2 and res[1][2] is False and fs is not None + and 59 <= fs - t0 <= 61 and tr[-1][1] == t0 + and all(a == t0 for _t, a, _s in tr if a is not None)) + + +async def t21(beside): + w = await live_car(10, 3, beside=beside) + w.sim.lag_s = 14.0 + res = spy_on(w) + await w.act("car_current", 12) + tr = await w.step(120) + return w, res, tr + + +for beside, side in SIDES: + LOG.rec.clear() + w, res, tr = run(t21(beside)) + keep(f"T21-{side}", w, res) + check(f"T21 [{side}] HA took it, the read-back comes 14 s late (False at " + "+10): never stuck, no 'another writer' row, 12 A adopted, one " + "write", [(a, r) for _t, a, r in res] == [(12.0, False)] + and not any(st for _t, _a, st in tr) + and "charger_other" not in w.rows() + and "charger_writer" not in w.rows() + and w.c.car_writer.last_a == 12.0 and w.sim.readback_a == 12.0) + + +async def t20(beside): + """EV-28 T15 shape: the 0 A is taken and the car stops, the select is + taken, then the restore is refused MAX_TRIES times 5 s apart at 0 W.""" + w = await live_car(16, 3, beside=beside) + res = spy_on(w) + await w.act("car_phases", 1) + for _ in range(60): + await w.step(1) + if w.sim.phases_allowed == 1: + break + w.sim.refuse = "error" + tr = await w.step(150) + return w, res, tr + + +for beside, side in SIDES: + LOG.rec.clear() + w, res, tr = run(t20(beside)) + keep(f"T20-{side}", w, res) + rest = [x for x in res if x[1] == 16.0] + fs = first_stuck(tr) + t_r = rest[0][0] if rest else None + check(f"T20 [{side}] the 0 A is taken, the restore is refused " + f"{len(rest)} times at 0 W with nothing changing: it arms as on " + f"the base, dated the first refusal (stuck at +" + f"{fs - t_r if fs and t_r else None})", + len(rest) >= carmode.MAX_TRIES and not any(r for _t, _a, r in rest) + and w.sim.power_w == 0.0 and fs is not None and 59 <= fs - t_r <= 61) + check(f"T20 [{side}] ...no select besides the one made, and the rows " + f"are as on the base ({w.amber()})", + len(w.sim.writes("phases")) == 1 + and "charger_stuck" in w.amber()) + + +# =========================================================================== # +print("\n4. W: AN ERROR AND A RESTART") +# =========================================================================== # +async def t13(exc): + w = await live_car() + n0 = len(LOG.rec) + + async def boom(a): + await w.sleep(1.0) + raise exc + w.drv.write_current = boom + await w.act("car_current", 10) + tr = await w.step(30) + return w, tr, n0 + + +from app import hass # noqa: E402 +for exc in (RuntimeError("the link broke"), hass.ReadOnly("read only")): + LOG.rec.clear() + w, tr, n0 = run(t13(exc)) + errs = [m for lv, m in LOG.rec[n0:] + if lv == "ERROR" and "car charger step failed" in m] + check(f"T13 write_current raises {type(exc).__name__}: as on the base: " + "never armed, no window left, no refusal counted, the mute set, " + f"the step error logged once ({len(errs)})", + never_stuck(tr) and pend(w.c.car) is None + and w.c.car_writer.fails == 0 and w.c.car.mute_until > 0 + and len(errs) == 1) + + +async def t25(): + w = await live_car() + w.sim.refuse = "ignore" + await w.act("car_current", 10) + await w.step(75) # two tries + fails_before = w.c.car_writer.fails + w.make(CAR) # a restart: a new Controller + return w, fails_before + + +w, fb = run(t25()) +check("T25 a restart after 2 refusals: a fresh tracker and writer, nothing " + "armed, nothing waiting, no failures counted", + fb == 2 and w.c.car.armed_at is None and pend(w.c.car) is None + and not w.c.car.stuck(w.t) and w.c.car_writer.fails == 0) + +# =========================================================================== # +print("\n5. C: THE PEAK GUARD (the real Controller on the SAFETY-81 plant)") +# =========================================================================== # +import ev04_peak as P # noqa: E402 +import safety81_sim as s81 # noqa: E402 + +HOUSE = 3000.0 +AIM = 6050.0 + + +def drive(events, dur, house=HOUSE, aim=AIM, **kw): + """P.drive with a trace per second, taken before that second's cycle: + (second, armed_at, stuck, car_alarm_w, the alarms so far).""" + tr = [] + + def note(plant, c): + tr.append((plant.t, c.car.armed_at, c.car.stuck_now, c.car_alarm_w())) + ev = {t: note for t in range(0, dur)} + for t, fn in events.items(): + ev[t] = (lambda p, c, fn=fn: (fn(p, c), note(p, c))) + kw.setdefault("phases", 3) + kw.setdefault("setpoint", 16) + kw.setdefault("user_a", 16) + r = P.drive(s81.constant(house), dur=dur, rating=12000.0, soc=60.0, + cap=aim, events=ev, **kw) + return r, tr + + +def user_change(a): + def fn(plant, c): + asyncio.get_event_loop().create_task(c.handle_action( + "car_current", value=a)) + return fn + + +def reserve(plant, c): + """Both units at the peak reserve, the house on, the car 11 kW.""" + plant.soc = 19.0 + plant.load = lambda t: HOUSE + plant.ch.power_w + + +def sends(r): + return [(round(x[0]), x[1], x[2]) for x in r["sim"].writes()] + + +def amber_rows(r): + return sorted(x["id"] for x in r["c"].checks() + if x["warn"] and not x["ok"] and x["id"].startswith("charger")) + + +ALARMS = P.ALARMS + ("goodwe_peak_floor_limited",) + + +def alarm_list(r): + return P.ids(r, *P.ALARMS) + + +# T22: a live refusal under a car-caused overload raises nothing the twin +# does not +def t22_events(change): + ev = {300: lambda p, c: (reserve(p, c), setattr(p.ch, "refuse", "ignore") + if change else None)} + if change: + ev[301] = user_change(10) + return ev + + +r_ref, tr_ref = drive(t22_events(True), 700) +r_twin, tr_twin = drive(t22_events(False), 700) +w_ref = [x[3] for x in tr_ref if x[0] >= 300] +w_twin = [x[3] for x in tr_twin if x[0] >= 300] +check("T22 PRECONDITION: the refusals happened (3 tries) and the twin wrote " + "nothing", len(r_ref["sim"].writes("current")) == 3 + and r_twin["sim"].writes("current") == []) +check("T22 a live refusal under a car-caused overload: the car figure used by " + "the alarm path is the twin's every cycle from 300 to 700 (+-1 W)", + len(w_ref) == len(w_twin) and all( + (a is None and b is None) or (a is not None and b is not None + and abs(a - b) <= 1.0) + for a, b in zip(w_ref, w_twin))) +check(f"T22 ...and the alarms are the twin's ({alarm_list(r_ref)} vs " + f"{alarm_list(r_twin)})", alarm_list(r_ref) == alarm_list(r_twin) + and alarm_list(r_ref) == []) +check("T22 ...never armed, never stuck", all(a is None and not s + for _t, a, s, _w in tr_ref)) + +# T16: the test_ev04 section 9 shape: everything frozen, the car really goes, +# the user sets 10 A: the write is refused and nothing changes + + +def freeze_all(plant, c): + plant.ch.freeze() # every reading sticks, the + plant.ch.unplug() # read-back too; the car goes + plant.load = lambda at: 9000.0 + plant.ch.power_w + + +r16, tr16 = drive({60: lambda p, c: (freeze_all(p, c), + user_change(10)(p, c))}, 400, + house=1100.0, aim=3500.0) +SEND["T16"] = ([], sends(r16)) +log16 = [x for x in r16["c"].car_writer.log if x[0] == "current"] +t_s = log16[0][2] if log16 else None +fs = next((t for t, _a, s, _w in tr16 if s), None) +al16 = P.ids(r16, "goodwe_peak_saturated") +check(f"T16 everything frozen, the write is refused: it arms at t_s={t_s} " + f"and is stuck at t_s+60 +-2 (first {fs})", + t_s is not None and fs is not None and 58 <= fs - t_s <= 62 + and not any(x[3] for x in log16)) +check(f"T16 ...after MAX_TRIES both rows show: {amber_rows(r16)}", + amber_rows(r16) == ["charger_refused", "charger_stuck"]) +check("T16 ...the car figure is not used while stuck, and the normal alarm " + f"fires before freeze+60+60+25 ({al16})", + r16["c"].car_alarm_w() is None and len(al16) == 1 + and al16[0][0] < 60 + 60 + 25) + +# T23 (EV-10 trap): a 6 A, 1 phase car (1.38 kW) takes no energy step inside +# the window, so its refusal arms as today. The house then steps 1.7 kW over +# the aim: the car does not explain it, so the alarm comes at the twins' cycle. +def t23_events(change, t_s=570): + def house_drain(plant, c): # test_ev10's trap shape + plant.soc = 19.0 + plant.load = lambda at: 12000.0 + plant.ch.power_w + return {t_s - 1: lambda p, c: (setattr(p.ch, "refuse", "ignore") + if change else None), + t_s: user_change(8) if change else (lambda p, c: None), + t_s + 30: house_drain} + + +def t23(change, mode="manual"): + return drive(t23_events(change), 800, house=1100.0, aim=4500.0, + phases=1, setpoint=6, user_a=6, mode=mode) + + +r23, tr23 = t23(True) +r23a, tr23a = t23(False) +r23o, tr23o = t23(False, mode="off") +a23, a23a, a23o = (P.ids(x, *P.ALARMS) for x in (r23, r23a, r23o)) +check(f"T23 PRECONDITION: the refusal found no life (6 A, 1.38 kW): it armed " + f"as today, stuck at t_s+60", any(s for _t, _a, s, _w in tr23) + and len(r23["sim"].writes("current")) >= 1) +check(f"T23 the alarm fires at the same second as both twins (refusal " + f"{a23}, no write {a23a}, Off {a23o})", len(a23) == 1 + and [n for _t, n in a23] == [n for _t, n in a23a] + and abs(a23[0][0] - a23a[0][0]) <= 1 and a23o + and abs(a23[0][0] - a23o[0][0]) <= 1) + + +# T24 (EV-18): after a live refusal (not armed) the energy meter stops while +# the power says 11 kW: the figure is contradicted and the quarter latched. +# (The tries are at 300, 360 and 420, each live; the meter stops after them.) +def meter_stops(plant, c): + sim, tick = plant.ch, plant.ch.tick + + def stuck_meter(secs=1.0): + kwh = sim.kwh + tick(secs) + sim.kwh = kwh + sim.tick = stuck_meter + + +def t24(change): + ev = {299: lambda p, c: (reserve(p, c), setattr(p.ch, "refuse", "ignore") + if change else None), + 300: user_change(10) if change else (lambda p, c: None), + 432: meter_stops} # after the 3rd try's window + seen = [] + + def watch(plant, c): + seen.append((plant.t, c._car_contradicted(c.car_now()), + c._car_contra_block)) + for t in range(300, 700): + prev = ev.get(t) + ev[t] = (lambda p, c, prev=prev: (prev(p, c) if prev else None, + watch(p, c))) + r, tr = drive(ev, 700) + return r, tr, seen + + +r24, tr24, seen24 = t24(True) +check("T24 PRECONDITION: a live refusal at 300 (not armed)", + len(r24["sim"].writes("current")) >= 1 + and all(a is None and not st for t, a, st, _w in tr24)) +check("T24 after a live refusal the meter that falls short for a window " + "contradicts the figure and latches the quarter (a refusal hides no " + "contradiction)", any(x[1] for x in seen24) + and seen24[-1][2] is not None) + +# =========================================================================== # +print("\n6. WRITES: THE SAME AS ON THE BASE (T26, N3)") +# =========================================================================== # +if os.environ.get("EV13_DUMP"): + for k in sorted(SEND): + print("DUMP", repr(k), repr(SEND[k])) +BASE_SENDS = { # recorded on 76f4de2 (release/1.0 before EV-13) + 'T1-ignore-beside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], [(11, 'current', 10.0), (71, 'current', 10.0), (131, 'current', 10.0)]), + 'T1-ignore-inside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], [(11, 'current', 10.0), (71, 'current', 10.0), (131, 'current', 10.0)]), + 'T11-beside': ([(1019, 10.0, False), (1079, 10.0, False), (1139, 10.0, False)], [(19, 'current', 10.0), (79, 'current', 10.0), (139, 'current', 10.0)]), + 'T11-inside': ([(1019, 10.0, False), (1079, 10.0, False), (1139, 10.0, False)], [(19, 'current', 10.0), (79, 'current', 10.0), (139, 'current', 10.0)]), + 'T16': ([], [(61, 'current', 10.0), (131, 'current', 10.0), (201, 'current', 10.0)]), + 'T19-beside': ([(1011, 0.0, False), (1071, 0.0, False), (1131, 0.0, False)], [(11, 'current', 0.0), (71, 'current', 0.0), (131, 'current', 0.0)]), + 'T19-inside': ([(1011, 0.0, False), (1071, 0.0, False), (1131, 0.0, False)], [(11, 'current', 0.0), (71, 'current', 0.0), (131, 'current', 0.0)]), + 'T2-error-beside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []), + 'T2-error-inside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []), + 'T20-beside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False), (1095, 16.0, False), (1155, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]), + 'T20-inside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False), (1095, 16.0, False), (1155, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]), + 'T21-beside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]), + 'T21-inside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]), +} +for k in sorted(SEND): + check(f"T26 {k}: the writes (second, value, taken) and what the model " + "received are the base's", BASE_SENDS.get(k) == SEND[k]) +check("T26 no write above the clamp (16 A), and the one select (T20) came " + "with the car at 0 W", all(a <= 16.0 for v in SEND.values() + for _t, a, _r in v[0]) + and sorted(k for k, v in SEND.items() + if any(x[1] == "phases" for x in v[1])) == ["T20-beside", + "T20-inside"]) + +print() +if fails: + print(f"FAIL: {len(fails)} check(s)") + for f in fails: + print(" -", f) + sys.exit(1) +print("ok: EV-13") -- 2.54.0 From c3903b796bb06195ad737d0f606cc1b3b0cf21c3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 02:23:56 +0100 Subject: [PATCH 20/55] EV-13: CHANGELOG line and DECISIONS note Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/CHANGELOG.md | 1 + goodwe_controller/DECISIONS/EV-04-manual-mode.md | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index bf5a514..535e9fe 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -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]]). diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index 39c2fa1..2237202 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -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), -- 2.54.0 From 1b39f1698a7f5e2d0ebe3774c4a81749b4203958 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:56:53 +0100 Subject: [PATCH 21/55] EV-13 router round 1: lapse a refusal's window on unavailable readings; T27, T28 and the N-ids Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/app/chargers.py | 9 ++ goodwe_controller/test_ev13.py | 163 ++++++++++++++++++++++++++++++ 2 files changed, 172 insertions(+) diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index 228b09f..a6bd23e 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -728,6 +728,8 @@ 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) @@ -833,6 +835,13 @@ class CarTracker: 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 diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index ecab25b..fe22e79 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -139,6 +139,9 @@ def play(timeline, mode="live", ok=False, was=16.0, to=10.0, pre_end=0, MODES = ("live", "ring", "polls") +N1, N2 = [], [] # (name, never stuck) / (name, seconds from the send to stuck) + + def pend(tr): """The refusal window a tracker keeps open (None: none).""" return getattr(tr, "_pend", None) @@ -147,6 +150,7 @@ def pend(tr): def life(name, changes, **kw): for m in MODES: tr, first, armed = play(steady(changes), m, **kw) + N1.append((f"{name} [{m}]", first is None and not tr.stuck_now)) check(f"{name} [{m}]: not armed, never stuck to TS+130", tr.armed_at is None and first is None and not armed and not tr.stuck_now) @@ -155,6 +159,7 @@ def life(name, changes, **kw): def armed(name, tl, at=TS, **kw): for m in MODES: tr, first, ever = play(tl, m, **kw) + N2.append((f"{name} [{m}]", None if first is None else first - TS)) check(f"{name} [{m}]: armed at the send, stuck at TS+60 (+-1), " f"not before TS+59 (first {first})", first is not None and TS + 59 <= first <= TS + 61 @@ -501,6 +506,7 @@ for beside, side in SIDES: len(res) == 3 and not any(r for _t, _a, r in res) and all(55 <= b - a <= 75 for a, b in zip(ts, ts[1:])) and w.c.car_writer.gave_up) + N1.append((nm, never_stuck(tr))) check(f"{nm}: the car shows life inside each window: never armed, " "never stuck, to 400 s", never_stuck(tr)) check(f"{nm}: after the 3rd try exactly ONE amber charger row, " @@ -529,6 +535,7 @@ for beside, side in SIDES: LOG.rec.clear() w, res, tr = run(t19(beside)) keep(f"T19-{side}", w, res) + N1.append((f"T19 [{side}]", never_stuck(tr))) check(f"T19 [{side}] the 0 A of a phase change is ignored and the car " "keeps drawing: tried MAX_TRIES times, no select, never armed or " "stuck", len(res) == carmode.MAX_TRIES @@ -560,6 +567,7 @@ for beside, side in SIDES: keep(f"T11-{side}", w, res) t_s = res[0][0] fs = first_stuck(tr) + N2.append((f"T11 [{side}]", None if fs is None else fs - t_s)) check(f"T11 [{side}] a paused car (B, 0 W) shows no life: it arms as " f"today, stuck at t_s+60 ({fs - t_s if fs else None})", w.sim.state == "B" and w.sim.power_w == 0.0 and fs is not None @@ -687,6 +695,7 @@ for beside, side in SIDES: rest = [x for x in res if x[1] == 16.0] fs = first_stuck(tr) t_r = rest[0][0] if rest else None + N2.append((f"T20 [{side}]", None if not (fs and t_r) else fs - t_r)) check(f"T20 [{side}] the 0 A is taken, the restore is refused " f"{len(rest)} times at 0 W with nothing changing: it arms as on " f"the base, dated the first refusal (stuck at +" @@ -849,6 +858,8 @@ log16 = [x for x in r16["c"].car_writer.log if x[0] == "current"] t_s = log16[0][2] if log16 else None fs = next((t for t, _a, s, _w in tr16 if s), None) al16 = P.ids(r16, "goodwe_peak_saturated") +N2.append(("T16", None if fs is None else fs - t_s)) +N1.append(("T22", all(a is None and not st for _t, a, st, _w in tr_ref))) check(f"T16 everything frozen, the write is refused: it arms at t_s={t_s} " f"and is stuck at t_s+60 +-2 (first {fs})", t_s is not None and fs is not None and 58 <= fs - t_s <= 62 @@ -963,6 +974,158 @@ check("T26 no write above the clamp (16 A), and the one select (T20) came " if any(x[1] == "phases" for x in v[1])) == ["T20-beside", "T20-inside"]) +# =========================================================================== # +print("\n7. A REFUSAL, THEN THE CHARGER GOES UNAVAILABLE") +# =========================================================================== # +GONE = CH.ChargerReading(available=False, why="no answer") + + +def gone_then_back(back_at, mode): + """Refusal at TS; no answer until `back_at`; then the frozen reading.""" + tl = [(TS + s, GONE if s < back_at else rd()) for s in range(1, 131)] + return play(tl, mode) + + +for mode in ("live", "ring"): + tr, first, _ = gone_then_back(21, mode) + check(f"unavailable [{mode}]: a refusal, no answer from TS+1 to TS+20 " + f"(past TOOK_S), then the reading back and frozen: armed dated the " + f"send, stuck at TS+60 as on the base (first {first})", + tr.armed_at == TS and first is not None and TS + 59 <= first + <= TS + 61 and pend(tr) is None) + tl = [(TS + k, GONE) for k in range(1, 31)] + tr, first, _ = play(tl, mode) + check(f"unavailable [{mode}]: a refusal and no answer at all for 30 s: " + "armed dated the send while it is still unavailable, as on the " + "base", tr.armed_at == TS and pend(tr) is None) + tr, first, _ = gone_then_back(75, mode) + check(f"unavailable [{mode}]: no answer until TS+75: the window lapsed " + f"unseen, so the first reading back is stuck at once, as on the base " + f"(first {first})", tr.armed_at == TS and first == TS + 75) + tr, first, _ = gone_then_back(5, mode) + check(f"unavailable [{mode}]: back inside the window and frozen: the " + "window runs on and arms at the send", tr.armed_at == TS + and first is not None and TS + 59 <= first <= TS + 61) + +# =========================================================================== # +print("\n8. N-IDS") +# =========================================================================== # +check(f"N1: no stuck after refusals that all showed life (T1-T5, T9 edges, " + f"T12a, T19, T22: {len(N1)} runs)", len(N1) >= 20 + and all(ok for _n, ok in N1)) +check(f"N2: every refusal with no life is stuck within 61 s of its send " + f"(T6-T11, T12b, T16, T20: {len(N2)} runs)", len(N2) >= 20 + and all(d is not None and d <= 61 for _n, d in N2)) +check("N5: no house-caused alarm later than the no-write twin or Off (T22 " + "equals its twin; T23 within a second of both)", + alarm_list(r_ref) == alarm_list(r_twin) + and abs(a23[0][0] - a23a[0][0]) <= 1 and abs(a23[0][0] - a23o[0][0]) <= 1) +from app import messages # noqa: E402 +check("N6: the constants and the row texts (EN and NL) are the base's", + (CH.STUCK_S, CH.STUCK_MIN_A, CH.OWN_WRITE_MUTE_S, CH.TOOK_S) == + (60.0, 1.0, 15.0, 10.0) + and (carmode.MAX_TRIES, carmode.RETRY_S) == (3, 60.0) + and messages.row_charger_stuck() == + "The charger reading may be stuck, so check the charger." + and messages.row_charger_stuck().nl == + "De meting van de laadpaal staat mogelijk vast, dus controleer de " + "laadpaal." + and messages.row_charger_refused() == + "The charger did not take the setting, so check the charger." + and messages.row_charger_refused().nl == + "De laadpaal nam de instelling niet over, dus controleer de laadpaal.") + +# =========================================================================== # +print("\n9. T27: THE EV-04 SECTION 9 CHECKS ARE THE BASE'S; T28: THE MUTANTS") +# =========================================================================== # +S9_SHA = "2a40480c804574207b0c81096365363c8d608eeb32285a1c18700478fc37fc41" +src04 = open(os.path.join(HERE, "test_ev04.py")).read() +a9 = src04.index('9. THE PEAK GUARD') +b9 = src04.index("# a plausible figure is bounded by what the read-back allows") +sec9 = src04[a9:b9] +check("T27 test_ev04 section 9 is byte-identical to 76f4de2", + hashlib.sha256(sec9.encode()).hexdigest() == S9_SHA) +check("T27 ...its two stuck checks are there", + "the amber row 'Charger reading may be stuck' says so" in sec9 + and "...while stuck, the car figure is not used by the alarm path" in sec9) +# the other files T27 names (ev04, ev10, ev10b, ev15, ev18, ev19, ev28, +# named_absence, bytecode) are test files of their own: CI runs every +# test_*.py, so a red one fails this PR; not re-run from here. + +MUTANTS = { + "M1": (" before = [x for x in self._ring if x[0] <= now]\n", + " return\n before = [x for x in self._ring if x[0] " + "<= now]\n"), + "M2": (" if old and all(v != o for o in old):", " if old:"), + "M3": (" t = now if r.taken_at is None else r.taken_at\n", + " t = now\n"), + "M4": (" self._pend_feed(t, v, t)\n\n def _life", + " self._pend_feed(t, v, t)\n self._pend_arm()\n\n" + " def _life"), + "M5": (' if max(t, arrival) > p["t"] + TOOK_S:\n' + ' self._pend_arm()', + ' if max(t, arrival) > p["t"] + TOOK_S:\n' + ' self._pend_arm(max(t, arrival))'), +} +M5_SIG = (" def _pend_arm(self) -> None:", + " def _pend_arm(self, at=None) -> None:") +M5_SET = (' self.armed_at, self.armed_sig = p["t"], p["sig"]', + ' self.armed_at, self.armed_sig = (p["t"] if at is None ' + 'else at), p["sig"]') +# what each mutant must turn red (substrings of the failing check names) +RED = {"M1": ["T6 ", "T7 ", "T11 ", "T16 "], "M2": ["T6 "], + "M3": ["T7 ", "T8 "], "M4": ["T2 "], "M5": ["T9 ", "T16 "]} + + +def mutant_run(name): + """A copy of the tree with the bug put back; test_ev13 (and, for the + stuck rows, test_ev04) run in it. The children skip this section.""" + import shutil + import subprocess + import tempfile + d = tempfile.mkdtemp(prefix="ev13m-") + dst = os.path.join(d, "gc") + shutil.copytree(HERE, dst, ignore=shutil.ignore_patterns( + "__pycache__", "*.pyc")) + p = os.path.join(dst, "app", "chargers.py") + txt = open(p).read() + edits = [MUTANTS[name]] + ([M5_SIG, M5_SET] if name == "M5" else []) + for old, new in edits: + assert txt.count(old) == 1, (name, old) + txt = txt.replace(old, new) + open(p, "w").write(txt) + env = dict(os.environ, EV13_MUTANT="1", PYTHONDONTWRITEBYTECODE="1") + procs = {f: subprocess.Popen( + [sys.executable, "-B", f], cwd=dst, env=env, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True) + for f in ("test_ev13.py", "test_ev04.py")} + out = {f: pr.communicate()[0] for f, pr in procs.items()} + shutil.rmtree(d, ignore_errors=True) + return {f: [ln for ln in o.splitlines() if ln.strip().startswith("FAIL")] + for f, o in out.items()}, {f: procs[f].returncode for f in procs} + + +if not os.environ.get("EV13_MUTANT"): + import concurrent.futures + with concurrent.futures.ThreadPoolExecutor(5) as ex: + res = dict(zip(MUTANTS, ex.map(mutant_run, MUTANTS))) + for name in MUTANTS: + reds, rcs = res[name] + got = reds["test_ev13.py"] + check(f"T28 {name}: test_ev13 goes red ({len(got)} checks) in " + f"{RED[name]}", rcs["test_ev13.py"] != 0 + and all(any(k in ln for ln in got) for k in RED[name])) + check("T28 M1 also turns the two test_ev04 section 9 stuck checks red", + res["M1"][1]["test_ev04.py"] != 0 + and any("amber row 'Charger reading may be stuck'" in ln + for ln in res["M1"][0]["test_ev04.py"]) + and any("car figure is not used" in ln + for ln in res["M1"][0]["test_ev04.py"])) + check("T28 M2 turns test_ev04 section 9 red too; M3, M4 and M5 do not " + "(its 85 s bound is too loose to see M5's 10 s: see the report)", + res["M2"][1]["test_ev04.py"] != 0 + and all(res[m][1]["test_ev04.py"] == 0 for m in ("M3", "M4", "M5"))) + print() if fails: print(f"FAIL: {len(fails)} check(s)") -- 2.54.0 From 5ebd830966afec5ab5ba9aa60beb4ba3133f9843 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 05:44:31 +0100 Subject: [PATCH 22/55] EV-13 review: compare phase currents per phase; test a late read-back A phase that drops out or comes back shifted the compressed current_a tuple and read as life, so a frozen charger never armed. ChargerReading.phase_a keeps L1/L2/L3 with None for a missing phase and the life test uses it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/app/chargers.py | 16 +++++++---- goodwe_controller/test_ev13.py | 44 +++++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index a6bd23e..c6cb8ee 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -166,6 +166,7 @@ class ChargerReading: # 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): @@ -285,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")), @@ -544,11 +546,10 @@ class AlfenHaDriver(ChargerDriver): """EV-13: keep what this wait saw of energy, power and phase currents (never raises: a write does not depend on it).""" try: - cur = tuple(a for a in (_amps(st.get(k)) for k in ("l1", "l2", "l3")) - if a is not None) self.polls.append((self._clock(), ChargerReading( available=True, power_w=_watts(st.get("power")), - energy_kwh=_kwh(st.get("energy")), current_a=cur))) + energy_kwh=_kwh(st.get("energy")), + phase_a=tuple(_amps(st.get(k)) for k in ("l1", "l2", "l3"))))) except Exception: # noqa: BLE001 pass @@ -656,8 +657,13 @@ 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.current_a or ())[:3] - return (r.energy_kwh, r.power_w) + cur + (None,) * (3 - len(cur)) + 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: diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index fe22e79..d89aa70 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -78,11 +78,13 @@ TOOK_S, STUCK_S = CH.TOOK_S, CH.STUCK_S print("1. S: WHAT COUNTS AS LIFE") # =========================================================================== # def rd(e=1.000, p=11040.0, cur=(16.0, 15.9, 16.0), a=16.0, taken=None, - state="C"): + state="C", ph=None): + """`cur` is `current_a` (a missing phase is left out of it); `ph` is the + per-phase `phase_a` (None for a missing phase) the driver also sets.""" return CH.ChargerReading( available=True, state=state, charging=state == "C", power_w=p, energy_kwh=e, current_a=cur, allowed_a=a, setpoint_a=a, - phases_allowed=3, taken_at=taken) + phases_allowed=3, taken_at=taken, phase_a=ph or ()) def steady(changes=None, start=1, end=130, **base): @@ -174,6 +176,21 @@ life("T9 the step at +9, inside the window", {9: dict(e=1.010)}) life("T9 the step exactly at +10 (the edge counts)", {10: dict(e=1.010)}) life("T12(a) power None, state C, energy rising", {4: dict(e=1.010)}, pre=dict(p=None)) +# P1/P2 (review): a phase that drops out or comes back is no change: the +# others must not shift against another phase's old value +armed("P1 L1 present before, absent after, all else frozen", + steady(cur=(16.0, 16.1))) +armed("P2 L1 absent before, present after (current_a only), all else frozen", + steady(), pre=dict(cur=(15.9, 16.0))) +armed("P1 per phase: L1 present before, absent after (phase_a)", + steady(cur=(16.0, 16.1), ph=(None, 16.0, 16.1)), + pre=dict(ph=(15.9, 16.0, 16.1))) +armed("P2 per phase: L1 absent before, present after (phase_a)", + steady(ph=(15.9, 16.0, 16.1)), pre=dict(cur=(16.0, 16.1), + ph=(None, 16.0, 16.1))) +life("P5 per phase: L1 absent, L2 really changes (phase_a)", + {4: dict(cur=(16.2, 16.1), ph=(None, 16.2, 16.1))}, + pre=dict(cur=(16.0, 16.1), ph=(None, 16.0, 16.1))) armed("T6 present but unchanged: every sample repeats the pre-write values", steady()) armed("T9 the step at +11 is outside the window; armed_at is the send, not " @@ -1007,6 +1024,29 @@ for mode in ("live", "ring"): "window runs on and arms at the send", tr.armed_at == TS and first is not None and TS + 59 <= first <= TS + 61) +# P4 (review): a refusal with no life, and a read-back that arrives late but +# inside TOOK_S. The base arms at the send and the moved read-back disarms it +# ("it moved: alive"); the window must do the same, not arm on the new value. +zero = dict(p=0.0, cur=(0.0, 0.0, 0.0)) +tr, first, ever = play(steady({5: dict(a=10.0)}, **zero), "live", pre=zero) +check(f"P4 [live]: no life, the read-back moves at +5, after the refusal was " + f"noted: armed dated the send and disarmed by the move, never stuck, " + f"as on the base ({tr.armed_at}, {first})", first is None + and tr.armed_at is None and not tr.stuck_now and pend(tr) is None) +tr, first, ever = play(steady({5: dict(a=10.0)}, **zero), "ring", pre=zero) +check(f"P4 [ring]: the read-back moved inside the window BEFORE the refusal " + f"was noted (the write waited): it still arms, dated the send, and is " + f"stuck at +60, as on the base (armed {tr.armed_at}, first {first})", + tr.armed_at == TS and first == TS + 60) +# ... and the same read-back arriving AFTER the window leaves it stuck until +# it moves: 12 s in, the base has been armed since the send, so it disarms then +tr, first, ever = play(steady({12: dict(a=10.0)}, **zero), "live", pre=zero) +check("P4 the read-back moves at +12 (after the window): disarmed then, " + "never stuck", first is None and tr.armed_at is None) +tr, first, ever = play(steady({70: dict(a=10.0)}, **zero), "live", pre=zero) +check(f"P4 the read-back moves at +70: stuck at +60 first, as on the base " + f"(first {first}-{TS})", first == TS + 60 and tr.armed_at is None) + # =========================================================================== # print("\n8. N-IDS") # =========================================================================== # -- 2.54.0 From 0774d1efd5c800a27518edce9f4dcbb9e3132051 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 06:54:30 +0100 Subject: [PATCH 23/55] EV-13 router round 3: N2 names P1/P2; P4 live window dated the send; kills R1 Co-Authored-By: Claude --- goodwe_controller/test_ev13.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index d89aa70..b0c57d6 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -1033,6 +1033,28 @@ check(f"P4 [live]: no life, the read-back moves at +5, after the refusal was " f"noted: armed dated the send and disarmed by the move, never stuck, " f"as on the base ({tr.armed_at}, {first})", first is None and tr.armed_at is None and not tr.stuck_now and pend(tr) is None) +# The live case, looked at second by second: between the send and the move the +# refusal is a window dated the send (not yet armed, as nothing is decided); +# it arms dated TS when it runs out, with the sig AT THE SEND, so the moved +# read-back disarms it at once (kills the reviewer's R1: arm with the current sig). +_dates = [] +_tr = CH.CarTracker() +for _i in range(-20, 1): + _tr.observe(rd(**zero), TS + _i, UTC, DAY) +_orig = _tr._pend_arm +_tr._pend_arm = lambda: (_dates.append((_tr._pend or {}).get("t")), _orig()) +_tr.note_write(TS, 16.0, 10.0, False) +_mid = [] +for _s, _r in steady({5: dict(a=10.0)}, end=14, **zero): + _tr.observe(_r, _s, UTC, DAY) + _mid.append((_s - TS, (pend(_tr) or {}).get("t"), _tr.armed_at)) +check("P4 [live]: from the send to the move the refusal is an open window " + "dated TS (armed_at still None)", all(w == TS and a is None + for s, w, a in _mid if s < 11)) +check(f"P4 [live]: the window arms dated TS when it runs out, and the moved " + f"read-back disarms it in the same sample ({_dates}, {_mid[-1]})", + _dates == [TS] and _tr.armed_at is None and not _tr.stuck_now + and pend(_tr) is None) tr, first, ever = play(steady({5: dict(a=10.0)}, **zero), "ring", pre=zero) check(f"P4 [ring]: the read-back moved inside the window BEFORE the refusal " f"was noted (the write waited): it still arms, dated the send, and is " @@ -1056,6 +1078,12 @@ check(f"N1: no stuck after refusals that all showed life (T1-T5, T9 edges, " check(f"N2: every refusal with no life is stuck within 61 s of its send " f"(T6-T11, T12b, T16, T20: {len(N2)} runs)", len(N2) >= 20 and all(d is not None and d <= 61 for _n, d in N2)) +for _p in ("P1 L1 present before", "P2 L1 absent before", + "P1 per phase", "P2 per phase"): + _runs = [d for n, d in N2 if n.startswith(_p)] + check(f"N2 includes {_p!r} in all three modes: {len(_runs)} runs, each " + f"stuck within 61 s of its send", len(_runs) == 3 + and all(d is not None and d <= 61 for d in _runs)) check("N5: no house-caused alarm later than the no-write twin or Off (T22 " "equals its twin; T23 within a second of both)", alarm_list(r_ref) == alarm_list(r_twin) -- 2.54.0 From 57a9f56a64006450a788755480f1eec87b8b21b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 07:58:56 +0100 Subject: [PATCH 24/55] EV-13: guard the P4 live check's last sample (test_named_absence) Co-Authored-By: Claude --- goodwe_controller/test_ev13.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index b0c57d6..98d2b29 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -1051,9 +1051,10 @@ for _s, _r in steady({5: dict(a=10.0)}, end=14, **zero): check("P4 [live]: from the send to the move the refusal is an open window " "dated TS (armed_at still None)", all(w == TS and a is None for s, w, a in _mid if s < 11)) +_last = _mid[-1] if _mid else None check(f"P4 [live]: the window arms dated TS when it runs out, and the moved " - f"read-back disarms it in the same sample ({_dates}, {_mid[-1]})", - _dates == [TS] and _tr.armed_at is None and not _tr.stuck_now + f"read-back disarms it in the same sample ({_dates}, {_last})", + _last is not None and _dates == [TS] and _tr.armed_at is None and not _tr.stuck_now and pend(_tr) is None) tr, first, ever = play(steady({5: dict(a=10.0)}, **zero), "ring", pre=zero) check(f"P4 [ring]: the read-back moved inside the window BEFORE the refusal " -- 2.54.0 From 6cd775788d44a2c5dc42d06b7b6e3c3ea63d6658 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:45:14 +0100 Subject: [PATCH 25/55] EV-13 review round 2: tie the driver's polls to the cycle reading per phase (D1, D2) Co-Authored-By: Claude --- goodwe_controller/test_ev13.py | 82 ++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index 98d2b29..95b69c0 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -1070,6 +1070,88 @@ tr, first, ever = play(steady({70: dict(a=10.0)}, **zero), "live", pre=zero) check(f"P4 the read-back moves at +70: stuck at +60 first, as on the base " f"(first {first}-{TS})", first == TS + 60 and tr.armed_at is None) +# =========================================================================== # +print("\n7b. THE DRIVER'S POLLS ARE THE CYCLE'S READING, PER PHASE (review round 2)") +# =========================================================================== # +# On a frozen Alfen the polls `_took` keeps are all the tracker sees of the +# refusal's window. If `_poll` lists the phases in another order than +# `reading_from_states`, a frozen 1-phase car reads as a change and is never +# flagged. T11/T16/T20 run at 0 W (every phase 0 A) and the S shapes build +# their polls by hand, so these two checks tie the real driver to the cycle. +_clk = {"t": 0.0} + + +async def _frozen_1ph_3ph(phases): + """Real AlfenHaDriver on chargersim: a car on `phases` phases at 16 A, the + charger frozen (every state), the write ignored: `_took` times out and its + polls reach `note_write`.""" + sim = SimCharger(phases_allowed=phases, setpoint_a=16.0) + sim.car_phases = phases + sim.state, sim.power_w = "C", 16.0 * 230.0 * phases + sim.refuse = "ignore" + sim.freeze() + drv = CH.AlfenHaDriver("number.wallbox_" + CH.SETPOINT_SUFFIX, 16.0) + drv.bind(FakeHa(sim)) + drv._clock = lambda: _clk["t"] + + async def _sleep(sec): + _clk["t"] += sec + drv._sleep = _sleep + tr = CH.CarTracker() + _clk["t"] = TS - 10 + while _clk["t"] <= TS: + tr.observe(await drv.read(), _clk["t"], UTC, DAY) + _clk["t"] += 1.0 + _clk["t"] = TS + 0.3 + ok = await drv.write_current(10.0) + tr.note_write(TS, 16.0, 10.0, ok, drv.polls) + first = None + while _clk["t"] <= TS + 130: + _clk["t"] += 1.0 + tr.observe(await drv.read(), _clk["t"], UTC, DAY) + if first is None and tr.stuck(_clk["t"]): + first = _clk["t"] - TS + return ok, tr, first, len(drv.polls) + + +for _n in (1, 3): + _ok, _tr, _first, _np = asyncio.run(_frozen_1ph_3ph(_n)) + N2.append((f"D1 driver, frozen {_n}-phase car [driver]", + None if _first is None else _first)) + check(f"D1 driver on chargersim, frozen charger, {_n}-phase car at 16 A, " + f"write ignored (not ok, {_np} polls): armed at the send, stuck at " + f"+60 (+-1) (armed {_tr.armed_at}, first {_first})", + not _ok and _np >= 2 and _tr.armed_at == TS and _first is not None + and 59 <= _first <= 61.5) + + +async def _poll_vs_cycle(drop): + """`_life_vals` of `_poll`'s reading equals that of the cycle's reading, + on the same states, with distinct per-phase currents; `drop` removes a + phase (an entity that does not answer).""" + sim = SimCharger(phases_allowed=3, setpoint_a=16.0) + drv = CH.AlfenHaDriver("number.wallbox_" + CH.SETPOINT_SUFFIX, 16.0) + drv.bind(FakeHa(sim)) + st = await drv._states() + for k, v in (("l1", "15.5"), ("l2", "16.5"), ("l3", "17.5")): + st[k] = dict(st[k], state=v) if isinstance(st[k], dict) else st[k] + if drop: + st[drop] = None + cyc = CH.reading_from_states(st) + drv.polls = [] + drv._poll(st) + return cyc, drv.polls[0][1] + + +for _drop in (None, "l1", "l2", "l3"): + _cyc, _pl = asyncio.run(_poll_vs_cycle(_drop)) + check(f"D2 `_life_vals` of _poll's reading equals the cycle reading's, " + f"{'all three phases present' if _drop is None else _drop + ' missing'}" + f" ({CH._life_vals(_pl)[2:]} vs {CH._life_vals(_cyc)[2:]})", + CH._life_vals(_pl) == CH._life_vals(_cyc) and _cyc.available + and (_drop is not None or CH._life_vals(_cyc)[2:5] == + (15.5, 16.5, 17.5))) + # =========================================================================== # print("\n8. N-IDS") # =========================================================================== # -- 2.54.0 From d0285470cb3cfafde791686114c0b773a05ce26a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 13:45:30 +0100 Subject: [PATCH 26/55] EV-14: Car Why says what happens in shadow mode and after a phase change that did not happen Display only: shadow mode over-limit Why speaks in would-terms; read phases that differ from the setting say the charger stays; a writer hold says something else set the charger. EN and NL texts, test_ev14.py. Co-Authored-By: Claude --- goodwe_controller/app/homeview.py | 32 +- goodwe_controller/app/ui_text/en.json | 3 + goodwe_controller/app/ui_text/nl.json | 3 + goodwe_controller/test_ev14.py | 826 ++++++++++++++++++++++++++ 4 files changed, 862 insertions(+), 2 deletions(-) create mode 100644 goodwe_controller/test_ev14.py diff --git a/goodwe_controller/app/homeview.py b/goodwe_controller/app/homeview.py index 4774469..84c0fdd 100644 --- a/goodwe_controller/app/homeview.py +++ b/goodwe_controller/app/homeview.py @@ -1318,14 +1318,34 @@ def _over_why_is_floor(c, pg) -> bool: return bool(pg is not None and pg.floor_limited and pg.soc is not None) +def _real_phases(c): + """EV-14: the phases the charger reports (1 or 3), or None: no fresh + reading, or none read. Reads only; unknown is never a difference.""" + car = getattr(c, "car", None) + r = getattr(car, "reading", None) + fresh = getattr(car, "fresh", None) + if r is None or fresh is None or not getattr(r, "available", False): + return None + if not fresh(c.car_now()): + return None + n = getattr(r, "phases_allowed", None) + return n if n in (1, 3) else None + + def _car_manual_why(c, key): """The Why of Manual: what you set, and what the peak limit does about it. - Plan lines: two sentences of at most 12 words.""" + Plan lines: two sentences of at most 12 words. EV-14: in shadow mode it + says what the add-on would set; after a phase change that did not happen + it says what the charger does.""" a = f"{float(c.car_a):.0f}" w = c.car_writer pct = _pct(c.o.get("peak_soc_floor", peakguard.PEAK_OPTION_DEFAULTS[ "peak_soc_floor"])) if c.car_over: + if c.shadow: + t, n = w.would if w.would is not None else (c.car_a, c.car_n) + return _t("car.why.manual_shadow_over", a=f"{float(t):.0f}", + phases=car_phases_word(n)) pg = getattr(c, "peak_guard", None) if not c.car_cover: return _t("car.why.manual_nocover", a=a) @@ -1337,6 +1357,8 @@ def _car_manual_why(c, key): phases=car_phases_word(n)) if not c.auto: return _t("car.why.manual_stopped") + if w.hold: + return _t("car.why.manual_other") if key in ("none", "full"): return _t("car.why.manual_wait", a=a) if w.blocked: @@ -1344,6 +1366,11 @@ def _car_manual_why(c, key): if c.car_cover and peak_engaged(c): giving = max(0.0, float(c.site_batt_w or 0.0)) return _t("car.why.manual_cover", a=a, kw=_kw(giving), pct=pct) + real = _real_phases(c) + if real is not None and real != c.car_n and w.seq is None: + return _t("car.why.manual_phases", a=a, + phases=car_phases_word(c.car_n), + real=car_phases_word(real)) return _t("car.why.manual_set", a=a, phases=car_phases_word(c.car_n)) @@ -1900,7 +1927,8 @@ def _samples() -> list: out += [("plan", _t("car.big." + k, t="09:12")) for k in words["car"]["big"]] out += [("plan", _t("car.why." + k, a="10", brand="Alfen", kw="8.6 kW", - pct="20 %", phases=car_phases_word(3))) + pct="20 %", phases=car_phases_word(3), + real=car_phases_word(1))) for k in words["car"]["why"]] out += [("plan", _t("peak.car", kw="12.1 kW", car="11.0 kW", cov="8.6 kW")), diff --git a/goodwe_controller/app/ui_text/en.json b/goodwe_controller/app/ui_text/en.json index 0cf0be9..ea2a878 100644 --- a/goodwe_controller/app/ui_text/en.json +++ b/goodwe_controller/app/ui_text/en.json @@ -329,6 +329,9 @@ "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.", + "manual_shadow_over": "Shadow mode: the add-on would set {a} A, {phases}. This charge would set the peak.", + "manual_phases": "You set {a} A, {phases}. The charger stays on {real}.", + "manual_other": "Something else set the charger. The add-on leaves it until you change something.", "manual_blocked": "The phases change once per 10 minutes at most. This waits." } }, diff --git a/goodwe_controller/app/ui_text/nl.json b/goodwe_controller/app/ui_text/nl.json index 975e3dd..62c123f 100644 --- a/goodwe_controller/app/ui_text/nl.json +++ b/goodwe_controller/app/ui_text/nl.json @@ -283,6 +283,9 @@ "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.", + "manual_shadow_over": "Schaduwmodus: de add-on zou {a} A instellen, {phases}. Deze lading zou de piek bepalen.", + "manual_phases": "U stelde {a} A in, {phases}. De laadpaal blijft op {real}.", + "manual_other": "Iets anders heeft de laadpaal ingesteld. De add-on laat dit zo tot u iets wijzigt.", "manual_blocked": "De fasen wisselen hooguit eens per 10 minuten. Dit wacht." } }, diff --git a/goodwe_controller/test_ev14.py b/goodwe_controller/test_ev14.py new file mode 100644 index 0000000..56f117f --- /dev/null +++ b/goodwe_controller/test_ev14.py @@ -0,0 +1,826 @@ +"""EV-14: the Car Why says what happens, not only what the user set. +`python3 -B test_ev14.py` + +Display only (homeview._car_manual_why, ui_text en/nl): + E1 shadow mode: no Why says "You set"; with the car over the limit it says + what the add-on WOULD set and that this charge would set the peak. + E2 a phase change that did not happen (read phases differ from the setting): + "The charger stays on {real}", never "keeps it". + E3 the writer holds for another writer: "Something else set the charger". + E4 phases equal or unknown, no hold: exactly as before. + E5 texts in en and nl, same keys, UX-08 limits. +N2 the render writes nothing; N3 it never sends to the charger. +Mutants: see the dev report (M1-M14). +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import copy +import dataclasses +import itertools +import json +import logging +import os +import re +import sys +from datetime import datetime, timezone + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode, chargers as CH, ctl_car, homeview, uitext # noqa: E402 +from app.carmode import PHASE_GAP_S, ManualWriter # noqa: E402 +from app.main import Controller # noqa: E402 +from app import freshness # noqa: E402 +from chargersim import FakeHa, SimCharger # noqa: E402 +from named_absence import nth, present # noqa: E402 + +fails = [] +logging.getLogger("goodwe").setLevel(logging.CRITICAL) + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +def run(coro): + return asyncio.run(coro) + + +# =========================================================================== # +# The texts the test holds the page to, written out (T34: base is byte-equal). +# =========================================================================== # +BASE_EN = { + "manual_set": "You set {a} A, {phases}. The charger keeps it, whatever the peak limit does.", + "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 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.", + "manual_blocked": "The phases change once per 10 minutes at most. This waits.", +} +BASE_NL = { + "manual_set": "U stelde {a} A in, {phases}. De laadpaal houdt dit aan, wat de piekgrens ook doet.", + "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 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.", + "manual_blocked": "De fasen wisselen hooguit eens per 10 minuten. Dit wacht.", +} +NEW_KEYS = ("manual_shadow_over", "manual_phases", "manual_other") +LANGS = ("en", "nl") +YOU = {"en": "You set", "nl": "U stelde"} +KEEPS = {"en": "The charger keeps it,", "nl": "De laadpaal houdt dit aan"} +WOULD = {"en": "would set", "nl": "zou"} +PEAK = {"en": "would set the peak", "nl": "zou de piek bepalen"} +STAYS = {"en": "stays on", "nl": "blijft op"} +OTHER = {"en": "Something else set the charger.", "nl": "Iets anders heeft de laadpaal ingesteld."} + + +def jwords(lang): + return uitext.words(lang)["home_words"]["car"]["why"] + + +def tx(lang, key, **kw): + """Render a car.why text the way the page does (a missing key is a text + of its own, so a check on it is a FAIL, not a crash).""" + homeview._LANG[0] = uitext.lang_of(lang) + try: + return homeview._t("car.why." + key, **kw) + except Exception as e: # noqa: BLE001 + return f"" + finally: + homeview._LANG[0] = "en" + + +def pw(n): + homeview._LANG[0] = "en" + return homeview.car_phases_word(n) + + +def pw_l(lang, n): + homeview._LANG[0] = uitext.lang_of(lang) + try: + return homeview.car_phases_word(n) + finally: + homeview._LANG[0] = "en" + + +# =========================================================================== # +# A stub site for the unit rows: what _car_manual_why reads, nothing else. +# =========================================================================== # +@dataclasses.dataclass +class G: + floor_limited: bool = True + soc: object = 19.0 + saturated: bool = False + floor_w: float = 300.0 + able_w: object = None + ceiling_w: float = 4500.0 + engaged: bool = True + blind: object = None + wanted_w: float = 300.0 + within_aim: bool = False + + +class Car: + def __init__(self, reading, fresh, last_good=None): + self.reading, self._fresh, self.last_good = reading, fresh, last_good + + def fresh(self, _now): + return self._fresh + + def status(self, *_a): + return "charging" + + +class U(ctl_car.CarMixin): + """The attributes `_car_manual_why` and `_car_why_tick` read.""" + + def __init__(self, **kw): + self.o = {"ev_batt_cover": kw.get("cover", True)} + self._now = 0.0 + self.w = 11000.0 + self.site_batt_w, self.site_rating_w = 8100.0, 9600.0 + self.shadow = kw.get("shadow", False) + self.auto = kw.get("auto", True) + self.peak_guard = kw.get("pg", G( + floor_limited=kw.get("floor", True), + floor_w=300.0 if kw.get("eng") else 0.0)) + self.state = "charging" + self.car_init({}, type("St", (), {"data": {}, "set": lambda s, k, v: 0})()) + self.car_a = kw.get("a", 10.0) + self.car_n = kw.get("n", 3) + self.car_over = kw.get("over", False) + wr = self.car_writer + wr.hold = wr.other = kw.get("hold", False) + wr.blocked = kw.get("blocked", False) + wr.seq = kw.get("seq", None) + wr.would = kw.get("would", None) + wr.phases_gave_up = kw.get("gave_up", False) + if "car" in kw: + self.car = kw["car"] + else: + real = kw.get("real", None) + rd = CH.ChargerReading(available=True, state="C", power_w=2300.0, + setpoint_a=10.0, allowed_a=10.0, + phases_allowed=real) + self.car = Car(rd, kw.get("fresh", True)) + + def car_now(self): + return self._now + + +def snap(c): + """Everything N2 says a render must not move.""" + keep = {k: v for k, v in vars(c).items() + if k.startswith(("car_", "_car")) and k != "car"} + car = getattr(c, "car", None) + return repr((vars(c.car_writer), vars(car) if hasattr(car, "__dict__") + else None, keep, c.shadow, c.auto)) + + +N2_BAD = [] +EXC = [] + + +def why(c, lang="en", key="charging"): + """The Why text; an exception becomes a text; N2 is checked on every call.""" + before = snap(c) + homeview._LANG[0] = uitext.lang_of(lang) + try: + out = homeview._car_manual_why(c, key) + except Exception as e: # noqa: BLE001 + EXC.append(repr(e)) + out = f"" + finally: + homeview._LANG[0] = "en" + if snap(c) != before: + N2_BAD.append(out) + return out + + +def exp(lang, key, **kw): + return tx(lang, key, **kw) + + +def a_(c): + return f"{float(c.car_a):.0f}" + + +# --------------------------------------------------------------------------- # +print("1. E1: shadow mode says what the add-on WOULD set") +# --------------------------------------------------------------------------- # +SHADOW_BAD_CASES = { + "T1 floor": dict(floor=True, cover=True), + "T2 full": dict(floor=False, cover=True), + "T3 cover off": dict(floor=True, cover=False), +} +for label, kw in SHADOW_BAD_CASES.items(): + for lang in LANGS: + c = U(shadow=True, over=True, a=16.0, n=3, would=(10.0, 3), **kw) + t = why(c, lang) + check(f"{label} ({lang}): would set 10 A and would set the peak; no " + f"'You set', no 16 A: {t!r}", + present(t) and WOULD[lang] in t and "10 A" in t + and PEAK[lang] in t and YOU[lang] not in t and "16 A" not in t) + check(f"{label} ({lang}): exactly the shadow-over text", + t == exp(lang, "manual_shadow_over", a="10", + phases=pw_l(lang, 3))) + +for lang in LANGS: + c = U(shadow=True, over=True, a=12.0, n=3, would=None) + t = why(c, lang) + check(f"T4 ({lang}): writer not stepped: falls back to (car_a, car_n), " + f"12 A, 3 phases, no 'You set': {t!r}", + t == exp(lang, "manual_shadow_over", a="12", phases=pw_l(lang, 3)) + and YOU[lang] not in t) + c = U(shadow=True, over=False, a=16.0, n=3, would=(10.0, 3)) + check(f"T5 ({lang}): shadow, not over: exactly today's manual_would", + why(c, lang) == BASE_EN["manual_would"].format( + a="10", phases="3 phases") if lang == "en" else + why(c, lang) == BASE_NL["manual_would"].format( + a="10", phases="3 fasen")) + +# T6/T7: the EV-16 episode, 5 s cycles, floor flipping every 10 s. +STEP = 5.0 + + +def tick(c, g, t, shadow=None): + c._now = t + c.peak_guard = g + if shadow is not None: + c.shadow = shadow + c._car_why_tick(g, t) + + +def episode(c, secs, flip=10.0, shadow_off_at=None): + out, t = [], 0.0 + while t < secs: + g = G(floor_limited=(int(t // flip) % 2 == 0)) + off = shadow_off_at is not None and t >= shadow_off_at + tick(c, g, t, shadow=False if off else None) + out.append((t, why(c))) + t += STEP + return out + + +c = U(shadow=True, over=True, a=16.0, would=(10.0, 3)) +ep = episode(c, 180.0) +texts = {t for _, t in ep} +check(f"T6: shadow over, floor flips for 180 s: one constant text, 0 changes " + f"({len(ep)} cycles)", len(ep) == 36 and len(texts) == 1 + and all(PEAK["en"] in t for t in texts)) +c = U(shadow=True, over=True, a=16.0, would=(10.0, 3)) +ep = episode(c, 180.0, flip=1000.0, shadow_off_at=90.0) +first = [t for tt, t in ep if tt < 90.0] +later = [t for tt, t in ep if tt >= 90.0] +check("T7: shadow switched off mid-episode with the floor held: the shadow " + "text, then exactly today's manual_over (EV-16 hold)", + len(first) == 18 and len(later) == 18 and len(set(first)) == 1 + and PEAK["en"] in nth(first) + and set(later) == {BASE_EN["manual_over"].format(a="16", pct=homeview._pct( + c.o.get("peak_soc_floor", 20)))}) + +# --------------------------------------------------------------------------- # +print("\n2. E2 / E3: units") +# --------------------------------------------------------------------------- # +for lang in LANGS: + c = U(real=1, n=3, a=10.0) + t = why(c, lang) + check(f"T9 ({lang}): 3 set, charger on 1: 'stays on 1 phase', not 'keeps " + f"it': {t!r}", + t == exp(lang, "manual_phases", a="10", phases=pw_l(lang, 3), + real=pw_l(lang, 1)) + and STAYS[lang] in t and KEEPS[lang] not in t + and pw_l(lang, 1) in t) + c = U(real=3, n=1, a=10.0) + t = why(c, lang) + check(f"T10 ({lang}): 1 set, charger on 3: 'stays on 3 phases': {t!r}", + t == exp(lang, "manual_phases", a="10", phases=pw_l(lang, 1), + real=pw_l(lang, 3)) and pw_l(lang, 3) in t.split(". ")[-1] + and KEEPS[lang] not in t) +check("T9: the words are the brief's (EN and NL)", + why(U(real=1, n=3)) == "You set 10 A, 3 phases. The charger stays on 1 phase." + and why(U(real=1, n=3), "nl") == + "U stelde 10 A in, 3 fasen. De laadpaal blijft op 1 fase.") + + +def sett(lang, c): + return exp(lang, "manual_set", a=a_(c), phases=pw_l(lang, c.car_n)) + + +for lang in LANGS: + c = U(real=1, n=3, auto=False) + check(f"T13a ({lang}): phases differ, control stopped: manual_stopped", + why(c, lang) == exp(lang, "manual_stopped")) + c = U(real=1, n=3, shadow=True, would=(10.0, 3)) + check(f"T13b ({lang}): phases differ, shadow: manual_would", + why(c, lang) == exp(lang, "manual_would", a="10", + phases=pw_l(lang, 3))) + for stage in ("zero", "settle"): + c = U(real=1, n=3, seq={"stage": stage}) + check(f"T14 ({lang}): phases differ, sequence at {stage}: manual_set", + why(c, lang) == sett(lang, c)) + c = U(real=1, n=3, blocked=True) + check(f"T15 ({lang}): phases differ, blocked: manual_blocked", + why(c, lang) == exp(lang, "manual_blocked")) + for key in ("none", "full"): + c = U(real=1, n=3) + check(f"T16 ({lang}): phases differ, key {key}: manual_wait", + why(c, lang, key) == exp(lang, "manual_wait", a="10")) + c = U(real=1, n=3, eng=True) + giving = max(0.0, float(c.site_batt_w)) + homeview._LANG[0] = uitext.lang_of(lang) + kw_ = homeview._kw(giving) + pct_ = homeview._pct(20) + homeview._LANG[0] = "en" + check(f"T17 ({lang}): phases differ, cover engaged, not over: manual_cover", + why(c, lang) == exp(lang, "manual_cover", a="10", kw=kw_, pct=pct_)) + for label, kw in (("floor", dict(floor=True)), ("full", dict(floor=False)), + ("nocover", dict(cover=False))): + c = U(real=1, n=3, over=True, **kw) + want = ("manual_nocover" if label == "nocover" else + "manual_over" if label == "floor" else "manual_full") + check(f"T18 ({lang}): phases differ, car over ({label}): {want}", + why(c, lang) == exp(lang, want, a="10", pct=pct_)) + +# T19/T20 are in the World section. T21-T26: the hold, units. +for lang in LANGS: + c = U(hold=True, real=1, n=3) + t = why(c, lang) + check(f"T21 ({lang}): hold, phases differ, not given up: the hold text " + f"{t!r}", t == exp(lang, "manual_other") and OTHER[lang] in t + and STAYS[lang] not in t and YOU[lang] not in t) + for key in ("none", "full"): + c = U(hold=True, real=3, n=3) + check(f"T22 ({lang}): hold, key {key}: the hold text, not 'set when a " + f"car is connected'", + why(c, lang, key) == exp(lang, "manual_other")) + c = U(hold=True, blocked=True, real=3, n=3) + check(f"T23a ({lang}): hold with a stale blocked: the hold text", + why(c, lang) == exp(lang, "manual_other")) + c = U(hold=True, real=3, n=3, eng=True) + check(f"T23b ({lang}): hold with the cover engaged: the hold text", + why(c, lang) == exp(lang, "manual_other")) + for label, kw in (("floor", dict(floor=True)), ("full", dict(floor=False)), + ("nocover", dict(cover=False))): + c = U(hold=True, over=True, real=3, n=3, **kw) + want = ("manual_nocover" if label == "nocover" else + "manual_over" if label == "floor" else "manual_full") + check(f"T24 ({lang}): hold and car over ({label}): {want}, no hold " + f"text", why(c, lang) == exp(lang, want, a="10", pct=pct_) + and OTHER[lang] not in why(c, lang)) + for key in ("charging", "none"): + c = U(hold=True, auto=False, real=3, n=3) + check(f"T25 ({lang}): hold, control stopped, key {key}: manual_stopped", + why(c, lang, key) == exp(lang, "manual_stopped")) + c = U(hold=True, shadow=True, over=False, would=(10.0, 3)) + check(f"T26a ({lang}): hold, shadow, not over: manual_would", + why(c, lang) == exp(lang, "manual_would", a="10", + phases=pw_l(lang, 3))) + c = U(hold=True, shadow=True, over=True, would=(10.0, 3)) + check(f"T26b ({lang}): hold, shadow, over: the shadow-over text", + why(c, lang) == exp(lang, "manual_shadow_over", a="10", + phases=pw_l(lang, 3))) + +# T29-T32: E4. +for lang in LANGS: + for n in (1, 3): + c = U(real=n, n=n) + want = (BASE_EN if lang == "en" else BASE_NL)["manual_set"].format( + a="10", phases=pw_l(lang, n)) + check(f"T29 ({lang}): {n}/{n} phases: byte-identical manual_set", + why(c, lang) == want) + c = U(real=None, n=3) + check(f"T30 ({lang}): phases_allowed None: manual_set, no exception", + why(c, lang) == sett(lang, c)) + c = U(real=3, n=1, fresh=False) + check(f"T32 ({lang}): reading not fresh: manual_set (stale is unknown)", + why(c, lang) == sett(lang, c)) +c = U(car=Car(None, True)) +check("T31a: reading None: today's text, no exception", + why(c) == sett("en", c)) +rd = CH.ChargerReading(available=False, phases_allowed=1) +c = U(car=Car(rd, True, last_good=None), n=3) +check("T31b: reading unavailable (phases 1 vs 3): today's text", + why(c) == sett("en", c)) +c = U(real=1, n=3, pg=None) +check("T31c: peak_guard None: no exception, the E2 text", + why(c) == exp("en", "manual_phases", a="10", phases="3 phases", + real="1 phase")) +c = U(real=1, n=3) +del c.car +check("T31d: no car object at all: no exception, today's text", + why(c) == sett("en", c)) +check("T31: no exception from any of the above", not EXC) + +# --------------------------------------------------------------------------- # +print("\n3. E5: the texts") +# --------------------------------------------------------------------------- # +PH = re.compile(r"\{(\w+)\}") +JARGON = { + "en": r"controllers?|control loop|setpoints?|SoC|state of charge|BMS|PV|" + r"failsafe|trip(?:ped)?|parked|discharg\w*|P1 feed|quarter-hour|" + r"payload|endpoint|JSON|API|timeout|boolean|config|commands?|" + r"charge level|ceiling|billed quarter|quarters?|banked|soft limit|" + r"open block|actuator|ESP32|master|meter source|circulating|" + r"sign disagreement|rail", + "nl": r"setpoints?|setpunt\w*|SoC|laadtoestand|BMS|PV|failsafe|regelaar|" + r"regellus|controller|latch|ontlad\w*|payload|endpoint|JSON|API|" + r"time-?out|boolean|config|kwartuur\w*|commando\w*|geparkeerd|" + r"ESP32|master", +} +JARGON = {k: re.compile(r"\b(?:" + v + r")\b", re.I) for k, v in JARGON.items()} +samples = {lang: [t for k, t in homeview.text_samples(lang) if k == "plan"] + for lang in LANGS} +for key in NEW_KEYS: + en_t, nl_t = jwords("en").get(key), jwords("nl").get(key) + check(f"T33 {key}: in en.json and nl.json with the same placeholders", + isinstance(en_t, str) and isinstance(nl_t, str) + and set(PH.findall(en_t)) == set(PH.findall(nl_t))) + for lang in LANGS: + raw = jwords(lang).get(key, "") + vals = {k: "10" for k in PH.findall(raw)} + vals.update(phases=pw_l(lang, 3), real=pw_l(lang, 1)) + shown = tx(lang, key, **vals) + sents = re.split(r"(?<=[.!?])\s+", shown) + nwords = [len(s.split()) for s in sents] + check(f"T33 {key} ({lang}): in text_samples as a plan line, no '{{', " + f"<=2 sentences of <=12 words ({nwords}), no jargon: {shown!r}", + shown in samples[lang] and "{" not in shown + and len(sents) <= 2 and max(nwords) <= 12 + and not JARGON[lang].search(PH.sub("X", shown))) +for lang in LANGS: + base = BASE_EN if lang == "en" else BASE_NL + words = jwords(lang) + check(f"T34 ({lang}): the 9 existing manual_* texts are byte-identical", + all(words.get(k) == v for k, v in base.items()) and len(base) == 9) + +# --------------------------------------------------------------------------- # +print("\n4. T35: the property sweep (both languages)") +# --------------------------------------------------------------------------- # +n_calls = 0 +viol = {"i": [], "ii": [], "iii": [], "iv": []} +for (sh, ov, cv, fl, hd, au, bl, eg, sq, key, pa, cn, fr) in itertools.product( + (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), + (None, {"stage": "zero"}), ("charging", "waiting", "none", "full"), + (None, 1, 3), (1, 3), (0, 1)): + for lang in LANGS: + c = U(shadow=bool(sh), over=bool(ov), cover=bool(cv), floor=bool(fl), + hold=bool(hd), auto=bool(au), blocked=bool(bl), eng=bool(eg), + seq=sq, real=pa, + n=cn, fresh=bool(fr), would=(10.0, 3)) + t = why(c, lang, key) + n_calls += 1 + if sh and YOU[lang] in t: + viol["i"].append((lang, t)) + known = pa is not None and fr + if (not sh and au and not ov + and (hd or (known and pa != cn and sq is None)) + and KEEPS[lang] in t): + viol["ii"].append((lang, t)) + if "{" in t or " 2 or max(len(s.split()) for s in sents) > 12: + viol["iv"].append((lang, t)) +check(f"T35 (i): shadow mode, no 'You set' anywhere ({n_calls} calls)", + n_calls == 2 * 24576 and not viol["i"]) +check("T35 (ii): no 'keeps it' under hold or a known, fresh phase difference", + not viol["ii"]) +check("T35 (iii): no '{' left, no exception", not viol["iii"] and not EXC) +check("T35 (iv): at most 2 sentences of 12 words (the new texts' share)", + not [v for v in viol["iv"] + if any(k in v[1] for k in ("stays on", "blijft op", "Something else", + "Iets anders", "would set the peak", + "zou de piek"))]) +check("T35 (vi)/N2: no render changed the writer, the car or the controller " + f"({len(N2_BAD)} did)", not N2_BAD) + +# =========================================================================== # +print("\n5. Integration: a real Controller on the charger model") +# =========================================================================== # +SET = "number.wallbox_power_connector_max_current_socket_1" +BASE = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid", + "soc_entity": "sensor.soc", "batt_entity": "sensor.batt", + "meter_source": "off", "max_w": 5000, "gain": 0.6, "slew_w": 500, + "deadband_w": 15, "target_grid_w": 0, "step_w": 10, "heartbeat_s": 10, + "stale_input_s": 15, "shadow_mode": "off", "peak_cap_w": 3500, + "pv_entities": ["sensor.pv"]} +CAR = dict(BASE, ev_charger="alfen_ha", ev_max_a=16, ev_phases="auto", + ev_current_entity=SET) +CLOCK = [1000.0] +freshness.monotonic = lambda: CLOCK[0] + + +class _Store: + def __init__(self): + self.data = {} + + def set(self, k, v): + self.data[k] = v + + def get(self, k, d=None): + return self.data.get(k, d) + + def set_time(self, k, v): + self.data[k] = v.isoformat() + + def get_time(self, k): + v = self.data.get(k) + return None if v is None else datetime.fromisoformat(v) + + +class _Pub: + enabled = False + + def publish(self, v): + pass + + def close(self): + pass + + +class Site(FakeHa): + def __init__(self, charger, grid=500.0, batt=0.0, pv=2000.0): + super().__init__(charger, None) + self.grid, self.batt, self.pv = grid, batt, pv + + async def limits(self, _e): + return (-5000.0, 5000.0, 1.0) + + def _all(self): + out = super()._all() + for eid, val, unit_ in (("sensor.grid", self.grid, "W"), + ("sensor.soc", 50.0, "%"), + ("sensor.batt", self.batt, "W"), + ("sensor.pv", self.pv, "W")): + out[eid] = {"entity_id": eid, "state": str(val), + "attributes": {"unit_of_measurement": unit_}} + return out + + async def number(self, entity_id, invert=False): + s = self._all().get(entity_id) + try: + v = float(s["state"]) + except (TypeError, ValueError, KeyError): + return None + return -v if invert else v + + async def set_number(self, entity_id, value): + if entity_id == "number.sp": + self.sets.append((entity_id, float(value))) + self.batt = float(value) + return True + return await super().set_number(entity_id, float(value)) + + +class World: + def __init__(self, opts=CAR, setpoint=10, grid=800.0, phases=1): + self.sim = SimCharger(setpoint_a=setpoint) + self.sim.plug_in() + self.sim.phases_allowed = phases + self.site = Site(self.sim, grid=grid) + self.t = 1000.0 + CLOCK[0] = self.t + self.c = Controller(dict(opts), self.site, _Store(), _Pub(), + stop=asyncio.Event()) + self.c.auto = True + self.c.dev_min, self.c.dev_max = -5000.0, 5000.0 + self.drv = self.c.charger + if hasattr(self.drv, "_sleep"): + self.drv._sleep = self.sleep + self.drv._clock = lambda: CLOCK[0] + + async def sleep(self, s): + self.sim.tick(s) + self.t += s + CLOCK[0] = self.t + + async def step(self, n=1, dt=1.0): + 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.cycle() + await self.c.car_settle() + + async def act(self, what, value): + return await self.c.handle_action(what, value=value) + + def writes(self, what=None): + return self.sim.writes(what) + + @property + def wr(self): + return self.c.car_writer + + +W_BAD = [] + + +def block_why(w, lang="en"): + """car_block's Why, with N2 and N3 held across the call.""" + c = w.c + before = (snap(c), len(w.sim.log), list(w.drv.sent), + len(w.site.charger_writes())) + homeview._LANG[0] = uitext.lang_of(lang) + try: + out = homeview.car_block(c, datetime.now(timezone.utc)) + t = out["why"] if out else "" + except Exception as e: # noqa: BLE001 + t = f"" + finally: + homeview._LANG[0] = "en" + after = (snap(c), len(w.sim.log), list(w.drv.sent), + len(w.site.charger_writes())) + if before != after: + W_BAD.append(t) + return t + + +def set_text(w, lang="en"): + return exp(lang, "manual_set", a=f"{float(w.c.car_a):.0f}", + phases=pw_l(lang, w.c.car_n)) + + +async def ready(phases, a, to, ramp=200.0, delay=1.0, shadow="off"): + w = World(dict(CAR, shadow_mode=shadow), setpoint=a, phases=phases) + await w.step(8) + await w.act("car_phases", phases) + await w.act("car_mode", "manual") + await w.act("car_current", a) + await w.step(8) + w.sim.ramp_w_s, w.sim.stop_delay_s = ramp, delay + await w.act("car_phases", to) + return w + + +async def t8(): + w = World(dict(CAR, shadow_mode="on"), setpoint=10, phases=3) + await w.step(8) + await w.act("car_phases", 3) + await w.act("car_mode", "manual") + await w.act("car_current", 16) + await w.step(80) + w.c.car_over = True + w.c.peak_guard = G(floor_limited=True) + return w, {lg: block_why(w, lg) for lg in LANGS} + + +w8, t8w = run(t8()) +would_a = nth(w8.wr.would) if w8.wr.would else None +check("T8: shadow world, Manual 16 A, car over: shadow-over text in en and " + f"nl, no 'You set': {t8w}", + w8.c.shadow and present(would_a) and w8.wr.would is not None + and all(PEAK[lg] in t8w[lg] and YOU[lg] not in t8w[lg] for lg in LANGS) + and t8w["en"] == exp("en", "manual_shadow_over", + a=f"{float(w8.wr.would[0]):.0f}", + phases=pw(w8.wr.would[1]))) +check("T8/N3: shadow world: no simulator log, no driver send, no charger " + "write", w8.sim.log == [] and w8.drv.sent == [] + and w8.site.charger_writes() == []) + + +async def gave_up(refuse_select): + # 3 phases wanted -> the sim is on 1; or the other way, as EV-28's T11. + w = await ready(3, 16, 1, ramp=(3000.0 if refuse_select else 200.0)) + if refuse_select: + w.sim.request_phases = lambda n: False + texts = {} + await w.step(40) + texts["try1"] = (w.wr.phases_gave_up, w.wr.phase_fails, block_why(w)) + await w.step(int(PHASE_GAP_S) + 60) + await w.step(int(PHASE_GAP_S) + 60) + texts["end"] = (w.wr.phases_gave_up, w.wr.phase_fails, block_why(w), + block_why(w, "nl")) + return w, texts + + +for label, refuse in (("T11 the car keeps drawing", False), + ("T12 the select is refused", True)): + w_, tt = run(gave_up(refuse)) + g1, f1, why1 = tt["try1"] + ge, fe, whye, whyn = tt["end"] + want = exp("en", "manual_phases", a="16", phases="1 phase", + real="3 phases") + check(f"{label}: after the 3rd failed try the Why is the E2 text " + f"{whye!r}", ge and fe == 3 and whye == want + and whyn == exp("nl", "manual_phases", a="16", + phases=pw_l("nl", 1), real=pw_l("nl", 3)) + and w_.sim.phases_allowed == 3 and KEEPS["en"] not in whye) + check(f"{label}: before the give-up (gap wait) it is manual_blocked " + f"{why1!r}", not g1 and f1 >= 1 + and why1 == exp("en", "manual_blocked")) + +# T19: another writer raises the current during a phase change. + + +async def other_in_seq(): + w = World(CAR, setpoint=10, phases=1) + w.sim.ramp_w_s, w.sim.stop_delay_s = 50.0, 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) + mid = (w.wr.seq is not None, block_why(w)) + w.sim.set_current(9) + got = None + for _ in range(60): + await w.step(1) + if w.wr.other: + got = (block_why(w), block_why(w, "nl")) + break + return w, mid, got + + +w19, mid19, got19 = run(other_in_seq()) +check("T19: during the sequence the Why is today's manual_set " + f"{mid19[1]!r}", mid19[0] and mid19[1] == set_text(w19)) +check("T19: the first car_block after w.other turns True is the hold text " + f"(en and nl): {got19!r}", + got19 is not None and got19[0] == exp("en", "manual_other") + and got19[1] == exp("nl", "manual_other") + and YOU["en"] not in got19[0] and KEEPS["en"] not in got19[0] + and STAYS["en"] not in got19[0]) + + +async def t27(): + w, _m, _g = await other_in_seq() + await w.act("car_current", 12) + await w.step(5) + return w, block_why(w) + + +w27, why27 = run(t27()) +okset = {set_text(w27), exp("en", "manual_blocked"), + exp("en", "manual_phases", a="12", phases="3 phases", + real="1 phase")} +check(f"T27: the user changes the current: the hold is lifted and the hold " + f"text is gone ({why27!r})", not w27.wr.hold + and why27 != exp("en", "manual_other") and why27 in okset) + +# T20 / T28: the other writer on equal phases. + + +async def other_equal(): + w = World(CAR, setpoint=10, phases=1) + await w.step(8) + await w.act("car_phases", 1) + await w.act("car_mode", "manual") + await w.act("car_current", 10) + await w.step(10) + pre = block_why(w) + t0 = w.t + w.sim.set_current(8) + before, first, secs = [], None, None + for _ in range(60): + await w.step(1) + if w.wr.other: + first, secs = block_why(w), w.t - t0 + break + before.append(block_why(w)) + held_for = None + w.sim.set_current(10) + after = [] + for _ in range(40): + await w.step(1) + after.append((w.wr.hold, block_why(w))) + if not w.wr.hold: + break + return w, pre, before, first, secs, after + + +w20, pre20, before20, first20, secs20, after20 = run(other_equal()) +check("T20: before the hold the Why is today's manual_set, every step " + f"({len(before20)} steps)", pre20 == set_text(w20) and before20 + and all(t == set_text(w20) for t in before20)) +check(f"T20: the hold text from the first call after w.other turns True, " + f"{secs20} s after the write (<= WRITER_S + 5 = 35)", + first20 == exp("en", "manual_other") and secs20 is not None + and secs20 <= carmode.WRITER_S + 5.0) +check("T28: the other writer puts the current back: the hold clears and the " + "Why is manual_set in the same step", + len(after20) >= 1 and not after20[-1][0] + and after20[-1][1] == set_text(w20) and len(after20) <= 5) + +# N2/N3 over every World call above. +check(f"N2/N3: every car_block call in the World rows changed nothing and " + f"sent nothing ({len(W_BAD)} did)", not W_BAD) + +print() +if fails: + print(f"{len(fails)} FAILED") + sys.exit(1) +print("all ok") -- 2.54.0 From b66ce68d4dd61645962a582016139ab440fff9d0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 13:50:40 +0100 Subject: [PATCH 27/55] EV-14: T33 reads the raw nl words; T29 carries a would --- goodwe_controller/test_ev14.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/goodwe_controller/test_ev14.py b/goodwe_controller/test_ev14.py index 56f117f..fac3a39 100644 --- a/goodwe_controller/test_ev14.py +++ b/goodwe_controller/test_ev14.py @@ -394,7 +394,7 @@ for lang in LANGS: # T29-T32: E4. for lang in LANGS: for n in (1, 3): - c = U(real=n, n=n) + c = U(real=n, n=n, would=(10.0, 3)) want = (BASE_EN if lang == "en" else BASE_NL)["manual_set"].format( a="10", phases=pw_l(lang, n)) check(f"T29 ({lang}): {n}/{n} phases: byte-identical manual_set", @@ -442,7 +442,8 @@ JARGON = {k: re.compile(r"\b(?:" + v + r")\b", re.I) for k, v in JARGON.items()} samples = {lang: [t for k, t in homeview.text_samples(lang) if k == "plan"] for lang in LANGS} for key in NEW_KEYS: - en_t, nl_t = jwords("en").get(key), jwords("nl").get(key) + en_t = uitext.raw("en")["home_words"]["car"]["why"].get(key) + nl_t = uitext.raw("nl")["home_words"]["car"]["why"].get(key) check(f"T33 {key}: in en.json and nl.json with the same placeholders", isinstance(en_t, str) and isinstance(nl_t, str) and set(PH.findall(en_t)) == set(PH.findall(nl_t))) -- 2.54.0 From 9987a324245256e291d7d8adeea55ddc6fef7c78 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 15:25:32 +0100 Subject: [PATCH 28/55] EV-14 review: T1 phases check (shadow-over phases come from would) Kills the surviving mutant 'shadow-over phases from car_n'. Co-Authored-By: Claude --- goodwe_controller/test_ev14.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/goodwe_controller/test_ev14.py b/goodwe_controller/test_ev14.py index fac3a39..5cace2b 100644 --- a/goodwe_controller/test_ev14.py +++ b/goodwe_controller/test_ev14.py @@ -242,6 +242,11 @@ for lang in LANGS: f"12 A, 3 phases, no 'You set': {t!r}", t == exp(lang, "manual_shadow_over", a="12", phases=pw_l(lang, 3)) and YOU[lang] not in t) + # Review: the phases word is the writer's `would`, as manual_would's. + c = U(shadow=True, over=True, a=16.0, n=1, would=(10.0, 3)) + check(f"T1 phases ({lang}): the phases come from would, not car_n", + why(c, lang) == exp(lang, "manual_shadow_over", a="10", + phases=pw_l(lang, 3))) c = U(shadow=True, over=False, a=16.0, n=3, would=(10.0, 3)) check(f"T5 ({lang}): shadow, not over: exactly today's manual_would", why(c, lang) == BASE_EN["manual_would"].format( -- 2.54.0 From 226e5a1e8bf3556ebb7ec9ba8a25ccce65b702a9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 20:31:26 +0100 Subject: [PATCH 29/55] EV-20: Car Solar mode, spare sun to the car (charging only) Solar as a second writer next to Manual (carmode.SolarPlan, SolarWriter on ManualWriter's one write site, safe phase sequence and other-writer watch): signed spare, Batteries first on the batteries' ratings, the margin, whole amps rounded down, the 30 s / 1 A rule, start and pause dwells, auto phases, a one-phase car. Every way out ends at 0 A, retried by EV-04's rule; at shutdown before the inverters, three tries inside 15 s (D3); start-up and a returning charger or HA write 0 A first (D2); never over another writer's hold. The peak guard treats a Solar car as a Manual car (D1 wording). Solar kWh sensor and card line; select.goodwe_car_sun_first; ev_margin_w, ev_start_min, ev_pause_min with config, validator, translations, DOCS, DECISIONS and CHANGELOG. Checks: test_ev20.py, test_ev20_exits.py, test_ev20_writers.py, test_ev20_guard.py, test_ev20_long.py, test_ev20_long_car.py, test_ev20_fuzz.py (harness tools/ev20_sun.py, ev20_kit.py, ev20_day.py); test_ev03/test_ev04 no longer use Solar as the refused example. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .gitea/ci/run-tests.sh | 4 +- goodwe_controller/CHANGELOG.md | 1 + .../DECISIONS/EV-20-solar-mode.md | 90 +++ goodwe_controller/DOCS.md | 83 ++- goodwe_controller/app/carmode.py | 699 ++++++++++++++++- goodwe_controller/app/chargers.py | 31 +- goodwe_controller/app/ctl_car.py | 325 +++++++- goodwe_controller/app/ctl_cycle.py | 9 +- goodwe_controller/app/ctl_status.py | 24 +- goodwe_controller/app/homeview.py | 75 +- goodwe_controller/app/main.py | 11 +- goodwe_controller/app/messages.py | 61 ++ goodwe_controller/app/mqtt.py | 30 +- goodwe_controller/app/static/app.js | 12 +- goodwe_controller/app/static/index.html | 5 + goodwe_controller/app/ui_text/en.json | 24 +- goodwe_controller/app/ui_text/nl.json | 24 +- goodwe_controller/app/uilayout.py | 3 + goodwe_controller/app/validate.py | 13 + goodwe_controller/app/web.py | 2 +- goodwe_controller/config.yaml | 18 +- goodwe_controller/test_ev03.py | 12 +- goodwe_controller/test_ev04.py | 48 +- goodwe_controller/test_ev20.py | 701 ++++++++++++++++++ goodwe_controller/test_ev20_exits.py | 579 +++++++++++++++ goodwe_controller/test_ev20_fuzz.py | 312 ++++++++ goodwe_controller/test_ev20_guard.py | 477 ++++++++++++ goodwe_controller/test_ev20_long.py | 52 ++ goodwe_controller/test_ev20_long_car.py | 52 ++ goodwe_controller/test_ev20_writers.py | 227 ++++++ goodwe_controller/tools/ev20_day.py | 180 +++++ goodwe_controller/tools/ev20_kit.py | 251 +++++++ goodwe_controller/tools/ev20_sun.py | 313 ++++++++ goodwe_controller/translations/en.yaml | 11 +- goodwe_controller/translations/nl.yaml | 11 +- 35 files changed, 4647 insertions(+), 123 deletions(-) create mode 100644 goodwe_controller/DECISIONS/EV-20-solar-mode.md create mode 100644 goodwe_controller/test_ev20.py create mode 100644 goodwe_controller/test_ev20_exits.py create mode 100644 goodwe_controller/test_ev20_fuzz.py create mode 100644 goodwe_controller/test_ev20_guard.py create mode 100644 goodwe_controller/test_ev20_long.py create mode 100644 goodwe_controller/test_ev20_long_car.py create mode 100644 goodwe_controller/test_ev20_writers.py create mode 100644 goodwe_controller/tools/ev20_day.py create mode 100644 goodwe_controller/tools/ev20_kit.py create mode 100644 goodwe_controller/tools/ev20_sun.py diff --git a/.gitea/ci/run-tests.sh b/.gitea/ci/run-tests.sh index 82ba2ef..48fac70 100755 --- a/.gitea/ci/run-tests.sh +++ b/.gitea/ci/run-tests.sh @@ -49,10 +49,12 @@ SERIAL="test_loop.py test_freeze.py test_safety87.py" # safety119 704, opt34 515, safety126 402, safety125 388, safety126b 364, # modes_p3 377, safety94 360, modes_p4c 291, modes_p4b 238, tariff24_weather 235, # modes_p4d 196, price_run_fixes 197, safety103 189, safety90 185, safety97 163. +# EV-20 (Solar), local runs at 8 workers: ev20_exits ~460, ev20_guard ~450, +# ev20 ~350, ev20_fuzz ~300, ev20_long_car ~280, ev20_long ~240, ev20_writers ~230. # CI-18 split test_modes_p4, test_safety126 and test_safety125 so no one file # is much over 400 s; test_opt34 and test_opt36 already fan out inside, and # test_safety119 part 4 is one coupled block, so those three stay whole. -HEAVY="test_opt36.py test_safety119.py test_opt34.py test_safety126.py test_safety125.py test_safety126b.py test_modes_p3.py test_safety94.py test_modes_p4c.py test_modes_p4b.py test_tariff24_weather.py test_modes_p4d.py test_safety125b.py test_price_run_fixes.py test_safety103.py test_safety90.py test_safety97.py test_peakguard.py test_opt20.py test_safety81.py" +HEAVY="test_opt36.py test_safety119.py test_opt34.py test_ev20_exits.py test_ev20_guard.py test_safety126.py test_safety125.py test_safety126b.py test_modes_p3.py test_safety94.py test_ev20.py test_ev20_fuzz.py test_modes_p4c.py test_ev20_long_car.py test_ev20_long.py test_modes_p4b.py test_ev20_writers.py test_tariff24_weather.py test_modes_p4d.py test_safety125b.py test_price_run_fixes.py test_safety103.py test_safety90.py test_safety97.py test_peakguard.py test_opt20.py test_safety81.py" # JOBS=${CI_JOBS:-10} cd "${TESTS_DIR:-/w/goodwe-addon/goodwe_controller}" diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index 535e9fe..9e39984 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -2,6 +2,7 @@ ### Not in a release yet +- **The car can now charge from spare sun (Solar mode).** Choose *Solar* on the Car card or in Home Assistant: the car gets only the sun the house does not use, after the batteries (or before them, your choice), and pauses when there is too little. Every way out of Solar, a stop and a restart set the charger to 0 A. Three new options, all with defaults: `ev_margin_w`, `ev_start_min`, `ev_pause_min`. See "Car charger" in DOCS ([[EV-20]]). - 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]]). diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md new file mode 100644 index 0000000..263c9b0 --- /dev/null +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -0,0 +1,90 @@ +# EV-20 — Solar mode: spare sun to the car (charging only) + +Part 1 of the split of cancelled EV-05 (owner 2026-11-19). The design is +`reports/EV-01-design-report.md` sections 2-5 and decision 5; the rules are +EV-20's brief (Expected 1-15, D1-D4). EV-21 (the car cut first for the peak) +and EV-22 (another writer's phase change) are separate cards. This record keeps +what the code had to decide. + +## Where it lives + +`app/carmode.py`: `SolarPlan` (pure: the spare, the room, the dwells, the auto +phases) and `SolarWriter`, a subclass of EV-04's `ManualWriter`. It writes only +through `ManualWriter._write` and `_advance`, so the two write call sites stay +exactly two (test_ev04 / test_ev20 T55). `app/ctl_car.py` builds the inputs +(`car_spare_w`, `car_room_w`), runs the step beside the cycle, the release at +shutdown and today's solar kWh. + +## One rule for every write (EV-05 review rounds 2-9) + +EV-05 needed nine review rounds, mostly on exits and other writers. EV-20 keeps +one small set of facts and derives every path from them: + +- `sent_a`: the current Solar last decided, recorded BEFORE the write goes out; + `taken`: the charger confirmed it. A write cancelled while it waits is never + trusted (round 2, T37). +- A value is written when Solar DECIDES a new one. One the charger did not take + is tried again after 60 s, three times, then the gave-up row and one + CHARGER_REFUSED warning (EV-04's rule; round 2's Critical, T36). A new 0 A + gets its own three tries and never waits. +- A read-back that shows what Solar sent confirms it, however late (round 9's + second Major, T48). +- A read-back that differs from what Solar sent is never written over: + EV-04's `_watch` judges it, and while the difference stands Solar writes + nothing in its running state. After 30 s the hold (amber row, one + CHARGER_OTHER warning) stops every write, the way-out 0 A and the shutdown's + included (N16; rounds 5-7). Only pressing Solar lifts it. +- `live`: Solar's own current may stand on the charger (a non-zero value it + sent, or a 0 A not yet confirmed). A way out (Off, Stop, shadow, a safety + stop, a charger error or stuck reading, no car, shutdown) writes 0 A only + then. So a start in shadow writes nothing, and once the way-out 0 A is + confirmed nothing more is written, shutdown included (rounds 6 and 7). +- The start-up and a charger (or Home Assistant) that comes back write 0 A + first whatever the charger shows, with the read-back references cleared, so + its own value is never "another writer" (D2; round 9's first Major, T29, + T30, T61). + +## Choices the brief left open + +- **Writes over an unexplained read-back stop at once**, not after 30 s: the + plan goes on, the next decision waits. A way out still writes its 0 A inside + those 30 s (T39 (b)): 0 A is the safe side. +- **The phases follow the charger.** Solar's arithmetic uses the phases the + charger reports (1 for a one-phase car); its plan adopts them whenever it is + not switching. It selects only by its own dwells (and a start from a pause in + auto, on 1 phase), never "back" over a change it did not make (D4: EV-22). + A lower current is never blocked by the 10-minute phase gap (round 8, T46). +- **An interrupted phase change ends at its 0 A.** Manual's restore of the old + current stays Manual's. +- **Pressing Solar** lifts another writer's hold and takes the charger as it + is; Solar's own value is then decided and written afresh. Choosing Solar from + another mode starts paused: 0 A, then the start rule. +- **Stale and unknown.** The spare is unknown with a meter older than + `stale_input_s` (P1's own bound may be longer), readings late past it, a + missing or NaN battery or grid figure, or a charging car whose figure is + stale, stuck or not corroborated. A paused or idle car counts as 0 W. Unknown + holds the current for `ev_pause_min`, then 0 A. A cycle that returns early for + missing or late readings still steps Solar (Manual is left as it was). +- **The guard treats a Solar car exactly as a Manual car** (Expected 8): every + alarm-path test that said "Manual" says "Manual or Solar" + (`car_controlled`). Solar's own phase change gets EV-15's grace as Manual's; + its own 0 A pause gets it from the send, at most `OWN_PAUSE_MAX_S`, and only + while the read-back still shows that 0 A (round 8's second Major). +- **D1 wording.** The card's Why says "Solar charges the car at {a} A. This + sets the peak."; STYLE.md allows a grey note and a grey row one sentence, so + they say "Solar charges the car at {a} A, which sets the peak." `{a}` is the + charger's read-back, never Manual's stored current. +- **D3 at shutdown.** In Solar the charger's 0 A goes out before the inverters' + 0 W: up to three tries 5 s apart, each waiting 4 s for its read-back + (`write_current(took_s=...)`), all inside `RELEASE_WAIT_S` (15 s, also a + wall-clock bound for a charger that hangs). Not taken: one CHARGER_RELEASE + warning, the notice *Car may still be charging* after the inverters are + released, and the next start writes 0 A first (D2) and takes the notice down. +- **A charger error** sets 0 A (while owed) with one CHARGER_ERROR warning + and the card's Why; the existing grey error row shows it. No new + notification. +- **Solar kWh** is counted per cycle in Solar only: `min(car, max(0, spare - + room))` Batteries first, `min(car, max(0, spare))` Car first; never above + today's kWh; stored with its day, reset at the day's change. +- **Rollback.** An older build reads a stored `car_mode = solar` as Off + (`start_mode`) and writes nothing; no state migration. diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index 1d358f7..92cb8fe 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -256,7 +256,10 @@ The label and description each setting shows on the Configuration tab, in tab or | Car charger | Charger limit (A) | `ev_max_a` | The most current the charger may ever be asked for. Never above what the charger reports. Lower it for a weaker fuse or cable. | | Car charger | Phases | `ev_phases` | How many phases the charger may use: 1, 3, or 1 and 3 (auto). | | Car charger | Batteries help with the peak | `ev_batt_cover` | While the car charges. On: the batteries cover it down to the peak reserve. Off: the peak guard leaves the car out, so the car alone can set the peak. | -| Car charger | Mode after a restart | `ev_mode_start` | Keep the last mode, or start in Off. A restart never changes the charger's current. | +| Car charger | Mode after a restart | `ev_mode_start` | Keep the last mode, or start in Off. A restart in Solar sets the charger to 0 A first, other modes leave its current. | +| Car charger | Sun kept back (W) | `ev_margin_w` | Solar: this much spare sun is never given to the car. | +| Car charger | Start after (minutes) | `ev_start_min` | Solar: the car starts after this long with enough spare sun. | +| Car charger | Pause after (minutes) | `ev_pause_min` | Solar: with too little sun the car holds 6 A this long, then pauses. | | Advanced | Start control on boot | `auto_start` | Off by default. Leave it off until the site is commissioned, so someone presses Start after each restart. | | Advanced | Control gain | `gain` | How much of the remaining error control corrects each cycle. Measured on real hardware, do not raise it. | | Advanced | Largest change per cycle (W) | `slew_w` | How far the command may move in one cycle. 0 follows “Inverter rating” and is recommended. | @@ -3278,9 +3281,10 @@ it. ### Car charger The add-on can drive your car charger and shows it on **Home**, on a *Car* card. -The card has two modes in this version: **Off** (the add-on only reads the -charger and writes nothing) and **Manual** (the add-on sets the current and the -phases you choose). Solar and Night modes come in later versions. +The card has three modes in this version: **Off** (the add-on only reads the +charger and writes nothing), **Manual** (the add-on sets the current and the +phases you choose) and **Solar** (the car charges only from spare sun). Night +mode comes in a later version. | option | meaning | |---|---| @@ -3290,6 +3294,9 @@ phases you choose). Solar and Night modes come in later versions. | `ev_phases` | `1`, `3` or `auto` (1 and 3). | | `ev_batt_cover` | On (the default): the batteries help cover the car down to the peak reserve. Off: the car is left out of what the peak guard protects. | | `ev_mode_start` | `keep` (the default) or `off`: the mode after a restart. | +| `ev_margin_w` | Solar: the spare sun never given to the car, 0 to 1000 W (100). | +| `ev_start_min` | Solar: minutes of enough sun before the car starts, 1 to 30 (2). | +| `ev_pause_min` | Solar: minutes the car holds 6 A on too little sun before it pauses, 1 to 30 (5). | **What the Car card shows.** The state (Charging, Connected waiting, No car connected, Car is full, Charger not reachable), the power and current, and the @@ -3299,7 +3306,7 @@ no longer buy energy for a car that charged last night. **Manual mode.** Choose *Manual* on Home, then set the current (6 A up to the charger limit) and 1 or 3 phases. The same three are Home Assistant entities -when MQTT is on: `select.goodwe_car_mode` (Off, Manual), `number.goodwe_car_current` +when MQTT is on: `select.goodwe_car_mode` (Off, Manual, Solar), `number.goodwe_car_current` and `select.goodwe_car_phases`. The mode, the current and the phases apply at once, with no restart. The add-on writes each one once, when you change it, and checks within 10 seconds that the charger took it. @@ -3320,6 +3327,56 @@ checks within 10 seconds that the charger took it. current again only if the charger shows a different one. - Off writes nothing, ever. +**Solar mode.** Choose *Solar* on Home, or `Solar` in `select.goodwe_car_mode`. +The car charges only from the spare sun: what the solar panels make that the +house does not use (the meter, the batteries and the car's own power add up to +it). *Spare sun goes first to* (on the card, and `select.goodwe_car_sun_first`) +says who gets it first: + +- **Batteries:** the car gets the sun the batteries cannot take. Each battery + that may charge from the sun (switched On, not refusing a charge, not full) + keeps its whole rating first. With your two batteries and one of them full, + 7.9 kW of sun and 0.9 kW of house leave 1.9 kW for the car: 8 A on 1 phase. +- **Car:** the car takes the spare sun first, the batteries get the rest. + +In both, `ev_margin_w` (100 W) is kept back. The current is the car's share +divided by 230 V per phase, rounded down, from 6 A up to the charger limit. It +changes at most once per 30 seconds and only by 1 A or more. + +- **Start and pause.** The car starts after `ev_start_min` (2 minutes) with + enough sun for 7 A. Under 6 A worth it holds 6 A for `ev_pause_min` (5 + minutes), from the batteries or the grid, then the charger goes to 0 A and + the card says *Waiting for sun*. +- **Phases** (`ev_phases` auto): Solar starts on 1 phase, goes to 3 at 4.5 kW for + 3 minutes and back to 1 under 4.0 kW for 5 minutes, at most once per 10 + minutes, always through the safe sequence above. With `ev_phases` 1 or 3 it + never switches. A car that draws one phase while three are allowed is counted + on one phase until it is unplugged. +- **When the sun cannot be measured** (the meter older than 15 seconds, a battery + or grid reading missing, readings late, a car reading that is stale or not + confirmed by the charger's energy meter), the current stands for + `ev_pause_min`, then 0 A. +- **The fail state is 0 A.** Choosing Off, stopping control, shadow mode, a + safety stop, a charger error, a stuck charger reading, unplugging the car and + stopping the add-on each set the charger to 0 A once. A 0 A the charger does + not take is tried again after a minute, three times, then an amber row says + so. After a restart, or when the charger or Home Assistant answers again, + Solar sets 0 A first and then starts by its own rules. At a stop of the + add-on the charger's 0 A goes out before the batteries go to 0 W, for at + most 15 seconds; if the charger does not take it, the notice *Car may still + be charging* follows. +- **Shadow mode** writes nothing but that one 0 A; a start in shadow mode writes + nothing at all. The card says what Solar would set. +- **Another writer.** If the charger shows a current Solar did not set for 30 + seconds, Solar writes nothing over it (also no 0 A), shows an amber row and + logs one warning, until you press Solar again or the charger shows Solar's + value. +- **The peak limit** treats a Solar car exactly as a Manual car (below). Solar + does not slow the car for the peak in this version. +- **Energy.** The card says "{kWh} charged today, {kWh} from the sun", and the + sensor `goodwe_car_today_solar_kwh` has the sun's part. Only Solar's own + share of spare sun counts, not the hold's battery or grid power. + **The car is never slowed for the peak limit.** A Manual charge goes on whatever the 15-minute peak does. With the default `ev_batt_cover` on, the batteries help cover it down to the peak reserve; a 3-phase 16 A charge (11 kW) can empty two @@ -3365,8 +3422,7 @@ charger* shows for an hour after a change. That is expected while you migrate. current your helper held (`input_number.ev_manual_current`). Plug in and check the current on the card and on the charger's display. 3. On the next sunny day, choose Solar, with *spare sun goes first to* set as - your priority switch was. (Solar comes in a later version; until then keep - Manual or Off.) + your priority switch was. 4. Keep your Home Assistant helpers for a week. To go back, set the add-on mode to Off and switch the automation on. After that you can delete the helpers and the automation. @@ -3377,8 +3433,8 @@ off before you choose Manual, and the add-on off (mode Off) before you turn the automation on. **Home Assistant entities.** With MQTT the add-on adds the sensors -`goodwe_car_power`, `goodwe_car_state` and `goodwe_car_today_kwh`, and the three -controls named above. A saved ("retained") command is never applied, so a +`goodwe_car_power`, `goodwe_car_state`, `goodwe_car_today_kwh` and +`goodwe_car_today_solar_kwh`, and the four controls named above. A saved ("retained") command is never applied, so a restart of Home Assistant cannot change the charger. ### Site @@ -3514,7 +3570,14 @@ The car charge you set (Manual) takes the 15-minute period over the peak limit, and the batteries cannot hold it because they are at the peak reserve or at their full power. The add-on never slows the car, so this is information, not an alarm. It is raised once per charging session. To stay under the limit, lower the -current. +current. In Solar it says "Solar charges the car at {a} A, which sets the +peak.": the same case, with the current the charger has. + +### Car may still be charging + +The add-on stopped in Solar mode, and the charger did not take the 0 A it sent +first. The batteries were set to 0 W on time anyway. Check the current at the +charger. At the next start Solar sets 0 A first and the notification goes. ### For installers: notifications diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 32a65a1..e58a777 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -25,22 +25,33 @@ THE RULES, each tested in test_ev04.py: mode or a value again. * A charger that comes back after being unavailable gets the setting again only if its read-back differs. + +EV-20 adds Solar (`SolarPlan`, `SolarWriter`, below): spare sun to the car, +charging only. DECISIONS/EV-20-solar-mode.md. """ from __future__ import annotations +import asyncio import logging +import math from . import chargers as CH _LOG = logging.getLogger("goodwe") -OFF, MANUAL = "off", "manual" -#: the modes this card offers. Solar and Night are later cards (EV-05, EV-02). -MODES = (OFF, MANUAL) +OFF, MANUAL, SOLAR = "off", "manual", "solar" +#: the modes offered. Night is a later card (EV-02). +MODES = (OFF, MANUAL, SOLAR) #: Home Assistant's select labels, English and pinned. -MODE_LABELS = {OFF: "Off", MANUAL: "Manual"} +MODE_LABELS = {OFF: "Off", MANUAL: "Manual", SOLAR: "Solar"} START_KEEP, START_OFF = "keep", "off" +#: EV-20: where Solar's spare sun goes first, runtime state in the store. +FIRST_BATT, FIRST_CAR = "batteries", "car" +FIRSTS = (FIRST_BATT, FIRST_CAR) +FIRST_LABELS = {FIRST_BATT: "Batteries", FIRST_CAR: "Car"} +DEFAULT_FIRST = FIRST_BATT +KEY_FIRST = "car_sun_first" KEY_MODE, KEY_A, KEY_PHASES = "car_mode", "car_current", "car_phases" DEFAULT_A = 6.0 @@ -250,10 +261,11 @@ class ManualWriter: "the add-on set %.0f A), so the add-on stops writing " "to it until you change it.", cur, known[0]) - async def _write(self, drv, a, was, now, tracker) -> bool: + async def _write(self, drv, a, was, now, tracker, **kw) -> bool: tracker.begin_write() # EV-12: the read-back is ours try: - ok = await drv.write_current(a) + # EV-20: `kw` is only Solar's shorter read-back wait at shutdown. + ok = await drv.write_current(a, **kw) finally: self._stamp(now) tracker.end_write(self.last_done) @@ -379,7 +391,10 @@ class ManualWriter: if now - q["t1"] < SETTLE_S: return hi = CH.ENTITY_MAX_A if clamp is None else float(clamp) - a = min(max(float(want_a), CH.MIN_A), hi) + # EV-20: Solar hands a function of the sequence (its current depends + # on whether the phases changed); Manual a number, as before. + want = want_a(q) if callable(want_a) else want_a + a = min(max(float(want), CH.MIN_A), hi) if await self._write(drv, a, 0.0, now, tracker): # Judged afresh next cycle: a value the user changed meanwhile is # still wanted, and one that is in place is adopted. @@ -397,3 +412,673 @@ class ManualWriter: self.rev_applied = None return q["t1"] = now - SETTLE_S + 5.0 # again in 5 s + + +# =========================================================================== # +# EV-20: Solar. `SolarPlan` decides what the car should get from the spare sun; +# `SolarWriter` makes the charger match it through ManualWriter's write, phase +# sequence and other-writer watch. DECISIONS/EV-20-solar-mode.md. +# =========================================================================== # +VOLTS = 230.0 # per phase: what an amp is worth in watts +SOLAR_WRITE_S = 30.0 # at most one current change per this ... +SOLAR_STEP_A = 1.0 # ... and only on a change of this or more +UP_W, UP_S = 4500.0, 180.0 # auto phases: to 3 at this for this long +DOWN_W, DOWN_S = 4000.0, 300.0 # ... back to 1 under this for this long +ONE_PHASE_S = 10.0 # one phase drawing while 3 are allowed this long +ONE_PHASE_MIN_W = 500.0 # ... with the car drawing at least this +# D3: at shutdown the 0 A is tried this many times, this far apart, each +# waiting this long for its read-back: inside `ctl_car.RELEASE_WAIT_S`. +RELEASE_TRIES = 3 +RELEASE_GAP_S = 5.0 +RELEASE_TOOK_S = 4.0 + + +def _num(v): + try: + f = float(v) + except (TypeError, ValueError): + return None + return f if math.isfinite(f) else None + + +def spare_w(car_w, batt_w, grid_w): + """The spare sun, SIGNED and not clipped: `car + battery charge - grid + import`, which is the solar production less the house. `batt_w` is the + add-on's site battery figure (discharge positive), so it is subtracted. + A grid charge of the batteries, or batteries giving more than the house + uses, is never spare sun. None when a figure is missing or not a number.""" + c, b, g = _num(car_w), _num(batt_w), _num(grid_w) + if c is None or b is None or g is None: + return None + return c - b - g + + +def car_target_w(spare, room_w, margin_w, first): + """What the car may take: Batteries first `spare - room - margin`, Car + first `spare - margin`. None while the spare is unknown.""" + s = _num(spare) + if s is None: + return None + room = float(_num(room_w) or 0.0) if first == FIRST_BATT else 0.0 + return s - room - float(_num(margin_w) or 0.0) + + +def amps_for(car_w, n, clamp=None): + """Whole amps for `car_w` on `n` phases, ROUNDED DOWN, never above the + clamp, never below 0. None for a figure that is not a number.""" + w = _num(car_w) + if w is None or n not in (1, 3): + return None + a = math.floor(w / (VOLTS * n) + 1e-9) + hi = CH.ENTITY_MAX_A if _num(clamp) is None else float(clamp) + return float(max(0, min(a, math.floor(hi)))) + + +def solar_option(opts: dict, key: str) -> float: + """`ev_margin_w`, `ev_pause_min` or `ev_start_min` as a number; the shipped + default when it is not one (the validator refuses it anyway).""" + v = _num((opts or {}).get(key)) + return float(CH.EV_OPTION_DEFAULTS[key]) if v is None else v + + +class SunInputs: + """One cycle's inputs for Solar, built by the Controller.""" + + def __init__(self, target_w=None, hold=False, auto=True, start_s=120.0, + pause_s=300.0, spare_w=None, room_w=0.0, margin_w=100.0, + first=DEFAULT_FIRST): + self.target_w, self.hold, self.auto = target_w, hold, auto + self.start_s, self.pause_s = start_s, pause_s + self.spare_w, self.room_w, self.margin_w = spare_w, room_w, margin_w + self.first = first + + +class SolarPlan: + """What Solar wants set, one `step()` per cycle. Pure: monotonic `now` + from the caller and no driver, so shadow mode runs it the same and the + card says what it would set. `a` is the current wanted (0: paused), `n` + the phases it is meant for; `switch` is a phase change it decided that + the writer has not finished.""" + + def __init__(self, n=1): + self.reset(n) + + def reset(self, n=1, why="paused"): + self.a = 0.0 + self.n = n if n in (1, 3) else 1 + self.switch = False + self.set_at = None # the latest non-zero change (30 s rule) + self.ok_since = None # enough sun to start, since + self.low_since = None # under 6 A worth, holding 6 A, since + self.unknown_since = None # the spare cannot be measured, since + self.up_since = self.down_since = None + self.why = why + self.target_w = None + self._before = None # the state before a phase change + + def pause(self, why="paused"): + self.a = 0.0 + self.switch, self._before = False, None + self.ok_since = self.low_since = self.unknown_since = None + self.up_since = self.down_since = None + self.why = why + + def _gate(self, now) -> bool: + return self.set_at is None or now - self.set_at >= SOLAR_WRITE_S + + def _set(self, a, now, n=None): + if n is not None and n != self.n: + self._before = (self.a, self.n, self.set_at, self.low_since, + self.why) + self.n, self.switch = n, True + self.a, self.set_at, self.why = float(a), now, "running" + self.ok_since = self.low_since = None + self.up_since = self.down_since = None + + def end_switch(self, done: bool) -> None: + """The writer finished (`done`) or gave up the phase change. Given up, + the plan is back where it was before it: its current for the old + phases, its hold count (N3), so nothing meant for the new phases is + written on the old ones.""" + if self.switch and not done and self._before is not None: + self.a, self.n, self.set_at, self.low_since, self.why = \ + self._before + self.switch, self._before = False, None + + def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s, + hold=False, gap_ok=True): + """`n_now`: the phases the car draws on now (1 for a one-phase car); + `auto`: Solar may choose the phases; `gap_ok`: a phase change is + allowed now (EV-04's one per `PHASE_GAP_S`); `hold`: readings late + under the stale bound, everything stands.""" + if hold: + # Readings late under the stale bound: nothing changes, but a + # hold or an unknown spare that has run its time still pauses + # (N3: never 6 A past `pause_s`, however often the verdict + # comes back). + if self.a > 0.0 and any( + since is not None and now - since >= pause_s + for since in (self.low_since, self.unknown_since)): + self.pause("unknown") + return + self.target_w = target_w + if not self.switch and n_now in (1, 3): + self.n = n_now # the phases are what the charger has + if target_w is None: # the sun cannot be measured: hold, then 0 + self.ok_since = None + if self.a > 0.0: + if self.unknown_since is None: + self.unknown_since = now + # A hold that began on a known low spare still ends on time. + if now - self.unknown_since >= pause_s or ( + self.low_since is not None + and now - self.low_since >= pause_s): + self.pause("unknown") + else: + self.why = "unknown" + return + self.unknown_since = None + if self.a <= 0.0: # paused: the start rule + n0 = 1 if auto else self.n + if target_w >= (CH.MIN_A + 1.0) * VOLTS * n0: + if self.ok_since is None: + self.ok_since = now + self.why = "start" + if now - self.ok_since >= start_s \ + and (n0 == self.n or gap_ok): + a = amps_for(target_w, n0, clamp) + if a is not None and a >= CH.MIN_A: + self._set(a, now, n0) + else: + self.ok_since = None + self.why = "paused" + return + hi = None if _num(clamp) is None else math.floor(float(clamp)) + if hi is not None and self.a > hi: # the clamp came down + if hi < CH.MIN_A: + self.pause() + return + self.a, self.set_at = float(hi), now + if auto and not self.switch: # auto phases, by dwells + if self.n == 1: + self.down_since = None + if target_w >= UP_W: + if self.up_since is None: + self.up_since = now + else: + self.up_since = None + if self.up_since is not None and now - self.up_since >= UP_S \ + and gap_ok and self._gate(now): + a = amps_for(target_w, 3, clamp) + if a is not None and a >= CH.MIN_A: + self._set(a, now, 3) + return + else: + self.up_since = None + if target_w < DOWN_W: + if self.down_since is None: + self.down_since = now + else: + self.down_since = None + if self.down_since is not None \ + and now - self.down_since >= DOWN_S \ + and gap_ok and self._gate(now): + a = amps_for(target_w, 1, clamp) + if a is not None and a >= CH.MIN_A: + self._set(a, now, 1) + return + want = amps_for(target_w, self.n, clamp) + if want is not None and want >= CH.MIN_A: + self.low_since = None + self.why = "running" + if abs(want - self.a) >= SOLAR_STEP_A and self._gate(now): + self.a, self.set_at = want, now + return + if auto and self.n == 3 and target_w >= DOWN_W and not self.switch: + # Inside the phase hysteresis (4.0 kW up to 6 A on 3 phases): 6 A + # on 3 phases stands until the down dwell, with no pause count. + self.low_since = None + self.why = "running" + if self.a != CH.MIN_A and self._gate(now): + self.a, self.set_at = CH.MIN_A, now + return + if self.low_since is None: + self.low_since = now + self.why = "hold" + if now - self.low_since >= pause_s: + self.pause() + return + if self.a != CH.MIN_A and self._gate(now): + self.a, self.set_at = CH.MIN_A, now + + +class SolarWriter(ManualWriter): + """What Solar does to the charger, one `step()` per cycle. It shares + ManualWriter's write, phase sequence and other-writer watch. + + ONE RULE FOR EVERY WRITE (EV-05 review rounds 2-9): Solar writes a value + when it DECIDES a new one (`sent_a` differs), and tries a value the + charger did not take again after `RETRY_S`, `MAX_TRIES` times, then the + gave-up row and warning. A read-back that shows the value Solar sent + confirms it, however late (`_adopt`). A read-back that differs from what + Solar sent is never written over: `_watch` judges it (EV-04's 30 s + other-writer rule), and while its hold stands nothing at all is written. + + WAYS OUT (Off, Stop, shadow, a safety stop, a charger error or stuck + reading, no car, shutdown) write 0 A only while Solar's own current may + stand on the charger (`live`): a non-zero value it sent, or a 0 A not yet + confirmed. Once that 0 A is confirmed nothing more is written, and a + start in shadow or with control stopped writes nothing. THE START-UP and + a charger (or Home Assistant) that comes back write 0 A first whatever the + charger shows, then the start rule (D2). An interrupted phase change ends + at the 0 A it began with; nothing is restored.""" + + def __init__(self): + super().__init__() + self.plan = SolarPlan() + self.engaged = False # Solar ran since it was chosen + self.sent_a = None # the current Solar last decided to write + self.taken = True # ... and the charger confirmed it + self.fresh_start = True # start-up or back: 0 A first (D2) + self.restart = True # writing again: the plan starts paused + self.out = False # not writing now (shadow, Stop, latch) + self.fault = None # "error" | "stuck" while it stands + self.single = False # a one-phase car on a 3-phase allowance + self._one_since = None + self.zero_at = None # EV-15: our own latest 0 A was sent then + self.sun = None # the last `SunInputs`, for the card + self._would_n = None # shadow: the phases the plan believes + self._would_switch = None # ... and when it last changed them + self.released = None # D3: True / False once shutdown tried + self.mode_was = None # the mode of the previous step + + # ------------------------------------------------------------- state + @property + def live(self) -> bool: + """May a current of Solar's own stand on the charger? A non-zero value + it sent (taken or not), or a 0 A not yet confirmed. Only then does a + way out write its 0 A.""" + return self.sent_a is not None and (self.sent_a > TOL_A + or not self.taken) + + @property + def zero_owed(self) -> bool: + """A way-out 0 A the charger has not confirmed yet (for the card).""" + return bool(self.engaged and self.sent_a is not None + and self.sent_a <= TOL_A and not self.taken + and not self.hold) + + def amps_out(self, clamp) -> float: + """The plan's current, never above the clamp; 0 when under 6 A.""" + a = float(self.plan.a) + if _num(clamp) is not None: + a = min(a, float(math.floor(float(clamp)))) + return a if a >= CH.MIN_A else 0.0 + + def user_changed(self) -> None: + """The user PRESSED SOLAR: another writer's hold is lifted and Solar + takes the charger as it is (its value is no longer a difference); + Solar's own value is decided and written afresh.""" + held = self.hold or self.mismatch_since is not None + super().user_changed() + self.gave_up, self.fails, self.fail_at = False, 0, None + if held: + self.last_a = None + self.sent_a, self.taken = None, True + + # ------------------------------------------------------------- writes + async def _write(self, drv, a, was, now, tracker, **kw) -> bool: + """ManualWriter's one write site. What Solar SENT is recorded before + the write goes out, so a write cancelled while it waits for its + read-back is never trusted (`live`).""" + self.sent_a, self.taken = float(a), False + zero = float(a) <= TOL_A + if zero: + self.zero_at = self.zero_sent_at = now + try: + ok = await super()._write(drv, a, was, now, tracker, **kw) + finally: + if zero: + self.zero_sent_at = None + if ok: + self.taken = True + self.fails, self.fail_at, self.gave_up = 0, None, False + else: + self._failed(now) + return ok + + def _failed(self, now) -> None: + self.fails += 1 + self.fail_at = now + if self.fails >= MAX_TRIES and not self.gave_up: + self.gave_up = True + _LOG.warning("The charger did not take the current, so the add-on " + "stops asking until you press Solar: " + "CHARGER_REFUSED.") + + def _adopt(self, cur) -> None: + """The read-back shows what Solar sent: taken, however late.""" + self.taken = True + self.last_a = cur + self.attempted_a = self.prior_a = None + self.fails, self.fail_at, self.gave_up = 0, None, False + + async def _put(self, drv, want, cur, now, tracker, stuck=False) -> None: + """Make the charger match `want`: write a new decision, try one the + charger did not take again after `RETRY_S`. A new 0 A gets its own + `MAX_TRIES` and never waits (0 A is the safe side).""" + if self.hold: + return + if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A: + if self.taken or self.gave_up or ( + self.fail_at is not None + and now - self.fail_at < RETRY_S): + return + await self._write(drv, want, cur, now, tracker) + return + if not stuck and cur is not None and abs(cur - want) <= TOL_A: + self.sent_a = want # it already stands + self._adopt(cur) + return + if want <= TOL_A: + self.fails, self.fail_at, self.gave_up = 0, None, False + elif self.gave_up or (self.fail_at is not None + and now - self.fail_at < RETRY_S): + return + await self._write(drv, want, cur, now, tracker) + + async def _zero(self, drv, cur, now, tracker, stuck=False) -> None: + """A way out: 0 A while Solar's own current may stand, never over + another writer's hold.""" + self.seq = None + self.plan.end_switch(False) + if self.live and not self.hold: + await self._put(drv, 0.0, cur, now, tracker, stuck) + + def _watch(self, cur, now) -> None: + was = self.hold + super()._watch(cur, now) + if self.hold and not was: + _LOG.warning("Something else changes the charger, so the add-on " + "stops writing to it until you press Solar: " + "CHARGER_OTHER.") + + def _mark(self, r, now) -> None: + """A car that draws one phase while 3 are allowed is a one-phase car + for the session: the sun arithmetic then uses 1 phase.""" + if r.state == "A": + if self.single: + _LOG.info("The car was unplugged, so the add-on counts the " + "phases the charger allows again.") + self.single, self._one_since = False, None + return + amps = [x for x in (r.current_a or ()) if x is not None] + drawing = [x for x in amps if x >= CH.IDLE_A] + one = (r.phases_allowed == 3 and r.charging is True + and r.power_w is not None and r.power_w >= ONE_PHASE_MIN_W + and len(amps) >= 3 and len(drawing) == 1) + if not one: + self._one_since = None + return + if self._one_since is None: + self._one_since = now + if now - self._one_since >= ONE_PHASE_S and not self.single: + self.single = True + _LOG.info("The car draws one phase while three are allowed, so " + "the add-on counts one phase for this charge.") + + def _leave(self) -> None: + """Solar is no longer the mode and owes nothing.""" + self.engaged, self.seq, self.would = False, None, None + self.out, self.fault = False, None + self.restart = True + self.mismatch_since = None + self.plan.reset(self.plan.n) + + def _gap_ok(self, now) -> bool: + return self.last_switch is None or now - self.last_switch \ + >= PHASE_GAP_S + + def _plan_step(self, sun, now, clamp, n_now, gap_ok) -> None: + self.plan.step( + now, target_w=sun.target_w, hold=sun.hold, n_now=n_now, + auto=sun.auto and not self.single and not self.phases_gave_up, + clamp=clamp, start_s=sun.start_s, pause_s=sun.pause_s, + gap_ok=gap_ok) + + @staticmethod + def _drawing(r) -> bool: + """EV-04's test of a car that has not stopped (`_advance`).""" + if r.power_w is not None: + return r.power_w >= QUIET_W + return r.state in ("C", "D") + + def _hold_over(self, now, sun) -> bool: + """Has the hold the plan was in before its phase change run out?""" + before = self.plan._before + return bool(before is not None and before[3] is not None + and sun is not None + and now - before[3] >= sun.pause_s) + + def _seq_want(self, clamp): + """The current that ends a phase change: for the new phases, or for + the old ones when the select did not happen.""" + def want(q): + before = self.plan._before + if q.get("failed") and before is not None: + return before[0] if before[0] >= CH.MIN_A else CH.MIN_A + return self.amps_out(clamp) or CH.MIN_A + return want + + async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None: + """Step 1 of the safe sequence: 0 A (kept when it already stands). + A 0 A the charger does not take ends the change; tried again later + by the plan's own dwell.""" + self.phase_done_at = None + if not (cur is not None and cur <= TOL_A and self.sent_a == 0.0 + and self.taken): + if not await self._write(drv, 0.0, cur, now, tracker): + self.plan.end_switch(False) + return + self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, + "prev": None, "from": r.phases_allowed} + + # ------------------------------------------------------------- step + async def step(self, drv, r, *, mode, sun, clamp, now, tracker, writing, + status, clock=None): + """One cycle. `sun` is `SunInputs` (None outside Solar); `writing` is + False in shadow mode, while control is stopped, under a safety stop + and while stopping.""" + self._clock = clock or (lambda: now) + entering = mode == SOLAR and self.mode_was != SOLAR + self.mode_was = mode + if entering: + # Chosen (or the start-up): the plan starts paused, 0 A first. + self.engaged, self.restart = True, True + self.sent_a, self.taken = None, True + self.fails, self.fail_at, self.gave_up = 0, None, False + if not self.engaged: + return + if sun is not None: + self.sun = sun + if r is None or not r.available: + self.was_available = False # nothing is tried while it is down + return + 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: + # A reading older than our latest write says nothing about it: + # no write and no watch, but the plan's dwells go on counting. + if mode == SOLAR and sun is not None and writing \ + and self.seq is None and not self.plan.switch \ + and not self.restart and self.fault is None \ + and not self.hold and self.mismatch_since is None: + self._plan_step(sun, now, clamp, self.plan.n, + self._gap_ok(now)) + return + if not self.was_available: + # Start-up, or back after the charger or Home Assistant was gone: + # the charger's current is its own, not another writer's, and the + # first write is 0 A whatever it shows (D2, round 9). + self.was_available = True + self.fresh_start = self.restart = True + self.mismatch_since = None + self.last_a = self.attempted_a = self.prior_a = None + cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a + stuck = bool(tracker is not None and tracker.stuck(now)) + if not self.taken and self.sent_a is not None and not stuck \ + and cur is not None and abs(cur - self.sent_a) <= TOL_A: + self._adopt(cur) # round 9: a late read-back + self._mark(r, now) + if mode != SOLAR: + self.would = None + if mode == OFF: # 0 A while owed, then nothing + await self._zero(drv, cur, now, tracker, stuck) + if self.live and not self.hold: + return # tried again (or gave up) + self._leave() # Manual writes its own current + return + n_real = r.phases_allowed if r.phases_allowed in (1, 3) \ + else self.plan.n + n_now = 1 if self.single else n_real + if not writing: + # Shadow, Stop, a safety stop, stopping: the way-out 0 A while + # owed, then nothing. The watch goes on (another writer is held + # for every reader) and so does the plan, for the card. + self.out = True + await self._zero(drv, cur, now, tracker, stuck) + self._watch(cur, now) + self._shadow_plan(sun, now, clamp, n_now) + self.restart = True + return + self.out = False + self._would_n = self._would_switch = None + self.would = None + fault = ("error" if (r.error or r.state in ("E", "F")) else + "stuck" if stuck else None) + if fault is not None: + # 0 A while owed, then no write until it clears; then the start + # rule. A stuck reading cannot confirm the 0 A. + if self.fault != fault: + self.fault = fault + if fault == "error": + _LOG.warning("The charger reports an error, so the add-on " + "sets the car to 0 A: CHARGER_ERROR.") + await self._zero(drv, cur, now, tracker, stuck) + self.plan.reset(n_now, why=fault) + self.restart = True + return + if self.fault is not None: + self.fault = None + if r.state == "A" or status == CH.NONE_: + # No car: 0 A while owed, then nothing until a car is plugged in + # and the start rule passes. + await self._zero(drv, cur, now, tracker) + self.plan.reset(n_now, why="none") + self.restart = True + return + if self.restart: + self.restart = False + self.seq = None + self.plan.reset(n_now) + if self.fresh_start: + self.fresh_start = False + self.sent_a, self.taken = None, True # 0 A first (D2) + if self.seq is None: + self._watch(cur, now) + if self.hold or self.mismatch_since is not None: + # Another writer's value, held or not yet: nothing is written + # over it; the plan goes on for the card. + self._plan_step(sun, now, clamp, n_now, False) + return + gap = self._gap_ok(now) + if self.sent_a == 0.0 and not self.taken: + self.plan.ok_since = None # 0 A first, then the start rule + if self.seq is not None: + self._plan_step(sun, now, clamp, self.plan.n, gap) + if self.plan.a < CH.MIN_A: + self.seq = None # paused: it stays at 0 A + self.plan.end_switch(True) + return + q = self.seq + if q["stage"] == "zero" and now - q["t0"] >= ZERO_WAIT_S \ + and self._drawing(r) and self._hold_over(now, sun): + # The car still draws at the cap and the hold the plan came + # from has run its time: no select and no current back (N3); + # the 0 A stands as the pause. EV-04 counts the try. + self.seq = None + self.last_switch = now + self.phase_fails += 1 + if self.phase_fails >= MAX_TRIES: + self.phases_gave_up = True + _LOG.warning("The car kept drawing, so the phases were not " + "changed.") + self.plan.end_switch(False) + self.plan.pause() + return + await self._advance(drv, r, cur, now, tracker, + self._seq_want(clamp), clamp, None) + if self.seq is None: + # Done when the phases were selected and the current is back; + # otherwise the plan returns to its old phases. + self.plan.end_switch(not q.get("failed")) + return + self._plan_step(sun, now, clamp, n_now, gap) + want = self.amps_out(clamp) + if want >= CH.MIN_A and self.plan.switch \ + and self.plan.n != n_now and not self.single: + if self.gave_up or (self.fail_at is not None + and now - self.fail_at < RETRY_S): + return + await self._begin_solar(drv, r, cur, self.plan.n, now, tracker) + return + if self.plan.switch: + self.plan.end_switch(self.plan.n == n_now) + await self._put(drv, want, cur, now, tracker) + + def _shadow_plan(self, sun, now, clamp, n_now) -> None: + """Not writing: the plan runs on the phases it believes, a phase + change it decides counting as done, so the card says what Solar would + set (`would`).""" + n = self._would_n if self._would_n in (1, 3) else n_now + gap = self._would_switch is None or now - self._would_switch \ + >= PHASE_GAP_S + if sun is not None: + self._plan_step(sun, now, clamp, n, gap) + if self.plan.switch: + self.plan.end_switch(True) + self._would_n, self._would_switch = self.plan.n, now + elif self._would_n is None: + self._would_n = self.plan.n + self.would = (self.amps_out(clamp), self.plan.n) + + async def release(self, drv, r, now, tracker) -> bool | None: + """The add-on stops in Solar (D3): 0 A while Solar's own current may + stand (a write cancelled while it waited counts), never over another + writer's hold. Up to `RELEASE_TRIES` tries `RELEASE_GAP_S` apart, each + waiting `RELEASE_TOOK_S` for its read-back. True: taken; False: not + taken (the caller warns); None: nothing was owed. Nothing is restored + of an interrupted phase change.""" + self.seq = None + self.plan.end_switch(False) + self._clock = self._clock or (lambda: now) + if not self.engaged or not self.live or self.hold: + return None + if r is not None and r.available: + cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a + else: + cur = None + clock = getattr(drv, "_clock", None) or (lambda: now) + sleep = getattr(drv, "_sleep", None) or asyncio.sleep + t0 = clock() + for k in range(RELEASE_TRIES): + if k: + wait = t0 + k * RELEASE_GAP_S - clock() + if wait > 0: + await sleep(wait) + if await self._write(drv, 0.0, cur, clock(), tracker, + took_s=RELEASE_TOOK_S): + self.released = True + return True + self.released = False + return False diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index c6cb8ee..c2d56c0 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -5,8 +5,8 @@ actuator per site, a census key, a read, a clamped write that says whether the charger took it, and a hand-back. A charger is a modulated actuator with a fail state, not one of DEV-01's on/off loads. -EV-04 IS THE FIRST CARD THAT WRITES TO THE CHARGER, and only in Manual -(`app/carmode.py` is the one caller). `write_current` is clamped to +EV-04 IS THE FIRST CARD THAT WRITES TO THE CHARGER, in Manual and (EV-20) in +Solar (`app/carmode.py` is the one caller). `write_current` is clamped to `min(ev_max_a, the station limit the charger reports, the entity's own range)` and a value above that is NEVER SENT: it is a software fault, logged in the OUTPUT_CLAMP shape. It says True only when the charger's read-back followed @@ -42,7 +42,13 @@ PHASES_CHOICES = ("1", "3", "auto") # config.yaml's shipped defaults, mirrored (test_defaults_pin.py checks it). EV_OPTION_DEFAULTS = {"ev_charger": "off", "ev_current_entity": "", "ev_max_a": 16, "ev_phases": "auto", - "ev_batt_cover": True, "ev_mode_start": "keep"} + "ev_batt_cover": True, "ev_mode_start": "keep", + # EV-20, Solar: the sun kept back and the two dwells + "ev_margin_w": 100, "ev_pause_min": 5, + "ev_start_min": 2} +#: EV-20: the ranges config.yaml's schema and the validator both hold. +SOLAR_RANGES = {"ev_margin_w": (0, 1000), "ev_pause_min": (1, 30), + "ev_start_min": (1, 30)} def max_a(opts: dict): @@ -396,7 +402,7 @@ class ChargerDriver: from the charger, the entity's own range max)`.""" raise NotImplementedError - async def write_current(self, a: float) -> bool: + async def write_current(self, a: float, took_s: float = TOOK_S) -> bool: raise NotImplementedError async def write_phases(self, n: int) -> bool: @@ -503,9 +509,10 @@ class AlfenHaDriver(ChargerDriver): pass return min(x for x in (self.max_a, station, rng) if x is not None) - async def write_current(self, a: float) -> bool: + async def write_current(self, a: float, took_s: float = TOOK_S) -> bool: """Set the current, once. True only when the charger took it: the - read-back followed within `TOOK_S`. A value above `clamp_a()` is a + read-back followed within `took_s` (`TOOK_S`; EV-20's shutdown 0 A + waits less, so three tries fit its 15 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 = [] @@ -527,10 +534,10 @@ class AlfenHaDriver(ChargerDriver): del self.sent[:-50] if not await hass.set_number(self.current_entity, a): return False - return await self._took(a) + return await self._took(a, took_s) - async def _took(self, a: float) -> bool: - """Did the read-back follow the write, within `TOOK_S`?""" + async def _took(self, a: float, took_s: float = TOOK_S) -> bool: + """Did the read-back follow the write, within `took_s`?""" t0 = self._clock() while True: st = await self._states(("readback", "current") + _LIFE_ROLES) @@ -538,7 +545,7 @@ class AlfenHaDriver(ChargerDriver): seen = _first(_amps(st["readback"]), _amps(st["current"])) if seen is not None and abs(seen - a) <= TOOK_TOL_A: return True - if self._clock() - t0 >= TOOK_S: + if self._clock() - t0 >= took_s: return False await self._sleep(1.0) @@ -576,7 +583,9 @@ class AlfenHaDriver(ChargerDriver): async def release(self, mode: str) -> bool: """The mode's fail state. Manual and Off keep the current (the charger - is a stand-alone device and the current is the user's setting).""" + is a stand-alone device and the current is the user's setting). + Solar's 0 A goes through `carmode.SolarWriter.release`, the one write + site, so nothing is written here.""" return True diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index eeb660c..8a4f08f 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -1,9 +1,12 @@ -"""EV-04: the Controller's side of the car's Manual mode. +"""EV-04 and EV-20: the Controller's side of the car's Manual and Solar modes. -The writes themselves are `carmode.ManualWriter`'s; this mixin owns the state -(mode, current, phases: runtime state in the store, like OPT-11's modes), the -actions, the background step that never holds up a control cycle, and what the -car means for the peak guard's ALARM PATH. DECISIONS/EV-04-manual-mode.md. +The writes themselves are `carmode.ManualWriter`'s and `carmode.SolarWriter`'s; +this mixin owns the state (mode, current, phases, where spare sun goes first: +runtime state in the store, like OPT-11's modes), the actions, the background +step that never holds up a control cycle, and what the car means for the peak +guard's ALARM PATH. DECISIONS/EV-04-manual-mode.md, DECISIONS/EV-20-solar-mode.md +(Solar's inputs, its 0 A before the inverters at shutdown, today's solar kWh; +the guard treats a Solar car exactly as a Manual car). """ import asyncio @@ -11,7 +14,7 @@ import dataclasses import logging from datetime import timezone -from . import carmode, chargers, messages, peakguard +from . import carmode, chargers, messages, packshare, peakguard from .tariff import QUARTER_S _LOG = logging.getLogger("goodwe") @@ -34,6 +37,13 @@ OWN_PAUSE_TAIL_S = chargers.CORR_WINDOW_S # EV-19: the meter's house side (held - car) moved no more than this since the # last cycle: it has not shown a battery rise the reading already shows. RISE_STILL_W = 50.0 +# EV-20: today's kWh from the sun, {day, kwh}; and a shutdown whose 0 A the +# charger did not take (D3), so the next start can take its notice down. +CAR_SUN_KEY = "car_sun" +CAR_RELEASE_KEY = "car_release_failed" +# EV-20 (D3): at shutdown in Solar the charger's 0 A waits at most this long, +# then the inverters are released whatever the charger did. +RELEASE_WAIT_S = 15.0 class CarMixin: @@ -55,6 +65,23 @@ class CarMixin: self.car_n = n if n in ok else ok[0] self.car_rev = 0 self.car_writer = carmode.ManualWriter() + self.car_solar = carmode.SolarWriter() # EV-20 + first = data.get(carmode.KEY_FIRST) + self.car_first = first if first in carmode.FIRSTS \ + else carmode.DEFAULT_FIRST + self._car_late_s = None # EV-20: the cycle's late verdict + self._car_sun_now = None # ... and Solar's inputs of that cycle + sun = data.get(CAR_SUN_KEY) + self.car_sun = {"day": None, "kwh": 0.0} + if isinstance(sun, dict): + try: + self.car_sun = {"day": sun.get("day"), + "kwh": max(0.0, float(sun.get("kwh") or 0.0))} + except (TypeError, ValueError): + pass + self._car_sun_mono = None + self._car_sun_saved = round(self.car_sun["kwh"], 2) + self._car_release_failed = bool(data.get(CAR_RELEASE_KEY)) self._car_task = None self._car_step_failed = False self.car_explains = False # the car alone explains the excess @@ -89,6 +116,23 @@ class CarMixin: return (self.charger.configured() and self.car_mode == carmode.MANUAL) + def car_solar_mode(self) -> bool: + """EV-20: a charger is set up and the mode is Solar.""" + ch = getattr(self, "charger", None) + return bool(ch is not None and ch.configured() + and getattr(self, "car_mode", None) == carmode.SOLAR) + + def car_controlled(self) -> bool: + """EV-20: Manual or Solar. The peak guard's alarm path treats a Solar + car exactly as a Manual car (Expected 8).""" + return self.car_manual() or self.car_solar_mode() + + def car_solar_engaged(self) -> bool: + """EV-20: Solar is the mode, or its way-out 0 A is still owed.""" + w = getattr(self, "car_solar", None) + return bool(self.charger.configured() and w is not None + and (self.car_mode == carmode.SOLAR or w.engaged)) + def car_clamp(self): return carmode.clamp_for(self.o, self.car.reading) @@ -110,8 +154,23 @@ class CarMixin: if what == "car_mode": if value not in carmode.MODES: return {"error": messages.car_refused("value")} + if value == carmode.SOLAR and self.car_mode != carmode.SOLAR: + # A Manual phase change in the middle is not restored: Solar + # starts from the 0 A it stands at. + self.car_writer.seq = None self.car_mode = value self.store.set(carmode.KEY_MODE, value) + elif what == "car_sun_first": + # EV-20: arithmetic only, from the next cycle; not a change of the + # writers (the 30 s rule and another writer's hold stand). + if value not in carmode.FIRSTS: + return {"error": messages.car_refused("value")} + self.car_first = value + self.store.set(carmode.KEY_FIRST, value) + self.log_event(f"car sun first set to {value} by operator", + hint=messages.hint("car_sun_first")) + return {"mode": self.car_mode, "current": self.car_a, + "phases": self.car_n, "sun_first": self.car_first} elif what == "car_current": clamp = self.car_clamp() if isinstance(value, bool): @@ -134,6 +193,11 @@ class CarMixin: self.store.set(carmode.KEY_PHASES, value) self.car_rev += 1 self.car_writer.user_changed() + if what == "car_mode" and value == carmode.SOLAR: + # EV-20: only pressing Solar lifts Solar's other-writer hold. + # Leaving Solar, or Manual's current or phases, is not the user + # handing the charger back to Solar (N10). + self.car_solar.user_changed() self.log_event(f"car {what[4:]} set to {value} by operator", hint=messages.hint(what)) return {"mode": self.car_mode, "current": self.car_a, @@ -143,7 +207,8 @@ class CarMixin: """The MQTT state of the three car entities.""" return {"car_mode": carmode.MODE_LABELS[self.car_mode], "car_current": round(self.car_a), - "car_phases": str(self.car_n)} + "car_phases": str(self.car_n), + "car_sun_first": carmode.FIRST_LABELS[self.car_first]} # ------------------------------------------------------------- the writer def car_kick(self) -> None: @@ -155,8 +220,20 @@ class CarMixin: t = self._car_task if t is not None and not t.done(): return + # EV-20: Solar's inputs as this cycle read them. The step runs beside + # the next read, which must not hand it a new meter reading with an + # old car reading (or the other way round). + self._car_sun_now = (self.car_sun_inputs(self.car_now()) + if self.car_solar_mode() else None) self._car_task = asyncio.ensure_future(self._car_run()) + def _car_hold_kick(self) -> None: + """EV-20: a cycle that holds for a missing or late reading returns + before `car_kick()`. Solar still steps (it holds, counts its dwell, + and a way out still writes its 0 A); Manual is left as it was.""" + if self.car_solar_engaged(): + self.car_kick() + async def car_settle(self) -> None: """Wait for the writer step in flight (the checks use it).""" t = self._car_task @@ -180,13 +257,29 @@ class CarMixin: self._car_step_failed = False async def car_shutdown(self) -> None: - """The add-on stops: no new write, and a phase change in the middle is - undone by giving the car its current back. The current stands - otherwise (Manual's fail state).""" + """The add-on stops: no new write. Manual: a phase change in the middle + is undone by giving the car its current back; the current stands + otherwise (Manual's fail state). Solar (EV-20, D3): 0 A, waited for at + most `RELEASE_WAIT_S` (`Controller.shutdown` calls this BEFORE the + inverters go to 0 W in Solar).""" t, self._car_task = getattr(self, "_car_task", None), None if t is not None and not t.done(): t.cancel() await asyncio.gather(t, return_exceptions=True) + if self.car_solar_engaged(): + try: + done = await asyncio.wait_for(self.car_solar.release( + self.charger, self.car.reading, self.car_now(), self.car), + RELEASE_WAIT_S) + except Exception: # noqa: BLE001 + done = False + if done is False: + self._car_release_failed = True + self.store.set(CAR_RELEASE_KEY, True) + _LOG.warning("The charger did not take 0 A before the add-on " + "stopped, so the car may still be charging: " + "CHARGER_RELEASE.") + return if not self.charger.configured() \ or getattr(self, "car_writer", None) is None \ or self.car_writer.seq is None: @@ -199,25 +292,171 @@ class CarMixin: _LOG.warning("The car could not be given its current back " "before the add-on stopped: CHARGER_RESTORE.") + async def car_release_notice(self) -> None: + """D3: after the inverters are released, one warning notice that the + car may still be charging. Bounded: the add-on is stopping.""" + if not self._car_release_failed or not self.car_solar_engaged(): + return + try: + await asyncio.wait_for(self.hass.call( + "persistent_notification", "create", + messages.car_release_failed().data()), 3.0) + except Exception: # noqa: BLE001 + _LOG.debug("The car notice could not be raised at shutdown", + exc_info=True) + + async def check_car_release(self) -> None: + """D3: the notice of a shutdown whose 0 A was not taken comes down once + Solar has confirmed its start-up 0 A.""" + w = self.car_solar + if self._car_release_failed and w.engaged and not w.fresh_start \ + and w.sent_a == 0.0 and w.taken: + self._car_release_failed = False + self.store.set(CAR_RELEASE_KEY, False) + await self.hass.call("persistent_notification", "dismiss", + messages.car_release_gone().data()) + async def car_step(self) -> None: - """One step of Manual. Reads nothing from the world (the cycle's read - did) and writes only through `carmode.ManualWriter`.""" + """One step of Manual or Solar. Reads nothing from the world (the + cycle's read did) and writes only through `carmode`'s writers.""" if not self.charger.configured(): return now = self.car_now() - await self.car_writer.step( - 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(), shadow=bool(self.shadow), - status=self.car.status(now, True), clock=self.car_now) + if self.car_mode != carmode.SOLAR: + await self.car_writer.step( + 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(), shadow=bool(self.shadow), + status=self.car.status(now, True), clock=self.car_now) + w = self.car_solar + if self.car_mode == carmode.SOLAR or w.engaged: + sun = None + if self.car_mode == carmode.SOLAR: + sun = getattr(self, "_car_sun_now", None) \ + or self.car_sun_inputs(now) + await w.step( + self.charger, self.car.reading, mode=self.car_mode, + sun=sun, + clamp=self.car_clamp(), now=now, tracker=self.car, + writing=self.car_writing(), status=self.car.status(now, True), + clock=self.car_now) + + # ------------------------------------------------------- EV-20: Solar + def car_may_charge(self, inv) -> bool: + """May this battery take the sun? On (battery modes), not refusing a + charge, not under a sign stop, its level read and under full.""" + if self.modes_on and not self.pack_mode(inv).use: + return False + refused = inv.refused if len(self.inverters) > 1 \ + else self.batt_refused + if (refused or 0) < 0 or inv.sign_wd.tripped: + return False + return inv.soc is not None and float(inv.soc) < packshare.FULL_PCT + + def car_room_w(self) -> float: + """Batteries first: the RATINGS of the batteries that may charge.""" + return float(sum(inv.rating_w() for inv in self.inverters + if self.car_may_charge(inv))) + + def car_spare_w(self, mono): + """The signed spare sun now, or None when it cannot be measured: a + missing meter or battery figure, a meter older than `stale_input_s`, + readings late past it, or a charging car whose figure is stale, stuck + or not corroborated. A paused or idle car with a fresh reading counts + as 0 W.""" + if not self.inputs_ok: + return None + stale = float(self.o.get("stale_input_s", 15)) + late = self._car_late_s + if late is not None and late >= stale: + return None + if self.p1_enabled: + # The meter's own bound (`meter_max_age_s`) may be longer than + # `stale_input_s`; a car write never comes from an older reading. + age = self.p1.age_s() + if age is None or age > stale: + return None + r = self.car.reading + if r is None or not r.available or not self.car.fresh(mono): + return None + car = self.car.car_w_trusted(mono) if r.charging is True else 0.0 + return carmode.spare_w(car, self.site_batt_w, self.grid) + + def car_sun_inputs(self, mono) -> "carmode.SunInputs": + o = self.o + spare = self.car_spare_w(mono) + late = self._car_late_s + hold = late is not None and late < float(o.get("stale_input_s", 15)) + room = self.car_room_w() + margin = carmode.solar_option(o, "ev_margin_w") + ph = str(o.get("ev_phases", chargers.EV_OPTION_DEFAULTS["ev_phases"])) + return carmode.SunInputs( + target_w=carmode.car_target_w(spare, room, margin, self.car_first), + hold=hold, auto=ph not in ("1", "3"), + start_s=60.0 * carmode.solar_option(o, "ev_start_min"), + pause_s=60.0 * carmode.solar_option(o, "ev_pause_min"), + spare_w=spare, room_w=room, margin_w=margin, first=self.car_first) + + def _car_sun_tick(self, mono) -> None: + """Solar kWh: per cycle, in Solar only, the car's power up to the sun + it may take (`spare - room` Batteries first, `spare` Car first). The + hold's battery or grid share and Manual do not count.""" + if not self.car_solar_mode(): + self._car_sun_mono = None + return + day = self.car.day + if day is not None and self.car_sun.get("day") != day: + self.car_sun = {"day": day, "kwh": 0.0} + self.store.set(CAR_SUN_KEY, dict(self.car_sun)) + self._car_sun_saved = 0.0 + last, self._car_sun_mono = self._car_sun_mono, mono + if last is None: + return + dt = min(max(mono - last, 0.0), 5.0) + p = self.car.car_w(mono) + spare = self.car_spare_w(mono) + if p is None or spare is None or dt <= 0.0: + return + sun = spare - (self.car_room_w() if self.car_first == carmode.FIRST_BATT + else 0.0) + share = min(float(p), max(0.0, sun)) + if share <= 0.0: + return + self.car_sun["kwh"] += share * dt / 3.6e6 + if round(self.car_sun["kwh"], 2) != self._car_sun_saved: + self._car_sun_saved = round(self.car_sun["kwh"], 2) + self.store.set(CAR_SUN_KEY, {"day": self.car_sun["day"], + "kwh": round(self.car_sun["kwh"], 4)}) + + def car_sun_kwh(self): + """Today's kWh from the sun, never above today's kWh; None without a + reading of today.""" + if self.car.today_kwh is None: + return None + if self.car_sun.get("day") != self.car.day: + return 0.0 + return max(0.0, min(float(self.car_sun["kwh"]), + float(self.car.today_kwh))) + + def car_amps_now(self): + """D1: the current Solar charges the car at now: the read-back, else + what Solar sent. Never Manual's stored value.""" + r = self.car.reading + if r is not None and r.available: + cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a + if cur is not None: + return float(cur) + w = self.car_solar + return float(w.sent_a or 0.0) # ------------------------------------------- the car and the peak guard def car_alarm_w(self): - """The car's power for the guard's alarm path: Manual only, fresh, not - stuck (`CarTracker.car_w_trusted`), and never above what the read-back - allows. None otherwise, and then the normal alarms stand.""" - if not self.car_manual(): + """The car's power for the guard's alarm path: Manual and (EV-20) + Solar, fresh, not stuck (`CarTracker.car_w_trusted`), and never above + what the read-back allows. None otherwise, and then the normal alarms + stand.""" + if not self.car_controlled(): return None return self.car.car_w_trusted(self.car_now()) @@ -226,13 +465,21 @@ class CarMixin: 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) + write was refused, or it ran past its own maximum. + + EV-20: Solar's own phase change the same way, and Solar's own 0 A + pause from the moment it is sent, at most `OWN_PAUSE_MAX_S`, and only + while the read-back still shows that 0 A (a car another writer starts + is never Solar's pause).""" + solar = self.car_solar_mode() + wr = getattr(self, "car_solar" if solar else "car_writer", None) + own_zero = solar and wr is not None and self._car_solar_zero(wr) 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: + and wr.zero_sent_at is None and not own_zero) \ + or wr.hold: return False r = self.car.reading - if not (self.car_manual() and self.car_writing() + if not (self.car_controlled() and self.car_writing() and r is not None and r.available and r.state != "A"): return False q = wr.seq @@ -241,7 +488,21 @@ class CarMixin: 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 + if own_zero and 0.0 <= mono - wr.zero_at <= OWN_PAUSE_MAX_S: + return True + return wr.phase_done_at is not None \ + and 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S + + def _car_solar_zero(self, wr) -> bool: + """EV-20: is Solar's own latest write a 0 A the charger took, and does + the read-back still show it? (Another writer's current ends it.)""" + if wr.zero_at is None or wr.sent_a != 0.0 or not wr.taken: + return False + r = self.car.reading + if r is None or not r.available: + return False + cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a + return cur is not None and cur <= carmode.TOL_A def _car_contradicted(self, mono) -> bool: """EV-18 (owner 2026-11-19): did the charger's energy meter answer @@ -251,7 +512,7 @@ class CarMixin: contradicts nothing.""" r = getattr(self.car, "reading", None) if r is None or not r.available or r.charging is not True \ - or not self.car_manual(): + or not self.car_controlled(): return False return (self.car.car_w(mono) is not None and not self.car.stuck(mono) and self.car.contradicted(mono)) @@ -348,6 +609,7 @@ class CarMixin: """After the guard has decided: does the car alone explain the excess? `real_proj` is the projection WITH the car, whatever the guard saw.""" mono = self.car_now() + self._car_sun_tick(mono) # EV-20: today's solar kWh w = self.car_alarm_w() # 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 @@ -538,6 +800,13 @@ class CarMixin: if not self.car_over or self._car_over_notified == self._car_session: return self._car_over_notified = self._car_session + if self.car_solar_mode(): # EV-20, D1 + _LOG.info("Solar's car charge takes this 15-minute period over " + "the peak limit: CAR_OVER_PEAK.") + await self.hass.call("persistent_notification", "create", + messages.car_over_solar( + f"{self.car_amps_now():.0f}").data()) + return _LOG.info("The car charge you set takes this 15-minute period over " "the peak limit: CAR_OVER_PEAK.") await self.hass.call("persistent_notification", "create", diff --git a/goodwe_controller/app/ctl_cycle.py b/goodwe_controller/app/ctl_cycle.py index 82c0bab..a86a6c3 100644 --- a/goodwe_controller/app/ctl_cycle.py +++ b/goodwe_controller/app/ctl_cycle.py @@ -253,6 +253,7 @@ class CycleMixin: stale_after = float(self.o.get("stale_input_s", 15)) late_s = self._readings_late(site_standing) # SAFETY-128 + self._car_late_s = late_s # EV-20: Solar holds, then the stale rule self._late_zero = late_s is not None and late_s >= stale_after # ⚠️ `any`, NOT the sole unit's. The hold exists so a single missed # poll does not become a fault; a LATCHED inverter must still reach the @@ -272,6 +273,7 @@ class CycleMixin: # this cycle's. (DECISIONS/MAIN-orchestration-archive.md) self.why_words = messages.why_waiting(bad_for) self._why_waiting_since = now - timedelta(seconds=bad_for) + self._car_hold_kick() # EV-20: Solar counts from now return if late_s is not None and late_s < stale_after and self.inputs_ok \ and (self.auto or self.shadow) \ @@ -279,6 +281,7 @@ class CycleMixin: and not (n_units > 1 and self.site_sign_wd.tripped): self.reason = f"readings late {late_s:.0f}s" # SAFETY-128: hold self.why_words = messages.why_late() + self._car_hold_kick() # EV-20: Solar holds its current return claims = [] @@ -396,8 +399,9 @@ class CycleMixin: # `_peak_proj_real` keeps the quarter as the meter will bill it, for # the car's own words. Only a fresh, trusted car reading is left out. self._peak_proj_real = self._peak_proj + # EV-20: a Solar car exactly as a Manual car. if (self._peak_proj is not None and not self.car_cover - and self.car_manual()): + and self.car_controlled()): self._peak_proj = self.car_exclude(self._peak_proj, self.car_alarm_w()) self.peak_guard = None if not self.p1_enabled else peakguard.decide( @@ -1065,7 +1069,8 @@ class CycleMixin: await self.check_price_gap() await self.check_charger() await self.check_car_over() - self.car_kick() # EV-04: Manual, in the background + await self.check_car_release() # EV-20 (D3) + self.car_kick() # EV-04/20: in the background await self.check_fixed_note() # SAFETY-31's alarm, and its boundary is the LATCH, not a number: it diff --git a/goodwe_controller/app/ctl_status.py b/goodwe_controller/app/ctl_status.py index 4dda3ec..f8a7986 100644 --- a/goodwe_controller/app/ctl_status.py +++ b/goodwe_controller/app/ctl_status.py @@ -205,7 +205,19 @@ class StatusMixin: "text": messages.row_charger_unreach( f"{brussels(self.car.bad_since_utc):%H:%M}")}) w = self.car_writer - if self.car_mode == "manual": + sw = self.car_solar + if self.car_mode == "solar" or (sw.engaged and sw.gave_up): + # EV-20: in Solar another writer stops the add-on's writes: amber. + if sw.other and self.car_mode == "solar": + out.append({"ok": False, "warn": True, "id": "charger_other", + "text": messages.row_charger_other_solar()}) + if sw.gave_up: + out.append({"ok": False, "warn": True, "id": "charger_refused", + "text": messages.row_charger_refused()}) + if sw.phases_gave_up and self.car_mode == "solar": + out.append({"ok": False, "warn": True, "id": "charger_phases", + "text": messages.row_charger_phases()}) + elif self.car_mode == "manual": # EV-04: in Manual the add-on's own writes are not "another # writer"; its own detector (a read-back that differs from the # last write for 30 s) says so, in grey. @@ -230,7 +242,10 @@ class StatusMixin: "text": messages.row_charger_error(r.error)}) if self.car_over: out.append({"ok": True, "warn": True, "id": "car_over", - "text": messages.row_car_over()}) + "text": (messages.row_car_over_solar( + f"{self.car_amps_now():.0f}") + if self.car_solar_mode() + else messages.row_car_over())}) return out def car_values(self) -> dict: @@ -250,6 +265,9 @@ class StatusMixin: or r.power_w is None else round(r.power_w, 1)), "car_today_kwh": (PAYLOAD_NONE if self.car.today_kwh is None else round(self.car.today_kwh, 3)), + # EV-20: today's kWh from the sun (Solar only adds to it) + "car_today_solar_kwh": (PAYLOAD_NONE if self.car_sun_kwh() is None + else round(self.car_sun_kwh(), 3)), } # -- UI ------------------------------------------------------------------ @@ -922,7 +940,7 @@ class StatusMixin: now = datetime.now(timezone.utc) if what in ("pack_use", "pack_mode", "pack_sell"): return self._pack_action(what, unit, value, now) - if what in ("car_mode", "car_current", "car_phases"): + if what in ("car_mode", "car_current", "car_phases", "car_sun_first"): return self._car_action(what, value, now) if what == "auto_toggle": self.auto = not self.auto diff --git a/goodwe_controller/app/homeview.py b/goodwe_controller/app/homeview.py index 84c0fdd..7f8b1af 100644 --- a/goodwe_controller/app/homeview.py +++ b/goodwe_controller/app/homeview.py @@ -1134,7 +1134,7 @@ def month_peak(c, now): ceiling = pg.ceiling_w or limit_w real = getattr(c, "_peak_proj_real", None) if getattr(c, "car_enabled", False) and c.charger.configured() \ - and not c.car_cover and c.car_manual() and real is not None \ + and not c.car_cover and c.car_controlled() and real is not None \ and getattr(real, "block_start", None) is not None: # EV-04, decision 1 off: the guard's own projection leaves the car # out; the period as the meter will bill it does not. @@ -1374,6 +1374,54 @@ def _car_manual_why(c, key): return _t("car.why.manual_set", a=a, phases=car_phases_word(c.car_n)) +def _car_solar_why(c, key): + """EV-20: the Why of Solar, from what the writer and its plan did this + cycle. Plan lines: two sentences of at most 12 words.""" + w = c.car_solar + p = w.plan + o = getattr(c, "o", {}) or {} + if c.car_over: # D1 + return _t("car.why.solar_over", a=f"{c.car_amps_now():.0f}") + if w.hold: + return _t("car.why.solar_other") + if w.zero_owed: + # The way-out 0 A is not taken yet: never "paused". + return _t("car.why.solar_zero_failed" if w.gave_up + else "car.why.solar_zeroing") + if w.gave_up: + return _t("car.why.solar_refused") + if c.shadow: + a, n = w.would if w.would is not None else (0.0, p.n) + if a and a >= 6: + return _t("car.why.manual_would", a=f"{float(a):.0f}", + phases=car_phases_word(n)) + return _t("car.why.solar_would") + if not c.auto or not c.car_writing(): + return _t("car.why.solar_stopped") + if w.fault in ("error", "stuck"): + return _t("car.why.solar_" + w.fault) + if key == "none": + return _t("car.why.none") + why = p.why + sun = w.sun + if why == "running": + if sun is None or sun.spare_w is None: + return _t("car.why.solar_unknown") + if sun.first == carmode.FIRST_CAR: + return _t("car.why.solar_car", + kw=_kw(max(0.0, sun.spare_w - sun.margin_w))) + return _t("car.why.solar_batt", + kw=_kw(max(0.0, sun.spare_w - sun.room_w - sun.margin_w))) + if why == "hold": + return _t("car.why.solar_hold", s=f"{carmode.solar_option(o, 'ev_pause_min'):.0f}") + if why == "unknown": + return _t("car.why.solar_unknown") + s = f"{carmode.solar_option(o, 'ev_start_min'):.0f}" + if why == "start": + return _t("car.why.solar_start", s=s) + return _t("car.why.solar_paused", s=s) + + def car_block(c, now): """The Car card for `/status`, or None when no charger is switched on (the page then draws nothing, as before).""" @@ -1386,12 +1434,21 @@ def car_block(c, now): good = c.car.last_good fresh = configured and c.car.fresh(mono) today = None - if configured and c.car.today_kwh is not None: - today = _t("car.today", kwh=_kwh(c.car.today_kwh)) mode = getattr(c, "car_mode", "off") if configured else "off" + if configured and c.car.today_kwh is not None: + sun = c.car_sun_kwh() if mode == "solar" else None + today = (_t("car.today_sun", kwh=_kwh(c.car.today_kwh), + sun=_kwh(sun)) if sun is not None + else _t("car.today", kwh=_kwh(c.car.today_kwh))) why = _car_why(key, c, good) if mode == "manual" and key in ("charging", "waiting", "none", "full"): why = _car_manual_why(c, key) + if mode == "solar" and key in ("charging", "waiting", "none", "full", + "fault"): + why = _car_solar_why(c, key) + # EV-20: a car Solar holds at 0 A is waiting for the sun. + if key == "waiting" and c.car_solar.plan.a <= 0.0: + key = "paused" out = { "state": key or "wait", "chip": car_state_word(key), @@ -1404,11 +1461,14 @@ def car_block(c, now): else round(float(r.power_w), 1)), } if configured: - # EV-04: what the page can set. Off and Manual only (Solar and Night - # are later cards, so they are not offered). + # EV-04: what the page can set. EV-20 adds Solar and where its spare + # sun goes first (Night is a later card, so it is not offered). clamp = c.car_clamp() hi = int(clamp) if clamp is not None and clamp >= 6 else 6 - out["modes"] = ["off", "manual"] + out["modes"] = list(carmode.MODES) + out["first"] = {"value": getattr(c, "car_first", + carmode.DEFAULT_FIRST), + "choices": list(carmode.FIRSTS)} out["current"] = {"value": round(float(c.car_a)), "min": 6, "max": hi} out["phases"] = {"value": c.car_n, @@ -1928,12 +1988,13 @@ def _samples() -> list: words["car"]["big"]] out += [("plan", _t("car.why." + k, a="10", brand="Alfen", kw="8.6 kW", pct="20 %", phases=car_phases_word(3), - real=car_phases_word(1))) + real=car_phases_word(1), s="5")) for k in words["car"]["why"]] out += [("plan", _t("peak.car", kw="12.1 kW", car="11.0 kW", cov="8.6 kW")), ("plan", _t("peak.set_by_car", t="19:45"))] out += [("plan", _t("car.today", kwh="14.2 kWh")), + ("plan", _t("car.today_sun", kwh="14.2 kWh", sun="3.1 kWh")), ("plan", "11.0 kW · 16 A · " + _t("car.phase_many", n=3))] out += [("plan", line_no_trade(k)) for k in ("not_covered", "no_prices", "peak", "not_firm", "not_worth", diff --git a/goodwe_controller/app/main.py b/goodwe_controller/app/main.py index 8b622c9..e9f11d6 100644 --- a/goodwe_controller/app/main.py +++ b/goodwe_controller/app/main.py @@ -1040,8 +1040,17 @@ class Controller(InputsMixin, WritesMixin, TradeMixin, CycleMixin, AlarmsMixin, self.stopping = True _LOG.info(handback.log_shutdown(handback.current()) or "shutting down - commanding 0 W on every inverter") + # EV-20 (D3): Solar's fail state is 0 A, and it goes out BEFORE the + # inverters go to 0 W, bounded by `ctl_car.RELEASE_WAIT_S`. Manual + # keeps EV-04's order: the inverters first, then undo a phase change. + solar = self.car_solar_engaged() + if solar: + await self.car_shutdown() await self.command_site_release() - await self.car_shutdown() # EV-04: undo a phase change half way + if solar: + await self.car_release_notice() + else: + await self.car_shutdown() # EV-04: undo a phase change half way self.mqtt.close() diff --git a/goodwe_controller/app/messages.py b/goodwe_controller/app/messages.py index 33ae65e..c1b971a 100644 --- a/goodwe_controller/app/messages.py +++ b/goodwe_controller/app/messages.py @@ -190,6 +190,8 @@ T_CHARGER_UNREACH = "Charger not reachable" T_CHARGER_UNREACH_NL = "Laadpaal onbereikbaar" T_CAR_OVER = "Car over the peak limit" T_CAR_OVER_NL = "Auto boven de piekgrens" +T_CAR_RELEASE = "Car may still be charging" +T_CAR_RELEASE_NL = "Auto laadt mogelijk nog" T_NO_PRICES = "No prices" T_NO_PRICES_NL = "Prijzen ontbreken" @@ -204,6 +206,7 @@ ID_MAINT_FAILED = "goodwe_maint_failed_{slug}" ID_NO_PRICES = "goodwe_no_prices" ID_CHARGER_UNREACH = "goodwe_charger_unreachable" ID_CAR_OVER = "goodwe_car_over" +ID_CAR_RELEASE = "goodwe_car_release" # PRICE-01: an earlier build raised a card with this id. Nothing raises it now; # the add-on only dismisses it at start. OLD_FIXED_CARD_ID = "goodwe_fixed_tariff_unused" @@ -518,6 +521,44 @@ def row_car_over() -> str: "piekgrens.") +def _solar_over(a_text): + # D1's words, in the one sentence STYLE.md allows a grey note and row; the + # card's Why has them as two (`car.why.solar_over`). + return (f"Solar charges the car at {a_text} A, which sets the peak.", + f"Zon laadt de auto met {a_text} A, wat de piek bepaalt.") + + +def car_over_solar(a_text) -> Notice: + """EV-20 (D1): in Solar the car's charge takes the 15-minute period over + the peak limit and the batteries cannot hold it. Grey, once per charging + session, as Manual's; `a_text` is Solar's current at that moment.""" + en, nl = _solar_over(a_text) + return Notice(ID_CAR_OVER, INFO, T_CAR_OVER, en, + body_nl=f"{T_CAR_OVER_NL}. {nl}") + + +def row_car_over_solar(a_text) -> str: + """EV-20 (D1): the grey row while Solar's charge is over the peak limit.""" + return Bi(*_solar_over(a_text)) + + +def car_release_failed() -> Notice: + """EV-20 (D3): at shutdown in Solar the charger did not take 0 A, and the + inverters were released on time anyway. Taken down when the next start's + 0 A is taken.""" + en = ("The add-on stopped before the charger took 0 A, so check the " + "charger.") + nl = ("De add-on stopte voor de laadpaal 0 A overnam, dus controleer de " + "laadpaal.") + return Notice(ID_CAR_RELEASE, WARNING, T_CAR_RELEASE, en, + body_nl=f"{T_CAR_RELEASE_NL}. {nl}") + + +def car_release_gone() -> Dismiss: + """EV-20 (D3): takes the 'Car may still be charging' notice down.""" + return Dismiss(ID_CAR_RELEASE) + + def row_charger_other() -> str: """EV-04: the grey row, in Manual, while something else sets the current.""" return Bi("Something else changes the charger, so the add-on writes " @@ -526,6 +567,15 @@ def row_charger_other() -> str: "tot u iets wijzigt.") +def row_charger_other_solar() -> str: + """EV-20: the amber row, in Solar, while something else sets the current: + Solar writes nothing until you press Solar or the read-back matches.""" + return Bi("Something else changes the charger, so Solar writes nothing " + "until you press it.", + "Iets anders wijzigt de laadpaal, dus Zon schrijft niets tot u " + "erop drukt.") + + def row_charger_stuck() -> str: """EV-04: the amber row when the charger's reading does not move.""" return Bi("The charger reading may be stuck, so check the charger.", @@ -1484,6 +1534,7 @@ HINTS = { "car_mode": "Car mode set", "car_current": "Car current set", "car_phases": "Car phases set", + "car_sun_first": "Where spare sun goes first set", "settings_saved": "Settings saved, they apply after a restart", "restart_requested": "Restart requested from the settings page", "setup_only": "In setup, nothing is sent to any inverter", @@ -1780,6 +1831,8 @@ def status_samples() -> list: ("row_charger_writer", GREEN, row_charger_writer()), ("row_car_over", GREEN, row_car_over()), ("row_charger_other", GREEN, row_charger_other()), + ("row_charger_other_solar", AMBER, row_charger_other_solar()), + ("row_car_over_solar", GREEN, row_car_over_solar("8")), ("row_charger_error", GREEN, row_charger_error("Socket error")), ("row_charger_stuck", AMBER, row_charger_stuck()), ("row_charger_refused", AMBER, row_charger_refused()), @@ -1822,6 +1875,8 @@ def samples() -> list: no_prices(), charger_unreachable("09:12"), car_over("16"), + car_over_solar("8"), + car_release_failed(), ] @@ -1890,6 +1945,9 @@ LABELS = { "ev_max_a": "Charger limit", "ev_batt_cover": "Batteries help with the peak", "ev_mode_start": "Mode after a restart", + "ev_margin_w": "Sun kept back", + "ev_pause_min": "Pause after", + "ev_start_min": "Start after", "ev_phases": "Phases", } @@ -1976,6 +2034,9 @@ LABELS_NL = { "ev_max_a": "Laadpaalgrens", "ev_batt_cover": "Batterijen helpen met de piek", "ev_mode_start": "Modus na een herstart", + "ev_margin_w": "Zon achtergehouden", + "ev_pause_min": "Pauzeren na", + "ev_start_min": "Starten na", "ev_phases": "Fasen", } # The inverter list shows two of them under a shorter name. diff --git a/goodwe_controller/app/mqtt.py b/goodwe_controller/app/mqtt.py index be471be..4d3478a 100644 --- a/goodwe_controller/app/mqtt.py +++ b/goodwe_controller/app/mqtt.py @@ -144,6 +144,8 @@ OPTIONAL_SENSORS = [ ("car_power", "goodwe_car_power", "Car power", "W", "power", "measurement", "mdi:car-electric"), ("car_state", "goodwe_car_state", "Car state", None, None, None, "mdi:ev-station"), ("car_today_kwh", "goodwe_car_today_kwh", "Car energy today", "kWh", "energy", "total_increasing", "mdi:ev-station"), + # EV-20: what of today's charge came from the sun (Solar mode only). + ("car_today_solar_kwh", "goodwe_car_today_solar_kwh", "Car solar energy today", "kWh", "energy", "total_increasing", "mdi:solar-power"), ] # ⚠️ HA's OWN "this sensor has no value" PAYLOAD, and the one place this add-on @@ -200,7 +202,8 @@ def optional_keys(opts: dict) -> tuple: from . import chargers as _ch # EV-03: same reason out = ("pv",) if _pv.entities(opts) else () if _ch.census_entity(opts): - out += ("car_power", "car_state", "car_today_kwh") + out += ("car_power", "car_state", "car_today_kwh", + "car_today_solar_kwh") return out @@ -524,25 +527,32 @@ def mode_payloads(units, modes) -> list: # --- EV-04: the car's mode, current and phases, as HA entities ---------------- # Announced only with a charger switched on, after every other row. A command # goes through Controller.handle_action(); a retained one is dropped. -CAR_MODE_LABELS = {"off": "Off", "manual": "Manual"} # English, pinned +CAR_MODE_LABELS = {"off": "Off", "manual": "Manual", # English, pinned + "solar": "Solar"} # EV-20 +# EV-20: where spare sun goes first; mirrors carmode.FIRST_LABELS (this module +# imports nothing from the package; test_ev20.py checks the two agree). +CAR_FIRST_LABELS = {"batteries": "Batteries", "car": "Car"} CAR_MODES = tuple(CAR_MODE_LABELS) CAR_CONFIGS_KEY = "mqtt_car_configs" CAR_MIN_A = 6 -_CAR_CMD_RE = re.compile(rf"{BASE}/car/(mode|current|phases)/set") +_CAR_CMD_RE = re.compile(rf"{BASE}/car/(mode|current|phases|sun_first)/set") _CAR_CONFIG_RE = re.compile( - rf"homeassistant/(select|number)/{BASE}_car_(mode|current|phases)/config") + rf"homeassistant/(select|number)/{BASE}_car_(mode|current|phases|sun_first)" + rf"/config") # (key, component, name, icon) CAR_ENTITIES = [ ("mode", "select", "Car mode", "mdi:car-electric"), ("current", "number", "Car current", "mdi:current-ac"), ("phases", "select", "Car phases", "mdi:sine-wave"), + ("sun_first", "select", "Car spare sun first", "mdi:solar-power"), # EV-20 ] def car_payloads(car) -> list: """The `(topic, payload)` for `select.goodwe_car_mode`, - `number.goodwe_car_current` and `select.goodwe_car_phases`. `car` is - `(max_a, phases)`; empty when it is None.""" + `number.goodwe_car_current`, `select.goodwe_car_phases` and (EV-20) + `select.goodwe_car_sun_first`. `car` is `(max_a, phases)`; empty when it + is None.""" if not car: return [] max_a, phases = car @@ -560,6 +570,8 @@ def car_payloads(car) -> list: cfg["options"] = list(CAR_MODE_LABELS.values()) elif key == "phases": cfg["options"] = [str(n) for n in phases] + elif key == "sun_first": + cfg["options"] = list(CAR_FIRST_LABELS.values()) else: cfg.update({"min": CAR_MIN_A, "max": int(max_a), "step": 1, "unit_of_measurement": "A", "device_class": "current", @@ -584,7 +596,8 @@ def car_configs(car, stored) -> tuple: def parse_car_command(topic, payload, retained): """`(action, value, reject)` for one message on a car command topic. - `action` is `car_mode`, `car_current` or `car_phases`. A value that is + `action` is `car_mode`, `car_current`, `car_phases` or (EV-20) + `car_sun_first`. A value that is none of the entity's own is None (the action then refuses it).""" m = _CAR_CMD_RE.fullmatch(topic) if isinstance(topic, str) else None if m is None: @@ -607,6 +620,9 @@ def parse_car_command(topic, payload, retained): None) elif key == "phases": value = {"1": 1, "3": 3}.get(text) + elif key == "sun_first": + value = next((k for k, v in CAR_FIRST_LABELS.items() if v == text), + None) else: try: f = float(text) diff --git a/goodwe_controller/app/static/app.js b/goodwe_controller/app/static/app.js index 82bae51..9efe6ee 100644 --- a/goodwe_controller/app/static/app.js +++ b/goodwe_controller/app/static/app.js @@ -160,8 +160,9 @@ $("#car-why").textContent = c.why; renderCarControls(c); } - // EV-04: Off and Manual. The mode and the phases send at once; the current - // sends after two seconds of rest. A slider being dragged is left alone. + // EV-04: Off and Manual; EV-20: Solar and where its spare sun goes first. + // The mode, the phases and the choice send at once; the current sends after + // two seconds of rest. A slider being dragged is left alone. let carTouch = 0, carTimer = null, carBusy = false; async function carAct(what, value) { if (carBusy) return; @@ -182,6 +183,13 @@ type: "button", role: "radio", "aria-checked": String(c.mode === m), onclick: () => carAct("car_mode", m) }, t("car.mode_" + m)))); $("#car-help").textContent = t("car.help_" + c.mode + ".description") || ""; + const sol = c.mode === "solar" && !!c.first; + $("#car-solar").hidden = !sol; + if (sol) { + $("#car-first").replaceChildren(...c.first.choices.map((f) => h("button", { + type: "button", role: "radio", "aria-checked": String(c.first.value === f), + onclick: () => carAct("car_sun_first", f) }, t("car.first_" + f)))); + } const on = c.mode === "manual" && !!c.current; $("#car-manual").hidden = !on; if (!on) return; diff --git a/goodwe_controller/app/static/index.html b/goodwe_controller/app/static/index.html index fa2a6fa..78dca29 100644 --- a/goodwe_controller/app/static/index.html +++ b/goodwe_controller/app/static/index.html @@ -52,6 +52,11 @@
+
diff --git a/goodwe_controller/app/ui_text/en.json b/goodwe_controller/app/ui_text/en.json index ea2a878..20f63e5 100644 --- a/goodwe_controller/app/ui_text/en.json +++ b/goodwe_controller/app/ui_text/en.json @@ -91,7 +91,7 @@ "loading": "Loading the forecast." }, "peak": {"name": "Peak limit", "this_month": "This month's peak", "limit": "Limit", "none": "None recorded yet", "unreadable": "Cannot be read now"}, - "car": {"name": "Car", "mode": "Mode", "mode_off": "Off", "mode_manual": "Manual", "help_off": {"description": "The add-on leaves the charger alone."}, "help_manual": {"description": "Charges at the current you set, whatever the sun or the peak limit do."}, "current": "Current", "phases": "Phases", "phases_1": "1 phase", "phases_3": "3 phases", "why": "Why"}, + "car": {"name": "Car", "mode": "Mode", "mode_off": "Off", "mode_manual": "Manual", "help_off": {"description": "The add-on leaves the charger alone."}, "help_manual": {"description": "Charges at the current you set, whatever the sun or the peak limit do."}, "current": "Current", "phases": "Phases", "phases_1": "1 phase", "phases_3": "3 phases", "why": "Why", "mode_solar": "Solar", "help_solar": {"description": "Charges only from spare sun and pauses when there is too little."}, "first": "Spare sun goes first to", "first_batteries": "Batteries", "first_car": "Car", "first_help": {"description": "Batteries: the car gets the sun the batteries cannot take."}}, "attention": {"name": "Needs attention", "nothing": "Nothing to look at", "to_look": "to look at", "details": "Details", "alarm": "Alarm", "warning": "Warning", "info": "Info"}, "control": {"name": "Control", "stop": "Stop control", "start": "Start control", "maint_start": "Start a battery cycle now", "maint_abort": "Stop the battery cycle", "docs": "Add-on documentation", "more": "More actions"}, "details": {"name": "Details for installers", "rows": "Status rows", "checks": "Checks", "event": "Last event"}, @@ -302,11 +302,12 @@ "warning": "See Needs attention below." }, "car": { - "state": {"charging": "Charging", "waiting": "Connected, waiting", "none": "No car connected", "full": "Car is full", "unreach": "Charger not reachable", "setup": "Charger not set up", "fault": "Charger fault", "wait": "No reading yet"}, - "big": {"waiting": "Connected, not charging.", "none": "Nothing to charge.", "full": "The car is full.", "seen": "Last seen at {t}.", "no_reading": "No reading.", "setup": "Not set up.", "fault": "The charger reports a fault.", "wait": "No reading yet."}, + "state": {"charging": "Charging", "waiting": "Connected, waiting", "none": "No car connected", "full": "Car is full", "unreach": "Charger not reachable", "setup": "Charger not set up", "fault": "Charger fault", "wait": "No reading yet", "paused": "Waiting for sun"}, + "big": {"waiting": "Connected, not charging.", "none": "Nothing to charge.", "full": "The car is full.", "seen": "Last seen at {t}.", "no_reading": "No reading.", "setup": "Not set up.", "fault": "The charger reports a fault.", "wait": "No reading yet.", "paused": "Waiting for spare sun."}, "phase_one": "1 phase", "phase_many": "{n} phases", "today": "{kwh} charged today.", + "today_sun": "{kwh} charged today, {sun} from the sun.", "why": { "charging": "The charger is charging the car. The add-on leaves it alone.", "waiting": "The car is connected and not charging. The add-on leaves the charger alone.", @@ -332,7 +333,22 @@ "manual_shadow_over": "Shadow mode: the add-on would set {a} A, {phases}. This charge would set the peak.", "manual_phases": "You set {a} A, {phases}. The charger stays on {real}.", "manual_other": "Something else set the charger. The add-on leaves it until you change something.", - "manual_blocked": "The phases change once per 10 minutes at most. This waits." + "manual_blocked": "The phases change once per 10 minutes at most. This waits.", + "solar_batt": "Batteries first. The car gets the {kw} of sun they cannot take.", + "solar_car": "Car first: the car takes {kw} of spare sun. The batteries get the rest.", + "solar_paused": "Too little spare sun for 6 A. The car starts after {s} minutes of enough sun.", + "solar_hold": "Too little spare sun, so the car holds 6 A. It pauses after {s} minutes.", + "solar_start": "There is enough spare sun now. The car starts after {s} minutes of it.", + "solar_unknown": "The spare sun cannot be measured now. The car pauses if this lasts.", + "solar_would": "Shadow mode: the add-on would keep the car paused.", + "solar_stopped": "Control is stopped, so the add-on set the car to 0 A.", + "solar_error": "The charger reports an error. The car is set to 0 A.", + "solar_stuck": "The charger reading may be stuck. The car is set to 0 A.", + "solar_other": "Something else changes the charger. Press Solar to give it back.", + "solar_zeroing": "The charger has not taken 0 A yet. The add-on tries again.", + "solar_zero_failed": "The charger did not take 0 A. Check it at the charger.", + "solar_refused": "The charger did not take the current. Press Solar to try again.", + "solar_over": "Solar charges the car at {a} A. This sets the peak." } }, "peak": { diff --git a/goodwe_controller/app/ui_text/nl.json b/goodwe_controller/app/ui_text/nl.json index 62c123f..176432c 100644 --- a/goodwe_controller/app/ui_text/nl.json +++ b/goodwe_controller/app/ui_text/nl.json @@ -88,7 +88,7 @@ "loading": "De prognose wordt geladen." }, "peak": {"name": "Piekgrens", "this_month": "Piek van deze maand", "limit": "Grens", "none": "Nog niets gemeten", "unreadable": "Nu niet leesbaar"}, - "car": {"name": "Auto", "mode": "Modus", "mode_off": "Uit", "mode_manual": "Handmatig", "help_off": {"description": "De add-on laat de laadpaal met rust."}, "help_manual": {"description": "Laadt met de stroom die u instelt, wat de zon of de piekgrens ook doen."}, "current": "Stroom", "phases": "Fasen", "phases_1": "1 fase", "phases_3": "3 fasen", "why": "Waarom"}, + "car": {"name": "Auto", "mode": "Modus", "mode_off": "Uit", "mode_manual": "Handmatig", "help_off": {"description": "De add-on laat de laadpaal met rust."}, "help_manual": {"description": "Laadt met de stroom die u instelt, wat de zon of de piekgrens ook doen."}, "current": "Stroom", "phases": "Fasen", "phases_1": "1 fase", "phases_3": "3 fasen", "why": "Waarom", "mode_solar": "Zon", "help_solar": {"description": "Laadt alleen met zonne-overschot en pauzeert als er te weinig is."}, "first": "Zonne-overschot gaat eerst naar", "first_batteries": "Batterijen", "first_car": "Auto", "first_help": {"description": "Batterijen: de auto krijgt de zon die de batterijen niet kunnen opnemen."}}, "attention": {"name": "Vraagt aandacht", "nothing": "Niets om na te kijken", "to_look": "na te kijken", "details": "Details", "alarm": "Alarm", "warning": "Waarschuwing", "info": "Info"}, "control": {"name": "Regeling", "stop": "Regeling stoppen", "start": "Regeling starten", "maint_start": "Nu een batterijcyclus starten", "maint_abort": "Batterijcyclus stoppen", "docs": "Documentatie van de add-on", "more": "Meer acties"}, "details": {"name": "Details voor installateurs", "rows": "Statusregels", "checks": "Controles", "event": "Laatste gebeurtenis"}, @@ -256,11 +256,12 @@ "pill": {"running": "Actief", "shadow": "Schaduwmodus", "stopped": "Gestopt", "alarm": "Heeft u nu nodig", "waiting": "Wacht op Home Assistant", "warning": "Actief, met een waarschuwing"}, "banner_sub": {"running": "De batterijen volgen het plan hieronder.", "shadow": "De plannen hieronder tonen wat de add-on zou doen.", "stopped": "Start de regeling hieronder als u klaar bent.", "alarm": "Zie Vraagt aandacht hieronder voor wat u moet doen.", "waiting": "De regeling gaat vanzelf verder zodra Home Assistant antwoordt.", "warning": "Zie Vraagt aandacht hieronder."}, "car": { - "state": {"charging": "Laadt", "waiting": "Aangesloten, wacht", "none": "Geen auto aangesloten", "full": "Auto is vol", "unreach": "Laadpaal onbereikbaar", "setup": "Laadpaal niet ingesteld", "fault": "Laadpaalstoring", "wait": "Nog geen meting"}, - "big": {"waiting": "Aangesloten, laadt niet.", "none": "Niets te laden.", "full": "De auto is vol.", "seen": "Laatst gezien om {t}.", "no_reading": "Geen meting.", "setup": "Niet ingesteld.", "fault": "De laadpaal meldt een storing.", "wait": "Nog geen meting."}, + "state": {"charging": "Laadt", "waiting": "Aangesloten, wacht", "none": "Geen auto aangesloten", "full": "Auto is vol", "unreach": "Laadpaal onbereikbaar", "setup": "Laadpaal niet ingesteld", "fault": "Laadpaalstoring", "wait": "Nog geen meting", "paused": "Wacht op zon"}, + "big": {"waiting": "Aangesloten, laadt niet.", "none": "Niets te laden.", "full": "De auto is vol.", "seen": "Laatst gezien om {t}.", "no_reading": "Geen meting.", "setup": "Niet ingesteld.", "fault": "De laadpaal meldt een storing.", "wait": "Nog geen meting.", "paused": "Wacht op zonne-overschot."}, "phase_one": "1 fase", "phase_many": "{n} fasen", "today": "Vandaag {kwh} geladen.", + "today_sun": "Vandaag {kwh} geladen, {sun} van de zon.", "why": { "charging": "De laadpaal laadt de auto. De add-on laat haar met rust.", "waiting": "De auto is aangesloten en laadt niet. De add-on laat de laadpaal met rust.", @@ -286,7 +287,22 @@ "manual_shadow_over": "Schaduwmodus: de add-on zou {a} A instellen, {phases}. Deze lading zou de piek bepalen.", "manual_phases": "U stelde {a} A in, {phases}. De laadpaal blijft op {real}.", "manual_other": "Iets anders heeft de laadpaal ingesteld. De add-on laat dit zo tot u iets wijzigt.", - "manual_blocked": "De fasen wisselen hooguit eens per 10 minuten. Dit wacht." + "manual_blocked": "De fasen wisselen hooguit eens per 10 minuten. Dit wacht.", + "solar_batt": "Eerst de batterijen. De auto krijgt de {kw} zon die ze niet opnemen.", + "solar_car": "Eerst de auto: die neemt {kw} zonne-overschot. De batterijen krijgen de rest.", + "solar_paused": "Te weinig zonne-overschot voor 6 A. De auto start na {s} minuten genoeg zon.", + "solar_hold": "Te weinig zonne-overschot, dus de auto houdt 6 A. Ze pauzeert na {s} minuten.", + "solar_start": "Er is nu genoeg zonne-overschot. De auto start na {s} minuten daarvan.", + "solar_unknown": "Het zonne-overschot is nu niet te meten. De auto pauzeert als dit duurt.", + "solar_would": "Schaduwmodus: de add-on zou de auto gepauzeerd houden.", + "solar_stopped": "De regeling is gestopt, dus de auto staat op 0 A.", + "solar_error": "De laadpaal meldt een fout. De auto staat op 0 A.", + "solar_stuck": "De meting van de laadpaal staat mogelijk vast. De auto staat op 0 A.", + "solar_other": "Iets anders wijzigt de laadpaal. Druk op Zon om ze terug te geven.", + "solar_zeroing": "De laadpaal nam 0 A nog niet over. De add-on probeert opnieuw.", + "solar_zero_failed": "De laadpaal nam 0 A niet over. Controleer ze aan de laadpaal.", + "solar_refused": "De laadpaal nam de stroom niet over. Druk op Zon om opnieuw te proberen.", + "solar_over": "Zon laadt de auto met {a} A. Dit bepaalt de piek." } }, "peak": { diff --git a/goodwe_controller/app/uilayout.py b/goodwe_controller/app/uilayout.py index 0bb138a..bedcbc5 100644 --- a/goodwe_controller/app/uilayout.py +++ b/goodwe_controller/app/uilayout.py @@ -234,6 +234,9 @@ GROUPS = ( Field("ev_phases", SEGMENTED, simple=True, show=_CAR), Field("ev_batt_cover", TOGGLE, simple=True, show=_CAR), Field("ev_mode_start", SEGMENTED, simple=True, show=_CAR), + Field("ev_margin_w", SLIDER, "W", step=10, show=_CAR), + Field("ev_start_min", SLIDER, "min", show=_CAR), + Field("ev_pause_min", SLIDER, "min", show=_CAR), )), )), Group("maintenance", ( diff --git a/goodwe_controller/app/validate.py b/goodwe_controller/app/validate.py index 58833ac..4a0f2c5 100644 --- a/goodwe_controller/app/validate.py +++ b/goodwe_controller/app/validate.py @@ -677,6 +677,19 @@ def _charger_problems(opts: dict, writers: dict) -> list[str]: out.append(f"{S('ev_charger')} is {messages.shown(raw)}. Choose " f"{', '.join(chargers.SELECTABLE)}.") return out + # EV-20: Solar's sun kept back and its two dwells, each in its range (as + # config.yaml's schema holds them, with or without a charger). + for key, (lo, hi) in chargers.SOLAR_RANGES.items(): + raw = opts.get(key, chargers.EV_OPTION_DEFAULTS[key]) + try: + v = float(raw) + ok = not isinstance(raw, bool) and v == v and v == int(v) \ + and lo <= v <= hi + except (TypeError, ValueError, OverflowError): + ok = False + if not ok: + out.append(f"{S(key)} is {messages.shown(raw)}. Set it from {lo} " + f"to {hi}.") if chargers.mode_of(opts) == chargers.OFF: return out ph = opts.get("ev_phases", chargers.EV_OPTION_DEFAULTS["ev_phases"]) diff --git a/goodwe_controller/app/web.py b/goodwe_controller/app/web.py index 3a17a94..81b4745 100644 --- a/goodwe_controller/app/web.py +++ b/goodwe_controller/app/web.py @@ -62,7 +62,7 @@ _LOG = logging.getLogger("goodwe.web") # OPT-11: the per-battery actions, which name a battery and a value. PACK_ACTIONS = ("pack_use", "pack_mode", "pack_sell") -CAR_ACTIONS = ("car_mode", "car_current", "car_phases") +CAR_ACTIONS = ("car_mode", "car_current", "car_phases", "car_sun_first") # MAINT-11: start or stop one battery's maintenance cycle (the unit is optional). MAINT_ACTIONS = ("maint_start", "maint_abort") diff --git a/goodwe_controller/config.yaml b/goodwe_controller/config.yaml index 90cae0d..70daeab 100644 --- a/goodwe_controller/config.yaml +++ b/goodwe_controller/config.yaml @@ -873,20 +873,25 @@ options: shadow_mode: "auto" # ========================================================================== - # CAR CHARGER (EV-03 reads it, EV-04 adds Manual) + # CAR CHARGER (EV-03 reads it, EV-04 adds Manual, EV-20 Solar) # ========================================================================== # `off` is the shipped value and means NO CHANGE AT ALL: nothing is read, # shown or announced, and the House tile and the house profile are as before. # `alfen_ha` drives the charger through its Home Assistant integration. The - # mode (Off or Manual), the current and the phases are runtime state in the - # store, not options. `ev_batt_cover`: the batteries help with the peak while - # the car charges. `ev_mode_start`: the mode after a restart. + # mode (Off, Manual or Solar), the current, the phases and where spare sun + # goes first are runtime state in the store, not options. `ev_batt_cover`: + # the batteries help with the peak while the car charges. `ev_mode_start`: + # the mode after a restart. Solar: `ev_margin_w` sun kept back, and the car + # starts after `ev_start_min` of enough sun and pauses after `ev_pause_min`. ev_charger: "off" ev_current_entity: "" ev_max_a: 16 ev_phases: "auto" ev_batt_cover: true ev_mode_start: "keep" + ev_margin_w: 100 + ev_start_min: 2 + ev_pause_min: 5 # ========================================================================== # ADVANCED - the control law and diagnostics @@ -1266,7 +1271,7 @@ schema: shadow_mode: list(auto|on|off) # ========================================================================== - # CAR CHARGER (EV-03 reads it, EV-04 adds Manual) + # CAR CHARGER (EV-03 reads it, EV-04 adds Manual, EV-20 Solar) # ========================================================================== # `ev_current_entity` is the charger's current setpoint; the other entities # are found from its name. `ev_max_a` may not exceed the charger's own station @@ -1277,6 +1282,9 @@ schema: ev_phases: list(1|3|auto) ev_batt_cover: bool ev_mode_start: list(keep|off) + ev_margin_w: int(0,1000) + ev_start_min: int(1,30) + ev_pause_min: int(1,30) # ========================================================================== # ADVANCED - the control law and diagnostics diff --git a/goodwe_controller/test_ev03.py b/goodwe_controller/test_ev03.py index 905ece4..71c2bcc 100644 --- a/goodwe_controller/test_ev03.py +++ b/goodwe_controller/test_ev03.py @@ -905,16 +905,18 @@ check("it stays for an hour and then goes", # --------------------------------------------------------------------------- # print("\n9. THE MQTT SENSORS") # --------------------------------------------------------------------------- # -check("the three car sensors are announced only with a charger on", +check("the car sensors (EV-20: four, with today's solar kWh) are announced " + "only with a charger on", mqtt.optional_keys(CAR) == ("pv", "car_power", "car_state", - "car_today_kwh") + "car_today_kwh", "car_today_solar_kwh") and mqtt.optional_keys(BASE) == ("pv",)) pl = dict(mqtt.discovery_payloads(include=mqtt.optional_keys(CAR))) names = sorted(k for k in pl if "_car_" in k) -check(f"discovery announces three sensors, goodwe_car_power, " - f"goodwe_car_state and goodwe_car_today_kwh ({names})", +check(f"discovery announces the sensors goodwe_car_power, goodwe_car_state, " + f"goodwe_car_today_kwh and (EV-20) goodwe_car_today_solar_kwh ({names})", [pl[k]["object_id"] for k in names] == [ - "goodwe_car_power", "goodwe_car_state", "goodwe_car_today_kwh"] + "goodwe_car_power", "goodwe_car_state", "goodwe_car_today_kwh", + "goodwe_car_today_solar_kwh"] and all(k.startswith("homeassistant/sensor/") for k in names)) check("...and no command entity (no select, number or switch for the car)", not [k for k in pl if "car" in k and not k.startswith( diff --git a/goodwe_controller/test_ev04.py b/goodwe_controller/test_ev04.py index fdc83e7..2fc9165 100644 --- a/goodwe_controller/test_ev04.py +++ b/goodwe_controller/test_ev04.py @@ -248,7 +248,7 @@ async def part2(): w = World() out = {} out["manual"] = await w.act("car_mode", "manual") - out["bad_mode"] = await w.act("car_mode", "solar") # not in this card + out["bad_mode"] = await w.act("car_mode", "bogus") # EV-20 accepts Solar out["night"] = await w.act("car_mode", "night") out["a12"] = await w.act("car_current", 12) out["a5"] = await w.act("car_current", 5) @@ -266,7 +266,7 @@ w2, o2 = run(part2()) check("Manual is chosen at once, no restart", o2["manual"] == { "mode": "manual", "current": 6.0, "phases": 1} and w2.c.car_mode == "manual" or w2.c.car_mode == "manual") -check("Solar and Night are not accepted (EV-05, EV-02)", +check("Night (EV-02) and an unknown mode are not accepted", "error" in o2["bad_mode"] and "error" in o2["night"] and w2.c.car_mode == "manual") check("a current between 6 A and the clamp is accepted and stored", @@ -307,7 +307,7 @@ check("ev_phases 1: 3 phases cannot be chosen, 1 can", async def part2c(): out = {} for start, stored in (("keep", "manual"), ("off", "manual"), - ("keep", None), ("keep", "solar")): + ("keep", None), ("keep", "night")): st = _Store() if stored: st.data["car_mode"] = stored @@ -322,7 +322,7 @@ check("ev_mode_start keep: a restart keeps Manual", check("ev_mode_start off: a restart starts in Off and the store says so", o2c[("off", "manual")] == ("off", "off")) check("no stored mode, or one this build does not know, is Off", - o2c[("keep", None)][0] == "off" and o2c[("keep", "solar")][0] == "off") + o2c[("keep", None)][0] == "off" and o2c[("keep", "night")][0] == "off") # =========================================================================== # print("\n3. MANUAL WRITES THE CURRENT ONCE PER USER CHANGE") @@ -1624,13 +1624,14 @@ pl = dict(mqtt.car_payloads((16, (1, 3)))) sel = pl["homeassistant/select/goodwe_ctl_car_mode/config"] num = pl["homeassistant/number/goodwe_ctl_car_current/config"] ph = pl["homeassistant/select/goodwe_ctl_car_phases/config"] -check("three entities: select.goodwe_car_mode, number.goodwe_car_current, " - "select.goodwe_car_phases", len(pl) == 3 +check("four entities: select.goodwe_car_mode, number.goodwe_car_current, " + "select.goodwe_car_phases and (EV-20) select.goodwe_car_sun_first", + len(pl) == 4 and sel["object_id"] == "goodwe_car_mode" and num["object_id"] == "goodwe_car_current" and ph["object_id"] == "goodwe_car_phases") -check("the mode's labels are English and pinned: Off, Manual (Solar and Night " - "are not offered)", sel["options"] == ["Off", "Manual"]) +check("the mode's labels are English and pinned: Off, Manual, Solar (EV-20; " + "Night is not offered)", sel["options"] == ["Off", "Manual", "Solar"]) check("the current is 6 A to the clamp, whole amps", num["min"] == 6 and num["max"] == 16 and num["step"] == 1 and num["unit_of_measurement"] == "A") @@ -1647,7 +1648,7 @@ check("nothing is announced without a charger (and the default announcement " "is as it was)", mqtt.car_payloads(None) == [] and mqtt.discovery_payloads() == mqtt.discovery_payloads(car=None)) check("the car entities come after every other row", - [t for t, _ in mqtt.discovery_payloads(car=(16, (1, 3)))][-3:] + [t for t, _ in mqtt.discovery_payloads(car=(16, (1, 3)))][-4:] == [t for t, _ in mqtt.car_payloads((16, (1, 3)))]) cmd = mqtt.parse_car_command check("a command parses: mode, current, phases", @@ -1659,8 +1660,8 @@ check("a command parses: mode, current, phases", == ("car_phases", 3, None)) check("a retained command is dropped", cmd("goodwe_ctl/car/mode/set", b"Manual", True)[2] == "retained") -check("Solar, Night, junk and a long payload are refused", - cmd("goodwe_ctl/car/mode/set", b"Solar", False)[1] is None +check("Night, an unknown mode, junk and a long payload are refused", + cmd("goodwe_ctl/car/mode/set", b"Bogus", False)[1] is None and cmd("goodwe_ctl/car/mode/set", b"Night", False)[1] is None and cmd("goodwe_ctl/car/current/set", b"abc", False)[1] is None and cmd("goodwe_ctl/car/phases/set", b"2", False)[1] is None @@ -1678,7 +1679,7 @@ async def ha_story(): out = {"mode": w.c.car_mode, "a": w.c.car_a, "rb": w.sim.readback_a, "pub": list(w.c.mqtt.values)[-1]} await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Off", True) # retained - await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Solar", False) + await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Night", False) await w.c.mqtt_command("goodwe_ctl/car/current/set", b"99", False) await w.c.mqtt_command("goodwe_ctl/car/phases/set", b"2", False) await w.step(5) @@ -1696,8 +1697,8 @@ check("HA commands go through handle_action(): Manual and 13 A are applied " "and written, and the new state is published", ha["mode"] == "manual" and ha["a"] == 13.0 and ha["rb"] == 13 and ha["pub"] == {"car_mode": "Manual", "car_current": 13, - "car_phases": "1"}) -check("a retained command, Solar, 99 A and 2 phases change nothing", + "car_phases": "1", "car_sun_first": "Batteries"}) +check("a retained command, Night, 99 A and 2 phases change nothing", ha["after"] == ("manual", 13.0, 1)) check("the three states are in the published values", ha["state"].get("car_mode") == "Manual" @@ -1718,11 +1719,11 @@ st_ = _S() car_, retract_ = _main.car_announcement(CAR, st_) check("with a charger the entities are announced and their topics kept", car_ == (16.0, (1, 3)) and not retract_ and len( - st_.data["mqtt_car_configs"]) == 3) + st_.data["mqtt_car_configs"]) == 4) car2, retract2 = _main.car_announcement(BASE, st_) check("turning the charger off removes exactly those entities", car2 is None and sorted(retract2) == sorted(st_.data["mqtt_car_configs"]) - and len(retract2) == 3) + and len(retract2) == 4) st2 = _S() check("a site that never had a charger publishes nothing and its store is " "not written", @@ -1752,7 +1753,7 @@ async def web_story(): ("manual", {"action": "car_mode", "value": "manual"}), ("a", {"action": "car_current", "value": 12}), ("n", {"action": "car_phases", "value": 3}), - ("solar", {"action": "car_mode", "value": "solar"}), + ("solar", {"action": "car_mode", "value": "night"}), ("big", {"action": "car_current", "value": 40})): async with s.post(root + "action", json=body) as r: out[key] = (r.status, await r.json(content_type=None)) @@ -1771,21 +1772,22 @@ check("POST /action car_mode, car_current and car_phases store and answer", web["manual"] == (200, {"ok": True, "result": { "mode": "manual", "current": 6.0, "phases": 1}}) and web["a"][0] == 200 and web["n"][0] == 200) -check("...Solar and 40 A (above the clamp) are a 400 with a plain reason", +check("...Night and 40 A (above the clamp) are a 400 with a plain reason", web["solar"][0] == 400 and web["solar"][1]["ok"] is False and web["solar"][1]["error"] == messages.car_refused("value") and web["big"][0] == 400) car_s = web["status_en"]["car"] -check("/status gives the page what it needs: the mode, the modes offered (Off " - "and Manual only), the current's range, the phases", - car_s["mode"] == "manual" and car_s["modes"] == ["off", "manual"] +check("/status gives the page what it needs: the mode, the modes offered (Off, " + "Manual and, EV-20, Solar), the current's range, the phases", + car_s["mode"] == "manual" + and car_s["modes"] == ["off", "manual", "solar"] and car_s["current"] == {"value": 12, "min": 6, "max": 16} and car_s["phases"] == {"value": 3, "choices": [1, 3]}) check("/status in Dutch has the Dutch Why", web["status_nl"]["car"]["why"].startswith("U stelde 12 A in")) -check("the page has the controls and no Solar or Night button", +check("the page has the controls and no Night button (EV-20 adds Solar)", 'id="car-manual"' in web["page"] and 'id="car-a"' in web["page"] - and "mode_solar" not in web["page"] and "mode_night" not in web["page"]) + and "mode_night" not in web["page"]) check("the page names the Manual strings in both languages", "Handmatig" in web["page"] and "Manual" in web["page"]) diff --git a/goodwe_controller/test_ev20.py b/goodwe_controller/test_ev20.py new file mode 100644 index 0000000..f212a17 --- /dev/null +++ b/goodwe_controller/test_ev20.py @@ -0,0 +1,701 @@ +"""EV-20: the car charger's Solar mode, spare sun to the car: the arithmetic, +the modes, the start, the hold and the pause, the phases (T1-T20, T56). +`python3 -B test_ev20.py` + +The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and +`chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit +rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section +names the T-ids and N-ids of reports/EV-20-test-plan.md it implements. +"Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare +2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start. +Times are the cycle's second; `race` runs use the production order (read, the +writer settles, the cycle). + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import json +import math +import os +import random +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402 +from app import mqtt, validate, web, main as app_main # noqa: E402 +from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from ev20_kit import * # noqa: E402,F401,F403 +from ev20_kit import LOG, check, fails, report # noqa: E402,F401 +from named_absence import nth, present # noqa: E402,F401 +from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401 + _until) + + +# =========================================================================== # +print("1. THE ARITHMETIC (T3, T9, T10, N11)") +# =========================================================================== # +# T3: signed spare. `spare_w(car, site battery W (discharge +), grid)`. +T3 = {"a": ((0.0, -5000.0, -2000.0), 7000.0), + "b": ((0.0, -6000.0, 6900.0), -900.0), + "c": ((1380.0, 9600.0, -5220.0), -3000.0), + "d": ((1380.0, 9600.0, -7220.0), -1000.0), + "e": ((0.0, 0.0, -3000.0), 3000.0)} +got = {k: spare_w(*a) for k, (a, _) in T3.items()} +check(f"T3: the signed spare, (a) to (e) = 7000, -900, -3000, -1000, 3000 W " + f"within 1 W ({got})", + all(got[k] is not None and abs(got[k] - w) <= 1.0 + for k, (_, w) in T3.items())) +clip = {k: max(0.0, a[0] + max(0.0, -a[1]) - max(0.0, a[2])) + for k, (a, _) in T3.items()} +check("T3/N11: a clipped formula fails (a), (c) and (e); ours does not: no " + "positive spare from a grid charge or from batteries giving more than " + "the house uses", + all(abs(clip[k] - T3[k][1]) > 1.0 for k in "ace") + and got["b"] < 0 and got["c"] < 0 and got["d"] < 0) +check("T3/T4: a missing or non-numeric figure is no spare (None, NaN, " + "'unavailable')", + spare_w(0.0, None, 100.0) is None + and spare_w(0.0, float("nan"), 100.0) is None + and spare_w(0.0, 100.0, "unavailable") is None + and spare_w(None, 0.0, 0.0) is None) + +# T9: the margin, both priorities, Car first on a 2400 W spare, 1 phase. +t9 = {m: amps_for(carmode.car_target_w(2400.0, 0.0, m, carmode.FIRST_CAR), 1, + 16) for m in (0, 100, 300, 1000)} +check(f"T9: ev_margin_w 0, 100, 300, 1000 on a 2400 W spare: 10, 10, 9, 6 A " + f"({t9})", t9 == {0: 10.0, 100: 10.0, 300: 9.0, 1000: 6.0}) +check("T9: the margin is taken once, in both priorities (Batteries first with " + "the room 0 is the same as Car first)", + carmode.car_target_w(2400.0, 0.0, 300, carmode.FIRST_BATT) + == carmode.car_target_w(2400.0, 5000.0, 300, carmode.FIRST_CAR) + == 2100.0) +# T10: rounded down, clamped. +t10 = (amps_for(1900, 1), amps_for(2299, 1), amps_for(6900, 3), + amps_for(6899, 3)) +check(f"T10: 1900 and 2299 W on 1 phase, 6900 and 6899 W on 3: 8, 9, 10, 9 A " + f"({t10}); a rounding would give 10 at 2299 W", + t10 == (8.0, 9.0, 10.0, 9.0) and round(2299 / 230) == 10) +check("T10: ev_max_a 10 with 6.9 kW on 1 phase is 10 A; a 13 A station limit " + "bounds it to 13 A", amps_for(6900, 1, 10) == 10.0 + and amps_for(6900, 1, 13) == 13.0) +rnd = random.Random(20) +bad10 = [] +for _ in range(1000): + tw = rnd.choice([float("nan"), -rnd.uniform(0, 5000), 1e9, + rnd.uniform(0, 12000), None]) + n = rnd.choice([1, 3]) + clamp = rnd.choice([None, 6.0, 10.0, 13.0, 16.0, 32.0, 40.0]) + p = SolarPlan(n) + for k in range(400): + p.step(float(k), target_w=tw, n_now=n, auto=False, clamp=clamp, + start_s=120.0, pause_s=300.0) + if p.a > 0.0: + hi = math.floor(clamp) if clamp is not None else CH.ENTITY_MAX_A + want = amps_for(tw, p.n, clamp) + if not (CH.MIN_A <= p.a <= hi) or ( + p.why == "running" and p.a != want): + bad10.append((tw, n, clamp, p.a, want)) + break +check(f"T10/N1 property: 1000 random spares (NaN, negative, 1e9, None), " + f"phases and limits: every non-zero current is floor(target / (230 x " + f"n)) inside [6 A, clamp] ({bad10[:2]})", not bad10) + +# =========================================================================== # +print("\n2. MODE SOLAR AND WHERE SPARE SUN GOES FIRST (T1, T2, T56)") +# =========================================================================== # +res1 = {} + + +async def _web(p, c): + import socket + import aiohttp + from aiohttp import web as aioweb + app = web.build_app(c, selfcfg=object()) + runner = aioweb.AppRunner(app) + await runner.setup() + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() + await aioweb.TCPSite(runner, "127.0.0.1", port).start() + try: + async with aiohttp.ClientSession() as s: + for key, body in (("solar", {"action": "car_mode", + "value": "solar"}), + ("night", {"action": "car_mode", + "value": "night"}), + ("first", {"action": "car_sun_first", + "value": "car"})): + async with s.post(f"http://127.0.0.1:{port}/action", + json=body) as rr: + res1[key] = (rr.status, await rr.json(content_type=None)) + async with s.get(f"http://127.0.0.1:{port}/status?lang=en") as rr: + res1["status"] = await rr.json(content_type=None) + finally: + await runner.cleanup() + + +r1 = run("T1", std, 400, mode="off", first="batteries", events={ + 10: _web, + 200: act("car_mode", "night", res1, "night_a"), + 201: act("car_mode", "bogus", res1, "bogus_a")}) +c1 = r1["c"] +w1 = cur_writes(r1) +check(f"T1: POST /action car_mode solar from the page is stored at once " + f"(car_mode=solar) and answers 200 ({res1.get('solar')})", + res1.get("solar", (0,))[0] == 200 + and r1["store"].data.get("car_mode") == "solar") +check(f"T1: the next writer steps run Solar with no restart: the start rule " + f"from the choice, 10 A at 10 + 120 s ({w1[:2]})", + bool(w1) and w1[0][1] == 10.0 and 128 <= w1[0][0] <= 132) +check("T1: Night and Bogus are refused (page and action), nothing changes", + res1.get("night", (0,))[0] == 400 and "error" in res1.get("night_a", {}) + and "error" in res1.get("bogus_a", {}) and c1.car_mode == "solar" + and r1["store"].data.get("car_mode") == "solar") +pl = dict(mqtt.car_payloads((16, (1, 3)))) +sel = pl.get("homeassistant/select/goodwe_ctl_car_mode/config", {}) +sf = pl.get("homeassistant/select/goodwe_ctl_car_sun_first/config", {}) +check(f"T1: select.goodwe_car_mode options are exactly Off, Manual, Solar " + f"({sel.get('options')})", sel.get("options") == ["Off", "Manual", + "Solar"]) +check(f"T2: select.goodwe_car_sun_first is announced with Batteries and Car " + f"({sf.get('options')}), labels as carmode's", + sf.get("object_id") == "goodwe_car_sun_first" + and sf.get("options") == ["Batteries", "Car"] + and mqtt.CAR_FIRST_LABELS == carmode.FIRST_LABELS + and mqtt.CAR_MODE_LABELS == carmode.MODE_LABELS) +check("T1: /status offers Off, Manual and Solar, and where spare sun goes " + "first", res1.get("status", {}).get("car", {}).get("modes") + == ["off", "manual", "solar"] + and res1["status"]["car"].get("first", {}).get("choices") + == ["batteries", "car"]) +cmd = mqtt.parse_car_command +check("T1/T2: MQTT parses Solar and the two priorities; Night, Bogus, an " + "unknown label and a retained command are refused", + cmd("goodwe_ctl/car/mode/set", b"Solar", False)[:2] + == ("car_mode", "solar") + and cmd("goodwe_ctl/car/sun_first/set", b"Car", False)[:2] + == ("car_sun_first", "car") + and cmd("goodwe_ctl/car/sun_first/set", b"Batteries", False)[1] + == "batteries" + and cmd("goodwe_ctl/car/mode/set", b"Night", False)[1] is None + and cmd("goodwe_ctl/car/mode/set", b"Bogus", False)[1] is None + and cmd("goodwe_ctl/car/sun_first/set", b"Sun", False)[1] is None + and cmd("goodwe_ctl/car/sun_first/set", b"Car", True)[2] == "retained") + +# T1 from MQTT, and T2: the priority from HA, a retained and an unknown one. +r2 = run("T2", S.drive, const(900.0), const(7900.0), dur=260, mode="off", + first="batteries", socs={"a": 71.0, "b": 100.0}, events={ + 5: mqtt_cmd("goodwe_ctl/car/mode/set", b"Solar"), + 160: mqtt_cmd("goodwe_ctl/car/sun_first/set", b"Car", True), + 161: mqtt_cmd("goodwe_ctl/car/sun_first/set", b"Sun"), + 200: mqtt_cmd("goodwe_ctl/car/sun_first/set", b"Car")}) +c2, tr2 = r2["c"], r2["trace"] +w2 = cur_writes(r2) +check(f"T1: MQTT 'Solar' is applied: the store says solar and Batteries " + f"first writes 8 A (scenario 2) after the start rule ({w2[:1]})", + r2["store"].data.get("car_mode") == "solar" and bool(w2) + and w2[0][1] == 8.0) +check("T2: a retained command and an unknown label change nothing (Batteries " + "until 200 s)", all(x["why"] for x in tr2) + and c2.car_sun_inputs is not None + and [x for x in w2 if x[0] < 200] == w2[:1]) +check(f"T2: Car at 200 s: the arithmetic changes next cycle and the new " + f"current (16 A) is written at once, the 30 s rule passed ({w2})", + any(t in (200.0, 201.0) and a == 16.0 for t, a, _ in w2) + and r2["store"].data.get("car_sun_first") == "car") + + +async def _rebuild(): + st = r2["store"] + from app.main import Controller + import opt11_identity as rig + c = Controller(dict(c2.o), r2["plant"], st, rig._Pub(), + stop=asyncio.Event()) + return c.car_first, c.car_mode + + +check(f"T2: the priority is runtime state in the store and survives a " + f"rebuild of the Controller on it ({asyncio.run(_rebuild())})", + asyncio.run(_rebuild()) == ("car", "solar")) +# T2: the 30 s rule still applies after a priority change. +r2b = run("T2b", S.drive, const(900.0), const(7900.0), dur=200, + first="batteries", socs={"a": 71.0, "b": 100.0}, + events={130: act("car_sun_first", "car")}) +w2b = cur_writes(r2b) +check(f"T2: Car chosen 10 s after Batteries first wrote 8 A: 16 A waits for " + f"the 30 s rule (at 150 s, not before) ({w2b})", + [a for _, a, _ in w2b] == [8.0, 16.0] and w2b[1][0] == w2b[0][0] + 30) + +# T56: rollback. The base build has no Solar in MODES; with it taken out, the +# stored mode reads as Off and the action is refused. +keep_modes = carmode.MODES +carmode.MODES = (carmode.OFF, carmode.MANUAL) +try: + t56 = carmode.start_mode({}, "solar") +finally: + carmode.MODES = keep_modes +check("T56: a build without Solar reads a stored car_mode=solar as Off " + "(start_mode); on head unknown modes still map to Off", + t56 == "off" and carmode.start_mode({}, "night") == "off" + and carmode.start_mode({}, "bogus") == "off" + and carmode.start_mode({}, "solar") == "solar") + +# =========================================================================== # +print("\n3. THE SPARE, THE ROOM, THE START (T5, T6, T7, T8, T9, T13)") +# =========================================================================== # +for race in (False, True): + tag = "race" if race else "step" + r6 = run("T6", S.drive, const(900.0), const(7900.0), dur=600, + first="batteries", socs={"a": 71.0, "b": 100.0}, race=race) + c6, tr6 = r6["c"], r6["trace"] + w6 = cur_writes(r6) + batt = [r6["plant"].batt_of("a", t) for t in range(400, 600)] + exp = [r6["plant"].grid(t) for t in range(400, 600)] + ok6 = next((x["ok"] for x in tr6 if x["ok"] is not None), None) + check(f"T6 [{tag}]: scenario 2, Batteries first: spare 7000, room 5000, " + f"car 1900 W -> 8 A on 1 phase after the 120 s dwell ({w6}, the " + f"dwell from {ok6})", + [a for _, a, _ in w6] == [8.0] and ok6 is not None + and 120 <= w6[0][0] - ok6 <= 121 + and tr6[300]["spare"] is not None + and abs(tr6[300]["spare"] - 7000.0) <= 50.0 + and selects(r6) == []) + check(f"T6 [{tag}]: steady: A charges 5000 +-100 W, export about 160 W, " + f"no drift ({min(batt):.0f}..{max(batt):.0f} W, grid " + f"{min(exp):.0f}..{max(exp):.0f} W)", + all(-5100.0 <= b <= -4900.0 for b in batt) + and all(-260.0 <= g <= -60.0 for g in exp)) + nevers(r6, f"T6 [{tag}]") +blk6 = homeview.car_block(c6, None) +check(f"T6: the Why is why.solar_batt ({blk6['why']!r})", + blk6["why"].startswith("Batteries first.")) +check("T6: v1 room (rating - charge now) would give 16 A on this spare: the " + "rating rule is what makes it 8 A", + amps_for(carmode.car_target_w(7000.0, 5000.0 - 5000.0, 100, + carmode.FIRST_BATT), 1, 16) == 16.0 + and amps_for(carmode.car_target_w(7000.0, 5000.0, 100, + carmode.FIRST_BATT), 1, 16) == 8.0) + +r7 = run("T7", S.drive, const(900.0), const(7900.0), dur=700, first="car", + socs={"a": 71.0, "b": 100.0}) +c7 = r7["c"] +w7, s7 = cur_writes(r7), selects(r7) +check(f"T7: scenario 2, Car first, auto: starts on 1 phase at the clamp " + f"(16 A) ({w7[:1]})", bool(w7) and w7[0][1] == 16.0 + and r7["trace"][150]["ph"] == 1) +check(f"T7: after 180 s at >= 4.5 kW the safe sequence to 3 phases, then " + f"floor(6900/690) = 10 A ({w7}, selects {[(x[0], x[2]) for x in s7]})", + [a for _, a, _ in w7] == [16.0, 0.0, 10.0] and len(s7) == 1 + and s7[0][2] == 3 and 298 <= w7[1][0] <= 303) +bt7 = [r7["plant"].batt(t) for t in range(500, 700)] +check(f"T7: the batteries charge 100 +-50 W ({min(bt7):.0f}..{max(bt7):.0f})", + all(-150.0 <= b <= -50.0 for b in bt7)) +check(f"T7: the Why is why.solar_car " + f"({homeview.car_block(c7, None)['why']!r})", + homeview.car_block(c7, None)["why"].startswith("Car first:")) +nevers(r7, "T7") + +# T8: the room. +r8a = run("T8a", S.drive, const(500.0), step_fn((200, 4500.0), base=8000.0), + dur=560, first="car", socs={"a": 60.0, "b": 100.0}, + events={200: act("car_sun_first", "batteries")}) +w8a = cur_writes(r8a) +check(f"T8 (a): Batteries first, spare 4000 W, A may charge (5000 W), B full: " + f"4000 - 5000 - 100 < 0: the 6 A hold, then 0 A at the pause ({w8a})", + [a for _, a, _ in w8a][-2:] == [6.0, 0.0] + and 499 <= w8a[-1][0] <= 502) +r8b = run("T8b", std, 200, sun=const(3500.0), first="batteries") +check(f"T8 (b): both full, spare 3000 W: 2900 W, 12 A " + f"({cur_writes(r8b)})", [a for _, a, _ in cur_writes(r8b)] == [12.0]) + + +def _room(socs, **setup): + out = {} + + def probe(p, c): + for k, v in setup.items(): + v(c) + out["room"] = c.car_room_w() + S.drive(const(500.0), const(7500.0), dur=3, first="batteries", + socs=socs, events={2: probe}) + return out["room"] + + +def _a_off(c): + from app import packmode + from app.store import unit_key + c.store.data[unit_key("inverter-a", packmode.USE_KEY)] = False + + +def _a_refuse(c): + c.inverters[0].refused = -1 + + +rooms = {"off": _room({"a": 60.0, "b": 60.0}, x=_a_off), + "refusing": _room({"a": 60.0, "b": 60.0}, x=_a_refuse), + "ceiling": _room({"a": 100.0, "b": 60.0}), + "both": _room({"a": 60.0, "b": 60.0})} +check(f"T8 (c): A Off, refusing a charge or at its ceiling leaves B's 4600 W " + f"as the room; both able gives 9600 W ({rooms})", + rooms == {"off": 4600.0, "refusing": 4600.0, "ceiling": 4600.0, + "both": 9600.0}) +r8c = run("T8c", S.drive, const(500.0), const(7500.0), dur=200, + first="batteries", socs={"a": 100.0, "b": 60.0}) +check(f"T8 (c): spare 7000, room 4600: 2300 W, 10 A ({cur_writes(r8c)})", + [a for _, a, _ in cur_writes(r8c)] == [10.0]) +r8d = run("T8d", S.drive, const(900.0), step_fn((300, 1600.0), base=7900.0), + dur=700, first="batteries", socs={"a": 71.0, "b": 100.0}) +w8d = cur_writes(r8d) +check(f"T8 (d): scenario 2's cloud (sun 1.6 kW, spare 700): 6 A for 300 s, " + f"then 0 A ({w8d})", [a for _, a, _ in w8d] == [8.0, 6.0, 0.0] + and 599 <= w8d[-1][0] <= 602) + +# T9 through the real Controller: Car first, spare 2400 W. +t9r = {} +for m in (0, 100, 300, 1000): + rr = S.drive(const(500.0), step_fn((200, 2900.0), base=5000.0), dur=260, + first="car", socs=dict(FULL), opts={"ev_margin_w": m}) + t9r[m] = [a for t, a, _ in cur_writes(rr) if t >= 200] +check(f"T9: running, then a 2400 W spare: the Controller writes 10, 10, 9, " + f"6 A for margins 0, 100, 300, 1000 W ({t9r}; 1400 W is 6 A, not a " + f"hold)", t9r == {0: [10.0], 100: [10.0], 300: [9.0], 1000: [6.0]}) + +# T10 through the Controller: a 13 A station limit with plenty of sun. +sim10 = SimCharger(setpoint_a=0) +r10 = run("T10", std, 300, sun=const(9000.0), sim=sim10, + opts={"ev_phases": "1"}, + events={200: lambda p, c: setattr(p.ch, "station_a", 13.0)}) +check(f"T10: 16 A, then the station limit comes down to 13 A: Solar writes " + f"13 A and never more, clamp_faults == [] ({cur_writes(r10)})", + [a for _, a, _ in cur_writes(r10)] == [16.0, 13.0] + and r10["c"].charger.clamp_faults == []) + +# T5: the car's figure. +p5 = {} +r5 = run("T5", std, 200, events={50: lambda p, c: p5.update( + trusted=c.car.car_w_trusted(c.car_now()), spare=c.car_spare_w( + c.car_now()))}) +tr5 = r5["trace"] +check(f"T5 (i)(ii): paused/idle, state B at 0 A, a fresh 0 W: the car counts " + f"0 W and the spare is computed (car_w_trusted is None there) ({p5})", + tr5[50]["st"] == "B" and p5.get("spare") is not None + and abs(p5["spare"] - 2400.0) < 1.0 and p5.get("trusted", 1) is None) +check(f"T5 (i)(ii): the start rule passes on it: 10 A at 120 s " + f"({cur_writes(r5)[:1]})", cur_writes(r5)[:1] + and cur_writes(r5)[0][1] == 10.0) + + +def _stop_car_keep_c(p, c): + """The car stops drawing while mode3 stays C, and the power sensor + sticks at what it read.""" + p.ch.freeze_power() + p.ch.stop_delay_s = 1e9 + p.ch.full = True + + +sim5 = SimCharger(setpoint_a=0) +r5c = run("T5c", std, 900, sim=sim5, sun=const(2900.0), + events={300: _stop_car_keep_c}) +tr5c = r5c["trace"] +gone = next((x["t"] for x in tr5c if x["t"] > 300 and x["spare"] is None), + None) +w5c = cur_writes(r5c) +check(f"T5 (iii): a frozen 2300 W figure after the car stopped (mode3 C): " + f"dropped once the energy meter does not corroborate it (<= 110 s; " + f"at {gone})", gone is not None and gone - 300 <= 110) +check(f"T5 (iii): then the hold: no new current once it is dropped, 0 A by " + f"300 + 2 s after it ({w5c})", + gone is not None and w5c[-1][1] == 0.0 + and gone + 299 <= w5c[-1][0] <= gone + 302 + and not [x for x in w5c if gone <= x[0] and x[1] > 0.0]) + + +def _down(p, c): + p.ch.go_unavailable(True) + + +r5d = run("T5d", std, 500, events={300: _down}) +check("T5 (iv): a charger reading older than 15 s (this driver: the charger " + "does not answer) is no spare, and nothing is written while it is down", + r5d["trace"][330]["spare"] is None + and [a for _, a, _ in cur_writes(r5d)] == [10.0]) + +# T13: the start rule. +for race in (False, True): + tag = "race" if race else "step" + d = 1 if race else 0 + ra = std(900, sun=const(500.0 + 100.0 + 1609.0), race=race) + rb = std(200, sun=const(500.0 + 100.0 + 1610.0), race=race) + rc = std(300, sun=lambda t: 500.0 + 100.0 + (1500.0 if at_s(t) == 60 + else 1610.0), race=race) + check(f"T13 (a) [{tag}]: 1609 W on 1 phase for 900 s: no start", + cur_writes(ra) == []) + # `race`: the writer's step runs a second later, the meter's sample not. + check(f"T13 (b) [{tag}]: 1610 W: 7 A at 120 s, not 119 s " + f"({cur_writes(rb)})", [(t, a) for t, a, _ in cur_writes(rb)] + in ([(120.0, 7.0)], [(120.0 + d, 7.0)])) + check(f"T13 (c) [{tag}]: a 1-cycle dip to 1500 W at 60 s: the start at " + f"181 s ({cur_writes(rc)})", [(t, a) for t, a, _ in cur_writes(rc)] + in ([(181.0, 7.0)], [(181.0 + d, 7.0)])) +rd = run("T13d", std, 300, sun=const(500.0 + 100.0 + 6900.0), phases=3) +wd, sd = cur_writes(rd), selects(rd) +check(f"T13 (d): auto, 6900 W, the charger left on 3 phases: 0 A kept, " + f"select 1, then the current; no non-zero write on 3 phases first " + f"({wd}, {[(x[0], x[2], x[4]) for x in sd]})", + len(sd) == 1 and sd[0][2] == 1 and sd[0][4] == 0.0 + and wd and wd[0][1] == 16.0 and wd[0][0] >= sd[0][0] - 1 + 10) +nevers(rd, "T13 (d)") +re1 = std(600, sun=const(500.0 + 100.0 + 4829.0), phases=3, + opts={"ev_phases": "3"}) +re2 = std(200, sun=const(500.0 + 100.0 + 4830.0), phases=3, + opts={"ev_phases": "3"}) +check(f"T13 (e): ev_phases 3: none at 4829 W; 7 A at 120 s for 4830 W " + f"({cur_writes(re2)})", cur_writes(re1) == [] + and [(t, a) for t, a, _ in cur_writes(re2)] == [(120.0, 7.0)] + and selects(re2) == []) + +# =========================================================================== # +print("\n4. THE 30 s / 1 A RULE, THE HOLD AND THE PAUSE (T11, T12, T14-T16)") +# =========================================================================== # +# T11: 8 A worth, write at t; at t+5 10 A worth. +for race in (False, True): + tag = "race" if race else "step" + r11 = std(300, sun=step_fn((125, 600.0 + 2300.0), base=600.0 + 1840.0), + race=race) + w11 = cur_writes(r11) + check(f"T11 (a) [{tag}]: 8 A at t, 10 A worth from t+5: 10 A at t+30 " + f"(+-1 cycle), not before ({w11})", + [a for _, a, _ in w11] == [8.0, 10.0] + and 29 <= w11[1][0] - w11[0][0] <= 31) + r11b = std(800, sun=step_fn((130, 600.0 + 8.9 * 230.0), + base=600.0 + 1840.0), race=race) + check(f"T11 (b) [{tag}]: 8 -> 8.9 A worth for 600 s: no write " + f"({cur_writes(r11b)})", [a for _, a, _ in cur_writes(r11b)] + == [8.0]) + +# T12: an exit 2 s after a normal write: the 0 A within 1 cycle. +T12 = { + "Stop": lambda p, c: setattr(c, "auto", False), + "Off": act("car_mode", "off"), + "shadow": lambda p, c: c.o.__setitem__("shadow_mode", "on"), + "unplug": lambda p, c: p.ch.unplug(), + "latch": lambda p, c: setattr(c.circ_wd, "tripped", True), + "error": lambda p, c: (setattr(p.ch, "error", "12: Socket error"), + p.ch.fault("E")), +} +t12 = {} +for name, fn in T12.items(): + rr = std(260, sun=step_fn((150, 600.0 + 2760.0), base=600.0 + 2300.0), + events={152: fn}) + w = cur_writes(rr) + t12[name] = w +check(f"T12: every exit 2 s after a normal write (12 A at 150 s) gets its " + f"0 A within 1 cycle, the 30 s gate never delays it " + f"({ {k: v[-2:] for k, v in t12.items()} })", + all(len(v) >= 2 and v[-2][:2] == (150.0, 12.0) and v[-1][1] == 0.0 + and v[-1][0] - 152 <= 1 for v in t12.values())) +p12 = SolarPlan(1) +p12.a, p12.set_at, p12.low_since, p12.why = 6.0, 98.0, -200.0, "hold" +p12.step(100.0, target_w=1000.0, n_now=1, auto=False, clamp=16, start_s=120, + pause_s=300) +check("T12: the pause is never gated: a plan whose last change was 2 s ago " + "pauses at its 300 s (0 A)", p12.a == 0.0) + +# T14: at 8 A, the target drops to 1200 W (5.2 A). +for race in (False, True): + tag = "race" if race else "step" + d = 1 if race else 0 + r14 = std(800, sun=step_fn((200, 600.0 + 1200.0), base=600.0 + 1840.0), + race=race, rows=False) + w14 = cur_writes(r14) + check(f"T14 (a) [{tag}]: 6 A written, then 0 A once at 300 s, not 299 s " + f"({w14})", [a for _, a, _ in w14] == [8.0, 6.0, 0.0] + and w14[2][0] in (500.0, 500.0 + d)) + r14b = std(1100, sun=lambda t: 600.0 + (1840.0 if at_s(t) < 200 else + 1500.0 if 499 <= at_s(t) < 510 + else 1200.0), + race=race) + w14b = cur_writes(r14b) + check(f"T14 (b) [{tag}]: back >= 6 A at 299 s, then low again: no 0 A " + f"then; the next dip needs a fresh 300 s ({w14b})", + [a for _, a, _ in w14b][-1:] == [0.0] + and w14b[-1][0] in (810.0, 810.0 + d) + and not any(a == 0.0 and t < 800 for t, a, _ in w14b)) +blk14 = homeview.car_block(r14["c"], None) +check(f"T14: the card says Waiting for sun and why.solar_paused " + f"({blk14['chip']!r}, {blk14['why']!r})", + blk14["chip"] == "Waiting for sun" + and blk14["why"].startswith("Too little spare sun for 6 A.")) + +# T15: the hold at the peak reserve. +r15a = run("T15a", S.drive, const(500.0), step_fn((200, 1000.0), + base=3000.0), + dur=600, first="car", socs={"a": 19.0, "b": 19.0}, + opts={"peak_soc_floor": 20}) +tr = r15a["trace"] +imp = sum(max(0.0, min(x["car"], x["grid"])) for x in tr if x["t"] >= 200) +w15a = cur_writes(r15a) +check(f"T15 (a): A and B at the peak reserve: the car's grid import in the " + f"hold is at most 1380 W x 302 s (116 Wh), then 0 A ({imp / 3600:.0f} " + f"Wh, {w15a})", imp <= 1380.0 * 302.0 and w15a[-1][1] == 0.0 + and 499 <= w15a[-1][0] <= 502) +r15b = run("T15b", S.drive, const(500.0), step_fn((200, 1000.0), + base=3000.0), + dur=600, first="car", socs={"a": 19.0, "b": 60.0}, + opts={"peak_soc_floor": 20}) +gr = [x["grid"] for x in r15b["trace"] if 240 <= x["t"] < 495] +check(f"T15 (b): A at the reserve, B at 60 %: B covers the car, the grid " + f"is about 0 in the hold ({min(gr):.0f}..{max(gr):.0f} W)", + all(abs(g) <= 150.0 for g in gr)) + +# T16: the wall clock jumps; the dwells are monotonic. +for jump in (3600.0, -3600.0): + def jmp(p, c, jump=jump): + p.utc_off = jump + r16 = std(800, sun=step_fn((200, 600.0 + 1200.0), base=600.0 + 1840.0), + events={60: jmp, 300: jmp}) + w16 = cur_writes(r16) + check(f"T16 ({jump:+.0f} s): a start dwell and a hold across a wall-clock " + f"jump: start at 120 s, pause at 300 s, monotonic ({w16})", + [(t, a) for t, a, _ in w16][:1] == [(120.0, 8.0)] + and w16[-1] == (500.0, 0.0, True)) + +# =========================================================================== # +print("\n5. AUTO PHASES, THE SAFE SEQUENCE, A ONE-PHASE CAR (T17-T20)") +# =========================================================================== # +for race in (False, True): + tag = "race" if race else "step" + d = 1 if race else 0 + r17 = std(800, sun=step_fn((400, 600.0 + 4500.0), base=600.0 + 3000.0), + race=race) + w17, s17 = cur_writes(r17), selects(r17) + z = [t for t, a, _ in w17 if a == 0.0] + check(f"T17 [{tag}]: 4500 W from 400 s: the sequence starts (its 0 A) at " + f"580 s, not 579 s ({w17}, {[x[0] for x in s17]})", + z[:1] in ([580.0], [580.0 + d]) and len(s17) == 1 + and s17[0][2] == 3) +r17b = std(3600, sun=step_fn((400, 600.0 + 4499.0), base=600.0 + 3000.0)) +check("T17: 4499 W for an hour on 1 phase: never a select", + selects(r17b) == []) +r17c = std(1900, sun=step_fn((400, 600.0 + 4500.0), (1000, 600.0 + 3999.0), + base=600.0 + 3000.0)) +s17c = selects(r17c) +check(f"T17: on 3 phases, 3999 W from 1000 s: to 1 phase at 1300 s " + f"({[(x[0], x[2]) for x in s17c]}, {cur_writes(r17c)[-2:]})", + len(s17c) == 2 and s17c[1][2] == 1 and 1300 <= s17c[1][0] <= 1312 + and cur_writes(r17c)[-1][1] == 16.0) +r17d = std(4600, sun=step_fn((400, 600.0 + 4500.0), (1000, 600.0 + 4000.0), + base=600.0 + 3000.0)) +check(f"T17: on 3 phases, 4000 W for an hour: never back to 1 phase, no " + f"pause ({[(x[0], x[2]) for x in selects(r17d)]})", + len(selects(r17d)) == 1 and r17d["sim"].setpoint_a == 6.0) +r17e = std(3600, sun=lambda t: 600.0 + 4000.0 + 499.0 * (t % 2)) +check("T17: the 4.0-4.5 kW band for an hour: never a select", + selects(r17e) == []) +nevers(r17c, "T17") + +# T18: up, down, up within 10 minutes. +r18 = std(2400, sun=step_fn((400, 600.0 + 4600.0), (700, 600.0 + 3000.0), + (1100, 600.0 + 4600.0), base=600.0 + 3000.0)) +s18 = [x[0] for x in selects(r18)] +check(f"T18: crossings up, down, up: at most one select per 600 s, the " + f"second waits for 600 s after the first ({s18})", + len(s18) >= 2 and all(b - a >= 600.0 for a, b in zip(s18, s18[1:])) + and s18[1] - s18[0] < 620) +nevers(r18, "T18") + +# T19: every Solar phase change, a slow car among them. +for slow in (False, True): + sim19 = SimCharger(setpoint_a=0) + if slow: + sim19.stop_delay_s = 15.0 + sim19.ramp_w_s = 300.0 + r19 = std(1600, sun=step_fn((400, 600.0 + 6900.0), (1000, 600.0 + 3000.0), + base=600.0 + 3000.0), sim=sim19) + seq_bad = [] + log19 = r19["sim"].log + for i, (t, what, v, pw, sp) in enumerate(log19): + if what != "phases": + continue + before = [x for x in log19[:i] if x[1] == "current"] + after = [x for x in log19[i + 1:] if x[1] == "current"] + if not before or before[-1][2] != 0.0: + seq_bad.append(("no 0 A first", t)) + if pw >= carmode.QUIET_W and before \ + and t - before[-1][0] < carmode.ZERO_WAIT_S: + seq_bad.append(("select while drawing", t, pw)) + if not after or after[0][0] - t < carmode.SETTLE_S: + seq_bad.append(("no 10 s settle", t)) + n = v + if after and after[0][2] not in (amps_for( + r19["plant"].sun(after[0][0]) - 500.0 - 100.0, n, 16), + CH.MIN_A): + seq_bad.append(("not floor(car_w/(230 x n))", after[0])) + check(f"T19 ({'slow car' if slow else 'quick car'}): every select comes " + f"after the 0 A, under 100 W or out of C (or the 20 s cap), then " + f"10 s, then floor(target/(230 x new n)) ({seq_bad}, " + f"{[(x[0], x[2]) for x in selects(r19)]})", + not seq_bad and len(selects(r19)) == 2) + nevers(r19, f"T19 {'slow' if slow else 'quick'}") +# A car that is still drawing at EV-04's 20 s cap (200 W/s from 6 A on 3 +# phases): no select, the current back on the old phases, and the plan back +# where it was (nothing meant for 1 phase is written on 3). +for pmin, back in ((10, 6.0), (5, 0.0)): + sim19f = SimCharger(setpoint_a=0) + sim19f.stop_delay_s, sim19f.ramp_w_s = 15.0, 200.0 + r19f = std(1500, sun=step_fn((400, 600.0 + 6900.0), + (1000, 600.0 + 3000.0), + base=600.0 + 3000.0), sim=sim19f, + opts={"ev_pause_min": pmin}) + w19f = [(t, a) for t, a, _ in cur_writes(r19f) if t >= 1290] + check(f"T19 (failed, ev_pause_min {pmin}): the car still draws at the " + f"20 s cap: no select to 1 phase; " + f"{'the hold 6 A back on 3 phases' if back else 'the hold has run out, so the 0 A stands (N3)'}" + f"; no 1-phase current on 3 phases " + f"({w19f}, selects {[(x[0], x[2]) for x in selects(r19f)]})", + len(selects(r19f)) == 1 and w19f[:1] == [(1300.0, 0.0)] + and (nth(w19f, 1)[1] == 6.0 if back else len(w19f) == 1) + and not [a for t, a in w19f if a > 6.0]) + nevers(r19f, f"T19 (failed, {pmin} min)") +r19a = std(1800, sun=const(600.0 + 6900.0), opts={"ev_phases": "1"}) +check(f"T19: fixed 1 with 6.9 kW for 30 min: no select, 16 A " + f"({cur_writes(r19a)})", selects(r19a) == [] + and [a for _, a, _ in cur_writes(r19a)] == [16.0]) +r19b = std(900, sun=const(600.0 + 3000.0), opts={"ev_phases": "3"}, + phases=3) +check("T19: fixed 3 with 3 kW: no select, no start (4830 W needed)", + selects(r19b) == [] and cur_writes(r19b) == []) +r19c = std(1000, sun=step_fn((400, 600.0 + 3000.0), base=600.0 + 5600.0), + opts={"ev_phases": "3"}, phases=3) +check(f"T19: fixed 3 running, then 3 kW: no select, the hold, then the " + f"pause ({cur_writes(r19c)})", selects(r19c) == [] + and [a for _, a, _ in cur_writes(r19c)] == [8.0, 6.0, 0.0]) + +# T20: a one-phase car on a 3-phase allowance. +sim20 = SimCharger(setpoint_a=0) +r20 = run("T20", std, 900, sim=sim20, phases=3, car_phases=1, + opts={"ev_phases": "3"}, + sun=step_fn((400, 600.0 + 2900.0 - 100.0), base=600.0 + 4900.0), + events={700: lambda p, c: p.ch.unplug(), + 710: lambda p, c: p.ch.plug_in(car_phases=3)}) +tr20 = r20["trace"] +marked = next((x["t"] for x in tr20 if x["single"]), None) +w20 = cur_writes(r20) +check(f"T20: the one-phase car is marked within 30 s of drawing (start " + f"{w20[:1]}, marked at {marked})", + marked is not None and w20 and marked - w20[0][0] <= 30) +check(f"T20: on 1-phase arithmetic: 16 A on 4.8 kW, then floor(2800/230) = " + f"12 A on 2.9 kW, no pause from the 4.2 A 3-phase figure ({w20})", + 12.0 in [a for t, a, _ in w20 if 400 <= t < 700] + and not any(a == 0.0 for t, a, _ in w20 if t < 700)) +check("T20: cleared on unplug; a balanced 3-phase car is never marked", + not tr20[705]["single"] and not any(x["single"] for x in tr20 + if x["t"] >= 700)) + +report() diff --git a/goodwe_controller/test_ev20_exits.py b/goodwe_controller/test_ev20_exits.py new file mode 100644 index 0000000..7039a3b --- /dev/null +++ b/goodwe_controller/test_ev20_exits.py @@ -0,0 +1,579 @@ +"""EV-20: every way out of Solar ends at 0 A (T23-T37, T61; N9, N12, N14). +`python3 -B test_ev20_exits.py` + +The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and +`chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit +rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section +names the T-ids and N-ids of reports/EV-20-test-plan.md it implements. +"Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare +2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start. +Times are the cycle's second; `race` runs use the production order (read, the +writer settles, the cycle). + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import json +import math +import os +import random +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402 +from app import mqtt, validate, web, main as app_main # noqa: E402 +from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from ev20_kit import * # noqa: E402,F401,F403 +from ev20_kit import LOG, check, fails, report # noqa: E402,F401 +from named_absence import nth, present # noqa: E402,F401 +from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401 + _until) + + +# =========================================================================== # +print("\n6. EXIT PATHS END AT 0 A (T23-T37, T61, N9, N12, N14)") +# =========================================================================== # + + +r23 = run("T23", std, 300, finale=_shutdown) +o23 = sets_order(r23) +z23 = [i for i, (t, e, v) in enumerate(o23) if e == SET and v == 0.0] +inv23 = [i for i, (t, e, v) in enumerate(o23) + if e.startswith("number.sp_") and i > (z23[0] if z23 else 0)] +check(f"T23: Controller.shutdown() in Solar at 10 A: one 0 A, sent BEFORE the " + f"first inverter 0 W of command_site_release ({o23[-4:]})", + len(z23) == 1 and bool(inv23) and r23["sim"].setpoint_a == 0.0) +for start, want in (("keep", "solar"), ("off", "off")): + sim23 = r23["sim"] + n0 = len(sim23.log) + rr = std(200, sim=sim23, store=r23["store"], mode="solar", + opts={"ev_mode_start": start}) + if start == "off": + rr["store"].data["car_mode"] = "solar" + new = sim23.log[n0:] + t_restart = 301.0 if start == "keep" else 0.0 + check(f"T23: restart on the same store, ev_mode_start {start}: " + f"{want}{', paused' if want == 'solar' else ''}, " + f"{'no non-zero write for 120 s' if want == 'solar' else 'nothing written'} " + f"({[(x[0], x[2]) for x in new]})", + rr["c"].car_mode == want + and not [x for x in new if x[2] > 0.0 and x[0] - t_restart < 120] + and (want == "solar" or new == [])) + t_restart = sim23.t + + +for kind in ("error", "ignore"): + def mk(kind=kind): + return TSim(setpoint_a=0, windows=[(299.5, 306.5, kind)]) + sim = mk() + r23b = run("T23b", std, 300, sim=sim, finale=_shutdown) + tries = [(t, v) for t, v in attempts(r23b) if t >= 299] + gap = [b[0] - a[0] for a, b in zip(tries, tries[1:])] + rel = _until(r23b, 299.0) + check(f"T23 (b) D3 [{kind}]: the 0 A refused for 7 s from shutdown: tries " + f"about 0, 5, 10 s (3 at most, >= 4 s apart), the third taken, then " + f"the inverters 0 W, all within 15 s ({tries}, release +{rel})", + len(tries) == 3 and all(g >= 4.0 for g in gap) + and r23b["sim"].setpoint_a == 0.0 and rel is not None + and rel <= 15.0 and r23b["c"].car_solar.released is True) +for kind in ("error", "ignore"): + sim = TSim(setpoint_a=0, windows=[(299.5, 1e9, kind)]) + n = LOG.mark() + r23c = run("T23c", std, 300, sim=sim, finale=_shutdown) + tries = [(t, v) for t, v in attempts(r23c) if t >= 299] + rel = _until(r23c, 299.0) + warn = [m for m in LOG.since(n, "WARNING") if "CHARGER_RELEASE" in m] + check(f"T23 (c) D3 [{kind}]: refused for the whole shutdown: 3 tries, the " + f"inverters' 0 W by 15 s (+{rel}), one warning that the car may still " + f"be charging, the notice raised after the inverters ({tries})", + len(tries) == 3 and rel is not None and rel <= 15.0 + and len(warn) == 1 and any(n_ == messages.ID_CAR_RELEASE + for _, n_ in r23c["raised"]) + and r23c["store"].data.get(ctl_car.CAR_RELEASE_KEY) is True) + sim.windows = [] + n0 = len(sim.log) + rr = std(300, sim=sim, store=r23c["store"], mode="solar") + new = [(x[0], x[2]) for x in sim.log[n0:]] + check(f"T23 (c)/D2 [{kind}]: restart on the same store (keep): the first " + f"charger write is 0 A, then only the start rule; the notice comes " + f"down ({new})", new[:1] and new[0][1] == 0.0 + and new[0][0] - sim.log[n0][0] <= 1 + and not [x for x in new[1:] if x[1] > 0 and x[0] - new[0][0] < 119] + and any(n_ == messages.ID_CAR_RELEASE + for _, n_ in rr["plant"].dismissed)) + + +async def _hang_shutdown(p, c): + p.hang = True + await c.shutdown() + +keep_wait = ctl_car.RELEASE_WAIT_S +ctl_car.RELEASE_WAIT_S = 0.3 +try: + import time as _time + t_0 = _time.monotonic() + r23u = run("T23u", std, 300, plant_cls=HangPlant, finale=_hang_shutdown) + took = _time.monotonic() - t_0 +finally: + ctl_car.RELEASE_WAIT_S = keep_wait +inv_u = [v for t, e, v in r23u["plant"].sets if e.startswith("number.sp_") + and t >= 299] +check(f"T23: a charger that never answers delays the inverter release by " + f"RELEASE_WAIT_S at most (15 s; 0.3 s here), then the inverters go to " + f"0 W ({inv_u[-2:]}) and the warning stands", + ctl_car.RELEASE_WAIT_S == 15.0 and inv_u and inv_u[-1] == 0.0 + and r23u["c"]._car_release_failed) + +# T24: the control task dies. + + +r24 = run("T24", std, 300, finale=_dies) +o24 = sets_order(r24) +z24 = [i for i, (t, e, v) in enumerate(o24) if e == SET and v == 0.0] +check(f"T24: the control task dies: 0 A once, before the inverters' 0 W; " + f"exit code 70 unchanged ({o24[-3:]})", + len(z24) == 1 and app_main.EXIT_CONTROL_DIED == 70 + and r24["plant"].died == (True, 1) + and any(e.startswith("number.sp_") for t, e, v in o24[z24[0]:])) +sim24 = TSim(setpoint_a=0, windows=[(299.5, 1e9, "error")]) +r24c = run("T24c", std, 300, sim=sim24, finale=_dies) +check(f"T24 D3: refused throughout: 3 tries about 5 s apart, the inverters " + f"by 15 s, the warning ({[t for t, v in attempts(r24c) if t >= 299]})", + len([1 for t, v in attempts(r24c) if t >= 299]) == 3 + and _until(r24c, 299.0) <= 15.0 and r24c["c"]._car_release_failed) +sim24b = TSim(setpoint_a=0, windows=[(299.5, 306.5, "error")]) +r24b = run("T24b", std, 300, sim=sim24b, finale=_dies) +check("T24 D3: refused for 7 s: the third try is taken, the inverters after", + r24b["sim"].setpoint_a == 0.0 and r24b["c"].car_solar.released is True) + +# T25: Stop, with shadow_mode off and the shipped auto. +for sm in ("off", "auto"): + r25 = std(800, opts={"shadow_mode": sm}, + events={300: act("auto_toggle", None), + 600: act("auto_toggle", None)}) + w25 = cur_writes(r25) + check(f"T25 [shadow_mode {sm}]: Stop at 300 s: 0 A once within 1 cycle, " + f"nothing while stopped; after Start only the start rule " + f"(10 A at 720 s) ({w25})", + [(t, a) for t, a, _ in w25] == [(120.0, 10.0), (300.0, 0.0), + (720.0, 10.0)]) + +# T26: the safety latches. +for name, fn in (("sign_wd", lambda p, c: setattr(c.inverters[0].sign_wd, + "tripped", True)), + ("site_sign_wd", lambda p, c: setattr(c.site_sign_wd, + "tripped", True)), + ("circ_wd", lambda p, c: setattr(c.circ_wd, "tripped", + True))): + r26 = std(700, events={300: fn}) + check(f"T26 [{name}]: 0 A once, nothing else while latched " + f"({cur_writes(r26)})", [(t, a) for t, a, _ in cur_writes(r26)] + == [(120.0, 10.0), (300.0, 0.0)]) + +# T27: a charger error. +n27 = LOG.mark() +blk27 = {} + + +def _err_card(p, c): + blk27["b"] = homeview.car_block(c, None) + + +def _err_clear(p, c): + p.ch.error = "0: No Error" + p.ch.state = "B" + + +r27 = std(900, events={300: _err, 400: _err_card, 600: _err_clear}) +w27 = cur_writes(r27) +warn27 = [m for m in LOG.since(n27, "WARNING") if "CHARGER_ERROR" in m] +check(f"T27: a charger error: 0 A once, no write during it, one warning; the " + f"start rule after it clears (10 A at 720 s) ({w27}, {len(warn27)})", + [(t, a) for t, a, _ in w27] == [(120.0, 10.0), (300.0, 0.0), + (720.0, 10.0)] and len(warn27) == 1) +check(f"T27: the card shows it ({blk27.get('b', {}).get('why')!r})", + blk27.get("b", {}).get("why", "").startswith("The charger reports an " + "error")) + +# T28: a stuck reading. +blk28 = {} + + +r28 = std(800, sun=step_fn((125, 600.0 + 2760.0), base=600.0 + 2300.0), + events={150: _freeze_after_write, + 300: lambda p, c: blk28.update(rows=c.checks()), + 600: lambda p, c: p.ch.freeze(False)}, + rows=True) +w28 = cur_writes(r28) +zt = [(t, ok) for t, a, ok in w28 if a == 0.0] +check(f"T28: the reading freezes as the 12 A write (150 s) goes out: 0 A at " + f"150 + 60 s (+1 cycle +10 s), not confirmed by the frozen read-back, " + f"tried 3 times 60 s apart, then the gave-up row ({w28})", + len(zt) == 3 and 210 <= zt[0][0] <= 221 + and all(not ok for _, ok in zt) + and [b[0] - a[0] for a, b in zip(zt, zt[1:])] == [60.0, 60.0] + and "charger_refused" in r28["trace"][450]["amber"]) +check("T28: the amber row 'Charger reading may be stuck'", + "charger_stuck" in [x["id"] for x in blk28.get("rows", [])]) +check(f"T28: no non-zero write until a reading moves; then the start rule " + f"(0 A confirmed by the moved reading, 10 A 120 s later) ({w28[-1:]})", + not [1 for t, a, ok in w28 if a > 0 and 150 < t < 600] + and w28[-1][1] == 12.0 and 718 <= w28[-1][0] <= 722 + if len(w28) > 4 else False) +# (b) the frozen read-back shows 0 A while the charger is not at 0 A: a stuck +# reading confirms nothing, so the 0 A is written (mutant `stuck_trust`). +r28b = std(800, sun=step_fn((200, 600.0 + 1000.0), (330, 600.0 + 6000.0), + base=600.0 + 2300.0), + opts={"ev_pause_min": 1, "ev_start_min": 1}, + events={300: _freeze_after_write, + 700: lambda p, c: p.ch.freeze(False)}) +w28b = cur_writes(r28b) +st28 = [x["t"] for x in r28b["trace"] if x["fault"] == "stuck"] +check(f"T28 (b): frozen at 0 A, then Solar starts (the write unconfirmed): " + f"once stuck, the 0 A is written, not read off the frozen 0 A, and the " + f"charger ends at 0 A ({w28b}, stuck from {st28[:1]})", + bool(st28) and [x for x in w28b if x[0] >= st28[0]][:1] + and [x for x in w28b if x[0] >= st28[0]][0][1] == 0.0 + and r28b["sim"].setpoint_a == 0.0) + +# T29: the charger unavailable 300-420 s. +T29 = {"i": lambda p, c: None, + "ii": lambda p, c: p.ch.set_current(16), + "iii": lambda p, c: p.ch.set_current(6), + "iv": lambda p, c: p.ch.set_phases(3)} +for k, fn in T29.items(): + n = LOG.mark() + rr = std(700, events={300: lambda p, c: p.ch.go_unavailable(True), + 360: fn, + 420: lambda p, c: p.ch.go_unavailable(False)}, + rows=True) + w = cur_writes(rr) + trr = rr["trace"] + other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m] + check(f"T29 ({k}): nothing tried while down; the first write after it is " + f"0 A within 1 cycle; no CHARGER_OTHER, no hold, no amber row for " + f"the charger's own value; then the start rule ({w})", + [a for t, a, _ in w if 300 <= t < 420] == [] + and [x for x in w if x[0] >= 420][:1] + and [x for x in w if x[0] >= 420][0][1] == 0.0 + and [x for x in w if x[0] >= 420][0][0] <= 421 + and not other and not any(x["hold"] for x in trr) + and not any("charger_other" in x["amber"] for x in trr) + and (k != "i" or [(t, a) for t, a, _ in w] + == [(120.0, 10.0), (420.0, 0.0), (540.0, 10.0)])) + +# T29 (v): Solar paused at 0 A before the charger went away; it comes back +# at 16 A (a reboot default): the 0 A is written first all the same. +n = LOG.mark() +rr = std(900, sun=step_fn((200, 600.0 + 1000.0), (560, 600.0 + 2300.0), + base=600.0 + 2300.0), + events={540: lambda p, c: p.ch.go_unavailable(True), + 545: lambda p, c: p.ch.set_current(16), + 600: lambda p, c: p.ch.go_unavailable(False)}) +w = cur_writes(rr) +after = [x for x in w if x[0] >= 600] +other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m] +check(f"T29 (v): paused at 0 A, the charger away 540-600 s and back at 16 A: " + f"0 A first within 1 cycle, then the start rule; no CHARGER_OTHER ({w})", + present(nth(after, 0)) and nth(after, 0)[1] == 0.0 + and nth(after, 0)[0] <= 601 and not other + and [a for t, a, _ in w if t < 600][-1:] == [0.0]) + +# T30: Home Assistant not answering 300-420 s. +for k, fn in (("i", lambda p, c: None), + ("ii", lambda p, c: p.ch.set_current(16))): + n = LOG.mark() + rr = std(700, events={300: lambda p, c: setattr(p, "ha_down", True), + 360: both(fn, mqtt_cmd("goodwe_ctl/car/current/set", + b"14")), + 420: lambda p, c: setattr(p, "ha_down", False)}) + w = cur_writes(rr) + other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m] + after = [x for x in w if x[0] >= 420] + check(f"T30 ({k}): HA not answering: nothing written while down (a lost " + f"MQTT command changes no current); when back 0 A first, then the " + f"start rule; no CHARGER_OTHER ({w})", + [x for x in attempts(rr) if 300 <= x[0] < 420] == [] + and present(nth(after, 0)) and nth(after, 0)[1] == 0.0 + and nth(after, 0)[0] <= 422 + and not other and not any(x["hold"] for x in rr["trace"])) + +# T31: the meter goes silent at 10 A. +for race in (False, True): + tag = "race" if race else "step" + d = 1 if race else 0 + r31 = std(900, events={300: lambda p, c: setattr(p, "meter_on", False)}, + race=race) + w31 = cur_writes(r31) + check(f"T31 (a) [{tag}]: silent from 300 s (the last sample 299.7 s): " + f"no write until 15 + 300 s, then 0 A once (+2 s) ({w31})", + [a for _, a, _ in w31] == [10.0, 0.0] + and 614 <= w31[-1][0] <= 617 + d) +r31b = std(900, events={300: lambda p, c: setattr(p, "meter_on", False), + 500: lambda p, c: setattr(p, "meter_on", True)}) +check(f"T31 (b): back at 200 s: no 0 A ({cur_writes(r31b)})", + [a for _, a, _ in cur_writes(r31b)] == [10.0]) + +# T32: READINGS_LATE at 10 A. + + +def _late(fn): + def ev(p, c): + c._readings_late = lambda standing, p=p: fn(p.t) + return ev + + +r32a = std(700, events={300: _late(lambda t: 10.0 if 300 <= t < 340 + else None)}, + sun=step_fn((310, 600.0 + 3000.0), base=600.0 + 2300.0)) +w32a = cur_writes(r32a) +check(f"T32 (a): late_s 10 s, then caught up: held, nothing written during " + f"it; the 30 s / 1 A rule after ({w32a})", + not [x for x in w32a if 300 <= x[0] < 340] and w32a[0][1] == 10.0) +r32b = std(900, events={300: _late(lambda t: (t - 300.0) + 1.0 + if 300 <= t < 700 else None)}) +w32b = cur_writes(r32b) +w32b = [x for x in w32b if x[0] < 700] +check(f"T32 (b): late past 15 s for 400 s: the late hold ends at 15 s, then " + f"the stale rule: 0 A once by 15 + 300 + 2 s ({w32b})", + [a for _, a, _ in w32b] == [10.0, 0.0] + and 612 <= w32b[-1][0] <= 617) + +# T32 (c): a late verdict that keeps coming back under the stale bound (0 to +# 10 s, over and over) while Solar holds 6 A: the hold still ends at its 300 s. +r32c = std(900, sun=step_fn((200, 600.0 + 1000.0), base=600.0 + 2300.0), + events={210: _late(lambda t: float((t - 210.0) % 11.0) + if 210 <= t < 800 else None)}) +w32c = cur_writes(r32c) +check(f"T32 (c): a READINGS_LATE verdict that keeps coming back while Solar " + f"holds 6 A: the 0 A still comes at the hold's 300 s, +2 s ({w32c})", + [a for _, a, _ in w32c] == [10.0, 6.0, 0.0] + and 499 <= w32c[-1][0] <= 502) + +# T33: a phase sequence interrupted. +INT = {"Off": act("car_mode", "off"), + "shadow": lambda p, c: c.o.__setitem__("shadow_mode", "on"), + "Stop": lambda p, c: setattr(c, "auto", False), + "latch": lambda p, c: setattr(c.circ_wd, "tripped", True), + "unplug": lambda p, c: p.ch.unplug()} +t33 = {} +for stage, dt in (("zero", 2), ("settle", 6)): + for name, fn in list(INT.items()) + [("shutdown", None)]: + sim33 = SimCharger(setpoint_a=0) + sim33.ramp_w_s = 600.0 # under 100 W only after ~5 s + ev = {} + fin = None + if fn is None: + fin = _shutdown + dur = 580 + dt + else: + ev = {580 + dt: fn} + dur = 700 + rr = std(dur, sun=step_fn((400, 600.0 + 4500.0), base=600.0 + 3000.0), + sim=sim33, events=ev, finale=fin) + w = cur_writes(rr) + zeros = [x for x in w if x[1] == 0.0] + sel = selects(rr) + t33[(stage, name)] = (w[-2:], [(x[0], x[2]) for x in sel]) + ok = rr["sim"].setpoint_a == 0.0 and present(nth(w, -1)) \ + and nth(w, -1)[1] == 0.0 \ + and not [x for x in w if x[0] > 580 and x[1] > 0.0] + if stage == "zero": + ok = ok and sel == [] + if name in ("Off", "shadow"): + ok = ok and len(zeros) == 1 + check(f"T33 [{stage}, {name}]: ends at 0 A, no select after it, no " + f"restore of the old current ({t33[(stage, name)]})", ok) + +# T34: unplug at 10 A; replug. +r34 = std(4500, events={800: lambda p, c: p.ch.unplug(), + 4400: lambda p, c: p.ch.plug_in()}) +w34 = cur_writes(r34) +check(f"T34: unplug at 800 s: one 0 A within 1 cycle (+ read-back), then " + f"nothing for 3600 s; replug: no write before the start rule ({w34})", + [(t, a) for t, a, _ in w34] == [(120.0, 10.0), (800.0, 0.0)]) +sim34 = TSim(setpoint_a=0, windows=[(800.0, 806.0, "error")]) +r34b = std(1000, sim=sim34, events={800: lambda p, c: p.ch.unplug()}) +check(f"T34 (b): the unplug 0 A refused once: tried again at +60 s, taken, " + f"then nothing ({cur_writes(r34b)})", + [(t, a, ok) for t, a, ok in cur_writes(r34b)] + == [(120.0, 10.0, True), (800.0, 0.0, False), (860.0, 0.0, True)]) +r34m = std(1000, mode="manual", events={800: lambda p, c: p.ch.unplug()}) +check("T34 guard: Manual unplug writes nothing", + not [x for x in r34m["sim"].log if x[0] > 800]) + +# T35: Solar to Off / shadow; the guards. +r35a = std(1300, events={600: act("car_mode", "off"), + 620: act("car_current", 14), + 630: act("car_phases", 3)}) +check(f"T35 (a): Solar to Off, then the user sets 14 A and 3 phases while " + f"Off for 600 s: one 0 A within 1 cycle, then nothing " + f"({cur_writes(r35a)}, sim {len(r35a['sim'].log)})", + [(t, a) for t, a, _ in cur_writes(r35a)] == [(120.0, 10.0), + (600.0, 0.0)] + and len(r35a["sim"].log) == 2) +for how, fn in (("option on", lambda p, c: c.o.__setitem__("shadow_mode", + "on")), + ("auto, stopped", lambda p, c: setattr(c, "auto", False))): + blk = {} + rr = std(1300, opts={"shadow_mode": "auto"} if how != "option on" else {}, + events={600: fn, 900: lambda p, c: blk.update( + b=homeview.car_block(c, None))}) + check(f"T35 (b) [{how}]: one 0 A within 1 cycle, then nothing; the card " + f"says what it would set ({cur_writes(rr)}, " + f"{blk.get('b', {}).get('why')!r})", + [(t, a) for t, a, _ in cur_writes(rr)] == [(120.0, 10.0), + (600.0, 0.0)] + and "would set 10 A" in blk.get("b", {}).get("why", "")) +for how, fn in (("Off", act("car_mode", "off")), + ("shadow", lambda p, c: c.o.__setitem__("shadow_mode", "on"))): + rr = std(900, sun=step_fn((200, 600.0 + 1000.0), base=600.0 + 2300.0), + events={600: fn}) + check(f"T35 (c): Solar paused at 0 A, then {how}: no write " + f"({cur_writes(rr)})", [a for _, a, _ in cur_writes(rr)] + == [10.0, 6.0, 0.0] and not [x for x in cur_writes(rr) + if x[0] >= 600]) +for how, ev in (("(d) Manual to Off", {600: act("car_mode", "off")}), + ("(e) shadow on in Manual", + {600: lambda p, c: c.o.__setitem__("shadow_mode", "on")})): + rr = std(900, mode="manual", events=ev) + check(f"T35 {how}: zero writes, as EV-04", + [x for x in rr["sim"].log if x[0] > 600] == []) +r35f = std(900, events={600: act("car_mode", "manual"), + 601: act("car_current", 13)}) +check(f"T35 (f): Solar to Manual: no Solar 0 A; Manual writes its own " + f"current ({[(x[0], x[2]) for x in r35f['sim'].log]})", + [x[2] for x in r35f["sim"].log if x[0] > 600][:1] in ([6.0], [13.0]) + and 0.0 not in [x[2] for x in r35f["sim"].log if x[0] > 600]) + +# T36: EV-05 r2 Critical, the exit 0 A refused then taken, on every path. + + +def _meter_off(p, c): + p.meter_on = False + + +PATHS = { + "Stop (shadow_mode off)": (300, {300: lambda p, c: setattr(c, "auto", + False)}, + {"shadow_mode": "off"}), + "Stop (auto)": (300, {300: lambda p, c: setattr(c, "auto", False)}, + {"shadow_mode": "auto"}), + "Off": (300, {300: act("car_mode", "off")}, {}), + "shadow on": (300, {300: lambda p, c: c.o.__setitem__("shadow_mode", + "on")}, {}), + "latch": (300, {300: lambda p, c: setattr(c.circ_wd, "tripped", True)}, + {}), + "charger error": (300, {300: _err}, {}), + "unplug": (300, {300: lambda p, c: p.ch.unplug()}, {}), + "meter stale": (514, {200: _meter_off}, {}), + "charger back": (420, {240: lambda p, c: p.ch.go_unavailable(True), + 300: lambda p, c: p.ch.set_current(16), + 420: lambda p, c: p.ch.go_unavailable(False)}, {}), + "HA back": (420, {240: lambda p, c: setattr(p, "ha_down", True), + 300: lambda p, c: p.ch.set_current(16), + 420: lambda p, c: setattr(p, "ha_down", False)}, {}), +} +for name, (t0, ev, opts) in PATHS.items(): + for kind in ("error", "ignore"): + sim = TSim(setpoint_a=0, windows=[(t0, t0 + 6.0, kind)]) + rr = std(t0 + 150, sim=sim, events=ev, opts=opts) + w = [(t, a, ok) for t, a, ok in cur_writes(rr) if t >= t0 - 1] + rel = [(round(t - w[0][0]), a, ok) for t, a, ok in w] if w else [] + check(f"T36 [{name}, {kind}]: the way-out 0 A not taken at t, tried " + f"again at t + 60 s and taken; 0 A and the car at 0 W by " + f"t + 70 s; nothing more ({w})", + rel == [(0, 0.0, False), (60, 0.0, True)] + and present(nth(w, 0)) and abs(nth(w, 0)[0] - t0) <= 1 + and rr["sim"].setpoint_a == 0.0 + and rr["sim"].power_w == 0.0) + n = LOG.mark() + blk = {} + sim = TSim(setpoint_a=0, windows=[(t0, t0 + 400.0, "error")]) + ev2 = dict(ev) + ev2[t0 + 190] = lambda p, c: blk.update(b=homeview.car_block(c, None), + rows=c.checks()) + rr = std(t0 + 200, sim=sim, events=ev2, opts=opts) + w = [(round(t - t0), a, ok) for t, a, ok in cur_writes(rr) if t >= t0 - 1] + warn = [m for m in LOG.since(n, "WARNING") if "CHARGER_REFUSED" in m] + check(f"T36 [{name}, kept]: tries at t, t+60, t+120, then the gave-up row " + f"and one CHARGER_REFUSED warning; the card does not say paused " + f"({w}, {blk.get('b', {}).get('why')!r})", + len(w) == 3 and abs(w[0][0]) <= 1 + and [d - w[0][0] for d, a, ok in w] == [0, 60, 120] + and all(a == 0.0 and not ok for _, a, ok in w) + and len(warn) == 1 + and "charger_refused" in [x["id"] for x in blk.get("rows", [])] + and "paused" not in blk.get("b", {}).get("why", "paused")) + +# T37: shutdown while a start write waits for its read-back. + + +async def _start_then_shutdown(p, c): + """The cycle of 120 s starts the 10 A write; the add-on stops while it + waits for its read-back (the model's sleep yields, as a real one).""" + async def sleep(s): + p.ch.tick(s) + p.clock[0] += s + p.t = p.clock[0] + await asyncio.sleep(0) + c.charger._sleep = sleep + p.ch.tick(1.0) + p.clock[0] = p.t = 120.0 + await c.read_inputs(now_mono=120.0) + await c.cycle() + for _ in range(200): # the 10 A write is out, unconfirmed + await asyncio.sleep(0) + if c.car_solar.sent_a == 10.0: + break + for _ in range(3): + await asyncio.sleep(0) + p.inflight = (c.car_solar.sent_a, c.car_solar.taken) + await c.shutdown() + p.ch.tick(30) + + +sim37 = SimCharger(setpoint_a=0) +sim37.lag_s = 8.0 +r37 = run("T37", std, 120, sim=sim37, finale=_start_then_shutdown) +check(f"T37: shutdown while the 0 -> 10 A start write waits for its " + f"read-back (lag 8 s): release writes 0 A and the charger ends at 0 A " + f"({getattr(r37['plant'], 'inflight', None)}, " + f"{[(x[0], x[2]) for x in sim37.log]}, sp {sim37.setpoint_a})", + getattr(r37["plant"], "inflight", None) == (10.0, False) + and [x[2] for x in sim37.log][-1:] == [0.0] + and sim37.setpoint_a == 0.0) + +# T61: the start-up in Solar after a stop with no release. +for k, sp, kw in (("10 A, keep", 10, {}), + ("16 A by another writer", 16, {}), + ("shadow on (option)", 16, {"opts": {"shadow_mode": "on"}}), + ("shadow auto, control stopped", 16, + {"opts": {"shadow_mode": "auto"}, "stopped": True}), + ("ev_mode_start off", 10, + {"opts": {"ev_mode_start": "off"}})): + n = LOG.mark() + sim61 = SimCharger(setpoint_a=sp) + opts = kw.get("opts", {}) + ev = {0: lambda p, c: setattr(c, "auto", False)} if kw.get("stopped") \ + else {} + rr = std(300, sim=sim61, opts=opts, events=ev) + w = cur_writes(rr) + other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m] + if "shadow" in k or "off" in k: + check(f"T61 [{k}]: nothing written ({w})", sim61.log == []) + else: + check(f"T61 [{k}]: D2: the first charger write is 0 A within 1 cycle " + f"of the first reading, then only the start rule; no " + f"CHARGER_OTHER ({w})", + present(nth(w, 0)) and nth(w, 0)[1] == 0.0 + and nth(w, 0)[0] <= 1.0 + and [(t, a) for t, a, _ in w[1:]] == [(120.0, 10.0)] + and not other) + +report() diff --git a/goodwe_controller/test_ev20_fuzz.py b/goodwe_controller/test_ev20_fuzz.py new file mode 100644 index 0000000..8c8b63a --- /dev/null +++ b/goodwe_controller/test_ev20_fuzz.py @@ -0,0 +1,312 @@ +"""EV-20: T54, the fuzz. `python3 -B test_ev20_fuzz.py` + +14 sites of random spare, outages, unplugs, refusals (at the exits too), other +writers (while stopped and in shadow too), a silent meter, shadow and Stop +toggles mid-sequence, Solar / Off / Manual changes; half in the production +cycle order. N1-N3, N5, N9, N10, N12-N14 and N16 on every step (N4 is +EV-21's; N6-N8, N11 and N15 are rows of test_ev20_*.py). +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import logging +import os +import random +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +class _Log(logging.Handler): + def __init__(self): + super().__init__(logging.DEBUG) + self.tb = [] + + def emit(self, r): + if r.exc_info: + self.tb.append(r.getMessage()) + + +LOG = _Log() +_g = logging.getLogger("goodwe") +_g.addHandler(LOG) +_g.setLevel(logging.DEBUG) +_g.propagate = False + + +def cur_writes(r): + return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log + if x[0] == "current"] + + +# =========================================================================== # +print("T54: THE FUZZ") +# =========================================================================== # +SITES = 14 +STEPS_PER = int(os.environ.get("EV20_FUZZ_STEPS", "2400")) + + +class FSim(SimCharger): + """The model, knowing who set its current last: the add-on in Solar (or + on its way out of Solar), Manual, or another writer.""" + ctl = None + setter = None + + def _apply(self, what, v): + if what == "current": + c = self.ctl + self.setter = ("manual" if c is not None + and c.car_mode == "manual" else "solar") + super()._apply(what, v) + + def set_current(self, a): + self.setter = "other" + super().set_current(a) + + +def fuzz_site(seed): + rnd = random.Random(seed) + sim = FSim(setpoint_a=rnd.choice([0, 6, 10, 16])) + sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0]) + if seed % 3 == 0: + sim.ramp_w_s, sim.stop_delay_s = 300.0, 4.0 + state = {"sun": rnd.uniform(3000, 11000), + "house": rnd.uniform(300, 2000)} + bad, counts, snap = [], {}, {} + seen = {"exit_since": None, "avail": None, "back": []} + + def bump(k): + counts[k] = counts.get(k, 0) + 1 + + async def ev(p, c): + sim.ctl = c + w = c.car_solar + t = p.t + # Outages end by themselves. + for k, off in (("outage", lambda: p.ch.go_unavailable(False)), + ("ha", lambda: setattr(p, "ha_down", False)), + ("meter", lambda: setattr(p, "meter_on", True)), + ("stop", lambda: setattr(c, "auto", True)), + ("shadow", lambda: c.o.__setitem__("shadow_mode", + "off"))): + if state.get(k) is not None and t >= state[k]: + off() + state[k] = None + if state.get("mode") is not None and t >= state["mode"]: + state["mode"] = None + await c.handle_action("car_mode", value="solar") + x = rnd.random() + if x < 0.02: + state["sun"] = max(0.0, min(12000.0, state["sun"] + + rnd.uniform(-4000, 4000))) + bump("spare") + elif x < 0.023: + state["house"] = rnd.uniform(300, 4000) + elif x < 0.0245 and state.get("outage") is None: + p.ch.go_unavailable(True) + state["outage"] = t + rnd.uniform(5, 120) + bump("outage") + elif x < 0.0255 and state.get("ha") is None: + p.ha_down = True + state["ha"] = t + rnd.uniform(5, 120) + bump("ha") + elif x < 0.0265: + (p.ch.unplug if p.ch.state != "A" else p.ch.plug_in)() + bump("unplug") + elif x < 0.0295: + p.ch.refuse = rnd.choice([None, None, "ignore", "error"]) + bump("refuse" + ("_exit" if not c.car_writing() + or c.car_mode != "solar" else "")) + elif x < 0.031: + p.ch.set_current(rnd.choice([0, 6, 13, 16])) + bump("other" + ("_out" if not c.car_writing() else "")) + elif (w.hold or w.gave_up) and x < 0.06: + bump("press") # the user hands it back to Solar + await c.handle_action("car_mode", value="solar") + elif x < 0.032 and state.get("meter") is None: + p.meter_on = False + state["meter"] = t + rnd.uniform(5, 360) + bump("meter") + elif x < 0.0355 or (w.seq is not None and x < 0.15): + k = rnd.choice(["stop", "shadow", "mode"]) + bump(k + ("_seq" if w.seq is not None else "")) + back = t + rnd.uniform(5, 240) + if k == "stop": + c.auto = False + c.o["shadow_mode"] = rnd.choice(["off", "auto"]) + state["stop"] = back + elif k == "shadow": + c.o["shadow_mode"] = "on" + state["shadow"] = back + else: + await c.handle_action("car_mode", value=rnd.choice( + ["off", "manual", "solar"])) + state["mode"] = back + elif x < 0.0365: + await c.handle_action("car_sun_first", value=rnd.choice( + ["batteries", "car"])) + if p.ch.refuse is not None and rnd.random() < 0.02: + p.ch.refuse = None + # What the step of this second starts from (it runs after this, in + # both cycle orders). + snap[p.t] = dict(mode=c.car_mode, writing=c.car_writing(), + live=w.live, hold=w.hold, engaged=w.engaged) + bump("s_" + ("hold" if w.hold else "solar" if c.car_mode == "solar" + and c.car_writing() else "out")) + + def on_cycle(p, c, t): + w, sim = c.car_solar, p.ch + r = c.car.reading + avail = bool(r is not None and r.available) + if avail and seen["avail"] is False: + cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a + seen["back"].append((t, cur)) + seen["avail"] = avail + # N3: Solar never keeps the car at 6 A or more past the pause after + # the spare fell under 6 A worth (while it writes and the charger + # answers: an unreachable charger is held, then set to 0 A on return). + pause_s = 60.0 * carmode.solar_option(c.o, "ev_pause_min") + p_ = w.plan + if c.car_mode == "solar" and c.car_writing() and avail \ + and (w.sent_a or 0.0) >= 6.0 and w.taken \ + and sim.setter == "solar" and sim.setpoint_a >= 6.0 \ + and p_.low_since is not None \ + and t - p_.low_since > pause_s + 2.0: + bad.append((seed, t, "N3 6 A past the pause")) + # N9: an exit from Solar leaves no current of its own standing once + # the charger takes writes again (a minute for the retry). + out = (c.car_mode == "off" or not c.car_writing() + or sim.state in ("A", "E", "F") or bool(r and r.error)) + quiet = (avail and not p.ha_down and sim.refuse is None + and not w.hold and not w.gave_up + and c.car_mode != "manual") + if out and quiet: + seen["exit_since"] = seen["exit_since"] or t + if t - seen["exit_since"] > carmode.RETRY_S + 15.0 \ + and sim.setter == "solar" and sim.setpoint_a > 0.0 \ + and not sim._pending: + bad.append((seed, t, "N9 Solar's current stands after the " + "way out", sim.setpoint_a)) + seen["exit_since"] = t + else: + seen["exit_since"] = None + + race = seed % 2 == 1 + evs = {t: ev for t in range(1, STEPS_PER)} + r = S.drive(lambda t: state["house"], lambda t: state["sun"], + dur=STEPS_PER, first=rnd.choice(["batteries", "car", "car"]), + socs={"a": rnd.uniform(40, 100), "b": rnd.uniform(70, 100)}, + sim=sim, race=race, events=evs, on_cycle=on_cycle, + phases=rnd.choice([1, 3]), + opts={"ev_start_min": rnd.choice([1, 1, 2]), + "ev_pause_min": rnd.choice([1, 2, 5]), + "ev_phases": rnd.choice(["auto", "auto", "1", "3"])}) + c = r["c"] + # N1 + if c.charger.clamp_faults: + bad.append((seed, "N1 clamp fault", c.charger.clamp_faults[:1])) + for t, what, v, pw, sp in sim.log: + if what == "current" and v > min(16.0, sim.station_a) + 1e-9: + bad.append((seed, t, "N1 over the clamp", v)) + # N2 + sel = [x for x in sim.log if x[1] == "phases"] + for a, b in zip(sel, sel[1:]): + if b[0] - a[0] < 600.0: + bad.append((seed, b[0], "N2 two selects inside 600 s")) + for x in sel: + if x[4] > 0.0: + bad.append((seed, x[0], "N2 select with the setpoint up", x)) + log = [x for x in c.car_solar.log if x[0] == "current"] + for kind, a, t, ok in log: + s = snap.get(t) or snap.get(t - 1) + if s is None: + continue + # N16: nothing while EV-04's hold stands. + if s["hold"]: + bad.append((seed, t, "N16 a write under the hold", a)) + # N10: off Solar or not writing, only the owed 0 A. + if (s["mode"] != "solar" or not s["writing"]) \ + and (a > 0.0 or not s["live"]): + bad.append((seed, t, "N10 a write while out", a, s)) + # N12: the first write after the charger (or HA) is back is 0 A, unless + # the charger came back at 0 A already. + for tb, cur in seen["back"]: + nxt = [x for x in log if x[2] >= tb] + if nxt and nxt[0][1] > 0.0 and (cur is None or cur > 0.5): + bad.append((seed, tb, "N12 non-zero first after the return", + nxt[0], cur)) + # N5 / N14 from Solar's own write log: decisions and retries. + dec = [(t, a, ok) for kind, a, t, ok in log] + for i, (t, a, ok) in enumerate(dec): + if i and dec[i - 1][1] == a and not dec[i - 1][2] \ + and t - dec[i - 1][0] < carmode.RETRY_S - 1e-9: + bad.append((seed, t, "N14 a retry under 60 s", a)) + tries = 0 + for i, (t, a, ok) in enumerate(dec): + tries = tries + 1 if (i and dec[i - 1][1] == a + and not dec[i - 1][2]) else 1 + if tries > carmode.MAX_TRIES: + bad.append((seed, t, "N14 more than 3 tries", a)) + nz = [(t, a) for t, a, ok in dec if a > 0.0] + for (t0, a0), (t1, a1) in zip(nz, nz[1:]): + if a1 != a0 and t1 - t0 < carmode.SOLAR_WRITE_S - 1e-9 \ + and not [1 for t, a, ok in dec if t0 < t < t1 and a == 0.0]: + bad.append((seed, t1, "N5 two changes under 30 s", + (t0, a0), (t1, a1))) + for (t0, a0), (t1, a1) in zip(nz, nz[1:]): + if a1 != a0 and abs(a1 - a0) < carmode.SOLAR_STEP_A: + bad.append((seed, t1, "N5 a change under 1 A")) + tally["sel"] += len([x for x in sim.log if x[1] == "phases"]) + tally["zero"] += len([x for x in log if x[1] == 0.0]) + print(f" site {seed:2d} ({'race' if race else 'step'}): " + f"{len(log)} writes, " + f"{len([x for x in sim.log if x[1] == 'phases'])} selects, " + f"{len([x for x in log if x[1] == 0.0])} at 0 A") + return bad, counts, len(sim.log), r + + +all_bad, all_counts, n_writes, steps = [], {}, 0, 0 +tally = {"sel": 0, "zero": 0} +for seed in range(SITES): + b, cnt, nw, r = fuzz_site(seed) + all_bad += b + n_writes += nw + steps += STEPS_PER + for k, v in cnt.items(): + all_counts[k] = all_counts.get(k, 0) + v +n_sel, n_zero = tally["sel"], tally["zero"] +print(f" {SITES} sites x {STEPS_PER} steps, {n_writes} charger writes; " + f"disturbances {sorted(all_counts.items())}") +check(f"T54: N1, N2, N3, N5, N9, N10, N12, N14 and N16 hold on every step " + f"({all_bad[:3]})", not all_bad) +need = ("spare", "outage", "ha", "unplug", "refuse", "refuse_exit", "other", + "other_out", "meter", "stop", "shadow", "mode") +check(f"T54: each disturbance happened, mid-sequence ones too " + f"({[k for k in need if not all_counts.get(k)]})", + all(all_counts.get(k) for k in need) + and (all_counts.get("stop_seq", 0) + all_counts.get("shadow_seq", 0) + + all_counts.get("mode_seq", 0)) > 0) +check(f"T54: Solar did write, select and pause ({n_writes} writes, " + f"{n_sel} selects, {n_zero} at 0 A)", + n_writes >= 5 * SITES and n_sel >= 3 and n_zero >= SITES) +check(f"T54: at least 1200 steps per site, in both cycle orders ({steps})", + STEPS_PER >= 1200) +check("T54/N13: no Traceback", LOG.tb == []) + +print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}") +for f in fails: + print(" FAIL:", f) +sys.exit(1 if fails else 0) diff --git a/goodwe_controller/test_ev20_guard.py b/goodwe_controller/test_ev20_guard.py new file mode 100644 index 0000000..24276a7 --- /dev/null +++ b/goodwe_controller/test_ev20_guard.py @@ -0,0 +1,477 @@ +"""EV-20: the peak guard treats a Solar car as a Manual car; Solar kWh; what +stays unchanged; the strings, docs and settings; the write seam (T21, T22, +T47-T52, T55, T57-T60). +`python3 -B test_ev20_guard.py` + +The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and +`chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit +rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section +names the T-ids and N-ids of reports/EV-20-test-plan.md it implements. +"Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare +2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start. +Times are the cycle's second; `race` runs use the production order (read, the +writer settles, the cycle). + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import json +import math +import os +import random +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402 +from app import mqtt, validate, web, main as app_main # noqa: E402 +from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from ev20_kit import * # noqa: E402,F401,F403 +from ev20_kit import LOG, check, fails, report # noqa: E402,F401 +from named_absence import nth, present # noqa: E402,F401 +from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401 + _until) + + +# =========================================================================== # +print("\n8. THE PEAK GUARD: A SOLAR CAR IS A MANUAL CAR (T21, T22, T47, T48)") +# =========================================================================== # +ALARMS = S.ALARMS + + +def twin(mode, **kw): + return S.drive(kw.pop("house"), kw.pop("sun"), mode=mode, rows=True, + **kw) + + +def manual_twin(rs, **kw): + """The Manual twin of a Solar run: the same plant and events, Manual with + its writer held still, and Solar's own writes put on the charger at the + same seconds, so both runs have the same charger trace and only the mode + differs for the peak guard.""" + ev = dict(kw.pop("events", None) or {}) + + def inert(p, c): + async def nop(*a, **k): + return None + c.car_writer.step = nop + rep_ = {} + for t_sim, what, v, _pw, _sp in rs["sim"].log: + rep_.setdefault(int(round(t_sim)), []).append((what, v)) + for t, acts in rep_.items(): + def put(p, c, acts=acts): + for what, v in acts: + (p.ch.set_current if what == "current" else p.ch.set_phases)(v) + ev[t] = both(ev[t], put) if t in ev else put + ev[0] = both(ev[0], inert) if 0 in ev else inert + return twin("manual", events=ev, **kw) + + +def guard_view(r, t0=0): + return [(x["t"], x["explains"], x["over"], tuple(x["red"]), + x["alarm_w"] is None) for x in r["trace"] if x["t"] >= t0] + + +def notes(r): + return [(t, n) for t, n in r["raised"] + if n in ALARMS + (messages.ID_CAR_OVER,)] + + +# (b) EV-05 r5 shape. +for cover in (True, False): + kw = dict(house=step_fn((1000, 3000.0), base=500.0), sun=const(7000.0), + dur=1800, first="car", phases=3, socs={"a": 10.0, "b": 10.0}, + opts={"ev_phases": "3", "ev_batt_cover": cover}, + events={600: lambda p, c: p.ch.set_current(16)}) + rs = twin("solar", **dict(kw)) + rm = manual_twin(rs, **dict(kw)) + gs, gm = guard_view(rs, 640), guard_view(rm, 640) + diff = [(a, b) for a, b in zip(gs, gm) if a[1:] != b[1:]] + check(f"T21 (b{'' if cover else ', c'}) cover {'on' if cover else 'off'}:" + f" another writer's 16 A in Solar is graded, shown and notified as " + f"the Manual car at 16 A, every cycle from 640 s ({len(diff)} " + f"differ: {diff[:2]})", not diff) + ns, nm = notes(rs), notes(rm) + check(f"T21 (b) cover {'on' if cover else 'off'}: the same notices at the " + f"same seconds +2 s, never silent ({ns} vs {nm})", + len(ns) == len(nm) and all(abs(a[0] - b[0]) <= 2 and a[1] == b[1] + for a, b in zip(ns, nm)) + and (ns or any(x[2] for x in gs))) + check(f"T21: the car's banked quarters are the Manual twin's " + f"({rs['c'].car_peak_q} vs {rm['c'].car_peak_q})", + rs["c"].car_peak_q == rm["c"].car_peak_q) + if not cover: + pj = [(round(a["proj"] or 0), round(b["proj"] or 0)) + for a, b in zip(rs["trace"], rm["trace"]) if a["t"] >= 640 + and round(a["proj"] or 0) != round(b["proj"] or 0)] + check(f"T21 (c): with the cover off, the guard's own projection " + f"(the car left out) is the Manual twin's ({pj[:2]})", not pj) +over_note = [x for x in rs["plant"].notes if x[1] == messages.ID_CAR_OVER] +check("T21 D1: Solar's car-over notice reads 'Solar charges the car at 16 A' " + "(the charger's current), never Manual's stored value", + messages.car_over_solar("16").body.startswith( + "Solar charges the car at 16 A") + and "You set" not in messages.car_over_solar("16").body) + +# (d) EV-05 r6 shape: Stop / shadow / circ_wd at 500 s, other writer at 600. +for name, fn, opts in (("Stop (auto)", lambda p, c: setattr(c, "auto", False), + {"shadow_mode": "auto"}), + ("shadow on", lambda p, c: c.o.__setitem__( + "shadow_mode", "on"), {}), + ("circ_wd", lambda p, c: setattr(c.circ_wd, "tripped", + True), {})): + kw = dict(house=step_fn((1000, 3000.0), base=500.0), sun=const(7000.0), + dur=1500, first="car", phases=3, socs={"a": 10.0, "b": 10.0}, + opts=dict({"ev_phases": "3"}, **opts), + events={500: fn, 600: lambda p, c: p.ch.set_current(16)}) + rs = twin("solar", **dict(kw)) + rm = manual_twin(rs, **dict(kw)) + gs, gm = guard_view(rs, 640), guard_view(rm, 640) + diff = [(a, b) for a, b in zip(gs, gm) if a[1:] != b[1:]] + check(f"T21 (d) [{name}]: graded and shown as the Manual twin each cycle " + f"({len(diff)} differ: {diff[:1]}); notices " + f"{notes(rs)} vs {notes(rm)}", + not diff and [n for _, n in notes(rs)] == [n for _, n in notes(rm)]) + +# T22: EV-15 shapes in Solar: Solar's own 3 -> 1 sequence and own 0 A pause +# with both batteries at the reserve. +for name, sun_fn in ( + ("own 3 -> 1 sequence", step_fn((300, 600.0 + 4600.0), + (700, 600.0 + 3700.0), + base=600.0 + 3000.0)), + ("own 0 A pause", step_fn((700, 600.0 + 600.0), + base=600.0 + 4600.0))): + kw = dict(house=const(600.0), sun=sun_fn, dur=1800, first="car", + socs={"a": 19.0, "b": 19.0}, + opts={"peak_soc_floor": 20, "ev_pause_min": 5}) + rs = twin("solar", **kw) + reds = [(x["t"], x["red"]) for x in rs["trace"] if x["red"]] + check(f"T22 [{name}]: no PEAK_GUARD_FLOOR_LIMITED / saturated, no " + f"goodwe_peak_soc_floor, no red row in any second " + f"({notes(rs)}, {reds[:2]}; writes {cur_writes(rs)[-3:]})", + not [n for _, n in notes(rs) if n in ALARMS] and not reds + and (name != "own 0 A pause" + or [a for _, a, _ in cur_writes(rs)][-1:] == [0.0])) + + +def _overload(p, c): + p.house = const(25000.0) + + +kw = dict(house=const(600.0), sun=step_fn((300, 600.0 + 4600.0), + (700, 600.0 + 3700.0), + base=600.0 + 3000.0), + dur=1200, first="car", socs={"a": 19.0, "b": 19.0}, + opts={"peak_soc_floor": 20}) +rs = twin("solar", **dict(kw, events={1006: _overload})) +seq_at = [x[0] for x in selects(rs)] +ro = twin("off", **dict(kw, events={1006: _overload}), plug=False) +a_s = [t for t, n in notes(rs) if n in ALARMS] +a_o = [t for t, n in notes(ro) if n in ALARMS] +check(f"T22: a 25 kW house overload 6 s into Solar's sequence (select at " + f"{seq_at}): the alarm at the same second as with the car Off (+2 s) " + f"({a_s[:1]} vs {a_o[:1]})", + a_s and a_o and abs(a_s[0] - a_o[0]) <= 2) + +# T47: EV-05 r7 M2 / r8 M2 / r9 Minor: another writer starts the car after +# Solar's own 0 A pause. +for T in (615, 640, 680): + kw = dict(house=step_fn((T + 5, 3000.0), base=500.0), + sun=step_fn((300, 0.0), base=7000.0), dur=T + 200, + first="car", phases=3, socs={"a": 10.0, "b": 10.0}, + opts={"ev_phases": "3"}, + events={T: lambda p, c: p.ch.set_current(16)}) + rs = twin("solar", **dict(kw)) + rm = manual_twin(rs, **dict(kw)) + gs, gm = guard_view(rs, T), guard_view(rm, T) + diff = [(a, b) for a, b in zip(gs, gm) if a[1:] != b[1:]] + own = [x["t"] for x in rs["trace"] if x["t"] >= T and x["own"]] + z = [t for t, a, _ in cur_writes(rs) if a == 0.0] + check(f"T47 [T={T}]: Solar's own 0 A at {z[:1]}; the other writer's car " + f"never counts as Solar's own pause (own-pause seconds from T: " + f"{own[:3]}), rows and car_explains as the Manual twin " + f"({len(diff)} differ: {diff[:1]})", + bool(z) and not own and not diff) +# Solar's own pause is graded as its own for at most OWN_PAUSE_MAX_S. +kw = dict(house=const(500.0), sun=step_fn((300, 0.0), base=7000.0), dur=1200, + first="car", phases=3, socs={"a": 10.0, "b": 10.0}, + opts={"ev_phases": "3"}) +rs = twin("solar", **kw) +z = [t for t, a, _ in cur_writes(rs) if a == 0.0] +own = [x["t"] for x in rs["trace"] if x["own"]] +check(f"T47: the grace of Solar's own 0 A (at {z[:1]}) lasts at most " + f"OWN_PAUSE_MAX_S ({ctl_car.OWN_PAUSE_MAX_S:.0f} s): own-pause seconds " + f"{own[:1]}..{own[-1:]}", + bool(z) and bool(own) and own[0] >= z[0] - 1 + and own[-1] - z[0] <= ctl_car.OWN_PAUSE_MAX_S + 1) + +# T48: EV-05 r9 Major 2, a read-back later than TOOK_S. + + +def _lag(on): + def f(p, c): + p.ch.lag_s = 12.0 if on else 0.0 + return f + + +for race in (False, True): + tag = "race" if race else "step" + n = LOG.mark() + kw = dict(sun=step_fn((200, 3600.0), base=2900.0), race=race, + rows=True) + rl = std(1300, events={190: _lag(True), 260: _lag(False)}, **kw) + r0 = std(1300, **kw) + wl = cur_writes(rl) + trl = rl["trace"] + refused = [m for m in LOG.since(n, "WARNING") if "CHARGER_REFUSED" in m] + check(f"T48 [{tag}]: the 13 A write at 200 s is not confirmed in 10 s and " + f"shows at ~213 s: within 1 cycle it counts as taken (no retry at " + f"260 s, no fail count, no CHARGER_REFUSED, no hold, no amber row) " + f"({wl})", + [a for _, a, _ in wl] == [10.0, 13.0] and wl[1][2] is False + and trl[215]["taken"] and trl[215]["fails"] == 0 + and not refused and not any(x["hold"] for x in trl) + and not [a for x in trl if x["t"] >= 216 for a in x["amber"] + if a.startswith(("charger", "car"))]) + d48 = [(a["t"], a["explains"], a["over"], b["explains"], b["over"]) + for a, b in zip(trl, r0["trace"]) if a["t"] >= 230 + and (a["explains"], a["over"]) != (b["explains"], b["over"])] + q1, q0 = rl["c"].car_peak_q, r0["c"].car_peak_q + check(f"T48 [{tag}]: car_explains and car_over equal the no-lag twin; " + f"car_peak_q banks the same quarters, within the 12 s of 10 A the " + f"lag cost ({d48[:2]}; {q1} vs {q0})", + not d48 and sorted(q1) == sorted(q0) + and all(abs(q1[k] - q0[k]) <= 12.0 for k in q0)) + +# =========================================================================== # +print("\n9. SOLAR kWh (T49), MANUAL, GUARD AND LOOP UNCHANGED (T57-T60)") +# =========================================================================== # + + +def kwh(r): + c = r["c"] + return c.car_sun_kwh(), c.car.today_kwh + + +r49a = std(3700, sun=const(3500.0)) # spare 3000: 12 A, 2760 W +r49b = S.drive(const(900.0), const(7900.0), dur=3700, first="batteries", + socs={"a": 71.0, "b": 100.0}) +r49c = std(3700, sun=step_fn((130, 1500.0), base=3500.0), + opts={"ev_pause_min": 30}) +r49d = std(3700, sun=step_fn((130, 0.0), base=3500.0), + opts={"ev_pause_min": 30}) +r49e = std(3700, mode="manual", sun=const(3500.0 + 2760.0)) +k = {x: kwh(r) for x, r in (("a", r49a), ("b", r49b), ("c", r49c), + ("d", r49d), ("e", r49e))} +print(f" kWh (sun, today): {k}") +check("T49 (a): Car first, spare 3000, the car 2760 W for ~1 h: the sun share " + "is all of it (+-10 Wh of the car's own count)", + k["a"][0] is not None and abs(k["a"][0] - k["a"][1]) <= 0.01 + and abs(k["a"][0] - 2760.0 * (3700 - 121) / 3.6e6) <= 0.02) +check("T49 (b): Batteries first, scenario 2 (spare 7000, room 5000, car " + "1840 W): all of the car's 1.84 kWh from the sun", + abs(k["b"][0] - k["b"][1]) <= 0.01 and 1.75 <= k["b"][0] <= 1.86) +hold49 = [x["t"] for x in r49c["trace"] if x["why"] == "hold"] +h49 = (hold49[-1] - hold49[0] + 1) if hold49 else 0 +check(f"T49 (c): Car first hold, spare 1000 W, the car 1380 W: per hour 1.00 " + f"of the 1.38 kWh; the hold lasts ev_pause_min, at most 30 min " + f"({h49} s here), so 1000/1380 of the hold's energy (the hold's grid or " + f"battery share is not counted)", + abs(k["c"][0] - 1000.0 * h49 / 3.6e6) <= 0.02 + and abs((k["c"][1] - k["c"][0]) - 380.0 * h49 / 3.6e6) <= 0.02) +check("T49 (d): a negative spare: nothing from the sun (only the 10 A before " + "the cloud)", k["d"][0] <= 0.01 + 2300.0 * 15 / 3.6e6) +check("T49 (e): Manual at 10 A with 3 kW export: 0 kWh from the sun", + k["e"][0] in (None, 0.0) and k["e"][1] > 1.0) +check("T49: 0 <= sun <= today, always", + all(v[0] is None or 0.0 <= v[0] <= (v[1] or 0.0) + 1e-9 + for v in k.values())) +c49 = r49a["c"] +vals = c49.car_values() +blk49 = homeview.car_block(c49, None) +check(f"T49: the sensor goodwe_car_today_solar_kwh and the card agree " + f"({vals.get('car_today_solar_kwh')}, {blk49['today']!r})", + vals.get("car_today_solar_kwh") == round(k["a"][0], 3) + and blk49["today"].endswith("from the sun.") + and f"{k['a'][0]:.1f}" in blk49["today"]) +c49.car.day = "2099-01-01" +c49._car_sun_tick(c49.car_now()) +check("T49 (f): at day rollover it is back to 0", + c49.car_sun["kwh"] == 0.0 and c49.car_sun["day"] == "2099-01-01") + +# T57: Manual ignores Solar's settings; Manual's shutdown fail state. +rm1 = std(600, mode="manual", opts={"ev_margin_w": 0, "ev_start_min": 1}) +rm2 = std(600, mode="manual", first="batteries", + events={100: act("car_sun_first", "car")}) +check("T57: Manual ignores sun_first, the margin and the dwells: the same " + "writes", [(x[0], x[2]) for x in rm1["sim"].log] + == [(x[0], x[2]) for x in rm2["sim"].log]) +rm3 = std(300, mode="manual", finale=_shutdown) +check("T57: Manual's fail state at shutdown: the current stands (no write)", + not [x for x in rm3["plant"].sets if x[1] == SET and x[0] >= 299]) + +# T58: Solar with no car vs no charger: the guard and the commands. +spikes = step_fn((300, 2500.0), (900, 6500.0), (1500, 1200.0), (2400, 4800.0), + base=900.0) +g1 = S.drive(spikes, const(0.0), dur=3600, first="car", plug=False, + socs={"a": 60.0, "b": 60.0}) +g2 = S.drive(spikes, const(0.0), dur=3600, first="car", plug=False, + socs={"a": 60.0, "b": 60.0}, opts={"ev_charger": "off"}) +cm1 = [(t, e, v) for t, e, v in g1["plant"].sets if e.startswith("number.sp_")] +cm2 = [(t, e, v) for t, e, v in g2["plant"].sets if e.startswith("number.sp_")] +pg = [(a["t"], a["floor"], a["want"]) for a, b in zip(g1["trace"], + g2["trace"]) + if (a["floor"], a["want"], a["proj"]) != (b["floor"], b["want"], + b["proj"])] +check(f"T58: Solar with no car (state A) for an hour of house steps against " + f"ev_charger off: the guard's floor, want and projection and every " + f"inverter command are bit-identical ({len(cm1)} commands, {pg[:1]})", + cm1 == cm2 and not pg and g1["sim"].log == []) + +# T59: the zero-grid loop with the car as a Solar car, or as a house load. +l1 = std(1200, sun=step_fn((400, 4500.0), (800, 2500.0), base=3500.0), + socs={"a": 60.0, "b": 60.0}) +car1 = {x["t"]: x["car"] for x in l1["trace"]} + + +def house2(ts): + return 500.0 + car1.get(float(round(ts + S.SAMPLE_LEAD_S)), 0.0) + + +l2 = S.drive(house2, step_fn((400, 4500.0), (800, 2500.0), base=3500.0), + dur=1200, first="car", plug=False, socs={"a": 60.0, "b": 60.0}, + opts={"ev_charger": "off"}) +lc1 = [(t, e, v) for t, e, v in l1["plant"].sets if e.startswith("number.sp_")] +lc2 = [(t, e, v) for t, e, v in l2["plant"].sets if e.startswith("number.sp_")] +dif = [(a, b) for a, b in zip(lc1, lc2) if a != b] +check(f"T59: the same meter series with the car as a Solar car and as a " + f"house load: the loop's commands are identical ({len(lc1)} vs " + f"{len(lc2)}, {dif[:1]}); the batteries charge what the car leaves", + lc1 == lc2 and min(v for _, _, v in lc1) < -500.0) + +# T60: the House tile and the profile leave the car out in Solar. +r60 = S.drive(const(900.0), const(7900.0), dur=200, first="car", + socs={"a": 71.0, "b": 100.0}) +c60 = r60["c"] +check(f"T60: in Solar the House tile and HouseProfile take the car out " + f"(car_term {c60.car_term()}, the car {r60['sim'].power_w:.0f} W)", + c60.car_term()[1] is False and r60["sim"].power_w > 1000.0 + and abs(c60.car_term()[0] - r60["sim"].power_w) < 1.0) + +# =========================================================================== # +print("\n10. STRINGS, DOCS, SETTINGS (T50, T51, T52), THE SEAM (T55)") +# =========================================================================== # +from app import uitext # noqa: E402 +import style_rules # noqa: E402 + +KEYS = ("why.solar_batt", "why.solar_car", "why.solar_paused", + "help_solar.description", "first", "first_help.description") +bad50 = [] +for lang in ("en", "nl"): + words_ = uitext.words(lang) + for key in KEYS: + node = words_["home_words"]["car"] if key.startswith("why") \ + else words_["home"]["car"] + for part in key.split("."): + node = node.get(part, {}) if isinstance(node, dict) else {} + text = uitext.say(node, kw="2.0 kW", s="5", a="8") \ + if isinstance(node, str) else "" + n_s = style_rules.sentences(text) + long_ = [s for s in text.split(". ") + if len(style_rules.words(s)) > 12] + if not text or n_s > 2 or long_: + bad50.append((lang, key, text)) +check(f"T50: why.solar_batt, why.solar_car, why.solar_paused, help.solar, " + f"first and first.help in EN and NL: <= 2 sentences of <= 12 words " + f"({bad50})", not bad50) +en_why = uitext.words("en")["home_words"]["car"]["why"]["solar_over"] +check(f"T50 D1: the card's Why reads exactly 'Solar charges the car at {{a}} " + f"A. This sets the peak.' ({en_why!r}); the notice and row carry the " + f"same words in one sentence (STYLE.md's rule for a grey note and row)", + en_why == "Solar charges the car at {a} A. This sets the peak." + and messages.row_car_over_solar("8").startswith( + "Solar charges the car at 8 A") + and messages.car_over_solar("8").body_nl) +check("T50 guard: Manual's car_over notice and row are unchanged", + messages.car_over("16").body == "You set 16 A, which takes this " + "15-minute period over the peak limit." + and str(messages.row_car_over()) == "The car charge you set takes this " + "15-minute period over the peak limit.") +check("T50 D3: the shutdown warning in EN and NL", + messages.car_release_failed().title == "Car may still be charging" + and "0 A" in messages.car_release_failed().body + and "0 A" in messages.car_release_failed().body_nl) + +docs = open(os.path.join(HERE, "DOCS.md"), encoding="utf-8").read() +chlog = open(os.path.join(HERE, "CHANGELOG.md"), encoding="utf-8").read() +nri = chlog.find("Not in a release yet") +check("T51: DOCS 'Car charger' has a Solar section, a DECISIONS file for EV-20 " + "exists, and a CHANGELOG line under 'Not in a release yet'", + "**Solar mode.**" in docs + and os.path.exists(os.path.join(HERE, "DECISIONS", + "EV-20-solar-mode.md")) + and nri >= 0 and "EV-20" in chlog[nri:nri + 4000]) +check("T51: the shipped defaults ev_margin_w 100, ev_pause_min 5, " + "ev_start_min 2, as config.yaml", + CH.EV_OPTION_DEFAULTS["ev_margin_w"] == 100 + and CH.EV_OPTION_DEFAULTS["ev_pause_min"] == 5 + and CH.EV_OPTION_DEFAULTS["ev_start_min"] == 2) + +cfg = open(os.path.join(HERE, "config.yaml"), encoding="utf-8").read() +schema = {k: v for k, v in (("ev_margin_w", "int(0,1000)"), + ("ev_pause_min", "int(1,30)"), + ("ev_start_min", "int(1,30)"))} +check("T52: config.yaml's schema holds the same ranges as the validator", + all(f" {k}: {v}" in cfg for k, v in schema.items()) + and CH.SOLAR_RANGES == {"ev_margin_w": (0, 1000), + "ev_pause_min": (1, 30), + "ev_start_min": (1, 30)}) +base_opts = {"ev_charger": "alfen_ha", "ev_current_entity": SET} +bad52, ok52 = [], [] +for key, vals, good in (("ev_margin_w", (-1, 1001), (0, 1000, 100)), + ("ev_pause_min", (0, 31), (1, 30, 5)), + ("ev_start_min", (0, 31), (1, 30, 2))): + for v in vals: + probs = validate._charger_problems(dict(base_opts, **{key: v}), {}) + if not any(messages.LABELS[key] in p for p in probs): + bad52.append((key, v, probs)) + for v in good: + probs = validate._charger_problems(dict(base_opts, **{key: v}), {}) + if probs: + ok52.append((key, v, probs)) +check(f"T52: -1/1001, 0/31, 0/31 are refused with a message naming the " + f"setting ({bad52[:1]})", not bad52) +check(f"T52: the edges and the defaults are accepted ({ok52[:1]})", not ok52) + + +def seam_callers(): + import ast + import io + out = [] + for f in sorted(os.listdir(os.path.join(HERE, "app"))): + if not f.endswith(".py") or f == "chargers.py": + continue + tree = ast.parse(io.open(os.path.join(HERE, "app", f), + encoding="utf-8").read()) + for n in ast.walk(tree): + if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) \ + and (n.func.attr in ("write_current", "write_phases") + or (n.func.attr == "release" + and "charger" in ast.dump(n.func.value))): + out.append((f, n.func.attr)) + return sorted(out) + + +check(f"T55: the write seam is still exactly carmode.py's write_current and " + f"write_phases ({seam_callers()}); Solar and release() go through them", + seam_callers() == [("carmode.py", "write_current"), + ("carmode.py", "write_phases")] + and carmode.SolarWriter._write is not carmode.ManualWriter._write + and "super()._write" in open(os.path.join(HERE, "app", "carmode.py"), + encoding="utf-8").read()) + +report() diff --git a/goodwe_controller/test_ev20_long.py b/goodwe_controller/test_ev20_long.py new file mode 100644 index 0000000..b2acace --- /dev/null +++ b/goodwe_controller/test_ev20_long.py @@ -0,0 +1,52 @@ +"""EV-20: T53, the acceptance sim day, Batteries first. `python3 -B test_ev20_long.py` + +The day and what is graded are in `tools/ev20_day.py`: the real Controller, +N=2, 08:00-18:00 of sun with 12 clouds of 1 to 8 minutes, a house of 0.4 to +2.5 kW with three +3 kW steps; `step` over the day, `step_race` over three +hours, a car-Off twin around the house steps. +Car first is test_ev20_long_car.py. +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import logging +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +import ev20_day # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +class _Log(logging.Handler): + def __init__(self): + super().__init__(logging.DEBUG) + self.tb = [] + + def emit(self, r): + if r.exc_info: + self.tb.append(r.getMessage()) + + +LOG = _Log() +_g = logging.getLogger("goodwe") +_g.addHandler(LOG) +_g.setLevel(logging.DEBUG) +_g.propagate = False + +print("T53: THE SIM DAY, BATTERIES FIRST") +ev20_day.run_day("batteries", check) +check("T53: no Traceback", LOG.tb == []) + +print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}") +for f in fails: + print(" FAIL:", f) +sys.exit(1 if fails else 0) diff --git a/goodwe_controller/test_ev20_long_car.py b/goodwe_controller/test_ev20_long_car.py new file mode 100644 index 0000000..3614925 --- /dev/null +++ b/goodwe_controller/test_ev20_long_car.py @@ -0,0 +1,52 @@ +"""EV-20: T53, the acceptance sim day, Car first. `python3 -B test_ev20_long_car.py` + +The day and what is graded are in `tools/ev20_day.py`: the real Controller, +N=2, 08:00-18:00 of sun with 12 clouds of 1 to 8 minutes, a house of 0.4 to +2.5 kW with three +3 kW steps; `step` over the day, `step_race` over three +hours, a car-Off twin around the house steps. +Batteries first is test_ev20_long.py. +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import logging +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +import ev20_day # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +class _Log(logging.Handler): + def __init__(self): + super().__init__(logging.DEBUG) + self.tb = [] + + def emit(self, r): + if r.exc_info: + self.tb.append(r.getMessage()) + + +LOG = _Log() +_g = logging.getLogger("goodwe") +_g.addHandler(LOG) +_g.setLevel(logging.DEBUG) +_g.propagate = False + +print("T53: THE SIM DAY, CAR FIRST") +ev20_day.run_day("car", check) +check("T53: no Traceback", LOG.tb == []) + +print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}") +for f in fails: + print(" FAIL:", f) +sys.exit(1 if fails else 0) diff --git a/goodwe_controller/test_ev20_writers.py b/goodwe_controller/test_ev20_writers.py new file mode 100644 index 0000000..08f085e --- /dev/null +++ b/goodwe_controller/test_ev20_writers.py @@ -0,0 +1,227 @@ +"""EV-20: Solar in shadow mode and beside another writer (T38-T46; N10, N16). +`python3 -B test_ev20_writers.py` + +The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and +`chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit +rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section +names the T-ids and N-ids of reports/EV-20-test-plan.md it implements. +"Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare +2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start. +Times are the cycle's second; `race` runs use the production order (read, the +writer settles, the cycle). + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import json +import math +import os +import random +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402 +from app import mqtt, validate, web, main as app_main # noqa: E402 +from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from ev20_kit import * # noqa: E402,F401,F403 +from ev20_kit import LOG, check, fails, report # noqa: E402,F401 +from named_absence import nth, present # noqa: E402,F401 +from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401 + _until) + + +# =========================================================================== # +print("\n7. SHADOW, ANOTHER WRITER (T38-T46)") +# =========================================================================== # +cloud = (lambda t: 600.0 + (5200.0 if (t // 400) % 3 == 0 else + 1200.0 if (t // 400) % 3 == 1 else 2600.0)) +for how, opts in (("on", {"shadow_mode": "on"}), + ("auto, stopped", {"shadow_mode": "auto"})): + ev = {0: lambda p, c: setattr(c, "auto", False)} \ + if how != "on" else {} + rs = std(3600, sun=cloud, opts=opts, events=ev) + rt = std(3600, sun=cloud) + sel_t = [x[0] for x in selects(rt)] + near = (lambda t: any(st - 10.0 <= t <= st + 15.0 for st in sel_t)) + diff = [(a["t"], (a["would"] or (0.0,))[0], b["a"]) + for a, b in zip(rs["trace"], rt["trace"]) + if (a["would"] or (0.0,))[0] != b["a"]] + far = [x for x in diff if not near(x[0])] + check(f"T38 [shadow {how}]: a 1 h cloudy run from the start: the charger " + f"log is empty, and every cycle's 'would set' is the current of a " + f"non-shadow twin, but within seconds of the twin's own phase " + f"selects ({len(diff)} differ, {len(far)} away from a select: " + f"{far[:3]}; selects {sel_t})", + rs["sim"].log == [] and not far and len(diff) <= 20 * len(sel_t) + and len(cur_writes(rt)) >= 3) + +# T39: another writer. +for race in (False, True): + tag = "race" if race else "step" + n = LOG.mark() + r39 = std(900, sun=const(600.0 + 1840.0), race=race, rows=True, + events={300: lambda p, c: p.ch.set_current(13), + 600: act("car_mode", "solar")}) + tr39 = r39["trace"] + held = next((x["t"] for x in tr39 if x["hold"]), None) + other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m] + check(f"T39 [{tag}]: sim.set_current(13) at 300 s while Solar set 8 A: " + f"the hold at 330 s, not 329 s (at {held}); no write over it", + held is not None and 330 <= held <= 331 + and not [x for x in cur_writes(r39) if 300 <= x[0] < 600]) + check(f"T39 [{tag}]: the amber charger_other row and one warning until " + f"Solar is pressed ({len(other)})", len(other) == 1 + and "charger_other" in tr39[400]["amber"] + and "charger_other" not in tr39[620]["amber"]) + check(f"T39 [{tag}]: pressing Solar takes the charger as it is and lifts " + f"the hold: Solar's own 8 A is written again " + f"({cur_writes(r39)[-1:]})", + cur_writes(r39)[-1][1] == 8.0 and 600 <= cur_writes(r39)[-1][0] + <= 602 and not tr39[700]["hold"]) +check("T39: the row's text in both languages", + messages.row_charger_other_solar().nl != "" + and "Solar" in str(messages.row_charger_other_solar()) + and "Zon" in messages.row_charger_other_solar().nl) +for name, fn in (("Stop", lambda p, c: setattr(c, "auto", False)), + ("Off", act("car_mode", "off"))): + rr = std(500, sun=const(600.0 + 1840.0), + events={300: lambda p, c: p.ch.set_current(13), 310: fn}) + check(f"T39 (b): {name} 10 s after the other writer, inside the 30 s: " + f"the way-out 0 A is written ({cur_writes(rr)})", + cur_writes(rr)[-1][1] == 0.0 and 310 <= cur_writes(rr)[-1][0] <= 311) +n = LOG.mark() +r39g = std(1500, sun=step_fn((400, 600.0 + 4600.0), (900, 600.0 + 1000.0), + base=600.0 + 1840.0)) +check("T39 guard: Solar's own writes, own 0 A pause and own phase sequence " + "are never flagged (no hold, no CHARGER_OTHER)", + not any(x["hold"] or x["mismatch"] is not None for x in r39g["trace"]) + and not [m for m in LOG.since(n) if "CHARGER_OTHER" in m] + and selects(r39g) and 0.0 in [a for _, a, _ in cur_writes(r39g)]) + +# T40: EV-05 r5 Major 3, the exits under the hold. +EXITS = {"Stop": lambda p, c: setattr(c, "auto", False), + "shadow on": lambda p, c: c.o.__setitem__("shadow_mode", "on"), + "latch": lambda p, c: setattr(c.circ_wd, "tripped", True), + "Off": act("car_mode", "off"), + "charger error": _err} +for name, fn in EXITS.items(): + rr = std(1000, sun=const(600.0 + 2070.0), + opts={"shadow_mode": "off"}, + events={600: lambda p, c: p.ch.set_current(16), 700: fn}) + check(f"T40 [{name}]: Solar at 9 A, another writer's 16 A at 600 s (hold " + f"at 630 s), {name} at 700 s: nothing written after 600 s; the " + f"charger still at 16 A ({cur_writes(rr)})", + not [x for x in attempts(rr) if x[0] >= 600] + and rr["sim"].setpoint_a == 16.0) + +# T41: the user changes Manual's values while Solar holds. +r41 = std(1000, sun=const(600.0 + 2070.0), + events={600: lambda p, c: p.ch.set_current(16), + 700: act("car_current", 12), 710: act("car_phases", 3)}) +check("T41: Manual's current and phases set while Solar holds: the hold is " + "not lifted, nothing written over the 16 A", + not [x for x in attempts(r41) if x[0] >= 600] + and r41["sim"].setpoint_a == 16.0 and r41["c"].car_solar.hold) + +# T42: EV-05 r6 Major 2, shutdown after an exit and another writer. +for name, fn, opts in (("shadow on", lambda p, c: c.o.__setitem__( + "shadow_mode", "on"), {}), + ("Stop (auto)", lambda p, c: setattr(c, "auto", False), + {"shadow_mode": "auto"}), + ("Stop (off)", lambda p, c: setattr(c, "auto", False), + {"shadow_mode": "off"}), + ("guard: writing", lambda p, c: None, {})): + rr = std(600, opts=opts, finale=_shutdown, + events={300: fn, 400: lambda p, c: p.ch.set_current(16)}) + shut = [x for x in attempts(rr) if x[0] >= 599] + check(f"T42 [{name}]: another writer's 16 A at 400 s, shutdown at 600 s: " + f"no charger write at shutdown, 16 A stands ({shut})", + shut == [] and rr["sim"].setpoint_a == 16.0 + and (name != "guard: writing" or rr["c"].car_solar.hold)) + +# T43: a start in Solar with shadow on, or stopped, over another writer. +for how, opts, ev in (("shadow on", {"shadow_mode": "on"}, {}), + ("auto, stopped", {"shadow_mode": "auto"}, + {0: lambda p, c: setattr(c, "auto", False)})): + blk = {} + ev = dict(ev) + ev[250] = lambda p, c: blk.update(b=homeview.car_block(c, None)) + rr = std(300, sim=SimCharger(setpoint_a=16), opts=opts, events=ev) + check(f"T43 [{how}]: a start in Solar while another writer has the car at " + f"16 A: nothing written; the card says what it would set " + f"({blk.get('b', {}).get('why')!r})", + rr["sim"].log == [] and "would" in blk.get("b", {}).get("why", "")) + +# T44: Stop, another writer, Start. +r44 = std(900, rows=True, events={300: lambda p, c: setattr(c, "auto", False), + 400: lambda p, c: p.ch.set_current(16), + 600: lambda p, c: setattr(c, "auto", True)}) +check(f"T44: Stop at 300 s (0 A taken), another writer's 16 A at 400 s, " + f"Start at 600 s: Solar holds off, amber row, no write " + f"({cur_writes(r44)})", + [(t, a) for t, a, _ in cur_writes(r44)] == [(120.0, 10.0), (300.0, 0.0)] + and "charger_other" in r44["trace"][700]["amber"]) + +# T45: EV-05 r7 Major 1, Solar to Off while not writing. +T45 = { + "a": ({"shadow_mode": "on"}, 16, {200: act("car_mode", "off")}), + "b": ({"shadow_mode": "auto"}, 16, + {0: lambda p, c: setattr(c, "auto", False), + 200: act("car_mode", "off")}), + "c": ({}, 0, {300: lambda p, c: c.o.__setitem__("shadow_mode", "on"), + 400: lambda p, c: p.ch.set_current(16), + 410: act("car_mode", "off")}), + "d": ({}, 0, {300: lambda p, c: c.o.__setitem__("shadow_mode", "on"), + 400: lambda p, c: p.ch.set_current(16), + 600: act("car_mode", "off")}), +} +for k, (opts, sp, ev) in T45.items(): + rr = std(800, sim=SimCharger(setpoint_a=sp), opts=opts, events=ev) + late = [x for x in attempts(rr) if x[0] >= 300 or sp] + check(f"T45 ({k}): Solar to Off while not writing: no write over the " + f"other writer, the charger stays at 16 A ({late})", + [x for x in late if not (k in "cd" and x == (300.0, 0.0))] == [] + and rr["sim"].setpoint_a == 16.0) +rr = std(400, sim=SimCharger(setpoint_a=16), opts={"shadow_mode": "on"}, + events={200: act("car_mode", "manual")}) +check("T45 guard: a shadow start, then Manual: nothing written", + rr["sim"].log == []) + +# T46: EV-05 r8 Major 1, another writer's phases. +r46 = run("T46", S.drive, step_fn((300, 700.0), (600, 900.0), base=500.0), + const(3500.0), dur=900, first="car", phases=3, + socs={"a": 10.0, "b": 10.0}, rows=True, + events={140: lambda p, c: p.ch.set_phases(3), + 300: lambda p, c: p.ch.set_phases(3)}) +w46, s46 = cur_writes(r46), selects(r46) +check(f"T46: Solar starts on 1 phase (select at the start), then another " + f"writer selects 3 phases: while Solar runs on them it selects nothing " + f"(a select back is EV-22's; the next start from the pause is on 1 " + f"phase, Expected 5) ({[(x[0], x[2]) for x in s46]})", + s46[:1] and s46[0][2] == 1 + and not [x for x in s46 if 140 < x[0] < 700]) +low = [x for x in w46 if 140 < x[0] < 700] +check(f"T46 (a)(b): the arithmetic uses the 3 phases the car draws on, and a " + f"lower current (the 6 A hold, the pause) is written within the 30 s " + f"rule, never blocked by PHASE_GAP_S ({w46})", + low and low[0][1] == 6.0 and low[0][0] <= 171 + and [a for _, a, _ in low][-1:] == [0.0]) +imp46 = sum(max(0.0, x["grid"]) for x in r46["trace"] + if x["t"] > 140 and x["sp"] > 0) +check(f"T46 (c): the car's grid import only within the hold rule " + f"(<= 300 s of 6 A on 3 phases) ({imp46 / 3600:.0f} Wh)", + imp46 <= 4140.0 * 302.0) +r46h = std(900, sun=const(3500.0), phases=3, + events={200: lambda p, c: p.ch.set_current(16), + 300: lambda p, c: p.ch.set_phases(3)}) +check("T46 (d)/N16: while EV-04's hold stands Solar writes nothing, a " + "select included", + not [x for x in attempts(r46h) if x[0] >= 200] + and not [x for x in selects(r46h) if x[0] >= 200]) + +report() diff --git a/goodwe_controller/tools/ev20_day.py b/goodwe_controller/tools/ev20_day.py new file mode 100644 index 0000000..e1ab41f --- /dev/null +++ b/goodwe_controller/tools/ev20_day.py @@ -0,0 +1,180 @@ +"""EV-20, T53: the acceptance sim day, shared by test_ev20_long.py (Batteries +first) and test_ev20_long_car.py (Car first). + +The real Controller, N=2 (A 40 % and may charge, B full), 08:00-18:00 of sun +(9 kW at noon) with 12 clouds of 1 to 8 minutes, a house of 0.4 to 2.5 kW with +three +3 kW steps of a little under 5 minutes. The cycle order of `step` over +the whole day, of `step_race` over the cloudiest three hours, and a car-Off +twin over the quarters around the house steps for the alarms. + +What is checked, per priority and cycle order: +- starts: at most one per stretch in which the car's target stayed under + 6 A worth longer than `ev_pause_min` (the morning counts as one), so no cloud + or house step shorter than that starts or pauses the car; +- no start and no pause inside a cloud of 300 s or less; +- selects at least 600 s apart; +- the car's grid energy outside its holds: SETTLED (not within 20 s of a step + of the sun, the house or the car's own current) at most 10 Wh; the zero-grid + loop's slew after such a step (500 W per cycle) is reported apart; +- house-caused alarms at the same seconds as the car-Off twin, +2 s. +""" + +import math +import random + +import ev20_sun as S + +DAY = 36000 # 08:00 to 18:00, 1 s cycles +PAUSE_S = 300.0 +MARGIN = 100.0 +_rnd = random.Random(53) +CLOUDS = [] +_t = 1800 +for _k in range(12): + _t += _rnd.randint(1200, 2400) + CLOUDS.append((_t, _t + _rnd.randint(60, 480))) +STEPS = [(9000, 9290), (19000, 19290), (27000, 27290)] +SOCS = {"a": 40.0, "b": 100.0} +RACE = (7200, 7200 + 10800) # the cloudiest three hours + + +def sun(t): + base = 9000.0 * max(0.0, math.sin(math.pi * t / DAY)) + for a, b in CLOUDS: + if a <= t < b: + return 0.15 * base + return base + + +def house(t): + w = 400.0 + 2100.0 * (0.5 + 0.5 * math.sin(t / 1700.0)) + for a, b in STEPS: + if a <= t < b: + w += 3000.0 + return w + + +def cur_writes(r): + return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log + if x[0] == "current"] + + +def low_stretches(r, first, longer=PAUSE_S): + """Stretches in which the car's target was under 6 A worth on 1 phase for + longer than `longer`: (start, end); the last may run to the day's end.""" + out, since = [], None + for x in r["trace"]: + sp = x["spare"] + room = x.get("room") or 0.0 + tgt = None if sp is None else sp - (room if first == "batteries" + else 0.0) - MARGIN + low = tgt is None or tgt < 6.0 * 230.0 + if low and since is None: + since = x["t"] + if not low and since is not None: + if x["t"] - since > longer: + out.append((since, x["t"])) + since = None + if since is not None and r["trace"] \ + and r["trace"][-1]["t"] - since > longer: + out.append((since, r["trace"][-1]["t"])) + return out + + +def grid_split(r): + """The car's grid energy outside its holds (W s): settled, and within 20 s + of a step of the sun, the house or the car's own current.""" + tr = r["trace"] + marks = [] + for i in range(1, len(tr)): + a, b = tr[i - 1], tr[i] + if abs(b["sun"] - a["sun"]) > 200.0 or abs(b["house"] - a["house"]) \ + > 200.0 or b["sp"] != a["sp"] or b["ph"] != a["ph"]: + marks.append(b["t"]) + settled = slew = 0.0 + j = 0 + for x in tr: + imp = max(0.0, min(x["car"], x["grid"])) \ + if x["why"] != "hold" and x["sp"] > 0 else 0.0 + if imp <= 0.0: + continue + while j < len(marks) and marks[j] < x["t"] - 20.0: + j += 1 + near = j < len(marks) and marks[j] <= x["t"] + if near: + slew += imp + else: + settled += imp + return settled, slew + + +def run_day(first, check): + """Run the day for one priority and grade it through `check`.""" + long_c = [(a, b) for a, b in CLOUDS if b - a > PAUSE_S] + short_c = [(a, b) for a, b in CLOUDS if b - a <= PAUSE_S] + print(f" clouds (start, length): {[(a, b - a) for a, b in CLOUDS]}") + runs = {"step": S.drive(house, sun, dur=DAY, first=first, socs=dict(SOCS), + race=False), + "race": S.drive(house, sun, dur=RACE[1] - RACE[0], t0=RACE[0], + first=first, socs=dict(SOCS), race=True)} + for tag, r in runs.items(): + w = cur_writes(r) + # A pause: a 0 A that is not a phase change's (no select within + # 30 s); a start: the first current after a pause or at the start. + log = r["c"].car_solar.log + sel_t = [t for k, a, t, ok in log if k == "phases"] + starts, pauses, paused = [], [], True + for kind, a, t, ok in log: + if kind != "current": + continue + if a == 0.0: + if not [1 for t2 in sel_t if t <= t2 <= t + 30.0]: + pauses.append(t) + paused = True + elif paused: + starts.append(t) + paused = False + lows = low_stretches(r, first) + check(f"T53 [{first} first, {tag}]: {len(starts)} starts, at most one " + f"per stretch under 6 A worth longer than the pause " + f"({len(lows)}: {lows[:6]})", len(starts) <= len(lows) + 1) + # A pause or start inside a short cloud is the cloud's only when the + # low stretch it ends began with that cloud. + every = low_stretches(r, first, longer=-1.0) + bad = [] + for t in pauses + starts: + for a, b in short_c: + if a <= t <= b + 1: + began = [s0 for s0, e0 in every if s0 <= t <= e0 + 1] + if not began or began[-1] >= a - 1: + bad.append((t, a, b)) + check(f"T53 [{first} first, {tag}]: no start and no pause from a " + f"cloud of 300 s or less ({bad[:2]}; {len(long_c)} clouds are " + f"longer)", not bad) + sel = [x[0] for x in r["sim"].log if x[1] == "phases"] + check(f"T53 [{first} first, {tag}]: selects at least 600 s apart " + f"({sel})", all(b - a >= 600.0 for a, b in zip(sel, sel[1:]))) + settled, slew = grid_split(r) + print(f" [{first} first, {tag}] writes {len(w)}; car grid energy " + f"outside holds: settled {settled / 3600.0:.1f} Wh, loop slew " + f"after a step {slew / 3600.0:.1f} Wh; sun " + f"{r['c'].car_sun_kwh()} of {r['c'].car.today_kwh} kWh") + check(f"T53 [{first} first, {tag}]: the car's settled grid energy " + f"outside its holds is at most 10 Wh ({settled / 3600.0:.1f} Wh)", + settled <= 10.0 * 3600.0) + r = runs["step"] + for a, _b in STEPS: + t0 = float(a - a % 900 - 900) + off = S.drive(house, sun, dur=2700, t0=t0, first=first, mode="off", + plug=False, socs=dict(SOCS)) + win = (t0 + 900.0, t0 + 2700.0) # the first quarter warms up + al = [t for t, n in r["raised"] if n in S.ALARMS + and win[0] <= t < win[1]] + ao = [t for t, n in off["raised"] if n in S.ALARMS + and win[0] <= t < win[1]] + check(f"T53 [{first} first]: house-caused alarms around the +3 kW " + f"step at {a} s at the same seconds as the car-Off twin, +2 s " + f"({al[:3]} vs {ao[:3]})", + len(al) == len(ao) and all(abs(x - y) <= 2 + for x, y in zip(al, ao))) + return runs diff --git a/goodwe_controller/tools/ev20_kit.py b/goodwe_controller/tools/ev20_kit.py new file mode 100644 index 0000000..93ff7e1 --- /dev/null +++ b/goodwe_controller/tools/ev20_kit.py @@ -0,0 +1,251 @@ +"""EV-20: shared pieces of the Solar checks (test_ev20*.py): the Std run, +the write logs, a charger model with refusals in time windows, the Never +checks every run can carry, and the shutdown and fault shapes. + +Each check file imports `check`, `fails` and `LOG` from here and is its own +process, so they are its own.""" + +import asyncio +import logging +import os +import sys + +_KIT = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, _KIT) +sys.path.insert(0, os.path.dirname(_KIT)) + +from app import carmode, main as app_main # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +class _Log(logging.Handler): + def __init__(self): + super().__init__(logging.DEBUG) + self.rec = [] + + def emit(self, r): + self.rec.append((r.levelname, r.getMessage(), bool(r.exc_info))) + + def mark(self): + return len(self.rec) + + def since(self, n, level=None): + return [m for lv, m, _x in self.rec[n:] if level in (None, lv)] + + def tracebacks(self, n=0): + return [m for lv, m, x in self.rec[n:] if x] + + +LOG = _Log() +_g = logging.getLogger("goodwe") +_g.addHandler(LOG) +_g.setLevel(logging.DEBUG) +_g.propagate = False + +FULL = {"a": 100.0, "b": 100.0} +SET = S.SET + + +def const(w): + return S.const(w) + + +def step_fn(*pairs, base=0.0): + """A function of t: `base`, then each (from_t, value) in order. The meter + is sampled 0.3 s before each cycle, so a change "at t0" is the cycle of + t0's.""" + def f(t): + v = base + for t0, x in pairs: + if t >= t0 - 0.5: + v = x + return float(v) + return f + + +def at_s(t): + """The cycle second a meter sample at `t` belongs to.""" + return int(round(t)) + + +def std(dur, *, sun=None, house=None, events=None, race=False, sim=None, + first="car", socs=None, **kw): + return S.drive(house or const(500.0), sun or const(2900.0), dur=dur, + first=first, socs=socs or dict(FULL), events=events, + race=race, sim=sim, **kw) + + +def cur_writes(r): + """(cycle second, amps, ok) of every current write Solar made.""" + return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log + if x[0] == "current"] + + +def attempts(r): + """(second, amps) of every current write that reached Home Assistant, + refused ones included.""" + return [(t, v) for t, e, v in r["plant"].sets if e == SET] + + +def selects(r): + return [x for x in r["sim"].log if x[1] == "phases"] + + +def act(what, value, out=None, key=None): + async def f(p, c): + res = await c.handle_action(what, value=value) + if out is not None: + out[key or what] = res + return f + + +def mqtt_cmd(topic, payload, retained=False): + async def f(p, c): + await c.mqtt_command(topic, payload, retained) + return f + + +def both(*fns): + async def f(p, c): + for fn in fns: + x = fn(p, c) + if asyncio.iscoroutine(x): + await x + return f + + +class TSim(SimCharger): + """The model with refusals in time windows of its own clock: (t0, t1, + "error" | "ignore").""" + + def __init__(self, *a, windows=(), **kw): + super().__init__(*a, **kw) + self.windows = list(windows) + + def _mode(self): + for t0, t1, kind in self.windows: + if t0 <= self.t <= t1: + return kind + return None + + def request_current(self, a): + keep, self.refuse = self.refuse, self._mode() or self.refuse + try: + return super().request_current(a) + finally: + self.refuse = keep + + +def nevers(r, tag, *, clamp=16.0, gap=600.0): + """N1, N2, N5 and N13 over one run: no write above the clamp and no + clamp fault; a select only at 0 A with the car under 100 W, one per 600 s; + no two non-zero decisions under 30 s apart or under 1 A apart; no + Traceback.""" + bad = [] + sim, c = r["sim"], r["c"] + if c.charger.clamp_faults: + bad.append(("N1 clamp fault", c.charger.clamp_faults)) + for t, what, v, power, sp in sim.log: + if what == "current" and v > clamp + 1e-9: + bad.append(("N1 over the clamp", t, v)) + last = None + for t, what, v, power, sp in sim.log: + if what != "phases": + continue + if sp > 0.0 or power >= carmode.QUIET_W: + bad.append(("N2 select under load", t, sp, power)) + if last is not None and t - last < gap: + bad.append(("N2 two selects", last, t)) + last = t + prev = None + for t, a, ok in cur_writes(r): + if a <= 0.0: + continue + if prev is not None and a != prev[1]: + if t - prev[0] < carmode.SOLAR_WRITE_S - 1e-9: + bad.append(("N5 under 30 s", prev, (t, a))) + if abs(a - prev[1]) < carmode.SOLAR_STEP_A: + bad.append(("N5 under 1 A", prev, (t, a))) + if prev is None or a != prev[1]: + prev = (t, a) + if LOG.tracebacks(r.get("_log", 0)): + bad.append(("N13 Traceback", LOG.tracebacks(r.get("_log", 0))[:1])) + check(f"{tag}: N1, N2, N5, N13 hold ({bad[:2]})", not bad) + return bad + + +def run(tag, fn, *a, **kw): + n = LOG.mark() + r = fn(*a, **kw) + r["_log"] = n + return r + + + +def sets_order(r): + return [(t, e, v) for t, e, v in r["plant"].sets] + + + +async def _shutdown(p, c): + await c.shutdown() + + + +def _until(r, t0): + """Seconds from `t0` to the first inverter 0 W at shutdown.""" + z = [t for t, e, v in r["plant"].sets + if e.startswith("number.sp_") and t >= t0 and v == 0.0] + return (z[0] - t0) if z else None + + + +def _err(p, c): + p.ch.error = "12: Socket error" + p.ch.fault("E") + + + +async def _dies(p, c): + async def boom(): + raise RuntimeError("control died") + stop, died = asyncio.Event(), [] + task = asyncio.ensure_future(boom()) + await asyncio.gather(task, return_exceptions=True) + app_main.control_task_done(task, controller=c, stop=stop, died=died) + p.died = (stop.is_set(), len(died)) + await c.shutdown() + + + +def _freeze_after_write(p, c): + p.ch.freeze() + + + +class HangPlant(S.SunPlant): + """Home Assistant that never answers a charger write.""" + hang = False + + async def set_number(self, e, v): + if e == SET and self.hang: + await asyncio.sleep(3600) + return await super().set_number(e, v) + + + + +def report(): + print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}") + for f in fails: + print(" FAIL:", f) + sys.exit(1 if fails else 0) diff --git a/goodwe_controller/tools/ev20_sun.py b/goodwe_controller/tools/ev20_sun.py new file mode 100644 index 0000000..f64623d --- /dev/null +++ b/goodwe_controller/tools/ev20_sun.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +"""EV-20: the real Controller on a sunny plant with N batteries and a car. + + python3 tools/ev20_sun.py # mock-up scenario 2, both priorities + +A 1 s cycle, a P1 meter that publishes 0.3 s before each cycle, N batteries +each with ITS OWN rating and level (switched On, so the zero-grid loop charges +them from the export), and `chargersim.SimCharger` behind the same Home +Assistant. The meter sees `house + car - sun - batteries` (battery discharge +positive), so the spare sun the add-on computes is `sun - house` whatever it +does. A battery at 100 % takes no charge. `events` is `{second: fn(plant, c)}`, +run before that cycle. `race=True` uses the production order (read, the writer +task settles, then the cycle), as test_ev04.py's `World.step_race`. + +Used by test_ev20.py and test_ev20_long.py. Adapted from EV-05's harness +(branch EV-05, never merged), without the peak cut.""" + +import asyncio +import logging +import os +import sys +import tempfile +from datetime import timedelta + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import opt11_identity as rig # noqa: E402 +import main_files # noqa: E402 +from app import packmode # noqa: E402 +from app.main import Controller # noqa: E402 +from app.p1 import make_sample, split_signed # noqa: E402 +from app.store import unit_key # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from app import p1 as _p1 # noqa: E402 + +SET = "number.wallbox_power_connector_max_current_socket_1" +PHASES = "select.wallbox_installation_max_allowed_phases" +ALARMS = ("goodwe_peak_saturated", "goodwe_peak_soc_floor") +RESPONSE_S = 0.5 # a battery reaches its new command this much later +SAMPLE_LEAD_S = 0.3 + + +class SunPlant: + """The house, the sun, N batteries and the charger on one meter.""" + + def __init__(self, house, sun, ratings, socs, charger): + self.house, self.sun = house, sun + self.ratings, self.socs = dict(ratings), dict(socs) + self.ch = charger + self.t = 0.0 + self.hists = {u: [(-1e9, 0.0)] for u in self.ratings} + self.notes = [] # (t, notification id) raised + self.dismissed = [] + self.sets = [] # (t, entity, value): every number write + # Every charger write the model took, as `SimCharger.log` has it but + # on THIS clock (the model's own runs ahead while a write waits). + self.wlog = [] + self.meter = 0.0 + self.meter_on = True # False: the meter stops publishing + self.batt_nan = set() # units whose battery figure reads None + self.utc_off = 0.0 # the wall clock jumps, the model clock not + self.ha_down = False # Home Assistant answers nothing (SAFETY-112) + self.response_s = RESPONSE_S # a slow battery takes longer + + def batt_of(self, u, at): + w = 0.0 + for when, v in self.hists[u]: + if when <= at: + w = v + r = self.ratings[u] + w = max(-r, min(r, float(round(w)))) + if self.socs[u] >= 100.0 and w < 0.0: + w = 0.0 # a full battery takes no charge + return w + + def batt(self, at): + return sum(self.batt_of(u, at) for u in self.ratings) + + def grid(self, at): + return self.house(at) + self.ch.power_w - self.sun(at) - self.batt(at) + + # -- Home Assistant ----------------------------------------------------- + async def limits(self, e): + return (-5000.0, 5000.0, 1.0) + + async def state(self, entity_id): + if self.ha_down: + return None + return self.ch.states().get(entity_id) + + async def states(self): + if self.ha_down: + return [] + return list(self.ch.states().values()) + + async def call(self, domain, service, data=None): + if self.ha_down: + return False + if service == "create": + self.notes.append((self.t, (data or {}).get("notification_id"))) + if service == "dismiss": + self.dismissed.append((self.t, (data or {}).get("notification_id"))) + if domain == "select" and service == "select_option": + n = 3 if "3" in str((data or {}).get("option")) else 1 + return self._logged("phases", n, self.ch.request_phases) + return True + + def _logged(self, what, v, fn): + n0, row = len(self.ch.log), (self.t, what, v, self.ch.power_w, + self.ch.setpoint_a) + ok = fn(v) + if len(self.ch.log) > n0: + self.wlog.append(row) + return ok + + async def number(self, e, invert=False): + if self.ha_down: + return None + for u in self.ratings: + if e == "sensor.soc_" + u: + return self.socs[u] + if e == "sensor.batt_" + u: + return None if u in self.batt_nan else self.batt_of(u, self.t) + if e in ("sensor.grid", "sensor.net"): + return self.meter + return None + + async def set_number(self, e, v): + if self.ha_down: + return False + self.sets.append((self.t, e, float(v))) + if e == SET: + return self._logged("current", float(v), self.ch.request_current) + if e.startswith("number.sp_"): + self.hists[e[-1]].append((self.t + self.response_s, float(v))) + return True + + +def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, + margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar", + first="batteries", events=None, sim=None, store=None, race=False, + on_cycle=None, car_phases=3, t0=0.0, caps=None, finale=None, + rows=False, plant_cls=None): + """Run it. Returns a dict: plant, controller, charger, notifications with + their second, and a per-second trace. `caps` ({unit: kWh}) lets each + battery's level move with what it charges or gives; without it the + levels stand still. `finale(plant, c)` (a coroutine) runs after the last + cycle, on the model clock (a shutdown, for instance); `rows=True` keeps + the ids of the amber and red rows of every cycle in the trace.""" + ratings = ratings or {"a": 5000.0, "b": 4600.0} + socs = socs or {u: 50.0 for u in ratings} + sim = sim or SimCharger(setpoint_a=setpoint) + if plug: + sim.plug_in(car_phases=car_phases) + sim.phases_allowed = phases + units = sorted(ratings) + o = rig._options(len(units), dict({ + "meter_source": "ha_signed", "p1_net_entity": "sensor.net", + "meter_phases": 1, "peak_cap_w": cap, "peak_margin_w": margin, + "battery_modes_enabled": True, + "ev_charger": "alfen_ha", "ev_max_a": 16, "ev_phases": "auto", + "ev_current_entity": SET}, **(opts or {}))) + if len(units) == 1: + o["max_w"] = ratings[units[0]] + else: + o["inverters"] = [dict(x, max_w=ratings[x["name"][-1]]) + for x in o["inverters"]] + store = store or rig._Store() + store.data["car_mode"] = mode + store.data["car_sun_first"] = first + for u in units: + store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = True + db = os.path.join(tempfile.mkdtemp(prefix="ev20-"), "tariff.db") + out = {} + events_in = events or {} + + async def go(): + plant = (plant_cls or SunPlant)(house, sun, ratings, socs, sim) + c = Controller(o, plant, store, rig._Pub(), stop=asyncio.Event(), + peak_db_path=db) + for i in c.inverters: + r = ratings[i.name[-1]] if len(units) > 1 else ratings[units[0]] + i.dev_min, i.dev_max = -r, r + c.auto = True + clock = [t0] + plant.clock = clock # a finale may move the model clock + c.car_now = lambda: clock[0] + real_time = _p1.time + + class _Time: + """The meter's age on the model clock, so a silent meter goes + stale in model seconds.""" + def __getattr__(self, k): + return getattr(real_time, k) + + @staticmethod + def monotonic(): + return clock[0] + _p1.time = _Time() + if hasattr(c.charger, "_sleep"): + async def sleep(s): + sim.tick(s) + clock[0] += s + plant.t = clock[0] + c.charger._sleep = sleep + c.charger._clock = lambda: clock[0] + real_dt = main_files.live.datetime + + class _DT(real_dt): + @classmethod + def now(cls, tz=None): + return rig.BASE + timedelta(seconds=clock[0] + plant.utc_off) + main_files.live.datetime = _DT + trace = [] + try: + t = t0 + while t < t0 + dur: + plant.t = clock[0] = t + fn = events_in.get(int(t)) if t == int(t) else None + if fn is not None: + r = fn(plant, c) + if asyncio.iscoroutine(r): + await r + sim.tick(1.0) + ts = t - SAMPLE_LEAD_S + if plant.meter_on and not plant.ha_down: + plant.meter = plant.grid(ts) + imp, exp = split_signed(plant.meter) + c.p1.submit(make_sample( + "ha_signed", imp, exp, phases=1, + ingest_ts=rig.BASE + timedelta(seconds=ts), + ingest_mono=ts)) + await c.read_inputs(now_mono=t) + if race: + await c.car_settle() + await c.cycle() + else: + await c.cycle() + await c.car_settle() + w = c.car_solar + g = c.peak_guard + trace.append(dict( + t=t, a=w.plan.a, why=w.plan.why, n=w.plan.n, + sp=sim.setpoint_a, rb=sim.readback_a, + ph=sim.phases_allowed, car=sim.power_w, st=sim.state, + grid=plant.grid(t), batt=plant.batt(t), + house=plant.house(t), sun=plant.sun(t), + explains=c.car_explains, over=c.car_over, + lim=bool(g is not None and (g.floor_limited + or g.saturated)), + floor=(None if g is None else g.floor_w), + excess=(None if g is None else g.excess_w), + want=(None if g is None else g.wanted_w), + socs=dict(plant.socs), + proj=(None if g is None else g.projected_w), + target=(None if g is None else g.target_w), + would=w.would, single=w.single, + spare=c.car_spare_w(t), ok=w.plan.ok_since, + hold=w.hold, gave_up=w.gave_up, sent=w.sent_a, + room=(None if w.sun is None else w.sun.room_w), + taken=w.taken, + red=[x["id"] for x in c.checks() + if x["ok"] is False and not x["warn"]] + if on_cycle == "rows" or rows else [], + amber=[x["id"] for x in c.checks() + if x["ok"] is False and x["warn"]] + if rows else [], + own=c._car_own_pause(c.car_now()), + alarm_w=c.car_alarm_w(), peak_q=dict(c.car_peak_q), + other=w.other, mismatch=w.mismatch_since, + fails=w.fails, fault=w.fault)) + if callable(on_cycle): + on_cycle(plant, c, t) + for u, kwh in (caps or {}).items(): + # 1 s of W, as a percent of kWh: W / 3600 / (kWh x 1000) x 100 + lv = plant.socs[u] - plant.batt_of(u, t) / 36000.0 / kwh + plant.socs[u] = max(0.0, min(100.0, lv)) + t += 1.0 + await c.car_settle() + if finale is not None: + plant.t = clock[0] + await finale(plant, c) + finally: + main_files.live.datetime = real_dt + _p1.time = real_time + out.update(plant=plant, c=c, sim=sim, trace=trace, store=store, + raised=list(plant.notes), clock=clock) + asyncio.run(go()) + return out + + +def ids(out, *wanted): + return [(t, n) for t, n in out["raised"] if n in wanted] + + +def writes(out, what="current"): + """(t, value) of every charger write of that kind, in model seconds.""" + return [(x[0], x[2]) for x in out["sim"].writes(what)] + + +def const(w): + return lambda t: float(w) + + +if __name__ == "__main__": + logging.disable(logging.CRITICAL) + for first in ("batteries", "car"): + r = drive(const(900.0), const(7900.0), dur=600, first=first, + socs={"a": 71.0, "b": 100.0}) + print(f"scenario 2, {first} first: writes {writes(r)} phases " + f"{writes(r, 'phases')} batteries {r['plant'].batt(599):.0f} W " + f"grid {r['plant'].grid(599):.0f} W") diff --git a/goodwe_controller/translations/en.yaml b/goodwe_controller/translations/en.yaml index 6ba1f20..a4d5bff 100644 --- a/goodwe_controller/translations/en.yaml +++ b/goodwe_controller/translations/en.yaml @@ -300,7 +300,16 @@ configuration: description: "While the car charges. On: the batteries cover it down to the peak reserve. Off: the peak guard leaves the car out, so the car alone can set the peak." ev_mode_start: name: "Car charger · Mode after a restart" - description: "Keep the last mode, or start in Off. A restart never changes the charger's current." + description: "Keep the last mode, or start in Off. A restart in Solar sets the charger to 0 A first, other modes leave its current." + ev_margin_w: + name: "Car charger · Sun kept back (W)" + description: "Solar: this much spare sun is never given to the car." + ev_start_min: + name: "Car charger · Start after (minutes)" + description: "Solar: the car starts after this long with enough spare sun." + ev_pause_min: + name: "Car charger · Pause after (minutes)" + description: "Solar: with too little sun the car holds 6 A this long, then pauses." auto_start: name: "Advanced · Start control on boot" description: "Off by default. Leave it off until the site is commissioned, so someone presses Start after each restart." diff --git a/goodwe_controller/translations/nl.yaml b/goodwe_controller/translations/nl.yaml index 064fd31..596080e 100644 --- a/goodwe_controller/translations/nl.yaml +++ b/goodwe_controller/translations/nl.yaml @@ -281,7 +281,16 @@ configuration: description: "Terwijl de auto laadt. Aan: de batterijen dekken ze tot de piekreserve. Uit: de piekbewaking laat de auto buiten beschouwing, dus de auto alleen kan de piek bepalen." ev_mode_start: name: "Laadpaal · Modus na een herstart" - description: "De laatste modus houden, of starten in Uit. Een herstart verandert de stroom van de laadpaal nooit." + description: "De laatste modus houden, of starten in Uit. Een herstart in Zon zet de laadpaal eerst op 0 A, andere modi laten haar stroom." + ev_margin_w: + name: "Laadpaal · Zon achtergehouden (W)" + description: "Zon: zoveel zonne-overschot krijgt de auto nooit." + ev_start_min: + name: "Laadpaal · Starten na (minuten)" + description: "Zon: de auto start na zo lang genoeg zonne-overschot." + ev_pause_min: + name: "Laadpaal · Pauzeren na (minuten)" + description: "Zon: met te weinig zon houdt de auto zo lang 6 A en pauzeert dan." auto_start: name: "Geavanceerd · Regeling starten bij opstarten" description: "Staat standaard uit. Laat het uit tot de installatie in dienst is, zodat iemand na elke herstart op Start drukt." -- 2.54.0 From d18ed56fad59b08fa31a9a6b99875312d688d1b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 20:47:58 +0100 Subject: [PATCH 30/55] EV-20: T4 through the Controller, T21 (a) on car_cycle itself T4: battery A's power missing, NaN or unavailable, for one cycle (no write) and for 400 s (no spare, the current held, 0 A at 300 s). T21 (a): car_cycle on the same projection, guard and reading gives the same car figure, explains and over in Solar and Manual. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/test_ev20_exits.py | 40 ++++++++++++++++++++++++++++ goodwe_controller/test_ev20_guard.py | 16 +++++++++++ 2 files changed, 56 insertions(+) diff --git a/goodwe_controller/test_ev20_exits.py b/goodwe_controller/test_ev20_exits.py index 7039a3b..c8e537c 100644 --- a/goodwe_controller/test_ev20_exits.py +++ b/goodwe_controller/test_ev20_exits.py @@ -303,6 +303,46 @@ for k, fn in (("i", lambda p, c: None), and nth(after, 0)[0] <= 422 and not other and not any(x["hold"] for x in rr["trace"])) +# T4: battery A's power or the site's battery power missing (None), not a +# number (NaN) or "unavailable", at 10 A: one cycle, then 400 s. +class NanPlant(S.SunPlant): + """Battery A's power reads NaN (or the text 'unavailable') while set.""" + bad = None + + async def number(self, e, invert=False): + if e == "sensor.batt_a" and self.bad is not None: + return float("nan") if self.bad == "nan" else None + return await super().number(e, invert) + + async def state(self, entity_id): + if entity_id == "sensor.batt_a" and self.bad == "unavailable": + return {"entity_id": entity_id, "state": "unavailable", + "attributes": {}} + return await super().state(entity_id) + + +def _bad(kind): + def f(p, c): + p.bad = kind + return f + + +for kind in ("none", "nan", "unavailable"): + r1 = std(400, plant_cls=NanPlant, + events={300: _bad(kind), 301: _bad(None)}) + r4 = std(800, plant_cls=NanPlant, events={300: _bad(kind), + 700: _bad(None)}) + w4 = cur_writes(r4) + sp = [x["spare"] for x in r4["trace"] if 302 <= x["t"] < 700] + check(f"T4 [{kind}]: battery A's power bad for 1 cycle: no write " + f"({[x for x in cur_writes(r1) if x[0] >= 300]})", + [x for x in cur_writes(r1) if x[0] >= 300] == []) + check(f"T4 [{kind}]: bad for 400 s: no spare computed, the current held, " + f"then 0 A once at 300 s (+2 s) ({w4})", + sp and all(v is None for v in sp) + and [a for _, a, _ in w4 if _ < 700] == [10.0, 0.0] + and 599 <= [t for t, a, _ in w4 if a == 0.0][0] <= 602) + # T31: the meter goes silent at 10 A. for race in (False, True): tag = "race" if race else "step" diff --git a/goodwe_controller/test_ev20_guard.py b/goodwe_controller/test_ev20_guard.py index 24276a7..58bd6c3 100644 --- a/goodwe_controller/test_ev20_guard.py +++ b/goodwe_controller/test_ev20_guard.py @@ -110,6 +110,22 @@ for cover in (True, False): and round(a["proj"] or 0) != round(b["proj"] or 0)] check(f"T21 (c): with the cover off, the guard's own projection " f"(the car left out) is the Manual twin's ({pj[:2]})", not pj) +# T21 (a): car_cycle itself, fed the same projection, guard and reading on +# two Controllers that differ only in the mode (the twins of (c), now). +cs, cm = rs["c"], rm["c"] +proj_s, guard_s = cs._peak_proj_real, cs.peak_guard +same_in = (proj_s == cm._peak_proj_real + and repr(guard_s) == repr(cm.peak_guard) + and cs.car.reading == cm.car.reading) +cs.car_cycle(proj_s, guard_s, 3400.0, None) +cm.car_cycle(proj_s, guard_s, 3400.0, None) +check(f"T21 (a): car_cycle on the same projection, guard and reading gives " + f"the same car_alarm_w, car_explains and car_over in Solar and Manual " + f"(inputs equal {same_in}; {cs.car_alarm_w()} {cs.car_explains} " + f"{cs.car_over} vs {cm.car_alarm_w()} {cm.car_explains} {cm.car_over})", + same_in and (cs.car_alarm_w(), cs.car_explains, cs.car_over) + == (cm.car_alarm_w(), cm.car_explains, cm.car_over) + and cs.car_alarm_w() is not None) over_note = [x for x in rs["plant"].notes if x[1] == messages.ID_CAR_OVER] check("T21 D1: Solar's car-over notice reads 'Solar charges the car at 16 A' " "(the charger's current), never Manual's stored value", -- 2.54.0 From e0138a2ae5b020d5e39b3e8e0657b70c346be97f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 21:33:28 +0100 Subject: [PATCH 31/55] EV-20: SPIKE-05 decisions C1, C6, C9 (brief v5) with rows for C1, C5, C6, C8, C9 C1: an own 0 A not yet read back is kept with the mode; a start in Off with it writes the 0 A (retried), without it nothing; a start that will not write warns once when the charger still has the add-on's current. C6: Solar's 30 s gate also counts from Manual's latest write. C9: an exit also owes its 0 A when the read-back shows Solar's own value. Rows for C5 and C8 too. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 20 +++ goodwe_controller/DOCS.md | 8 ++ goodwe_controller/app/carmode.py | 49 +++++++- goodwe_controller/app/ctl_car.py | 51 ++++++++ goodwe_controller/app/ctl_cycle.py | 1 + goodwe_controller/app/messages.py | 19 +++ goodwe_controller/test_ev20.py | 25 +++- goodwe_controller/test_ev20_exits.py | 114 +++++++++++++++++- 8 files changed, 282 insertions(+), 5 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 263c9b0..4711d22 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -88,3 +88,23 @@ one small set of facts and derives every path from them: today's kWh; stored with its day, reset at the day's change. - **Rollback.** An older build reads a stored `car_mode = solar` as Off (`start_mode`) and writes nothing; no state migration. + +## SPIKE-05 decisions (brief v4/v5) + +- **C1.** An own 0 A that is out and not read back is kept in the store with + the mode (`car_exit_0a_pending`). A start in Off with that flag writes the + 0 A (when it may write), retried by the exit rule; Off without it writes + nothing (N10). A start that will not write (shadow, control stopped) after + Manual or Solar, with the charger showing a current, writes nothing and + raises one warning, *Charger kept its current*, taken down at 0 A. +- **C5.** Each shutdown try waits 4 s for its read-back (D3 above). +- **C6.** One write clock: Solar's 30 s gate also counts from Manual's latest + non-zero write, the start included. Solar's first write after Manual is its + 0 A, which is never gated. +- **C8.** A charger or HA outage ends a phase change: the return restarts the + plan paused, so nothing of the sequence resumes; only a 0 A may come before + the start rule. +- **C9.** An exit owes its 0 A while Solar's own value may stand: by its own + bookkeeping (a 0 A not read back counts) or by the read-back showing a value + it sent, confirmed, tried or saw at a refused try. +- **C3** is T43-T45; **C7** is EV-22's. diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index 92cb8fe..49beb91 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -3573,6 +3573,14 @@ alarm. It is raised once per charging session. To stay under the limit, lower th current. In Solar it says "Solar charges the car at {a} A, which sets the peak.": the same case, with the current the charger has. +### Charger kept its current + +The add-on started without writing to the charger (shadow mode, or control +not started yet), and the charger still has the current the add-on set before +it stopped, in Manual or Solar. Nothing changes the charger until you start +control or turn shadow mode off. Check the charger if the car should not be +charging. The notification goes once the charger shows 0 A. + ### Car may still be charging The add-on stopped in Solar mode, and the charger did not take the 0 A it sent diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index e58a777..2b75293 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -515,6 +515,7 @@ class SolarPlan: self.why = why self.target_w = None self._before = None # the state before a phase change + self.ext_at = None # C6: Manual's latest non-zero write def pause(self, why="paused"): self.a = 0.0 @@ -524,7 +525,9 @@ class SolarPlan: self.why = why def _gate(self, now) -> bool: - return self.set_at is None or now - self.set_at >= SOLAR_WRITE_S + """30 s since the latest non-zero write, Solar's or (C6) Manual's.""" + return all(t is None or now - t >= SOLAR_WRITE_S + for t in (self.set_at, self.ext_at)) def _set(self, a, now, n=None): if n is not None and n != self.n: @@ -584,7 +587,7 @@ class SolarPlan: if self.ok_since is None: self.ok_since = now self.why = "start" - if now - self.ok_since >= start_s \ + if now - self.ok_since >= start_s and self._gate(now) \ and (n0 == self.n or gap_ok): a = amps_for(target_w, n0, clamp) if a is not None and a >= CH.MIN_A: @@ -691,6 +694,19 @@ class SolarWriter(ManualWriter): self._would_switch = None # ... and when it last changed them self.released = None # D3: True / False once shutdown tried self.mode_was = None # the mode of the previous step + self.start_owed = False # C1: a start in Off with a 0 A pending + self.other_at = None # C6: Manual's latest non-zero write + self.on_owed = None # C1: told when an own 0 A is out / back + + def owe_start(self) -> None: + """C1: the add-on starts in Off while an exit 0 A of its own was still + pending at the stop: the current the charger shows is the add-on's, + so the 0 A is owed (once it may write), retried by the exit rule.""" + self.start_owed = self.engaged = True + + def _owed(self, pending: bool) -> None: + if self.on_owed is not None: + self.on_owed(pending) # ------------------------------------------------------------- state @property @@ -735,6 +751,7 @@ class SolarWriter(ManualWriter): zero = float(a) <= TOL_A if zero: self.zero_at = self.zero_sent_at = now + self._owed(True) # C1: kept with the mode until back try: ok = await super()._write(drv, a, was, now, tracker, **kw) finally: @@ -743,6 +760,8 @@ class SolarWriter(ManualWriter): if ok: self.taken = True self.fails, self.fail_at, self.gave_up = 0, None, False + if zero: + self._owed(False) else: self._failed(now) return ok @@ -758,6 +777,8 @@ class SolarWriter(ManualWriter): def _adopt(self, cur) -> None: """The read-back shows what Solar sent: taken, however late.""" + if self.sent_a is not None and self.sent_a <= TOL_A: + self._owed(False) self.taken = True self.last_a = cur self.attempted_a = self.prior_a = None @@ -787,11 +808,23 @@ class SolarWriter(ManualWriter): return await self._write(drv, want, cur, now, tracker) + def _own_readback(self, cur) -> bool: + """C9: does the read-back show a current of Solar's own (sent, + confirmed, tried, or shown when a try was refused)?""" + if cur is None or cur <= TOL_A: + return False + return any(k is not None and k > TOL_A and abs(cur - k) <= TOL_A + for k in (self.sent_a, self.last_a, self.attempted_a, + self.prior_a)) + async def _zero(self, drv, cur, now, tracker, stuck=False) -> None: - """A way out: 0 A while Solar's own current may stand, never over + """A way out: 0 A while Solar's own current may stand (its own + bookkeeping, or C9 the read-back showing its value), never over another writer's hold.""" self.seq = None self.plan.end_switch(False) + if not self.live and self._own_readback(cur) and not stuck: + self.taken = False # C9: a 0 A is owed if self.live and not self.hold: await self._put(drv, 0.0, cur, now, tracker, stuck) @@ -830,6 +863,7 @@ class SolarWriter(ManualWriter): def _leave(self) -> None: """Solar is no longer the mode and owes nothing.""" self.engaged, self.seq, self.would = False, None, None + self.start_owed = False self.out, self.fault = False, None self.restart = True self.mismatch_since = None @@ -840,6 +874,7 @@ class SolarWriter(ManualWriter): >= PHASE_GAP_S def _plan_step(self, sun, now, clamp, n_now, gap_ok) -> None: + self.plan.ext_at = self.other_at self.plan.step( now, target_w=sun.target_w, hold=sun.hold, n_now=n_now, auto=sun.auto and not self.single and not self.phases_gave_up, @@ -932,6 +967,14 @@ class SolarWriter(ManualWriter): self._mark(r, now) if mode != SOLAR: self.would = None + if mode == OFF and self.start_owed: + if not writing: + return # C1: waits; the start warning says so + self.start_owed = False + if cur is not None and cur > TOL_A and not self.hold: + self.sent_a, self.taken = cur, True # ours, from before + else: + self._owed(False) if mode == OFF: # 0 A while owed, then nothing await self._zero(drv, cur, now, tracker, stuck) if self.live and not self.hold: diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 8a4f08f..e014347 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -41,6 +41,9 @@ RISE_STILL_W = 50.0 # charger did not take (D3), so the next start can take its notice down. CAR_SUN_KEY = "car_sun" CAR_RELEASE_KEY = "car_release_failed" +# C1 (SPIKE-05): an own 0 A of Solar's is out and not read back yet, kept with +# the mode, so a start in Off after a power cut still writes it. +CAR_EXIT_KEY = "car_exit_0a_pending" # EV-20 (D3): at shutdown in Solar the charger's 0 A waits at most this long, # then the inverters are released whatever the charger did. RELEASE_WAIT_S = 15.0 @@ -53,6 +56,13 @@ class CarMixin: restart does with the mode. A site with no charger keeps defaults and writes nothing.""" data = getattr(store, "data", None) or {} + # C1: the mode before the stop, and an exit 0 A still pending then. + stored = data.get(carmode.KEY_MODE) + self._car_stored_mode = stored if stored in carmode.MODES \ + else carmode.OFF + self._car_exit_pending = bool(data.get(CAR_EXIT_KEY)) + self._car_start_seen = False + self._car_start_warned = False self.car_mode = carmode.start_mode(opts, data.get(carmode.KEY_MODE)) if carmode.start_mode(opts, carmode.MANUAL) == carmode.OFF \ and data.get(carmode.KEY_MODE) not in (None, carmode.OFF): @@ -66,6 +76,9 @@ class CarMixin: self.car_rev = 0 self.car_writer = carmode.ManualWriter() self.car_solar = carmode.SolarWriter() # EV-20 + self.car_solar.on_owed = self._car_owed + if self.car_mode == carmode.OFF and self._car_exit_pending: + self.car_solar.owe_start() # C1 first = data.get(carmode.KEY_FIRST) self.car_first = first if first in carmode.FIRSTS \ else carmode.DEFAULT_FIRST @@ -116,6 +129,40 @@ class CarMixin: return (self.charger.configured() and self.car_mode == carmode.MANUAL) + def _car_owed(self, pending) -> None: + """C1: keep "an own 0 A is out, not read back" with the mode.""" + pending = bool(pending) + if pending != self._car_exit_pending: + self._car_exit_pending = pending + self.store.set(CAR_EXIT_KEY, pending) + + async def check_car_start(self) -> None: + """C1: the first reading after a start that will not write (shadow, + control stopped) shows a current the add-on set before the stop + (Manual or Solar then): one warning, taken down once it is 0 A.""" + r = self.car.reading + if r is None or not r.available or not self.charger.configured(): + return + cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a + if not self._car_start_seen: + self._car_start_seen = True + if self._car_stored_mode in (carmode.MANUAL, carmode.SOLAR) \ + and not self.car_writing() and cur is not None \ + and cur > carmode.TOL_A: + self._car_start_warned = True + _LOG.warning("The charger still has a current from before " + "the restart, and the add-on does not write " + "now: CHARGER_START_CURRENT.") + _LOG.debug("The charger shows %.0f A at the start.", cur) + await self.hass.call("persistent_notification", "create", + messages.car_start_current( + f"{cur:.0f}").data()) + elif self._car_start_warned and cur is not None \ + and cur <= carmode.TOL_A: + self._car_start_warned = False + await self.hass.call("persistent_notification", "dismiss", + messages.car_start_current_gone().data()) + def car_solar_mode(self) -> bool: """EV-20: a charger is set up and the mode is Solar.""" ch = getattr(self, "charger", None) @@ -331,6 +378,10 @@ class CarMixin: status=self.car.status(now, True), clock=self.car_now) w = self.car_solar if self.car_mode == carmode.SOLAR or w.engaged: + # C6: one write clock: Manual's latest non-zero write counts. + w.other_at = max((t for kind, a, t, ok in self.car_writer.log + if kind == "current" and a > carmode.TOL_A), + default=None) sun = None if self.car_mode == carmode.SOLAR: sun = getattr(self, "_car_sun_now", None) \ diff --git a/goodwe_controller/app/ctl_cycle.py b/goodwe_controller/app/ctl_cycle.py index a86a6c3..59dd444 100644 --- a/goodwe_controller/app/ctl_cycle.py +++ b/goodwe_controller/app/ctl_cycle.py @@ -1070,6 +1070,7 @@ class CycleMixin: await self.check_charger() await self.check_car_over() await self.check_car_release() # EV-20 (D3) + await self.check_car_start() # EV-20 (C1) self.car_kick() # EV-04/20: in the background await self.check_fixed_note() diff --git a/goodwe_controller/app/messages.py b/goodwe_controller/app/messages.py index c1b971a..40cf951 100644 --- a/goodwe_controller/app/messages.py +++ b/goodwe_controller/app/messages.py @@ -191,6 +191,8 @@ T_CHARGER_UNREACH_NL = "Laadpaal onbereikbaar" T_CAR_OVER = "Car over the peak limit" T_CAR_OVER_NL = "Auto boven de piekgrens" T_CAR_RELEASE = "Car may still be charging" +T_CAR_START = "Charger kept its current" +T_CAR_START_NL = "Laadpaal hield haar stroom" T_CAR_RELEASE_NL = "Auto laadt mogelijk nog" T_NO_PRICES = "No prices" T_NO_PRICES_NL = "Prijzen ontbreken" @@ -207,6 +209,7 @@ ID_NO_PRICES = "goodwe_no_prices" ID_CHARGER_UNREACH = "goodwe_charger_unreachable" ID_CAR_OVER = "goodwe_car_over" ID_CAR_RELEASE = "goodwe_car_release" +ID_CAR_START = "goodwe_car_start_current" # PRICE-01: an earlier build raised a card with this id. Nothing raises it now; # the add-on only dismisses it at start. OLD_FIXED_CARD_ID = "goodwe_fixed_tariff_unused" @@ -554,6 +557,21 @@ def car_release_failed() -> Notice: body_nl=f"{T_CAR_RELEASE_NL}. {nl}") +def car_start_current(a_text) -> Notice: + """EV-20 (C1): the add-on starts without writing (shadow mode, control + stopped) and the charger still has a current the add-on set before the + stop. Taken down once the charger shows 0 A.""" + return Notice(ID_CAR_START, WARNING, T_CAR_START, + f"Charger still at {a_text} A from before the restart.", + body_nl=f"{T_CAR_START_NL}. Laadpaal staat nog op {a_text} A " + f"van voor de herstart.") + + +def car_start_current_gone() -> Dismiss: + """EV-20 (C1): takes the 'Charger kept its current' notice down.""" + return Dismiss(ID_CAR_START) + + def car_release_gone() -> Dismiss: """EV-20 (D3): takes the 'Car may still be charging' notice down.""" return Dismiss(ID_CAR_RELEASE) @@ -1877,6 +1895,7 @@ def samples() -> list: car_over("16"), car_over_solar("8"), car_release_failed(), + car_start_current("10"), ] diff --git a/goodwe_controller/test_ev20.py b/goodwe_controller/test_ev20.py index f212a17..18a3c17 100644 --- a/goodwe_controller/test_ev20.py +++ b/goodwe_controller/test_ev20.py @@ -31,7 +31,7 @@ import ev20_sun as S # noqa: E40 from chargersim import SimCharger # noqa: E402 from ev20_kit import * # noqa: E402,F401,F403 from ev20_kit import LOG, check, fails, report # noqa: E402,F401 -from named_absence import nth, present # noqa: E402,F401 +from named_absence import given, nth, present # noqa: E402,F401 from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401 _until) @@ -426,6 +426,29 @@ check("T5 (iv): a charger reading older than 15 s (this driver: the charger " r5d["trace"][330]["spare"] is None and [a for _, a, _ in cur_writes(r5d)] == [10.0]) +# C6: one write clock. A plan whose start dwell is done waits 30 s from +# Manual's latest non-zero write (`ext_at`), and from its own. +p6 = SolarPlan(1) +starts6 = [] +for k in range(300): + p6.ext_at = 150.0 + p6.step(float(k), target_w=3000.0, n_now=1, auto=False, clamp=16, + start_s=120.0, pause_s=300.0) + if p6.a > 0.0 and not starts6: + starts6.append(k) +check(f"C6: Manual wrote at 150 s; Solar's start dwell is done at 120 s but " + f"its first current waits for 180 s ({starts6})", starts6 == [180]) +r6m = std(400, mode="manual", sim=SimCharger(setpoint_a=0), + opts={"ev_start_min": 1}, + events={100: act("car_current", 12), 105: act("car_mode", "solar")}) +w6m = [(t, a) for t, a, _ in cur_writes(r6m)] +man = [x[0] for x in r6m["sim"].log if x[2] > 0.0 and x[0] <= 106] +check(f"C6: Manual writes 12 A, then Solar is chosen: Solar's own first " + f"write is 0 A, and no current of Solar's within 30 s of Manual's " + f"({man}, Solar {w6m})", + w6m[:1] and w6m[0][1] == 0.0 and present(nth(man, -1)) + and not [t for t, a in w6m if a > 0.0 and t - nth(man, -1) < 30.0]) + # T13: the start rule. for race in (False, True): tag = "race" if race else "step" diff --git a/goodwe_controller/test_ev20_exits.py b/goodwe_controller/test_ev20_exits.py index c8e537c..1136b76 100644 --- a/goodwe_controller/test_ev20_exits.py +++ b/goodwe_controller/test_ev20_exits.py @@ -30,7 +30,7 @@ import ev20_sun as S # noqa: E40 from chargersim import SimCharger # noqa: E402 from ev20_kit import * # noqa: E402,F401,F403 from ev20_kit import LOG, check, fails, report # noqa: E402,F401 -from named_absence import nth, present # noqa: E402,F401 +from named_absence import given, nth, present # noqa: E402,F401 from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401 _until) @@ -589,6 +589,118 @@ check(f"T37: shutdown while the 0 -> 10 A start write waits for its " and [x[2] for x in sim37.log][-1:] == [0.0] and sim37.setpoint_a == 0.0) +# C1 (SPIKE-05, brief v5): a start-up after a stop with no release. +import opt11_identity as rig # noqa: E402 + + +def _store(mode, pending=None): + st = rig._Store() + st.data["car_mode"] = mode + if pending is not None: + st.data[ctl_car.CAR_EXIT_KEY] = pending + return st + + +for pending, name in ((True, "Off, flag set, charger at 10 A -> 0 A written"), + (False, "Off, no flag -> nothing")): + simc = TSim(setpoint_a=10, windows=[(0.0, 2.5, "error")]) + rr = std(200, sim=simc, mode="off", store=_store("off", pending)) + w = cur_writes(rr) + if pending: + check(f"C1 [{name}]: the 0 A at the first reading, refused, tried " + f"again 60 s later and taken; the flag cleared ({w})", + [(round(t), a, ok) for t, a, ok in w] + in ([(0, 0.0, False), (60, 0.0, True)], + [(1, 0.0, False), (61, 0.0, True)]) + and simc.setpoint_a == 0.0 + and rr["store"].data.get(ctl_car.CAR_EXIT_KEY) is False) + else: + check(f"C1 [{name}]: nothing written (N10) ({simc.log})", + simc.log == [] and simc.setpoint_a == 10.0) +# The PM's shape: Solar at 10 A, Off whose 0 A is refused, a power cut before +# the retry; the restart (keep) in Off writes the 0 A. +simp = TSim(setpoint_a=0, windows=[(300.0, 1e9, "error")]) +rp = std(330, sim=simp, events={300: act("car_mode", "off")}) +flag = rp["store"].data.get(ctl_car.CAR_EXIT_KEY) +simp.windows = [] +n0 = len(simp.log) +rq = std(100, sim=simp, store=rp["store"], mode="off") +new = [(x[0], x[2]) for x in simp.log[n0:]] +check(f"C1: Off whose 0 A was refused, a power cut before its retry: the flag " + f"is kept ({flag}), and the restart in Off writes the 0 A at once " + f"({new})", flag is True and new[:1] and new[0][1] == 0.0 + and simp.setpoint_a == 0.0) +# Shadow or control stopped at the start: no write, one warning. +for stored, opts, ev, warn in ( + ("solar", {"shadow_mode": "on"}, {}, True), + ("manual", {"shadow_mode": "on"}, {}, True), + ("solar", {"shadow_mode": "auto"}, + {0: lambda p, c: setattr(c, "auto", False)}, True), + ("off", {"shadow_mode": "on"}, {}, False)): + n = LOG.mark() + simw = SimCharger(setpoint_a=10) + rr = std(120, sim=simw, opts=opts, events=ev, mode=stored) + wl = [m for m in LOG.since(n, "WARNING") if "CHARGER_START_CURRENT" in m] + notes_ = [x for _, x in rr["raised"] if x == messages.ID_CAR_START] + check(f"C1 [stored {stored}, {opts.get('shadow_mode')}" + f"{', stopped' if ev else ''}]: nothing written; " + f"{'one warning' if warn else 'no warning'} " + f"({len(wl)} log, {len(notes_)} notice)", + simw.log == [] and len(wl) == (1 if warn else 0) + and len(notes_) == (1 if warn else 0)) +check("C1: the warning's words, EN and NL", + messages.car_start_current("10").body + == "Charger still at 10 A from before the restart." + and "10 A" in messages.car_start_current("10").body_nl) + +# C5: each shutdown try waits at most 4 s for its read-back, so three fit in +# 15 s against a charger that ignores the write. +sim5 = TSim(setpoint_a=0, windows=[(299.5, 1e9, "ignore")]) +r5 = run("C5", std, 300, sim=sim5, finale=_shutdown) +tr5 = [t for t, v in attempts(r5) if t >= 299] +check(f"C5: a charger that ignores the 0 A: three tries ({tr5}) about 5 s " + f"apart, each waiting 4 s at most, the inverters by 15 s " + f"(+{_until(r5, 299.0)})", + len(tr5) == 3 and all(4.0 <= b - a <= 6.0 for a, b in zip(tr5, tr5[1:])) + and present(given(_until(r5, 299.0))) + and _until(r5, 299.0) <= 15.0) + +# C8: a charger outage in the middle of a phase change ends it; the first +# write after the return is never a current (N12). +for stage, dt in (("zero", 2), ("settle", 6)): + sim8 = SimCharger(setpoint_a=0) + sim8.ramp_w_s = 600.0 + rr = std(900, sun=step_fn((400, 600.0 + 4500.0), base=600.0 + 3000.0), + sim=sim8, events={580 + dt: lambda p, c: p.ch.go_unavailable(True), + 620: lambda p, c: p.ch.go_unavailable(False)}) + w = [(t, a) for t, a, _ in cur_writes(rr) if t >= 620] + check(f"C8 [{stage}]: the charger away from 580 + {dt} s to 620 s: the " + f"sequence ends, nothing of it resumes: before the start rule's " + f"120 s from the return only a 0 A may be written (here the " + f"charger came back at the sequence's 0 A) ({w})", + not [a for t, a in w if a > 0.0 and t < 740.0] + and rr["trace"][625]["sp"] == 0.0) + +# C9: Solar's 6 A lands late, then its 0 A pause is refused, then Off: the +# exit 0 A and its retry still come (decided from the read-back). +sim9 = SimCharger(setpoint_a=0) +r9 = std(500, sim=sim9, sun=step_fn((190, 600.0 + 700.0), + base=600.0 + 2300.0), + opts={"ev_pause_min": 1}, + events={185: lambda p, c: setattr(p.ch, "lag_s", 12.0), + 205: lambda p, c: setattr(p.ch, "lag_s", 0.0), + 249: lambda p, c: setattr(p.ch, "refuse", "error"), + 255: act("car_mode", "off"), + 257: lambda p, c: setattr(p.ch, "refuse", None)}) +w9 = cur_writes(r9) +z9 = [(t, ok) for t, a, ok in w9 if a == 0.0] +check(f"C9: the 6 A late, the pause's 0 A refused, then Off: the 0 A is " + f"tried again 60 s after the refusal and taken; the charger ends at " + f"0 A ({w9})", + len(z9) == 2 and present(nth(z9, 0)) and nth(z9, 0)[1] is False + and nth(z9, 1)[1] is True and 59 <= nth(z9, 1)[0] - nth(z9, 0)[0] <= 61 + and sim9.setpoint_a == 0.0) + # T61: the start-up in Solar after a stop with no release. for k, sp, kw in (("10 A, keep", 10, {}), ("16 A by another writer", 16, {}), -- 2.54.0 From 9c82bc816a0c70601dcde5cca19fc703a7407ddc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 00:34:24 +0100 Subject: [PATCH 32/55] EV-20 review round 1: no 1-phase current on 3 phases after a select; rows for mE, mF, mC After its own phase select (taken, or with a late read-back), Solar ends the sequence with the lower of the currents for the new phases and the phases the charger reports, and keeps the plan on them; the old phases' current comes back only when no select went out (EV-28's cap). Rows: T19/T33 settle write refused or ignored once and select confirmed late; an exit after a given-up write; shutdown in Off with the 0 A owed; Stop with a refused 0 A and another writer. NoCharger.write_current takes took_s; ev_mode_start text names C1; NL solar_hold wording. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/DOCS.md | 2 +- goodwe_controller/app/carmode.py | 36 ++++++++++++++++------ goodwe_controller/app/chargers.py | 2 +- goodwe_controller/app/ui_text/nl.json | 2 +- goodwe_controller/test_ev20.py | 42 ++++++++++++++++++++++++++ goodwe_controller/test_ev20_exits.py | 28 +++++++++++++++++ goodwe_controller/test_ev20_writers.py | 12 ++++++++ goodwe_controller/translations/en.yaml | 2 +- goodwe_controller/translations/nl.yaml | 2 +- 9 files changed, 114 insertions(+), 14 deletions(-) diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index 49beb91..0990a0e 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -256,7 +256,7 @@ The label and description each setting shows on the Configuration tab, in tab or | Car charger | Charger limit (A) | `ev_max_a` | The most current the charger may ever be asked for. Never above what the charger reports. Lower it for a weaker fuse or cable. | | Car charger | Phases | `ev_phases` | How many phases the charger may use: 1, 3, or 1 and 3 (auto). | | Car charger | Batteries help with the peak | `ev_batt_cover` | While the car charges. On: the batteries cover it down to the peak reserve. Off: the peak guard leaves the car out, so the car alone can set the peak. | -| Car charger | Mode after a restart | `ev_mode_start` | Keep the last mode, or start in Off. A restart in Solar sets the charger to 0 A first, other modes leave its current. | +| Car charger | Mode after a restart | `ev_mode_start` | Keep the last mode, or start in Off. A restart sets 0 A first in Solar, and in Off when a 0 A was pending. | | Car charger | Sun kept back (W) | `ev_margin_w` | Solar: this much spare sun is never given to the car. | | Car charger | Start after (minutes) | `ev_start_min` | Solar: the car starts after this long with enough spare sun. | | Car charger | Pause after (minutes) | `ev_pause_min` | Solar: with too little sun the car holds 6 A this long, then pauses. | diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 2b75293..ab77539 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -895,14 +895,23 @@ class SolarWriter(ManualWriter): and sun is not None and now - before[3] >= sun.pause_s) - def _seq_want(self, clamp): - """The current that ends a phase change: for the new phases, or for - the old ones when the select did not happen.""" + def _seq_want(self, clamp, n_reported): + """The current that ends a phase change. No select went out (EV-28's + cap): the old current, on the old phases. A select went out, taken + or not (its read-back may be late): the lower of the current for the + new phases and for the phases the charger reports, so nothing meant + for 1 phase is ever written on 3 (review round 1, Major 1).""" def want(q): before = self.plan._before - if q.get("failed") and before is not None: + if q.get("failed") and not q.get("sel") and before is not None: return before[0] if before[0] >= CH.MIN_A else CH.MIN_A - return self.amps_out(clamp) or CH.MIN_A + a = self.amps_out(clamp) or CH.MIN_A + tgt = self.plan.target_w + for n in (q.get("n"), n_reported): + b = amps_for(tgt, n, clamp) if n in (1, 3) else None + if b is not None: + a = min(a, max(b, CH.MIN_A)) + return a return want async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None: @@ -1059,12 +1068,21 @@ class SolarWriter(ManualWriter): self.plan.end_switch(False) self.plan.pause() return + n_log = len(self.log) await self._advance(drv, r, cur, now, tracker, - self._seq_want(clamp), clamp, None) + self._seq_want(clamp, r.phases_allowed), + clamp, None) + if any(x[0] == "phases" for x in self.log[n_log:]): + q["sel"] = True # a select went out, taken or not if self.seq is None: - # Done when the phases were selected and the current is back; - # otherwise the plan returns to its old phases. - self.plan.end_switch(not q.get("failed")) + # Back on the old phases only when no select went out; after + # one the plan keeps the current it wrote (the lower one) and + # takes the phases the charger reports from the next cycle. + done = not q.get("failed") or bool(q.get("sel")) + if done and q.get("sel") and self.sent_a is not None \ + and self.sent_a >= CH.MIN_A: + self.plan.a = min(self.plan.a, self.sent_a) + self.plan.end_switch(done) return self._plan_step(sun, now, clamp, n_now, gap) want = self.amps_out(clamp) diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index c2d56c0..1ea8fb7 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -618,7 +618,7 @@ class UnavailableCharger(ChargerDriver): async def read(self) -> ChargerReading: return ChargerReading(why=self.why) - async def write_current(self, a): + async def write_current(self, a, took_s=TOOK_S): return False async def write_phases(self, n): diff --git a/goodwe_controller/app/ui_text/nl.json b/goodwe_controller/app/ui_text/nl.json index 176432c..99ce893 100644 --- a/goodwe_controller/app/ui_text/nl.json +++ b/goodwe_controller/app/ui_text/nl.json @@ -291,7 +291,7 @@ "solar_batt": "Eerst de batterijen. De auto krijgt de {kw} zon die ze niet opnemen.", "solar_car": "Eerst de auto: die neemt {kw} zonne-overschot. De batterijen krijgen de rest.", "solar_paused": "Te weinig zonne-overschot voor 6 A. De auto start na {s} minuten genoeg zon.", - "solar_hold": "Te weinig zonne-overschot, dus de auto houdt 6 A. Ze pauzeert na {s} minuten.", + "solar_hold": "Te weinig zonne-overschot, dus de auto houdt 6 A. Hij pauzeert na {s} minuten.", "solar_start": "Er is nu genoeg zonne-overschot. De auto start na {s} minuten daarvan.", "solar_unknown": "Het zonne-overschot is nu niet te meten. De auto pauzeert als dit duurt.", "solar_would": "Schaduwmodus: de add-on zou de auto gepauzeerd houden.", diff --git a/goodwe_controller/test_ev20.py b/goodwe_controller/test_ev20.py index 18a3c17..fdc3939 100644 --- a/goodwe_controller/test_ev20.py +++ b/goodwe_controller/test_ev20.py @@ -686,6 +686,48 @@ for pmin, back in ((10, 6.0), (5, 0.0)): and (nth(w19f, 1)[1] == 6.0 if back else len(w19f) == 1) and not [a for t, a in w19f if a > 6.0]) nevers(r19f, f"T19 (failed, {pmin} min)") +# Review round 1, Major 1: Solar's own 1 -> 3 change (the T7 shape) where the +# select went out but (i) the settle current write is refused once, or (ii) +# the select's read-back comes later than 10 s. Every current written after the +# select is floor(car_w / (230 x the phases the charger reports)): 10 A, never +# the 1-phase 16 A on 3 phases. + + +class LateSel(SimCharger): + """The phases select shows in the read-back 12 s late (HA took it).""" + + def request_phases(self, n): + keep, self.lag_s = self.lag_s, 12.0 + try: + return super().request_phases(n) + finally: + self.lag_s = keep + + +r7b = S.drive(const(900.0), const(7900.0), dur=500, first="car", + socs={"a": 71.0, "b": 100.0}) +ts7 = [x[0] for x in r7b["sim"].log if x[1] == "current" + and x[2] not in (0.0, 16.0)] +for how, sim_ in (("settle write refused once", + TSim(setpoint_a=0, windows=[(nth(ts7, 0) - 1, + nth(ts7, 0) + 1, "error")])), + ("settle write ignored once", + TSim(setpoint_a=0, windows=[(nth(ts7, 0) - 1, + nth(ts7, 0) + 2, "ignore")])), + ("select confirmed late", LateSel(setpoint_a=0))): + rm1 = S.drive(const(900.0), const(7900.0), dur=600, first="car", + socs={"a": 71.0, "b": 100.0}, sim=sim_) + over = [(x["t"], x["sp"]) for x in rm1["trace"] + if x["ph"] == 3 and x["sp"] > 10.0] + after = [a for t, e, a in rm1["plant"].sets + if e == SET and t > 290.0] + check(f"T19/T33 [{how}]: after the select every current is 10 A for 3 " + f"phases, never 1-phase 16 A on 3 ({len(over)} s over 10 A on 3: " + f"{over[:3]}; currents tried after 290 s {after})", + present(nth(ts7, 0)) and not over and 16.0 not in after + and rm1["sim"].phases_allowed == 3 + and rm1["sim"].setpoint_a == 10.0) + nevers(rm1, f"T19/T33 [{how}]") r19a = std(1800, sun=const(600.0 + 6900.0), opts={"ev_phases": "1"}) check(f"T19: fixed 1 with 6.9 kW for 30 min: no select, 16 A " f"({cur_writes(r19a)})", selects(r19a) == [] diff --git a/goodwe_controller/test_ev20_exits.py b/goodwe_controller/test_ev20_exits.py index 1136b76..0f0c2ed 100644 --- a/goodwe_controller/test_ev20_exits.py +++ b/goodwe_controller/test_ev20_exits.py @@ -551,6 +551,34 @@ for name, (t0, ev, opts) in PATHS.items(): and "charger_refused" in [x["id"] for x in blk.get("rows", [])] and "paused" not in blk.get("b", {}).get("why", "paused")) +# Review round 1, Major 2 (mutant mE): an exit after a given-up non-zero write. +# Solar at 10 A; 13 A refused at 200, 260 and 320 s (given up); Off at 340 s: +# its 0 A has its own tries and goes out at once (N9). +simE = TSim(setpoint_a=0, windows=[(195.0, 330.0, "error")]) +rE = std(600, sim=simE, sun=step_fn((200, 3600.0), base=2900.0), + events={340: act("car_mode", "off")}) +aE = attempts(rE) +eo = [(t, v) for t, v in aE if t >= 340] +check(f"T36 [exit after a given-up write]: 13 A refused three times, then " + f"Off: the 0 A at once (340 s) and the charger at 0 A ({aE})", + [v for t, v in aE if 195 <= t < 340] == [13.0, 13.0, 13.0] + and present(nth(eo, 0)) and nth(eo, 0)[1] == 0.0 + and nth(eo, 0)[0] <= 342 and simE.setpoint_a == 0.0) + +# Review round 1, Major 4 (mutant mC): shutdown in Off while the exit 0 A is +# still owed: tried before the inverters' 0 W (E9, D3, N9). +simC = TSim(setpoint_a=0, windows=[(299.0, 1e9, "error")]) +rC = std(330, sim=simC, events={300: act("car_mode", "off")}, + finale=_shutdown) +oC = sets_order(rC) +zC = [i for i, (t, e, v) in enumerate(oC) if e == SET and v == 0.0 + and t >= 329] +iC = [i for i, (t, e, v) in enumerate(oC) + if e.startswith("number.sp_") and v == 0.0 and t >= 329] +check(f"T23/T36 [shutdown in Off, the 0 A still owed]: tried (3 times) " + f"before the inverters' 0 W ({[x for x in oC if x[0] >= 329][:6]})", + len(zC) == 3 and present(nth(iC, 0)) and nth(zC, 0) < nth(iC, 0)) + # T37: shutdown while a start write waits for its read-back. diff --git a/goodwe_controller/test_ev20_writers.py b/goodwe_controller/test_ev20_writers.py index 08f085e..babfc09 100644 --- a/goodwe_controller/test_ev20_writers.py +++ b/goodwe_controller/test_ev20_writers.py @@ -119,6 +119,18 @@ for name, fn in EXITS.items(): not [x for x in attempts(rr) if x[0] >= 600] and rr["sim"].setpoint_a == 16.0) +# Review round 1, Major 3 (mutant mF): Solar watches another writer while it +# does not write. Stop at 300 s (shadow_mode off), its 0 A refused 299-305 s; +# another writer sets 16 A at 310 s: nothing written over it (N10, N16). +simF = TSim(setpoint_a=0, windows=[(299.0, 305.0, "error")]) +rF = std(600, sim=simF, opts={"shadow_mode": "off"}, + events={300: lambda p, c: setattr(c, "auto", False), + 310: lambda p, c: p.ch.set_current(16)}) +lateF = [(t, v) for t, v in attempts(rF) if t >= 310] +check(f"T40/T42 [Stop, its 0 A refused, another writer]: nothing written " + f"over the 16 A, which stands ({attempts(rF)})", + not lateF and simF.setpoint_a == 16.0 and rF["c"].car_solar.hold) + # T41: the user changes Manual's values while Solar holds. r41 = std(1000, sun=const(600.0 + 2070.0), events={600: lambda p, c: p.ch.set_current(16), diff --git a/goodwe_controller/translations/en.yaml b/goodwe_controller/translations/en.yaml index a4d5bff..c96d837 100644 --- a/goodwe_controller/translations/en.yaml +++ b/goodwe_controller/translations/en.yaml @@ -300,7 +300,7 @@ configuration: description: "While the car charges. On: the batteries cover it down to the peak reserve. Off: the peak guard leaves the car out, so the car alone can set the peak." ev_mode_start: name: "Car charger · Mode after a restart" - description: "Keep the last mode, or start in Off. A restart in Solar sets the charger to 0 A first, other modes leave its current." + description: "Keep the last mode, or start in Off. A restart sets 0 A first in Solar, and in Off when a 0 A was pending." ev_margin_w: name: "Car charger · Sun kept back (W)" description: "Solar: this much spare sun is never given to the car." diff --git a/goodwe_controller/translations/nl.yaml b/goodwe_controller/translations/nl.yaml index 596080e..bdaf93f 100644 --- a/goodwe_controller/translations/nl.yaml +++ b/goodwe_controller/translations/nl.yaml @@ -281,7 +281,7 @@ configuration: description: "Terwijl de auto laadt. Aan: de batterijen dekken ze tot de piekreserve. Uit: de piekbewaking laat de auto buiten beschouwing, dus de auto alleen kan de piek bepalen." ev_mode_start: name: "Laadpaal · Modus na een herstart" - description: "De laatste modus houden, of starten in Uit. Een herstart in Zon zet de laadpaal eerst op 0 A, andere modi laten haar stroom." + description: "De laatste modus houden, of starten in Uit. Een herstart zet eerst 0 A in Zon, en in Uit als een 0 A openstond." ev_margin_w: name: "Laadpaal · Zon achtergehouden (W)" description: "Zon: zoveel zonne-overschot krijgt de auto nooit." -- 2.54.0 From cd8c393161516fca59462bf9c61a20bc3308dda2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 01:25:06 +0100 Subject: [PATCH 33/55] EV-20 review round 2: one write clock for every non-zero current (C6, N5) ManualWriter._write, the one write_current call, stamps every non-zero current either writer sends; Solar's 30 s gate reads that stamp (its own and Manual's), so the step back up after a phase change's closing write waits 30 s on every path. The closing current is fixed once per sequence, retries too. Rows: every select shape (refused, ignored, late; settle refused three times; T7 1 -> 3 and T22 3 -> 1) with nevers(). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/app/carmode.py | 27 ++++++++++++--- goodwe_controller/app/ctl_car.py | 4 +-- goodwe_controller/test_ev20.py | 58 ++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+), 8 deletions(-) diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index ab77539..eaf7593 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -139,6 +139,7 @@ class ManualWriter: 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 + self.nonzero_at = None # EV-20 C6: the latest non-zero write sent # ------------------------------------------------------------------ user def user_changed(self) -> None: @@ -263,6 +264,11 @@ class ManualWriter: async def _write(self, drv, a, was, now, tracker, **kw) -> bool: tracker.begin_write() # EV-12: the read-back is ours + if float(a) > TOL_A: + # EV-20 C6, THE ONE WRITE CLOCK: every non-zero current either + # writer sends, whatever path it comes from, is stamped here (the + # one write_current call). Solar's 30 s gate reads this stamp. + self.nonzero_at = now try: # EV-20: `kw` is only Solar's shorter read-back wait at shutdown. ok = await drv.write_current(a, **kw) @@ -874,7 +880,9 @@ class SolarWriter(ManualWriter): >= PHASE_GAP_S def _plan_step(self, sun, now, clamp, n_now, gap_ok) -> None: - self.plan.ext_at = self.other_at + # C6: the write clock, Solar's own latest non-zero write and Manual's. + self.plan.ext_at = max((t for t in (self.nonzero_at, self.other_at) + if t is not None), default=None) self.plan.step( now, target_w=sun.target_w, hold=sun.hold, n_now=n_now, auto=sun.auto and not self.single and not self.phases_gave_up, @@ -902,6 +910,14 @@ class SolarWriter(ManualWriter): new phases and for the phases the charger reports, so nothing meant for 1 phase is ever written on 3 (review round 1, Major 1).""" def want(q): + if "close_a" in q: + return q["close_a"] # one value per sequence, its retries too + q["close_a"] = a = self._close_a(q, clamp, n_reported) + return a + return want + + def _close_a(self, q, clamp, n_reported): + if True: before = self.plan._before if q.get("failed") and not q.get("sel") and before is not None: return before[0] if before[0] >= CH.MIN_A else CH.MIN_A @@ -912,7 +928,6 @@ class SolarWriter(ManualWriter): if b is not None: a = min(a, max(b, CH.MIN_A)) return a - return want async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None: """Step 1 of the safe sequence: 0 A (kept when it already stands). @@ -1079,10 +1094,12 @@ class SolarWriter(ManualWriter): # one the plan keeps the current it wrote (the lower one) and # takes the phases the charger reports from the next cycle. done = not q.get("failed") or bool(q.get("sel")) - if done and q.get("sel") and self.sent_a is not None \ - and self.sent_a >= CH.MIN_A: - self.plan.a = min(self.plan.a, self.sent_a) self.plan.end_switch(done) + close = q.get("close_a") + if close is not None and close >= CH.MIN_A: + # The sequence ended on this current: the plan's current + # now (its 30 s count is the write clock's, `_write`). + self.plan.a = float(close) return self._plan_step(sun, now, clamp, n_now, gap) want = self.amps_out(clamp) diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index e014347..7c0fdc4 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -379,9 +379,7 @@ class CarMixin: w = self.car_solar if self.car_mode == carmode.SOLAR or w.engaged: # C6: one write clock: Manual's latest non-zero write counts. - w.other_at = max((t for kind, a, t, ok in self.car_writer.log - if kind == "current" and a > carmode.TOL_A), - default=None) + w.other_at = self.car_writer.nonzero_at sun = None if self.car_mode == carmode.SOLAR: sun = getattr(self, "_car_sun_now", None) \ diff --git a/goodwe_controller/test_ev20.py b/goodwe_controller/test_ev20.py index fdc3939..e24ff24 100644 --- a/goodwe_controller/test_ev20.py +++ b/goodwe_controller/test_ev20.py @@ -728,6 +728,64 @@ for how, sim_ in (("settle write refused once", and rm1["sim"].phases_allowed == 3 and rm1["sim"].setpoint_a == 10.0) nevers(rm1, f"T19/T33 [{how}]") +# Review round 2 (C6, N5): every select shape, 1 -> 3 (T7) and 3 -> 1 (T22): +# no current meant for fewer phases than the charger has, and never two +# different non-zero currents under 30 s apart (the one write clock). + + +class PhSim(TSim): + """The phases select: 'lag' (read-back 12 s late), 'error' (HA refuses + it), 'ignore' (HA says yes, the charger keeps its phases).""" + ph_mode = None + + def request_phases(self, n): + if self.ph_mode == "lag": + keep, self.lag_s = self.lag_s, 12.0 + try: + return super().request_phases(n) + finally: + self.lag_s = keep + keep, self.refuse = self.refuse, self.ph_mode or self.refuse + try: + return super().request_phases(n) + finally: + self.refuse = keep + + +def _phsim(windows=(), ph=None): + s_ = PhSim(setpoint_a=0, windows=list(windows)) + s_.ph_mode = ph + return s_ + + +sun31 = step_fn((300, 600.0 + 4600.0), (700, 600.0 + 3700.0), + base=600.0 + 3000.0) +for how, shape, sim_, back in ( + ("select refused", "T7", _phsim(ph="error"), 16.0), + ("select ignored", "T7", _phsim(ph="ignore"), 16.0), + ("select late", "T7", _phsim(ph="lag"), 10.0), + ("settle refused 3 times", "T7", _phsim([(313, 330, "error")]), None), + ("normal", "T22", _phsim(), None), + ("select refused", "T22", _phsim(ph="error"), None), + ("select ignored", "T22", _phsim(ph="ignore"), None), + ("select late", "T22", _phsim(ph="lag"), None)): + if shape == "T7": + rs_ = S.drive(const(900.0), const(7900.0), dur=900, sim=sim_, + first="car", socs={"a": 71.0, "b": 100.0}) + cap3 = 10.0 + else: + rs_ = S.drive(const(600.0), sun31, dur=1500, sim=sim_, first="car", + socs={"a": 19.0, "b": 19.0}) + cap3 = 5.0 # 3700 - 600 - 100 W on 3 phases, under 6 A + over = [(x["t"], x["sp"]) for x in rs_["trace"] + if x["ph"] == 3 and x["sp"] > max(cap3, 6.0) and x["t"] > 300] + bad_ = nevers(rs_, f"round 2 [{shape}, {how}]") + end = rs_["trace"][-1] + check(f"round 2 [{shape}, {how}]: no current meant for fewer phases on " + f"the charger's ({over[:3]}); end {end['sp']} A on {end['ph']} " + f"phases ({[(x[0], x[1], x[2]) for x in rs_['sim'].log]})", + not over and not bad_ + and (back is None or (end["sp"] == back))) r19a = std(1800, sun=const(600.0 + 6900.0), opts={"ev_phases": "1"}) check(f"T19: fixed 1 with 6.9 kW for 30 min: no select, 16 A " f"({cur_writes(r19a)})", selects(r19a) == [] -- 2.54.0 From 5147c300b852a25fadb462a9d2c9009c2bfc5993 Mon Sep 17 00:00:00 2001 From: EV-20 reviewer Date: Mon, 23 Nov 2026 10:24:40 +0100 Subject: [PATCH 34/55] EV-20 review round 3: drop the if True wrapper in SolarWriter._close_a (cosmetic, no logic change) Co-Authored-By: Claude --- goodwe_controller/app/carmode.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index eaf7593..f30d669 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -917,17 +917,17 @@ class SolarWriter(ManualWriter): return want def _close_a(self, q, clamp, n_reported): - if True: - before = self.plan._before - if q.get("failed") and not q.get("sel") and before is not None: - return before[0] if before[0] >= CH.MIN_A else CH.MIN_A - a = self.amps_out(clamp) or CH.MIN_A - tgt = self.plan.target_w - for n in (q.get("n"), n_reported): - b = amps_for(tgt, n, clamp) if n in (1, 3) else None - if b is not None: - a = min(a, max(b, CH.MIN_A)) - return a + """`_seq_want`'s value, worked out once per sequence.""" + before = self.plan._before + if q.get("failed") and not q.get("sel") and before is not None: + return before[0] if before[0] >= CH.MIN_A else CH.MIN_A + a = self.amps_out(clamp) or CH.MIN_A + tgt = self.plan.target_w + for n in (q.get("n"), n_reported): + b = amps_for(tgt, n, clamp) if n in (1, 3) else None + if b is not None: + a = min(a, max(b, CH.MIN_A)) + return a async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None: """Step 1 of the safe sequence: 0 A (kept when it already stands). -- 2.54.0 From 711c5f362736cc62d85dc380044dc74cef316da8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 14:28:21 +0100 Subject: [PATCH 35/55] EV-20 rig round 1: stuck check armed on the reading before the send; no amp ping-pong; ha_signed meter age The stuck check's baseline is the signature of the latest reading taken before the send (kept at begin_write), never one that arrived while the write waited; a refused write's first post-send sample is its baseline (EV-36). After a step down, a step back up needs UP_HYST_W past the boundary. Solar's 15 s meter-age gate applies only where the age measures arrival; on ha_signed it is the source's meter_max_age_s. Rows in test_ev20_rig.py; harness modes for the rig's interleave and an on-change meter. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/app/carmode.py | 17 +- goodwe_controller/app/chargers.py | 27 ++- goodwe_controller/app/ctl_car.py | 9 +- goodwe_controller/test_ev20_exits.py | 13 +- goodwe_controller/test_ev20_rig.py | 262 +++++++++++++++++++++++++++ goodwe_controller/tools/ev20_sun.py | 27 ++- 6 files changed, 342 insertions(+), 13 deletions(-) create mode 100644 goodwe_controller/test_ev20_rig.py diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index f30d669..760d309 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -430,6 +430,10 @@ SOLAR_WRITE_S = 30.0 # at most one current change per this ... SOLAR_STEP_A = 1.0 # ... and only on a change of this or more UP_W, UP_S = 4500.0, 180.0 # auto phases: to 3 at this for this long DOWN_W, DOWN_S = 4000.0, 300.0 # ... back to 1 under this for this long +# Rig round 1: after a step down, a step back up needs this much more than the +# amp boundary, so a spare that dithers on a boundary is one change, not 10 / +# 9 / 10 every 30 s (N5's intent). +UP_HYST_W = 100.0 ONE_PHASE_S = 10.0 # one phase drawing while 3 are allowed this long ONE_PHASE_MIN_W = 500.0 # ... with the car drawing at least this # D3: at shutdown the 0 A is tried this many times, this far apart, each @@ -522,6 +526,7 @@ class SolarPlan: self.target_w = None self._before = None # the state before a phase change self.ext_at = None # C6: Manual's latest non-zero write + self.last_dir = 0 # the latest change: +1 up, -1 down def pause(self, why="paused"): self.a = 0.0 @@ -541,6 +546,7 @@ class SolarPlan: self.why) self.n, self.switch = n, True self.a, self.set_at, self.why = float(a), now, "running" + self.last_dir = 0 self.ok_since = self.low_since = None self.up_since = self.down_since = None @@ -607,7 +613,7 @@ class SolarPlan: if hi < CH.MIN_A: self.pause() return - self.a, self.set_at = float(hi), now + self.a, self.set_at, self.last_dir = float(hi), now, -1 if auto and not self.switch: # auto phases, by dwells if self.n == 1: self.down_since = None @@ -640,7 +646,13 @@ class SolarPlan: if want is not None and want >= CH.MIN_A: self.low_since = None self.why = "running" + if want > self.a and self.last_dir < 0: + # Up again after a step down: only past the boundary plus + # `UP_HYST_W` (no ping-pong on an amp boundary). + up = amps_for(target_w - UP_HYST_W, self.n, clamp) or 0.0 + want = max(self.a, up) if abs(want - self.a) >= SOLAR_STEP_A and self._gate(now): + self.last_dir = 1 if want > self.a else -1 self.a, self.set_at = want, now return if auto and self.n == 3 and target_w >= DOWN_W and not self.switch: @@ -649,6 +661,7 @@ class SolarPlan: self.low_since = None self.why = "running" if self.a != CH.MIN_A and self._gate(now): + self.last_dir = 1 if CH.MIN_A > self.a else -1 self.a, self.set_at = CH.MIN_A, now return if self.low_since is None: @@ -658,7 +671,7 @@ class SolarPlan: self.pause() return if self.a != CH.MIN_A and self._gate(now): - self.a, self.set_at = CH.MIN_A, now + self.a, self.set_at, self.last_dir = CH.MIN_A, now, -1 class SolarWriter(ManualWriter): diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index 1ea8fb7..62a850b 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -715,6 +715,10 @@ class CarTracker: _prev: tuple | None = None # EV-04: our own writes, and the stuck-reading rule (SAFETY-37's shape) mute_until: float = 0.0 + # EV-20 rig round 1: the signature of the latest reading taken BEFORE our + # write went out, kept at `begin_write` (the arming baseline). The empty + # tuple means "no write begun", and `note_write` then uses `sig`. + pre_sig: tuple = () armed_at: float | None = None armed_sig: tuple | None = None sig: tuple | None = None @@ -782,8 +786,15 @@ class CarTracker: def begin_write(self) -> None: """EV-12: a write of ours is in flight. Its read-back can reach the tracker before `note_write` runs (the write waits for it), so the mute - is open until `end_write`.""" + is open until `end_write`. + + EV-20 (rig round 1, EV-32): the stuck check's baseline is taken HERE, + before the send. The write waits for its read-back and the cycle reads + the charger meanwhile, so by `note_write` `sig` can already be the + reading AFTER the write; armed on that, a car that then stays paused + (constant power and read-back) was called stuck 60 s later.""" self.mute_until = float("inf") + self.pre_sig = (self.sig,) def end_write(self, now: float) -> None: """EV-12: the write returned (or failed). The mute runs @@ -805,6 +816,10 @@ class CarTracker: 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 + # The baseline: the reading before the send (`begin_write`), never one + # that arrived while the write waited. + base = self.pre_sig[0] if self.pre_sig else self.sig + self.pre_sig = () try: moved = was_a is None or abs(float(to_a) - float(was_a)) \ >= STUCK_MIN_A @@ -816,13 +831,13 @@ class CarTracker: return if ok: self._pend = None - self.armed_at, self.armed_sig = now, self.sig + self.armed_at, self.armed_sig = now, base 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} + self._pend = {"t": now, "pre": pre, "sig": base, "post0": False} 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]): @@ -844,6 +859,12 @@ class CarTracker: return if t <= p["t"]: p["pre"] = (p["pre"] + [vals])[-8:] # taken before the send + elif not p.get("post0", True): + # EV-36 (SPIKE-05 C4): the first sample after the send may carry a + # value newer than the cycle's last read but frozen since; it is + # the baseline, and life must show in a sample after it. + p["post0"] = True + p["pre"] = (p["pre"] + [vals])[-8:] elif t <= p["t"] + TOOK_S and _alive(vals, p["pre"]): self._pend = None # life: nothing to arm return diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 7c0fdc4..3fa122c 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -423,8 +423,15 @@ class CarMixin: if self.p1_enabled: # The meter's own bound (`meter_max_age_s`) may be longer than # `stale_input_s`; a car write never comes from an older reading. + # Rig round 1: only where the age measures ARRIVAL. On `ha_signed` + # it measures the time since the value CHANGED (p1.py, Home + # Assistant emits changes only), so a healthy meter under a flat + # load would read as stale and pause the car; there the source's + # own `meter_max_age_s` (the cycle's `inputs_ok`) is the bound. age = self.p1.age_s() - if age is None or age > stale: + src = str(self.o.get("meter_source") or "") + bound = None if src == "ha_signed" else stale + if age is None or (bound is not None and age > bound): return None r = self.car.reading if r is None or not r.available or not self.car.fresh(mono): diff --git a/goodwe_controller/test_ev20_exits.py b/goodwe_controller/test_ev20_exits.py index 0f0c2ed..5eb8d40 100644 --- a/goodwe_controller/test_ev20_exits.py +++ b/goodwe_controller/test_ev20_exits.py @@ -343,19 +343,24 @@ for kind in ("none", "nan", "unavailable"): and [a for _, a, _ in w4 if _ < 700] == [10.0, 0.0] and 599 <= [t for t, a, _ in w4 if a == 0.0][0] <= 602) -# T31: the meter goes silent at 10 A. +# T31: the meter goes silent at 10 A. Rig round 1: `stale_input_s` holds where +# the sample age measures arrival (here the HomeWizard local source); on +# `ha_signed` the age is the time since the value changed, and the source's own +# meter_max_age_s is the bound (test_ev20_rig.py). +ARRIVAL = {"meter_source": "homewizard_local", "p1_host": "192.0.2.10"} for race in (False, True): tag = "race" if race else "step" d = 1 if race else 0 r31 = std(900, events={300: lambda p, c: setattr(p, "meter_on", False)}, - race=race) + race=race, opts=ARRIVAL) w31 = cur_writes(r31) check(f"T31 (a) [{tag}]: silent from 300 s (the last sample 299.7 s): " f"no write until 15 + 300 s, then 0 A once (+2 s) ({w31})", [a for _, a, _ in w31] == [10.0, 0.0] and 614 <= w31[-1][0] <= 617 + d) r31b = std(900, events={300: lambda p, c: setattr(p, "meter_on", False), - 500: lambda p, c: setattr(p, "meter_on", True)}) + 500: lambda p, c: setattr(p, "meter_on", True)}, + opts=ARRIVAL) check(f"T31 (b): back at 200 s: no 0 A ({cur_writes(r31b)})", [a for _, a, _ in cur_writes(r31b)] == [10.0]) @@ -511,7 +516,7 @@ PATHS = { {}), "charger error": (300, {300: _err}, {}), "unplug": (300, {300: lambda p, c: p.ch.unplug()}, {}), - "meter stale": (514, {200: _meter_off}, {}), + "meter stale": (514, {200: _meter_off}, ARRIVAL), "charger back": (420, {240: lambda p, c: p.ch.go_unavailable(True), 300: lambda p, c: p.ch.set_current(16), 420: lambda p, c: p.ch.go_unavailable(False)}, {}), diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py new file mode 100644 index 0000000..ca9a9df --- /dev/null +++ b/goodwe_controller/test_ev20_rig.py @@ -0,0 +1,262 @@ +"""EV-20 rig round 1 (rig FAIL on cc8c0dc), with EV-32 and EV-36. +`python3 -B test_ev20_rig.py` + +1. The stuck check's arming race (Critical, EV-32): a write waits for its + read-back while the next cycle reads the charger; the check must be armed on + the reading taken before the send, so a car that then stays paused is not + "stuck". Tracker rows and the real Controller in the rig's interleave + (`beside`), the rig's repro scenario among them. +2. EV-36 (SPIKE-05 C4): a frozen value newer than the last read is not life. +3. No 1 A ping-pong on an amp boundary (Major). +4. The 6 A hold lasts its full `ev_pause_min` from the spare's drop, 1 and 3 + phases (Major); a meter as Home Assistant publishes it (`ha_signed`, on a + change only) does not pause the car while it is healthy (Minors). +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import math +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from datetime import datetime, timezone # noqa: E402 + +from app import chargers as CH # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from ev20_kit import (check, const, cur_writes, nevers, report, # noqa: E402 + step_fn) +from named_absence import nth, present # noqa: E402 + +UTC = datetime(2026, 11, 23, 12, 0, tzinfo=timezone.utc) +DAY = "2026-11-23" +TS = 1000.0 + + +def rd(power=2300.0, allowed=10.0, e=4004.85, state="C"): + return CH.ChargerReading( + available=True, state=state, connected=True, + charging=state in ("C", "D"), power_w=power, energy_kwh=e, + current_a=(power / 230.0, 0.0, 0.0), setpoint_a=allowed, + allowed_a=allowed, phases_allowed=1) + + +# =========================================================================== # +print("1. THE STUCK CHECK'S ARMING (rig Critical, EV-32)") +# =========================================================================== # +# The race as the rig had it: begin_write (the send), the cycle's read lands +# while the write waits (it already shows the new 0 A and the paused car), +# then note_write; the car stays paused (constant 0 W, 0 A) for two minutes. +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(e=4004.85 + i / 1000.0), TS + i, UTC, DAY) +tr.begin_write() +tr.observe(rd(power=0.0, allowed=0.0, state="B"), TS + 1, UTC, DAY) +tr.end_write(TS + 2) +tr.note_write(TS, 10.0, 0.0, True) +stuck_at = None +for i in range(2, 130): + tr.observe(rd(power=0.0, allowed=0.0, state="B"), TS + i, UTC, DAY) + if stuck_at is None and tr.stuck(TS + i): + stuck_at = i +check(f"race (EV-32): an accepted 10 -> 0 A write whose post-write reading " + f"arrived while it waited; the car then stays paused at constant " + f"values: never 'stuck' (stuck at +{stuck_at})", stuck_at is None) +# The same with an accepted non-zero write (EV-32's "after an accepted current +# write"): a car that then draws steadily is not stuck either. +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(power=0.0, allowed=0.0, state="B"), TS + i, UTC, DAY) +tr.begin_write() +tr.observe(rd(power=1840.0, allowed=8.0), TS + 1, UTC, DAY) +tr.end_write(TS + 2) +tr.note_write(TS, 0.0, 8.0, True) +st2 = [i for i in range(2, 130) + if (tr.observe(rd(power=1840.0, allowed=8.0), TS + i, UTC, DAY) + or tr.stuck(TS + i))] +check(f"race (EV-32): an accepted 0 -> 8 A write, the car draws a steady " + f"1840 W: never 'stuck' ({st2[:1]})", not st2) +# A reading that really froze before the send still is stuck at +60 s (the +# EV-04 rule kept): the write was accepted, but every reading after it is the +# one from before the send. +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(), TS + i, UTC, DAY) +tr.begin_write() +tr.end_write(TS + 1) +tr.note_write(TS, 10.0, 0.0, True) +st3 = None +for i in range(1, 80): + tr.observe(rd(), TS + i, UTC, DAY) + if st3 is None and tr.stuck(TS + i): + st3 = i +check(f"kept: readings frozen at the value from before the send are stuck at " + f"+60 s (at +{st3})", st3 == 60) + +# =========================================================================== # +print("\n2. EV-36: A FROZEN VALUE NEWER THAN THE LAST READ IS NOT LIFE") +# =========================================================================== # +# The cycle last read energy 4004.85 kWh at TS-1. The charger froze a moment +# later at 4004.87 (a newer value); the refused write's polls and every later +# read show that same frozen value. +tr = CH.CarTracker() +for i in range(-5, 0): + tr.observe(rd(e=4004.85), TS + i, UTC, DAY) +tr.begin_write() +polls = [(TS + s, rd(e=4004.87)) for s in range(1, 11)] +tr.end_write(TS + 10) +tr.note_write(TS, 16.0, 10.0, False, polls) +st36 = None +for i in range(11, 130): + tr.observe(rd(e=4004.87), TS + i, UTC, DAY) + if st36 is None and tr.stuck(TS + i): + st36 = i +check(f"EV-36: a refused write; the first sample after the send carries a " + f"newer value that then never moves: no life, so it arms at the send " + f"and is stuck at +60 s (at +{st36})", st36 == 60) +tr = CH.CarTracker() +for i in range(-5, 0): + tr.observe(rd(e=4004.85), TS + i, UTC, DAY) +tr.begin_write() +polls = [(TS + s, rd(e=4004.85 + s / 1000.0)) for s in range(1, 11)] +tr.end_write(TS + 10) +tr.note_write(TS, 16.0, 10.0, False, polls) +for i in range(11, 130): + tr.observe(rd(e=4004.86 + i / 1000.0), TS + i, UTC, DAY) +check("EV-36 guard: a refused write on a charger whose energy keeps moving " + "is not stuck (life in the second sample and after)", + tr.armed_at is None and not tr.stuck(TS + 129)) + +# =========================================================================== # +print("\n3. THE REAL CONTROLLER IN THE RIG'S INTERLEAVE (beside)") +# =========================================================================== # + + +def rig_run(**kw): + sim = kw.pop("sim", None) or SimCharger(setpoint_a=kw.pop("setpoint", 0)) + sim.lag_s = 1.0 + return S.drive(kw.pop("house"), kw.pop("sun"), beside=True, sim=sim, + **kw) + + +# The rig's repro, EV20-solar-steady-no-false-stuck: the charger's own 10 A, +# the car charging; Solar, Car first, sun 7.9 kW, house 0.9 kW (mock-up +# scenario 2): 0 A first (D2), then the start rule, then charging to the end. +for mc in (False, True): + tag = "meter on change" if mc else "meter every second" + r = rig_run(house=const(900.0), sun=const(7900.0), dur=1800, first="car", + socs={"a": 71.0, "b": 100.0}, + sim=SimCharger(setpoint_a=10), meter_change=mc) + w = cur_writes(r) + stuck = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] + check(f"scenario EV20-solar-steady-no-false-stuck [{tag}]: 0 A first, the " + f"start within 125 s, charging to the end, never stuck ({w[:4]}, " + f"stuck {stuck[:1]})", + present(nth(w, 0)) and nth(w, 0)[1] == 0.0 + and present(nth(w, 1)) and nth(w, 1)[1] > 0.0 + and nth(w, 1)[0] - nth(w, 0)[0] <= 125 and not stuck + and r["sim"].power_w > 3000.0) + nevers(r, f"scenario EV20-solar-steady-no-false-stuck [{tag}]") +# E2 of the scenario: a cloud pause (0 A), then the sun back: the car +# restarts 120 s after the sun returns; no stuck verdict holds it at 0 A. +r = rig_run(house=const(500.0), sun=step_fn((400, 900.0), (1000, 2900.0), + base=2900.0), + dur=1400, first="car", socs={"a": 100.0, "b": 100.0}) +w = cur_writes(r) +stuck = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] +late = [(t, a) for t, a, _ in w if t >= 1000] +check(f"scenario E2: after the cloud pause the car restarts 120 s after the " + f"sun returns, never held by a stuck verdict ({w}, stuck {stuck[:1]})", + not stuck and present(nth(late, 0)) and nth(late, 0)[1] > 0.0 + and 1119 <= nth(late, 0)[0] <= 1125) + +# =========================================================================== # +print("\n4. NO PING-PONG ON AN AMP BOUNDARY (rig Major)") +# =========================================================================== # +for ph, sun_w, amps in ((1, 2900.0, 10.0), (3, 600.0 + 6900.0, 10.0)): + def dither(t, base=sun_w): + return base + (6.0 if int(t // 17) % 2 else -6.0) + opts = {"ev_phases": "1" if ph == 1 else "3"} + r = S.drive(const(500.0), dither, dur=1500, first="car", + socs={"a": 100.0, "b": 100.0}, opts=opts, phases=ph) + w = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0] + changes = len(w) - 1 + check(f"[{ph} phase] the spare dithers +-6 W around the {amps:.0f} A " + f"boundary for 1500 s: at most one change after the start " + f"({changes} changes: {w[:6]})", present(nth(w, 0)) and changes <= 1) + nevers(r, f"ping-pong [{ph} phase]") +# A real rise after a step down still raises the current. +r = S.drive(const(500.0), step_fn((300, 2890.0), (600, 3200.0), base=2900.0), + dur=900, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_phases": "1"}) +w = [(t, a) for t, a, _ in cur_writes(r)] +check(f"guard: 10 A, down to 9 A on a 10 W dip, then a real rise to 11 A " + f"worth: 11 A is written ({w})", + [a for _, a in w] == [10.0, 9.0, 11.0]) + +# =========================================================================== # +print("\n5. THE HOLD LASTS ITS TIME; A HEALTHY ha_signed METER (rig Major, Minors)") +# =========================================================================== # +for mode, kw in (("every second", {}), ("rig interleave, meter on change", + {"beside": True, + "meter_change": True})): + sim = SimCharger(setpoint_a=0) + if kw.get("beside"): + sim.lag_s = 1.0 + # 1 phase: a 290 s cloud never pauses; a 400 s one pauses at 300 s. + r = S.drive(const(500.0), lambda t: 900.0 if 400 <= t < 690 + or 1200 <= t < 1600 else 2900.0, dur=1800, first="car", + socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, + sim=sim, **kw) + w = [(t, a) for t, a, _ in cur_writes(r)] + zeros = [t for t, a in w if a == 0.0] + check(f"[1 phase, {mode}] a 290 s cloud: the 6 A hold, no pause; a 400 s " + f"cloud: 0 A at 300 s from the drop, +2 ({w})", + not [t for t in zeros if 400 <= t < 700] + and [t for t in zeros if 1200 <= t < 1600][:1] + and 1499 <= nth([t for t in zeros if 1200 <= t < 1600], 0) <= 1502) + nevers(r, f"hold [1 phase, {mode}]") + sim = SimCharger(setpoint_a=0) + if kw.get("beside"): + sim.lag_s = 1.0 + # 3 phases: 7 A, then the spare under 6 A worth from 600 s: 6 A, 0 A at + # 900 s (+2), not before. + r = S.drive(const(500.0), step_fn((600, 600.0 + 2500.0), + base=600.0 + 6000.0), + dur=1100, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_phases": "3"}, phases=3, sim=sim, **kw) + w = [(t, a) for t, a, _ in cur_writes(r)] + zeros = [t for t, a in w if a == 0.0 and t > 200] + check(f"[3 phases, {mode}] the hold from 600 s: 6 A, then 0 A at 900 s " + f"(+2), not before ({w})", + present(nth(zeros, 0)) and 899 <= nth(zeros, 0) <= 902 + and 6.0 in [a for t, a in w if 600 <= t < 900]) + nevers(r, f"hold [3 phases, {mode}]") + +# A healthy meter on ha_signed: Home Assistant publishes it only on a change, +# so at a flat load the value may stand 20-40 s; the car is not paused. +r = S.drive(const(500.0), lambda t: 2900.0 + (15.0 if int(t // 40) % 2 + else 0.0), + dur=1200, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_phases": "1"}, meter_change=True) +w = cur_writes(r) +unk = [x["t"] for x in r["trace"] if x["spare"] is None and x["t"] > 5] +check(f"ha_signed, a healthy meter whose value stands 40 s at a time: the " + f"spare stays known and the car is never paused ({w}, unknown " + f"{unk[:3]})", not [x for x in w if x[1] == 0.0 and x[0] > 5] + and not unk) +# A silent meter on ha_signed: unknown from the source's own meter_max_age_s +# (30 s), then 0 A after ev_pause_min (300 s). +r = S.drive(const(500.0), const(2900.0), dur=900, first="car", + socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, + events={300: lambda p, c: setattr(p, "meter_on", False)}) +w = cur_writes(r) +z = [t for t, a, _ in w if a == 0.0] +check(f"ha_signed, the meter silent from 300 s: 0 A at 30 + 300 s (+2), " + f"never from a stale value ({w})", + present(nth(z, 0)) and 629 <= nth(z, 0) <= 633 + and [a for t, a, _ in w if 300 <= t < 629] == []) + +report() diff --git a/goodwe_controller/tools/ev20_sun.py b/goodwe_controller/tools/ev20_sun.py index f64623d..2d2c0bf 100644 --- a/goodwe_controller/tools/ev20_sun.py +++ b/goodwe_controller/tools/ev20_sun.py @@ -141,13 +141,18 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar", first="batteries", events=None, sim=None, store=None, race=False, on_cycle=None, car_phases=3, t0=0.0, caps=None, finale=None, - rows=False, plant_cls=None): + rows=False, plant_cls=None, beside=False, meter_change=False): """Run it. Returns a dict: plant, controller, charger, notifications with their second, and a per-second trace. `caps` ({unit: kWh}) lets each battery's level move with what it charges or gives; without it the levels stand still. `finale(plant, c)` (a coroutine) runs after the last cycle, on the model clock (a shutdown, for instance); `rows=True` keeps - the ids of the amber and red rows of every cycle in the trace.""" + the ids of the amber and red rows of every cycle in the trace. + `beside=True` plays the production interleave the rig showed (EV-20 rig + round 1): a write that waits for its read-back is still waiting when the + next cycle reads the charger; it resumes after that read. + `meter_change=True` publishes the meter as Home Assistant does on + `ha_signed`: only when the whole-watt value changes.""" ratings = ratings or {"a": 5000.0, "b": 4600.0} socs = socs or {u: 50.0 for u in ratings} sim = sim or SimCharger(setpoint_a=setpoint) @@ -205,6 +210,19 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, plant.t = clock[0] c.charger._sleep = sleep c.charger._clock = lambda: clock[0] + if beside: + gate = asyncio.Event() + + async def bsleep(_s): + gate.clear() + await gate.wait() + + async def settle(): + gate.set() + for _ in range(8): + await asyncio.sleep(0) + c.charger._sleep = bsleep + c.car_settle = settle real_dt = main_files.live.datetime class _DT(real_dt): @@ -224,7 +242,10 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, await r sim.tick(1.0) ts = t - SAMPLE_LEAD_S - if plant.meter_on and not plant.ha_down: + if plant.meter_on and not plant.ha_down and not ( + meter_change + and round(plant.grid(ts)) == round(plant.meter) + and t > t0): plant.meter = plant.grid(ts) imp, exp = split_signed(plant.meter) c.p1.submit(make_sample( -- 2.54.0 From 3a170127a32050a543a0e72d78f41421175b972d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 15:16:41 +0100 Subject: [PATCH 36/55] EV-20 rig round 1: stuck check clears on the car's answer or a paused car; EV-36 first-sample rule An accepted write keeps the car's power from the reading before the send (begin_write); a later reading whose power differs from it, or that shows a paused car (not charging, under PAUSED_W), clears the armed check. A refused write's first sample after the send is not life by itself (EV-36). EV-13 T7/T8 and the refusal-window row get two-change variants so mutant M3 stays killed. DECISIONS records the arming rule. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 29 +++++++++++ goodwe_controller/app/chargers.py | 52 ++++++++++++------- goodwe_controller/test_ev13.py | 18 ++++++- goodwe_controller/test_ev20_rig.py | 35 ++++++++----- 4 files changed, 102 insertions(+), 32 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 4711d22..2a13051 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -108,3 +108,32 @@ one small set of facts and derives every path from them: bookkeeping (a 0 A not read back counts) or by the read-back showing a value it sent, confirmed, tried or saw at a refused try. - **C3** is T43-T45; **C7** is EV-22's. + +## Rig round 1 (rig FAIL on cc8c0dc), with EV-32 and EV-36 + +- **The stuck-reading check (chargers.py `CarTracker`), for every writer.** + - Arms: an accepted write that moved the setpoint by `STUCK_MIN_A` arms at + its send (`armed_at`), on the signature (power, read-back) the tracker + holds at `note_write`, as before (EV-04). It also keeps + `armed_pre_w`: the car's power in the latest reading taken BEFORE the + send (`begin_write`). + - Clears: any later reading whose signature differs from the armed one; or + (new) whose power differs from `armed_pre_w` (the car answered the write, + even when that reading came while the write waited, which was the rig's + race); or (new) that shows a paused car (not charging, under + `PAUSED_W` 100 W), where constant values are expected. + - Stuck: armed and not cleared for `STUCK_S` (60 s). + - A refused write (EV-13) arms only with no life in `TOOK_S` after the + send. EV-36: the first sample after the send is not life by itself (it may + be a value newer than the cycle's last read and frozen since); life is a + later sample that differs from the samples before the send AND from that + first one. +- **No amp ping-pong:** after a step down, a step back up needs + `UP_HYST_W` (100 W) past the amp boundary. +- **The meter's age:** Solar's own `stale_input_s` gate applies where the age + measures arrival (HomeWizard local, MQTT, DSMR). On `ha_signed` the age is + the time since the value changed (Home Assistant publishes changes only), so + a healthy meter at a flat load would read as stale; there the source's own + `meter_max_age_s` is the bound (a silent meter: 0 A at + `meter_max_age_s` + `ev_pause_min`). + diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index 62a850b..03c2c49 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -76,6 +76,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 +PAUSED_W = 100.0 # EV-20: a car not charging, under this, is paused 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 @@ -716,9 +717,10 @@ class CarTracker: # EV-04: our own writes, and the stuck-reading rule (SAFETY-37's shape) mute_until: float = 0.0 # EV-20 rig round 1: the signature of the latest reading taken BEFORE our - # write went out, kept at `begin_write` (the arming baseline). The empty - # tuple means "no write begun", and `note_write` then uses `sig`. + # write went out, kept at `begin_write`; `armed_pre_w` is its power, kept + # while the check is armed. Empty / None: no write begun or not armed. pre_sig: tuple = () + armed_pre_w: float | None = None armed_at: float | None = None armed_sig: tuple | None = None sig: tuple | None = None @@ -788,11 +790,10 @@ class CarTracker: tracker before `note_write` runs (the write waits for it), so the mute is open until `end_write`. - EV-20 (rig round 1, EV-32): the stuck check's baseline is taken HERE, - before the send. The write waits for its read-back and the cycle reads - the charger meanwhile, so by `note_write` `sig` can already be the - reading AFTER the write; armed on that, a car that then stays paused - (constant power and read-back) was called stuck 60 s later.""" + EV-20 (rig round 1, EV-32): the power of the reading before the send is + kept HERE. The write waits for its read-back and the cycle reads the + charger meanwhile, so the reading the check is armed on can already + show the car's answer; the power before the send tells it.""" self.mute_until = float("inf") self.pre_sig = (self.sig,) @@ -816,9 +817,7 @@ class CarTracker: 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 - # The baseline: the reading before the send (`begin_write`), never one - # that arrived while the write waited. - base = self.pre_sig[0] if self.pre_sig else self.sig + pre = self.pre_sig[0] if self.pre_sig else None self.pre_sig = () try: moved = was_a is None or abs(float(to_a) - float(was_a)) \ @@ -831,13 +830,17 @@ class CarTracker: return if ok: self._pend = None - self.armed_at, self.armed_sig = now, base + self.armed_at, self.armed_sig = now, self.sig + # EV-20 rig round 1: the car's power before the send. A power + # that has moved from it is the car's answer (alive), however + # early that reading came (it may be the one `sig` holds). + self.armed_pre_w = None if pre is None else pre[0] 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": base, "post0": False} + self._pend = {"t": now, "pre": pre, "sig": self.sig, "first": None} 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]): @@ -859,13 +862,13 @@ class CarTracker: return if t <= p["t"]: p["pre"] = (p["pre"] + [vals])[-8:] # taken before the send - elif not p.get("post0", True): + elif p.get("first") is None: # EV-36 (SPIKE-05 C4): the first sample after the send may carry a # value newer than the cycle's last read but frozen since; it is - # the baseline, and life must show in a sample after it. - p["post0"] = True - p["pre"] = (p["pre"] + [vals])[-8:] - elif t <= p["t"] + TOOK_S and _alive(vals, p["pre"]): + # not life by itself, and life must differ from it as well. + p["first"] = vals + elif t <= p["t"] + TOOK_S and _alive(vals, p["pre"]) \ + and _alive(vals, [p["first"]]): self._pend = None # life: nothing to arm return if max(t, arrival) > p["t"] + TOOK_S: @@ -883,12 +886,23 @@ class CarTracker: 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"] + self.armed_pre_w = None # a refusal: no answer to look for def _sig(self, r, now: float) -> None: sig = (r.power_w, r.allowed_a) - if self.armed_at is not None and self.armed_sig is not None \ - and sig != self.armed_sig: + # EV-20 rig round 1: after an accepted write the car's power moved + # from its value before the send (the car answered), or the car is + # paused (not charging, under QUIET_W): constant values are expected + # then, so neither is a stuck reading. + answered = (self.armed_pre_w is not None and r.power_w is not None + and r.power_w != self.armed_pre_w) + paused = (self.armed_pre_w is not None and r.charging is False + and r.power_w is not None and r.power_w < PAUSED_W) + if self.armed_at is not None and ( + answered or paused or (self.armed_sig is not None + and sig != self.armed_sig)): self.armed_at = self.armed_sig = None # it moved: alive + self.armed_pre_w = None self.stuck_now = False elif self.armed_at is not None and self.armed_sig is None: self.armed_sig = sig diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index 95b69c0..932894c 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -205,6 +205,19 @@ for what, e in (("the same values", 1.000), ("changed values", 1.010)): tl = [(TS + s, rd(e=e, taken=TS - 1.0)) for s in range(1, 131)] armed(f"T7 stale sample ({what}, taken-at TS-1 again and again)", tl) +# EV-20 rig round 1 (EV-36): one changed sample after the send is not life by +# itself, so these variants change twice. Every sample is still TAKEN before +# the send (TS-1), so the correct tracker sees no life and arms; one that dates +# samples by arrival (mutant M3) sees life. +tl2 = [(TS + s, rd(e=1.010 if s < 3 else 1.020, taken=TS - 1.0)) + for s in range(1, 131)] +armed("T7 stale samples, two changed values (taken-at TS-1 again and again)", + tl2) +late2 = [(TS + s, rd(e=1.010 if s < 3 else 1.020, taken=TS - 1.0) + if s <= 3 else rd(e=1.020)) for s in range(2, 131)] +armed("T8 samples taken at TS-1 (+10, then +20 Wh) arrive at TS+2 and TS+3, " + "nothing changes after them", late2, pre_end=-3) + # T8: the late pre-write sample (EV-12 ordering): taken TS-1, arrives TS+2 late = [(TS + s, rd(e=1.010, taken=TS - 1.0) if s == 2 else rd(e=1.010)) for s in range(2, 131)] @@ -265,8 +278,11 @@ tr = CH.CarTracker() for i in range(-5, 1): tr.observe(rd(), TS + i, UTC, DAY) tr.note_write(TS, 16, 10, False) +# EV-36 (SPIKE-05 C4): life shows after the first sample past the send (one +# changed sample that then stands may be a frozen newer value), so the energy +# moves twice here. for i in range(1, 5): - tr.observe(rd(e=1.010), TS + i, UTC, DAY) + tr.observe(rd(e=1.010 if i < 3 else 1.020), TS + i, UTC, DAY) tr.note_write(TS + 20, 10, 8, False) check("a refusal that showed life leaves no window; a later refusal gets " "its own", pend(tr) is not None and pend(tr)["t"] == TS + 20 diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py index ca9a9df..4eb0c2e 100644 --- a/goodwe_controller/test_ev20_rig.py +++ b/goodwe_controller/test_ev20_rig.py @@ -134,6 +134,12 @@ print("\n3. THE REAL CONTROLLER IN THE RIG'S INTERLEAVE (beside)") # =========================================================================== # +def jit(f): + """A few watts of noise on a plant figure, as the rig's plant had, so a + meter published on change does change (every 7 s here).""" + return lambda t: f(t) + (2.0 if int(t // 7) % 2 else -2.0) + + def rig_run(**kw): sim = kw.pop("sim", None) or SimCharger(setpoint_a=kw.pop("setpoint", 0)) sim.lag_s = 1.0 @@ -146,7 +152,8 @@ def rig_run(**kw): # scenario 2): 0 A first (D2), then the start rule, then charging to the end. for mc in (False, True): tag = "meter on change" if mc else "meter every second" - r = rig_run(house=const(900.0), sun=const(7900.0), dur=1800, first="car", + r = rig_run(house=jit(const(900.0)), sun=const(7900.0), dur=1800, + first="car", socs={"a": 71.0, "b": 100.0}, sim=SimCharger(setpoint_a=10), meter_change=mc) w = cur_writes(r) @@ -188,11 +195,11 @@ for ph, sun_w, amps in ((1, 2900.0, 10.0), (3, 600.0 + 6900.0, 10.0)): f"({changes} changes: {w[:6]})", present(nth(w, 0)) and changes <= 1) nevers(r, f"ping-pong [{ph} phase]") # A real rise after a step down still raises the current. -r = S.drive(const(500.0), step_fn((300, 2890.0), (600, 3200.0), base=2900.0), +r = S.drive(const(500.0), step_fn((300, 2890.0), (600, 3300.0), base=2900.0), dur=900, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}) w = [(t, a) for t, a, _ in cur_writes(r)] -check(f"guard: 10 A, down to 9 A on a 10 W dip, then a real rise to 11 A " +check(f"guard: 10 A, down to 9 A on a 10 W dip, then a real rise to 11.3 A " f"worth: 11 A is written ({w})", [a for _, a in w] == [10.0, 9.0, 11.0]) @@ -206,7 +213,7 @@ for mode, kw in (("every second", {}), ("rig interleave, meter on change", if kw.get("beside"): sim.lag_s = 1.0 # 1 phase: a 290 s cloud never pauses; a 400 s one pauses at 300 s. - r = S.drive(const(500.0), lambda t: 900.0 if 400 <= t < 690 + r = S.drive(jit(const(500.0)), lambda t: 900.0 if 400 <= t < 690 or 1200 <= t < 1600 else 2900.0, dur=1800, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, sim=sim, **kw) @@ -223,8 +230,8 @@ for mode, kw in (("every second", {}), ("rig interleave, meter on change", sim.lag_s = 1.0 # 3 phases: 7 A, then the spare under 6 A worth from 600 s: 6 A, 0 A at # 900 s (+2), not before. - r = S.drive(const(500.0), step_fn((600, 600.0 + 2500.0), - base=600.0 + 6000.0), + r = S.drive(jit(const(500.0)), step_fn((600, 600.0 + 2500.0), + base=600.0 + 6000.0), dur=1100, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "3"}, phases=3, sim=sim, **kw) w = [(t, a) for t, a, _ in cur_writes(r)] @@ -236,17 +243,21 @@ for mode, kw in (("every second", {}), ("rig interleave, meter on change", nevers(r, f"hold [3 phases, {mode}]") # A healthy meter on ha_signed: Home Assistant publishes it only on a change, -# so at a flat load the value may stand 20-40 s; the car is not paused. -r = S.drive(const(500.0), lambda t: 2900.0 + (15.0 if int(t // 40) % 2 +# so at a flat load the value may stand longer than stale_input_s (15 s); here +# 25 s at a time, under the source's meter_max_age_s (30 s). The spare stays +# known and the car is not paused. +r = S.drive(const(500.0), lambda t: 2900.0 + (15.0 if int(t // 25) % 2 else 0.0), dur=1200, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, meter_change=True) w = cur_writes(r) unk = [x["t"] for x in r["trace"] if x["spare"] is None and x["t"] > 5] -check(f"ha_signed, a healthy meter whose value stands 40 s at a time: the " - f"spare stays known and the car is never paused ({w}, unknown " - f"{unk[:3]})", not [x for x in w if x[1] == 0.0 and x[0] > 5] - and not unk) +check(f"ha_signed, a healthy meter whose value stands 25 s at a time: the " + f"spare stays known, the car starts by the start rule and is never " + f"paused ({w}, unknown {unk[:3]})", + not [x for x in w if x[1] == 0.0 and x[0] > 5] and not unk + and present(nth(w, 0)) and nth(w, 0)[1] > 0.0 + and nth(w, 0)[0] <= 125) # A silent meter on ha_signed: unknown from the source's own meter_max_age_s # (30 s), then 0 A after ev_pause_min (300 s). r = S.drive(const(500.0), const(2900.0), dur=900, first="car", -- 2.54.0 From 82dc77df6279f908865e9e23d522268670a79027 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:03:18 +0100 Subject: [PATCH 37/55] EV-20 SPIKE-06 round: arm the stuck check on the pre-send reading; Solar restarts after its own 0 A under a stuck verdict SPIKE-06 option 2 (PM decision). The stuck check's baseline is the reading before the send, for accepted and refused writes; it clears on any change from it (3a17012's power rules removed), so the race cannot arm it (C10, C11, C13). Frozen power under an accepted write is left to the energy meter and the read-back cap (EV-13 T14/T17/T18 changed). Once Solar's own 0 A stands, a stuck verdict no longer blocks the start rule (C12), at most MAX_TRIES starts per verdict, then CHARGER_REFUSED until Solar is pressed. Rows in test_ev20_rig.py section 6. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 34 ++-- goodwe_controller/app/carmode.py | 22 +++ goodwe_controller/app/chargers.py | 42 ++--- goodwe_controller/test_ev13.py | 102 +++++++----- goodwe_controller/test_ev20_rig.py | 156 +++++++++++++++++- 5 files changed, 271 insertions(+), 85 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 2a13051..8518943 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -111,23 +111,25 @@ one small set of facts and derives every path from them: ## Rig round 1 (rig FAIL on cc8c0dc), with EV-32 and EV-36 -- **The stuck-reading check (chargers.py `CarTracker`), for every writer.** - - Arms: an accepted write that moved the setpoint by `STUCK_MIN_A` arms at - its send (`armed_at`), on the signature (power, read-back) the tracker - holds at `note_write`, as before (EV-04). It also keeps - `armed_pre_w`: the car's power in the latest reading taken BEFORE the - send (`begin_write`). - - Clears: any later reading whose signature differs from the armed one; or - (new) whose power differs from `armed_pre_w` (the car answered the write, - even when that reading came while the write waited, which was the rig's - race); or (new) that shows a paused car (not charging, under - `PAUSED_W` 100 W), where constant values are expected. +- **The stuck-reading check (chargers.py `CarTracker`), for every writer** + (SPIKE-06 option 2, PM decision; replaces 3a17012's power rules). + - Baseline: the signature (power, read-back) of the latest reading taken + BEFORE the send, kept at `begin_write`; never a reading that arrived + while the write waited (the rig's race, C10/C11, C13). + - Arms: a write that moved the setpoint by `STUCK_MIN_A`. Accepted: at its + send, on the baseline. Refused (EV-13): only with no life in `TOOK_S`, + dated the send, on the baseline. EV-36: the first sample after the send + is not life by itself; life differs from the samples before the send + AND from that first one. + - Clears: any reading whose signature differs from the baseline. - Stuck: armed and not cleared for `STUCK_S` (60 s). - - A refused write (EV-13) arms only with no life in `TOOK_S` after the - send. EV-36: the first sample after the send is not life by itself (it may - be a value newer than the cycle's last read and frozen since); life is a - later sample that differs from the samples before the send AND from that - first one. + - A frozen POWER under an accepted write (the read-back moves) is no longer + judged here: the energy meter (EV-18 `contradicted`) and the read-back + cap on the trusted figure judge it. +- **Solar after a stuck verdict (C12):** once Solar's own 0 A stands + (written and taken), a stuck verdict no longer holds the car at 0 A; the + start rule runs. Its write moves the reading (the verdict clears) or is + refused (EV-04's retries, then CHARGER_REFUSED). - **No amp ping-pong:** after a step down, a step back up needs `UP_HYST_W` (100 W) past the amp boundary. - **The meter's age:** Solar's own `stale_input_s` gate applies where the age diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 760d309..2996fca 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -716,6 +716,7 @@ class SolarWriter(ManualWriter): self.start_owed = False # C1: a start in Off with a 0 A pending self.other_at = None # C6: Manual's latest non-zero write self.on_owed = None # C1: told when an own 0 A is out / back + self.stuck_starts = 0 # SPIKE-06 C12: starts under one stuck verdict def owe_start(self) -> None: """C1: the add-on starts in Off while an exit 0 A of its own was still @@ -757,6 +758,7 @@ class SolarWriter(ManualWriter): held = self.hold or self.mismatch_since is not None super().user_changed() self.gave_up, self.fails, self.fail_at = False, 0, None + self.stuck_starts = 0 if held: self.last_a = None self.sent_a, self.taken = None, True @@ -768,6 +770,8 @@ class SolarWriter(ManualWriter): read-back is never trusted (`live`).""" self.sent_a, self.taken = float(a), False zero = float(a) <= TOL_A + if not zero and tracker is not None and tracker.stuck(now): + self.stuck_starts += 1 # C12: a start under a stuck verdict if zero: self.zero_at = self.zero_sent_at = now self._owed(True) # C1: kept with the mode until back @@ -1036,6 +1040,24 @@ class SolarWriter(ManualWriter): self.would = None fault = ("error" if (r.error or r.state in ("E", "F")) else "stuck" if stuck else None) + if not stuck: + if self.stuck_starts >= MAX_TRIES and self.gave_up: + self.gave_up = False # the reading moved: start afresh + self.stuck_starts = 0 + if fault == "stuck" and self.taken and self.sent_a is not None \ + and self.sent_a <= TOL_A: + # SPIKE-06 C12 (option 2): Solar's own 0 A stands, so a stuck + # verdict no longer holds the car at 0 A; the start rule runs. Its + # write moves the reading (the verdict clears) or is not taken: + # then the 0 A again, and after MAX_TRIES such starts under one + # verdict, CHARGER_REFUSED and the 0 A stands (EV-04's rule). + if self.stuck_starts < MAX_TRIES: + fault = None + elif not self.gave_up: + self.gave_up = True + _LOG.warning("The charger did not take the current, so the " + "add-on stops asking until you press Solar: " + "CHARGER_REFUSED.") if fault is not None: # 0 A while owed, then no write until it clears; then the start # rule. A stuck reading cannot confirm the 0 A. diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index 03c2c49..a2082b0 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -76,7 +76,6 @@ 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 -PAUSED_W = 100.0 # EV-20: a car not charging, under this, is paused 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 @@ -717,10 +716,9 @@ class CarTracker: # EV-04: our own writes, and the stuck-reading rule (SAFETY-37's shape) mute_until: float = 0.0 # EV-20 rig round 1: the signature of the latest reading taken BEFORE our - # write went out, kept at `begin_write`; `armed_pre_w` is its power, kept - # while the check is armed. Empty / None: no write begun or not armed. + # write went out, kept at `begin_write` (the arming baseline). Empty: no + # write begun, and `note_write` uses `sig`. pre_sig: tuple = () - armed_pre_w: float | None = None armed_at: float | None = None armed_sig: tuple | None = None sig: tuple | None = None @@ -790,10 +788,11 @@ class CarTracker: tracker before `note_write` runs (the write waits for it), so the mute is open until `end_write`. - EV-20 (rig round 1, EV-32): the power of the reading before the send is - kept HERE. The write waits for its read-back and the cycle reads the - charger meanwhile, so the reading the check is armed on can already - show the car's answer; the power before the send tells it.""" + EV-20 (rig round 1, EV-32; SPIKE-06 option 2): the stuck check's + baseline is the signature kept HERE, before the send. The write waits + for its read-back and the cycle reads the charger meanwhile, so `sig` + can already be the car's answer by `note_write`; armed on that, an + unchanged car was called stuck 60 s later.""" self.mute_until = float("inf") self.pre_sig = (self.sig,) @@ -817,7 +816,9 @@ class CarTracker: 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 - pre = self.pre_sig[0] if self.pre_sig else None + # The baseline: the reading before the send (`begin_write`), never one + # that arrived while the write waited (no `begin_write`: `sig`). + base = self.pre_sig[0] if self.pre_sig else self.sig self.pre_sig = () try: moved = was_a is None or abs(float(to_a) - float(was_a)) \ @@ -830,17 +831,13 @@ class CarTracker: return if ok: self._pend = None - self.armed_at, self.armed_sig = now, self.sig - # EV-20 rig round 1: the car's power before the send. A power - # that has moved from it is the car's answer (alive), however - # early that reading came (it may be the one `sig` holds). - self.armed_pre_w = None if pre is None else pre[0] + self.armed_at, self.armed_sig = now, base 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, "first": None} + self._pend = {"t": now, "pre": pre, "sig": base, "first": None} 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]): @@ -886,23 +883,12 @@ class CarTracker: 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"] - self.armed_pre_w = None # a refusal: no answer to look for def _sig(self, r, now: float) -> None: sig = (r.power_w, r.allowed_a) - # EV-20 rig round 1: after an accepted write the car's power moved - # from its value before the send (the car answered), or the car is - # paused (not charging, under QUIET_W): constant values are expected - # then, so neither is a stuck reading. - answered = (self.armed_pre_w is not None and r.power_w is not None - and r.power_w != self.armed_pre_w) - paused = (self.armed_pre_w is not None and r.charging is False - and r.power_w is not None and r.power_w < PAUSED_W) - if self.armed_at is not None and ( - answered or paused or (self.armed_sig is not None - and sig != self.armed_sig)): + if self.armed_at is not None and self.armed_sig is not None \ + and sig != self.armed_sig: self.armed_at = self.armed_sig = None # it moved: alive - self.armed_pre_w = None self.stuck_now = False elif self.armed_at is not None and self.armed_sig is None: self.armed_sig = sig diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index 932894c..f4b71ae 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -609,27 +609,57 @@ for beside, side in SIDES: f"{w.amber()}", w.amber() == ["charger_refused", "charger_stuck"]) +# SPIKE-06 option 2 (PM decision, EV-20): the stuck check is armed on the +# reading before the send, so a frozen POWER under an accepted write (the +# read-back moves) is no longer judged by it. The energy-meter check (EV-18, +# `contradicted`) judges it, and the alarm figure stays capped by the +# read-back. Each row: never stuck; when the meter contradicts the figure. +async def contra_steps(w, n): + """[(t, contradicted, trusted figure, stuck)] one per second.""" + out = [] + for _ in range(n): + await w.step(1) + tk = w.c.car + out.append((w.t, tk.contradicted(w.t), tk.car_w_trusted(w.t), + tk.stuck(w.t))) + return out + + +def contra_report(name, t_w, cs, cap_w): + first = next((t for t, c, _f, _s in cs if c), None) + stuck = [t for t, _c, _f, s in cs if s] + # once the read-back shows the new current (its 3 s lag, +2) + over = [(t, f) for t, _c, f, _s in cs + if f is not None and f > cap_w and t >= t_w + 5] + rel = None if first is None else first - t_w + check(f"{name}: never stuck (the read-back moved), and the trusted " + f"figure never exceeds the read-back's {cap_w:.0f} W (energy meter " + f"contradicts it from the write +{rel} s; stuck {stuck[:1]}, over " + f"{over[:1]})", not stuck and over == []) + return rel + + async def t14(): w = await live_car(beside=True) w.sim.lag_s = 3.0 # the read-back is seen by the cycle w.sim.freeze_power() # the power sticks, the rest is live res = spy_on(w) - await w.act("car_current", 8) - tr = await w.step(100) - return w, res, tr + await w.act("car_current", TO_A) + cs = await contra_steps(w, 200) + return w, res, cs -LOG.rec.clear() -w, res, tr = run(t14()) -t_s = res[0][0] -fs = first_stuck(tr) -check(f"T14 an ACCEPTED write (read-back 3 s late) under a frozen power: " - f"stuck at t_s+60 (+-1), as before ({fs - t_s if fs else None})", - res[0][2] is True and fs is not None and 59 <= fs - t_s <= 61 - and w.c.car.armed_at == t_s) -check("T14 ...the amber row 'charger_stuck' shows, and the car figure is not " - "trusted while stuck (N4)", "charger_stuck" in w.amber() - and w.c.car.car_w_trusted(w.t) is None and w.c.car_alarm_w() is None) +for TO_A in (8, 6): + LOG.rec.clear() + w, res, cs = run(t14()) + rel = contra_report(f"T14 an ACCEPTED 16 -> {TO_A} A write (read-back 3 s " + f"late) under a frozen power", res[0][0], cs, + TO_A * CH.CEILING_V * 3) + check(f"T14 [{TO_A} A] ...the write was accepted", res[0][2] is True) + if TO_A == 6: + check(f"T14 [6 A] the energy meter flags the frozen figure (EV-18) " + f"within 120 s of the write (+{rel})", + rel is not None and rel <= 120) async def t17(): @@ -637,25 +667,22 @@ async def t17(): w.sim.refuse = "ignore" res = spy_on(w) await w.act("car_current", 10) - tr = await w.step(70) # tries at t_s and t_s+60: live + await w.step(70) # tries at t_s and t_s+60: live w.sim.refuse = None w.sim.lag_s = 3.0 w.sim.freeze_power() await w.act("car_current", 12) - tr += await w.step(120) - return w, res, tr + cs = await contra_steps(w, 200) + return w, res, cs LOG.rec.clear() -w, res, tr = run(t17()) -t_s, t_acc = res[0][0], res[-1][0] -fs = first_stuck(tr) -check(f"T17 live refusals (not armed), then an accepted write at t_s+" - f"{t_acc - t_s:.0f}: not armed before it, stuck at ITS +60 (+-1) " - f"({fs - t_acc if fs else None})", - res[-1][2] is True and t_acc - t_s > 61 and fs is not None - and 59 <= fs - t_acc <= 61 - and all(a is None for t, a, _s in tr if t < t_acc)) +w, res, cs = run(t17()) +T17_S = contra_report("T17 live refusals, then an ACCEPTED write to 12 A " + "under a frozen power", res[-1][0], cs, + 12 * CH.CEILING_V * 3) +check("T17 ...the last write was accepted, after the refusals", + res[-1][2] is True and res[0][2] is False) async def t18(): @@ -663,25 +690,22 @@ async def t18(): w.sim.lag_s = 3.0 w.sim.freeze_power() res = spy_on(w) - await w.act("car_current", 12) # accepted: arms - tr = await w.step(19) + await w.act("car_current", 12) # accepted + cs = await contra_steps(w, 19) w.sim.lag_s = 0.0 w.sim.refuse = "ignore" await w.act("car_current", 10) # a live refusal 20 s later - tr += await w.step(100) - return w, res, tr + cs += await contra_steps(w, 180) + return w, res, cs LOG.rec.clear() -w, res, tr = run(t18()) -t0 = res[0][0] -fs = first_stuck(tr) -check(f"T18 an accepted write armed at t0; a live refusal at t0+" - f"{res[1][0] - t0:.0f} neither clears nor delays it: stuck at t0+60 " - f"({fs - t0 if fs else None}), still dated t0", - len(res) >= 2 and res[1][2] is False and fs is not None - and 59 <= fs - t0 <= 61 and tr[-1][1] == t0 - and all(a == t0 for _t, a, _s in tr if a is not None)) +w, res, cs = run(t18()) +T18_S = contra_report("T18 an ACCEPTED write to 12 A under a frozen power, a " + "refusal 20 s later", res[0][0], cs, + 12 * CH.CEILING_V * 3) +check("T18 ...the second write was refused", len(res) >= 2 + and res[1][2] is False) async def t21(beside): diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py index 4eb0c2e..eb9940b 100644 --- a/goodwe_controller/test_ev20_rig.py +++ b/goodwe_controller/test_ev20_rig.py @@ -11,6 +11,8 @@ 4. The 6 A hold lasts its full `ev_pause_min` from the spare's drop, 1 and 3 phases (Major); a meter as Home Assistant publishes it (`ha_signed`, on a change only) does not pause the car while it is healthy (Minors). +5. SPIKE-06: the race as the formal replay plays it; C12 (a refusal on a + paused car no longer holds Solar at 0 A); C13 (a capped car is not stuck). Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). """ @@ -23,10 +25,11 @@ sys.path.insert(0, os.path.join(HERE, "tools")) from datetime import datetime, timezone # noqa: E402 -from app import chargers as CH # noqa: E402 +from app import carmode, chargers as CH # noqa: E402 import ev20_sun as S # noqa: E402 from chargersim import SimCharger # noqa: E402 -from ev20_kit import (check, const, cur_writes, nevers, report, # noqa: E402 +from ev20_kit import (LOG, TSim, act, check, const, cur_writes, # noqa: E402 + nevers, report, step_fn) from named_absence import nth, present # noqa: E402 @@ -270,4 +273,153 @@ check(f"ha_signed, the meter silent from 300 s: 0 A at 30 + 300 s (+2), " present(nth(z, 0)) and 629 <= nth(z, 0) <= 633 and [a for t, a, _ in w if 300 <= t < 629] == []) +# =========================================================================== # +print("\n6. SPIKE-06: C12, C13 AND THE RACE AS THE FORMAL REPLAY PLAYS IT") +# =========================================================================== # + + +def race_hook(p, c): + """The race exactly as production interleaves it (SPIKE-06 replay): the + driver's read-back wait runs the next cycle's charger read, so the tracker + files the post-write reading before `note_write`.""" + orig = c.charger._sleep + + async def sleep(s): + await orig(s) + await c._read_charger(p.clock[0]) + c.charger._sleep = sleep + + +def stuck_ts(r): + return [x["t"] for x in r["trace"] if x["fault"] == "stuck"] + + +# C10/C11 replays (ctl A: the charger's power-on 10 A, Solar's D2 0 A; ctl B: +# Solar's 10 A start on a charging car), each with the race. +sim = SimCharger(setpoint_a=10) +sim.lag_s = 1.0 +r = S.drive(const(500.0), const(2900.0), dur=900, first="car", + socs={"a": 100.0, "b": 100.0}, sim=sim, events={0: race_hook}) +w = cur_writes(r) +check(f"race replay ctl A: D2 0 A, then the start at 120 s, never stuck " + f"({w[:3]}, stuck {stuck_ts(r)[:1]}, tracker {r['c'].car.stuck_now})", + present(nth(w, 1)) and nth(w, 0)[1] == 0.0 and nth(w, 1)[1] > 0.0 + and 119 <= nth(w, 1)[0] <= 125 and not stuck_ts(r) + and not r["c"].car.stuck_now) +nevers(r, "race replay ctl A") +sim = SimCharger(setpoint_a=0) +sim.lag_s = 1.0 +r = S.drive(const(500.0), const(2900.0), dur=900, first="car", + socs={"a": 100.0, "b": 100.0}, sim=sim, events={0: race_hook}) +w = cur_writes(r) +check(f"race replay ctl B: one start write, the car charges to the end, " + f"never stuck ({w[:3]}, stuck {stuck_ts(r)[:1]})", + len(w) == 1 and w[0][1] > 0.0 and not stuck_ts(r) + and not r["c"].car.stuck_now and r["sim"].power_w > 2000.0) +nevers(r, "race replay ctl B") + +# C12: a paused (full) car, a live charger ignores Solar's start write once. +# No life (0 W, flat energy), so the refusal arms and is stuck 60 s later; +# Solar's 0 A then stands. Option 2: the stuck verdict no longer holds the +# car at 0 A; the start rule writes again within 2 min, the reading moves. +for race in (False, True): + sim = TSim(setpoint_a=0, windows=[(100.0, 135.0, "ignore")]) + sim.car_full() + if race: + sim.lag_s = 1.0 + r = S.drive(const(500.0), const(2900.0), dur=900, first="car", + socs={"a": 100.0, "b": 100.0}, sim=sim, + events={0: race_hook} if race else None) + w = cur_writes(r) + tr = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] + st = r["c"].car + z = [t for t, a, _ in w if a == 0.0 and t > 125] + nz = [t for t, a, _ in w if a > 0.0 and present(nth(z, 0)) and t > z[0]] + check(f"C12 [race={race}] a live charger ignores one start write on a " + f"paused car: after Solar's 0 A the start rule writes again within " + f"125 s and the stuck verdict clears (writes {w[:6]}, 0 A at " + f"{z[:1]}, again at {nz[:1]}, stuck now {st.stuck_now})", + present(nth(z, 0)) and present(nth(nz, 0)) + and nth(nz, 0) - nth(z, 0) <= 125 and not st.stuck_now + and r["trace"][-1]["fault"] is None) + nevers(r, f"C12 [race={race}]") + +# C12's bound: a charger whose reading is really frozen. Solar's own 0 A +# stands (the frozen read-back shows 0 A), so the start rule runs; each start +# write is not taken and the 0 A follows. At most MAX_TRIES starts under one +# verdict, then ONE CHARGER_REFUSED warning and the 0 A stands (EV-04: until +# Solar is pressed). Here the reading comes back at 1200 s with the very +# values it froze with (0 W, 0 A), so nothing moves; pressing Solar at 1250 s +# starts afresh. +n0 = LOG.mark() +r = S.drive(const(600.0), lambda t: 600.0 + (1000.0 if 200 <= t < 330 + else 2300.0 if t < 200 + else 6000.0), + dur=1500, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_pause_min": 1, "ev_start_min": 1}, + events={300: lambda p, c: p.ch.freeze(), + 1200: lambda p, c: p.ch.freeze(False), + 1250: act("car_mode", "solar")}) +r["_log"] = n0 +w = cur_writes(r) +st = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] +t0 = nth(st, 0) if st else 0.0 +starts = [t for t, a, _ in w if a > 0.0 and t0 <= t < 1200] +warn = [m for m in LOG.since(n0, "WARNING") if "CHARGER_REFUSED" in m] +after = [(t, a) for t, a, _ in w if t >= 1200] +quiet = [(t, a) for t, a in after if t < 1250] +check(f"C12 bound: a frozen charger after Solar's own 0 A: at most 3 starts " + f"under the verdict ({starts}), one CHARGER_REFUSED ({len(warn)}), the " + f"charger at 0 A, nothing written until Solar is pressed, then a start " + f"within the start rule ({after[:2]})", + bool(st) and 1 <= len(starts) <= carmode.MAX_TRIES and len(warn) == 1 + and not quiet and present(nth(after, 0)) and nth(after, 0)[1] > 0.0 + and nth(after, 0)[0] <= 1250 + 75 + and [a for t, a, _ in w if t0 <= t < 1200][-1:] == [0.0]) +nevers(r, "C12 bound") + +# C13: a car that draws less than allowed (an on-board limit of 1380 W, or a +# taper). Tracker level: a raise 6 -> 10 A, the post-write reading filed +# during the wait (race) or not: never stuck. +for race in (True, False): + tr = CH.CarTracker() + tr.observe(rd(power=1380.0, allowed=6.0), TS, UTC, DAY) + tr.begin_write() + if race: + tr.observe(rd(power=1380.0, allowed=10.0), TS + 1, UTC, DAY) + tr.note_write(TS, 6.0, 10.0, True) + tr.end_write(TS + 1.5) + first = None + for i in range(2, 301): + tr.observe(rd(power=1380.0, allowed=10.0), TS + i, UTC, DAY) + if first is None and tr.stuck(TS + i): + first = i + check(f"C13 tracker [race={race}] a capped car (1380 W), raised 6 -> 10 " + f"A: never stuck (first at {first})", first is None) + + +class CapSim(SimCharger): + """A car whose on-board charger draws at most `cap_w`.""" + cap_w = 1380.0 + + def target_w(self): + return min(super().target_w(), self.cap_w) + + +for race in (True, False): + sim = CapSim(setpoint_a=0) + sim.lag_s = 1.0 + r = S.drive(const(500.0), lambda t: 3600.0 if t >= 300 else 2900.0, + dur=900, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, + events={0: race_hook} if race else None) + w = cur_writes(r) + up = [(t, a) for t, a, _ in w if t >= 300] + check(f"C13 controller [race={race}] a capped car, Solar raises the " + f"current at 300 s: never stuck, no 0 A after it ({w[:5]}, stuck " + f"{stuck_ts(r)[:1]})", + present(nth(up, 0)) and nth(up, 0)[1] > 10.0 and not stuck_ts(r) + and not [a for _, a in up if a == 0.0]) + nevers(r, f"C13 controller [race={race}]") + + report() -- 2.54.0 From b99f8c7e529abf17faa15219007ea52ac9c050f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:49:04 +0100 Subject: [PATCH 38/55] EV-20 SPIKE-06 re-check: a stuck verdict does not hold Solar while no own current may stand (C14) The exemption now applies whenever Solar is not live (also just after Solar is chosen under a verdict Manual's refusals left), so Solar writes its 0 A over the other current first and then the start rule runs. EV-13 T14 [8 A], T17 and T18 now assert that the energy meter does not flag the frozen figure (PM accepted the trade-off); T14 [6 A] that it flags at +57 s. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 8 ++++-- goodwe_controller/app/carmode.py | 15 +++++----- goodwe_controller/test_ev13.py | 15 ++++++++-- goodwe_controller/test_ev20_rig.py | 28 +++++++++++++++++++ 4 files changed, 54 insertions(+), 12 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 8518943..3407b49 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -126,9 +126,11 @@ one small set of facts and derives every path from them: - A frozen POWER under an accepted write (the read-back moves) is no longer judged here: the energy meter (EV-18 `contradicted`) and the read-back cap on the trusted figure judge it. -- **Solar after a stuck verdict (C12):** once Solar's own 0 A stands - (written and taken), a stuck verdict no longer holds the car at 0 A; the - start rule runs. Its write moves the reading (the verdict clears) or is +- **Solar after a stuck verdict (C12, C14):** while no current of Solar's + own may stand (its own 0 A stands, or Solar was just chosen), a stuck + verdict no longer holds Solar: it writes its 0 A first over a current that + is not its own, then the start rule runs; at most MAX_TRIES starts per + verdict, then CHARGER_REFUSED until Solar is pressed. Its write moves the reading (the verdict clears) or is refused (EV-04's retries, then CHARGER_REFUSED). - **No amp ping-pong:** after a step down, a step back up needs `UP_HYST_W` (100 W) past the amp boundary. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 2996fca..9f2302b 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -1044,13 +1044,14 @@ class SolarWriter(ManualWriter): if self.stuck_starts >= MAX_TRIES and self.gave_up: self.gave_up = False # the reading moved: start afresh self.stuck_starts = 0 - if fault == "stuck" and self.taken and self.sent_a is not None \ - and self.sent_a <= TOL_A: - # SPIKE-06 C12 (option 2): Solar's own 0 A stands, so a stuck - # verdict no longer holds the car at 0 A; the start rule runs. Its - # write moves the reading (the verdict clears) or is not taken: - # then the 0 A again, and after MAX_TRIES such starts under one - # verdict, CHARGER_REFUSED and the 0 A stands (EV-04's rule). + if fault == "stuck" and not self.live: + # SPIKE-06 C12/C14 (option 2): no current of Solar's own may stand + # (its own 0 A stands, or Solar was just chosen), so a stuck + # verdict no longer holds the car: Solar's normal step writes its + # 0 A first over a current that is not its own, then the start + # rule. A start moves the reading (the verdict clears) or is not + # taken: then the 0 A again, and after MAX_TRIES such starts under + # one verdict, CHARGER_REFUSED and the 0 A stands (EV-04's rule). if self.stuck_starts < MAX_TRIES: fault = None elif not self.gave_up: diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index f4b71ae..45d4ece 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -658,8 +658,13 @@ for TO_A in (8, 6): check(f"T14 [{TO_A} A] ...the write was accepted", res[0][2] is True) if TO_A == 6: check(f"T14 [6 A] the energy meter flags the frozen figure (EV-18) " - f"within 120 s of the write (+{rel})", - rel is not None and rel <= 120) + f"at about +57 s after the write (+{rel})", + rel is not None and 50 <= rel <= 65) + else: + # The frozen figure is exactly 2x the real draw: CORR_RATIO 0.5 is + # not undercut, so EV-18 never flags it (PM accepted, SPIKE-06). + check(f"T14 [8 A] the energy meter does NOT flag the frozen figure " + f"(+{rel}); only the read-back cap bounds it", rel is None) async def t17(): @@ -681,6 +686,9 @@ w, res, cs = run(t17()) T17_S = contra_report("T17 live refusals, then an ACCEPTED write to 12 A " "under a frozen power", res[-1][0], cs, 12 * CH.CEILING_V * 3) +check(f"T17 the energy meter does NOT flag the frozen figure (+{T17_S}); " + f"only the read-back cap bounds it (PM accepted, SPIKE-06)", + T17_S is None) check("T17 ...the last write was accepted, after the refusals", res[-1][2] is True and res[0][2] is False) @@ -704,6 +712,9 @@ w, res, cs = run(t18()) T18_S = contra_report("T18 an ACCEPTED write to 12 A under a frozen power, a " "refusal 20 s later", res[0][0], cs, 12 * CH.CEILING_V * 3) +check(f"T18 the energy meter does NOT flag the frozen figure (+{T18_S}); " + f"only the read-back cap bounds it (PM accepted, SPIKE-06)", + T18_S is None) check("T18 ...the second write was refused", len(res) >= 2 and res[1][2] is False) diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py index eb9940b..d1ce379 100644 --- a/goodwe_controller/test_ev20_rig.py +++ b/goodwe_controller/test_ev20_rig.py @@ -378,6 +378,34 @@ check(f"C12 bound: a frozen charger after Solar's own 0 A: at most 3 starts " and [a for t, a, _ in w if t0 <= t < 1200][-1:] == [0.0]) nevers(r, "C12 bound") +# C14: Manual's refused writes leave a stuck verdict on a paused, live car, +# then the user presses Solar. No current of Solar's own may stand, so the +# verdict does not hold Solar: its 0 A first (over Manual's 6 A), then the +# start rule with spare sun; the start moves the reading, the verdict clears. +for name, win, t_s in (("Manual's 12 A refused 3 times, Solar at 400 s", + (99.5, 250.0), 400),): + sim = TSim(setpoint_a=0, windows=[(win[0], win[1], "ignore")]) + sim.car_full() + seen = {} + r = S.drive(const(500.0), const(2900.0), dur=1200, first="car", + socs={"a": 100.0, "b": 100.0}, sim=sim, mode="manual", + events={100: act("car_current", 12), + t_s - 1: lambda p, c: seen.update( + armed=c.car.armed_at, stuck=c.car.stuck_now), + t_s: act("car_mode", "solar")}) + w = cur_writes(r) + nz = [(t, a) for t, a, _ in w if a > 0.0] + check(f"C14 [{name}]: the check armed by Manual's refusal before the " + f"press ({seen})", seen.get("armed") is not None) + check(f"C14 [{name}]: Solar writes 0 A first, then a start within the " + f"start rule, and the verdict clears ({w[:4]}, stuck now " + f"{r['c'].car.stuck_now})", + present(nth(w, 0)) and nth(w, 0)[1] == 0.0 + and nth(w, 0)[0] <= t_s + 2 and present(nth(nz, 0)) + and nth(nz, 0)[0] <= t_s + 125 and not r["c"].car.stuck_now + and r["trace"][-1]["fault"] is None) + nevers(r, f"C14 [{name}]") + # C13: a car that draws less than allowed (an on-board limit of 1380 W, or a # taper). Tracker level: a raise 6 -> 10 A, the post-write reading filed # during the wait (race) or not: never stuck. -- 2.54.0 From d17f15b33ca6bdc516c087bbbfc780e5e8b757ab Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 19:01:36 +0100 Subject: [PATCH 39/55] EV-20 SPIKE-06: stuck start cap backs off instead of holding Under one stuck verdict Solar still makes at most MAX_TRIES starts and gives one CHARGER_REFUSED; then one more start after 15 min and one every 30 min (each by the start rule and the write clock), so a fault that clears is found again. The episode ends when the reading follows a start, on a press of Solar, Off, Manual, shadow or a stop. Rows: cap, backoff times, recovery, press, episode end; T28 (b) no flapping. DOCS and DECISIONS. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 5 +- goodwe_controller/DOCS.md | 5 +- goodwe_controller/app/carmode.py | 48 +++++-- goodwe_controller/test_ev20_exits.py | 6 + goodwe_controller/test_ev20_rig.py | 118 +++++++++++++----- 5 files changed, 135 insertions(+), 47 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 3407b49..a844e3b 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -130,7 +130,10 @@ one small set of facts and derives every path from them: own may stand (its own 0 A stands, or Solar was just chosen), a stuck verdict no longer holds Solar: it writes its 0 A first over a current that is not its own, then the start rule runs; at most MAX_TRIES starts per - verdict, then CHARGER_REFUSED until Solar is pressed. Its write moves the reading (the verdict clears) or is + verdict, then one CHARGER_REFUSED, then one more start after 15 min and + one every 30 min (PM decision: no hold until a press). The episode ends + when the reading follows a start, on a press of Solar, Off, Manual, shadow + or a stop (`_stuck_end`). Its write moves the reading (the verdict clears) or is refused (EV-04's retries, then CHARGER_REFUSED). - **No amp ping-pong:** after a step down, a step back up needs `UP_HYST_W` (100 W) past the amp boundary. diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index 0990a0e..18f080d 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -3361,7 +3361,10 @@ changes at most once per 30 seconds and only by 1 A or more. stopping the add-on each set the charger to 0 A once. A 0 A the charger does not take is tried again after a minute, three times, then an amber row says so. After a restart, or when the charger or Home Assistant answers again, - Solar sets 0 A first and then starts by its own rules. At a stop of the + Solar sets 0 A first and then starts by its own rules. After a stuck + charger reading, Solar tries to start again by its start rule; after three + tries an amber row says so, and it tries once more after 15 minutes, then + every 30 minutes, until the reading follows. At a stop of the add-on the charger's 0 A goes out before the batteries go to 0 W, for at most 15 seconds; if the charger does not take it, the notice *Car may still be charging* follows. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 9f2302b..7555685 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -64,6 +64,8 @@ PHASE_GAP_S = 600.0 # at most one phase switch per this WRITER_S = 30.0 # a differing read-back this long is another writer RETRY_S = 60.0 # a write the charger did not take, tried again after MAX_TRIES = 3 # ... this many times, then it waits for the user +STUCK_BACKOFF_FIRST_S = 900.0 # Solar under a stuck verdict, its starts used +STUCK_BACKOFF_S = 1800.0 # up: one more after 15 min, then every 30 min TOL_A = CH.TOOK_TOL_A @@ -717,6 +719,8 @@ class SolarWriter(ManualWriter): self.other_at = None # C6: Manual's latest non-zero write self.on_owed = None # C1: told when an own 0 A is out / back self.stuck_starts = 0 # SPIKE-06 C12: starts under one stuck verdict + self.stuck_wait = None # ... used up: the next start not before + self.stuck_warned = False # ... and its one CHARGER_REFUSED was given def owe_start(self) -> None: """C1: the add-on starts in Off while an exit 0 A of its own was still @@ -724,6 +728,15 @@ class SolarWriter(ManualWriter): so the 0 A is owed (once it may write), retried by the exit rule.""" self.start_owed = self.engaged = True + def _stuck_end(self) -> None: + """SPIKE-06: a stuck episode ends (the reading followed a start, a + press of Solar, Off, Manual or shadow): starts counted afresh, and + its CHARGER_REFUSED is cleared.""" + if self.stuck_warned: + self.gave_up = False + self.stuck_starts, self.stuck_wait = 0, None + self.stuck_warned = False + def _owed(self, pending: bool) -> None: if self.on_owed is not None: self.on_owed(pending) @@ -758,7 +771,7 @@ class SolarWriter(ManualWriter): held = self.hold or self.mismatch_since is not None super().user_changed() self.gave_up, self.fails, self.fail_at = False, 0, None - self.stuck_starts = 0 + self._stuck_end() if held: self.last_a = None self.sent_a, self.taken = None, True @@ -772,6 +785,8 @@ class SolarWriter(ManualWriter): zero = float(a) <= TOL_A if not zero and tracker is not None and tracker.stuck(now): self.stuck_starts += 1 # C12: a start under a stuck verdict + if self.stuck_wait is not None: + self.stuck_wait = now + STUCK_BACKOFF_S # a backoff try if zero: self.zero_at = self.zero_sent_at = now self._owed(True) # C1: kept with the mode until back @@ -1007,6 +1022,7 @@ class SolarWriter(ManualWriter): self._adopt(cur) # round 9: a late read-back self._mark(r, now) if mode != SOLAR: + self._stuck_end() self.would = None if mode == OFF and self.start_owed: if not writing: @@ -1026,6 +1042,7 @@ class SolarWriter(ManualWriter): else self.plan.n n_now = 1 if self.single else n_real if not writing: + self._stuck_end() # Shadow, Stop, a safety stop, stopping: the way-out 0 A while # owed, then nothing. The watch goes on (another writer is held # for every reader) and so does the plan, for the card. @@ -1041,24 +1058,31 @@ class SolarWriter(ManualWriter): fault = ("error" if (r.error or r.state in ("E", "F")) else "stuck" if stuck else None) if not stuck: - if self.stuck_starts >= MAX_TRIES and self.gave_up: - self.gave_up = False # the reading moved: start afresh - self.stuck_starts = 0 + self._stuck_end() # the reading moved: start afresh if fault == "stuck" and not self.live: # SPIKE-06 C12/C14 (option 2): no current of Solar's own may stand # (its own 0 A stands, or Solar was just chosen), so a stuck # verdict no longer holds the car: Solar's normal step writes its # 0 A first over a current that is not its own, then the start - # rule. A start moves the reading (the verdict clears) or is not - # taken: then the 0 A again, and after MAX_TRIES such starts under - # one verdict, CHARGER_REFUSED and the 0 A stands (EV-04's rule). + # rule. A start moves the reading (the episode ends) or is not + # taken: then the 0 A again. After MAX_TRIES such starts, one + # CHARGER_REFUSED, then one more start after 15 min and one every + # 30 min (PM decision): a fault that clears is found again. if self.stuck_starts < MAX_TRIES: fault = None - elif not self.gave_up: - self.gave_up = True - _LOG.warning("The charger did not take the current, so the " - "add-on stops asking until you press Solar: " - "CHARGER_REFUSED.") + else: + if self.stuck_wait is None: + self.stuck_wait = now + STUCK_BACKOFF_FIRST_S + if not self.stuck_warned: + self.stuck_warned = True + _LOG.warning("The charger did not take the current, so " + "the add-on tries again in 15 min, then " + "every 30 min: CHARGER_REFUSED.") + if now >= self.stuck_wait: + self.gave_up = False + fault = None + else: + self.gave_up = True if fault is not None: # 0 A while owed, then no write until it clears; then the start # rule. A stuck reading cannot confirm the 0 A. diff --git a/goodwe_controller/test_ev20_exits.py b/goodwe_controller/test_ev20_exits.py index 5eb8d40..c351c70 100644 --- a/goodwe_controller/test_ev20_exits.py +++ b/goodwe_controller/test_ev20_exits.py @@ -240,6 +240,12 @@ check(f"T28 (b): frozen at 0 A, then Solar starts (the write unconfirmed): " bool(st28) and [x for x in w28b if x[0] >= st28[0]][:1] and [x for x in w28b if x[0] >= st28[0]][0][1] == 0.0 and r28b["sim"].setpoint_a == 0.0) +# SPIKE-06 (PM): under the verdict at most MAX_TRIES starts, then the backoff +# (15 min, then 30 min; test_ev20_rig.py): no 72 s flapping. +s28b = [t for t, a, _ in w28b if a > 0.0 and st28 and t >= st28[0]] +check(f"T28 (b): at most {carmode.MAX_TRIES} starts under the verdict in the " + f"run, then none before the 15 min backoff ({s28b})", + len(s28b) <= carmode.MAX_TRIES) # T29: the charger unavailable 300-420 s. T29 = {"i": lambda p, c: None, diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py index d1ce379..e81a551 100644 --- a/goodwe_controller/test_ev20_rig.py +++ b/goodwe_controller/test_ev20_rig.py @@ -344,39 +344,91 @@ for race in (False, True): and r["trace"][-1]["fault"] is None) nevers(r, f"C12 [race={race}]") -# C12's bound: a charger whose reading is really frozen. Solar's own 0 A -# stands (the frozen read-back shows 0 A), so the start rule runs; each start -# write is not taken and the 0 A follows. At most MAX_TRIES starts under one -# verdict, then ONE CHARGER_REFUSED warning and the 0 A stands (EV-04: until -# Solar is pressed). Here the reading comes back at 1200 s with the very -# values it froze with (0 W, 0 A), so nothing moves; pressing Solar at 1250 s -# starts afresh. -n0 = LOG.mark() -r = S.drive(const(600.0), lambda t: 600.0 + (1000.0 if 200 <= t < 330 - else 2300.0 if t < 200 - else 6000.0), - dur=1500, first="car", socs={"a": 100.0, "b": 100.0}, - opts={"ev_pause_min": 1, "ev_start_min": 1}, - events={300: lambda p, c: p.ch.freeze(), - 1200: lambda p, c: p.ch.freeze(False), - 1250: act("car_mode", "solar")}) -r["_log"] = n0 -w = cur_writes(r) -st = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] -t0 = nth(st, 0) if st else 0.0 -starts = [t for t, a, _ in w if a > 0.0 and t0 <= t < 1200] -warn = [m for m in LOG.since(n0, "WARNING") if "CHARGER_REFUSED" in m] -after = [(t, a) for t, a, _ in w if t >= 1200] -quiet = [(t, a) for t, a in after if t < 1250] -check(f"C12 bound: a frozen charger after Solar's own 0 A: at most 3 starts " - f"under the verdict ({starts}), one CHARGER_REFUSED ({len(warn)}), the " - f"charger at 0 A, nothing written until Solar is pressed, then a start " - f"within the start rule ({after[:2]})", - bool(st) and 1 <= len(starts) <= carmode.MAX_TRIES and len(warn) == 1 - and not quiet and present(nth(after, 0)) and nth(after, 0)[1] > 0.0 - and nth(after, 0)[0] <= 1250 + 75 - and [a for t, a, _ in w if t0 <= t < 1200][-1:] == [0.0]) -nevers(r, "C12 bound") +# C12's cap and backoff (PM decision): a charger whose reading is really +# frozen (at 300 s, with the values it will show when it comes back). Solar's +# own 0 A stands, so the start rule runs; each start is not taken and the 0 A +# follows. At most MAX_TRIES starts under one verdict, then ONE +# CHARGER_REFUSED; then one more start 15 min later, then one every 30 min +# (each by the start rule), never the 72 s flapping. +def frozen_run(dur, events=None): + n0 = LOG.mark() + ev = {300: lambda p, c: p.ch.freeze()} + ev.update(events or {}) + r = S.drive(const(600.0), lambda t: 600.0 + (1000.0 if 200 <= t < 330 + else 2300.0 if t < 200 + else 6000.0), + dur=dur, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_pause_min": 1, "ev_start_min": 1}, events=ev) + r["_log"] = n0 + st = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] + t0 = nth(st, 0) if st else 1e9 + w = cur_writes(r) + starts = [t for t, a, _ in w if a > 0.0 and t >= t0] + warn = [m for m in LOG.since(n0, "WARNING") if "CHARGER_REFUSED" in m] + return r, w, starts, warn + + +r, w, starts, warn = frozen_run(4000) +first3, later = starts[:3], starts[3:] +t3 = nth(first3, 2) +gaps = [b - a for a, b in zip(later, later[1:])] +check(f"cap: a frozen charger: 3 starts under the verdict ({first3}), then " + f"one CHARGER_REFUSED ({len(warn)})", + len(first3) == carmode.MAX_TRIES and len(warn) == 1 + and all(b - a < 120 for a, b in zip(first3, first3[1:]))) +check(f"backoff: one more start 15 min after the 3rd (+ the start rule), " + f"then one every 30 min (+ the start rule): {later} (gaps {gaps})", + present(t3) and len(later) == 2 + and 900 <= nth(later, 0) - t3 <= 900 + 80 + and all(1800 <= g <= 1800 + 80 for g in gaps)) +nevers(r, "cap and backoff") + +# Recovery: the reading comes back at 1200 s with the values it froze with, +# so nothing moves by itself; the next backoff start is taken, the reading +# follows it, the episode ends (warning cleared) and the car charges. +r, w, starts, warn = frozen_run(2400, {1200: lambda p, c: p.ch.freeze(False)}) +t3 = nth(starts, 2) +rec = [t for t in starts if t > 1200] +check(f"recovery: the fault clears at 1200 s; the next backoff start " + f"({rec[:1]}, 15 min after the 3rd at {t3}) is taken and the car " + f"charges to the end, warning cleared, not stuck", + present(nth(rec, 0)) and present(t3) + and 900 <= nth(rec, 0) - t3 <= 980 + and r["sim"].power_w > 1000.0 and not r["c"].car.stuck_now + and not r["c"].car_solar.gave_up) +nevers(r, "recovery") + +# A press of Solar during the backoff starts the episode afresh: a start by +# the start rule after the press, not 15 min later. +r, w, starts, warn = frozen_run(1400, {1000: act("car_mode", "solar")}) +after = [t for t in starts if t >= 1000] +check(f"press: Solar pressed at 1000 s during the backoff: a start by the " + f"start rule after the press ({after[:1]})", + present(nth(after, 0)) and nth(after, 0) <= 1000 + 75) + +# The episode ends on Off, Manual and shadow: counter, wait and warning +# cleared (read 5 s after the switch). +for name, fn in (("Off", act("car_mode", "off")), + ("Manual", act("car_mode", "manual")), + ("shadow", lambda p, c: c.o.__setitem__("shadow_mode", + "on"))): + seen = {} + + def look(p, c, seen=seen): + sw = c.car_solar + seen.update(starts=sw.stuck_starts, gave_up=sw.gave_up, + wait=getattr(sw, "stuck_wait", None), + warned=getattr(sw, "stuck_warned", None)) + before = {} + + def look0(p, c, before=before): + before.update(starts=c.car_solar.stuck_starts, + gave_up=c.car_solar.gave_up) + r, w, starts, warn = frozen_run(900, {790: look0, 800: fn, 805: look}) + check(f"episode end on {name}: before {before}, after {seen}", + before.get("starts") == carmode.MAX_TRIES and before.get("gave_up") + and seen.get("starts") == 0 and seen.get("gave_up") is False + and seen.get("wait") is None and seen.get("warned") is False) # C14: Manual's refused writes leave a stuck verdict on a paused, live car, # then the user presses Solar. No current of Solar's own may stand, so the -- 2.54.0 From a486a0c5b35b67ca45e1cdb50a10dceaed0feccf Mon Sep 17 00:00:00 2001 From: ems-agent <2+ems-agent@noreply.localhost> Date: Mon, 23 Nov 2026 23:30:09 +0100 Subject: [PATCH 40/55] infra-pin: bump to admin/goodwe e4e8897 --- .gitea/infra-pin | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitea/infra-pin b/.gitea/infra-pin index 1bdc5ea..9238cab 100644 --- a/.gitea/infra-pin +++ b/.gitea/infra-pin @@ -1,2 +1,2 @@ # The admin/goodwe commit CI tests against. Bump: set to the full SHA of admin/goodwe release/1.0 HEAD (README.md, "CI and the infra pin"). -f88461234f3a7d53c025a68beda4cb6e4384cebf +e4e889723e1be9353862d1aa27636447026cb43e -- 2.54.0 From 8d62abe36b1b5de0c47bdaf816376a153e67d099 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 23:46:48 +0100 Subject: [PATCH 41/55] EV-20 rig round 2: a short charger read gap keeps the last reading; ha_signed pause timed from the meter age A charger reading missing for less than stale_input_s keeps the last trusted reading in CarTracker (shared by Solar, Manual and the peak guard): no decision or write in that cycle, no stuck arm or clear. At stale_input_s the safe path is unchanged. This also stops the false PEAK_GUARD_FLOOR_LIMITED after one gap (EV-18 T10(b) updated). On ha_signed Solar's unknown-sun pause comes at meter age meter_max_age_s + ev_pause_min, checked every cycle. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 15 +++ goodwe_controller/app/carmode.py | 15 ++- goodwe_controller/app/chargers.py | 19 +++ goodwe_controller/app/ctl_car.py | 19 ++- goodwe_controller/test_ev18.py | 26 +++- goodwe_controller/test_ev20_rig.py | 112 ++++++++++++++++++ 6 files changed, 198 insertions(+), 8 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index a844e3b..dcf2f45 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -144,3 +144,18 @@ one small set of facts and derives every path from them: `meter_max_age_s` is the bound (a silent meter: 0 A at `meter_max_age_s` + `ev_pause_min`). +## Rig round 2 (rig FAIL on 09b6af9), PM rulings + +- **A short charger read gap** (chargers.py `CarTracker.observe`, shared by + Solar, Manual and the peak guard): a reading missing for less than + `stale_input_s` keeps the last trusted reading (`held`); nothing is decided + or written in that cycle (`ctl_car.car_step` returns), and it neither arms + nor clears the stuck check. At `stale_input_s` the missing reading is taken + as before (the safe path: the charger is gone, 0 A first on its return). + This also ends the false PEAK_GUARD_FLOOR_LIMITED after one gap (EV-18 + T10(b) changed accordingly). +- **Silent meter on `ha_signed`:** Solar's unknown-sun pause is timed from the + meter's age: unknown since the age passed `meter_max_age_s`, so 0 A when the + age reaches `meter_max_age_s` + `ev_pause_min` (330 s), checked every + control cycle (bound 330 s + one cycle). Arrival sources are unchanged. + diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 7555685..f82465e 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -498,8 +498,12 @@ class SunInputs: def __init__(self, target_w=None, hold=False, auto=True, start_s=120.0, pause_s=300.0, spare_w=None, room_w=0.0, margin_w=100.0, - first=DEFAULT_FIRST): + first=DEFAULT_FIRST, unknown_s=0.0): self.target_w, self.hold, self.auto = target_w, hold, auto + # EV-20 rig round 2: how long the sun has already been unknown when + # the cause is the meter's own age (`ha_signed`): the pause is timed + # from that age, not from the cycle that noticed it. + self.unknown_s = unknown_s self.start_s, self.pause_s = start_s, pause_s self.spare_w, self.room_w, self.margin_w = spare_w, room_w, margin_w self.first = first @@ -563,7 +567,7 @@ class SolarPlan: self.switch, self._before = False, None def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s, - hold=False, gap_ok=True): + hold=False, gap_ok=True, unknown_s=0.0): """`n_now`: the phases the car draws on now (1 for a one-phase car); `auto`: Solar may choose the phases; `gap_ok`: a phase change is allowed now (EV-04's one per `PHASE_GAP_S`); `hold`: readings late @@ -586,6 +590,11 @@ class SolarPlan: if self.a > 0.0: if self.unknown_since is None: self.unknown_since = now + if unknown_s > 0.0: + # ha_signed: unknown since the meter's age passed its + # bound, so the pause comes at that age + `pause_s`. + self.unknown_since = min(self.unknown_since, + now - unknown_s) # A hold that began on a known low spare still ends on time. if now - self.unknown_since >= pause_s or ( self.low_since is not None @@ -919,7 +928,7 @@ class SolarWriter(ManualWriter): now, target_w=sun.target_w, hold=sun.hold, n_now=n_now, auto=sun.auto and not self.single and not self.phases_gave_up, clamp=clamp, start_s=sun.start_s, pause_s=sun.pause_s, - gap_ok=gap_ok) + gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0)) @staticmethod def _drawing(r) -> bool: diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index a2082b0..cb311d7 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -719,6 +719,7 @@ class CarTracker: # write went out, kept at `begin_write` (the arming baseline). Empty: no # write begun, and `note_write` uses `sig`. pre_sig: tuple = () + held: bool = False # EV-20: the last reading stands in for a gap armed_at: float | None = None armed_sig: tuple | None = None sig: tuple | None = None @@ -735,6 +736,17 @@ class CarTracker: persist: bool = False # set when `today` changed, for the store def observe(self, r: ChargerReading, now: float, now_utc, day: str): + if not r.available and self.bad_since is None: + self.bad_since, self.bad_since_utc = now, now_utc + if self._held(r, now): + # EV-20 rig round 2 (PM): a reading missing for less than + # `stale_s` keeps the last trusted figure and decides nothing: + # no write, no pause, and it neither arms nor clears the stuck + # check. At `stale_s` the missing reading is taken as before. + self.held = True + self._status_edge(now, now_utc) + return + self.held = False self.reading = r self.obs_at = now self._corr_note(r, now) @@ -757,6 +769,13 @@ class CarTracker: self._timers(r, now) self._status_edge(now, now_utc) + def _held(self, r, now: float) -> bool: + """Is this missing reading a short gap behind a usable one?""" + last = self.reading + return (not r.available and last is not None and last.available + and self.last_ok is not None + and now - self.last_ok < self.stale_s) + # -- reachability ---------------------------------------------------------- def unreachable(self, now: float) -> bool: return self.bad_since is not None and now - self.bad_since >= UNREACHABLE_S diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 3fa122c..cbee191 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -368,6 +368,11 @@ class CarMixin: cycle's read did) and writes only through `carmode`'s writers.""" if not self.charger.configured(): return + if self.car.held: + # EV-20 rig round 2 (PM): the charger missed a read for less than + # `stale_input_s`; the last trusted figure stands and nothing is + # decided or written from the gap. + return now = self.car_now() if self.car_mode != carmode.SOLAR: await self.car_writer.step( @@ -452,7 +457,19 @@ class CarMixin: hold=hold, auto=ph not in ("1", "3"), start_s=60.0 * carmode.solar_option(o, "ev_start_min"), pause_s=60.0 * carmode.solar_option(o, "ev_pause_min"), - spare_w=spare, room_w=room, margin_w=margin, first=self.car_first) + spare_w=spare, room_w=room, margin_w=margin, first=self.car_first, + unknown_s=self._car_meter_over_s() if spare is None else 0.0) + + def _car_meter_over_s(self) -> float: + """EV-20 rig round 2 (PM): on `ha_signed`, how far the meter's age is + past `meter_max_age_s`, so Solar's pause comes at that age + + `ev_pause_min` (checked every cycle), not a cycle or two later.""" + if not self.p1_enabled \ + or str(self.o.get("meter_source") or "") != "ha_signed": + return 0.0 + age = self.p1.age_s() + bound = float(self.o.get("meter_max_age_s", 30) or 30) + return 0.0 if age is None else max(0.0, age - bound) def _car_sun_tick(self, mono) -> None: """Solar kWh: per cycle, in Solar only, the car's power up to the sun diff --git a/goodwe_controller/test_ev18.py b/goodwe_controller/test_ev18.py index 9737c5c..b54a57e 100644 --- a/goodwe_controller/test_ev18.py +++ b/goodwe_controller/test_ev18.py @@ -605,11 +605,14 @@ for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))), r10b, tr10b = H.run(a=ZERO, extra=unavailable(E + 1, E + 2), **kw) summary(f"T10(b) {nm}", r10b, tr10b) if nm == "T2": + # EV-20 rig round 2 (PM): a charger read missing for less than + # stale_input_s keeps the last trusted figure, so this one-cycle gap + # is no longer an unknown car figure (was: the alarm for that cycle). check("T10(b) T2: the charger unavailable for one cycle (E+1): the " - "alarm stands for that cycle only (Expected 5)", - H.edges(tr10b) == [E + 1] - and all(not x["alarm"] for x in H.window(tr10b, E + 2, E + 899)) - and all(x["explains"] for x in H.window(tr10b, E + 2, E + 899) + "last trusted figure stands (EV-20), no alarm edge, the car " + "explains every limited cycle", + H.edges(tr10b) == [] and quiet(r10b, tr10b) + and all(x["explains"] for x in H.window(tr10b, E, E + 899) if x["lim"])) else: check("T10(b) T5: the alarm at the base second and it stands", @@ -813,6 +816,21 @@ def per_quarter(ts): return out +# EV-20 rig round 2: ONE failed charger read in the T2 shape. The tracker keeps +# the last trusted figure for a gap under `stale_input_s`, so the car still +# explains the peak and no floor alarm comes (rig: a false FLOOR_LIMITED 1-2 s +# after a single read gap, on base and head). +for gap in (1, 2): + rg, trg = H.run(H.shape(14000.0), a=ZERO, b=const(800.0), + extra={E + 30: lambda p, c: p.ch.go_unavailable(), + E + 30 + gap: lambda p, c: p.ch.go_unavailable( + False)}) + wg, limg = summary(f"T-gap {gap} s", rg, trg) + check(f"T-gap: {gap} missed charger read(s) at E+30: no " + f"goodwe_peak_soc_floor, no FLOOR_LIMITED ERROR, no red peak_guard " + f"row, the car explains every limited cycle", + quiet(rg, trg) and all_explained(limg)) + # Cover off, the T9(c) liar at the reserve: the guard's own engagement flips # as the liar's figure is corroborated now and then (its input is # `car_exclude`), pre-existing (base: 4 edges). Printed, not graded here. diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py index e81a551..04cd247 100644 --- a/goodwe_controller/test_ev20_rig.py +++ b/goodwe_controller/test_ev20_rig.py @@ -502,4 +502,116 @@ for race in (True, False): nevers(r, f"C13 controller [race={race}]") +# =========================================================================== # +print("\n7. RIG ROUND 2: A SHORT CHARGER READ GAP; THE ha_signed PAUSE BY AGE") +# =========================================================================== # +# Full sun, Car first, charging 10 A from 120 s; the charger does not answer +# for 1, 2 or 16 cycles at 600 s (Home Assistant shows it unavailable). +def gap_run(n, beside=False): + sim = SimCharger(setpoint_a=0) + if beside: + sim.lag_s = 1.0 + return S.drive(const(500.0), const(2900.0), dur=1100, first="car", + socs={"a": 100.0, "b": 100.0}, sim=sim, beside=beside, + events={600: lambda p, c: p.ch.go_unavailable(), + 600 + n: lambda p, c: p.ch.go_unavailable(False)}) + + +for n in (1, 2): + for beside in (False, True): + r = gap_run(n, beside) + w = cur_writes(r) + late = [(t, a) for t, a, _ in w if t >= 590] + unk = [x["t"] for x in r["trace"] if 590 <= x["t"] < 1100 + and x["spare"] is None] + check(f"read gap of {n} sample(s) at 600 s [beside={beside}]: no " + f"write and no pause after it, the spare stays known (writes " + f"from 590 s {late}, unknown {unk[:3]})", + late == [] and unk == [] and r["sim"].power_w > 2000.0) + nevers(r, f"read gap {n} [beside={beside}]") + +# 16 s (>= stale_input_s): the safe path as before. The charger is taken as +# gone; on its return Solar writes 0 A first (D2), then the start rule. +r = gap_run(16) +w = cur_writes(r) +late = [(t, a) for t, a, _ in w if t >= 590] +check(f"read gap of 16 s: the safe path, 0 A first on the return, then the " + f"start rule ({late[:3]})", + present(nth(late, 0)) and nth(late, 0)[1] == 0.0 + and 616 <= nth(late, 0)[0] <= 620 and present(nth(late, 1)) + and nth(late, 1)[1] > 0.0) + +# The held figure neither arms nor clears the stuck check: a frozen reading +# after an accepted write is still stuck, with a 2-sample gap inside the 60 s +# (flagged at the first real reading at or after +60 s). +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(), TS + i, UTC, DAY) +tr.begin_write() +tr.end_write(TS + 1) +tr.note_write(TS, 10.0, 0.0, True) +gone = CH.ChargerReading(why="no answer") +st_at = None +for i in range(1, 90): + if i in (59, 60): + tr.observe(gone, TS + i, UTC, DAY) + else: + tr.observe(rd(), TS + i, UTC, DAY) + if st_at is None and tr.stuck(TS + i): + st_at = i +check(f"frozen reading with a 2-sample gap at +59/+60: still stuck, at the " + f"first real reading after +60 (+{st_at})", st_at == 61) +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(), TS + i, UTC, DAY) +tr.begin_write() +tr.end_write(TS + 1) +tr.note_write(TS, 10.0, 0.0, True) +for i in range(1, 70): + tr.observe(rd(), TS + i, UTC, DAY) +tr.observe(gone, TS + 70, UTC, DAY) +check("a held gap does not clear a stuck verdict (+70 s gap, still stuck)", + tr.stuck(TS + 70) and getattr(tr, "held", None) is True) + +# ha_signed: the pause is timed from the meter's age (PM): unknown since the +# age passed meter_max_age_s, so 0 A when the age reaches 330 s. A plan +# stepped every 10 s (the rig's cycle) that notices the stale meter 7 s late +# pauses at the first step at or after age 330 (bound: 330 + one cycle). +plan = carmode.SolarPlan() +plan.reset(1) +kw = dict(n_now=1, auto=False, clamp=16.0, start_s=120.0, pause_s=300.0) +t = 0.0 +while plan.a <= 0.0 and t < 400: + plan.step(t, target_w=2900.0, **kw) + t += 10.0 +age0 = t + 3.0 # the meter's last reading; the bound passes at +30 +paused_at = None +while t < age0 + 400: + age = t - age0 + over = max(0.0, age - 30.0) + try: + plan.step(t, target_w=None if age > 30.0 else 2900.0, + unknown_s=over, **kw) + except TypeError: # a build without the age rule + plan.step(t, target_w=None if age > 30.0 else 2900.0, **kw) + if plan.a == 0.0 and paused_at is None: + paused_at = age + break + t += 10.0 +check(f"ha_signed pause by age, plan stepped every 10 s: 0 A at meter age " + f"{paused_at} (330 <= age <= 340)", + paused_at is not None and 330.0 <= paused_at <= 340.0) +# The controller hands Solar that age: 40 s after the meter went silent at +# 300 s, `unknown_s` is 10 (age 40 - 30). +seen = {} +r = S.drive(const(500.0), const(2900.0), dur=360, first="car", + socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, + events={300: lambda p, c: setattr(p, "meter_on", False), + 340: lambda p, c: seen.update( + u=getattr(c.car_sun_inputs(p.clock[0]), + "unknown_s", None))}) +check(f"ha_signed: 40 s after the meter went silent Solar is told the sun " + f"has been unknown for 10 s ({seen})", + seen.get("u") is not None and 9.0 <= seen["u"] <= 12.0) + report() -- 2.54.0 From 49e010fdfbf6564bccf284a7dada669b41692b8d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 23:55:17 +0100 Subject: [PATCH 42/55] EV-20 rig round 2: the age row notices the stale meter late, as the rig's cycle does Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/test_ev20_rig.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py index 04cd247..18cf734 100644 --- a/goodwe_controller/test_ev20_rig.py +++ b/goodwe_controller/test_ev20_rig.py @@ -575,8 +575,10 @@ check("a held gap does not clear a stuck verdict (+70 s gap, still stuck)", # ha_signed: the pause is timed from the meter's age (PM): unknown since the # age passed meter_max_age_s, so 0 A when the age reaches 330 s. A plan -# stepped every 10 s (the rig's cycle) that notices the stale meter 7 s late -# pauses at the first step at or after age 330 (bound: 330 + one cycle). +# stepped every 10 s (the rig's cycle) that first sees the unknown sun at age +# 57 (a cycle or two after the bound passed) still pauses at the first step at +# or after age 330 (bound: 330 + one cycle); timed from the noticing step it +# would be age 357. plan = carmode.SolarPlan() plan.reset(1) kw = dict(n_now=1, auto=False, clamp=16.0, start_s=120.0, pause_s=300.0) @@ -590,10 +592,10 @@ while t < age0 + 400: age = t - age0 over = max(0.0, age - 30.0) try: - plan.step(t, target_w=None if age > 30.0 else 2900.0, - unknown_s=over, **kw) + plan.step(t, target_w=None if age > 50.0 else 2900.0, + unknown_s=over if age > 50.0 else 0.0, **kw) except TypeError: # a build without the age rule - plan.step(t, target_w=None if age > 30.0 else 2900.0, **kw) + plan.step(t, target_w=None if age > 50.0 else 2900.0, **kw) if plan.a == 0.0 and paused_at is None: paused_at = age break -- 2.54.0 From f62501174dbe3356d964c54de2f65b04bb5114e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 00:46:34 +0100 Subject: [PATCH 43/55] EV-20 rig round 2: hold only real read gaps, not a reading's own unavailable cause A failed read or every required entity unavailable is a gap and keeps the last reading; one entity missing, a wrong power unit or login off stay the reading they are (EV-03 round 4 rows green again). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 5 ++++- goodwe_controller/app/chargers.py | 21 ++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index dcf2f45..061d8e1 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -148,7 +148,10 @@ one small set of facts and derives every path from them: - **A short charger read gap** (chargers.py `CarTracker.observe`, shared by Solar, Manual and the peak guard): a reading missing for less than - `stale_input_s` keeps the last trusted reading (`held`); nothing is decided + `stale_input_s` keeps the last trusted reading (`held`). A gap is a read + that got no answer, or every required entity unavailable; one entity + missing, a wrong power unit or the login off stay readings of their own + (EV-03 round 4, unchanged); nothing is decided or written in that cycle (`ctl_car.car_step` returns), and it neither arms nor clears the stuck check. At `stale_input_s` the missing reading is taken as before (the safe path: the charger is gone, 0 A first on its return). diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index cb311d7..71afd92 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -255,6 +255,18 @@ def display_class(text) -> str | None: return None +def _is_gap(why) -> bool: + """EV-20: does this unavailable reading's cause mean "no answer" (a read + gap), not a reading the charger gave?""" + why = why or "" + if why == "no answer": + return True + if why.startswith("no answer from "): + gone = {x.strip() for x in why[len("no answer from "):].split(",")} + return set(REQUIRED) <= gone + return False + + def reading_from_states(states: dict) -> ChargerReading: """A `ChargerReading` from `{role: state object or None}`. Pure.""" def txt(role): @@ -770,10 +782,13 @@ class CarTracker: self._status_edge(now, now_utc) def _held(self, r, now: float) -> bool: - """Is this missing reading a short gap behind a usable one?""" + """Is this missing reading a short gap behind a usable one? A gap is + a read that failed (no answer at all) or Home Assistant showing every + required entity unavailable. One entity missing, a wrong unit or the + login off are readings of their own (EV-03), never held.""" last = self.reading - return (not r.available and last is not None and last.available - and self.last_ok is not None + return (not r.available and _is_gap(r.why) and last is not None + and last.available and self.last_ok is not None and now - self.last_ok < self.stale_s) # -- reachability ---------------------------------------------------------- -- 2.54.0 From 3083093e22e2e342c860d922e1609a73f77355d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 01:24:36 +0100 Subject: [PATCH 44/55] EV-20 round 3: no non-zero write while the meter is silent (C17); the age pause on a held read (C18) While the meter's age is past meter_max_age_s, or on a held charger read, Solar sends no non-zero current: no retry, no raise, no phase change begun, and a phase change under way ends at its 0 A. 0 A is always allowed. On a held read Solar still steps (Manual does not), so a pause due then is not slipped. Rows in test_ev20_rig.py section 8. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 10 ++++ goodwe_controller/app/carmode.py | 29 ++++++++-- goodwe_controller/app/ctl_car.py | 22 +++++-- goodwe_controller/test_ev20_rig.py | 57 +++++++++++++++++++ 4 files changed, 109 insertions(+), 9 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 061d8e1..7830e24 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -161,4 +161,14 @@ one small set of facts and derives every path from them: meter's age: unknown since the age passed `meter_max_age_s`, so 0 A when the age reaches `meter_max_age_s` + `ev_pause_min` (330 s), checked every control cycle (bound 330 s + one cycle). Arrival sources are unchanged. +- **No non-zero write while the meter is silent (SPIKE-06 C17, N8 strict):** + while the meter's age is past `meter_max_age_s`, Solar sends no non-zero + current: no retry, no raise, no phase change begun, and a phase change + under way ends at its 0 A (no select after that, no closing current); the + plan pauses. 0 A is always allowed. Also on a held read (`nz_block`). +- **The age pause on a held read (C18):** on a held cycle Solar still steps + (Manual does not), so a pause due on that cycle is not slipped; it can only + write 0 A there. +- **Accepted (PM, P9g):** a frozen charger that also stops answering is + flagged only once it answers again; the 15 s safe path covers the gap. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index f82465e..3450d77 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -498,12 +498,15 @@ class SunInputs: def __init__(self, target_w=None, hold=False, auto=True, start_s=120.0, pause_s=300.0, spare_w=None, room_w=0.0, margin_w=100.0, - first=DEFAULT_FIRST, unknown_s=0.0): + first=DEFAULT_FIRST, unknown_s=0.0, silent=False): self.target_w, self.hold, self.auto = target_w, hold, auto # EV-20 rig round 2: how long the sun has already been unknown when # the cause is the meter's own age (`ha_signed`): the pause is timed # from that age, not from the cycle that noticed it. self.unknown_s = unknown_s + # EV-20 SPIKE-06 C17 (N8): the meter is known silent (its age past + # `meter_max_age_s`): no non-zero current goes out, only 0 A. + self.silent = silent self.start_s, self.pause_s = start_s, pause_s self.spare_w, self.room_w, self.margin_w = spare_w, room_w, margin_w self.first = first @@ -730,6 +733,7 @@ class SolarWriter(ManualWriter): self.stuck_starts = 0 # SPIKE-06 C12: starts under one stuck verdict self.stuck_wait = None # ... used up: the next start not before self.stuck_warned = False # ... and its one CHARGER_REFUSED was given + self.nz_block = False # C17/C18: this step writes 0 A at most def owe_start(self) -> None: """C1: the add-on starts in Off while an exit 0 A of its own was still @@ -837,6 +841,8 @@ class SolarWriter(ManualWriter): `MAX_TRIES` and never waits (0 A is the safe side).""" if self.hold: return + if want > TOL_A and self.nz_block: + return # C17/C18: 0 A only, no retry or raise if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A: if self.taken or self.gave_up or ( self.fail_at is not None @@ -985,11 +991,17 @@ class SolarWriter(ManualWriter): # ------------------------------------------------------------- step async def step(self, drv, r, *, mode, sun, clamp, now, tracker, writing, - status, clock=None): + status, clock=None, held=False): """One cycle. `sun` is `SunInputs` (None outside Solar); `writing` is False in shadow mode, while control is stopped, under a safety stop - and while stopping.""" + and while stopping. `held`: the charger missed this read and the last + reading stands in (EV-20 round 2): the step may pause, never raise.""" self._clock = clock or (lambda: now) + # SPIKE-06 C17/C18: while the meter is silent, or on a held read, no + # non-zero current goes out (no retry, no raise, no closing current + # of a phase change); 0 A always may. + self.nz_block = bool(held or (sun is not None + and getattr(sun, "silent", False))) entering = mode == SOLAR and self.mode_was != SOLAR self.mode_was = mode if entering: @@ -1130,6 +1142,15 @@ class SolarWriter(ManualWriter): gap = self._gap_ok(now) if self.sent_a == 0.0 and not self.taken: self.plan.ok_since = None # 0 A first, then the start rule + if self.seq is not None and self.nz_block: + # C17: a phase change under way ends at its 0 A; no select and no + # closing current while the meter is silent. The plan pauses and + # starts again by the start rule. + self.seq = None + self.plan.end_switch(False) + self.plan.pause("unknown") + await self._put(drv, 0.0, cur, now, tracker) + return if self.seq is not None: self._plan_step(sun, now, clamp, self.plan.n, gap) if self.plan.a < CH.MIN_A: @@ -1172,7 +1193,7 @@ class SolarWriter(ManualWriter): return self._plan_step(sun, now, clamp, n_now, gap) want = self.amps_out(clamp) - if want >= CH.MIN_A and self.plan.switch \ + if want >= CH.MIN_A and self.plan.switch and not self.nz_block \ and self.plan.n != n_now and not self.single: if self.gave_up or (self.fail_at is not None and now - self.fail_at < RETRY_S): diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index cbee191..c789df7 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -368,13 +368,15 @@ class CarMixin: cycle's read did) and writes only through `carmode`'s writers.""" if not self.charger.configured(): return - if self.car.held: + held = bool(self.car.held) + now = self.car_now() + if held and self.car_mode != carmode.SOLAR \ + and not self.car_solar.engaged: # EV-20 rig round 2 (PM): the charger missed a read for less than # `stale_input_s`; the last trusted figure stands and nothing is # decided or written from the gap. return - now = self.car_now() - if self.car_mode != carmode.SOLAR: + if self.car_mode != carmode.SOLAR and not held: await self.car_writer.step( self.charger, self.car.reading, mode=self.car_mode, want_a=self.car_a, want_phases=self.car_n, rev=self.car_rev, @@ -394,7 +396,7 @@ class CarMixin: sun=sun, clamp=self.car_clamp(), now=now, tracker=self.car, writing=self.car_writing(), status=self.car.status(now, True), - clock=self.car_now) + clock=self.car_now, held=held) # ------------------------------------------------------- EV-20: Solar def car_may_charge(self, inv) -> bool: @@ -458,7 +460,17 @@ class CarMixin: start_s=60.0 * carmode.solar_option(o, "ev_start_min"), pause_s=60.0 * carmode.solar_option(o, "ev_pause_min"), spare_w=spare, room_w=room, margin_w=margin, first=self.car_first, - unknown_s=self._car_meter_over_s() if spare is None else 0.0) + unknown_s=self._car_meter_over_s() if spare is None else 0.0, + silent=self._car_meter_silent()) + + def _car_meter_silent(self) -> bool: + """SPIKE-06 C17 (N8): is the meter known silent (its age past + `meter_max_age_s`)? Then Solar writes no non-zero current.""" + if not self.p1_enabled: + return False + age = self.p1.age_s() + bound = float(self.o.get("meter_max_age_s", 30) or 30) + return age is not None and age > bound def _car_meter_over_s(self) -> float: """EV-20 rig round 2 (PM): on `ha_signed`, how far the meter's age is diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py index 18cf734..3532cf0 100644 --- a/goodwe_controller/test_ev20_rig.py +++ b/goodwe_controller/test_ev20_rig.py @@ -616,4 +616,61 @@ check(f"ha_signed: 40 s after the meter went silent Solar is told the sun " f"has been unknown for 10 s ({seen})", seen.get("u") is not None and 9.0 <= seen["u"] <= 12.0) +# =========================================================================== # +print("\n8. SPIKE-06 ROUND 3: NO NON-ZERO WRITE WHILE THE METER IS SILENT (C17);") +print(" THE AGE PAUSE ON A HELD READ (C18)") +# =========================================================================== # +# C17 (a): 7 A, a raise to 10 A at 340 s that the charger ignores, the meter +# silent from 345 s (ha_signed). No re-send of the 10 A (the retry would come +# at 400 s, meter age 55 s); 0 A when the age reaches 330 s. +sim = TSim(setpoint_a=0, windows=[(335.0, 350.0, "ignore")]) +r = S.drive(const(500.0), lambda t: 3000.0 if t >= 340 else 2300.0, + dur=900, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, + opts={"ev_phases": "1"}, + events={345: lambda p, c: setattr(p, "meter_on", False)}) +w = cur_writes(r) +nz = [(t, a) for t, a, _ in w if a > 0.0 and t > 345 + 30] +z = [t for t, a, _ in w if a == 0.0 and t > 345] +raise_ = [(t, a, ok) for t, a, ok in w if 330 <= t <= 345] +check(f"C17 (a): an ignored raise ({raise_}), then the meter silent from " + f"345 s: no re-send while it is silent ({nz}), 0 A at meter age 330 " + f"(+2) ({z[:1]})", + present(nth(raise_, 0)) and nth(raise_, 0)[2] is False and nz == [] + and present(nth(z, 0)) and 345 + 329 <= nth(z, 0) <= 345 + 333) +nevers(r, "C17 (a)") + +# C17 (b): a 1 -> 3 phase change starts at 301 s (its 0 A); the meter has been +# silent since 276 s, so its age passes 30 s at 307 s, before the closing +# current (313 s without silence). The change ends at its 0 A: no closing +# current, nothing non-zero until the meter is back. +r = S.drive(const(500.0), const(7600.0), dur=900, first="car", + socs={"a": 100.0, "b": 100.0}, car_phases=3, + events={276: lambda p, c: setattr(p, "meter_on", False), + 800: lambda p, c: setattr(p, "meter_on", True)}) +w = cur_writes(r) +seq0 = [t for t, a, _ in w if a == 0.0 and 295 <= t <= 305] +nz = [(t, a) for t, a, _ in w if a > 0.0 and 306 < t < 800] +check(f"C17 (b): a phase change under way when the meter goes silent ends at " + f"its 0 A ({seq0}): no closing current, no non-zero write while silent " + f"({nz}); writes {w[:6]}", + present(nth(seq0, 0)) and nz == [] + and [a for t, a, _ in w if 301 <= t < 800][-1:] == [0.0]) +nevers(r, "C17 (b)") + +# C18: a charger read gap on the very cycle the age pause is due (ha_signed, +# meter silent from 300 s: due at 629 s without a gap, the meter's last sample +# being at 299 s). The held cycle still steps Solar's pause: 0 A at 629 s, at +# most one cycle later (f625011: 631 s with the gap from 629 s). +for gap_at in (629, 630): + r = S.drive(const(500.0), const(2900.0), dur=760, first="car", + socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, + events={300: lambda p, c: setattr(p, "meter_on", False), + gap_at: lambda p, c: p.ch.go_unavailable(), + gap_at + 2: lambda p, c: p.ch.go_unavailable(False)}) + w = cur_writes(r) + z = [t for t, a, _ in w if a == 0.0 and t > 300] + check(f"C18: a 2-sample read gap from {gap_at} s, the age pause due at " + f"629 s: 0 A at {z[:1]} (629-630)", + present(nth(z, 0)) and 629 <= nth(z, 0) <= 630) + report() -- 2.54.0 From 0ef8de26cba626751e1df7f53c31029b723265b4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 02:05:05 +0100 Subject: [PATCH 45/55] EV-20 round 3: on a held read Solar writes only a new 0 A, no retry A retry on a held cycle went to a charger that was not answering and changed the try count (test_ev20_fuzz T54 N14, seed 1). Held cycles now allow only a new 0 A decision, such as the age pause. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/DECISIONS/EV-20-solar-mode.md | 2 +- goodwe_controller/app/carmode.py | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 7830e24..c5bb9cf 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -168,7 +168,7 @@ one small set of facts and derives every path from them: plan pauses. 0 A is always allowed. Also on a held read (`nz_block`). - **The age pause on a held read (C18):** on a held cycle Solar still steps (Manual does not), so a pause due on that cycle is not slipped; it can only - write 0 A there. + write a NEW 0 A there (no retry to a charger that is not answering). - **Accepted (PM, P9g):** a frozen charger that also stops answering is flagged only once it answers again; the 15 s safe path covers the gap. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 3450d77..429e195 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -734,6 +734,7 @@ class SolarWriter(ManualWriter): self.stuck_wait = None # ... used up: the next start not before self.stuck_warned = False # ... and its one CHARGER_REFUSED was given self.nz_block = False # C17/C18: this step writes 0 A at most + self.held_step = False # C18: a held read: only a NEW 0 A goes out def owe_start(self) -> None: """C1: the add-on starts in Off while an exit 0 A of its own was still @@ -844,6 +845,8 @@ class SolarWriter(ManualWriter): if want > TOL_A and self.nz_block: return # C17/C18: 0 A only, no retry or raise if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A: + if self.held_step: + return # C18: no retry to a charger not answering if self.taken or self.gave_up or ( self.fail_at is not None and now - self.fail_at < RETRY_S): @@ -1002,6 +1005,7 @@ class SolarWriter(ManualWriter): # of a phase change); 0 A always may. self.nz_block = bool(held or (sun is not None and getattr(sun, "silent", False))) + self.held_step = bool(held) entering = mode == SOLAR and self.mode_was != SOLAR self.mode_was = mode if entering: -- 2.54.0 From 6fbf2600f9193f3bdff55264455a76e4546ff549 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 03:19:19 +0100 Subject: [PATCH 46/55] EV-20 C19: a held read does nothing to a phase change under way The C17 branch (end a phase change at its 0 A and pause) ran on a held read too, so one failed read just after a select stopped the car for the 600 s phase gap. A held read now leaves the change alone; it goes on at the next real reading. The silent meter still ends it at its 0 A. Rows: test_ev20_rig section 9. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 6 +++ goodwe_controller/app/carmode.py | 5 +++ goodwe_controller/test_ev20_rig.py | 40 +++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index c5bb9cf..8203fcb 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -171,4 +171,10 @@ one small set of facts and derives every path from them: write a NEW 0 A there (no retry to a charger that is not answering). - **Accepted (PM, P9g):** a frozen charger that also stops answering is flagged only once it answers again; the 15 s safe path covers the gap. +- **A held read during a phase change (SPIKE-06 C19):** a phase change under + way does nothing on a held read (no write, no pause) and goes on at the next + real reading; it ends at its 0 A only while the meter is silent (C17). No + phase change begins on a held cycle; a gap of `stale_input_s` or more takes + the safe path unchanged. Accepted by design (PM): a one-sample partial + reading (only power unavailable, say) still gives the D2 0 A. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 429e195..38ea06b 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -1146,6 +1146,11 @@ class SolarWriter(ManualWriter): gap = self._gap_ok(now) if self.sent_a == 0.0 and not self.taken: self.plan.ok_since = None # 0 A first, then the start rule + if self.seq is not None and self.held_step: + # SPIKE-06 C19: a held read decides nothing for a phase change + # under way (no write, no pause); it goes on at the next real + # reading. A gap that reaches `stale_input_s` takes the safe path. + return if self.seq is not None and self.nz_block: # C17: a phase change under way ends at its 0 A; no select and no # closing current while the meter is silent. The plan pauses and diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py index 3532cf0..d6f0826 100644 --- a/goodwe_controller/test_ev20_rig.py +++ b/goodwe_controller/test_ev20_rig.py @@ -673,4 +673,44 @@ for gap_at in (629, 630): f"629 s: 0 A at {z[:1]} (629-630)", present(nth(z, 0)) and 629 <= nth(z, 0) <= 630) +# =========================================================================== # +print("\n9. SPIKE-06 C19: A READ GAP DURING A PHASE CHANGE") +# =========================================================================== # +# The C17 (b) shape without the silent meter: a 1 -> 3 change, its 0 A at +# 301 s, select 3, closing current at 313 s. One to six failed charger reads +# right after the select change nothing: the closing current comes on time +# and no pause follows (0ef8de2: paused, no current until about 914 s). +def phase_run(events): + return S.drive(const(500.0), const(7600.0), dur=700, first="car", + socs={"a": 100.0, "b": 100.0}, car_phases=3, + events=events) + + +for n in (1, 2, 6): + r = phase_run({305: lambda p, c: p.ch.go_unavailable(), + 305 + n: lambda p, c: p.ch.go_unavailable(False)}) + w = cur_writes(r) + close = [(t, a) for t, a, _ in w if a > 0.0 and 301 < t < 700] + check(f"C19: {n} failed read(s) at 305 s, just after the select: the " + f"closing current on time ({close[:2]}), no pause ({w[:5]})", + present(nth(close, 0)) and 312 <= nth(close, 0)[0] <= 313 + n + and [a for t, a, _ in w if 301 < t < 700 and a == 0.0] == []) + nevers(r, f"C19 gap {n}") +# A gap of stale_input_s or more during the change: the safe path as before. +# The charger is taken as gone: nothing while it is away and no closing +# current; on its return the change is dropped and Solar starts over (0 A +# first, already standing here, so nothing is written; then the start rule, +# which on the 3 phases the select left waits for the phase gap). +r = phase_run({305: lambda p, c: p.ch.go_unavailable(), + 322: lambda p, c: p.ch.go_unavailable(False)}) +w = cur_writes(r) +during = [(t, a) for t, a, _ in w if 305 <= t < 322] +after = [(t, a) for t, a, _ in w if t >= 322] +check(f"C19: a 17 s gap during the change takes the safe path: nothing while " + f"away ({during}), no closing current, nothing non-zero before the " + f"start rule after the return ({after[:2]})", + during == [] and not [1 for t, a in after if a > 0.0 and t < 322 + 115] + and r["c"].car_solar.seq is None) +nevers(r, "C19 long gap") + report() -- 2.54.0 From 0cfb99ed6513e1852c6db72dde72b0c2096c8f79 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 06:54:07 +0100 Subject: [PATCH 47/55] EV-20 review r3: a held read moves no plan count; only the meter-age pause may fire On a held charger read no writer steps and the Solar plan does nothing: no phase change or switching start begins, no _set or end_switch, ok_since, up_since, down_since, low_since and set_at stay, and the hold pause does not fire; a decision due then runs on the next real reading. The one exception is the pause by the meter's age (C18, SolarWriter.held_pause). Rows: the reviewer's three shapes with 1- and 2-read gaps on and before the decision cycle, and the hold pause on a held cycle. DECISIONS wording fixed. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 15 ++-- goodwe_controller/app/carmode.py | 20 +++++ goodwe_controller/app/ctl_car.py | 22 ++++-- goodwe_controller/test_ev20_rig.py | 74 +++++++++++++++++++ 4 files changed, 118 insertions(+), 13 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 8203fcb..394fe7b 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -152,8 +152,11 @@ one small set of facts and derives every path from them: that got no answer, or every required entity unavailable; one entity missing, a wrong power unit or the login off stay readings of their own (EV-03 round 4, unchanged); nothing is decided - or written in that cycle (`ctl_car.car_step` returns), and it neither arms - nor clears the stuck check. At `stale_input_s` the missing reading is taken + or written in that cycle: no writer steps (`ctl_car.car_step` returns), no + plan count moves (start, phase change, hold, `set_at`) and a decision due + then runs on the next real reading (review r3, PM design). The one + exception is Solar's pause by the meter's age (C18, `held_pause`). It + neither arms nor clears the stuck check. At `stale_input_s` the missing reading is taken as before (the safe path: the charger is gone, 0 A first on its return). This also ends the false PEAK_GUARD_FLOOR_LIMITED after one gap (EV-18 T10(b) changed accordingly). @@ -166,9 +169,11 @@ one small set of facts and derives every path from them: current: no retry, no raise, no phase change begun, and a phase change under way ends at its 0 A (no select after that, no closing current); the plan pauses. 0 A is always allowed. Also on a held read (`nz_block`). -- **The age pause on a held read (C18):** on a held cycle Solar still steps - (Manual does not), so a pause due on that cycle is not slipped; it can only - write a NEW 0 A there (no retry to a charger that is not answering). +- **The age pause on a held read (C18):** on a held cycle Solar does not step + (review r3, PM design); only `held_pause` runs: while the meter is silent + and its age has reached `meter_max_age_s` + `ev_pause_min`, the plan pauses + and a NEW 0 A goes out (no retry to a charger that is not answering). No + phase change, start, hold pause or other count moves on a held cycle. - **Accepted (PM, P9g):** a frozen charger that also stops answering is flagged only once it answers again; the 15 s safe path covers the gap. - **A held read during a phase change (SPIKE-06 C19):** a phase change under diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 38ea06b..c67e4fb 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -993,6 +993,26 @@ class SolarWriter(ManualWriter): "prev": None, "from": r.phases_allowed} # ------------------------------------------------------------- step + async def held_pause(self, drv, r, *, sun, now, tracker) -> None: + """EV-20 (C18, PM design r3): on a held charger read only the pause by + the meter's age may come (0 A): nothing else in the plan moves, no + phase change begins or goes on, no retry. Called instead of `step`.""" + if not self.engaged or self.seq is not None or self.hold \ + or self.fault is not None or self.restart \ + or self.plan.a <= 0.0 or self.plan.switch: + return + if not getattr(sun, "silent", False) \ + or getattr(sun, "unknown_s", 0.0) < sun.pause_s: + return + self.nz_block = self.held_step = True + try: + self.plan.pause("unknown") + cur = None if r is None else ( + r.allowed_a if r.allowed_a is not None else r.setpoint_a) + await self._put(drv, 0.0, cur, now, tracker) + finally: + self.nz_block = self.held_step = False + async def step(self, drv, r, *, mode, sun, clamp, now, tracker, writing, status, clock=None, held=False): """One cycle. `sun` is `SunInputs` (None outside Solar); `writing` is diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index c789df7..6796016 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -370,11 +370,21 @@ class CarMixin: return held = bool(self.car.held) now = self.car_now() - if held and self.car_mode != carmode.SOLAR \ - and not self.car_solar.engaged: + sun = None + if self.car_mode == carmode.SOLAR: + sun = getattr(self, "_car_sun_now", None) \ + or self.car_sun_inputs(now) + if held: # EV-20 rig round 2 (PM): the charger missed a read for less than # `stale_input_s`; the last trusted figure stands and nothing is - # decided or written from the gap. + # decided or written from the gap. No writer steps and no plan + # count (start, phase change, hold) moves (review r3, PM design); + # a decision due now runs on the next real reading. The one + # exception: Solar's pause by the meter's age (C18). + if sun is not None and self.car_writing(): + await self.car_solar.held_pause( + self.charger, self.car.reading, sun=sun, now=now, + tracker=self.car) return if self.car_mode != carmode.SOLAR and not held: await self.car_writer.step( @@ -387,16 +397,12 @@ class CarMixin: if self.car_mode == carmode.SOLAR or w.engaged: # C6: one write clock: Manual's latest non-zero write counts. w.other_at = self.car_writer.nonzero_at - sun = None - if self.car_mode == carmode.SOLAR: - sun = getattr(self, "_car_sun_now", None) \ - or self.car_sun_inputs(now) await w.step( self.charger, self.car.reading, mode=self.car_mode, sun=sun, clamp=self.car_clamp(), now=now, tracker=self.car, writing=self.car_writing(), status=self.car.status(now, True), - clock=self.car_now, held=held) + clock=self.car_now) # ------------------------------------------------------- EV-20: Solar def car_may_charge(self, inv) -> bool: diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py index d6f0826..f85dcdd 100644 --- a/goodwe_controller/test_ev20_rig.py +++ b/goodwe_controller/test_ev20_rig.py @@ -713,4 +713,78 @@ check(f"C19: a 17 s gap during the change takes the safe path: nothing while " and r["c"].car_solar.seq is None) nevers(r, "C19 long gap") +# =========================================================================== # +print("\n10. REVIEW R3: A HELD READ ON A DECISION CYCLE (PM design)") +# =========================================================================== # +# The reviewer's three shapes (house 500 W, Car first, 3-phase car). A 1- or +# 2-sample read gap on the cycle a phase change or a switching start is due, +# or on the cycle before it: the decision waits for the next real reading and +# every write lands within 2 s of the run without the gap (a60ebd3: the wait +# restarted, and 3 -> 1 became a 0 A pause in full sun). +def sun_b(t): + return 7600.0 if t < 1000 else (300.0 if t < 1400 else 2600.0) + + +SHAPES = (("A 1 -> 3", const(7600.0), 700, 301), + ("B a start that needs 3 -> 1", sun_b, 1900, 1521), + ("C 3 -> 1", lambda t: 7600.0 if t < 1000 else 4300.0, 1700, 1301)) + + +def shape_run(sunf, dur, events=None): + return S.drive(const(500.0), sunf, dur=dur, first="car", + socs={"a": 100.0, "b": 100.0}, car_phases=3, + events=events or {}) + + +def after(r, t0, t1): + return [(t, a) for t, a, _ in cur_writes(r) if t0 <= t < t1] + + +for name, sunf, dur, d in SHAPES: + twin = after(shape_run(sunf, dur), d - 5, d + 200) + for off in (-1, 0): + for n in (1, 2): + g = d + off + r = shape_run(sunf, dur, + {g: lambda p, c: p.ch.go_unavailable(), + g + n: lambda p, c: p.ch.go_unavailable(False)}) + got = after(r, d - 5, d + 200) + same = (len(got) == len(twin) and all( + a1 == a2 and abs(t1 - t2) <= 2.0 + for (t1, a1), (t2, a2) in zip(got, twin))) + check(f"review r3 [{name}] {n}-read gap at {g} (decision due " + f"{d}): the writes of the run without the gap, within 2 s " + f"({got[:4]} vs {twin[:4]})", same and bool(twin)) + nevers(r, f"review r3 [{name}] gap {n} at {g}") + +# The hold's pause (low_since past ev_pause_min) never fires on a held cycle: +# it comes on the next real reading, and only if that reading still says low. +base = S.drive(const(500.0), lambda t: 900.0 if t >= 400 else 2900.0, + dur=900, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_phases": "1"}) +z0 = nth([t for t, a, _ in cur_writes(base) if a == 0.0 and t > 400], 0) +check(f"hold twin: 0 A at {z0} (300 s from the drop at 400, +2)", + present(z0) and 699 <= z0 <= 702) +if present(z0): + zi = int(z0) + r = S.drive(const(500.0), lambda t: 900.0 if t >= 400 else 2900.0, + dur=900, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_phases": "1"}, + events={zi: lambda p, c: p.ch.go_unavailable(), + zi + 1: lambda p, c: p.ch.go_unavailable(False)}) + z = [t for t, a, _ in cur_writes(r) if a == 0.0 and t > 400] + check(f"hold pause due on a held read ({zi}): 0 A on the next real " + f"reading ({z[:1]}), not on the held cycle", + present(nth(z, 0)) and nth(z, 0) == zi + 1) + r = S.drive(const(500.0), + lambda t: 900.0 if 400 <= t < zi else 2900.0, + dur=900, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_phases": "1"}, + events={zi: lambda p, c: p.ch.go_unavailable(), + zi + 1: lambda p, c: p.ch.go_unavailable(False)}) + z = [t for t, a, _ in cur_writes(r) if a == 0.0 and t > 400] + check(f"hold pause due on a held read ({zi}), the sun back from that " + f"second, so the next real reading ({zi + 1}) is not low: no pause " + f"({z[:1]})", z == []) + report() -- 2.54.0 From 4dc030929a9fe9bceb2116da48b912826d08a990 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 09:40:31 +0100 Subject: [PATCH 48/55] EV-20 review r4: wording only (DECISIONS held-read sentence, step docstring) Co-Authored-By: Claude --- goodwe_controller/DECISIONS/EV-20-solar-mode.md | 6 +++--- goodwe_controller/app/carmode.py | 4 +++- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 394fe7b..044b62c 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -155,9 +155,9 @@ one small set of facts and derives every path from them: or written in that cycle: no writer steps (`ctl_car.car_step` returns), no plan count moves (start, phase change, hold, `set_at`) and a decision due then runs on the next real reading (review r3, PM design). The one - exception is Solar's pause by the meter's age (C18, `held_pause`). It - neither arms nor clears the stuck check. At `stale_input_s` the missing reading is taken - as before (the safe path: the charger is gone, 0 A first on its return). + exception is Solar's pause by the meter's age (C18, `held_pause`). A held + read neither arms nor clears the stuck check. At `stale_input_s` the + missing reading is taken as before (the safe path: the charger is gone, 0 A first on its return). This also ends the false PEAK_GUARD_FLOOR_LIMITED after one gap (EV-18 T10(b) changed accordingly). - **Silent meter on `ha_signed`:** Solar's unknown-sun pause is timed from the diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index c67e4fb..410dcb1 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -1018,7 +1018,9 @@ class SolarWriter(ManualWriter): """One cycle. `sun` is `SunInputs` (None outside Solar); `writing` is False in shadow mode, while control is stopped, under a safety stop and while stopping. `held`: the charger missed this read and the last - reading stands in (EV-20 round 2): the step may pause, never raise.""" + reading stands in (EV-20 round 2): the step may pause, never raise. + `ctl_car.car_step` no longer passes it (review r3): on a held cycle + only `held_pause` runs.""" self._clock = clock or (lambda: now) # SPIKE-06 C17/C18: while the meter is silent, or on a held read, no # non-zero current goes out (no retry, no raise, no closing current -- 2.54.0 From 68856bc3a041513f7bbf20c107a99a837be0b113 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Tue, 24 Nov 2026 17:11:44 +0100 Subject: [PATCH 49/55] EV-51: Solar decides every meter-age rule on the writer step's own age; DEBUG line per step The writer step took the meter age from the snapshot of the previous cycle (silent / unknown_s / hold), so in production order the silent-meter pause came one cycle late (C21) and a start or raise could still be written at an own age of 31-39 s (C22, N8). The step now judges its own age: the pause timing and held_pause, the non-zero write block (nz_block), and the late-readings hold with its stale rule. Meter values stay from the snapshot; car.held / car.reading and the arrival sources' spare-unknown check are unchanged. Also: one DEBUG line per Solar writer step (time, meter age, decision, write); tools/ev20_sun.drive takes cyc / phase / jitter / cset (default unchanged); test_ev51.py (T1-T43, N1-N12); DECISIONS states the rule once. Co-Authored-By: Claude Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 18 +- goodwe_controller/app/carmode.py | 18 +- goodwe_controller/app/ctl_car.py | 67 +- goodwe_controller/app/ctl_cycle.py | 1 + goodwe_controller/test_ev51.py | 872 ++++++++++++++++++ goodwe_controller/tools/ev20_sun.py | 47 +- 6 files changed, 1012 insertions(+), 11 deletions(-) create mode 100644 goodwe_controller/test_ev51.py diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 044b62c..4baec40 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -161,9 +161,21 @@ one small set of facts and derives every path from them: This also ends the false PEAK_GUARD_FLOOR_LIMITED after one gap (EV-18 T10(b) changed accordingly). - **Silent meter on `ha_signed`:** Solar's unknown-sun pause is timed from the - meter's age: unknown since the age passed `meter_max_age_s`, so 0 A when the - age reaches `meter_max_age_s` + `ev_pause_min` (330 s), checked every - control cycle (bound 330 s + one cycle). Arrival sources are unchanged. + meter's age: unknown since the age passed `meter_max_age_s`, so 0 A on the + first car step whose own meter age (now minus the last reading, at that + step) is >= `meter_max_age_s` + `ev_pause_min` (330 s), held steps included. + Arrival sources are unchanged. +- **EV-51: decided at the step's own meter age.** Every decision that rests on + the meter's AGE is taken at the writer step's own age, not at the age the + cycle saw one step earlier: the pause above, the write block while the meter + is silent (no non-zero current, C17), the held-read pause (C18) and the + late-readings hold with its stale rule (a spare read while the hold was on + is not used once the step's own late time reaches `stale_input_s`). The + meter's VALUES (spare, target) stay the cycle's, one cycle of sensor latency + being normal; `car.held` and `car.reading` are unchanged. Arrival sources + keep the cycle's age for their "spare unknown" check. At log level debug + each Solar step logs one line: time, the meter age at the step, the decision + and the write. - **No non-zero write while the meter is silent (SPIKE-06 C17, N8 strict):** while the meter's age is past `meter_max_age_s`, Solar sends no non-zero current: no retry, no raise, no phase change begun, and a phase change diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 410dcb1..bf12a17 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -498,8 +498,13 @@ class SunInputs: def __init__(self, target_w=None, hold=False, auto=True, start_s=120.0, pause_s=300.0, spare_w=None, room_w=0.0, margin_w=100.0, - first=DEFAULT_FIRST, unknown_s=0.0, silent=False): + first=DEFAULT_FIRST, unknown_s=0.0, silent=False, + meter_back=False, age_s=None): self.target_w, self.hold, self.auto = target_w, hold, auto + # EV-51: the meter's own age at the writer step (None: no reading), and + # `meter_back`: the cycle's snapshot said "meter too old" but the step's + # own age says a new reading came, so no unknown timer is carried over. + self.meter_back, self.age_s = meter_back, age_s # EV-20 rig round 2: how long the sun has already been unknown when # the cause is the meter's own age (`ha_signed`): the pause is timed # from that age, not from the cycle that noticed it. @@ -570,11 +575,15 @@ class SolarPlan: self.switch, self._before = False, None def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s, - hold=False, gap_ok=True, unknown_s=0.0): + hold=False, gap_ok=True, unknown_s=0.0, meter_back=False): """`n_now`: the phases the car draws on now (1 for a one-phase car); `auto`: Solar may choose the phases; `gap_ok`: a phase change is allowed now (EV-04's one per `PHASE_GAP_S`); `hold`: readings late - under the stale bound, everything stands.""" + under the stale bound, everything stands. `meter_back` (EV-51): the + meter's own age is fresh again at this step: the unknown timer that + counted its silence starts over.""" + if meter_back: + self.unknown_since = None if hold: # Readings late under the stale bound: nothing changes, but a # hold or an unknown spare that has run its time still pauses @@ -937,7 +946,8 @@ class SolarWriter(ManualWriter): now, target_w=sun.target_w, hold=sun.hold, n_now=n_now, auto=sun.auto and not self.single and not self.phases_gave_up, clamp=clamp, start_s=sun.start_s, pause_s=sun.pause_s, - gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0)) + gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0), + meter_back=getattr(sun, "meter_back", False)) @staticmethod def _drawing(r) -> bool: diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 6796016..120a8dd 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -10,6 +10,7 @@ the guard treats a Solar car exactly as a Manual car). """ import asyncio +import copy import dataclasses import logging from datetime import timezone @@ -83,6 +84,7 @@ class CarMixin: self.car_first = first if first in carmode.FIRSTS \ else carmode.DEFAULT_FIRST self._car_late_s = None # EV-20: the cycle's late verdict + self._car_late_mono = None # ... and the time it was read (EV-51) self._car_sun_now = None # ... and Solar's inputs of that cycle sun = data.get(CAR_SUN_KEY) self.car_sun = {"day": None, "kwh": 0.0} @@ -372,8 +374,69 @@ class CarMixin: now = self.car_now() sun = None if self.car_mode == carmode.SOLAR: - sun = getattr(self, "_car_sun_now", None) \ - or self.car_sun_inputs(now) + sun = self.car_sun_own(getattr(self, "_car_sun_now", None) + or self.car_sun_inputs(now), now) + w0 = self.car_solar + a0, n_log = w0.plan.a, len(w0.log) + await self._car_step_run(held, now, sun) + if sun is not None and _LOG.isEnabledFor(logging.DEBUG): + self._car_step_debug(held, now, sun, a0, n_log) + + def _car_step_debug(self, held, now, sun, a0, n_log) -> None: + """EV-51: one DEBUG line per Solar writer step: the time, the meter's + age at the step, what was decided and what was written. Nothing at + info and above; no secrets in it.""" + w = self.car_solar + a1 = w.plan.a + if a0 > 0.0 and a1 <= 0.0: + what = "pause" + elif held: + what = "wait-held" + elif sun.hold: + what = "hold" + elif a0 <= 0.0 and a1 > 0.0: + what = "start" + elif a1 > a0 + carmode.TOL_A: + what = "raise" + elif a1 < a0 - carmode.TOL_A: + what = "lower" + elif sun.target_w is None: + what = "wait-unknown" + else: + what = "steady" + sent = [] + for kind, v, _t, ok in w.log[n_log:]: + if kind == "current": + sent.append(f"sent {v:g} A" + (" confirmed" if ok else "")) + else: + sent.append(f"phases {v}" + (" confirmed" if ok else "")) + age = sun.age_s + _LOG.debug("Solar step: t=%.1f age=%s decision=%s write=%s", now, + "none" if age is None else f"{age:.1f}", what, + "; ".join(sent) or "none") + + def car_sun_own(self, snap, now): + """EV-51 (PM): every decision on the meter's AGE is taken at the writer + step's own age (now minus the meter's last reading), not the age the + cycle saw one step earlier: the write block while the meter is silent + (N8), the unknown/pause timing (held reads too) and the late-readings + hold with its stale rule. The meter's VALUES (spare, target) stay the + cycle's; arrival sources' `car_spare_w` keeps the cycle's age.""" + own = copy.copy(snap) + own.silent = self._car_meter_silent() + own.unknown_s = self._car_meter_over_s() + own.age_s = self.p1.age_s() if self.p1_enabled else None + own.meter_back = snap.unknown_s > 0.0 and own.unknown_s <= 0.0 + stale = float(self.o.get("stale_input_s", 15)) + late = self._car_late_s # the verdict stands: it has aged since + if late is not None and self._car_late_mono is not None: + late += max(0.0, now - self._car_late_mono) + own.hold = late is not None and late < stale + if late is not None and late >= stale: + own.spare_w = own.target_w = None # the stale rule, on own late + return own + + async def _car_step_run(self, held, now, sun) -> None: if held: # EV-20 rig round 2 (PM): the charger missed a read for less than # `stale_input_s`; the last trusted figure stands and nothing is diff --git a/goodwe_controller/app/ctl_cycle.py b/goodwe_controller/app/ctl_cycle.py index 59dd444..9a638dd 100644 --- a/goodwe_controller/app/ctl_cycle.py +++ b/goodwe_controller/app/ctl_cycle.py @@ -254,6 +254,7 @@ class CycleMixin: stale_after = float(self.o.get("stale_input_s", 15)) late_s = self._readings_late(site_standing) # SAFETY-128 self._car_late_s = late_s # EV-20: Solar holds, then the stale rule + self._car_late_mono = self._now_mono # EV-51: when that verdict was read self._late_zero = late_s is not None and late_s >= stale_after # ⚠️ `any`, NOT the sole unit's. The hold exists so a single missed # poll does not become a fault; a LATCHED inverter must still reach the diff --git a/goodwe_controller/test_ev51.py b/goodwe_controller/test_ev51.py new file mode 100644 index 0000000..2c3759c --- /dev/null +++ b/goodwe_controller/test_ev51.py @@ -0,0 +1,872 @@ +"""EV-51: every meter-age decision of a Solar writer step is judged on the +step's OWN age (T1-T43; N1-N12 of reports/EV-51-test-plan.md). +`python3 -B test_ev51.py` + +The real Controller on `tools/ev20_sun.py` (the harness now takes a cycle +length, phase, jitter and the production order). "Plain" order: the cycle, +then the writer settles. "Race" order (`race=True`): the production order, the +writer step of a cycle runs beside the NEXT read, so its snapshot is one cycle +old. "Own age" = now minus the meter's last-reading stamp, taken in the writer +step (recorded here by wrapping `Controller.car_step`). + +Shared setup: `ha_signed`, `meter_max_age_s` 30, `ev_pause_min` 5 (bound 330 s), +Car first, both batteries full, house 500 W, sun 2900 W, 1 phase, the car at +10 A from 120 s, the meter silent from t = 300. The last sample before the +silence is ingested at 298.7 (the event runs before that second's submit): the +test takes ages from the steps, not from a constant. + +DEBUG format (T28): one line per Solar writer step, held steps included, + Solar step: t=630.0 age=331.3 decision=pause write=sent 0 A confirmed +decision: steady, wait-unknown, hold, start, raise, lower, pause, wait-held; +write: none, or "sent X A" (a refused try) / "sent X A confirmed", joined by "; ". + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import dataclasses +import logging +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode # noqa: E402 +from app.carmode import SolarPlan # noqa: E402 +from app.main import Controller # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from ev20_kit import * # noqa: E402,F401,F403 +from ev20_kit import LOG, check, fails, report # noqa: E402,F401 +from ev20_kit import TSim, cur_writes, selects # noqa: E402,F401 +from named_absence import nth, present # noqa: E402,F401 + +GOOGLE = logging.getLogger("goodwe") +STEPS = [] +SNAP = {} +_orig_step = Controller.car_step +_orig_kick = Controller.car_kick + + +async def _rec_step(self): + """Records every writer step: its own age (taken before it runs), the + snapshot's, whether the read was held and the current writes it made.""" + w = self.car_solar + snap = getattr(self, "_car_sun_now", None) + age = self.p1.age_s() if self.p1_enabled else None + held = bool(self.car.held) + a0, n0 = w.plan.a, len(w.log) + solar = self.car_mode == carmode.SOLAR + now = self.car_now() + await _orig_step(self) + STEPS.append(dict( + now=now, age=age, held=held, a0=a0, a1=w.plan.a, solar=solar, + snap_age=SNAP.get(id(snap), (None, None))[1], + snap_sil=None if snap is None else snap.silent, + snap_tgt=None if snap is None else snap.target_w, + snap_hold=None if snap is None else snap.hold, + writes=[(x[1], x[2], x[3]) for x in w.log[n0:] if x[0] == "current"], + phases=[x for x in w.log[n0:] if x[0] == "phases"])) + + +def _rec_kick(self): + _orig_kick(self) + sun = getattr(self, "_car_sun_now", None) + if sun is not None: + SNAP[id(sun)] = (sun, self.p1.age_s() if self.p1_enabled else None) + + +Controller.car_step = _rec_step +Controller.car_kick = _rec_kick + +SIL = 300 +FULLB = dict(FULL) +OPT1 = {"ev_phases": "1"} + + +def go(onset=SIL, dur=760, *, sun=2900.0, house=500.0, events=None, opts=None, + first="car", **kw): + """The shared setup: the meter off from `onset`, plain unless race=True. + Returns (run, steps).""" + STEPS.clear() + SNAP.clear() + ev = {} if onset is None else { + onset: lambda p, c: setattr(p, "meter_on", False)} + ev.update(events or {}) + r = S.drive(house if callable(house) else S.const(house), + sun if callable(sun) else S.const(sun), dur=dur, first=first, + socs=dict(FULLB), opts=dict(OPT1, **(opts or {})), events=ev, + **kw) + return r, list(STEPS) + + +def cyc_t(t0, cyc, phase, after): + """The first cycle second at or after `after`.""" + t = t0 + phase + while t < after: + t += cyc + return t + + +def pause_step(steps, bound=330.0, since=SIL): + """(S, previous): S = the first Solar step with own age >= bound.""" + ss = [s for s in steps if s["solar"] and s["age"] is not None + and s["now"] > since] + for i, s in enumerate(ss): + if s["age"] >= bound: + return s, (ss[i - 1] if i else None) + return None, None + + +def timing(steps, bound=330.0, exp_age=None, since=SIL): + """Pass: the plan's current goes from > 0 to 0 in the first step S with + own age >= bound; the step before has age < bound; the 0 A is sent in S + (N2, N7).""" + s, prev = pause_step(steps, bound, since) + if s is None or prev is None: + return False + ok = (s["a0"] > 0.0 and s["a1"] == 0.0 + and any(a == 0.0 for a, _t, _o in s["writes"]) and prev["age"] < bound) + if exp_age is not None: + ok = ok and abs(s["age"] - exp_age) < 0.05 + return ok + + +def n8(steps, limit=30.0): + """N8: non-zero current writes at a step whose own age is > limit.""" + return [(round(s["now"], 1), round(s["age"], 1), a) for s in steps + if s["age"] is not None and s["age"] > limit + for a, _t, _o in s["writes"] if a > 0.0] + + +def common(tag, r, steps, *, solar_steps=True, silent_from=SIL, back=None): + """Every row: cycles > 0 (not vacuous), N8, N1, N4 (no select while the + meter is silent), N6 (no Traceback, no step failure).""" + bad = [] + if not [s for s in steps if s["solar"]]: + bad.append("no Solar step ran") + if n8(steps): + bad.append(("N8", n8(steps)[:2])) + if r["c"].charger.clamp_faults: + bad.append("N1 clamp fault") + over = [x for x in r["sim"].log if x[1] == "current" and x[2] > 16.0] + if over: + bad.append(("N1", over[:1])) + end = back if back is not None else 1e9 + sel = [x[0] for x in selects(r) if silent_from + 31 < x[0] < end] + if sel: + bad.append(("N4", sel[:2])) + n = r.get("_log", 0) + if LOG.tracebacks(n) or [m for m in LOG.since(n) + if "car charger step failed" in m]: + bad.append("N6") + check(f"{tag}: N1, N4, N6, N8 hold, cycles > 0 ({bad[:2]})", not bad) + return not bad + + +def run_log(fn, *a, **kw): + n = LOG.mark() + r, st = fn(*a, **kw) + r["_log"] = n + return r, st + + +def jit(): + return (4, 6, 5, 4, 6, 5, 6) + + +def jit_set(dur): + t, out, i = 0, [], 0 + while t < dur: + out.append(t) + t += jit()[i % len(jit())] + i += 1 + return out + + +def lines(n0=0): + """The parsed DEBUG step lines: [{t, age, decision, write}].""" + out = [] + for lv, m, _x in LOG.rec[n0:]: + g = re.match(r"Solar step: t=(\S+) age=(\S+) decision=(\S+) " + r"write=(.*)$", m) + if lv == "DEBUG" and g: + out.append(dict(t=float(g[1]), + age=None if g[2] == "none" else float(g[2]), + decision=g[3], write=g[4])) + return out + + +def late_at(l0, l1): + """T10/T43: the late verdict stands from l0 (late_s = now - l0) until l1, + set where the controller reads it (`answer.late_s`), not as a constant.""" + def f(p, c): + c.answer.late_s = lambda now: (now - l0) if l0 <= now < l1 else None + return f + + +# =========================================================================== # +print("1. THE PAUSE ON THE FIRST STEP AT OWN AGE >= 330 (T1-T10, T20, T23)") +# =========================================================================== # +for race in (False, True): + tag = "race" if race else "plain" + ok, ages = True, [] + for ph in range(5): + r, st = run_log(go, cyc=5, phase=ph, race=race) + t = cyc_t(0, 5, ph, SIL + 30 + 300 - 1.3) # 628.7 + ok = ok and timing(st, exp_age=t - 298.7) and common( + f"T1 [{tag} ph{ph}]", r, st) + s, _ = pause_step(st) + ages.append(s and round(s["age"], 1)) + check(f"T1 [{tag}]: 5 s cycles, phases 0-4: the 0 A in the first step at " + f"own age >= 330 ({ages}; 331.3 332.3 333.3 334.3 330.3)", + ok and ages == [331.3, 332.3, 333.3, 334.3, 330.3]) + +R3 = {"F-silent-1": (32, [327, 332, 337, 343], 333.3), + "F-silent-2": (35, [327, 332, 336, 340, 345], 333.3), + "F-silent-3": (36, [324, 330, 335, 341], 331.3), + "F-exit": (33, [328, 334, 338], 335.3)} +for name, (first, tail, want) in R3.items(): + ages = list(range(first, tail[0], 5)) + tail + list(range(tail[-1] + 5, 460, 5)) + cset = set(range(0, SIL, 5)) | {int(round(SIL - 1 + 0.7 + a)) for a in ages} + for race in (False, True): + r, st = run_log(go, cset=cset, race=race) + s, _ = pause_step(st) + check(f"T2 [{name} {'race' if race else 'plain'}]: round-3 cadence: " + f"0 A at own age {s and round(s['age'], 1)} (want {want})", + timing(st, exp_age=want) and common("T2", r, st)) + +for race in (False, True): + tag = "race" if race else "plain" + ok = True + for cyc, phs in ((10, range(10)), (14, (0, 7))): + for ph in phs: + r, st = run_log(go, cyc=cyc, phase=ph, race=race, dur=720) + t = cyc_t(0, cyc, ph, 628.7) + ok = ok and timing(st, exp_age=t - 298.7) + check(f"T3 [{tag}]: 10 s cycles phases 0-9, 14 s cycles phases 0 and 7: " + f"the first step at own age >= 330 pauses", ok) + +for race in (False, True): + r, st = run_log(go, cset=set(jit_set(800)), race=race) + check(f"T4 [{'race' if race else 'plain'}]: jittered cycles 4/6/5/4/6/5/6 s: " + f"0 A at own age 332.3 (the silence's first steps do not move it)", + timing(st, exp_age=332.3) and common("T4", r, st)) + +# T5: the boundary: >= and not >, at the plan and at the controller. +def _plan_at(unknown_s, now): + p = SolarPlan(1) + p.a, p.n, p.set_at = 10.0, 1, 0.0 + p.step(now, target_w=None, n_now=1, auto=False, clamp=16.0, start_s=120.0, + pause_s=300.0, unknown_s=unknown_s) + return p.a + + +check("T5 (plan): own age 329.9 over a 30 s bound (unknown 299.9): no pause; " + "own age 330.0 (unknown 300.0): the pause", + _plan_at(299.9, 630.0) == 10.0 and _plan_at(300.0, 630.0) == 0.0) +for race in (False, True): + for ingest, want_t, tag in ((299.1, 629, "329.9"), (300.0, 630, "330.0")): + def _stamp(p, c, ingest=ingest): + c.p1._last = dataclasses.replace(c.p1._last, ingest_mono=ingest) + r, st = run_log(go, dur=700, race=race, + events={SIL: lambda p, c, f=_stamp: ( + setattr(p, "meter_on", False), f(p, c))}) + s, prev = pause_step(st) + z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0 + and x["now"] > SIL] + # ingest 299.1: the step at 629 has age 329.9 (no pause); 630 has 330.9. + # ingest 300.0: the step at 629 has age 329.0, 630 has exactly 330.0. + first_z = z[0]["now"] if z else None + check(f"T5 (controller, {'race' if race else 'plain'}): the sample " + f"stamped {ingest}: the pause is in the step at {want_t + (1 if tag == '329.9' else 0)} " + f"(first 0 A step {first_z}); ages seen {[round(x['age'], 1) for x in st if x['now'] in (629.0, 630.0)]}", + first_z == (630.0 if tag == "329.9" else 630.0) and bool(z)) + +for race in (False, True): + for ret_age, back_at, off_at in ((329, 628, 629), (200, 500, 501)): + r, st = run_log(go, dur=1400, cyc=5, phase=0, race=race, + events={back_at: lambda p, c: setattr(p, "meter_on", True), + off_at: lambda p, c: setattr(p, "meter_on", False)}) + ing = back_at - 0.3 + z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0 and x["now"] > SIL] + want = cyc_t(0, 5, 0, ing + 330.0) + check(f"T6 [{'race' if race else 'plain'}]: the meter back for one " + f"sample at age ~{ret_age}, silent again: no 0 A from the old " + f"silence, the pause at the first step at new own age >= 330 " + f"(t {z[0]['now'] if z else None}, want {want})", + bool(z) and z[0]["now"] == want + and abs(z[0]["age"] - (want - ing)) < 0.05) + +# T7, T8: C18, a held read. +for race in (False, True): + tag = "race" if race else "plain" + g0, g1 = (625, 626) if race else (630, 633) + r, st = run_log(go, dur=760, cyc=5, phase=0, race=race, + events={g0: lambda p, c: p.ch.go_unavailable(), + g1: lambda p, c: p.ch.go_unavailable(False)}) + s, prev = pause_step(st) + check(f"T7 [{tag}]: the charger read held on the step at 630 (own age " + f"331.3): the 0 A in that step ({s and (s['now'], round(s['age'], 1), s['held'], s['writes'])}), " + f"a NEW 0 A, no phase select, nothing else sent", + s is not None and s["held"] and s["now"] == 630.0 + and s["a0"] > 0.0 and s["a1"] == 0.0 + and [a for a, _t, _o in s["writes"]] == [0.0] and not s["phases"]) + common(f"T7 [{tag}]", r, st) + r, st = run_log(go, dur=760, cyc=5, phase=0, race=race, + events={330: lambda p, c: p.ch.go_unavailable(), + 333: lambda p, c: p.ch.go_unavailable(False)}) + check(f"T8 [{tag}] (Q3): the charger away on the first silent cycles " + f"(own age 31-34): the pause at own age 331.3", + timing(st, exp_age=331.3) and common(f"T8 [{tag}]", r, st)) + +r, st = run_log(go, dur=760, cyc=5, phase=0, + events={624: lambda p, c: p.ch.go_unavailable(), + 641: lambda p, c: p.ch.go_unavailable(False)}) +w = [(t, a) for t, a, _ in cur_writes(r)] +away = [x for x in w if 624 <= x[0] < 641] +after = [x for x in w if x[0] >= 641] +check(f"T9: the charger away 17 s from 624 (own age 325-342): the step at 630 is " + f"a held read (6 s, under stale_input_s), so its pause is C18's one 0 A; " + f"nothing else while away ({away}); no non-zero write on the return " + f"({after[:1]}), the 0 A already standing (D2: 0 A first, kept)", + away == [(630.0, 0.0)] and not [x for x in after if x[1] > 0.0] + and common("T9", r, st)) + +for ph in (0, 2, 4): + for race in (False, True): + r, st = run_log(go, dur=760, cyc=5, phase=ph, race=race, + events={0: late_at(600, 700)}) + t = cyc_t(0, 5, ph, 628.7) + check(f"T10 [{'race' if race else 'plain'} ph{ph}]: late readings (5 s) " + f"over 600-700: the hold branch pauses at own age {t - 298.7:.1f}", + timing(st, exp_age=t - 298.7) and common("T10", r, st)) + +# =========================================================================== # +print("\n2. PHASES, GAPS, RETURNS (T11-T19)") +# =========================================================================== # +r = S.drive(S.const(500.0), S.const(7600.0), dur=1100, first="car", + socs=dict(FULLB), car_phases=3, + events={276: lambda p, c: setattr(p, "meter_on", False), + 800: lambda p, c: setattr(p, "meter_on", True)}) +w = cur_writes(r) +seq0 = [t for t, a, _ in w if a == 0.0 and 295 <= t <= 305] +nz = [(t, a) for t, a, _ in w if a > 0.0 and 306 < t < 800] +back = [(t, a) for t, a, _ in w if a > 0.0 and t >= 800] +check(f"T11 (C17 b): a 1 -> 3 change at 301 s with the meter silent from 276: " + f"it ends at its 0 A ({seq0}), no non-zero write 306-800 ({nz}), after " + f"the return only by the start rule ({back[:1]}, >= 920)", + bool(seq0) and not nz and (not back or back[0][0] >= 920 - 1) + and not [x for x in selects(r) if 306 < x[0] < 800]) + +for race in (False, True): + r, st = run_log(go, onset=320, dur=800, cyc=5, phase=0, race=race, + sun=7600.0, car_phases=3, opts={"ev_phases": "auto"}) + s, _ = pause_step(st, since=320) + check(f"T12 [{'race' if race else 'plain'}]: 3-phase car, the meter silent " + f"from 320 s: 3 phases stand; the pause at own age 331.3 (step at 650)", + timing(st, exp_age=331.3, since=320) and common( + "T12", r, st, silent_from=320) + and r["sim"].phases_allowed == 3 and s["now"] == 650.0) + +sim13 = TSim(setpoint_a=0, windows=[(335.0, 350.0, "ignore")]) +for race in (False, True): + r, st = run_log(go, onset=345, dur=900, cyc=5, phase=0, race=race, + sim=TSim(setpoint_a=0, windows=[(335.0, 350.0, "ignore")]), + sun=lambda t: 3000.0 if t >= 340 else 2300.0) + nzr = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > 345 + 30] + check(f"T13 [{'race' if race else 'plain'}]: an ignored raise to 10 A at " + f"340, the meter silent from 345: no re-send ({nzr}), the pause at " + f"the first step at own age >= 330", + not nzr and timing(st, since=345) and common( + "T13", r, st, silent_from=345)) + +for n in (1, 2, 6): + r = S.drive(S.const(500.0), S.const(7600.0), dur=700, first="car", + socs=dict(FULLB), car_phases=3, + events={305: lambda p, c: p.ch.go_unavailable(), + 305 + n: lambda p, c: p.ch.go_unavailable(False)}) + w = cur_writes(r) + close = [(t, a) for t, a, _ in w if a > 0.0 and 301 < t < 700] + check(f"T14 (C19): {n} failed read(s) at 305 s: the closing current on " + f"time ({close[:1]}), no pause", + bool(close) and 312 <= close[0][0] <= 313 + n + and not [1 for t, a, _ in w if 301 < t < 700 and a == 0.0]) + +# T15: unavailable = nothing ingested (the state is rejected before ingest). +for race in (False, True): + r, st = run_log(go, dur=1000, cyc=5, phase=0, race=race) + check(f"T15 [{'race' if race else 'plain'}]: meter unavailable from 300: " + f"the same age rule as silent", timing(st, exp_age=331.3)) + r, st = run_log(go, dur=1000, cyc=5, phase=0, race=race, + events={450: lambda p, c: setattr(p, "meter_on", False), + 900: lambda p, c: setattr(p, "meter_on", True)}) + z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0 and x["now"] > SIL] + zw = [t for t, a, _ in cur_writes(r) if a == 0.0 and 300 < t < 900] + check(f"T15 [{'race' if race else 'plain'}]: silent, then unavailable at " + f"450, back at 900: unavailable does not reset the age; exactly one " + f"0 A ({zw})", len(zw) == 1 and len(z) == 1 + and abs(z[0]["age"] - 331.3) < 0.05 and common( + "T15", r, st, back=900)) + +# T16: arrival sources keep the cycle's age (and the 15 s + 300 s rule). +ARRIVAL = {} +for src in ("homewizard_local", "mqtt_p1"): + for race in (False, True): + for cyc in (1, 5): + r, st = run_log(go, dur=760, cyc=cyc, phase=0, race=race, + opts={"meter_source": src}) + z = [t for t, a, _ in cur_writes(r) if a == 0.0 and t > SIL] + nz16 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > SIL + 30] + ARRIVAL[(src, race, cyc)] = z[:1] + check(f"T16 [{src} {'race' if race else 'plain'} cyc {cyc}]: " + f"arrival source: p1 on {r['c'].p1_enabled}; first 0 A at " + f"{z[:1]} (spare unknown at 15 s, then 300 s), no non-zero " + f"while silent ({nz16})", + r["c"].p1_enabled and not nz16 and bool(z) + and 300 + 15 + 300 - 1 <= z[0] <= 300 + 15 + 300 + 8) + +# T17, T18: an add-on restart: a new Controller, the store and charger kept. +for restart_at in (500, 640): + r1, _ = go(dur=restart_at) + n = LOG.mark() + STEPS.clear() + n_dbg = LOG.mark() + r2 = S.drive(S.const(500.0), S.const(2900.0), dur=500, first="car", + socs=dict(FULLB), opts=dict(OPT1), sim=r1["sim"], + store=r1["store"], t0=float(restart_at), + events={restart_at: lambda p, c: setattr(p, "meter_on", False), + restart_at + 300: lambda p, c: setattr(p, "meter_on", True)}) + w = [(t, a) for t, a, _ in cur_writes(r2)] + pre = [x for x in w if x[0] < restart_at + 300] + nzr = [x for x in pre if x[1] > 0.0] + after = [x for x in w if x[1] > 0.0 and x[0] >= restart_at + 300] + dl = lines(n_dbg) + none_age = [x for x in dl if x["age"] is None] + check(f"T17: restart at own age {restart_at - 298.7:.0f} with the meter " + f"still silent: the first write before the return is 0 A or none, " + f"the 0 A already standing ({pre[:1]}), 0 " + f"non-zero until it returns ({nzr}), then the start rule " + f"(>= +120: {after[:1]}); the age counts from the first reading: " + f"DEBUG shows age none until then ({len(none_age)} lines)", + (not pre or pre[0][1] == 0.0) and not nzr + and (not after or after[0][0] >= restart_at + 300 + 120 - 1) + and len(none_age) > 0 + and not LOG.tracebacks(n)) +r1, _ = go(dur=500) +n = LOG.mark() +r2 = S.drive(S.const(500.0), S.const(2900.0), dur=900, first="car", + socs=dict(FULLB), opts=dict(OPT1), sim=r1["sim"], + store=r1["store"], t0=500.0, + events={500: lambda p, c: setattr(p, "meter_on", False)}) +check("T18: restart, the meter never returns (900 s): 0 non-zero writes, no " + "Traceback, no 'car charger step failed'", + not [1 for t, a, _ in cur_writes(r2) if a > 0.0] + and not LOG.tracebacks(n) + and not [m for m in LOG.since(n) if "car charger step failed" in m]) + +for race in (False, True): + r, st = run_log(go, dur=1500, cyc=5, phase=0, race=race, + events={1100: lambda p, c: setattr(p, "meter_on", True)}) + nz19 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > 1000] + check(f"T19 [{'race' if race else 'plain'}]: the pause, the meter back at " + f"1100: the first non-zero write {nz19[:1]} within [1220, 1226]", + bool(nz19) and 1220 <= nz19[0][0] <= 1226 and 10.0 <= nz19[0][1] <= 12.0) + +# =========================================================================== # +print("\n3. BOUNDS, QUARTER START, OTHER WRITERS (T20-T24)") +# =========================================================================== # +for ma, pm, bound in ((5, 1, 65), (30, 1, 90), (300, 1, 360), (300, 30, 2100)): + for race in (False, True): + r, st = run_log(go, dur=SIL + bound + 120, cyc=5, phase=0, race=race, + opts={"meter_max_age_s": ma, "ev_pause_min": pm}) + t = cyc_t(0, 5, 0, 298.7 + bound) + ok = timing(st, bound=float(bound), exp_age=t - 298.7) + check(f"T20 [{ma},{pm}] {'race' if race else 'plain'}: the pause at the " + f"first step at own age >= {bound} ({t - 298.7:.1f}); no non-zero " + f"write past {ma} s", + ok and not n8(st, float(ma))) + +r = S.drive(S.const(500.0), S.const(300.0), dur=900, first="car", + socs=dict(FULLB), opts=dict(OPT1), + events={SIL: lambda p, c: setattr(p, "meter_on", False)}) +check(f"T21: a paused car (0 W, 0 A) when the meter goes silent: no write at " + f"all ({cur_writes(r)[:2]})", cur_writes(r) == []) +r = S.drive(S.const(500.0), S.const(2900.0), dur=1000, first="car", + socs=dict(FULLB), opts=dict(OPT1), + events={SIL: lambda p, c: setattr(p, "meter_on", False), + 310: lambda p, c: p.ch.freeze()}) +check(f"T21: a frozen car reading during the silence: nothing non-zero past " + f"30 s of silence ({[(t, a) for t, a, _ in cur_writes(r) if a > 0 and t > 330]})", + not [1 for t, a, _ in cur_writes(r) if a > 0 and t > 330]) + +r = S.drive(S.const(500.0), S.const(2900.0), dur=760, first="car", + socs=dict(FULLB), opts=dict(OPT1), + events={200: lambda p, c: p.ch.set_current(13), + SIL: lambda p, c: setattr(p, "meter_on", False)}) +check(f"T22 (N3): another writer's 13 A at 200, the meter silent from 300: " + f"nothing written over it ({[x for x in r['plant'].sets if x[1] == S.SET and x[0] >= 200]}), " + f"it stands at {r['sim'].setpoint_a}", + not [x for x in r["plant"].sets if x[1] == S.SET and x[0] >= 200] + and r["sim"].setpoint_a == 13.0) + +for race in (False, True): + r, st = run_log(go, onset=570, dur=1100, cyc=5, phase=0, race=race) + s, _ = pause_step(st, since=570) + check(f"T23 [{'race' if race else 'plain'}]: silence from 570: the first " + f"step at own age >= 330 is the quarter start t=900 " + f"({s and s['now']}); the peak guard never limits", + timing(st, exp_age=331.3, since=570) and s["now"] == 900.0 + and not [x for x in r["trace"] if x["lim"]]) + +# T24: battery setpoints are the same with the age rule at the cycle's age (the +# base behaviour) as with the step's own age: the car's rules never touch them. +def _sets(r): + return [(t, e, v) for t, e, v in r["plant"].sets if e.startswith("number.sp_")] + + +_real_own = getattr(Controller, "car_sun_own", None) +for first, sun in (("car", 2900.0), ("batteries", 7900.0)): + sets = [] + for own in (True, False): + if _real_own is not None: + Controller.car_sun_own = _real_own if own else (lambda self, s, n: s) + try: + kw = dict(first=first, sun=sun, dur=760, cyc=5, phase=0, race=True) + STEPS.clear() + r = S.drive(S.const(500.0), S.const(sun), dur=760, first=first, + socs={"a": 100.0, "b": 100.0} if first == "car" + else {"a": 50.0, "b": 50.0}, opts=dict(OPT1), + events={SIL: lambda p, c: setattr(p, "meter_on", False)}, + cyc=5, phase=0, race=True) + finally: + if _real_own is not None: + Controller.car_sun_own = _real_own + sets.append(_sets(r)) + sa, sb = sets + check(f"T24 [{first} first, sun {sun:.0f}]: the batteries' setpoints are " + f"the same on every cycle whichever age the writer step uses " + f"({len(sa)} writes)", sa == sb and bool(sa)) + +# =========================================================================== # +print("\n4. DOCS (T26)") +# =========================================================================== # +doc = open(os.path.join(HERE, "DECISIONS", "EV-20-solar-mode.md")).read() +check("T26: DECISIONS states the rule once: 0 A on the first car step whose own " + "meter age is >= meter_max_age_s + ev_pause_min, held steps included; the " + "'(bound 330 s + one cycle)' wording is gone", + "bound 330 s + one cycle" not in doc + and doc.count("EV-51: decided at the step's own meter age") == 1 + and "held steps included" in doc) + +# =========================================================================== # +print("\n5. THE DEBUG LINE (T28-T34; N9, N10, N11)") +# =========================================================================== # +n = LOG.mark() +r, st = run_log(go, dur=760, cyc=5, phase=0, race=True) +dl = lines(n) +solar_steps = [s for s in st if s["solar"]] +pre = [x for x in dl if x["age"] is not None and x["age"] < 330.0] +at = [x for x in dl if x["age"] is not None and x["age"] >= 330.0] +at0 = nth(at, 0) +check(f"T28: one DEBUG line per Solar writer step ({len(dl)} lines, " + f"{len(solar_steps)} steps); steps under 330: steady or wait-unknown, " + f"write none; the step at own age 331.3: pause, sent 0 A, confirmed; " + f"later steps write nothing", + len(dl) == len(solar_steps) and bool(pre) + and all(x["decision"] in ("steady", "wait-unknown") and x["write"] == "none" + for x in pre if x["t"] > 130) + and present(at0) and at0["decision"] == "pause" + and abs(at0["age"] - 331.3) < 0.05 + and at0["write"] == "sent 0 A confirmed" + and all(x["write"] == "none" for x in at[1:])) +check("T28: the line's fields are the record time t and the meter age, the " + "decision word and the write", + all(set(x) == {"t", "age", "decision", "write"} for x in dl)) + +n = LOG.mark() +r, st = run_log(go, dur=760, cyc=10, phase=3, race=True) +dl = lines(n) +bad = [x for x in dl if x["t"] > SIL + 1 and ( + x["age"] is None or abs(x["age"] - (x["t"] - 298.7)) > 0.05)] +check(f"T29: race order, 10 s cycles, phase 3: the logged age is the step's own " + f"(now - 298.7), never the snapshot's (10 s less) ({bad[:1]})", + bool(dl) and not bad and len([x for x in dl if x["t"] > SIL]) > 30) + +# T30 / N9: nothing new at info. The records of the run on 5bff894 (measured +# there, pinned): none at INFO or above for this run. +GOOGLE.setLevel(logging.INFO) +try: + n = LOG.mark() + r, st = run_log(go, dur=760, cyc=5, phase=0, race=True) + info = [(lv, m) for lv, m, _x in LOG.rec[n:]] +finally: + GOOGLE.setLevel(logging.DEBUG) +# Measured on 5bff894 (same run, INFO), pinned: +BASE_INFO = [ + ('INFO', 'maintenance history: moved 5 saved values to one part per inverter: unit/inverter-a/last_completed, unit/inverter-a/last_failed, unit/inverter-a/last_start_attempt, unit/inverter-a/phase, unit/inverter-a/phase_started'), + ('INFO', 'Month peak store: fresh start, nothing saved'), + ('INFO', "No price history is kept (no durable volume at /data), so missing hours are not filled from yesterday's prices."), + ('INFO', 'Price history: unavailable - no durable volume at /data'), + ('WARNING', 'No meter reading for over 30 seconds, so control waits and then sets the battery to 0 W.'), +] +check(f"T30 (N9): at INFO the new line is not there ({len(lines(n))} lines) and " + f"the INFO+ records equal the run on 5bff894 ({info[:3]})", + lines(n) == [] and not [m for lv, m in info if "Solar step" in m] + and info == BASE_INFO) + +# T31: Nones in the line. +n = LOG.mark() +r, st = run_log(go, onset=0, dur=400, cyc=5, phase=0, race=True) +dl = lines(n) +check(f"T31 (a): no reading since boot: age none ({len(dl)} lines), no failure", + bool(dl) and all(x["age"] is None for x in dl) + and not LOG.tracebacks(n) + and not [m for m in LOG.since(n) if "car charger step failed" in m]) +n = LOG.mark() +r, st = run_log(go, dur=400, cyc=5, phase=0, + events={0: lambda p, c: p.ch.go_unavailable()}) +check(f"T31 (b): the charger unavailable the whole run: lines still print, no " + f"failure ({len(lines(n))} lines)", + bool(lines(n)) and not LOG.tracebacks(n) + and not [m for m in LOG.since(n) if "car charger step failed" in m]) +n = LOG.mark() +r = S.drive(S.const(500.0), S.const(2900.0), dur=500, first="car", + socs=dict(FULLB), opts=dict(OPT1), mode="manual", + events={200: act("car_mode", "solar")}) +check(f"T31 (c): Solar engaged after Manual (sent_a None): the line prints " + f"({len(lines(n))} lines), no failure", + bool(lines(n)) and not LOG.tracebacks(n) + and not [m for m in LOG.since(n) if "car charger step failed" in m]) + + +def _same_at_levels(tag, mk): + """DEBUG vs INFO: the same writes and the same Home Assistant calls (N11).""" + outs = [] + for lvl in (logging.DEBUG, logging.INFO): + GOOGLE.setLevel(lvl) + try: + n = LOG.mark() + r = mk() + outs.append((r["plant"].sets, r["raised"], r["sim"].log, + len(lines(n)))) + finally: + GOOGLE.setLevel(logging.DEBUG) + return outs + + +outs = _same_at_levels("T31", lambda: go(dur=300, cyc=5, phase=0, onset=0)[0]) +o_dbg, o_inf = outs +same = o_dbg[:3] == o_inf[:3] +check("T31 (N11): no reading since boot: the writes and Home Assistant calls " + "are the same at DEBUG and INFO", + same and o_dbg[3] > 0 and o_inf[3] == 0) + +# T32: the pause's 0 A refused. +def _t32(plant_cls=None, sim=None): + return go(dur=760, cyc=5, phase=0, sim=sim, plant_cls=plant_cls)[0] + + +class RefusePlant(S.SunPlant): + async def set_number(self, e, v): + if e == S.SET and float(v) == 0.0 and 630 <= self.t <= 700: + self.sets.append((self.t, e, float(v))) + return False + return await super().set_number(e, v) + + +for what, mk in (("the charger ignores it", lambda: _t32( + sim=TSim(setpoint_a=0, windows=[(629.5, 700, "ignore")]))), + ("Home Assistant refuses it", lambda: _t32(plant_cls=RefusePlant))): + outs = _same_at_levels("T32", mk) + o_dbg, o_inf = outs + same32 = o_dbg[:3] == o_inf[:3] + GOOGLE.setLevel(logging.DEBUG) + n = LOG.mark() + mk() + sent = [x for x in lines(n) if x["write"].startswith("sent 0 A") + and x["t"] >= 630] + unconf = [x for x in sent if "confirmed" not in x["write"]] + check(f"T32 [{what}]: DEBUG shows 'sent 0 A' without 'confirmed' for each " + f"refused try ({[(x['t'], x['write']) for x in sent[:4]]}); the " + f"writes and Home Assistant calls equal the INFO run (N11)", + bool(unconf) and same32) + +# T33 / N10: secrets. +SENT = {"price_service_token": "SENTINEL-TOKEN-3317", + "mqtt_password": "SENTINEL-MQTT-3317", "api_key": "SENTINEL-KEY-3317", + "ha_token": "SENTINEL-HA-3317"} +n = LOG.mark() +r, st = run_log(go, dur=760, cyc=5, phase=0, race=True, opts=dict(SENT)) +check("T33 (N10): sentinel values in every secret-like option never reach a " + "log record", + not [m for _lv, m, _x in LOG.rec[n:] if "SENTINEL" in m] + and len(lines(n)) > 0) + +# T34: volume. +n = LOG.mark() +r, st = run_log(go, dur=760) +dl = lines(n) +check(f"T34: 1 s cycles, 760 s: the new lines equal the Solar writer steps " + f"({len(dl)} vs {len([s for s in st if s['solar']])}), none per poll", + 0 < len(dl) <= 760 and len(dl) == len([s for s in st if s["solar"]])) + +# =========================================================================== # +print("\n6. THE HARNESS CADENCE (T35-T39)") +# =========================================================================== # +def _sig(r): + return ([(x["t"], x["a"], x["why"], x["sp"]) for x in r["trace"]], + list(r["sim"].log), list(r["plant"].sets)) + + +for tag, kw in (("silent car-first", dict()), + ("batteries first, sun 4.4 kW", dict(first="batteries", sun=4400.0))): + a, _ = go(dur=500, **kw) + b, _ = go(dur=500, cyc=1, phase=0, jitter=None, race=False, **kw) + check(f"T35 [{tag}]: the default call equals an explicit cyc=1, phase=0, " + f"jitter=None, race=False (same trace, writes and sets)", + _sig(a) == _sig(b) and len(a["trace"]) == 500) + +for cyc in (5, 10): + badph = [] + for ph in range(cyc): + r, st = go(dur=60, cyc=cyc, phase=ph, onset=None) + ts = [x["t"] for x in r["trace"]] + if ts != [float(t) for t in range(ph, 60, cyc)] or [ + s["now"] for s in st] != ts: + badph.append((ph, ts[:3])) + check(f"T36: cyc {cyc}, every phase: trace rows and writer steps only at " + f"seconds with (t - t0) mod cyc == phase ({badph[:2]})", not badph) +r, st = go(dur=60, cyc=5, phase=2, onset=20) +check(f"T36: the meter and the charger still tick every second: the meter " + f"samples {r['c'].p1.samples} (20 s on) and {len(r['trace'])} rows", + r["c"].p1.samples == 20 and len(r["trace"]) == 12) + +r, st = go(dur=60, jitter=(4, 6, 5), onset=None) +check(f"T37: jitter 4/6/5: rows at {[x['t'] for x in r['trace']][:6]}", + [x["t"] for x in r["trace"]] + == [0.0, 4.0, 10.0, 15.0, 19.0, 25.0, 30.0, 34.0, 40.0, 45.0, 49.0, + 55.0]) +r, st = go(dur=40, cset=[3, 7, 8, 39, 40, 99], onset=None, t0=0.0) +check(f"T37: an explicit set of cycle seconds: rows exactly at those inside " + f"[t0, t0 + dur) ({[x['t'] for x in r['trace']]})", + [x["t"] for x in r["trace"]] == [3.0, 7.0, 8.0, 39.0]) + +for race in (False, True): + r, st = go(dur=700, cyc=10, phase=3, race=race) + # (the run's last settle runs one step off the cycle grid: left out) + st2 = [s for s in st if s["solar"] and s["now"] > SIL + 40 + and s["snap_age"] is not None and s["now"] % 10 == 3] + d = [round(s["age"] - s["snap_age"], 1) for s in st2] + want = 10.0 if race else 0.0 + check(f"T38 [{'race' if race else 'plain'}]: the snapshot's age is the " + f"step's own age minus {want:.0f} s ({sorted(set(d))[:3]})", + bool(st2) and all(abs(x - want) <= 0.05 for x in d)) + +bads = 0 +for kw in (dict(cyc=0), dict(cyc=-5), dict(cyc=5, phase=5), dict(cyc=5, phase=-1), + dict(cset=[900]), dict(cset=[]), dict(jitter=()), dict(jitter=(0,))): + try: + go(dur=20, onset=None, **kw) + except ValueError: + bads += 1 +check(f"T39: a cycle length of 0 or less, a phase outside [0, cyc), a set with " + f"no second in the run, an empty jitter: ValueError ({bads} of 8)", + bads == 8) + +# =========================================================================== # +print("\n7. THE METER BACK; THE SWEEPS; THE HOLD (T40-T43; N12)") +# =========================================================================== # +r, st = run_log(go, dur=900, cyc=5, phase=0, race=True, + events={630: lambda p, c: setattr(p, "meter_on", True)}) +s630 = [s for s in st if s["now"] == 630.0][0] +w40 = [(t, a) for t, a, _ in cur_writes(r) if t > SIL] +check(f"T40: race, the meter back at 630 (sample ingested before the step, " + f"snapshot 625 said silent at {s630['snap_age']:.1f}): own age " + f"{s630['age']:.1f}, no pause, no current write 300-900 ({w40}); the " + f"plan keeps 10 A ({r['c'].car_solar.plan.a})", + abs(s630["age"] - 0.3) < 0.05 and w40 == [] + and r["c"].car_solar.plan.a == 10.0 and common("T40", r, st, back=630)) + +for back_at in (631, 635): + r, st = run_log(go, dur=1100, cyc=5, phase=0, race=True, + events={back_at: lambda p, c: setattr(p, "meter_on", True)}) + s, _ = pause_step(st) + nzb = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > 630] + check(f"T41: race, the meter back at {back_at}: the 0 A in the step at 630 " + f"(own age {s and round(s['age'], 1)}); after the return only the " + f"start rule ({nzb[:1]}, >= {back_at + 120})", + timing(st, exp_age=331.3) and s["now"] == 630.0 + and (not nzb or nzb[0][0] >= back_at + 120 - 1)) + + +def sweep(kind, cyc, race, onsets): + """T42: the silence onset swept; the non-zero writes at a step whose own + age is > 30.""" + hits = [] + for s in onsets: + if kind == "starts": + r, st = go(onset=s, dur=s + 120, cyc=cyc, phase=0, race=race) + else: + r, st = go(onset=s, dur=min(s + 130, 760), cyc=cyc, phase=0, + race=race, + sun=lambda t: 4400.0 if t >= 200 else 2900.0) + b = n8(st) + if b: + hits.append((s, b[0])) + return hits + + +for cyc in (5, 10): + for race in (False, True): + h = sweep("starts", cyc, race, range(60, 126)) + check(f"T42 starts [{cyc} s {'race' if race else 'plain'}]: a start due " + f"just after the silence onset (onset 60-125): 0 of 66 onsets " + f"with a non-zero write at own age > 30 ({len(h)}: {h[:2]})", + not h) +for race in (False, True): + h = sweep("raises", 5, race, range(200, 330)) + check(f"T42 raises [5 s {'race' if race else 'plain'}]: a raise due " + f"(sun 4.4 kW from 200), onset 200-329: 0 of 130 onsets with a " + f"non-zero write at own age > 30 ({len(h)}: {h[:2]})", not h) + +for l0, want in ((598, 915.0), (602, 920.0)): + for race in (False, True): + r, st = run_log(go, onset=None, dur=1100, cyc=5, phase=0, race=race, + events={0: late_at(l0, 1000)}) + z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0] + nz43 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and 600 <= t < 1000] + cross = [s for s in st if s["now"] >= l0 + 15][0] + check(f"T43 (a) [L0 {l0} {'race' if race else 'plain'}]: running at 10 A, " + f"late from {l0}: the crossing step (own late >= 15) takes the " + f"stale rule, the 0 A at {z[0]['now'] if z else None} " + f"(want {want}); no non-zero write 600-1000 ({nz43})", + bool(z) and z[0]["now"] == want and not nz43) + n = LOG.mark() + run_log(go, onset=None, dur=640, cyc=5, phase=0, race=race, + events={0: late_at(l0, 1000)}) + dl = lines(n) + cr = [x for x in dl if x["t"] == float(cross["now"])] + before = [x for x in dl if x["t"] == float(cross["now"]) - 5] + check(f"T43 (a) DEBUG [{'race' if race else 'plain'} L0 {l0}]: the step " + f"before the crossing holds, the crossing step does not " + f"({before and before[0]['decision']} -> {cr and cr[0]['decision']})", + bool(cr) and bool(before) and before[0]["decision"] == "hold" + and cr[0]["decision"] == "wait-unknown") + +for l0 in (101, 103, 105): + for race in (False, True): + r, st = run_log(go, onset=None, dur=500, cyc=5, phase=0, race=race, + events={0: late_at(l0, 400)}) + nz43 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and 116 <= t < 400] + cross = [s for s in st if s["now"] >= l0 + 15][0] + check(f"T43 (b) (N12) [L0 {l0} {'race' if race else 'plain'}]: paused " + f"with a start due, late from {l0}: the crossing step at " + f"{cross['now']} writes nothing ({cross['writes']}) from its " + f"snapshot ({cross['snap_tgt']} W); no non-zero write 116-400 " + f"({nz43})", cross["now"] == 120.0 and not cross["writes"] + and not nz43) + +report() diff --git a/goodwe_controller/tools/ev20_sun.py b/goodwe_controller/tools/ev20_sun.py index 2d2c0bf..b3892e6 100644 --- a/goodwe_controller/tools/ev20_sun.py +++ b/goodwe_controller/tools/ev20_sun.py @@ -137,11 +137,41 @@ class SunPlant: return True +def _cycle_seconds(t0, dur, cyc, phase, jitter, cset): + """EV-51: the seconds a cycle runs, or None for every second.""" + if cset is not None: + due = {int(x) for x in cset if t0 <= x < t0 + dur} + if not due: + raise ValueError("cset has no second inside the run") + return due + if jitter is not None: + gaps = [int(g) for g in jitter] + if not gaps or min(gaps) <= 0: + raise ValueError("jitter needs gaps above 0") + due, t, i = set(), int(t0), 0 + while t < t0 + dur: + due.add(t) + t += gaps[i % len(gaps)] + i += 1 + return due + if cyc != int(cyc) or cyc <= 0: + raise ValueError("cyc must be a whole number of seconds above 0") + if not 0 <= phase < cyc: + raise ValueError("phase must be in [0, cyc)") + if cyc == 1: + return None + due = {int(t0) + k for k in range(int(phase), int(dur), int(cyc))} + if not due: + raise ValueError("no cycle inside the run") + return due + + def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar", first="batteries", events=None, sim=None, store=None, race=False, on_cycle=None, car_phases=3, t0=0.0, caps=None, finale=None, - rows=False, plant_cls=None, beside=False, meter_change=False): + rows=False, plant_cls=None, beside=False, meter_change=False, + cyc=1, phase=0, jitter=None, cset=None): """Run it. Returns a dict: plant, controller, charger, notifications with their second, and a per-second trace. `caps` ({unit: kWh}) lets each battery's level move with what it charges or gives; without it the @@ -152,7 +182,14 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, round 1): a write that waits for its read-back is still waiting when the next cycle reads the charger; it resumes after that read. `meter_change=True` publishes the meter as Home Assistant does on - `ha_signed`: only when the whole-watt value changes.""" + `ha_signed`: only when the whole-watt value changes. + EV-51, the cycle's cadence (the meter and the charger model still tick + every 1 s; only the control cycle is thinned): `cyc` seconds between + cycles and `phase` (the first cycle at t0 + phase), or `jitter`, a + tuple of gaps used in turn (the first cycle at t0), or `cset`, the + cycle seconds. The default (1 s) runs every second as before. A cadence + that would run no cycle is a ValueError, never a vacuous pass.""" + due = _cycle_seconds(t0, dur, cyc, phase, jitter, cset) ratings = ratings or {"a": 5000.0, "b": 4600.0} socs = socs or {u: 50.0 for u in ratings} sim = sim or SimCharger(setpoint_a=setpoint) @@ -252,6 +289,12 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, "ha_signed", imp, exp, phases=1, ingest_ts=rig.BASE + timedelta(seconds=ts), ingest_mono=ts)) + if due is not None and int(t) not in due: + for u, kwh in (caps or {}).items(): + lv = plant.socs[u] - plant.batt_of(u, t) / 36000.0 / kwh + plant.socs[u] = max(0.0, min(100.0, lv)) + t += 1.0 + continue await c.read_inputs(now_mono=t) if race: await c.car_settle() -- 2.54.0 From a33eb8ef1c12cec83389080a5c2ed17b96ddbfa7 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Tue, 24 Nov 2026 19:52:36 +0100 Subject: [PATCH 50/55] EV-51 round 1: C23 (no spare/target from data the own age calls old), N5 label, T44 car_sun_own now sets spare_w / target_w to None while the step's own meter age says silent, so no plan start or raise comes from a snapshot value over meter_max_age_s old; the start comes from a fresh reading after the meter returns, with its dwell. T44 sweeps a start due just after the silence (red on 68856bc, green now). T24 is labelled N5 and also runs at SoC 50 so the batteries' setpoints in the silence are compared. Co-Authored-By: Claude Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/app/ctl_car.py | 6 +++-- goodwe_controller/test_ev51.py | 44 +++++++++++++++++++++++++++----- 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 120a8dd..a23543c 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -432,8 +432,10 @@ class CarMixin: if late is not None and self._car_late_mono is not None: late += max(0.0, now - self._car_late_mono) own.hold = late is not None and late < stale - if late is not None and late >= stale: - own.spare_w = own.target_w = None # the stale rule, on own late + if own.silent or (late is not None and late >= stale): + # The stale rule on the step's own age / own late (C23): a spare + # read from data the own age calls old starts or raises nothing. + own.spare_w = own.target_w = None return own async def _car_step_run(self, held, now, sun) -> None: diff --git a/goodwe_controller/test_ev51.py b/goodwe_controller/test_ev51.py index 2c3759c..95e7b6f 100644 --- a/goodwe_controller/test_ev51.py +++ b/goodwe_controller/test_ev51.py @@ -528,7 +528,8 @@ def _sets(r): _real_own = getattr(Controller, "car_sun_own", None) -for first, sun in (("car", 2900.0), ("batteries", 7900.0)): +for first, sun, soc in (("car", 2900.0, 100.0), ("car", 2900.0, 50.0), + ("batteries", 7900.0, 50.0)): sets = [] for own in (True, False): if _real_own is not None: @@ -537,8 +538,7 @@ for first, sun in (("car", 2900.0), ("batteries", 7900.0)): kw = dict(first=first, sun=sun, dur=760, cyc=5, phase=0, race=True) STEPS.clear() r = S.drive(S.const(500.0), S.const(sun), dur=760, first=first, - socs={"a": 100.0, "b": 100.0} if first == "car" - else {"a": 50.0, "b": 50.0}, opts=dict(OPT1), + socs={"a": soc, "b": soc}, opts=dict(OPT1), events={SIL: lambda p, c: setattr(p, "meter_on", False)}, cyc=5, phase=0, race=True) finally: @@ -546,9 +546,13 @@ for first, sun in (("car", 2900.0), ("batteries", 7900.0)): Controller.car_sun_own = _real_own sets.append(_sets(r)) sa, sb = sets - check(f"T24 [{first} first, sun {sun:.0f}]: the batteries' setpoints are " - f"the same on every cycle whichever age the writer step uses " - f"({len(sa)} writes)", sa == sb and bool(sa)) + sil_a = [x for x in sa if x[0] >= SIL] + sil_b = [x for x in sb if x[0] >= SIL] + check(f"T24 / N5 [{first} first, sun {sun:.0f}, SoC {soc:.0f}]: the batteries' setpoints " + f"are the same on every cycle, and in the silence from {SIL} s, " + f"whichever age the writer step uses ({len(sa)} writes, " + f"{len(sil_a)} in the silence)", + sa == sb and sil_a == sil_b and (soc >= 100.0 or bool(sil_a))) # =========================================================================== # print("\n4. DOCS (T26)") @@ -869,4 +873,32 @@ for l0 in (101, 103, 105): f"({nz43})", cross["now"] == 120.0 and not cross["writes"] and not nz43) +# T44 (C23, PM): a start due just after the silence begins. No plan start and +# no non-zero write from data the step's own age calls old (> 30 s); after the +# meter returns the start comes only from a fresh reading, with its dwell. +def _c23(cyc): + bad = [] + for onset in range(88, 100): + back = onset + 60 + r, st = run_log(go, onset=onset, dur=back + 200, cyc=cyc, phase=0, + race=True, + events={back: lambda p, c: setattr(p, "meter_on", True)}) + stale_start = [(x["now"], round(x["age"], 1)) for x in st + if x["age"] is not None and x["age"] > 30.0 + and x["a0"] <= 0.0 < x["a1"]] + nzw = [(x["now"], w[0], x["snap_tgt"]) for x in st for w in x["writes"] + if w[0] > 0.0] + late_nz = [x for x in nzw if x[2] is None] # from a None target + if stale_start or n8(st) or late_nz: + bad.append((onset, stale_start[:1], nzw[:1])) + return bad + + +for cyc in (5, 10): + bad = _c23(cyc) + check(f"T44 (C23) [{cyc} s race]: a start due just after the silence " + f"(onset 88-99, back 60 s later): no plan start at own age > 30, no " + f"non-zero write from old data; the start only from a fresh reading " + f"(a start at own age <= 30 is the normal dwell) ({len(bad)} bad: {bad[:2]})", not bad) + report() -- 2.54.0 From 6412d007839ed3c9f0b1579dd47621a255549c4f Mon Sep 17 00:00:00 2001 From: ems-agent Date: Tue, 24 Nov 2026 22:05:33 +0100 Subject: [PATCH 51/55] EV-51 round 2: T44 checks the start after the meter returns; T24 SoC 100 no longer carries N5 T44 (C23) now also asserts that a start and a non-zero write come, either before the silence passes 30 s (from fresh data) or after the meter is back at a step with own age <= 30, between the first fresh step + ev_start_min and that + 2 cycles, and that the car is still charging at the end. A fix that blocks every start after a silence fails it. T24: the SoC 100 run (no battery write in the silence) is checked for T24 only; N5 rides on the SoC 50 runs, which must have writes in the silence. Co-Authored-By: Claude --- goodwe_controller/test_ev51.py | 64 +++++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 9 deletions(-) diff --git a/goodwe_controller/test_ev51.py b/goodwe_controller/test_ev51.py index 95e7b6f..2a613ed 100644 --- a/goodwe_controller/test_ev51.py +++ b/goodwe_controller/test_ev51.py @@ -527,6 +527,9 @@ def _sets(r): return [(t, e, v) for t, e, v in r["plant"].sets if e.startswith("number.sp_")] +# The plan's T1 run (full batteries, SoC 100) gets no setpoint write in the +# silence, so it is checked for T24 only; N5 rides on the SoC 50 runs, which +# must have writes in the silence. _real_own = getattr(Controller, "car_sun_own", None) for first, sun, soc in (("car", 2900.0, 100.0), ("car", 2900.0, 50.0), ("batteries", 7900.0, 50.0)): @@ -548,11 +551,18 @@ for first, sun, soc in (("car", 2900.0, 100.0), ("car", 2900.0, 50.0), sa, sb = sets sil_a = [x for x in sa if x[0] >= SIL] sil_b = [x for x in sb if x[0] >= SIL] + if soc >= 100.0: + check(f"T24 [{first} first, sun {sun:.0f}, SoC {soc:.0f}, the T1 run]: the " + f"batteries' setpoints are the same on every cycle whichever age " + f"the writer step uses ({len(sa)} writes), and none in the silence " + f"either way (not N5: no write there to compare)", + sa == sb and bool(sa) and not sil_a and not sil_b) + continue check(f"T24 / N5 [{first} first, sun {sun:.0f}, SoC {soc:.0f}]: the batteries' setpoints " f"are the same on every cycle, and in the silence from {SIL} s, " f"whichever age the writer step uses ({len(sa)} writes, " - f"{len(sil_a)} in the silence)", - sa == sb and sil_a == sil_b and (soc >= 100.0 or bool(sil_a))) + f"{len(sil_a)} in the silence, which must not be empty)", + sa == sb and sil_a == sil_b and bool(sil_a)) # =========================================================================== # print("\n4. DOCS (T26)") @@ -876,13 +886,19 @@ for l0 in (101, 103, 105): # T44 (C23, PM): a start due just after the silence begins. No plan start and # no non-zero write from data the step's own age calls old (> 30 s); after the # meter returns the start comes only from a fresh reading, with its dwell. +START_S = 60.0 * carmode.solar_option({}, "ev_start_min") # 120 s + + def _c23(cyc): - bad = [] + """Returns (bad, n_back): bad onsets, and how many onsets started only + after the meter came back (the 'green after' half must not be vacuous).""" + bad, n_back = [], 0 for onset in range(88, 100): back = onset + 60 r, st = run_log(go, onset=onset, dur=back + 200, cyc=cyc, phase=0, race=True, events={back: lambda p, c: setattr(p, "meter_on", True)}) + # (a) nothing from data over 30 s old. stale_start = [(x["now"], round(x["age"], 1)) for x in st if x["age"] is not None and x["age"] > 30.0 and x["a0"] <= 0.0 < x["a1"]] @@ -890,15 +906,45 @@ def _c23(cyc): if w[0] > 0.0] late_nz = [x for x in nzw if x[2] is None] # from a None target if stale_start or n8(st) or late_nz: - bad.append((onset, stale_start[:1], nzw[:1])) - return bad + bad.append((onset, "old data", stale_start[:1], nzw[:1])) + continue + # (b) the start does come, from a fresh reading, with its dwell. + starts = [x for x in st if x["a0"] <= 0.0 < x["a1"]] + if not starts: + bad.append((onset, "no start at all")) + continue + s0 = starts[0] + if s0["now"] < onset + 30.0: + # Started before the silence passed 30 s, from fresh data (own + # age <= 30, checked in (a)); it must still be charging at the end. + ok = (s0["now"] >= st[0]["now"] + START_S + and st[-1]["a1"] > 0.0 and s0["writes"] + and s0["writes"][0][0] > 0.0) + if not ok: + bad.append((onset, "early start", s0["now"], st[-1]["a1"])) + continue + n_back += 1 + fresh = [x["now"] for x in st if x["now"] >= back + and x["age"] is not None and x["age"] <= 30.0] + nz_after = [t for t, a, _x in nzw if t >= s0["now"] and a > 0.0] + ok = (bool(fresh) and s0["age"] is not None and s0["age"] <= 30.0 + and fresh[0] + START_S <= s0["now"] <= fresh[0] + START_S + 2 * cyc + and bool(nz_after) and st[-1]["a1"] > 0.0) + if not ok: + bad.append((onset, "after back", back, fresh[:1], s0["now"], + s0["age"], nz_after[:1])) + return bad, n_back for cyc in (5, 10): - bad = _c23(cyc) + bad, n_back = _c23(cyc) check(f"T44 (C23) [{cyc} s race]: a start due just after the silence " - f"(onset 88-99, back 60 s later): no plan start at own age > 30, no " - f"non-zero write from old data; the start only from a fresh reading " - f"(a start at own age <= 30 is the normal dwell) ({len(bad)} bad: {bad[:2]})", not bad) + f"(onset 88-99, back 60 s later): (a) no plan start at own age > 30, " + f"no non-zero write from old data; (b) a start and a non-zero write " + f"come: before onset + 30 from fresh data, or after the meter is back " + f"at a step with own age <= 30, between the first fresh step + " + f"{START_S:.0f} s and that + 2 cycles; still charging at the end " + f"({n_back} onsets start after back; {len(bad)} bad: {bad[:2]})", + not bad and n_back >= 9) report() -- 2.54.0 From 45df1ac54991a60e1e18805a4b50ec1f1eb48684 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Wed, 25 Nov 2026 00:04:10 +0100 Subject: [PATCH 52/55] EV-51 review: T45 sweeps N8 on own age for retries and phase-change closing currents; docs name the decision words and C23 T45: race order, 5 s and 10 s cycles, silence onset swept 1 s at a time, (a) a raise the charger ignores (re-sends) and (b) a 1 -> 3 phase change (closing current): no non-zero current write at own age > 30 s. Red on 5bff894 and on the reviewer's R4 (nz_block from the snapshot, C23 on own age), green on head. T26 also checks the DECISIONS entry names every decision word and the C23 value rule. DECISIONS and the car_sun_own / _car_step_debug docstrings: snapshot values are used only while the step's own age says fresh (C23); the decision words are listed. No code change. Co-Authored-By: Claude --- .../DECISIONS/EV-20-solar-mode.md | 13 +++-- goodwe_controller/app/ctl_car.py | 11 +++- goodwe_controller/test_ev51.py | 56 ++++++++++++++++++- 3 files changed, 72 insertions(+), 8 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 4baec40..ac58f63 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -172,10 +172,15 @@ one small set of facts and derives every path from them: late-readings hold with its stale rule (a spare read while the hold was on is not used once the step's own late time reaches `stale_input_s`). The meter's VALUES (spare, target) stay the cycle's, one cycle of sensor latency - being normal; `car.held` and `car.reading` are unchanged. Arrival sources - keep the cycle's age for their "spare unknown" check. At log level debug - each Solar step logs one line: time, the meter age at the step, the decision - and the write. + being normal, but only while the step's own age says the meter is fresh: + once it is past `meter_max_age_s` the spare is unknown, so nothing starts or + rises from it (C23). `car.held` and `car.reading` are unchanged. Arrival + sources keep the cycle's age for their "spare unknown" check. At log level + debug each Solar step logs one line: time, the meter age at the step, the + decision and the write. The decision is one word: `steady`, `start`, + `raise`, `lower`, `pause`, `hold` (the late-readings hold), `wait-unknown` + (the spare is unknown and the pause timer counts) or `wait-held` (a held + charger read). - **No non-zero write while the meter is silent (SPIKE-06 C17, N8 strict):** while the meter's age is past `meter_max_age_s`, Solar sends no non-zero current: no retry, no raise, no phase change begun, and a phase change diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index a23543c..4b59668 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -384,8 +384,11 @@ class CarMixin: def _car_step_debug(self, held, now, sun, a0, n_log) -> None: """EV-51: one DEBUG line per Solar writer step: the time, the meter's - age at the step, what was decided and what was written. Nothing at - info and above; no secrets in it.""" + age at the step, what was decided and what was written. The decision + is one word: steady, start, raise, lower, pause, hold (the + late-readings hold), wait-unknown (the spare is unknown and the pause + timer counts) or wait-held (a held charger read). Nothing at info and + above; no secrets in it.""" w = self.car_solar a1 = w.plan.a if a0 > 0.0 and a1 <= 0.0: @@ -421,7 +424,9 @@ class CarMixin: cycle saw one step earlier: the write block while the meter is silent (N8), the unknown/pause timing (held reads too) and the late-readings hold with its stale rule. The meter's VALUES (spare, target) stay the - cycle's; arrival sources' `car_spare_w` keeps the cycle's age.""" + cycle's only while the step's own age says the meter is fresh; once it + is past `meter_max_age_s` they are unknown (C23). Arrival sources' + `car_spare_w` keeps the cycle's age.""" own = copy.copy(snap) own.silent = self._car_meter_silent() own.unknown_s = self._car_meter_over_s() diff --git a/goodwe_controller/test_ev51.py b/goodwe_controller/test_ev51.py index 2a613ed..aabfc13 100644 --- a/goodwe_controller/test_ev51.py +++ b/goodwe_controller/test_ev51.py @@ -1,5 +1,6 @@ """EV-51: every meter-age decision of a Solar writer step is judged on the -step's OWN age (T1-T43; N1-N12 of reports/EV-51-test-plan.md). +step's OWN age (T1-T45; N1-N12 of reports/EV-51-test-plan.md; T44 and T45 +from the round-1 formal check and the review). `python3 -B test_ev51.py` The real Controller on `tools/ev20_sun.py` (the harness now takes a cycle @@ -574,6 +575,14 @@ check("T26: DECISIONS states the rule once: 0 A on the first car step whose own "bound 330 s + one cycle" not in doc and doc.count("EV-51: decided at the step's own meter age") == 1 and "held steps included" in doc) +_words = ("steady", "start", "raise", "lower", "pause", "hold", "wait-unknown", + "wait-held") +_ev51 = doc.split("EV-51: decided at the step's own meter age", 1)[-1].split("\n- **", 1)[0] +check("T26 (review): the EV-51 entry names every decision word of the DEBUG " + "line and says the snapshot values are unknown once the step's own age " + "is past meter_max_age_s (C23)", + all(f"`{w}`" in _ev51 for w in _words) and "(C23)" in _ev51 + and "only while the step's own age says the meter is fresh" in _ev51) # =========================================================================== # print("\n5. THE DEBUG LINE (T28-T34; N9, N10, N11)") @@ -947,4 +956,49 @@ for cyc in (5, 10): f"({n_back} onsets start after back; {len(bad)} bad: {bad[:2]})", not bad and n_back >= 9) +# T45 (review, N8 / C22 on the paths that do not come from the plan's target): +# (a) the re-send of an ignored write, (b) the closing current of a 1 -> 3 +# phase change. Race order, the silence onset swept 1 s at a time: no non-zero +# current write at a step whose own age is > meter_max_age_s (30 s). The C23 +# hiding of spare/target cannot stop these; only `nz_block` on own age does. +def _t45_retry(cyc): + hits, resent = [], 0 + for onset in range(300, 440): + r, st = run_log(go, onset=onset, dur=onset + 60, cyc=cyc, phase=0, + race=True, + sim=TSim(setpoint_a=0, windows=[(335.0, 900.0, "ignore")]), + sun=lambda t: 3000.0 if t >= 340 else 2300.0) + if len([a for s in st if s["now"] >= 340 for a, _t, _o in s["writes"] + if a > 0.0]) >= 2: + resent += 1 # the ignored raise was sent again + if n8(st): + hits.append((onset, n8(st)[:1])) + return hits, resent + + +def _t45_phase(cyc): + hits, changed = [], 0 + for onset in range(240, 340): + r, st = run_log(go, onset=onset, dur=onset + 60, cyc=cyc, phase=0, + race=True, opts={"ev_phases": "auto"}, car_phases=3, + sun=7600.0) + if [s for s in st if s["phases"]]: + changed += 1 # a 1 -> 3 phase change ran + if n8(st): + hits.append((onset, n8(st)[:1])) + return hits, changed + + +for cyc in (5, 10): + hits, resent = _t45_retry(cyc) + check(f"T45 retry [{cyc} s race]: a raise to 10 A at 340 the charger ignores, " + f"silence onset 300-439: no re-send at own age > 30 ({resent} runs " + f"re-sent; {len(hits)} onsets with a hit: {hits[:2]})", + not hits and resent >= 20) + hits, changed = _t45_phase(cyc) + check(f"T45 phase change [{cyc} s race]: 1 -> 3 phases (sun 7600 W, 3-phase " + f"car), silence onset 240-339: no closing current at own age > 30 " + f"({changed} runs with a phase change; {len(hits)} onsets with a hit: " + f"{hits[:2]})", not hits and changed >= 20) + report() -- 2.54.0 From 550d2d3934f60c8c294690997011a3a90bd54fd0 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Wed, 25 Nov 2026 12:57:38 +0100 Subject: [PATCH 53/55] Release 0.25.0: version bump and CHANGELOG Pinned to EV-51's merge c79eb37 on release/1.0 (TOOL-51, go #62). Only goodwe_controller/config.yaml (version) and CHANGELOG.md change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/CHANGELOG.md | 133 +++++++++++++++++++++++++++++++-- goodwe_controller/config.yaml | 2 +- 2 files changed, 129 insertions(+), 6 deletions(-) diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index 9e39984..0ced066 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -1,11 +1,134 @@ # Changelog -### Not in a release yet +## 0.25.0 -- **The car can now charge from spare sun (Solar mode).** Choose *Solar* on the Car card or in Home Assistant: the car gets only the sun the house does not use, after the batteries (or before them, your choice), and pauses when there is too little. Every way out of Solar, a stop and a restart set the charger to 0 A. Three new options, all with defaults: `ev_margin_w`, `ev_start_min`, `ev_pause_min`. See "Car charger" in DOCS ([[EV-20]]). -- 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]]). +**A minor bump: the car can now charge from spare sun (Solar mode), and the Car card raises fewer false alarms. Three new options were added, all with defaults, and none needs setting.** +Three options were added (`ev_margin_w`, `ev_start_min` and `ev_pause_min`), none was removed or renamed, and no default changed (95 options, 92 before). **Existing installs need no option change:** the new options have defaults, and `ev_charger` is still off, so an install that does not use the car charger runs as 0.24.0 did. It is a minor bump because it adds a feature and new options. Every saved setting still starts. + +**The car can charge from spare sun (Solar mode).** Choose *Solar* on the Car card or in Home Assistant. The car gets only the sun the house does not use, after the batteries or before them (your choice), and pauses when there is too little. When the sun cannot be measured, for example when the meter goes silent, the current stands for 5 minutes and then goes to 0 A. Every way out of Solar, a stop and a restart set the charger to 0 A. See "Car charger" in DOCS ([[EV-20]], [[EV-51]]). + +**Car charger fixes.** The add-on no longer changes the car's phases while the car still draws. Fewer false "Battery stopped limiting the peak" alarms while the car charges. A current the charger does not take shows one amber row, not two. The Car card's *Why* line says what the charger does and no longer switches between two wordings ([[EV-28]], [[EV-15]], [[EV-18]], [[EV-19]], [[EV-13]], [[EV-14]], [[EV-16]]). + +**No change in behaviour:** the build checks now test against a newer copy of the shared test tools. + +Contents of this release, in merge order since 0.24.0 (`f66048b`): + +| | | +|---|---| +| `9fdce02` | 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]], #262) | +| `43b0db7` | While the car explains why the house is over the peak limit, the alarm no longer fires at the start of a 15-minute period and stays red for the whole period ([[EV-18]], #264) | +| `8150608` | No alarm for a moment when the batteries first reach the peak reserve early in a Manual car session ([[EV-19]], #265) | +| `00b116e` | With *Batteries help with the peak* on, the Car card's *Why* line no longer switches between two wordings while the car is over the peak limit ([[EV-16]], #266) | +| `4eba2d9` | The build checks test against a newer copy of the shared test tools. There is no change in behaviour ([[CI-20]], #267) | +| `76f4de2` | 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 still draws after 20 s it gives the current back and tries again after 10 minutes ([[EV-28]], #268) | +| `c8f5292` | When the charger does not take a current setting but is plainly working, you see one amber row ("did not take the setting"), not a second "reading may be stuck" ([[EV-13]], #269) | +| `885528a` | In shadow mode, and after a phase change was given up, the Car card's *Why* line says what the charger does, not what you set ([[EV-14]], #270) | +| `cc8c0dc` | The car can charge from spare sun (Solar mode), with three new options: `ev_margin_w`, `ev_start_min` and `ev_pause_min` ([[EV-20]], #271) | +| `09b6af9` | Solar mode: no false "charger reading may be stuck" after the add-on's own write, no back and forth between two currents, and the waits count from when the sun drops ([[EV-20]], #272) | +| `2768755` | The build checks test against a newer copy of the shared test tools. There is no change in behaviour (#273) | +| `5bff894` | Solar mode: one failed charger reading no longer pauses the car in full sun ([[EV-20]], #274) | +| `c79eb37` | Solar mode: when the meter goes silent, the car goes to 0 A at the first check once the meter reading is 330 s old ([[EV-51]], #275) | + + +### Known issues + +- A false "Battery is not keeping up" can still show when the peak guard pauses a maintenance charge ([[SAFETY-92]]). +- A battery capped at a low limit with a perfectly flat reading can still trip the stale check ([[SAFETY-74]]). +- A battery whose reading at rest is beyond about ±175 W is still not caught when it refuses ([[SAFETY-97]]). +- The peak guard can still back off near the end of a 15-minute period when a meter reading is late, by less than 30 s. This is about the guard's discharge only; a grid charge is cut back since 0.19.2 ([[SAFETY-99]]). +- Two inverters: the maintenance charge can switch on and off while the house is above the peak aim ([[SAFETY-88]]). +- Two inverters: the "circulating" figure counts a battery's reading at rest ([[SAFETY-98]]). +- Two inverters: a drain that starts during a big step in house use can send the other battery to full power, and about 1 kW goes to the grid for about 10 s ([[SAFETY-104]]). +- Two inverters: when a battery comes back during a maintenance charge, the grid can step by several kW at once ([[SAFETY-101]]). +- Two inverters: when a battery drops out during a solar surplus, the others can swing by up to 1.5 kW in a simulation ([[SAFETY-105]]). +- Two inverters: after a drain ends, a change in house use can go unanswered for about 9 s, because some readings are old ([[SAFETY-106]]). +- Two inverters: when one battery's level is missing, both batteries are held at 0 W, and for about 15 s the last command stays on ([[SAFETY-108]]). +- Two inverters: if one battery's level stays missing for 12 h, the other battery's cycle can be marked failed, with a 7-day wait and a notice, though it is healthy. This comes from reading the code; it has not been seen on a site ([[MAINT-17]]). +- When the 15-minute demand forecast sensor counts the battery's own charge, the maintenance charge runs at about half the power the peak limit leaves, so it takes about twice as long (seen on a site: about 1.2 kW instead of 2.5 kW; the peak limit was kept). At the start of a month, before a peak above the limit, that is about 2 kWh a night in a rig test: the cycle can reach its 36 h limit after about 4 nights and fail, and since 0.22.0 the other battery gets no grid charge on those nights ([[SAFETY-111]]). +- One inverter: after a link drop, the battery's own safety stop to 0 W can be taken as a refusal, and the site stays at 0 W for up to 15 min ([[SAFETY-102]]). +- After a Home Assistant restart, control still waits until Home Assistant has finished starting, which can take several minutes, though the readings are already there ([[SAFETY-115]]). +- While Home Assistant is not answering, the page can list inverters as refusing commands and sensors as missing, and send you to Developer Tools, though they are fine ([[UX-37]]). +- If Home Assistant hangs or stops, the page keeps saying "Waiting for Home Assistant" and never turns into an alarm ([[SAFETY-113]]). +- Right after Home Assistant has started, the page can say for about 4 s that an inverter cannot be controlled, and the first command can come late ([[SAFETY-114]]). +- After a Home Assistant restart, the controller status sensor can still say "running" while the add-on cannot control. It was seen once, and the cause is not known ([[SAFETY-116]]). +- Battery modes on: after a planned top-up from the grid, the Batteries screen can say "Enough sun is forecast" ([[UX-32]]). +- Battery modes on: the forecast line "we count on" can show more sun than the plan counts, because the plan takes house use off first ([[UX-33]]). +- Battery modes on: before a planned top-up, the Today list shows a smaller "gives" amount than the plan will use; it grows as the charge happens ([[UX-34]]). +- Two inverters, battery modes on: while the other battery is in its maintenance charge, a battery's card can say it charges from the grid while it stays at 0 W ([[OPT-18]]). +- Two inverters, battery modes on: while a battery refuses to charge in a cheap run, the action log on the page gets about 8 lines an hour for its retries, and the page hint says "waiting for a better price" ([[UX-38]]). +- A battery in a safety stop, or one the add-on cannot reach, can still be started for a cycle, and its drain then waits about 12 h and ends in a failed-cycle notice. This comes from reading the code; it has not been seen on a site ([[MAINT-19]]). +- On the Settings page, the rows of the solar forecast lists are labelled "Phase 1", "Phase 2" instead of "Sensor 1", "Sensor 2" ([[UX-27]]). +- In the solar forecast list, a blank or repeated row makes "source 2 of 2" count differently from the rows on the Settings page ([[UX-28]]). +- The solar forecast message says "has no reading" also when the sensor shows a number that is too old or in the wrong unit ([[UX-29]]). +- If you use only the forecast lists, two Settings notes sit on the single-sensor field, and one of them tells you to set that field ([[UX-30]]). +- After a restart during a price outage, the "No prices" message can say "yet" when prices did come in earlier ([[UX-39]]). +- On the new settings page, you cannot see whether a price service token is set. Check the Configuration tab ([[UX-41]]). +- On the classic settings page, the first click on Save after editing a field can do nothing. Click again ([[UX-42]]). +- A steady overload on a 1 s meter can warn, and send the Home Assistant notification, 2 or 3 times at the start of each 15-minute period instead of once. The peak limit is still kept ([[SAFETY-122]]). +- A fixed tariff is priced once per hour, so a price window that starts or ends at :15, :30 or :45 gets the wrong price for part of that hour. Windows that start and end on the hour are right ([[TARIFF-23]]). +- Step 6 of the setup wizard stays empty because of an error in the page, in English and in Dutch ([[UX-51]]). +- On Dutch pages, refusal texts, the last-event line under the Home buttons, the installer details and the trading status sentences are still English, and a few Dutch texts read badly, such as "1 metingen geweigerd" ([[UX-52]]). +- Some price texts say "hour" where the add-on acts on a 15-minute period, such as "cheapest hour" ([[UX-47]]). +- After the add-on restarts, the Home price chart shows no price for the earlier part of today, and the setup check can say "12 of 24 hours", though the prices are known ([[UX-48]]). +- With battery modes on and only batteries on "Leftover solar", the Home price chart can mark a cheap period where no battery charges ([[UX-49]]). +- On a phone, the bars of the Home price chart are too thin to tap one 15-minute period. The arrow keys work ([[UX-50]]). +- In the last second of a 15-minute period, being a few watts over the aim can make the peak guard ask a battery for full power for one second. When a charge ends on a period edge, the last-second give can fade out over about 10 s, and a rig test exported up to 7.4 kW for about 8 s ([[SAFETY-124]]). +- During the night grid charge, a 15-minute period can end 6 to 14 W over the peak aim, because the battery charges harder than asked. This was seen in simulation; a rig test saw 2 to 8 W ([[OPT-35]]). +- The test rig could not bring back the false peak alarm that [[SAFETY-126]] fixes, so that fix is shown in simulation only. Watch the notifications for a few nights ([[TEST-35]]). +- The night cheap run is sized for the batteries' full charging power, not for what the peak limit leaves. Under a tight limit the run can end before the batteries reach their level, and Home can show a level they do not reach (79.9 % against a shown 95 % in a rig test) ([[OPT-25]]). +- By day, a Leftover solar plan that has only a daily forecast figure counts the sun from now, not from when the figure was read. It counts about 22 % too much for a figure one hour old; the night plan is not affected ([[OPT-30]]). +- The night charge can buy too much in a house that uses more at night than by day, such as one with a heat pump or a car charger that is not set up in the add-on, and on a sunny day, because spare sun in one expensive hour does not count for the later ones ([[OPT-31]]). +- A cheap run that has already started can overlap a new give run after a re-plan, so a battery can charge from the grid at the dearest price for part of an hour. This was seen in a test case, not on a site. Also in 0.19.2 ([[OPT-32]]). +- If the solar forecast sensors stop updating before 17:00, as in winter or further north, there is no forecast from three hours after their last update until 20:00 ([[OPT-33]]). +- With a forecast that gives only a daily total, the sun is spread an hour off on the two clock-change days after the change. The day's total is right ([[OPT-24]]). +- The add-on learns the house's use only once a solar forecast is set, so a site that adds a forecast later waits one more day for its first plan ([[OPT-26]]). +- Home says "No trading on price yet: no prices have arrived" when every battery is on Solar first, though the prices are shown ([[UX-55]]). +- The Home plan header can say "Charges in the cheapest hour, gives power in the dearest" when Home draws no charge, and it says "hour" for 15-minute prices ([[UX-56]]). +- While the peak guard holds back charging, Home hides the rest of the cheap run and gives no reason. The charge starts again when the guard lets go ([[UX-57]]). +- With battery modes on and selling on, Home can draw a "Sells up to" block when the add-on judges the trade not worth it, and then it will not sell ([[UX-58]]). +- Home, the plan and the Forecast tab stop drawing a battery's give at the trading floor, though control goes on giving down to the battery's cut-out ([[UX-59]]). +- During a price outage, the Batteries screen says "Prices differ too little" and Home says "The price gap is too small" ([[UX-60]]). +- With battery modes on and no meter, or a meter that is a Home Assistant entity, a grid charge is not possible and nothing says so ([[UX-61]]). +- On the Batteries screen, a charge the add-on refused in a cheap run reads as "Saves its power for ...", for up to 15 minutes ([[UX-62]]). +- A Leftover solar battery with no capacity set never charges from the grid when a solar forecast is set, and nothing warns about it ([[UX-63]]). +- The "How the modes work" box on the Batteries screen does not describe Cheap hours only ([[UX-64]]). +- With battery modes on, Settings still shows "Trade on the price spread", which the modes ignore. A site with modes on and no price source starts, and the Batteries screen says "No prices, so it follows the house" without pointing to Settings ([[UX-65]]). +- With battery modes off and several equal prices in a row, Home and the Forecast tab draw one price quarter, while the add-on trades every quarter of the run ([[UX-67]]). +- Late in the day, the Forecast tab's "now" line and last bars sit over the axis labels at the right edge ([[UX-68]]). +- The Forecast tab's level curve charges at each battery's full rating. Under a peak limit the levels it draws are too high and a charge block can end early (54.6 % shown against 39.7 % in a rig test) ([[UX-70]]). +- The peak forecast check says maintenance charging is not kept under the peak limit when no peak forecast is set, but since 0.19.2 it is ([[UX-73]]). +- The peak guard row can show the same figure twice, such as "at this rate 3 500 W, over 3 500 W". Also in 0.19.2 ([[UX-74]]). +- If the inverter's setpoint entity appears in Home Assistant after the add-on has started, the page keeps saying "Inverter control: not found in Home Assistant" and the batteries say "An alarm stopped control" until a restart, though control runs ([[UX-75]]). +- In the last minute of a 15-minute period, with Home Assistant readings 30 s late, the period can end about 80 W over the peak aim and over the limit: 3 530 W against a 3 450 W aim and a 3 500 W limit in a rig test with a 2 kW load added 45 s before the end. The peak guard sees the load too late to hold it back ([[SAFETY-133]]). +- With Home Assistant readings 10 s late, the grid charge in a cheap run can swing by several kW. In a test the add-on asked for an 8.7 kW charge (9.6 kW on 0.20.0) ([[SAFETY-132]]). +- A plan rebuilt while the battery levels are missing for a moment can drop a cheap run that has not started yet, so the battery does not charge that day. Seen in a replay of real prices, where it cost about EUR 0.40 of extra grid use; the Leftover solar change in 0.20.1 no longer triggers it in those replays, but the cause stays ([[OPT-37]]). +- On a 5 s meter, Home Assistant readings 10 s late are still not caught, and readings 15 s late only after about 4 minutes. Control now follows the meter more gently, so less goes to the grid: in a simulation with a changing load, 340 Wh became 189 Wh at 10 s late and 363 Wh became 296 Wh at 15 s late. In a rig test, 15 s late exported 13 to 19 % more than before ([[SAFETY-136]], [[SAFETY-134]]). +- With readings 10 to 15 s late, the hold can end in the middle of the delay and the swing can come back. Seen in rig tests with a 2 s and a 5 s meter ([[SAFETY-134]]). +- With readings 10 s late on a 1 s meter, the grid can still move between -422 and +340 W while the batteries are held. With a very long delay (30 to 90 s) the request can swing by about 900 W every few seconds. Seen in review tests ([[SAFETY-130]]). +- A battery that answers very slowly (10 s or more) can be taken for late Home Assistant readings and held, and the page then blames Home Assistant. A GoodWe battery settles in about 6 s and this has not been seen on one ([[SAFETY-131]]). +- The page row for late readings reads awkwardly in English ("Home Assistant readings show requests about N seconds late, so control holds the batteries"), and the Dutch text misses a word ([[UX-78]]). +- When the add-on stops, a write that takes more than 2 s can still land after the 0 W, and the 30 s safety timer on the ESPHome board then sets 0 W. After the Stop button, a cycle that had already decided can send its share (560 to 670 W) just after the 0 W; the next cycle sends 0 W again ([[SAFETY-138]]). +- In the last hour of a cheap run, Home can draw a battery's grid charge up to an hour past the time control stops charging it. It only draws too much, never too little ([[UX-79]]). +- A tomorrow solar forecast sensor that reports just after midnight with yesterday's value can be used as the new day's forecast for up to 12 hours. This has not been seen on a site ([[OPT-39]]). +- During a cheap-hours charge, at some 15-minute boundaries the add-on sends 0 W for one tick ("no trade (headroom)") and then goes on. Seen in a rig test, in 5 of 8 cases; once, with a frozen battery reading, it left a battery at 0 W until 23:45 ([[OPT-40]]). +- While one battery's monthly cycle charges, the other battery's card on Home says "Saves its power for higher prices", and the plan still shows its grid charge in the cheap hours, though it will not charge ([[UX-80]]). +- After a failed monthly cycle, the plan line shows the day the wait ends, such as 18 November, not when the cycle tries again, such as 19 November at 19:00 ([[MAINT-26]]). +- At the start of a cheap window the peak guard can step once although the period is under the aim, and the step can land on a battery in its monthly charge. In a rig test it gave 1.7 to 2.3 kW for 6 s ([[SAFETY-140]]). +- A grid charge at full power in the last seconds of a 15-minute period can run into the next period, where the peak guard cuts it back ([[SAFETY-139]]). +- In a long real peak, the peak guard can end a 15-minute period up to 10 W over its aim, as 0.22.0 does (up to 31 W there). In a rig test the month's highest peak did not rise ([[SAFETY-141]]). +- The peak reserve notification can be created again and again, 24 to 47 times in 2 hours in a rig test, while the guard holds a battery at its reserve. 0.22.0 does the same ([[MAINT-29]]). +- When you switch the car charger off, its three sensors stay in Home Assistant with their last values. From reading the code, the PV power sensor does the same when it is switched off ([[TEL-19]]). +- In Settings, the choice for no car charger says "None", while its help says "Off" ([[UX-81]]). +- DOCS names the car's energy sensor `goodwe_car_today_kwh`, but Home Assistant creates it as `sensor.goodwe_car_energy_today` ([[TEL-20]]). +- While the car charges in Manual mode, a false "Battery stopped limiting the peak" can still show in the first minutes of a 15-minute period, though the period is heading under the limit. Seen in rig tests, also on builds before this one ([[EV-19]]). +- The fixes for [[EV-14]], [[EV-18]] and [[EV-19]] are shown in tests only: the test rig could not run them or could not show a difference. Watch the Car card and the notifications for a few nights. + +### If you are crossing from a version older than 0.10.0 + +`## 0.10.0` below can refuse an old config: `slew_w` above its limit, and the +withdrawn `price_provider` ids `engie_dynamic`, `totalenergies_dynamic` and +`eneco_eddy`. Read it before you update. Run `tools/predeploy_check.py` with the +bare options (`jq '.data.options'`) first. ## 0.24.0 diff --git a/goodwe_controller/config.yaml b/goodwe_controller/config.yaml index 70daeab..e5faf3c 100644 --- a/goodwe_controller/config.yaml +++ b/goodwe_controller/config.yaml @@ -1,5 +1,5 @@ name: GoodWe RS485 Controller -version: "0.24.0" +version: "0.25.0" slug: goodwe_controller description: >- Drives a GoodWe ES/BP battery inverter over its RS485 EMS port by sending it a -- 2.54.0 From 37b85fffb5ff850f7d0e4c88ead50aa4413e3164 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Wed, 25 Nov 2026 14:01:42 +0100 Subject: [PATCH 54/55] Release 0.25.0: keep the empty "Not in a release yet" heading; cite SAFETY-143 test_ev20_guard T51 needs the heading (PM ruling, option a). CHANGELOG.md only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- goodwe_controller/CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index 0ced066..4330d35 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -1,5 +1,7 @@ # Changelog +### Not in a release yet + ## 0.25.0 **A minor bump: the car can now charge from spare sun (Solar mode), and the Car card raises fewer false alarms. Three new options were added, all with defaults, and none needs setting.** @@ -120,7 +122,7 @@ Contents of this release, in merge order since 0.24.0 (`f66048b`): - When you switch the car charger off, its three sensors stay in Home Assistant with their last values. From reading the code, the PV power sensor does the same when it is switched off ([[TEL-19]]). - In Settings, the choice for no car charger says "None", while its help says "Off" ([[UX-81]]). - DOCS names the car's energy sensor `goodwe_car_today_kwh`, but Home Assistant creates it as `sensor.goodwe_car_energy_today` ([[TEL-20]]). -- While the car charges in Manual mode, a false "Battery stopped limiting the peak" can still show in the first minutes of a 15-minute period, though the period is heading under the limit. Seen in rig tests, also on builds before this one ([[EV-19]]). +- While the car charges in Manual mode, a false "Battery stopped limiting the peak" can still show in the first minutes of a 15-minute period, though the period is heading under the limit. Seen in rig tests, also on builds before this one ([[SAFETY-143]]). - The fixes for [[EV-14]], [[EV-18]] and [[EV-19]] are shown in tests only: the test rig could not run them or could not show a difference. Watch the Car card and the notifications for a few nights. ### If you are crossing from a version older than 0.10.0 -- 2.54.0 From 0862d87c8aa3cae96e2cf806f82dbee6d50f6e8c Mon Sep 17 00:00:00 2001 From: ems-agent Date: Wed, 25 Nov 2026 14:52:33 +0100 Subject: [PATCH 55/55] Release 0.25.0: CHANGELOG wording (release review) Move the tests-only note for EV-14, EV-18 and EV-19 out of Known issues into the car charger fixes paragraph: it cites only closed tickets and has no open card. Name the Pause after option (ev_pause_min) behind the 5 minutes in the Solar paragraph. CHANGELOG.md only. Co-Authored-By: Claude --- goodwe_controller/CHANGELOG.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index 4330d35..264fd00 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -7,9 +7,9 @@ **A minor bump: the car can now charge from spare sun (Solar mode), and the Car card raises fewer false alarms. Three new options were added, all with defaults, and none needs setting.** Three options were added (`ev_margin_w`, `ev_start_min` and `ev_pause_min`), none was removed or renamed, and no default changed (95 options, 92 before). **Existing installs need no option change:** the new options have defaults, and `ev_charger` is still off, so an install that does not use the car charger runs as 0.24.0 did. It is a minor bump because it adds a feature and new options. Every saved setting still starts. -**The car can charge from spare sun (Solar mode).** Choose *Solar* on the Car card or in Home Assistant. The car gets only the sun the house does not use, after the batteries or before them (your choice), and pauses when there is too little. When the sun cannot be measured, for example when the meter goes silent, the current stands for 5 minutes and then goes to 0 A. Every way out of Solar, a stop and a restart set the charger to 0 A. See "Car charger" in DOCS ([[EV-20]], [[EV-51]]). +**The car can charge from spare sun (Solar mode).** Choose *Solar* on the Car card or in Home Assistant. The car gets only the sun the house does not use, after the batteries or before them (your choice), and pauses when there is too little. When the sun cannot be measured, for example when the meter goes silent, the current stands for 5 minutes (*Pause after*, `ev_pause_min`) and then goes to 0 A. Every way out of Solar, a stop and a restart set the charger to 0 A. See "Car charger" in DOCS ([[EV-20]], [[EV-51]]). -**Car charger fixes.** The add-on no longer changes the car's phases while the car still draws. Fewer false "Battery stopped limiting the peak" alarms while the car charges. A current the charger does not take shows one amber row, not two. The Car card's *Why* line says what the charger does and no longer switches between two wordings ([[EV-28]], [[EV-15]], [[EV-18]], [[EV-19]], [[EV-13]], [[EV-14]], [[EV-16]]). +**Car charger fixes.** The add-on no longer changes the car's phases while the car still draws. Fewer false "Battery stopped limiting the peak" alarms while the car charges. A current the charger does not take shows one amber row, not two. The Car card's *Why* line says what the charger does and no longer switches between two wordings ([[EV-28]], [[EV-15]], [[EV-18]], [[EV-19]], [[EV-13]], [[EV-14]], [[EV-16]]). The fixes for [[EV-14]], [[EV-18]] and [[EV-19]] are shown in tests only: the test rig could not run them or could not show a difference. Watch the Car card and the notifications for a few nights. **No change in behaviour:** the build checks now test against a newer copy of the shared test tools. @@ -123,7 +123,6 @@ Contents of this release, in merge order since 0.24.0 (`f66048b`): - In Settings, the choice for no car charger says "None", while its help says "Off" ([[UX-81]]). - DOCS names the car's energy sensor `goodwe_car_today_kwh`, but Home Assistant creates it as `sensor.goodwe_car_energy_today` ([[TEL-20]]). - While the car charges in Manual mode, a false "Battery stopped limiting the peak" can still show in the first minutes of a 15-minute period, though the period is heading under the limit. Seen in rig tests, also on builds before this one ([[SAFETY-143]]). -- The fixes for [[EV-14]], [[EV-18]] and [[EV-19]] are shown in tests only: the test rig could not run them or could not show a difference. Watch the Car card and the notifications for a few nights. ### If you are crossing from a version older than 0.10.0 -- 2.54.0