"""EV-52: one plain info line when the add-on writes a new car current, and one when the car mode changes. `python3 -B test_ev52.py` Logging only: no write, no time and no notification changes (T43-T45 pin that against golden lists taken on the base build 02166e2). The real Controller on `tools/ev20_sun.py` (a model clock, the charger model, one 1 s cycle), as test_ev20.py and test_ev21_paths.py use it; a few rows call the writer's own `_write` from the run's finale or on a stub driver. Time is the model clock throughout, never x10 and never wall time. Rows T1-T45 and N1-N11 of reports/EV-52-test-plan.md, with T23 as PM ruling Q2 changed it: a write the charger took late logs its line ONCE, at the accept. A "line" is an INFO record that starts `Car: set`; a "mode line" one that starts `Car mode is now`; each is placed on the cycle second it was logged in (None: before the first cycle or in the finale). Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). """ import asyncio import os import re import sys 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, chargers as CH, ctl_car # noqa: E402 import ev20_sun as S # noqa: E402 import ev21_kit as K # noqa: E402 from chargersim import SimCharger # noqa: E402 from ev20_kit import (LOG, check, fails, const, step_fn, act, # noqa: E402 report) SET = S.SET SETP = "Car: set" MODEP = "Car mode is now" MOPT = {"ev_phases": "1"} # a one-phase installation ALL = [] # every run of this file, for N2 / N10 # The reason a caller names; the base build (no line) takes no such argument, # so its rows read red there instead of crashing. WHY = {"why": "Manual"} if hasattr(carmode.ManualWriter, "_log_set") else {} # ------------------------------------------------------------------ helpers def _stamp(): n0, stamps = LOG.mark(), {} def oc(p, c, t): stamps[t] = LOG.mark() return n0, stamps, oc def _tag(r, n0, stamps): ts = sorted(stamps) out = [] for i in range(n0, len(LOG.rec)): lv, m, _x = LOG.rec[i] out.append((next((t for t in ts if stamps[t] > i), None), lv, m)) r["lines"], r["n0"], r["end"] = out, n0, len(LOG.rec) ALL.append(r) return r def run(mode, dur, house=900.0, sun=0.0, events=None, **kw): n0, stamps, oc = _stamp() r = S.drive(house if callable(house) else const(house), sun if callable(sun) else const(sun), dur=dur, mode=mode, events=events, on_cycle=oc, **kw) return _tag(r, n0, stamps) def kdrive(house, sun, **kw): n0, stamps, oc = _stamp() r = K.drive(house, sun, on_cycle=oc, **kw) return _tag(r, n0, stamps) def kshape(kind, **kw): n0, stamps, oc = _stamp() r = K.shape(kind, on_cycle=oc, **kw) return _tag(r, n0, stamps) def sets(r, lo=None, hi=None): return [(t, m) for t, lv, m in r["lines"] if m.startswith(SETP) and (lo is None or (t if t is not None else 1e12) >= lo) and (hi is None or (t if t is not None else 1e12) < hi)] def texts(r, **kw): return [m for _t, m in sets(r, **kw)] def modes(r): return [(t, m) for t, lv, m in r["lines"] if m.startswith(MODEP)] def taken(r): """Every current write the charger took, Manual's and Solar's.""" return [x for w in (r["c"].car_writer, r["c"].car_solar) for x in w.log if x[0] == "current" and x[3]] def warns(r, text): return [m for _t, lv, m in r["lines"] if lv == "WARNING" and text in m] def wlist(r): return [(round(t), v) for t, v in S.writes(r)] def amps_in(m): return float(re.search(r" to (\d+) A", m).group(1)) MANUAL = {10: act("car_phases", 1), 15: act("car_current", 6), 20: act("car_mode", "manual")} def manual(dur, events=None, **kw): ev = dict(MANUAL) ev.update(events or {}) kw.setdefault("setpoint", 10) kw.setdefault("phases", 1) kw.setdefault("car_phases", 1) kw.setdefault("opts", MOPT) return run("off", dur, events=ev, **kw) def solar(dur, house=900.0, sun=7900.0, **kw): kw.setdefault("first", "car") kw.setdefault("phases", 1) kw.setdefault("car_phases", 1) kw.setdefault("opts", MOPT) return run("solar", dur, house=house, sun=sun, **kw) def both(*fns): async def f(p, c): for fn in fns: x = fn(p, c) if asyncio.iscoroutine(x): await x return f async def _shutdown(p, c): await c.shutdown() def refuse(kind): def f(p, c): p.ch.refuse = kind return f def lift(p, c): p.ch.refuse = None # =========================================================================== # print("1. MANUAL: A NEW CURRENT LOGS ONE LINE (T1-T3)") # =========================================================================== # r1 = manual(500, events={200: act("car_current", 8), 300: act("car_current", 8)}) s1 = sets(r1) check(f"T1: Manual 10 -> 6 A (user set 6 A, then Manual), 180 cycles: exactly " f"1 line, old 10 A, 1 phase, Manual ({texts(r1, hi=200)})", texts(r1, hi=200) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."]) check(f"T1: logged in the writer's own step at the action's cycle " f"({s1[:1]}) at INFO, and it equals what was sent " f"({r1['c'].charger.sent[:1]})", [t for t, _m in s1[:1]] == [20] and r1["c"].charger.sent[0] == 6.0 and all(lv == "INFO" for _t, lv, m in r1["lines"] if m.startswith(SETP))) check(f"T2: the user sets 8 A: exactly 1 more line, 6 -> 8, Manual " f"({texts(r1, lo=200)})", texts(r1, lo=200) == ["Car: set from 6 A to 8 A on 1 phase (Manual)."]) check(f"T3: the same 8 A again and 200 more cycles: 0 new lines and 0 new " f"writes ({len(s1)} lines, {len(wlist(r1))} writes)", len(sets(r1, lo=300)) == 0 and len(wlist(r1)) == 2) check("T3/N4: one line per taken write, none per cycle", len(s1) == len(taken(r1)) == 2) check("T1: the mode line comes with the action", [m for t, m in modes(r1) if t == 20] == ["Car mode is now Manual."]) # T24 / T25: the old value, or the phases, unknown. The writer's own `_write` # from the finale: no old value, then no reading at all. async def _unknown(p, c): w = c.car_writer await w._write(c.charger, 7.0, None, 400.0, c.car, **WHY) w._r = None await w._write(c.charger, 9.0, None, 401.0, c.car, **WHY) r24 = manual(150, finale=_unknown) check(f"T24/T25: the old value unknown: 'set to 7 A on 1 phase'; no reading, " f"so no phase count either: 'set to 9 A (Manual)'; no exception " f"({[m for t, m in sets(r24) if t is None]})", [m for t, m in sets(r24) if t is None] == [ "Car: set to 7 A on 1 phase (Manual).", "Car: set to 9 A (Manual)."]) def _odd(): w = carmode.ManualWriter() n0 = LOG.mark() for a, was, n in ((float("nan"), 6.0, 1), (None, 6.0, 1), ("x", None, 3), (6.0, float("inf"), "1"), (6.0, 6.0, 1)): if hasattr(w, "_log_set"): # the base build has none: red, not a crash w._log_set(a, was, "Manual", n) return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)] check(f"N9: a NaN, None, text or infinite figure never raises and logs " f"nothing wrong; an unchanged value logs nothing ({_odd()})", _odd() == ["Car: set to 6 A (Manual)."]) # =========================================================================== # print("\n2. THE MODE (T4-T6, T31)") # =========================================================================== # r4 = manual(200, events={100: act("car_mode", "manual"), 110: act("car_current", 9), 120: act("car_phases", 1), 130: act("car_sun_first", "car"), 140: act("car_mode", "bogus"), 150: act("car_current", 9)}) check(f"T4: Off -> Manual: exactly 1 mode line at the action ({modes(r4)})", [m for t, m in modes(r4) if t == 20] == ["Car mode is now Manual."]) check(f"T4: the add-on's start logs the mode it started in, once " f"({modes(r4)[:1]})", modes(r4)[:1] == [(0.0, "Car mode is now Off.")]) check(f"T5: Manual picked again, a value, the phases, Sun first and a bad " f"mode: no mode line ({modes(r4)})", len(modes(r4)) == 2) r6 = run("off", 300, events={20: act("car_mode", "manual"), 40: act("car_current", 9)}, opts={"ev_charger": "off"}) check(f"T6/N6: no charger: no car line, no mode line, not at start-up " f"either ({[m for _t, _l, m in r6['lines'] if m.startswith(('Car:', MODEP))]})", not [m for _t, _l, m in r6["lines"] if m.startswith(("Car:", MODEP))] and not wlist(r6)) r31 = run("solar", 60, opts=dict(MOPT, ev_mode_start="off"), first="car", phases=1, car_phases=1) check(f"T31: ev_mode_start off with Solar stored: one mode line, Off " f"({modes(r31)})", [m for _t, m in modes(r31)] == ["Car mode is now Off."]) # =========================================================================== # print("\n3. SOLAR (T7-T10, T14, T26)") # =========================================================================== # r7 = solar(700) t7 = sets(r7)[0][0] if sets(r7) else -10 ** 6 check(f"T7: Solar, Car first, spare sun, charger at 0 A: exactly 1 line for " f"the start current ({texts(r7)})", texts(r7) == ["Car: set from 0 A to 16 A on 1 phase (Solar)."]) check(f"T7: the line is in the step of the write ({t7}; write {wlist(r7)})", wlist(r7) == [(t7 + 1, 16)]) check("T9: Solar steady, 580 cycles after the start: 0 new lines", len(sets(r7, lo=t7 + 1)) == 0) check("T7: the mode line once, at start-up", [m for _t, m in modes(r7)] == ["Car mode is now Solar."]) def cloud_house(t): return 900.0 + 800.0 if 300 <= t < 720 else 900.0 r8 = solar(900, house=cloud_house, sun=3400.0) check(f"T8: Solar steady, a cloud (the house imports 800 W for 420 s): one " f"line per taken write, each Solar ({texts(r8)}, taken " f"{len(taken(r8))})", len(sets(r8)) == len(taken(r8)) and len(sets(r8)) >= 2 and all(m.endswith("(Solar).") for m in texts(r8))) def dither(t): return 900.0 + 2300.0 + 100.0 + (0.0 if int(t // 7) % 2 else -10.0) r10 = solar(900, sun=dither) ln = [t for t, _m in sets(r10)] gaps = [b - a for a, b in zip(ln, ln[1:])] check(f"T10: spare dithering on an amp boundary: lines == taken writes " f"({len(ln)}), at most one per SOLAR_WRITE_S ({gaps}); it fired " f"{len(ln)} times in 900 s", len(ln) == len(taken(r10)) and all(g >= carmode.SOLAR_WRITE_S - 1 for g in gaps)) r14 = run("solar", 900, sun=9600.0, first="car", phases=1, car_phases=3) t14 = texts(r14) z14 = [m for m in t14 if " to 0 A on 1 phase (Solar)" in m] c14 = [m for m in t14 if "on 3 phases (Solar)" in m] check(f"T14: Solar auto 1 -> 3 phases: one 0 A line on 1 phase, one close on " f"3 phases, nothing else ({t14}; selects {S.writes(r14, 'phases')})", len(S.writes(r14, "phases")) == 1 and len(z14) == 1 and len(c14) == 1 and len(t14) == 3 and t14.index(z14[0]) < t14.index(c14[0])) check("T12: the select itself logs nothing: one line per taken current write", len(sets(r14)) == len(taken(r14))) r26 = solar(300, sun=0.0, setpoint=0) check(f"T26: Solar, the charger already shows the 0 A Solar wants: no write, " f"0 lines ({texts(r26)}, writes {wlist(r26)})", not texts(r26) and not wlist(r26)) # =========================================================================== # print("\n4. MANUAL PHASE CHANGE (T11-T13, T42)") # =========================================================================== # r11 = manual(300, events={200: act("car_phases", 3)}, car_phases=3, opts={}) t11 = texts(r11, lo=200) s11 = [t for t, _m in sets(r11, lo=200)] check(f"T11: Manual 6 A on 1 phase, the user picks 3 phases, the car stops: " f"exactly 2 lines, the 0 A on 1 phase and the 6 A on 3 ({t11})", t11 == ["Car: set from 6 A to 0 A on 1 phase (Manual).", "Car: set from 0 A to 6 A on 3 phases (Manual)."]) check(f"T11/T12: the 0 A logs as a write; the close comes after the select " f"and the 10 s settle, the select itself logs nothing ({s11}; selects " f"{S.writes(r11, 'phases')})", len(s11) == 2 and s11[1] - s11[0] >= carmode.SETTLE_S and len(S.writes(r11, "phases")) == 1) def drawing(p, c): p.ch.ramp_w_s = 0.0001 # the car does not let go r13 = manual(400, events={200: both(drawing, act("car_phases", 3))}, car_phases=3, opts={}) t13 = texts(r13, lo=200) check(f"T13: the car keeps drawing: the 0 A line, the existing warning once, " f"the restore line on 1 phase ({t13})", t13 == ["Car: set from 6 A to 0 A on 1 phase (Manual).", "Car: set from 0 A to 6 A on 1 phase (Manual)."] and len(warns(r13, "The car kept drawing, so the phases were not " "changed.")) == 1) def shadow_on(p, c): c.o["shadow_mode"] = "on" r42 = manual(260, events={200: act("car_phases", 3), 201: shadow_on}, car_phases=3, opts={}) t42 = texts(r42, lo=200) check(f"T42: shadow mode in the middle of a phase change: the 0 A and the one " f"write shadow allows, Manual's undo: 2 lines, then none ({t42})", t42 == ["Car: set from 6 A to 0 A on 1 phase (Manual).", "Car: set from 0 A to 6 A on 1 phase (Manual)."] and not S.writes(r42, "phases")) # =========================================================================== # print("\n5. THE PEAK CUT (T15-T17, T41)") # =========================================================================== # r15 = kdrive(step_fn((960, 900.0 + 5700.0), (966, 900.0 + 9000.0), base=900.0), const(13000.0), dur=1100, first="car", phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"}, events={958: lambda p, c: setattr(c.car_solar, "nonzero_at", p.t)}) cuts = sets(r15, lo=958) wcut = [v for t, v in S.writes(r15) if t >= 958] check(f"T15: the EV-21 cut (two cuts as the excess grows): one line per cut, " f"each 'peak cut' with the value written ({[m for _t, m in cuts]}; " f"writes {wcut})", len(cuts) == len(wcut) >= 1 and all(m.endswith("(peak cut).") for _t, m in cuts) and [amps_in(m) for _t, m in cuts] == wcut) cut_note = [m for _t, lv, m in r15["lines"] if m == "Solar lowered the car for the peak: CAR_CUT."] check(f"T15: the existing CAR_CUT info line and notice once per session, " f"unchanged ({len(cut_note)}, notices " f"{[n for _t, n in r15['raised'] if 'cut' in n]})", len(cut_note) == 1) check("T15: the 16 A before the cut was Solar's own line, not a cut", texts(r15, hi=958)[-1].endswith("(Solar).") if texts(r15, hi=958) else False) r16 = kshape("C", dur=1300) c16 = texts(r16, lo=950) check(f"T16: a cut deeper than the car can follow (to 0 A): the line says " f"'to 0 A' and 'peak cut' ({c16})", c16 == ["Car: set from 10 A to 0 A on 3 phases (peak cut)."]) r18 = kshape("C", dur=1300, events={959: lambda p, c: setattr(p.ch, "refuse", "ignore")}) check(f"T18: the cut refused (3 tries 60 s apart): the existing CHARGER_REFUSED " f"once, 0 lines for the cut ({texts(r18, lo=950)}, " f"{len(warns(r18, 'CHARGER_REFUSED'))}, tries " f"{[round(t) for t, v in S.writes(r18) if t >= 959]})", not texts(r18, lo=950) and len(warns(r18, "CHARGER_REFUSED")) == 1 and len([1 for t, v in S.writes(r18) if t >= 959]) == 3) class Drv: """A driver that takes, or not, what it is given, for the writer's own steps. `write_current` notes how many log records existed when it returned (N3: the line follows the write).""" def __init__(self, ok=True): self.ok, self.sent, self.marks = ok, [], [] async def write_current(self, a, **kw): self.sent.append(a) self.marks.append(LOG.mark()) return self.ok async def write_phases(self, n): return True def reading(**kw): base = dict(available=True, state="C", power_w=0.0, phases_allowed=3, allowed_a=0.0, setpoint_a=0.0) base.update(kw) return CH.ChargerReading(**base) def tracker(): return CH.CarTracker() def go(coro): return asyncio.run(coro) # T17: the cut's cap lowers the closing current of a phase change. async def t17(): w = carmode.SolarWriter() drv, tr = Drv(), tracker() w.plan.a, w.plan.target_w, w.plan.n = 16.0, 16.0 * 230.0 * 3, 3 w.cut_a = 8.0 w.seq = {"stage": "settle", "t0": 0.0, "t1": 0.0, "n": 3, "tries": 0, "prev": None, "sel_ok": True} n0 = LOG.mark() await w._advance(drv, reading(), 0.0, 20.0, tr, w._seq_want(16.0, 3), 16.0, None) return drv, [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)] d17, l17 = go(t17()) check(f"T17: a cut due while Solar's phase change is under way: the close " f"carries 'peak cut' and the capped value, no extra line ({l17}, sent " f"{d17.sent})", l17 == ["Car: set from 0 A to 8 A on 3 phases (peak cut)."] and d17.sent == [8.0]) async def t17b(): w = carmode.SolarWriter() drv, tr = Drv(), tracker() w.plan.a, w.plan.target_w, w.plan.n = 10.0, 10.0 * 230.0 * 3, 3 w.seq = {"stage": "settle", "t0": 0.0, "t1": 0.0, "n": 3, "tries": 0, "prev": None, "sel_ok": True} n0 = LOG.mark() await w._advance(drv, reading(), 0.0, 20.0, tr, w._seq_want(16.0, 3), 16.0, None) return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)] check(f"T17: the same close with no cut: 'Solar', the plan's value " f"({go(t17b())})", go(t17b()) == ["Car: set from 0 A to 10 A on 3 phases (Solar)."]) # T41: a write either side of the quarter boundary (900): one line each. sun41 = step_fn((899, 4760.0), (931, 4100.0), base=4300.0) r41 = solar(1000, sun=sun41) l41 = sets(r41, lo=890, hi=960) check(f"T41: Solar writes at 899 and 931 across the quarter boundary: one " f"line each, no duplicate ({l41}, writes " f"{[x for x in wlist(r41) if x[0] > 890]})", len(l41) == 2 and len({m for _t, m in l41}) == 2 and len(l41) == len([1 for t, v in S.writes(r41) if t > 890])) # =========================================================================== # print("\n6. FAILED OR LATE WRITES (T19-T23, T33, T37, T39, N2, N3)") # =========================================================================== # REF = "The charger did not take the current, so the add-on stops asking" for kind in ("ignore", "error"): r19 = manual(400, events={19: refuse(kind)}) check(f"T19 [{kind}]: Manual write refused, 3 tries 60 s apart: 0 lines, " f"CHARGER_REFUSED once, text unchanged ({texts(r19)}, " f"{len(warns(r19, REF))})", not texts(r19) and len(warns(r19, REF)) == 1) r20 = manual(300, events={19: refuse("ignore"), 40: lift}) t20 = sets(r20) check(f"T20: refused once, the charger takes it at the retry: exactly 1 line, " f"at the retry, 60 s or more after the fail ({t20})", len(t20) == 1 and t20[0][0] >= 20 + 60 and t20[0][1] == "Car: set from 10 A to 6 A on 1 phase (Manual).") async def _clamp(p, c): p.clamp_ok = await c.car_writer._write(c.charger, 30.0, 10.0, 400.0, c.car) r21 = manual(120, finale=_clamp) fin = [(lv, m) for t, lv, m in r21["lines"] if t is None] check(f"T21: a write above the clamp: CHARGER_CLAMP error unchanged, nothing " f"sent, no line ({[(lv, m[:30]) for lv, m in fin]})", any(lv == "ERROR" and m.endswith("CHARGER_CLAMP.") for lv, m in fin) and not [m for lv, m in fin if m.startswith(SETP)] and r21["plant"].clamp_ok is False) class RaisingPlant(S.SunPlant): """Home Assistant whose call on the current entity raises, from 19 s.""" async def set_number(self, e, v): if e == SET and self.t >= 19.0: raise RuntimeError("HA call error") return await super().set_number(e, v) r22 = manual(200, plant_cls=RaisingPlant) check(f"T22: the driver raises in write_current: 0 lines, the existing 'step " f"failed' error once, no new exception from the log path " f"({texts(r22)})", not texts(r22) and len([1 for _t, lv, m in r22["lines"] if lv == "ERROR" and m == "The car charger step failed"]) == 1) def slow(p, c): p.ch.lag_s = 12.0 # over TOOK_S (10 s) r23 = solar(400, events={100: slow}) w23 = [(round(t), v) for t, v in S.writes(r23)] check(f"T23 (Q2): a late read-back (12 s, over TOOK_S): the write is not " f"taken at once, then adopted; exactly 1 'set' line, at the accept " f"({sets(r23)}, write {w23})", texts(r23) == ["Car: set from 0 A to 16 A on 1 phase (Solar)."] and sets(r23)[0][0] >= 120 + 10 and len(taken(r23)) == 0) check("T23 (Q2): no line at the write itself, none for the failed try", not sets(r23, hi=130)) async def t23b(): """The accept after the warning: three refused tries, then the charger shows the value (late): the warning is the existing one, then one line.""" w = carmode.SolarWriter() drv, tr = Drv(ok=False), tracker() w.engaged = True n0 = LOG.mark() for k in range(3): await w._write(drv, 16.0, 0.0, 100.0 + 70 * k, tr) mid = [m for _lv, m, _x in LOG.rec[n0:]] w._adopt(16.0) w._adopt(16.0) # a second read-back: nothing again end = [m for _lv, m, _x in LOG.rec[n0:]] return mid, end mid, end = go(t23b()) check(f"T23 (Q2): three tries not taken give the existing CHARGER_REFUSED " f"warning and no line; the accept then gives exactly one line " f"({mid} -> {end})", len(mid) == 1 and mid[0].endswith("CHARGER_REFUSED.") and end[1:] == ["Car: set from 0 A to 16 A (Solar)."]) async def t23c(): w = carmode.SolarWriter() drv, tr = Drv(ok=False), tracker() n0 = LOG.mark() await w._write(drv, 16.0, 0.0, 100.0, tr) w._adopt(10.0) # shows something else: not our write return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)] check("T23/M4: a read-back that shows another value is not an accept: 0 lines", go(t23c()) == []) # Q2 for Manual: a write taken late logs its line once, at the accept. r23m = manual(200, events={10: slow}) w23m = [(round(t), v) for t, v in S.writes(r23m)] check(f"T23 Manual (Q2): a late read-back (12 s): no line at the write, " f"exactly 1 line at the accept, a few seconds later ({sets(r23m)}, " f"write {w23m})", texts(r23m) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."] and sets(r23m)[0][0] >= 20 + 10 and len(taken(r23m)) == 0) async def t23m(): """Three tries not taken: the existing CHARGER_REFUSED warning, no line; the charger then shows the value: exactly one line, once.""" w = carmode.ManualWriter() w.boot = False drv, tr = Drv(ok=False), tracker() async def step(a, now): await w.step(drv, reading(state="C", allowed_a=a, setpoint_a=a, phases_allowed=1), mode=carmode.MANUAL, want_a=6.0, want_phases=1, rev=1, clamp=16.0, now=now, tracker=tr, writing=True, status="charging") n0 = LOG.mark() for k in range(3): await step(10.0, 100.0 + 70 * k) mid = [m for lv, m, _x in LOG.rec[n0:] if lv != "DEBUG"] await step(6.0, 300.0) await step(6.0, 310.0) # the next read-back: nothing again return mid, [m for lv, m, _x in LOG.rec[n0:] if lv != "DEBUG"] mid, end = go(t23m()) check(f"T23 Manual (Q2): three tries not taken give the existing Manual " f"CHARGER_REFUSED warning and no line; the accept then gives exactly " f"one line ({mid} -> {end})", len(mid) == 1 and mid[0].endswith("CHARGER_REFUSED.") and end[1:] == ["Car: set from 10 A to 6 A on 1 phase (Manual)."]) async def stale(shape): """Review round 2: a refused Manual try is not a request any more once the user changed something or another mode ran. Another source then shows the same value; Manual's adopt must log nothing.""" w = carmode.ManualWriter() w.boot = False drv, tr = Drv(ok=False), tracker() async def step(a, now, mode=carmode.MANUAL, rev=1): await w.step(drv, reading(state="C", allowed_a=a, setpoint_a=a, phases_allowed=1), mode=mode, want_a=6.0, want_phases=1, rev=rev, clamp=16.0, now=now, tracker=tr, writing=True, status="charging") n0 = LOG.mark() await step(10.0, 100.0) # refused if shape == "solar": # the user picks Solar, then Manual w.user_changed() await step(10.0, 200.0, mode=carmode.SOLAR, rev=2) await step(6.0, 300.0, mode=carmode.SOLAR, rev=2) # Solar's own 6 A w.user_changed() await step(6.0, 500.0, rev=3) elif shape == "off": # Off, the wallbox app sets 6 A await step(10.0, 150.0, mode=carmode.OFF) await step(6.0, 400.0, mode=carmode.OFF) await step(6.0, 500.0) else: # the user changed the value w.user_changed() await step(6.0, 500.0, rev=2) return [m for lv, m, _x in LOG.rec[n0:] if lv != "DEBUG" and m.startswith(SETP)] for shape in ("solar", "off", "user"): check(f"T23 Manual (review round 2, N2) [{shape}]: a refused try is not " f"logged later when the same value comes from another source", go(stale(shape)) == []) async def t23l(): """Review round 2: Solar's refused try is history once Solar is left; a later read-back of that value logs nothing.""" w = carmode.SolarWriter() drv, tr = Drv(ok=False), tracker() w.engaged = True n0 = LOG.mark() await w._write(drv, 16.0, 0.0, 100.0, tr) w._leave() w._adopt(16.0) return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)] check("T23 (review round 2, N2) [solar leave]: a refused Solar try is not " "logged after Solar is left: 0 lines", go(t23l()) == []) # T33: shutdown, the charger refuses all 3 release tries. async def _refuse_shutdown(p, c): p.ch.refuse = "ignore" await c.shutdown() r33 = solar(300, finale=_refuse_shutdown) check(f"T33: Solar shutdown, the charger refuses all 3 release tries: " f"CHARGER_RELEASE unchanged once, 0 shutdown lines " f"({texts(r33, lo=121)}, {len(warns(r33, 'CHARGER_RELEASE'))})", len(warns(r33, "CHARGER_RELEASE")) == 1 and not texts(r33, lo=121) and not [m for t, m in sets(r33) if "(shutdown)" in m]) # T37: stale charger reads with no write due. r37 = solar(500, events={300: lambda p, c: p.ch.freeze(), 308: lambda p, c: p.ch.freeze(False)}) check(f"T37: a frozen charger reading for 8 s with no write due: 0 lines " f"({texts(r37, lo=125)}, writes {wlist(r37)})", not texts(r37, lo=125) and len(wlist(r37)) == 1) # T39: a stuck (frozen) charger, Solar's starts are not taken. r39 = solar(1300, events={100: lambda p, c: p.ch.freeze()}) check(f"T39: a stuck charger reading, the 3 starts not taken: 0 lines, the " f"stuck CHARGER_REFUSED once, unchanged " f"({texts(r39)}, {len(warns(r39, 'CHARGER_REFUSED'))}, " f"{len([1 for t, v in S.writes(r39) if v > 0])} starts)", not texts(r39) and len(warns(r39, "CHARGER_REFUSED")) == 1) # N3: the line follows the write: nothing is logged before it returns. async def n3(): w = carmode.ManualWriter() drv, tr = Drv(), tracker() n0 = LOG.mark() await w._write(drv, 7.0, 10.0, 50.0, tr, **WHY) rec = LOG.rec[n0:] first = next((i for i, x in enumerate(rec) if x[1].startswith(SETP)), 10 ** 9) return n0 + first, drv.marks[0] at, ret = go(n3()) check(f"N3: the line is logged after write_current returned (record {at} vs " f"the driver's return at {ret})", ret <= at < 10 ** 8) # =========================================================================== # print("\n7. START-UP, SHUTDOWN, WAYS OUT (T27-T30, T32, T34-T36, T38, T40)") # =========================================================================== # st27 = S.rig._Store() st27.data["car_current"] = 6.0 r27 = run("manual", 120, store=st27, setpoint=10, phases=1, car_phases=1, opts=MOPT) check(f"T27: restart in Manual, stored 6 A, the charger shows 10 A: 1 mode " f"line at start-up, exactly 1 line, 'start-up' " f"({modes(r27)}, {texts(r27)})", [m for _t, m in modes(r27)] == ["Car mode is now Manual."] and texts(r27) == ["Car: set from 10 A to 6 A on 1 phase (start-up)."]) r28 = solar(400, setpoint=10) check(f"T28: restart in Solar, the charger shows its own 10 A (D2): the mode " f"line, the 0 A as 'start-up', the start current as 'Solar' " f"({texts(r28)})", [m for _t, m in modes(r28)] == ["Car mode is now Solar."] and texts(r28) == ["Car: set from 10 A to 0 A on 1 phase (start-up).", "Car: set from 0 A to 16 A on 1 phase (Solar)."]) st29 = S.rig._Store() st29.data[ctl_car.CAR_EXIT_KEY] = True r29 = run("off", 120, store=st29, setpoint=10, phases=1, car_phases=1, opts=MOPT) check(f"T29: restart in Off with the exit 0 A owed (C1), charger 10 A: the " f"mode line Off and 1 line 'to 0 A (start-up)' " f"({modes(r29)}, {texts(r29)})", [m for _t, m in modes(r29)] == ["Car mode is now Off."] and texts(r29) == ["Car: set from 10 A to 0 A on 1 phase (start-up)."]) r30 = run("off", 2000, events={1800: act("car_mode", "manual")}, setpoint=10, phases=1, car_phases=1, opts=MOPT) check(f"T30: restart in Off, nothing owed; 30 min later the user picks " f"Manual: the start mode line once, the later write is 'Manual', not " f"'start-up' ({modes(r30)}, {texts(r30)})", [m for _t, m in modes(r30)] == ["Car mode is now Off.", "Car mode is now Manual."] and texts(r30) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."]) check("T30: the Manual line is not 'start-up' even for the first write of " "the process (M9)", bool(texts(r30)) and "start-up" not in " ".join(texts(r30))) r32 = solar(300, finale=_shutdown) check(f"T32: Solar shutdown, 0 A taken: 1 line 'to 0 A ... (shutdown)' " f"({texts(r32, lo=121)}, {[t for t, m in sets(r32)]})", [m for t, m in sets(r32) if t is None] == [ "Car: set from 16 A to 0 A on 1 phase (shutdown)."]) r34 = manual(205, events={200: act("car_phases", 3)}, car_phases=3, opts={}, finale=_shutdown) check(f"T34: Manual shutdown in the middle of a phase change (abandon), the " f"give-back taken: 1 line, 'shutdown' ({texts(r34, lo=200)})", [m for t, m in sets(r34) if t is None] == [ "Car: set from 0 A to 6 A on 3 phases (shutdown)."]) r35 = solar(400, events={300: act("car_mode", "off")}) check(f"T35: Solar -> Off while Solar's 16 A stands: 1 mode line Off, 1 line " f"'to 0 A (Solar)' (Q3), then nothing ({modes(r35)[-1:]}, " f"{texts(r35, lo=300)})", [m for _t, m in modes(r35)[-1:]] == ["Car mode is now Off."] and texts(r35, lo=300) == [ "Car: set from 16 A to 0 A on 1 phase (Solar)."]) r36 = solar(400, events={300: act("car_mode", "manual")}) check(f"T36: Solar -> Manual (user 6 A, charger 16 A): 1 mode line and 1 line " f"for Manual's 6 A, reason Manual ({modes(r36)[-1:]}, " f"{texts(r36, lo=300)})", [m for _t, m in modes(r36)[-1:]] == ["Car mode is now Manual."] and texts(r36, lo=300) == [ "Car: set from 16 A to 6 A on 1 phase (Manual)."]) r38 = kshape("C", dur=1400, events={940: lambda p, c: setattr(p, "meter_on", False)}) check(f"T38: the meter silent past meter_max_age_s: Solar's pause, exactly 1 " f"line 'to 0 A (Solar)' ({texts(r38, lo=940)})", texts(r38, lo=940) == [ "Car: set from 10 A to 0 A on 3 phases (Solar)."]) class Liar(SimCharger): """The read-back shows what was asked; the car draws a third more.""" def target_w(self): w = super().target_w() return w * 8.0 / 6.0 if self.setpoint_a == 6.0 else w r40 = manual(120, sim=Liar(setpoint_a=10)) check(f"T40: the read-back shows 6 A but the car draws 8 A (1840 W): the line " f"says 6 A, what was written ({texts(r40)}, car " f"{round(r40['trace'][-1]['car'])} W)", texts(r40) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."] and round(r40["trace"][-1]["car"]) == 1840) # =========================================================================== # print("\n8. NOTHING ELSE MOVES (T43-T45, N1, N2, N7, N8, N10, N11)") # =========================================================================== # # N5: a mode line only for a mode change (and the one at start-up). chg4 = 1 + 1 # r4: the start, then Off -> Manual check(f"N5: no mode line without a change: {len(modes(r4))} in r4 (start + " f"the one change, six more same-mode or refused actions), " f"{len(modes(r7))} in a 700 s Solar run with no action, " f"{len(modes(r1))} in r1 (start + Manual, two same-value actions)", len(modes(r4)) == chg4 and len(modes(r7)) == 1 and len(modes(r1)) == 2 and len(modes(r30)) == 2) # N8: the existing warning and info texts are the base's, word for word. EXACT = { "The charger did not take the current, so the add-on stops asking until " "you change it: CHARGER_REFUSED.", "The charger did not take the current, so the add-on stops asking until " "you press Solar: CHARGER_REFUSED.", "The charger did not take the current, so the add-on tries again in 15 " "min, then every 30 min: CHARGER_REFUSED.", "The charger did not take 0 A before the add-on stopped, so the car may " "still be charging: CHARGER_RELEASE.", "Software fault: the add-on was about to ask the charger for more than " "its limit, so nothing was sent: CHARGER_CLAMP.", "Solar lowered the car for the peak: CAR_CUT.", "The car kept drawing, so the phases were not changed."} seen8 = {m for r in ALL for _t, lv, m in r["lines"] if lv != "DEBUG" and ("CHARGER_" in m or "CAR_CUT" in m or "kept drawing" in m)} check(f"N8: every CHARGER_* / CAR_CUT / kept-drawing line seen in any run is " f"one of base's texts, and each of the seven was seen " f"({sorted(seen8 - EXACT)[:2]}, missing {sorted(EXACT - seen8)[:2]})", seen8 == EXACT) # T44: the existing suites run unedited in CI (checks / unit) and were run # here (the report lists them). What a unit row can pin: the two existing # files this ticket had to touch still hold their own assertions and set # aside ONLY the two new prefixes. _here = os.path.dirname(os.path.abspath(__file__)) _t28 = open(os.path.join(_here, "test_ev28.py")).read() _t51 = open(os.path.join(_here, "test_ev51.py")).read() check("T44: test_ev28 and test_ev51 keep their pinned rows and filter only " "'Car: set' and 'Car mode is now'", 'check(f"T13: a clean change logs nothing at INFO or above' in _t28 and "CAP.loud(MARK[0]) == []" in _t28 and "info == BASE_INFO" in _t51 and _t28.count('("Car: set", "Car mode is now")') == 1 and _t51.count('("Car: set", "Car mode is now")') == 1) # Taken on the base build 02166e2 with EV52_GOLDEN=1 (the same scenarios). _CAR1 = ["car current set to 8 by operator", "car current set to 8 by operator", "car mode set to manual by operator", "car current set to 6 by operator", "car phases set to 1 by operator"] GOLDEN = { "T1": {"cur": [(21, 6.0), (201, 8.0)], "events": _CAR1, "keys": "bb1fe135bd15690c", "notes": [], "ph": [], "sent": [6.0, 8.0]}, "T11": {"cur": [(21, 6.0), (201, 0.0), (212, 6.0)], "events": ["car phases set to 3 by operator", "car mode set to manual by operator", "car current set to 6 by operator", "car phases set to 1 by operator"], "keys": "bb1fe135bd15690c", "notes": [], "ph": [(202, 3)], "sent": [6.0, 0.0, 6.0]}, "T15": {"cur": [(121, 16.0), (961, 13.0), (967, 12.0), (997, 6.0)], "events": [], "keys": "00425fef63358fa7", "notes": [(13, "goodwe_integrator_bound"), (961, "goodwe_car_cut")], "ph": [], "sent": [16.0, 13.0, 12.0, 6.0]}, "T28": {"cur": [(1, 0.0), (121, 16.0)], "events": [], "keys": "642fc116d64d9487", "notes": [], "ph": [], "sent": [0.0, 16.0]}, "T32": {"cur": [(121, 16.0), (300, 0.0)], "events": [], "keys": "642fc116d64d9487", "notes": [], "ph": [], "sent": [16.0, 0.0]}, "T7": {"cur": [(121, 16.0)], "events": [], "keys": "00425fef63358fa7", "notes": [], "ph": [], "sent": [16.0]}, } def view(r): return {"cur": wlist(r), "ph": [(round(t), n) for t, n in S.writes(r, "phases")], "sent": list(r["c"].charger.sent), "notes": [(round(t), n) for t, n in r["raised"]], "events": [e[9:] for e in r["c"].events if e[9:].startswith("car ")], "keys": K.digest(sorted(r["store"].data))} SCEN = {"T1": r1, "T7": r7, "T11": r11, "T15": r15, "T28": r28, "T32": r32} if os.environ.get("EV52_GOLDEN"): import json print("GOLDEN", json.dumps({k: view(v) for k, v in SCEN.items()}, sort_keys=True)) for k, r in SCEN.items(): check(f"T43/T45 {k}: the writes (value, second, phases), the notices, the " f"action log and the store keys are those of the base build", view(r) == GOLDEN.get(k)) check("N7: no new store key, notification or option (the key lists above are " "base's)", all(view(r)["keys"] == GOLDEN.get(k, {}).get("keys") for k, r in SCEN.items())) bad = [m for r in ALL for _t, lv, m in r["lines"] if m.startswith((SETP, MODEP)) and ( lv != "INFO" or re.search(r"number\.|select\.|sensor\.|http|token", m))] check(f"N10: every new line is INFO, with no entity id or secret ({bad[:2]})", not bad) n2 = [] for r in ALL: sent = {v for _t, v in S.writes(r)} | set( getattr(r["c"].charger, "sent", ())) n2 += [m for _t, m in sets(r) if amps_in(m) not in sent] check(f"N2: every line's value is a value the add-on sent ({n2[:2]})", not n2) n11 = [] for r in ALL: if r.get("sim") is None: continue n11 += [x for x in r["sim"].log if x[1] == "current" and x[2] > 16.0] n11 += [x for x in r["sim"].log if x[1] == "phases" and x[3] >= 100.0 and x[4] > 0.0] check(f"N1/N11: no write above the clamp and no select under load in any " f"run ({n11[:2]})", not n11) tb = [i for r in ALL if r is not r22 for _lv, _m, x in LOG.rec[r["n0"]:r["end"]] if x] check(f"N9: no exception from the log path in any run but T22's own " f"({len(tb)})", not tb) report()