From 68856bc3a041513f7bbf20c107a99a837be0b113 Mon Sep 17 00:00:00 2001 From: ems-agent Date: Tue, 24 Nov 2026 17:11:44 +0100 Subject: [PATCH] EV-51: Solar decides every meter-age rule on the writer step's own age; DEBUG line per step The writer step took the meter age from the snapshot of the previous cycle (silent / unknown_s / hold), so in production order the silent-meter pause came one cycle late (C21) and a start or raise could still be written at an own age of 31-39 s (C22, N8). The step now judges its own age: the pause timing and held_pause, the non-zero write block (nz_block), and the late-readings hold with its stale rule. Meter values stay from the snapshot; car.held / car.reading and the arrival sources' spare-unknown check are unchanged. Also: one DEBUG line per Solar writer step (time, meter age, decision, write); tools/ev20_sun.drive takes cyc / phase / jitter / cset (default unchanged); test_ev51.py (T1-T43, N1-N12); DECISIONS states the rule once. Co-Authored-By: Claude Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w --- .../DECISIONS/EV-20-solar-mode.md | 18 +- goodwe_controller/app/carmode.py | 18 +- goodwe_controller/app/ctl_car.py | 67 +- goodwe_controller/app/ctl_cycle.py | 1 + goodwe_controller/test_ev51.py | 872 ++++++++++++++++++ goodwe_controller/tools/ev20_sun.py | 47 +- 6 files changed, 1012 insertions(+), 11 deletions(-) create mode 100644 goodwe_controller/test_ev51.py diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 044b62c..4baec40 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -161,9 +161,21 @@ one small set of facts and derives every path from them: This also ends the false PEAK_GUARD_FLOOR_LIMITED after one gap (EV-18 T10(b) changed accordingly). - **Silent meter on `ha_signed`:** Solar's unknown-sun pause is timed from the - meter's age: unknown since the age passed `meter_max_age_s`, so 0 A when the - age reaches `meter_max_age_s` + `ev_pause_min` (330 s), checked every - control cycle (bound 330 s + one cycle). Arrival sources are unchanged. + meter's age: unknown since the age passed `meter_max_age_s`, so 0 A on the + first car step whose own meter age (now minus the last reading, at that + step) is >= `meter_max_age_s` + `ev_pause_min` (330 s), held steps included. + Arrival sources are unchanged. +- **EV-51: decided at the step's own meter age.** Every decision that rests on + the meter's AGE is taken at the writer step's own age, not at the age the + cycle saw one step earlier: the pause above, the write block while the meter + is silent (no non-zero current, C17), the held-read pause (C18) and the + late-readings hold with its stale rule (a spare read while the hold was on + is not used once the step's own late time reaches `stale_input_s`). The + meter's VALUES (spare, target) stay the cycle's, one cycle of sensor latency + being normal; `car.held` and `car.reading` are unchanged. Arrival sources + keep the cycle's age for their "spare unknown" check. At log level debug + each Solar step logs one line: time, the meter age at the step, the decision + and the write. - **No non-zero write while the meter is silent (SPIKE-06 C17, N8 strict):** while the meter's age is past `meter_max_age_s`, Solar sends no non-zero current: no retry, no raise, no phase change begun, and a phase change diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 410dcb1..bf12a17 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -498,8 +498,13 @@ class SunInputs: def __init__(self, target_w=None, hold=False, auto=True, start_s=120.0, pause_s=300.0, spare_w=None, room_w=0.0, margin_w=100.0, - first=DEFAULT_FIRST, unknown_s=0.0, silent=False): + first=DEFAULT_FIRST, unknown_s=0.0, silent=False, + meter_back=False, age_s=None): self.target_w, self.hold, self.auto = target_w, hold, auto + # EV-51: the meter's own age at the writer step (None: no reading), and + # `meter_back`: the cycle's snapshot said "meter too old" but the step's + # own age says a new reading came, so no unknown timer is carried over. + self.meter_back, self.age_s = meter_back, age_s # EV-20 rig round 2: how long the sun has already been unknown when # the cause is the meter's own age (`ha_signed`): the pause is timed # from that age, not from the cycle that noticed it. @@ -570,11 +575,15 @@ class SolarPlan: self.switch, self._before = False, None def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s, - hold=False, gap_ok=True, unknown_s=0.0): + hold=False, gap_ok=True, unknown_s=0.0, meter_back=False): """`n_now`: the phases the car draws on now (1 for a one-phase car); `auto`: Solar may choose the phases; `gap_ok`: a phase change is allowed now (EV-04's one per `PHASE_GAP_S`); `hold`: readings late - under the stale bound, everything stands.""" + under the stale bound, everything stands. `meter_back` (EV-51): the + meter's own age is fresh again at this step: the unknown timer that + counted its silence starts over.""" + if meter_back: + self.unknown_since = None if hold: # Readings late under the stale bound: nothing changes, but a # hold or an unknown spare that has run its time still pauses @@ -937,7 +946,8 @@ class SolarWriter(ManualWriter): now, target_w=sun.target_w, hold=sun.hold, n_now=n_now, auto=sun.auto and not self.single and not self.phases_gave_up, clamp=clamp, start_s=sun.start_s, pause_s=sun.pause_s, - gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0)) + gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0), + meter_back=getattr(sun, "meter_back", False)) @staticmethod def _drawing(r) -> bool: diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 6796016..120a8dd 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -10,6 +10,7 @@ the guard treats a Solar car exactly as a Manual car). """ import asyncio +import copy import dataclasses import logging from datetime import timezone @@ -83,6 +84,7 @@ class CarMixin: self.car_first = first if first in carmode.FIRSTS \ else carmode.DEFAULT_FIRST self._car_late_s = None # EV-20: the cycle's late verdict + self._car_late_mono = None # ... and the time it was read (EV-51) self._car_sun_now = None # ... and Solar's inputs of that cycle sun = data.get(CAR_SUN_KEY) self.car_sun = {"day": None, "kwh": 0.0} @@ -372,8 +374,69 @@ class CarMixin: now = self.car_now() sun = None if self.car_mode == carmode.SOLAR: - sun = getattr(self, "_car_sun_now", None) \ - or self.car_sun_inputs(now) + sun = self.car_sun_own(getattr(self, "_car_sun_now", None) + or self.car_sun_inputs(now), now) + w0 = self.car_solar + a0, n_log = w0.plan.a, len(w0.log) + await self._car_step_run(held, now, sun) + if sun is not None and _LOG.isEnabledFor(logging.DEBUG): + self._car_step_debug(held, now, sun, a0, n_log) + + def _car_step_debug(self, held, now, sun, a0, n_log) -> None: + """EV-51: one DEBUG line per Solar writer step: the time, the meter's + age at the step, what was decided and what was written. Nothing at + info and above; no secrets in it.""" + w = self.car_solar + a1 = w.plan.a + if a0 > 0.0 and a1 <= 0.0: + what = "pause" + elif held: + what = "wait-held" + elif sun.hold: + what = "hold" + elif a0 <= 0.0 and a1 > 0.0: + what = "start" + elif a1 > a0 + carmode.TOL_A: + what = "raise" + elif a1 < a0 - carmode.TOL_A: + what = "lower" + elif sun.target_w is None: + what = "wait-unknown" + else: + what = "steady" + sent = [] + for kind, v, _t, ok in w.log[n_log:]: + if kind == "current": + sent.append(f"sent {v:g} A" + (" confirmed" if ok else "")) + else: + sent.append(f"phases {v}" + (" confirmed" if ok else "")) + age = sun.age_s + _LOG.debug("Solar step: t=%.1f age=%s decision=%s write=%s", now, + "none" if age is None else f"{age:.1f}", what, + "; ".join(sent) or "none") + + def car_sun_own(self, snap, now): + """EV-51 (PM): every decision on the meter's AGE is taken at the writer + step's own age (now minus the meter's last reading), not the age the + cycle saw one step earlier: the write block while the meter is silent + (N8), the unknown/pause timing (held reads too) and the late-readings + hold with its stale rule. The meter's VALUES (spare, target) stay the + cycle's; arrival sources' `car_spare_w` keeps the cycle's age.""" + own = copy.copy(snap) + own.silent = self._car_meter_silent() + own.unknown_s = self._car_meter_over_s() + own.age_s = self.p1.age_s() if self.p1_enabled else None + own.meter_back = snap.unknown_s > 0.0 and own.unknown_s <= 0.0 + stale = float(self.o.get("stale_input_s", 15)) + late = self._car_late_s # the verdict stands: it has aged since + if late is not None and self._car_late_mono is not None: + late += max(0.0, now - self._car_late_mono) + own.hold = late is not None and late < stale + if late is not None and late >= stale: + own.spare_w = own.target_w = None # the stale rule, on own late + return own + + async def _car_step_run(self, held, now, sun) -> None: if held: # EV-20 rig round 2 (PM): the charger missed a read for less than # `stale_input_s`; the last trusted figure stands and nothing is diff --git a/goodwe_controller/app/ctl_cycle.py b/goodwe_controller/app/ctl_cycle.py index 59dd444..9a638dd 100644 --- a/goodwe_controller/app/ctl_cycle.py +++ b/goodwe_controller/app/ctl_cycle.py @@ -254,6 +254,7 @@ class CycleMixin: stale_after = float(self.o.get("stale_input_s", 15)) late_s = self._readings_late(site_standing) # SAFETY-128 self._car_late_s = late_s # EV-20: Solar holds, then the stale rule + self._car_late_mono = self._now_mono # EV-51: when that verdict was read self._late_zero = late_s is not None and late_s >= stale_after # ⚠️ `any`, NOT the sole unit's. The hold exists so a single missed # poll does not become a fault; a LATCHED inverter must still reach the diff --git a/goodwe_controller/test_ev51.py b/goodwe_controller/test_ev51.py new file mode 100644 index 0000000..2c3759c --- /dev/null +++ b/goodwe_controller/test_ev51.py @@ -0,0 +1,872 @@ +"""EV-51: every meter-age decision of a Solar writer step is judged on the +step's OWN age (T1-T43; N1-N12 of reports/EV-51-test-plan.md). +`python3 -B test_ev51.py` + +The real Controller on `tools/ev20_sun.py` (the harness now takes a cycle +length, phase, jitter and the production order). "Plain" order: the cycle, +then the writer settles. "Race" order (`race=True`): the production order, the +writer step of a cycle runs beside the NEXT read, so its snapshot is one cycle +old. "Own age" = now minus the meter's last-reading stamp, taken in the writer +step (recorded here by wrapping `Controller.car_step`). + +Shared setup: `ha_signed`, `meter_max_age_s` 30, `ev_pause_min` 5 (bound 330 s), +Car first, both batteries full, house 500 W, sun 2900 W, 1 phase, the car at +10 A from 120 s, the meter silent from t = 300. The last sample before the +silence is ingested at 298.7 (the event runs before that second's submit): the +test takes ages from the steps, not from a constant. + +DEBUG format (T28): one line per Solar writer step, held steps included, + Solar step: t=630.0 age=331.3 decision=pause write=sent 0 A confirmed +decision: steady, wait-unknown, hold, start, raise, lower, pause, wait-held; +write: none, or "sent X A" (a refused try) / "sent X A confirmed", joined by "; ". + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import dataclasses +import logging +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode # noqa: E402 +from app.carmode import SolarPlan # noqa: E402 +from app.main import Controller # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from ev20_kit import * # noqa: E402,F401,F403 +from ev20_kit import LOG, check, fails, report # noqa: E402,F401 +from ev20_kit import TSim, cur_writes, selects # noqa: E402,F401 +from named_absence import nth, present # noqa: E402,F401 + +GOOGLE = logging.getLogger("goodwe") +STEPS = [] +SNAP = {} +_orig_step = Controller.car_step +_orig_kick = Controller.car_kick + + +async def _rec_step(self): + """Records every writer step: its own age (taken before it runs), the + snapshot's, whether the read was held and the current writes it made.""" + w = self.car_solar + snap = getattr(self, "_car_sun_now", None) + age = self.p1.age_s() if self.p1_enabled else None + held = bool(self.car.held) + a0, n0 = w.plan.a, len(w.log) + solar = self.car_mode == carmode.SOLAR + now = self.car_now() + await _orig_step(self) + STEPS.append(dict( + now=now, age=age, held=held, a0=a0, a1=w.plan.a, solar=solar, + snap_age=SNAP.get(id(snap), (None, None))[1], + snap_sil=None if snap is None else snap.silent, + snap_tgt=None if snap is None else snap.target_w, + snap_hold=None if snap is None else snap.hold, + writes=[(x[1], x[2], x[3]) for x in w.log[n0:] if x[0] == "current"], + phases=[x for x in w.log[n0:] if x[0] == "phases"])) + + +def _rec_kick(self): + _orig_kick(self) + sun = getattr(self, "_car_sun_now", None) + if sun is not None: + SNAP[id(sun)] = (sun, self.p1.age_s() if self.p1_enabled else None) + + +Controller.car_step = _rec_step +Controller.car_kick = _rec_kick + +SIL = 300 +FULLB = dict(FULL) +OPT1 = {"ev_phases": "1"} + + +def go(onset=SIL, dur=760, *, sun=2900.0, house=500.0, events=None, opts=None, + first="car", **kw): + """The shared setup: the meter off from `onset`, plain unless race=True. + Returns (run, steps).""" + STEPS.clear() + SNAP.clear() + ev = {} if onset is None else { + onset: lambda p, c: setattr(p, "meter_on", False)} + ev.update(events or {}) + r = S.drive(house if callable(house) else S.const(house), + sun if callable(sun) else S.const(sun), dur=dur, first=first, + socs=dict(FULLB), opts=dict(OPT1, **(opts or {})), events=ev, + **kw) + return r, list(STEPS) + + +def cyc_t(t0, cyc, phase, after): + """The first cycle second at or after `after`.""" + t = t0 + phase + while t < after: + t += cyc + return t + + +def pause_step(steps, bound=330.0, since=SIL): + """(S, previous): S = the first Solar step with own age >= bound.""" + ss = [s for s in steps if s["solar"] and s["age"] is not None + and s["now"] > since] + for i, s in enumerate(ss): + if s["age"] >= bound: + return s, (ss[i - 1] if i else None) + return None, None + + +def timing(steps, bound=330.0, exp_age=None, since=SIL): + """Pass: the plan's current goes from > 0 to 0 in the first step S with + own age >= bound; the step before has age < bound; the 0 A is sent in S + (N2, N7).""" + s, prev = pause_step(steps, bound, since) + if s is None or prev is None: + return False + ok = (s["a0"] > 0.0 and s["a1"] == 0.0 + and any(a == 0.0 for a, _t, _o in s["writes"]) and prev["age"] < bound) + if exp_age is not None: + ok = ok and abs(s["age"] - exp_age) < 0.05 + return ok + + +def n8(steps, limit=30.0): + """N8: non-zero current writes at a step whose own age is > limit.""" + return [(round(s["now"], 1), round(s["age"], 1), a) for s in steps + if s["age"] is not None and s["age"] > limit + for a, _t, _o in s["writes"] if a > 0.0] + + +def common(tag, r, steps, *, solar_steps=True, silent_from=SIL, back=None): + """Every row: cycles > 0 (not vacuous), N8, N1, N4 (no select while the + meter is silent), N6 (no Traceback, no step failure).""" + bad = [] + if not [s for s in steps if s["solar"]]: + bad.append("no Solar step ran") + if n8(steps): + bad.append(("N8", n8(steps)[:2])) + if r["c"].charger.clamp_faults: + bad.append("N1 clamp fault") + over = [x for x in r["sim"].log if x[1] == "current" and x[2] > 16.0] + if over: + bad.append(("N1", over[:1])) + end = back if back is not None else 1e9 + sel = [x[0] for x in selects(r) if silent_from + 31 < x[0] < end] + if sel: + bad.append(("N4", sel[:2])) + n = r.get("_log", 0) + if LOG.tracebacks(n) or [m for m in LOG.since(n) + if "car charger step failed" in m]: + bad.append("N6") + check(f"{tag}: N1, N4, N6, N8 hold, cycles > 0 ({bad[:2]})", not bad) + return not bad + + +def run_log(fn, *a, **kw): + n = LOG.mark() + r, st = fn(*a, **kw) + r["_log"] = n + return r, st + + +def jit(): + return (4, 6, 5, 4, 6, 5, 6) + + +def jit_set(dur): + t, out, i = 0, [], 0 + while t < dur: + out.append(t) + t += jit()[i % len(jit())] + i += 1 + return out + + +def lines(n0=0): + """The parsed DEBUG step lines: [{t, age, decision, write}].""" + out = [] + for lv, m, _x in LOG.rec[n0:]: + g = re.match(r"Solar step: t=(\S+) age=(\S+) decision=(\S+) " + r"write=(.*)$", m) + if lv == "DEBUG" and g: + out.append(dict(t=float(g[1]), + age=None if g[2] == "none" else float(g[2]), + decision=g[3], write=g[4])) + return out + + +def late_at(l0, l1): + """T10/T43: the late verdict stands from l0 (late_s = now - l0) until l1, + set where the controller reads it (`answer.late_s`), not as a constant.""" + def f(p, c): + c.answer.late_s = lambda now: (now - l0) if l0 <= now < l1 else None + return f + + +# =========================================================================== # +print("1. THE PAUSE ON THE FIRST STEP AT OWN AGE >= 330 (T1-T10, T20, T23)") +# =========================================================================== # +for race in (False, True): + tag = "race" if race else "plain" + ok, ages = True, [] + for ph in range(5): + r, st = run_log(go, cyc=5, phase=ph, race=race) + t = cyc_t(0, 5, ph, SIL + 30 + 300 - 1.3) # 628.7 + ok = ok and timing(st, exp_age=t - 298.7) and common( + f"T1 [{tag} ph{ph}]", r, st) + s, _ = pause_step(st) + ages.append(s and round(s["age"], 1)) + check(f"T1 [{tag}]: 5 s cycles, phases 0-4: the 0 A in the first step at " + f"own age >= 330 ({ages}; 331.3 332.3 333.3 334.3 330.3)", + ok and ages == [331.3, 332.3, 333.3, 334.3, 330.3]) + +R3 = {"F-silent-1": (32, [327, 332, 337, 343], 333.3), + "F-silent-2": (35, [327, 332, 336, 340, 345], 333.3), + "F-silent-3": (36, [324, 330, 335, 341], 331.3), + "F-exit": (33, [328, 334, 338], 335.3)} +for name, (first, tail, want) in R3.items(): + ages = list(range(first, tail[0], 5)) + tail + list(range(tail[-1] + 5, 460, 5)) + cset = set(range(0, SIL, 5)) | {int(round(SIL - 1 + 0.7 + a)) for a in ages} + for race in (False, True): + r, st = run_log(go, cset=cset, race=race) + s, _ = pause_step(st) + check(f"T2 [{name} {'race' if race else 'plain'}]: round-3 cadence: " + f"0 A at own age {s and round(s['age'], 1)} (want {want})", + timing(st, exp_age=want) and common("T2", r, st)) + +for race in (False, True): + tag = "race" if race else "plain" + ok = True + for cyc, phs in ((10, range(10)), (14, (0, 7))): + for ph in phs: + r, st = run_log(go, cyc=cyc, phase=ph, race=race, dur=720) + t = cyc_t(0, cyc, ph, 628.7) + ok = ok and timing(st, exp_age=t - 298.7) + check(f"T3 [{tag}]: 10 s cycles phases 0-9, 14 s cycles phases 0 and 7: " + f"the first step at own age >= 330 pauses", ok) + +for race in (False, True): + r, st = run_log(go, cset=set(jit_set(800)), race=race) + check(f"T4 [{'race' if race else 'plain'}]: jittered cycles 4/6/5/4/6/5/6 s: " + f"0 A at own age 332.3 (the silence's first steps do not move it)", + timing(st, exp_age=332.3) and common("T4", r, st)) + +# T5: the boundary: >= and not >, at the plan and at the controller. +def _plan_at(unknown_s, now): + p = SolarPlan(1) + p.a, p.n, p.set_at = 10.0, 1, 0.0 + p.step(now, target_w=None, n_now=1, auto=False, clamp=16.0, start_s=120.0, + pause_s=300.0, unknown_s=unknown_s) + return p.a + + +check("T5 (plan): own age 329.9 over a 30 s bound (unknown 299.9): no pause; " + "own age 330.0 (unknown 300.0): the pause", + _plan_at(299.9, 630.0) == 10.0 and _plan_at(300.0, 630.0) == 0.0) +for race in (False, True): + for ingest, want_t, tag in ((299.1, 629, "329.9"), (300.0, 630, "330.0")): + def _stamp(p, c, ingest=ingest): + c.p1._last = dataclasses.replace(c.p1._last, ingest_mono=ingest) + r, st = run_log(go, dur=700, race=race, + events={SIL: lambda p, c, f=_stamp: ( + setattr(p, "meter_on", False), f(p, c))}) + s, prev = pause_step(st) + z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0 + and x["now"] > SIL] + # ingest 299.1: the step at 629 has age 329.9 (no pause); 630 has 330.9. + # ingest 300.0: the step at 629 has age 329.0, 630 has exactly 330.0. + first_z = z[0]["now"] if z else None + check(f"T5 (controller, {'race' if race else 'plain'}): the sample " + f"stamped {ingest}: the pause is in the step at {want_t + (1 if tag == '329.9' else 0)} " + f"(first 0 A step {first_z}); ages seen {[round(x['age'], 1) for x in st if x['now'] in (629.0, 630.0)]}", + first_z == (630.0 if tag == "329.9" else 630.0) and bool(z)) + +for race in (False, True): + for ret_age, back_at, off_at in ((329, 628, 629), (200, 500, 501)): + r, st = run_log(go, dur=1400, cyc=5, phase=0, race=race, + events={back_at: lambda p, c: setattr(p, "meter_on", True), + off_at: lambda p, c: setattr(p, "meter_on", False)}) + ing = back_at - 0.3 + z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0 and x["now"] > SIL] + want = cyc_t(0, 5, 0, ing + 330.0) + check(f"T6 [{'race' if race else 'plain'}]: the meter back for one " + f"sample at age ~{ret_age}, silent again: no 0 A from the old " + f"silence, the pause at the first step at new own age >= 330 " + f"(t {z[0]['now'] if z else None}, want {want})", + bool(z) and z[0]["now"] == want + and abs(z[0]["age"] - (want - ing)) < 0.05) + +# T7, T8: C18, a held read. +for race in (False, True): + tag = "race" if race else "plain" + g0, g1 = (625, 626) if race else (630, 633) + r, st = run_log(go, dur=760, cyc=5, phase=0, race=race, + events={g0: lambda p, c: p.ch.go_unavailable(), + g1: lambda p, c: p.ch.go_unavailable(False)}) + s, prev = pause_step(st) + check(f"T7 [{tag}]: the charger read held on the step at 630 (own age " + f"331.3): the 0 A in that step ({s and (s['now'], round(s['age'], 1), s['held'], s['writes'])}), " + f"a NEW 0 A, no phase select, nothing else sent", + s is not None and s["held"] and s["now"] == 630.0 + and s["a0"] > 0.0 and s["a1"] == 0.0 + and [a for a, _t, _o in s["writes"]] == [0.0] and not s["phases"]) + common(f"T7 [{tag}]", r, st) + r, st = run_log(go, dur=760, cyc=5, phase=0, race=race, + events={330: lambda p, c: p.ch.go_unavailable(), + 333: lambda p, c: p.ch.go_unavailable(False)}) + check(f"T8 [{tag}] (Q3): the charger away on the first silent cycles " + f"(own age 31-34): the pause at own age 331.3", + timing(st, exp_age=331.3) and common(f"T8 [{tag}]", r, st)) + +r, st = run_log(go, dur=760, cyc=5, phase=0, + events={624: lambda p, c: p.ch.go_unavailable(), + 641: lambda p, c: p.ch.go_unavailable(False)}) +w = [(t, a) for t, a, _ in cur_writes(r)] +away = [x for x in w if 624 <= x[0] < 641] +after = [x for x in w if x[0] >= 641] +check(f"T9: the charger away 17 s from 624 (own age 325-342): the step at 630 is " + f"a held read (6 s, under stale_input_s), so its pause is C18's one 0 A; " + f"nothing else while away ({away}); no non-zero write on the return " + f"({after[:1]}), the 0 A already standing (D2: 0 A first, kept)", + away == [(630.0, 0.0)] and not [x for x in after if x[1] > 0.0] + and common("T9", r, st)) + +for ph in (0, 2, 4): + for race in (False, True): + r, st = run_log(go, dur=760, cyc=5, phase=ph, race=race, + events={0: late_at(600, 700)}) + t = cyc_t(0, 5, ph, 628.7) + check(f"T10 [{'race' if race else 'plain'} ph{ph}]: late readings (5 s) " + f"over 600-700: the hold branch pauses at own age {t - 298.7:.1f}", + timing(st, exp_age=t - 298.7) and common("T10", r, st)) + +# =========================================================================== # +print("\n2. PHASES, GAPS, RETURNS (T11-T19)") +# =========================================================================== # +r = S.drive(S.const(500.0), S.const(7600.0), dur=1100, first="car", + socs=dict(FULLB), car_phases=3, + events={276: lambda p, c: setattr(p, "meter_on", False), + 800: lambda p, c: setattr(p, "meter_on", True)}) +w = cur_writes(r) +seq0 = [t for t, a, _ in w if a == 0.0 and 295 <= t <= 305] +nz = [(t, a) for t, a, _ in w if a > 0.0 and 306 < t < 800] +back = [(t, a) for t, a, _ in w if a > 0.0 and t >= 800] +check(f"T11 (C17 b): a 1 -> 3 change at 301 s with the meter silent from 276: " + f"it ends at its 0 A ({seq0}), no non-zero write 306-800 ({nz}), after " + f"the return only by the start rule ({back[:1]}, >= 920)", + bool(seq0) and not nz and (not back or back[0][0] >= 920 - 1) + and not [x for x in selects(r) if 306 < x[0] < 800]) + +for race in (False, True): + r, st = run_log(go, onset=320, dur=800, cyc=5, phase=0, race=race, + sun=7600.0, car_phases=3, opts={"ev_phases": "auto"}) + s, _ = pause_step(st, since=320) + check(f"T12 [{'race' if race else 'plain'}]: 3-phase car, the meter silent " + f"from 320 s: 3 phases stand; the pause at own age 331.3 (step at 650)", + timing(st, exp_age=331.3, since=320) and common( + "T12", r, st, silent_from=320) + and r["sim"].phases_allowed == 3 and s["now"] == 650.0) + +sim13 = TSim(setpoint_a=0, windows=[(335.0, 350.0, "ignore")]) +for race in (False, True): + r, st = run_log(go, onset=345, dur=900, cyc=5, phase=0, race=race, + sim=TSim(setpoint_a=0, windows=[(335.0, 350.0, "ignore")]), + sun=lambda t: 3000.0 if t >= 340 else 2300.0) + nzr = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > 345 + 30] + check(f"T13 [{'race' if race else 'plain'}]: an ignored raise to 10 A at " + f"340, the meter silent from 345: no re-send ({nzr}), the pause at " + f"the first step at own age >= 330", + not nzr and timing(st, since=345) and common( + "T13", r, st, silent_from=345)) + +for n in (1, 2, 6): + r = S.drive(S.const(500.0), S.const(7600.0), dur=700, first="car", + socs=dict(FULLB), car_phases=3, + events={305: lambda p, c: p.ch.go_unavailable(), + 305 + n: lambda p, c: p.ch.go_unavailable(False)}) + w = cur_writes(r) + close = [(t, a) for t, a, _ in w if a > 0.0 and 301 < t < 700] + check(f"T14 (C19): {n} failed read(s) at 305 s: the closing current on " + f"time ({close[:1]}), no pause", + bool(close) and 312 <= close[0][0] <= 313 + n + and not [1 for t, a, _ in w if 301 < t < 700 and a == 0.0]) + +# T15: unavailable = nothing ingested (the state is rejected before ingest). +for race in (False, True): + r, st = run_log(go, dur=1000, cyc=5, phase=0, race=race) + check(f"T15 [{'race' if race else 'plain'}]: meter unavailable from 300: " + f"the same age rule as silent", timing(st, exp_age=331.3)) + r, st = run_log(go, dur=1000, cyc=5, phase=0, race=race, + events={450: lambda p, c: setattr(p, "meter_on", False), + 900: lambda p, c: setattr(p, "meter_on", True)}) + z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0 and x["now"] > SIL] + zw = [t for t, a, _ in cur_writes(r) if a == 0.0 and 300 < t < 900] + check(f"T15 [{'race' if race else 'plain'}]: silent, then unavailable at " + f"450, back at 900: unavailable does not reset the age; exactly one " + f"0 A ({zw})", len(zw) == 1 and len(z) == 1 + and abs(z[0]["age"] - 331.3) < 0.05 and common( + "T15", r, st, back=900)) + +# T16: arrival sources keep the cycle's age (and the 15 s + 300 s rule). +ARRIVAL = {} +for src in ("homewizard_local", "mqtt_p1"): + for race in (False, True): + for cyc in (1, 5): + r, st = run_log(go, dur=760, cyc=cyc, phase=0, race=race, + opts={"meter_source": src}) + z = [t for t, a, _ in cur_writes(r) if a == 0.0 and t > SIL] + nz16 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > SIL + 30] + ARRIVAL[(src, race, cyc)] = z[:1] + check(f"T16 [{src} {'race' if race else 'plain'} cyc {cyc}]: " + f"arrival source: p1 on {r['c'].p1_enabled}; first 0 A at " + f"{z[:1]} (spare unknown at 15 s, then 300 s), no non-zero " + f"while silent ({nz16})", + r["c"].p1_enabled and not nz16 and bool(z) + and 300 + 15 + 300 - 1 <= z[0] <= 300 + 15 + 300 + 8) + +# T17, T18: an add-on restart: a new Controller, the store and charger kept. +for restart_at in (500, 640): + r1, _ = go(dur=restart_at) + n = LOG.mark() + STEPS.clear() + n_dbg = LOG.mark() + r2 = S.drive(S.const(500.0), S.const(2900.0), dur=500, first="car", + socs=dict(FULLB), opts=dict(OPT1), sim=r1["sim"], + store=r1["store"], t0=float(restart_at), + events={restart_at: lambda p, c: setattr(p, "meter_on", False), + restart_at + 300: lambda p, c: setattr(p, "meter_on", True)}) + w = [(t, a) for t, a, _ in cur_writes(r2)] + pre = [x for x in w if x[0] < restart_at + 300] + nzr = [x for x in pre if x[1] > 0.0] + after = [x for x in w if x[1] > 0.0 and x[0] >= restart_at + 300] + dl = lines(n_dbg) + none_age = [x for x in dl if x["age"] is None] + check(f"T17: restart at own age {restart_at - 298.7:.0f} with the meter " + f"still silent: the first write before the return is 0 A or none, " + f"the 0 A already standing ({pre[:1]}), 0 " + f"non-zero until it returns ({nzr}), then the start rule " + f"(>= +120: {after[:1]}); the age counts from the first reading: " + f"DEBUG shows age none until then ({len(none_age)} lines)", + (not pre or pre[0][1] == 0.0) and not nzr + and (not after or after[0][0] >= restart_at + 300 + 120 - 1) + and len(none_age) > 0 + and not LOG.tracebacks(n)) +r1, _ = go(dur=500) +n = LOG.mark() +r2 = S.drive(S.const(500.0), S.const(2900.0), dur=900, first="car", + socs=dict(FULLB), opts=dict(OPT1), sim=r1["sim"], + store=r1["store"], t0=500.0, + events={500: lambda p, c: setattr(p, "meter_on", False)}) +check("T18: restart, the meter never returns (900 s): 0 non-zero writes, no " + "Traceback, no 'car charger step failed'", + not [1 for t, a, _ in cur_writes(r2) if a > 0.0] + and not LOG.tracebacks(n) + and not [m for m in LOG.since(n) if "car charger step failed" in m]) + +for race in (False, True): + r, st = run_log(go, dur=1500, cyc=5, phase=0, race=race, + events={1100: lambda p, c: setattr(p, "meter_on", True)}) + nz19 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > 1000] + check(f"T19 [{'race' if race else 'plain'}]: the pause, the meter back at " + f"1100: the first non-zero write {nz19[:1]} within [1220, 1226]", + bool(nz19) and 1220 <= nz19[0][0] <= 1226 and 10.0 <= nz19[0][1] <= 12.0) + +# =========================================================================== # +print("\n3. BOUNDS, QUARTER START, OTHER WRITERS (T20-T24)") +# =========================================================================== # +for ma, pm, bound in ((5, 1, 65), (30, 1, 90), (300, 1, 360), (300, 30, 2100)): + for race in (False, True): + r, st = run_log(go, dur=SIL + bound + 120, cyc=5, phase=0, race=race, + opts={"meter_max_age_s": ma, "ev_pause_min": pm}) + t = cyc_t(0, 5, 0, 298.7 + bound) + ok = timing(st, bound=float(bound), exp_age=t - 298.7) + check(f"T20 [{ma},{pm}] {'race' if race else 'plain'}: the pause at the " + f"first step at own age >= {bound} ({t - 298.7:.1f}); no non-zero " + f"write past {ma} s", + ok and not n8(st, float(ma))) + +r = S.drive(S.const(500.0), S.const(300.0), dur=900, first="car", + socs=dict(FULLB), opts=dict(OPT1), + events={SIL: lambda p, c: setattr(p, "meter_on", False)}) +check(f"T21: a paused car (0 W, 0 A) when the meter goes silent: no write at " + f"all ({cur_writes(r)[:2]})", cur_writes(r) == []) +r = S.drive(S.const(500.0), S.const(2900.0), dur=1000, first="car", + socs=dict(FULLB), opts=dict(OPT1), + events={SIL: lambda p, c: setattr(p, "meter_on", False), + 310: lambda p, c: p.ch.freeze()}) +check(f"T21: a frozen car reading during the silence: nothing non-zero past " + f"30 s of silence ({[(t, a) for t, a, _ in cur_writes(r) if a > 0 and t > 330]})", + not [1 for t, a, _ in cur_writes(r) if a > 0 and t > 330]) + +r = S.drive(S.const(500.0), S.const(2900.0), dur=760, first="car", + socs=dict(FULLB), opts=dict(OPT1), + events={200: lambda p, c: p.ch.set_current(13), + SIL: lambda p, c: setattr(p, "meter_on", False)}) +check(f"T22 (N3): another writer's 13 A at 200, the meter silent from 300: " + f"nothing written over it ({[x for x in r['plant'].sets if x[1] == S.SET and x[0] >= 200]}), " + f"it stands at {r['sim'].setpoint_a}", + not [x for x in r["plant"].sets if x[1] == S.SET and x[0] >= 200] + and r["sim"].setpoint_a == 13.0) + +for race in (False, True): + r, st = run_log(go, onset=570, dur=1100, cyc=5, phase=0, race=race) + s, _ = pause_step(st, since=570) + check(f"T23 [{'race' if race else 'plain'}]: silence from 570: the first " + f"step at own age >= 330 is the quarter start t=900 " + f"({s and s['now']}); the peak guard never limits", + timing(st, exp_age=331.3, since=570) and s["now"] == 900.0 + and not [x for x in r["trace"] if x["lim"]]) + +# T24: battery setpoints are the same with the age rule at the cycle's age (the +# base behaviour) as with the step's own age: the car's rules never touch them. +def _sets(r): + return [(t, e, v) for t, e, v in r["plant"].sets if e.startswith("number.sp_")] + + +_real_own = getattr(Controller, "car_sun_own", None) +for first, sun in (("car", 2900.0), ("batteries", 7900.0)): + sets = [] + for own in (True, False): + if _real_own is not None: + Controller.car_sun_own = _real_own if own else (lambda self, s, n: s) + try: + kw = dict(first=first, sun=sun, dur=760, cyc=5, phase=0, race=True) + STEPS.clear() + r = S.drive(S.const(500.0), S.const(sun), dur=760, first=first, + socs={"a": 100.0, "b": 100.0} if first == "car" + else {"a": 50.0, "b": 50.0}, opts=dict(OPT1), + events={SIL: lambda p, c: setattr(p, "meter_on", False)}, + cyc=5, phase=0, race=True) + finally: + if _real_own is not None: + Controller.car_sun_own = _real_own + sets.append(_sets(r)) + sa, sb = sets + check(f"T24 [{first} first, sun {sun:.0f}]: the batteries' setpoints are " + f"the same on every cycle whichever age the writer step uses " + f"({len(sa)} writes)", sa == sb and bool(sa)) + +# =========================================================================== # +print("\n4. DOCS (T26)") +# =========================================================================== # +doc = open(os.path.join(HERE, "DECISIONS", "EV-20-solar-mode.md")).read() +check("T26: DECISIONS states the rule once: 0 A on the first car step whose own " + "meter age is >= meter_max_age_s + ev_pause_min, held steps included; the " + "'(bound 330 s + one cycle)' wording is gone", + "bound 330 s + one cycle" not in doc + and doc.count("EV-51: decided at the step's own meter age") == 1 + and "held steps included" in doc) + +# =========================================================================== # +print("\n5. THE DEBUG LINE (T28-T34; N9, N10, N11)") +# =========================================================================== # +n = LOG.mark() +r, st = run_log(go, dur=760, cyc=5, phase=0, race=True) +dl = lines(n) +solar_steps = [s for s in st if s["solar"]] +pre = [x for x in dl if x["age"] is not None and x["age"] < 330.0] +at = [x for x in dl if x["age"] is not None and x["age"] >= 330.0] +at0 = nth(at, 0) +check(f"T28: one DEBUG line per Solar writer step ({len(dl)} lines, " + f"{len(solar_steps)} steps); steps under 330: steady or wait-unknown, " + f"write none; the step at own age 331.3: pause, sent 0 A, confirmed; " + f"later steps write nothing", + len(dl) == len(solar_steps) and bool(pre) + and all(x["decision"] in ("steady", "wait-unknown") and x["write"] == "none" + for x in pre if x["t"] > 130) + and present(at0) and at0["decision"] == "pause" + and abs(at0["age"] - 331.3) < 0.05 + and at0["write"] == "sent 0 A confirmed" + and all(x["write"] == "none" for x in at[1:])) +check("T28: the line's fields are the record time t and the meter age, the " + "decision word and the write", + all(set(x) == {"t", "age", "decision", "write"} for x in dl)) + +n = LOG.mark() +r, st = run_log(go, dur=760, cyc=10, phase=3, race=True) +dl = lines(n) +bad = [x for x in dl if x["t"] > SIL + 1 and ( + x["age"] is None or abs(x["age"] - (x["t"] - 298.7)) > 0.05)] +check(f"T29: race order, 10 s cycles, phase 3: the logged age is the step's own " + f"(now - 298.7), never the snapshot's (10 s less) ({bad[:1]})", + bool(dl) and not bad and len([x for x in dl if x["t"] > SIL]) > 30) + +# T30 / N9: nothing new at info. The records of the run on 5bff894 (measured +# there, pinned): none at INFO or above for this run. +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:]] +finally: + GOOGLE.setLevel(logging.DEBUG) +# Measured on 5bff894 (same run, INFO), pinned: +BASE_INFO = [ + ('INFO', 'maintenance history: moved 5 saved values to one part per inverter: unit/inverter-a/last_completed, unit/inverter-a/last_failed, unit/inverter-a/last_start_attempt, unit/inverter-a/phase, unit/inverter-a/phase_started'), + ('INFO', 'Month peak store: fresh start, nothing saved'), + ('INFO', "No price history is kept (no durable volume at /data), so missing hours are not filled from yesterday's prices."), + ('INFO', 'Price history: unavailable - no durable volume at /data'), + ('WARNING', 'No meter reading for over 30 seconds, so control waits and then sets the battery to 0 W.'), +] +check(f"T30 (N9): at INFO the new line is not there ({len(lines(n))} lines) and " + f"the INFO+ records equal the run on 5bff894 ({info[:3]})", + lines(n) == [] and not [m for lv, m in info if "Solar step" in m] + and info == BASE_INFO) + +# T31: Nones in the line. +n = LOG.mark() +r, st = run_log(go, onset=0, dur=400, cyc=5, phase=0, race=True) +dl = lines(n) +check(f"T31 (a): no reading since boot: age none ({len(dl)} lines), no failure", + bool(dl) and all(x["age"] is None for x in dl) + and not LOG.tracebacks(n) + and not [m for m in LOG.since(n) if "car charger step failed" in m]) +n = LOG.mark() +r, st = run_log(go, dur=400, cyc=5, phase=0, + events={0: lambda p, c: p.ch.go_unavailable()}) +check(f"T31 (b): the charger unavailable the whole run: lines still print, no " + f"failure ({len(lines(n))} lines)", + bool(lines(n)) and not LOG.tracebacks(n) + and not [m for m in LOG.since(n) if "car charger step failed" in m]) +n = LOG.mark() +r = S.drive(S.const(500.0), S.const(2900.0), dur=500, first="car", + socs=dict(FULLB), opts=dict(OPT1), mode="manual", + events={200: act("car_mode", "solar")}) +check(f"T31 (c): Solar engaged after Manual (sent_a None): the line prints " + f"({len(lines(n))} lines), no failure", + bool(lines(n)) and not LOG.tracebacks(n) + and not [m for m in LOG.since(n) if "car charger step failed" in m]) + + +def _same_at_levels(tag, mk): + """DEBUG vs INFO: the same writes and the same Home Assistant calls (N11).""" + outs = [] + for lvl in (logging.DEBUG, logging.INFO): + GOOGLE.setLevel(lvl) + try: + n = LOG.mark() + r = mk() + outs.append((r["plant"].sets, r["raised"], r["sim"].log, + len(lines(n)))) + finally: + GOOGLE.setLevel(logging.DEBUG) + return outs + + +outs = _same_at_levels("T31", lambda: go(dur=300, cyc=5, phase=0, onset=0)[0]) +o_dbg, o_inf = outs +same = o_dbg[:3] == o_inf[:3] +check("T31 (N11): no reading since boot: the writes and Home Assistant calls " + "are the same at DEBUG and INFO", + same and o_dbg[3] > 0 and o_inf[3] == 0) + +# T32: the pause's 0 A refused. +def _t32(plant_cls=None, sim=None): + return go(dur=760, cyc=5, phase=0, sim=sim, plant_cls=plant_cls)[0] + + +class RefusePlant(S.SunPlant): + async def set_number(self, e, v): + if e == S.SET and float(v) == 0.0 and 630 <= self.t <= 700: + self.sets.append((self.t, e, float(v))) + return False + return await super().set_number(e, v) + + +for what, mk in (("the charger ignores it", lambda: _t32( + sim=TSim(setpoint_a=0, windows=[(629.5, 700, "ignore")]))), + ("Home Assistant refuses it", lambda: _t32(plant_cls=RefusePlant))): + outs = _same_at_levels("T32", mk) + o_dbg, o_inf = outs + same32 = o_dbg[:3] == o_inf[:3] + GOOGLE.setLevel(logging.DEBUG) + n = LOG.mark() + mk() + sent = [x for x in lines(n) if x["write"].startswith("sent 0 A") + and x["t"] >= 630] + unconf = [x for x in sent if "confirmed" not in x["write"]] + check(f"T32 [{what}]: DEBUG shows 'sent 0 A' without 'confirmed' for each " + f"refused try ({[(x['t'], x['write']) for x in sent[:4]]}); the " + f"writes and Home Assistant calls equal the INFO run (N11)", + bool(unconf) and same32) + +# T33 / N10: secrets. +SENT = {"price_service_token": "SENTINEL-TOKEN-3317", + "mqtt_password": "SENTINEL-MQTT-3317", "api_key": "SENTINEL-KEY-3317", + "ha_token": "SENTINEL-HA-3317"} +n = LOG.mark() +r, st = run_log(go, dur=760, cyc=5, phase=0, race=True, opts=dict(SENT)) +check("T33 (N10): sentinel values in every secret-like option never reach a " + "log record", + not [m for _lv, m, _x in LOG.rec[n:] if "SENTINEL" in m] + and len(lines(n)) > 0) + +# T34: volume. +n = LOG.mark() +r, st = run_log(go, dur=760) +dl = lines(n) +check(f"T34: 1 s cycles, 760 s: the new lines equal the Solar writer steps " + f"({len(dl)} vs {len([s for s in st if s['solar']])}), none per poll", + 0 < len(dl) <= 760 and len(dl) == len([s for s in st if s["solar"]])) + +# =========================================================================== # +print("\n6. THE HARNESS CADENCE (T35-T39)") +# =========================================================================== # +def _sig(r): + return ([(x["t"], x["a"], x["why"], x["sp"]) for x in r["trace"]], + list(r["sim"].log), list(r["plant"].sets)) + + +for tag, kw in (("silent car-first", dict()), + ("batteries first, sun 4.4 kW", dict(first="batteries", sun=4400.0))): + a, _ = go(dur=500, **kw) + b, _ = go(dur=500, cyc=1, phase=0, jitter=None, race=False, **kw) + check(f"T35 [{tag}]: the default call equals an explicit cyc=1, phase=0, " + f"jitter=None, race=False (same trace, writes and sets)", + _sig(a) == _sig(b) and len(a["trace"]) == 500) + +for cyc in (5, 10): + badph = [] + for ph in range(cyc): + r, st = go(dur=60, cyc=cyc, phase=ph, onset=None) + ts = [x["t"] for x in r["trace"]] + if ts != [float(t) for t in range(ph, 60, cyc)] or [ + s["now"] for s in st] != ts: + badph.append((ph, ts[:3])) + check(f"T36: cyc {cyc}, every phase: trace rows and writer steps only at " + f"seconds with (t - t0) mod cyc == phase ({badph[:2]})", not badph) +r, st = go(dur=60, cyc=5, phase=2, onset=20) +check(f"T36: the meter and the charger still tick every second: the meter " + f"samples {r['c'].p1.samples} (20 s on) and {len(r['trace'])} rows", + r["c"].p1.samples == 20 and len(r["trace"]) == 12) + +r, st = go(dur=60, jitter=(4, 6, 5), onset=None) +check(f"T37: jitter 4/6/5: rows at {[x['t'] for x in r['trace']][:6]}", + [x["t"] for x in r["trace"]] + == [0.0, 4.0, 10.0, 15.0, 19.0, 25.0, 30.0, 34.0, 40.0, 45.0, 49.0, + 55.0]) +r, st = go(dur=40, cset=[3, 7, 8, 39, 40, 99], onset=None, t0=0.0) +check(f"T37: an explicit set of cycle seconds: rows exactly at those inside " + f"[t0, t0 + dur) ({[x['t'] for x in r['trace']]})", + [x["t"] for x in r["trace"]] == [3.0, 7.0, 8.0, 39.0]) + +for race in (False, True): + r, st = go(dur=700, cyc=10, phase=3, race=race) + # (the run's last settle runs one step off the cycle grid: left out) + st2 = [s for s in st if s["solar"] and s["now"] > SIL + 40 + and s["snap_age"] is not None and s["now"] % 10 == 3] + d = [round(s["age"] - s["snap_age"], 1) for s in st2] + want = 10.0 if race else 0.0 + check(f"T38 [{'race' if race else 'plain'}]: the snapshot's age is the " + f"step's own age minus {want:.0f} s ({sorted(set(d))[:3]})", + bool(st2) and all(abs(x - want) <= 0.05 for x in d)) + +bads = 0 +for kw in (dict(cyc=0), dict(cyc=-5), dict(cyc=5, phase=5), dict(cyc=5, phase=-1), + dict(cset=[900]), dict(cset=[]), dict(jitter=()), dict(jitter=(0,))): + try: + go(dur=20, onset=None, **kw) + except ValueError: + bads += 1 +check(f"T39: a cycle length of 0 or less, a phase outside [0, cyc), a set with " + f"no second in the run, an empty jitter: ValueError ({bads} of 8)", + bads == 8) + +# =========================================================================== # +print("\n7. THE METER BACK; THE SWEEPS; THE HOLD (T40-T43; N12)") +# =========================================================================== # +r, st = run_log(go, dur=900, cyc=5, phase=0, race=True, + events={630: lambda p, c: setattr(p, "meter_on", True)}) +s630 = [s for s in st if s["now"] == 630.0][0] +w40 = [(t, a) for t, a, _ in cur_writes(r) if t > SIL] +check(f"T40: race, the meter back at 630 (sample ingested before the step, " + f"snapshot 625 said silent at {s630['snap_age']:.1f}): own age " + f"{s630['age']:.1f}, no pause, no current write 300-900 ({w40}); the " + f"plan keeps 10 A ({r['c'].car_solar.plan.a})", + abs(s630["age"] - 0.3) < 0.05 and w40 == [] + and r["c"].car_solar.plan.a == 10.0 and common("T40", r, st, back=630)) + +for back_at in (631, 635): + r, st = run_log(go, dur=1100, cyc=5, phase=0, race=True, + events={back_at: lambda p, c: setattr(p, "meter_on", True)}) + s, _ = pause_step(st) + nzb = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > 630] + check(f"T41: race, the meter back at {back_at}: the 0 A in the step at 630 " + f"(own age {s and round(s['age'], 1)}); after the return only the " + f"start rule ({nzb[:1]}, >= {back_at + 120})", + timing(st, exp_age=331.3) and s["now"] == 630.0 + and (not nzb or nzb[0][0] >= back_at + 120 - 1)) + + +def sweep(kind, cyc, race, onsets): + """T42: the silence onset swept; the non-zero writes at a step whose own + age is > 30.""" + hits = [] + for s in onsets: + if kind == "starts": + r, st = go(onset=s, dur=s + 120, cyc=cyc, phase=0, race=race) + else: + r, st = go(onset=s, dur=min(s + 130, 760), cyc=cyc, phase=0, + race=race, + sun=lambda t: 4400.0 if t >= 200 else 2900.0) + b = n8(st) + if b: + hits.append((s, b[0])) + return hits + + +for cyc in (5, 10): + for race in (False, True): + h = sweep("starts", cyc, race, range(60, 126)) + check(f"T42 starts [{cyc} s {'race' if race else 'plain'}]: a start due " + f"just after the silence onset (onset 60-125): 0 of 66 onsets " + f"with a non-zero write at own age > 30 ({len(h)}: {h[:2]})", + not h) +for race in (False, True): + h = sweep("raises", 5, race, range(200, 330)) + check(f"T42 raises [5 s {'race' if race else 'plain'}]: a raise due " + f"(sun 4.4 kW from 200), onset 200-329: 0 of 130 onsets with a " + f"non-zero write at own age > 30 ({len(h)}: {h[:2]})", not h) + +for l0, want in ((598, 915.0), (602, 920.0)): + for race in (False, True): + r, st = run_log(go, onset=None, dur=1100, cyc=5, phase=0, race=race, + events={0: late_at(l0, 1000)}) + z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0] + nz43 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and 600 <= t < 1000] + cross = [s for s in st if s["now"] >= l0 + 15][0] + check(f"T43 (a) [L0 {l0} {'race' if race else 'plain'}]: running at 10 A, " + f"late from {l0}: the crossing step (own late >= 15) takes the " + f"stale rule, the 0 A at {z[0]['now'] if z else None} " + f"(want {want}); no non-zero write 600-1000 ({nz43})", + bool(z) and z[0]["now"] == want and not nz43) + n = LOG.mark() + run_log(go, onset=None, dur=640, cyc=5, phase=0, race=race, + events={0: late_at(l0, 1000)}) + dl = lines(n) + cr = [x for x in dl if x["t"] == float(cross["now"])] + before = [x for x in dl if x["t"] == float(cross["now"]) - 5] + check(f"T43 (a) DEBUG [{'race' if race else 'plain'} L0 {l0}]: the step " + f"before the crossing holds, the crossing step does not " + f"({before and before[0]['decision']} -> {cr and cr[0]['decision']})", + bool(cr) and bool(before) and before[0]["decision"] == "hold" + and cr[0]["decision"] == "wait-unknown") + +for l0 in (101, 103, 105): + for race in (False, True): + r, st = run_log(go, onset=None, dur=500, cyc=5, phase=0, race=race, + events={0: late_at(l0, 400)}) + nz43 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and 116 <= t < 400] + cross = [s for s in st if s["now"] >= l0 + 15][0] + check(f"T43 (b) (N12) [L0 {l0} {'race' if race else 'plain'}]: paused " + f"with a start due, late from {l0}: the crossing step at " + f"{cross['now']} writes nothing ({cross['writes']}) from its " + f"snapshot ({cross['snap_tgt']} W); no non-zero write 116-400 " + f"({nz43})", cross["now"] == 120.0 and not cross["writes"] + and not nz43) + +report() diff --git a/goodwe_controller/tools/ev20_sun.py b/goodwe_controller/tools/ev20_sun.py index 2d2c0bf..b3892e6 100644 --- a/goodwe_controller/tools/ev20_sun.py +++ b/goodwe_controller/tools/ev20_sun.py @@ -137,11 +137,41 @@ class SunPlant: return True +def _cycle_seconds(t0, dur, cyc, phase, jitter, cset): + """EV-51: the seconds a cycle runs, or None for every second.""" + if cset is not None: + due = {int(x) for x in cset if t0 <= x < t0 + dur} + if not due: + raise ValueError("cset has no second inside the run") + return due + if jitter is not None: + gaps = [int(g) for g in jitter] + if not gaps or min(gaps) <= 0: + raise ValueError("jitter needs gaps above 0") + due, t, i = set(), int(t0), 0 + while t < t0 + dur: + due.add(t) + t += gaps[i % len(gaps)] + i += 1 + return due + if cyc != int(cyc) or cyc <= 0: + raise ValueError("cyc must be a whole number of seconds above 0") + if not 0 <= phase < cyc: + raise ValueError("phase must be in [0, cyc)") + if cyc == 1: + return None + due = {int(t0) + k for k in range(int(phase), int(dur), int(cyc))} + if not due: + raise ValueError("no cycle inside the run") + return due + + def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar", first="batteries", events=None, sim=None, store=None, race=False, on_cycle=None, car_phases=3, t0=0.0, caps=None, finale=None, - rows=False, plant_cls=None, beside=False, meter_change=False): + rows=False, plant_cls=None, beside=False, meter_change=False, + cyc=1, phase=0, jitter=None, cset=None): """Run it. Returns a dict: plant, controller, charger, notifications with their second, and a per-second trace. `caps` ({unit: kWh}) lets each battery's level move with what it charges or gives; without it the @@ -152,7 +182,14 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, round 1): a write that waits for its read-back is still waiting when the next cycle reads the charger; it resumes after that read. `meter_change=True` publishes the meter as Home Assistant does on - `ha_signed`: only when the whole-watt value changes.""" + `ha_signed`: only when the whole-watt value changes. + EV-51, the cycle's cadence (the meter and the charger model still tick + every 1 s; only the control cycle is thinned): `cyc` seconds between + cycles and `phase` (the first cycle at t0 + phase), or `jitter`, a + tuple of gaps used in turn (the first cycle at t0), or `cset`, the + cycle seconds. The default (1 s) runs every second as before. A cadence + that would run no cycle is a ValueError, never a vacuous pass.""" + due = _cycle_seconds(t0, dur, cyc, phase, jitter, cset) ratings = ratings or {"a": 5000.0, "b": 4600.0} socs = socs or {u: 50.0 for u in ratings} sim = sim or SimCharger(setpoint_a=setpoint) @@ -252,6 +289,12 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, "ha_signed", imp, exp, phases=1, ingest_ts=rig.BASE + timedelta(seconds=ts), ingest_mono=ts)) + if due is not None and int(t) not in due: + for u, kwh in (caps or {}).items(): + lv = plant.socs[u] - plant.batt_of(u, t) / 36000.0 / kwh + plant.socs[u] = max(0.0, min(100.0, lv)) + t += 1.0 + continue await c.read_inputs(now_mono=t) if race: await c.car_settle()