"""EV-20 rig round 1 (rig FAIL on cc8c0dc), with EV-32 and EV-36. `python3 -B test_ev20_rig.py` 1. The stuck check's arming race (Critical, EV-32): a write waits for its read-back while the next cycle reads the charger; the check must be armed on the reading taken before the send, so a car that then stays paused is not "stuck". Tracker rows and the real Controller in the rig's interleave (`beside`), the rig's repro scenario among them. 2. EV-36 (SPIKE-05 C4): a frozen value newer than the last read is not life. 3. No 1 A ping-pong on an amp boundary (Major). 4. The 6 A hold lasts its full `ev_pause_min` from the spare's drop, 1 and 3 phases (Major); a meter as Home Assistant publishes it (`ha_signed`, on a change only) does not pause the car while it is healthy (Minors). 5. SPIKE-06: the race as the formal replay plays it; C12 (a refusal on a paused car no longer holds Solar at 0 A); C13 (a capped car is not stuck). Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). """ import math import os import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "tools")) from datetime import datetime, timezone # noqa: E402 from app import carmode, chargers as CH # noqa: E402 import ev20_sun as S # noqa: E402 from chargersim import SimCharger # noqa: E402 from ev20_kit import (LOG, TSim, act, check, const, cur_writes, # noqa: E402 nevers, report, step_fn) from named_absence import nth, present # noqa: E402 UTC = datetime(2026, 11, 23, 12, 0, tzinfo=timezone.utc) DAY = "2026-11-23" TS = 1000.0 def rd(power=2300.0, allowed=10.0, e=4004.85, state="C"): return CH.ChargerReading( available=True, state=state, connected=True, charging=state in ("C", "D"), power_w=power, energy_kwh=e, current_a=(power / 230.0, 0.0, 0.0), setpoint_a=allowed, allowed_a=allowed, phases_allowed=1) # =========================================================================== # print("1. THE STUCK CHECK'S ARMING (rig Critical, EV-32)") # =========================================================================== # # The race as the rig had it: begin_write (the send), the cycle's read lands # while the write waits (it already shows the new 0 A and the paused car), # then note_write; the car stays paused (constant 0 W, 0 A) for two minutes. tr = CH.CarTracker() for i in range(-5, 1): tr.observe(rd(e=4004.85 + i / 1000.0), TS + i, UTC, DAY) tr.begin_write() tr.observe(rd(power=0.0, allowed=0.0, state="B"), TS + 1, UTC, DAY) tr.end_write(TS + 2) tr.note_write(TS, 10.0, 0.0, True) stuck_at = None for i in range(2, 130): tr.observe(rd(power=0.0, allowed=0.0, state="B"), TS + i, UTC, DAY) if stuck_at is None and tr.stuck(TS + i): stuck_at = i check(f"race (EV-32): an accepted 10 -> 0 A write whose post-write reading " f"arrived while it waited; the car then stays paused at constant " f"values: never 'stuck' (stuck at +{stuck_at})", stuck_at is None) # The same with an accepted non-zero write (EV-32's "after an accepted current # write"): a car that then draws steadily is not stuck either. tr = CH.CarTracker() for i in range(-5, 1): tr.observe(rd(power=0.0, allowed=0.0, state="B"), TS + i, UTC, DAY) tr.begin_write() tr.observe(rd(power=1840.0, allowed=8.0), TS + 1, UTC, DAY) tr.end_write(TS + 2) tr.note_write(TS, 0.0, 8.0, True) st2 = [i for i in range(2, 130) if (tr.observe(rd(power=1840.0, allowed=8.0), TS + i, UTC, DAY) or tr.stuck(TS + i))] check(f"race (EV-32): an accepted 0 -> 8 A write, the car draws a steady " f"1840 W: never 'stuck' ({st2[:1]})", not st2) # A reading that really froze before the send still is stuck at +60 s (the # EV-04 rule kept): the write was accepted, but every reading after it is the # one from before the send. tr = CH.CarTracker() for i in range(-5, 1): tr.observe(rd(), TS + i, UTC, DAY) tr.begin_write() tr.end_write(TS + 1) tr.note_write(TS, 10.0, 0.0, True) st3 = None for i in range(1, 80): tr.observe(rd(), TS + i, UTC, DAY) if st3 is None and tr.stuck(TS + i): st3 = i check(f"kept: readings frozen at the value from before the send are stuck at " f"+60 s (at +{st3})", st3 == 60) # =========================================================================== # print("\n2. EV-36: A FROZEN VALUE NEWER THAN THE LAST READ IS NOT LIFE") # =========================================================================== # # The cycle last read energy 4004.85 kWh at TS-1. The charger froze a moment # later at 4004.87 (a newer value); the refused write's polls and every later # read show that same frozen value. tr = CH.CarTracker() for i in range(-5, 0): tr.observe(rd(e=4004.85), TS + i, UTC, DAY) tr.begin_write() polls = [(TS + s, rd(e=4004.87)) for s in range(1, 11)] tr.end_write(TS + 10) tr.note_write(TS, 16.0, 10.0, False, polls) st36 = None for i in range(11, 130): tr.observe(rd(e=4004.87), TS + i, UTC, DAY) if st36 is None and tr.stuck(TS + i): st36 = i check(f"EV-36: a refused write; the first sample after the send carries a " f"newer value that then never moves: no life, so it arms at the send " f"and is stuck at +60 s (at +{st36})", st36 == 60) tr = CH.CarTracker() for i in range(-5, 0): tr.observe(rd(e=4004.85), TS + i, UTC, DAY) tr.begin_write() polls = [(TS + s, rd(e=4004.85 + s / 1000.0)) for s in range(1, 11)] tr.end_write(TS + 10) tr.note_write(TS, 16.0, 10.0, False, polls) for i in range(11, 130): tr.observe(rd(e=4004.86 + i / 1000.0), TS + i, UTC, DAY) check("EV-36 guard: a refused write on a charger whose energy keeps moving " "is not stuck (life in the second sample and after)", tr.armed_at is None and not tr.stuck(TS + 129)) # =========================================================================== # print("\n3. THE REAL CONTROLLER IN THE RIG'S INTERLEAVE (beside)") # =========================================================================== # def jit(f): """A few watts of noise on a plant figure, as the rig's plant had, so a meter published on change does change (every 7 s here).""" return lambda t: f(t) + (2.0 if int(t // 7) % 2 else -2.0) def rig_run(**kw): sim = kw.pop("sim", None) or SimCharger(setpoint_a=kw.pop("setpoint", 0)) sim.lag_s = 1.0 return S.drive(kw.pop("house"), kw.pop("sun"), beside=True, sim=sim, **kw) # The rig's repro, EV20-solar-steady-no-false-stuck: the charger's own 10 A, # the car charging; Solar, Car first, sun 7.9 kW, house 0.9 kW (mock-up # scenario 2): 0 A first (D2), then the start rule, then charging to the end. for mc in (False, True): tag = "meter on change" if mc else "meter every second" r = rig_run(house=jit(const(900.0)), sun=const(7900.0), dur=1800, first="car", socs={"a": 71.0, "b": 100.0}, sim=SimCharger(setpoint_a=10), meter_change=mc) w = cur_writes(r) stuck = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] check(f"scenario EV20-solar-steady-no-false-stuck [{tag}]: 0 A first, the " f"start within 125 s, charging to the end, never stuck ({w[:4]}, " f"stuck {stuck[:1]})", present(nth(w, 0)) and nth(w, 0)[1] == 0.0 and present(nth(w, 1)) and nth(w, 1)[1] > 0.0 and nth(w, 1)[0] - nth(w, 0)[0] <= 125 and not stuck and r["sim"].power_w > 3000.0) nevers(r, f"scenario EV20-solar-steady-no-false-stuck [{tag}]") # E2 of the scenario: a cloud pause (0 A), then the sun back: the car # restarts 120 s after the sun returns; no stuck verdict holds it at 0 A. r = rig_run(house=const(500.0), sun=step_fn((400, 900.0), (1000, 2900.0), base=2900.0), dur=1400, first="car", socs={"a": 100.0, "b": 100.0}) w = cur_writes(r) stuck = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] late = [(t, a) for t, a, _ in w if t >= 1000] check(f"scenario E2: after the cloud pause the car restarts 120 s after the " f"sun returns, never held by a stuck verdict ({w}, stuck {stuck[:1]})", not stuck and present(nth(late, 0)) and nth(late, 0)[1] > 0.0 and 1119 <= nth(late, 0)[0] <= 1125) # =========================================================================== # print("\n4. NO PING-PONG ON AN AMP BOUNDARY (rig Major)") # =========================================================================== # for ph, sun_w, amps in ((1, 2900.0, 10.0), (3, 600.0 + 6900.0, 10.0)): def dither(t, base=sun_w): return base + (6.0 if int(t // 17) % 2 else -6.0) opts = {"ev_phases": "1" if ph == 1 else "3"} r = S.drive(const(500.0), dither, dur=1500, first="car", socs={"a": 100.0, "b": 100.0}, opts=opts, phases=ph) w = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0] changes = len(w) - 1 check(f"[{ph} phase] the spare dithers +-6 W around the {amps:.0f} A " f"boundary for 1500 s: at most one change after the start " f"({changes} changes: {w[:6]})", present(nth(w, 0)) and changes <= 1) nevers(r, f"ping-pong [{ph} phase]") # A real rise after a step down still raises the current. r = S.drive(const(500.0), step_fn((300, 2890.0), (600, 3300.0), base=2900.0), dur=900, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}) w = [(t, a) for t, a, _ in cur_writes(r)] check(f"guard: 10 A, down to 9 A on a 10 W dip, then a real rise to 11.3 A " f"worth: 11 A is written ({w})", [a for _, a in w] == [10.0, 9.0, 11.0]) # =========================================================================== # print("\n5. THE HOLD LASTS ITS TIME; A HEALTHY ha_signed METER (rig Major, Minors)") # =========================================================================== # for mode, kw in (("every second", {}), ("rig interleave, meter on change", {"beside": True, "meter_change": True})): sim = SimCharger(setpoint_a=0) if kw.get("beside"): sim.lag_s = 1.0 # 1 phase: a 290 s cloud never pauses; a 400 s one pauses at 300 s. r = S.drive(jit(const(500.0)), lambda t: 900.0 if 400 <= t < 690 or 1200 <= t < 1600 else 2900.0, dur=1800, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, sim=sim, **kw) w = [(t, a) for t, a, _ in cur_writes(r)] zeros = [t for t, a in w if a == 0.0] check(f"[1 phase, {mode}] a 290 s cloud: the 6 A hold, no pause; a 400 s " f"cloud: 0 A at 300 s from the drop, +2 ({w})", not [t for t in zeros if 400 <= t < 700] and [t for t in zeros if 1200 <= t < 1600][:1] and 1499 <= nth([t for t in zeros if 1200 <= t < 1600], 0) <= 1502) nevers(r, f"hold [1 phase, {mode}]") sim = SimCharger(setpoint_a=0) if kw.get("beside"): sim.lag_s = 1.0 # 3 phases: 7 A, then the spare under 6 A worth from 600 s: 6 A, 0 A at # 900 s (+2), not before. r = S.drive(jit(const(500.0)), step_fn((600, 600.0 + 2500.0), base=600.0 + 6000.0), dur=1100, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "3"}, phases=3, sim=sim, **kw) w = [(t, a) for t, a, _ in cur_writes(r)] zeros = [t for t, a in w if a == 0.0 and t > 200] check(f"[3 phases, {mode}] the hold from 600 s: 6 A, then 0 A at 900 s " f"(+2), not before ({w})", present(nth(zeros, 0)) and 899 <= nth(zeros, 0) <= 902 and 6.0 in [a for t, a in w if 600 <= t < 900]) nevers(r, f"hold [3 phases, {mode}]") # A healthy meter on ha_signed: Home Assistant publishes it only on a change, # so at a flat load the value may stand longer than stale_input_s (15 s); here # 25 s at a time, under the source's meter_max_age_s (30 s). The spare stays # known and the car is not paused. r = S.drive(const(500.0), lambda t: 2900.0 + (15.0 if int(t // 25) % 2 else 0.0), dur=1200, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, meter_change=True) w = cur_writes(r) unk = [x["t"] for x in r["trace"] if x["spare"] is None and x["t"] > 5] check(f"ha_signed, a healthy meter whose value stands 25 s at a time: the " f"spare stays known, the car starts by the start rule and is never " f"paused ({w}, unknown {unk[:3]})", not [x for x in w if x[1] == 0.0 and x[0] > 5] and not unk and present(nth(w, 0)) and nth(w, 0)[1] > 0.0 and nth(w, 0)[0] <= 125) # A silent meter on ha_signed: unknown from the source's own meter_max_age_s # (30 s), then 0 A after ev_pause_min (300 s). r = S.drive(const(500.0), const(2900.0), dur=900, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, events={300: lambda p, c: setattr(p, "meter_on", False)}) w = cur_writes(r) z = [t for t, a, _ in w if a == 0.0] check(f"ha_signed, the meter silent from 300 s: 0 A at 30 + 300 s (+2), " f"never from a stale value ({w})", present(nth(z, 0)) and 629 <= nth(z, 0) <= 633 and [a for t, a, _ in w if 300 <= t < 629] == []) # =========================================================================== # print("\n6. SPIKE-06: C12, C13 AND THE RACE AS THE FORMAL REPLAY PLAYS IT") # =========================================================================== # def race_hook(p, c): """The race exactly as production interleaves it (SPIKE-06 replay): the driver's read-back wait runs the next cycle's charger read, so the tracker files the post-write reading before `note_write`.""" orig = c.charger._sleep async def sleep(s): await orig(s) await c._read_charger(p.clock[0]) c.charger._sleep = sleep def stuck_ts(r): return [x["t"] for x in r["trace"] if x["fault"] == "stuck"] # C10/C11 replays (ctl A: the charger's power-on 10 A, Solar's D2 0 A; ctl B: # Solar's 10 A start on a charging car), each with the race. sim = SimCharger(setpoint_a=10) sim.lag_s = 1.0 r = S.drive(const(500.0), const(2900.0), dur=900, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, events={0: race_hook}) w = cur_writes(r) check(f"race replay ctl A: D2 0 A, then the start at 120 s, never stuck " f"({w[:3]}, stuck {stuck_ts(r)[:1]}, tracker {r['c'].car.stuck_now})", present(nth(w, 1)) and nth(w, 0)[1] == 0.0 and nth(w, 1)[1] > 0.0 and 119 <= nth(w, 1)[0] <= 125 and not stuck_ts(r) and not r["c"].car.stuck_now) nevers(r, "race replay ctl A") sim = SimCharger(setpoint_a=0) sim.lag_s = 1.0 r = S.drive(const(500.0), const(2900.0), dur=900, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, events={0: race_hook}) w = cur_writes(r) check(f"race replay ctl B: one start write, the car charges to the end, " f"never stuck ({w[:3]}, stuck {stuck_ts(r)[:1]})", len(w) == 1 and w[0][1] > 0.0 and not stuck_ts(r) and not r["c"].car.stuck_now and r["sim"].power_w > 2000.0) nevers(r, "race replay ctl B") # C12: a paused (full) car, a live charger ignores Solar's start write once. # No life (0 W, flat energy), so the refusal arms and is stuck 60 s later; # Solar's 0 A then stands. Option 2: the stuck verdict no longer holds the # car at 0 A; the start rule writes again within 2 min, the reading moves. for race in (False, True): sim = TSim(setpoint_a=0, windows=[(100.0, 135.0, "ignore")]) sim.car_full() if race: sim.lag_s = 1.0 r = S.drive(const(500.0), const(2900.0), dur=900, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, events={0: race_hook} if race else None) w = cur_writes(r) tr = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] st = r["c"].car z = [t for t, a, _ in w if a == 0.0 and t > 125] nz = [t for t, a, _ in w if a > 0.0 and present(nth(z, 0)) and t > z[0]] check(f"C12 [race={race}] a live charger ignores one start write on a " f"paused car: after Solar's 0 A the start rule writes again within " f"125 s and the stuck verdict clears (writes {w[:6]}, 0 A at " f"{z[:1]}, again at {nz[:1]}, stuck now {st.stuck_now})", present(nth(z, 0)) and present(nth(nz, 0)) and nth(nz, 0) - nth(z, 0) <= 125 and not st.stuck_now and r["trace"][-1]["fault"] is None) nevers(r, f"C12 [race={race}]") # C12's cap and backoff (PM decision): a charger whose reading is really # frozen (at 300 s, with the values it will show when it comes back). Solar's # own 0 A stands, so the start rule runs; each start is not taken and the 0 A # follows. At most MAX_TRIES starts under one verdict, then ONE # CHARGER_REFUSED; then one more start 15 min later, then one every 30 min # (each by the start rule), never the 72 s flapping. def frozen_run(dur, events=None): n0 = LOG.mark() ev = {300: lambda p, c: p.ch.freeze()} ev.update(events or {}) r = S.drive(const(600.0), lambda t: 600.0 + (1000.0 if 200 <= t < 330 else 2300.0 if t < 200 else 6000.0), dur=dur, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_pause_min": 1, "ev_start_min": 1}, events=ev) r["_log"] = n0 st = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] t0 = nth(st, 0) if st else 1e9 w = cur_writes(r) starts = [t for t, a, _ in w if a > 0.0 and t >= t0] warn = [m for m in LOG.since(n0, "WARNING") if "CHARGER_REFUSED" in m] return r, w, starts, warn r, w, starts, warn = frozen_run(4000) first3, later = starts[:3], starts[3:] t3 = nth(first3, 2) gaps = [b - a for a, b in zip(later, later[1:])] check(f"cap: a frozen charger: 3 starts under the verdict ({first3}), then " f"one CHARGER_REFUSED ({len(warn)})", len(first3) == carmode.MAX_TRIES and len(warn) == 1 and all(b - a < 120 for a, b in zip(first3, first3[1:]))) check(f"backoff: one more start 15 min after the 3rd (+ the start rule), " f"then one every 30 min (+ the start rule): {later} (gaps {gaps})", present(t3) and len(later) == 2 and 900 <= nth(later, 0) - t3 <= 900 + 80 and all(1800 <= g <= 1800 + 80 for g in gaps)) nevers(r, "cap and backoff") # Recovery: the reading comes back at 1200 s with the values it froze with, # so nothing moves by itself; the next backoff start is taken, the reading # follows it, the episode ends (warning cleared) and the car charges. r, w, starts, warn = frozen_run(2400, {1200: lambda p, c: p.ch.freeze(False)}) t3 = nth(starts, 2) rec = [t for t in starts if t > 1200] check(f"recovery: the fault clears at 1200 s; the next backoff start " f"({rec[:1]}, 15 min after the 3rd at {t3}) is taken and the car " f"charges to the end, warning cleared, not stuck", present(nth(rec, 0)) and present(t3) and 900 <= nth(rec, 0) - t3 <= 980 and r["sim"].power_w > 1000.0 and not r["c"].car.stuck_now and not r["c"].car_solar.gave_up) nevers(r, "recovery") # A press of Solar during the backoff starts the episode afresh: a start by # the start rule after the press, not 15 min later. r, w, starts, warn = frozen_run(1400, {1000: act("car_mode", "solar")}) after = [t for t in starts if t >= 1000] check(f"press: Solar pressed at 1000 s during the backoff: a start by the " f"start rule after the press ({after[:1]})", present(nth(after, 0)) and nth(after, 0) <= 1000 + 75) # The episode ends on Off, Manual and shadow: counter, wait and warning # cleared (read 5 s after the switch). for name, fn in (("Off", act("car_mode", "off")), ("Manual", act("car_mode", "manual")), ("shadow", lambda p, c: c.o.__setitem__("shadow_mode", "on"))): seen = {} def look(p, c, seen=seen): sw = c.car_solar seen.update(starts=sw.stuck_starts, gave_up=sw.gave_up, wait=getattr(sw, "stuck_wait", None), warned=getattr(sw, "stuck_warned", None)) before = {} def look0(p, c, before=before): before.update(starts=c.car_solar.stuck_starts, gave_up=c.car_solar.gave_up) r, w, starts, warn = frozen_run(900, {790: look0, 800: fn, 805: look}) check(f"episode end on {name}: before {before}, after {seen}", before.get("starts") == carmode.MAX_TRIES and before.get("gave_up") and seen.get("starts") == 0 and seen.get("gave_up") is False and seen.get("wait") is None and seen.get("warned") is False) # C14: Manual's refused writes leave a stuck verdict on a paused, live car, # then the user presses Solar. No current of Solar's own may stand, so the # verdict does not hold Solar: its 0 A first (over Manual's 6 A), then the # start rule with spare sun; the start moves the reading, the verdict clears. for name, win, t_s in (("Manual's 12 A refused 3 times, Solar at 400 s", (99.5, 250.0), 400),): sim = TSim(setpoint_a=0, windows=[(win[0], win[1], "ignore")]) sim.car_full() seen = {} r = S.drive(const(500.0), const(2900.0), dur=1200, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, mode="manual", events={100: act("car_current", 12), t_s - 1: lambda p, c: seen.update( armed=c.car.armed_at, stuck=c.car.stuck_now), t_s: act("car_mode", "solar")}) w = cur_writes(r) nz = [(t, a) for t, a, _ in w if a > 0.0] check(f"C14 [{name}]: the check armed by Manual's refusal before the " f"press ({seen})", seen.get("armed") is not None) check(f"C14 [{name}]: Solar writes 0 A first, then a start within the " f"start rule, and the verdict clears ({w[:4]}, stuck now " f"{r['c'].car.stuck_now})", present(nth(w, 0)) and nth(w, 0)[1] == 0.0 and nth(w, 0)[0] <= t_s + 2 and present(nth(nz, 0)) and nth(nz, 0)[0] <= t_s + 125 and not r["c"].car.stuck_now and r["trace"][-1]["fault"] is None) nevers(r, f"C14 [{name}]") # C13: a car that draws less than allowed (an on-board limit of 1380 W, or a # taper). Tracker level: a raise 6 -> 10 A, the post-write reading filed # during the wait (race) or not: never stuck. for race in (True, False): tr = CH.CarTracker() tr.observe(rd(power=1380.0, allowed=6.0), TS, UTC, DAY) tr.begin_write() if race: tr.observe(rd(power=1380.0, allowed=10.0), TS + 1, UTC, DAY) tr.note_write(TS, 6.0, 10.0, True) tr.end_write(TS + 1.5) first = None for i in range(2, 301): tr.observe(rd(power=1380.0, allowed=10.0), TS + i, UTC, DAY) if first is None and tr.stuck(TS + i): first = i check(f"C13 tracker [race={race}] a capped car (1380 W), raised 6 -> 10 " f"A: never stuck (first at {first})", first is None) class CapSim(SimCharger): """A car whose on-board charger draws at most `cap_w`.""" cap_w = 1380.0 def target_w(self): return min(super().target_w(), self.cap_w) for race in (True, False): sim = CapSim(setpoint_a=0) sim.lag_s = 1.0 r = S.drive(const(500.0), lambda t: 3600.0 if t >= 300 else 2900.0, dur=900, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, events={0: race_hook} if race else None) w = cur_writes(r) up = [(t, a) for t, a, _ in w if t >= 300] check(f"C13 controller [race={race}] a capped car, Solar raises the " f"current at 300 s: never stuck, no 0 A after it ({w[:5]}, stuck " f"{stuck_ts(r)[:1]})", present(nth(up, 0)) and nth(up, 0)[1] > 10.0 and not stuck_ts(r) and not [a for _, a in up if a == 0.0]) nevers(r, f"C13 controller [race={race}]") # =========================================================================== # print("\n7. RIG ROUND 2: A SHORT CHARGER READ GAP; THE ha_signed PAUSE BY AGE") # =========================================================================== # # Full sun, Car first, charging 10 A from 120 s; the charger does not answer # for 1, 2 or 16 cycles at 600 s (Home Assistant shows it unavailable). def gap_run(n, beside=False): sim = SimCharger(setpoint_a=0) if beside: sim.lag_s = 1.0 return S.drive(const(500.0), const(2900.0), dur=1100, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, beside=beside, events={600: lambda p, c: p.ch.go_unavailable(), 600 + n: lambda p, c: p.ch.go_unavailable(False)}) for n in (1, 2): for beside in (False, True): r = gap_run(n, beside) w = cur_writes(r) late = [(t, a) for t, a, _ in w if t >= 590] unk = [x["t"] for x in r["trace"] if 590 <= x["t"] < 1100 and x["spare"] is None] check(f"read gap of {n} sample(s) at 600 s [beside={beside}]: no " f"write and no pause after it, the spare stays known (writes " f"from 590 s {late}, unknown {unk[:3]})", late == [] and unk == [] and r["sim"].power_w > 2000.0) nevers(r, f"read gap {n} [beside={beside}]") # 16 s (>= stale_input_s): the safe path as before. The charger is taken as # gone; on its return Solar writes 0 A first (D2), then the start rule. r = gap_run(16) w = cur_writes(r) late = [(t, a) for t, a, _ in w if t >= 590] check(f"read gap of 16 s: the safe path, 0 A first on the return, then the " f"start rule ({late[:3]})", present(nth(late, 0)) and nth(late, 0)[1] == 0.0 and 616 <= nth(late, 0)[0] <= 620 and present(nth(late, 1)) and nth(late, 1)[1] > 0.0) # The held figure neither arms nor clears the stuck check: a frozen reading # after an accepted write is still stuck, with a 2-sample gap inside the 60 s # (flagged at the first real reading at or after +60 s). tr = CH.CarTracker() for i in range(-5, 1): tr.observe(rd(), TS + i, UTC, DAY) tr.begin_write() tr.end_write(TS + 1) tr.note_write(TS, 10.0, 0.0, True) gone = CH.ChargerReading(why="no answer") st_at = None for i in range(1, 90): if i in (59, 60): tr.observe(gone, TS + i, UTC, DAY) else: tr.observe(rd(), TS + i, UTC, DAY) if st_at is None and tr.stuck(TS + i): st_at = i check(f"frozen reading with a 2-sample gap at +59/+60: still stuck, at the " f"first real reading after +60 (+{st_at})", st_at == 61) tr = CH.CarTracker() for i in range(-5, 1): tr.observe(rd(), TS + i, UTC, DAY) tr.begin_write() tr.end_write(TS + 1) tr.note_write(TS, 10.0, 0.0, True) for i in range(1, 70): tr.observe(rd(), TS + i, UTC, DAY) tr.observe(gone, TS + 70, UTC, DAY) check("a held gap does not clear a stuck verdict (+70 s gap, still stuck)", tr.stuck(TS + 70) and getattr(tr, "held", None) is True) # ha_signed: the pause is timed from the meter's age (PM): unknown since the # age passed meter_max_age_s, so 0 A when the age reaches 330 s. A plan # stepped every 10 s (the rig's cycle) that first sees the unknown sun at age # 57 (a cycle or two after the bound passed) still pauses at the first step at # or after age 330 (bound: 330 + one cycle); timed from the noticing step it # would be age 357. plan = carmode.SolarPlan() plan.reset(1) kw = dict(n_now=1, auto=False, clamp=16.0, start_s=120.0, pause_s=300.0) t = 0.0 while plan.a <= 0.0 and t < 400: plan.step(t, target_w=2900.0, **kw) t += 10.0 age0 = t + 3.0 # the meter's last reading; the bound passes at +30 paused_at = None while t < age0 + 400: age = t - age0 over = max(0.0, age - 30.0) try: plan.step(t, target_w=None if age > 50.0 else 2900.0, unknown_s=over if age > 50.0 else 0.0, **kw) except TypeError: # a build without the age rule plan.step(t, target_w=None if age > 50.0 else 2900.0, **kw) if plan.a == 0.0 and paused_at is None: paused_at = age break t += 10.0 check(f"ha_signed pause by age, plan stepped every 10 s: 0 A at meter age " f"{paused_at} (330 <= age <= 340)", paused_at is not None and 330.0 <= paused_at <= 340.0) # The controller hands Solar that age: 40 s after the meter went silent at # 300 s, `unknown_s` is 10 (age 40 - 30). seen = {} r = S.drive(const(500.0), const(2900.0), dur=360, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, events={300: lambda p, c: setattr(p, "meter_on", False), 340: lambda p, c: seen.update( u=getattr(c.car_sun_inputs(p.clock[0]), "unknown_s", None))}) check(f"ha_signed: 40 s after the meter went silent Solar is told the sun " f"has been unknown for 10 s ({seen})", seen.get("u") is not None and 9.0 <= seen["u"] <= 12.0) # =========================================================================== # print("\n8. SPIKE-06 ROUND 3: NO NON-ZERO WRITE WHILE THE METER IS SILENT (C17);") print(" THE AGE PAUSE ON A HELD READ (C18)") # =========================================================================== # # C17 (a): 7 A, a raise to 10 A at 340 s that the charger ignores, the meter # silent from 345 s (ha_signed). No re-send of the 10 A (the retry would come # at 400 s, meter age 55 s); 0 A when the age reaches 330 s. sim = TSim(setpoint_a=0, windows=[(335.0, 350.0, "ignore")]) r = S.drive(const(500.0), lambda t: 3000.0 if t >= 340 else 2300.0, dur=900, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, opts={"ev_phases": "1"}, events={345: lambda p, c: setattr(p, "meter_on", False)}) w = cur_writes(r) nz = [(t, a) for t, a, _ in w if a > 0.0 and t > 345 + 30] z = [t for t, a, _ in w if a == 0.0 and t > 345] raise_ = [(t, a, ok) for t, a, ok in w if 330 <= t <= 345] check(f"C17 (a): an ignored raise ({raise_}), then the meter silent from " f"345 s: no re-send while it is silent ({nz}), 0 A at meter age 330 " f"(+2) ({z[:1]})", present(nth(raise_, 0)) and nth(raise_, 0)[2] is False and nz == [] and present(nth(z, 0)) and 345 + 329 <= nth(z, 0) <= 345 + 333) nevers(r, "C17 (a)") # C17 (b): a 1 -> 3 phase change starts at 301 s (its 0 A); the meter has been # silent since 276 s, so its age passes 30 s at 307 s, before the closing # current (313 s without silence). The change ends at its 0 A: no closing # current, nothing non-zero until the meter is back. r = S.drive(const(500.0), const(7600.0), dur=900, first="car", socs={"a": 100.0, "b": 100.0}, car_phases=3, events={276: lambda p, c: setattr(p, "meter_on", False), 800: lambda p, c: setattr(p, "meter_on", True)}) w = cur_writes(r) seq0 = [t for t, a, _ in w if a == 0.0 and 295 <= t <= 305] nz = [(t, a) for t, a, _ in w if a > 0.0 and 306 < t < 800] check(f"C17 (b): a phase change under way when the meter goes silent ends at " f"its 0 A ({seq0}): no closing current, no non-zero write while silent " f"({nz}); writes {w[:6]}", present(nth(seq0, 0)) and nz == [] and [a for t, a, _ in w if 301 <= t < 800][-1:] == [0.0]) nevers(r, "C17 (b)") # C18: a charger read gap on the very cycle the age pause is due (ha_signed, # meter silent from 300 s: due at 629 s without a gap, the meter's last sample # being at 299 s). The held cycle still steps Solar's pause: 0 A at 629 s, at # most one cycle later (f625011: 631 s with the gap from 629 s). for gap_at in (629, 630): r = S.drive(const(500.0), const(2900.0), dur=760, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, events={300: lambda p, c: setattr(p, "meter_on", False), gap_at: lambda p, c: p.ch.go_unavailable(), gap_at + 2: lambda p, c: p.ch.go_unavailable(False)}) w = cur_writes(r) z = [t for t, a, _ in w if a == 0.0 and t > 300] check(f"C18: a 2-sample read gap from {gap_at} s, the age pause due at " f"629 s: 0 A at {z[:1]} (629-630)", present(nth(z, 0)) and 629 <= nth(z, 0) <= 630) # =========================================================================== # print("\n9. SPIKE-06 C19: A READ GAP DURING A PHASE CHANGE") # =========================================================================== # # The C17 (b) shape without the silent meter: a 1 -> 3 change, its 0 A at # 301 s, select 3, closing current at 313 s. One to six failed charger reads # right after the select change nothing: the closing current comes on time # and no pause follows (0ef8de2: paused, no current until about 914 s). def phase_run(events): return S.drive(const(500.0), const(7600.0), dur=700, first="car", socs={"a": 100.0, "b": 100.0}, car_phases=3, events=events) for n in (1, 2, 6): r = phase_run({305: lambda p, c: p.ch.go_unavailable(), 305 + n: lambda p, c: p.ch.go_unavailable(False)}) w = cur_writes(r) close = [(t, a) for t, a, _ in w if a > 0.0 and 301 < t < 700] check(f"C19: {n} failed read(s) at 305 s, just after the select: the " f"closing current on time ({close[:2]}), no pause ({w[:5]})", present(nth(close, 0)) and 312 <= nth(close, 0)[0] <= 313 + n and [a for t, a, _ in w if 301 < t < 700 and a == 0.0] == []) nevers(r, f"C19 gap {n}") # A gap of stale_input_s or more during the change: the safe path as before. # The charger is taken as gone: nothing while it is away and no closing # current; on its return the change is dropped and Solar starts over (0 A # first, already standing here, so nothing is written; then the start rule, # which on the 3 phases the select left waits for the phase gap). r = phase_run({305: lambda p, c: p.ch.go_unavailable(), 322: lambda p, c: p.ch.go_unavailable(False)}) w = cur_writes(r) during = [(t, a) for t, a, _ in w if 305 <= t < 322] after = [(t, a) for t, a, _ in w if t >= 322] check(f"C19: a 17 s gap during the change takes the safe path: nothing while " f"away ({during}), no closing current, nothing non-zero before the " f"start rule after the return ({after[:2]})", during == [] and not [1 for t, a in after if a > 0.0 and t < 322 + 115] and r["c"].car_solar.seq is None) nevers(r, "C19 long gap") # =========================================================================== # print("\n10. REVIEW R3: A HELD READ ON A DECISION CYCLE (PM design)") # =========================================================================== # # The reviewer's three shapes (house 500 W, Car first, 3-phase car). A 1- or # 2-sample read gap on the cycle a phase change or a switching start is due, # or on the cycle before it: the decision waits for the next real reading and # every write lands within 2 s of the run without the gap (a60ebd3: the wait # restarted, and 3 -> 1 became a 0 A pause in full sun). def sun_b(t): return 7600.0 if t < 1000 else (300.0 if t < 1400 else 2600.0) SHAPES = (("A 1 -> 3", const(7600.0), 700, 301), ("B a start that needs 3 -> 1", sun_b, 1900, 1521), ("C 3 -> 1", lambda t: 7600.0 if t < 1000 else 4300.0, 1700, 1301)) def shape_run(sunf, dur, events=None): return S.drive(const(500.0), sunf, dur=dur, first="car", socs={"a": 100.0, "b": 100.0}, car_phases=3, events=events or {}) def after(r, t0, t1): return [(t, a) for t, a, _ in cur_writes(r) if t0 <= t < t1] for name, sunf, dur, d in SHAPES: twin = after(shape_run(sunf, dur), d - 5, d + 200) for off in (-1, 0): for n in (1, 2): g = d + off r = shape_run(sunf, dur, {g: lambda p, c: p.ch.go_unavailable(), g + n: lambda p, c: p.ch.go_unavailable(False)}) got = after(r, d - 5, d + 200) same = (len(got) == len(twin) and all( a1 == a2 and abs(t1 - t2) <= 2.0 for (t1, a1), (t2, a2) in zip(got, twin))) check(f"review r3 [{name}] {n}-read gap at {g} (decision due " f"{d}): the writes of the run without the gap, within 2 s " f"({got[:4]} vs {twin[:4]})", same and bool(twin)) nevers(r, f"review r3 [{name}] gap {n} at {g}") # The hold's pause (low_since past ev_pause_min) never fires on a held cycle: # it comes on the next real reading, and only if that reading still says low. base = S.drive(const(500.0), lambda t: 900.0 if t >= 400 else 2900.0, dur=900, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}) z0 = nth([t for t, a, _ in cur_writes(base) if a == 0.0 and t > 400], 0) check(f"hold twin: 0 A at {z0} (300 s from the drop at 400, +2)", present(z0) and 699 <= z0 <= 702) if present(z0): zi = int(z0) r = S.drive(const(500.0), lambda t: 900.0 if t >= 400 else 2900.0, dur=900, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, events={zi: lambda p, c: p.ch.go_unavailable(), zi + 1: lambda p, c: p.ch.go_unavailable(False)}) z = [t for t, a, _ in cur_writes(r) if a == 0.0 and t > 400] check(f"hold pause due on a held read ({zi}): 0 A on the next real " f"reading ({z[:1]}), not on the held cycle", present(nth(z, 0)) and nth(z, 0) == zi + 1) r = S.drive(const(500.0), lambda t: 900.0 if 400 <= t < zi else 2900.0, dur=900, first="car", socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, events={zi: lambda p, c: p.ch.go_unavailable(), zi + 1: lambda p, c: p.ch.go_unavailable(False)}) z = [t for t, a, _ in cur_writes(r) if a == 0.0 and t > 400] check(f"hold pause due on a held read ({zi}), the sun back from that " f"second, so the next real reading ({zi + 1}) is not low: no pause " f"({z[:1]})", z == []) report()