Compare commits

...
11 Commits
Author SHA1 Message Date
ems-agentandClaude 7613468cf9 EV-54 review r2: fails counts only refusals of the value now owed
checks / unit (pull_request) Successful in 45m48s
infra-pin / fresh (pull_request) Successful in 2s
Where a refused cut value stops being owed without a drop (the charger's return, another value written in its place), fails goes to 0; cut_fails is untouched. After a return under a capped quarter, Solar's own write gets its own 3 tries again instead of giving up after 1. New rows T40 (refused to 1430), T41 (to 1600, against the run without the away), T42 (replaced value).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 06:37:40 +01:00
ems-agentandClaude 095f773921 EV-54 review r1: no stale fails block after the charger returns; peak cut reason
checks / unit (pull_request) Successful in 45m27s
infra-pin / fresh (pull_request) Successful in 2s
The fails >= MAX_TRIES block on non-cut writes applies only while the refused cut value is still owed, so Solar resumes after the charger came back under a capped quarter (it froze before). The quarter's cut count is untouched and D2's 0 A stays held while capped. A new cut value under the read-back above a refused one logs 'peak cut'. New rows T36 (away while capped, 0 A and 6 A), T37 (F6), T38 (Off after 3 tries), T39 (reason replay).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 04:51:54 +01:00
ems-agentandClaude cf07f6f99b EV-54 tests: T26 asserts the first write after the lift is the step-up; T8 checks named T8
checks / unit (pull_request) Successful in 50m12s
infra-pin / fresh (pull_request) Successful in 1s
Mutant M18 (the drop leaves taken False) re-sent the standing read-back at the lift and T26 missed it; the T8 checks were filed under T2/T5 by name. Test-only.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 01:47:38 +01:00
ems-agentandClaude a698211318 EV-54: a refused peak cut no longer stops Solar; tried again next quarter
checks / unit (pull_request) Successful in 52m35s
infra-pin / fresh (pull_request) Successful in 1s
Refused cut tries are capped at 3 per quarter key and never set the session-wide gave_up. The next quarter tries again while a cut is needed. Once no cut stands, a refused cut value is dropped (sent_a and the plan current = the read-back, taken), never re-sent; the drop waits for a good, known read-back. A cut write that raises counts as a refused try. New notice text (Q3); the hold path's text is unchanged. Tests: test_ev54.py, test_ev54_drop.py (T1-T35); test_ev52 N8 knows the new text.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-30 00:24:58 +01:00
ems-agent bdfd3e6848 Merge pull request 'EV-52: log one plain line for a new car current and a car mode change' (#279) from EV-52 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-29 14:54:38 +01:00
ems-agent 64991d7cde EV-52 review round 2: test row for Solar's late try cleared on leave
checks / unit (pull_request) Successful in 45m23s
infra-pin / fresh (pull_request) Successful in 1s
Test only. Kills a mutant that drops the _late clear in SolarWriter._leave(), which no row covered.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-29 14:08:48 +01:00
ems-agent 2931e6e852 EV-52 round 2: a refused Manual try is not logged later by another source's value
checks / unit (pull_request) Successful in 44m13s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 11:55:51 +01:00
ems-agent fd1cb423b1 EV-52 round 1: Manual late-accept line (Q2), N5, N8, T44 rows
checks / unit (pull_request) Successful in 44m57s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 09:49:52 +01:00
ems-agent ca06456ffa EV-52: charger-less stubs, CHANGELOG, EV-28/EV-51 log rows set the two new lines aside
checks / unit (pull_request) Successful in 47m21s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 07:47:17 +01:00
ems-agent c1536b0e93 EV-52: log one plain line for a new car current and for a car mode change
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 06:48:52 +01:00
ems-agent 02166e28eb Merge pull request 'EV-21: Solar cuts the car first for the quarter peak' (#278) from EV-21 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-29 03:24:38 +01:00
13 changed files with 2915 additions and 23 deletions
+2
View File
@@ -2,6 +2,8 @@
### Not in a release yet ### Not in a release yet
- **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]]). - **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.25.0 ## 0.25.0
@@ -0,0 +1,64 @@
# EV-54 — Solar: a refused peak cut is tried again next quarter
EV-21 sent its cut tries through Solar's normal retry, whose third refusal set
the session-wide `gave_up`. A cut is held at 0 A (or a partial value) under a
standing cap, so neither way out of `gave_up` could come: after three refused
tries Solar never wrote again, also once the charger took writes again (EV-21
rig, finding 1). The rules below are the PM rulings Q1-Q9, G1-G6, QA, QB and
QC (brief v6); the formal check is reports/EV-54-formal-report.md.
## The rule, in plain words
- **A cut try** is a Solar write while a cut is due or stands, at or under its
cap (the cut, its retry, a 0 A of a phase change or a way out): `_cut_try`.
- **At most 3 refused cut tries per quarter key** (the projection's
`block_start`), across cut values and episodes. A deeper cut does not give
new tries; a press of Solar, or Off then Solar, does not either. The count
is in memory only: a restart starts afresh (`cut_quarter`, `cut_fails`).
- **A refused cut try never sets `gave_up`.** Solar's normal writes go on. The
third refusal of a quarter logs one warning per episode: "The charger did not
take the peak cut, so the add-on tries again next quarter: CHARGER_REFUSED."
(DEBUG after; a taken cut or a mode change re-arms it). The amber row and
the card's Why show it while the tries are used up and the charger shows
more than the cut (`cut_refused`). The hold path's text is unchanged.
- **The next quarter tries again** while a cut is still needed, as EV-21's cut:
at once without headroom, else after the 15 s wait; a same-value retry no
sooner than 60 s after the last refusal.
- **The drop.** Once no cut stands (the cap lifted, or a new quarter's cut
waits) a refused cut value is never sent again. Solar takes the read-back
as its own: `sent_a` = read-back, taken, `gave_up` cleared, and the plan's
current = read-back, timed as a new decision (`_drop`). The retry clock
stays, so nothing non-zero reaches the charger within 60 s of its refusal.
The drop waits while the reading is stuck (QA) or the read-back is unknown
(QB); meanwhile Solar sends nothing but a way out's 0 A.
- **A stuck reading after the lift** keeps base's fault path: its 0 A goes
out three times 60 s apart with reason Solar, then `gave_up` with the hold
path's text; the first good reading drops it and clears `gave_up` (QC).
- **A cut write that raises** counts as a refused cut try (no Traceback, no
try per cycle). The same gap outside the cut is EV-56.
## Choices the rulings left open
- Refused cut tries still count in `fails` (without `gave_up`), and outside the
cut `fails >= MAX_TRIES` stops a write as `gave_up` did, but only while the
refused value is still owed. So Off's way-out 0 A after refused cut tries is
written exactly as before (N10). Once that value is gone (the charger came
back, another value was written), nothing blocks Solar's normal writes
(review round 1: a gate on `fails` alone froze Solar after the charger came
back under a capped quarter). The gate is scoped rather than `fails` reset,
so one rule covers every way the value goes, and the quarter's cut count
(`cut_fails`) is never touched by it. When the cut
stops standing in Solar and the value cannot be dropped yet (stuck), that
value becomes Solar's own: reason Solar, a fresh `fails` count (QC).
- `fails` counts only refusals of the value now owed (PM, review round 2).
Where a refused cut value stops being owed without a drop (the charger's
return, another value written in its place), `fails` goes to 0
(`_forget_refused`); `cut_fails` stays. Elsewhere `fails` is already
right: a drop, a taken write or an adopt clear it; a Solar press or a
change into Solar clear it; Off and the quarter roll keep the owed value,
so its count stays (Off's way-out as before).
- At a new quarter's wait the cut tick holds the read-back the writer is about
to take, not the refused value, so the wait never re-sends it (G1).
- No drop over another writer's value (a hold or a difference being watched).
- A new cut value under the read-back is logged "peak cut", also when it lies
above a refused value.
+4
View File
@@ -3389,6 +3389,10 @@ changes at most once per 30 seconds and only by 1 A or more.
fault, or a lower current the charger has not shown yet), the peak alarms fault, or a lower current the charger has not shown yet), the peak alarms
treat the car as in Off. A Solar charge is never counted as setting the treat the car as in Off. A Solar charge is never counted as setting the
month's peak. month's peak.
- **A cut the charger does not take** is tried again after a minute, at most
three times per 15-minute period; then one warning and an amber row say so.
Solar's normal control goes on, and the cut is tried again at the start of
the next period while it is still needed.
- **Energy.** The card says "{kWh} charged today, {kWh} from the sun", and the - **Energy.** The card says "{kWh} charged today, {kWh} from the sun", and the
sensor `goodwe_car_today_solar_kwh` has the sun's part. Only Solar's own sensor `goodwe_car_today_solar_kwh` has the sun's part. Only Solar's own
share of spare sun counts, not the hold's battery or grid power. share of spare sun counts, not the hold's battery or grid power.
+254 -12
View File
@@ -142,17 +142,25 @@ class ManualWriter:
self.phase_done_at = None # EV-15: our phase change ended well then self.phase_done_at = None # EV-15: our phase change ended well then
self.zero_sent_at = None # EV-15: our 0 A write is out, not yet back self.zero_sent_at = None # EV-15: our 0 A write is out, not yet back
self.nonzero_at = None # EV-20 C6: the latest non-zero write sent self.nonzero_at = None # EV-20 C6: the latest non-zero write sent
# EV-52: what the one info line per taken write needs.
self.boot = True # no user change since the process started
self._seen = False # the charger was available once
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
# ------------------------------------------------------------------ user # ------------------------------------------------------------------ user
def user_changed(self) -> None: def user_changed(self) -> None:
"""The user changed the mode or a value: one more write is allowed, """The user changed the mode or a value: one more write is allowed,
and another writer's hold is lifted.""" and another writer's hold is lifted."""
self.boot = False
self.rev_applied = None self.rev_applied = None
self.hold = self.other = False self.hold = self.other = False
self.mismatch_since = None self.mismatch_since = None
self.fails, self.fail_at, self.gave_up = 0, None, False self.fails, self.fail_at, self.gave_up = 0, None, False
self.phase_fails, self.phases_gave_up = 0, False self.phase_fails, self.phases_gave_up = 0, False
self.attempted_a = self.prior_a = None self.attempted_a = self.prior_a = None
self._late = None # EV-52: that request is not current now
# ------------------------------------------------------------------ step # ------------------------------------------------------------------ step
async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp, async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp,
@@ -164,6 +172,7 @@ class ManualWriter:
if r is None or not r.available: if r is None or not r.available:
self.was_available = False self.was_available = False
return return
self._r = r
# A reading taken before our latest write was confirmed says nothing # A reading taken before our latest write was confirmed says nothing
# about it (the writer runs beside the cycle and can finish between a # about it (the writer runs beside the cycle and can finish between a
# read and the step that follows): wait for one taken after. # read and the step that follows): wait for one taken after.
@@ -172,6 +181,8 @@ class ManualWriter:
and tracker.obs_at <= self.last_done: and tracker.obs_at <= self.last_done:
return return
if not self.was_available: if not self.was_available:
self._returned = self._returned or self._seen
self._seen = True
self.was_available = True self.was_available = True
self.reapply = True # on return: only if it differs self.reapply = True # on return: only if it differs
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
@@ -184,6 +195,7 @@ class ManualWriter:
return return
self.would = None self.would = None
if mode != MANUAL: if mode != MANUAL:
self._late = None # EV-52: another mode: that try is history
return return
if clamp is None or clamp < CH.MIN_A: if clamp is None or clamp < CH.MIN_A:
return return
@@ -210,6 +222,10 @@ class ManualWriter:
self.fails, self.blocked = 0, False self.fails, self.blocked = 0, False
if cur is not None: if cur is not None:
self.last_a = cur # adopt what is already set self.last_a = cur # adopt what is already set
# EV-52 (PM Q2): a write taken late is logged once, here.
late, self._late = self._late, None
if late is not None and abs(cur - float(late[0])) <= TOL_A:
self._log_set(*late)
return return
if not (need_user or self.reapply): if not (need_user or self.reapply):
return # a difference nobody asked for: `_watch()` judges return # a difference nobody asked for: `_watch()` judges
@@ -264,7 +280,47 @@ class ManualWriter:
"the add-on set %.0f A), so the add-on stops writing " "the add-on set %.0f A), so the add-on stops writing "
"to it until you change it.", cur, known[0]) "to it until you change it.", cur, known[0])
# ----------------------------------------------------- EV-52: the info line
def _why_default(self) -> str:
"""The reason of a write nobody named: Manual's own, or `start-up`
while nothing was changed since the process started."""
return "start-up" if self.boot and not self._returned else "Manual"
def _close_why(self, q):
return None
def _phases_of(self, n=None):
"""The phase count a current is written for: the one the caller
names, else what the charger reports. None when unknown."""
if n in (1, 3):
return n
if getattr(self, "single", False):
return 1
p = getattr(self._r, "phases_allowed", None)
return p if p in (1, 3) else None
def _log_set(self, a, was, why, n) -> None:
"""One plain INFO line for a current the charger took. Never raises:
a line is not worth a failed write."""
try:
new, old, ph = _num(a), _num(was), self._phases_of(n)
if new is None:
return
head = f"Car: set to {new:.0f} A"
if old is not None:
if abs(old - new) <= TOL_A:
return # it stood there: not a change
head = f"Car: set from {old:.0f} A to {new:.0f} A"
tail = "" if ph is None else (
" on 1 phase" if ph == 1 else " on 3 phases")
_LOG.info("%s%s (%s).", head, tail, why)
except Exception: # noqa: BLE001
pass
async def _write(self, drv, a, was, now, tracker, **kw) -> bool: 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)
self._late = None
tracker.begin_write() # EV-12: the read-back is ours tracker.begin_write() # EV-12: the read-back is ours
if float(a) > TOL_A: if float(a) > TOL_A:
# EV-20 C6, THE ONE WRITE CLOCK: every non-zero current either # EV-20 C6, THE ONE WRITE CLOCK: every non-zero current either
@@ -283,8 +339,10 @@ class ManualWriter:
if ok: if ok:
self.last_a = a self.last_a = a
self.attempted_a = self.prior_a = None self.attempted_a = self.prior_a = None
self._log_set(a, was, why, n)
else: else:
self.attempted_a, self.prior_a = a, was self.attempted_a, self.prior_a = a, was
self._late = (a, was, why, n) # logged if it is adopted later
return ok return ok
def _stamp(self, now) -> None: def _stamp(self, now) -> None:
@@ -310,7 +368,7 @@ class ManualWriter:
self.rev_applied, self.reapply = None, True self.rev_applied, self.reapply = None, True
a = self._restore_a(q.get("prev"), clamp) a = self._restore_a(q.get("prev"), clamp)
if a is not None: if a is not None:
await self._write(drv, a, 0.0, now, tracker) await self._write(drv, a, 0.0, now, tracker, why="Manual")
async def _begin(self, drv, r, cur, n, now, tracker) -> None: async def _begin(self, drv, r, cur, n, now, tracker) -> None:
"""Step 1 of the safe sequence: 0 A. A charger that does not take it """Step 1 of the safe sequence: 0 A. A charger that does not take it
@@ -337,7 +395,7 @@ class ManualWriter:
a = None if q is None else self._restore_a(q.get("prev"), clamp) a = None if q is None else self._restore_a(q.get("prev"), clamp)
if a is not None: if a is not None:
self._clock = self._clock or (lambda: now) self._clock = self._clock or (lambda: now)
await self._write(drv, a, 0.0, now, tracker) await self._write(drv, a, 0.0, now, tracker, why="shutdown")
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev): async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
q = self.seq q = self.seq
@@ -379,6 +437,7 @@ class ManualWriter:
q["stage"] = "select" q["stage"] = "select"
if q["stage"] == "select": if q["stage"] == "select":
ok = await drv.write_phases(q["n"]) ok = await drv.write_phases(q["n"])
q["sel_ok"] = bool(ok) # EV-52: the close's phase count
self._stamp(now) self._stamp(now)
self.last_switch = now self.last_switch = now
self.log.append(("phases", q["n"], now, ok)) self.log.append(("phases", q["n"], now, ok))
@@ -403,7 +462,9 @@ class ManualWriter:
# on whether the phases changed); Manual a number, as before. # on whether the phases changed); Manual a number, as before.
want = want_a(q) if callable(want_a) else want_a want = want_a(q) if callable(want_a) else want_a
a = min(max(float(want), CH.MIN_A), hi) a = min(max(float(want), CH.MIN_A), hi)
if await self._write(drv, a, 0.0, now, tracker): if await self._write(drv, a, 0.0, now, tracker,
why=self._close_why(q),
n=q["n"] if q.get("sel_ok") else None):
# Judged afresh next cycle: a value the user changed meanwhile is # Judged afresh next cycle: a value the user changed meanwhile is
# still wanted, and one that is in place is adopted. # still wanted, and one that is in place is adopted.
self.seq, self.rev_applied, self.reapply = None, None, False self.seq, self.rev_applied, self.reapply = None, None, False
@@ -782,12 +843,25 @@ class SolarWriter(ManualWriter):
self.held_step = False # C18: a held read: only a NEW 0 A goes out self.held_step = False # C18: a held read: only a NEW 0 A goes out
self.cut_a = None # EV-21: the peak cut's cap, set per cycle self.cut_a = None # EV-21: the peak cut's cap, set per cycle
self.sent_at = None # EV-21: when `sent_a` went out self.sent_at = None # EV-21: when `sent_a` went out
self.startup_zero = False # EV-52: the 0 A the start itself caused
self.sent_why = None # EV-52: the reason of `sent_a`'s write
# EV-54: the peak cut's refused tries, per quarter key, in memory only
# (DECISIONS/EV-54-refused-cut-retry.md).
self.cut_on = False # a cut stands (its cap), set per cycle
self.cut_blind = False # ... sized on a stale or blind meter now
self.cut_key = None # the quarter key the count is for
self.cut_fails = 0 # cut tries the charger did not take in it
self.cut_fail_at = None # ... the latest of them
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
def owe_start(self) -> None: def owe_start(self) -> None:
"""C1: the add-on starts in Off while an exit 0 A of its own was still """C1: the add-on starts in Off while an exit 0 A of its own was still
pending at the stop: the current the charger shows is the add-on's, pending at the stop: the current the charger shows is the add-on's,
so the 0 A is owed (once it may write), retried by the exit rule.""" so the 0 A is owed (once it may write), retried by the exit rule."""
self.start_owed = self.engaged = True self.start_owed = self.engaged = True
self.startup_zero = True
def _stuck_end(self) -> None: def _stuck_end(self) -> None:
"""SPIKE-06: a stuck episode ends (the reading followed a start, a """SPIKE-06: a stuck episode ends (the reading followed a start, a
@@ -818,6 +892,60 @@ class SolarWriter(ManualWriter):
and self.sent_a <= TOL_A and not self.taken and self.sent_a <= TOL_A and not self.taken
and not self.hold) and not self.hold)
@property
def cut_refused(self) -> bool:
"""EV-54: the quarter's cut tries are used up and the charger still
shows more than the cut (the amber row and the card's Why)."""
return bool(self.cut_fails >= MAX_TRIES
and self.refused_cut is not None and not self.taken)
def cut_quarter(self, key) -> None:
"""EV-54 (Q1, Q8): a new quarter key gives the cut MAX_TRIES tries
again. Only a known key counts: a cycle without a projection keeps
the count."""
if key is not None and key != self.cut_key:
self.cut_key, self.cut_fails = key, 0
def _cut_try(self, a) -> bool:
"""EV-54 (Q6): a write while a cut is due or stands, at or under its
cap, is a cut try (the cut, a retry, a 0 A of a way out or of a phase
change)."""
return self.cut_a is not None and float(a) <= self.cut_a + TOL_A
def _forget_refused(self) -> None:
"""EV-54 (PM, review r2): a refused cut value is no longer owed and
is not dropped (the charger's return, another value written): its
refusals leave `fails` with it. `cut_fails`, the quarter's cap, stays."""
if self.refused_cut is not None:
self.refused_cut = None
self.fails = 0
def drop_ready(self, cur, stuck) -> bool:
"""EV-54 (drop rule): a cut value the charger did not take, no cut
stands any more (lifted, or a new quarter's cut waits), and a known
read-back that is not stuck and not another writer's: Solar takes
the charger as it is instead of sending that value again."""
return bool(self.refused_cut is not None and not self.taken
and not self.cut_on and not stuck and cur is not None
and not self.hold and self.mismatch_since is None
and not self.fresh_start)
def _drop(self, cur, now) -> None:
"""EV-54: `sent_a` = the read-back, taken (an adopt: `gave_up` and the
try count cleared), and the plan's current = the read-back, timed as
a new decision. Nothing is written. The retry clock stays: no
non-zero write reaches the charger within RETRY_S of its refusal."""
if self.sent_a is not None and self.sent_a <= TOL_A:
self._owed(False) # that 0 A is no longer owed
at = self.fail_at
self.sent_a, self.sent_cut = float(cur), False
self._adopt(cur)
self.fail_at = at
if float(cur) >= CH.MIN_A:
self.plan._set(float(cur), now)
else:
self.plan.pause()
def amps_out(self, clamp) -> float: def amps_out(self, clamp) -> float:
"""The plan's current, never above the clamp; 0 when under 6 A.""" """The plan's current, never above the clamp; 0 when under 6 A."""
a = float(self.plan.a) a = float(self.plan.a)
@@ -836,6 +964,7 @@ class SolarWriter(ManualWriter):
if held: if held:
self.last_a = None self.last_a = None
self.sent_a, self.taken = None, True self.sent_a, self.taken = None, True
self.refused_cut = None
# ------------------------------------------------------------- writes # ------------------------------------------------------------- writes
async def _write(self, drv, a, was, now, tracker, **kw) -> bool: async def _write(self, drv, a, was, now, tracker, **kw) -> bool:
@@ -843,6 +972,17 @@ class SolarWriter(ManualWriter):
the write goes out, so a write cancelled while it waits for its the write goes out, so a write cancelled while it waits for its
read-back is never trusted (`live`).""" read-back is never trusted (`live`)."""
prev = self.sent_a prev = self.sent_a
why = kw.get("why")
if why is None:
# EV-52: the 0 A the start caused is `start-up`, else Solar's own.
why = "start-up" if self.startup_zero and float(a) <= TOL_A \
and self.boot else "Solar"
kw["why"] = why
self.sent_why = why
cut_try = self.sent_cut = self._cut_try(a)
if self.refused_cut is not None \
and abs(self.refused_cut - float(a)) > TOL_A:
self._forget_refused() # EV-54: another value, not that one
self.sent_a, self.taken = float(a), False self.sent_a, self.taken = float(a), False
if prev is None or abs(prev - float(a)) > TOL_A: if prev is None or abs(prev - float(a)) > TOL_A:
# EV-21 (PM Q1, formal C15): the 2 s grace of a lowering on its # EV-21 (PM Q1, formal C15): the 2 s grace of a lowering on its
@@ -859,19 +999,56 @@ class SolarWriter(ManualWriter):
self._owed(True) # C1: kept with the mode until back self._owed(True) # C1: kept with the mode until back
try: try:
ok = await super()._write(drv, a, was, now, tracker, **kw) ok = await super()._write(drv, a, was, now, tracker, **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
ok = False
finally: finally:
if zero: if zero:
self.zero_sent_at = None self.zero_sent_at = None
if ok: if ok:
self.taken = True self.taken = True
self.startup_zero = False
self.fails, self.fail_at, self.gave_up = 0, None, False self.fails, self.fail_at, self.gave_up = 0, None, False
self.refused_cut = None
if cut_try:
self.cut_warned = False # EV-54: a taken cut re-arms it
if zero: if zero:
self._owed(False) self._owed(False)
else: else:
self._failed(now) self._failed(now)
return ok return ok
def _close_why(self, q):
"""EV-52: a phase change's closing current: capped by the peak cut,
or Solar's."""
return "peak cut" if q.get("cut") else "Solar"
def _failed(self, now) -> None: def _failed(self, now) -> None:
if self.sent_cut:
# EV-54 (Q1, F7): a refused cut try counts against the quarter's
# MAX_TRIES and never stops Solar; the next quarter tries again.
# `fails` counts it as before, so a way out of Off that follows
# is tried as often as before (N10).
self.fails += 1
self.fail_at = self.cut_fail_at = now
self.cut_fails += 1
self.refused_cut = self.sent_a
if self.cut_fails >= MAX_TRIES:
if not self.cut_warned:
self.cut_warned = True
_LOG.warning("The charger did not take the peak cut, so "
"the add-on tries again next quarter: "
"CHARGER_REFUSED.")
else:
_LOG.debug("The charger did not take the peak cut, %d "
"tries this quarter.", self.cut_fails)
return
self.fails += 1 self.fails += 1
self.fail_at = now self.fail_at = now
if self.fails >= MAX_TRIES and not self.gave_up: if self.fails >= MAX_TRIES and not self.gave_up:
@@ -885,26 +1062,59 @@ class SolarWriter(ManualWriter):
if self.sent_a is not None and self.sent_a <= TOL_A: if self.sent_a is not None and self.sent_a <= TOL_A:
self._owed(False) self._owed(False)
self.taken = True self.taken = True
self.startup_zero = False
self.last_a = cur self.last_a = cur
self.attempted_a = self.prior_a = None self.attempted_a = self.prior_a = None
self.fails, self.fail_at, self.gave_up = 0, None, False self.fails, self.fail_at, self.gave_up = 0, None, False
self.refused_cut = None
if self.sent_cut:
self.cut_warned = False # EV-54: a cut taken late re-arms it
# EV-52 (PM Q2): a write the charger took late is logged once, here.
late, self._late = self._late, None
if late is not None and cur is not None \
and abs(float(cur) - float(late[0])) <= TOL_A:
self._log_set(*late)
async def _put(self, drv, want, cur, now, tracker, stuck=False) -> None: async def _put(self, drv, want, cur, now, tracker, stuck=False,
out=False) -> None:
"""Make the charger match `want`: write a new decision, try one the """Make the charger match `want`: write a new decision, try one the
charger did not take again after `RETRY_S`. A new 0 A gets its own charger did not take again after `RETRY_S`. A new 0 A gets its own
`MAX_TRIES` and never waits (0 A is the safe side).""" `MAX_TRIES` and never waits (0 A is the safe side). EV-54: a cut try
is capped per quarter, never stopped by `gave_up`; a refused cut
value no cut needs is dropped (`_drop`), never sent again, except as
a way out's 0 A (`out`)."""
if self.hold: if self.hold:
return return
if want > TOL_A and self.nz_block: if want > TOL_A and self.nz_block:
return # C17/C18: 0 A only, no retry or raise return # C17/C18: 0 A only, no retry or raise
# EV-54: refused cut tries count in `fails` without `gave_up`; outside
# the cut they stop a write as `gave_up` did before, but only while
# that refused value is still owed. Once it is gone (the charger's
# return, another write) no stale count blocks Solar (review r1).
# The quarter's cut count (`cut_fails`) is not touched.
stopped = self.gave_up or (self.fails >= MAX_TRIES
and self.refused_cut is not None
and not self.taken)
cut_try = self._cut_try(want)
if cut_try and self.cut_fails >= MAX_TRIES:
return # EV-54 (Q1): this quarter's tries used
if cut_try and self.cut_blind and self.refused_cut is not None \
and abs(want - self.refused_cut) <= TOL_A:
return # EV-54 (N7): no retry on a stale meter
if not out and self.refused_cut is not None and not self.taken \
and not self.cut_on and (
want > TOL_A or abs(want - self.refused_cut) <= TOL_A):
return # EV-54: the drop waits for a reading
if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A: if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A:
if self.held_step: if self.held_step:
return # C18: no retry to a charger not answering return # C18: no retry to a charger not answering
if self.taken or self.gave_up or ( if self.taken or (stopped and not cut_try) or (
self.fail_at is not None self.fail_at is not None
and now - self.fail_at < RETRY_S): and now - self.fail_at < RETRY_S):
return return
await self._write(drv, want, cur, now, tracker) # EV-52: a retry keeps the reason of the first try.
await self._write(drv, want, cur, now, tracker,
why=self.sent_why)
return return
if not stuck and cur is not None and abs(cur - want) <= TOL_A: if not stuck and cur is not None and abs(cur - want) <= TOL_A:
self.sent_a = want # it already stands self.sent_a = want # it already stands
@@ -912,13 +1122,23 @@ class SolarWriter(ManualWriter):
return return
cut = (self.cut_a is not None and want <= self.cut_a + TOL_A cut = (self.cut_a is not None and want <= self.cut_a + TOL_A
and self.sent_a is not None and want < self.sent_a - TOL_A) and self.sent_a is not None and want < self.sent_a - TOL_A)
if cut_try and self.refused_cut is None \
and self.cut_fail_at is not None \
and now - self.cut_fail_at < RETRY_S:
return # EV-54 (F6): a new episode's try
if want <= TOL_A or cut: if want <= TOL_A or cut:
# A new 0 A, or EV-21's new lower cut value: its own tries, at once. # A new 0 A, or EV-21's new lower cut value: its own tries, at once.
self.fails, self.fail_at, self.gave_up = 0, None, False self.fails, self.fail_at, self.gave_up = 0, None, False
elif self.gave_up or (self.fail_at is not None elif (stopped and not cut_try) or (
and now - self.fail_at < RETRY_S): self.fail_at is not None and now - self.fail_at < RETRY_S):
return return
await self._write(drv, want, cur, now, tracker) # EV-54 (review r1): a new cut value under the read-back is a peak cut,
# also when it lies above the refused one (`cut` compares with
# `sent_a`, which is that refused value).
peak = cut or (cut_try and self.refused_cut is not None
and cur is not None and want < cur - TOL_A)
await self._write(drv, want, cur, now, tracker,
why="peak cut" if peak else None)
def _own_readback(self, cur) -> bool: def _own_readback(self, cur) -> bool:
"""C9: does the read-back show a current of Solar's own (sent, """C9: does the read-back show a current of Solar's own (sent,
@@ -938,7 +1158,7 @@ class SolarWriter(ManualWriter):
if not self.live and self._own_readback(cur) and not stuck: if not self.live and self._own_readback(cur) and not stuck:
self.taken = False # C9: a 0 A is owed self.taken = False # C9: a 0 A is owed
if self.live and not self.hold: if self.live and not self.hold:
await self._put(drv, 0.0, cur, now, tracker, stuck) await self._put(drv, 0.0, cur, now, tracker, stuck, out=True)
def _watch(self, cur, now) -> None: def _watch(self, cur, now) -> None:
was = self.hold was = self.hold
@@ -975,6 +1195,7 @@ class SolarWriter(ManualWriter):
def _leave(self) -> None: def _leave(self) -> None:
"""Solar is no longer the mode and owes nothing.""" """Solar is no longer the mode and owes nothing."""
self.engaged, self.seq, self.would = False, None, None self.engaged, self.seq, self.would = False, None, None
self._late = None # EV-52: no late accept after leaving
self.start_owed = False self.start_owed = False
self.out, self.fault = False, None self.out, self.fault = False, None
self.restart = True self.restart = True
@@ -1023,6 +1244,7 @@ class SolarWriter(ManualWriter):
cap = self.cut_a # EV-21: never above a peak cut's cap cap = self.cut_a # EV-21: never above a peak cut's cap
if cap is not None and cap >= CH.MIN_A and a > cap: if cap is not None and cap >= CH.MIN_A and a > cap:
q["close_a"] = a = float(cap) q["close_a"] = a = float(cap)
q["cut"] = True # EV-52: the close is a peak cut
return a return a
return want return want
@@ -1095,6 +1317,10 @@ class SolarWriter(ManualWriter):
self.engaged, self.restart = True, True self.engaged, self.restart = True, True
self.sent_a, self.taken = None, True self.sent_a, self.taken = None, True
self.fails, self.fail_at, self.gave_up = 0, None, False self.fails, self.fail_at, self.gave_up = 0, None, False
# EV-54: nothing refused is pending; a mode change re-arms the
# notice. The quarter's try count stays (Q5).
self.refused_cut, self.sent_cut, self.cut_warned = None, False, \
False
if not self.engaged: if not self.engaged:
return return
if sun is not None: if sun is not None:
@@ -1102,6 +1328,7 @@ class SolarWriter(ManualWriter):
if r is None or not r.available: if r is None or not r.available:
self.was_available = False # nothing is tried while it is down self.was_available = False # nothing is tried while it is down
return return
self._r = r
if self.last_done is not None and tracker is not None \ if self.last_done is not None and tracker is not None \
and tracker.obs_at is not None \ and tracker.obs_at is not None \
and tracker.obs_at <= self.last_done: and tracker.obs_at <= self.last_done:
@@ -1119,6 +1346,10 @@ class SolarWriter(ManualWriter):
# the charger's current is its own, not another writer's, and the # the charger's current is its own, not another writer's, and the
# first write is 0 A whatever it shows (D2, round 9). # first write is 0 A whatever it shows (D2, round 9).
self.was_available = True self.was_available = True
self._returned = self._returned or self._seen
self._seen = True
# EV-52: only the process's own start owes a `start-up` 0 A.
self.startup_zero = self.boot and not self._returned
self.fresh_start = self.restart = True self.fresh_start = self.restart = True
self.mismatch_since = None self.mismatch_since = None
self.last_a = self.attempted_a = self.prior_a = None self.last_a = self.attempted_a = self.prior_a = None
@@ -1162,6 +1393,12 @@ class SolarWriter(ManualWriter):
self.out = False self.out = False
self._would_n = self._would_switch = None self._would_n = self._would_switch = None
self.would = None self.would = None
if self.refused_cut is not None and not self.taken \
and not self.cut_on and self.sent_cut:
# EV-54 (QC): no cut stands, so a value still owed is Solar's own
# (a stuck reading's way out), not a peak cut: its reason is
# Solar's and it gets Solar's own tries.
self.sent_why, self.sent_cut, self.fails = "Solar", False, 0
fault = ("error" if (r.error or r.state in ("E", "F")) else fault = ("error" if (r.error or r.state in ("E", "F")) else
"stuck" if stuck else None) "stuck" if stuck else None)
if not stuck: if not stuck:
@@ -1218,6 +1455,10 @@ class SolarWriter(ManualWriter):
if self.fresh_start: if self.fresh_start:
self.fresh_start = False self.fresh_start = False
self.sent_a, self.taken = None, True # 0 A first (D2) self.sent_a, self.taken = None, True # 0 A first (D2)
self._forget_refused()
if self.drop_ready(cur, stuck):
# EV-54 (drop rule): the refused cut value is not sent again.
self._drop(cur, now)
if self.seq is None: if self.seq is None:
self._watch(cur, now) self._watch(cur, now)
if self.hold or self.mismatch_since is not None: if self.hold or self.mismatch_since is not None:
@@ -1324,6 +1565,7 @@ class SolarWriter(ManualWriter):
if not self.engaged or not self.live or self.hold: if not self.engaged or not self.live or self.hold:
return None return None
if r is not None and r.available: if r is not None and r.available:
self._r = r
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
else: else:
cur = None cur = None
@@ -1336,7 +1578,7 @@ class SolarWriter(ManualWriter):
if wait > 0: if wait > 0:
await sleep(wait) await sleep(wait)
if await self._write(drv, 0.0, cur, clock(), tracker, if await self._write(drv, 0.0, cur, clock(), tracker,
took_s=RELEASE_TOOK_S): took_s=RELEASE_TOOK_S, why="shutdown"):
self.released = True self.released = True
return True return True
self.released = False self.released = False
+20 -5
View File
@@ -88,6 +88,10 @@ class CarMixin:
ok = carmode.allowed_phases(opts) ok = carmode.allowed_phases(opts)
self.car_n = n if n in ok else ok[0] self.car_n = n if n in ok else ok[0]
self.car_rev = 0 self.car_rev = 0
ch = getattr(self, "charger", None)
if ch is not None and ch.configured(): # EV-52: the mode at the start
_LOG.info("Car mode is now %s.",
carmode.MODE_LABELS[self.car_mode])
self.car_writer = carmode.ManualWriter() self.car_writer = carmode.ManualWriter()
self.car_solar = carmode.SolarWriter() # EV-20 self.car_solar = carmode.SolarWriter() # EV-20
self.car_solar.on_owed = self._car_owed self.car_solar.on_owed = self._car_owed
@@ -290,7 +294,7 @@ class CarMixin:
w = self.car_solar w = self.car_solar
if not self.car_solar_mode(): if not self.car_solar_mode():
self._cut = self._cut_fresh(None) self._cut = self._cut_fresh(None)
w.cut_a = None w.cut_a, w.cut_on, w.cut_blind = None, False, False
return return
key = None if real_proj is None else real_proj.block_start key = None if real_proj is None else real_proj.block_start
st = self._cut st = self._cut
@@ -302,7 +306,10 @@ class CarMixin:
# N9: nothing sized from a stale projection; what stands stays. # N9: nothing sized from a stale projection; what stands stays.
w.cut_a = st["cap"] if st["cap"] is not None \ w.cut_a = st["cap"] if st["cap"] is not None \
else self._car_wait_a(st) else self._car_wait_a(st)
w.cut_on, w.cut_blind = st["cap"] is not None, True
return return
w.cut_blind = False
w.cut_quarter(key) # EV-54: the quarter's refused cut tries
ex = peakguard.excess_w(real_proj, target_w) ex = peakguard.excess_w(real_proj, target_w)
left = QUARTER_S - float(real_proj.elapsed_s) left = QUARTER_S - float(real_proj.elapsed_s)
r = self.car.reading r = self.car.reading
@@ -351,10 +358,11 @@ class CarMixin:
st = self._cut = self._cut_fresh(key) st = self._cut = self._cut_fresh(key)
st["cuts"] = cuts st["cuts"] = cuts
w.cut_a = st["cap"] w.cut_a = st["cap"]
w.cut_on = st["cap"] is not None
return return
if not due: if not due:
st["since"], st["wait"] = None, None # the batteries caught it st["since"], st["wait"] = None, None # the batteries caught it
w.cut_a = None w.cut_a, w.cut_on = None, False
return return
if st["since"] is None: if st["since"] is None:
st["since"], st["car0"], st["ex"] = mono, car_w, ex st["since"], st["car0"], st["ex"] = mono, car_w, ex
@@ -369,13 +377,18 @@ class CarMixin:
st["cap"] = 0.0 if a is None else a st["cap"] = 0.0 if a is None else a
st["cuts"] += 1 st["cuts"] += 1
st["wait"], st["at"] = None, mono st["wait"], st["at"] = None, mono
w.cut_a = st["cap"] w.cut_a, w.cut_on = st["cap"], True
return return
# C4: due and waiting: no raise meanwhile. PM R1: held in watts (the # C4: due and waiting: no raise meanwhile. PM R1: held in watts (the
# plan's current on its phases), turned into amps with the phases at # plan's current on its phases), turned into amps with the phases at
# the write. # the write. EV-54 (G1): a refused cut value is dropped in the wait,
# so the hold is the read-back the writer takes, not that value.
w.cut_on = False
p = w.plan p = w.plan
now_w = float(p.a) * carmode.VOLTS * (p.n if p.n in (1, 3) else n) a_now = float(p.a)
if w.drop_ready(cur, self.car.stuck(mono)):
a_now = float(cur)
now_w = a_now * carmode.VOLTS * (p.n if p.n in (1, 3) else n)
st["wait"] = now_w if st["wait"] is None else min(st["wait"], now_w) st["wait"] = now_w if st["wait"] is None else min(st["wait"], now_w)
w.cut_a = self._car_wait_a(st) w.cut_a = self._car_wait_a(st)
@@ -476,6 +489,8 @@ class CarMixin:
# A Manual phase change in the middle is not restored: Solar # A Manual phase change in the middle is not restored: Solar
# starts from the 0 A it stands at. # starts from the 0 A it stands at.
self.car_writer.seq = None self.car_writer.seq = None
if value != self.car_mode: # EV-52: one plain line
_LOG.info("Car mode is now %s.", carmode.MODE_LABELS[value])
self.car_mode = value self.car_mode = value
self.store.set(carmode.KEY_MODE, value) self.store.set(carmode.KEY_MODE, value)
elif what == "car_sun_first": elif what == "car_sun_first":
+1 -1
View File
@@ -211,7 +211,7 @@ class StatusMixin:
if sw.other and self.car_mode == "solar": if sw.other and self.car_mode == "solar":
out.append({"ok": False, "warn": True, "id": "charger_other", out.append({"ok": False, "warn": True, "id": "charger_other",
"text": messages.row_charger_other_solar()}) "text": messages.row_charger_other_solar()})
if sw.gave_up: if sw.gave_up or getattr(sw, "cut_refused", False): # EV-54
out.append({"ok": False, "warn": True, "id": "charger_refused", out.append({"ok": False, "warn": True, "id": "charger_refused",
"text": messages.row_charger_refused()}) "text": messages.row_charger_refused()})
if sw.phases_gave_up and self.car_mode == "solar": if sw.phases_gave_up and self.car_mode == "solar":
+3 -2
View File
@@ -1386,11 +1386,12 @@ def _car_solar_why(c, key):
return _t("car.why.solar_peak") return _t("car.why.solar_peak")
if w.hold: if w.hold:
return _t("car.why.solar_other") return _t("car.why.solar_other")
refused = w.gave_up or getattr(w, "cut_refused", False) # EV-54
if w.zero_owed: if w.zero_owed:
# The way-out 0 A is not taken yet: never "paused". # The way-out 0 A is not taken yet: never "paused".
return _t("car.why.solar_zero_failed" if w.gave_up return _t("car.why.solar_zero_failed" if refused
else "car.why.solar_zeroing") else "car.why.solar_zeroing")
if w.gave_up: if refused:
return _t("car.why.solar_refused") return _t("car.why.solar_refused")
if c.shadow: if c.shadow:
a, n = w.would if w.would is not None else (0.0, p.n) a, n = w.would if w.would is not None else (0.0, p.n)
+6 -2
View File
@@ -57,8 +57,12 @@ class _Cap(logging.Handler):
self.rec.append((r.levelno, r.getMessage())) self.rec.append((r.levelno, r.getMessage()))
def loud(self, since=0): def loud(self, since=0):
"""INFO and above from `since` on.""" """INFO and above from `since` on, but for EV-52's two plain lines
return [m for lv, m in self.rec[since:] if lv >= logging.INFO] ("Car: set ..." for a taken write, "Car mode is now ..."): they are
asserted in test_ev52.py (T11, T13); this file's rows are about every
OTHER line a phase change may log."""
return [m for lv, m in self.rec[since:] if lv >= logging.INFO
and not m.startswith(("Car: set", "Car mode is now"))]
CAP = _Cap() CAP = _Cap()
+5 -1
View File
@@ -624,7 +624,11 @@ GOOGLE.setLevel(logging.INFO)
try: try:
n = LOG.mark() n = LOG.mark()
r, st = run_log(go, dur=760, cyc=5, phase=0, race=True) r, st = run_log(go, dur=760, cyc=5, phase=0, race=True)
info = [(lv, m) for lv, m, _x in LOG.rec[n:]] # EV-52 adds two plain INFO lines ("Car: set ...", "Car mode is now ...");
# test_ev52.py asserts them. This row is about EV-51's own line, so they
# are set aside here and every other record must still be base's.
info = [(lv, m) for lv, m, _x in LOG.rec[n:]
if not m.startswith(("Car: set", "Car mode is now"))]
finally: finally:
GOOGLE.setLevel(logging.DEBUG) GOOGLE.setLevel(logging.DEBUG)
# Measured on 5bff894 (same run, INFO), pinned: # Measured on 5bff894 (same run, INFO), pinned:
+942
View File
@@ -0,0 +1,942 @@
"""EV-52: one plain info line when the add-on writes a new car current, and one
when the car mode changes. `python3 -B test_ev52.py`
Logging only: no write, no time and no notification changes (T43-T45 pin that
against golden lists taken on the base build 02166e2). The real Controller on
`tools/ev20_sun.py` (a model clock, the charger model, one 1 s cycle), as
test_ev20.py and test_ev21_paths.py use it; a few rows call the writer's own
`_write` from the run's finale or on a stub driver. Time is the model clock
throughout, never x10 and never wall time.
Rows T1-T45 and N1-N11 of reports/EV-52-test-plan.md, with T23 as PM ruling Q2
changed it: a write the charger took late logs its line ONCE, at the accept.
A "line" is an INFO record that starts `Car: set`; a "mode line" one that
starts `Car mode is now`; each is placed on the cycle second it was logged in
(None: before the first cycle or in the finale).
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import os
import re
import sys
from types import SimpleNamespace
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode, chargers as CH, ctl_car # noqa: E402
import ev20_sun as S # noqa: E402
import ev21_kit as K # noqa: E402
from chargersim import SimCharger # noqa: E402
from ev20_kit import (LOG, check, fails, const, step_fn, act, # noqa: E402
report)
SET = S.SET
SETP = "Car: set"
MODEP = "Car mode is now"
MOPT = {"ev_phases": "1"} # a one-phase installation
ALL = [] # every run of this file, for N2 / N10
# The reason a caller names; the base build (no line) takes no such argument,
# so its rows read red there instead of crashing.
WHY = {"why": "Manual"} if hasattr(carmode.ManualWriter, "_log_set") else {}
# ------------------------------------------------------------------ helpers
def _stamp():
n0, stamps = LOG.mark(), {}
def oc(p, c, t):
stamps[t] = LOG.mark()
return n0, stamps, oc
def _tag(r, n0, stamps):
ts = sorted(stamps)
out = []
for i in range(n0, len(LOG.rec)):
lv, m, _x = LOG.rec[i]
out.append((next((t for t in ts if stamps[t] > i), None), lv, m))
r["lines"], r["n0"], r["end"] = out, n0, len(LOG.rec)
ALL.append(r)
return r
def run(mode, dur, house=900.0, sun=0.0, events=None, **kw):
n0, stamps, oc = _stamp()
r = S.drive(house if callable(house) else const(house),
sun if callable(sun) else const(sun), dur=dur, mode=mode,
events=events, on_cycle=oc, **kw)
return _tag(r, n0, stamps)
def kdrive(house, sun, **kw):
n0, stamps, oc = _stamp()
r = K.drive(house, sun, on_cycle=oc, **kw)
return _tag(r, n0, stamps)
def kshape(kind, **kw):
n0, stamps, oc = _stamp()
r = K.shape(kind, on_cycle=oc, **kw)
return _tag(r, n0, stamps)
def sets(r, lo=None, hi=None):
return [(t, m) for t, lv, m in r["lines"]
if m.startswith(SETP)
and (lo is None or (t if t is not None else 1e12) >= lo)
and (hi is None or (t if t is not None else 1e12) < hi)]
def texts(r, **kw):
return [m for _t, m in sets(r, **kw)]
def modes(r):
return [(t, m) for t, lv, m in r["lines"] if m.startswith(MODEP)]
def taken(r):
"""Every current write the charger took, Manual's and Solar's."""
return [x for w in (r["c"].car_writer, r["c"].car_solar) for x in w.log
if x[0] == "current" and x[3]]
def warns(r, text):
return [m for _t, lv, m in r["lines"] if lv == "WARNING" and text in m]
def wlist(r):
return [(round(t), v) for t, v in S.writes(r)]
def amps_in(m):
return float(re.search(r" to (\d+) A", m).group(1))
MANUAL = {10: act("car_phases", 1), 15: act("car_current", 6),
20: act("car_mode", "manual")}
def manual(dur, events=None, **kw):
ev = dict(MANUAL)
ev.update(events or {})
kw.setdefault("setpoint", 10)
kw.setdefault("phases", 1)
kw.setdefault("car_phases", 1)
kw.setdefault("opts", MOPT)
return run("off", dur, events=ev, **kw)
def solar(dur, house=900.0, sun=7900.0, **kw):
kw.setdefault("first", "car")
kw.setdefault("phases", 1)
kw.setdefault("car_phases", 1)
kw.setdefault("opts", MOPT)
return run("solar", dur, house=house, sun=sun, **kw)
def both(*fns):
async def f(p, c):
for fn in fns:
x = fn(p, c)
if asyncio.iscoroutine(x):
await x
return f
async def _shutdown(p, c):
await c.shutdown()
def refuse(kind):
def f(p, c):
p.ch.refuse = kind
return f
def lift(p, c):
p.ch.refuse = None
# =========================================================================== #
print("1. MANUAL: A NEW CURRENT LOGS ONE LINE (T1-T3)")
# =========================================================================== #
r1 = manual(500, events={200: act("car_current", 8),
300: act("car_current", 8)})
s1 = sets(r1)
check(f"T1: Manual 10 -> 6 A (user set 6 A, then Manual), 180 cycles: exactly "
f"1 line, old 10 A, 1 phase, Manual ({texts(r1, hi=200)})",
texts(r1, hi=200) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."])
check(f"T1: logged in the writer's own step at the action's cycle "
f"({s1[:1]}) at INFO, and it equals what was sent "
f"({r1['c'].charger.sent[:1]})",
[t for t, _m in s1[:1]] == [20] and r1["c"].charger.sent[0] == 6.0
and all(lv == "INFO" for _t, lv, m in r1["lines"]
if m.startswith(SETP)))
check(f"T2: the user sets 8 A: exactly 1 more line, 6 -> 8, Manual "
f"({texts(r1, lo=200)})",
texts(r1, lo=200) == ["Car: set from 6 A to 8 A on 1 phase (Manual)."])
check(f"T3: the same 8 A again and 200 more cycles: 0 new lines and 0 new "
f"writes ({len(s1)} lines, {len(wlist(r1))} writes)",
len(sets(r1, lo=300)) == 0 and len(wlist(r1)) == 2)
check("T3/N4: one line per taken write, none per cycle",
len(s1) == len(taken(r1)) == 2)
check("T1: the mode line comes with the action",
[m for t, m in modes(r1) if t == 20] == ["Car mode is now Manual."])
# T24 / T25: the old value, or the phases, unknown. The writer's own `_write`
# from the finale: no old value, then no reading at all.
async def _unknown(p, c):
w = c.car_writer
await w._write(c.charger, 7.0, None, 400.0, c.car, **WHY)
w._r = None
await w._write(c.charger, 9.0, None, 401.0, c.car, **WHY)
r24 = manual(150, finale=_unknown)
check(f"T24/T25: the old value unknown: 'set to 7 A on 1 phase'; no reading, "
f"so no phase count either: 'set to 9 A (Manual)'; no exception "
f"({[m for t, m in sets(r24) if t is None]})",
[m for t, m in sets(r24) if t is None] == [
"Car: set to 7 A on 1 phase (Manual).",
"Car: set to 9 A (Manual)."])
def _odd():
w = carmode.ManualWriter()
n0 = LOG.mark()
for a, was, n in ((float("nan"), 6.0, 1), (None, 6.0, 1),
("x", None, 3), (6.0, float("inf"), "1"),
(6.0, 6.0, 1)):
if hasattr(w, "_log_set"): # the base build has none: red, not a crash
w._log_set(a, was, "Manual", n)
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check(f"N9: a NaN, None, text or infinite figure never raises and logs "
f"nothing wrong; an unchanged value logs nothing ({_odd()})",
_odd() == ["Car: set to 6 A (Manual)."])
# =========================================================================== #
print("\n2. THE MODE (T4-T6, T31)")
# =========================================================================== #
r4 = manual(200, events={100: act("car_mode", "manual"),
110: act("car_current", 9),
120: act("car_phases", 1),
130: act("car_sun_first", "car"),
140: act("car_mode", "bogus"),
150: act("car_current", 9)})
check(f"T4: Off -> Manual: exactly 1 mode line at the action ({modes(r4)})",
[m for t, m in modes(r4) if t == 20] == ["Car mode is now Manual."])
check(f"T4: the add-on's start logs the mode it started in, once "
f"({modes(r4)[:1]})", modes(r4)[:1] == [(0.0, "Car mode is now Off.")])
check(f"T5: Manual picked again, a value, the phases, Sun first and a bad "
f"mode: no mode line ({modes(r4)})", len(modes(r4)) == 2)
r6 = run("off", 300, events={20: act("car_mode", "manual"),
40: act("car_current", 9)},
opts={"ev_charger": "off"})
check(f"T6/N6: no charger: no car line, no mode line, not at start-up "
f"either ({[m for _t, _l, m in r6['lines'] if m.startswith(('Car:', MODEP))]})",
not [m for _t, _l, m in r6["lines"]
if m.startswith(("Car:", MODEP))] and not wlist(r6))
r31 = run("solar", 60, opts=dict(MOPT, ev_mode_start="off"), first="car",
phases=1, car_phases=1)
check(f"T31: ev_mode_start off with Solar stored: one mode line, Off "
f"({modes(r31)})",
[m for _t, m in modes(r31)] == ["Car mode is now Off."])
# =========================================================================== #
print("\n3. SOLAR (T7-T10, T14, T26)")
# =========================================================================== #
r7 = solar(700)
t7 = sets(r7)[0][0] if sets(r7) else -10 ** 6
check(f"T7: Solar, Car first, spare sun, charger at 0 A: exactly 1 line for "
f"the start current ({texts(r7)})",
texts(r7) == ["Car: set from 0 A to 16 A on 1 phase (Solar)."])
check(f"T7: the line is in the step of the write ({t7}; write {wlist(r7)})",
wlist(r7) == [(t7 + 1, 16)])
check("T9: Solar steady, 580 cycles after the start: 0 new lines",
len(sets(r7, lo=t7 + 1)) == 0)
check("T7: the mode line once, at start-up",
[m for _t, m in modes(r7)] == ["Car mode is now Solar."])
def cloud_house(t):
return 900.0 + 800.0 if 300 <= t < 720 else 900.0
r8 = solar(900, house=cloud_house, sun=3400.0)
check(f"T8: Solar steady, a cloud (the house imports 800 W for 420 s): one "
f"line per taken write, each Solar ({texts(r8)}, taken "
f"{len(taken(r8))})",
len(sets(r8)) == len(taken(r8)) and len(sets(r8)) >= 2
and all(m.endswith("(Solar).") for m in texts(r8)))
def dither(t):
return 900.0 + 2300.0 + 100.0 + (0.0 if int(t // 7) % 2 else -10.0)
r10 = solar(900, sun=dither)
ln = [t for t, _m in sets(r10)]
gaps = [b - a for a, b in zip(ln, ln[1:])]
check(f"T10: spare dithering on an amp boundary: lines == taken writes "
f"({len(ln)}), at most one per SOLAR_WRITE_S ({gaps}); it fired "
f"{len(ln)} times in 900 s",
len(ln) == len(taken(r10)) and all(g >= carmode.SOLAR_WRITE_S - 1
for g in gaps))
r14 = run("solar", 900, sun=9600.0, first="car", phases=1, car_phases=3)
t14 = texts(r14)
z14 = [m for m in t14 if " to 0 A on 1 phase (Solar)" in m]
c14 = [m for m in t14 if "on 3 phases (Solar)" in m]
check(f"T14: Solar auto 1 -> 3 phases: one 0 A line on 1 phase, one close on "
f"3 phases, nothing else ({t14}; selects {S.writes(r14, 'phases')})",
len(S.writes(r14, "phases")) == 1 and len(z14) == 1 and len(c14) == 1
and len(t14) == 3 and t14.index(z14[0]) < t14.index(c14[0]))
check("T12: the select itself logs nothing: one line per taken current write",
len(sets(r14)) == len(taken(r14)))
r26 = solar(300, sun=0.0, setpoint=0)
check(f"T26: Solar, the charger already shows the 0 A Solar wants: no write, "
f"0 lines ({texts(r26)}, writes {wlist(r26)})",
not texts(r26) and not wlist(r26))
# =========================================================================== #
print("\n4. MANUAL PHASE CHANGE (T11-T13, T42)")
# =========================================================================== #
r11 = manual(300, events={200: act("car_phases", 3)}, car_phases=3, opts={})
t11 = texts(r11, lo=200)
s11 = [t for t, _m in sets(r11, lo=200)]
check(f"T11: Manual 6 A on 1 phase, the user picks 3 phases, the car stops: "
f"exactly 2 lines, the 0 A on 1 phase and the 6 A on 3 ({t11})",
t11 == ["Car: set from 6 A to 0 A on 1 phase (Manual).",
"Car: set from 0 A to 6 A on 3 phases (Manual)."])
check(f"T11/T12: the 0 A logs as a write; the close comes after the select "
f"and the 10 s settle, the select itself logs nothing ({s11}; selects "
f"{S.writes(r11, 'phases')})",
len(s11) == 2 and s11[1] - s11[0] >= carmode.SETTLE_S
and len(S.writes(r11, "phases")) == 1)
def drawing(p, c):
p.ch.ramp_w_s = 0.0001 # the car does not let go
r13 = manual(400, events={200: both(drawing, act("car_phases", 3))},
car_phases=3, opts={})
t13 = texts(r13, lo=200)
check(f"T13: the car keeps drawing: the 0 A line, the existing warning once, "
f"the restore line on 1 phase ({t13})",
t13 == ["Car: set from 6 A to 0 A on 1 phase (Manual).",
"Car: set from 0 A to 6 A on 1 phase (Manual)."]
and len(warns(r13, "The car kept drawing, so the phases were not "
"changed.")) == 1)
def shadow_on(p, c):
c.o["shadow_mode"] = "on"
r42 = manual(260, events={200: act("car_phases", 3), 201: shadow_on},
car_phases=3, opts={})
t42 = texts(r42, lo=200)
check(f"T42: shadow mode in the middle of a phase change: the 0 A and the one "
f"write shadow allows, Manual's undo: 2 lines, then none ({t42})",
t42 == ["Car: set from 6 A to 0 A on 1 phase (Manual).",
"Car: set from 0 A to 6 A on 1 phase (Manual)."]
and not S.writes(r42, "phases"))
# =========================================================================== #
print("\n5. THE PEAK CUT (T15-T17, T41)")
# =========================================================================== #
r15 = kdrive(step_fn((960, 900.0 + 5700.0), (966, 900.0 + 9000.0), base=900.0),
const(13000.0), dur=1100, first="car", phases=3,
socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
events={958: lambda p, c: setattr(c.car_solar, "nonzero_at",
p.t)})
cuts = sets(r15, lo=958)
wcut = [v for t, v in S.writes(r15) if t >= 958]
check(f"T15: the EV-21 cut (two cuts as the excess grows): one line per cut, "
f"each 'peak cut' with the value written ({[m for _t, m in cuts]}; "
f"writes {wcut})",
len(cuts) == len(wcut) >= 1
and all(m.endswith("(peak cut).") for _t, m in cuts)
and [amps_in(m) for _t, m in cuts] == wcut)
cut_note = [m for _t, lv, m in r15["lines"]
if m == "Solar lowered the car for the peak: CAR_CUT."]
check(f"T15: the existing CAR_CUT info line and notice once per session, "
f"unchanged ({len(cut_note)}, notices "
f"{[n for _t, n in r15['raised'] if 'cut' in n]})", len(cut_note) == 1)
check("T15: the 16 A before the cut was Solar's own line, not a cut",
texts(r15, hi=958)[-1].endswith("(Solar).") if texts(r15, hi=958)
else False)
r16 = kshape("C", dur=1300)
c16 = texts(r16, lo=950)
check(f"T16: a cut deeper than the car can follow (to 0 A): the line says "
f"'to 0 A' and 'peak cut' ({c16})",
c16 == ["Car: set from 10 A to 0 A on 3 phases (peak cut)."])
r18 = kshape("C", dur=1300,
events={959: lambda p, c: setattr(p.ch, "refuse", "ignore")})
check(f"T18: the cut refused (3 tries 60 s apart): the existing CHARGER_REFUSED "
f"once, 0 lines for the cut ({texts(r18, lo=950)}, "
f"{len(warns(r18, 'CHARGER_REFUSED'))}, tries "
f"{[round(t) for t, v in S.writes(r18) if t >= 959]})",
not texts(r18, lo=950) and len(warns(r18, "CHARGER_REFUSED")) == 1
and len([1 for t, v in S.writes(r18) if t >= 959]) == 3)
class Drv:
"""A driver that takes, or not, what it is given, for the writer's own
steps. `write_current` notes how many log records existed when it
returned (N3: the line follows the write)."""
def __init__(self, ok=True):
self.ok, self.sent, self.marks = ok, [], []
async def write_current(self, a, **kw):
self.sent.append(a)
self.marks.append(LOG.mark())
return self.ok
async def write_phases(self, n):
return True
def reading(**kw):
base = dict(available=True, state="C", power_w=0.0, phases_allowed=3,
allowed_a=0.0, setpoint_a=0.0)
base.update(kw)
return CH.ChargerReading(**base)
def tracker():
return CH.CarTracker()
def go(coro):
return asyncio.run(coro)
# T17: the cut's cap lowers the closing current of a phase change.
async def t17():
w = carmode.SolarWriter()
drv, tr = Drv(), tracker()
w.plan.a, w.plan.target_w, w.plan.n = 16.0, 16.0 * 230.0 * 3, 3
w.cut_a = 8.0
w.seq = {"stage": "settle", "t0": 0.0, "t1": 0.0, "n": 3, "tries": 0,
"prev": None, "sel_ok": True}
n0 = LOG.mark()
await w._advance(drv, reading(), 0.0, 20.0, tr, w._seq_want(16.0, 3),
16.0, None)
return drv, [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
d17, l17 = go(t17())
check(f"T17: a cut due while Solar's phase change is under way: the close "
f"carries 'peak cut' and the capped value, no extra line ({l17}, sent "
f"{d17.sent})",
l17 == ["Car: set from 0 A to 8 A on 3 phases (peak cut)."]
and d17.sent == [8.0])
async def t17b():
w = carmode.SolarWriter()
drv, tr = Drv(), tracker()
w.plan.a, w.plan.target_w, w.plan.n = 10.0, 10.0 * 230.0 * 3, 3
w.seq = {"stage": "settle", "t0": 0.0, "t1": 0.0, "n": 3, "tries": 0,
"prev": None, "sel_ok": True}
n0 = LOG.mark()
await w._advance(drv, reading(), 0.0, 20.0, tr, w._seq_want(16.0, 3),
16.0, None)
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check(f"T17: the same close with no cut: 'Solar', the plan's value "
f"({go(t17b())})",
go(t17b()) == ["Car: set from 0 A to 10 A on 3 phases (Solar)."])
# T41: a write either side of the quarter boundary (900): one line each.
sun41 = step_fn((899, 4760.0), (931, 4100.0), base=4300.0)
r41 = solar(1000, sun=sun41)
l41 = sets(r41, lo=890, hi=960)
check(f"T41: Solar writes at 899 and 931 across the quarter boundary: one "
f"line each, no duplicate ({l41}, writes "
f"{[x for x in wlist(r41) if x[0] > 890]})",
len(l41) == 2 and len({m for _t, m in l41}) == 2
and len(l41) == len([1 for t, v in S.writes(r41) if t > 890]))
# =========================================================================== #
print("\n6. FAILED OR LATE WRITES (T19-T23, T33, T37, T39, N2, N3)")
# =========================================================================== #
REF = "The charger did not take the current, so the add-on stops asking"
for kind in ("ignore", "error"):
r19 = manual(400, events={19: refuse(kind)})
check(f"T19 [{kind}]: Manual write refused, 3 tries 60 s apart: 0 lines, "
f"CHARGER_REFUSED once, text unchanged ({texts(r19)}, "
f"{len(warns(r19, REF))})",
not texts(r19) and len(warns(r19, REF)) == 1)
r20 = manual(300, events={19: refuse("ignore"), 40: lift})
t20 = sets(r20)
check(f"T20: refused once, the charger takes it at the retry: exactly 1 line, "
f"at the retry, 60 s or more after the fail ({t20})",
len(t20) == 1 and t20[0][0] >= 20 + 60
and t20[0][1] == "Car: set from 10 A to 6 A on 1 phase (Manual).")
async def _clamp(p, c):
p.clamp_ok = await c.car_writer._write(c.charger, 30.0, 10.0, 400.0, c.car)
r21 = manual(120, finale=_clamp)
fin = [(lv, m) for t, lv, m in r21["lines"] if t is None]
check(f"T21: a write above the clamp: CHARGER_CLAMP error unchanged, nothing "
f"sent, no line ({[(lv, m[:30]) for lv, m in fin]})",
any(lv == "ERROR" and m.endswith("CHARGER_CLAMP.") for lv, m in fin)
and not [m for lv, m in fin if m.startswith(SETP)]
and r21["plant"].clamp_ok is False)
class RaisingPlant(S.SunPlant):
"""Home Assistant whose call on the current entity raises, from 19 s."""
async def set_number(self, e, v):
if e == SET and self.t >= 19.0:
raise RuntimeError("HA call error")
return await super().set_number(e, v)
r22 = manual(200, plant_cls=RaisingPlant)
check(f"T22: the driver raises in write_current: 0 lines, the existing 'step "
f"failed' error once, no new exception from the log path "
f"({texts(r22)})",
not texts(r22) and len([1 for _t, lv, m in r22["lines"]
if lv == "ERROR"
and m == "The car charger step failed"]) == 1)
def slow(p, c):
p.ch.lag_s = 12.0 # over TOOK_S (10 s)
r23 = solar(400, events={100: slow})
w23 = [(round(t), v) for t, v in S.writes(r23)]
check(f"T23 (Q2): a late read-back (12 s, over TOOK_S): the write is not "
f"taken at once, then adopted; exactly 1 'set' line, at the accept "
f"({sets(r23)}, write {w23})",
texts(r23) == ["Car: set from 0 A to 16 A on 1 phase (Solar)."]
and sets(r23)[0][0] >= 120 + 10
and len(taken(r23)) == 0)
check("T23 (Q2): no line at the write itself, none for the failed try",
not sets(r23, hi=130))
async def t23b():
"""The accept after the warning: three refused tries, then the charger
shows the value (late): the warning is the existing one, then one line."""
w = carmode.SolarWriter()
drv, tr = Drv(ok=False), tracker()
w.engaged = True
n0 = LOG.mark()
for k in range(3):
await w._write(drv, 16.0, 0.0, 100.0 + 70 * k, tr)
mid = [m for _lv, m, _x in LOG.rec[n0:]]
w._adopt(16.0)
w._adopt(16.0) # a second read-back: nothing again
end = [m for _lv, m, _x in LOG.rec[n0:]]
return mid, end
mid, end = go(t23b())
check(f"T23 (Q2): three tries not taken give the existing CHARGER_REFUSED "
f"warning and no line; the accept then gives exactly one line "
f"({mid} -> {end})",
len(mid) == 1 and mid[0].endswith("CHARGER_REFUSED.")
and end[1:] == ["Car: set from 0 A to 16 A (Solar)."])
async def t23c():
w = carmode.SolarWriter()
drv, tr = Drv(ok=False), tracker()
n0 = LOG.mark()
await w._write(drv, 16.0, 0.0, 100.0, tr)
w._adopt(10.0) # shows something else: not our write
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check("T23/M4: a read-back that shows another value is not an accept: 0 lines",
go(t23c()) == [])
# Q2 for Manual: a write taken late logs its line once, at the accept.
r23m = manual(200, events={10: slow})
w23m = [(round(t), v) for t, v in S.writes(r23m)]
check(f"T23 Manual (Q2): a late read-back (12 s): no line at the write, "
f"exactly 1 line at the accept, a few seconds later ({sets(r23m)}, "
f"write {w23m})",
texts(r23m) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."]
and sets(r23m)[0][0] >= 20 + 10 and len(taken(r23m)) == 0)
async def t23m():
"""Three tries not taken: the existing CHARGER_REFUSED warning, no line;
the charger then shows the value: exactly one line, once."""
w = carmode.ManualWriter()
w.boot = False
drv, tr = Drv(ok=False), tracker()
async def step(a, now):
await w.step(drv, reading(state="C", allowed_a=a, setpoint_a=a,
phases_allowed=1), mode=carmode.MANUAL,
want_a=6.0, want_phases=1, rev=1, clamp=16.0, now=now,
tracker=tr, writing=True, status="charging")
n0 = LOG.mark()
for k in range(3):
await step(10.0, 100.0 + 70 * k)
mid = [m for lv, m, _x in LOG.rec[n0:] if lv != "DEBUG"]
await step(6.0, 300.0)
await step(6.0, 310.0) # the next read-back: nothing again
return mid, [m for lv, m, _x in LOG.rec[n0:] if lv != "DEBUG"]
mid, end = go(t23m())
check(f"T23 Manual (Q2): three tries not taken give the existing Manual "
f"CHARGER_REFUSED warning and no line; the accept then gives exactly "
f"one line ({mid} -> {end})",
len(mid) == 1 and mid[0].endswith("CHARGER_REFUSED.")
and end[1:] == ["Car: set from 10 A to 6 A on 1 phase (Manual)."])
async def stale(shape):
"""Review round 2: a refused Manual try is not a request any more once
the user changed something or another mode ran. Another source then
shows the same value; Manual's adopt must log nothing."""
w = carmode.ManualWriter()
w.boot = False
drv, tr = Drv(ok=False), tracker()
async def step(a, now, mode=carmode.MANUAL, rev=1):
await w.step(drv, reading(state="C", allowed_a=a, setpoint_a=a,
phases_allowed=1), mode=mode,
want_a=6.0, want_phases=1, rev=rev, clamp=16.0, now=now,
tracker=tr, writing=True, status="charging")
n0 = LOG.mark()
await step(10.0, 100.0) # refused
if shape == "solar": # the user picks Solar, then Manual
w.user_changed()
await step(10.0, 200.0, mode=carmode.SOLAR, rev=2)
await step(6.0, 300.0, mode=carmode.SOLAR, rev=2) # Solar's own 6 A
w.user_changed()
await step(6.0, 500.0, rev=3)
elif shape == "off": # Off, the wallbox app sets 6 A
await step(10.0, 150.0, mode=carmode.OFF)
await step(6.0, 400.0, mode=carmode.OFF)
await step(6.0, 500.0)
else: # the user changed the value
w.user_changed()
await step(6.0, 500.0, rev=2)
return [m for lv, m, _x in LOG.rec[n0:]
if lv != "DEBUG" and m.startswith(SETP)]
for shape in ("solar", "off", "user"):
check(f"T23 Manual (review round 2, N2) [{shape}]: a refused try is not "
f"logged later when the same value comes from another source",
go(stale(shape)) == [])
async def t23l():
"""Review round 2: Solar's refused try is history once Solar is left;
a later read-back of that value logs nothing."""
w = carmode.SolarWriter()
drv, tr = Drv(ok=False), tracker()
w.engaged = True
n0 = LOG.mark()
await w._write(drv, 16.0, 0.0, 100.0, tr)
w._leave()
w._adopt(16.0)
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check("T23 (review round 2, N2) [solar leave]: a refused Solar try is not "
"logged after Solar is left: 0 lines", go(t23l()) == [])
# T33: shutdown, the charger refuses all 3 release tries.
async def _refuse_shutdown(p, c):
p.ch.refuse = "ignore"
await c.shutdown()
r33 = solar(300, finale=_refuse_shutdown)
check(f"T33: Solar shutdown, the charger refuses all 3 release tries: "
f"CHARGER_RELEASE unchanged once, 0 shutdown lines "
f"({texts(r33, lo=121)}, {len(warns(r33, 'CHARGER_RELEASE'))})",
len(warns(r33, "CHARGER_RELEASE")) == 1 and not texts(r33, lo=121)
and not [m for t, m in sets(r33) if "(shutdown)" in m])
# T37: stale charger reads with no write due.
r37 = solar(500, events={300: lambda p, c: p.ch.freeze(),
308: lambda p, c: p.ch.freeze(False)})
check(f"T37: a frozen charger reading for 8 s with no write due: 0 lines "
f"({texts(r37, lo=125)}, writes {wlist(r37)})",
not texts(r37, lo=125) and len(wlist(r37)) == 1)
# T39: a stuck (frozen) charger, Solar's starts are not taken.
r39 = solar(1300, events={100: lambda p, c: p.ch.freeze()})
check(f"T39: a stuck charger reading, the 3 starts not taken: 0 lines, the "
f"stuck CHARGER_REFUSED once, unchanged "
f"({texts(r39)}, {len(warns(r39, 'CHARGER_REFUSED'))}, "
f"{len([1 for t, v in S.writes(r39) if v > 0])} starts)",
not texts(r39) and len(warns(r39, "CHARGER_REFUSED")) == 1)
# N3: the line follows the write: nothing is logged before it returns.
async def n3():
w = carmode.ManualWriter()
drv, tr = Drv(), tracker()
n0 = LOG.mark()
await w._write(drv, 7.0, 10.0, 50.0, tr, **WHY)
rec = LOG.rec[n0:]
first = next((i for i, x in enumerate(rec) if x[1].startswith(SETP)),
10 ** 9)
return n0 + first, drv.marks[0]
at, ret = go(n3())
check(f"N3: the line is logged after write_current returned (record {at} vs "
f"the driver's return at {ret})", ret <= at < 10 ** 8)
# =========================================================================== #
print("\n7. START-UP, SHUTDOWN, WAYS OUT (T27-T30, T32, T34-T36, T38, T40)")
# =========================================================================== #
st27 = S.rig._Store()
st27.data["car_current"] = 6.0
r27 = run("manual", 120, store=st27, setpoint=10, phases=1, car_phases=1,
opts=MOPT)
check(f"T27: restart in Manual, stored 6 A, the charger shows 10 A: 1 mode "
f"line at start-up, exactly 1 line, 'start-up' "
f"({modes(r27)}, {texts(r27)})",
[m for _t, m in modes(r27)] == ["Car mode is now Manual."]
and texts(r27) == ["Car: set from 10 A to 6 A on 1 phase (start-up)."])
r28 = solar(400, setpoint=10)
check(f"T28: restart in Solar, the charger shows its own 10 A (D2): the mode "
f"line, the 0 A as 'start-up', the start current as 'Solar' "
f"({texts(r28)})",
[m for _t, m in modes(r28)] == ["Car mode is now Solar."]
and texts(r28) == ["Car: set from 10 A to 0 A on 1 phase (start-up).",
"Car: set from 0 A to 16 A on 1 phase (Solar)."])
st29 = S.rig._Store()
st29.data[ctl_car.CAR_EXIT_KEY] = True
r29 = run("off", 120, store=st29, setpoint=10, phases=1, car_phases=1,
opts=MOPT)
check(f"T29: restart in Off with the exit 0 A owed (C1), charger 10 A: the "
f"mode line Off and 1 line 'to 0 A (start-up)' "
f"({modes(r29)}, {texts(r29)})",
[m for _t, m in modes(r29)] == ["Car mode is now Off."]
and texts(r29) == ["Car: set from 10 A to 0 A on 1 phase (start-up)."])
r30 = run("off", 2000, events={1800: act("car_mode", "manual")}, setpoint=10,
phases=1, car_phases=1, opts=MOPT)
check(f"T30: restart in Off, nothing owed; 30 min later the user picks "
f"Manual: the start mode line once, the later write is 'Manual', not "
f"'start-up' ({modes(r30)}, {texts(r30)})",
[m for _t, m in modes(r30)] == ["Car mode is now Off.",
"Car mode is now Manual."]
and texts(r30) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."])
check("T30: the Manual line is not 'start-up' even for the first write of "
"the process (M9)", bool(texts(r30))
and "start-up" not in " ".join(texts(r30)))
r32 = solar(300, finale=_shutdown)
check(f"T32: Solar shutdown, 0 A taken: 1 line 'to 0 A ... (shutdown)' "
f"({texts(r32, lo=121)}, {[t for t, m in sets(r32)]})",
[m for t, m in sets(r32) if t is None] == [
"Car: set from 16 A to 0 A on 1 phase (shutdown)."])
r34 = manual(205, events={200: act("car_phases", 3)}, car_phases=3, opts={},
finale=_shutdown)
check(f"T34: Manual shutdown in the middle of a phase change (abandon), the "
f"give-back taken: 1 line, 'shutdown' ({texts(r34, lo=200)})",
[m for t, m in sets(r34) if t is None] == [
"Car: set from 0 A to 6 A on 3 phases (shutdown)."])
r35 = solar(400, events={300: act("car_mode", "off")})
check(f"T35: Solar -> Off while Solar's 16 A stands: 1 mode line Off, 1 line "
f"'to 0 A (Solar)' (Q3), then nothing ({modes(r35)[-1:]}, "
f"{texts(r35, lo=300)})",
[m for _t, m in modes(r35)[-1:]] == ["Car mode is now Off."]
and texts(r35, lo=300) == [
"Car: set from 16 A to 0 A on 1 phase (Solar)."])
r36 = solar(400, events={300: act("car_mode", "manual")})
check(f"T36: Solar -> Manual (user 6 A, charger 16 A): 1 mode line and 1 line "
f"for Manual's 6 A, reason Manual ({modes(r36)[-1:]}, "
f"{texts(r36, lo=300)})",
[m for _t, m in modes(r36)[-1:]] == ["Car mode is now Manual."]
and texts(r36, lo=300) == [
"Car: set from 16 A to 6 A on 1 phase (Manual)."])
r38 = kshape("C", dur=1400, events={940: lambda p, c: setattr(p, "meter_on",
False)})
check(f"T38: the meter silent past meter_max_age_s: Solar's pause, exactly 1 "
f"line 'to 0 A (Solar)' ({texts(r38, lo=940)})",
texts(r38, lo=940) == [
"Car: set from 10 A to 0 A on 3 phases (Solar)."])
class Liar(SimCharger):
"""The read-back shows what was asked; the car draws a third more."""
def target_w(self):
w = super().target_w()
return w * 8.0 / 6.0 if self.setpoint_a == 6.0 else w
r40 = manual(120, sim=Liar(setpoint_a=10))
check(f"T40: the read-back shows 6 A but the car draws 8 A (1840 W): the line "
f"says 6 A, what was written ({texts(r40)}, car "
f"{round(r40['trace'][-1]['car'])} W)",
texts(r40) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."]
and round(r40["trace"][-1]["car"]) == 1840)
# =========================================================================== #
print("\n8. NOTHING ELSE MOVES (T43-T45, N1, N2, N7, N8, N10, N11)")
# =========================================================================== #
# N5: a mode line only for a mode change (and the one at start-up).
chg4 = 1 + 1 # r4: the start, then Off -> Manual
check(f"N5: no mode line without a change: {len(modes(r4))} in r4 (start + "
f"the one change, six more same-mode or refused actions), "
f"{len(modes(r7))} in a 700 s Solar run with no action, "
f"{len(modes(r1))} in r1 (start + Manual, two same-value actions)",
len(modes(r4)) == chg4 and len(modes(r7)) == 1 and len(modes(r1)) == 2
and len(modes(r30)) == 2)
# N8: the existing warning and info texts are the base's, word for word.
# EV-54 (Q3) adds the refused peak cut's own text; the others are unchanged.
EXACT = {
"The charger did not take the current, so the add-on stops asking until "
"you change it: CHARGER_REFUSED.",
"The charger did not take the current, so the add-on stops asking until "
"you press Solar: CHARGER_REFUSED.",
"The charger did not take the peak cut, so the add-on tries again next "
"quarter: CHARGER_REFUSED.",
"The charger did not take the current, so the add-on tries again in 15 "
"min, then every 30 min: CHARGER_REFUSED.",
"The charger did not take 0 A before the add-on stopped, so the car may "
"still be charging: CHARGER_RELEASE.",
"Software fault: the add-on was about to ask the charger for more than "
"its limit, so nothing was sent: CHARGER_CLAMP.",
"Solar lowered the car for the peak: CAR_CUT.",
"The car kept drawing, so the phases were not changed."}
seen8 = {m for r in ALL for _t, lv, m in r["lines"] if lv != "DEBUG"
and ("CHARGER_" in m or "CAR_CUT" in m or "kept drawing" in m)}
check(f"N8: every CHARGER_* / CAR_CUT / kept-drawing line seen in any run is "
f"one of base's texts or EV-54's, and each of the eight was seen "
f"({sorted(seen8 - EXACT)[:2]}, missing {sorted(EXACT - seen8)[:2]})",
seen8 == EXACT)
# T44: the existing suites run unedited in CI (checks / unit) and were run
# here (the report lists them). What a unit row can pin: the two existing
# files this ticket had to touch still hold their own assertions and set
# aside ONLY the two new prefixes.
_here = os.path.dirname(os.path.abspath(__file__))
_t28 = open(os.path.join(_here, "test_ev28.py")).read()
_t51 = open(os.path.join(_here, "test_ev51.py")).read()
check("T44: test_ev28 and test_ev51 keep their pinned rows and filter only "
"'Car: set' and 'Car mode is now'",
'check(f"T13: a clean change logs nothing at INFO or above' in _t28
and "CAP.loud(MARK[0]) == []" in _t28
and "info == BASE_INFO" in _t51
and _t28.count('("Car: set", "Car mode is now")') == 1
and _t51.count('("Car: set", "Car mode is now")') == 1)
# Taken on the base build 02166e2 with EV52_GOLDEN=1 (the same scenarios).
_CAR1 = ["car current set to 8 by operator", "car current set to 8 by operator",
"car mode set to manual by operator", "car current set to 6 by operator",
"car phases set to 1 by operator"]
GOLDEN = {
"T1": {"cur": [(21, 6.0), (201, 8.0)], "events": _CAR1,
"keys": "bb1fe135bd15690c", "notes": [], "ph": [],
"sent": [6.0, 8.0]},
"T11": {"cur": [(21, 6.0), (201, 0.0), (212, 6.0)],
"events": ["car phases set to 3 by operator",
"car mode set to manual by operator",
"car current set to 6 by operator",
"car phases set to 1 by operator"],
"keys": "bb1fe135bd15690c", "notes": [], "ph": [(202, 3)],
"sent": [6.0, 0.0, 6.0]},
"T15": {"cur": [(121, 16.0), (961, 13.0), (967, 12.0), (997, 6.0)],
"events": [], "keys": "00425fef63358fa7",
"notes": [(13, "goodwe_integrator_bound"), (961, "goodwe_car_cut")],
"ph": [], "sent": [16.0, 13.0, 12.0, 6.0]},
"T28": {"cur": [(1, 0.0), (121, 16.0)], "events": [],
"keys": "642fc116d64d9487", "notes": [], "ph": [],
"sent": [0.0, 16.0]},
"T32": {"cur": [(121, 16.0), (300, 0.0)], "events": [],
"keys": "642fc116d64d9487", "notes": [], "ph": [],
"sent": [16.0, 0.0]},
"T7": {"cur": [(121, 16.0)], "events": [], "keys": "00425fef63358fa7",
"notes": [], "ph": [], "sent": [16.0]},
}
def view(r):
return {"cur": wlist(r), "ph": [(round(t), n) for t, n in
S.writes(r, "phases")],
"sent": list(r["c"].charger.sent),
"notes": [(round(t), n) for t, n in r["raised"]],
"events": [e[9:] for e in r["c"].events if e[9:].startswith("car ")],
"keys": K.digest(sorted(r["store"].data))}
SCEN = {"T1": r1, "T7": r7, "T11": r11, "T15": r15, "T28": r28, "T32": r32}
if os.environ.get("EV52_GOLDEN"):
import json
print("GOLDEN", json.dumps({k: view(v) for k, v in SCEN.items()},
sort_keys=True))
for k, r in SCEN.items():
check(f"T43/T45 {k}: the writes (value, second, phases), the notices, the "
f"action log and the store keys are those of the base build",
view(r) == GOLDEN.get(k))
check("N7: no new store key, notification or option (the key lists above are "
"base's)", all(view(r)["keys"] == GOLDEN.get(k, {}).get("keys")
for k, r in SCEN.items()))
bad = [m for r in ALL for _t, lv, m in r["lines"]
if m.startswith((SETP, MODEP)) and (
lv != "INFO" or re.search(r"number\.|select\.|sensor\.|http|token",
m))]
check(f"N10: every new line is INFO, with no entity id or secret ({bad[:2]})",
not bad)
n2 = []
for r in ALL:
sent = {v for _t, v in S.writes(r)} | set(
getattr(r["c"].charger, "sent", ()))
n2 += [m for _t, m in sets(r) if amps_in(m) not in sent]
check(f"N2: every line's value is a value the add-on sent ({n2[:2]})", not n2)
n11 = []
for r in ALL:
if r.get("sim") is None:
continue
n11 += [x for x in r["sim"].log if x[1] == "current" and x[2] > 16.0]
n11 += [x for x in r["sim"].log if x[1] == "phases" and x[3] >= 100.0
and x[4] > 0.0]
check(f"N1/N11: no write above the clamp and no select under load in any "
f"run ({n11[:2]})", not n11)
tb = [i for r in ALL if r is not r22
for _lv, _m, x in LOG.rec[r["n0"]:r["end"]] if x]
check(f"N9: no exception from the log path in any run but T22's own "
f"({len(tb)})", not tb)
report()
+577
View File
@@ -0,0 +1,577 @@
"""EV-54: after the quarter's refused cut tries, Solar's normal control goes
on, and the cut is tried again at the next quarter start while one is needed.
`python3 -B test_ev54.py`
Rows T1-T13 and T15-T23 of reports/EV-54-test-plan.md (T14 and T25-T35, the
drop rule, are in test_ev54_drop.py; T24 is the run of the existing files).
The real Controller on `tools/ev20_sun.py` through `tools/ev54_kit.py`;
Shape C is N=2, both batteries at 10 %, the car at 10 A on 3 phases, the
house 3000 W and the sun 0 from 960; the second period runs 900-1800.
"Refusal" is the charger ignoring a write ("ignore") or Home Assistant
refusing it ("error"). Golden values marked bdfd3e6 were taken on that tree
with `EV54_GOLDEN=1 python3 -B test_ev54.py`.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
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, messages # noqa: E402
from ev20_kit import LOG, check, fails, act, step_fn, const # noqa: E402
from ev21_kit import (ALARMS, digest, merge, shape, view_guard, # noqa: E402
view_writes, refuse_n1, set_resp)
from ev54_kit import (HOLD_TEXT, Q3_TEXT, W54, as_off, cut_writes, # noqa: E402
house_c, key_change, never54, refused_by_key, row,
rows, run, sun_c, t_lift, twin, window, writes,
dropped, first, nth, present)
n_log0 = LOG.mark()
TAKE = os.environ.get("EV54_GOLDEN") == "1"
CUT = messages.ID_CAR_CUT
GOLDEN = {
'T10 [C]': ('938225cc1dd6d8f8', 'ba8e36dfa3011013'),
'T10 [W]': ('dfb6d075dd1f2330', 'eec4c29653ce1e3e'),
'T10 [M]': ('385ae1fbf07b25d6', 'a52b1c929747cd07'),
'T11 [Manual]': ([(1601.0, 8.0), (1671.0, 8.0), (1741.0, 8.0)],
['WARNING']),
'T11 [Off]': [(1080.0, 0.0, False)],
}
got = {}
def golden(name, value):
got[name] = value
if TAKE:
print(f"GOLDEN {name!r}: {value!r},")
return GOLDEN.get(name)
def refused(r, t0=0, t1=1e9):
"""(t, a) of the refused cut tries in [t0, t1)."""
return [(t, a) for t, a, ok, _why, _k in cut_writes(r, t0, t1) if not ok]
def gaps(ts):
return [b - a for a, b in zip(ts, ts[1:])]
def near(t, want, lo, hi):
return t is not None and want - lo <= t <= want + hi
def amber(r, t0, t1, rid="charger_refused"):
return [x["t"] for x in r["trace"] if t0 <= x["t"] < t1
and rid in (x.get("amber") or [])]
def gave_up_at(r, t0=0, t1=1e9):
return [x["t"] for x in rows(r, t0, t1) if x["gave_up"]]
def roll_try(name, r, kc, n, *, value=0.0, taken_by=None, hold_s=0.0,
graded=True):
"""T4's bound: the new key's first try in its first cycle (at N=2 up to
max_hold_s before :00), then (if `taken_by`) the next try 60 s or more
later is taken, read back within 2 s, and (`graded`, T4's own row)
graded can-cut from that cycle (+1 s) with the CAR_CUT note once."""
w2 = [(t, a, ok) for t, a, ok, _w, _k in cut_writes(r, 1800 - hold_s - 1)]
t1 = nth(w2, 0)
lo = 1800 - (hold_s if n == 2 else 0) - 1
ok1 = present(t1) and lo <= t1[0] <= 1801 and abs(t1[1] - value) < 0.01 \
and present(kc) and abs(t1[0] - kc) <= 1
if taken_by is None:
check(f"{name}: the new key ({kc}) is tried in its first cycle "
f"({t1}, bound [{lo}, 1801]), as {value} A", ok1)
return
t2 = nth(w2, 1)
ok2 = present(t1, t2) and t2[2] and not t1[2] \
and t2[0] - t1[0] >= carmode.RETRY_S and t2[0] <= taken_by + 61
rb = [x["t"] for x in rows(r, t2[0] if present(t2) else 1e9)
if abs(x["rb"] - value) < 0.01]
can = [x["t"] for x in rows(r, t2[0] if present(t2) else 1e9)
if x["can"]]
cuts = [t for t, n_ in r["raised"] if n_ == CUT and t >= 1790]
check(f"{name}: the new key ({kc}) tried in its first cycle ({t1}, bound "
f"[{lo}, 1801]) and refused; the next try {t2} 60 s or more later "
f"is taken, read back by {first(rb)}, can-cut from {first(can)}; "
f"CAR_CUT once ({cuts})",
ok1 and ok2 and bool(rb) and rb[0] <= t2[0] + 2
and (not graded or (bool(can) and can[0] <= rb[0] + 1
and len(cuts) == 1)))
# =========================================================================== #
print("\n1. SOLAR GOES ON AFTER THE QUARTER'S TRIES (T1, T2, T3)")
# =========================================================================== #
T1R = {}
for kind in ("ignore", "error"):
r = run(house_c((1250, 900.0)), sun_c((1250, 9000.0)), dur=1800,
events=window({}, 959, 1100, kind))
T1R[kind] = r
tr = refused(r, 900, 1800)
ts = [t for t, _a in tr]
tl = t_lift(r, 1100, 1800)
nz = [(t, a, why) for t, a, ok, why in writes(r, (tl or 1e9) + 1,
(tl or 1e9) + 131)
if a > 0.0 and ok]
check(f"T1 [{kind}]: tries {tr}: 0 A at 960+-1, 1020+-2, 1080+-2, no "
f"4th in 900-1800",
len(tr) == 3 and all(a == 0.0 for _t, a in tr)
and near(nth(ts, 0), 960, 1, 1) and near(nth(ts, 1), 1020, 2, 2)
and near(nth(ts, 2), 1080, 2, 2))
check(f"T1 [{kind}]: the cap lifts at {tl} (1370+-2); the drop then: "
f"sent_a 10, taken, plan 10 ({dropped(r, tl or 0, 10.0)}); a "
f"non-zero Solar write within 130 s ({nz[:2]}); gave_up never "
f"({gave_up_at(r, 900, 1800)[:2]})",
near(tl, 1370, 2, 2) and dropped(r, tl or 0, 10.0) is not None
and bool(nz) and 6.0 <= nz[0][1] <= 16.0 and nz[0][2] == "Solar"
and not gave_up_at(r, 900, 1800))
never54(f"T1 [{kind}]", r)
ev2 = window({}, 959, None)
T2 = run(house_c(), sun_c(), dur=1800, events=ev2)
tr = refused(T2, 900, 1800)
ts = [t for t, _a in tr]
nz2 = [(t, a) for t, a, _ok, _why in writes(T2, 900, 1800) if a > 0.0]
caps = sorted({x["cap"] for x in rows(T2, 961, 1800)}, key=str)
check(f"T2: a cut needed all quarter: exactly 3 tries ({tr}), all 0 A, gaps "
f"{gaps(ts)} >= 60; no non-zero Solar write ({nz2[:2]}); the cap stays "
f"0 ({caps})",
len(tr) == 3 and all(a == 0.0 for _t, a in tr)
and all(g >= 60 for g in gaps(ts)) and not nz2 and caps == [0.0])
never54("T2", T2)
# T1 continued, in the next period: in 900-1800 the import of 960-1250 keeps
# the projection near the aim, so a sun drop there makes a new cut due, and
# with the quarter's tries used up none goes out (Q1). From 1800 the period
# is fresh: the sun falls to 7 A worth at 1900, under 6 A worth at 2000.
r = run(house_c((1250, 900.0)),
sun_c((1250, 9000.0), (1900, 5900.0), (2000, 4400.0)), dur=2350,
events=window({}, 959, 1100))
w3 = [(t, a, ok, why) for t, a, ok, why in writes(r, 1081, 2350)]
down = [x for x in w3 if 1900 <= x[0] <= 1932]
hold6 = [x for x in w3 if 2000 <= x[0] <= 2032 and x[1] == 6.0]
pause = [x for x in w3 if 2298 <= x[0] <= 2302 and x[1] == 0.0]
prev = [x for x in w3 if x[0] < 1900]
caps3 = [x["t"] for x in rows(r, 1800, 2350) if x["cap"] is not None]
check(f"T3: after the drop Solar follows the spare: a step-down by 1932 "
f"({down}), the 6 A hold by 2032 ({hold6}), the pause 0 A 'Solar' at "
f"2300+-2 ({pause}); all taken ({[x for x in w3 if not x[2]]}); no cut "
f"in that period ({caps3[:2]})",
bool(down) and bool(prev) and down[0][1] < prev[-1][1] and bool(hold6)
and bool(pause) and pause[0][3] == "Solar"
and all(x[2] for x in w3) and not caps3)
never54("T3", r)
# =========================================================================== #
print("\n2. THE NEXT QUARTER TRIES AGAIN (T4, T5, T6)")
# =========================================================================== #
T4R = {}
for n in (2, 1):
for kind in ("ignore", "error"):
r = run(house_c(), sun_c(), dur=1950, n=n,
events=window({}, 959, 1830, kind))
T4R[(n, kind)] = r
hold_s = r["c"].p1.averager.max_hold_s
rbk = refused_by_key(r)
kc = key_change(r, 1700, 1900)
k900 = [v for k, v in rbk.items() if k == row(r, 1000)["key"]] \
if present(row(r, 1000)) else []
check(f"T4 [N={n}, {kind}]: 3 refused tries in 900-1800 ({k900})",
bool(k900) and len(k900[0]) == 3)
roll_try(f"T4 [N={n}, {kind}]", r, kc, n, taken_by=1830,
hold_s=hold_s)
never54(f"T4 [N={n}, {kind}]", r)
T5R = {}
for tag, socs in (("both at 10 %", None), ("a 10 %, b 60 %",
{"a": 10.0, "b": 60.0})):
r = run(house_c(), sun_c(), dur=3600, socs=socs,
events=window({}, 959, None))
T5R[tag] = r
rbk = refused_by_key(r, 900, 3600)
per = sorted(len(v) for v in rbk.values())
allt = sorted(t for v in rbk.values() for t in v)
other = [(t, a) for t, a, ok, _why in writes(r, 900, 3600)
if t not in allt]
vals = sorted({a for t, a, ok, _w in writes(r, 900, 3600)})
check(f"T5 [{tag}]: refusal never lifted: exactly 3 tries in each of 3 "
f"quarter keys ({ {k: v for k, v in rbk.items()} }), all 0 A "
f"({vals}), gaps {gaps(allt)} >= 60 within and across; no other "
f"write ({other[:3]})",
per == [3, 3, 3] and vals == [0.0]
and all(g >= 60 for g in gaps(allt)) and not other)
never54(f"T5 [{tag}]", r)
r = run(house_c((1790, 900.0)), sun_c((1790, 9000.0)), dur=2700,
events=window({}, 959, 1900))
kc = key_change(r, 1700, 1900)
bad = [(t, a, why) for t, a, ok, why in writes(r, 1795, 2700)
if a == 0.0 or why == "peak cut"]
nxt = first(x for x in writes(r, (kc or 1e9) + 1, 2700))
check(f"T6: the new quarter starts under the aim: no 0 A and no 'peak cut' "
f"write from 1795 ({bad[:3]}); the drop at the key change {kc} "
f"(1800+-2): {dropped(r, kc or 0, 10.0)}; the next write a normal one "
f"({nxt})",
not bad and near(kc, 1800, 2 + r["c"].p1.averager.max_hold_s, 2)
and dropped(r, kc or 0, 10.0) is not None
and (nxt is None or not present(nxt) or nxt[3] == "Solar"))
never54("T6", r)
# =========================================================================== #
print("\n3. AS OFF WHILE THE CUT IS REFUSED (T7)")
# =========================================================================== #
for name, r, win in (
("T1 [ignore]", T1R["ignore"], (961, 1360)),
("T2", T2, (961, 1800)),
("T4 [N=2, ignore]", T4R[(2, "ignore")], (961, 1855)),
("T5 [both at 10 %]", T5R["both at 10 %"], (961, 3600))):
as_off(f"T7 {name}", r, twin(r), ALARMS, refused=win)
evw = merge(window({}, 959, 1830), 900, set_resp(20.0))
r = run(house_c(), sun_c(), dur=1900, socs={"a": 60.0, "b": 60.0},
events=evw)
as_off("T7 [Shape W, refusal 959-1830]", r, twin(r, {900: set_resp(20.0)}),
ALARMS, refused=(961, 1800))
never54("T7 [Shape W]", r)
# =========================================================================== #
print("\n4. THE NOTICE (T8) AND SOLAR'S OWN REFUSED WRITE (T9)")
# =========================================================================== #
for name, r, t1 in (("T2", T2, 1800), ("T5", T5R["both at 10 %"], 3600)):
ts = [t for t, _a in refused(r, 900, 1800)]
q3 = r["w"].lines(Q3_TEXT)
q3w = [(t, lv) for t, lv, _m in q3 if lv == "WARNING"]
old = [t for t, _lv, _m in r["w"].lines("until you press Solar")]
amb = amber(r, (nth(ts, 2) if present(nth(ts, 2)) else 1e9) + 1, 1800)
want_amb = list(range(int(nth(ts, 2)) + 1, 1800)) \
if present(nth(ts, 2)) else [None]
check(f"T8 [{name} run]: at the 3rd refused try ({nth(ts, 2)}) one WARNING "
f"'{Q3_TEXT}' ({q3w}) over the run (DEBUG after: "
f"{[(t, lv) for t, lv, _m in q3 if lv != 'WARNING'][:3]}); no "
f"'until you press Solar' ({old[:2]}); the amber row from the 3rd "
f"try to 1800 ({len(amb)} of {len(want_amb)} s); gave_up never "
f"({gave_up_at(r)[:2]})",
len(q3w) == 1 and present(nth(ts, 2))
and abs(q3w[0][0] - nth(ts, 2)) <= 1 and not old
and [float(t) for t in want_amb] == amb and not gave_up_at(r))
r = run(const(900.0), step_fn((1000, 6700.0), base=7900.0), dur=1900,
events=window({}, 999, None))
w9 = writes(r, 999, 1900)
hold = [(t, lv) for t, lv, _m in r["w"].lines(HOLD_TEXT)]
third = nth(w9, 2)
amb = amber(r, (third[0] if present(third) else 1e9) + 1, 1900)
check(f"T9: Solar's own step-down refused 3 times ({w9[:5]}): the existing "
f"'{HOLD_TEXT}' once ({hold}), the amber row after it ({len(amb)} s), "
f"no write after the 3rd, also across 1800 ({w9[3:5]})",
len(w9) == 3 and all(not ok for _t, _a, ok, _w in w9)
and len({a for _t, a, _o, _w in w9}) == 1 and len(hold) == 1
and hold[0][1] == "WARNING" and len(amb) >= 1800 - third[0] - 2)
never54("T9", r)
# =========================================================================== #
print("\n5. A CHARGER THAT TAKES THE CUT; MANUAL AND OFF (T10, T11)")
# =========================================================================== #
for kind in ("C", "W", "S", "F", "M"):
rec = W54()
r = shape(kind, dur=1300, on_cycle=rec)
r["w"] = rec
cw = cut_writes(r, 950)
vals = [a for _t, a, _ok, _w, _k in cw]
check(f"T10 [{kind}]: the charger takes the cut: one write per value, "
f"each taken, no retry ({[(t, a, ok) for t, a, ok, _w, _k in cw]})",
all(ok for _t, _a, ok, _w, _k in cw)
and len(vals) == len(set(vals)))
if kind in ("C", "W", "M"):
d = (digest(view_writes(r)), digest(view_guard(r)))
want = golden(f"T10 [{kind}]", d)
check(f"T10 [{kind}]: view_writes and view_guard as bdfd3e6 "
f"({d} vs {want})", d == want)
import opt11_identity as rig # noqa: E402
st = rig._Store()
st.data["car_current"], st.data["car_phases"] = 10.0, 3
evm = window({1600: act("car_current", 8)}, 1599, None)
r = run(house_c(), sun_c(), dur=1900, mode="manual", store=st, events=evm)
wm = [(x[0], x[2]) for x in r["sim"].log if x[1] == "current"
and x[0] >= 1590]
mt = [lv for _t, lv, _m in r["w"].lines(
"stops asking until you change it: CHARGER_REFUSED.")]
d = (wm, mt)
want = golden("T11 [Manual]", d)
check(f"T11 [Manual]: a change refused 3 times ({wm}), then the roll at "
f"1800: no 4th; the Manual text once ({mt}); as bdfd3e6 ({want})",
len(wm) == 3 and mt == ["WARNING"] and d == want)
evo = window({1030: act("car_mode", "off")}, 959, None)
r = run(house_c(), sun_c(), dur=1300, events=evo)
wo = [(t, a, ok) for t, a, ok, _w in writes(r, 1025)]
want = golden("T11 [Off]", wo)
check(f"T11 [Off]: Solar left to Off during a refused cut: Off's way-out "
f"0 A writes {wo} as bdfd3e6's ({want})", wo == want and bool(wo))
# =========================================================================== #
print("\n6. AN UNTRUSTED CAR (T12), A SILENT METER (T13)")
# =========================================================================== #
def no_energy(p, c):
p.ch.no_energy = True
ev12 = window({950: no_energy}, 959, 1830)
r = run(house_c(h=9000.0), sun_c(), dur=1950, events=ev12)
tr = refused(r, 900, 1795)
check(f"T12: an untrusted car figure: the cut is 0 A, 3 tries in 900-1800 "
f"({tr})", len(tr) == 3 and all(a == 0.0 for _t, a in tr))
roll_try("T12", r, key_change(r, 1700, 1900), 2, taken_by=1830,
hold_s=r["c"].p1.averager.max_hold_s, graded=False)
o = twin(r, {950: no_energy})
a_r = first(t for t, n in r["raised"] if n in ALARMS and t >= 900)
a_o = first(t for t, n in o["raised"] if n in ALARMS and t >= 900)
check(f"T12: the alarm at the Off twin's second +2 ({a_r} vs {a_o})",
present(a_r, a_o) and a_r is not None and a_o is not None
and abs(a_r - a_o) <= 2)
never54("T12", r)
def silent(on):
def f(p, c):
p.meter_on = not on
return f
seen13 = []
def fresh13(p, c):
"""Before the cycle (a refused write's read-back wait moves the model
clock inside it): is the meter fresh for the cut (N9)?"""
seen13.append((p.t, c._car_cut_meter_fresh()))
ev13 = window({1780: silent(True), 1900: silent(False)}, 959, None)
for t in range(1781, 1900):
ev13 = merge(ev13, t, fresh13)
r = run(house_c(), sun_c(), dur=2000, events=ev13)
# The bound is EV-21's N9 (`_car_cut_meter_fresh`): stale_input_s, or
# meter_max_age_s on `ha_signed` (the harness's meter source).
stale_t = first(t for t, ok in seen13 if not ok)
dark = [(t, a) for t, a, _ok, _w in writes(r, stale_t or 1e9, 1900)]
nxt = first((t, a) for t, a, _ok, _w in writes(r, 1900))
k2 = [len(v) for k, v in refused_by_key(r, 1795).items()]
check(f"T13: the meter silent 1780-1900, stale for the cut (N9) from "
f"{stale_t}: no try while stale ({dark}); the first try at {nxt} "
f"(within [1900, 1902]); at most 3 in the new key ({k2})",
present(stale_t) and stale_t is not None and stale_t < 1860
and not dark and present(nxt) and nxt is not None
and 1900 <= nxt[0] <= 1902 and all(k <= 3 for k in k2))
never54("T13", r)
# =========================================================================== #
print("\n7. A RAISING WRITE (T15), A RESTART (T16), THE KEY (T17)")
# =========================================================================== #
calls15 = []
def boom(p, c):
drv = c.charger
drv._ev54_wc = drv.write_current
async def wc(a, **kw):
calls15.append((p.t, a))
raise RuntimeError("EV-54 T15: the write raised")
drv.write_current = wc
def unboom(p, c):
c.charger.write_current = c.charger._ev54_wc
m15 = LOG.mark()
r = run(house_c(), sun_c(), dur=1950, events={959: boom, 1830: unboom})
c1 = [t for t, _a in calls15 if t < 1795]
c2 = [t for t, _a in calls15 if t >= 1795]
step_w = [m for m in LOG.since(m15, "ERROR") + LOG.since(m15, "WARNING")
if "charger step failed" in m]
tb15 = LOG.tracebacks(m15)
kc = key_change(r, 1700, 1900)
taken2 = [(t, a) for t, a, ok, _w in writes(r, 1830) if ok and a == 0.0]
check(f"T15: a write that raises counts as a refused try: {c1} in 900-1800 "
f"(3, >= 60 s apart), never once per cycle; the new key's try at "
f"{c2[:1]} (key {kc}), the next taken {taken2[:1]}; step-failed "
f"warnings {len(step_w)} (<= 1), Tracebacks {len(tb15)}",
len(c1) == 3 and all(g >= 60 for g in gaps(c1)) and bool(c2)
and present(kc) and kc is not None and abs(c2[0] - kc) <= 1
and bool(taken2) and taken2[0][0] - c2[0] >= 60
and len(step_w) <= 1 and not tb15)
r1 = run(house_c(), sun_c(), dur=1050, events=window({}, 959, None))
r2 = run(house_c(), sun_c(), t0=1050.0, dur=850, sim=r1["sim"],
store=r1["store"], plug=False, events={1830: lambda p, c:
setattr(p.ch, "refuse",
None)})
w16 = [(t, a, ok, why) for t, a, ok, why in writes(r2, 1050, 1795)]
ts = [t for t, _a, _ok, _w in w16]
keys = [k for k in r1["store"].data if "cut" in str(k).lower()
or "tries" in str(k).lower()]
check(f"T16: 2 refused tries, then a restart at 1050: D2's 0 A at 1050+-1 "
f"'start-up' ({w16[:1]}); its retries >= 60 s apart ({gaps(ts)}), at "
f"most 3 in 1050-1800 ({len(w16)}); no store key holds a count "
f"({keys})",
bool(w16) and near(w16[0][0], 1050, 1, 1) and w16[0][1] == 0.0
and w16[0][3] == "start-up" and all(g >= 60 for g in gaps(ts))
and len(w16) <= 3 and all(a == 0.0 for _t, a, _o, _w in w16)
and not keys)
roll_try("T16", r2, key_change(r2, 1700, 1900), 2, taken_by=1830,
hold_s=r2["c"].p1.averager.max_hold_s)
never54("T16", r2)
def none_proj(p, c):
orig = c._car_cut_tick
def tick(proj, guard, target, mono):
if 1801 <= p.t <= 1803:
proj = None
return orig(proj, guard, target, mono)
c._car_cut_tick = tick
r = run(house_c(), sun_c(), dur=2700, events=window({1795: none_proj},
959, None))
rbk = refused_by_key(r, 1700, 2700)
keyed = {k: v for k, v in rbk.items() if k is not None}
check(f"T17 (a): the early roll, then no projection 1801-1803, then fresh: "
f"the count reset once ({keyed}: exactly 3 in the new key, the first "
f"at the roll)",
len(keyed) == 1 and [len(v) for v in keyed.values()] == [3])
never54("T17 (a)", r)
def jump(dt):
def f(p, c):
p.utc_off = dt
return f
r = run(house_c(), sun_c(), dur=2000, events=window({1790: jump(-3600.0)},
959, None))
allt = sorted(t for t, _a, ok, _w in writes(r, 900) if not ok)
check(f"T17 (b): the wall clock jumps -3600 s at 1790: tries {allt} stay "
f">= 60 s apart on the monotonic clock",
bool(allt) and all(g >= 60 for g in gaps(allt)))
never54("T17 (b)", r)
# =========================================================================== #
print("\n8. A PHASE CHANGE (T18), A LATE TAKE (T19), COVER OFF (T20)")
# =========================================================================== #
kw18 = dict(n=2, opts={"ev_phases": "auto"}, phases=1)
r0 = run(const(900.0), const(9280.0), dur=700, **kw18)
log0 = r0["c"].car_solar.log
sel = [t for k, _a, t, _ok in log0 if k == "phases"]
zb = [t for k, a, t, _ok in log0 if k == "current" and a == 0.0
and sel and t <= sel[0]]
tb = int(nth(zb, -1)) if present(nth(zb, -1)) else 400
q1 = (tb // 900 + 1) * 900
ev18 = window({}, tb - 1, None)
r = run(step_fn((tb + 1, 9280.0 + 3400.0 + 2000.0), base=900.0),
const(9280.0), dur=q1 + 100, events=ev18, **kw18)
ph = [(t, n, ok) for k, n, t, ok in r["c"].car_solar.log
if k == "phases" and t >= tb - 1]
nz = [(t, a) for t, a, _ok, _w in writes(r, tb - 1) if a > 0.0]
cw = [(t, a, ok) for t, a, ok, _w, k in cut_writes(r, tb - 1, q1)]
sw = [x["t"] for x in rows(r, tb + 5, q1) if x["switch"]]
nq = first((t, a) for t, a, _ok, _w, _k in cut_writes(r, q1 - 15))
check(f"T18: Solar's own change sent its 0 A at {tb}, the cut due from "
f"{tb + 1}, the charger refusing: no select ({ph}), no closing current "
f"({nz[:2]}); at most 3 cut tries in the quarter ({cw}); the plan's "
f"switch ended ({sw[:2]}); the next quarter's try {nq} is 0 A",
bool(zb) and not ph and not nz and 1 <= len(cw) <= 3 and not sw
and present(nq) and nq is not None and nq[1] == 0.0)
never54("T18", r)
def late_take(p, c):
p.ch.refuse = None
p.ch.set_current(0)
r = run(house_c(), sun_c(), dur=1300, events=window({1110: late_take},
959, None))
set_l = [(t, m) for t, _lv, m in r["w"].lines("Car: set") if t >= 900]
after3 = [(t, a) for t, a, _ok, _w in writes(r, 1081)]
can = [x["t"] for x in rows(r, 1110) if x["can"]]
cuts = [t for t, n in r["raised"] if n == CUT]
new_ref = [t for t, _lv, _m in r["w"].lines("CHARGER_REFUSED") if t >= 1100]
check(f"T19: the charger shows 0 A at 1110 after the 3rd try: one 'Car: set "
f"from 10 A to 0 A (peak cut).' at 1110+-1 ({set_l}); no further try "
f"({after3}); can-cut from {can[:1]}; CAR_CUT once ({cuts}); no new "
f"CHARGER_REFUSED ({new_ref})",
len(set_l) == 1 and near(set_l[0][0], 1110, 1, 1)
and set_l[0][1] == "Car: set from 10 A to 0 A on 3 phases (peak cut)."
and not after3 and bool(can) and can[0] <= 1111 and len(cuts) == 1
and not new_ref)
r = run(house_c(), sun_c(), dur=1950, opts={"ev_batt_cover": False},
events=window({}, 959, 1830))
tr = refused(r, 900, 1795)
check(f"T20: the cover off: the cut at once at 960+-1 and 3 tries in "
f"900-1800 ({tr})", len(tr) == 3 and near(tr[0][0], 960, 1, 1))
roll_try("T20", r, key_change(r, 1700, 1900), 2, taken_by=1830,
hold_s=r["c"].p1.averager.max_hold_s, graded=False)
never54("T20", r)
# =========================================================================== #
print("\n9. TWO EPISODES (T21), A 50 W CAR (T22), A PRESS (T23)")
# =========================================================================== #
r = run(house_c(), sun_c((961, 9000.0), (1400, 0.0)), dur=1700,
opts={"ev_start_min": 1}, events=window({}, 959, 1800))
tr = refused(r, 900, 1800)
ts = [t for t, _a in tr]
tl = t_lift(r, 961, 1300)
check(f"T21: episode 1 (lifted at {tl}) and episode 2 from 1400 share the "
f"quarter's 3 refused tries ({tr}): 960, 1020, then 1400+-1; none "
f"after", len(tr) == 3 and near(nth(ts, 2), 1400, 0, 1)
and present(tl) and tl is not None and nth(ts, 1) < tl)
never54("T21", r)
def car50(p, c):
p.ch.target_w = lambda: 50.0
ev22 = window({900: car50}, 959, None)
r = run(house_c(h=9000.0), sun_c(), dur=1800, events=ev22)
o = twin(r, {900: car50})
a_r = first(t for t, n in r["raised"] if n in ALARMS and t >= 900)
a_o = first(t for t, n in o["raised"] if n in ALARMS and t >= 900)
tr = refused(r, 900, 1800)
check(f"T22: a 50 W car on 10 A: the house alarm at the Off twin's second "
f"({a_r} vs {a_o}); tries {tr} (<= 3)",
present(a_r, a_o) and a_r is not None and a_o is not None
and abs(a_r - a_o) <= 2 and len(tr) <= 3)
never54("T22", r)
for tag, ev in (("Solar pressed at 1100", {1100: act("car_mode", "solar")}),
("Off at 1100, Solar at 1200",
{1100: act("car_mode", "off"),
1200: act("car_mode", "solar")})):
r = run(house_c(), sun_c(), dur=1950, events=window(ev, 959, 1830))
tr = refused(r, 900, 1795)
check(f"T23 [{tag}]: no 4th cut try in 900-1800 ({tr})", len(tr) == 3)
roll_try(f"T23 [{tag}]", r, key_change(r, 1700, 1900), 2,
taken_by=1830, hold_s=r["c"].p1.averager.max_hold_s)
never54(f"T23 [{tag}]", r)
tb_all = LOG.tracebacks(n_log0)
check(f"N13: no traceback in this file's runs ({tb_all[:1]})", not tb_all)
if TAKE:
print("(golden taken; no checks graded)")
sys.exit(0)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)
+702
View File
@@ -0,0 +1,702 @@
"""EV-54: the drop rule. A cut value the charger did not take is never sent
again once no cut stands: Solar takes the read-back as its own (sent, taken,
the plan's current), and the next cut try is a new episode's.
`python3 -B test_ev54_drop.py`
Rows T14 and T25-T35 of reports/EV-54-test-plan.md (G1-G6, QA, QB, QC) and
the writer-level replay of the formal check's C4. The real Controller on
`tools/ev20_sun.py` through `tools/ev54_kit.py`; Shape C as in test_ev54.py.
Golden values marked bdfd3e6 were taken on that tree with
`EV54_GOLDEN=1 python3 -B test_ev54_drop.py`.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
import ev20_sun as S # noqa: E402
from app import carmode, messages # noqa: E402
from ev20_kit import LOG, check, fails, act, step_fn # noqa: E402
from ev21_kit import ALARMS, NoGive, refuse_n1, merge, set_resp # noqa: E402
from ev54_kit import (HOLD_TEXT, as_off, cut_writes, dropped, first, # noqa: E402
house_c, key_change, never54, nth, present,
refused_by_key, row, rows, run, sun_c, t_lift, twin,
window, writes)
n_log0 = LOG.mark()
TAKE = os.environ.get("EV54_GOLDEN") == "1"
CUT = messages.ID_CAR_CUT
GOLDEN = {
'T35 (b)': [],
'T35 (c)': ([(1020.0, 0.0, True)],
['Car: set from 10 A to 0 A on 3 phases (peak cut).']),
'T38': [],
}
def golden(name, value):
if TAKE:
print(f"GOLDEN {name!r}: {value!r},")
return GOLDEN.get(name)
def refused(r, t0=0, t1=1e9):
return [(t, a) for t, a, ok, _why, _k in cut_writes(r, t0, t1) if not ok]
def near(t, want, lo, hi):
return t is not None and present(t) and want - lo <= t <= want + hi
def gave_up_at(r, t0=0, t1=1e9):
return [x["t"] for x in rows(r, t0, t1) if x["gave_up"]]
def stick(p, c):
"""The charger's reading freezes and the tracker's stuck check is armed
now: a stuck verdict STUCK_S later (chargers.py), as after a write."""
p.ch.freeze()
c.car.armed_at = float(p.t)
c.car.armed_sig = c.car.sig
def unstick(a):
"""The reading moves again and shows `a` A; the charger takes writes."""
def f(p, c):
p.ch.freeze(False)
p.ch.refuse = None
p.ch.set_current(a)
return f
def held(t0, t1):
"""The charger's read fails t0-t1 (under stale_input_s: held reads)."""
return {t0: lambda p, c: p.ch.go_unavailable(),
t1: lambda p, c: p.ch.go_unavailable(False)}
# =========================================================================== #
print("\n1. QA + QC: A STUCK READING AND THE LIFT (T14, T34, T35 (a))")
# =========================================================================== #
# The car's high import is short (960-1010) so the start rule's projection,
# with the start power counted while the car figure is untrusted, lifts the
# cap inside the stuck spell (from 1100).
ev14 = dict(held(1015, 1025))
ev14.update({1040: stick, 1600: unstick(9)})
ev14 = window(ev14, 959, None)
r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0), (1600, 4900.0)),
dur=1950, events=ev14)
w14 = writes(r, 900, 1950)
tr = refused(r, 900, 1300)
ts = [t for t, _a in tr]
heldw = [(t, a) for t, a, _ok, _w in writes(r, 1015, 1025)]
tl = t_lift(r, 1100, 1600)
stuck_from = first(x["t"] for x in rows(r, 1040) if x["stuck"])
check(f"T14: tries {tr}: 0 A at 960, at the first real read after the held "
f"reads 1015-1025, then 60 s on; none while held ({heldw})",
len(tr) == 3 and near(nth(ts, 0), 960, 1, 1)
and near(nth(ts, 1), 1025, 0, 2) and not heldw
and nth(ts, 2) - nth(ts, 1) >= 60 if len(tr) == 3 else False)
pre = [(t, a) for t, a, _ok, _w in writes(r, 1090, tl or 1e9)]
check(f"T14: stuck from {stuck_from}, the cap standing to {tl}: no 0 A from "
f"the stuck path while the tries are used up ({pre})",
present(stuck_from) and tl is not None and stuck_from < tl and not pre)
sw = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, 1600)]
hold = [(t, lv) for t, lv, _m in r["w"].lines(HOLD_TEXT)]
nodrop = [x["t"] for x in rows(r, (tl or 1e9), 1600)
if x["sent"] != 0.0 or x["taken"]]
cf = sorted({x["cut_fails"] for x in rows(r, (tl or 1e9), 1600)}, key=str)
check(f"T14 (QA b, QC 1): after the lift at {tl}, while stuck: the fault "
f"path's 0 A 3 times, 60 s apart, reason Solar, refused ({sw}); not "
f"cut tries (count {cf}); at the 3rd gave_up and the hold path's text "
f"once ({hold}); no drop while stuck ({nodrop[:3]})",
len(sw) == 3 and all(a == 0.0 and not ok and why == "Solar"
for _t, a, ok, why in sw)
and near(sw[0][0], tl or 0, 0, 2) and near(sw[1][0], sw[0][0], -58, 62)
and near(sw[2][0], sw[1][0], -58, 62) and cf == [3]
and len(hold) == 1 and near(hold[0][0], sw[2][0], 1, 1)
and hold[0][1] == "WARNING" and bool(gave_up_at(r, sw[2][0], 1600))
and not nodrop if len(sw) == 3 else False)
d14 = dropped(r, 1600, 9.0)
gu = [x["t"] for x in rows(r, d14 or 1e9, 1950) if x["gave_up"]]
pause = [(t, a, ok, why) for t, a, ok, why in writes(r, 1890, 1910)
if a == 0.0]
check(f"T14 (QA a): the first good reading 1600 shows 9 A: the drop at "
f"{d14} with sent_a 9 (not the frozen 10), taken, plan 9, gave_up "
f"cleared ({gu[:2]}); Solar resumes: the pause 0 A, Solar, taken, at "
f"1900+-2 ({pause})",
near(d14, 1600, 0, 2) and not gu and len(pause) == 1
and near(pause[0][0], 1900, 2, 2) and pause[0][2]
and pause[0][3] == "Solar")
never54("T14", r)
ev34 = window({1040: stick, 2400: unstick(9)}, 959, None)
r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0)), dur=2500, n=2,
events=ev34)
tl = t_lift(r, 1100, 2400)
sw = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, 2400)]
hold = [(t, lv) for t, lv, _m in r["w"].lines(HOLD_TEXT)]
gu = [x["t"] for x in rows(r, (nth(sw, 2)[0] if present(nth(sw, 2))
else 1e9) + 1, 2400) if not x["gave_up"]]
d34 = dropped(r, 2400, 9.0)
up = [(t, a, why) for t, a, ok, why in writes(r, 2401, 2500)
if a > 10.0 and ok]
check(f"T34 (QC 1): stuck 1040-2400, across the roll: after the lift at "
f"{tl} the stuck 0 A 3 times ({sw}), then gave_up and one hold-path "
f"WARNING ({hold}); nothing to 2400, also at the roll; gave_up stands "
f"({gu[:2]}); the drop at {d34} (2400+-2, the good reading 9 A); a "
f"step-up > 10 A, Solar, in [2430, 2460] ({up[:1]})",
len(sw) == 3 and len(hold) == 1 and not gu and near(d34, 2400, 0, 2)
and bool(up) and 2430 <= up[0][0] <= 2460 and up[0][1] <= 16.0
and up[0][2] == "Solar"
and not [x for x in rows(r, d34 or 0, 2500) if x["gave_up"]])
never54("T34", r)
st35 = {"lift": None, "prev": None}
def lift_watch(p, c, t):
"""T35 (a): 30 s after the lift the charger takes writes and its reading
follows again (the stuck verdict stands until it moves)."""
cap = (getattr(c, "_cut", None) or {}).get("cap")
if st35["lift"] is None and st35["prev"] is not None and cap is None \
and t > 1100:
st35["lift"] = t
st35["prev"] = cap
if st35["lift"] is not None and t == st35["lift"] + 29:
p.ch.refuse = None
p.ch.freeze(False)
r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0)), dur=1600,
events=window({1040: stick}, 959, None), on_cycle=lift_watch)
tl = st35["lift"]
sw = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, 1600)
if a == 0.0]
lines = [(t, m) for t, _lv, m in r["w"].lines("Car: set") if t >= 900
and " to 0 A" in m]
pk = [(t, m) for t, _lv, m in r["w"].lines("peak cut") if t >= (tl or 0)]
check(f"T35 (a) (QC 2): the stuck 0 A after the lift at {tl}: refused, then "
f"taken at the 2nd try ({sw}), reason Solar; one 'Car: set from 10 A "
f"to 0 A ... (Solar).' ({lines}); no 'peak cut' line after the lift "
f"({pk})",
len(sw) == 2 and not sw[0][2] and sw[1][2]
and all(why == "Solar" for _t, _a, _o, why in sw)
and [m for _t, m in lines]
== ["Car: set from 10 A to 0 A on 3 phases (Solar)."] and not pk
if len(sw) == 2 else False)
never54("T35 (a)", r)
# =========================================================================== #
print("\n2. G1: A NEW QUARTER'S CUT WAIT (T25)")
# =========================================================================== #
class GiveFrom(S.SunPlant):
"""The battery gives nothing until 1800, then what it is asked, slowly
(its 20 s response from 1790): headroom at the new quarter, not used
within its first seconds."""
def batt_of(self, u, at):
v = super().batt_of(u, at)
return min(v, 0.0) if at < 1800 else v
def free(p, c):
c.batt_refused = 0
for tag, car_sun, s in (("0 A", 5830.0, 0.0), ("6 A", 7900.0, 1900.0)):
a0 = 7.0 if tag == "0 A" else 10.0
ev = {t: refuse_n1 for t in range(0, 1795)}
for t in range(1795, 1830):
ev = merge(ev, t, free)
ev = window(merge(ev, 1790, set_resp(20.0)), 959, 1810)
r = run(house_c(h=900.0), step_fn((960, s), base=car_sun), dur=1900,
n=1, socs={"a": 60.0}, events=ev, plant_cls=GiveFrom,
rows=False)
tr = refused(r, 900, 1800)
d = dropped(r, 1800, a0)
wait = [x["t"] for x in rows(r, 1800, 1830) if x["wait"] is not None]
inwait = [(t, a) for t, a, _ok, _w in writes(r, 1800, 1830)
if t <= (wait[-1] if wait else 1e9)]
cw = [(t, a, ok, why) for t, a, ok, why, _k in cut_writes(r, 1800, 1830)]
c1 = nth(cw, 0)
rb = [x["t"] for x in rows(r, c1[0] if present(c1) else 1e9)
if present(c1) and abs(x["rb"] - c1[1]) < 0.01]
cuts = [t for t, n in r["raised"] if n == CUT and t >= 1800]
want = 0.0 if tag == "0 A" else 6.0
check(f"T25 [{tag}] (G1): 3 refused tries in 900-1800 ({tr}); the drop "
f"at {d} (1800+-2: sent_a {a0}, taken, plan {a0}); the wait "
f"{wait[:1]}..{wait[-1:]} with no write in it ({inwait}); then the "
f"cut try {c1} ({want} A, peak cut, taken) after the wait, read "
f"back by {rb[:1]}, CAR_CUT once ({cuts})",
len(tr) == 3 and near(d, 1800, 0, 2) and bool(wait)
and not inwait and present(c1) and c1[0] > wait[-1]
and c1[0] <= 1817 and c1[1] == want and c1[2]
and c1[3] == "peak cut" and bool(rb) and rb[0] <= c1[0] + 2
and len(cuts) == 1 if wait else False)
never54(f"T25 [{tag}]", r)
# =========================================================================== #
print("\n3. G2, G3: THE LIFT (T26, T27, T28) AND THE C4 REPLAY")
# =========================================================================== #
r = run(house_c((1250, 900.0)), sun_c((1250, 9000.0)), dur=2700,
events=window({}, 959, 1300))
tl = t_lift(r, 1100, 1800)
d = dropped(r, tl or 0, 10.0)
paused = [x["t"] for x in rows(r, tl or 1e9, (tl or 1e9) + 30)
if x["plan"] < 6.0 or x["plan_why"] == "paused"]
z = [(t, ok) for t, a, ok, _w in writes(r, 1081, 2700) if a == 0.0]
up = [(t, a, why) for t, a, ok, why in writes(r, (tl or 1e9) + 30,
(tl or 1e9) + 61) if a > 10.0]
nxt = first((t, a, why) for t, a, _ok, why in writes(r, 1081, 2700))
check(f"T26 (G2): the lift at {tl} (1370+-2): the drop {d} (plan 10, not "
f"paused {paused[:2]}, so '0 A first' does not clear its start count); "
f"no 0 A after the 3rd try ({z[:2]}); then the first write {nxt} is a "
f"step-up > 10 A, Solar, in [t_lift+30, t_lift+60] ({up[:1]})",
near(tl, 1370, 2, 2) and d is not None and not paused and not z
and bool(up) and up[0][1] <= 16.0 and up[0][2] == "Solar"
and present(nxt) and nxt == up[0])
never54("T26", r)
for tag, H in (("6 A", 12500.0), ("0 A", 16000.0)):
ev = {t: refuse_n1 for t in range(0, 2701)}
ev = window(ev, 1699, 1900)
# The period sits near the aim (EV-21's near_end): the house steps at
# 1700 for 5 s (100 s left, so the cut is at once), the cut stands;
# it lifts only at the period's end, with tries left.
house = step_fn((900, 3350.0), (1500, 900.0), (1700, H), (1705, 900.0),
base=900.0)
sun = step_fn((900, 0.0), (1500, 7900.0), (1700, 7000.0), base=7900.0)
r = run(house, sun, dur=2700, n=1, socs={"a": 60.0}, events=ev,
plant_cls=NoGive, rows=False)
want = 6.0 if tag == "6 A" else 0.0
tr = refused(r, 1690, 1800)
d = dropped(r, 1800, 10.0)
bad = [(t, a, why) for t, a, ok, why in writes(r, 1800, 2700)
if abs(a - want) < 0.01 or why == "peak cut"]
nxt = first(x for x in writes(r, 1800, 2700))
check(f"T27 [{tag}] (G3, tries left): {tr} refused ({want} A) before the "
f"period's end; the drop at {d} (1800+-2); no re-send of {want} A "
f"and no 'peak cut' write in [1800, 2700) ({bad[:3]}); the next "
f"write the plan's ({nxt})",
1 <= len(tr) <= 2 and all(a == want for _t, a in tr)
and near(d, 1800, 0, 2) and not bad
and (not present(nxt) or nxt[3] == "Solar"))
never54(f"T27 [{tag}]", r)
class Drv:
def __init__(self):
self.calls = []
async def write_current(self, a, **kw):
self.calls.append(a)
return False
class Trk:
obs_at = None
def begin_write(self):
pass
def end_write(self, *a):
pass
def note_write(self, *a, **k):
pass
def stuck(self, now):
return False
async def c4_replay():
w = carmode.SolarWriter()
w.engaged, w.sent_a, w.taken, w.last_a = True, 10.0, True, 10.0
drv, trk = Drv(), Trk()
w.cut_a, w.cut_on = 6.0, True
await w._put(drv, 6.0, 10.0, 1000.0, trk)
first_try = list(drv.calls)
w.cut_a, w.cut_on = None, False
await w._put(drv, 6.0, 10.0, 1070.0, trk)
return first_try, drv.calls[len(first_try):], w.sent_why
try:
c4 = asyncio.run(c4_replay())
except Exception as e: # noqa: BLE001
c4 = (None, ["raised " + repr(e)], None)
check(f"T27 (formal C4 replay): a 6 A cut refused once {c4[0]}; with no "
f"cut 70 s later `_put(6)` sends nothing ({c4[1]})",
c4[0] == [6.0] and c4[1] == [])
r = run(house_c((1250, 900.0)), sun_c((1250, 7950.0)), dur=2700,
events=window({}, 959, 1900))
tl = t_lift(r, 1100, 1800)
d = dropped(r, tl or 0, 10.0)
w28 = [(t, a) for t, a, _ok, _w in writes(r, 1081, 2700)]
check(f"T28 (G3, tries used up): the lift at {tl}: the drop {d}; no write "
f"at all in (1080, 2700) ({w28[:3]}), also not at the roll; gave_up "
f"never ({gave_up_at(r, 900)[:2]})",
near(tl, 1370, 2, 2) and d is not None and not w28
and not gave_up_at(r, 900))
never54("T28", r)
# =========================================================================== #
print("\n4. G4, G5, G6: A PARTIAL CUT (T29, T30, T32), A DEEPER CUT (T31)")
# =========================================================================== #
r = run(house_c((1250, 900.0), h=900.0), sun_c((1250, 9000.0), s=1900.0),
dur=1800, events=window({}, 959, 1100))
tr = refused(r, 900, 1800)
tl = t_lift(r, 1100, 1800)
d = dropped(r, tl or 0, 10.0)
six = [(t, a) for t, a, _ok, _w in writes(r, 1081, 1800) if a == 6.0]
up = [(t, a, why) for t, a, ok, why in writes(r, (tl or 1e9),
(tl or 1e9) + 61) if a > 10.0]
check(f"T29 (G4): 6 A refused 3 times ({tr}), no 4th; the lift at {tl}: the "
f"drop {d} (sent 10, plan 10); no 6 A after 1080 ({six}); a step-up "
f"> 10 A, Solar, within t_lift+60 ({up[:1]})",
[a for _t, a in tr] == [6.0, 6.0, 6.0] and near(tl, 1370, 2, 2)
and d is not None and not six and bool(up) and up[0][1] <= 16.0
and up[0][2] == "Solar")
never54("T29", r)
as_off("T29", r, twin(r), ALARMS, refused=(961, (tl or 1371) - 1))
pre = [(t, a) for t, a, _ok, _w in writes(r, 1081, (tl or 1e9) - 2)]
hi = [(x["t"], x["plan"]) for x in rows(r, 1081, tl or 1e9)
if x["plan"] > 6.0]
check(f"T32 (G6): the tries used up, the spare about 16 A from 1250, the cap "
f"to {tl}: no write in (1080, t_lift-2) ({pre}); the plan at most 6 A "
f"until the lift ({hi[:3]})", tl is not None and not pre and not hi)
for n in (1, 2):
for tag, s2 in (("6 A", 1900.0), ("under 6 A", 1200.0)):
r = run(house_c(h=900.0), sun_c((1800, s2), s=1900.0), dur=1900,
n=n, events=window({}, 959, 1790))
tr = refused(r, 900, 1795)
hold_s = r["c"].p1.averager.max_hold_s
kc = key_change(r, 1700, 1900)
c2 = first((t, a, ok) for t, a, ok, _w, _k in
cut_writes(r, 1800 - hold_s - 1))
lo = 1800 - (hold_s if n == 2 else 0) - 1
x2 = row(r, c2[0]) if present(c2) else None
cap2 = x2["cap"] if present(x2) and x2 is not None else None
rb = [x["t"] for x in rows(r, c2[0] if present(c2) else 1e9)
if present(c2) and abs(x["rb"] - c2[1]) < 0.01]
cuts = [t for t, nn in r["raised"] if nn == CUT and t >= 1790]
# The value is the new quarter's cut, or lower when Solar's own plan
# is lower (here its pause: the spare stayed under 6 A worth).
check(f"T30 [N={n}, {tag}] (G4): 3 refused tries of 6 A ({tr}); the "
f"new key ({kc}) tried in its first cycle ({c2}, bound "
f"[{lo}, 1801]) at or under the new quarter's sized cut "
f"({cap2} A), 0 A or 6 A and more, never 1-5 A, taken, read "
f"back by {rb[:1]}; CAR_CUT once ({cuts})",
[a for _t, a in tr] == [6.0, 6.0, 6.0] and present(c2)
and c2 is not None and lo <= c2[0] <= 1801
and cap2 is not None and c2[1] <= cap2 + 0.01
and (c2[1] == 0.0 or c2[1] >= 6.0) and c2[2] and bool(rb)
and rb[0] <= c2[0] + 2 and len(cuts) == 1)
never54(f"T30 [N={n}, {tag}]", r)
if n == 2 and tag == "6 A":
as_off("T30 [N=2, 6 A]", r, twin(r), ALARMS,
refused=(961, 1790))
r = run(house_c((1030, 3000.0), h=900.0), sun_c((1030, 0.0), s=1900.0),
dur=1950, events=window({}, 959, 1830))
tr = refused(r, 900, 1795)
check(f"T31 (G5): 6 A refused at 960 and 1020, the cut deepens at 1030: 0 A "
f"at once, refused, try 3 ({tr}); no 4th refused try in 900-1800; "
f"gave_up never ({gave_up_at(r, 900, 1800)[:2]})",
[a for _t, a in tr] == [6.0, 6.0, 0.0] and near(nth(tr, 2)[0]
if present(nth(tr, 2))
else None, 1030, 0, 2)
and not gave_up_at(r, 900, 1800))
hold_s = r["c"].p1.averager.max_hold_s
kc = key_change(r, 1700, 1900)
w2 = [(t, a, ok) for t, a, ok, _w, _k in cut_writes(r, 1800 - hold_s - 1)]
check(f"T31: the new key ({kc}) tried in its first cycle and refused, the "
f"next 60 s or more later taken ({w2[:2]})",
len(w2) >= 2 and not w2[0][2] and w2[1][2]
and w2[1][0] - w2[0][0] >= 60 and present(kc) and kc is not None
and abs(w2[0][0] - kc) <= 1)
never54("T31", r)
# =========================================================================== #
print("\n5. QB: NO READ-BACK AT THE LIFT (T33)")
# =========================================================================== #
def rb_none(on):
"""The charger answers, but neither its setpoint nor its read-back is a
number: `allowed_a` and `setpoint_a` are both None."""
def f(p, c):
ch = p.ch
if on:
orig = ch.states
def st():
d = dict(orig())
for k in list(d):
if k.endswith("_power_connector_max_current_socket_1") \
or k.endswith("_main_active_max_current_socket_1"):
d[k] = dict(d[k], state="-")
return d
ch._ev54_states = orig
ch.states = st
else:
ch.states = ch._ev54_states
return f
seen33 = []
def rd33(p, c, t):
rd = c.car.reading
if rd is not None and 1340 <= t < 1400:
seen33.append((rd.available, rd.allowed_a, rd.setpoint_a))
r = run(house_c((1250, 900.0)), sun_c((1250, 7950.0)), dur=2700,
events=window({1340: rb_none(True), 1400: rb_none(False)}, 959, 1900),
on_cycle=rd33)
tl = t_lift(r, 1100, 1800)
w33 = [(t, a) for t, a, _ok, _w in writes(r, 1081, 2700)]
nod = [x["t"] for x in rows(r, 1340, 1400) if x["sent"] != 0.0 or x["taken"]]
d = dropped(r, 1400, 10.0)
check(f"T33 (QB): the read-back unknown 1340-1400 ({sorted(set(seen33))}), "
f"the lift at {tl} inside it: no write ({w33[:3]}), no drop and "
f"sent_a 0 untaken, not None ({nod[:3]}); the drop at {d} (1400+-2) "
f"with 10 A; then no write to 2700",
sorted(set(seen33)) == [(True, None, None)] and present(tl)
and tl is not None and 1340 < tl < 1400 and not w33 and not nod
and near(d, 1400, 0, 2))
never54("T33", r)
# The variant: the charger away 1100-1400, the cap lifted while it is away
# (T14's short import spell, so the start rule's projection lifts it without
# a car figure).
ev = window({1100: lambda p, c: p.ch.go_unavailable(),
1400: lambda p, c: p.ch.go_unavailable(False)}, 959, 1900)
r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0)), dur=1500,
events=ev)
tl = t_lift(r, 1100, 1400)
away = [(t, a) for t, a, _ok, _w in writes(r, 1100, 1400)]
back = [(t, a, why) for t, a, _ok, why in writes(r, 1400, 1500)]
keys = [k for k in r["store"].data if "cut" in str(k).lower()]
check(f"T33 [charger away 1100-1400, the lift at {tl}]: nothing while away "
f"({away}); on return D2's 0 A as bdfd3e6 ({back[:1]}), not a re-send "
f"of the cut; no store key ({keys})",
present(tl) and tl is not None and 1100 < tl < 1400 and not away
and bool(back) and near(back[0][0], 1400, 0, 1) and back[0][1] == 0.0
and back[0][2] != "peak cut" and not keys)
never54("T33 [away]", r)
# =========================================================================== #
print("\n6. QC 2: THE WAY-OUT REASON WITH OFF (T35 (b), (c))")
# =========================================================================== #
r = run(house_c((1250, 900.0)), sun_c((1250, 9000.0)), dur=1500,
events=window({1400: act("car_mode", "off")}, 959, 1380))
wb = [(t, a, ok) for t, a, ok, _w in writes(r, 1395)]
lb = [m for t, _lv, m in r["w"].lines("Car: set") if t >= 1395]
whyb = [why for t, _a, _ok, why in writes(r, 1395)]
# bdfd3e6 writes nothing here: it is frozen with `gave_up` after the lift (C3)
# and Off does not clear it. After the drop the car's 10 A is Solar's, so Off
# writes EV-20's way-out 0 A once, at the press, as Solar's.
want = golden("T35 (b)", wb)
check(f"T35 (b): Off at 1400 after the lift: its way-out 0 A {wb} once at "
f"the press (bdfd3e6: {want}, frozen), reason Solar ({whyb}); one line "
f"({lb})",
wb == [(1400.0, 0.0, True)] and whyb == ["Solar"]
and lb == ["Car: set from 10 A to 0 A on 3 phases (Solar)."])
r = run(house_c(), sun_c(), dur=1200,
events=window({1000: act("car_mode", "off")}, 959, 999))
wc = [(t, a, ok) for t, a, ok, _w in writes(r, 995)]
lc = [m for t, _lv, m in r["w"].lines("Car: set") if t >= 995]
want = golden("T35 (c)", (wc, lc))
check(f"T35 (c): Off at 1000 while the cut stands: writes {wc} and lines "
f"{lc} as bdfd3e6's ({want})", (wc, lc) == want and bool(wc))
# =========================================================================== #
print("\n7. REVIEW ROUND 1: AWAY WHILE CAPPED (T36), F6 (T37), OFF (T38), "
"THE REASON (T39)")
# =========================================================================== #
# T36 (review r1, Major): the charger is away 1100-1200 and comes back while
# the cap stands with the quarter's 3 tries used up; then the lift. D2's 0 A
# is a cut try and stays held (ruling 3); the return does not give the
# quarter new tries; after the lift Solar's control resumes.
for tag, h, s in (("0 A", 3000.0, 0.0), ("6 A", 900.0, 1900.0)):
ev = window({1100: lambda p, c: p.ch.go_unavailable(),
1200: lambda p, c: p.ch.go_unavailable(False)}, 959, 1300)
r = run(house_c((1250, 900.0), h=h), sun_c((1250, 9000.0), s=s),
dur=2700, events=ev)
tr = refused(r, 900, 1100)
tl = t_lift(r, 1200, 1800)
held_w = [(t, a) for t, a, _ok, _w in writes(r, 1081, tl or 1e9)]
cf = sorted({x["cut_fails"] for x in rows(r, 1081, tl or 1e9)}, key=str)
nz = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9,
(tl or 1e9) + 61)
if a > 0.0]
check(f"T36 [{tag}] (review r1): 3 refused tries ({tr}); the charger away "
f"1100-1200 and back while capped: no D2 0 A or other write until "
f"the lift at {tl} ({held_w}); the quarter's cut count stays 3 "
f"across the return ({cf}); after the lift a Solar write within "
f"60 s ({nz[:1]})",
len(tr) == 3 and present(tl) and tl is not None and not held_w
and cf == [3] and bool(nz) and nz[0][2] and nz[0][3] == "Solar")
never54(f"T36 [{tag}]", r)
# T37 (review r1, F6): episode 1 is lifted by the start rule (60 s) after
# 2 refused tries (960, 1020); episode 2 is due at 1040, within 60 s of the
# last refusal, with one try left: that try waits to 1080.
r = run(house_c(), sun_c((961, 9000.0), (1040, 0.0)), dur=1300,
opts={"ev_start_min": 1}, events=window({}, 959, 1800))
tl = t_lift(r, 961, 1040)
due2 = first(x["t"] for x in rows(r, (tl or 1e9) + 1, 1100)
if x["cap"] is not None or x["wait"] is not None)
tr = [t for t, _a in refused(r, 900, 1300)]
early = [t for t, _a, _ok, _w in writes(r, due2 or 1e9, 1080)]
check(f"T37 (review r1, F6): episode 1 lifted at {tl} after tries {tr[:2]}; "
f"episode 2 due at {due2}: no try before 60 s after the last refusal "
f"({early}), then try 3 at {nth(tr, 2)} (>= 1080); none after",
present(tl) and tl is not None and present(due2) and due2 is not None
and due2 < 1080 and tr[:2] == [960.0, 1020.0] and not early
and len(tr) == 3 and tr[2] >= 1080 if len(tr) >= 2 else False)
never54("T37", r)
# T38 (review r1, the fails gate): Off after the quarter's 3 refused tries,
# the refused 0 A still owed: no way-out try, as bdfd3e6 (gave_up there).
r = run(house_c(), sun_c(), dur=1300,
events=window({1100: act("car_mode", "off")}, 959, None))
w38 = [(t, a, ok) for t, a, ok, _w in writes(r, 1081)]
want = golden("T38", w38)
check(f"T38 (review r1): Off at 1100 after 3 refused cut tries: Off's "
f"way-out writes {w38} as bdfd3e6's ({want})", w38 == want)
async def reason_replay():
"""T39: a refused 6 A cut, then the next quarter sizes 7 A (above the
refused value, under the 10 A read-back)."""
w = carmode.SolarWriter()
w.engaged, w.sent_a, w.taken, w.last_a = True, 10.0, True, 10.0
drv, trk = Drv(), Trk()
w.cut_quarter("q1")
w.cut_a, w.cut_on = 6.0, True
await w._put(drv, 6.0, 10.0, 1000.0, trk)
w.cut_quarter("q2")
w.cut_a = 7.0
await w._put(drv, 7.0, 10.0, 1070.0, trk)
return list(drv.calls), w.sent_why
try:
t39 = asyncio.run(reason_replay())
except Exception as e: # noqa: BLE001
t39 = (["raised " + repr(e)], None)
check(f"T39 (review r1): a new cut value above the refused one, under the "
f"read-back, goes out as 'peak cut' ({t39})",
t39[0] == [6.0, 7.0] and t39[1] == "peak cut")
# =========================================================================== #
print("\n8. REVIEW ROUND 2: `fails` COUNTS ONLY THE OWED VALUE (T40-T42)")
# =========================================================================== #
def away_run(h, s, refuse_end, away=True):
ev = {}
if away:
ev = {1100: lambda p, c: p.ch.go_unavailable(),
1200: lambda p, c: p.ch.go_unavailable(False)}
return run(house_c((1250, 900.0), h=h), sun_c((1250, 9000.0), s=s),
dur=1800, events=window(ev, 959, refuse_end))
def after_lift(r):
tl = t_lift(r, 1200, 1800)
w = [(t, a, ok) for t, a, ok, _w in writes(r, tl or 1e9, 1800)]
hold = [t for t, _lv, _m in r["w"].lines(HOLD_TEXT)]
gu = [x["t"] for x in rows(r, tl or 1e9, 1800) if x["gave_up"]]
cf = sorted({x["cut_fails"] for x in rows(r, 1081, tl or 1e9)}, key=str)
return tl, w, hold, gu, cf
# T40 (PM row a): the charger refuses to 1430: after the return Solar's own
# write gets its own tries; the 2nd, 60 s later, is taken.
for tag, h, s in (("0 A", 3000.0, 0.0), ("6 A", 900.0, 1900.0)):
r = away_run(h, s, 1430)
tl, w, hold, gu, cf = after_lift(r)
pre = [t for t, _a, _ok, _w in writes(r, 1081, tl or 1e9)]
tk = [t for t, _a, ok in w if ok]
check(f"T40 [{tag}] (review r2): away 1100-1200 while capped, refused to "
f"1430: nothing until the lift at {tl} ({pre}); then Solar tries "
f"{w[:3]}: the 1st refused, the 2nd 60 s later, a taken write by "
f"1462 ({tk[:1]}); no gave_up ({gu[:2]}) or hold text ({hold}); "
f"the quarter's cut count unchanged across the return ({cf})",
present(tl) and tl is not None and not pre and len(w) >= 2
and not w[0][2] and w[1][0] - w[0][0] >= 60 and bool(tk)
and tk[0] <= 1462 and not gu and not hold and cf == [3])
never54(f"T40 [{tag}]", r)
def ok41(res):
tl, w, hold, gu, cf = res
if not (len(w) == 3 and len(hold) == 1 and present(tl) and tl is not None
and bool(gu)):
return False
return (not any(ok for _t, _a, ok in w) and w[0][0] <= tl + 60
and all(b[0] - a[0] >= 60 for a, b in zip(w, w[1:]))
and abs(hold[0] - w[2][0]) <= 1 and gu[0] >= w[2][0] - 1
and cf == [3])
# T41 (PM row b): refused to 1600: Solar's own 3 tries 60 s apart, then
# gave_up and the hold text, as in the same run without the away.
for tag, h, s in (("0 A", 3000.0, 0.0), ("6 A", 900.0, 1900.0)):
ra = after_lift(away_run(h, s, 1600, away=True))
rn = after_lift(away_run(h, s, 1600, away=False))
check(f"T41 [{tag}] (review r2): refused to 1600: with the away {ra[1]}, "
f"gave_up from {ra[3][:1]}, hold text {ra[2]}; without it {rn[1]}, "
f"gave_up from {rn[3][:1]}, hold text {rn[2]}: 3 tries 60 s apart, "
f"then gave_up, in both", ok41(ra) and ok41(rn))
async def replaced_value():
"""T42 (PM row c): a refused 6 A cut, then the next quarter's 7 A (the
reachable path of T39) replaces it and is refused too: `fails` counts
only the owed 7 A."""
w = carmode.SolarWriter()
w.engaged, w.sent_a, w.taken, w.last_a = True, 10.0, True, 10.0
drv, trk = Drv(), Trk()
w.cut_quarter("q1")
w.cut_a, w.cut_on = 6.0, True
await w._put(drv, 6.0, 10.0, 1000.0, trk)
w.cut_quarter("q2")
w.cut_a = 7.0
await w._put(drv, 7.0, 10.0, 1070.0, trk)
return list(drv.calls), w.fails, w.cut_fails, w.refused_cut
try:
t42 = asyncio.run(replaced_value())
except Exception as e: # noqa: BLE001
t42 = (["raised " + repr(e)], None, None, None)
check(f"T42 (review r2): 6 A refused, then 7 A written in its place and "
f"refused (calls {t42[0]}): fails {t42[1]} counts only the owed 7 A "
f"(1), the new quarter's cut count {t42[2]} (1), owed {t42[3]}",
t42[0] == [6.0, 7.0] and t42[1] == 1 and t42[2] == 1
and t42[3] == 7.0)
tb_all = LOG.tracebacks(n_log0)
check(f"N13: no traceback in this file's runs ({tb_all[:1]})", not tb_all)
if TAKE:
print("(golden taken; no checks graded)")
sys.exit(0)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)
+335
View File
@@ -0,0 +1,335 @@
"""EV-54: shared pieces of the refused-cut checks (test_ev54*.py): the run
with a per-cycle writer recorder, refusal windows, the cut tries per quarter
key, the Off twin with Solar's charger replayed, and the Never checks of
reports/EV-54-test-plan.md every run carries.
The plant is EV-21's (`ev21_kit.drive` on `ev20_sun`): Shape C is N=2, both
batteries at 10 %, the car 10 A on 3 phases, the house 3000 W and the sun 0
from 960. Aim 3400 W; the second period runs 900-1800. Every value is read
through getattr or `named_absence`, so a tree without EV-54 grades FAIL,
never a crash."""
import os
import sys
_KIT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _KIT)
sys.path.insert(0, os.path.dirname(_KIT))
from app import carmode # noqa: E402
from ev20_kit import LOG, check, step_fn # noqa: E402,F401
from ev21_kit import drive, merge, Q, NoGive, refuse_n1 # noqa: E402,F401
from named_absence import first, nth, given, present # noqa: E402,F401
Q3_TEXT = ("The charger did not take the peak cut, so the add-on tries again "
"next quarter: CHARGER_REFUSED.")
HOLD_TEXT = ("The charger did not take the current, so the add-on stops "
"asking until you press Solar: CHARGER_REFUSED.")
RETRY_S = carmode.RETRY_S
TOL = 0.01
class W54:
"""Per cycle, after the cycle and its writer step: the cut state, the
writer's own state, the read-back and the log mark; and every current
write Solar made, with the reason it was sent with."""
def __init__(self):
self.rows = []
self.writes = [] # (t, a, ok, why)
self.n = 0
self.marks = [] # (t, log index after the cycle)
self.mark0 = LOG.mark()
def __call__(self, p, c, t):
w = c.car_solar
st = getattr(c, "_cut", None) or {}
for x in w.log[self.n:]:
if x[0] == "current":
self.writes.append((x[2], x[1], x[3],
getattr(w, "sent_why", None)))
self.n = len(w.log)
cc = getattr(c, "car_solar_can_cut", None)
g = c.peak_guard
self.rows.append(dict(
t=t, key=st.get("key"), cap=st.get("cap"), wait=st.get("wait"),
cuts=st.get("cuts"), under=st.get("under"),
cut_a=w.cut_a, sent=w.sent_a, taken=w.taken, gave_up=w.gave_up,
why=getattr(w, "sent_why", None), fails=w.fails,
cut_fails=getattr(w, "cut_fails", None), plan=w.plan.a,
plan_why=w.plan.why, ok_since=w.plan.ok_since,
set_at=w.plan.set_at, switch=w.plan.switch, seq=w.seq,
rb=p.ch.readback_a, sp=p.ch.setpoint_a, car=p.ch.power_w,
can=getattr(c, "_car_can", None),
can_now=bool(cc()) if cc else None, explains=c.car_explains,
floor=None if g is None else g.floor_w, mode=c.car_mode,
hold=w.hold, fault=w.fault, stuck=bool(c.car.stuck(t))))
self.marks.append((t, LOG.mark()))
def at(self, t):
return first(x for x in self.rows if x["t"] == t)
def lines(self, text=None, level=None):
"""(cycle second, level, message) of the log lines of this run."""
out, lo = [], self.mark0
for t, hi in self.marks:
for lv, m, _x in LOG.rec[lo:hi]:
if (text is None or text in m) and level in (None, lv):
out.append((t, lv, m))
lo = hi
return out
def refuse(kind="ignore"):
def f(p, c):
p.ch.refuse = kind
return f
def accept(p, c):
p.ch.refuse = None
def window(ev, t0, t1, kind="ignore"):
"""The charger refuses `kind` from t0 to t1 (None: to the end)."""
ev = merge(ev, int(t0), refuse(kind))
if t1 is not None:
ev = merge(ev, int(t1), accept)
return ev
def house_c(*more, h=3000.0):
"""Shape C's house: 900 W, `h` from 960, then the (t, W) pairs."""
return step_fn((960, h), *more, base=900.0)
def sun_c(*more, s=0.0):
"""Shape C's sun: 7900 W (the car's 10 A, the house and 100 W), `s`
from 960, then the (t, W) pairs."""
return step_fn((960, s), *more, base=7900.0)
def run(house=None, sun=None, *, dur, n=2, socs=None, events=None,
opts=None, mode="solar", setpoint=0, phases=3, **kw):
"""Shape C (N=2 both at 10 %, or N=1 `a` at 10 %) with `house` and `sun`,
Car first, the car on 3 phases. `out["w"]` is the W54 recorder. At N=1
without a `plant_cls`, the sole battery refuses to give (EV-21's N=1
rows: `refuse_n1` with the `NoGive` plant), so the cut stays needed."""
if n == 1 and "plant_cls" not in kw:
kw["plant_cls"] = NoGive
kw.setdefault("rows", False)
ev = dict(events or {})
for t in range(int(kw.get("t0", 0.0)), int(kw.get("t0", 0.0) + dur)):
ev = merge(ev, t, refuse_n1)
events = ev
ratings = {"a": 5000.0, "b": 4600.0} if n == 2 else {"a": 5000.0}
socs = dict(socs or {u: 10.0 for u in ratings})
rec = W54()
oc = kw.pop("on_cycle", None)
def on_cycle(p, c, t):
rec(p, c, t)
if callable(oc):
oc(p, c, t)
o = dict({"ev_phases": "3"}, **(opts or {}))
out = drive(house or house_c(), sun or sun_c(), dur=dur, first="car",
phases=phases, mode=mode, socs=socs, ratings=ratings, opts=o,
events=events, setpoint=setpoint, on_cycle=on_cycle, **kw)
out["w"] = rec
out["spec"] = dict(house=house or house_c(), sun=sun or sun_c(),
dur=dur, n=n, socs=socs, opts=opts, phases=phases,
kw=kw)
return out
# ------------------------------------------------------------- reading runs
def writes(r, t0=0, t1=1e9):
"""(t, a, ok, why) of every current write Solar made in [t0, t1)."""
return [x for x in r["w"].writes if t0 <= x[0] < t1]
def row(r, t):
return r["w"].at(t)
def rows(r, t0=0, t1=1e9):
return [x for x in r["w"].rows if t0 <= x["t"] < t1]
def cut_writes(r, t0=0, t1=1e9):
"""The writes made while a cut was due or stood (the cycle's cap or its
wait): the cut tries, (t, a, ok, why, key)."""
out = []
for t, a, ok, why in writes(r, t0, t1):
x = row(r, t)
if present(x) and (x["cap"] is not None or x["wait"] is not None):
out.append((t, a, ok, why, x["key"]))
return out
def refused_by_key(r, t0=0, t1=1e9):
"""{quarter key: [t, ...]} of the refused cut tries."""
out = {}
for t, _a, ok, _why, key in cut_writes(r, t0, t1):
if not ok:
out.setdefault(key, []).append(t)
return out
def key_change(r, t0, t1):
"""The first cycle in [t0, t1) whose quarter key differs from the one
before it."""
prev = None
for x in r["w"].rows:
if x["t"] >= t0 and x["t"] < t1 and prev is not None \
and x["key"] is not None and x["key"] != prev:
return x["t"]
if x["key"] is not None:
prev = x["key"]
return None
def t_lift(r, t0, t1):
"""The cycle the cap was lifted in [t0, t1): a cap, then none."""
prev = None
for x in r["w"].rows:
if t0 <= x["t"] < t1 and prev is not None and x["cap"] is None:
return x["t"]
prev = x["cap"] if t0 <= x["t"] else None
return None
def dropped(r, t, a, slack=2):
"""The drop by `t` (+-slack): `sent_a` = `a` (the read-back), taken, the
plan's current `a`. Returns the first cycle that shows it, or None."""
for x in rows(r, t - slack, t + slack + 1):
if x["sent"] is not None and abs(x["sent"] - a) <= TOL and x["taken"] \
and abs(x["plan"] - a) <= TOL:
return x["t"]
return None
def same_gaps(r, t0=0, t1=1e9):
"""N2: two tries of the same value less than RETRY_S apart (the list of
offending pairs), refused tries and their retries."""
w = [(t, a) for t, a, ok, _why in writes(r, t0, t1)]
bad = []
for i, (ta, aa) in enumerate(w):
for tb, ab in w[i + 1:]:
if abs(aa - ab) <= TOL and tb - ta < RETRY_S - 1e-9:
prev_ok = [ok for t, a, ok, _w in writes(r, ta, ta + 1)
if abs(a - aa) <= TOL]
if prev_ok and not prev_ok[0]:
bad.append((ta, tb, aa))
break
return bad
def never54(name, r, *, clamp=16.0, max_q=3, peak_free=True):
"""N1 (at most 3 refused cut tries per quarter key), N2 (the same value
not twice within RETRY_S after a refusal), N3 (no write between 0 and
6 A), N4 (none above the clamp), N6 (no non-zero write above a standing
cap), N12 (`gave_up` never set by a cut try; no "until you press Solar"
while a cut is due or stands), N13 (no Traceback), N16 (no "peak cut"
write while no cut is due or stands)."""
rbk = refused_by_key(r)
bad1 = {k: v for k, v in rbk.items() if len(v) > max_q}
check(f"{name}: N1 at most {max_q} refused cut tries per quarter key "
f"({bad1})", not bad1)
bad2 = same_gaps(r)
check(f"{name}: N2 no retry of a refused value within {RETRY_S:.0f} s "
f"({bad2[:3]})", not bad2)
w = writes(r)
bad3 = [(t, a) for t, a, _ok, _why in w if 0.0 + TOL < a < 6.0 - TOL]
bad4 = [(t, a) for t, a, _ok, _why in w if a > clamp + TOL]
check(f"{name}: N3 no write between 0 and 6 A ({bad3[:3]}); N4 none above "
f"the clamp ({bad4[:3]})", not bad3 and not bad4)
bad6 = []
for t, a, _ok, _why in w:
x = row(r, t)
if a > TOL and present(x) and x["cap"] is not None \
and a > x["cap"] + TOL:
bad6.append((t, a, x["cap"]))
check(f"{name}: N6 no non-zero write above a standing cut ({bad6[:3]})",
not bad6)
hi = r["w"].marks[-1][1] if r["w"].marks else r["w"].mark0
tb = [m for _lv, m, x in LOG.rec[r["w"].mark0:hi] if x]
check(f"{name}: N13 no Traceback ({tb[:1]})", not tb)
if peak_free:
bad16 = []
for t, a, _ok, why in w:
x = row(r, t)
if why == "peak cut" and present(x) and x["cap"] is None \
and x["wait"] is None:
bad16.append((t, a))
for t, _lv, m in r["w"].lines("(peak cut)"):
x = row(r, t)
if present(x) and x["cap"] is None and x["wait"] is None:
bad16.append((t, m))
check(f"{name}: N16 no 'peak cut' write or line while no cut is due "
f"or stands ({bad16[:3]})", not bad16)
# ------------------------------------------------------------- the Off twin
def twin(r, extra_events=None):
"""The run of `r` in Off: the same house, sun and batteries, and the
charger moved at the same seconds as Solar's taken writes moved it, so
the car is the same and only the mode differs."""
sp = r["spec"]
ev = dict(extra_events or {})
prev = None
for x in r["trace"]:
if prev is not None and abs(x["sp"] - prev) > TOL:
def put(p, c, v=x["sp"]):
p.ch.set_current(v)
ev = merge(ev, int(x["t"]) + 1, put)
prev = x["sp"]
kw = dict(sp["kw"])
return run(sp["house"], sp["sun"], dur=sp["dur"], n=sp["n"],
socs=sp["socs"], opts=sp["opts"], mode="off", setpoint=0,
phases=sp["phases"], events=ev, **kw)
def alarms_by_q(r, ids):
out = {}
for t, n in r["raised"]:
if n in ids:
q0 = int(t) // Q * Q
out.setdefault(q0, t)
return out
def as_off(name, r, o, ids, *, t0=900, refused=None):
"""T7 / N5: the run `r` against its Off twin `o`. Before the read-back
shows the cut, `car_explains` is never True; the first alarm of every
quarter at the twin's second +2; `car_peak_q` as the twin's; the guard's
floor within 50 W of the twin's while the cut is refused (`refused`:
the (t0, t1) of that); `car_solar_can_cut()` False while the read-back
is above `sent_a`."""
# Graded out only in the cut's own cycle (nothing written yet: EV-21
# T30); from the cycle after its write, as Off until the read-back.
t_ex = refused[0] if refused is not None else t0
bad_ex = [x["t"] for x in rows(r, t_ex) if x["explains"] and x["sent"]
is not None and x["rb"] > x["sent"] + TOL]
a_r, a_o = alarms_by_q(r, ids), alarms_by_q(o, ids)
qs = sorted(set(a_r) | set(a_o))
bad_a = [(q, a_r.get(q), a_o.get(q)) for q in qs if q >= t0 and (
a_r.get(q) is None or a_o.get(q) is None
or abs(a_r[q] - a_o[q]) > 2)]
bad_f = []
if refused is not None:
fo = {x["t"]: x["floor"] for x in o["w"].rows}
for x in rows(r, refused[0], refused[1]):
y = fo.get(x["t"])
if abs((x["floor"] or 0.0) - (y or 0.0)) > 50.0:
bad_f.append((x["t"], x["floor"], y))
bad_c = [x["t"] for x in rows(r, t0) if x["can_now"] and x["sent"]
is not None and x["rb"] > x["sent"] + TOL]
check(f"{name}: T7 as Off: car_explains never True before the read-back "
f"shows the cut ({bad_ex[:3]}); each quarter's first alarm at the "
f"twin's second +2 ({bad_a[:3]}); car_peak_q as the twin's "
f"({r['c'].car_peak_q} vs {o['c'].car_peak_q}); floor within 50 W "
f"while refused ({bad_f[:3]}); can-cut False while the read-back is "
f"above sent_a ({bad_c[:3]})",
not bad_ex and not bad_a and not bad_f and not bad_c
and r["c"].car_peak_q == o["c"].car_peak_q)