Files
goodwe-addon/goodwe_controller/test_ev22.py
T
Claude e0e51dac12
infra-pin / fresh (pull_request) Waiting to run
checks / unit (pull_request) In progress
EV-22 review round 1: press covers one reading, unknown read keeps the count, window ends on the close's clock
Major 1: the `pressed` mark of a sequence is consumed by the first `_advance`
(the first reading judged after the press); a later raise in the same zero
stage gets the raise-check hold again (Solar and Manual).
Major 2: with `cur` None `_watch` does not judge the current: the count
neither starts nor clears (phases are still judged).
Finding 4 (PM): the DA3 window uses the close's own clock and comparison
(`now - t1 < SETTLE_S`) and the one step that closes at its end is still
inside it, so a `last_done` a fraction of a second after the step's now no
longer pushes the close step outside the window.
Tests: rows A-D, R1 (Manual red under the mutant), the two fraction rows,
all red on b7c91ff. test_ev60: comment exactly as ruled, unused imports gone.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:30:17 +01:00

1211 lines
52 KiB
Python

"""EV-22: Car Solar mode never writes over another writer; one rule of control
for the current and the phases, inside a phase change as well.
`python3 -B test_ev22.py`
Rows T1-T37 and T39-T49 and the review row "T48 (stale)" of
reports/EV-22-test-plan.md (T38, the fuzz with N1-N10, is test_ev22_fuzz.py;
T40 is the list of existing suites that must stay green and is run by CI,
test_ev20_writers T46 (a)(b)(c) being the one ruled edit). Every check's
label starts with its id.
C7: the watch runs in every step of a phase change, in both writers, with the
change's own values counted as own, and nothing is written over another
writer's value (the close, the EV-28 restore, a select). D4: Solar judges the
read-back phases like the current, against the phases it chose itself. DA1:
a press that lifts a difference inside a change ends the change at its 0 A.
DA2: the not-writing path does not judge the current with a reading from
before its own 0 A. DA3: no phase mismatch while an own select is in flight
or settling (SETTLE_S from the try's RETURN).
Harness: the real Controller on `tools/ev20_sun.py` (`std`), a 1 s cycle on a
model clock; Manual rows run the same plant with `mode="off"` and the
actions that choose Manual. Times are the cycle's second (the plant clock).
"R39": own 1 -> 3 (0 A at 580, select at 582, close at 592); "R8": the car on
3 phases, Solar selects 1 at 121 and writes 12 A at 131. `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 os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode as CM, chargers as CH # 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, _err # noqa: E402,F401
STATION = 16.0
# ----------------------------------------------------------------- harness
def setc(a):
return lambda p, c: p.ch.set_current(a)
def setph(n):
return lambda p, c: p.ch.set_phases(n)
def merge(*dicts):
"""Events of several dicts; two at one second run both."""
out = {}
for d in dicts:
for k, fn in d.items():
out[k] = both(out[k], fn) if k in out else fn
return out
def stop_ctl(p, c):
c.auto = False
def start_ctl(p, c):
c.auto = True
class XSim(SimCharger):
"""The model with phase-select refusal windows on its own clock (t0, t1,
"ignore" | "error"), and phases the charger reports as unknown."""
def __init__(self, *a, pwin=(), **kw):
super().__init__(*a, **kw)
self.pwin = list(pwin)
self.unknown = False
def request_phases(self, n):
for t0, t1, kind in self.pwin:
if t0 <= self.t <= t1:
keep, self.refuse = self.refuse, kind
try:
return super().request_phases(n)
finally:
self.refuse = keep
return super().request_phases(n)
def _build(self):
out = super()._build()
if self.unknown:
for k in list(out):
if "phases" in k and ("select." in k or "max_allowed" in k):
out[k] = dict(out[k], state="unknown")
return out
def unk(on):
def f(p, c):
p.ch.unknown = on
return f
class Rec:
"""What every cycle ended with, for both writers."""
def __init__(self):
self.d = {}
def __call__(self, p, c, t):
w, m = c.car_solar, c.car_writer
q, mq = w.seq, m.seq
self.d[int(t)] = dict(
ms=w.mismatch_since, hold=w.hold, other=w.other,
cut=c.car_solar_can_cut(), sseq=None if q is None else q["stage"],
mm=m.mismatch_since, mhold=m.hold,
mseq=None if mq is None else (mq["stage"], mq["t0"]),
own_n=getattr(w, "_own_n", None), ph=getattr(w, "_ph_diff", None),
sp=p.ch.setpoint_a,
phs=p.ch.phases_allowed)
def first(self, key, pred=lambda v: v is not None, lo=0, hi=10 ** 9):
for t in sorted(self.d):
if lo <= t <= hi and pred(self.d[t][key]):
return t
return None
def every(self, key, pred, lo, hi):
return all(pred(self.d[t][key]) for t in range(lo, hi + 1)
if t in self.d)
def other_n(n):
return len([m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m])
def after(r, t0):
"""Current writes that reached the charger and selects, from t0 on."""
return ([x for x in attempts(r) if x[0] >= t0]
+ [x for x in r["plant"].wlog if x[0] >= t0 and x[1] == "phases"])
def wl(r, what="current"):
return [(x[0], x[2]) for x in r["plant"].wlog if x[1] == what]
def solar(dur, events=None, rec=None, race=False, **kw):
kw.setdefault("rows", True)
return std(dur, race=race, events=events or {}, on_cycle=rec, **kw)
R39 = step_fn((400, 600.0 + 4600.0), base=600.0 + 1840.0)
TS = 582 # R39: its select; the close is at 592 (own 6 A)
EXITS = {"Stop": stop_ctl,
"shadow on": lambda p, c: c.o.__setitem__("shadow_mode", "on"),
"latch": lambda p, c: setattr(c.circ_wd, "tripped", True),
"Off": act("car_mode", "off"),
"charger error": _err}
def man(dur, events=None, rec=None, race=False, sim=None):
"""Manual, 12 A on 1 phase from 0 s; the user picks 3 phases at 100 s:
0 A at 100, select at 101, close at 111 (R-M)."""
base = {0: both(act("car_mode", "manual"), act("car_current", 12),
act("car_phases", 1)),
100: act("car_phases", 3)}
return S.drive(const(500.0), const(500.0), dur=dur, mode="off",
first="car", socs=dict(FULL), phases=1, sim=sim,
events=merge(base, events or {}), on_cycle=rec, race=race)
def slow_sim():
s = SimCharger(setpoint_a=0)
s.ramp_w_s, s.stop_delay_s = 50.0, 40.0
return s
# =========================================================================== #
print("PRECONDITIONS")
# =========================================================================== #
rp = man(160, rec=Rec())
check(f"PRE: Manual's change: 0 A at 100, select at 101, close at 111 "
f"({wl(rp)}, {wl(rp, 'phases')})",
wl(rp) == [(0.0, 12.0), (100.0, 0.0), (111.0, 12.0)]
and wl(rp, "phases") == [(101.0, 3)])
rs = solar(700, sun=R39)
check(f"PRE: R39: 0 A at 580, select at {TS}, close at 592 "
f"({[x[:3] for x in rs['c'].car_solar.log]})",
[x[:3] for x in rs["c"].car_solar.log if x[0] == "phases"]
== [("phases", 3, float(TS))]
and (592.0, 6.0) in [(x[2], x[1]) for x in rs["c"].car_solar.log
if x[0] == "current"])
# =========================================================================== #
print("\nC7, MANUAL (T1-T8)")
# =========================================================================== #
for race in (False, True):
tag = "race" if race else "step"
rec = Rec()
r = man(400, {104: setc(9)}, rec=rec, race=race)
mm, ho = rec.first("mm"), rec.first("mhold", lambda v: v)
check(f"T1 [{tag}]: another writer's 9 A inside Manual's settle: no write "
f"from 104 on, mismatch from {mm}, the hold at {ho} (30 s later, "
f"not 29), 9 A stands ({[x for x in after(r, 104)]})",
after(r, 104) == [] and mm is not None and 104 <= mm <= 105
and ho is not None and 30 <= ho - mm <= 31
and r["sim"].setpoint_a == 9.0 and r["c"].car_writer.other)
rec = Rec()
r = man(300, {104: setc(9), 119: setc(0)}, rec=rec)
w2 = [x for x in after(r, 104) if x[1] > 0]
check(f"T2: the writer sets 0 A at 119: the mismatch ends that cycle, one "
f"close of 12 A at once, no hold ({after(r, 104)}, hold "
f"{rec.first('mhold', lambda v: v)})",
len(w2) == 1 and w2[0][1] == 12.0 and 119 <= w2[0][0] <= 121
and rec.first("mhold", lambda v: v) is None
and rec.d[121]["mm"] is None)
rec = Rec()
r = man(300, {104: setc(9), 160: act("car_current", 14)}, rec=rec)
w3 = [x for x in after(r, 160)]
check(f"T3: a user change after the hold: hold and row gone within 2 "
f"cycles, 14 A written, no select ({w3}, hold at 160+ "
f"{rec.first('mhold', lambda v: v, 162)})",
rec.first("mhold", lambda v: v) is not None
and rec.every("mhold", lambda v: not v, 162, 299)
and not r["c"].car_writer.other and r["sim"].setpoint_a == 14.0
and not [x for x in w3 if x[1] == "phases"])
# T4 / T5: the zero stage.
rec = Rec()
r = man(300, {105: setc(5)}, rec=rec, sim=slow_sim())
mm, ho = rec.first("mm", lo=104), rec.first("mhold", lambda v: v)
check(f"T4: 5 A (under the raise edge) in the zero stage: mismatch from "
f"{mm}, the EV-28 restore at 120 is not written over it, the hold at "
f"{ho}, no select ({after(r, 105)})",
mm is not None and mm <= 106 and after(r, 105) == []
and ho is not None and 30 <= ho - mm <= 31)
for a in (6, 9):
rec = Rec()
r = man(300, {103: setc(a)}, rec=rec, sim=slow_sim())
check(f"T5 [{a} A]: the raise check holds at once and ends the change, "
f"no select, nothing written after ({after(r, 103)}, hold at "
f"{rec.first('mhold', lambda v: v)})",
rec.first("mhold", lambda v: v) is not None
and rec.first("mhold", lambda v: v) <= 104 and after(r, 103) == []
and rec.d[110]["mseq"] is None)
# T6: Manual's own changes are never flagged.
bad6 = []
for lag in (0.0, 3.0, 12.0):
for race in (False, True):
sim = SimCharger(setpoint_a=0)
sim.lag_s = lag
rec = Rec()
r = man(1400, {800: act("car_phases", 1)}, rec=rec, race=race,
sim=sim)
n = LOG.mark()
if rec.first("mm") is not None or rec.first("mhold",
lambda v: v) is not None:
bad6.append((lag, race, rec.first("mm")))
if len([x for x in wl(r, "phases")]) != 2:
bad6.append((lag, race, "selects", wl(r, "phases")))
rec = Rec()
r = man(300, rec=rec, sim=slow_sim())
if rec.first("mm") is not None or rec.first("mhold", lambda v: v) is not None:
bad6.append(("EV-28", rec.first("mm")))
check(f"T6: Manual's own changes 1->3 and 3->1 (lag 0/3/12, both orders) and "
f"the EV-28 kept-drawing path: never a mismatch or a hold ({bad6[:3]})",
not bad6)
# T7: Manual's own close refused, then taken late.
sim7 = TSim(setpoint_a=0, windows=[(111.0, 127.0, "ignore")])
rec = Rec()
r = man(400, rec=rec, sim=sim7)
check(f"T7: Manual's own close refused 111-127 s, then taken: never a "
f"mismatch or a hold, 12 A in the end (closes {wl(r)[-5:]})",
rec.first("mm") is None and rec.first("mhold", lambda v: v) is None
and r["sim"].setpoint_a == 12.0)
# T8: another writer in the settle stage, then Stop; a Stop guard.
rec = Rec()
r = man(400, {104: setc(9), 106: stop_ctl}, rec=rec)
check(f"T8: 9 A in the settle stage, Stop at 106: nothing written over it "
f"for 290 s ({after(r, 104)})", after(r, 104) == []
and r["sim"].setpoint_a == 9.0)
rec = Rec()
r = man(300, {101: stop_ctl}, rec=rec, sim=slow_sim())
rs8 = [x for x in wl(r) if x[0] > 100]
check(f"T8 guard: Stop in the zero stage, no other writer: exactly one "
f"clamped restore, no select ({wl(r)}, {wl(r, 'phases')})",
len(rs8) == 1 and rs8[0][1] == 12.0 and wl(r, "phases") == []
and rec.first("mm") is None)
# =========================================================================== #
print("\nC7, SOLAR (T9-T15)")
# =========================================================================== #
twin = solar(700, sun=R39)
CLOSE = ([x[1] for x in twin["c"].car_solar.log
if x[0] == "current" and x[2] == 592.0] or [None])[0]
for race in (False, True):
tag = "race" if race else "step"
n, rec = LOG.mark(), Rec()
r = solar(800, sun=R39, race=race, rec=rec, events={TS + 3: setc(16)})
mm, ho = rec.first("ms", lo=TS), rec.first("hold", lambda v: v)
check(f"T9 [{tag}]: another writer's 16 A inside Solar's settle: no close, "
f"no write after it ({after(r, TS + 3)}), mismatch from {mm}, "
f"can_cut False from then ({[rec.d[t]['cut'] for t in range(TS + 4, TS + 8)]}), "
f"hold at {ho} (30 s after), one CHARGER_OTHER ({other_n(n)}), "
f"16 A stands",
after(r, TS + 3) == [] and mm is not None and TS + 3 <= mm <= TS + 4
and ho is not None and 30 <= ho - mm <= 31
and not any(rec.d[t]["cut"] for t in range(mm, ho + 1))
and other_n(n) == 1 and r["sim"].setpoint_a == 16.0
and "charger_other" in r["trace"][ho + 20]["amber"])
rec = Rec()
r = solar(800, sun=R39, rec=rec, events={TS + 3: setc(16), TS + 25: setc(0)})
w10 = [x for x in after(r, TS + 3) if x[1] > 0]
check(f"T10: the writer back at 0 A at {TS + 25}: the close is written once at "
f"once, with the value it had on base ({CLOSE} A), no hold "
f"({after(r, TS + 3)})",
len(w10) == 1 and w10[0][1] == CLOSE and TS + 25 <= w10[0][0] <= TS + 27
and rec.first("hold", lambda v: v) is None)
rec = Rec()
r = solar(900, sun=step_fn((400, 600.0 + 4600.0), (TS + 5, 600.0 + 700.0),
base=600.0 + 1840.0),
rec=rec, opts={"ev_pause_min": 1},
events={TS + 3: setc(16), TS + 70: setc(0)})
nz = [x for x in after(r, TS + 3) if x[1] > 0 and x[0] >= TS + 3]
check(f"T10 variant: the spare falls under 6 A at {TS + 5} and the pause comes "
f"before the writer is back: no non-zero write over it, 0 A stands "
f"(N4) ({after(r, TS + 3)})",
not nz and r["sim"].setpoint_a == 0.0)
n, rec = LOG.mark(), Rec()
r = solar(900, sun=R39, rec=rec, events={TS + 3: setc(16), TS + 6: stop_ctl,
TS + 100: start_ctl})
ho = rec.first("hold", lambda v: v)
check(f"T11: SPIKE-05 C7 trace (16 A at {TS + 3}, Stop at {TS + 6}, Start at "
f"{TS + 100}): the hold at {ho}, 30 s after the change (base: at Stop "
f"+30), nothing written after the change, the hold stands after the "
f"Start ({after(r, TS + 3)})",
ho is not None and ho <= TS + 3 + 32 and after(r, TS + 3) == []
and rec.every("hold", lambda v: v, ho, 899) and other_n(n) == 1
and "charger_other" in r["trace"][800]["amber"])
r = solar(800, sun=R39, events={TS + 3: setc(16), TS + 6: act("car_mode", "off")})
check(f"T12: Off at {TS + 6}, after the other writer: nothing written after "
f"the change, 16 A stands ({after(r, TS + 3)})",
after(r, TS + 3) == [] and r["sim"].setpoint_a == 16.0)
sim13 = slow_sim()
rec = Rec()
r13 = solar(800, sun=R39, sim=sim13, rec=rec)
t0 = ([x[2] for x in r13["c"].car_solar.log
if x[0] == "current" and x[1] == 0.0 and x[2] > 400] or [580.0])[0]
rec = Rec()
r = solar(800, sun=R39, sim=slow_sim(), rec=rec, events={int(t0) + 2: setc(16)})
check(f"T13: 16 A at {int(t0) + 2}, in the zero stage (the 0 A at {t0}): the "
f"raise check holds at once, no select, nothing written ({after(r, int(t0) + 2)})",
rec.first("hold", lambda v: v) is not None
and rec.first("hold", lambda v: v) <= int(t0) + 4
and after(r, int(t0) + 2) == [])
# T14: Solar's own changes are never flagged.
bad14 = []
def own_clean(tag, r, rec, n):
if rec.first("ms") is not None or rec.first("hold", lambda v: v) \
is not None or other_n(n):
bad14.append((tag, rec.first("ms"), other_n(n)))
for race in (False, True):
for lag in (0.0, 12.0):
sim = SimCharger(setpoint_a=0)
sim.lag_s = lag
n, rec = LOG.mark(), Rec()
r = solar(1500, sun=step_fn((400, 5200.0), (900, 1600.0), base=2440.0),
rec=rec, race=race, sim=sim)
own_clean(f"1->3->1 lag {lag} race {race}", r, rec, n)
if lag == 0.0 and not selects(r):
bad14.append(("no select", lag, race))
n, rec = LOG.mark(), Rec()
r = solar(800, sun=R39, sim=slow_sim(), rec=rec)
own_clean("EV-28", r, rec, n)
n, rec = LOG.mark(), Rec()
r = solar(800, sun=R39, rec=rec,
events={TS + 3: lambda p, c: setattr(p, "meter_on", False),
TS + 30: lambda p, c: setattr(p, "meter_on", True)})
own_clean("C17 silent meter in settle", r, rec, n)
check(f"T14: Solar's own 1->3 and 3->1 changes (lag 0 and 12, both orders), "
f"the EV-28 path and a silent meter in settle: never a mismatch, a hold "
f"or CHARGER_OTHER ({bad14[:3]})", not bad14)
bad15 = []
for gap in (1, 2):
n, rec = LOG.mark(), Rec()
r = solar(800, sun=R39, rec=rec,
events={TS + 3: lambda p, c: p.ch.go_unavailable(True),
TS + 3 + gap: lambda p, c: p.ch.go_unavailable(False)})
close = [x[0] for x in cur_writes(r) if x[0] > TS and x[1] >= 6.0][:1]
if rec.first("ms") is not None or other_n(n) or not close \
or close[0] > 596:
bad15.append((gap, rec.first("ms"), close))
check(f"T15: a 1- and a 2-sample read gap in settle: no mismatch starts, the "
f"close comes at the next real reading ({bad15})", not bad15)
# =========================================================================== #
print("\nD4: PHASES (T16-T22)")
# =========================================================================== #
R8 = dict(sun=const(3500.0), phases=3)
for race in (False, True):
tag = "race" if race else "step"
n, rec = LOG.mark(), Rec()
r = solar(1500, rec=rec, race=race, events={300: setph(3)}, **R8)
mm, ho = rec.first("ms", lo=290), rec.first("hold", lambda v: v)
check(f"T16 [{tag}]: another writer's 3 phases at 300: no current write, "
f"no select from 300 ({after(r, 300)}), mismatch from {mm}, can_cut "
f"False from then, hold at {ho} (not before 330), one CHARGER_OTHER "
f"({other_n(n)}), the amber row, no select to 1500",
after(r, 300) == [] and mm is not None and 300 <= mm <= 301
and not rec.d[mm]["cut"] and not rec.d[mm + 1]["cut"]
and not any(rec.d[t]["cut"] for t in range(mm, 1500))
and ho is not None and 330 <= ho <= 331 and other_n(n) == 1
and "charger_other" in r["trace"][400]["amber"]
and len(selects(r)) == 1)
# T17: the alarm path against the Off twin.
bad17 = []
for house, sw in ((500.0, 300), (700.0, 140), (900.0, 140)):
kw = dict(dur=900, first="car", socs={"a": 10.0, "b": 10.0}, car_phases=3,
rows=True)
rs = S.drive(const(house), const(3500.0 + house), phases=3,
events={sw: setph(3)}, **kw)
ro = S.drive(const(house), const(3500.0 + house), phases=1, mode="off",
sim=SimCharger(setpoint_a=14), events={sw: setph(3)}, **kw)
ts_ = [t for t, n_ in S.ids(rs, *S.ALARMS)][:1]
to_ = [t for t, n_ in S.ids(ro, *S.ALARMS)][:1]
ex_s = [x["explains"] for x in rs["trace"] if x["t"] >= sw + 2]
ex_o = [x["explains"] for x in ro["trace"] if x["t"] >= sw + 2]
rd_s = [x["red"] for x in rs["trace"] if x["t"] >= sw + 2]
rd_o = [x["red"] for x in ro["trace"] if x["t"] >= sw + 2]
if not (ts_ and to_ and abs(ts_[0] - to_[0]) <= 2.0):
bad17.append((house, sw, "alarm", ts_, to_))
if ex_s != ex_o or rd_s != rd_o:
bad17.append((house, sw, "rows"))
check(f"T17: the alarm path after a foreign phase switch is the Off twin's "
f"(alarm within 2 s, car_explains and the red rows equal) ({bad17[:2]})",
not bad17)
n, rec = LOG.mark(), Rec()
r = solar(1500, rec=rec, events={300: setph(3), 320: setph(1)}, **R8)
check(f"T18: the writer back to 1 phase at 320: the mismatch ends within a "
f"cycle, no hold, no warning, Solar goes on by its rules "
f"(mismatch {rec.first('ms', lo=290)}.., {other_n(n)} warnings)",
rec.first("ms", lo=290) is not None and rec.first("ms", lo=290) <= 301
and rec.every("ms", lambda v: v is None, 322, 1499)
and not any(rec.d[t]["hold"] for t in rec.d) and other_n(n) == 0
and [x for x in after(r, 300) if x[0] < 320] == [])
n, rec = LOG.mark(), Rec()
r = solar(900, rec=rec, events={300: setph(3), 400: setph(1)}, **R8)
check(f"T19: hold at 330, the writer back to 1 phase at 400: hold and row "
f"gone within a cycle, one warning ({other_n(n)})",
rec.first("hold", lambda v: v) is not None
and rec.every("hold", lambda v: not v, 402, 899) and other_n(n) == 1
and "charger_other" not in r["trace"][450]["amber"])
n, rec = LOG.mark(), Rec()
r = solar(900, rec=rec, events={300: both(setc(16), setph(3)), 400: setph(1),
450: setc(12)}, **R8)
check(f"T19 variant: the writer also set 16 A and only the phases come back: "
f"the hold stands until the current is back at 12 A (450)",
rec.every("hold", lambda v: v, 335, 449)
and rec.every("hold", lambda v: not v, 452, 899) and other_n(n) == 1)
n, rec = LOG.mark(), Rec()
r = solar(1200, rec=rec, events={300: setph(3), 600: act("car_mode", "solar")},
**R8)
sel20 = [x for x in selects(r) if 600 <= x[0] < 121 + CM.PHASE_GAP_S + 1]
check(f"T20: a press of Solar at 600 lifts the hold within a cycle; the 3 "
f"phases are Solar's own, no select before Solar's own dwell and gap "
f"(PHASE_GAP_S after its select at 121: {selects(r)}), no new hold "
f"({sel20}, own phases {rec.d[650]['own_n']})",
rec.every("hold", lambda v: not v, 601, 1199)
and rec.d[650]["own_n"] == 3 and not sel20 and other_n(n) == 1
and rec.every("ms", lambda v: v is None, 603, 1199))
n, rec = LOG.mark(), Rec()
r = solar(900, rec=rec, events={300: stop_ctl, 400: setph(3),
600: start_ctl}, **R8)
check(f"T21: Stop at 300 (0 A), another writer's phases at 400, Start at 600: "
f"hold at {rec.first('hold', lambda v: v)} (430), nothing written, the "
f"amber row after the Start ({after(r, 301)})",
rec.first("hold", lambda v: v) is not None
and 430 <= rec.first("hold", lambda v: v) <= 431
and after(r, 301) == [] and other_n(n) == 1
and "charger_other" in r["trace"][700]["amber"])
bad22, bad23 = [], []
for name, fn in EXITS.items():
r = solar(900, events={300: setph(3), 400: fn}, opts={"shadow_mode": "off"},
**R8)
if after(r, 300) != [] or r["sim"].setpoint_a != 12.0 \
or r["sim"].phases_allowed != 3:
bad22.append((name, after(r, 300)))
r = solar(900, events={300: setph(3), 310: fn}, opts={"shadow_mode": "off"},
**R8)
aft = after(r, 300)
if not (len(aft) == 1 and aft[0][1] == 0.0 and 310 <= aft[0][0] <= 311):
bad23.append((name, aft))
check(f"T22: under the phase hold (330) an exit at 400 writes nothing from "
f"300 to the end; 12 A and 3 phases stand ({bad22[:2]})", not bad22)
check(f"T23: an exit at 310, during the count: the way-out 0 A within a cycle, "
f"no select, nothing non-zero ({bad23[:2]})", not bad23)
# T24: a fresh entry starts clean.
n, rec = LOG.mark(), Rec()
r = S.drive(const(500.0), const(3500.0 + 500.0), dur=1000, mode="manual",
first="car", socs=dict(FULL), phases=1, rows=True, on_cycle=rec,
events={0: both(act("car_current", 10), act("car_phases", 3)),
600: act("car_mode", "solar")})
check(f"T24 (i): Manual 10 A on 3 phases, Solar chosen at 600: no mismatch, "
f"no hold, no warning, the start state is 3 phases "
f"({rec.d[605]['own_n']}, sets {wl(r)[:4]})",
rec.first("ms", lo=600) is None and rec.first(
"hold", lambda v: v) is None and other_n(n) == 0
and rec.d[605]["own_n"] == 3)
n, rec = LOG.mark(), Rec()
r = solar(1000, rec=rec, events={300: setph(3), 500: act("car_mode", "off"),
700: act("car_mode", "solar")}, **R8)
check(f"T24 (ii): a phase hold, Off at 500, Solar chosen at 700: no hold, no "
f"new warning, start state 3 ({other_n(n)}, {rec.d[705]['own_n']})",
rec.every("hold", lambda v: not v, 702, 999) and other_n(n) == 1
and rec.every("ms", lambda v: v is None, 702, 999)
and rec.d[705]["own_n"] == 3)
# T25: unknown phases.
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, sim=XSim(setpoint_a=0),
events={310: unk(True), 340: unk(False)}, **R8)
check("T25 (i): phases unknown 310-340 with no other writer: no mismatch, no "
"hold", rec.first("ms") is None
and rec.first("hold", lambda v: v) is None and other_n(n) == 0)
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, sim=XSim(setpoint_a=0),
events={300: setph(3), 310: unk(True), 320: unk(False)}, **R8)
check(f"T25 (ii): another writer's phases at 300, unknown 310-320: no write and "
f"no select, no lift on unknown, the hold at 330 ({after(r, 300)}, hold "
f"{rec.first('hold', lambda v: v)})",
after(r, 300) == [] and rec.every("ms", lambda v: v is not None, 301,
329)
and 330 <= (rec.first("hold", lambda v: v) or 0) <= 331)
# T26: stale reads.
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec,
events={290: lambda p, c: p.ch.freeze(), 300: setph(3),
400: lambda p, c: p.ch.freeze(False)}, **R8)
mm26 = rec.first("ms", lo=290)
check(f"T26 (i): a frozen (stale) charger 290-400 hides another writer's "
f"phases of 300: no mismatch during the freeze, mismatch from {mm26}, "
f"hold at {rec.first('hold', lambda v: v)} (430), no non-zero write "
f"over it ({[x for x in after(r, 300) if x[1] != 0.0]})",
mm26 is not None and 400 <= mm26 <= 402
and rec.every("ms", lambda v: v is None, 295, 399)
and 430 <= (rec.first("hold", lambda v: v) or 0) <= 433
and not [x for x in after(r, 400) if x[1] != 0.0])
bad26 = []
for lag in (3.0, 12.0):
for race in (False, True):
sim = SimCharger(setpoint_a=0)
sim.lag_s = lag
rec = Rec()
solar(400, rec=rec, sim=sim, race=race, **R8)
if rec.first("ms") is not None:
bad26.append((lag, race))
check(f"T26 (ii): the cycles after an own select read before it was "
f"confirmed: never a mismatch ({bad26})", not bad26)
# T27: failed reads.
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec,
events={300: setph(3), 310: lambda p, c: p.ch.go_unavailable(True),
312: lambda p, c: p.ch.go_unavailable(False)}, **R8)
check(f"T27 (i): a 2-sample read gap at 310 does not end the mismatch: no "
f"write, hold at {rec.first('hold', lambda v: v)} (330-331)",
after(r, 300) == [] and 330 <= (rec.first("hold", lambda v: v) or 0)
<= 332)
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec,
events={300: lambda p, c: p.ch.go_unavailable(True),
360: setph(3), 420: lambda p, c: p.ch.go_unavailable(False)},
**R8)
check(f"T27 (ii): the charger away 300-420, phases changed at 360: no hold, "
f"no warning, the start state is the read-back at the return "
f"({rec.d[430]['own_n']})",
rec.first("hold", lambda v: v) is None and other_n(n) == 0
and rec.d[430]["own_n"] == 3)
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec,
events={300: setph(3), 400: lambda p, c: p.ch.go_unavailable(True),
520: lambda p, c: p.ch.go_unavailable(False)}, **R8)
check(f"T27 (iii): a hold standing, the charger away 400-520: the hold stands, "
f"nothing is written ({after(r, 300)})",
after(r, 300) == [] and rec.every("hold", lambda v: v, 335, 699))
# =========================================================================== #
print("\nDA3, THE WINDOW (T28, T29, T47-T49)")
# =========================================================================== #
# R8: select 1 at 121 (sim 122); refused it returns at 131 (TOOK_S), the close
# is at 141 on the old phases.
SEL, TR = 121, 131
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, sim=XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")]),
**R8)
check(f"T28: Solar's select refused: the close goes on the old phases, the old "
f"phases are never a mismatch, own phases stay 3 ({wl(r)[:3]}, "
f"{rec.d[300]['own_n']})",
rec.first("ms") is None and rec.first("hold", lambda v: v) is None
and other_n(n) == 0 and rec.d[300]["own_n"] == 3
and r["sim"].phases_allowed == 3 and wl(r)[0][0] >= TR)
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, sim=XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")]),
events={TR + 5: setph(1)}, **R8)
check(f"T28 variant: the select is taken 5 s after it returned, inside its "
f"window: own, no mismatch, own phases 1 ({rec.d[300]['own_n']})",
rec.first("ms") is None and rec.first("hold", lambda v: v) is None
and other_n(n) == 0 and rec.d[300]["own_n"] == 1)
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, events={SEL + 3: setph(3)}, **R8)
close = [x for x in cur_writes(r) if x[0] >= SEL + 5][:1]
mm = rec.first("ms", lo=SEL)
check(f"T29: another writer's 3 phases at {SEL + 3}, inside Solar's own taken "
f"3->1 settle: the close is at the 3-phase value ({close}), the "
f"mismatch from the window's end ({mm}, {SEL + 10}+1), the hold 30 s "
f"later, no select back ({selects(r)})",
close and close[0][1] <= 6.0 and mm is not None
and SEL + 10 < mm <= SEL + 12
and mm + 30 <= (rec.first("hold", lambda v: v) or 0) <= mm + 31
and len(selects(r)) == 1 and other_n(n) == 1)
# T30, T31.
n, rec = LOG.mark(), Rec()
r = solar(1800, rec=rec, car_phases=1, **R8)
check("T30: a one-phase car on a 3-phase allowance, 1800 s: never a mismatch",
rec.first("ms") is None and rec.first("hold", lambda v: v) is None
and other_n(n) == 0)
for opt, ph0, ph1 in (("3", 3, 1), ("1", 1, 3)):
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, sun=const(3500.0), phases=ph0,
opts={"ev_phases": opt}, events={300: setph(ph1)})
check(f"T31 [ev_phases {opt}]: another writer's {ph1} phases at 300: as "
f"T16 (mismatch {rec.first('ms', lo=290)}, hold "
f"{rec.first('hold', lambda v: v)})",
after(r, 300) == [] and 300 <= (rec.first("ms", lo=290) or 0) <= 301
and 330 <= (rec.first("hold", lambda v: v) or 0) <= 331
and other_n(n) == 1)
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, events={300: both(setc(16), setph(3)),
400: setph(1), 450: setc(12)}, **R8)
check(f"T32: the other writer changes current and phases at 300: one hold at "
f"{rec.first('hold', lambda v: v)}, one warning ({other_n(n)}); the "
f"phases back at 400 alone keep it, the current back at 450 lifts it",
330 <= (rec.first("hold", lambda v: v) or 0) <= 331 and other_n(n) == 1
and rec.every("hold", lambda v: v, 335, 449)
and rec.every("hold", lambda v: not v, 452, 699))
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, events={300: both(setc(16), setph(3)),
400: setc(12), 450: setph(1)}, **R8)
check(f"T32 variant: the current back at 400 while the other writer's phases "
f"stand: the hold stays (no lift on the current alone); the phases back "
f"at 450 lift it, one warning ({other_n(n)})",
rec.every("hold", lambda v: v, 335, 449)
and rec.every("hold", lambda v: not v, 452, 699) and other_n(n) == 1)
# T33: a restart.
rw = CM.SolarWriter()
check("T33: a fresh writer (a restart) has no stored hold and no own phases "
"until it reads the charger",
not rw.hold and rw.mismatch_since is None
and getattr(rw, "_own_n", None) is None
and not any("hold" in str(k) or "other" in str(k)
for k in r["store"].data))
n, rec = LOG.mark(), Rec()
r = solar(300, rec=rec, **R8)
check("T33 (i): the charger on 3 phases from before the start: the first read "
"is the start state, no hold, no warning",
rec.d[5]["own_n"] == 3 and rec.first("ms", hi=120) is None
and other_n(n) == 0)
# T34: Manual's phases are unchanged.
rec = Rec()
r = man(1500, {300: setph(1), 1000: act("car_current", 13)}, rec=rec)
sel34 = [x for x in wl(r, "phases") if x[0] > 101]
check(f"T34: Manual 12 A on 1 phase, another writer's 3 phases at 300: no "
f"hold, no row, no select until the user changes something ({sel34}), "
f"then the change goes as today",
rec.first("mhold", lambda v: v) is None and rec.first("mm", lo=200)
is None and sel34 and sel34[0][0] >= 1000)
# T35: a false mismatch never blocks the cut.
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, sim=XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")]),
events={TR + 5: setph(1)}, **R8)
check("T35: after an own select the charger took late and a refused one, the "
"cut is allowed again at once (can_cut True), never a mismatch",
rec.first("ms") is None and all(rec.d[t]["cut"] for t in range(160, 300)))
# T36 / T37 / T39: writer level.
class Rd:
def __init__(self, a, ph=1, power=None, state="C"):
self.available = True
self.allowed_a = self.setpoint_a = a
self.phases_allowed = ph
self.power_w = power
self.state = state
self.error = False
self.charging = True
self.current_a = ()
self.station_a = None
class Trk:
obs_at = None
def begin_write(self):
pass
def end_write(self, *_):
pass
def note_write(self, *a, **k):
pass
def stuck(self, now):
return False
class Drv:
def __init__(self, cur, take=lambda a, d: True, ph=1):
self.cur, self.ph, self.take = cur, ph, take
self.calls, self.now, self.polls, self.sel = [], 0.0, (), []
async def write_current(self, a, **kw):
self.calls.append((self.now, float(a)))
if self.take(float(a), self):
self.cur = float(a)
return True
return False
async def write_phases(self, n):
self.sel.append((self.now, n))
self.ph = n
return True
def _clock(self):
return self.now
async def _sleep(self, s):
self.now += s
LOOP = asyncio.new_event_loop()
def swriter(cur, ph=1):
w = CM.SolarWriter()
w.engaged, w.mode_was = True, CM.SOLAR
w.fresh_start = w.restart = False
w.was_available = w._seen = True
w.sent_a, w.taken, w.last_a = cur, True, cur
w.plan.a, w.plan.n = cur, ph
def plan_step(sun, now, clamp, n, gap):
c = w.cut_a
if c is not None and c >= CH.MIN_A and w.plan.a > c + 1e-9:
w.plan._cut(c)
w._plan_step = plan_step
return w
def wrun(w, drv, t0, t1, pre=None, rd=None):
trk = Trk()
for t in range(t0, t1 + 1):
drv.now = float(t)
if pre:
pre(w, drv, t)
w.cut_quarter(int(t // 900))
r = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
LOOP.run_until_complete(w.step(
drv, r, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0),
clamp=16.0, now=float(t), tracker=trk, writing=True,
status="charging"))
# T36: the cut cap across a lift.
w = swriter(8.0)
drv = Drv(8.0, take=lambda a, d: a > 6.5) # the cut value is refused
w._own_n = 1
def pre36(w, d, t):
w.cut_a, w.cut_on = (6.0, True)
if t == 130:
d.ph = 3 # another writer's phases
if t == 150:
d.ph = 1 # ... and back
wrun(w, drv, 0, 1199, pre=pre36)
cut_tries = [int(t) for t, a in drv.calls if a <= 6.0 + 1e-9]
k0 = [t for t in cut_tries if t < 900]
k1 = [t for t in cut_tries if t >= 900]
check(f"T36: 3 refused cut tries in key 0, a phase mismatch at 130 and its "
f"lift at 150: no 4th cut try in the key, tries come again in the next "
f"({k0}, {k1[:3]})", len(k0) == 3 and len(k1) >= 1 and w.cut_fails >= 1)
# T37: the N3 reading, a 6 A hold and a phase mismatch.
w = swriter(6.0)
drv = Drv(6.0)
def pre37(w, d, t):
if t == 60:
d.ph = 3
if t == 250:
d.ph = 1
wrun(w, drv, 0, 700, pre=pre37)
nz37 = [(int(t), a) for t, a in drv.calls if a > 0]
check(f"T37: a 6 A hold, a phase mismatch at 60 and its lift at 250: nothing "
f"above 6 A is written ({nz37})", all(a <= 6.0 for t, a in nz37))
# T39: the start state.
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, sim=XSim(setpoint_a=0), opts={"ev_phases": "3"},
sun=const(3500.0), phases=3,
events={0: unk(True), 60: unk(False), 300: setph(1)})
check(f"T39 (i): phases unknown for 60 s, then 3: the start state is 3, "
f"another writer's 1 phase at 300 is a mismatch (hold "
f"{rec.first('hold', lambda v: v)})",
rec.first("ms", hi=290) is None and 300 <= (rec.first("ms") or 0) <= 301
and 330 <= (rec.first("hold", lambda v: v) or 0) <= 331)
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, sim=XSim(setpoint_a=0),
events={122: unk(True), 123: act("car_mode", "solar"),
150: unk(False), 300: setph(3)}, **R8)
check(f"T39 (ii): phases unknown while Solar's own select of 1 is taken (a "
f"press at 123 took the start state afresh): own "
f"phases are 1, a later 3 is a mismatch ({rec.d[200]['own_n']}, "
f"{rec.first('ms', lo=250)})",
rec.d[200]["own_n"] == 1 and 300 <= (rec.first("ms", lo=250) or 0) <= 301)
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec,
sim=XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")]),
events={122: unk(True), 123: act("car_mode", "solar"),
134: unk(False)}, **R8)
inside = rec.d[137]["own_n"]
check(f"T39 (iii): the first known read falls inside Solar's own select window "
f"and shows 3: that read is not the start state ({inside}); after the "
f"window own = the phases then read ({rec.d[160]['own_n']}), no mismatch",
inside is None and rec.d[160]["own_n"] == 3 and rec.first("ms") is None)
n, rec = LOG.mark(), Rec()
r = solar(700, rec=rec, sim=XSim(setpoint_a=0), events={0: unk(True)}, **R8)
check("T39 (iv): phases unknown the whole run: never a phase mismatch",
rec.first("ms") is None and rec.first("hold", lambda v: v) is None
and other_n(n) == 0)
# =========================================================================== #
print("\nG3, DA1, DA2, DA3 (T41-T49)")
# =========================================================================== #
S200 = 200
HP = 529 # the std run's pause by the silent meter (no other writer)
for tid, setter in (("T41", setc(16)), ("T42", setph(3))):
for k, at in (("(i)", HP - 20), ("(ii)", HP - 40)):
n, rec = LOG.mark(), Rec()
r = solar(
700, rec=rec, sun=const(600.0 + 2070.0),
events={S200: lambda p, c: setattr(p, "meter_on", False),
at: setter,
HP: lambda p, c: p.ch.go_unavailable(True),
HP + 1: lambda p, c: p.ch.go_unavailable(False)})
aft = after(r, at)
if k == "(i)":
ok = len(aft) == 1 and aft[0][1] == 0.0 and HP <= aft[0][0] <= HP + 2
else:
ok = aft == []
check(f"{tid} {k}: held_pause with another writer's "
f"{'current' if tid == 'T41' else 'phases'} at {at}: "
f"{f'0 A at {HP}' if k == '(i)' else 'nothing written'} ({aft})",
ok)
# T43: DA1, Manual.
rec = Rec()
r = man(300, {105: setc(5), 108: act("car_current", 14)}, rec=rec,
sim=slow_sim())
check(f"T43: Manual, 5 A in the zero stage, a press at 108: the change ends at "
f"its 0 A in the press cycle (old t0 100: {rec.d[108]['mseq']}), no hold "
f"and no row up to +120 s, the car ends at 14 A "
f"({r['sim'].setpoint_a})",
(rec.d[108]["mseq"] is None or rec.d[108]["mseq"][1] != 100.0)
and rec.first("mhold", lambda v: v) is None
and r["sim"].setpoint_a == 14.0)
rec = Rec()
r = man(300, {104: setc(9), 108: act("car_current", 14)}, rec=rec)
check(f"T43 variant: 9 A in the settle stage, a press at 108: the change ends "
f"in the press cycle ({rec.d[108]['mseq']}), no hold, 14 A at the end",
rec.d[108]["mseq"] is None and rec.first("mhold", lambda v: v) is None
and r["sim"].setpoint_a == 14.0)
# T44: DA1, Solar.
n, rec = LOG.mark(), Rec()
r = solar(800, rec=rec, sun=R39,
events={TS + 3: setc(16), TS + 8: act("car_mode", "solar")})
check(f"T44: Solar, 16 A in the settle stage, a press at {TS + 8}: the change "
f"ends in the press cycle ({rec.d[TS + 8]['sseq']}), no old close, no "
f"hold and no warning up to +120 s ({after(r, TS + 3)}, {other_n(n)})",
rec.d[TS + 8]["sseq"] is None
and rec.every("hold", lambda v: not v, TS + 8, TS + 128)
and other_n(n) == 0 and not [x for x in after(r, TS + 3)
if x[1] == CLOSE and x[0] >= TS + 9])
n, rec = LOG.mark(), Rec()
t0 = int(t0)
r = solar(800, rec=rec, sun=R39, sim=slow_sim(),
events={t0 + 2: lambda p, c: p.ch.go_unavailable(True),
t0 + 3: setc(16),
t0 + 4: both(lambda p, c: p.ch.go_unavailable(False),
act("car_mode", "solar"))})
check(f"T44 variant: the zero stage, 16 A seen only after a press: no "
f"raise-check hold ({rec.first('hold', lambda v: v)}), no warning "
f"({other_n(n)})",
rec.first("hold", lambda v: v) is None and other_n(n) == 0)
# T45: DA2, Solar's own Stop.
bad45 = []
for name, fn in (("Stop", stop_ctl), ("shadow", EXITS["shadow on"]),
("latch", EXITS["latch"])):
n, rec = LOG.mark(), Rec()
r = solar(500, rec=rec, events={300: fn}, opts={"shadow_mode": "off"})
zeros = [x for x in after(r, 300) if x[1] == 0.0]
if rec.first("ms", lo=295) is not None or other_n(n) \
or len(zeros) != 1:
bad45.append((name, rec.first("ms", lo=295), other_n(n), zeros))
check(f"T45: Solar's own Stop/shadow/latch with no other writer: its 0 A is "
f"written once and no mismatch is ever counted ({bad45[:2]})", not bad45)
# T46: DA2, the formal C-stop replay.
n, rec = LOG.mark(), Rec()
r = solar(420, rec=rec,
events={300: setc(16), 324: lambda p, c: p.ch.go_unavailable(True),
325: setc(10),
331: both(lambda p, c: p.ch.go_unavailable(False), stop_ctl)})
check(f"T46: a count from 16 A at 300, held reads 324-330 while the writer "
f"puts 10 A back at 325, Stop at 331: the way-out 0 A at 331, no hold "
f"and no CHARGER_OTHER over Solar's own value ({after(r, 331)}, hold "
f"{rec.first('hold', lambda v: v)}, {other_n(n)})",
rec.first("hold", lambda v: v) is None and other_n(n) == 0
and [x for x in after(r, 331)] in ([(331.0, 0.0)], [(332.0, 0.0)]))
# T47: the window's end.
bad47 = []
for at in (SEL + 9, SEL + 10, SEL + 11):
n, rec = LOG.mark(), Rec()
r = solar(400, rec=rec, events={at: setph(3)}, **R8)
mm = rec.first("ms", lo=SEL)
ho = rec.first("hold", lambda v: v)
if at == SEL + 11:
okk = mm is not None and SEL + 11 <= mm <= SEL + 13
else:
okk = mm is not None and SEL + 10 < mm <= SEL + 13
if not (okk and ho is not None and ho <= TR - 10 + 42 and other_n(n) == 1
and len(selects(r)) == 1):
bad47.append((at, mm, ho, other_n(n)))
check(f"T47: another writer's 3 phases at, and just after, the end of Solar's "
f"own window (121+9, +10, +11): not judged inside it, a mismatch from "
f"the next cycle, the hold 30 s later, one warning ({bad47})", not bad47)
# T48: a late take after the window.
bad48 = []
simw = lambda: XSim(setpoint_a=0, pwin=[(100.0, 170.0, "ignore")])
for at, late in ((TR + 15, True), (TR + 9, False)):
n, rec = LOG.mark(), Rec()
r = solar(500, rec=rec, sim=simw(), events={at: setph(1)}, **R8)
mm = rec.first("ms", lo=TR)
if late:
if not (mm is not None and at <= mm <= at + 2
and (rec.first("hold", lambda v: v) or 0) <= at + 33
and other_n(n) == 1 and after(r, at + 2) == []):
bad48.append((at, mm, other_n(n)))
elif mm is not None or other_n(n) or rec.d[300]["own_n"] != 1:
bad48.append((at, mm))
check(f"T48: Solar's refused select taken by the charger after its window: a "
f"mismatch, then a hold, nothing written; taken inside it: own ({bad48})",
not bad48)
n, rec = LOG.mark(), Rec()
r = solar(500, rec=rec, sim=simw(),
events={TR + 3: lambda p, c: p.ch.freeze(), TR + 5: setph(1),
TR + 12: lambda p, c: p.ch.freeze(False)}, **R8)
mm = rec.first("ms", lo=TR)
check(f"T48 (stale): a take inside the window, first read after the window "
f"because a frozen read lies in between: a mismatch from {mm} "
f"({TR + 12}), then a hold ({rec.first('hold', lambda v: v)})",
mm is not None and TR + 12 <= mm <= TR + 30
and rec.first("hold", lambda v: v) is not None and other_n(n) == 1)
# T49: refused retries, each with its own window.
keep_gap = CM.PHASE_GAP_S
CM.PHASE_GAP_S = 60.0
try:
pw = [(100.0, 10000.0, "ignore")]
n, rec = LOG.mark(), Rec()
r = solar(900, rec=rec, sim=XSim(setpoint_a=0, pwin=pw), **R8)
sel49 = [x[2] for x in r["c"].car_solar.log if x[0] == "phases"]
check(f"T49: a select refused MAX_TRIES times, each after the gap: a "
f"window after each, the old phases never a mismatch, no more "
f"selects after the 3rd ({sel49})",
len(sel49) == CM.MAX_TRIES and rec.first("ms") is None
and r["c"].car_solar.phases_gave_up and other_n(n) == 0)
n, rec = LOG.mark(), Rec()
if len(sel49) < 3:
sel49 = [121.0, 181.0, 241.0] # the run's own tries are missing
t3 = sel49[-1]
r = solar(900, rec=rec, sim=XSim(setpoint_a=0, pwin=pw),
events={int(sel49[1]) + 15: setph(1)}, **R8)
w2_ = [x[2] for x in r["c"].car_solar.log if x[0] == "phases"]
check(f"T49 variant 2: the 2nd try taken inside its window (15 s after "
f"it went): own, no mismatch, own phases 1 "
f"({rec.first('ms', lo=int(sel49[1]))}, {rec.d[500]['own_n']})",
rec.first("ms", lo=int(sel49[1])) is None
and rec.d[int(sel49[1]) + 30]["own_n"] == 1)
n, rec = LOG.mark(), Rec()
r = solar(900, rec=rec, sim=XSim(setpoint_a=0, pwin=pw),
events={int(t3) + 40: setph(1)}, **R8)
check(f"T49 variant 3: a foreign switch 40 s after the 3rd try is a "
f"mismatch from that cycle ({rec.first('ms', lo=int(t3))})",
rec.first("ms", lo=int(t3)) is not None
and int(t3) + 40 <= rec.first("ms", lo=int(t3)) <= int(t3) + 42)
finally:
CM.PHASE_GAP_S = keep_gap
# =========================================================================== #
print("\nREVIEW ROUND 1 (rows A-D, R1, the window's closing step)")
# =========================================================================== #
class NoneSim(SimCharger):
"""The read-back and the setpoint answer with a non-number while
`badcur` (the charger is available, `cur` is None)."""
badcur = False
def _build(self):
out = super()._build()
if self.badcur:
for k in list(out):
if k.endswith("max_current_socket_1") and \
("number." in k or "main_active" in k):
out[k] = dict(out[k], state="n/a")
return out
def badcur(on):
def f(p, c):
p.ch.badcur = on
return f
class LateSim(SimCharger):
"""Ignores current writes while t0 <= sim t < t1 and remembers the last;
`late` (an event) shows it: a write the charger took late."""
owed = None
t0, t1 = 0.0, 0.0
def request_current(self, a):
if self.t0 <= self.t < self.t1:
self.owed = a
keep, self.refuse = self.refuse, "ignore"
try:
return super().request_current(a)
finally:
self.refuse = keep
return super().request_current(a)
def late(p, c):
if p.ch.owed is not None:
p.ch.set_current(p.ch.owed)
T0Z = int(([x[2] for x in r13["c"].car_solar.log
if x[0] == "current" and x[1] == 0.0 and x[2] > 400]
or [580.0])[0])
# A (Major 1, Solar): the press covers the first reading only; a later raise
# in the same zero stage is held at once.
n, rec = LOG.mark(), Rec()
r = solar(800, sun=R39, sim=slow_sim(), rec=rec,
events={T0Z + 2: act("car_mode", "solar"), T0Z + 8: setc(16)})
check(f"T44 (A): Solar, a press at {T0Z + 2} in the zero stage, another "
f"writer's 16 A at {T0Z + 8}: the raise check holds at once "
f"({rec.first('hold', lambda v: v, T0Z + 8)}), nothing written over it "
f"({after(r, T0Z + 8)})",
(rec.first("hold", lambda v: v, T0Z + 8) or 99999) <= T0Z + 9
and after(r, T0Z + 8) == [])
# B (Major 1, Manual)
rec = Rec()
r = man(300, {102: act("car_current", 14), 106: setc(9)}, rec=rec,
sim=slow_sim())
check(f"T43 (B): Manual, the user sets 14 A at 102 in the zero stage, another "
f"writer's 9 A at 106: held at once "
f"({rec.first('mhold', lambda v: v, 106)}), nothing written over it "
f"({after(r, 107)})",
(rec.first("mhold", lambda v: v, 106) or 99999) <= 107
and after(r, 107) == [] and r["sim"].setpoint_a == 9.0)
# C (Major 2, Solar): an unknown read-back leaves the count alone.
n, rec = LOG.mark(), Rec()
r = solar(700, sun=R39, sim=NoneSim(setpoint_a=0), rec=rec,
events={TS + 3: setc(16), TS + 9: badcur(True),
TS + 12: badcur(False)})
check(f"T9 (C): another writer's 16 A at {TS + 3}, an unknown read-back "
f"{TS + 9}-{TS + 11}: the count stands "
f"({[rec.d[t]['ms'] for t in (TS + 8, TS + 10, TS + 12)]}), nothing "
f"is written over the 16 A ({after(r, TS + 3)}), the hold comes",
rec.every("ms", lambda v: v is not None, TS + 5, TS + 14)
and after(r, TS + 3) == []
and rec.first("hold", lambda v: v) is not None)
# D (Major 2, Manual)
rec = Rec()
r = man(300, {104: setc(9), 109: badcur(True), 113: badcur(False)}, rec=rec,
sim=NoneSim(setpoint_a=0))
check(f"T1 (D): Manual, 9 A at 104, an unknown read-back 109-112 over the "
f"close at 111: no write over the 9 A ({after(r, 104)}), the count "
f"stands ({[rec.d[t]['mm'] for t in (108, 110, 112)]})",
after(r, 104) == [] and rec.every("mm", lambda v: v is not None, 106, 112))
# R1: the sequence's own values count as own after a press (formal note).
lm = LateSim(setpoint_a=0)
lm.t0, lm.t1 = 110.0, 120.0
rec = Rec()
r = man(260, {113: act("car_current", 12), 120: late}, rec=rec, sim=lm)
check(f"T43 (R1, Manual): the close refused until 120, a press at 113 clears "
f"`attempted_a`, the charger then shows the late close: own value, "
f"never a mismatch or a hold "
f"({rec.first('mm', lo=100)}, {rec.first('mhold', lambda v: v)})",
rec.first("mm", lo=100) is None
and rec.first("mhold", lambda v: v) is None)
ls = LateSim(setpoint_a=0)
ls.t0, ls.t1 = TS + 10.5, TS + 14.0 # the close at 592 (sim 593) ignored
rec = Rec()
r = solar(700, sun=R39, sim=ls, rec=rec,
events={TS + 12: act("car_mode", "solar"), TS + 14: late})
check(f"T44 (R1, Solar): the close refused from 592, a press at {TS + 12}, "
f"the charger then shows the late close: own value, never a mismatch "
f"or a hold ({rec.first('ms', lo=TS)}, "
f"{rec.first('hold', lambda v: v)})",
rec.first("ms", lo=TS) is None
and rec.first("hold", lambda v: v) is None)
# Finding 4: `last_done` a fraction of a second after the step's `now`: the
# step that closes is still inside the window.
def frac_run(taken_late):
w = swriter(0.0, ph=3)
w.plan.a, w.plan.n = 12.0, 1
drv = Drv(0.0, ph=3)
w.seq = {"stage": "settle", "t0": 119.0, "t1": 121.4, "n": 1, "tries": 0,
"prev": None, "from": 3, "own": [0.0], "sel": True}
w.last_done = 121.4
w._own_n = 3
w._select_try(1, not taken_late)
ms = {}
def pre(w_, d, t):
if taken_late:
d.ph = 1 if t >= 132 else 3 # the take is first seen at 132
else:
d.ph = 3 if t >= 124 else 1 # another writer's 3 phases
ms[t] = w_.mismatch_since
trk = Trk()
for t in range(122, 138):
drv.now = float(t)
pre(w, drv, t)
rd = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
LOOP.run_until_complete(w.step(
drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0),
clamp=16.0, now=float(t), tracker=trk, writing=True,
status="charging"))
ms[t] = w.mismatch_since
return w, drv, ms
w, drv, ms = frac_run(False)
cl = [(int(t), a) for t, a in drv.calls if a > 0]
check(f"T29 (fraction): last_done 121.4, the close step at 132 (10.6 s later) "
f"is inside the window: the close is written at 132 ({cl}), no "
f"mismatch at 132 ({ms[132]}), the mismatch from 133 ({ms[133]})",
cl and cl[0][0] == 132 and ms[132] is None and ms[133] == 133.0)
w, drv, ms = frac_run(True)
check(f"T48 (fraction): a take first seen on the closing step (132, last_done "
f"121.4) is Solar's own: own phases {w._own_n}, no mismatch "
f"({ms[132]}, {ms[134]})",
w._own_n == 1 and ms[132] is None and ms[134] is None)
report()