"""EV-20: every way out of Solar ends at 0 A (T23-T37, T61; N9, N12, N14). `python3 -B test_ev20_exits.py` The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and `chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section names the T-ids and N-ids of reports/EV-20-test-plan.md it implements. "Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare 2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start. Times are the cycle's second; `race` runs use the production order (read, the writer settles, the cycle). Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). """ import asyncio import json import math import os import random import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "tools")) from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402 from app import mqtt, validate, web, main as app_main # noqa: E402 from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402 import ev20_sun as S # noqa: E402 from chargersim import SimCharger # noqa: E402 from ev20_kit import * # noqa: E402,F401,F403 from ev20_kit import LOG, check, fails, report # noqa: E402,F401 from named_absence import given, nth, present # noqa: E402,F401 from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401 _until) # =========================================================================== # print("\n6. EXIT PATHS END AT 0 A (T23-T37, T61, N9, N12, N14)") # =========================================================================== # r23 = run("T23", std, 300, finale=_shutdown) o23 = sets_order(r23) z23 = [i for i, (t, e, v) in enumerate(o23) if e == SET and v == 0.0] inv23 = [i for i, (t, e, v) in enumerate(o23) if e.startswith("number.sp_") and i > (z23[0] if z23 else 0)] check(f"T23: Controller.shutdown() in Solar at 10 A: one 0 A, sent BEFORE the " f"first inverter 0 W of command_site_release ({o23[-4:]})", len(z23) == 1 and bool(inv23) and r23["sim"].setpoint_a == 0.0) for start, want in (("keep", "solar"), ("off", "off")): sim23 = r23["sim"] n0 = len(sim23.log) rr = std(200, sim=sim23, store=r23["store"], mode="solar", opts={"ev_mode_start": start}) if start == "off": rr["store"].data["car_mode"] = "solar" new = sim23.log[n0:] t_restart = 301.0 if start == "keep" else 0.0 check(f"T23: restart on the same store, ev_mode_start {start}: " f"{want}{', paused' if want == 'solar' else ''}, " f"{'no non-zero write for 120 s' if want == 'solar' else 'nothing written'} " f"({[(x[0], x[2]) for x in new]})", rr["c"].car_mode == want and not [x for x in new if x[2] > 0.0 and x[0] - t_restart < 120] and (want == "solar" or new == [])) t_restart = sim23.t for kind in ("error", "ignore"): def mk(kind=kind): return TSim(setpoint_a=0, windows=[(299.5, 306.5, kind)]) sim = mk() r23b = run("T23b", std, 300, sim=sim, finale=_shutdown) tries = [(t, v) for t, v in attempts(r23b) if t >= 299] gap = [b[0] - a[0] for a, b in zip(tries, tries[1:])] rel = _until(r23b, 299.0) check(f"T23 (b) D3 [{kind}]: the 0 A refused for 7 s from shutdown: tries " f"about 0, 5, 10 s (3 at most, >= 4 s apart), the third taken, then " f"the inverters 0 W, all within 15 s ({tries}, release +{rel})", len(tries) == 3 and all(g >= 4.0 for g in gap) and r23b["sim"].setpoint_a == 0.0 and rel is not None and rel <= 15.0 and r23b["c"].car_solar.released is True) for kind in ("error", "ignore"): sim = TSim(setpoint_a=0, windows=[(299.5, 1e9, kind)]) n = LOG.mark() r23c = run("T23c", std, 300, sim=sim, finale=_shutdown) tries = [(t, v) for t, v in attempts(r23c) if t >= 299] rel = _until(r23c, 299.0) warn = [m for m in LOG.since(n, "WARNING") if "CHARGER_RELEASE" in m] check(f"T23 (c) D3 [{kind}]: refused for the whole shutdown: 3 tries, the " f"inverters' 0 W by 15 s (+{rel}), one warning that the car may still " f"be charging, the notice raised after the inverters ({tries})", len(tries) == 3 and rel is not None and rel <= 15.0 and len(warn) == 1 and any(n_ == messages.ID_CAR_RELEASE for _, n_ in r23c["raised"]) and r23c["store"].data.get(ctl_car.CAR_RELEASE_KEY) is True) sim.windows = [] n0 = len(sim.log) rr = std(300, sim=sim, store=r23c["store"], mode="solar") new = [(x[0], x[2]) for x in sim.log[n0:]] check(f"T23 (c)/D2 [{kind}]: restart on the same store (keep): the first " f"charger write is 0 A, then only the start rule; the notice comes " f"down ({new})", new[:1] and new[0][1] == 0.0 and new[0][0] - sim.log[n0][0] <= 1 and not [x for x in new[1:] if x[1] > 0 and x[0] - new[0][0] < 119] and any(n_ == messages.ID_CAR_RELEASE for _, n_ in rr["plant"].dismissed)) async def _hang_shutdown(p, c): p.hang = True await c.shutdown() keep_wait = ctl_car.RELEASE_WAIT_S ctl_car.RELEASE_WAIT_S = 0.3 try: import time as _time t_0 = _time.monotonic() r23u = run("T23u", std, 300, plant_cls=HangPlant, finale=_hang_shutdown) took = _time.monotonic() - t_0 finally: ctl_car.RELEASE_WAIT_S = keep_wait inv_u = [v for t, e, v in r23u["plant"].sets if e.startswith("number.sp_") and t >= 299] check(f"T23: a charger that never answers delays the inverter release by " f"RELEASE_WAIT_S at most (15 s; 0.3 s here), then the inverters go to " f"0 W ({inv_u[-2:]}) and the warning stands", ctl_car.RELEASE_WAIT_S == 15.0 and inv_u and inv_u[-1] == 0.0 and r23u["c"]._car_release_failed) # T24: the control task dies. r24 = run("T24", std, 300, finale=_dies) o24 = sets_order(r24) z24 = [i for i, (t, e, v) in enumerate(o24) if e == SET and v == 0.0] check(f"T24: the control task dies: 0 A once, before the inverters' 0 W; " f"exit code 70 unchanged ({o24[-3:]})", len(z24) == 1 and app_main.EXIT_CONTROL_DIED == 70 and r24["plant"].died == (True, 1) and any(e.startswith("number.sp_") for t, e, v in o24[z24[0]:])) sim24 = TSim(setpoint_a=0, windows=[(299.5, 1e9, "error")]) r24c = run("T24c", std, 300, sim=sim24, finale=_dies) check(f"T24 D3: refused throughout: 3 tries about 5 s apart, the inverters " f"by 15 s, the warning ({[t for t, v in attempts(r24c) if t >= 299]})", len([1 for t, v in attempts(r24c) if t >= 299]) == 3 and _until(r24c, 299.0) <= 15.0 and r24c["c"]._car_release_failed) sim24b = TSim(setpoint_a=0, windows=[(299.5, 306.5, "error")]) r24b = run("T24b", std, 300, sim=sim24b, finale=_dies) check("T24 D3: refused for 7 s: the third try is taken, the inverters after", r24b["sim"].setpoint_a == 0.0 and r24b["c"].car_solar.released is True) # T25: Stop, with shadow_mode off and the shipped auto. for sm in ("off", "auto"): r25 = std(800, opts={"shadow_mode": sm}, events={300: act("auto_toggle", None), 600: act("auto_toggle", None)}) w25 = cur_writes(r25) check(f"T25 [shadow_mode {sm}]: Stop at 300 s: 0 A once within 1 cycle, " f"nothing while stopped; after Start only the start rule " f"(10 A at 720 s) ({w25})", [(t, a) for t, a, _ in w25] == [(120.0, 10.0), (300.0, 0.0), (720.0, 10.0)]) # T26: the safety latches. for name, fn in (("sign_wd", lambda p, c: setattr(c.inverters[0].sign_wd, "tripped", True)), ("site_sign_wd", lambda p, c: setattr(c.site_sign_wd, "tripped", True)), ("circ_wd", lambda p, c: setattr(c.circ_wd, "tripped", True))): r26 = std(700, events={300: fn}) check(f"T26 [{name}]: 0 A once, nothing else while latched " f"({cur_writes(r26)})", [(t, a) for t, a, _ in cur_writes(r26)] == [(120.0, 10.0), (300.0, 0.0)]) # T27: a charger error. n27 = LOG.mark() blk27 = {} def _err_card(p, c): blk27["b"] = homeview.car_block(c, None) def _err_clear(p, c): p.ch.error = "0: No Error" p.ch.state = "B" r27 = std(900, events={300: _err, 400: _err_card, 600: _err_clear}) w27 = cur_writes(r27) warn27 = [m for m in LOG.since(n27, "WARNING") if "CHARGER_ERROR" in m] check(f"T27: a charger error: 0 A once, no write during it, one warning; the " f"start rule after it clears (10 A at 720 s) ({w27}, {len(warn27)})", [(t, a) for t, a, _ in w27] == [(120.0, 10.0), (300.0, 0.0), (720.0, 10.0)] and len(warn27) == 1) check(f"T27: the card shows it ({blk27.get('b', {}).get('why')!r})", blk27.get("b", {}).get("why", "").startswith("The charger reports an " "error")) # T28: a stuck reading. blk28 = {} r28 = std(800, sun=step_fn((125, 600.0 + 2760.0), base=600.0 + 2300.0), events={150: _freeze_after_write, 300: lambda p, c: blk28.update(rows=c.checks()), 600: lambda p, c: p.ch.freeze(False)}, rows=True) w28 = cur_writes(r28) zt = [(t, ok) for t, a, ok in w28 if a == 0.0] check(f"T28: the reading freezes as the 12 A write (150 s) goes out: 0 A at " f"150 + 60 s (+1 cycle +10 s), not confirmed by the frozen read-back, " f"tried 3 times 60 s apart, then the gave-up row ({w28})", len(zt) == 3 and 210 <= zt[0][0] <= 221 and all(not ok for _, ok in zt) and [b[0] - a[0] for a, b in zip(zt, zt[1:])] == [60.0, 60.0] and "charger_refused" in r28["trace"][450]["amber"]) check("T28: the amber row 'Charger reading may be stuck'", "charger_stuck" in [x["id"] for x in blk28.get("rows", [])]) check(f"T28: no non-zero write until a reading moves; then the start rule " f"(0 A confirmed by the moved reading, 10 A 120 s later) ({w28[-1:]})", not [1 for t, a, ok in w28 if a > 0 and 150 < t < 600] and w28[-1][1] == 12.0 and 718 <= w28[-1][0] <= 722 if len(w28) > 4 else False) # (b) the frozen read-back shows 0 A while the charger is not at 0 A: a stuck # reading confirms nothing, so the 0 A is written (mutant `stuck_trust`). r28b = std(800, sun=step_fn((200, 600.0 + 1000.0), (330, 600.0 + 6000.0), base=600.0 + 2300.0), opts={"ev_pause_min": 1, "ev_start_min": 1}, events={300: _freeze_after_write, 700: lambda p, c: p.ch.freeze(False)}) w28b = cur_writes(r28b) st28 = [x["t"] for x in r28b["trace"] if x["fault"] == "stuck"] check(f"T28 (b): frozen at 0 A, then Solar starts (the write unconfirmed): " f"once stuck, the 0 A is written, not read off the frozen 0 A, and the " f"charger ends at 0 A ({w28b}, stuck from {st28[:1]})", bool(st28) and [x for x in w28b if x[0] >= st28[0]][:1] and [x for x in w28b if x[0] >= st28[0]][0][1] == 0.0 and r28b["sim"].setpoint_a == 0.0) # SPIKE-06 (PM): under the verdict at most MAX_TRIES starts, then the backoff # (15 min, then 30 min; test_ev20_rig.py): no 72 s flapping. s28b = [t for t, a, _ in w28b if a > 0.0 and st28 and t >= st28[0]] check(f"T28 (b): at most {carmode.MAX_TRIES} starts under the verdict in the " f"run, then none before the 15 min backoff ({s28b})", len(s28b) <= carmode.MAX_TRIES) # T29: the charger unavailable 300-420 s. T29 = {"i": lambda p, c: None, "ii": lambda p, c: p.ch.set_current(16), "iii": lambda p, c: p.ch.set_current(6), "iv": lambda p, c: p.ch.set_phases(3)} for k, fn in T29.items(): n = LOG.mark() rr = std(700, events={300: lambda p, c: p.ch.go_unavailable(True), 360: fn, 420: lambda p, c: p.ch.go_unavailable(False)}, rows=True) w = cur_writes(rr) trr = rr["trace"] other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m] check(f"T29 ({k}): nothing tried while down; the first write after it is " f"0 A within 1 cycle; no CHARGER_OTHER, no hold, no amber row for " f"the charger's own value; then the start rule ({w})", [a for t, a, _ in w if 300 <= t < 420] == [] and [x for x in w if x[0] >= 420][:1] and [x for x in w if x[0] >= 420][0][1] == 0.0 and [x for x in w if x[0] >= 420][0][0] <= 421 and not other and not any(x["hold"] for x in trr) and not any("charger_other" in x["amber"] for x in trr) and (k != "i" or [(t, a) for t, a, _ in w] == [(120.0, 10.0), (420.0, 0.0), (540.0, 10.0)])) # T29 (v): Solar paused at 0 A before the charger went away; it comes back # at 16 A (a reboot default): the 0 A is written first all the same. n = LOG.mark() rr = std(900, sun=step_fn((200, 600.0 + 1000.0), (560, 600.0 + 2300.0), base=600.0 + 2300.0), events={540: lambda p, c: p.ch.go_unavailable(True), 545: lambda p, c: p.ch.set_current(16), 600: lambda p, c: p.ch.go_unavailable(False)}) w = cur_writes(rr) after = [x for x in w if x[0] >= 600] other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m] check(f"T29 (v): paused at 0 A, the charger away 540-600 s and back at 16 A: " f"0 A first within 1 cycle, then the start rule; no CHARGER_OTHER ({w})", present(nth(after, 0)) and nth(after, 0)[1] == 0.0 and nth(after, 0)[0] <= 601 and not other and [a for t, a, _ in w if t < 600][-1:] == [0.0]) # T30: Home Assistant not answering 300-420 s. for k, fn in (("i", lambda p, c: None), ("ii", lambda p, c: p.ch.set_current(16))): n = LOG.mark() rr = std(700, events={300: lambda p, c: setattr(p, "ha_down", True), 360: both(fn, mqtt_cmd("goodwe_ctl/car/current/set", b"14")), 420: lambda p, c: setattr(p, "ha_down", False)}) w = cur_writes(rr) other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m] after = [x for x in w if x[0] >= 420] check(f"T30 ({k}): HA not answering: nothing written while down (a lost " f"MQTT command changes no current); when back 0 A first, then the " f"start rule; no CHARGER_OTHER ({w})", [x for x in attempts(rr) if 300 <= x[0] < 420] == [] and present(nth(after, 0)) and nth(after, 0)[1] == 0.0 and nth(after, 0)[0] <= 422 and not other and not any(x["hold"] for x in rr["trace"])) # T4: battery A's power or the site's battery power missing (None), not a # number (NaN) or "unavailable", at 10 A: one cycle, then 400 s. class NanPlant(S.SunPlant): """Battery A's power reads NaN (or the text 'unavailable') while set.""" bad = None async def number(self, e, invert=False): if e == "sensor.batt_a" and self.bad is not None: return float("nan") if self.bad == "nan" else None return await super().number(e, invert) async def state(self, entity_id): if entity_id == "sensor.batt_a" and self.bad == "unavailable": return {"entity_id": entity_id, "state": "unavailable", "attributes": {}} return await super().state(entity_id) def _bad(kind): def f(p, c): p.bad = kind return f for kind in ("none", "nan", "unavailable"): r1 = std(400, plant_cls=NanPlant, events={300: _bad(kind), 301: _bad(None)}) r4 = std(800, plant_cls=NanPlant, events={300: _bad(kind), 700: _bad(None)}) w4 = cur_writes(r4) sp = [x["spare"] for x in r4["trace"] if 302 <= x["t"] < 700] check(f"T4 [{kind}]: battery A's power bad for 1 cycle: no write " f"({[x for x in cur_writes(r1) if x[0] >= 300]})", [x for x in cur_writes(r1) if x[0] >= 300] == []) check(f"T4 [{kind}]: bad for 400 s: no spare computed, the current held, " f"then 0 A once at 300 s (+2 s) ({w4})", sp and all(v is None for v in sp) and [a for _, a, _ in w4 if _ < 700] == [10.0, 0.0] and 599 <= [t for t, a, _ in w4 if a == 0.0][0] <= 602) # T31: the meter goes silent at 10 A. Rig round 1: `stale_input_s` holds where # the sample age measures arrival (here the HomeWizard local source); on # `ha_signed` the age is the time since the value changed, and the source's own # meter_max_age_s is the bound (test_ev20_rig.py). ARRIVAL = {"meter_source": "homewizard_local", "p1_host": "192.0.2.10"} for race in (False, True): tag = "race" if race else "step" d = 1 if race else 0 r31 = std(900, events={300: lambda p, c: setattr(p, "meter_on", False)}, race=race, opts=ARRIVAL) w31 = cur_writes(r31) check(f"T31 (a) [{tag}]: silent from 300 s (the last sample 299.7 s): " f"no write until 15 + 300 s, then 0 A once (+2 s) ({w31})", [a for _, a, _ in w31] == [10.0, 0.0] and 614 <= w31[-1][0] <= 617 + d) r31b = std(900, events={300: lambda p, c: setattr(p, "meter_on", False), 500: lambda p, c: setattr(p, "meter_on", True)}, opts=ARRIVAL) check(f"T31 (b): back at 200 s: no 0 A ({cur_writes(r31b)})", [a for _, a, _ in cur_writes(r31b)] == [10.0]) # T32: READINGS_LATE at 10 A. def _late(fn): def ev(p, c): c._readings_late = lambda standing, p=p: fn(p.t) return ev r32a = std(700, events={300: _late(lambda t: 10.0 if 300 <= t < 340 else None)}, sun=step_fn((310, 600.0 + 3000.0), base=600.0 + 2300.0)) w32a = cur_writes(r32a) check(f"T32 (a): late_s 10 s, then caught up: held, nothing written during " f"it; the 30 s / 1 A rule after ({w32a})", not [x for x in w32a if 300 <= x[0] < 340] and w32a[0][1] == 10.0) r32b = std(900, events={300: _late(lambda t: (t - 300.0) + 1.0 if 300 <= t < 700 else None)}) w32b = cur_writes(r32b) w32b = [x for x in w32b if x[0] < 700] check(f"T32 (b): late past 15 s for 400 s: the late hold ends at 15 s, then " f"the stale rule: 0 A once by 15 + 300 + 2 s ({w32b})", [a for _, a, _ in w32b] == [10.0, 0.0] and 612 <= w32b[-1][0] <= 617) # T32 (c): a late verdict that keeps coming back under the stale bound (0 to # 10 s, over and over) while Solar holds 6 A: the hold still ends at its 300 s. r32c = std(900, sun=step_fn((200, 600.0 + 1000.0), base=600.0 + 2300.0), events={210: _late(lambda t: float((t - 210.0) % 11.0) if 210 <= t < 800 else None)}) w32c = cur_writes(r32c) check(f"T32 (c): a READINGS_LATE verdict that keeps coming back while Solar " f"holds 6 A: the 0 A still comes at the hold's 300 s, +2 s ({w32c})", [a for _, a, _ in w32c] == [10.0, 6.0, 0.0] and 499 <= w32c[-1][0] <= 502) # T33: a phase sequence interrupted. INT = {"Off": act("car_mode", "off"), "shadow": lambda p, c: c.o.__setitem__("shadow_mode", "on"), "Stop": lambda p, c: setattr(c, "auto", False), "latch": lambda p, c: setattr(c.circ_wd, "tripped", True), "unplug": lambda p, c: p.ch.unplug()} t33 = {} for stage, dt in (("zero", 2), ("settle", 6)): for name, fn in list(INT.items()) + [("shutdown", None)]: sim33 = SimCharger(setpoint_a=0) sim33.ramp_w_s = 600.0 # under 100 W only after ~5 s ev = {} fin = None if fn is None: fin = _shutdown dur = 580 + dt else: ev = {580 + dt: fn} dur = 700 rr = std(dur, sun=step_fn((400, 600.0 + 4500.0), base=600.0 + 3000.0), sim=sim33, events=ev, finale=fin) w = cur_writes(rr) zeros = [x for x in w if x[1] == 0.0] sel = selects(rr) t33[(stage, name)] = (w[-2:], [(x[0], x[2]) for x in sel]) ok = rr["sim"].setpoint_a == 0.0 and present(nth(w, -1)) \ and nth(w, -1)[1] == 0.0 \ and not [x for x in w if x[0] > 580 and x[1] > 0.0] if stage == "zero": ok = ok and sel == [] if name in ("Off", "shadow"): ok = ok and len(zeros) == 1 check(f"T33 [{stage}, {name}]: ends at 0 A, no select after it, no " f"restore of the old current ({t33[(stage, name)]})", ok) # T34: unplug at 10 A; replug. r34 = std(4500, events={800: lambda p, c: p.ch.unplug(), 4400: lambda p, c: p.ch.plug_in()}) w34 = cur_writes(r34) check(f"T34: unplug at 800 s: one 0 A within 1 cycle (+ read-back), then " f"nothing for 3600 s; replug: no write before the start rule ({w34})", [(t, a) for t, a, _ in w34] == [(120.0, 10.0), (800.0, 0.0)]) sim34 = TSim(setpoint_a=0, windows=[(800.0, 806.0, "error")]) r34b = std(1000, sim=sim34, events={800: lambda p, c: p.ch.unplug()}) check(f"T34 (b): the unplug 0 A refused once: tried again at +60 s, taken, " f"then nothing ({cur_writes(r34b)})", [(t, a, ok) for t, a, ok in cur_writes(r34b)] == [(120.0, 10.0, True), (800.0, 0.0, False), (860.0, 0.0, True)]) r34m = std(1000, mode="manual", events={800: lambda p, c: p.ch.unplug()}) check("T34 guard: Manual unplug writes nothing", not [x for x in r34m["sim"].log if x[0] > 800]) # T35: Solar to Off / shadow; the guards. r35a = std(1300, events={600: act("car_mode", "off"), 620: act("car_current", 14), 630: act("car_phases", 3)}) check(f"T35 (a): Solar to Off, then the user sets 14 A and 3 phases while " f"Off for 600 s: one 0 A within 1 cycle, then nothing " f"({cur_writes(r35a)}, sim {len(r35a['sim'].log)})", [(t, a) for t, a, _ in cur_writes(r35a)] == [(120.0, 10.0), (600.0, 0.0)] and len(r35a["sim"].log) == 2) for how, fn in (("option on", lambda p, c: c.o.__setitem__("shadow_mode", "on")), ("auto, stopped", lambda p, c: setattr(c, "auto", False))): blk = {} rr = std(1300, opts={"shadow_mode": "auto"} if how != "option on" else {}, events={600: fn, 900: lambda p, c: blk.update( b=homeview.car_block(c, None))}) check(f"T35 (b) [{how}]: one 0 A within 1 cycle, then nothing; the card " f"says what it would set ({cur_writes(rr)}, " f"{blk.get('b', {}).get('why')!r})", [(t, a) for t, a, _ in cur_writes(rr)] == [(120.0, 10.0), (600.0, 0.0)] and "would set 10 A" in blk.get("b", {}).get("why", "")) for how, fn in (("Off", act("car_mode", "off")), ("shadow", lambda p, c: c.o.__setitem__("shadow_mode", "on"))): rr = std(900, sun=step_fn((200, 600.0 + 1000.0), base=600.0 + 2300.0), events={600: fn}) check(f"T35 (c): Solar paused at 0 A, then {how}: no write " f"({cur_writes(rr)})", [a for _, a, _ in cur_writes(rr)] == [10.0, 6.0, 0.0] and not [x for x in cur_writes(rr) if x[0] >= 600]) for how, ev in (("(d) Manual to Off", {600: act("car_mode", "off")}), ("(e) shadow on in Manual", {600: lambda p, c: c.o.__setitem__("shadow_mode", "on")})): rr = std(900, mode="manual", events=ev) check(f"T35 {how}: zero writes, as EV-04", [x for x in rr["sim"].log if x[0] > 600] == []) r35f = std(900, events={600: act("car_mode", "manual"), 601: act("car_current", 13)}) check(f"T35 (f): Solar to Manual: no Solar 0 A; Manual writes its own " f"current ({[(x[0], x[2]) for x in r35f['sim'].log]})", [x[2] for x in r35f["sim"].log if x[0] > 600][:1] in ([6.0], [13.0]) and 0.0 not in [x[2] for x in r35f["sim"].log if x[0] > 600]) # T36: EV-05 r2 Critical, the exit 0 A refused then taken, on every path. def _meter_off(p, c): p.meter_on = False PATHS = { "Stop (shadow_mode off)": (300, {300: lambda p, c: setattr(c, "auto", False)}, {"shadow_mode": "off"}), "Stop (auto)": (300, {300: lambda p, c: setattr(c, "auto", False)}, {"shadow_mode": "auto"}), "Off": (300, {300: act("car_mode", "off")}, {}), "shadow on": (300, {300: lambda p, c: c.o.__setitem__("shadow_mode", "on")}, {}), "latch": (300, {300: lambda p, c: setattr(c.circ_wd, "tripped", True)}, {}), "charger error": (300, {300: _err}, {}), "unplug": (300, {300: lambda p, c: p.ch.unplug()}, {}), "meter stale": (514, {200: _meter_off}, ARRIVAL), "charger back": (420, {240: lambda p, c: p.ch.go_unavailable(True), 300: lambda p, c: p.ch.set_current(16), 420: lambda p, c: p.ch.go_unavailable(False)}, {}), "HA back": (420, {240: lambda p, c: setattr(p, "ha_down", True), 300: lambda p, c: p.ch.set_current(16), 420: lambda p, c: setattr(p, "ha_down", False)}, {}), } for name, (t0, ev, opts) in PATHS.items(): for kind in ("error", "ignore"): sim = TSim(setpoint_a=0, windows=[(t0, t0 + 6.0, kind)]) rr = std(t0 + 150, sim=sim, events=ev, opts=opts) w = [(t, a, ok) for t, a, ok in cur_writes(rr) if t >= t0 - 1] rel = [(round(t - w[0][0]), a, ok) for t, a, ok in w] if w else [] check(f"T36 [{name}, {kind}]: the way-out 0 A not taken at t, tried " f"again at t + 60 s and taken; 0 A and the car at 0 W by " f"t + 70 s; nothing more ({w})", rel == [(0, 0.0, False), (60, 0.0, True)] and present(nth(w, 0)) and abs(nth(w, 0)[0] - t0) <= 1 and rr["sim"].setpoint_a == 0.0 and rr["sim"].power_w == 0.0) n = LOG.mark() blk = {} sim = TSim(setpoint_a=0, windows=[(t0, t0 + 400.0, "error")]) ev2 = dict(ev) ev2[t0 + 190] = lambda p, c: blk.update(b=homeview.car_block(c, None), rows=c.checks()) rr = std(t0 + 200, sim=sim, events=ev2, opts=opts) w = [(round(t - t0), a, ok) for t, a, ok in cur_writes(rr) if t >= t0 - 1] warn = [m for m in LOG.since(n, "WARNING") if "CHARGER_REFUSED" in m] check(f"T36 [{name}, kept]: tries at t, t+60, t+120, then the gave-up row " f"and one CHARGER_REFUSED warning; the card does not say paused " f"({w}, {blk.get('b', {}).get('why')!r})", len(w) == 3 and abs(w[0][0]) <= 1 and [d - w[0][0] for d, a, ok in w] == [0, 60, 120] and all(a == 0.0 and not ok for _, a, ok in w) and len(warn) == 1 and "charger_refused" in [x["id"] for x in blk.get("rows", [])] and "paused" not in blk.get("b", {}).get("why", "paused")) # Review round 1, Major 2 (mutant mE): an exit after a given-up non-zero write. # Solar at 10 A; 13 A refused at 200, 260 and 320 s (given up); Off at 340 s: # its 0 A has its own tries and goes out at once (N9). simE = TSim(setpoint_a=0, windows=[(195.0, 330.0, "error")]) rE = std(600, sim=simE, sun=step_fn((200, 3600.0), base=2900.0), events={340: act("car_mode", "off")}) aE = attempts(rE) eo = [(t, v) for t, v in aE if t >= 340] check(f"T36 [exit after a given-up write]: 13 A refused three times, then " f"Off: the 0 A at once (340 s) and the charger at 0 A ({aE})", [v for t, v in aE if 195 <= t < 340] == [13.0, 13.0, 13.0] and present(nth(eo, 0)) and nth(eo, 0)[1] == 0.0 and nth(eo, 0)[0] <= 342 and simE.setpoint_a == 0.0) # Review round 1, Major 4 (mutant mC): shutdown in Off while the exit 0 A is # still owed: tried before the inverters' 0 W (E9, D3, N9). simC = TSim(setpoint_a=0, windows=[(299.0, 1e9, "error")]) rC = std(330, sim=simC, events={300: act("car_mode", "off")}, finale=_shutdown) oC = sets_order(rC) zC = [i for i, (t, e, v) in enumerate(oC) if e == SET and v == 0.0 and t >= 329] iC = [i for i, (t, e, v) in enumerate(oC) if e.startswith("number.sp_") and v == 0.0 and t >= 329] check(f"T23/T36 [shutdown in Off, the 0 A still owed]: tried (3 times) " f"before the inverters' 0 W ({[x for x in oC if x[0] >= 329][:6]})", len(zC) == 3 and present(nth(iC, 0)) and nth(zC, 0) < nth(iC, 0)) # T37: shutdown while a start write waits for its read-back. async def _start_then_shutdown(p, c): """The cycle of 120 s starts the 10 A write; the add-on stops while it waits for its read-back (the model's sleep yields, as a real one).""" async def sleep(s): p.ch.tick(s) p.clock[0] += s p.t = p.clock[0] await asyncio.sleep(0) c.charger._sleep = sleep p.ch.tick(1.0) p.clock[0] = p.t = 120.0 await c.read_inputs(now_mono=120.0) await c.cycle() for _ in range(200): # the 10 A write is out, unconfirmed await asyncio.sleep(0) if c.car_solar.sent_a == 10.0: break for _ in range(3): await asyncio.sleep(0) p.inflight = (c.car_solar.sent_a, c.car_solar.taken) await c.shutdown() p.ch.tick(30) sim37 = SimCharger(setpoint_a=0) sim37.lag_s = 8.0 r37 = run("T37", std, 120, sim=sim37, finale=_start_then_shutdown) check(f"T37: shutdown while the 0 -> 10 A start write waits for its " f"read-back (lag 8 s): release writes 0 A and the charger ends at 0 A " f"({getattr(r37['plant'], 'inflight', None)}, " f"{[(x[0], x[2]) for x in sim37.log]}, sp {sim37.setpoint_a})", getattr(r37["plant"], "inflight", None) == (10.0, False) and [x[2] for x in sim37.log][-1:] == [0.0] and sim37.setpoint_a == 0.0) # C1 (SPIKE-05, brief v5): a start-up after a stop with no release. import opt11_identity as rig # noqa: E402 def _store(mode, pending=None): st = rig._Store() st.data["car_mode"] = mode if pending is not None: st.data[ctl_car.CAR_EXIT_KEY] = pending return st for pending, name in ((True, "Off, flag set, charger at 10 A -> 0 A written"), (False, "Off, no flag -> nothing")): simc = TSim(setpoint_a=10, windows=[(0.0, 2.5, "error")]) rr = std(200, sim=simc, mode="off", store=_store("off", pending)) w = cur_writes(rr) if pending: check(f"C1 [{name}]: the 0 A at the first reading, refused, tried " f"again 60 s later and taken; the flag cleared ({w})", [(round(t), a, ok) for t, a, ok in w] in ([(0, 0.0, False), (60, 0.0, True)], [(1, 0.0, False), (61, 0.0, True)]) and simc.setpoint_a == 0.0 and rr["store"].data.get(ctl_car.CAR_EXIT_KEY) is False) else: check(f"C1 [{name}]: nothing written (N10) ({simc.log})", simc.log == [] and simc.setpoint_a == 10.0) # The PM's shape: Solar at 10 A, Off whose 0 A is refused, a power cut before # the retry; the restart (keep) in Off writes the 0 A. simp = TSim(setpoint_a=0, windows=[(300.0, 1e9, "error")]) rp = std(330, sim=simp, events={300: act("car_mode", "off")}) flag = rp["store"].data.get(ctl_car.CAR_EXIT_KEY) simp.windows = [] n0 = len(simp.log) rq = std(100, sim=simp, store=rp["store"], mode="off") new = [(x[0], x[2]) for x in simp.log[n0:]] check(f"C1: Off whose 0 A was refused, a power cut before its retry: the flag " f"is kept ({flag}), and the restart in Off writes the 0 A at once " f"({new})", flag is True and new[:1] and new[0][1] == 0.0 and simp.setpoint_a == 0.0) # Shadow or control stopped at the start: no write, one warning. for stored, opts, ev, warn in ( ("solar", {"shadow_mode": "on"}, {}, True), ("manual", {"shadow_mode": "on"}, {}, True), ("solar", {"shadow_mode": "auto"}, {0: lambda p, c: setattr(c, "auto", False)}, True), ("off", {"shadow_mode": "on"}, {}, False)): n = LOG.mark() simw = SimCharger(setpoint_a=10) rr = std(120, sim=simw, opts=opts, events=ev, mode=stored) wl = [m for m in LOG.since(n, "WARNING") if "CHARGER_START_CURRENT" in m] notes_ = [x for _, x in rr["raised"] if x == messages.ID_CAR_START] check(f"C1 [stored {stored}, {opts.get('shadow_mode')}" f"{', stopped' if ev else ''}]: nothing written; " f"{'one warning' if warn else 'no warning'} " f"({len(wl)} log, {len(notes_)} notice)", simw.log == [] and len(wl) == (1 if warn else 0) and len(notes_) == (1 if warn else 0)) check("C1: the warning's words, EN and NL", messages.car_start_current("10").body == "Charger still at 10 A from before the restart." and "10 A" in messages.car_start_current("10").body_nl) # C5: each shutdown try waits at most 4 s for its read-back, so three fit in # 15 s against a charger that ignores the write. sim5 = TSim(setpoint_a=0, windows=[(299.5, 1e9, "ignore")]) r5 = run("C5", std, 300, sim=sim5, finale=_shutdown) tr5 = [t for t, v in attempts(r5) if t >= 299] check(f"C5: a charger that ignores the 0 A: three tries ({tr5}) about 5 s " f"apart, each waiting 4 s at most, the inverters by 15 s " f"(+{_until(r5, 299.0)})", len(tr5) == 3 and all(4.0 <= b - a <= 6.0 for a, b in zip(tr5, tr5[1:])) and present(given(_until(r5, 299.0))) and _until(r5, 299.0) <= 15.0) # C8: a charger outage in the middle of a phase change ends it; the first # write after the return is never a current (N12). for stage, dt in (("zero", 2), ("settle", 6)): sim8 = SimCharger(setpoint_a=0) sim8.ramp_w_s = 600.0 rr = std(900, sun=step_fn((400, 600.0 + 4500.0), base=600.0 + 3000.0), sim=sim8, events={580 + dt: lambda p, c: p.ch.go_unavailable(True), 620: lambda p, c: p.ch.go_unavailable(False)}) w = [(t, a) for t, a, _ in cur_writes(rr) if t >= 620] check(f"C8 [{stage}]: the charger away from 580 + {dt} s to 620 s: the " f"sequence ends, nothing of it resumes: before the start rule's " f"120 s from the return only a 0 A may be written (here the " f"charger came back at the sequence's 0 A) ({w})", not [a for t, a in w if a > 0.0 and t < 740.0] and rr["trace"][625]["sp"] == 0.0) # C9: Solar's 6 A lands late, then its 0 A pause is refused, then Off: the # exit 0 A and its retry still come (decided from the read-back). sim9 = SimCharger(setpoint_a=0) r9 = std(500, sim=sim9, sun=step_fn((190, 600.0 + 700.0), base=600.0 + 2300.0), opts={"ev_pause_min": 1}, events={185: lambda p, c: setattr(p.ch, "lag_s", 12.0), 205: lambda p, c: setattr(p.ch, "lag_s", 0.0), 249: lambda p, c: setattr(p.ch, "refuse", "error"), 255: act("car_mode", "off"), 257: lambda p, c: setattr(p.ch, "refuse", None)}) w9 = cur_writes(r9) z9 = [(t, ok) for t, a, ok in w9 if a == 0.0] check(f"C9: the 6 A late, the pause's 0 A refused, then Off: the 0 A is " f"tried again 60 s after the refusal and taken; the charger ends at " f"0 A ({w9})", len(z9) == 2 and present(nth(z9, 0)) and nth(z9, 0)[1] is False and nth(z9, 1)[1] is True and 59 <= nth(z9, 1)[0] - nth(z9, 0)[0] <= 61 and sim9.setpoint_a == 0.0) # T61: the start-up in Solar after a stop with no release. for k, sp, kw in (("10 A, keep", 10, {}), ("16 A by another writer", 16, {}), ("shadow on (option)", 16, {"opts": {"shadow_mode": "on"}}), ("shadow auto, control stopped", 16, {"opts": {"shadow_mode": "auto"}, "stopped": True}), ("ev_mode_start off", 10, {"opts": {"ev_mode_start": "off"}})): n = LOG.mark() sim61 = SimCharger(setpoint_a=sp) opts = kw.get("opts", {}) ev = {0: lambda p, c: setattr(c, "auto", False)} if kw.get("stopped") \ else {} rr = std(300, sim=sim61, opts=opts, events=ev) w = cur_writes(rr) other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m] if "shadow" in k or "off" in k: check(f"T61 [{k}]: nothing written ({w})", sim61.log == []) else: check(f"T61 [{k}]: D2: the first charger write is 0 A within 1 cycle " f"of the first reading, then only the start rule; no " f"CHARGER_OTHER ({w})", present(nth(w, 0)) and nth(w, 0)[1] == 0.0 and nth(w, 0)[0] <= 1.0 and [(t, a) for t, a, _ in w[1:]] == [(120.0, 10.0)] and not other) report()