Compare commits

...
9 Commits
Author SHA1 Message Date
Claude 5bd2b1ec97 EV-60: Solar never passes the cut cap of 3 refused tries per quarter key
infra-pin / fresh (pull_request) Waiting to run
checks / unit (pull_request) In progress
Solar's phase change 0 A and its capped close are cut tries. They now pass
the same gates as `_put`: none at cut_fails >= MAX_TRIES, none within RETRY_S
of the last refused cut try (the sequence's first cut close waits at 0 A, the
rest keep the 5 s spacing). A gated 0 A waits for the next quarter key and
never gives up; a capped close with no tries left ends the change at 0 A
(end_switch(False), reapply, no write). Solar's close end adds no extra
_failed (EV-56 F1 on the cut path, EV-59 finding 2 on the non-cut path), so
a press during the close retries gives the value MAX_TRIES tries.

Solar only (override in SolarWriter); Manual is byte for byte as before.
Edited tests as ruled (Q3, Q4): test_ev59 T25/T14, T25 press, T14c and the
N11 digest list; test_ev56 T19b [a]/[b], T12 and golden "T20 T12 [R]".

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-02 05:48:20 +01:00
ems-agent 2e09622fe1 Merge pull request 'EV-59: Manual gives one value at most MAX_TRIES tries per user change' (#282) from EV-59 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-12-01 10:10:11 +01:00
Claude 7628cacdb7 EV-59 review: CHANGELOG line; T21 power-unknown check exact
checks / unit (pull_request) Successful in 50m12s
infra-pin / fresh (pull_request) Successful in 1s
Reviewer fixes, Minor only, no implementation change:
- CHANGELOG.md: the user-visible change under "Not in a release yet".
- test_ev59 T21 (power unknown): assert the 3 restore tries at 20, 25, 30,
  the give-up and one REF, instead of "at most 3" (which passed with 0).
  Red on 1b909fb (20, 25, 30, 90, 150).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 09:19:38 +01:00
Claude e522e6ffbb EV-59: test_ev59 gains T14c, T17, T18, T11c, N3, N7, N11, N12; docstring
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Successful in 51m36s
T14c drives SolarWriter._advance with a moving close value (pinned to the
base result). T17, T18, T11c and N11 are source checks on the edited test
files. N3 is asserted in every run, N7 with an answering charger, N12 on the
tracker notes. The docstring now says which row is here, which is carried by
another suite, and which existing tests are edited.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 05:32:29 +01:00
Claude e83b2e315b EV-59: test_ev13 T26 goldens, N4/N8/N10 tests, stronger T12b/T11a
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Failing after 1h13m10s
PM ruling: drop the 4th and 5th tries (1095, 1155) from the test_ev13 T26
goldens T20-beside and T20-inside. test_ev59 gains T13e (a give-up never
blocks _undo, abandon or _begin), N8 and N10, and the fails-at-select and
fails-at-timeout asserts that kill mutant M12.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 02:50:45 +01:00
Claude 009393a5ee EV-59: Manual gives one value at most MAX_TRIES tries per user change
A refused phase-change close ended its sequence with one `_failed`, so the
same value got 5 tries (3 closes, then 2 on the normal path). Manual now
counts the not-taken closes of the value owed since the last user change
(`_close_k`); at the capped close end `fails` = that count, so `gave_up` and
CHARGER_REFUSED come at the 3rd refused close, and a value changed during the
retries still gets 3 tries. SolarWriter overrides the end hook and is
unchanged (EV-60).

Tests: new test_ev59.py; test_ev56 T5, T5b and the T20 T5 [R] golden,
test_ev28 T15 and the test_ev13 T13 text per the brief rulings.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 02:40:49 +01:00
ems-agent 1b909fb7bd Merge pull request 'EV-56: a charger write that raises counts as a not-taken try' (#281) from EV-56 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-30 20:00:48 +01:00
ems-agentandClaude 3682b0754b EV-56: a charger write that raises counts as a not-taken try
checks / unit (pull_request) Successful in 57m33s
infra-pin / fresh (pull_request) Successful in 2s
ManualWriter._write catches an Exception from drv.write_current (not CancelledError) and returns False, so every caller in Manual and Solar counts it as a refused try: RETRY_S spacing, MAX_TRIES, CHARGER_REFUSED. The tracker is not told (Q2). One ERROR record per raised value, armed again by another value, a taken write, a user change or the charger's return (Q1, G2). Shutdown writes (abandon, release) pass strict and keep base's behaviour (F3, H1, G3); the peak cut path keeps EV-54's (G1). test_ev13 T13: fails is 1 now (Q2). New test_ev56.py.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 18:52:11 +01:00
ems-agent 344c974f90 Merge pull request 'EV-54: a refused peak cut no longer stops Solar; tried again next quarter' (#280) from EV-54 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-30 09:14:11 +01:00
8 changed files with 3206 additions and 21 deletions
+2
View File
@@ -2,6 +2,8 @@
### Not in a release yet
- **A car phase change whose current the charger refuses no longer sends that current five times.** After three refused tries the add-on stops at once and warns CHARGER_REFUSED; the car stays at 0 A until you change something. A value you change meanwhile gets its own three tries ([[EV-59]]).
- **A car current the add-on cannot send because of an error is no longer sent again every second.** It counts as a write the charger did not take: 3 tries a minute apart, then the add-on stops and warns CHARGER_REFUSED. The error is logged once per current ([[EV-56]]).
- **A peak cut the charger does not take no longer stops Solar.** After three refused tries in a 15-minute period, Solar goes on controlling the car and tries the cut again at the start of the next period while it is still needed. The warning now says "The charger did not take the peak cut, so the add-on tries again next quarter: CHARGER_REFUSED." ([[EV-54]]).
- **The add-on log now says when the add-on sets a new car current or the car mode changes.** One line each, for example "Car: set from 10 A to 6 A on 1 phase (Manual)." and "Car mode is now Manual." It names the reason: Manual, Solar, peak cut, start-up or shutdown. A refused write adds no such line, and nothing is written or timed differently ([[EV-52]]).
- **Solar now lowers the car first for the peak limit.** When the 15-minute period heads over the limit, Solar lowers the car before the batteries give more, and brings it back when the period allows. One grey note says "Solar lowered the car for the peak." A Solar car the add-on cannot lower (another writer, shadow mode, a stop) no longer hides a peak alarm. Manual and Off do not change. See "Car charger" in DOCS ([[EV-21]]).
@@ -0,0 +1,37 @@
# EV-56 — a charger write that raises is a not-taken try
`drv.write_current` raising (an HA call error, a binding or setup error, a bug)
left `ManualWriter._write` before any bookkeeping, so no caller counted it and
Manual and Solar sent the same write every cycle. The rules below are the PM
rulings Q1-Q4, F1, F3, G1-G3, H1, H3 and H4 (brief v6); the formal check is
reports/EV-56-formal-report.md.
## The rule, in plain words
- **A raise is a try the charger did not take**, on every path that writes a
current (the normal write, a phase change's 0 A and closing current, the
Off or shadow undo): the same RETRY_S spacing, MAX_TRIES cap, give-up and
CHARGER_REFUSED as a refusal, and the same writer state (`log` row,
`attempted_a`, a late accept). `ManualWriter._write` catches it and returns
False; the callers count it as before. Solar counts it in its own `_write`.
- **The tracker is not told** (Q2): no `note_write`, so no refusal window and
no stuck arming. The write's `end_write` (the mute) still runs.
- **One ERROR record per raised value** (Q1): "The car charger step failed",
with the traceback, at the first raise of a value; DEBUG on its retries. It
is armed again by another value written, a taken write, a user change and
the charger's return (G2), in `_rec_a`.
- **A peak cut try that raises** keeps EV-54's path: one DEBUG line, no record
(G1).
- **Shutdown is as before** (F3, H1, G3): `abandon` and `release` pass
`strict`, so a raise still leaves the write. Manual's give-back keeps its
CHARGER_RESTORE; Solar's release stops after 1 try with no cut standing and
keeps the cut path's 3 tries with one. No record at shutdown.
- **Cancel is not a raise**: only `Exception` is caught, never
`CancelledError`.
## Left as they were
The phase select (`write_phases`, Q4, EV-58), Solar's 4 fails for a refused
close (F1), Manual's up to 5 tries of a close value (H3, EV-59) and the cut
tries through a phase change (H4, EV-60). test_ev56.py T5b and T19b pin the
last two at base.
+114 -13
View File
@@ -148,6 +148,8 @@ class ManualWriter:
self._returned = False # ... and came back after being gone
self._r = None # the latest reading, for the phase count
self._late = None # (a, was, why, n) of a write not taken
self._rec_a = None # EV-56: the raised value already logged
self._close_k = 0 # EV-59: not-taken closes of the value owed
# ------------------------------------------------------------------ user
def user_changed(self) -> None:
@@ -158,9 +160,11 @@ class ManualWriter:
self.hold = self.other = False
self.mismatch_since = None
self.fails, self.fail_at, self.gave_up = 0, None, False
self._close_k = 0 # EV-59
self.phase_fails, self.phases_gave_up = 0, False
self.attempted_a = self.prior_a = None
self._late = None # EV-52: that request is not current now
self._rec_a = None # EV-56 (G2): a raise is logged again
# ------------------------------------------------------------------ step
async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp,
@@ -185,6 +189,7 @@ class ManualWriter:
self._seen = True
self.was_available = True
self.reapply = True # on return: only if it differs
self._rec_a = None # EV-56 (G2): logged again
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
if self.seq is not None:
if self.seq["stage"] in ("zero", "select") \
@@ -220,6 +225,7 @@ class ManualWriter:
if not (phases_need or cur_need):
self.rev_applied, self.reapply = rev, False
self.fails, self.blocked = 0, False
self._close_k = 0
if cur is not None:
self.last_a = cur # adopt what is already set
# EV-52 (PM Q2): a write taken late is logged once, here.
@@ -246,6 +252,7 @@ class ManualWriter:
self._failed(now)
return
self.fails, self.fail_at = 0, None
self._close_k = 0
if not phases_need:
self.rev_applied, self.reapply = rev, False
@@ -259,6 +266,15 @@ class ManualWriter:
"stops asking until you change it: CHARGER_REFUSED.")
_LOG.debug("The charger refused the current %d times.", self.fails)
def _close_end(self, now) -> None:
"""EV-59: the closing current was refused MAX_TRIES times in this
sequence. The value owed has had `_close_k` not-taken closes since the
last user change: `fails` is that count, so the give-up comes only
when the value has used all its tries; else the normal path gives the
rest."""
self.fails = max(min(self._close_k, MAX_TRIES) - 1, 0)
self._failed(now)
def _watch(self, cur, now) -> None:
"""Is the read-back what we wrote? A difference that stands for
`WRITER_S` is another writer."""
@@ -320,31 +336,58 @@ class ManualWriter:
async def _write(self, drv, a, was, now, tracker, **kw) -> bool:
why = kw.pop("why", None) or self._why_default()
n = kw.pop("n", None)
# EV-56: a raise at shutdown is left to the caller (CHARGER_RESTORE).
strict = kw.pop("strict", False)
self._late = None
if self._rec_a is not None and abs(self._rec_a - float(a)) > TOL_A:
self._rec_a = None # EV-56 (G2): another value
tracker.begin_write() # EV-12: the read-back is ours
if float(a) > TOL_A:
# EV-20 C6, THE ONE WRITE CLOCK: every non-zero current either
# writer sends, whatever path it comes from, is stamped here (the
# one write_current call). Solar's 30 s gate reads this stamp.
self.nonzero_at = now
err = None
try:
# EV-20: `kw` is only Solar's shorter read-back wait at shutdown.
ok = await drv.write_current(a, **kw)
except Exception as e: # noqa: BLE001
if strict:
raise
ok, err = False, e
finally:
self._stamp(now)
tracker.end_write(self.last_done)
if err is not None:
self._raised(err, a, was, now, why, n)
return False
tracker.note_write(now, was, a, ok, getattr(drv, "polls", ()))
tracker.end_write(self.last_done)
self.log.append(("current", a, now, ok))
if ok:
self.last_a = a
self.attempted_a = self.prior_a = None
self._rec_a = None # EV-56 (G2): a taken write
self._log_set(a, was, why, n)
else:
self.attempted_a, self.prior_a = a, was
self._late = (a, was, why, n) # logged if it is adopted later
return ok
def _raised(self, err, a, was, now, why, n) -> None:
"""EV-56: a write that raised (an HA call error, a setup error, a bug)
is a try the charger did not take, counted by the caller as a refusal
is. It is no charger answer, so the tracker is not told (Q2). Its
ERROR record, with the traceback, comes once per raised value (Q1)."""
self.log.append(("current", a, now, False))
self.attempted_a, self.prior_a = a, was
self._late = (a, was, why, n) # logged if it is adopted later
if self._rec_a is None:
self._rec_a = float(a)
_LOG.error("The car charger step failed", exc_info=err)
else:
_LOG.debug("The car charger write failed again: %s", err)
def _stamp(self, now) -> None:
self.last_done = (self._clock or (lambda: now))()
@@ -395,7 +438,8 @@ class ManualWriter:
a = None if q is None else self._restore_a(q.get("prev"), clamp)
if a is not None:
self._clock = self._clock or (lambda: now)
await self._write(drv, a, 0.0, now, tracker, why="shutdown")
await self._write(drv, a, 0.0, now, tracker, why="shutdown",
strict=True)
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
q = self.seq
@@ -469,15 +513,17 @@ class ManualWriter:
# still wanted, and one that is in place is adopted.
self.seq, self.rev_applied, self.reapply = None, None, False
self.fails, self.blocked = 0, False
self._close_k = 0
if not q.get("failed"):
self.phase_done_at = self.last_done # EV-15
return
q["failed"] = True # EV-15: a refused write ends it
q["tries"] += 1
self._close_k += 1 # EV-59: read by Manual's end only
if q["tries"] >= MAX_TRIES:
# Left at 0 A is the safe side; the next reading re-applies.
self.seq, self.last_a, self.reapply = None, None, True
self._failed(now)
self._close_end(now)
self.rev_applied = None
return
q["t1"] = now - SETTLE_S + 5.0 # again in 5 s
@@ -855,6 +901,7 @@ class SolarWriter(ManualWriter):
self.cut_warned = False # ... and its one CHARGER_REFUSED was given
self.sent_cut = False # `sent_a` went out as a cut try
self.refused_cut = None # a cut value the charger did not take
self._cap_end = False # EV-60: a capped close ended the change
def owe_start(self) -> None:
"""C1: the add-on starts in Off while an exit 0 A of its own was still
@@ -972,6 +1019,7 @@ class SolarWriter(ManualWriter):
the write goes out, so a write cancelled while it waits for its
read-back is never trusted (`live`)."""
prev = self.sent_a
strict = kw.pop("strict", False) # EV-56: `release` (H1)
why = kw.get("why")
if why is None:
# EV-52: the 0 A the start caused is `start-up`, else Solar's own.
@@ -998,15 +1046,22 @@ class SolarWriter(ManualWriter):
self.zero_at = self.zero_sent_at = now
self._owed(True) # C1: kept with the mode until back
try:
ok = await super()._write(drv, a, was, now, tracker, **kw)
ok = await super()._write(drv, a, was, now, tracker,
strict=True, **kw)
except Exception as e: # noqa: BLE001
if not cut_try:
raise
# EV-54 (T15): a cut write that raises is a refused cut try, so it
# is spaced and capped like one, not tried once per cycle.
_LOG.debug("The peak cut write failed: %s", e)
self.log.append(("current", a, now, False))
self.attempted_a, self.prior_a = a, was
if strict:
raise # EV-56 (H1): shutdown as before
# EV-56: a try the charger did not take, counted below as a
# refusal is; the tracker is not told (Q2).
self._raised(e, a, was, now, why, kw.get("n"))
else:
# EV-54 (T15): a cut write that raises is a refused cut try,
# so it is spaced and capped like one, not tried once per
# cycle.
_LOG.debug("The peak cut write failed: %s", e)
self.log.append(("current", a, now, False))
self.attempted_a, self.prior_a = a, was
ok = False
finally:
if zero:
@@ -1029,6 +1084,42 @@ class SolarWriter(ManualWriter):
or Solar's."""
return "peak cut" if q.get("cut") else "Solar"
def _close_end(self, now) -> None:
"""EV-60: no extra `_failed`. Each refused close was counted when it
went (`_write`), a cut try in `cut_fails` too, so the sequence's end
adds nothing (Manual's `_close_end` is EV-59's, unchanged)."""
def _cut_gate(self, now) -> bool:
"""EV-60 (Q1): the quarter key's cut tries are used up, or the last
refused one is less than RETRY_S old (`_put`'s two gates)."""
return self.cut_fails >= MAX_TRIES or (
self.cut_fail_at is not None and now - self.cut_fail_at < RETRY_S)
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
"""EV-60: Solar's capped close is a cut try, so it passes the cut's
gates. Tries used up: the change ends at its 0 A, nothing written
(`_cap_end`: `step` then leaves the plan as `end_switch(False)` put
it). The sequence's first cut close waits at 0 A until RETRY_S after
the last refused cut try (counts nothing, ends nothing); after a cut
close of the sequence went, the 5 s spacing of `_advance` rules."""
q = self.seq
if q["stage"] == "settle" and now - q["t1"] >= SETTLE_S \
and callable(want_a):
hi = CH.ENTITY_MAX_A if clamp is None else float(clamp)
a = min(max(float(want_a(q)), CH.MIN_A), hi)
if self._cut_try(a):
if self.cut_fails >= MAX_TRIES:
self.seq, self.last_a, self.reapply = None, None, True
self.rev_applied = None
self.plan.end_switch(False)
self._cap_end = True
return
if not q.get("cut_went") and self.cut_fail_at is not None \
and now - self.cut_fail_at < RETRY_S:
return
q["cut_went"] = True
await super()._advance(drv, r, cur, now, tracker, want_a, clamp, rev)
def _failed(self, now) -> None:
if self.sent_cut:
# EV-54 (Q1, F7): a refused cut try counts against the quarter's
@@ -1264,10 +1355,15 @@ class SolarWriter(ManualWriter):
async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None:
"""Step 1 of the safe sequence: 0 A (kept when it already stands).
A 0 A the charger does not take ends the change; tried again later
by the plan's own dwell."""
by the plan's own dwell. EV-60: under a cap that 0 A is a cut try and
passes the cut's gates; stopped by them the change waits (nothing
written or counted, never a give-up) for the next quarter key."""
owed = not (cur is not None and cur <= TOL_A and self.sent_a == 0.0
and self.taken)
if owed and self._cut_try(0.0) and self._cut_gate(now):
return
self.phase_done_at = None
if not (cur is not None and cur <= TOL_A and self.sent_a == 0.0
and self.taken):
if owed:
if not await self._write(drv, 0.0, cur, now, tracker):
self.plan.end_switch(False)
return
@@ -1353,6 +1449,7 @@ class SolarWriter(ManualWriter):
self.fresh_start = self.restart = True
self.mismatch_since = None
self.last_a = self.attempted_a = self.prior_a = None
self._rec_a = None # EV-56 (G2): logged again
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
stuck = bool(tracker is not None and tracker.stuck(now))
if not self.taken and self.sent_a is not None and not stuck \
@@ -1511,6 +1608,9 @@ class SolarWriter(ManualWriter):
clamp, None)
if any(x[0] == "phases" for x in self.log[n_log:]):
q["sel"] = True # a select went out, taken or not
if self.seq is None and self._cap_end:
self._cap_end = False # EV-60: ended at 0 A, plan as it was
return
if self.seq is None:
# Back on the old phases only when no select went out; after
# one the plan keeps the current it wrote (the lower one) and
@@ -1578,7 +1678,8 @@ class SolarWriter(ManualWriter):
if wait > 0:
await sleep(wait)
if await self._write(drv, 0.0, cur, clock(), tracker,
took_s=RELEASE_TOOK_S, why="shutdown"):
took_s=RELEASE_TOOK_S, why="shutdown",
strict=True):
self.released = True
return True
self.released = False
+4 -4
View File
@@ -799,10 +799,10 @@ for exc in (RuntimeError("the link broke"), hass.ReadOnly("read only")):
errs = [m for lv, m in LOG.rec[n0:]
if lv == "ERROR" and "car charger step failed" in m]
check(f"T13 write_current raises {type(exc).__name__}: as on the base: "
"never armed, no window left, no refusal counted, the mute set, "
"never armed, no window left, one refusal counted, the mute set, "
f"the step error logged once ({len(errs)})",
never_stuck(tr) and pend(w.c.car) is None
and w.c.car_writer.fails == 0 and w.c.car.mute_until > 0
and w.c.car_writer.fails == 1 and w.c.car.mute_until > 0
and len(errs) == 1)
@@ -1027,8 +1027,8 @@ BASE_SENDS = { # recorded on 76f4de2 (release/1.0 before EV-13)
'T19-inside': ([(1011, 0.0, False), (1071, 0.0, False), (1131, 0.0, False)], [(11, 'current', 0.0), (71, 'current', 0.0), (131, 'current', 0.0)]),
'T2-error-beside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []),
'T2-error-inside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []),
'T20-beside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False), (1095, 16.0, False), (1155, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
'T20-inside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False), (1095, 16.0, False), (1155, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
'T20-beside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
'T20-inside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
'T21-beside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]),
'T21-inside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]),
}
+8 -4
View File
@@ -704,7 +704,8 @@ async def t15():
await w.step(19)
w.sim.refuse = "error"
await w.step(40)
mid = (list(calls), w.wr.seq is None and w.wr.fails == 1,
mid = (list(calls), w.wr.seq is None and w.wr.fails == MAX_TRIES
and w.wr.gave_up,
bool(w.writes("phases")))
w.sim.refuse = None
await w.step(int(carmode.RETRY_S) + 10)
@@ -715,11 +716,14 @@ w, (calls, over, anyph) = run(t15())
tries = [c for c in calls if c[1] == 16.0]
gaps = [round(b[0] - a[0]) for a, b in zip(tries, tries[1:])]
check(f"T15: the restore is refused: tried {len(tries)} times ~5 s apart "
f"({gaps}), no select, sequence ends, one failed write counted",
f"({gaps}), no select, sequence ends, the 3 closes counted: given up "
"(EV-59)",
len(tries) == MAX_TRIES and all(4 <= g <= 6 for g in gaps) and over
and not anyph and not w.writes("phases"))
check("T15: after the refusal ends the current is back at 16 A, never a "
"select", w.sim.readback_a == 16 and not w.writes("phases"))
check("T15: EV-59: given up after the 3 closes: no 4th try, the current stays "
"at 0 A until a user change, never a select",
w.sim.readback_a == 0 and len(tries) == MAX_TRIES
and not w.writes("phases"))
# --- T14: the controller level (the EV-15 harness) ------------------------- #
File diff suppressed because it is too large Load Diff
+824
View File
@@ -0,0 +1,824 @@
"""EV-59: Manual gives one value at most MAX_TRIES tries per user change, the
phase-change closes included. `python3 -B test_ev59.py`
Rows T1-T25 and N1-N14 of reports/EV-59-test-plan.md. Here: T1-T13, T14c, T15
(the answering charger, writer level), T16, T17, T18 (source checks on the
edited test files), T20-T25, T11c and N1-N14 (N8, N10, N11 as source checks).
Carried by other suites, green and unedited: T14a, T14b, T14d (test_ev56 T8,
T11, T12, T13, T19b and their T20 digests), T15's T20 digests (test_ev56
[A]), T12b/T12c's EV-28 side (test_ev28 T11-T13), T19 (the listed suites).
EDITED, not unedited: test_ev56 T5, T5b and the golden "T20 T5 [R]" (Q1, Q2),
test_ev28 T15 (Q3, T11c), test_ev13 T13 text and T26 goldens (rulings).
The `ManualWriter` / `SolarWriter` on a stub driver, a stub tracker
and a stub reading; time is the 1 s step counter, never wall time. The close
of the plan's T5 world: 0 A at t=0 and the select at t=1, both taken, so the
settle ends at s=11 and the closes are at 11, 16, 21.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import logging
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 # noqa: E402
fails = []
CLOCK = {"t": 0}
LOG = []
BIG = 1e12
REF = "CHARGER_REFUSED"
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)
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 __init__(self):
self.notes = []
def begin_write(self):
pass
def end_write(self, *_):
pass
def note_write(self, now, was, a, ok, polls=()):
self.notes.append((now, a, ok))
def stuck(self, now):
return False
class Drv:
"""answer(a, n) -> True | False | "raise"; True sets the charger. `sel`:
the answer to write_phases. `phases_log`: (t, n, the power seen then)."""
def __init__(self, cur, answer, ph=1, sel=True):
self.cur, self.ph, self.answer, self.sel = cur, ph, answer, sel
self.calls, self.now, self.polls = [], 0.0, ()
self.phases_log, self.power = [], None
async def write_current(self, a, **kw):
self.calls.append((self.now, float(a)))
r = self.answer(float(a), len(self.calls))
if r == "raise":
raise RuntimeError("HA call error")
if r:
self.cur = float(a)
return bool(r)
async def write_phases(self, n):
self.phases_log.append((self.now, n, self.power))
if self.sel:
self.ph = n
return self.sel
def refuse(a, n):
return a == 0.0
def raises(a, n):
return True if a == 0.0 else "raise"
def snap(w):
q = w.seq
return dict(fails=w.fails, gave_up=w.gave_up, fail_at=w.fail_at,
seq=None if q is None else (q["stage"], q["tries"]),
last_a=w.last_a, reapply=w.reapply, rev_applied=w.rev_applied,
phase_done_at=w.phase_done_at, phase_fails=w.phase_fails)
class Run:
pass
def run(answer, secs, *, cls=CM.ManualWriter, cb=None, a=6.0, n=3, cur=10.0,
sel=True, power=None, avail=None, clamp=16.0, mode=CM.MANUAL,
rd_none=False, w=None):
"""One writer run, one step per second. `cb(t, st, w, drv)` may change the
request in `st` (a, n, rev, clamp, mode) or call `w.user_changed()` (use
`uc`); it may be a coroutine. Per step: the state before and after."""
LOG.clear()
w, trk = w or cls(), Trk()
drv = Drv(cur, answer, sel=sel)
st = dict(a=a, n=n, rev=1, clamp=clamp, mode=mode)
out = Run()
out.w, out.drv, out.trk, out.st = w, drv, trk, st
out.rows, out.errs, out.ucs = {}, [], []
async def main():
for t in range(secs):
drv.now = float(t)
CLOCK["t"] = t
if cb:
x = cb(t, st, w, drv)
if asyncio.iscoroutine(x):
await x
pw = power(t, drv) if power else (
0.0 if drv.cur == 0 else 1380.0)
drv.power = pw
r = Rd(None if rd_none else drv.cur, drv.ph, power=pw)
if avail is not None and not avail(t):
r.available = False
seq0 = w.seq is not None
try:
await w.step(drv, r, mode=st["mode"], want_a=st["a"],
want_phases=st["n"], rev=st["rev"],
clamp=st["clamp"], now=float(t), tracker=trk,
writing=True, status="charging")
except Exception as e: # noqa: BLE001
out.errs.append((t, e))
d = snap(w)
d["seq0"], d["ncalls"] = seq0, len(drv.calls)
out.rows[t] = d
asyncio.run(main())
out.log = list(LOG)
return out
def uc(st, w, t, out_ucs=None, **kw):
w.user_changed()
st["rev"] += 1
st.update(kw)
UCS.append(t)
UCS = []
def at(t0, **kw):
"""A callback: one user change at t0 with these request changes."""
def cb(t, st, w, drv):
if t == t0:
uc(st, w, t, **kw)
return cb
def nz(r, lo=-BIG, hi=BIG, a=None):
return [int(t) for t, x in r.drv.calls
if x > 0 and lo <= t < hi and (a is None or abs(x - a) < 0.01)]
def zeros(r):
return [int(t) for t, x in r.drv.calls if x == 0.0]
def refs(r):
return [t for t, lv, m in r.log if lv == "WARNING" and REF in m]
def recs(r):
return [t for t, lv, m in r.log if lv == "ERROR" and m == REC]
def near(got_, want, tol=1):
return len(got_) == len(want) and all(abs(g - w_) <= tol
for g, w_ in zip(got_, want))
def never(name, r, *, ucs=(), clamp=16.0):
"""N1 (no non-zero write while given up before a user change), N2 (one
REF per give-up), N5 (no select under load), N6 (nothing above the clamp
or in 0-6 A), N9 (no exception out of a step), N13 (closes at least 5 s
apart, normal tries RETRY_S apart)."""
bad1, bad3, up = [], [], 0
t_prev, gv = None, False
for t in sorted(r.rows):
row = r.rows[t]
before = r.rows.get(t - 1)
n_new = row["ncalls"] - (before["ncalls"] if before else 0)
if gv and n_new and not any(u <= t and u > (t_prev or -1) for u in ucs) \
and any(x > 0 for tt, x in r.drv.calls if tt == t):
bad1.append(t)
if row["gave_up"] and not (before or {}).get("gave_up"):
up += 1
# N3: not before MAX_TRIES tries of the value owed since the
# last user change (the last call's value, from that change on).
u0 = max([u for u in ucs if u <= t], default=-1)
last = [(tt, x) for tt, x in r.drv.calls if tt <= t and x > 0]
if last:
v = last[-1][1]
n_v = len([1 for tt, x in last if tt >= u0])
if n_v < CM.MAX_TRIES:
bad3.append((t, v, n_v))
if not row["gave_up"] and (before or {}).get("gave_up"):
gv = False
if any(u == t for u in ucs):
gv = False
elif row["gave_up"]:
gv = True
t_prev = t
nzc = [(t, x) for t, x in r.drv.calls if x > 0]
bad13 = []
for (ta, aa), (tb, ab) in zip(nzc, nzc[1:]):
inseq = r.rows[int(tb)]["seq0"]
lim = 5.0 if inseq else CM.RETRY_S
user = any(ta < u <= tb for u in ucs)
if tb - ta < lim - 1e-9 and not (user and not inseq) \
and abs(aa - ab) < 0.01:
bad13.append((ta, tb))
bad5 = [x for x in r.drv.phases_log if x[2] is not None
and x[2] >= CM.QUIET_W]
bad6 = [x for _t, x in nzc if x > clamp + 1e-9 or x < 6.0 - 1e-9]
check(f"{name}: N3 no give-up before MAX_TRIES tries of the value owed "
f"({bad3[:3]})", not bad3)
check(f"{name}: N1 no write while given up ({bad1[:3]}); N2 one REF per "
f"give-up ({len(refs(r))} for {up}); N5 no select under load "
f"({bad5[:2]}); N6 nothing above the clamp or under 6 A "
f"({bad6[:3]}); N9 no exception ({r.errs[:1]}); N13 spacing "
f"({bad13[:3]})",
not bad1 and len(refs(r)) == up and not bad5 and not bad6
and not r.errs and not bad13)
print("1. THE REPLAY, THE STATE AT THE CAP (T1, T2, T3, T23)")
UCS.clear()
R1 = run(refuse, 600)
check(f"T1: 6 A tried at {nz(R1)}: 11, 16, 21 and nothing after to 600 s; "
"the car stays at 0 A",
nz(R1) == [11, 16, 21] and R1.drv.cur == 0.0
and all(x == 6.0 for _t, x in R1.drv.calls if x > 0))
r21, r20 = R1.rows[21], R1.rows[20]
check(f"T2: at the 3rd refused close: seq None, last_a None, reapply, "
f"rev_applied None, fails MAX_TRIES, gave_up, fail_at 21, "
f"phase_done_at None ({r21}); one REF in that step ({refs(R1)})",
r21["seq"] is None and r21["last_a"] is None and r21["reapply"] is True
and r21["rev_applied"] is None and r21["fails"] == CM.MAX_TRIES
and r21["gave_up"] is True and r21["fail_at"] == 21
and r21["phase_done_at"] is None and r21["phase_fails"] == 0
and refs(R1) == [21] and r20["gave_up"] is False and r20["fails"] == 0)
check("T23: offByOne: the 2nd close (16) does not end the sequence and the "
"3rd (21) does; the states up to 16 are the base's",
R1.rows[11]["seq"] == ("settle", 1) and R1.rows[16]["seq"] ==
("settle", 2) and R1.rows[16]["fails"] == 0
and not R1.rows[16]["gave_up"] and R1.rows[21]["seq"] is None
and not any(refs(R1)[i] < 21 for i in range(len(refs(R1)))))
never("T1", R1)
RX = run(raises, 600)
strip = lambda d: {k: v for k, v in d.items() if k not in ("ncalls",)} # noqa
check("T3a: every close raises: calls, states and cycle by cycle as R; 1 "
f"ERROR record at 11 ({recs(RX)}), REF at 21 ({refs(RX)}); the "
"tracker is not told of a raise",
RX.drv.calls == R1.drv.calls
and all(strip(RX.rows[t]) == strip(R1.rows[t]) for t in range(600))
and recs(RX) == [11] and refs(RX) == [21]
and not [x for x in RX.trk.notes if x[1] > 0]
and len([x for x in R1.trk.notes if x[1] > 0]) == 3)
never("T3a", RX)
RM = run(lambda a, n: True if a == 0.0 else ("raise" if n in (2, 4)
else False), 600)
check("T3b: raise, refuse, raise: 3 tries, 1 ERROR, 1 REF at 21, fails "
f"{RM.rows[21]['fails']}",
nz(RM) == [11, 16, 21] and recs(RM) == [11] and refs(RM) == [21]
and RM.rows[21]["fails"] == CM.MAX_TRIES and RM.rows[21]["gave_up"]
and [x[1] for x in RM.trk.notes if x[1] > 0] == [6.0])
never("T3b", RM)
print("\n2. TAKEN CLOSES AND FOLLOW-UPS (T4, T5, T6, T7, T8)")
UCS.clear()
R4 = run(lambda a, n: a == 0.0 or n == 2, 400, cb=at(100, a=8.0))
r4 = R4.rows[11]
check(f"T4: the close taken on try 1: seq None, fails 0, no give-up, no REF, "
f"phase_done_at 11 ({r4['phase_done_at']}); 8 A at 100 gets 3 tries "
f"({nz(R4, 100, a=8.0)}) and one REF ({refs(R4)})",
r4["seq"] is None and r4["fails"] == 0 and not r4["gave_up"]
and r4["phase_done_at"] == 11 and near(nz(R4, 100, a=8.0),
[100, 160, 220])
and refs(R4) == [220])
never("T4", R4, ucs=[100])
for tag, tk in (("a", 3), ("b", 4)):
UCS.clear()
R5 = run(lambda a, n, tk=tk: a == 0.0 or n == tk, 400, cb=at(100, a=8.0))
r5 = R5.rows[40]
check(f"T5{tag}: close taken on try {tk - 1}: fails 0, no give-up, no "
f"REF, phase_done_at None ({r5['phase_done_at']}); 8 A at 100 gets "
f"3 full tries ({nz(R5, 100, a=8.0)})",
r5["fails"] == 0 and not r5["gave_up"] and r5["seq"] is None
and r5["phase_done_at"] is None
and near(nz(R5, 100, a=8.0), [100, 160, 220])
and refs(R5) == [220] and R5.rows[21]["fails"] == 0)
never(f"T5{tag}", R5, ucs=[100])
for tag, kw, want in (("a", dict(a=8.0), 8.0), ("b", dict(a=6.0), 6.0)):
UCS.clear()
R6 = run(refuse, 400, cb=at(100, **kw))
got6 = nz(R6, 100, a=want)
check(f"T6{tag}: after the give-up a user change to {want:.0f} A: a "
f"write at 100 and tries at +60, +120, then REF once more, never "
f"a 4th ({got6}, REF {refs(R6)})",
near(got6, [100, 160, 220]) and refs(R6) == [21, 220]
and R6.rows[100]["gave_up"] is False)
never(f"T6{tag}", R6, ucs=[100])
UCS.clear()
R6c = run(refuse, 760, cb=at(700, n=1))
check(f"T6c: after the give-up a 1 phase request (past PHASE_GAP_S): gave_up "
f"does not block it; the 0 A at 700 ({zeros(R6c)}), the select at the "
f"quiet car, then closes ({nz(R6c, 700)})",
near([z for z in zeros(R6c) if z >= 700], [700])
and R6c.rows[700]["gave_up"] is False
and [x[1] for x in R6c.drv.phases_log if x[0] >= 700] == [1]
and near(nz(R6c, 700), [711, 716, 721]) and refs(R6c) == [21, 721])
UCS.clear()
def off_then_manual(t, st, w, drv):
if t == 100:
st["mode"] = "off"
if t == 103:
st["mode"] = CM.MANUAL
uc(st, w, t)
R6d = run(refuse, 400, cb=off_then_manual)
check(f"T6d: Off, then Manual at 103: as T6b from the pick "
f"({nz(R6d, 100, a=6.0)})",
near(nz(R6d, 100, a=6.0), [103, 163, 223]) and refs(R6d) == [21, 223])
UCS.clear()
R7a = run(refuse, 600, avail=lambda t: not 130 <= t < 161)
check(f"T7a: the charger away 130-160, back at 161: no write after the "
f"return to 600 s ({nz(R7a, 100)}); gave_up stays",
nz(R7a, 100) == [] and R7a.rows[599]["gave_up"] and refs(R7a) == [21])
never("T7a", R7a)
R7b = run(refuse, 600, avail=lambda t: not 12 <= t < 31)
check(f"T7b: away between close 1 and 2, back at 31: the count goes on: 3 "
f"tries of 6 A ({nz(R7b)}), then the give-up, REF once ({refs(R7b)})",
len(nz(R7b, a=6.0)) == 3 and R7b.rows[599]["gave_up"]
and len(refs(R7b)) == 1
and all(b - a >= 5 for a, b in zip(nz(R7b), nz(R7b)[1:])))
never("T7b", R7b)
UCS.clear()
R7c = run(raises, 600, avail=lambda t: not 130 <= t < 161,
cb=at(200, a=6.0))
check(f"T7c: X, away and back, then a user change at 200: no write before "
f"200 after the return; the record is armed again: ERROR at "
f"{recs(R7c)} (1 before 200, 1 after)",
not nz(R7c, 100, 200) and len([x for x in recs(R7c) if x < 200]) == 1
and len([x for x in recs(R7c) if x >= 200]) == 1)
UCS.clear()
R8 = run(lambda a, n: a == 0.0 or n == 4, 1200, cb=at(700, n=1))
b_calls = nz(R8, 700)
check(f"T8: sequence A (refused, refused, taken): fails "
f"{R8.rows[21]['fails']}, no give-up; then sequence B: 3 tries "
f"({b_calls}), no give-up after 1 or 2 "
f"({R8.rows[711]['gave_up']}, {R8.rows[716]['gave_up']}), then the "
f"give-up and 1 REF ({refs(R8)})",
R8.rows[21]["fails"] == 0 and not R8.rows[21]["gave_up"]
and near(b_calls, [711, 716, 721])
and not R8.rows[711]["gave_up"] and not R8.rows[716]["gave_up"]
and R8.rows[721]["gave_up"] and refs(R8) == [721])
never("T8", R8, ucs=[700])
print("\n3. A USER CHANGE DURING THE CLOSE RETRIES (T9, T24)")
for tag, t0, kw, want, exp_a, exp_6 in (
("a", 18, dict(a=8.0), 8.0, [21, 81, 141], [11, 16]),
("b", 13, dict(a=8.0), 8.0, [16, 21, 81], [11])):
for how, ans in (("R", refuse), ("X", raises)):
UCS.clear()
R9 = run(ans, 600, cb=at(t0, **kw))
g8 = nz(R9, a=8.0)
refs9 = refs(R9)
check(f"T9{tag} [{how}]: user change to 8 A at {t0}: 8 A gets "
f"exactly 3 tries ({g8}), the 6 A before it ({nz(R9, a=6.0)}); "
f"the REF once, at the 3rd try ({refs9}); fails after the "
f"close end {R9.rows[21]['fails']}",
near(g8, exp_a) and nz(R9, a=6.0) == exp_6
and refs9 == [exp_a[-1]]
and not any(R9.rows[t]["gave_up"] for t in range(exp_a[-1]))
and R9.rows[exp_a[-1]]["gave_up"])
never(f"T9{tag} [{how}]", R9, ucs=[t0])
UCS.clear()
R24 = run(refuse, 600, cb=at(18, a=8.0))
check("T24b: the user change after close 2: at the close end (21) fails 1, "
f"no give-up ({R24.rows[21]['fails']}, {R24.rows[21]['gave_up']}); the "
"normal path gives 2 more tries >= RETRY_S apart, then 1 REF",
R24.rows[21]["fails"] == 1 and not R24.rows[21]["gave_up"]
and R24.rows[81]["fails"] == 2 and R24.rows[141]["fails"] == 3
and R24.rows[141]["gave_up"] and refs(R24) == [141])
check("T24a: no user change: k = 3, fails 3, gave_up, 1 REF at the close end "
f"({R1.rows[21]['fails']}, {refs(R1)})",
R1.rows[21]["fails"] == CM.MAX_TRIES and refs(R1) == [21])
UCS.clear()
R9c = run(refuse, 600, cb=at(18, a=6.0))
after = [t for t in nz(R9c, a=6.0) if t >= 18]
check(f"T9c: the same value again at 18: 3 tries after the change ({after}), "
f"REF once at the last ({refs(R9c)})",
near(after, [21, 81, 141]) and refs(R9c) == [141]
and nz(R9c, a=6.0)[:2] == [11, 16])
never("T9c", R9c, ucs=[18])
UCS.clear()
R9d = run(refuse, 600, cb=at(2, a=8.0))
check(f"T9 (change before the 1st close): 8 A gets 3 tries "
f"({nz(R9d, a=8.0)}), REF {refs(R9d)}",
len(nz(R9d, a=8.0)) == 3 and len(refs(R9d)) == 1)
print("\n4. THE CLAMP, THE RESTORE CLOSES, THE SELECT (T10, T11, T12)")
UCS.clear()
def clamp_falls(t, st, w, drv):
if t == 18:
st["clamp"] = 8.0
R10 = run(refuse, 400, a=10.0, clamp=10.0, cb=clamp_falls)
check(f"T10: the clamp falls to 8 A at 18: tries {nz(R10)} with values "
f"{[x for _t, x in R10.drv.calls if x > 0]}: never above the clamp then, "
f"at most 3 in all, REF once ({refs(R10)})",
len(nz(R10)) == 3 and [x for _t, x in R10.drv.calls if x > 0]
== [10.0, 10.0, 8.0] and refs(R10) == [21])
never("T10", R10, clamp=10.0)
UCS.clear()
R11a = run(refuse, 400, cur=16.0, a=16.0, power=lambda t, d: 1380.0,
cb=at(300))
check(f"T11a: the drawing timeout, the 16 A restore refused: 3 tries 5 s "
f"apart ({nz(R11a, 0, 300)}), fails {R11a.rows[30]['fails']}, "
f"gave_up, REF once ({refs(R11a)}); phase_fails "
f"{R11a.rows[30]['phase_fails']}; no select ({R11a.drv.phases_log}); "
f"a user change writes 16 A at once ({nz(R11a, 300)[:1]})",
near(nz(R11a, 0, 300), [20, 25, 30])
and R11a.rows[30]["fails"] == CM.MAX_TRIES and R11a.rows[30]["gave_up"]
and refs(R11a) == [30] and R11a.rows[30]["phase_fails"] == 1
and R11a.rows[20]["fails"] == 0 and R11a.rows[25]["fails"] == 0
and not R11a.drv.phases_log and nz(R11a, 300)[:1] == [300])
never("T11a", R11a, ucs=[300])
UCS.clear()
R11b = run(refuse, 400, cur=16.0, a=16.0, sel=False, cb=at(300))
check(f"T11b: the select refused, the restore close refused: 3 tries "
f"({nz(R11b, 0, 300)}), fails {R11b.rows[21]['fails']}, gave_up, "
f"REF once ({refs(R11b)}); phase_fails {R11b.rows[21]['phase_fails']}; "
f"1 select try ({len(R11b.drv.phases_log)}); a user change writes at "
"once",
near(nz(R11b, 0, 300), [11, 16, 21])
and R11b.rows[21]["fails"] == CM.MAX_TRIES and R11b.rows[21]["gave_up"]
and refs(R11b) == [21] and R11b.rows[21]["phase_fails"] == 1
and len(R11b.drv.phases_log) == 1 and nz(R11b, 300)[:1] == [300])
never("T11b", R11b, ucs=[300])
UCS.clear()
R12a = run(lambda a, n: a != 0.0, 400)
check(f"T12a: only the 0 A fails (_begin): tries {zeros(R12a)} >= 60 s "
f"apart, at most 3, no select, REF once ({refs(R12a)})",
0 < len(zeros(R12a)) <= 3 and not R12a.drv.phases_log
and all(b - a >= 60 for a, b in zip(zeros(R12a), zeros(R12a)[1:]))
and len(refs(R12a)) == 1 and R12a.rows[399]["gave_up"])
R12b = run(lambda a, n: True, 100, sel=False)
check(f"T12b: a refused select counts for the phases only: close taken, fails "
f"{R12b.rows[60]['fails']}, phase_fails {R12b.rows[60]['phase_fails']}, "
"no REF",
R12b.rows[60]["fails"] == 0 and R12b.rows[60]["phase_fails"] == 1
and R12b.rows[1]["fails"] == 0 and R12b.rows[1]["phase_fails"] == 1
and not refs(R12b) and not R12b.rows[60]["gave_up"])
R12c = run(lambda a, n: True, 100, cur=16.0, a=16.0,
power=lambda t, d: 1380.0)
check(f"T12c: the drawing timeout, the restore taken: fails "
f"{R12c.rows[60]['fails']}, no give-up, phase_fails "
f"{R12c.rows[60]['phase_fails']}",
R12c.rows[60]["fails"] == 0 and not R12c.rows[60]["gave_up"]
and R12c.rows[60]["phase_fails"] == 1 and not refs(R12c))
print("\n5. UNDO, SHUTDOWN, SOLAR, A CHARGER THAT ANSWERS (T13, T14, T15)")
UCS.clear()
def off_at(t0):
def cb(t, st, w, drv):
if t == t0:
st["mode"] = "off"
return cb
R13a = run(refuse, 100, power=lambda t, d: 1380.0, cb=off_at(5))
check(f"T13a: Off in stage zero: 10 A restored once ({nz(R13a)}), undone "
f"{R13a.w.undone}, fails {R13a.rows[99]['fails']}",
near(nz(R13a, a=10.0), [5]) and len(nz(R13a)) == 1
and R13a.w.undone == 1 and R13a.rows[99]["fails"] == 0)
R13b = run(refuse, 100, cb=off_at(12))
check(f"T13b: Off after close 1: the closes go on ({nz(R13b)}), give-up at "
f"21, REF once ({refs(R13b)}), no write after",
nz(R13b) == [11, 16, 21] and R13b.rows[21]["gave_up"]
and refs(R13b) == [21])
box = {}
def abandon_cb(t0, ans_kind):
def cb(t, st, w, drv):
if t == t0 + 1:
async def go():
n0 = len(drv.calls)
try:
await w.abandon(drv, float(t), Trk(), clamp=16.0)
box[ans_kind] = ("ok", len(drv.calls) - n0)
except RuntimeError:
box[ans_kind] = ("raised", len(drv.calls) - n0)
return go()
return cb
R13c = run(refuse, 40, cb=abandon_cb(11, "R"))
check(f"T13c: shutdown between close 1 and 2: the old 10 A restored once, "
f"strict, no exception ({box.get('R')}), seq None, calls {nz(R13c)}",
box.get("R") == ("ok", 1) and R13c.w.seq is None
and near(nz(R13c, a=10.0), [12]))
R13x = run(raises, 40, cb=abandon_cb(11, "X"))
check(f"T13c: X: the raise comes out of abandon, as base, for the caller's "
f"CHARGER_RESTORE ({box.get('X')}); the writer's seq is None",
box.get("X") == ("raised", 1) and R13x.w.seq is None)
R13d = run(refuse, 40, cb=abandon_cb(40, "D"))
n_d = len(R13d.drv.calls)
async def after_giveup():
n0 = len(R13d.drv.calls)
await R13d.w.abandon(R13d.drv, 41.0, Trk(), clamp=16.0)
return len(R13d.drv.calls) - n0
check("T13d: shutdown after the give-up: no write",
asyncio.run(after_giveup()) == 0 and R13d.w.gave_up)
def solar_writer(cur):
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, 1
w._plan_step = lambda *a, **k: None
return w
def sp3(press, cls=solar_writer):
LOG.clear()
drv = Drv(8.0, refuse)
w, trk = cls(8.0), Trk()
w.plan._set(8.0, 0.0, 3)
pressed = None
async def main():
nonlocal pressed
for t in range(1, 200):
if press and pressed is None and \
len([x for x in drv.calls if x[1] > 0]) == 1:
w.user_changed()
pressed = t
drv.now = float(t)
CLOCK["t"] = t
w.cut_quarter(int(t // 900))
r = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
await 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")
asyncio.run(main())
nzs = [int(t) for t, x in drv.calls if x > 0]
rf = [t for t, lv, m in LOG if lv == "WARNING" and REF in m]
return nzs, w.fails, w.gave_up, rf, pressed
S_NONE = sp3(False)
S_PRESS = sp3(True)
check(f"T25/T14 (N14, EV-60): Solar has no extra _failed at its close end. "
f"No press: 8 A at 12, 17, 22, fails 3, gave_up, REF at 22 "
f"({S_NONE})",
S_NONE == ([12, 17, 22], 3, True, [22], None))
check(f"T25 (resetSuper trap, EV-60): a Solar press at 13 does not reset "
f"Solar's close tries, and the value gets MAX_TRIES tries since the "
f"press: 8 A at 12, 17, 22, 82, fails 3, gave_up, REF at 82 "
f"({S_PRESS})",
S_PRESS == ([12, 17, 22, 82], 3, True, [82], 13))
def t14c():
"""T14c: Solar's close value changes between the tries (the spare falls
during the settle): `want_a(q)` is a function of the sequence. `_advance`
driven directly on a SolarWriter in stage settle, the close refused."""
LOG.clear()
w, drv, trk = solar_writer(8.0), Drv(0.0, lambda a, n: False), Trk()
w.seq = {"stage": "settle", "t0": 0.0, "n": 3, "tries": 0, "prev": 8.0,
"t1": 0.0}
vals = {10: 8.0, 15: 7.0, 20: 6.0}
async def main():
for t in range(10, 40):
if w.seq is None:
break
drv.now = float(t)
CLOCK["t"] = t
r = Rd(drv.cur, drv.ph, power=0.0)
await w._advance(drv, r, 0.0, float(t), trk,
lambda q: vals.get(t, 5.0), 16.0, 1)
asyncio.run(main())
rf = [t for t, lv, m in LOG if lv == "WARNING" and REF in m]
return ([(int(t), x) for t, x in drv.calls], w.fails, w.gave_up, rf,
w.seq)
S14C = t14c()
check(f"T14c (N14, EV-60): Solar's close value moves between tries: 8, 7, 6 A "
f"at 10, 15, 20, then `fails` 3 (no extra _failed), gave_up, REF at "
f"20, seq None ({S14C})",
S14C == ([(10, 8.0), (15, 7.0), (20, 6.0)], 3, True, [20], None))
print("\n6. THE CAP, RESTART, UNKNOWN, NO CHARGER (T15-T22)")
UCS.clear()
RA = run(lambda a, n: True, 100)
check(f"T15: a charger that answers: 0 A at 0, 6 A at 11, nothing else "
f"({RA.drv.calls}); fails 0, no give-up, phase_done_at "
f"{RA.rows[11]['phase_done_at']}",
RA.drv.calls == [(0.0, 0.0), (11.0, 6.0)]
and RA.rows[99]["fails"] == 0 and RA.rows[11]["phase_done_at"] == 11
and not refs(RA))
for cap in (2, 4):
UCS.clear()
saved = CM.MAX_TRIES
CM.MAX_TRIES = cap
try:
R16 = run(refuse, 400)
finally:
CM.MAX_TRIES = saved
want16 = [11 + 5 * i for i in range(cap)]
check(f"T16: MAX_TRIES {cap}: tries {nz(R16)} (never {cap + 1}), give-up "
f"at {want16[-1]}, REF {refs(R16)}",
nz(R16) == want16 and refs(R16) == [want16[-1]]
and R16.rows[want16[-1]]["fails"] == cap
and R16.rows[want16[-1]]["gave_up"])
UCS.clear()
w20 = CM.ManualWriter()
check("T20: a restart: the new writer starts with 0 fails, no give-up, and "
"no count",
w20.fails == 0 and not w20.gave_up
and getattr(w20, "_close_k", 0) == 0)
R20 = run(refuse, 30, w=w20)
check(f"T20: after the restart the first write goes out once ({zeros(R20)})",
zeros(R20) == [0])
R21 = run(refuse, 400, rd_none=True)
check(f"T21: the read-back unknown (allowed and setpoint None): judged by the "
f"write's result: tries {nz(R21)}, give-up, REF once ({refs(R21)})",
len(nz(R21)) == 3 and R21.rows[399]["gave_up"] and len(refs(R21)) == 1
and not R21.errs)
R21b = run(refuse, 400, power=lambda t, d: None, cur=16.0, a=16.0)
check(f"T21: the power unknown: the drawing timeout's restore is tried 3 "
f"times (20, 25, 30), then the give-up and one REF, no exception "
f"({nz(R21b)}, {refs(R21b)}, {R21b.errs[:1]})",
nz(R21b) == [20, 25, 30] and R21b.rows[30]["gave_up"]
and refs(R21b) == [30] and not R21b.errs)
R22 = run(refuse, 600, avail=lambda t: False)
check("T22: no charger: 0 writes, no lines, no REF",
not R22.drv.calls and not R22.log and not refs(R22))
print("\n6b. A GIVE-UP NEVER BLOCKS THE UNDO, THE SHUTDOWN OR A NEW SEQUENCE (N4)")
def given_up_writer():
w = CM.ManualWriter()
w.gave_up, w.fails = True, CM.MAX_TRIES
w.seq = {"stage": "zero", "t0": 0.0, "n": 3, "tries": 0, "prev": 10.0}
return w, Drv(0.0, lambda a, n: True), Trk()
w13, d13, t13 = given_up_writer()
asyncio.run(w13._undo(d13, 1.0, t13, 16.0, False))
check(f"T13e/N4: `_undo` with gave_up set restores the 10 A ({d13.calls})",
d13.calls == [(0.0, 10.0)] and w13.seq is None)
w13, d13, t13 = given_up_writer()
asyncio.run(w13.abandon(d13, 1.0, t13, clamp=16.0))
check(f"T13e/N4: `abandon` with gave_up set gives the 10 A back "
f"({d13.calls})", d13.calls == [(0.0, 10.0)] and w13.seq is None)
w13, d13, t13 = given_up_writer()
w13.seq = None
asyncio.run(w13._begin(d13, Rd(10.0), 10.0, 3, 1.0, t13))
check(f"T13e/N4: `_begin` with gave_up set still writes the 0 A "
f"({d13.calls})", d13.calls == [(0.0, 0.0)] and w13.seq is not None)
print("\n6c. THE EDITS TO EXISTING TESTS, N7, N12 (T17, T18, T11c, N7, N11, N12)")
def tsrc(name):
return open(os.path.join(HERE, name), encoding="utf-8").read()
s56, s13, s28 = tsrc("test_ev56.py"), tsrc("test_ev13.py"), tsrc("test_ev28.py")
BASE_DIGESTS = ("905c0b8ba89bb307", "343ea01aacfa1019", "ff6306ce56b35c64",
"f1fb141275839562", "369069be9187ab3c", "2cd78dee7ee93aaa",
"f0adb058a5bbefba", "6d7bcb747d1dc5a3", "2be1a760b699b28c",
# EV-60 (Q4): "T20 T12 [R]" re-taken, was 2fd24ddbb18f14cc
"a5888e4557b4ee8f", "25a205989dc44204", "1ad97e089468d71b",
"7baf8981ab382e05", "54701b140ec6f30b", "0cfd3ccd334f378d",
"1d85595302dc032a", "5fc65dbdc730e539")
check("T17 (Q1, Q2): test_ev56 has the re-taken golden 'T20 T5 [R]' "
"(78ffe9cf72c5e214, the old ba32810fbb40d0f9 gone), T5 asserts "
"fails == MAX_TRIES and gave_up, T5b asserts len == MAX_TRIES",
'"T20 T5 [R]": "78ffe9cf72c5e214"' in s56
and "ba32810fbb40d0f9" not in s56
and 'end5[1]["fails"] == CM.MAX_TRIES' in s56
and 'end5[1]["gave_up"] is True' in s56
and "len(six) == CM.MAX_TRIES" in s56)
check("N11: every other golden digest of test_ev56 is the base's, and "
"GOLDEN['T5b'] still holds base's 5 tries",
all(f'"{d}"' in s56 for d in BASE_DIGESTS)
and '"T5b": [(111.0, 6.0), (116.0, 6.0), (121.0, 6.0), (181.0, 6.0),'
in s56)
check("T18: test_ev13 T13's check text says 'one refusal counted' and its "
"assert is still fails == 1",
"no window left, one refusal counted, the mute set" in s13
and "no refusal counted" not in s13
and "w.c.car_writer.fails == 1 and w.c.car.mute_until > 0" in s13)
check("N11: test_ev13 T26 lost only the 4th and 5th tries (1095, 1155) of "
"'T20-beside' and 'T20-inside'",
s13.count("(1035, 16.0, False)], [(11, 'current', 0.0), "
"(15, 'phases', 1)])") == 2
and "(1095, 16.0, False)" not in s13
and "(1155, 16.0, False)" not in s13)
check("T11c: test_ev28 T15 asserts fails == MAX_TRIES, gave_up, 3 tries and "
"the car at 0 A with no select (the only edit, ruled Q3)",
"w.wr.fails == MAX_TRIES" in s28 and "w.wr.gave_up" in s28
and "w.sim.readback_a == 0 and len(tries) == MAX_TRIES" in s28)
UCS.clear()
RN7 = run(lambda a, n: True, 400, cb=at(100, a=8.0))
check(f"N7: a charger that answers: the calls are 0 A at 0, 6 A at 11, 8 A at "
f"100 and nothing else ({RN7.drv.calls}); no REF, fails 0, no "
"give-up, no ERROR",
RN7.drv.calls == [(0.0, 0.0), (11.0, 6.0), (100.0, 8.0)]
and not refs(RN7) and not recs(RN7)
and RN7.rows[399]["fails"] == 0 and not RN7.rows[399]["gave_up"])
n12 = [x for x in R1.trk.notes if x[1] > 0]
check(f"N12: the tracker is told of each refused close once ({n12}) and of "
f"no raised close ({[x for x in RX.trk.notes if x[1] > 0]}, "
f"begin/end per write {RX.trk.notes[:1]})",
len(n12) == 3 and all(not ok for _t, _a, ok in n12)
and not [x for x in RX.trk.notes if x[1] > 0])
print("\n7. N4, N8, N10")
APP = os.path.join(HERE, "app")
SRC = {f: open(os.path.join(APP, f), encoding="utf-8").read()
for f in sorted(os.listdir(APP)) if f.endswith(".py")}
cm_src = SRC["carmode.py"]
check("N8 (write_phases and the peak-cut rules untouched): carmode.py still "
"has the one `write_phases(` call and no new write path; base had 1",
cm_src.count("write_phases(") == 1
and cm_src.count("drv.write_current(") == 1)
check("N10 (no new store key, setting, notification or timer): `_close_k` "
"lives in carmode.py only, never next to a store or option; the "
"asyncio.sleep, create_task and _LOG.warning counts are the base's "
"(1, 0, 10)",
[f for f, s in SRC.items() if "_close_k" in s] == ["carmode.py"]
and cm_src.count("asyncio.sleep") == 1
and cm_src.count("create_task") == 0
and cm_src.count("_LOG.warning(") == 10
and not any("_close_k" in line and ("store" in line or "opts" in line)
for line in cm_src.splitlines()))
w4 = CM.ManualWriter()
w4.gave_up, w4.fails, w4._close_k = True, 3, 3
w4.user_changed()
check("N4: user_changed clears gave_up, fails and the close count",
not w4.gave_up and w4.fails == 0 and w4._close_k == 0)
R4n = run(refuse, 400, cb=at(100, a=8.0))
check("N4: a give-up does not block the next user change or phase change "
f"({nz(R4n, 100)[:1]})", nz(R4n, 100)[:1] == [100])
print()
if fails:
print(f"FAIL: {len(fails)} check(s)")
for f in fails:
print(" -", f)
sys.exit(1)
print("ok: EV-59")
+889
View File
@@ -0,0 +1,889 @@
"""EV-60: Solar never passes EV-54's cap of MAX_TRIES refused cut tries per
quarter key (the phase change's 0 A and the capped close included), and a
Solar press during the close retries gives the value MAX_TRIES tries.
`python3 -B test_ev60.py`
Rows T1-T24 (with T1b, T2b, T2c, T3b, T3c, T8b, T21b) and N1-N14 of
reports/EV-60-test-plan.md. Here: T1-T11, T14 (writer level), T16-T22, T24
(the shutdown rows against `Base60`), and the source checks of T15, T23 and
N7, N10, N11. Carried by the other suites, green: T12 (test_ev54*), T13
(test_ev59 Manual rows, test_ev56, test_ev28, test_ev15, test_ev04), T15
(test_ev56 T12, "T20 T12 [R]"), T23.
Writer level: `SolarWriter` on a stub driver, a stub tracker and a stub
reading; time is the 1 s step counter, never wall time. R = the answer False,
X = it raises. `Base60` is 2e09622's Solar (the three methods this ticket
changes, restored); it is the red side of every row (mutant M1).
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import hashlib
import inspect
import logging
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 # noqa: E402
fails = []
CLOCK = {"t": 0}
LOG = []
REF_S = "until you press Solar: CHARGER_REFUSED."
Q3W = "tries again next quarter: CHARGER_REFUSED."
CUTDBG = "The peak cut write failed"
REC = "The car charger step failed"
MANUAL_SHA = "284ce1a94bfb7a6335f224a29bddc4e0b80c36af78b5c7907031c511a6a9eaa8"
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 near(got, want, tol=1.0):
return len(got) == len(want) and all(abs(g - w) <= tol
for g, w in zip(got, want))
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 __init__(self):
self.notes = []
def begin_write(self):
pass
def end_write(self, *_):
pass
def note_write(self, now, was, a, ok, polls=()):
self.notes.append((now, a, ok))
def stuck(self, now):
return False
class Drv:
def __init__(self, cur, answer, ph=1, sel=True):
self.cur, self.ph, self.answer, self.sel = cur, ph, answer, sel
self.calls, self.now, self.polls = [], 0.0, ()
self.phases_log = []
async def write_current(self, a, **kw):
self.calls.append((self.now, float(a)))
r = self.answer(float(a), len(self.calls))
if r == "raise":
raise RuntimeError("HA call error")
if r:
self.cur = float(a)
return bool(r)
async def write_phases(self, n):
self.phases_log.append((self.now, n, self.cur))
if self.sel:
self.ph = n
return self.sel
def _clock(self):
return self.now
async def _sleep(self, s):
self.now += s
class Base60(CM.SolarWriter):
"""2e09622's Solar: the three things EV-60 changes, as they were."""
async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None:
self.phase_done_at = None
if not (cur is not None and cur <= CM.TOL_A and self.sent_a == 0.0
and self.taken):
if not await self._write(drv, 0.0, cur, now, tracker):
self.plan.end_switch(False)
return
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
"prev": None, "from": r.phases_allowed}
async def _advance(self, *a, **k):
return await CM.ManualWriter._advance(self, *a, **k)
def _close_end(self, now) -> None:
self._failed(now)
def solar_writer(cur, 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, 1
def plan_step(sun, now, clamp, n, gap):
"""The plan's own rule, the part that matters here: a standing cap
lowers its current (`SolarPlan.step` -> `_cut`), nothing else moves."""
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
LOOP = asyncio.new_event_loop()
ALL = [] # every writer-level run of the design
class Res:
pass
def state(w, drv):
q = w.seq
return dict(cf=w.cut_fails, f=w.fails, gu=w.gave_up,
seq=None if q is None else (q["stage"], q["tries"]),
sw=w.plan.switch, n=len(drv.calls), re=w.reapply,
la=w.last_a, rv=w.rev_applied, pa=w.plan.a, pn=w.plan.n,
warned=w.cut_warned)
def world(kind, until, *, start=0, setup=None, pre=None, post=None,
take=None, cls=None, cur=8.0, sun=None, avail=None):
"""One writer-level run from `start` to `until` (both included). `take`
(a, drv, w) -> True: the charger takes the write; the others are refused
(R) or raise (X) as `kind`'s characters say, one per refused write, the
last repeated. `pre` / `post`: (w, drv, t) before / after each step."""
del LOG[:]
r = Res()
r.kind, r.tries, r.viol, r.snap, r.refused = kind, [], [], {}, 0
r.ended, r.noncut, r.cap_ = None, 0, CM.MAX_TRIES
w = solar_writer(cur, cls)
trk = Trk()
def answer(a, n):
cut = w.cut_a
if cut is not None and a > cut + CM.TOL_A:
r.viol.append((drv.now, a))
if 0.0 < a < CM.CH.MIN_A - 1e-9:
r.viol.append((drv.now, a))
ok = take(a, drv, w) if take else (a == 0.0 and w.cut_a is None)
if ok:
return True
c = kind[min(r.refused, len(kind) - 1)]
r.refused += 1
if cut is not None and a <= cut + CM.TOL_A:
r.tries.append(int(drv.now))
else:
r.noncut += 1
return "raise" if c == "X" else False
drv = Drv(cur, answer)
r.w, r.drv = w, drv
if setup:
setup(w, drv)
for t in range(start, until + 1):
drv.now = float(t)
CLOCK["t"] = t
if pre:
pre(w, drv, t)
w.cut_quarter(int(t // 900))
rd = Rd(drv.cur, drv.ph, power=(0.0 if drv.cur == 0 else 1840.0))
if avail is not None and not avail(t):
rd.available = False
had = w.seq is not None
s = sun(t) if sun else CM.SunInputs(target_w=2000.0)
LOOP.run_until_complete(w.step(
drv, rd, mode=CM.SOLAR, sun=s, clamp=16.0, now=float(t),
tracker=trk, writing=True, status="charging"))
if had and w.seq is None and r.ended is None:
r.ended = t
r.snap[t] = state(w, drv)
if post:
post(w, drv, t)
r.log = list(LOG)
r.errs = [m for _t, lv, m in LOG if lv == "ERROR"]
r.refs = [t for t, lv, m in LOG if lv == "WARNING" and REF_S in m]
r.q3w = [t for t, lv, m in LOG if lv == "WARNING" and Q3W in m]
r.cutdbg = [t for t, lv, m in LOG if CUTDBG in m]
r.nz = [(int(t), a) for t, a in drv.calls if a > 0]
r.zeros = [int(t) for t, a in drv.calls if a == 0.0]
if (cls or CM.SolarWriter) is CM.SolarWriter:
ALL.append(r)
return r
def per_key(tries):
out = {}
for t in tries:
out[t // 900] = out.get(t // 900, 0) + 1
return out
# ------------------------------------------------------------ the worlds
def route_a(kind, until=899, plan_a=8.0, take=None, cls=None, post=None,
pre_extra=None):
"""EV-56 c4c: 0 A cut tries by `_put` at 0, 60, 120; the cut lifts at 121
(drop); the plan decides 1 -> 3; a 6 A cap comes back."""
def pre(w, d, t):
if t == 0:
set_cap(w, 0.0)
w.plan.a = 0.0
if t == 121:
set_cap(w, None)
w.plan.a = 8.0
if pre_extra:
pre_extra(w, d, t)
def post_(w, d, t):
if t == 121:
w.plan._set(8.0, 121.0, 3)
set_cap(w, 6.0)
w.plan.a = plan_a
if post:
post(w, d, t)
return world(kind, until, pre=pre, post=post_, cls=cls,
take=take or (lambda a, d, w: False))
def route_b(kind, put_tries=3, until=898, cls=None, take_after=False):
"""EV-56 c4b: `put_tries` refused 0 A cut tries by `_put`; the cut lifts
(drop); the plan decides 1 -> 3; the change's 0 A and select are taken; a
6 A cap comes in settle and the capped close is refused."""
t_lift = 60 * put_tries
ph = {"all": True}
def take(a, d, w):
return (not ph["all"]) and a == 0.0 and w.cut_a is None
def pre(w, d, t):
if t == 0:
set_cap(w, 0.0)
w.plan.a = 0.0
if t == t_lift:
set_cap(w, None)
ph["all"] = False
w.plan.a = 8.0
def post(w, d, t):
if t == t_lift:
w.plan._set(8.0, float(t), 3)
elif t > t_lift and w.seq is not None \
and w.seq.get("stage") == "settle" and w.cut_a is None:
set_cap(w, 6.0)
return world(kind, until, pre=pre, post=post, take=take, cls=cls)
def one_cut(w, d, t):
"""A cut try of 0 A refused at 100; the cut lifts at 120 (drop); a press
at 125 clears `fail_at` (F3) so a change can begin at 130 / 140."""
if t == 100:
set_cap(w, 0.0)
w.plan.a = 0.0
if t == 120:
set_cap(w, None)
w.plan.a = 8.0
if t == 125:
w.user_changed()
def cap_in_settle(at=None):
def post(w, d, t):
if w.seq is not None and w.seq.get("stage") == "settle" \
and w.cut_a is None and (at is None or t >= at):
set_cap(w, 6.0)
return post
def t2b(kind, begin=140, until=240, extra_pre=None, take=None, cls=None,
avail=None, sun=None):
def pre(w, d, t):
one_cut(w, d, t)
if t == begin:
w.plan._set(8.0, float(begin), 3)
if extra_pre:
extra_pre(w, d, t)
return world(kind, until, start=90, pre=pre, post=cap_in_settle(),
take=take, cls=cls, avail=avail, sun=sun)
def t2c(kind, until=240, cls=None):
"""Q6: close 1 (8 A, no cap) refused; the cap arrives at 143; close 2 is
a cut try within RETRY_S of cut_fail_at 100."""
def pre(w, d, t):
one_cut(w, d, t)
if t == 130:
w.plan._set(8.0, 130.0, 3)
if t == 143:
set_cap(w, 6.0)
return world(kind, until, start=90, pre=pre, cls=cls,
take=lambda a, d, w: a == 0.0 and d.now >= 120)
def t3(kind, until=899, cls=None, extra_pre=None):
"""Route (a) then (b), one key: a 6 A cap stands; the change's 0 A is
refused at 0 and taken at 60; the capped close is refused."""
def pre(w, d, t):
if t == 0:
set_cap(w, 6.0)
w.plan._set(8.0, 0.0, 3)
if t == 60 and not w.plan.switch:
w.plan._set(8.0, 60.0, 3)
if extra_pre:
extra_pre(w, d, t)
return world(kind, until, pre=pre, cls=cls,
take=lambda a, d, w: a == 0.0 and d.now >= 60)
def sp3(kind, press=None, until=299, cls=None):
def pre(w, d, t):
if press is not None and t == press:
w.user_changed()
return world(kind, until, start=1, pre=pre, cls=cls,
setup=lambda w, d: w.plan._set(8.0, 0.0, 3),
take=lambda a, d, w: a == 0.0)
# =========================================================================== #
print("1. ROUTE (a): THE PHASE CHANGE'S 0 A (T1, T1b, T4, T5)")
# =========================================================================== #
RA = {k: route_a(k) for k in "RX"}
for k in "RX":
r = RA[k]
after = [(t, a) for t, a in r.drv.calls if t > 121]
check(f"T1 [{k}]: cut tries [0, 60, 120], cut_fails 3, no write at all in "
f"122-899 ({r.tries}, {r.w.cut_fails}, {after[:3]}), seq None, "
f"switch True, no give-up, no select, no ERROR record",
r.tries == [0, 60, 120] and r.w.cut_fails == 3 and not after
and r.w.seq is None and r.w.plan.switch and not r.w.gave_up
and not r.drv.phases_log and not r.errs)
check("T1: X equals R (calls, cut_fails, fails, seq, switch)",
RA["X"].drv.calls == RA["R"].drv.calls
and RA["X"].snap[899] == RA["R"].snap[899])
r = RA["R"]
flat = {tuple(sorted((k, str(v)) for k, v in r.snap[t].items() if k != "n"))
for t in range(122, 900)}
check("T4: the gated steps 122-899 change nothing: cut_fails, fails, gave_up, "
"seq, switch the same every step; the change waits (switch True), "
"end_switch never called by the gate",
len(flat) == 1 and r.snap[899]["sw"] and not r.snap[899]["gu"]
and not r.refs and len(r.q3w) == 1)
check(f"T10: the cut's one CHARGER_REFUSED, in the step cut_fails reached 3 "
f"({r.q3w}); REF_S never from cut tries ({r.refs})",
r.q3w == [120] and not r.refs)
def t1b(kind, cls=None):
def pre(w, d, t):
if t == 0:
set_cap(w, 0.0)
w.plan.a = 0.0
if t == 30:
set_cap(w, None)
w.plan.a = 8.0
if t == 31:
w.plan._set(8.0, 31.0, 3)
if t == 32:
set_cap(w, 6.0)
if t == 33:
w.user_changed()
return world(kind, 119, pre=pre, cls=cls,
take=lambda a, d, w: a == 0.0 and d.now >= 60)
for k in "RX":
r = t1b(k)
fire = [t for t in r.zeros]
check(f"T1b [{k}] (F3): no 0 A in 31-59 although the press cleared "
f"fail_at; 0 A at 60 ({fire}); cut_fails 1 after the press "
f"({r.snap[59]['cf']}); then select and the capped closes, 3 "
f"cut tries in all ({r.tries}), no 3rd close",
not [t for t in fire if 31 <= t <= 59] and 60 in fire
and r.snap[59]["cf"] == 1 and len(r.tries) == 3
and r.tries[0] == 0 and near(r.tries[1:], [71, 76], 1)
and r.w.cut_fails == 3 and not r.w.gave_up and not r.errs)
# T5: the next key gives control back
for k in "R":
# (a) the cap stands, the charger takes from 900
r = route_a(k, until=1500, plan_a=6.0,
take=lambda a, d, w: d.now >= 900)
z = [t for t in r.zeros if t >= 900]
check(f"T5a: at key 1 cut_fails is 0 and Solar controls again: 0 A at 900 "
f"({z[:1]}), 6 A close, plan.n 3, seq None, cut_warned False "
f"({r.snap[900]['cf']}, {r.w.plan.n}, {r.w.cut_warned})",
r.snap[899]["cf"] == 3 and r.snap[900]["cf"] == 0
and z and abs(z[0] - 900) <= 1 and r.w.plan.n == 3
and r.w.seq is None and not r.w.cut_warned
and any(a == 6.0 and t > 900 for t, a in r.drv.calls)
and not r.w.gave_up)
# (c) the charger still refuses
r = route_a(k, until=1500, plan_a=6.0)
k1 = [t for t in r.tries if t >= 900]
check(f"T5c: charger still refuses: exactly 3 refused cut tries in key 1, "
f">= 60 s apart, then a wait ({k1}); gave_up never; Q3W once per "
f"reaching ({r.q3w}); no REF_S ({r.refs})",
len(k1) == 3 and all(b - a >= 60 for a, b in zip(k1, k1[1:]))
and not r.w.gave_up and not r.refs and r.q3w == [120])
# T11a: no cap any more: not a cut try
r = route_a("R", until=420, plan_a=8.0,
take=lambda a, d, w: a == 0.0 and w.cut_a is None
or d.now >= 300, pre_extra=lambda w, d, t: (
(set_cap(w, None), setattr(w.plan, "a", 8.0))
if t == 299 else None))
c300 = [(int(t), a) for t, a in r.drv.calls if t >= 299]
check(f"T11a: cut_fails 3, the cap lifted: the pending change's 0 A at 300, "
f"the select and the close at the plan's value 8 A, not cut tries "
f"({c300}); one tries list {r.tries}",
c300 and abs(c300[0][0] - 300) <= 1 and c300[0][1] == 0.0
and len(c300) == 2 and c300[1][1] == 8.0 and len(r.drv.phases_log) == 1
and r.tries == [0, 60, 120] and r.w.plan.n == 3)
# =========================================================================== #
print("\n2. ROUTE (b): THE CAPPED CLOSE (T2, T2b, T2c, T3, T6, T21)")
# =========================================================================== #
RB = {k: route_b(k) for k in "RX"}
for k in "RX":
r = RB[k]
sixes = [t for t, a in r.nz if a == 6.0]
e = r.snap[r.ended] if r.ended else {}
check(f"T2 [{k}]: cut tries [0, 60, 120], cut_fails 3, no close write "
f"({r.tries}, {r.w.cut_fails}, {sixes}); the sequence ends at "
f"192 ({r.ended}); no non-zero write while the cap stands",
r.tries == [0, 60, 120] and r.w.cut_fails == 3 and not sixes
and r.ended is not None and abs(r.ended - 192) <= 1
and not r.nz and not r.errs)
r = RB["R"]
e, e0 = r.snap[r.ended], r.snap[r.ended - 1]
check(f"T6: the capped close end: seq None, reapply, last_a and rev_applied "
f"None, end_switch(False): switch False, plan back at its value before "
f"the change (a 8, n 1), no write in that step, last write 0 A, "
f"gave_up False, cut_fails 3, no extra _failed ({e})",
e["seq"] is None and e["re"] is True and e["la"] is None
and e["rv"] is None and not e["sw"] and e["pa"] == 8.0 and e["pn"] == 1
and e["n"] == e0["n"] and r.drv.calls[-1][1] == 0.0 and not e["gu"]
and e["cf"] == 3 and e["f"] == e0["f"])
check("T2: X equals R", RB["X"].drv.calls == RB["R"].drv.calls
and RB["X"].ended == RB["R"].ended)
for k in "RX":
r = t2b(k)
wait = range(151, 160)
calls_wait = [t for t, a in r.nz if 151 <= t <= 159]
closes = [t for t, a in r.nz if a == 6.0]
fa = {r.snap[t]["f"] for t in wait}
check(f"T2b [{k}] (Q5, T22): 151-159 no write, seq in settle, the car at "
f"0 A, cut_fails 1, fails unchanged, no give-up, no REF; close 1 "
f"at 160, close 2 at 165 ({closes}); cut_fails 3, one Q3W at 165 "
f"({r.q3w}); the end 5 s later (T6 state) ({r.ended})",
not calls_wait and all(r.snap[t]["seq"] and r.snap[t]["seq"][0]
== "settle" and r.snap[t]["cf"] == 1
and not r.snap[t]["gu"] for t in wait)
and len(fa) == 1 and r.drv.cur == 0.0
and near(closes, [160, 165], 1) and r.w.cut_fails == 3
and near(r.q3w, [165], 1) and not r.refs and not r.w.gave_up
and r.ended and abs(r.ended - 170) <= 1
and r.snap[r.ended]["re"] and not r.snap[r.ended]["sw"]
and r.snap[r.ended]["n"] == r.snap[r.ended - 1]["n"]
and r.snap[r.ended]["cf"] == 3 and not r.errs)
for k in "RX":
r = t2c(k)
w130 = [(int(t), a) for t, a in r.drv.calls if t >= 130]
check(f"T2c [{k}] (Q6): 0 A 130, 8 A close 1 ~141 (not a cut try), the cap "
f"at 143; 146-159 no write, no try counted (cut_fails 1, fails 1), "
f"seq in settle, no give-up, no REF; close 2 (6 A) at 160, close "
f"3 at 165 ({w130}); cut_fails 3, one Q3W at 165 ({r.q3w}); the "
f"end on its 3 tries, no 4th close, no extra _failed",
len(w130) == 4 and abs(w130[1][0] - 141) <= 1 and w130[1][1] == 8.0
and near([x for x, _a in w130[2:]], [160, 165], 1)
and all(a == 6.0 for _x, a in w130[2:])
and all(r.snap[t]["cf"] == 1 and r.snap[t]["f"] == 1
and r.snap[t]["seq"][0] == "settle"
and r.snap[t]["n"] == r.snap[146]["n"]
for t in range(146, 160))
and r.w.cut_fails == 3 and near(r.q3w, [165], 1) and not r.refs
and not r.w.gave_up and r.w.seq is None and r.w.reapply
and len(r.errs) <= 1) # X: the 8 A close is no cut try (G1)
for k in "RX":
r = t3(k)
c1 = r.tries[1] if len(r.tries) > 1 else None
check(f"T3 [{k}] (Q1): refused cut tries [0, c1, c1+5] = 3 ({r.tries}); "
f"no close at c1+10; the T6 end; cut_fails 3; one Q3W in the c1+5 "
f"step ({r.q3w})",
len(r.tries) == 3 and r.tries[0] == 0 and c1 >= 60
and r.tries[2] == c1 + 5 and r.w.cut_fails == 3
and r.q3w == [c1 + 5] and r.ended is not None
and abs(r.ended - (c1 + 10)) <= 1 and r.w.seq is None
and r.w.reapply and not r.w.plan.switch
and r.drv.calls[-1][1] == 6.0 and not r.w.gave_up and not r.errs)
r3 = t3("R", extra_pre=lambda w, d, t: (
(setattr(w.plan, "n", 3), w.plan._set(8.0, 200.0, 1))
if t == 200 else None)) # the plan on 3 phases decides back to 1
after = [(int(t), a) for t, a in r3.drv.calls if t > 81]
check(f"T3b (Q1): route (b) then (a): cut_fails 3 in key 0; a new switch "
f"under the cap writes no 0 A until key 1 ({after}); it waits "
f"(switch True), no give-up",
not after and r3.w.cut_fails == 3 and r3.w.plan.switch
and not r3.w.gave_up and r3.w.seq is None)
flat = {tuple(sorted((k, str(v)) for k, v in r3.snap[t].items() if k != "n"))
for t in range(201, 900)}
check("T4: T3b's gated steps change nothing, no REF_S, one Q3W",
len(flat) == 1 and not r3.refs and len(r3.q3w) == 1)
# T3c: mixed answers
base3 = t3("R")
mix = t3("XRX")
check(f"T3c: X, R, X in that order: the same times and counts as R "
f"({mix.tries} vs {base3.tries}); each raise one try; one CUTDBG per "
f"raised cut try ({len(mix.cutdbg)}); 0 ERROR records",
mix.tries == base3.tries and mix.w.cut_fails == 3
and len(mix.cutdbg) == 2 and not mix.errs
and mix.drv.calls == base3.drv.calls)
mixb = t2b("XR")
bb = t2b("R")
check(f"T3c: T2b with X then R: same calls and counts as R; one CUTDBG "
f"({len(mixb.cutdbg)})",
mixb.drv.calls == bb.drv.calls and mixb.w.cut_fails == 3
and len(mixb.cutdbg) == 1 and not mixb.errs)
# T10 over the routes
for nm, r, at in (("T2b", t2b("R"), 165), ("T2c", t2c("R"), 165),
("T3", t3("R"), None)):
check(f"T10 [{nm}]: Q3W exactly once ({r.q3w}), none in a gated or "
f"waiting step, REF_S never ({r.refs})",
len(r.q3w) == 1 and not r.refs
and (at is None or abs(r.q3w[0] - at) <= 1))
# T21: the key rolls between the closes
def pre_roll(fail_at, begin):
def setup(w, d):
w.cut_key, w.cut_fails, w.cut_fail_at = 0, 2, float(fail_at)
def pre(w, d, t):
if t == begin:
w.plan._set(8.0, float(begin), 3)
return setup, pre
for k in "RX":
setup, pre = pre_roll(800, 884)
r = world(k, 960, start=870, setup=setup, pre=pre,
post=cap_in_settle())
cl = [t for t, a in r.nz if a == 6.0]
key1 = [t for t in r.tries if t >= 900]
check(f"T21 [{k}]: cut_fails 2, close 1 refused at 895 (key 0 ends at 3), "
f"close 2 at 900 (key 1 fresh), close 3 at 905 ({cl}); key 1 holds "
f"2 ({key1}, {r.w.cut_fails}); the sequence never has a 4th close; "
f"gave_up False; no extra _failed ({r.snap[899]['cf']})",
near(cl, [895, 900, 905], 1) and r.snap[899]["cf"] == 3
and r.w.cut_fails == 2 and len(key1) == 2 and not r.w.gave_up
and r.w.seq is None and r.w.reapply and not r.errs)
for k in "RX":
setup, pre = pre_roll(870, 874)
r = world(k, 990, start=870, setup=setup, pre=pre,
post=cap_in_settle())
cl = [t for t, a in r.nz if a == 6.0]
quiet = [t for t, a in r.nz if 880 <= t <= 929]
check(f"T21b [{k}] (Q5, T22): 885-929 no write, waiting at 0 A, no try "
f"counted, no give-up; key 0 stays 2; the close at 930 "
f"(cut_fail_at + RETRY_S across the roll), 935, 940 ({cl}); key 1 "
f"= 3, one Q3W at 940 ({r.q3w}); the end on its 3 tries",
not quiet and r.snap[899]["cf"] == 2 and r.snap[900]["cf"] == 0
and all(not r.snap[t]["gu"] for t in range(885, 930))
and near(cl, [930, 935, 940], 1) and r.w.cut_fails == 3
and near(r.q3w, [940], 1) and r.w.seq is None and r.w.reapply
and not r.w.gave_up and not r.errs)
setup, pre = pre_roll(870, 874)
r = world("R", 990, start=870, setup=setup, pre=pre, post=cap_in_settle(),
take=lambda a, d, w: a == 0.0 and w.cut_a is None or d.now >= 930)
check("T21b variant: the charger takes the close at 930: the change is done "
f"(plan.n {r.w.plan.n}, switch {r.w.plan.switch})",
r.w.plan.n == 3 and not r.w.plan.switch and r.w.seq is None
and r.w.cut_fails == 0)
# =========================================================================== #
print("\n3. SOLAR'S CLOSE RETRIES AND THE PRESS (T7, T8, T8b, T9, T17)")
# =========================================================================== #
for k in "RX":
r = sp3(k)
check(f"T7 [{k}] (C5s, no press): 8 A at 12, 17, 22, fails 3, gave_up, "
f"REF_S once at 22, no write after 22 ({[t for t, _a in r.nz]}, "
f"{r.w.fails}, {r.refs})",
[t for t, _a in r.nz] == [12, 17, 22] and r.w.fails == 3
and r.w.gave_up and r.refs == [22] and len(r.errs) <= 1)
for k in "RX":
r = sp3(k, press=13)
check(f"T8 [{k}] (C5s, press at 13): 8 A at 12, 17, 22, 82; at 22 fails "
f"2, no give-up, no REF; at 82 fails 3, gave_up, REF once "
f"({[t for t, _a in r.nz]}, {r.snap[22]['f']}, {r.refs})",
[t for t, _a in r.nz] == [12, 17, 22, 82]
and r.snap[22]["f"] == 2 and not r.snap[22]["gu"]
and r.snap[82]["f"] == 3 and r.snap[82]["gu"] and r.refs == [82]
and len(r.errs) <= 2) # X: the press re-arms the ERROR line
r = sp3("R", press=18)
r2 = sp3("R", press=11)
check(f"T8b: (a) press at 18: 12, 17, 22, 82, 142, REF at 142 only "
f"({[t for t, _a in r.nz]}, {r.refs}); (b) press at 11: 12, 17, 22, "
f"fails 3, REF at 22 ({[t for t, _a in r2.nz]}, {r2.w.fails}, "
f"{r2.refs})",
[t for t, _a in r.nz] == [12, 17, 22, 82, 142] and r.refs == [142]
and [t for t, _a in r2.nz] == [12, 17, 22] and r2.w.fails == 3
and r2.refs == [22])
LOG14 = []
def t14c(cls=CM.SolarWriter):
del LOG[:]
w = solar_writer(8.0, cls)
drv = Drv(0.0, lambda a, n: False)
w.seq = {"stage": "settle", "t0": 0.0, "n": 3, "tries": 0, "prev": 8.0,
"t1": 0.0}
vals = {10: 8.0, 15: 7.0, 20: 6.0}
async def main():
for t in range(10, 40):
if w.seq is None:
break
drv.now = float(t)
CLOCK["t"] = t
await w._advance(drv, Rd(drv.cur, drv.ph, power=0.0), 0.0,
float(t), Trk(), lambda q: vals.get(t, 5.0),
16.0, 1)
LOOP.run_until_complete(main())
rf = [t for t, lv, m in LOG if lv == "WARNING" and REF_S in m]
return [(int(t), a) for t, a in drv.calls], w.fails, w.gave_up, rf, w.seq
S9 = t14c()
check(f"T9: the close value moves 8, 7, 6 A at 10, 15, 20: fails 3, gave_up, "
f"REF at 20, seq None ({S9})",
S9 == ([(10, 8.0), (15, 7.0), (20, 6.0)], 3, True, [20], None))
setup, pre = pre_roll(0, 0)
r = t2b("R", extra_pre=lambda w, d, t: w.user_changed() if t == 162 else None)
cl = [t for t, a in r.nz if a == 6.0]
check(f"T17: a Solar press between close 1 and close 2 resets neither "
f"cut_fails nor the sequence's tries: closes {cl}, cut_fails "
f"{r.w.cut_fails}, end as T6, no give-up",
near(cl, [160, 165], 1) and r.w.cut_fails == 3 and not r.w.gave_up
and r.ended and abs(r.ended - 170) <= 1 and r.snap[r.ended]["re"]
and not r.snap[r.ended]["sw"])
# =========================================================================== #
print("\n4. M1: THE BASE CLASS IS RED, A CHARGER THAT ANSWERS IS THE SAME")
# =========================================================================== #
r = route_a("R", cls=Base60)
check(f"M1 self-check: Base60 is 2e09622 on route (a): cut tries "
f"{r.tries} (base [0, 60, 120, 180]), cut_fails {r.w.cut_fails}",
r.tries == [0, 60, 120, 180] and r.w.cut_fails == 4)
r = route_b("R", cls=Base60, until=250)
check(f"M1 self-check: Base60 on route (b): {r.tries} (base [0, 60, 120, "
f"192, 197, 202]), cut_fails {r.w.cut_fails}",
r.tries == [0, 60, 120, 192, 197, 202] and r.w.cut_fails == 7)
r = sp3("R", cls=Base60)
check(f"M1 self-check: Base60 on sp3: fails {r.w.fails} (base 4), REF "
f"{r.refs}", r.w.fails == 4 and r.refs == [22])
# T14: a charger that answers: the same writes at the same times as base
for nm, fn in (("route (a) world, the cap standing, all taken",
lambda c: route_a("R", until=300, plan_a=6.0, cls=c,
take=lambda a, d, w: True)),
("a standing cap, the change's 0 A and close taken",
lambda c: world("R", 300, cls=c,
setup=lambda w, d: (
set_cap(w, 6.0),
w.plan._set(8.0, 0.0, 3)),
take=lambda a_, d, w: True)),
("capped change in settle (T2b), the charger takes all",
lambda c: t2b("R", until=240, cls=c,
take=lambda a, d, w: True)),
("no cap, close at the plan's value (sp3 shape)",
lambda c: world("R", 120, start=1, cls=c,
setup=lambda w, d: w.plan._set(8.0, 0.0, 3),
take=lambda a, d, w: True))):
a, b = fn(CM.SolarWriter), fn(Base60)
check(f"T14 (N8): {nm}: same writes at the same times and selects as "
f"base ({a.drv.calls[:4]}); same plan, fails 0",
a.drv.calls == b.drv.calls and a.drv.phases_log == b.drv.phases_log
and a.w.fails == b.w.fails == 0 and a.w.plan.n == b.w.plan.n
and a.w.cut_fails == b.w.cut_fails)
# T11b: no cap ever, every write refused (non-cut): same as base
a = world("R", 399, start=1, setup=lambda w, d: w.plan._set(8.0, 0.0, 3),
take=lambda a_, d, w: False)
b = world("R", 399, start=1, setup=lambda w, d: w.plan._set(8.0, 0.0, 3),
take=lambda a_, d, w: False, cls=Base60)
check(f"T11b: no cap, every write refused: same calls as base "
f"({a.drv.calls[:3]}), same fails and give-up",
a.drv.calls == b.drv.calls and a.w.fails == b.w.fails
and a.w.gave_up == b.w.gave_up)
def zero_way(cls):
w = solar_writer(8.0, cls)
drv = Drv(8.0, lambda a, n: False)
set_cap(w, 6.0)
w.cut_key, w.cut_fails = 0, 3
drv.now = 10.0
LOOP.run_until_complete(w._zero(drv, 8.0, 10.0, Trk()))
return drv.calls, w.cut_fails, w.fails
check("T11c: the way out's 0 A with the cap and cut_fails 3: as base",
zero_way(CM.SolarWriter) == zero_way(Base60))
# =========================================================================== #
print("\n5. T16, T18-T20, T24")
# =========================================================================== #
for cap_ in (2, 4):
saved = CM.MAX_TRIES
CM.MAX_TRIES = cap_
try:
ra = route_a("R", until=899)
r2b = t2b("R", until=260)
r3_ = t3("R", until=300)
r7 = sp3("R")
finally:
CM.MAX_TRIES = saved
check(f"T16: MAX_TRIES {cap_}: cut tries per key == {cap_} on T1 "
f"({len(ra.tries)}), T2b ({len(r2b.tries)}), T3 ({len(r3_.tries)}); "
f"T7 tries == {cap_} then REF ({[t for t, _a in r7.nz]}, "
f"{r7.refs})",
len(ra.tries) == cap_ and len(r2b.tries) == cap_
and len(r3_.tries) == cap_ and len(r7.nz) == cap_
and len(r7.refs) == 1)
w18 = CM.SolarWriter()
check("T18: a new SolarWriter after a restart: cut_fails 0, cut_key None, "
"cut_fail_at None, no counters carried",
w18.cut_fails == 0 and w18.cut_key is None and w18.cut_fail_at is None
and not w18.gave_up)
# T19 (a): the meter goes silent in the Q5 wait: C17
r = t2b("R", sun=lambda t: CM.SunInputs(target_w=2000.0, silent=(t >= 155)))
late = [(int(t), a) for t, a in r.drv.calls if t >= 150 and a > 0]
check(f"T19a (C17): silent meter in the Q5 wait: the change ends at its 0 A "
f"(seq None, switch False), no non-zero write ({late}), cut_fails 1",
r.snap[155]["seq"] is None and not r.snap[155]["sw"] and not late
and r.snap[155]["cf"] == 1 and not r.errs)
# (b) a stale meter: no retry of the refused value (N7, N14)
w19 = solar_writer(8.0)
set_cap(w19, 6.0)
w19.cut_blind, w19.refused_cut, w19.sent_a, w19.taken = True, 6.0, 6.0, False
w19.sent_cut = True
d19 = Drv(8.0, lambda a, n: False)
d19.now = 500.0
LOOP.run_until_complete(w19._put(d19, 6.0, 8.0, 500.0, Trk()))
check("T19b/N14: cut_blind with the refused 6 A: no retry on a stale meter",
not d19.calls)
# T20: the charger unavailable
r = t2b("R", avail=lambda t: not (155 <= t <= 175))
down = [t for t, a in r.drv.calls if 155 <= t <= 175]
check(f"T20a: unavailable 155-175: no write while down ({down}); the key's "
f"cut tries stay at most 3 ({r.tries}); no ERROR",
not down and len(r.tries) <= 3 and r.w.cut_fails <= 3 and not r.errs)
r = world("R", 300, avail=lambda t: False,
setup=lambda w, d: (set_cap(w, 0.0), setattr(w.plan, "a", 0.0)))
check("T20b: no charger: 0 writes, no count", not r.drv.calls
and r.w.cut_fails == 0)
# T24: shutdown as base (EV-61 is out of scope)
def rel(cls):
w = solar_writer(8.0, cls)
set_cap(w, 6.0)
d = Drv(8.0, lambda a, n: False)
d.now = 0.0
res = LOOP.run_until_complete(w.release(d, Rd(8.0), 0.0, Trk()))
return d.calls, res, w.cut_fails, w.fails
check(f"T24: release as base: 3 tries 5 s apart, not released ({rel(CM.SolarWriter)})",
rel(CM.SolarWriter) == rel(Base60) and len(rel(CM.SolarWriter)[0]) == 3)
r = route_a("R")
d24 = Drv(8.0, lambda a, n: False)
res24 = LOOP.run_until_complete(r.w.release(d24, Rd(8.0), 899.0, Trk()))
check(f"T24: shutdown during T1's wait: no exception, release as base "
f"({d24.calls})", res24 in (False, None) and len(d24.calls) in (0, 3))
# =========================================================================== #
print("\n6. THE NEVERS OVER EVERY RUN, SOURCE CHECKS (N1-N14, T15, T23)")
# =========================================================================== #
worst = max((max(per_key(r.tries).values(), default=0) - r.cap_
for r in ALL), default=0)
check(f"N1: never more than MAX_TRIES refused or raised cut tries in one "
f"quarter key, over {len(ALL)} runs (worst: {worst} over the cap)",
worst <= 0 and len(ALL) > 40)
check("N2: no write above the cap or between 0 and 6 A, over every run",
not [v for r in ALL for v in r.viol])
CUT_ONLY = [r for r in ALL if r.tries and r.w.cut_fails >= 1
and not r.noncut]
check(f"N3: no give-up and no REF_S from cut tries, the gate or the Q5 wait "
f"({len(CUT_ONLY)} cut runs)",
len(CUT_ONLY) > 10 and not [1 for r in CUT_ONLY
if r.w.gave_up or r.refs])
check("N5: no select while the car drew (0 A not taken), over every run",
all(c == 0.0 for r in ALL for _t, _n, c in r.drv.phases_log))
check("N9: no exception out of a step or release in any run (every run "
"completed), and no ERROR record on a cut try (G1)",
not [e for r in CUT_ONLY for e in r.errs])
check("N7: ManualWriter's source is 2e09622's, byte for byte",
hashlib.sha256(inspect.getsource(CM.ManualWriter).encode())
.hexdigest() == MANUAL_SHA)
def tsrc(name):
return open(os.path.join(HERE, name), encoding="utf-8").read()
src = tsrc(os.path.join("app", "carmode.py"))
check("N10 (write_phases and the notices untouched): one write_phases( and "
"one drv.write_current( call, no new asyncio.sleep, create_task or "
"_LOG.warning (1, 1, 1, 0, 10)",
src.count("write_phases(") == 1 and src.count("drv.write_current(") == 1
and src.count("asyncio.sleep") == 1 and src.count("create_task") == 0
and src.count("_LOG.warning(") == 10)
print()
if fails:
print(f"FAIL: {len(fails)} check(s)")
for f in fails:
print(" -", f[:200])
sys.exit(1)
print("OK")