diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index ee84ce5..1e80155 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -2,6 +2,7 @@ ### Not in a release yet +- **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]]). - **The add-on log now says when the add-on sets a new car current or the car mode changes.** One line each, for example "Car: set from 10 A to 6 A on 1 phase (Manual)." and "Car mode is now Manual." It names the reason: Manual, Solar, peak cut, start-up or shutdown. A refused write adds no such line, and nothing is written or timed differently ([[EV-52]]). - **Solar now lowers the car first for the peak limit.** When the 15-minute period heads over the limit, Solar lowers the car before the batteries give more, and brings it back when the period allows. One grey note says "Solar lowered the car for the peak." A Solar car the add-on cannot lower (another writer, shadow mode, a stop) no longer hides a peak alarm. Manual and Off do not change. See "Car charger" in DOCS ([[EV-21]]). diff --git a/goodwe_controller/DECISIONS/EV-56-raising-write.md b/goodwe_controller/DECISIONS/EV-56-raising-write.md new file mode 100644 index 0000000..5f960b5 --- /dev/null +++ b/goodwe_controller/DECISIONS/EV-56-raising-write.md @@ -0,0 +1,37 @@ +# EV-56 — a charger write that raises is a not-taken try + +`drv.write_current` raising (an HA call error, a binding or setup error, a bug) +left `ManualWriter._write` before any bookkeeping, so no caller counted it and +Manual and Solar sent the same write every cycle. The rules below are the PM +rulings Q1-Q4, F1, F3, G1-G3, H1, H3 and H4 (brief v6); the formal check is +reports/EV-56-formal-report.md. + +## The rule, in plain words + +- **A raise is a try the charger did not take**, on every path that writes a + current (the normal write, a phase change's 0 A and closing current, the + Off or shadow undo): the same RETRY_S spacing, MAX_TRIES cap, give-up and + CHARGER_REFUSED as a refusal, and the same writer state (`log` row, + `attempted_a`, a late accept). `ManualWriter._write` catches it and returns + False; the callers count it as before. Solar counts it in its own `_write`. +- **The tracker is not told** (Q2): no `note_write`, so no refusal window and + no stuck arming. The write's `end_write` (the mute) still runs. +- **One ERROR record per raised value** (Q1): "The car charger step failed", + with the traceback, at the first raise of a value; DEBUG on its retries. It + is armed again by another value written, a taken write, a user change and + the charger's return (G2), in `_rec_a`. +- **A peak cut try that raises** keeps EV-54's path: one DEBUG line, no record + (G1). +- **Shutdown is as before** (F3, H1, G3): `abandon` and `release` pass + `strict`, so a raise still leaves the write. Manual's give-back keeps its + CHARGER_RESTORE; Solar's release stops after 1 try with no cut standing and + keeps the cut path's 3 tries with one. No record at shutdown. +- **Cancel is not a raise**: only `Exception` is caught, never + `CancelledError`. + +## Left as they were + +The phase select (`write_phases`, Q4, EV-58), Solar's 4 fails for a refused +close (F1), Manual's up to 5 tries of a close value (H3, EV-59) and the cut +tries through a phase change (H4, EV-60). test_ev56.py T5b and T19b pin the +last two at base. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 23bc92a..91a5c90 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -148,6 +148,7 @@ class ManualWriter: self._returned = False # ... and came back after being gone 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 # ------------------------------------------------------------------ user def user_changed(self) -> None: @@ -161,6 +162,7 @@ class ManualWriter: 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 + self._rec_a = None # EV-56 (G2): a raise is logged again # ------------------------------------------------------------------ step async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp, @@ -185,6 +187,7 @@ class ManualWriter: self._seen = True self.was_available = True self.reapply = True # on return: only if it differs + 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: if self.seq["stage"] in ("zero", "select") \ @@ -320,31 +323,58 @@ class ManualWriter: async def _write(self, drv, a, was, now, tracker, **kw) -> bool: why = kw.pop("why", None) or self._why_default() n = kw.pop("n", None) + # EV-56: a raise at shutdown is left to the caller (CHARGER_RESTORE). + strict = kw.pop("strict", False) self._late = None + 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 if float(a) > TOL_A: # EV-20 C6, THE ONE WRITE CLOCK: every non-zero current either # writer sends, whatever path it comes from, is stamped here (the # one write_current call). Solar's 30 s gate reads this stamp. self.nonzero_at = now + err = None try: # EV-20: `kw` is only Solar's shorter read-back wait at shutdown. ok = await drv.write_current(a, **kw) + except Exception as e: # noqa: BLE001 + if strict: + raise + ok, err = False, e finally: self._stamp(now) tracker.end_write(self.last_done) + if err is not None: + self._raised(err, a, was, now, why, n) + return False tracker.note_write(now, was, a, ok, getattr(drv, "polls", ())) tracker.end_write(self.last_done) self.log.append(("current", a, now, ok)) if ok: self.last_a = a self.attempted_a = self.prior_a = None + self._rec_a = None # EV-56 (G2): a taken write self._log_set(a, was, why, n) else: self.attempted_a, self.prior_a = a, was self._late = (a, was, why, n) # logged if it is adopted later return ok + def _raised(self, err, a, was, now, why, n) -> None: + """EV-56: a write that raised (an HA call error, a setup error, a bug) + is a try the charger did not take, counted by the caller as a refusal + is. It is no charger answer, so the tracker is not told (Q2). Its + ERROR record, with the traceback, comes once per raised value (Q1).""" + self.log.append(("current", a, now, False)) + self.attempted_a, self.prior_a = a, was + self._late = (a, was, why, n) # logged if it is adopted later + if self._rec_a is None: + self._rec_a = float(a) + _LOG.error("The car charger step failed", exc_info=err) + else: + _LOG.debug("The car charger write failed again: %s", err) + def _stamp(self, now) -> None: self.last_done = (self._clock or (lambda: now))() @@ -395,7 +425,8 @@ class ManualWriter: a = None if q is None else self._restore_a(q.get("prev"), clamp) if a is not None: self._clock = self._clock or (lambda: now) - await self._write(drv, a, 0.0, now, tracker, why="shutdown") + await self._write(drv, a, 0.0, now, tracker, why="shutdown", + strict=True) async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev): q = self.seq @@ -972,6 +1003,7 @@ class SolarWriter(ManualWriter): the write goes out, so a write cancelled while it waits for its read-back is never trusted (`live`).""" prev = self.sent_a + strict = kw.pop("strict", False) # EV-56: `release` (H1) why = kw.get("why") if why is None: # EV-52: the 0 A the start caused is `start-up`, else Solar's own. @@ -998,15 +1030,22 @@ class SolarWriter(ManualWriter): self.zero_at = self.zero_sent_at = now self._owed(True) # C1: kept with the mode until back try: - ok = await super()._write(drv, a, was, now, tracker, **kw) + ok = await super()._write(drv, a, was, now, tracker, + strict=True, **kw) except Exception as e: # noqa: BLE001 if not cut_try: - raise - # EV-54 (T15): a cut write that raises is a refused cut try, so it - # is spaced and capped like one, not tried once per cycle. - _LOG.debug("The peak cut write failed: %s", e) - self.log.append(("current", a, now, False)) - self.attempted_a, self.prior_a = a, was + if strict: + raise # EV-56 (H1): shutdown as before + # EV-56: a try the charger did not take, counted below as a + # refusal is; the tracker is not told (Q2). + self._raised(e, a, was, now, why, kw.get("n")) + else: + # EV-54 (T15): a cut write that raises is a refused cut try, + # so it is spaced and capped like one, not tried once per + # cycle. + _LOG.debug("The peak cut write failed: %s", e) + self.log.append(("current", a, now, False)) + self.attempted_a, self.prior_a = a, was ok = False finally: if zero: @@ -1353,6 +1392,7 @@ class SolarWriter(ManualWriter): self.fresh_start = self.restart = True self.mismatch_since = None 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 stuck = bool(tracker is not None and tracker.stuck(now)) if not self.taken and self.sent_a is not None and not stuck \ @@ -1578,7 +1618,8 @@ class SolarWriter(ManualWriter): if wait > 0: await sleep(wait) if await self._write(drv, 0.0, cur, clock(), tracker, - took_s=RELEASE_TOOK_S, why="shutdown"): + took_s=RELEASE_TOOK_S, why="shutdown", + strict=True): self.released = True return True self.released = False diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index 45d4ece..b1be2e4 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -802,7 +802,7 @@ for exc in (RuntimeError("the link broke"), hass.ReadOnly("read only")): "never armed, no window left, no refusal counted, the mute set, " f"the step error logged once ({len(errs)})", never_stuck(tr) and pend(w.c.car) is None - and w.c.car_writer.fails == 0 and w.c.car.mute_until > 0 + and w.c.car_writer.fails == 1 and w.c.car.mute_until > 0 and len(errs) == 1) diff --git a/goodwe_controller/test_ev56.py b/goodwe_controller/test_ev56.py new file mode 100644 index 0000000..7f69fb5 --- /dev/null +++ b/goodwe_controller/test_ev56.py @@ -0,0 +1,1315 @@ +"""EV-56: a charger write that raises counts as a not-taken try in Manual and +in Solar, as a refused one does. `python3 -B test_ev56.py` + +Rows T1-T29 (with T5b, T7c, T15d, T19b, T28b) and N1-N14 of +reports/EV-56-test-plan.md. The real Controller on `tools/ev20_sun.py` (a +model clock, the charger model, a 1 s cycle), with `drv.write_current` +replaced by a stub (`Stub`): R returns False, X raises, A takes the real +driver, each after the same model delay (1 s unless a row says otherwise). +Rows marked "writer level" call `ManualWriter`/`SolarWriter` directly with a +stub driver, a stub tracker and `ctl_car`'s own `_car_run` around each step. +Time is the model clock throughout, never x10 and never wall time (T16b +alone measures a real `asyncio.wait_for`, with RELEASE_WAIT_S scaled down). +Golden values marked 344c974 were taken on that tree with +`EV56_GOLDEN=1 python3 -B test_ev56.py` (rows that must equal base). + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import os +import sys +import time +from types import SimpleNamespace + +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, ctl_car, hass # noqa: E402 +import ev20_sun as S # noqa: E402 +import ev54_kit as K # noqa: E402 +from ev20_kit import LOG, act, const, step_fn, report # noqa: E402 +from ev20_kit import check as _check # noqa: E402 +from ev21_kit import merge, digest # noqa: E402 +from named_absence import nth, present # noqa: E402 + +REC = "The car charger step failed" +REF_M = "stops asking until you change it: CHARGER_REFUSED." +REF_S = "stops asking until you press Solar: CHARGER_REFUSED." +Q3 = "tries again next quarter: CHARGER_REFUSED." +RESTORE = "CHARGER_RESTORE." +RELEASE = "CHARGER_RELEASE." +CUTDBG = "The peak cut write failed" +SETP = "Car: set" +TAKE = os.environ.get("EV56_GOLDEN") == "1" +BIG = 1e12 +GOLDEN = { + # 344c974, refusing stub (R): the 6 A tries of T5's world to 300 s. + "T5b": [(111.0, 6.0), (116.0, 6.0), (121.0, 6.0), (181.0, 6.0), + (241.0, 6.0)], + # 344c974: (seconds after the shutdown began, values, released, the + # (fails, cut_fails) increase) of Solar's release with a cut standing. + "T15d [X]": ([0.0, 5.0, 10.0], [0.0, 0.0, 0.0], False, (3, 3)), + "T15d [R]": ([0.0, 5.0, 10.0], [0.0, 0.0, 0.0], False, (3, 3)), + # 344c974: T20's digests (`view`) of each world with the accepting (A) + # 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 T8 [A]": "2cd78dee7ee93aaa", "T20 T8 [R]": "f0adb058a5bbefba", + "T20 T11 [A]": "6d7bcb747d1dc5a3", "T20 T11 [R]": "2be1a760b699b28c", + "T20 T12 [A]": "a5888e4557b4ee8f", "T20 T12 [R]": "2fd24ddbb18f14cc", + "T20 T13 [A]": "1ad97e089468d71b", "T20 T13 [R]": "7baf8981ab382e05", + "T20 T15 [A]": "54701b140ec6f30b", "T20 T15 [R]": "0cfd3ccd334f378d", + "T20 T15d [A]": "1d85595302dc032a", "T20 T15d [R]": "5fc65dbdc730e539", +} +got = {} + + +def check(name, cond): + """ev20_kit's check, the name cut at 360 characters (a base run's lists + of a call every cycle would fill the screen).""" + _check(name if len(name) <= 360 else name[:360] + " ...", cond) + + +def golden(name, value): + got[name] = value + if TAKE: + print(f"GOLDEN {name!r}: {value!r},") + return GOLDEN.get(name) + + +# =========================================================================== # +# The stub driver and the run +# =========================================================================== # +class Stub: + """`c.charger.write_current` replaced (an event before the first cycle, + or a finale). kind "R": False; "X": raises; "A": the real driver; each + after `delay` model seconds (the driver's own sleep). `when(p, a)` + picks the writes it acts on (the others go to the real driver); + `n_bad`: only that many, then the real driver; `take`: the charger + takes the value before the raise (T17); `exc`: the exception's + factory; `hang`: real seconds to wait first (T16b).""" + + def __init__(self, kind, when=None, delay=1.0, exc=None, take=False, + hang=None, n_bad=None): + self.kind, self.when, self.delay = kind, when, delay + self.exc, self.take, self.hang, self.n_bad = exc, take, hang, n_bad + self.calls = [] + self.off = False + + def __call__(self, p, c): + drv = c.charger + real = drv.write_current + + async def wc(a, **kw): + if self.off or (self.when is not None and not self.when(p, a)) \ + or (self.n_bad is not None + and len(self.calls) >= self.n_bad): + return await real(a, **kw) + self.calls.append((p.t, float(a))) + if self.hang: + await asyncio.sleep(self.hang) + if self.delay: + await drv._sleep(self.delay) + if self.kind == "A": + return await real(a, **kw) + if self.take: + p.ch.set_current(a) + if self.kind == "X": + raise (self.exc() if self.exc else + RuntimeError("HA call error")) + return False + drv.write_current = wc + + +def stop_stub(stub): + def f(p, c): + stub.off = True + return f + + +MF = ("fails", "fail_at", "gave_up", "attempted_a", "prior_a", "last_a", + "phase_fails", "last_switch", "reapply", "rev_applied", "undone", + "zero_sent_at", "phase_done_at", "hold") +SF = ("sent_a", "taken", "refused_cut", "cut_fails") + + +def snap(w, solar=False): + d = {k: getattr(w, k, None) for k in MF + (SF if solar else ())} + q = w.seq + d["seq"] = None if q is None else (q.get("stage"), q.get("tries"), + bool(q.get("failed"))) + late = getattr(w, "_late", None) + d["late"] = None if late is None else tuple(late) + d["log"] = (len(w.log), tuple(w.log[-1]) if w.log else None) + if solar: + d["plan"] = (w.plan.a, w.plan.n, w.plan.switch) + return d + + +def go(mode, dur, *, stub=None, events=None, house=900.0, sun=0.0, **kw): + """One run. `out["rows"]`: per cycle (t, Manual's state, Solar's state, + the tracker); `out["lines"]`: (cycle second or None, level, message, + traceback?) of every log record of the run (None: the finale).""" + n0, marks, rows = LOG.mark(), [], [] + + def oc(p, c, t): + marks.append((t, LOG.mark())) + car = c.car + rows.append((t, snap(c.car_writer), snap(c.car_solar, True), + dict(pend=getattr(car, "_pend", None) is not None, + armed=car.armed_at, mute=car.mute_until, + stuck=bool(car.stuck(t)), + done_m=c.car_writer.last_done, + done_s=c.car_solar.last_done))) + ev = dict(events or {}) + if stub is not None: + ev = merge(ev, 0, stub) + kw.setdefault("first", "car") + r = S.drive(house if callable(house) else const(house), + sun if callable(sun) else const(sun), dur=dur, mode=mode, + events=ev, on_cycle=oc, **kw) + lines = [] + for i in range(n0, len(LOG.rec)): + lv, m, x = LOG.rec[i] + t = next((tt for tt, hi in marks if hi > i), None) + lines.append((t, lv, m, x)) + r.update(rows=rows, lines=lines, stub=stub or Stub("A")) + return r + + +MAN_EV = {10: act("car_phases", 1), 15: act("car_current", 6), + 20: act("car_mode", "manual")} + + +def manual(dur, stub=None, events=None, **kw): + """Manual, 1 phase: the charger shows its own 10 A; the user sets 6 A + and picks Manual at 20 (t0).""" + ev = dict(MAN_EV) + for k, v in (events or {}).items(): + ev = merge(ev, k, v) + kw.setdefault("setpoint", 10) + kw.setdefault("phases", 1) + kw.setdefault("car_phases", 1) + kw.setdefault("opts", {"ev_phases": "1"}) + return go("off", dur, stub=stub, events=ev, **kw) + + +MP_EV = {5: act("car_current", 6), 6: act("car_phases", 1), + 7: act("car_mode", "manual"), 100: act("car_phases", 3)} + + +def mphase(dur, stub=None, events=None, **kw): + """Manual at 6 A on 1 phase, the car at 1380 W; the user picks 3 phases + at 100.""" + ev = dict(MP_EV) + for k, v in (events or {}).items(): + ev = merge(ev, k, v) + return go("off", dur, stub=stub, events=ev, setpoint=6, phases=1, + car_phases=3, opts={"ev_phases": "auto"}, **kw) + + +def sun8(t0=1000, more=()): + """Solar at 10 A on 3 phases (spare 7000 W, Car first), then the sun + falls at `t0` and the plan steps down to 8 A.""" + return step_fn((t0, 6700.0), *more, base=7900.0) + + +def solar(dur, stub=None, sun=None, **kw): + kw.setdefault("phases", 3) + kw.setdefault("car_phases", 3) + kw.setdefault("opts", {"ev_phases": "3"}) + return go("solar", dur, stub=stub, sun=sun or sun8(), **kw) + + +def after(t0): + return lambda p, a: p.t >= t0 + + +def zero_after(t0): + return lambda p, a: p.t >= t0 and float(a) <= CM.TOL_A + + +def nz_after(t0): + return lambda p, a: p.t >= t0 and float(a) > CM.TOL_A + + +def freeze(p, c): + p.ch.freeze_power() + + +# ------------------------------------------------------------- reading runs +def calls(r, lo=-BIG, hi=BIG, a=None): + return [(t, v) for t, v in r["stub"].calls + if lo <= t < hi and (a is None or abs(v - a) < 0.01)] + + +def ts(xs): + return [t for t, _v in xs] + + +def gaps(xs): + return [b - a for a, b in zip(xs, xs[1:])] + + +def near_seq(got_, want, tol=1.0): + return len(got_) == len(want) and all(abs(g - w) <= tol + for g, w in zip(got_, want)) + + +def _in(t, lo, hi): + tt = BIG if t is None else t + return lo <= tt < hi + + +def tt(t): + """A line's cycle second; a finale's (None) sorts last.""" + return BIG if t is None else t + + +def recs(r, lo=-BIG, hi=BIG * 2): + """(second, traceback?) of every step-failed ERROR record.""" + return [(tt(t), x) for t, lv, m, x in r["lines"] + if lv == "ERROR" and m == REC and _in(t, lo, hi)] + + +def warns(r, text, lo=-BIG, hi=BIG * 2): + return [t for t, lv, m, _x in r["lines"] + if lv == "WARNING" and text in m and _in(t, lo, hi)] + + +def charger_warns(r): + return [(t, m) for t, lv, m, _x in r["lines"] + if lv == "WARNING" and "CHARGER_" in m] + + +def sets_(r, lo=-BIG, hi=BIG * 2): + return [(tt(t), m) for t, lv, m, _x in r["lines"] + if m.startswith(SETP) and _in(t, lo, hi)] + + +def debugs(r, text, lo=-BIG, hi=BIG * 2): + return [t for t, lv, m, _x in r["lines"] + if lv == "DEBUG" and text in m and _in(t, lo, hi)] + + +def tracebacks(r): + return [m for _t, _lv, m, x in r["lines"] if x] + + +def row_at(r, t): + return next((x for x in r["rows"] if x[0] == t), None) + + +def stuck_split(r1, r2): + """The first cycle whose stuck verdict differs between the two runs, or + BIG. A refused write is told to the tracker and a raised one is not + (Q2), so the R twin can reach a stuck verdict the X run never does.""" + return next((x[0] for x, y in zip(r1["rows"], r2["rows"]) + if x[3]["stuck"] != y[3]["stuck"]), BIG) + + +def writer_eq(r1, r2, which): + """The plan's "writer equal": the stub's call list, the writer's state + every cycle, the CHARGER_* warnings and (with `rows`) the amber rows, + but the tracker's own `charger_stuck` (Q2: the tracker is not told of + a raise). Solar reads the stuck verdict, so Solar's are compared up to + the first cycle where the two verdicts differ (`stuck_split`); Manual + never reads it and is compared over the whole run. The list of + differences (empty: equal).""" + k = 1 if which == "m" else 2 + end = BIG if which == "m" else stuck_split(r1, r2) + a = [(x[0], x[k]) for x in r1["rows"] if x[0] < end] + b = [(x[0], x[k]) for x in r2["rows"] if x[0] < end] + bad = [(x, y) for x, y in zip(a, b) if x != y][:1] + if len(a) != len(b): + bad.append(("cycles", len(a), len(b))) + c1 = [x for x in r1["stub"].calls if x[0] < end] + c2 = [x for x in r2["stub"].calls if x[0] < end] + if c1 != c2: + bad.append(("calls", c1[:5], c2[:5])) + w1 = [x for x in charger_warns(r1) if _in(x[0], -BIG, end)] + w2 = [x for x in charger_warns(r2) if _in(x[0], -BIG, end)] + if w1 != w2: + bad.append(("warnings", w1, w2)) + am1 = [(x["t"], tuple(a_ for a_ in x["amber"] if a_ != "charger_stuck")) + for x in r1["trace"] if x["t"] < end] + am2 = [(x["t"], tuple(a_ for a_ in x["amber"] if a_ != "charger_stuck")) + for x in r2["trace"] if x["t"] < end] + if am1 != am2: + bad.append(("amber", [x for x in am1 if x not in am2][:2])) + return bad + + +X_RUNS = [] # every Controller run with a raising stub (T18) + + +def xrun(r): + X_RUNS.append(r) + return r + + +def never(name, r, *, close_ok=False, clamp=16.0): + """N1 (the same value not twice within RETRY_S, 5 s on a phase change's + close; no write every cycle), N6 (no select after a 0 A that was not + taken, none under load), N7 (no write above the clamp or between 0 and + 6 A) over one run's stub calls and charger log.""" + bad1 = [] + seq_at = {x[0]: (x[1]["seq"] or x[2]["seq"]) for x in r["rows"]} + cl = r["stub"].calls + for i, (ta, aa) in enumerate(cl): + nxt = next(((tb, ab) for tb, ab in cl[i + 1:] + if abs(ab - aa) < 0.01), None) + if nxt is None: + continue + gap = nxt[0] - ta + in_seq = close_ok and seq_at.get(ta) is not None + if gap < (5.0 - 1e-9 if in_seq else CM.RETRY_S - 1.0 - 1e-9): + bad1.append((ta, nxt[0], aa)) + every = [t for t, n in _per_sec(cl) if n > 1] + sim = r["sim"] + bad6 = [x for x in sim.log if x[1] == "phases" + and (x[3] >= CM.QUIET_W or x[4] > 0.0)] + vals = [v for _t, v in cl] + [x[2] for x in sim.log if x[1] == "current"] + bad7 = [v for v in vals if v > clamp + 1e-9 or 0.0 + 1e-9 < v < 6.0 - 1e-9] + check(f"{name}: N1 no same value twice within RETRY_S ({bad1[:3]}), no two " + f"tries in one second ({every[:3]}); N6 no select under load " + f"({bad6[:2]}); N7 nothing above the clamp or in 0-6 A ({bad7[:3]})", + not bad1 and not every and not bad6 and not bad7) + + +def _per_sec(cl): + out = {} + for t, _v in cl: + out[int(t)] = out.get(int(t), 0) + 1 + return sorted(out.items()) + + +# =========================================================================== # +# Writer level: a stub reading, tracker and driver, `_car_run` around a step +# =========================================================================== # +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, self.ends, self.begins = [], [], 0 + self.mute_until = 0.0 + + def begin_write(self): + self.begins += 1 + + def end_write(self, t): + self.ends.append(t) + + 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.""" + + def __init__(self, cur, answer, ph=1): + self.cur, self.ph, self.answer = cur, ph, answer + self.calls, self.now, self.polls = [], 0.0, () + + 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.ph = n + return True + + +class Runner: + """`ctl_car`'s own `_car_run` around each step, as the Controller runs + it (its once-per-spell record on the base build).""" + + def __init__(self): + self.me = SimpleNamespace(_car_step_failed=False, car_step=None) + self.n0 = LOG.mark() + + def run(self, make): + async def step(): + await make() + self.me.car_step = step + asyncio.run(ctl_car.CarMixin._car_run(self.me)) + + def recs(self): + return [x for lv, m, x in LOG.rec[self.n0:] + if lv == "ERROR" and m == REC] + + def lines(self, lv=None, text=""): + return [m for l_, m, _x in LOG.rec[self.n0:] + if lv in (None, l_) and text in m] + + +def mstep(w, drv, t, trk, r=None, want=6.0, n=1, rev=1, mode=CM.MANUAL, + writing=True): + drv.now = float(t) + rd = r if r is not None else Rd(drv.cur, drv.ph, + power=0.0 if drv.cur == 0 else 1380.0) + return w.step(drv, rd, mode=mode, want_a=want, want_phases=n, rev=rev, + clamp=16.0, now=float(t), tracker=trk, writing=writing, + status="charging") + + +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 # the plan set by hand + return w + + +def sstep(w, drv, t, trk, quarter=900, sun=None): + drv.now = float(t) + w.cut_quarter(int(t // quarter)) + r = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0) + return w.step(drv, r, mode=CM.SOLAR, + sun=sun or CM.SunInputs(target_w=2000.0), clamp=16.0, + now=float(t), tracker=trk, writing=True, status="charging") + + +# =========================================================================== # +print("1. MANUAL: A RAISING WRITE IS A NOT-TAKEN TRY (T1-T3, T22)") +# =========================================================================== # +R1 = {k: manual(300, stub=Stub(k), rows=True) for k in "RX"} +x1 = xrun(R1["X"]) +w1 = x1["c"].car_writer +eq1 = writer_eq(R1["R"], x1, "m") +c1 = calls(x1) +check(f"T1: Manual 10 -> 6 A, raising (X) vs refusing (R) stub: writer equal " + f"cycle by cycle ({eq1[:1]})", not eq1) +check(f"T1: tries at t0, +60, +120, then none to 300 s ({c1})", + near_seq(ts(c1), [20, 80, 140]) and all(v == 6.0 for _t, v in c1)) +check(f"T1: one CHARGER_REFUSED at the 3rd try ({warns(x1, REF_M)}); " + f"gave_up {w1.gave_up}, attempted {w1.attempted_a}, prior {w1.prior_a}; " + f"log {w1.log}", + len(warns(x1, REF_M)) == 1 and abs(nth(warns(x1, REF_M), 0) - 140) <= 1 + and w1.gave_up is True and w1.attempted_a == 6.0 and w1.prior_a == 10.0 + and [(k, a, ok) for k, a, _t, ok in w1.log] == [("current", 6.0, False)] * 3) +never("T1 [X]", x1) +rc3 = recs(x1) +check(f"T3: exactly one record with a traceback, at the first try " + f"({rc3}); none on the retries; 1 CHARGER_REFUSED; no 'Car: set' " + f"({sets_(x1)})", + len(rc3) == 1 and abs(nth(rc3, 0)[0] - 20) <= 1 + and nth(rc3, 0)[1] is True and len(warns(x1, REF_M)) == 1 + and not sets_(x1)) + +r2 = xrun(manual(700, stub=Stub("X"), + events={400: act("car_current", 8)})) +a2, b2 = calls(r2, 0, 400), calls(r2, 400, 700) +check(f"T2: no write every cycle: 0-400 s {ts(a2)} (<= 3, >= 60 s apart), " + f"8 A at 400+-1 then {ts(b2)} (<= 3, >= 60 s apart)", + 0 < len(a2) <= 3 and all(g >= 59 for g in gaps(ts(a2))) + and 0 < len(b2) <= 3 and all(g >= 59 for g in gaps(ts(b2))) + and abs(nth(ts(b2), 0) - 400) <= 1 and nth(b2, 0)[1] == 8.0) +never("T2", r2) + +for name, exc in (("RuntimeError", lambda: RuntimeError("x")), + ("ChargerNotBound", lambda: CH.ChargerNotBound("x")), + ("hass.ReadOnly", lambda: hass.ReadOnly("x")), + ("ValueError", lambda: ValueError("x")), + ("TimeoutError", lambda: TimeoutError("x"))): + r22 = xrun(manual(300, stub=Stub("X", exc=exc))) + check(f"T22 [{name}]: 3 tries ({ts(calls(r22))}), 1 CHARGER_REFUSED " + f"({len(warns(r22, REF_M))}), 1 record ({len(recs(r22))})", + near_seq(ts(calls(r22)), [20, 80, 140]) + and len(warns(r22, REF_M)) == 1 and len(recs(r22)) == 1) + + +# Writer level, the failure-mode row: a read-back of None (allowed_a and +# setpoint_a unknown) is still a not-taken try, X as R. +def t1_none(kind): + w, trk, run = CM.ManualWriter(), Trk(), Runner() + drv = Drv(10.0, lambda a, n: "raise" if kind == "X" else False) + for t in range(300): + run.run(lambda t=t: mstep(w, drv, t, trk, r=Rd(None, 1, power=1380.0))) + return w, drv, run + + +(wR, dR, _uR), (wX, dX, uX) = t1_none("R"), t1_none("X") +check(f"T1 (read-back None): X tries {dX.calls} as R {dR.calls}; fails " + f"{wX.fails}, gave_up {wX.gave_up}; 1 record ({len(uX.recs())})", + dX.calls == dR.calls == [(0.0, 6.0), (60.0, 6.0), (120.0, 6.0)] + and wX.fails == wR.fails == 3 and wX.gave_up and len(uX.recs()) == 1) + +# =========================================================================== # +print("\n2. MANUAL: THE PHASE SEQUENCE AND THE UNDO (T4-T6)") +# =========================================================================== # +R4 = {k: mphase(400, stub=Stub(k, when=zero_after(50)), rows=True) + for k in "RX"} +x4 = xrun(R4["X"]) +eq4 = writer_eq(R4["R"], x4, "m") +c4 = calls(x4) +w4 = x4["c"].car_writer +seqs4 = [x[1]["seq"] for x in x4["rows"]] +zs4 = [x[1]["zero_sent_at"] for x in x4["rows"]] +check(f"T4: the 0 A raises (_begin): writer equal to R ({eq4[:1]})", not eq4) +check(f"T4: no select ever ({S.writes(x4, 'phases')}); 0 A tries {c4} " + f"(<= 3, >= 60 s apart); CHARGER_REFUSED ({warns(x4, REF_M)}); seq None " + f"every cycle, last_switch {w4.last_switch}, zero_sent_at None after " + f"each try; the car stays at 6 A ({x4['sim'].setpoint_a}); 1 record " + f"({len(recs(x4))})", + not S.writes(x4, "phases") and 0 < len(c4) <= 3 + and all(v == 0.0 for _t, v in c4) and all(g >= 60 for g in gaps(ts(c4))) + and len(warns(x4, REF_M)) == 1 and all(s is None for s in seqs4) + and w4.last_switch is None and all(z is None for z in zs4) + and x4["sim"].setpoint_a == 6.0 and len(recs(x4)) == 1) +never("T4", x4) + +R5 = {k: mphase(300, stub=Stub(k, when=nz_after(100)), rows=True) + for k in "RX"} +x5 = xrun(R5["X"]) +eq5 = writer_eq(R5["R"], x5, "m") +sel5 = S.writes(x5, "phases") +t_sel = nth(sel5, 0)[0] +c5 = calls(x5, 100, 200) +t_end = nth(c5, 2)[0] +end5 = row_at(x5, t_end) +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]})", + 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 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 + 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) + del gold + +def shadow_on(p, c): + c.o["shadow_mode"] = "on" + + +for variant, how in (("Off", act("car_mode", "off")), ("shadow", shadow_on)): + R6 = {k: mphase(250, stub=Stub(k, when=nz_after(100)), rows=True, + events={101: freeze, 105: how}) for k in "RX"} + x6 = xrun(R6["X"]) + eq6 = writer_eq(R6["R"], x6, "m") + w6 = x6["c"].car_writer + rest6 = [(t, a, ok) for k_, a, t, ok in w6.log if a > 0.0] + check(f"T6 [{variant}]: the undo raises (_undo): writer equal to R " + f"({eq6[:1]}); 1 restore try ({calls(x6)}), undone {w6.undone}, " + f"attempted {w6.attempted_a}, 1 log row ({rest6}); no retry in " + f"120 s; 1 record ({len(recs(x6))})", + not eq6 and ts(calls(x6)) == [105.0] and w6.undone == 1 + and w6.attempted_a == 6.0 and len(rest6) == 1 + and len(recs(x6)) == 1) + +# =========================================================================== # +print("\n3. SHUTDOWN (T7, T15, T15d, T16b, T29, T7c)") +# =========================================================================== # +FIN = [] # the finales of T7a, T15a/b, T15d, T29 (T7c) + + +def shut(stub=None, install=False): + """A finale: (`install`: the stub), then `car_shutdown()`. `p.fin`: the + log records it made, the model seconds it took, an exception out of + it, and the stub's calls during it.""" + async def f(p, c): + if install and stub is not None: + stub(p, c) + k0 = len(stub.calls) if stub is not None else 0 + n0, t0, err = LOG.mark(), p.clock[0], None + st0 = (c.car_solar.fails, getattr(c.car_solar, "cut_fails", None)) + try: + await c.car_shutdown() + except BaseException as e: # noqa: BLE001 + err = e + p.fin = dict(lines=LOG.rec[n0:], dt=p.clock[0] - t0, err=err, t0=t0, + calls=(stub.calls[k0:] if stub is not None else []), + st0=st0, st1=(c.car_solar.fails, + getattr(c.car_solar, "cut_fails", None)), + released=getattr(c.car_solar, "released", None)) + return f + + +def fin_recs(fin): + return [m for lv, m, _x in fin["lines"] if lv == "ERROR"] + + +def fin_warns(fin, text=""): + return [m for lv, m, _x in fin["lines"] if lv == "WARNING" and text in m] + + +for k in "XR": + st7 = Stub(k, when=nz_after(100)) + r7 = mphase(107, stub=st7, events={101: freeze}, finale=shut(st7)) + f7 = r7["plant"].fin + if k == "X": + FIN.append(("T7a", f7)) + check(f"T7a: Manual's give-back raises at shutdown: exactly 1 try " + f"({f7['calls']}), done in {f7['dt']} s (<= delay + 1), no " + f"exception ({f7['err']!r}), CHARGER_RESTORE once " + f"({len(fin_warns(f7, RESTORE))}), no 'Car: set'", + len(f7["calls"]) == 1 and f7["dt"] <= 2.0 and f7["err"] is None + and len(fin_warns(f7, RESTORE)) == 1 + and not [m for _l, m, _x in f7["lines"] if m.startswith(SETP)]) + else: + check(f"T7b: a refused give-back: 1 try ({f7['calls']}), no " + f"CHARGER_RESTORE ({fin_warns(f7)}), as base", + len(f7["calls"]) == 1 and not fin_warns(f7, RESTORE)) + +# T29a: the close raises at t; the shutdown comes 2 s later. +st29 = Stub("X", when=nz_after(100)) +r29 = mphase(113, stub=st29, finale=shut(st29)) +f29 = r29["plant"].fin +check(f"T29a: a close raised at 111, car_shutdown at {f29['t0']}: the " + f"give-back at once ({f29['calls']}), 1 try, CHARGER_RESTORE once, no " + f"wait ({f29['dt']} s)", + len(f29["calls"]) == 1 and nth(f29["calls"], 0)[0] <= 114 + and len(fin_warns(f29, RESTORE)) == 1 and f29["dt"] <= 2.0 + and f29["err"] is None) +FIN.append(("T29a", f29)) + +# Solar at 10 A (no cut), then the add-on stops. +for tag, stub in (("a", Stub("X")), ("b", Stub("X", n_bad=1)), + ("c", Stub("R"))): + r15 = solar(300, finale=shut(stub, install=True)) + f15 = r15["plant"].fin + c15 = f15["calls"] + if tag in "ab": + FIN.append((f"T15{tag}", f15)) + # `released` stays None: the raise leaves `release` before it is set, + # as on the base (H1); car_shutdown takes it as not released. + check(f"T15{tag}: Solar's shutdown 0 A raises (no cut): exactly 1 try " + f"({c15}), not released ({f15['released']}), CHARGER_RELEASE " + f"once ({len(fin_warns(f15, RELEASE))}), done in {f15['dt']} s, " + f"no exception ({f15['err']!r})", + len(c15) == 1 and f15["released"] is not True + and len(fin_warns(f15, RELEASE)) == 1 and f15["dt"] <= 2.0 + and f15["err"] is None) + else: + rel = [t - f15["t0"] for t, _a in c15] + check(f"T15c: a refused shutdown 0 A: 3 tries at about 0, 5, 10 s " + f"({rel}), as base", + near_seq(rel, [0, 5, 10])) + +# T15d: a cut stands (Shape C: the cut due at 960, refused), shutdown at 980. +for k in "XR": + st = Stub(k) + r = K.run(dur=981, events=K.window({}, 959, None), + finale=shut(st, install=True)) + f = r["plant"].fin + rel = [t - f["t0"] for t, _a in f["calls"]] + dbg = [m for lv, m, _x in f["lines"] if lv == "DEBUG" and CUTDBG in m] + d_f = None if None in f["st0"] + f["st1"] else ( + f["st1"][0] - f["st0"][0], f["st1"][1] - f["st0"][1]) + v15 = (rel, [a for _t, a in f["calls"]], f["released"], d_f) + golden(f"T15d [{k}]", v15) + gold = GOLDEN.get(f"T15d [{k}]") + check(f"T15d [{k}]: a cut stands: as base (3 tries of 0 A at about 0, 5, " + f"10 s {rel}, released {f['released']}, fails and cut_fails +1 per " + f"try {d_f}); CHARGER_RELEASE once; " + + (f"one DEBUG cut line per try ({len(dbg)}); " if k == "X" else "") + + f"no record ({fin_recs(f)}); 344c974 {gold}", + gold is not None and v15[1:] == tuple(gold[1:]) + and near_seq(rel, gold[0], 0.01) + and near_seq(rel, [0, 5, 10]) and [a for _t, a in f["calls"]] + == [0.0] * 3 and f["released"] is False and d_f == (3, 3) + and len(fin_warns(f, RELEASE)) == 1 and not fin_recs(f) + and (k == "R" or len(dbg) == 3)) + if k == "X": + FIN.append(("T15d", f)) + +# T29b: Solar's 8 A step-down raised 3 times (gave_up), then the add-on stops. +st29b = Stub("X", when=after(1000)) +r29b = solar(1122, stub=st29b, finale=shut(st29b)) +f29b = r29b["plant"].fin +check(f"T29b: Solar gave up 1 s ago ({r29b['c'].car_solar.fail_at}); the " + f"shutdown 0 A at once ({f29b['calls']}), 1 try, CHARGER_RELEASE once, " + f"no wait ({f29b['dt']} s)", + len(f29b["calls"]) == 1 and nth(f29b["calls"], 0)[1] == 0.0 + and len(fin_warns(f29b, RELEASE)) == 1 and f29b["dt"] <= 2.0) +FIN.append(("T29b", f29b)) + +def _sd_warns(f): + """The shutdown's warnings but base's own peak-cut notice (T15d: the + 3rd refused cut try is made by the release, as on the base).""" + return [m for m in fin_warns(f) if Q3 not in m] + + +bad7c = [(n, fin_recs(f), fin_warns(f)) for n, f in FIN + if fin_recs(f) or len(_sd_warns(f)) != 1 + or not (RESTORE in nth(_sd_warns(f), 0) + or RELEASE in nth(_sd_warns(f), 0))] +check(f"T7c (G3): no step-failed record at shutdown, only CHARGER_RESTORE or " + f"CHARGER_RELEASE, once ({len(FIN)} shutdowns; {bad7c[:2]})", + not bad7c and len(FIN) == 6) + +# T16b: the shutdown write hangs past RELEASE_WAIT_S (scaled: 0.3 s real). +st16 = Stub("X", hang=1.0, delay=0.0) +_wait = ctl_car.RELEASE_WAIT_S +ctl_car.RELEASE_WAIT_S = 0.3 + + +def _timed(stub): + inner = shut(stub, install=True) + + async def f(p, c): + t0 = time.monotonic() + await inner(p, c) + p.fin["real"] = time.monotonic() - t0 + return f + + +try: + r16 = solar(300, finale=_timed(st16)) +finally: + ctl_car.RELEASE_WAIT_S = _wait +f16 = r16["plant"].fin +check(f"T16b: a hanging shutdown write: car_shutdown back by the wait + 0.5 s " + f"({f16.get('real')}), not released ({f16['released']}), " + f"CHARGER_RELEASE once, no further try ({f16['calls']})", + f16.get("real", BIG) <= 0.8 and f16["released"] is not True + and len(fin_warns(f16, RELEASE)) == 1 and len(f16["calls"]) == 1) + +# =========================================================================== # +print("\n4. SOLAR (T8-T14)") +# =========================================================================== # +R8 = {k: solar(1700, stub=Stub(k, when=after(1000)), rows=True) for k in "RX"} +x8 = xrun(R8["X"]) +eq8 = writer_eq(R8["R"], x8, "s") +c8 = calls(x8) +s8 = x8["c"].car_solar +check(f"T8: Solar's 8 A step-down raises: writer equal to R ({eq8[:1]})", + not eq8) +check(f"T8: 8 A tries {c8} at 1000, +60, +120; one CHARGER_REFUSED " + f"({warns(x8, REF_S)}); gave_up {s8.gave_up}, sent {s8.sent_a}, taken " + f"{s8.taken}; no 4th try to 1700", + near_seq(ts(c8), [1000, 1060, 1120]) and all(v == 8.0 for _t, v in c8) + and len(warns(x8, REF_S)) == 1 and s8.gave_up is True + and s8.sent_a == 8.0 and s8.taken is False) +never("T8", x8) + +# The charger shows its own 10 A at the start, so D2's 0 A goes out first. +r9 = xrun(solar(600, stub=Stub("X"), sun=const(7900.0), setpoint=10)) +c9 = calls(r9) +by9 = {} +for t, v in c9: + by9.setdefault(v, []).append(t) +nz9 = [x for x in r9["sim"].log if x[1] == "current" and x[2] > 0.0] +check(f"T9: every write raises from the start: {by9} (<= 3 per value, >= 60 " + f"s apart); no non-zero write while the 0 A is not taken ({nz9[:2]})", + bool(c9) and all(len(v) <= 3 and all(g >= 60 for g in gaps(v)) + for v in by9.values()) + and not nz9 and all(v == 0.0 for _t, v in c9)) +never("T9", r9) +check(f"T10: Solar records: T8 exactly 1 at 1000+-1 ({recs(x8)}), T9 exactly " + f"1 at the start-up 0 A ({recs(r9)}, first try {c9[:1]}); 1 " + f"CHARGER_REFUSED each; no 'Car: set' after the first raise", + len(recs(x8)) == 1 and abs(nth(recs(x8), 0)[0] - 1000) <= 1 + and len(recs(r9)) == 1 + and abs(nth(recs(r9), 0)[0] - nth(ts(c9), 0)) <= 1 + and len(warns(x8, REF_S)) == 1 and len(warns(r9, REF_S)) == 1 + and not sets_(x8, 1000) and not sets_(r9)) + +AUTO = dict(opts={"ev_phases": "auto"}, phases=1, car_phases=3) +R11 = {k: solar(900, stub=Stub(k, when=zero_after(60)), sun=const(6500.0), + rows=True, **AUTO) for k in "RX"} +x11 = xrun(R11["X"]) +eq11 = writer_eq(R11["R"], x11, "s") +c11 = calls(x11) +p11 = [row_at(x11, t) for t in ts(c11)] +check(f"T11: the phase change's 0 A raises (_begin_solar): writer equal to R " + f"({eq11[:1]})", not eq11) +# The plan's next change comes after its own dwell (UP_S), each one after +# Solar adopted its old current again (a new episode, as R and base: T20). +check(f"T11: 0 A tries {ts(c11)} (>= 60 s apart, 1 per change); in each " + f"try's step the plan ends the change " + f"({[x and x[2]['plan'] for x in p11]}); fails after each try <= 3; no " + f"select ({S.writes(x11, 'phases')})", + bool(c11) and all(g >= 60 for g in gaps(ts(c11))) + and all(x is not None and x[2]["plan"][1] == 1 + and x[2]["plan"][2] is False and x[2]["fails"] <= 3 + for x in p11) + and not S.writes(x11, "phases")) +never("T11", x11) + + +def on3(p, a): + return float(a) > CM.TOL_A and p.ch.phases_allowed == 3 + + +R12 = {k: solar(900, stub=Stub(k, when=on3), sun=const(6500.0), rows=True, + **AUTO) for k in "RX"} +x12 = xrun(R12["X"]) +eq12 = writer_eq(R12["R"], x12, "s") +c12 = calls(x12) +sel12 = S.writes(x12, "phases") +t12 = nth(c12, 2)[0] +e12 = row_at(x12, t12) +check(f"T12: the change's close raises: writer equal to R ({eq12[:1]})", + not eq12) +check(f"T12: 3 close tries 5 s apart ({ts(c12)[:3]}); then seq None, the " + f"change ended ({e12 and e12[2]['plan']}), fails 4 as with R " + f"({e12 and e12[2]['fails']}); the car at 0 A; one select only " + f"({sel12})", + len(c12) >= 3 and gaps(ts(c12)[:3]) == [5.0, 5.0] + and e12 is not None and e12[2]["seq"] is None + and e12[2]["fails"] == 4 and e12[2]["plan"][2] is False + and x12["sim"].setpoint_a == 0.0 and len(sel12) == 1) +never("T12", x12, close_ok=True) + +for variant, how in (("Off", act("car_mode", "off")), + ("unplugged", lambda p, c: p.ch.unplug()), + ("error E", lambda p, c: p.ch.fault("E"))): + R13 = {k: solar(800, stub=Stub(k, when=zero_after(500)), rows=True, + sun=const(7900.0), events={500: how}) for k in "RX"} + x13 = xrun(R13["X"]) + eq13 = writer_eq(R13["R"], x13, "s") + c13 = calls(x13) + s13 = x13["c"].car_solar + check(f"T13 [{variant}]: the way-out 0 A raises: writer equal to R " + f"({eq13[:1]}); tries {ts(c13)} (<= 3, >= 60 s apart), then gave_up " + f"({s13.gave_up}), live {s13.live}; no Manual write " + f"({x13['c'].car_writer.log[:1]})", + not eq13 and 0 < len(c13) <= 3 and all(g >= 60 for g in gaps(ts(c13))) + and s13.gave_up is True and s13.live is True + and not x13["c"].car_writer.log) + + +# T14, writer level: the 0 A on a held read and a silent meter (held_pause), +# and a phase change under way ended by `nz_block`. +def t14(kind, seq=False): + w, trk, run = solar_writer(10.0), Trk(), Runner() + drv = Drv(10.0, lambda a, n: "raise" if kind == "X" else False, ph=3) + sun = CM.SunInputs(target_w=6900.0, silent=True, unknown_s=400.0, + pause_s=300.0) + if seq: + w.sent_a, w.taken = 0.0, False + w.seq = {"stage": "zero", "t0": 0.0, "n": 3, "tries": 0, + "prev": None, "from": 1} + for t in range(1, 50 if seq else 120): + drv.now = float(t) + if seq: + run.run(lambda t=t: sstep(w, drv, t, trk, sun=sun)) + else: + run.run(lambda t=t: w.held_pause(drv, Rd(drv.cur, 3, 6900.0), + sun=sun, now=float(t), + tracker=trk)) + return w, drv, run + + +for seq in (False, True): + (wR, dR, _u), (wX, dX, uX) = t14("R", seq), t14("X", seq) + tag = "a phase change under way" if seq else "held_pause" + check(f"T14 [{tag}]: 1 try ({dX.calls}) as R ({dR.calls}); fails " + f"{wX.fails} (1); no non-zero write; seq {wX.seq}", + dX.calls == dR.calls and len(dX.calls) == 1 + and nth(dX.calls, 0)[1] == 0.0 and wX.fails == wR.fails == 1 + and wX.seq is None) + +# =========================================================================== # +print("\n5. EV-52: THE LINES (T17, T18)") +# =========================================================================== # +r17 = xrun(manual(200, stub=Stub("X", take=True))) +s17 = sets_(r17) +check(f"T17 [Manual]: the charger took 6 A, then the call raised: no 2nd " + f"write ({calls(r17)}); exactly one line at the adopting cycle ({s17})", + ts(calls(r17)) == [20.0] and [m for _t, m in s17] + == ["Car: set from 10 A to 6 A on 1 phase (Manual)."] + and 21 <= nth(s17, 0)[0] <= 23) +r17s = xrun(solar(1300, stub=Stub("X", take=True, when=after(1000)))) +s17s = sets_(r17s, 1000) +check(f"T17 [Solar]: 8 A taken, the call raised, adopted: no 2nd write " + f"({calls(r17s)}); exactly one line ({s17s})", + ts(calls(r17s)) == [1000.0] and [m for _t, m in s17s] + == ["Car: set from 10 A to 8 A on 3 phases (Solar)."] + and 1001 <= nth(s17s, 0)[0] <= 1003) + +# =========================================================================== # +print("\n6. EV-54: THE PEAK CUT (T19, T19b)") +# =========================================================================== # +st19 = Stub("X") +r19 = K.run(dur=1950, events={959: st19, 1830: stop_stub(st19)}) +c19 = [(t, a) for t, a in st19.calls if 900 <= t < 1800] +bad19 = [] +for t, a in c19: + x0, x1_ = K.row(r19, t - 1), K.row(r19, t) + rows19 = [x for x in r19["c"].car_solar.log + if x[0] == "current" and x[2] == t] + if not (present(x0, x1_) and x1_["fails"] - x0["fails"] == 1 + and x1_["cut_fails"] - x0["cut_fails"] == 1 + and rows19 == [("current", 0.0, t, False)]): + bad19.append((t, present(x0) and x0["fails"], + present(x1_) and x1_["fails"], rows19)) +w19 = r19["w"] +dbg19 = [t for t, lv, m in w19.lines(CUTDBG) if lv == "DEBUG" + and 900 <= t < 1800] +rec19 = [t for t, lv, m in w19.lines(REC)] +tb19 = [m for _lv, m, x in LOG.rec[w19.mark0:] if x] +check(f"T19: a raising cut try: 3 tries in 900-1800 ({ts(c19)}); per raise " + f"fails +1, cut_fails +1, one log row ({bad19[:2]}); one DEBUG cut line " + f"each ({dbg19}); no record ({rec19}), no Traceback ({len(tb19)})", + len(c19) == 3 and all(a == 0.0 for _t, a in c19) and not bad19 + and len(dbg19) == 3 and not rec19 and not tb19) +check(f"T19: the cut's CHARGER_REFUSED once ({len(w19.lines(Q3))}); 'until " + f"you press Solar' never ({w19.lines(REF_S)})", + len(w19.lines(Q3)) == 1 and not w19.lines(REF_S)) + + +# T19b (H4, formal C4), writer level: the two routes past the cut cap. Head +# R equals head X equals base (formal replay c4c / c4b on 344c974). +def c4c(kind): + tries = [] + bad = "raise" if kind == "X" else False + + def answer(a, n): + cut = w.cut_a + if cut is not None and a <= cut + CM.TOL_A: + tries.append(int(drv.now)) + return bad + drv = Drv(8.0, answer) + w, trk, run = solar_writer(8.0), Trk(), Runner() + w.cut_a, w.cut_on = 0.0, True + w.plan.a = 0.0 + for t in range(0, 121): + run.run(lambda t=t: sstep(w, drv, t, trk)) + w.cut_a, w.cut_on = None, False + w.plan.a = 8.0 + run.run(lambda: sstep(w, drv, 121, trk)) # the drop: 8 A adopted + w.plan._set(8.0, 121.0, 3) # the plan: 1 -> 3 + w.cut_a, w.cut_on = 6.0, True # a 6 A cap again + for t in range(122, 200): + run.run(lambda t=t: sstep(w, drv, t, trk)) + return tries, w.cut_fails, run + + +def c4b(kind): + tries = [] + ph = {"all": True} + bad = "raise" if kind == "X" else False + + def answer(a, n): + cut = w.cut_a + r = bad if ph["all"] else (True if a == 0.0 and cut is None else bad) + if cut is not None and a <= cut + CM.TOL_A and r is not True: + tries.append(int(drv.now)) + return r + drv = Drv(8.0, answer) + w, trk, run = solar_writer(8.0), Trk(), Runner() + w.cut_a, w.cut_on = 0.0, True + w.plan.a = 0.0 + t = 0 + while t < 180: + run.run(lambda t=t: sstep(w, drv, t, trk)) + t += 1 + w.cut_a, w.cut_on = None, False + ph["all"] = False + w.plan.a = 8.0 + run.run(lambda t=t: sstep(w, drv, t, trk)) + w.plan._set(8.0, float(t), 3) + for t in range(181, 250): + run.run(lambda t=t: sstep(w, drv, t, trk)) + if w.seq is not None and w.seq.get("stage") == "settle" \ + and w.cut_a is None: + w.cut_a, w.cut_on = 6.0, True + return tries, w.cut_fails, run + + +for route, fn, want, cf in (("a", c4c, [0, 60, 120, 180], 4), + ("b", c4b, [0, 60, 120, 192, 197, 202], 7)): + res = {k: fn(k) for k in "RX"} + check(f"T19b [{route}] (H4, not worse than base): refused cut tries per " + f"key R {res['R'][0]} cut_fails {res['R'][1]}, X {res['X'][0]} " + f"cut_fails {res['X'][1]} = base {want} / {cf}; no record", + res["R"][0] == res["X"][0] == want + and res["R"][1] == res["X"][1] == cf + and not res["X"][2].recs() and not res["R"][2].recs()) + +# =========================================================================== # +print("\n7. THE TRACKER, TIMING, RESTART, NO CHARGER, A RESET (T21, T23, " + "T25-T27)") +# =========================================================================== # +for d in (0.0, 12.0): + rm = {k: manual(300, stub=Stub(k, delay=d), rows=True) for k in "RX"} + rs = {k: solar(1400, stub=Stub(k, delay=d, when=after(1000)), rows=True) + for k in "RX"} + for tag, rr, which in (("Manual", rm, "m"), ("Solar", rs, "s")): + xrun(rr["X"]) + cx = calls(rr["X"]) + e = writer_eq(rr["R"], rr["X"], which) + check(f"T21 [{tag}, the raise after {d} s]: tries {ts(cx)} (3, >= 60 " + f"s apart from the try's cycle); writer equal to R ({e[:1]})", + len(cx) == 3 and all(g >= 60 for g in gaps(ts(cx))) and not e) + + +def ramp0(p, c): + p.ch.ramp_w_s = 0.0 # a dead car: 0 W, the energy flat + + +for tag, ev in (("dead car", {0: ramp0}), ("live car", {})): + ev = merge(dict(ev), 15, act("car_current", 16)) + r23 = xrun(manual(300, stub=Stub("X"), events=ev, rows=True)) + c23 = calls(r23) + bad = [x[0] for x in r23["rows"] if x[3]["pend"] or x[3]["armed"]] + mute = [(t, row_at(r23, t)) for t, _a in c23] + badm = [t for t, x in mute if x is None or abs( + x[3]["mute"] - (x[3]["done_m"] + CH.OWN_WRITE_MUTE_S)) > 1e-6] + stuck = [x["t"] for x in r23["trace"] + if "charger_stuck" in (x["amber"] or []) + (x["red"] or [])] + check(f"T23 [Manual, {tag}]: 10 -> 16 A raises {ts(c23)}: the tracker is " + f"not told: no window, never armed ({bad[:2]}); mute = the try's " + f"return + {CH.OWN_WRITE_MUTE_S} s ({badm[:2]}); no charger_stuck " + f"({stuck[:1]}); the writer counts 3 tries", + len(c23) == 3 and not bad and not badm and not stuck + and r23["c"].car_writer.fails == 3) +r23s = xrun(solar(1400, stub=Stub("X", when=after(1000)), events={0: ramp0}, + rows=True)) +bad = [x[0] for x in r23s["rows"] if x[0] >= 1000 + and (x[3]["pend"] or x[3]["armed"])] +check(f"T23 [Solar, dead car]: no window, never armed after the raises " + f"({bad[:2]}); the writer counts {r23s['c'].car_solar.fails} tries", + not bad and len(calls(r23s)) == 3 and r23s["c"].car_solar.fails == 3) + +r25a = xrun(manual(90, stub=Stub("X"))) +keys = sorted(r25a["store"].data) +keys_r = sorted(manual(90, stub=Stub("R"))["store"].data) +r25 = xrun(go("manual", 300, stub=Stub("X"), store=r25a["store"], + setpoint=10, phases=1, car_phases=1, opts={"ev_phases": "1"})) +c25 = calls(r25) +check(f"T25: a restart after 2 raised tries ({ts(calls(r25a))}): fresh " + f"counts, the start-up write at once and spaced as T1 ({ts(c25)}), " + f"CHARGER_REFUSED only after 3 new tries ({warns(r25, REF_M)}), 1 new " + f"record ({len(recs(r25))}); no store key for the count (the keys " + f"are the refusing twin's: {keys == keys_r})", + len(calls(r25a)) == 2 and len(c25) == 3 and nth(ts(c25), 0) <= 2 + and all(g >= 60 for g in gaps(ts(c25))) + and len(warns(r25, REF_M)) == 1 + and abs(nth(warns(r25, REF_M), 0) - nth(ts(c25), 2)) <= 1 + and len(recs(r25)) == 1 + and keys == keys_r) + +for mode in ("manual", "solar"): + st = Stub("X") + r26 = go(mode, 300, stub=st, sun=7900.0, + opts={"ev_charger": "off"}, setpoint=10) + car = [m for _t, lv, m, _x in r26["lines"] + if m.startswith("Car") or "CHARGER_" in m] + check(f"T26 [{mode}]: no charger: 0 calls ({st.calls}), 0 car lines, no " + f"warnings ({car[:2]})", not st.calls and not car) + +for k in "RX": + r27 = manual(500, stub=Stub(k), events={300: act("car_current", 8)}) + if k == "X": + xrun(r27) + c27 = calls(r27, 300) + check(f"T27 [Manual]: after the give-up the user sets 8 A: a write at " + f"once and 3 fresh tries ({c27}), as R ({calls(m27, 300)})", + near_seq(ts(c27), [300, 360, 420]) and c27 == calls(m27, 300)) + m27 = r27 +for k in "RX": + r27s = solar(1600, stub=Stub(k, when=after(1000)), + events={1300: act("car_mode", "solar")}) + if k == "X": + xrun(r27s) + c27 = calls(r27s, 1300) + check(f"T27 [Solar]: after the give-up the user presses Solar: a write " + f"at once and 3 fresh tries ({c27}), as R " + f"({calls(m27s, 1300)})", + near_seq(ts(c27), [1300, 1360, 1420]) + and c27 == calls(m27s, 1300)) + m27s = r27s + +# =========================================================================== # +print("\n8. ONE RECORD PER RAISED VALUE (T28, T28b)") +# =========================================================================== # +r28 = xrun(manual(500, stub=Stub("X"), events={300: act("car_current", 8)})) +check(f"T28 [Manual]: 6 A raises 3 times, then 8 A: exactly 2 records " + f"({recs(r28)}) at 20 and 300", + near_seq([t for t, _x in recs(r28)], [20, 300])) +r28s = xrun(solar(1300, stub=Stub("X", when=after(1000)), + sun=sun8(more=((1030, 6000.0),)))) +c28s = calls(r28s) +check(f"T28 [Solar]: 8 A raises at 1000, the plan's 7 A at 1060 raises: " + f"tries {c28s}; exactly 2 records ({recs(r28s)})", + nth(c28s, 0) == (1000.0, 8.0) + and (1060.0, 7.0) in c28s + and near_seq([t for t, _x in recs(r28s)], [1000, 1060])) + + +def away(t0, t1): + def gone(p, c): + p.ch.go_unavailable(True) + + def back(p, c): + p.ch.go_unavailable(False) + return {t0: gone, t1: back} + + +r28bs = xrun(solar(400, stub=Stub("X"), sun=const(7900.0), setpoint=10, + events=away(70, 101))) +c28bs = calls(r28bs) +check(f"T28b (i) [Solar]: 0 A raises at {ts(c28bs)[:2]}, away 70-100, back " + f"at 101 and the same 0 A raises at once: 2 records ({recs(r28bs)})", + near_seq(ts(c28bs)[:3], [nth(ts(c28bs), 0), nth(ts(c28bs), 0) + 60, + 101], 1) + and len(recs(r28bs)) == 2 + and abs(nth(recs(r28bs), 1)[0] - 101) <= 1) +r28bm = xrun(manual(200, stub=Stub("X"), events=away(30, 61))) +c28bm = calls(r28bm) +check(f"T28b (i) [Manual]: 6 A raises at 20, away 30-60, 6 A again at 80 " + f"({ts(c28bm)}): 2 records ({recs(r28bm)})", + ts(c28bm)[:2] == [20.0, 80.0] + and near_seq([t for t, _x in recs(r28bm)], [20, 80])) + + +def t28b_ii(answers): + w, trk, run = CM.ManualWriter(), Trk(), Runner() + it = iter(answers) + drv = Drv(10.0, lambda a, n: next(it, False)) + for i in range(len(answers)): + run.run(lambda i=i: w._write(drv, 6.0, 10.0, float(i), trk)) + return run + + +check(f"T28b (ii): raise, taken, raise of the same 6 A: 2 records " + f"({len(t28b_ii(['raise', True, 'raise']).recs())})", + len(t28b_ii(["raise", True, "raise"]).recs()) == 2) +r28b3 = xrun(manual(400, stub=Stub("X"), events={300: act("car_current", 6)})) +check(f"T28b (iii): 6 A raised 3 times, the user sets 6 A again at 300 and " + f"it raises: 2 records ({recs(r28b3)}), tries {ts(calls(r28b3))}", + near_seq([t for t, _x in recs(r28b3)], [20, 300]) + and ts(calls(r28b3))[:4] == [20.0, 80.0, 140.0, 300.0]) +r28b4 = t28b_ii(["raise", "raise", "raise"]) +check(f"T28b (iv): no reset between raises: 1 record per value (writer level " + f"{len(r28b4.recs())}; T1 {len(recs(x1))}; T9 {len(recs(r9))})", + len(r28b4.recs()) == 1 and len(recs(x1)) == 1 and len(recs(r9)) == 1) + +# =========================================================================== # +print("\n9. CANCEL IS NOT A REFUSAL (T16a)") +# =========================================================================== # + + +class Hang(Drv): + async def write_current(self, a, **kw): + self.calls.append((self.now, float(a))) + await asyncio.Event().wait() + + +async def _t16(make_w, call): + w, trk = make_w(), Trk() + drv = Hang(10.0, None) + st0 = (w.fails, w.fail_at, len(w.log)) + task = asyncio.ensure_future(call(w, drv, trk)) + for _ in range(5): + await asyncio.sleep(0) + task.cancel() + res = await asyncio.gather(task, return_exceptions=True) + return w, trk, drv, st0, task, res + + +for tag, mk, call in ( + ("Manual", CM.ManualWriter, + lambda w, drv, trk: mstep(w, drv, 0, trk)), + ("Solar", lambda: solar_writer(10.0), + lambda w, drv, trk: w._write(drv, 8.0, 10.0, 0.0, trk))): + n0 = LOG.mark() + w, trk, drv, st0, task, res = asyncio.run(_t16(mk, call)) + bad = [m for lv, m, _x in LOG.rec[n0:] if lv in ("ERROR", "WARNING")] + check(f"T16a [{tag}]: cancelled while the write waits: CancelledError " + f"out ({res}), the task cancelled; fails, fail_at and log unchanged " + f"({st0} -> {(w.fails, w.fail_at, len(w.log))}); no warning or " + f"record ({bad}); end_write ran ({trk.ends})", + task.cancelled() and isinstance(nth(res, 0), asyncio.CancelledError) + and (w.fails, w.fail_at, len(w.log)) == st0 and not bad + and len(trk.ends) == 1 and len(drv.calls) == 1) + +# =========================================================================== # +print("\n10. A DRIVER THAT ANSWERS OR REFUSES: AS BASE (T18, T20)") +# =========================================================================== # +bad18 = [] +for r in X_RUNS: + raised = {int(t) for t, _a in r["stub"].calls} + bad18 += [(t, m) for t, m in sets_(r) if t is not None and int(t) in raised + and not r["stub"].take] +check(f"T18: no 'Car: set' line for a raised try in {len(X_RUNS)} X runs " + f"({bad18[:2]})", not bad18 and len(X_RUNS) >= 20) + + +def view(r): + """What T20 pins: the stub's calls, the charger's log, every cycle's + writer and tracker state, the log lines at INFO and above, the + notifications.""" + rows = [(x[0], x[1], x[2], (x[3]["pend"], x[3]["armed"], x[3]["mute"])) + for x in r["rows"]] + return digest([r["stub"].calls, r["sim"].log, rows, + [(t, lv, m) for t, lv, m, _x in r["lines"] + if lv != "DEBUG"], r["raised"]]) + + +WORLDS = { + "T1": (None, lambda st: manual(300, stub=st)), + "T4": (zero_after(50), lambda st: mphase(400, stub=st)), + "T5": (nz_after(100), lambda st: mphase(300, stub=st)), + "T8": (after(1000), lambda st: solar(1700, stub=st)), + "T11": (zero_after(60), + lambda st: solar(900, stub=st, sun=const(6500.0), **AUTO)), + "T12": (on3, lambda st: solar(900, stub=st, sun=const(6500.0), **AUTO)), + "T13": (zero_after(500), + lambda st: solar(800, stub=st, sun=const(7900.0), + events={500: act("car_mode", "off")})), + "T15": (None, lambda st: solar(300, finale=shut(st, install=True))), + "T15d": (None, lambda st: K.run(dur=981, events=K.window({}, 959, None), + finale=shut(st, install=True))), +} +for wname, (when, mk) in WORLDS.items(): + for k in "AR": + st = Stub(k, when=when) + r = mk(st) + r["stub"] = st + if "rows" not in r: + r["rows"], r["lines"] = [], [(None, lv, m, x) for lv, m, x + in LOG.rec[r["w"].mark0:]] + v = view(r) + gold = golden(f"T20 {wname} [{k}]", v) + check(f"T20 {wname} [{k}]: as base ({v} vs 344c974 {gold})", + gold is not None and v == gold) + +report()