diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 91a5c90..c758493 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -149,6 +149,7 @@ class ManualWriter: self._r = None # the latest reading, for the phase count 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 # ------------------------------------------------------------------ user def user_changed(self) -> None: @@ -159,6 +160,7 @@ class ManualWriter: self.hold = self.other = False self.mismatch_since = None self.fails, self.fail_at, self.gave_up = 0, None, False + self._close_k = 0 # EV-59 self.phase_fails, self.phases_gave_up = 0, False self.attempted_a = self.prior_a = None self._late = None # EV-52: that request is not current now @@ -223,6 +225,7 @@ class ManualWriter: if not (phases_need or cur_need): self.rev_applied, self.reapply = rev, False self.fails, self.blocked = 0, False + self._close_k = 0 if cur is not None: self.last_a = cur # adopt what is already set # EV-52 (PM Q2): a write taken late is logged once, here. @@ -249,6 +252,7 @@ class ManualWriter: self._failed(now) return self.fails, self.fail_at = 0, None + self._close_k = 0 if not phases_need: self.rev_applied, self.reapply = rev, False @@ -262,6 +266,15 @@ class ManualWriter: "stops asking until you change it: CHARGER_REFUSED.") _LOG.debug("The charger refused the current %d times.", self.fails) + def _close_end(self, now) -> None: + """EV-59: the closing current was refused MAX_TRIES times in this + sequence. The value owed has had `_close_k` not-taken closes since the + last user change: `fails` is that count, so the give-up comes only + when the value has used all its tries; else the normal path gives the + rest.""" + self.fails = max(min(self._close_k, MAX_TRIES) - 1, 0) + self._failed(now) + def _watch(self, cur, now) -> None: """Is the read-back what we wrote? A difference that stands for `WRITER_S` is another writer.""" @@ -500,15 +513,17 @@ class ManualWriter: # still wanted, and one that is in place is adopted. self.seq, self.rev_applied, self.reapply = None, None, False self.fails, self.blocked = 0, False + self._close_k = 0 if not q.get("failed"): self.phase_done_at = self.last_done # EV-15 return q["failed"] = True # EV-15: a refused write ends it q["tries"] += 1 + 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.seq, self.last_a, self.reapply = None, None, True - self._failed(now) + self._close_end(now) self.rev_applied = None return q["t1"] = now - SETTLE_S + 5.0 # again in 5 s @@ -1068,6 +1083,9 @@ class SolarWriter(ManualWriter): or Solar's.""" return "peak cut" if q.get("cut") else "Solar" + def _close_end(self, now) -> None: + self._failed(now) # EV-59: Solar stays as it was (EV-60) + def _failed(self, now) -> None: if self.sent_cut: # EV-54 (Q1, F7): a refused cut try counts against the quarter's diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index b1be2e4..28cb15d 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -799,7 +799,7 @@ for exc in (RuntimeError("the link broke"), hass.ReadOnly("read only")): errs = [m for lv, m in LOG.rec[n0:] if lv == "ERROR" and "car charger step failed" in m] check(f"T13 write_current raises {type(exc).__name__}: as on the base: " - "never armed, no window left, no refusal counted, the mute set, " + "never armed, no window left, one refusal counted, the mute set, " f"the step error logged once ({len(errs)})", never_stuck(tr) and pend(w.c.car) is None and w.c.car_writer.fails == 1 and w.c.car.mute_until > 0 diff --git a/goodwe_controller/test_ev28.py b/goodwe_controller/test_ev28.py index eae959f..0d59e24 100644 --- a/goodwe_controller/test_ev28.py +++ b/goodwe_controller/test_ev28.py @@ -704,7 +704,8 @@ async def t15(): await w.step(19) w.sim.refuse = "error" await w.step(40) - mid = (list(calls), w.wr.seq is None and w.wr.fails == 1, + mid = (list(calls), w.wr.seq is None and w.wr.fails == MAX_TRIES + and w.wr.gave_up, bool(w.writes("phases"))) w.sim.refuse = None await w.step(int(carmode.RETRY_S) + 10) @@ -715,11 +716,14 @@ w, (calls, over, anyph) = run(t15()) tries = [c for c in calls if c[1] == 16.0] gaps = [round(b[0] - a[0]) for a, b in zip(tries, tries[1:])] check(f"T15: the restore is refused: tried {len(tries)} times ~5 s apart " - f"({gaps}), no select, sequence ends, one failed write counted", + f"({gaps}), no select, sequence ends, the 3 closes counted: given up " + "(EV-59)", len(tries) == MAX_TRIES and all(4 <= g <= 6 for g in gaps) and over and not anyph and not w.writes("phases")) -check("T15: after the refusal ends the current is back at 16 A, never a " - "select", w.sim.readback_a == 16 and not w.writes("phases")) +check("T15: EV-59: given up after the 3 closes: no 4th try, the current stays " + "at 0 A until a user change, never a select", + w.sim.readback_a == 0 and len(tries) == MAX_TRIES + and not w.writes("phases")) # --- T14: the controller level (the EV-15 harness) ------------------------- # diff --git a/goodwe_controller/test_ev56.py b/goodwe_controller/test_ev56.py index 7f69fb5..8939718 100644 --- a/goodwe_controller/test_ev56.py +++ b/goodwe_controller/test_ev56.py @@ -55,7 +55,7 @@ GOLDEN = { # and the refusing (R) stub. "T20 T1 [A]": "905c0b8ba89bb307", "T20 T1 [R]": "343ea01aacfa1019", "T20 T4 [A]": "ff6306ce56b35c64", "T20 T4 [R]": "f1fb141275839562", - "T20 T5 [A]": "369069be9187ab3c", "T20 T5 [R]": "ba32810fbb40d0f9", + "T20 T5 [A]": "369069be9187ab3c", "T20 T5 [R]": "78ffe9cf72c5e214", # EV-59 "T20 T8 [A]": "2cd78dee7ee93aaa", "T20 T8 [R]": "f0adb058a5bbefba", "T20 T11 [A]": "6d7bcb747d1dc5a3", "T20 T11 [R]": "2be1a760b699b28c", "T20 T12 [A]": "a5888e4557b4ee8f", "T20 T12 [R]": "2fd24ddbb18f14cc", @@ -598,28 +598,30 @@ before5 = row_at(x5, t_end - 1) check(f"T5: the close raises (_advance): writer equal to R ({eq5[:1]})", not eq5) check(f"T5: close tries {ts(c5)} at settle end ({t_sel} + 10), +5, +10; then " - f"seq None, reapply, last_a None, fails 1, the sequence failed, " - f"phase_done_at None ({end5 and end5[1]})", + f"seq None, reapply, last_a None, fails MAX_TRIES, gave_up, the " + f"sequence failed, phase_done_at None ({end5 and end5[1]})", present(t_sel) and near_seq(ts(c5)[:3], [t_sel + 10, t_sel + 15, t_sel + 20]) and end5 is not None and before5 is not None and end5[1]["seq"] is None and end5[1]["reapply"] is True - and end5[1]["last_a"] is None and end5[1]["fails"] == 1 + and end5[1]["last_a"] is None and end5[1]["fails"] == CM.MAX_TRIES + and end5[1]["gave_up"] is True and before5[1]["seq"] is not None and before5[1]["seq"][2] is True and end5[1]["phase_done_at"] is None) nxt5 = calls(x5, t_end + 1 if present(t_end) else BIG) -check(f"T5: no write for 60 s after ({ts(nxt5)[:1]}); the car stays at 0 A " - f"to 300 s ({x5['sim'].setpoint_a}); 1 record for the close value " - f"({len(recs(x5))})", - present(t_end) and nth(ts(nxt5), 0) - t_end >= 59 +check(f"T5: EV-59: no write after the 3rd close ({ts(nxt5)[:1]}); the car " + f"stays at 0 A to 300 s ({x5['sim'].setpoint_a}); 1 record for the " + f"close value ({len(recs(x5))})", + present(t_end) and not nxt5 and x5["sim"].setpoint_a == 0.0 and len(recs(x5)) == 1) never("T5", x5, close_ok=True) for k in "RX": six = calls(R5[k], 100, 300, a=6.0) gold = golden(f"T5b [{k}]", six) check(f"T5b [{k}] (H3, not worse than base): the close value's tries " - f"{six} = base R's {GOLDEN['T5b']} (5, never a 6th)", - near_seq(ts(six), ts(GOLDEN["T5b"])) and len(six) == 5) + f"{six} = base R's first 3 {GOLDEN['T5b'][:3]} (EV-59: 3, never a " + f"4th)", + near_seq(ts(six), ts(GOLDEN["T5b"][:3])) and len(six) == CM.MAX_TRIES) del gold def shadow_on(p, c): diff --git a/goodwe_controller/test_ev59.py b/goodwe_controller/test_ev59.py new file mode 100644 index 0000000..3c6ff1e --- /dev/null +++ b/goodwe_controller/test_ev59.py @@ -0,0 +1,669 @@ +"""EV-59: Manual gives one value at most MAX_TRIES tries per user change, the +phase-change closes included. `python3 -B test_ev59.py` + +Rows T1-T25 and N1-N14 of reports/EV-59-test-plan.md (T14a, T14b, T14d, T15 +and T19 are carried by the unedited EV-56, EV-28 and EV-04 suites: see the dev +report). The `ManualWriter` / `SolarWriter` on a stub driver, a stub tracker +and a stub reading; time is the 1 s step counter, never wall time. The close +of the plan's T5 world: 0 A at t=0 and the select at t=1, both taken, so the +settle ends at s=11 and the closes are at 11, 16, 21. + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import logging +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode as CM # noqa: E402 + +fails = [] +CLOCK = {"t": 0} +LOG = [] +BIG = 1e12 +REF = "CHARGER_REFUSED" +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) + + +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 __init__(self): + self.notes = [] + + def begin_write(self): + pass + + def end_write(self, *_): + pass + + def note_write(self, now, was, a, ok, polls=()): + self.notes.append((now, a, ok)) + + def stuck(self, now): + return False + + +class Drv: + """answer(a, n) -> True | False | "raise"; True sets the charger. `sel`: + the answer to write_phases. `phases_log`: (t, n, the power seen then).""" + + def __init__(self, cur, answer, ph=1, sel=True): + self.cur, self.ph, self.answer, self.sel = cur, ph, answer, sel + self.calls, self.now, self.polls = [], 0.0, () + self.phases_log, self.power = [], None + + async def write_current(self, a, **kw): + self.calls.append((self.now, float(a))) + r = self.answer(float(a), len(self.calls)) + if r == "raise": + raise RuntimeError("HA call error") + if r: + self.cur = float(a) + return bool(r) + + async def write_phases(self, n): + self.phases_log.append((self.now, n, self.power)) + if self.sel: + self.ph = n + return self.sel + + +def refuse(a, n): + return a == 0.0 + + +def raises(a, n): + return True if a == 0.0 else "raise" + + +def snap(w): + q = w.seq + return dict(fails=w.fails, gave_up=w.gave_up, fail_at=w.fail_at, + seq=None if q is None else (q["stage"], q["tries"]), + last_a=w.last_a, reapply=w.reapply, rev_applied=w.rev_applied, + phase_done_at=w.phase_done_at, phase_fails=w.phase_fails) + + +class Run: + pass + + +def run(answer, secs, *, cls=CM.ManualWriter, cb=None, a=6.0, n=3, cur=10.0, + sel=True, power=None, avail=None, clamp=16.0, mode=CM.MANUAL, + rd_none=False, w=None): + """One writer run, one step per second. `cb(t, st, w, drv)` may change the + request in `st` (a, n, rev, clamp, mode) or call `w.user_changed()` (use + `uc`); it may be a coroutine. Per step: the state before and after.""" + LOG.clear() + w, trk = w or cls(), Trk() + drv = Drv(cur, answer, sel=sel) + st = dict(a=a, n=n, rev=1, clamp=clamp, mode=mode) + out = Run() + out.w, out.drv, out.trk, out.st = w, drv, trk, st + out.rows, out.errs, out.ucs = {}, [], [] + + async def main(): + for t in range(secs): + drv.now = float(t) + CLOCK["t"] = t + if cb: + x = cb(t, st, w, drv) + if asyncio.iscoroutine(x): + await x + pw = power(t, drv) if power else ( + 0.0 if drv.cur == 0 else 1380.0) + drv.power = pw + r = Rd(None if rd_none else drv.cur, drv.ph, power=pw) + if avail is not None and not avail(t): + r.available = False + seq0 = w.seq is not None + try: + await w.step(drv, r, mode=st["mode"], want_a=st["a"], + want_phases=st["n"], rev=st["rev"], + clamp=st["clamp"], now=float(t), tracker=trk, + writing=True, status="charging") + except Exception as e: # noqa: BLE001 + out.errs.append((t, e)) + d = snap(w) + d["seq0"], d["ncalls"] = seq0, len(drv.calls) + out.rows[t] = d + asyncio.run(main()) + out.log = list(LOG) + return out + + +def uc(st, w, t, out_ucs=None, **kw): + w.user_changed() + st["rev"] += 1 + st.update(kw) + UCS.append(t) + + +UCS = [] + + +def at(t0, **kw): + """A callback: one user change at t0 with these request changes.""" + def cb(t, st, w, drv): + if t == t0: + uc(st, w, t, **kw) + return cb + + +def nz(r, lo=-BIG, hi=BIG, a=None): + return [int(t) for t, x in r.drv.calls + if x > 0 and lo <= t < hi and (a is None or abs(x - a) < 0.01)] + + +def zeros(r): + return [int(t) for t, x in r.drv.calls if x == 0.0] + + +def refs(r): + return [t for t, lv, m in r.log if lv == "WARNING" and REF in m] + + +def recs(r): + return [t for t, lv, m in r.log if lv == "ERROR" and m == REC] + + +def near(got_, want, tol=1): + return len(got_) == len(want) and all(abs(g - w_) <= tol + for g, w_ in zip(got_, want)) + + +def never(name, r, *, ucs=(), clamp=16.0): + """N1 (no non-zero write while given up before a user change), N2 (one + REF per give-up), N5 (no select under load), N6 (nothing above the clamp + or in 0-6 A), N9 (no exception out of a step), N13 (closes at least 5 s + apart, normal tries RETRY_S apart).""" + bad1, up = [], 0 + t_prev, gv = None, False + for t in sorted(r.rows): + row = r.rows[t] + before = r.rows.get(t - 1) + n_new = row["ncalls"] - (before["ncalls"] if before else 0) + if gv and n_new and not any(u <= t and u > (t_prev or -1) for u in ucs) \ + and any(x > 0 for tt, x in r.drv.calls if tt == t): + bad1.append(t) + if row["gave_up"] and not (before or {}).get("gave_up"): + up += 1 + if not row["gave_up"] and (before or {}).get("gave_up"): + gv = False + if any(u == t for u in ucs): + gv = False + elif row["gave_up"]: + gv = True + t_prev = t + nzc = [(t, x) for t, x in r.drv.calls if x > 0] + bad13 = [] + for (ta, aa), (tb, ab) in zip(nzc, nzc[1:]): + inseq = r.rows[int(tb)]["seq0"] + lim = 5.0 if inseq else CM.RETRY_S + user = any(ta < u <= tb for u in ucs) + if tb - ta < lim - 1e-9 and not (user and not inseq) \ + and abs(aa - ab) < 0.01: + bad13.append((ta, tb)) + bad5 = [x for x in r.drv.phases_log if x[2] is not None + and x[2] >= CM.QUIET_W] + bad6 = [x for _t, x in nzc if x > clamp + 1e-9 or x < 6.0 - 1e-9] + check(f"{name}: N1 no write while given up ({bad1[:3]}); N2 one REF per " + f"give-up ({len(refs(r))} for {up}); N5 no select under load " + f"({bad5[:2]}); N6 nothing above the clamp or under 6 A " + f"({bad6[:3]}); N9 no exception ({r.errs[:1]}); N13 spacing " + f"({bad13[:3]})", + not bad1 and len(refs(r)) == up and not bad5 and not bad6 + and not r.errs and not bad13) + + +print("1. THE REPLAY, THE STATE AT THE CAP (T1, T2, T3, T23)") +UCS.clear() +R1 = run(refuse, 600) +check(f"T1: 6 A tried at {nz(R1)}: 11, 16, 21 and nothing after to 600 s; " + "the car stays at 0 A", + nz(R1) == [11, 16, 21] and R1.drv.cur == 0.0 + and all(x == 6.0 for _t, x in R1.drv.calls if x > 0)) +r21, r20 = R1.rows[21], R1.rows[20] +check(f"T2: at the 3rd refused close: seq None, last_a None, reapply, " + f"rev_applied None, fails MAX_TRIES, gave_up, fail_at 21, " + f"phase_done_at None ({r21}); one REF in that step ({refs(R1)})", + r21["seq"] is None and r21["last_a"] is None and r21["reapply"] is True + and r21["rev_applied"] is None and r21["fails"] == CM.MAX_TRIES + and r21["gave_up"] is True and r21["fail_at"] == 21 + and r21["phase_done_at"] is None and r21["phase_fails"] == 0 + and refs(R1) == [21] and r20["gave_up"] is False and r20["fails"] == 0) +check("T23: offByOne: the 2nd close (16) does not end the sequence and the " + "3rd (21) does; the states up to 16 are the base's", + R1.rows[11]["seq"] == ("settle", 1) and R1.rows[16]["seq"] == + ("settle", 2) and R1.rows[16]["fails"] == 0 + and not R1.rows[16]["gave_up"] and R1.rows[21]["seq"] is None + and not any(refs(R1)[i] < 21 for i in range(len(refs(R1))))) +never("T1", R1) + +RX = run(raises, 600) +strip = lambda d: {k: v for k, v in d.items() if k not in ("ncalls",)} # noqa +check("T3a: every close raises: calls, states and cycle by cycle as R; 1 " + f"ERROR record at 11 ({recs(RX)}), REF at 21 ({refs(RX)}); the " + "tracker is not told of a raise", + RX.drv.calls == R1.drv.calls + and all(strip(RX.rows[t]) == strip(R1.rows[t]) for t in range(600)) + and recs(RX) == [11] and refs(RX) == [21] + and not [x for x in RX.trk.notes if x[1] > 0] + and len([x for x in R1.trk.notes if x[1] > 0]) == 3) +never("T3a", RX) +RM = run(lambda a, n: True if a == 0.0 else ("raise" if n in (2, 4) + else False), 600) +check("T3b: raise, refuse, raise: 3 tries, 1 ERROR, 1 REF at 21, fails " + f"{RM.rows[21]['fails']}", + nz(RM) == [11, 16, 21] and recs(RM) == [11] and refs(RM) == [21] + and RM.rows[21]["fails"] == CM.MAX_TRIES and RM.rows[21]["gave_up"] + and [x[1] for x in RM.trk.notes if x[1] > 0] == [6.0]) +never("T3b", RM) + +print("\n2. TAKEN CLOSES AND FOLLOW-UPS (T4, T5, T6, T7, T8)") +UCS.clear() +R4 = run(lambda a, n: a == 0.0 or n == 2, 400, cb=at(100, a=8.0)) +r4 = R4.rows[11] +check(f"T4: the close taken on try 1: seq None, fails 0, no give-up, no REF, " + f"phase_done_at 11 ({r4['phase_done_at']}); 8 A at 100 gets 3 tries " + f"({nz(R4, 100, a=8.0)}) and one REF ({refs(R4)})", + r4["seq"] is None and r4["fails"] == 0 and not r4["gave_up"] + and r4["phase_done_at"] == 11 and near(nz(R4, 100, a=8.0), + [100, 160, 220]) + and refs(R4) == [220]) +never("T4", R4, ucs=[100]) +for tag, tk in (("a", 3), ("b", 4)): + UCS.clear() + R5 = run(lambda a, n, tk=tk: a == 0.0 or n == tk, 400, cb=at(100, a=8.0)) + r5 = R5.rows[40] + check(f"T5{tag}: close taken on try {tk - 1}: fails 0, no give-up, no " + f"REF, phase_done_at None ({r5['phase_done_at']}); 8 A at 100 gets " + f"3 full tries ({nz(R5, 100, a=8.0)})", + r5["fails"] == 0 and not r5["gave_up"] and r5["seq"] is None + and r5["phase_done_at"] is None + and near(nz(R5, 100, a=8.0), [100, 160, 220]) + and refs(R5) == [220] and R5.rows[21]["fails"] == 0) + never(f"T5{tag}", R5, ucs=[100]) + +for tag, kw, want in (("a", dict(a=8.0), 8.0), ("b", dict(a=6.0), 6.0)): + UCS.clear() + R6 = run(refuse, 400, cb=at(100, **kw)) + got6 = nz(R6, 100, a=want) + check(f"T6{tag}: after the give-up a user change to {want:.0f} A: a " + f"write at 100 and tries at +60, +120, then REF once more, never " + f"a 4th ({got6}, REF {refs(R6)})", + near(got6, [100, 160, 220]) and refs(R6) == [21, 220] + and R6.rows[100]["gave_up"] is False) + never(f"T6{tag}", R6, ucs=[100]) +UCS.clear() +R6c = run(refuse, 760, cb=at(700, n=1)) +check(f"T6c: after the give-up a 1 phase request (past PHASE_GAP_S): gave_up " + f"does not block it; the 0 A at 700 ({zeros(R6c)}), the select at the " + f"quiet car, then closes ({nz(R6c, 700)})", + near([z for z in zeros(R6c) if z >= 700], [700]) + and R6c.rows[700]["gave_up"] is False + and [x[1] for x in R6c.drv.phases_log if x[0] >= 700] == [1] + and near(nz(R6c, 700), [711, 716, 721]) and refs(R6c) == [21, 721]) +UCS.clear() + + +def off_then_manual(t, st, w, drv): + if t == 100: + st["mode"] = "off" + if t == 103: + st["mode"] = CM.MANUAL + uc(st, w, t) + + +R6d = run(refuse, 400, cb=off_then_manual) +check(f"T6d: Off, then Manual at 103: as T6b from the pick " + f"({nz(R6d, 100, a=6.0)})", + near(nz(R6d, 100, a=6.0), [103, 163, 223]) and refs(R6d) == [21, 223]) + +UCS.clear() +R7a = run(refuse, 600, avail=lambda t: not 130 <= t < 161) +check(f"T7a: the charger away 130-160, back at 161: no write after the " + f"return to 600 s ({nz(R7a, 100)}); gave_up stays", + nz(R7a, 100) == [] and R7a.rows[599]["gave_up"] and refs(R7a) == [21]) +never("T7a", R7a) +R7b = run(refuse, 600, avail=lambda t: not 12 <= t < 31) +check(f"T7b: away between close 1 and 2, back at 31: the count goes on: 3 " + f"tries of 6 A ({nz(R7b)}), then the give-up, REF once ({refs(R7b)})", + len(nz(R7b, a=6.0)) == 3 and R7b.rows[599]["gave_up"] + and len(refs(R7b)) == 1 + and all(b - a >= 5 for a, b in zip(nz(R7b), nz(R7b)[1:]))) +never("T7b", R7b) +UCS.clear() +R7c = run(raises, 600, avail=lambda t: not 130 <= t < 161, + cb=at(200, a=6.0)) +check(f"T7c: X, away and back, then a user change at 200: no write before " + f"200 after the return; the record is armed again: ERROR at " + f"{recs(R7c)} (1 before 200, 1 after)", + not nz(R7c, 100, 200) and len([x for x in recs(R7c) if x < 200]) == 1 + and len([x for x in recs(R7c) if x >= 200]) == 1) + +UCS.clear() +R8 = run(lambda a, n: a == 0.0 or n == 4, 1200, cb=at(700, n=1)) +b_calls = nz(R8, 700) +check(f"T8: sequence A (refused, refused, taken): fails " + f"{R8.rows[21]['fails']}, no give-up; then sequence B: 3 tries " + f"({b_calls}), no give-up after 1 or 2 " + f"({R8.rows[711]['gave_up']}, {R8.rows[716]['gave_up']}), then the " + f"give-up and 1 REF ({refs(R8)})", + R8.rows[21]["fails"] == 0 and not R8.rows[21]["gave_up"] + and near(b_calls, [711, 716, 721]) + and not R8.rows[711]["gave_up"] and not R8.rows[716]["gave_up"] + and R8.rows[721]["gave_up"] and refs(R8) == [721]) +never("T8", R8, ucs=[700]) + +print("\n3. A USER CHANGE DURING THE CLOSE RETRIES (T9, T24)") +for tag, t0, kw, want, exp_a, exp_6 in ( + ("a", 18, dict(a=8.0), 8.0, [21, 81, 141], [11, 16]), + ("b", 13, dict(a=8.0), 8.0, [16, 21, 81], [11])): + for how, ans in (("R", refuse), ("X", raises)): + UCS.clear() + R9 = run(ans, 600, cb=at(t0, **kw)) + g8 = nz(R9, a=8.0) + refs9 = refs(R9) + check(f"T9{tag} [{how}]: user change to 8 A at {t0}: 8 A gets " + f"exactly 3 tries ({g8}), the 6 A before it ({nz(R9, a=6.0)}); " + f"the REF once, at the 3rd try ({refs9}); fails after the " + f"close end {R9.rows[21]['fails']}", + near(g8, exp_a) and nz(R9, a=6.0) == exp_6 + and refs9 == [exp_a[-1]] + and not any(R9.rows[t]["gave_up"] for t in range(exp_a[-1])) + and R9.rows[exp_a[-1]]["gave_up"]) + never(f"T9{tag} [{how}]", R9, ucs=[t0]) +UCS.clear() +R24 = run(refuse, 600, cb=at(18, a=8.0)) +check("T24b: the user change after close 2: at the close end (21) fails 1, " + f"no give-up ({R24.rows[21]['fails']}, {R24.rows[21]['gave_up']}); the " + "normal path gives 2 more tries >= RETRY_S apart, then 1 REF", + R24.rows[21]["fails"] == 1 and not R24.rows[21]["gave_up"] + and R24.rows[81]["fails"] == 2 and R24.rows[141]["fails"] == 3 + and R24.rows[141]["gave_up"] and refs(R24) == [141]) +check("T24a: no user change: k = 3, fails 3, gave_up, 1 REF at the close end " + f"({R1.rows[21]['fails']}, {refs(R1)})", + R1.rows[21]["fails"] == CM.MAX_TRIES and refs(R1) == [21]) +UCS.clear() +R9c = run(refuse, 600, cb=at(18, a=6.0)) +after = [t for t in nz(R9c, a=6.0) if t >= 18] +check(f"T9c: the same value again at 18: 3 tries after the change ({after}), " + f"REF once at the last ({refs(R9c)})", + near(after, [21, 81, 141]) and refs(R9c) == [141] + and nz(R9c, a=6.0)[:2] == [11, 16]) +never("T9c", R9c, ucs=[18]) +UCS.clear() +R9d = run(refuse, 600, cb=at(2, a=8.0)) +check(f"T9 (change before the 1st close): 8 A gets 3 tries " + f"({nz(R9d, a=8.0)}), REF {refs(R9d)}", + len(nz(R9d, a=8.0)) == 3 and len(refs(R9d)) == 1) + +print("\n4. THE CLAMP, THE RESTORE CLOSES, THE SELECT (T10, T11, T12)") +UCS.clear() + + +def clamp_falls(t, st, w, drv): + if t == 18: + st["clamp"] = 8.0 + + +R10 = run(refuse, 400, a=10.0, clamp=10.0, cb=clamp_falls) +check(f"T10: the clamp falls to 8 A at 18: tries {nz(R10)} with values " + f"{[x for _t, x in R10.drv.calls if x > 0]}: never above the clamp then, " + f"at most 3 in all, REF once ({refs(R10)})", + len(nz(R10)) == 3 and [x for _t, x in R10.drv.calls if x > 0] + == [10.0, 10.0, 8.0] and refs(R10) == [21]) +never("T10", R10, clamp=10.0) + +UCS.clear() +R11a = run(refuse, 400, cur=16.0, a=16.0, power=lambda t, d: 1380.0, + cb=at(300)) +check(f"T11a: the drawing timeout, the 16 A restore refused: 3 tries 5 s " + f"apart ({nz(R11a, 0, 300)}), fails {R11a.rows[30]['fails']}, " + f"gave_up, REF once ({refs(R11a)}); phase_fails " + f"{R11a.rows[30]['phase_fails']}; no select ({R11a.drv.phases_log}); " + f"a user change writes 16 A at once ({nz(R11a, 300)[:1]})", + near(nz(R11a, 0, 300), [20, 25, 30]) + and R11a.rows[30]["fails"] == CM.MAX_TRIES and R11a.rows[30]["gave_up"] + and refs(R11a) == [30] and R11a.rows[30]["phase_fails"] == 1 + and not R11a.drv.phases_log and nz(R11a, 300)[:1] == [300]) +never("T11a", R11a, ucs=[300]) +UCS.clear() +R11b = run(refuse, 400, cur=16.0, a=16.0, sel=False, cb=at(300)) +check(f"T11b: the select refused, the restore close refused: 3 tries " + f"({nz(R11b, 0, 300)}), fails {R11b.rows[21]['fails']}, gave_up, " + f"REF once ({refs(R11b)}); phase_fails {R11b.rows[21]['phase_fails']}; " + f"1 select try ({len(R11b.drv.phases_log)}); a user change writes at " + "once", + near(nz(R11b, 0, 300), [11, 16, 21]) + and R11b.rows[21]["fails"] == CM.MAX_TRIES and R11b.rows[21]["gave_up"] + and refs(R11b) == [21] and R11b.rows[21]["phase_fails"] == 1 + and len(R11b.drv.phases_log) == 1 and nz(R11b, 300)[:1] == [300]) +never("T11b", R11b, ucs=[300]) + +UCS.clear() +R12a = run(lambda a, n: a != 0.0, 400) +check(f"T12a: only the 0 A fails (_begin): tries {zeros(R12a)} >= 60 s " + f"apart, at most 3, no select, REF once ({refs(R12a)})", + 0 < len(zeros(R12a)) <= 3 and not R12a.drv.phases_log + and all(b - a >= 60 for a, b in zip(zeros(R12a), zeros(R12a)[1:])) + and len(refs(R12a)) == 1 and R12a.rows[399]["gave_up"]) +R12b = run(lambda a, n: True, 100, sel=False) +check(f"T12b: a refused select counts for the phases only: close taken, fails " + f"{R12b.rows[60]['fails']}, phase_fails {R12b.rows[60]['phase_fails']}, " + "no REF", + R12b.rows[60]["fails"] == 0 and R12b.rows[60]["phase_fails"] == 1 + and not refs(R12b) and not R12b.rows[60]["gave_up"]) +R12c = run(lambda a, n: True, 100, cur=16.0, a=16.0, + power=lambda t, d: 1380.0) +check(f"T12c: the drawing timeout, the restore taken: fails " + f"{R12c.rows[60]['fails']}, no give-up, phase_fails " + f"{R12c.rows[60]['phase_fails']}", + R12c.rows[60]["fails"] == 0 and not R12c.rows[60]["gave_up"] + and R12c.rows[60]["phase_fails"] == 1 and not refs(R12c)) + +print("\n5. UNDO, SHUTDOWN, SOLAR, A CHARGER THAT ANSWERS (T13, T14, T15)") +UCS.clear() + + +def off_at(t0): + def cb(t, st, w, drv): + if t == t0: + st["mode"] = "off" + return cb + + +R13a = run(refuse, 100, power=lambda t, d: 1380.0, cb=off_at(5)) +check(f"T13a: Off in stage zero: 10 A restored once ({nz(R13a)}), undone " + f"{R13a.w.undone}, fails {R13a.rows[99]['fails']}", + near(nz(R13a, a=10.0), [5]) and len(nz(R13a)) == 1 + and R13a.w.undone == 1 and R13a.rows[99]["fails"] == 0) +R13b = run(refuse, 100, cb=off_at(12)) +check(f"T13b: Off after close 1: the closes go on ({nz(R13b)}), give-up at " + f"21, REF once ({refs(R13b)}), no write after", + nz(R13b) == [11, 16, 21] and R13b.rows[21]["gave_up"] + and refs(R13b) == [21]) + + +box = {} + + +def abandon_cb(t0, ans_kind): + def cb(t, st, w, drv): + if t == t0 + 1: + async def go(): + n0 = len(drv.calls) + try: + await w.abandon(drv, float(t), Trk(), clamp=16.0) + box[ans_kind] = ("ok", len(drv.calls) - n0) + except RuntimeError: + box[ans_kind] = ("raised", len(drv.calls) - n0) + return go() + return cb + + +R13c = run(refuse, 40, cb=abandon_cb(11, "R")) +check(f"T13c: shutdown between close 1 and 2: the old 10 A restored once, " + f"strict, no exception ({box.get('R')}), seq None, calls {nz(R13c)}", + box.get("R") == ("ok", 1) and R13c.w.seq is None + and near(nz(R13c, a=10.0), [12])) +R13x = run(raises, 40, cb=abandon_cb(11, "X")) +check(f"T13c: X: the raise comes out of abandon, as base, for the caller's " + f"CHARGER_RESTORE ({box.get('X')}); the writer's seq is None", + box.get("X") == ("raised", 1) and R13x.w.seq is None) +R13d = run(refuse, 40, cb=abandon_cb(40, "D")) +n_d = len(R13d.drv.calls) + + +async def after_giveup(): + n0 = len(R13d.drv.calls) + await R13d.w.abandon(R13d.drv, 41.0, Trk(), clamp=16.0) + return len(R13d.drv.calls) - n0 +check("T13d: shutdown after the give-up: no write", + asyncio.run(after_giveup()) == 0 and R13d.w.gave_up) + + +def solar_writer(cur): + 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, 1 + w._plan_step = lambda *a, **k: None + return w + + +def sp3(press, cls=solar_writer): + LOG.clear() + drv = Drv(8.0, refuse) + w, trk = cls(8.0), Trk() + w.plan._set(8.0, 0.0, 3) + pressed = None + + async def main(): + nonlocal pressed + for t in range(1, 200): + if press and pressed is None and \ + len([x for x in drv.calls if x[1] > 0]) == 1: + w.user_changed() + pressed = t + drv.now = float(t) + CLOCK["t"] = t + w.cut_quarter(int(t // 900)) + r = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0) + await 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") + asyncio.run(main()) + nzs = [int(t) for t, x in drv.calls if x > 0] + rf = [t for t, lv, m in LOG if lv == "WARNING" and REF in m] + return nzs, w.fails, w.gave_up, rf, pressed + + +S_NONE = sp3(False) +S_PRESS = sp3(True) +check(f"T25/T14 (N14): Solar equals base. No press: 8 A at 12, 17, 22, fails " + f"4, gave_up, REF at 22 ({S_NONE})", + S_NONE == ([12, 17, 22], 4, True, [22], None)) +check(f"T25 (resetSuper trap): a Solar press at 13 does not reset Solar's " + f"tries: 8 A at 12, 17, 22, fails 3, gave_up, REF at 22 ({S_PRESS})", + S_PRESS == ([12, 17, 22], 3, True, [22], 13)) + +print("\n6. THE CAP, RESTART, UNKNOWN, NO CHARGER (T15-T22)") +UCS.clear() +RA = run(lambda a, n: True, 100) +check(f"T15: a charger that answers: 0 A at 0, 6 A at 11, nothing else " + f"({RA.drv.calls}); fails 0, no give-up, phase_done_at " + f"{RA.rows[11]['phase_done_at']}", + RA.drv.calls == [(0.0, 0.0), (11.0, 6.0)] + and RA.rows[99]["fails"] == 0 and RA.rows[11]["phase_done_at"] == 11 + and not refs(RA)) +for cap in (2, 4): + UCS.clear() + saved = CM.MAX_TRIES + CM.MAX_TRIES = cap + try: + R16 = run(refuse, 400) + finally: + CM.MAX_TRIES = saved + want16 = [11 + 5 * i for i in range(cap)] + check(f"T16: MAX_TRIES {cap}: tries {nz(R16)} (never {cap + 1}), give-up " + f"at {want16[-1]}, REF {refs(R16)}", + nz(R16) == want16 and refs(R16) == [want16[-1]] + and R16.rows[want16[-1]]["fails"] == cap + and R16.rows[want16[-1]]["gave_up"]) +UCS.clear() +w20 = CM.ManualWriter() +check("T20: a restart: the new writer starts with 0 fails, no give-up, and " + "no count", + w20.fails == 0 and not w20.gave_up + and getattr(w20, "_close_k", 0) == 0) +R20 = run(refuse, 30, w=w20) +check(f"T20: after the restart the first write goes out once ({zeros(R20)})", + zeros(R20) == [0]) +R21 = run(refuse, 400, rd_none=True) +check(f"T21: the read-back unknown (allowed and setpoint None): judged by the " + f"write's result: tries {nz(R21)}, give-up, REF once ({refs(R21)})", + len(nz(R21)) == 3 and R21.rows[399]["gave_up"] and len(refs(R21)) == 1 + and not R21.errs) +R21b = run(refuse, 400, power=lambda t, d: None, cur=16.0, a=16.0) +check(f"T21: the power unknown: the sequence ends in 3 tries at most, no " + f"exception ({nz(R21b)}, {R21b.errs[:1]})", + len(nz(R21b)) <= 3 and not R21b.errs) +R22 = run(refuse, 600, avail=lambda t: False) +check("T22: no charger: 0 writes, no lines, no REF", + not R22.drv.calls and not R22.log and not refs(R22)) + +print("\n7. N4") +w4 = CM.ManualWriter() +w4.gave_up, w4.fails, w4._close_k = True, 3, 3 +w4.user_changed() +check("N4: user_changed clears gave_up, fails and the close count", + not w4.gave_up and w4.fails == 0 and w4._close_k == 0) +R4n = run(refuse, 400, cb=at(100, a=8.0)) +check("N4: a give-up does not block the next user change or phase change " + f"({nz(R4n, 100)[:1]})", nz(R4n, 100)[:1] == [100]) + +print() +if fails: + print(f"FAIL: {len(fails)} check(s)") + for f in fails: + print(" -", f) + sys.exit(1) +print("ok: EV-59")