A phase change that ends on MAX_TRIES (both writers) or on Solar's EV-60 cap end now carries every value it tried, its 0 A too, until the first of: an own take, any own current write, a user change, a hold, Solar's charger return. A carried take resets fails/gave_up only (GUR). Tests: test_ev69.py (T1-T20, T23-T25), test_ev69_fuzz.py (T21), tools/ev69_kit.py. Co-Authored-By: Claude <noreply@anthropic.com>
309 lines
9.6 KiB
Python
309 lines
9.6 KiB
Python
"""EV-69: the writer-level harness of test_ev69.py and test_ev69_fuzz.py: a
|
|
`SolarWriter` / `ManualWriter` on a stub driver, a stub tracker and a stub
|
|
reading, one step per second on a model clock; `Run` records what every step
|
|
ended with. `Base69` / `BaseM69` are de733f4's writers (the carry switched
|
|
off): the red side of a row.
|
|
|
|
Each check file is its own process, so `fails` and `LOG` are its own."""
|
|
|
|
import asyncio
|
|
import logging
|
|
import os
|
|
import sys
|
|
|
|
_KIT = os.path.dirname(os.path.abspath(__file__))
|
|
sys.path.insert(0, os.path.dirname(_KIT))
|
|
|
|
from app import carmode as CM # noqa: E402
|
|
|
|
fails = []
|
|
CLOCK = {"t": 0}
|
|
LOG = []
|
|
OTHER = "CHARGER_OTHER"
|
|
SOMETHING = "Something else changes the charger"
|
|
REC = "The car charger step failed"
|
|
|
|
|
|
class Cap(logging.Handler):
|
|
def emit(self, rec):
|
|
LOG.append((CLOCK["t"], rec.levelname, rec.getMessage()))
|
|
|
|
|
|
logging.getLogger("goodwe").addHandler(Cap())
|
|
logging.getLogger("goodwe").setLevel(logging.DEBUG)
|
|
|
|
|
|
def check(name, cond):
|
|
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
|
if not cond:
|
|
fails.append(name)
|
|
|
|
|
|
def done():
|
|
print("\nall passed" if not fails else f"\n{len(fails)} FAILED")
|
|
for f in fails:
|
|
print(" FAIL:", f)
|
|
sys.exit(1 if fails else 0)
|
|
|
|
|
|
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:
|
|
"""`take(a, drv)` -> True (the charger takes it), False (refused) or
|
|
"raise" (the call raises)."""
|
|
|
|
def __init__(self, cur, take, 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)))
|
|
r = self.take(float(a), self)
|
|
if r == "raise":
|
|
raise RuntimeError("HA call error")
|
|
if r is True:
|
|
self.cur = float(a)
|
|
return r is True
|
|
|
|
async def write_phases(self, n):
|
|
self.sel.append((self.now, n, self.cur))
|
|
self.ph = n
|
|
return True
|
|
|
|
def _clock(self):
|
|
return self.now
|
|
|
|
async def _sleep(self, s):
|
|
self.now += s
|
|
|
|
|
|
class Base69(CM.SolarWriter):
|
|
"""de733f4's Solar: an ended sequence's values are not carried."""
|
|
|
|
def _carry_end(self, q):
|
|
self._carry = []
|
|
|
|
|
|
class BaseM69(CM.ManualWriter):
|
|
"""de733f4's Manual."""
|
|
|
|
def _carry_end(self, q):
|
|
self._carry = []
|
|
|
|
|
|
LOOP = asyncio.new_event_loop()
|
|
|
|
|
|
def swriter(cur, ph=1, cls=None):
|
|
w = (cls or 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 >= CM.CH.MIN_A and w.plan.a > c + 1e-9:
|
|
w.plan._cut(c)
|
|
w._plan_step = plan_step
|
|
return w
|
|
|
|
|
|
def set_cap(w, a):
|
|
w.cut_a, w.cut_on = a, a is not None
|
|
|
|
|
|
def show(a):
|
|
return lambda w, d, s: setattr(d, "cur", float(a))
|
|
|
|
|
|
def press(w, d, s):
|
|
w.user_changed()
|
|
s["rev"] = s.get("rev", 1) + 1
|
|
|
|
|
|
def cap(a):
|
|
return lambda w, d, s: set_cap(w, a)
|
|
|
|
|
|
def chain(*fns):
|
|
def f(w, d, s):
|
|
for fn in fns:
|
|
fn(w, d, s)
|
|
return f
|
|
|
|
|
|
def evs(*pairs):
|
|
"""{t: fn(w, drv, st)}; two at one second run both."""
|
|
out = {}
|
|
for t, fn in pairs:
|
|
out[t] = chain(out[t], fn) if t in out else fn
|
|
return out
|
|
|
|
|
|
class Run:
|
|
"""One writer-level run; per second: mismatch, hold, counts."""
|
|
|
|
def __init__(self, w, drv, kind="solar", st=None):
|
|
del LOG[:]
|
|
self.w, self.drv, self.kind = w, drv, kind
|
|
self.trk, self.st = Trk(), st if st is not None else {}
|
|
self.ms, self.hold, self.gu, self.fl, self.seq = {}, {}, {}, {}, {}
|
|
self.taken, self.last_a, self.sent_a = {}, {}, {}
|
|
self.prior, self.att, self.carry, self.ncalls = {}, {}, {}, {}
|
|
self.own = {}
|
|
self.viol, self.ended, self.log = [], None, []
|
|
|
|
def go(self, t0, t1, ev=None, hook=None, clamp=16.0, writing=None,
|
|
cur=None, stale=None, gone=None):
|
|
w, drv = self.w, self.drv
|
|
for t in range(t0, t1 + 1):
|
|
drv.now = float(t)
|
|
CLOCK["t"] = t
|
|
if ev and t in ev:
|
|
ev[t](w, drv, self.st)
|
|
if hook:
|
|
hook(t, w, drv, self.st)
|
|
if hasattr(w, "cut_quarter"):
|
|
w.cut_quarter(int(t // 900))
|
|
c = drv.cur if cur is None else cur(t, drv)
|
|
rd = Rd(c, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
|
|
if gone is not None and gone(t):
|
|
rd.available = False
|
|
cl = clamp(t) if callable(clamp) else clamp
|
|
if self.kind == "manual":
|
|
cl = self.st.get("clamp", cl)
|
|
self.trk.obs_at = None
|
|
if stale is not None and stale(t):
|
|
self.trk.obs_at = w.last_done if w.last_done is not None \
|
|
else 0.0
|
|
wr = True if writing is None else writing(t)
|
|
n0, s0 = len(drv.calls), w.seq is not None
|
|
if self.kind == "solar":
|
|
LOOP.run_until_complete(w.step(
|
|
drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0),
|
|
clamp=cl, now=float(t), tracker=self.trk, writing=wr,
|
|
status="charging"))
|
|
else:
|
|
LOOP.run_until_complete(w.step(
|
|
drv, rd, mode=CM.MANUAL, want_a=self.st["a"],
|
|
want_phases=self.st["n"], rev=self.st["rev"], clamp=cl,
|
|
now=float(t), tracker=self.trk, writing=wr,
|
|
status="charging"))
|
|
if s0 and w.seq is None and self.ended is None:
|
|
self.ended = t
|
|
# N2 is judged on the state after the step's own watch: a count
|
|
# a read cleared in this step (the foreign value went) is no
|
|
# count when the write goes out.
|
|
stood = bool(w.hold or (self.kind == "solar"
|
|
and w.mismatch_since is not None))
|
|
for tt, a in drv.calls[n0:]:
|
|
# N2 / N5 per write
|
|
if a > 0 and stood:
|
|
self.viol.append((t, "N2 write while a count/hold stood",
|
|
a))
|
|
if a > cl + 1e-9 or 0 < a < CM.CH.MIN_A - 1e-9:
|
|
if not (w.cut_a is not None and a <= w.cut_a + 1e-9):
|
|
self.viol.append((t, "N5 write outside clamp/6 A", a))
|
|
if getattr(w, "cut_fails", 0) > CM.MAX_TRIES:
|
|
self.viol.append((t, "N6 cut tries over the cap"))
|
|
self.ms[t], self.hold[t] = w.mismatch_since, w.hold
|
|
self.gu[t], self.fl[t] = w.gave_up, w.fails
|
|
self.seq[t], self.taken[t] = w.seq is not None, getattr(
|
|
w, "taken", None)
|
|
self.last_a[t], self.sent_a[t] = w.last_a, getattr(
|
|
w, "sent_a", None)
|
|
self.prior[t], self.att[t] = w.prior_a, w.attempted_a
|
|
self.carry[t] = list(getattr(w, "_carry", []))
|
|
self.own[t] = list(w._own_values())
|
|
self.ncalls[t] = len(drv.calls)
|
|
self.log = list(LOG)
|
|
LAST[0] = self
|
|
return self
|
|
|
|
# ---------------------------------------------------------- readings
|
|
def calls_from(self, t0, t1=10 ** 9, nz=False):
|
|
return [(int(t), a) for t, a in self.drv.calls
|
|
if t0 <= t <= t1 and (not nz or a > 0)]
|
|
|
|
def clean(self, lo, hi):
|
|
"""No mismatch, no hold, no CHARGER_OTHER line, no 'Something else
|
|
changes' line in lo..hi."""
|
|
return (all(self.ms[t] is None and not self.hold[t]
|
|
for t in range(lo, hi + 1) if t in self.ms)
|
|
and not [1 for t, lv, m in self.log if lo <= t <= hi
|
|
and (OTHER in m or SOMETHING in m)])
|
|
|
|
def first_ms(self, lo=0):
|
|
for t in sorted(self.ms):
|
|
if t >= lo and self.ms[t] is not None:
|
|
return t
|
|
return None
|
|
|
|
def first_hold(self, lo=0):
|
|
for t in sorted(self.hold):
|
|
if t >= lo and self.hold[t]:
|
|
return t
|
|
return None
|
|
|
|
|
|
LAST = [None] # the run that ended last: what `n_other` / `n_some` count
|
|
|
|
|
|
def n_other():
|
|
return len([1 for t, lv, m in LAST[0].log if OTHER in m])
|
|
|
|
|
|
def n_some():
|
|
return len([1 for t, lv, m in LAST[0].log if SOMETHING in m])
|
|
|
|
|
|
def near(x, lo, hi):
|
|
return x is not None and lo <= x <= hi
|
|
|
|
|
|
def nev(tag, run):
|
|
"""N2, N5, N6 over one run (collected per step by `Run.go`), N9 (one
|
|
CHARGER_OTHER per hold rise), N8 (a select only at 0 A)."""
|
|
rises = 0
|
|
prev = False
|
|
for t in sorted(run.hold):
|
|
if run.hold[t] and not prev:
|
|
rises += 1
|
|
prev = run.hold[t]
|
|
sel_bad = [x for x in run.drv.sel if x[2] > CM.TOL_A]
|
|
check(f"N2/N5/N6 {tag}: no write over a count or hold, none above the "
|
|
f"clamp or in 0-6 A, at most 3 cut tries ({run.viol[:2]})",
|
|
not run.viol)
|
|
check(f"N8/N9 {tag}: a select only at 0 A ({sel_bad[:1]}), at most one "
|
|
f"CHARGER_OTHER per hold ({n_other()} for {rises})",
|
|
not sel_bad and n_other() <= rises)
|