Files
Claude 226e5a1e8b
checks / unit (pull_request) Successful in 57m6s
infra-pin / fresh (pull_request) Successful in 3s
EV-20: Car Solar mode, spare sun to the car (charging only)
Solar as a second writer next to Manual (carmode.SolarPlan, SolarWriter on
ManualWriter's one write site, safe phase sequence and other-writer watch):
signed spare, Batteries first on the batteries' ratings, the margin, whole
amps rounded down, the 30 s / 1 A rule, start and pause dwells, auto phases,
a one-phase car. Every way out ends at 0 A, retried by EV-04's rule; at
shutdown before the inverters, three tries inside 15 s (D3); start-up and a
returning charger or HA write 0 A first (D2); never over another writer's
hold. The peak guard treats a Solar car as a Manual car (D1 wording). Solar
kWh sensor and card line; select.goodwe_car_sun_first; ev_margin_w,
ev_start_min, ev_pause_min with config, validator, translations, DOCS,
DECISIONS and CHANGELOG.

Checks: test_ev20.py, test_ev20_exits.py, test_ev20_writers.py,
test_ev20_guard.py, test_ev20_long.py, test_ev20_long_car.py,
test_ev20_fuzz.py (harness tools/ev20_sun.py, ev20_kit.py, ev20_day.py);
test_ev03/test_ev04 no longer use Solar as the refused example.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-22 20:31:26 +01:00

252 lines
6.6 KiB
Python

"""EV-20: shared pieces of the Solar checks (test_ev20*.py): the Std run,
the write logs, a charger model with refusals in time windows, the Never
checks every run can carry, and the shutdown and fault shapes.
Each check file imports `check`, `fails` and `LOG` from here and is its own
process, so they are its own."""
import asyncio
import logging
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, main as app_main # noqa: E402
import ev20_sun as S # noqa: E402
from chargersim import SimCharger # noqa: E402
fails = []
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
class _Log(logging.Handler):
def __init__(self):
super().__init__(logging.DEBUG)
self.rec = []
def emit(self, r):
self.rec.append((r.levelname, r.getMessage(), bool(r.exc_info)))
def mark(self):
return len(self.rec)
def since(self, n, level=None):
return [m for lv, m, _x in self.rec[n:] if level in (None, lv)]
def tracebacks(self, n=0):
return [m for lv, m, x in self.rec[n:] if x]
LOG = _Log()
_g = logging.getLogger("goodwe")
_g.addHandler(LOG)
_g.setLevel(logging.DEBUG)
_g.propagate = False
FULL = {"a": 100.0, "b": 100.0}
SET = S.SET
def const(w):
return S.const(w)
def step_fn(*pairs, base=0.0):
"""A function of t: `base`, then each (from_t, value) in order. The meter
is sampled 0.3 s before each cycle, so a change "at t0" is the cycle of
t0's."""
def f(t):
v = base
for t0, x in pairs:
if t >= t0 - 0.5:
v = x
return float(v)
return f
def at_s(t):
"""The cycle second a meter sample at `t` belongs to."""
return int(round(t))
def std(dur, *, sun=None, house=None, events=None, race=False, sim=None,
first="car", socs=None, **kw):
return S.drive(house or const(500.0), sun or const(2900.0), dur=dur,
first=first, socs=socs or dict(FULL), events=events,
race=race, sim=sim, **kw)
def cur_writes(r):
"""(cycle second, amps, ok) of every current write Solar made."""
return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log
if x[0] == "current"]
def attempts(r):
"""(second, amps) of every current write that reached Home Assistant,
refused ones included."""
return [(t, v) for t, e, v in r["plant"].sets if e == SET]
def selects(r):
return [x for x in r["sim"].log if x[1] == "phases"]
def act(what, value, out=None, key=None):
async def f(p, c):
res = await c.handle_action(what, value=value)
if out is not None:
out[key or what] = res
return f
def mqtt_cmd(topic, payload, retained=False):
async def f(p, c):
await c.mqtt_command(topic, payload, retained)
return f
def both(*fns):
async def f(p, c):
for fn in fns:
x = fn(p, c)
if asyncio.iscoroutine(x):
await x
return f
class TSim(SimCharger):
"""The model with refusals in time windows of its own clock: (t0, t1,
"error" | "ignore")."""
def __init__(self, *a, windows=(), **kw):
super().__init__(*a, **kw)
self.windows = list(windows)
def _mode(self):
for t0, t1, kind in self.windows:
if t0 <= self.t <= t1:
return kind
return None
def request_current(self, a):
keep, self.refuse = self.refuse, self._mode() or self.refuse
try:
return super().request_current(a)
finally:
self.refuse = keep
def nevers(r, tag, *, clamp=16.0, gap=600.0):
"""N1, N2, N5 and N13 over one run: no write above the clamp and no
clamp fault; a select only at 0 A with the car under 100 W, one per 600 s;
no two non-zero decisions under 30 s apart or under 1 A apart; no
Traceback."""
bad = []
sim, c = r["sim"], r["c"]
if c.charger.clamp_faults:
bad.append(("N1 clamp fault", c.charger.clamp_faults))
for t, what, v, power, sp in sim.log:
if what == "current" and v > clamp + 1e-9:
bad.append(("N1 over the clamp", t, v))
last = None
for t, what, v, power, sp in sim.log:
if what != "phases":
continue
if sp > 0.0 or power >= carmode.QUIET_W:
bad.append(("N2 select under load", t, sp, power))
if last is not None and t - last < gap:
bad.append(("N2 two selects", last, t))
last = t
prev = None
for t, a, ok in cur_writes(r):
if a <= 0.0:
continue
if prev is not None and a != prev[1]:
if t - prev[0] < carmode.SOLAR_WRITE_S - 1e-9:
bad.append(("N5 under 30 s", prev, (t, a)))
if abs(a - prev[1]) < carmode.SOLAR_STEP_A:
bad.append(("N5 under 1 A", prev, (t, a)))
if prev is None or a != prev[1]:
prev = (t, a)
if LOG.tracebacks(r.get("_log", 0)):
bad.append(("N13 Traceback", LOG.tracebacks(r.get("_log", 0))[:1]))
check(f"{tag}: N1, N2, N5, N13 hold ({bad[:2]})", not bad)
return bad
def run(tag, fn, *a, **kw):
n = LOG.mark()
r = fn(*a, **kw)
r["_log"] = n
return r
def sets_order(r):
return [(t, e, v) for t, e, v in r["plant"].sets]
async def _shutdown(p, c):
await c.shutdown()
def _until(r, t0):
"""Seconds from `t0` to the first inverter 0 W at shutdown."""
z = [t for t, e, v in r["plant"].sets
if e.startswith("number.sp_") and t >= t0 and v == 0.0]
return (z[0] - t0) if z else None
def _err(p, c):
p.ch.error = "12: Socket error"
p.ch.fault("E")
async def _dies(p, c):
async def boom():
raise RuntimeError("control died")
stop, died = asyncio.Event(), []
task = asyncio.ensure_future(boom())
await asyncio.gather(task, return_exceptions=True)
app_main.control_task_done(task, controller=c, stop=stop, died=died)
p.died = (stop.is_set(), len(died))
await c.shutdown()
def _freeze_after_write(p, c):
p.ch.freeze()
class HangPlant(S.SunPlant):
"""Home Assistant that never answers a charger write."""
hang = False
async def set_number(self, e, v):
if e == SET and self.hang:
await asyncio.sleep(3600)
return await super().set_number(e, v)
def report():
print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}")
for f in fails:
print(" FAIL:", f)
sys.exit(1 if fails else 0)