EV-52: log one plain line for a new car current and a car mode change #279

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