From 7d1ed1bbcf247fa62416538291ee5e2cd6ae91e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 3 Dec 2026 23:53:54 +0100 Subject: [PATCH] EV-69: an ended phase change's close values stay own (no false CHARGER_OTHER) A phase change that ends on MAX_TRIES (both writers) or on Solar's EV-60 cap end now carries every value it tried, its 0 A too, until the first of: an own take, any own current write, a user change, a hold, Solar's charger return. A carried take resets fails/gave_up only (GUR). Tests: test_ev69.py (T1-T20, T23-T25), test_ev69_fuzz.py (T21), tools/ev69_kit.py. Co-Authored-By: Claude --- goodwe_controller/app/carmode.py | 42 ++- goodwe_controller/test_ev69.py | 518 ++++++++++++++++++++++++++++ goodwe_controller/test_ev69_fuzz.py | 245 +++++++++++++ goodwe_controller/tools/ev69_kit.py | 308 +++++++++++++++++ 4 files changed, 1112 insertions(+), 1 deletion(-) create mode 100644 goodwe_controller/test_ev69.py create mode 100644 goodwe_controller/test_ev69_fuzz.py create mode 100644 goodwe_controller/tools/ev69_kit.py diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 5cdeceb..8ed20a1 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -152,6 +152,7 @@ class ManualWriter: 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) + self._carry = [] # EV-69: the closes an ended sequence tried # ------------------------------------------------------------------ user def user_changed(self) -> None: @@ -172,6 +173,7 @@ class ManualWriter: self._close_k = 0 # EV-59 self.phase_fails, self.phases_gave_up = 0, False self.attempted_a = self.prior_a = None + self._carry = [] # EV-69: a user change ends the carry self._late = None # EV-52: that request is not current now self._rec_a = None # EV-56 (G2): a raise is logged again @@ -240,6 +242,7 @@ class ManualWriter: self._close_k = 0 if cur is not None: self.last_a = cur # adopt what is already set + self._carry = [] # EV-69: an own take ends the carry # EV-52 (PM Q2): a write taken late is logged once, here. late, self._late = self._late, None if late is not None and abs(cur - float(late[0])) <= TOL_A: @@ -301,7 +304,23 @@ class ManualWriter: if x is not None] if self.seq is not None: vals += self.seq.get("own", ()) - return vals + return vals + self._carry + + def _carry_ok(self) -> bool: + """EV-69: may an ended sequence's values be carried? Manual: yes.""" + return True + + def _carry_end(self, q) -> None: + """EV-69 (OQ1, OQ2): a sequence ended (MAX_TRIES, or Solar's EV-60 cap + end): every value it tried, its 0 A too, stays own on the lifetime of + `attempted_a`/`prior_a`, for a late take of an earlier close. Not when + the end's own value is already taken (`_carry_ok`). It ends at an own + take, any own current write, a user change, a hold, Solar's return.""" + self._carry = list(q.get("own", ())) if self._carry_ok() else [] + + def _carried_take(self) -> None: + """EV-69 (GUR): the charger shows a carried close. Own; the carry + stays. Manual: nothing changes.""" def _watch(self, cur, now, judge=True) -> None: """Is the read-back what we wrote? A difference that stands for @@ -317,11 +336,15 @@ class ManualWriter: known = self._own_values() if known and cur is not None: diff = not any(abs(cur - k) <= TOL_A for k in known) + if not diff and cur > TOL_A and any( + abs(cur - k) <= TOL_A for k in self._carry): + self._carried_take() 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 + self._carry = [] # EV-69: never own after a hold if diff: _LOG.info("Something else changes the charger (read-back " "%.0f A, the add-on set %.0f A), so the add-on " @@ -382,6 +405,7 @@ class ManualWriter: # EV-56: a raise at shutdown is left to the caller (CHARGER_RESTORE). strict = kw.pop("strict", False) self._late = None + self._carry = [] # EV-69: a new own write ends the carry if self._rec_a is not None and abs(self._rec_a - float(a)) > TOL_A: self._rec_a = None # EV-56 (G2): another value tracker.begin_write() # EV-12: the read-back is ours @@ -512,6 +536,7 @@ class ManualWriter: self._took_as_is() return self.hold = self.other = True + self._carry = [] _LOG.info("Something else raised the charger's current during a " "phase change, so the phases were not touched.") return @@ -588,6 +613,7 @@ class ManualWriter: self._close_k += 1 # EV-59: read by Manual's end only if q["tries"] >= MAX_TRIES: # Left at 0 A is the safe side; the next reading re-applies. + self._carry_end(q) # EV-69: the closes tried stay own self.seq, self.last_a, self.reapply = None, None, True self._close_end(now) self.rev_applied = None @@ -1174,6 +1200,17 @@ class SolarWriter(ManualWriter): went (`_write`), a cut try in `cut_fails` too, so the sequence's end adds nothing (Manual's `_close_end` is EV-59's, unchanged).""" + def _carry_ok(self) -> bool: + """EV-69 (formal Dev note 2): the end's own value (`sent_a`) was + already taken (an `_adopt` earlier in the step): nothing is carried.""" + return not self.taken + + def _carried_take(self) -> None: + """EV-69 GUR: a carried take resets `fails` and `gave_up` only, never + `taken` or `last_a`: `sent_a` stays owed, so the clamp value is sent + again at the next RETRY_S step.""" + self.fails, self.gave_up = 0, False + def _cut_gate(self, now) -> bool: """EV-60 (Q1): the quarter key's cut tries are used up, or the last refused one is less than RETRY_S old (`_put`'s two gates).""" @@ -1199,6 +1236,7 @@ class SolarWriter(ManualWriter): v = inner(q) if self._cut_try(min(max(float(v), CH.MIN_A), hi)): if self.cut_fails >= MAX_TRIES: + self._carry_end(q) # EV-69: the closes stay own self.seq, self.last_a, self.reapply = None, None, True self.rev_applied = None self.plan.end_switch(False) @@ -1251,6 +1289,7 @@ class SolarWriter(ManualWriter): self.startup_zero = False self.last_a = cur self.attempted_a = self.prior_a = None + self._carry = [] # EV-69: an own take ends the carry self.fails, self.fail_at, self.gave_up = 0, None, False self.refused_cut = None if self.sent_cut: @@ -1598,6 +1637,7 @@ class SolarWriter(ManualWriter): 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._carry = [] # EV-69: the return ends the carry self._rec_a = None # EV-56 (G2): logged again cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a stuck = bool(tracker is not None and tracker.stuck(now)) diff --git a/goodwe_controller/test_ev69.py b/goodwe_controller/test_ev69.py new file mode 100644 index 0000000..7052ab1 --- /dev/null +++ b/goodwe_controller/test_ev69.py @@ -0,0 +1,518 @@ +"""EV-69: a close value an ended phase change tried stays the add-on's own, so +the charger taking it late is never read as another writer (no false +CHARGER_OTHER, the peak cut never blocked). `python3 -B test_ev69.py` + +Rows T1-T20, T23-T25 and the Never rules N1-N9 of reports/EV-69-test-plan.md +(T21 is test_ev69_fuzz.py, T14 and T22 are the existing suites CI runs). Every +check's label starts with its id. Writer level, `tools/ev69_kit.py`: a +`SolarWriter` / `ManualWriter` on a stub driver, a stub tracker and a stub +reading; time is a 1 s step counter on the model clock. `Base69` is de733f4's +behaviour (the carry switched off): the red side of a row, and the equal side +of T17 (i). + +"S1" is the EV-22 review repro (round 2): own 3 -> 1 select taken (window from +122), clamp 16 up to 134 and 8 from 135, close tries 12 A at 132, 8 A at 137 +and 142 (all refused), a press at 138, MAX_TRIES ends the change at 142, the +12 A shown at 140. "S1-np": no press. "S1-nt": no take at 140. "CE": the +EV-60 cap end (cut_fails 2, close 1 refused, cap 6 A, close 2 = 6 A refused, +then the cap end E). "MW": the Manual shape. + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +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 # noqa: E402 +from named_absence import nth, present # noqa: E402 +from ev69_kit import (Base69, BaseM69, Drv, LOG, LOOP, Rd, Run, CLOCK, # noqa: E402,F401 + REC, cap, check, done, evs, n_other, n_some, near, + nev, press, set_cap, show, swriter, LAST) + + +# ------------------------------------------------------------------ worlds +def mk_s1(cls=None, take=None): + w = swriter(0.0, ph=3, cls=cls) + w.plan.a, w.plan.n = 12.0, 1 + drv = Drv(0.0, take or (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) + return w, drv + + +def clamp_s1(t): + return 16.0 if t < 135 else 8.0 + + +def s1(until=400, ev=(), press_at=138, show_at=140, take=None, cls=None, + cur=None, stale=None, gone=None, writing=None): + w, drv = mk_s1(cls, take) + pairs = list(ev) + if press_at is not None: + pairs.append((press_at, press)) + if show_at is not None: + pairs.append((show_at, lambda w_, d, s: setattr( + d, "cur", d.calls[0][1]))) + r = Run(w, drv) + return r.go(123, until, ev=evs(*pairs), clamp=clamp_s1, cur=cur, + stale=stale, gone=gone, writing=writing) + + +def mk_ce(cls=None, take=None, cut_fails=2, plan_a=8.0): + w = swriter(plan_a, ph=1, cls=cls) + w.cut_key, w.cut_fails, w.cut_fail_at = 0, cut_fails, -100.0 + w.plan._set(plan_a, 130.0, 3) + drv = Drv(plan_a, take or (lambda a, d: a == 0.0), ph=1) + return w, drv + + +def ce(until=960, cls=None, hook=None, ev=(), plan_a=8.0, take=None, + press_after_close2=False): + """Close 1 refused, the cap comes in the step after it, close 2 (a cut + try, 6 A) refused, then the cap end E.""" + w, drv = mk_ce(cls, take, plan_a=plan_a) + st = {"cap": False} + + def h(t, w_, d, s): + nz = [1 for tt, a in d.calls if a > 0] + if nz and not s["cap"]: + s["cap"] = True + set_cap(w_, 6.0) + if press_after_close2 and len(nz) == 2 and not s.get("pr"): + s["pr"] = True + w_.user_changed() + if hook: + hook(t, w_, d, s) + r = Run(w, drv, st=st) + return r.go(130, until, ev=evs(*ev), hook=h) + + +def close_times(r): + return [int(t) for t, a in r.drv.calls if a > 0] + + +def mw(until, user=False, hook2=None, cls=None): + """Manual at 12 A on 1 phase; the user picks 3 phases at 100. Every + current write but the 0 A is refused. Close 1 = 12 A, then the clamp + falls to 8 (or the user lowers the current to 8) before try 2.""" + w = (cls or CM.ManualWriter)() + drv = Drv(12.0, lambda a, d: a == 0.0, ph=1) + st = {"a": 12.0, "n": 1, "rev": 1, "clamp": 16.0} + r = Run(w, drv, kind="manual", st=st) + + def hook(t, w_, d, s): + if t == 100: + w_.user_changed() + s["rev"] += 1 + s["n"] = 3 + nzc = [1 for tt, a in d.calls if a > 0] + if len(nzc) == 1 and not s.get("low"): + s["low"] = True + if user: + w_.user_changed() + s["rev"] += 1 + s["a"] = 8.0 + else: + s["clamp"] = 8.0 + if hook2: + hook2(t, w_, d, s) + return r.go(0, until, hook=hook) + + +# =========================================================================== # +print("S1 (the reviewer's clamp shape), Solar") +# =========================================================================== # +cut150 = (150, cap(6.0)) +base = s1(400, ev=[cut150], cls=Base69) +check(f"T1 [red on base]: S1 on de733f4 (the carry off): mismatch " + f"{base.first_ms(140)}, hold {base.first_hold()}, no peak cut write " + f"({base.calls_from(143, 400, True)[:3]})", + near(base.first_ms(140), 143, 144) and near(base.first_hold(), 173, 174) + and 6.0 not in [a for _, a in base.calls_from(143, 200)]) +r = s1(400, ev=[cut150]) +cut_w = [x for x in r.calls_from(150, 152) if x[1] == 6.0] +check(f"T1: S1 (12 A shown at 140), the cut due at 150: 140-400 no mismatch, " + f"hold, CHARGER_OTHER or 'Something else' line ({r.first_ms(140)}, " + f"{n_other()}, {n_some()}), the 6 A peak cut write " + f"at 150-151 ({cut_w}), gave_up never True", + r.clean(140, 400) and n_other() == 0 and n_some() == 0 and cut_w + and not any(r.gu[t] for t in range(140, 401))) +nev("T1", r) + +r = s1(400) +check("T2: S1 to 400, no cut: no mismatch, hold or CHARGER_OTHER 140-400", + r.clean(140, 400) and n_other() == 0 and n_some() == 0) +w8 = [x for x in r.calls_from(190, 215) if x[1] == 8.0] +check(f"T2: the 8 A retry goes out at about 202 and is refused ({w8}); 12 A " + f"stays own after that write: prior_a = was = 12 " + f"({r.prior[205]}, {r.att[205]})", + len(w8) == 1 and near(w8[0][0], 202, 203) and r.prior[205] == 12.0 + and r.att[205] == 8.0 and r.carry[205] == []) +nev("T2", r) + +# T3 (changed, GUR): H2 and the reset of fails / gave_up +rb = s1(400, press_at=None, ev=[cut150], cls=Base69) +rc = s1(400, press_at=None, ev=[cut150]) +cw = [x for x in rc.calls_from(150, 152) if x[1] == 6.0] +check(f"T3: S1-np, the cut from 150: the 6 A cut write at 150-151 ({cw}), no " + f"mismatch, hold or CHARGER_OTHER 140-400 ({n_other()})", + cw and rc.clean(140, 400) and n_other() == 0) +nev("T3", rc) +rp = s1(400, press_at=None) +check(f"T3: H2, the press is not needed: S1-np on de733f4 gives mismatch " + f"{rb.first_ms(140)}, hold {rb.first_hold()}, gave_up {rb.gu[142]}, " + f"and no cut write ({rb.calls_from(143, 200, True)[:2]}) (B1)", + near(rb.first_ms(140), 143, 144) and rb.first_hold() is not None + and rb.gu[142] is True + and 6.0 not in [a for _, a in rb.calls_from(143, 200)]) +check(f"T3: S1-np, no cut: no mismatch, hold or CHARGER_OTHER 140-400 " + f"({n_other()})", rp.clean(140, 400) and n_other() == 0) +check(f"T3 (GUR): the carried 12 A take resets fails/gave_up only: gave_up " + f"True at 142 ({rp.gu[142]}), False and fails 0 from 143 " + f"({rp.gu[143]}, {rp.fl[143]}); the clamp value 8 A is re-sent at the " + f"next retry ({rp.calls_from(190, 215)}). EV-69 GUR: a carried take " + f"resets fails/gave_up only", + rp.gu[142] is True and not any(rp.gu[t] for t in range(143, 202)) + and all(rp.fl[t] == 0 for t in range(143, 202)) + and rp.calls_from(190, 215) == [(202, 8.0)]) + +# T23 (GUR): a carried take is not an adopt +check(f"T23: S1-np, the carried 12 A take: taken stays False, last_a None, " + f"sent_a 8 A unchanged 143-201 " + f"({set(rp.taken[t] for t in range(143, 202))}, " + f"{set(rp.last_a[t] for t in range(143, 202))}, " + f"{set(rp.sent_a[t] for t in range(143, 202))}); the 8 A goes out at " + f"the next RETRY_S step ({rp.calls_from(143, 400)[:1]})", + all(rp.taken[t] is False for t in range(143, 202)) + and all(rp.last_a[t] is None for t in range(143, 202)) + and all(rp.sent_a[t] == 8.0 for t in range(143, 202)) + and (142 + int(CM.RETRY_S), 8.0) in rp.calls_from(143, 400)) + +# T4: a late take after the end +for tk in (150, 143, 170, 199): + ev = [(tk, show(12.0))] + rb = s1(400, show_at=None, ev=ev, cls=Base69) + r = s1(400, show_at=None, ev=ev) + check(f"T4: S1-nt, 12 A from {tk}: no mismatch 142-400 (the standing 0 A " + f"is no take and does not end the carry) ({r.first_ms(142)}); " + f"base: {rb.first_ms(142)}", + r.clean(142, 400) and n_other() == 0 + and rb.first_ms(142) is not None) + +# T6 (c): a foreign value after the end is still counted and held +r = s1(400, ev=[(160, show(16.0))]) +check(f"T6 (i): S1 then foreign 16 A at 160: mismatch at 160-161 " + f"({r.first_ms(150)}), hold at +30 ({r.first_hold()}) and not +29, " + f"exactly 1 CHARGER_OTHER ({n_other()}), nothing non-zero written 160-" + f"400 ({r.calls_from(160, 400, True)})", + near(r.first_ms(150), 160, 161) and near(r.first_hold(), 190, 191) + and r.first_hold() - r.first_ms(150) == 30 and n_other() == 1 + and not r.calls_from(160, 400, True) and not r.viol) +nev("T6 (i)", r) +r = s1(400, show_at=None, ev=[(150, show(5.0))]) +check(f"T6 (iii): S1-nt, foreign 5 A at 150: mismatch at 150-151 " + f"({r.first_ms(142)}), hold 30 s later ({r.first_hold()}), 1 " + f"CHARGER_OTHER ({n_other()}), nothing non-zero written after " + f"({r.calls_from(150, 400, True)})", + near(r.first_ms(142), 150, 151) and r.first_hold() - r.first_ms(142) + == 30 and n_other() == 1 and not r.calls_from(150, 400, True)) +nev("T6 (iii)", r) + +# T7: OQ3, the known limit and its edge +r = s1(400, show_at=None, ev=[(150, show(12.0))]) +check(f"T7 (i): S1-nt, a foreign value exactly 12 A at 150: no mismatch " + f"150-200 (the accepted OQ3 limit, EV-67 class) ({r.first_ms(150)})", + r.clean(150, 200)) +r = s1(400, show_at=None, ev=[(230, show(12.0))], + take=lambda a, d: a == 8.0 and d.now >= 200) +check(f"T7 (ii): the 8 A retry taken at 202 (an own take ends the bound), " + f"foreign 12 A at 230: mismatch at 230 ({r.first_ms(203)}), hold at " + f"260 ({r.first_hold()}), 1 CHARGER_OTHER ({n_other()})", + near(r.first_ms(203), 230, 231) and near(r.first_hold(), 260, 261) + and n_other() == 1) + +# T10-T13: the bound +r = s1(400, show_at=None, ev=[(150, show(8.0)), (160, show(12.0))]) +check(f"T10: S1-nt, the charger takes 8 A (sent_a, an adopt) at 150, then " + f"shows 12 A at 160: mismatch at 160 ({r.first_ms(150)}), hold at 190 " + f"({r.first_hold()}), 1 CHARGER_OTHER ({n_other()}), nothing non-zero " + f"written 160-400 ({r.calls_from(160, 400, True)})", + near(r.first_ms(150), 160, 161) and near(r.first_hold(), 190, 191) + and n_other() == 1 and not r.calls_from(160, 400, True) + and r.carry[151] == []) +nev("T10", r) +r = s1(400, show_at=None, ev=[(210, show(12.0))]) +check(f"T11: S1-nt, the 8 A retry at about 202 refused on 0 A (prior_a 0), " + f"12 A at 210: mismatch at 210 ({r.first_ms(150)}), hold at 240 " + f"({r.first_hold()}), 1 CHARGER_OTHER ({n_other()})", + near(r.first_ms(150), 210, 211) and near(r.first_hold(), 240, 241) + and n_other() == 1 and r.prior[205] == 0.0) +r = s1(400, show_at=None, ev=[(190, cap(6.0)), (210, show(12.0))]) +check(f"T11 variant: the new write is a cut try (cap 6 at 190): 12 A at 210: " + f"mismatch ({r.first_ms(150)}), hold ({r.first_hold()}), 1 " + f"CHARGER_OTHER ({n_other()}), cut written " + f"({r.calls_from(190, 195, True)})", + near(r.first_ms(150), 210, 211) and near(r.first_hold(), 240, 241) + and n_other() == 1 and (190, 6.0) in r.calls_from(190, 192, True)) +r = s1(400, show_at=None, ev=[(145, press), (150, show(12.0))]) +check(f"T12: S1-nt, a press at 145 (no hold: the carry ends), 12 A at 150: " + f"mismatch at 150 ({r.first_ms(146)}), hold at 180 ({r.first_hold()}), " + f"1 CHARGER_OTHER ({n_other()}), no write at or above 12 A " + f"({[x for x in r.calls_from(145) if x[1] >= 12.0]})", + near(r.first_ms(146), 150, 151) and near(r.first_hold(), 180, 181) + and n_other() == 1 and not [x for x in r.calls_from(145) + if x[1] >= 12.0]) +nev("T12", r) +r = s1(400, show_at=None, ev=[(145, show(16.0)), (200, show(12.0))]) +check(f"T13: S1-nt, foreign 16 A at 145 (hold at 175), the writer then sets " + f"12 A at 200: the hold stands 175-400 (no lift by match on an old " + f"value) ({r.first_hold()}, {all(r.hold[t] for t in range(176, 401))}), " + f"1 CHARGER_OTHER ({n_other()}), nothing written 145-400 " + f"({r.calls_from(145, 400)})", + near(r.first_hold(), 175, 176) and all(r.hold[t] for t in range(177, 401)) + and n_other() == 1 and not r.calls_from(145, 400, True) + and r.carry[176] == []) +nev("T13", r) + +# T15: unknown read-backs +r = s1(400, show_at=None, ev=[(151, show(12.0))], + cur=lambda t, d: None if 143 <= t <= 150 else d.cur) +check(f"T15 (i): S1-nt, an unknown read-back 143-150 and 12 A at 151: no " + f"mismatch 143-400 ({r.first_ms(140)}), no hold, no CHARGER_OTHER " + f"({n_other()})", r.clean(143, 400) and n_other() == 0) +r = s1(400, show_at=None, ev=[(145, show(16.0))], + cur=lambda t, d: None if 150 <= t <= 160 else d.cur) +check(f"T15 (ii): foreign 16 A at 145, unknown 150-160, 16 A again from 161: " + f"mismatch from 145 ({r.first_ms(140)}), the count stands through " + f"None ({all(r.ms[t] is not None for t in range(146, 175))}), hold at " + f"175 ({r.first_hold()})", + near(r.first_ms(140), 145, 146) + and all(r.ms[t] is not None for t in range(146, 175)) + and near(r.first_hold(), 175, 176) and n_other() == 1) + +# T16: stale reads +r = s1(400, show_at=None, ev=[(143, show(12.0))], + stale=lambda t: 143 <= t <= 147) +check(f"T16 (i): S1-nt, 12 A shown from 143 but stale for 143-147: those " + f"steps decide nothing, 148-400 no mismatch ({r.first_ms(140)}), no " + f"CHARGER_OTHER ({n_other()}); the carry stands through them " + f"({r.carry[147]})", + r.clean(143, 400) and n_other() == 0 and r.carry[147] != []) +r = s1(400, show_at=None, ev=[(145, show(16.0))]) +check(f"T16 (ii): a frozen foreign read is a mismatch, then a hold, as " + f"before ({r.first_ms(140)}, {r.first_hold()})", + near(r.first_ms(140), 145, 146) and near(r.first_hold(), 175, 176)) + +# T17: restart and return +rn = s1(400, show_at=None, cur=lambda t, d: 12.0 if t >= 156 else d.cur, + gone=lambda t: 145 <= t <= 155) +rbs = s1(400, show_at=None, cur=lambda t, d: 12.0 if t >= 156 else d.cur, + gone=lambda t: 145 <= t <= 155, cls=Base69) +same = all((rn.ms[t], rn.hold[t], rn.ncalls[t]) == + (rbs.ms[t], rbs.hold[t], rbs.ncalls[t]) for t in range(156, 401)) +check(f"T17 (i): the charger gone 145-155, back showing 12 A: from 156 every " + f"cycle's writes, mismatch and hold equal de733f4 on the same run " + f"({same}); the carry stands while it is gone ({rn.carry[155]}) and is " + f"gone with the return ({rn.carry[156]})", + same and rn.carry[156] == [] and rn.carry[155] != []) +src = open(os.path.join(HERE, "app", "carmode.py")).read() +others = [f for f in os.listdir(os.path.join(HERE, "app")) + if f.endswith(".py") and f != "carmode.py" + and "_carry" in open(os.path.join(HERE, "app", f)).read()] +w2, m2 = CM.SolarWriter(), CM.ManualWriter() +check(f"T17 (ii): a new writer (a process restart) carries nothing " + f"({w2._carry}, {m2._carry}); the carry is in no other module (no state " + f"file key) ({others})", + w2._carry == [] and m2._carry == [] and not others) + +# T18: a raised try is carried +for lab, val in (("(i) try 2 (8 A) raising", 8.0), + ("(ii) try 1 (12 A) raising", 12.0)): + take = (lambda v: lambda a, d: "raise" if a == v else False)(val) + rb = s1(400, show_at=None, ev=[(150, show(12.0))], take=take, + cls=Base69, press_at=None) + r = s1(400, show_at=None, ev=[(150, show(12.0))], take=take, + press_at=None) + errs = [t for t, lv, m in r.log if lv == "ERROR" and m == REC] + check(f"T18 {lab}: 12 A shown at 150: no mismatch 150-400 " + f"({r.first_ms(150)}), the raised value counted as a try, one " + f"ERROR record per value ({len(errs)}); base: {rb.first_ms(150)}", + r.clean(150, 400) and n_other() == 0 and len(errs) == 1 + and rb.first_ms(150) is not None) + +# T20: Stop / the 0 A rule +t0 = lambda a, d: a == 0.0 and d.now >= 158 # noqa: E731 +r = s1(400, show_at=140, take=t0, writing=lambda t: t < 160) +z = [x for x in r.calls_from(160) if x[1] == 0.0] +check(f"T20 (i): S1 (12 A own), Stop at 160: the way-out 0 A at 160 ({z[:1]}), " + f"no mismatch at 160 ({r.ms[160]}), no hold, no CHARGER_OTHER " + f"({n_other()})", + z and near(z[0][0], 160, 161) and r.ms[160] is None + and not any(r.hold.values()) and n_other() == 0) +r = s1(400, take=t0, ev=[(160, show(16.0))], writing=lambda t: t < 170) +z = [x for x in r.calls_from(160) if x[1] == 0.0] +check(f"T20 (ii): T6 (i) with Stop at 170 (the count running since 160): the " + f"0 A goes out in the count ({z[:2]}), no hold after it " + f"({r.first_hold()}), no CHARGER_OTHER ({n_other()})", + z and near(z[0][0], 170, 171) and r.first_hold() is None + and n_other() == 0) +r = s1(400, take=t0, ev=[(160, show(16.0))], writing=lambda t: t < 200) +check(f"T20 (iii): T6 (i) with Stop at 200 (the hold stands): nothing " + f"written 160-400 ({r.calls_from(160, 400)}), the hold stands " + f"({r.hold[300]}), 1 CHARGER_OTHER ({n_other()})", + not r.calls_from(160, 400) and r.hold[300] and n_other() == 1) + +# =========================================================================== # +print("CE (the EV-60 cap end), Solar") +# =========================================================================== # +r = ce(960) +ct = close_times(r) +E = nth(ct, 1) + 5 +check(f"T5 setup: close 1 (8 A) at {nth(ct, 0)}, the cap, close 2 (6 A) at " + f"{nth(ct, 1)}, the cap end at {E} with no write ({r.ended})", + present(E) and len(ct) >= 2 and r.drv.calls[0][1] == 0.0 + and [a for t, a in r.drv.calls if a > 0][:2] == [8.0, 6.0] + and r.ended == E) +for lab, at_ in (("at E+8", E + 8), ("between close 2 and E", E - 2)): + rb = ce(960, ev=[(at_, show(8.0))], cls=Base69) + r = ce(960, ev=[(at_, show(8.0))]) + k1 = [x for x in r.calls_from(E + 1, 959) if x[1] > 0] + check(f"T5: CE, the charger shows 8 A (close 1) {lab}: no mismatch, hold " + f"or CHARGER_OTHER E..960 ({r.first_ms(E)}, {n_other()}), no write " + f"in key 0 after E, the 6 A cut try at the key roll 900-901 " + f"({k1[:2]}), cut_fails never above 3", + r.clean(E, 960) and n_other() == 0 + and not [x for x in k1 if x[0] < 900] + and [x for x in k1 if 900 <= x[0] <= 901 and x[1] == 6.0] + and not r.viol) + check(f"T5 [red on base] {lab}: base mismatch ({rb.first_ms(E)}), hold " + f"({rb.first_hold()}), no cut try at 900 " + f"({[x for x in rb.calls_from(E + 1, 959) if x[1] > 0][:2]})", + rb.first_ms(E) is not None and rb.first_hold() is not None + and not [x for x in rb.calls_from(900, 905) if x[1] > 0]) +nev("T5", r) +r = ce(960, ev=[(E + 20, show(10.0))]) +check(f"T6 (ii): CE, foreign 10 A at E+20: mismatch at the change " + f"({r.first_ms(E)}), hold at +30 ({r.first_hold()}), 1 CHARGER_OTHER " + f"({n_other()}), nothing non-zero written from the change to 960 " + f"({r.calls_from(E + 20, 960, True)})", + near(r.first_ms(E), E + 20, E + 21) + and r.first_hold() - r.first_ms(E) == 30 and n_other() == 1 + and not r.calls_from(E + 20, 960, True)) +nev("T6 (ii)", r) + +# T19: the quarter boundary +rb = ce(960, ev=[(900, show(8.0))], cls=Base69) +r = ce(960, ev=[(900, show(8.0))]) +check(f"T19: CE, the cap standing to 960, the charger shows 8 A at the step " + f"of 900: no mismatch 900-960, the key-1 cut try at 900-901 " + f"({r.calls_from(899, 905)}), its refusal keeps 8 A own " + f"(prior_a {r.prior[902]})", + r.clean(900, 960) and n_other() == 0 + and [x for x in r.calls_from(900, 901) if x[1] == 6.0] + and r.prior[902] == 8.0) +check(f"T19 [red on base]: mismatch at 900 ({rb.first_ms(895)})", + rb.first_ms(895) is not None) + +# T24 (formal Dev note 1): the 0 A is carried +r = ce(500, press_after_close2=True) +E = close_times(r)[1] + 5 +r = ce(500, press_after_close2=True, ev=[(E + 3, show(0.0))]) +check(f"T24: cap end with a press inside the sequence (prior_a cleared), the " + f"charger then shows its own 0 A: no mismatch_since, no hold " + f"({r.first_ms(E)}, {r.first_hold()}); the carry holds the 0 A " + f"({r.carry[E + 4]})", + r.ended == E and r.clean(E, 500) and 0.0 in r.carry[E + 4] + and r.prior[E - 1] is None) + + +# T25 (formal Dev note 2): no carry when the end's own value is taken +def ce25(): + w, drv = mk_ce(plan_a=12.0) + st = {"cap": False} + + def hook(t, w_, d, s): + nz = [(tt, a) for tt, a in d.calls if a > 0] + if nz and not s["cap"]: + s["cap"] = True + set_cap(w_, 6.0) + if len(nz) >= 2 and t == nz[1][0] + 5: + d.cur = 6.0 # close 2 taken late, read at E + if len(nz) >= 2 and t == nz[1][0] + 5 + 10: + d.cur = 12.0 # an earlier close value + return Run(w, drv, st=st).go(130, 600, hook=hook) + + +r = ce25() +E = close_times(r)[1] + 5 +check(f"T25: CE, the read at E adopts sent_a (6 A taken late) before the cap " + f"end: nothing is carried ({r.carry[E]}, {r.carry[E + 10]}), the 12 A " + f"(an earlier close value) is no own value when it shows at E+10 " + f"({r.own[E + 10]}), 6 A stays taken (taken {r.taken[E]}, sent_a " + f"{r.sent_a[E + 10]}); no write in key 0 after E " + f"({r.calls_from(E, 899)})", + r.ended == E and all(r.carry[t] == [] for t in range(E, 601)) + and 12.0 not in r.own[E + 10] and r.taken[E] is True + and r.sent_a[E + 10] == 6.0 and not r.calls_from(E, 899)) +# The test plan reads T25 as "a mismatch, a hold at +30". It cannot, by the +# code: the cap end sets last_a None (F5) and the adopt cleared attempted_a / +# prior_a, so no own value is left at all and `_watch` judges nothing (the +# EV-22 start-state blind spot, not EV-69's). The row asserts the rule itself: +# nothing carried (red under carryAfterTake, which carries 0, 12 and 6). + +# =========================================================================== # +print("MW (Manual, OQ2)") +# =========================================================================== # +r = mw(300) +nzc = [int(t) for t, a in r.drv.calls if a > 0] +E = nth(nzc, -1) +check(f"T8 setup: Manual closes 12 A, the clamp falls, tries 2 and 3 are 8 A " + f"({[(int(t), a) for t, a in r.drv.calls]}), the :589 end at {r.ended}", + present(E) and [a for t, a in r.drv.calls if a > 0] == [12.0, 8.0, 8.0] + and r.ended == E and r.gu[E] is True) +for lab, kw in (("the clamp falls", dict()), + ("the user lowers car_current 12 -> 8", dict(user=True))): + r0 = mw(300, **kw) + E = r0.ended + rb = mw(E + 300, cls=BaseM69, hook2=lambda t, w, d, s, E=E: setattr( + d, "cur", 12.0) if t == E + 3 else None, **kw) + r = mw(E + 300, hook2=lambda t, w, d, s, E=E: setattr( + d, "cur", 12.0) if t == E + 3 else None, **kw) + check(f"T8: Manual, {lab}, the charger shows 12 A at E+3: no mismatch, " + f"hold or 'Something else changes the charger' line E..E+300 " + f"({r.first_ms(E)}, {n_some()}); the EV-59 count is unchanged " + f"(gave_up {r.gu[E + 4]}); base: hold at {rb.first_hold(E)}", + r.clean(E, E + 300) and n_some() == 0 + and r.gu[E + 4] is (not kw) # clamp: EV-59 gave up; user: the + # count restarted, it asks again + and rb.first_hold(E) is not None and near( + rb.first_hold(E), E + 33, E + 34)) + nev(f"T8 ({lab})", r) +r0 = mw(300) +E = r0.ended +r = mw(E + 300, hook2=lambda t, w, d, s: setattr(d, "cur", 16.0) + if t == E + 5 else None) +check(f"T9: Manual, foreign 16 A at E+5: mismatch at E+5 ({r.first_ms(E)}), " + f"hold at E+35 ({r.first_hold(E)}), 1 INFO line ({n_some()}), no write " + f"over 16 A to E+300 ({r.calls_from(E + 1, 10 ** 9, True)})", + near(r.first_ms(E), E + 5, E + 6) and near(r.first_hold(E), E + 35, + E + 36) + and n_some() == 1 and not r.calls_from(E + 1, 10 ** 9, True)) + +# =========================================================================== # +print("Rules the code keeps (Dev notes)") +# =========================================================================== # +check("T1 [Dev note 1]: one helper `_carry_end` serves both ends and both " + "writers (ManualWriter defines it, SolarWriter does not redefine it)", + "_carry_end" in vars(CM.ManualWriter) + and "_carry_end" not in vars(CM.SolarWriter) + and src.count("self._carry_end(q)") == 2) +check("T1 [Dev note 6]: `_put` keeps `stopped and not cut_try` (the cut never " + "waits on gave_up)", "(stopped and not cut_try)" in src) +done() diff --git a/goodwe_controller/test_ev69_fuzz.py b/goodwe_controller/test_ev69_fuzz.py new file mode 100644 index 0000000..8c10e0e --- /dev/null +++ b/goodwe_controller/test_ev69_fuzz.py @@ -0,0 +1,245 @@ +"""EV-69 T21: the fuzz for the carry (N1-N9 of reports/EV-69-test-plan.md), 10 +seeds x 1200 s for Solar and for Manual, both cycle orders. +`python3 -B test_ev69_fuzz.py` + +Writer level (`tools/ev69_kit.py`: `SolarWriter` / `ManualWriter` on a stub +driver). Random: clamp steps, a peak cut cap, refused and raised writes (0 A +and the select are taken), phase changes begun by the plan (Solar) or the user +(Manual), late takes of ANY value the writer tried, foreign values (some equal +to a tried value), presses, unknown and stale reads, the charger gone and +back. Order A applies a cycle's events before its step, order B after it (the +event is read one cycle later). + +Every cycle checks, by an oracle that does not read the carry: +- N1: after a phase change ends without its value taken (MAX_TRIES, or + Solar's cap end), while nothing has ended the bound (a write, a press, a + hold or count, a return, a take of what the writer sent or wants), the + charger showing a value the change tried gives no mismatch and no hold. +- N2: no non-zero write while a count runs or a hold stands. +- N4: no carry under a hold, after a press, or after a write that is not + itself followed by an end. +- N5: no write above the clamp or the cap, none in 0-6 A. +- N6: at most MAX_TRIES cut tries per quarter key. +- N7: no 0 A written under a hold. +- N8: a select only at 0 A. +- N9: at most one CHARGER_OTHER (Solar) / one INFO line (Manual) per hold. +N3 (the cut never waits on a false hold) follows from N1 and the rows T1, T5, +T19. 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")) + +import ev69_kit as K # noqa: E402 +from app import carmode as CM # noqa: E402 + +SEEDS = int(os.environ.get("EV69_FUZZ_SEEDS", "10")) +STEPS = int(os.environ.get("EV69_FUZZ_STEPS", "1200")) +COUNT = {} + + +def bump(k, n=1): + COUNT[k] = COUNT.get(k, 0) + n + + +def fuzz(kind, seed): + rnd = random.Random(seed * 7 + (0 if kind == "solar" else 1)) + order_b = seed % 2 == 1 + st = {"a": rnd.choice([8.0, 10.0, 12.0]), "n": 1, "rev": 1, + "clamp": 16.0} + if kind == "solar": + w = K.swriter(8.0, ph=1) + w.cut_key = 0 + else: + w = CM.ManualWriter() + mode = {"refuse": 0.97, "raise": 0.0} + + def take(a, d): + if a == 0.0: + return True + if rnd.random() < mode["raise"]: + return "raise" + return rnd.random() >= mode["refuse"] + drv = K.Drv(8.0 if kind == "solar" else st["a"], take, ph=1) + run = K.Run(w, drv, kind=kind, st=st) + bad = [] + s = dict(armed=False, vals=[], seq_own=[], hold_rises=0, press_t=-1, + prev_hold=False, was_gone=False, gone=False, tried=set(), + nsel=0) + clamp = {"v": 16.0} + + def ev(t): + if rnd.random() < (0.25 if w.seq is not None else 0.01): + clamp["v"] = rnd.choice([16.0, 12.0, 10.0, 8.0, 8.0]) + st["clamp"] = clamp["v"] + if kind == "solar" and rnd.random() < 0.01: + K.set_cap(w, rnd.choice([None, 6.0, 6.0, 7.0])) + if rnd.random() < 0.004: + mode["refuse"] = rnd.choice([0.0, 0.5, 0.97, 1.0, 1.0, 1.0]) + mode["raise"] = rnd.choice([0.0, 0.0, 0.3]) + # a phase change: Solar's plan decides it, Manual's user asks for it + if w.seq is None and rnd.random() < 0.03: + n_to = 3 if drv.ph == 1 else 1 + if kind == "solar": + if not w.plan.switch: + w.plan._set(rnd.choice([8.0, 10.0, 12.0]), float(t), n_to) + else: + w.user_changed() + st["rev"] += 1 + st["n"] = n_to + st["a"] = rnd.choice([8.0, 10.0, 12.0, 14.0]) + s["press_t"] = t + # a late take of any value the writer tried (the ended change's + # values first) + if rnd.random() < 0.08: + pool = [v for v in s["vals"] if v > 0] if ( + s["armed"] and rnd.random() < 0.6) else sorted( + v for v in s["tried"] if v > 0) + if pool: + v = rnd.choice(pool) + drv.cur = v + bump("late_take") + if s["armed"] and v in s["vals"]: + bump("late_take_ended_val") + if v != s["vals"][-1]: + bump("late_take_nonlast") + if rnd.random() < 0.005: + drv.cur = rnd.choice([5.0, 7.0, 9.0, 11.0, 13.0, 15.0] + + sorted(s["tried"])) + bump("foreign") + if rnd.random() < 0.005: + w.user_changed() + if kind == "manual": + st["rev"] += 1 + s["press_t"] = t + bump("press") + if rnd.random() < 0.01: + drv.cur = 0.0 + s["gone"] = rnd.random() < (0.8 if s["gone"] else 0.003) + + for t in range(STEPS): + if not order_b: + ev(t) + gone, unk, stale = s["gone"], rnd.random() < 0.02, rnd.random() < 0.02 + hold0, ms0 = w.hold, w.mismatch_since + n0, sel0 = len(drv.calls), len(drv.sel) + before_seq = w.seq is not None + if before_seq: + s["seq_own"] = list(w.seq.get("own", ())) + drv.now = float(t) + K.CLOCK["t"] = t + if hasattr(w, "cut_quarter"): + w.cut_quarter(int(t // 900)) + seen = None if unk else drv.cur + rd = K.Rd(seen, drv.ph, power=0.0 if drv.cur == 0 else 1840.0) + rd.available = not gone + run.trk.obs_at = (w.last_done if (stale and w.last_done is not None) + else None) + cl = clamp["v"] + if kind == "solar": + K.LOOP.run_until_complete(w.step( + drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0), + clamp=cl, now=float(t), tracker=run.trk, writing=True, + status="charging")) + else: + K.LOOP.run_until_complete(w.step( + drv, rd, mode=CM.MANUAL, want_a=st["a"], + want_phases=st["n"], rev=st["rev"], clamp=cl, now=float(t), + tracker=run.trk, writing=True, status="charging")) + new = drv.calls[n0:] + wrote = bool(new) + press_now = s["press_t"] == t + for tt, a in new: + if a > 0: + s["tried"].add(a) + if a > 0 and (w.hold or (kind == "solar" + and w.mismatch_since is not None)): + # judged after the step's own watch (a count a read cleared + # in this step is no count when the write goes out); Manual + # writes through a count and stops at the hold (EV-22) + bad.append((kind, seed, t, "N2 write while a count/hold " + "stood", a)) + if a == 0.0 and w.hold: + bad.append((kind, seed, t, "N7 0 A under a hold")) + cutv = getattr(w, "cut_a", None) + if a > cl + 1e-9 and not (cutv is not None and a <= cutv + 1e-9): + bad.append((kind, seed, t, "N5 above the clamp", a, cl)) + if 0 < a < CM.CH.MIN_A - 1e-9: + bad.append((kind, seed, t, "N5 in 0-6 A", a)) + if getattr(w, "cut_fails", 0) > CM.MAX_TRIES: + bad.append((kind, seed, t, "N6 cut tries over the cap")) + for tt, n_, cur_ in drv.sel[sel0:]: + if cur_ > CM.TOL_A: + bad.append((kind, seed, t, "N8 select over load", cur_)) + if w.hold and not s["prev_hold"]: + s["hold_rises"] += 1 + bump("hold") + s["prev_hold"] = w.hold + lines = len([1 for _t, lv, m in K.LOG + if (kind == "solar" and K.OTHER in m) + or (kind == "manual" and K.SOMETHING in m)]) + if lines > s["hold_rises"]: + bad.append((kind, seed, t, "N9 more lines than holds", lines, + s["hold_rises"])) + ended_now = before_seq and w.seq is None + if w.hold and w._carry: + bad.append((kind, seed, t, "N4 carry under a hold", w._carry)) + if press_now and w._carry and not ended_now: + bad.append((kind, seed, t, "N4 carry after a press", w._carry)) + if wrote and w._carry and not ended_now: + bad.append((kind, seed, t, "N4 carry after a write", w._carry)) + # the oracle's bound: armed by an end whose last value is not taken, + # disarmed by anything that ends it (a superset of the code's ends) + took = (kind == "solar" and w.taken) or ( + kind == "manual" and w.last_a is not None) + if ended_now and not took and not gone: + s["vals"] = [0.0] + [a for a in s["seq_own"] if a > 0] + [ + a for tt, a in new if a > 0] + s["armed"] = True + bump("end") + if kind == "solar" and w.cut_fails >= CM.MAX_TRIES: + bump("end_cap") + elif s["armed"]: + if wrote or press_now or w.hold or gone or s["was_gone"] \ + or took: + s["armed"] = False + elif w.mismatch_since is not None: + if seen is not None and seen > CM.TOL_A and seen in s["vals"]: + bad.append((kind, seed, t, "N1 a late take of a tried " + "value is held as another writer's", seen, + s["vals"])) + s["armed"] = False # a foreign value: judged as ever + bump("armed_foreign") + elif seen is not None and seen > CM.TOL_A and seen in s["vals"]: + bump("armed_take_seen") + s["was_gone"] = gone + if order_b: + ev(t) + return bad + + +allbad = [] +for kind in ("solar", "manual"): + for seed in range(SEEDS): + allbad += fuzz(kind, seed) +for tag in ("N1", "N2", "N4", "N5", "N6", "N7", "N8", "N9"): + K.check(f"T21 {tag}: holds in every cycle of {SEEDS} seeds x {STEPS} s, " + f"Solar and Manual, both orders " + f"({[b for b in allbad if b[3].startswith(tag)][:2]})", + not [b for b in allbad if b[3].startswith(tag)]) +print(" counts", dict(sorted(COUNT.items()))) +floor = {"end": 20, "end_cap": 3, "late_take_ended_val": 10, + "late_take_nonlast": 5, "armed_take_seen": 20, "foreign": 20, + "hold": 5} +if STEPS >= 1200 and SEEDS >= 10: + K.check(f"T21: the fuzz reaches its branches " + f"({ {k: COUNT.get(k, 0) for k in floor} }, floor {floor})", + all(COUNT.get(k, 0) >= v for k, v in floor.items())) +K.done() diff --git a/goodwe_controller/tools/ev69_kit.py b/goodwe_controller/tools/ev69_kit.py new file mode 100644 index 0000000..35e364b --- /dev/null +++ b/goodwe_controller/tools/ev69_kit.py @@ -0,0 +1,308 @@ +"""EV-69: the writer-level harness of test_ev69.py and test_ev69_fuzz.py: a +`SolarWriter` / `ManualWriter` on a stub driver, a stub tracker and a stub +reading, one step per second on a model clock; `Run` records what every step +ended with. `Base69` / `BaseM69` are de733f4's writers (the carry switched +off): the red side of a row. + +Each check file is its own process, so `fails` and `LOG` are its own.""" + +import asyncio +import logging +import os +import sys + +_KIT = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.dirname(_KIT)) + +from app import carmode as CM # noqa: E402 + +fails = [] +CLOCK = {"t": 0} +LOG = [] +OTHER = "CHARGER_OTHER" +SOMETHING = "Something else changes the charger" +REC = "The car charger step failed" + + +class Cap(logging.Handler): + def emit(self, rec): + LOG.append((CLOCK["t"], rec.levelname, rec.getMessage())) + + +logging.getLogger("goodwe").addHandler(Cap()) +logging.getLogger("goodwe").setLevel(logging.DEBUG) + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +def done(): + print("\nall passed" if not fails else f"\n{len(fails)} FAILED") + for f in fails: + print(" FAIL:", f) + sys.exit(1 if fails else 0) + + +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: + """`take(a, drv)` -> True (the charger takes it), False (refused) or + "raise" (the call raises).""" + + def __init__(self, cur, take, 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))) + r = self.take(float(a), self) + if r == "raise": + raise RuntimeError("HA call error") + if r is True: + self.cur = float(a) + return r is True + + async def write_phases(self, n): + self.sel.append((self.now, n, self.cur)) + self.ph = n + return True + + def _clock(self): + return self.now + + async def _sleep(self, s): + self.now += s + + +class Base69(CM.SolarWriter): + """de733f4's Solar: an ended sequence's values are not carried.""" + + def _carry_end(self, q): + self._carry = [] + + +class BaseM69(CM.ManualWriter): + """de733f4's Manual.""" + + def _carry_end(self, q): + self._carry = [] + + +LOOP = asyncio.new_event_loop() + + +def swriter(cur, ph=1, cls=None): + w = (cls or 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 >= CM.CH.MIN_A and w.plan.a > c + 1e-9: + w.plan._cut(c) + w._plan_step = plan_step + return w + + +def set_cap(w, a): + w.cut_a, w.cut_on = a, a is not None + + +def show(a): + return lambda w, d, s: setattr(d, "cur", float(a)) + + +def press(w, d, s): + w.user_changed() + s["rev"] = s.get("rev", 1) + 1 + + +def cap(a): + return lambda w, d, s: set_cap(w, a) + + +def chain(*fns): + def f(w, d, s): + for fn in fns: + fn(w, d, s) + return f + + +def evs(*pairs): + """{t: fn(w, drv, st)}; two at one second run both.""" + out = {} + for t, fn in pairs: + out[t] = chain(out[t], fn) if t in out else fn + return out + + +class Run: + """One writer-level run; per second: mismatch, hold, counts.""" + + def __init__(self, w, drv, kind="solar", st=None): + del LOG[:] + self.w, self.drv, self.kind = w, drv, kind + self.trk, self.st = Trk(), st if st is not None else {} + self.ms, self.hold, self.gu, self.fl, self.seq = {}, {}, {}, {}, {} + self.taken, self.last_a, self.sent_a = {}, {}, {} + self.prior, self.att, self.carry, self.ncalls = {}, {}, {}, {} + self.own = {} + self.viol, self.ended, self.log = [], None, [] + + def go(self, t0, t1, ev=None, hook=None, clamp=16.0, writing=None, + cur=None, stale=None, gone=None): + w, drv = self.w, self.drv + for t in range(t0, t1 + 1): + drv.now = float(t) + CLOCK["t"] = t + if ev and t in ev: + ev[t](w, drv, self.st) + if hook: + hook(t, w, drv, self.st) + if hasattr(w, "cut_quarter"): + w.cut_quarter(int(t // 900)) + c = drv.cur if cur is None else cur(t, drv) + rd = Rd(c, drv.ph, power=0.0 if drv.cur == 0 else 1840.0) + if gone is not None and gone(t): + rd.available = False + cl = clamp(t) if callable(clamp) else clamp + if self.kind == "manual": + cl = self.st.get("clamp", cl) + self.trk.obs_at = None + if stale is not None and stale(t): + self.trk.obs_at = w.last_done if w.last_done is not None \ + else 0.0 + wr = True if writing is None else writing(t) + n0, s0 = len(drv.calls), w.seq is not None + if self.kind == "solar": + LOOP.run_until_complete(w.step( + drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0), + clamp=cl, now=float(t), tracker=self.trk, writing=wr, + status="charging")) + else: + LOOP.run_until_complete(w.step( + drv, rd, mode=CM.MANUAL, want_a=self.st["a"], + want_phases=self.st["n"], rev=self.st["rev"], clamp=cl, + now=float(t), tracker=self.trk, writing=wr, + status="charging")) + if s0 and w.seq is None and self.ended is None: + self.ended = t + # N2 is judged on the state after the step's own watch: a count + # a read cleared in this step (the foreign value went) is no + # count when the write goes out. + stood = bool(w.hold or (self.kind == "solar" + and w.mismatch_since is not None)) + for tt, a in drv.calls[n0:]: + # N2 / N5 per write + if a > 0 and stood: + self.viol.append((t, "N2 write while a count/hold stood", + a)) + if a > cl + 1e-9 or 0 < a < CM.CH.MIN_A - 1e-9: + if not (w.cut_a is not None and a <= w.cut_a + 1e-9): + self.viol.append((t, "N5 write outside clamp/6 A", a)) + if getattr(w, "cut_fails", 0) > CM.MAX_TRIES: + self.viol.append((t, "N6 cut tries over the cap")) + self.ms[t], self.hold[t] = w.mismatch_since, w.hold + self.gu[t], self.fl[t] = w.gave_up, w.fails + self.seq[t], self.taken[t] = w.seq is not None, getattr( + w, "taken", None) + self.last_a[t], self.sent_a[t] = w.last_a, getattr( + w, "sent_a", None) + self.prior[t], self.att[t] = w.prior_a, w.attempted_a + self.carry[t] = list(getattr(w, "_carry", [])) + self.own[t] = list(w._own_values()) + self.ncalls[t] = len(drv.calls) + self.log = list(LOG) + LAST[0] = self + return self + + # ---------------------------------------------------------- readings + def calls_from(self, t0, t1=10 ** 9, nz=False): + return [(int(t), a) for t, a in self.drv.calls + if t0 <= t <= t1 and (not nz or a > 0)] + + def clean(self, lo, hi): + """No mismatch, no hold, no CHARGER_OTHER line, no 'Something else + changes' line in lo..hi.""" + return (all(self.ms[t] is None and not self.hold[t] + for t in range(lo, hi + 1) if t in self.ms) + and not [1 for t, lv, m in self.log if lo <= t <= hi + and (OTHER in m or SOMETHING in m)]) + + def first_ms(self, lo=0): + for t in sorted(self.ms): + if t >= lo and self.ms[t] is not None: + return t + return None + + def first_hold(self, lo=0): + for t in sorted(self.hold): + if t >= lo and self.hold[t]: + return t + return None + + +LAST = [None] # the run that ended last: what `n_other` / `n_some` count + + +def n_other(): + return len([1 for t, lv, m in LAST[0].log if OTHER in m]) + + +def n_some(): + return len([1 for t, lv, m in LAST[0].log if SOMETHING in m]) + + +def near(x, lo, hi): + return x is not None and lo <= x <= hi + + +def nev(tag, run): + """N2, N5, N6 over one run (collected per step by `Run.go`), N9 (one + CHARGER_OTHER per hold rise), N8 (a select only at 0 A).""" + rises = 0 + prev = False + for t in sorted(run.hold): + if run.hold[t] and not prev: + rises += 1 + prev = run.hold[t] + sel_bad = [x for x in run.drv.sel if x[2] > CM.TOL_A] + check(f"N2/N5/N6 {tag}: no write over a count or hold, none above the " + f"clamp or in 0-6 A, at most 3 cut tries ({run.viol[:2]})", + not run.viol) + check(f"N8/N9 {tag}: a select only at 0 A ({sel_bad[:1]}), at most one " + f"CHARGER_OTHER per hold ({n_other()} for {rises})", + not sel_bad and n_other() <= rises)