From c7b1b7dbd1fbb20519de7b8906380c34c8c62744 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 04:21:38 +0100 Subject: [PATCH 1/4] EV-22: Solar and Manual never write over another writer; one rule of control C7: the other-writer watch now runs in every step of a phase change (zero, select, settle) in both writers, with the change's own 0 A and every closing current it tried counted as own. While a difference or a hold stands, nothing non-zero is written over it: no settle close, no EV-28 restore, no select, no Manual undo or abandon. The 6 A raise check stays and runs first. D4 (Solar): the read-back phases are judged like the current, against the phases Solar itself chose (start state = first known read-back outside an own select window, or an own select seen taken), never the plan's adopted n. Same mismatch_since, hold and CHARGER_OTHER; lift only when current and phases both match, or a press. The window of an own select is SETTLE_S from the try's return; a take seen after it is another writer's. DA1: a press that lifts a difference inside a phase change ends the change at its 0 A (both writers); the raise check never holds over a value the press took. DA2: the not-writing path does not judge the current with the reading from before its own 0 A. test_ev22.py (T1-T49, review row T48 (stale)), test_ev22_fuzz.py (T38, N1-N10). test_ev20_writers T46 (a)(b)(c) edited as ruled (PM, v3). Co-Authored-By: Claude --- goodwe_controller/CHANGELOG.md | 1 + goodwe_controller/DOCS.md | 9 +- goodwe_controller/app/carmode.py | 179 +++- goodwe_controller/test_ev20_writers.py | 44 +- goodwe_controller/test_ev22.py | 1050 ++++++++++++++++++++++++ goodwe_controller/test_ev22_fuzz.py | 467 +++++++++++ 6 files changed, 1700 insertions(+), 50 deletions(-) create mode 100644 goodwe_controller/test_ev22.py create mode 100644 goodwe_controller/test_ev22_fuzz.py diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index b627a86..99cc06d 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -2,6 +2,7 @@ ### Not in a release yet +- **Solar no longer writes over another writer's car current or phases.** If something else changes the car's current or its phases, also in the middle of a phase change, the add-on writes nothing over it. After 30 seconds it stops writing until you press Solar, and warns CHARGER_OTHER once. Manual does the same for a current changed during its own phase change ([[EV-22]]). - **A car phase change whose current the charger refuses no longer sends that current five times.** After three refused tries the add-on stops at once and warns CHARGER_REFUSED; the car stays at 0 A until you change something. A value you change meanwhile gets its own three tries ([[EV-59]]). - **A car current the add-on cannot send because of an error is no longer sent again every second.** It counts as a write the charger did not take: 3 tries a minute apart, then the add-on stops and warns CHARGER_REFUSED. The error is logged once per current ([[EV-56]]). - **A peak cut the charger does not take no longer stops Solar.** After three refused tries in a 15-minute period, Solar goes on controlling the car and tries the cut again at the start of the next period while it is still needed. The warning now says "The charger did not take the peak cut, so the add-on tries again next quarter: CHARGER_REFUSED." ([[EV-54]]). diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index ec0ddb2..b46f044 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -3370,10 +3370,11 @@ changes at most once per 30 seconds and only by 1 A or more. 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. +- **Another writer.** If the charger shows a current or a number of phases + that Solar did not set, Solar writes nothing over it from the first moment, + also in the middle of a phase change. After 30 seconds it writes nothing more + (also no 0 A), shows an amber row and logs one warning, until you press Solar + again or the charger shows Solar's own current and phases. - **The peak limit: the car is cut first.** When the 15-minute period heads over the peak limit, Solar lowers the car first, also while the batteries could instead charge less: by the excess, to 0 A when less than 6 A would be left. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index fe8165e..d49f41d 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -150,11 +150,20 @@ class ManualWriter: self._late = None # (a, was, why, n) of a write not taken self._rec_a = None # EV-56: the raised value already logged self._close_k = 0 # EV-59: not-taken closes of the value owed + self._ph_diff = False # EV-22: the phases differ from our own + # (Solar only; Manual never sets it) # ------------------------------------------------------------------ user def user_changed(self) -> None: """The user changed the mode or a value: one more write is allowed, - and another writer's hold is lifted.""" + and another writer's hold is lifted. EV-22 (DA1): a change that lifts + a difference inside a phase change ends the change at its 0 A; the + raise check never holds over the value the user's change took.""" + if self.seq is not None: + if self._other_stands(): + self.seq = None + else: + self.seq["pressed"] = True # the raise check holds off self.boot = False self.rev_applied = None self.hold = self.other = False @@ -192,6 +201,9 @@ class ManualWriter: self._rec_a = None # EV-56 (G2): logged again cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a if self.seq is not None: + # EV-22 (C7): the watch runs in every step of a phase change; the + # change's own values count as own (`_own_values`). + self._watch(cur, now) if self.seq["stage"] in ("zero", "select") \ and (mode != MANUAL or not writing): await self._undo(drv, now, tracker, clamp, shadow) @@ -275,26 +287,54 @@ class ManualWriter: self.fails = max(min(self._close_k, MAX_TRIES) - 1, 0) self._failed(now) - def _watch(self, cur, now) -> None: + def _other_stands(self) -> bool: + """EV-22: another writer's value is held, or its count is running: + nothing non-zero is written over it.""" + return bool(self.hold or self.mismatch_since is not None) + + def _own_values(self) -> list: + """The currents that are ours: what we wrote, tried or saw before a + try, and (EV-22, C7) every value of the phase change under way: its + 0 A and each closing current it tried (also after a user change + cleared `attempted_a`).""" + vals = [x for x in (self.last_a, self.attempted_a, self.prior_a) + if x is not None] + if self.seq is not None: + vals += self.seq.get("own", ()) + return vals + + def _watch(self, cur, now, judge=True) -> None: """Is the read-back what we wrote? A difference that stands for - `WRITER_S` is another writer.""" - known = [x for x in (self.last_a, self.attempted_a, self.prior_a) - if x is not None] - if not known or cur is None: - self.mismatch_since = None + `WRITER_S` is another writer. EV-22: one count and one hold for the + current and (Solar) the phases; `judge=False`: the reading is from + before our own write of this step, so the current is not judged and + the count stands.""" + known, diff = [], None + if judge: + known = self._own_values() + if known and cur is not None: + diff = not any(abs(cur - k) <= TOL_A for k in known) + if diff or self._ph_diff: + if self.mismatch_since is None: + self.mismatch_since = now + elif now - self.mismatch_since >= WRITER_S and not self.hold: + self.hold = self.other = True + if diff: + _LOG.info("Something else changes the charger (read-back " + "%.0f A, the add-on set %.0f A), so the add-on " + "stops writing to it until you change it.", + cur, known[0]) + else: + _LOG.info("Something else changes the charger (the " + "phases are not the ones the add-on chose), so " + "the add-on stops writing to it until you " + "change it.") return - if any(abs(cur - k) <= TOL_A for k in known): - self.mismatch_since = None - if self.hold: - self.hold = self.other = False + if not judge: return - if self.mismatch_since is None: - self.mismatch_since = now - elif now - self.mismatch_since >= WRITER_S and not self.hold: - self.hold = self.other = True - _LOG.info("Something else changes the charger (read-back %.0f A, " - "the add-on set %.0f A), so the add-on stops writing " - "to it until you change it.", cur, known[0]) + self.mismatch_since = None + if diff is False and self.hold: + self.hold = self.other = False # ----------------------------------------------------- EV-52: the info line def _why_default(self) -> str: @@ -410,7 +450,8 @@ class ManualWriter: self.undone += 1 self.rev_applied, self.reapply = None, True a = self._restore_a(q.get("prev"), clamp) - if a is not None: + if a is not None and not self._other_stands(): # EV-22: not over theirs + q.setdefault("own", []).append(a) await self._write(drv, a, 0.0, now, tracker, why="Manual") async def _begin(self, drv, r, cur, n, now, tracker) -> None: @@ -428,7 +469,7 @@ class ManualWriter: self._failed(now) return self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, - "prev": cur} + "prev": cur, "own": [0.0]} async def abandon(self, drv, now, tracker, clamp=None) -> None: """The add-on is stopping in the middle of a phase change: give the car @@ -436,11 +477,19 @@ class ManualWriter: like every write. The phases stay as the select left them.""" q, self.seq = self.seq, None a = None if q is None else self._restore_a(q.get("prev"), clamp) - if a is not None: + if a is not None and not self._other_stands(): # EV-22: not over theirs self._clock = self._clock or (lambda: now) await self._write(drv, a, 0.0, now, tracker, why="shutdown", strict=True) + def _select_try(self, n, ok) -> None: + """EV-22: a phase select of ours went out and returned (Solar's + window and own phases; Manual does not judge phases).""" + + def _took_as_is(self) -> None: + """EV-22 (DA1): a user's change took the charger's value as it is + (Solar forgets what it sent).""" + async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev): q = self.seq if q["stage"] in ("zero", "select") and cur is not None \ @@ -450,11 +499,20 @@ class ManualWriter: # change, and leave the charger to whoever set it until the user # changes something. self.seq = None - self.hold = self.other = True self.last_a = self.attempted_a = self.prior_a = None + if q.get("pressed"): + # EV-22 (DA1): the user's change came during this change: the + # charger is taken as it is, never held over that value. + self._took_as_is() + return + self.hold = self.other = True _LOG.info("Something else raised the charger's current during a " "phase change, so the phases were not touched.") return + if self._other_stands(): + # EV-22 (C7): another writer's value stands (its count runs, or + # it is held): no select, no restore, no closing current over it. + return if q["stage"] == "zero": # A power reading decides; only without one does mode3 (not C, # not D) say the car is quiet. Still drawing at the timeout: no @@ -486,6 +544,7 @@ class ManualWriter: self.last_switch = now self.log.append(("phases", q["n"], now, ok)) q["stage"], q["t1"] = "settle", self.last_done # from its return + self._select_try(q["n"], bool(ok)) 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 @@ -506,6 +565,7 @@ class ManualWriter: # 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) + q.setdefault("own", []).append(a) # EV-22: a value we tried is ours if await self._write(drv, a, 0.0, now, tracker, why=self._close_why(q), n=q["n"] if q.get("sel_ok") else None): @@ -907,6 +967,13 @@ class SolarWriter(ManualWriter): self.sent_cut = False # `sent_a` went out as a cut try self.refused_cut = None # a cut value the charger did not take self._cap_end = False # EV-60: a capped close ended the change + # EV-22 (D4): the phases Solar itself chose. `_own_n`: the last it + # TOOK (or the start state); `_sel_n` and `_win_end`: its latest + # select try and the SETTLE_S after that try returned, in which a + # read-back is not judged. + self._own_n = None + self._sel_n = None + self._win_end = None def owe_start(self) -> None: """C1: the add-on starts in Off while an exit 0 A of its own was still @@ -1009,10 +1076,16 @@ class SolarWriter(ManualWriter): """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() + held = self._other_stands() + had_seq = self.seq is not None + super().user_changed() # EV-22 (DA1): ends a change it lifts self.gave_up, self.fails, self.fail_at = False, 0, None self._stuck_end() + # EV-22: the phases are taken afresh (the start state again); an own + # select's window stays. + self._own_n, self._ph_diff = None, False + if held and had_seq: + self.plan.end_switch(False) if held: self.last_a = None self.sent_a, self.taken = None, True @@ -1266,9 +1339,50 @@ class SolarWriter(ManualWriter): if self.live and not self.hold: await self._put(drv, 0.0, cur, now, tracker, stuck, out=True) - def _watch(self, cur, now) -> None: + def _took_as_is(self) -> None: + self.sent_a, self.taken = None, True + self.refused_cut = None + + def _reset_phases(self, window=True) -> None: + """EV-22: the phases Solar judges start afresh (entering Solar, the + charger's return, a press). The window of an own select goes too + unless it is kept.""" + self._own_n, self._ph_diff = None, False + if window: + self._sel_n = self._win_end = None + + def _select_try(self, n, ok) -> None: + """EV-22 (DA3): our own select try returned. SETTLE_S from now a + read-back is not judged (A7: from its return, not from its send); a + taken select is our phases at once, one the charger did not confirm + becomes ours if a read inside the window shows it.""" + self._sel_n = n + self._win_end = float(self.last_done) + SETTLE_S + if ok: + self._own_n, self._ph_diff = n, False + + def _judge_phases(self, r, now) -> None: + """EV-22 (D4): the read-back phases against the phases Solar itself + chose (never the plan's adopted `n`). Unknown phases and reads inside + a select's window start nothing and lift nothing.""" + p = getattr(r, "phases_allowed", None) + if p not in (1, 3): + return + if self._win_end is not None: + if now <= self._win_end: + if p == self._sel_n: + self._own_n, self._ph_diff = p, False # the take + return + self._sel_n = self._win_end = None + if self._own_n is None: + self._own_n, self._ph_diff = p, False # the start state + return + self._ph_diff = p != self._own_n + + def _watch(self, cur, now, judge=True) -> None: was = self.hold - super()._watch(cur, now) + self._judge_phases(self._r, now) + super()._watch(cur, now, judge) 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: " @@ -1306,6 +1420,7 @@ class SolarWriter(ManualWriter): self.out, self.fault = False, None self.restart = True self.mismatch_since = None + self._reset_phases() self.plan.reset(self.plan.n) def _gap_ok(self, now) -> bool: @@ -1383,7 +1498,7 @@ class SolarWriter(ManualWriter): self.plan.end_switch(False) return self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, - "prev": None, "from": r.phases_allowed} + "prev": None, "from": r.phases_allowed, "own": [0.0]} # ------------------------------------------------------------- step async def held_pause(self, drv, r, *, sun, now, tracker) -> None: @@ -1432,6 +1547,7 @@ class SolarWriter(ManualWriter): # notice. The quarter's try count stays (Q5). self.refused_cut, self.sent_cut, self.cut_warned = None, False, \ False + self._reset_phases() # EV-22: a fresh entry starts clean if not self.engaged: return if sun is not None: @@ -1463,6 +1579,8 @@ class SolarWriter(ManualWriter): self.startup_zero = self.boot and not self._returned self.fresh_start = self.restart = True self.mismatch_since = None + if not self.hold: + self._reset_phases(window=False) # EV-22: start state again self.last_a = self.attempted_a = self.prior_a = None self._rec_a = None # EV-56 (G2): logged again cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a @@ -1497,8 +1615,11 @@ class SolarWriter(ManualWriter): # 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 + n_log = len(self.log) await self._zero(drv, cur, now, tracker, stuck) - self._watch(cur, now) + # EV-22 (DA2): `cur` is from before our own 0 A of this step: + # the current is not judged then (the phases are). + self._watch(cur, now, judge=len(self.log) == n_log) self._shadow_plan(sun, now, clamp, n_now) self.restart = True return @@ -1571,8 +1692,8 @@ class SolarWriter(ManualWriter): if self.drop_ready(cur, stuck): # EV-54 (drop rule): the refused cut value is not sent again. self._drop(cur, now) + self._watch(cur, now) # EV-22 (C7): inside a change too 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. diff --git a/goodwe_controller/test_ev20_writers.py b/goodwe_controller/test_ev20_writers.py index ab00667..3dc6fe7 100644 --- a/goodwe_controller/test_ev20_writers.py +++ b/goodwe_controller/test_ev20_writers.py @@ -217,23 +217,33 @@ check(f"T46: Solar starts on 1 phase (select at the start), then another " 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] -# EV-21: with both batteries at the cut-out, the other writer's 3 phases -# take the period over the aim, so Solar's peak cut lowers the car first, -# within 1 cycle and at 690 W/A (EV-21 T34 (ii)); the 6 A hold and the pause -# follow. Every write in the stretch lowers; none waits for PHASE_GAP_S. -six = [x for x in low if x[1] == 6.0] -check(f"T46 (a)(b): the arithmetic uses the 3 phases the car draws on, and a " - f"lower current (EV-21's cut, the 6 A hold, the pause) is written " - f"within the 30 s rule, never blocked by PHASE_GAP_S ({w46})", - low and six and six[0][0] <= 171 and low[0][0] <= 171 - and all(b[1] < a[1] for a, b in zip(low, low[1:])) - 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) +# EV-22 (PM ruling v3, D4): another writer's phase switch is a mismatch from +# its first cycle, like a foreign current. Solar writes nothing after it (no +# cut, no 6 A hold, no pause: it does not cut a car it does not control) and +# holds after WRITER_S with one CHARGER_OTHER; the guard's alarm path is the +# one it has with the car in Off (`car_solar_can_cut` False), which is the +# alarm. Before (EV-21 T34 (ii) via EV-05): the cut, the 6 A hold and the +# pause were written within the 30 s rule, a 4140 W x 302 s import. +n46 = r46["_log"] +hold46 = next((x["t"] for x in r46["trace"] if x["hold"]), None) +other46 = [m for m in LOG.since(n46, "WARNING") if "CHARGER_OTHER" in m] +check(f"T46 (a)(b): no Solar write after another writer's 3 phases at 140 " + f"({[x for x in w46 if x[0] > 140]}), the hold at {hold46} (170), " + f"CHARGER_OTHER once ({len(other46)})", + not [x for x in w46 if x[0] > 140] + and hold46 is not None and 170 <= hold46 <= 171 and len(other46) == 1) +off46 = run("T46 Off", S.drive, step_fn((300, 700.0), (600, 900.0), base=500.0), + const(3500.0), dur=900, first="car", phases=1, mode="off", + sim=SimCharger(setpoint_a=12), socs={"a": 10.0, "b": 10.0}, + rows=True, events={140: lambda p, c: p.ch.set_phases(3)}) +al_s = [t for t, _n in S.ids(r46, *S.ALARMS)][:1] +al_o = [t for t, _n in S.ids(off46, *S.ALARMS)][:1] +ex_s = [(x["explains"], x["red"]) for x in r46["trace"] if x["t"] >= 142] +ex_o = [(x["explains"], x["red"]) for x in off46["trace"] if x["t"] >= 142] +check(f"T46 (c): the alarm path is the one with the car in Off: the alarm " + f"within 2 s of the Off twin's ({al_s} / {al_o}), car_explains and the " + f"red rows equal in every cycle from 142 s", + al_s and al_o and abs(al_s[0] - al_o[0]) <= 2.0 and ex_s == ex_o) 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)}) diff --git a/goodwe_controller/test_ev22.py b/goodwe_controller/test_ev22.py new file mode 100644 index 0000000..722b6ef --- /dev/null +++ b/goodwe_controller/test_ev22.py @@ -0,0 +1,1050 @@ +"""EV-22: Car Solar mode never writes over another writer; one rule of control +for the current and the phases, inside a phase change as well. +`python3 -B test_ev22.py` + +Rows T1-T37 and T39-T49 and the review row "T48 (stale)" of +reports/EV-22-test-plan.md (T38, the fuzz with N1-N10, is test_ev22_fuzz.py; +T40 is the list of existing suites that must stay green and is run by CI, +test_ev20_writers T46 (a)(b)(c) being the one ruled edit). Every check's +label starts with its id. + +C7: the watch runs in every step of a phase change, in both writers, with the +change's own values counted as own, and nothing is written over another +writer's value (the close, the EV-28 restore, a select). D4: Solar judges the +read-back phases like the current, against the phases it chose itself. DA1: +a press that lifts a difference inside a change ends the change at its 0 A. +DA2: the not-writing path does not judge the current with a reading from +before its own 0 A. DA3: no phase mismatch while an own select is in flight +or settling (SETTLE_S from the try's RETURN). + +Harness: the real Controller on `tools/ev20_sun.py` (`std`), a 1 s cycle on a +model clock; Manual rows run the same plant with `mode="off"` and the +actions that choose Manual. Times are the cycle's second (the plant clock). +"R39": own 1 -> 3 (0 A at 580, select at 582, close at 592); "R8": the car on +3 phases, Solar selects 1 at 121 and writes 12 A at 131. `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 os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode as CM, chargers as CH # 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, _err # noqa: E402,F401 + +STATION = 16.0 + + +# ----------------------------------------------------------------- harness +def setc(a): + return lambda p, c: p.ch.set_current(a) + + +def setph(n): + return lambda p, c: p.ch.set_phases(n) + + +def merge(*dicts): + """Events of several dicts; two at one second run both.""" + out = {} + for d in dicts: + for k, fn in d.items(): + out[k] = both(out[k], fn) if k in out else fn + return out + + +def stop_ctl(p, c): + c.auto = False + + +def start_ctl(p, c): + c.auto = True + + +class XSim(SimCharger): + """The model with phase-select refusal windows on its own clock (t0, t1, + "ignore" | "error"), and phases the charger reports as unknown.""" + + def __init__(self, *a, pwin=(), **kw): + super().__init__(*a, **kw) + self.pwin = list(pwin) + self.unknown = False + + def request_phases(self, n): + for t0, t1, kind in self.pwin: + if t0 <= self.t <= t1: + keep, self.refuse = self.refuse, kind + try: + return super().request_phases(n) + finally: + self.refuse = keep + return super().request_phases(n) + + def _build(self): + out = super()._build() + if self.unknown: + for k in list(out): + if "phases" in k and ("select." in k or "max_allowed" in k): + out[k] = dict(out[k], state="unknown") + return out + + +def unk(on): + def f(p, c): + p.ch.unknown = on + return f + + +class Rec: + """What every cycle ended with, for both writers.""" + + def __init__(self): + self.d = {} + + def __call__(self, p, c, t): + w, m = c.car_solar, c.car_writer + q, mq = w.seq, m.seq + self.d[int(t)] = dict( + ms=w.mismatch_since, hold=w.hold, other=w.other, + cut=c.car_solar_can_cut(), sseq=None if q is None else q["stage"], + mm=m.mismatch_since, mhold=m.hold, + mseq=None if mq is None else (mq["stage"], mq["t0"]), + own_n=getattr(w, "_own_n", None), ph=getattr(w, "_ph_diff", None), + sp=p.ch.setpoint_a, + phs=p.ch.phases_allowed) + + def first(self, key, pred=lambda v: v is not None, lo=0, hi=10 ** 9): + for t in sorted(self.d): + if lo <= t <= hi and pred(self.d[t][key]): + return t + return None + + def every(self, key, pred, lo, hi): + return all(pred(self.d[t][key]) for t in range(lo, hi + 1) + if t in self.d) + + +def other_n(n): + return len([m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m]) + + +def after(r, t0): + """Current writes that reached the charger and selects, from t0 on.""" + return ([x for x in attempts(r) if x[0] >= t0] + + [x for x in r["plant"].wlog if x[0] >= t0 and x[1] == "phases"]) + + +def wl(r, what="current"): + return [(x[0], x[2]) for x in r["plant"].wlog if x[1] == what] + + +def solar(dur, events=None, rec=None, race=False, **kw): + kw.setdefault("rows", True) + return std(dur, race=race, events=events or {}, on_cycle=rec, **kw) + + +R39 = step_fn((400, 600.0 + 4600.0), base=600.0 + 1840.0) +TS = 582 # R39: its select; the close is at 592 (own 6 A) +EXITS = {"Stop": stop_ctl, + "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} + + +def man(dur, events=None, rec=None, race=False, sim=None): + """Manual, 12 A on 1 phase from 0 s; the user picks 3 phases at 100 s: + 0 A at 100, select at 101, close at 111 (R-M).""" + base = {0: both(act("car_mode", "manual"), act("car_current", 12), + act("car_phases", 1)), + 100: act("car_phases", 3)} + return S.drive(const(500.0), const(500.0), dur=dur, mode="off", + first="car", socs=dict(FULL), phases=1, sim=sim, + events=merge(base, events or {}), on_cycle=rec, race=race) + + +def slow_sim(): + s = SimCharger(setpoint_a=0) + s.ramp_w_s, s.stop_delay_s = 50.0, 40.0 + return s + + +# =========================================================================== # +print("PRECONDITIONS") +# =========================================================================== # +rp = man(160, rec=Rec()) +check(f"PRE: Manual's change: 0 A at 100, select at 101, close at 111 " + f"({wl(rp)}, {wl(rp, 'phases')})", + wl(rp) == [(0.0, 12.0), (100.0, 0.0), (111.0, 12.0)] + and wl(rp, "phases") == [(101.0, 3)]) +rs = solar(700, sun=R39) +check(f"PRE: R39: 0 A at 580, select at {TS}, close at 592 " + f"({[x[:3] for x in rs['c'].car_solar.log]})", + [x[:3] for x in rs["c"].car_solar.log if x[0] == "phases"] + == [("phases", 3, float(TS))] + and (592.0, 6.0) in [(x[2], x[1]) for x in rs["c"].car_solar.log + if x[0] == "current"]) + +# =========================================================================== # +print("\nC7, MANUAL (T1-T8)") +# =========================================================================== # +for race in (False, True): + tag = "race" if race else "step" + rec = Rec() + r = man(400, {104: setc(9)}, rec=rec, race=race) + mm, ho = rec.first("mm"), rec.first("mhold", lambda v: v) + check(f"T1 [{tag}]: another writer's 9 A inside Manual's settle: no write " + f"from 104 on, mismatch from {mm}, the hold at {ho} (30 s later, " + f"not 29), 9 A stands ({[x for x in after(r, 104)]})", + after(r, 104) == [] and mm is not None and 104 <= mm <= 105 + and ho is not None and 30 <= ho - mm <= 31 + and r["sim"].setpoint_a == 9.0 and r["c"].car_writer.other) + +rec = Rec() +r = man(300, {104: setc(9), 119: setc(0)}, rec=rec) +w2 = [x for x in after(r, 104) if x[1] > 0] +check(f"T2: the writer sets 0 A at 119: the mismatch ends that cycle, one " + f"close of 12 A at once, no hold ({after(r, 104)}, hold " + f"{rec.first('mhold', lambda v: v)})", + len(w2) == 1 and w2[0][1] == 12.0 and 119 <= w2[0][0] <= 121 + and rec.first("mhold", lambda v: v) is None + and rec.d[121]["mm"] is None) + +rec = Rec() +r = man(300, {104: setc(9), 160: act("car_current", 14)}, rec=rec) +w3 = [x for x in after(r, 160)] +check(f"T3: a user change after the hold: hold and row gone within 2 " + f"cycles, 14 A written, no select ({w3}, hold at 160+ " + f"{rec.first('mhold', lambda v: v, 162)})", + rec.first("mhold", lambda v: v) is not None + and rec.every("mhold", lambda v: not v, 162, 299) + and not r["c"].car_writer.other and r["sim"].setpoint_a == 14.0 + and not [x for x in w3 if x[1] == "phases"]) + +# T4 / T5: the zero stage. +rec = Rec() +r = man(300, {105: setc(5)}, rec=rec, sim=slow_sim()) +mm, ho = rec.first("mm", lo=104), rec.first("mhold", lambda v: v) +check(f"T4: 5 A (under the raise edge) in the zero stage: mismatch from " + f"{mm}, the EV-28 restore at 120 is not written over it, the hold at " + f"{ho}, no select ({after(r, 105)})", + mm is not None and mm <= 106 and after(r, 105) == [] + and ho is not None and 30 <= ho - mm <= 31) +for a in (6, 9): + rec = Rec() + r = man(300, {103: setc(a)}, rec=rec, sim=slow_sim()) + check(f"T5 [{a} A]: the raise check holds at once and ends the change, " + f"no select, nothing written after ({after(r, 103)}, hold at " + f"{rec.first('mhold', lambda v: v)})", + rec.first("mhold", lambda v: v) is not None + and rec.first("mhold", lambda v: v) <= 104 and after(r, 103) == [] + and rec.d[110]["mseq"] is None) + +# T6: Manual's own changes are never flagged. +bad6 = [] +for lag in (0.0, 3.0, 12.0): + for race in (False, True): + sim = SimCharger(setpoint_a=0) + sim.lag_s = lag + rec = Rec() + r = man(1400, {800: act("car_phases", 1)}, rec=rec, race=race, + sim=sim) + n = LOG.mark() + if rec.first("mm") is not None or rec.first("mhold", + lambda v: v) is not None: + bad6.append((lag, race, rec.first("mm"))) + if len([x for x in wl(r, "phases")]) != 2: + bad6.append((lag, race, "selects", wl(r, "phases"))) +rec = Rec() +r = man(300, rec=rec, sim=slow_sim()) +if rec.first("mm") is not None or rec.first("mhold", lambda v: v) is not None: + bad6.append(("EV-28", rec.first("mm"))) +check(f"T6: Manual's own changes 1->3 and 3->1 (lag 0/3/12, both orders) and " + f"the EV-28 kept-drawing path: never a mismatch or a hold ({bad6[:3]})", + not bad6) + +# T7: Manual's own close refused, then taken late. +sim7 = TSim(setpoint_a=0, windows=[(111.0, 127.0, "ignore")]) +rec = Rec() +r = man(400, rec=rec, sim=sim7) +check(f"T7: Manual's own close refused 111-127 s, then taken: never a " + f"mismatch or a hold, 12 A in the end (closes {wl(r)[-5:]})", + rec.first("mm") is None and rec.first("mhold", lambda v: v) is None + and r["sim"].setpoint_a == 12.0) + +# T8: another writer in the settle stage, then Stop; a Stop guard. +rec = Rec() +r = man(400, {104: setc(9), 106: stop_ctl}, rec=rec) +check(f"T8: 9 A in the settle stage, Stop at 106: nothing written over it " + f"for 290 s ({after(r, 104)})", after(r, 104) == [] + and r["sim"].setpoint_a == 9.0) +rec = Rec() +r = man(300, {101: stop_ctl}, rec=rec, sim=slow_sim()) +rs8 = [x for x in wl(r) if x[0] > 100] +check(f"T8 guard: Stop in the zero stage, no other writer: exactly one " + f"clamped restore, no select ({wl(r)}, {wl(r, 'phases')})", + len(rs8) == 1 and rs8[0][1] == 12.0 and wl(r, "phases") == [] + and rec.first("mm") is None) + +# =========================================================================== # +print("\nC7, SOLAR (T9-T15)") +# =========================================================================== # +twin = solar(700, sun=R39) +CLOSE = ([x[1] for x in twin["c"].car_solar.log + if x[0] == "current" and x[2] == 592.0] or [None])[0] +for race in (False, True): + tag = "race" if race else "step" + n, rec = LOG.mark(), Rec() + r = solar(800, sun=R39, race=race, rec=rec, events={TS + 3: setc(16)}) + mm, ho = rec.first("ms", lo=TS), rec.first("hold", lambda v: v) + check(f"T9 [{tag}]: another writer's 16 A inside Solar's settle: no close, " + f"no write after it ({after(r, TS + 3)}), mismatch from {mm}, " + f"can_cut False from then ({[rec.d[t]['cut'] for t in range(TS + 4, TS + 8)]}), " + f"hold at {ho} (30 s after), one CHARGER_OTHER ({other_n(n)}), " + f"16 A stands", + after(r, TS + 3) == [] and mm is not None and TS + 3 <= mm <= TS + 4 + and ho is not None and 30 <= ho - mm <= 31 + and not any(rec.d[t]["cut"] for t in range(mm, ho + 1)) + and other_n(n) == 1 and r["sim"].setpoint_a == 16.0 + and "charger_other" in r["trace"][ho + 20]["amber"]) + +rec = Rec() +r = solar(800, sun=R39, rec=rec, events={TS + 3: setc(16), TS + 25: setc(0)}) +w10 = [x for x in after(r, TS + 3) if x[1] > 0] +check(f"T10: the writer back at 0 A at {TS + 25}: the close is written once at " + f"once, with the value it had on base ({CLOSE} A), no hold " + f"({after(r, TS + 3)})", + len(w10) == 1 and w10[0][1] == CLOSE and TS + 25 <= w10[0][0] <= TS + 27 + and rec.first("hold", lambda v: v) is None) +rec = Rec() +r = solar(900, sun=step_fn((400, 600.0 + 4600.0), (TS + 5, 600.0 + 700.0), + base=600.0 + 1840.0), + rec=rec, opts={"ev_pause_min": 1}, + events={TS + 3: setc(16), TS + 70: setc(0)}) +nz = [x for x in after(r, TS + 3) if x[1] > 0 and x[0] >= TS + 3] +check(f"T10 variant: the spare falls under 6 A at {TS + 5} and the pause comes " + f"before the writer is back: no non-zero write over it, 0 A stands " + f"(N4) ({after(r, TS + 3)})", + not nz and r["sim"].setpoint_a == 0.0) + +n, rec = LOG.mark(), Rec() +r = solar(900, sun=R39, rec=rec, events={TS + 3: setc(16), TS + 6: stop_ctl, + TS + 100: start_ctl}) +ho = rec.first("hold", lambda v: v) +check(f"T11: SPIKE-05 C7 trace (16 A at {TS + 3}, Stop at {TS + 6}, Start at " + f"{TS + 100}): the hold at {ho}, 30 s after the change (base: at Stop " + f"+30), nothing written after the change, the hold stands after the " + f"Start ({after(r, TS + 3)})", + ho is not None and ho <= TS + 3 + 32 and after(r, TS + 3) == [] + and rec.every("hold", lambda v: v, ho, 899) and other_n(n) == 1 + and "charger_other" in r["trace"][800]["amber"]) + +r = solar(800, sun=R39, events={TS + 3: setc(16), TS + 6: act("car_mode", "off")}) +check(f"T12: Off at {TS + 6}, after the other writer: nothing written after " + f"the change, 16 A stands ({after(r, TS + 3)})", + after(r, TS + 3) == [] and r["sim"].setpoint_a == 16.0) + +sim13 = slow_sim() +rec = Rec() +r13 = solar(800, sun=R39, sim=sim13, rec=rec) +t0 = ([x[2] for x in r13["c"].car_solar.log + if x[0] == "current" and x[1] == 0.0 and x[2] > 400] or [580.0])[0] +rec = Rec() +r = solar(800, sun=R39, sim=slow_sim(), rec=rec, events={int(t0) + 2: setc(16)}) +check(f"T13: 16 A at {int(t0) + 2}, in the zero stage (the 0 A at {t0}): the " + f"raise check holds at once, no select, nothing written ({after(r, int(t0) + 2)})", + rec.first("hold", lambda v: v) is not None + and rec.first("hold", lambda v: v) <= int(t0) + 4 + and after(r, int(t0) + 2) == []) + +# T14: Solar's own changes are never flagged. +bad14 = [] + + +def own_clean(tag, r, rec, n): + if rec.first("ms") is not None or rec.first("hold", lambda v: v) \ + is not None or other_n(n): + bad14.append((tag, rec.first("ms"), other_n(n))) + + +for race in (False, True): + for lag in (0.0, 12.0): + sim = SimCharger(setpoint_a=0) + sim.lag_s = lag + n, rec = LOG.mark(), Rec() + r = solar(1500, sun=step_fn((400, 5200.0), (900, 1600.0), base=2440.0), + rec=rec, race=race, sim=sim) + own_clean(f"1->3->1 lag {lag} race {race}", r, rec, n) + if lag == 0.0 and not selects(r): + bad14.append(("no select", lag, race)) +n, rec = LOG.mark(), Rec() +r = solar(800, sun=R39, sim=slow_sim(), rec=rec) +own_clean("EV-28", r, rec, n) +n, rec = LOG.mark(), Rec() +r = solar(800, sun=R39, rec=rec, + events={TS + 3: lambda p, c: setattr(p, "meter_on", False), + TS + 30: lambda p, c: setattr(p, "meter_on", True)}) +own_clean("C17 silent meter in settle", r, rec, n) +check(f"T14: Solar's own 1->3 and 3->1 changes (lag 0 and 12, both orders), " + f"the EV-28 path and a silent meter in settle: never a mismatch, a hold " + f"or CHARGER_OTHER ({bad14[:3]})", not bad14) + +bad15 = [] +for gap in (1, 2): + n, rec = LOG.mark(), Rec() + r = solar(800, sun=R39, rec=rec, + events={TS + 3: lambda p, c: p.ch.go_unavailable(True), + TS + 3 + gap: lambda p, c: p.ch.go_unavailable(False)}) + close = [x[0] for x in cur_writes(r) if x[0] > TS and x[1] >= 6.0][:1] + if rec.first("ms") is not None or other_n(n) or not close \ + or close[0] > 596: + bad15.append((gap, rec.first("ms"), close)) +check(f"T15: a 1- and a 2-sample read gap in settle: no mismatch starts, the " + f"close comes at the next real reading ({bad15})", not bad15) + +# =========================================================================== # +print("\nD4: PHASES (T16-T22)") +# =========================================================================== # +R8 = dict(sun=const(3500.0), phases=3) +for race in (False, True): + tag = "race" if race else "step" + n, rec = LOG.mark(), Rec() + r = solar(1500, rec=rec, race=race, events={300: setph(3)}, **R8) + mm, ho = rec.first("ms", lo=290), rec.first("hold", lambda v: v) + check(f"T16 [{tag}]: another writer's 3 phases at 300: no current write, " + f"no select from 300 ({after(r, 300)}), mismatch from {mm}, can_cut " + f"False from then, hold at {ho} (not before 330), one CHARGER_OTHER " + f"({other_n(n)}), the amber row, no select to 1500", + after(r, 300) == [] and mm is not None and 300 <= mm <= 301 + and not rec.d[mm]["cut"] and not rec.d[mm + 1]["cut"] + and not any(rec.d[t]["cut"] for t in range(mm, 1500)) + and ho is not None and 330 <= ho <= 331 and other_n(n) == 1 + and "charger_other" in r["trace"][400]["amber"] + and len(selects(r)) == 1) + +# T17: the alarm path against the Off twin. +bad17 = [] +for house, sw in ((500.0, 300), (700.0, 140), (900.0, 140)): + kw = dict(dur=900, first="car", socs={"a": 10.0, "b": 10.0}, car_phases=3, + rows=True) + rs = S.drive(const(house), const(3500.0 + house), phases=3, + events={sw: setph(3)}, **kw) + ro = S.drive(const(house), const(3500.0 + house), phases=1, mode="off", + sim=SimCharger(setpoint_a=14), events={sw: setph(3)}, **kw) + ts_ = [t for t, n_ in S.ids(rs, *S.ALARMS)][:1] + to_ = [t for t, n_ in S.ids(ro, *S.ALARMS)][:1] + ex_s = [x["explains"] for x in rs["trace"] if x["t"] >= sw + 2] + ex_o = [x["explains"] for x in ro["trace"] if x["t"] >= sw + 2] + rd_s = [x["red"] for x in rs["trace"] if x["t"] >= sw + 2] + rd_o = [x["red"] for x in ro["trace"] if x["t"] >= sw + 2] + if not (ts_ and to_ and abs(ts_[0] - to_[0]) <= 2.0): + bad17.append((house, sw, "alarm", ts_, to_)) + if ex_s != ex_o or rd_s != rd_o: + bad17.append((house, sw, "rows")) +check(f"T17: the alarm path after a foreign phase switch is the Off twin's " + f"(alarm within 2 s, car_explains and the red rows equal) ({bad17[:2]})", + not bad17) + +n, rec = LOG.mark(), Rec() +r = solar(1500, rec=rec, events={300: setph(3), 320: setph(1)}, **R8) +check(f"T18: the writer back to 1 phase at 320: the mismatch ends within a " + f"cycle, no hold, no warning, Solar goes on by its rules " + f"(mismatch {rec.first('ms', lo=290)}.., {other_n(n)} warnings)", + rec.first("ms", lo=290) is not None and rec.first("ms", lo=290) <= 301 + and rec.every("ms", lambda v: v is None, 322, 1499) + and not any(rec.d[t]["hold"] for t in rec.d) and other_n(n) == 0 + and [x for x in after(r, 300) if x[0] < 320] == []) + +n, rec = LOG.mark(), Rec() +r = solar(900, rec=rec, events={300: setph(3), 400: setph(1)}, **R8) +check(f"T19: hold at 330, the writer back to 1 phase at 400: hold and row " + f"gone within a cycle, one warning ({other_n(n)})", + rec.first("hold", lambda v: v) is not None + and rec.every("hold", lambda v: not v, 402, 899) and other_n(n) == 1 + and "charger_other" not in r["trace"][450]["amber"]) +n, rec = LOG.mark(), Rec() +r = solar(900, rec=rec, events={300: both(setc(16), setph(3)), 400: setph(1), + 450: setc(12)}, **R8) +check(f"T19 variant: the writer also set 16 A and only the phases come back: " + f"the hold stands until the current is back at 12 A (450)", + rec.every("hold", lambda v: v, 335, 449) + and rec.every("hold", lambda v: not v, 452, 899) and other_n(n) == 1) + +n, rec = LOG.mark(), Rec() +r = solar(1200, rec=rec, events={300: setph(3), 600: act("car_mode", "solar")}, + **R8) +sel20 = [x for x in selects(r) if 600 <= x[0] < 121 + CM.PHASE_GAP_S + 1] +check(f"T20: a press of Solar at 600 lifts the hold within a cycle; the 3 " + f"phases are Solar's own, no select before Solar's own dwell and gap " + f"(PHASE_GAP_S after its select at 121: {selects(r)}), no new hold " + f"({sel20}, own phases {rec.d[650]['own_n']})", + rec.every("hold", lambda v: not v, 601, 1199) + and rec.d[650]["own_n"] == 3 and not sel20 and other_n(n) == 1 + and rec.every("ms", lambda v: v is None, 603, 1199)) + +n, rec = LOG.mark(), Rec() +r = solar(900, rec=rec, events={300: stop_ctl, 400: setph(3), + 600: start_ctl}, **R8) +check(f"T21: Stop at 300 (0 A), another writer's phases at 400, Start at 600: " + f"hold at {rec.first('hold', lambda v: v)} (430), nothing written, the " + f"amber row after the Start ({after(r, 301)})", + rec.first("hold", lambda v: v) is not None + and 430 <= rec.first("hold", lambda v: v) <= 431 + and after(r, 301) == [] and other_n(n) == 1 + and "charger_other" in r["trace"][700]["amber"]) + +bad22, bad23 = [], [] +for name, fn in EXITS.items(): + r = solar(900, events={300: setph(3), 400: fn}, opts={"shadow_mode": "off"}, + **R8) + if after(r, 300) != [] or r["sim"].setpoint_a != 12.0 \ + or r["sim"].phases_allowed != 3: + bad22.append((name, after(r, 300))) + r = solar(900, events={300: setph(3), 310: fn}, opts={"shadow_mode": "off"}, + **R8) + aft = after(r, 300) + if not (len(aft) == 1 and aft[0][1] == 0.0 and 310 <= aft[0][0] <= 311): + bad23.append((name, aft)) +check(f"T22: under the phase hold (330) an exit at 400 writes nothing from " + f"300 to the end; 12 A and 3 phases stand ({bad22[:2]})", not bad22) +check(f"T23: an exit at 310, during the count: the way-out 0 A within a cycle, " + f"no select, nothing non-zero ({bad23[:2]})", not bad23) + +# T24: a fresh entry starts clean. +n, rec = LOG.mark(), Rec() +r = S.drive(const(500.0), const(3500.0 + 500.0), dur=1000, mode="manual", + first="car", socs=dict(FULL), phases=1, rows=True, on_cycle=rec, + events={0: both(act("car_current", 10), act("car_phases", 3)), + 600: act("car_mode", "solar")}) +check(f"T24 (i): Manual 10 A on 3 phases, Solar chosen at 600: no mismatch, " + f"no hold, no warning, the start state is 3 phases " + f"({rec.d[605]['own_n']}, sets {wl(r)[:4]})", + rec.first("ms", lo=600) is None and rec.first( + "hold", lambda v: v) is None and other_n(n) == 0 + and rec.d[605]["own_n"] == 3) +n, rec = LOG.mark(), Rec() +r = solar(1000, rec=rec, events={300: setph(3), 500: act("car_mode", "off"), + 700: act("car_mode", "solar")}, **R8) +check(f"T24 (ii): a phase hold, Off at 500, Solar chosen at 700: no hold, no " + f"new warning, start state 3 ({other_n(n)}, {rec.d[705]['own_n']})", + rec.every("hold", lambda v: not v, 702, 999) and other_n(n) == 1 + and rec.every("ms", lambda v: v is None, 702, 999) + and rec.d[705]["own_n"] == 3) + +# T25: unknown phases. +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, sim=XSim(setpoint_a=0), + events={310: unk(True), 340: unk(False)}, **R8) +check("T25 (i): phases unknown 310-340 with no other writer: no mismatch, no " + "hold", rec.first("ms") is None + and rec.first("hold", lambda v: v) is None and other_n(n) == 0) +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, sim=XSim(setpoint_a=0), + events={300: setph(3), 310: unk(True), 320: unk(False)}, **R8) +check(f"T25 (ii): another writer's phases at 300, unknown 310-320: no write and " + f"no select, no lift on unknown, the hold at 330 ({after(r, 300)}, hold " + f"{rec.first('hold', lambda v: v)})", + after(r, 300) == [] and rec.every("ms", lambda v: v is not None, 301, + 329) + and 330 <= (rec.first("hold", lambda v: v) or 0) <= 331) + +# T26: stale reads. +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, + events={290: lambda p, c: p.ch.freeze(), 300: setph(3), + 400: lambda p, c: p.ch.freeze(False)}, **R8) +mm26 = rec.first("ms", lo=290) +check(f"T26 (i): a frozen (stale) charger 290-400 hides another writer's " + f"phases of 300: no mismatch during the freeze, mismatch from {mm26}, " + f"hold at {rec.first('hold', lambda v: v)} (430), no non-zero write " + f"over it ({[x for x in after(r, 300) if x[1] != 0.0]})", + mm26 is not None and 400 <= mm26 <= 402 + and rec.every("ms", lambda v: v is None, 295, 399) + and 430 <= (rec.first("hold", lambda v: v) or 0) <= 433 + and not [x for x in after(r, 400) if x[1] != 0.0]) +bad26 = [] +for lag in (3.0, 12.0): + for race in (False, True): + sim = SimCharger(setpoint_a=0) + sim.lag_s = lag + rec = Rec() + solar(400, rec=rec, sim=sim, race=race, **R8) + if rec.first("ms") is not None: + bad26.append((lag, race)) +check(f"T26 (ii): the cycles after an own select read before it was " + f"confirmed: never a mismatch ({bad26})", not bad26) + +# T27: failed reads. +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, + events={300: setph(3), 310: lambda p, c: p.ch.go_unavailable(True), + 312: lambda p, c: p.ch.go_unavailable(False)}, **R8) +check(f"T27 (i): a 2-sample read gap at 310 does not end the mismatch: no " + f"write, hold at {rec.first('hold', lambda v: v)} (330-331)", + after(r, 300) == [] and 330 <= (rec.first("hold", lambda v: v) or 0) + <= 332) +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, + events={300: lambda p, c: p.ch.go_unavailable(True), + 360: setph(3), 420: lambda p, c: p.ch.go_unavailable(False)}, + **R8) +check(f"T27 (ii): the charger away 300-420, phases changed at 360: no hold, " + f"no warning, the start state is the read-back at the return " + f"({rec.d[430]['own_n']})", + rec.first("hold", lambda v: v) is None and other_n(n) == 0 + and rec.d[430]["own_n"] == 3) +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, + events={300: setph(3), 400: lambda p, c: p.ch.go_unavailable(True), + 520: lambda p, c: p.ch.go_unavailable(False)}, **R8) +check(f"T27 (iii): a hold standing, the charger away 400-520: the hold stands, " + f"nothing is written ({after(r, 300)})", + after(r, 300) == [] and rec.every("hold", lambda v: v, 335, 699)) + +# =========================================================================== # +print("\nDA3, THE WINDOW (T28, T29, T47-T49)") +# =========================================================================== # +# R8: select 1 at 121 (sim 122); refused it returns at 131 (TOOK_S), the close +# is at 141 on the old phases. +SEL, TR = 121, 131 +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, sim=XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")]), + **R8) +check(f"T28: Solar's select refused: the close goes on the old phases, the old " + f"phases are never a mismatch, own phases stay 3 ({wl(r)[:3]}, " + f"{rec.d[300]['own_n']})", + rec.first("ms") is None and rec.first("hold", lambda v: v) is None + and other_n(n) == 0 and rec.d[300]["own_n"] == 3 + and r["sim"].phases_allowed == 3 and wl(r)[0][0] >= TR) +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, sim=XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")]), + events={TR + 5: setph(1)}, **R8) +check(f"T28 variant: the select is taken 5 s after it returned, inside its " + f"window: own, no mismatch, own phases 1 ({rec.d[300]['own_n']})", + rec.first("ms") is None and rec.first("hold", lambda v: v) is None + and other_n(n) == 0 and rec.d[300]["own_n"] == 1) + +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, events={SEL + 3: setph(3)}, **R8) +close = [x for x in cur_writes(r) if x[0] >= SEL + 5][:1] +mm = rec.first("ms", lo=SEL) +check(f"T29: another writer's 3 phases at {SEL + 3}, inside Solar's own taken " + f"3->1 settle: the close is at the 3-phase value ({close}), the " + f"mismatch from the window's end ({mm}, {SEL + 10}+1), the hold 30 s " + f"later, no select back ({selects(r)})", + close and close[0][1] <= 6.0 and mm is not None + and SEL + 10 < mm <= SEL + 12 + and mm + 30 <= (rec.first("hold", lambda v: v) or 0) <= mm + 31 + and len(selects(r)) == 1 and other_n(n) == 1) + +# T30, T31. +n, rec = LOG.mark(), Rec() +r = solar(1800, rec=rec, car_phases=1, **R8) +check("T30: a one-phase car on a 3-phase allowance, 1800 s: never a mismatch", + rec.first("ms") is None and rec.first("hold", lambda v: v) is None + and other_n(n) == 0) +for opt, ph0, ph1 in (("3", 3, 1), ("1", 1, 3)): + n, rec = LOG.mark(), Rec() + r = solar(700, rec=rec, sun=const(3500.0), phases=ph0, + opts={"ev_phases": opt}, events={300: setph(ph1)}) + check(f"T31 [ev_phases {opt}]: another writer's {ph1} phases at 300: as " + f"T16 (mismatch {rec.first('ms', lo=290)}, hold " + f"{rec.first('hold', lambda v: v)})", + after(r, 300) == [] and 300 <= (rec.first("ms", lo=290) or 0) <= 301 + and 330 <= (rec.first("hold", lambda v: v) or 0) <= 331 + and other_n(n) == 1) + +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, events={300: both(setc(16), setph(3)), + 400: setph(1), 450: setc(12)}, **R8) +check(f"T32: the other writer changes current and phases at 300: one hold at " + f"{rec.first('hold', lambda v: v)}, one warning ({other_n(n)}); the " + f"phases back at 400 alone keep it, the current back at 450 lifts it", + 330 <= (rec.first("hold", lambda v: v) or 0) <= 331 and other_n(n) == 1 + and rec.every("hold", lambda v: v, 335, 449) + and rec.every("hold", lambda v: not v, 452, 699)) +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, events={300: both(setc(16), setph(3)), + 400: setc(12), 450: setph(1)}, **R8) +check(f"T32 variant: the current back at 400 while the other writer's phases " + f"stand: the hold stays (no lift on the current alone); the phases back " + f"at 450 lift it, one warning ({other_n(n)})", + rec.every("hold", lambda v: v, 335, 449) + and rec.every("hold", lambda v: not v, 452, 699) and other_n(n) == 1) + +# T33: a restart. +rw = CM.SolarWriter() +check("T33: a fresh writer (a restart) has no stored hold and no own phases " + "until it reads the charger", + not rw.hold and rw.mismatch_since is None + and getattr(rw, "_own_n", None) is None + and not any("hold" in str(k) or "other" in str(k) + for k in r["store"].data)) +n, rec = LOG.mark(), Rec() +r = solar(300, rec=rec, **R8) +check("T33 (i): the charger on 3 phases from before the start: the first read " + "is the start state, no hold, no warning", + rec.d[5]["own_n"] == 3 and rec.first("ms", hi=120) is None + and other_n(n) == 0) + +# T34: Manual's phases are unchanged. +rec = Rec() +r = man(1500, {300: setph(1), 1000: act("car_current", 13)}, rec=rec) +sel34 = [x for x in wl(r, "phases") if x[0] > 101] +check(f"T34: Manual 12 A on 1 phase, another writer's 3 phases at 300: no " + f"hold, no row, no select until the user changes something ({sel34}), " + f"then the change goes as today", + rec.first("mhold", lambda v: v) is None and rec.first("mm", lo=200) + is None and sel34 and sel34[0][0] >= 1000) + +# T35: a false mismatch never blocks the cut. +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, sim=XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")]), + events={TR + 5: setph(1)}, **R8) +check("T35: after an own select the charger took late and a refused one, the " + "cut is allowed again at once (can_cut True), never a mismatch", + rec.first("ms") is None and all(rec.d[t]["cut"] for t in range(160, 300))) + + +# T36 / T37 / T39: writer level. +class Rd: + def __init__(self, a, ph=1, power=None, state="C"): + self.available = True + self.allowed_a = self.setpoint_a = a + self.phases_allowed = ph + self.power_w = power + self.state = state + self.error = False + self.charging = True + self.current_a = () + self.station_a = None + + +class Trk: + obs_at = None + + def begin_write(self): + pass + + def end_write(self, *_): + pass + + def note_write(self, *a, **k): + pass + + def stuck(self, now): + return False + + +class Drv: + def __init__(self, cur, take=lambda a, d: True, ph=1): + self.cur, self.ph, self.take = cur, ph, take + self.calls, self.now, self.polls, self.sel = [], 0.0, (), [] + + async def write_current(self, a, **kw): + self.calls.append((self.now, float(a))) + if self.take(float(a), self): + self.cur = float(a) + return True + return False + + async def write_phases(self, n): + self.sel.append((self.now, n)) + self.ph = n + return True + + def _clock(self): + return self.now + + async def _sleep(self, s): + self.now += s + + +LOOP = asyncio.new_event_loop() + + +def swriter(cur, ph=1): + w = CM.SolarWriter() + w.engaged, w.mode_was = True, CM.SOLAR + w.fresh_start = w.restart = False + w.was_available = w._seen = True + w.sent_a, w.taken, w.last_a = cur, True, cur + w.plan.a, w.plan.n = cur, ph + + def plan_step(sun, now, clamp, n, gap): + c = w.cut_a + if c is not None and c >= CH.MIN_A and w.plan.a > c + 1e-9: + w.plan._cut(c) + w._plan_step = plan_step + return w + + +def wrun(w, drv, t0, t1, pre=None, rd=None): + trk = Trk() + for t in range(t0, t1 + 1): + drv.now = float(t) + if pre: + pre(w, drv, t) + w.cut_quarter(int(t // 900)) + r = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0) + LOOP.run_until_complete(w.step( + drv, r, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0), + clamp=16.0, now=float(t), tracker=trk, writing=True, + status="charging")) + + +# T36: the cut cap across a lift. +w = swriter(8.0) +drv = Drv(8.0, take=lambda a, d: a > 6.5) # the cut value is refused +w._own_n = 1 + + +def pre36(w, d, t): + w.cut_a, w.cut_on = (6.0, True) + if t == 130: + d.ph = 3 # another writer's phases + if t == 150: + d.ph = 1 # ... and back + + +wrun(w, drv, 0, 1199, pre=pre36) +cut_tries = [int(t) for t, a in drv.calls if a <= 6.0 + 1e-9] +k0 = [t for t in cut_tries if t < 900] +k1 = [t for t in cut_tries if t >= 900] +check(f"T36: 3 refused cut tries in key 0, a phase mismatch at 130 and its " + f"lift at 150: no 4th cut try in the key, tries come again in the next " + f"({k0}, {k1[:3]})", len(k0) == 3 and len(k1) >= 1 and w.cut_fails >= 1) + +# T37: the N3 reading, a 6 A hold and a phase mismatch. +w = swriter(6.0) +drv = Drv(6.0) + + +def pre37(w, d, t): + if t == 60: + d.ph = 3 + if t == 250: + d.ph = 1 + + +wrun(w, drv, 0, 700, pre=pre37) +nz37 = [(int(t), a) for t, a in drv.calls if a > 0] +check(f"T37: a 6 A hold, a phase mismatch at 60 and its lift at 250: nothing " + f"above 6 A is written ({nz37})", all(a <= 6.0 for t, a in nz37)) + +# T39: the start state. +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, sim=XSim(setpoint_a=0), opts={"ev_phases": "3"}, + sun=const(3500.0), phases=3, + events={0: unk(True), 60: unk(False), 300: setph(1)}) +check(f"T39 (i): phases unknown for 60 s, then 3: the start state is 3, " + f"another writer's 1 phase at 300 is a mismatch (hold " + f"{rec.first('hold', lambda v: v)})", + rec.first("ms", hi=290) is None and 300 <= (rec.first("ms") or 0) <= 301 + and 330 <= (rec.first("hold", lambda v: v) or 0) <= 331) +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, sim=XSim(setpoint_a=0), + events={122: unk(True), 123: act("car_mode", "solar"), + 150: unk(False), 300: setph(3)}, **R8) +check(f"T39 (ii): phases unknown while Solar's own select of 1 is taken (a " + f"press at 123 took the start state afresh): own " + f"phases are 1, a later 3 is a mismatch ({rec.d[200]['own_n']}, " + f"{rec.first('ms', lo=250)})", + rec.d[200]["own_n"] == 1 and 300 <= (rec.first("ms", lo=250) or 0) <= 301) +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, + sim=XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")]), + events={122: unk(True), 123: act("car_mode", "solar"), + 134: unk(False)}, **R8) +inside = rec.d[137]["own_n"] +check(f"T39 (iii): the first known read falls inside Solar's own select window " + f"and shows 3: that read is not the start state ({inside}); after the " + f"window own = the phases then read ({rec.d[160]['own_n']}), no mismatch", + inside is None and rec.d[160]["own_n"] == 3 and rec.first("ms") is None) +n, rec = LOG.mark(), Rec() +r = solar(700, rec=rec, sim=XSim(setpoint_a=0), events={0: unk(True)}, **R8) +check("T39 (iv): phases unknown the whole run: never a phase mismatch", + rec.first("ms") is None and rec.first("hold", lambda v: v) is None + and other_n(n) == 0) + +# =========================================================================== # +print("\nG3, DA1, DA2, DA3 (T41-T49)") +# =========================================================================== # +S200 = 200 +HP = 529 # the std run's pause by the silent meter (no other writer) +for tid, setter in (("T41", setc(16)), ("T42", setph(3))): + for k, at in (("(i)", HP - 20), ("(ii)", HP - 40)): + n, rec = LOG.mark(), Rec() + r = solar( + 700, rec=rec, sun=const(600.0 + 2070.0), + events={S200: lambda p, c: setattr(p, "meter_on", False), + at: setter, + HP: lambda p, c: p.ch.go_unavailable(True), + HP + 1: lambda p, c: p.ch.go_unavailable(False)}) + aft = after(r, at) + if k == "(i)": + ok = len(aft) == 1 and aft[0][1] == 0.0 and HP <= aft[0][0] <= HP + 2 + else: + ok = aft == [] + check(f"{tid} {k}: held_pause with another writer's " + f"{'current' if tid == 'T41' else 'phases'} at {at}: " + f"{f'0 A at {HP}' if k == '(i)' else 'nothing written'} ({aft})", + ok) + +# T43: DA1, Manual. +rec = Rec() +r = man(300, {105: setc(5), 108: act("car_current", 14)}, rec=rec, + sim=slow_sim()) +check(f"T43: Manual, 5 A in the zero stage, a press at 108: the change ends at " + f"its 0 A in the press cycle (old t0 100: {rec.d[108]['mseq']}), no hold " + f"and no row up to +120 s, the car ends at 14 A " + f"({r['sim'].setpoint_a})", + (rec.d[108]["mseq"] is None or rec.d[108]["mseq"][1] != 100.0) + and rec.first("mhold", lambda v: v) is None + and r["sim"].setpoint_a == 14.0) +rec = Rec() +r = man(300, {104: setc(9), 108: act("car_current", 14)}, rec=rec) +check(f"T43 variant: 9 A in the settle stage, a press at 108: the change ends " + f"in the press cycle ({rec.d[108]['mseq']}), no hold, 14 A at the end", + rec.d[108]["mseq"] is None and rec.first("mhold", lambda v: v) is None + and r["sim"].setpoint_a == 14.0) + +# T44: DA1, Solar. +n, rec = LOG.mark(), Rec() +r = solar(800, rec=rec, sun=R39, + events={TS + 3: setc(16), TS + 8: act("car_mode", "solar")}) +check(f"T44: Solar, 16 A in the settle stage, a press at {TS + 8}: the change " + f"ends in the press cycle ({rec.d[TS + 8]['sseq']}), no old close, no " + f"hold and no warning up to +120 s ({after(r, TS + 3)}, {other_n(n)})", + rec.d[TS + 8]["sseq"] is None + and rec.every("hold", lambda v: not v, TS + 8, TS + 128) + and other_n(n) == 0 and not [x for x in after(r, TS + 3) + if x[1] == CLOSE and x[0] >= TS + 9]) +n, rec = LOG.mark(), Rec() +t0 = int(t0) +r = solar(800, rec=rec, sun=R39, sim=slow_sim(), + events={t0 + 2: lambda p, c: p.ch.go_unavailable(True), + t0 + 3: setc(16), + t0 + 4: both(lambda p, c: p.ch.go_unavailable(False), + act("car_mode", "solar"))}) +check(f"T44 variant: the zero stage, 16 A seen only after a press: no " + f"raise-check hold ({rec.first('hold', lambda v: v)}), no warning " + f"({other_n(n)})", + rec.first("hold", lambda v: v) is None and other_n(n) == 0) + +# T45: DA2, Solar's own Stop. +bad45 = [] +for name, fn in (("Stop", stop_ctl), ("shadow", EXITS["shadow on"]), + ("latch", EXITS["latch"])): + n, rec = LOG.mark(), Rec() + r = solar(500, rec=rec, events={300: fn}, opts={"shadow_mode": "off"}) + zeros = [x for x in after(r, 300) if x[1] == 0.0] + if rec.first("ms", lo=295) is not None or other_n(n) \ + or len(zeros) != 1: + bad45.append((name, rec.first("ms", lo=295), other_n(n), zeros)) +check(f"T45: Solar's own Stop/shadow/latch with no other writer: its 0 A is " + f"written once and no mismatch is ever counted ({bad45[:2]})", not bad45) + +# T46: DA2, the formal C-stop replay. +n, rec = LOG.mark(), Rec() +r = solar(420, rec=rec, + events={300: setc(16), 324: lambda p, c: p.ch.go_unavailable(True), + 325: setc(10), + 331: both(lambda p, c: p.ch.go_unavailable(False), stop_ctl)}) +check(f"T46: a count from 16 A at 300, held reads 324-330 while the writer " + f"puts 10 A back at 325, Stop at 331: the way-out 0 A at 331, no hold " + f"and no CHARGER_OTHER over Solar's own value ({after(r, 331)}, hold " + f"{rec.first('hold', lambda v: v)}, {other_n(n)})", + rec.first("hold", lambda v: v) is None and other_n(n) == 0 + and [x for x in after(r, 331)] in ([(331.0, 0.0)], [(332.0, 0.0)])) + +# T47: the window's end. +bad47 = [] +for at in (SEL + 9, SEL + 10, SEL + 11): + n, rec = LOG.mark(), Rec() + r = solar(400, rec=rec, events={at: setph(3)}, **R8) + mm = rec.first("ms", lo=SEL) + ho = rec.first("hold", lambda v: v) + if at == SEL + 11: + okk = mm is not None and SEL + 11 <= mm <= SEL + 13 + else: + okk = mm is not None and SEL + 10 < mm <= SEL + 13 + if not (okk and ho is not None and ho <= TR - 10 + 42 and other_n(n) == 1 + and len(selects(r)) == 1): + bad47.append((at, mm, ho, other_n(n))) +check(f"T47: another writer's 3 phases at, and just after, the end of Solar's " + f"own window (121+9, +10, +11): not judged inside it, a mismatch from " + f"the next cycle, the hold 30 s later, one warning ({bad47})", not bad47) + +# T48: a late take after the window. +bad48 = [] +simw = lambda: XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")]) +for at, late in ((TR + 15, True), (TR + 9, False)): + n, rec = LOG.mark(), Rec() + r = solar(500, rec=rec, sim=simw(), events={at: setph(1)}, **R8) + mm = rec.first("ms", lo=TR) + if late: + if not (mm is not None and at <= mm <= at + 2 + and (rec.first("hold", lambda v: v) or 0) <= at + 33 + and other_n(n) == 1 and after(r, at + 2) == []): + bad48.append((at, mm, other_n(n))) + elif mm is not None or other_n(n) or rec.d[300]["own_n"] != 1: + bad48.append((at, mm)) +check(f"T48: Solar's refused select taken by the charger after its window: a " + f"mismatch, then a hold, nothing written; taken inside it: own ({bad48})", + not bad48) +n, rec = LOG.mark(), Rec() +r = solar(500, rec=rec, sim=simw(), + events={TR + 3: lambda p, c: p.ch.freeze(), TR + 5: setph(1), + TR + 12: lambda p, c: p.ch.freeze(False)}, **R8) +mm = rec.first("ms", lo=TR) +check(f"T48 (stale): a take inside the window, first read after the window " + f"because a frozen read lies in between: a mismatch from {mm} " + f"({TR + 12}), then a hold ({rec.first('hold', lambda v: v)})", + mm is not None and TR + 12 <= mm <= TR + 30 + and rec.first("hold", lambda v: v) is not None and other_n(n) == 1) + +# T49: refused retries, each with its own window. +keep_gap = CM.PHASE_GAP_S +CM.PHASE_GAP_S = 60.0 +try: + pw = [(100.0, 10000.0, "ignore")] + n, rec = LOG.mark(), Rec() + r = solar(900, rec=rec, sim=XSim(setpoint_a=0, pwin=pw), **R8) + sel49 = [x[2] for x in r["c"].car_solar.log if x[0] == "phases"] + check(f"T49: a select refused MAX_TRIES times, each after the gap: a " + f"window after each, the old phases never a mismatch, no more " + f"selects after the 3rd ({sel49})", + len(sel49) == CM.MAX_TRIES and rec.first("ms") is None + and r["c"].car_solar.phases_gave_up and other_n(n) == 0) + n, rec = LOG.mark(), Rec() + if len(sel49) < 3: + sel49 = [121.0, 181.0, 241.0] # the run's own tries are missing + t3 = sel49[-1] + r = solar(900, rec=rec, sim=XSim(setpoint_a=0, pwin=pw), + events={int(sel49[1]) + 15: setph(1)}, **R8) + w2_ = [x[2] for x in r["c"].car_solar.log if x[0] == "phases"] + check(f"T49 variant 2: the 2nd try taken inside its window (15 s after " + f"it went): own, no mismatch, own phases 1 " + f"({rec.first('ms', lo=int(sel49[1]))}, {rec.d[500]['own_n']})", + rec.first("ms", lo=int(sel49[1])) is None + and rec.d[int(sel49[1]) + 30]["own_n"] == 1) + n, rec = LOG.mark(), Rec() + r = solar(900, rec=rec, sim=XSim(setpoint_a=0, pwin=pw), + events={int(t3) + 40: setph(1)}, **R8) + check(f"T49 variant 3: a foreign switch 40 s after the 3rd try is a " + f"mismatch from that cycle ({rec.first('ms', lo=int(t3))})", + rec.first("ms", lo=int(t3)) is not None + and int(t3) + 40 <= rec.first("ms", lo=int(t3)) <= int(t3) + 42) +finally: + CM.PHASE_GAP_S = keep_gap + +report() diff --git a/goodwe_controller/test_ev22_fuzz.py b/goodwe_controller/test_ev22_fuzz.py new file mode 100644 index 0000000..9fe1a79 --- /dev/null +++ b/goodwe_controller/test_ev22_fuzz.py @@ -0,0 +1,467 @@ +"""EV-22 T38: the Solar fuzz for the one rule of control (N1-N10 of +reports/EV-22-test-plan.md), 14 seeds of 3600 s, both cycle orders. +`python3 -B test_ev22_fuzz.py` + +A model charger that knows who set its current and its phases last (the +add-on, or another writer); random foreign currents and phase switches at any +stage (zero, select, settle), unknown phases, read gaps, refused selects and +writes, late takes of a refused select inside and after the window, Stop, Off, +shadow, latch, a press (also inside a change), and a silent meter. Every cycle +checks: N1/N2 (no non-zero write, no select over a foreign value or phase that +has stood WRITER_S, unless a press took it), N3 (no mismatch, hold or +CHARGER_OTHER without a foreign event shortly before), N4 (the N3 reading, 6 A +never past the pause), N5 (the cut cap), N6 (the select rules), N7 (no select +under a mismatch or hold), N8 (can_cut False under one), N9 (one +CHARGER_OTHER per hold), N10 (Manual never judges phases; the raise check +never holds over the value a press took). The branches are counted and a +floor is asserted, so a fuzz that never reaches them fails. + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +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 +from ev20_kit import LOG, check, fails, nevers, report # noqa: E402 + +SITES = 14 +STEPS_PER = int(os.environ.get("EV22_FUZZ_STEPS", "3600")) +ONLY = [int(x) for x in os.environ.get("EV22_FUZZ_ONLY", "").split(",") if x] +DEBUG = bool(os.environ.get("EV22_FUZZ_DEBUG")) +WRITER_S = carmode.WRITER_S +# The fuzz shortens Solar's dwells and the phase gap so that a 1 h run holds +# many phase changes (it is the changes that carry C7); nothing else moves. +if not os.environ.get("EV22_FUZZ_SLOW"): + carmode.UP_S, carmode.DOWN_S, carmode.PHASE_GAP_S = 20.0, 30.0, 60.0 + + +class FSim(SimCharger): + """Who set the current and the phases last, and when.""" + ctl = None + + def __init__(self, *a, **kw): + super().__init__(*a, **kw) + self.setter = None + self.cur_other_at = None # a foreign current stands since + self.ph_other_at = None # foreign phases stand since + self.own_ph = None # set at the first event (the start) + self.unknown = False + self.sel_log = [] # (sim t, n, taken?) of own selects + self.late = None # (n, t_sent) a refused select to take + + def _apply(self, what, v): + if what == "current": + self.setter = "solar" + self.cur_other_at = None + else: + self.own_ph = 3 if v == 3 else 1 + self.ph_other_at = None + super()._apply(what, v) + + now_t = 0.0 # the plant's clock (not this model's) + refuse_ph = False # only the phase selects are ignored + + last_sel = None # (n, plant second) of the latest select + + def request_phases(self, n): + self.last_sel = (n, self.now_t) + self.sel_log.append((self.now_t, n, self.refuse_ph, self.refuse, + self.phases_allowed, self.own_ph)) + keep = self.refuse + if self.refuse_ph: + self.refuse = "ignore" + try: + ok = super().request_phases(n) + finally: + self.refuse = keep + if ok and (self.refuse_ph or keep == "ignore"): + self.late = (n, self.now_t) + return ok + + def set_current(self, a): + if abs(float(a) - self.setpoint_a) > 0.5: + self.setter = "other" + self.cur_other_at = self.now_t + super().set_current(a) + + def set_phases(self, n): + super().set_phases(n) + if self.own_ph is None: + return # Solar has no phases of its own yet + if self.phases_allowed != self.own_ph: + self.ph_other_at = self.now_t + else: + self.ph_other_at = None + + def _build(self): + out = super()._build() + if self.unknown: + for k in list(out): + if "phases" in k and ("select." in k or "max_allowed" in k): + out[k] = dict(out[k], state="unknown") + return out + + +COUNT = {} +EVLOG = [] + + +NOW = [0.0] + + +def bump(k, n=1): + COUNT[k] = COUNT.get(k, 0) + n + EVLOG.append((NOW[0], k)) + + +HIST = {} + + +def fuzz_site(seed): + rnd = random.Random(seed) + HIST.clear() + del EVLOG[:] + 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, mem = [], dict(last_foreign=-1e9, press_at=-1e9, hold=False, + rises=0, n_sel=0, n_cur=0, seq=None, zero_cnt=0, + was_ms=False) + pend = {} # name -> end second of an outage + + async def ev(p, c): + sim.ctl = c + w = c.car_solar + t = p.t + NOW[0] = sim.now_t = t + + def takes_charger(): + """The user's press (or Solar entered, or the charger back with + no hold) takes the charger as it is: nothing on it is foreign, + and Solar's phases are the first known read after it (OQ2), which + `on_cycle` copies from Solar's start state.""" + sim.own_ph, sim.ph_other_at = None, None + sim.cur_other_at = None + if pend.get("outage") is not None and t >= pend["outage"] \ + and not w.hold: + takes_charger() + for k, off in (("outage", lambda: p.ch.go_unavailable(False)), + ("meter", lambda: setattr(p, "meter_on", True)), + ("stop", lambda: setattr(c, "auto", True)), + ("unknown", lambda: setattr(sim, "unknown", False)), + ("shadow", lambda: c.o.__setitem__("shadow_mode", + "off"))): + if pend.get(k) is not None and t >= pend[k]: + off() + pend[k] = None + if pend.get("mode") is not None and t >= pend["mode"]: + pend["mode"] = None + mem["press_at"] = t + takes_charger() + await c.handle_action("car_mode", value="solar") + if sim.refuse is not None and rnd.random() < 0.03: + sim.refuse = None + # a late take of a refused select: inside (<= 12 s after it went) or + # after (>= 25 s) the window + if sim.late is not None: + n_, t_ = sim.late + age = t - t_ + if 3 <= age <= 12 and rnd.random() < 0.005: + sim.set_phases(n_) + sim.own_ph = sim.phases_allowed + sim.ph_other_at = None + sim.late = None + bump("late_in") + elif age >= 25 and rnd.random() < 0.2: + sim.set_phases(n_) + mem["last_foreign"] = t + sim.late = None + bump("late_after") + elif age > 400: + sim.late = None + if pend.get("latch") is not None and t >= pend["latch"]: + c.circ_wd.tripped = False + pend["latch"] = None + seqnow = w.seq is not None + s = "_seq" if seqnow else "" + # independent draws; a change in progress draws far more events + if rnd.random() < 0.02: + state["sun"] = max(0.0, min(12000.0, state["sun"] + + rnd.uniform(-8000, 8000))) + if rnd.random() < 0.002: + state["house"] = rnd.uniform(300, 4000) + if rnd.random() < 0.0004 and pend.get("outage") is None: + p.ch.go_unavailable(True) + pend["outage"] = t + rnd.uniform(1, 40) + bump("outage") + if rnd.random() < 0.0003: + (p.ch.unplug if p.ch.state != "A" else p.ch.plug_in)() + if rnd.random() < 0.002: + sim.refuse = rnd.choice([None, "ignore", "ignore", "error"]) + bump("refuse") + if rnd.random() < (0.12 if seqnow else 0.0015): + sim.set_current(rnd.choice([0, 5, 6, 13, 16])) + mem["last_foreign"] = t + bump("f_cur" + s) + if rnd.random() < (0.12 if seqnow else 0.003): + x = rnd.choice([1, 3]) + ls = sim.last_sel + if ls is not None and t - ls[1] <= 25: + # inside Solar's own select window nothing is judged (DA3, + # Finding 4): a foreign switch there can hide behind the take + # and is not drawn; T47 and T48 cover its edges + bump("f_ph_skipped_in_window") + else: + sim.set_phases(x) + if sim.ph_other_at is not None: + mem["last_foreign"] = t + bump("f_ph" + s) + ls = sim.last_sel + in_sel = ls is not None and t - ls[1] <= 40 + if in_sel and sim.unknown: + # a take that nobody could read inside the window is judged when + # seen (DA3, Finding 3): no unknown phases around an own select + sim.unknown, pend["unknown"] = False, None + if rnd.random() < 0.001 and pend.get("unknown") is None \ + and not in_sel: + sim.unknown = True + pend["unknown"] = t + rnd.uniform(3, 30) + bump("unknown") + if (w.hold or w.mismatch_since is not None) and rnd.random() < 0.012: + # the other writer puts its change back: the read-back is ours + if w.last_a is not None: + sim.set_current(w.last_a) + if sim.own_ph is not None: + sim.set_phases(sim.own_ph) + sim.setter = "solar" + sim.cur_other_at = sim.ph_other_at = None + bump("put_back") + if (w.hold or w.gave_up) and rnd.random() < 0.025: + mem["press_at"] = t + takes_charger() + bump("press_hold") + await c.handle_action("car_mode", value="solar") + elif seqnow and rnd.random() < (0.3 if w.mismatch_since is not None + else 0.03): + if w.hold or w.mismatch_since is not None: + bump("lift_press_seq") + mem["press_at"] = t + takes_charger() + bump("press_seq") + await c.handle_action("car_mode", value="solar") + if seqnow and not sim.refuse_ph and rnd.random() < 0.2: + sim.refuse_ph = True # a select the charger ignores + bump("refuse_seq") + elif sim.refuse_ph and rnd.random() < 0.02: + sim.refuse_ph = False + if rnd.random() < 0.0004 and pend.get("meter") is None: + p.meter_on = False + pend["meter"] = t + rnd.uniform(5, 60) + bump("meter") + counting = w.mismatch_since is not None and not w.hold + if rnd.random() < (0.05 if seqnow else 0.05 if counting else 0.0006): + k = rnd.choice(["stop", "shadow", "mode", "latch"]) + bump(k + s) + back = t + rnd.uniform(5, 60) + if k == "stop" and pend.get("stop") is None: + c.auto = False + c.o["shadow_mode"] = rnd.choice(["off", "auto"]) + pend["stop"] = back + elif k == "shadow" and pend.get("shadow") is None: + c.o["shadow_mode"] = "on" + pend["shadow"] = back + elif k == "latch" and pend.get("latch") is None: + c.circ_wd.tripped = True + pend["latch"] = back + elif k == "mode" and pend.get("mode") is None: + await c.handle_action("car_mode", value="off") + pend["mode"] = back + if rnd.random() < 0.0005: + await c.handle_action("car_sun_first", value=rnd.choice( + ["batteries", "car"])) + + def on_cycle(p, c, t): + w, m = c.car_solar, c.car_writer + t = float(t) + if sim.own_ph is None and getattr(w, "_own_n", None) is not None: + sim.own_ph = w._own_n + HIST[t] = (w.mismatch_since, w.hold, getattr(w, "_own_n", None), + getattr(w, "_win_end", None), + None if w.seq is None else w.seq["stage"], + p.ch.phases_allowed, p.ch.own_ph, p.ch.ph_other_at, + w.sent_a, p.ch.setpoint_a) + held = w.hold + was_hold = mem["hold"] + ms = w.mismatch_since is not None + # N8 + if (held or ms) and c.car_solar_can_cut(): + bad.append((seed, t, "N8 can_cut under a mismatch or hold")) + # N10: Manual never judges phases + if getattr(m, "_ph_diff", False): + bad.append((seed, t, "N10 Manual judges phases")) + # N3: a mismatch or hold needs a foreign event shortly before + # (judged where it starts: a foreign value that stands unseen while + # Solar does not watch, no car or a fault, is seen when it does) + explained = (sim.ph_other_at is not None + or sim.cur_other_at is not None + or t - mem["last_foreign"] <= 400 + or t - mem["press_at"] <= 400) + if ((ms and not mem["was_ms"]) or (held and not mem["hold"])) \ + and not explained: + bad.append((seed, t, "N3 mismatch or hold with no foreign event", + w.mismatch_since, held)) + if ms and not mem["was_ms"]: + bump("mismatch") + if mem["seq"] is not None: + bump("mismatch_seq") + mem["was_ms"] = ms + mem["seq"] = w.seq + if held and not mem["hold"]: + mem["rises"] += 1 + bump("hold") + if getattr(w, "_ph_diff", False): + bump("hold_ph") + if mem["hold"] and not held: + if t - mem["press_at"] <= 2: + bump("lift_press") + else: + bump("lift_match") + mem["hold"] = held + # N10: no hold over the value a press took, in the 3 cycles after it + if held and 0 <= t - mem["press_at"] <= 3 \ + and t - mem["last_foreign"] > 3: + bad.append((seed, t, "N10 hold right after a press")) + # N9: one CHARGER_OTHER per hold + others = len([1 for m_ in LOG.since(mem.get("mark", 0), "WARNING") + if "CHARGER_OTHER" in m_]) + if others > mem["rises"]: + bad.append((seed, t, "N9 more CHARGER_OTHER than holds", others, + mem["rises"])) + # N5: the cut cap + if w.cut_fails > carmode.MAX_TRIES: + bad.append((seed, t, "N5 cut tries over the cap", w.cut_fails)) + # N1 / N2 / N7 on the writes of this cycle + for e in p.wlog[mem["n_wlog"]:]: + # a write waits for its read-back, so its own stamp runs ahead of + # the cycle that sent it: judge by the cycle's second + tt, what, v = t, e[1], e[2] + if what == "current" and v > 0: + bump("nz_write") + for lab, since in (("N1 current", sim.cur_other_at), + ("N2 phases", sim.ph_other_at)): + if since is not None and sim.setter in ("other", "solar") \ + and tt - since >= WRITER_S + 2 \ + and mem["press_at"] < since: + bad.append((seed, tt, lab, "write over a foreign " + "value that stood", v, since)) + if what == "phases": + bump("select") + if sim.ph_other_at is not None \ + and tt - sim.ph_other_at >= WRITER_S + 2 \ + and mem["press_at"] < sim.ph_other_at: + bad.append((seed, tt, "N2 select over foreign phases", + sim.ph_other_at, mem["press_at"], + sim.own_ph, sim.phases_allowed)) + if ms or held: + bad.append((seed, tt, "N7 select under a mismatch/hold")) + if what == "current" and v == 0.0 and ms and not held: + bump("zero_in_count") + # (the way-out 0 A of the step in which the count runs out is + # written before the watch holds: OQ1) + if what == "current" and v == 0.0 and held and was_hold: + bad.append((seed, tt, "N2 0 A written under a hold")) + mem["n_wlog"] = len(p.wlog) + if held and (c.car_mode != "solar" or not c.car_writing()): + bump("stop_under_hold") + # N4: 6 A never past the pause + pause_s = 60.0 * carmode.solar_option(c.o, "ev_pause_min") + rd = c.car.reading + avail = bool(rd is not None and rd.available) + 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 w.plan.low_since is not None \ + and t - w.plan.low_since > pause_s + 2.0 and not ms and not held: + bad.append((seed, t, "N4 6 A past the pause")) + + race = seed % 2 == 1 + evs = {t: ev for t in range(30, STEPS_PER)} + mark = LOG.mark() + mem["mark"] = mark + mem["n_wlog"] = 0 + 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"] * 5 + ["1", "3"])}) + r["_log"] = mark + nv = nevers(r, f"N6/N13 seed {seed}", gap=carmode.PHASE_GAP_S) + if DEBUG and bad: + t0 = float(os.environ.get("EV22_FUZZ_T0") or bad[0][1]) + print(" DEBUG first bad", bad[0]) + print(" writes", [(x[0], x[1], x[2]) for x in r["plant"].wlog + if t0 - 90 <= x[0] <= t0 + 5]) + print(" events", sorted(x for x in EVLOG if t0 - 120 <= x[0] <= t0 + 5)) + print(" lag", sim.lag_s, "seed", seed) + print(" selects (plant s, n, refuse_ph, refuse, phases, own)", + [x for x in sim.sel_log if t0 - 200 <= x[0] <= t0 + 5]) + print(" hist (t, ms, hold, own_n, win_end, seq, phases, model own," + " model foreign since)") + for tk in sorted(HIST): + if t0 - 40 <= tk <= t0 + 2: + print(" ", tk, HIST[tk]) + return bad, nv + + +print("T38: THE FUZZ") +allbad, allnv = [], [] +for seed in (ONLY or range(SITES)): + bad, nv = fuzz_site(seed) + allbad += bad + allnv += nv + if bad: + print(" seed", seed, bad[:2]) +check(f"T38: N1-N5, N7-N10 hold in every cycle of {SITES} seeds x " + f"{STEPS_PER} s ({allbad[:3]})", not allbad) +WHAT = { + "N1": "no non-zero current write over a foreign current that stood " + "WRITER_S (the close, the EV-28 restore, an undo included)", + "N2": "no non-zero write and no select over foreign phases that stood " + "WRITER_S; a 0 A is never written under a hold", + "N3": "no mismatch, hold or CHARGER_OTHER without a foreign event shortly " + "before (own writes, own selects, own sequence values, a reading " + "from before the step's own 0 A, unknown, stale or failed reads)", + "N4": "the N3 reading: never 6 A past pause_s", + "N5": "at most MAX_TRIES cut tries per quarter key", + "N7": "no phase select under a mismatch or a hold", + "N8": "car_solar_can_cut is never True under a mismatch or a hold", + "N9": "at most one CHARGER_OTHER per hold", + "N10": "Manual never judges phases; no hold right after a press", +} +for k, txt in WHAT.items(): + check(f"{k}: {txt} (every cycle of {SITES} seeds)", + not [b for b in allbad if b[2].split()[0] == k]) +check(f"N6: no write above the clamp, a select only at 0 A under 100 W, one " + f"per 600 s, no Traceback (nevers of every seed) ({allnv[:2]})", + not allnv) +print(" counts", dict(sorted(COUNT.items())), "UP_S", carmode.UP_S, + "PHASE_GAP_S", carmode.PHASE_GAP_S) +floor = {"mismatch_seq": 20, "hold_ph": 10, "lift_match": 10, "lift_press": 10, + "lift_press_seq": 5, "zero_in_count": 5, "stop_under_hold": 5, + "late_after": 5} +if STEPS_PER >= 3600: + check(f"T38: the fuzz reaches its branches ({ {k: COUNT.get(k, 0) for k in floor} }, " + f"floor {floor})", all(COUNT.get(k, 0) >= v for k, v in floor.items())) +report() -- 2.54.0 From b7c91ff7461a9e14e4e0d7ca0a9534627addf4b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 05:32:46 +0100 Subject: [PATCH 2/4] EV-22: retire the ManualWriter source pin in test_ev60 N7 (PM ruling) The SHA-256 of ManualWriter's source was an EV-60 review-time pin. EV-22 changes ManualWriter by design (C7, DA1), so the pin is removed; the behavioural Manual rows of test_ev56, test_ev59 and test_ev60 are unchanged and green. Co-Authored-By: Claude --- goodwe_controller/test_ev60.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/goodwe_controller/test_ev60.py b/goodwe_controller/test_ev60.py index 3fe988e..c5c8038 100644 --- a/goodwe_controller/test_ev60.py +++ b/goodwe_controller/test_ev60.py @@ -44,7 +44,6 @@ REF_S = "until you press Solar: CHARGER_REFUSED." Q3W = "tries again next quarter: CHARGER_REFUSED." CUTDBG = "The peak cut write failed" REC = "The car charger step failed" -MANUAL_SHA = "284ce1a94bfb7a6335f224a29bddc4e0b80c36af78b5c7907031c511a6a9eaa8" class Cap(logging.Handler): @@ -1075,9 +1074,7 @@ check("N5: no select while the car drew (0 A not taken), over every run", check("N9: no exception out of a step or release in any run (every run " "completed), and no ERROR record on a cut try (G1)", not [e for r in CUT_ONLY for e in r.errs]) -check("T13/N7: ManualWriter's source is 2e09622's, byte for byte", - hashlib.sha256(inspect.getsource(CM.ManualWriter).encode()) - .hexdigest() == MANUAL_SHA) +# T13/N7: EV-60 review-time pin; retired by EV-22, which changes ManualWriter by design (C7, DA1) def tsrc(name): -- 2.54.0 From e0e51dac1261d4540dbc6f714a8becdf420c31ac Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 12:30:17 +0100 Subject: [PATCH 3/4] EV-22 review round 1: press covers one reading, unknown read keeps the count, window ends on the close's clock Major 1: the `pressed` mark of a sequence is consumed by the first `_advance` (the first reading judged after the press); a later raise in the same zero stage gets the raise-check hold again (Solar and Manual). Major 2: with `cur` None `_watch` does not judge the current: the count neither starts nor clears (phases are still judged). Finding 4 (PM): the DA3 window uses the close's own clock and comparison (`now - t1 < SETTLE_S`) and the one step that closes at its end is still inside it, so a `last_done` a fraction of a second after the step's now no longer pushes the close step outside the window. Tests: rows A-D, R1 (Manual red under the mutant), the two fraction rows, all red on b7c91ff. test_ev60: comment exactly as ruled, unused imports gone. Co-Authored-By: Claude --- goodwe_controller/app/carmode.py | 48 ++++++--- goodwe_controller/test_ev22.py | 160 ++++++++++++++++++++++++++++ goodwe_controller/test_ev22_fuzz.py | 2 +- goodwe_controller/test_ev60.py | 4 +- 4 files changed, 194 insertions(+), 20 deletions(-) diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index d49f41d..5cdeceb 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -310,6 +310,9 @@ class ManualWriter: before our own write of this step, so the current is not judged and the count stands.""" known, diff = [], None + if cur is None: + judge = False # an unknown read: the count neither starts + # nor clears (phases are still judged) if judge: known = self._own_values() if known and cur is not None: @@ -492,6 +495,7 @@ class ManualWriter: async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev): q = self.seq + pressed = q.pop("pressed", False) # covers the first reading only if q["stage"] in ("zero", "select") and cur is not None \ and cur >= CH.MIN_A: # Something else raised the current while the car was being @@ -500,9 +504,11 @@ class ManualWriter: # changes something. self.seq = None self.last_a = self.attempted_a = self.prior_a = None - if q.get("pressed"): - # EV-22 (DA1): the user's change came during this change: the - # charger is taken as it is, never held over that value. + if pressed: + # EV-22 (DA1): the user's change came during this change and + # this is the first reading judged after it: the charger is + # taken as it is, never held over that value. A later raise + # is held as ever. self._took_as_is() return self.hold = self.other = True @@ -968,12 +974,13 @@ class SolarWriter(ManualWriter): self.refused_cut = None # a cut value the charger did not take self._cap_end = False # EV-60: a capped close ended the change # EV-22 (D4): the phases Solar itself chose. `_own_n`: the last it - # TOOK (or the start state); `_sel_n` and `_win_end`: its latest - # select try and the SETTLE_S after that try returned, in which a - # read-back is not judged. + # TOOK (or the start state); `_sel_n` and `_win_t1`: its latest + # select try and when that try returned; SETTLE_S after it (and the + # one step that closes there, `_win_last`) a read-back is not judged. self._own_n = None self._sel_n = None - self._win_end = None + self._win_t1 = None + self._win_last = False def owe_start(self) -> None: """C1: the add-on starts in Off while an exit 0 A of its own was still @@ -1349,7 +1356,8 @@ class SolarWriter(ManualWriter): unless it is kept.""" self._own_n, self._ph_diff = None, False if window: - self._sel_n = self._win_end = None + self._sel_n = self._win_t1 = None + self._win_last = False def _select_try(self, n, ok) -> None: """EV-22 (DA3): our own select try returned. SETTLE_S from now a @@ -1357,23 +1365,31 @@ class SolarWriter(ManualWriter): taken select is our phases at once, one the charger did not confirm becomes ours if a read inside the window shows it.""" self._sel_n = n - self._win_end = float(self.last_done) + SETTLE_S + self._win_t1 = float(self.last_done) + self._win_last = False if ok: self._own_n, self._ph_diff = n, False def _judge_phases(self, r, now) -> None: """EV-22 (D4): the read-back phases against the phases Solar itself chose (never the plan's adopted `n`). Unknown phases and reads inside - a select's window start nothing and lift nothing.""" + a select's window start nothing and lift nothing. The window is the + sequence's settle time on the same clock and with the same + comparison as the close (`now - t1 < SETTLE_S`), and the one step + that closes at its end is still inside it, whatever fraction of a + second `last_done` lies after the step's `now`.""" p = getattr(r, "phases_allowed", None) - if p not in (1, 3): - return - if self._win_end is not None: - if now <= self._win_end: - if p == self._sel_n: + if self._win_t1 is not None: + inside = now - self._win_t1 < SETTLE_S + if not inside and not self._win_last: + self._win_last = inside = True # the closing step + if inside: + if p in (1, 3) and p == self._sel_n: self._own_n, self._ph_diff = p, False # the take return - self._sel_n = self._win_end = None + self._sel_n = self._win_t1 = None + if p not in (1, 3): + return if self._own_n is None: self._own_n, self._ph_diff = p, False # the start state return diff --git a/goodwe_controller/test_ev22.py b/goodwe_controller/test_ev22.py index 722b6ef..a4909c3 100644 --- a/goodwe_controller/test_ev22.py +++ b/goodwe_controller/test_ev22.py @@ -1047,4 +1047,164 @@ try: finally: CM.PHASE_GAP_S = keep_gap +# =========================================================================== # +print("\nREVIEW ROUND 1 (rows A-D, R1, the window's closing step)") +# =========================================================================== # + + +class NoneSim(SimCharger): + """The read-back and the setpoint answer with a non-number while + `badcur` (the charger is available, `cur` is None).""" + badcur = False + + def _build(self): + out = super()._build() + if self.badcur: + for k in list(out): + if k.endswith("max_current_socket_1") and \ + ("number." in k or "main_active" in k): + out[k] = dict(out[k], state="n/a") + return out + + +def badcur(on): + def f(p, c): + p.ch.badcur = on + return f + + +class LateSim(SimCharger): + """Ignores current writes while t0 <= sim t < t1 and remembers the last; + `late` (an event) shows it: a write the charger took late.""" + owed = None + t0, t1 = 0.0, 0.0 + + def request_current(self, a): + if self.t0 <= self.t < self.t1: + self.owed = a + keep, self.refuse = self.refuse, "ignore" + try: + return super().request_current(a) + finally: + self.refuse = keep + return super().request_current(a) + + +def late(p, c): + if p.ch.owed is not None: + p.ch.set_current(p.ch.owed) + + +T0Z = int(([x[2] for x in r13["c"].car_solar.log + if x[0] == "current" and x[1] == 0.0 and x[2] > 400] + or [580.0])[0]) +# A (Major 1, Solar): the press covers the first reading only; a later raise +# in the same zero stage is held at once. +n, rec = LOG.mark(), Rec() +r = solar(800, sun=R39, sim=slow_sim(), rec=rec, + events={T0Z + 2: act("car_mode", "solar"), T0Z + 8: setc(16)}) +check(f"T44 (A): Solar, a press at {T0Z + 2} in the zero stage, another " + f"writer's 16 A at {T0Z + 8}: the raise check holds at once " + f"({rec.first('hold', lambda v: v, T0Z + 8)}), nothing written over it " + f"({after(r, T0Z + 8)})", + (rec.first("hold", lambda v: v, T0Z + 8) or 99999) <= T0Z + 9 + and after(r, T0Z + 8) == []) +# B (Major 1, Manual) +rec = Rec() +r = man(300, {102: act("car_current", 14), 106: setc(9)}, rec=rec, + sim=slow_sim()) +check(f"T43 (B): Manual, the user sets 14 A at 102 in the zero stage, another " + f"writer's 9 A at 106: held at once " + f"({rec.first('mhold', lambda v: v, 106)}), nothing written over it " + f"({after(r, 107)})", + (rec.first("mhold", lambda v: v, 106) or 99999) <= 107 + and after(r, 107) == [] and r["sim"].setpoint_a == 9.0) +# C (Major 2, Solar): an unknown read-back leaves the count alone. +n, rec = LOG.mark(), Rec() +r = solar(700, sun=R39, sim=NoneSim(setpoint_a=0), rec=rec, + events={TS + 3: setc(16), TS + 9: badcur(True), + TS + 12: badcur(False)}) +check(f"T9 (C): another writer's 16 A at {TS + 3}, an unknown read-back " + f"{TS + 9}-{TS + 11}: the count stands " + f"({[rec.d[t]['ms'] for t in (TS + 8, TS + 10, TS + 12)]}), nothing " + f"is written over the 16 A ({after(r, TS + 3)}), the hold comes", + rec.every("ms", lambda v: v is not None, TS + 5, TS + 14) + and after(r, TS + 3) == [] + and rec.first("hold", lambda v: v) is not None) +# D (Major 2, Manual) +rec = Rec() +r = man(300, {104: setc(9), 109: badcur(True), 113: badcur(False)}, rec=rec, + sim=NoneSim(setpoint_a=0)) +check(f"T1 (D): Manual, 9 A at 104, an unknown read-back 109-112 over the " + f"close at 111: no write over the 9 A ({after(r, 104)}), the count " + f"stands ({[rec.d[t]['mm'] for t in (108, 110, 112)]})", + after(r, 104) == [] and rec.every("mm", lambda v: v is not None, 106, 112)) +# R1: the sequence's own values count as own after a press (formal note). +lm = LateSim(setpoint_a=0) +lm.t0, lm.t1 = 110.0, 120.0 +rec = Rec() +r = man(260, {113: act("car_current", 12), 120: late}, rec=rec, sim=lm) +check(f"T43 (R1, Manual): the close refused until 120, a press at 113 clears " + f"`attempted_a`, the charger then shows the late close: own value, " + f"never a mismatch or a hold " + f"({rec.first('mm', lo=100)}, {rec.first('mhold', lambda v: v)})", + rec.first("mm", lo=100) is None + and rec.first("mhold", lambda v: v) is None) +ls = LateSim(setpoint_a=0) +ls.t0, ls.t1 = TS + 10.5, TS + 14.0 # the close at 592 (sim 593) ignored +rec = Rec() +r = solar(700, sun=R39, sim=ls, rec=rec, + events={TS + 12: act("car_mode", "solar"), TS + 14: late}) +check(f"T44 (R1, Solar): the close refused from 592, a press at {TS + 12}, " + f"the charger then shows the late close: own value, never a mismatch " + f"or a hold ({rec.first('ms', lo=TS)}, " + f"{rec.first('hold', lambda v: v)})", + rec.first("ms", lo=TS) is None + and rec.first("hold", lambda v: v) is None) + + +# Finding 4: `last_done` a fraction of a second after the step's `now`: the +# step that closes is still inside the window. +def frac_run(taken_late): + w = swriter(0.0, ph=3) + w.plan.a, w.plan.n = 12.0, 1 + drv = Drv(0.0, ph=3) + w.seq = {"stage": "settle", "t0": 119.0, "t1": 121.4, "n": 1, "tries": 0, + "prev": None, "from": 3, "own": [0.0], "sel": True} + w.last_done = 121.4 + w._own_n = 3 + w._select_try(1, not taken_late) + ms = {} + + def pre(w_, d, t): + if taken_late: + d.ph = 1 if t >= 132 else 3 # the take is first seen at 132 + else: + d.ph = 3 if t >= 124 else 1 # another writer's 3 phases + ms[t] = w_.mismatch_since + trk = Trk() + for t in range(122, 138): + drv.now = float(t) + pre(w, drv, t) + rd = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0) + LOOP.run_until_complete(w.step( + drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0), + clamp=16.0, now=float(t), tracker=trk, writing=True, + status="charging")) + ms[t] = w.mismatch_since + return w, drv, ms + + +w, drv, ms = frac_run(False) +cl = [(int(t), a) for t, a in drv.calls if a > 0] +check(f"T29 (fraction): last_done 121.4, the close step at 132 (10.6 s later) " + f"is inside the window: the close is written at 132 ({cl}), no " + f"mismatch at 132 ({ms[132]}), the mismatch from 133 ({ms[133]})", + cl and cl[0][0] == 132 and ms[132] is None and ms[133] == 133.0) +w, drv, ms = frac_run(True) +check(f"T48 (fraction): a take first seen on the closing step (132, last_done " + f"121.4) is Solar's own: own phases {w._own_n}, no mismatch " + f"({ms[132]}, {ms[134]})", + w._own_n == 1 and ms[132] is None and ms[134] is None) + report() diff --git a/goodwe_controller/test_ev22_fuzz.py b/goodwe_controller/test_ev22_fuzz.py index 9fe1a79..657aa34 100644 --- a/goodwe_controller/test_ev22_fuzz.py +++ b/goodwe_controller/test_ev22_fuzz.py @@ -295,7 +295,7 @@ def fuzz_site(seed): if sim.own_ph is None and getattr(w, "_own_n", None) is not None: sim.own_ph = w._own_n HIST[t] = (w.mismatch_since, w.hold, getattr(w, "_own_n", None), - getattr(w, "_win_end", None), + getattr(w, "_win_t1", None), None if w.seq is None else w.seq["stage"], p.ch.phases_allowed, p.ch.own_ph, p.ch.ph_other_at, w.sent_a, p.ch.setpoint_a) diff --git a/goodwe_controller/test_ev60.py b/goodwe_controller/test_ev60.py index c5c8038..0850701 100644 --- a/goodwe_controller/test_ev60.py +++ b/goodwe_controller/test_ev60.py @@ -26,8 +26,6 @@ Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). """ import asyncio -import hashlib -import inspect import logging import os import sys @@ -1074,7 +1072,7 @@ check("N5: no select while the car drew (0 A not taken), over every run", check("N9: no exception out of a step or release in any run (every run " "completed), and no ERROR record on a cut try (G1)", not [e for r in CUT_ONLY for e in r.errs]) -# T13/N7: EV-60 review-time pin; retired by EV-22, which changes ManualWriter by design (C7, DA1) +# EV-60 review-time pin; retired by EV-22, which changes ManualWriter by design (C7, DA1) def tsrc(name): -- 2.54.0 From 7710d45393563ac191d9dbd01a2a933a3e8184a4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 15:12:19 +0100 Subject: [PATCH 4/4] EV-22 review r2: Solar row where R1 is seen (clamp falls between close tries); note on the masked Solar row Test only, no implementation change. Green on e0e51da, red under R1 (seq own dropped). Co-Authored-By: Claude --- goodwe_controller/test_ev22.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/goodwe_controller/test_ev22.py b/goodwe_controller/test_ev22.py index a4909c3..2c49847 100644 --- a/goodwe_controller/test_ev22.py +++ b/goodwe_controller/test_ev22.py @@ -1150,6 +1150,9 @@ check(f"T43 (R1, Manual): the close refused until 120, a press at 113 clears " f"({rec.first('mm', lo=100)}, {rec.first('mhold', lambda v: v)})", rec.first("mm", lo=100) is None and rec.first("mhold", lambda v: v) is None) +# R1 is masked in this row: _adopt takes a read-back equal to sent_a as own +# before the watch (red under R1 only with that take off); the clamp row +# below sees R1 for Solar (EV-22 review round 2). ls = LateSim(setpoint_a=0) ls.t0, ls.t1 = TS + 10.5, TS + 14.0 # the close at 592 (sim 593) ignored rec = Rec() @@ -1161,6 +1164,37 @@ check(f"T44 (R1, Solar): the close refused from 592, a press at {TS + 12}, " f"{rec.first('hold', lambda v: v)})", rec.first("ms", lo=TS) is None and rec.first("hold", lambda v: v) is None) +# R1 for Solar where _adopt does not cover it (review round 2): the clamp +# falls between two close tries, so the retry sends 8 A (sent_a 8); after a +# press the charger shows the FIRST close (12 A) late. Only seq["own"] has it. +w = swriter(0.0, ph=3) +w.plan.a, w.plan.n = 12.0, 1 +drv = Drv(0.0, take=lambda a, d: False, ph=1) +w.seq = {"stage": "settle", "t0": 119.0, "t1": 122.0, "n": 1, "tries": 0, + "prev": None, "from": 3, "own": [0.0], "sel": True} +w.last_done = 122.0 +w._own_n = 3 +w._select_try(1, True) +trk, msr = Trk(), {} +for t in range(123, 143): + drv.now = float(t) + if t == 138: + w.user_changed() + if t == 140 and drv.calls: + drv.cur = drv.calls[0][1] + rd = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0) + LOOP.run_until_complete(w.step( + drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0), + clamp=16.0 if t < 135 else 8.0, now=float(t), tracker=trk, + writing=True, status="charging")) + msr[t] = (w.mismatch_since, w.hold, w.seq is not None) +check(f"T44 (R1, Solar, clamp): close 12 A refused, the retry at the new " + f"clamp 8 A refused, a press at 138, the 12 A shown late at 140: own " + f"inside the change, the retry goes on ({drv.calls}, " + f"{[msr[t] for t in (140, 141, 142)]})", + [a for _, a in drv.calls[:2]] == [12.0, 8.0] + and all(msr[t][0] is None and not msr[t][1] for t in (140, 141)) + and msr[141][2] and (142.0, 8.0) in drv.calls) # Finding 4: `last_done` a fraction of a second after the step's `now`: the -- 2.54.0