diff --git a/goodwe_controller/DECISIONS/EV-20-solar-mode.md b/goodwe_controller/DECISIONS/EV-20-solar-mode.md index 4711d22..a844e3b 100644 --- a/goodwe_controller/DECISIONS/EV-20-solar-mode.md +++ b/goodwe_controller/DECISIONS/EV-20-solar-mode.md @@ -108,3 +108,39 @@ one small set of facts and derives every path from them: bookkeeping (a 0 A not read back counts) or by the read-back showing a value it sent, confirmed, tried or saw at a refused try. - **C3** is T43-T45; **C7** is EV-22's. + +## Rig round 1 (rig FAIL on cc8c0dc), with EV-32 and EV-36 + +- **The stuck-reading check (chargers.py `CarTracker`), for every writer** + (SPIKE-06 option 2, PM decision; replaces 3a17012's power rules). + - Baseline: the signature (power, read-back) of the latest reading taken + BEFORE the send, kept at `begin_write`; never a reading that arrived + while the write waited (the rig's race, C10/C11, C13). + - Arms: a write that moved the setpoint by `STUCK_MIN_A`. Accepted: at its + send, on the baseline. Refused (EV-13): only with no life in `TOOK_S`, + dated the send, on the baseline. EV-36: the first sample after the send + is not life by itself; life differs from the samples before the send + AND from that first one. + - Clears: any reading whose signature differs from the baseline. + - Stuck: armed and not cleared for `STUCK_S` (60 s). + - A frozen POWER under an accepted write (the read-back moves) is no longer + judged here: the energy meter (EV-18 `contradicted`) and the read-back + cap on the trusted figure judge it. +- **Solar after a stuck verdict (C12, C14):** while no current of Solar's + own may stand (its own 0 A stands, or Solar was just chosen), a stuck + verdict no longer holds Solar: it writes its 0 A first over a current that + is not its own, then the start rule runs; at most MAX_TRIES starts per + verdict, then one CHARGER_REFUSED, then one more start after 15 min and + one every 30 min (PM decision: no hold until a press). The episode ends + when the reading follows a start, on a press of Solar, Off, Manual, shadow + or a stop (`_stuck_end`). Its write moves the reading (the verdict clears) or is + refused (EV-04's retries, then CHARGER_REFUSED). +- **No amp ping-pong:** after a step down, a step back up needs + `UP_HYST_W` (100 W) past the amp boundary. +- **The meter's age:** Solar's own `stale_input_s` gate applies where the age + measures arrival (HomeWizard local, MQTT, DSMR). On `ha_signed` the age is + the time since the value changed (Home Assistant publishes changes only), so + a healthy meter at a flat load would read as stale; there the source's own + `meter_max_age_s` is the bound (a silent meter: 0 A at + `meter_max_age_s` + `ev_pause_min`). + diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index 0990a0e..18f080d 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -3361,7 +3361,10 @@ changes at most once per 30 seconds and only by 1 A or more. stopping the add-on each set the charger to 0 A once. A 0 A the charger does not take is tried again after a minute, three times, then an amber row says so. After a restart, or when the charger or Home Assistant answers again, - Solar sets 0 A first and then starts by its own rules. At a stop of the + Solar sets 0 A first and then starts by its own rules. After a stuck + charger reading, Solar tries to start again by its start rule; after three + tries an amber row says so, and it tries once more after 15 minutes, then + every 30 minutes, until the reading follows. At a stop of the add-on the charger's 0 A goes out before the batteries go to 0 W, for at most 15 seconds; if the charger does not take it, the notice *Car may still be charging* follows. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index f30d669..7555685 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -64,6 +64,8 @@ PHASE_GAP_S = 600.0 # at most one phase switch per this WRITER_S = 30.0 # a differing read-back this long is another writer RETRY_S = 60.0 # a write the charger did not take, tried again after MAX_TRIES = 3 # ... this many times, then it waits for the user +STUCK_BACKOFF_FIRST_S = 900.0 # Solar under a stuck verdict, its starts used +STUCK_BACKOFF_S = 1800.0 # up: one more after 15 min, then every 30 min TOL_A = CH.TOOK_TOL_A @@ -430,6 +432,10 @@ SOLAR_WRITE_S = 30.0 # at most one current change per this ... SOLAR_STEP_A = 1.0 # ... and only on a change of this or more UP_W, UP_S = 4500.0, 180.0 # auto phases: to 3 at this for this long DOWN_W, DOWN_S = 4000.0, 300.0 # ... back to 1 under this for this long +# Rig round 1: after a step down, a step back up needs this much more than the +# amp boundary, so a spare that dithers on a boundary is one change, not 10 / +# 9 / 10 every 30 s (N5's intent). +UP_HYST_W = 100.0 ONE_PHASE_S = 10.0 # one phase drawing while 3 are allowed this long ONE_PHASE_MIN_W = 500.0 # ... with the car drawing at least this # D3: at shutdown the 0 A is tried this many times, this far apart, each @@ -522,6 +528,7 @@ class SolarPlan: self.target_w = None self._before = None # the state before a phase change self.ext_at = None # C6: Manual's latest non-zero write + self.last_dir = 0 # the latest change: +1 up, -1 down def pause(self, why="paused"): self.a = 0.0 @@ -541,6 +548,7 @@ class SolarPlan: self.why) self.n, self.switch = n, True self.a, self.set_at, self.why = float(a), now, "running" + self.last_dir = 0 self.ok_since = self.low_since = None self.up_since = self.down_since = None @@ -607,7 +615,7 @@ class SolarPlan: if hi < CH.MIN_A: self.pause() return - self.a, self.set_at = float(hi), now + self.a, self.set_at, self.last_dir = float(hi), now, -1 if auto and not self.switch: # auto phases, by dwells if self.n == 1: self.down_since = None @@ -640,7 +648,13 @@ class SolarPlan: if want is not None and want >= CH.MIN_A: self.low_since = None self.why = "running" + if want > self.a and self.last_dir < 0: + # Up again after a step down: only past the boundary plus + # `UP_HYST_W` (no ping-pong on an amp boundary). + up = amps_for(target_w - UP_HYST_W, self.n, clamp) or 0.0 + want = max(self.a, up) if abs(want - self.a) >= SOLAR_STEP_A and self._gate(now): + self.last_dir = 1 if want > self.a else -1 self.a, self.set_at = want, now return if auto and self.n == 3 and target_w >= DOWN_W and not self.switch: @@ -649,6 +663,7 @@ class SolarPlan: self.low_since = None self.why = "running" if self.a != CH.MIN_A and self._gate(now): + self.last_dir = 1 if CH.MIN_A > self.a else -1 self.a, self.set_at = CH.MIN_A, now return if self.low_since is None: @@ -658,7 +673,7 @@ class SolarPlan: self.pause() return if self.a != CH.MIN_A and self._gate(now): - self.a, self.set_at = CH.MIN_A, now + self.a, self.set_at, self.last_dir = CH.MIN_A, now, -1 class SolarWriter(ManualWriter): @@ -703,6 +718,9 @@ class SolarWriter(ManualWriter): self.start_owed = False # C1: a start in Off with a 0 A pending self.other_at = None # C6: Manual's latest non-zero write self.on_owed = None # C1: told when an own 0 A is out / back + self.stuck_starts = 0 # SPIKE-06 C12: starts under one stuck verdict + self.stuck_wait = None # ... used up: the next start not before + self.stuck_warned = False # ... and its one CHARGER_REFUSED was given def owe_start(self) -> None: """C1: the add-on starts in Off while an exit 0 A of its own was still @@ -710,6 +728,15 @@ class SolarWriter(ManualWriter): so the 0 A is owed (once it may write), retried by the exit rule.""" self.start_owed = self.engaged = True + def _stuck_end(self) -> None: + """SPIKE-06: a stuck episode ends (the reading followed a start, a + press of Solar, Off, Manual or shadow): starts counted afresh, and + its CHARGER_REFUSED is cleared.""" + if self.stuck_warned: + self.gave_up = False + self.stuck_starts, self.stuck_wait = 0, None + self.stuck_warned = False + def _owed(self, pending: bool) -> None: if self.on_owed is not None: self.on_owed(pending) @@ -744,6 +771,7 @@ class SolarWriter(ManualWriter): held = self.hold or self.mismatch_since is not None super().user_changed() self.gave_up, self.fails, self.fail_at = False, 0, None + self._stuck_end() if held: self.last_a = None self.sent_a, self.taken = None, True @@ -755,6 +783,10 @@ class SolarWriter(ManualWriter): read-back is never trusted (`live`).""" self.sent_a, self.taken = float(a), False zero = float(a) <= TOL_A + if not zero and tracker is not None and tracker.stuck(now): + self.stuck_starts += 1 # C12: a start under a stuck verdict + if self.stuck_wait is not None: + self.stuck_wait = now + STUCK_BACKOFF_S # a backoff try if zero: self.zero_at = self.zero_sent_at = now self._owed(True) # C1: kept with the mode until back @@ -990,6 +1022,7 @@ class SolarWriter(ManualWriter): self._adopt(cur) # round 9: a late read-back self._mark(r, now) if mode != SOLAR: + self._stuck_end() self.would = None if mode == OFF and self.start_owed: if not writing: @@ -1009,6 +1042,7 @@ class SolarWriter(ManualWriter): else self.plan.n n_now = 1 if self.single else n_real if not writing: + self._stuck_end() # Shadow, Stop, a safety stop, stopping: the way-out 0 A while # owed, then nothing. The watch goes on (another writer is held # for every reader) and so does the plan, for the card. @@ -1023,6 +1057,32 @@ class SolarWriter(ManualWriter): self.would = None fault = ("error" if (r.error or r.state in ("E", "F")) else "stuck" if stuck else None) + if not stuck: + self._stuck_end() # the reading moved: start afresh + if fault == "stuck" and not self.live: + # SPIKE-06 C12/C14 (option 2): no current of Solar's own may stand + # (its own 0 A stands, or Solar was just chosen), so a stuck + # verdict no longer holds the car: Solar's normal step writes its + # 0 A first over a current that is not its own, then the start + # rule. A start moves the reading (the episode ends) or is not + # taken: then the 0 A again. After MAX_TRIES such starts, one + # CHARGER_REFUSED, then one more start after 15 min and one every + # 30 min (PM decision): a fault that clears is found again. + if self.stuck_starts < MAX_TRIES: + fault = None + else: + if self.stuck_wait is None: + self.stuck_wait = now + STUCK_BACKOFF_FIRST_S + if not self.stuck_warned: + self.stuck_warned = True + _LOG.warning("The charger did not take the current, so " + "the add-on tries again in 15 min, then " + "every 30 min: CHARGER_REFUSED.") + if now >= self.stuck_wait: + self.gave_up = False + fault = None + else: + self.gave_up = True if fault is not None: # 0 A while owed, then no write until it clears; then the start # rule. A stuck reading cannot confirm the 0 A. diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index 1ea8fb7..a2082b0 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -715,6 +715,10 @@ class CarTracker: _prev: tuple | None = None # EV-04: our own writes, and the stuck-reading rule (SAFETY-37's shape) mute_until: float = 0.0 + # EV-20 rig round 1: the signature of the latest reading taken BEFORE our + # write went out, kept at `begin_write` (the arming baseline). Empty: no + # write begun, and `note_write` uses `sig`. + pre_sig: tuple = () armed_at: float | None = None armed_sig: tuple | None = None sig: tuple | None = None @@ -782,8 +786,15 @@ class CarTracker: def begin_write(self) -> None: """EV-12: a write of ours is in flight. Its read-back can reach the tracker before `note_write` runs (the write waits for it), so the mute - is open until `end_write`.""" + is open until `end_write`. + + EV-20 (rig round 1, EV-32; SPIKE-06 option 2): the stuck check's + baseline is the signature kept HERE, before the send. The write waits + for its read-back and the cycle reads the charger meanwhile, so `sig` + can already be the car's answer by `note_write`; armed on that, an + unchanged car was called stuck 60 s later.""" self.mute_until = float("inf") + self.pre_sig = (self.sig,) def end_write(self, now: float) -> None: """EV-12: the write returned (or failed). The mute runs @@ -805,6 +816,10 @@ class CarTracker: plainly alive is not a stuck reading. `polls` are the samples the write itself saw while it waited, `[(time, ChargerReading)]`.""" self.mute_until = now + OWN_WRITE_MUTE_S + # The baseline: the reading before the send (`begin_write`), never one + # that arrived while the write waited (no `begin_write`: `sig`). + base = self.pre_sig[0] if self.pre_sig else self.sig + self.pre_sig = () try: moved = was_a is None or abs(float(to_a) - float(was_a)) \ >= STUCK_MIN_A @@ -816,13 +831,13 @@ class CarTracker: return if ok: self._pend = None - self.armed_at, self.armed_sig = now, self.sig + self.armed_at, self.armed_sig = now, base return if self._pend is not None: return # an earlier refusal's window before = [x for x in self._ring if x[0] <= now] pre = [max(before, key=lambda x: x[0])[1]] if before else [] - self._pend = {"t": now, "pre": pre, "sig": self.sig} + self._pend = {"t": now, "pre": pre, "sig": base, "first": None} later = [(t, _life_vals(r)) for t, r in polls] later += [(t, v) for t, v in self._ring if t > now] for t, v in sorted(later, key=lambda x: x[0]): @@ -844,7 +859,13 @@ class CarTracker: return if t <= p["t"]: p["pre"] = (p["pre"] + [vals])[-8:] # taken before the send - elif t <= p["t"] + TOOK_S and _alive(vals, p["pre"]): + elif p.get("first") is None: + # EV-36 (SPIKE-05 C4): the first sample after the send may carry a + # value newer than the cycle's last read but frozen since; it is + # not life by itself, and life must differ from it as well. + p["first"] = vals + elif t <= p["t"] + TOOK_S and _alive(vals, p["pre"]) \ + and _alive(vals, [p["first"]]): self._pend = None # life: nothing to arm return if max(t, arrival) > p["t"] + TOOK_S: diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 7c0fdc4..3fa122c 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -423,8 +423,15 @@ class CarMixin: if self.p1_enabled: # The meter's own bound (`meter_max_age_s`) may be longer than # `stale_input_s`; a car write never comes from an older reading. + # Rig round 1: only where the age measures ARRIVAL. On `ha_signed` + # it measures the time since the value CHANGED (p1.py, Home + # Assistant emits changes only), so a healthy meter under a flat + # load would read as stale and pause the car; there the source's + # own `meter_max_age_s` (the cycle's `inputs_ok`) is the bound. age = self.p1.age_s() - if age is None or age > stale: + src = str(self.o.get("meter_source") or "") + bound = None if src == "ha_signed" else stale + if age is None or (bound is not None and age > bound): return None r = self.car.reading if r is None or not r.available or not self.car.fresh(mono): diff --git a/goodwe_controller/test_ev13.py b/goodwe_controller/test_ev13.py index 95b69c0..45d4ece 100644 --- a/goodwe_controller/test_ev13.py +++ b/goodwe_controller/test_ev13.py @@ -205,6 +205,19 @@ for what, e in (("the same values", 1.000), ("changed values", 1.010)): tl = [(TS + s, rd(e=e, taken=TS - 1.0)) for s in range(1, 131)] armed(f"T7 stale sample ({what}, taken-at TS-1 again and again)", tl) +# EV-20 rig round 1 (EV-36): one changed sample after the send is not life by +# itself, so these variants change twice. Every sample is still TAKEN before +# the send (TS-1), so the correct tracker sees no life and arms; one that dates +# samples by arrival (mutant M3) sees life. +tl2 = [(TS + s, rd(e=1.010 if s < 3 else 1.020, taken=TS - 1.0)) + for s in range(1, 131)] +armed("T7 stale samples, two changed values (taken-at TS-1 again and again)", + tl2) +late2 = [(TS + s, rd(e=1.010 if s < 3 else 1.020, taken=TS - 1.0) + if s <= 3 else rd(e=1.020)) for s in range(2, 131)] +armed("T8 samples taken at TS-1 (+10, then +20 Wh) arrive at TS+2 and TS+3, " + "nothing changes after them", late2, pre_end=-3) + # T8: the late pre-write sample (EV-12 ordering): taken TS-1, arrives TS+2 late = [(TS + s, rd(e=1.010, taken=TS - 1.0) if s == 2 else rd(e=1.010)) for s in range(2, 131)] @@ -265,8 +278,11 @@ tr = CH.CarTracker() for i in range(-5, 1): tr.observe(rd(), TS + i, UTC, DAY) tr.note_write(TS, 16, 10, False) +# EV-36 (SPIKE-05 C4): life shows after the first sample past the send (one +# changed sample that then stands may be a frozen newer value), so the energy +# moves twice here. for i in range(1, 5): - tr.observe(rd(e=1.010), TS + i, UTC, DAY) + tr.observe(rd(e=1.010 if i < 3 else 1.020), TS + i, UTC, DAY) tr.note_write(TS + 20, 10, 8, False) check("a refusal that showed life leaves no window; a later refusal gets " "its own", pend(tr) is not None and pend(tr)["t"] == TS + 20 @@ -593,27 +609,62 @@ for beside, side in SIDES: f"{w.amber()}", w.amber() == ["charger_refused", "charger_stuck"]) +# SPIKE-06 option 2 (PM decision, EV-20): the stuck check is armed on the +# reading before the send, so a frozen POWER under an accepted write (the +# read-back moves) is no longer judged by it. The energy-meter check (EV-18, +# `contradicted`) judges it, and the alarm figure stays capped by the +# read-back. Each row: never stuck; when the meter contradicts the figure. +async def contra_steps(w, n): + """[(t, contradicted, trusted figure, stuck)] one per second.""" + out = [] + for _ in range(n): + await w.step(1) + tk = w.c.car + out.append((w.t, tk.contradicted(w.t), tk.car_w_trusted(w.t), + tk.stuck(w.t))) + return out + + +def contra_report(name, t_w, cs, cap_w): + first = next((t for t, c, _f, _s in cs if c), None) + stuck = [t for t, _c, _f, s in cs if s] + # once the read-back shows the new current (its 3 s lag, +2) + over = [(t, f) for t, _c, f, _s in cs + if f is not None and f > cap_w and t >= t_w + 5] + rel = None if first is None else first - t_w + check(f"{name}: never stuck (the read-back moved), and the trusted " + f"figure never exceeds the read-back's {cap_w:.0f} W (energy meter " + f"contradicts it from the write +{rel} s; stuck {stuck[:1]}, over " + f"{over[:1]})", not stuck and over == []) + return rel + + async def t14(): w = await live_car(beside=True) w.sim.lag_s = 3.0 # the read-back is seen by the cycle w.sim.freeze_power() # the power sticks, the rest is live res = spy_on(w) - await w.act("car_current", 8) - tr = await w.step(100) - return w, res, tr + await w.act("car_current", TO_A) + cs = await contra_steps(w, 200) + return w, res, cs -LOG.rec.clear() -w, res, tr = run(t14()) -t_s = res[0][0] -fs = first_stuck(tr) -check(f"T14 an ACCEPTED write (read-back 3 s late) under a frozen power: " - f"stuck at t_s+60 (+-1), as before ({fs - t_s if fs else None})", - res[0][2] is True and fs is not None and 59 <= fs - t_s <= 61 - and w.c.car.armed_at == t_s) -check("T14 ...the amber row 'charger_stuck' shows, and the car figure is not " - "trusted while stuck (N4)", "charger_stuck" in w.amber() - and w.c.car.car_w_trusted(w.t) is None and w.c.car_alarm_w() is None) +for TO_A in (8, 6): + LOG.rec.clear() + w, res, cs = run(t14()) + rel = contra_report(f"T14 an ACCEPTED 16 -> {TO_A} A write (read-back 3 s " + f"late) under a frozen power", res[0][0], cs, + TO_A * CH.CEILING_V * 3) + check(f"T14 [{TO_A} A] ...the write was accepted", res[0][2] is True) + if TO_A == 6: + check(f"T14 [6 A] the energy meter flags the frozen figure (EV-18) " + f"at about +57 s after the write (+{rel})", + rel is not None and 50 <= rel <= 65) + else: + # The frozen figure is exactly 2x the real draw: CORR_RATIO 0.5 is + # not undercut, so EV-18 never flags it (PM accepted, SPIKE-06). + check(f"T14 [8 A] the energy meter does NOT flag the frozen figure " + f"(+{rel}); only the read-back cap bounds it", rel is None) async def t17(): @@ -621,25 +672,25 @@ async def t17(): w.sim.refuse = "ignore" res = spy_on(w) await w.act("car_current", 10) - tr = await w.step(70) # tries at t_s and t_s+60: live + await w.step(70) # tries at t_s and t_s+60: live w.sim.refuse = None w.sim.lag_s = 3.0 w.sim.freeze_power() await w.act("car_current", 12) - tr += await w.step(120) - return w, res, tr + cs = await contra_steps(w, 200) + return w, res, cs LOG.rec.clear() -w, res, tr = run(t17()) -t_s, t_acc = res[0][0], res[-1][0] -fs = first_stuck(tr) -check(f"T17 live refusals (not armed), then an accepted write at t_s+" - f"{t_acc - t_s:.0f}: not armed before it, stuck at ITS +60 (+-1) " - f"({fs - t_acc if fs else None})", - res[-1][2] is True and t_acc - t_s > 61 and fs is not None - and 59 <= fs - t_acc <= 61 - and all(a is None for t, a, _s in tr if t < t_acc)) +w, res, cs = run(t17()) +T17_S = contra_report("T17 live refusals, then an ACCEPTED write to 12 A " + "under a frozen power", res[-1][0], cs, + 12 * CH.CEILING_V * 3) +check(f"T17 the energy meter does NOT flag the frozen figure (+{T17_S}); " + f"only the read-back cap bounds it (PM accepted, SPIKE-06)", + T17_S is None) +check("T17 ...the last write was accepted, after the refusals", + res[-1][2] is True and res[0][2] is False) async def t18(): @@ -647,25 +698,25 @@ async def t18(): w.sim.lag_s = 3.0 w.sim.freeze_power() res = spy_on(w) - await w.act("car_current", 12) # accepted: arms - tr = await w.step(19) + await w.act("car_current", 12) # accepted + cs = await contra_steps(w, 19) w.sim.lag_s = 0.0 w.sim.refuse = "ignore" await w.act("car_current", 10) # a live refusal 20 s later - tr += await w.step(100) - return w, res, tr + cs += await contra_steps(w, 180) + return w, res, cs LOG.rec.clear() -w, res, tr = run(t18()) -t0 = res[0][0] -fs = first_stuck(tr) -check(f"T18 an accepted write armed at t0; a live refusal at t0+" - f"{res[1][0] - t0:.0f} neither clears nor delays it: stuck at t0+60 " - f"({fs - t0 if fs else None}), still dated t0", - len(res) >= 2 and res[1][2] is False and fs is not None - and 59 <= fs - t0 <= 61 and tr[-1][1] == t0 - and all(a == t0 for _t, a, _s in tr if a is not None)) +w, res, cs = run(t18()) +T18_S = contra_report("T18 an ACCEPTED write to 12 A under a frozen power, a " + "refusal 20 s later", res[0][0], cs, + 12 * CH.CEILING_V * 3) +check(f"T18 the energy meter does NOT flag the frozen figure (+{T18_S}); " + f"only the read-back cap bounds it (PM accepted, SPIKE-06)", + T18_S is None) +check("T18 ...the second write was refused", len(res) >= 2 + and res[1][2] is False) async def t21(beside): diff --git a/goodwe_controller/test_ev20_exits.py b/goodwe_controller/test_ev20_exits.py index 0f0c2ed..c351c70 100644 --- a/goodwe_controller/test_ev20_exits.py +++ b/goodwe_controller/test_ev20_exits.py @@ -240,6 +240,12 @@ check(f"T28 (b): frozen at 0 A, then Solar starts (the write unconfirmed): " bool(st28) and [x for x in w28b if x[0] >= st28[0]][:1] and [x for x in w28b if x[0] >= st28[0]][0][1] == 0.0 and r28b["sim"].setpoint_a == 0.0) +# SPIKE-06 (PM): under the verdict at most MAX_TRIES starts, then the backoff +# (15 min, then 30 min; test_ev20_rig.py): no 72 s flapping. +s28b = [t for t, a, _ in w28b if a > 0.0 and st28 and t >= st28[0]] +check(f"T28 (b): at most {carmode.MAX_TRIES} starts under the verdict in the " + f"run, then none before the 15 min backoff ({s28b})", + len(s28b) <= carmode.MAX_TRIES) # T29: the charger unavailable 300-420 s. T29 = {"i": lambda p, c: None, @@ -343,19 +349,24 @@ for kind in ("none", "nan", "unavailable"): and [a for _, a, _ in w4 if _ < 700] == [10.0, 0.0] and 599 <= [t for t, a, _ in w4 if a == 0.0][0] <= 602) -# T31: the meter goes silent at 10 A. +# T31: the meter goes silent at 10 A. Rig round 1: `stale_input_s` holds where +# the sample age measures arrival (here the HomeWizard local source); on +# `ha_signed` the age is the time since the value changed, and the source's own +# meter_max_age_s is the bound (test_ev20_rig.py). +ARRIVAL = {"meter_source": "homewizard_local", "p1_host": "192.0.2.10"} for race in (False, True): tag = "race" if race else "step" d = 1 if race else 0 r31 = std(900, events={300: lambda p, c: setattr(p, "meter_on", False)}, - race=race) + race=race, opts=ARRIVAL) w31 = cur_writes(r31) check(f"T31 (a) [{tag}]: silent from 300 s (the last sample 299.7 s): " f"no write until 15 + 300 s, then 0 A once (+2 s) ({w31})", [a for _, a, _ in w31] == [10.0, 0.0] and 614 <= w31[-1][0] <= 617 + d) r31b = std(900, events={300: lambda p, c: setattr(p, "meter_on", False), - 500: lambda p, c: setattr(p, "meter_on", True)}) + 500: lambda p, c: setattr(p, "meter_on", True)}, + opts=ARRIVAL) check(f"T31 (b): back at 200 s: no 0 A ({cur_writes(r31b)})", [a for _, a, _ in cur_writes(r31b)] == [10.0]) @@ -511,7 +522,7 @@ PATHS = { {}), "charger error": (300, {300: _err}, {}), "unplug": (300, {300: lambda p, c: p.ch.unplug()}, {}), - "meter stale": (514, {200: _meter_off}, {}), + "meter stale": (514, {200: _meter_off}, ARRIVAL), "charger back": (420, {240: lambda p, c: p.ch.go_unavailable(True), 300: lambda p, c: p.ch.set_current(16), 420: lambda p, c: p.ch.go_unavailable(False)}, {}), diff --git a/goodwe_controller/test_ev20_rig.py b/goodwe_controller/test_ev20_rig.py new file mode 100644 index 0000000..e81a551 --- /dev/null +++ b/goodwe_controller/test_ev20_rig.py @@ -0,0 +1,505 @@ +"""EV-20 rig round 1 (rig FAIL on cc8c0dc), with EV-32 and EV-36. +`python3 -B test_ev20_rig.py` + +1. The stuck check's arming race (Critical, EV-32): a write waits for its + read-back while the next cycle reads the charger; the check must be armed on + the reading taken before the send, so a car that then stays paused is not + "stuck". Tracker rows and the real Controller in the rig's interleave + (`beside`), the rig's repro scenario among them. +2. EV-36 (SPIKE-05 C4): a frozen value newer than the last read is not life. +3. No 1 A ping-pong on an amp boundary (Major). +4. The 6 A hold lasts its full `ev_pause_min` from the spare's drop, 1 and 3 + phases (Major); a meter as Home Assistant publishes it (`ha_signed`, on a + change only) does not pause the car while it is healthy (Minors). +5. SPIKE-06: the race as the formal replay plays it; C12 (a refusal on a + paused car no longer holds Solar at 0 A); C13 (a capped car is not stuck). +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import math +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from datetime import datetime, timezone # noqa: E402 + +from app import carmode, chargers as CH # noqa: E402 +import ev20_sun as S # noqa: E402 +from chargersim import SimCharger # noqa: E402 +from ev20_kit import (LOG, TSim, act, check, const, cur_writes, # noqa: E402 + nevers, report, + step_fn) +from named_absence import nth, present # noqa: E402 + +UTC = datetime(2026, 11, 23, 12, 0, tzinfo=timezone.utc) +DAY = "2026-11-23" +TS = 1000.0 + + +def rd(power=2300.0, allowed=10.0, e=4004.85, state="C"): + return CH.ChargerReading( + available=True, state=state, connected=True, + charging=state in ("C", "D"), power_w=power, energy_kwh=e, + current_a=(power / 230.0, 0.0, 0.0), setpoint_a=allowed, + allowed_a=allowed, phases_allowed=1) + + +# =========================================================================== # +print("1. THE STUCK CHECK'S ARMING (rig Critical, EV-32)") +# =========================================================================== # +# The race as the rig had it: begin_write (the send), the cycle's read lands +# while the write waits (it already shows the new 0 A and the paused car), +# then note_write; the car stays paused (constant 0 W, 0 A) for two minutes. +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(e=4004.85 + i / 1000.0), TS + i, UTC, DAY) +tr.begin_write() +tr.observe(rd(power=0.0, allowed=0.0, state="B"), TS + 1, UTC, DAY) +tr.end_write(TS + 2) +tr.note_write(TS, 10.0, 0.0, True) +stuck_at = None +for i in range(2, 130): + tr.observe(rd(power=0.0, allowed=0.0, state="B"), TS + i, UTC, DAY) + if stuck_at is None and tr.stuck(TS + i): + stuck_at = i +check(f"race (EV-32): an accepted 10 -> 0 A write whose post-write reading " + f"arrived while it waited; the car then stays paused at constant " + f"values: never 'stuck' (stuck at +{stuck_at})", stuck_at is None) +# The same with an accepted non-zero write (EV-32's "after an accepted current +# write"): a car that then draws steadily is not stuck either. +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(power=0.0, allowed=0.0, state="B"), TS + i, UTC, DAY) +tr.begin_write() +tr.observe(rd(power=1840.0, allowed=8.0), TS + 1, UTC, DAY) +tr.end_write(TS + 2) +tr.note_write(TS, 0.0, 8.0, True) +st2 = [i for i in range(2, 130) + if (tr.observe(rd(power=1840.0, allowed=8.0), TS + i, UTC, DAY) + or tr.stuck(TS + i))] +check(f"race (EV-32): an accepted 0 -> 8 A write, the car draws a steady " + f"1840 W: never 'stuck' ({st2[:1]})", not st2) +# A reading that really froze before the send still is stuck at +60 s (the +# EV-04 rule kept): the write was accepted, but every reading after it is the +# one from before the send. +tr = CH.CarTracker() +for i in range(-5, 1): + tr.observe(rd(), TS + i, UTC, DAY) +tr.begin_write() +tr.end_write(TS + 1) +tr.note_write(TS, 10.0, 0.0, True) +st3 = None +for i in range(1, 80): + tr.observe(rd(), TS + i, UTC, DAY) + if st3 is None and tr.stuck(TS + i): + st3 = i +check(f"kept: readings frozen at the value from before the send are stuck at " + f"+60 s (at +{st3})", st3 == 60) + +# =========================================================================== # +print("\n2. EV-36: A FROZEN VALUE NEWER THAN THE LAST READ IS NOT LIFE") +# =========================================================================== # +# The cycle last read energy 4004.85 kWh at TS-1. The charger froze a moment +# later at 4004.87 (a newer value); the refused write's polls and every later +# read show that same frozen value. +tr = CH.CarTracker() +for i in range(-5, 0): + tr.observe(rd(e=4004.85), TS + i, UTC, DAY) +tr.begin_write() +polls = [(TS + s, rd(e=4004.87)) for s in range(1, 11)] +tr.end_write(TS + 10) +tr.note_write(TS, 16.0, 10.0, False, polls) +st36 = None +for i in range(11, 130): + tr.observe(rd(e=4004.87), TS + i, UTC, DAY) + if st36 is None and tr.stuck(TS + i): + st36 = i +check(f"EV-36: a refused write; the first sample after the send carries a " + f"newer value that then never moves: no life, so it arms at the send " + f"and is stuck at +60 s (at +{st36})", st36 == 60) +tr = CH.CarTracker() +for i in range(-5, 0): + tr.observe(rd(e=4004.85), TS + i, UTC, DAY) +tr.begin_write() +polls = [(TS + s, rd(e=4004.85 + s / 1000.0)) for s in range(1, 11)] +tr.end_write(TS + 10) +tr.note_write(TS, 16.0, 10.0, False, polls) +for i in range(11, 130): + tr.observe(rd(e=4004.86 + i / 1000.0), TS + i, UTC, DAY) +check("EV-36 guard: a refused write on a charger whose energy keeps moving " + "is not stuck (life in the second sample and after)", + tr.armed_at is None and not tr.stuck(TS + 129)) + +# =========================================================================== # +print("\n3. THE REAL CONTROLLER IN THE RIG'S INTERLEAVE (beside)") +# =========================================================================== # + + +def jit(f): + """A few watts of noise on a plant figure, as the rig's plant had, so a + meter published on change does change (every 7 s here).""" + return lambda t: f(t) + (2.0 if int(t // 7) % 2 else -2.0) + + +def rig_run(**kw): + sim = kw.pop("sim", None) or SimCharger(setpoint_a=kw.pop("setpoint", 0)) + sim.lag_s = 1.0 + return S.drive(kw.pop("house"), kw.pop("sun"), beside=True, sim=sim, + **kw) + + +# The rig's repro, EV20-solar-steady-no-false-stuck: the charger's own 10 A, +# the car charging; Solar, Car first, sun 7.9 kW, house 0.9 kW (mock-up +# scenario 2): 0 A first (D2), then the start rule, then charging to the end. +for mc in (False, True): + tag = "meter on change" if mc else "meter every second" + r = rig_run(house=jit(const(900.0)), sun=const(7900.0), dur=1800, + first="car", + socs={"a": 71.0, "b": 100.0}, + sim=SimCharger(setpoint_a=10), meter_change=mc) + w = cur_writes(r) + stuck = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] + check(f"scenario EV20-solar-steady-no-false-stuck [{tag}]: 0 A first, the " + f"start within 125 s, charging to the end, never stuck ({w[:4]}, " + f"stuck {stuck[:1]})", + present(nth(w, 0)) and nth(w, 0)[1] == 0.0 + and present(nth(w, 1)) and nth(w, 1)[1] > 0.0 + and nth(w, 1)[0] - nth(w, 0)[0] <= 125 and not stuck + and r["sim"].power_w > 3000.0) + nevers(r, f"scenario EV20-solar-steady-no-false-stuck [{tag}]") +# E2 of the scenario: a cloud pause (0 A), then the sun back: the car +# restarts 120 s after the sun returns; no stuck verdict holds it at 0 A. +r = rig_run(house=const(500.0), sun=step_fn((400, 900.0), (1000, 2900.0), + base=2900.0), + dur=1400, first="car", socs={"a": 100.0, "b": 100.0}) +w = cur_writes(r) +stuck = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] +late = [(t, a) for t, a, _ in w if t >= 1000] +check(f"scenario E2: after the cloud pause the car restarts 120 s after the " + f"sun returns, never held by a stuck verdict ({w}, stuck {stuck[:1]})", + not stuck and present(nth(late, 0)) and nth(late, 0)[1] > 0.0 + and 1119 <= nth(late, 0)[0] <= 1125) + +# =========================================================================== # +print("\n4. NO PING-PONG ON AN AMP BOUNDARY (rig Major)") +# =========================================================================== # +for ph, sun_w, amps in ((1, 2900.0, 10.0), (3, 600.0 + 6900.0, 10.0)): + def dither(t, base=sun_w): + return base + (6.0 if int(t // 17) % 2 else -6.0) + opts = {"ev_phases": "1" if ph == 1 else "3"} + r = S.drive(const(500.0), dither, dur=1500, first="car", + socs={"a": 100.0, "b": 100.0}, opts=opts, phases=ph) + w = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0] + changes = len(w) - 1 + check(f"[{ph} phase] the spare dithers +-6 W around the {amps:.0f} A " + f"boundary for 1500 s: at most one change after the start " + f"({changes} changes: {w[:6]})", present(nth(w, 0)) and changes <= 1) + nevers(r, f"ping-pong [{ph} phase]") +# A real rise after a step down still raises the current. +r = S.drive(const(500.0), step_fn((300, 2890.0), (600, 3300.0), base=2900.0), + dur=900, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_phases": "1"}) +w = [(t, a) for t, a, _ in cur_writes(r)] +check(f"guard: 10 A, down to 9 A on a 10 W dip, then a real rise to 11.3 A " + f"worth: 11 A is written ({w})", + [a for _, a in w] == [10.0, 9.0, 11.0]) + +# =========================================================================== # +print("\n5. THE HOLD LASTS ITS TIME; A HEALTHY ha_signed METER (rig Major, Minors)") +# =========================================================================== # +for mode, kw in (("every second", {}), ("rig interleave, meter on change", + {"beside": True, + "meter_change": True})): + sim = SimCharger(setpoint_a=0) + if kw.get("beside"): + sim.lag_s = 1.0 + # 1 phase: a 290 s cloud never pauses; a 400 s one pauses at 300 s. + r = S.drive(jit(const(500.0)), lambda t: 900.0 if 400 <= t < 690 + or 1200 <= t < 1600 else 2900.0, dur=1800, first="car", + socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, + sim=sim, **kw) + w = [(t, a) for t, a, _ in cur_writes(r)] + zeros = [t for t, a in w if a == 0.0] + check(f"[1 phase, {mode}] a 290 s cloud: the 6 A hold, no pause; a 400 s " + f"cloud: 0 A at 300 s from the drop, +2 ({w})", + not [t for t in zeros if 400 <= t < 700] + and [t for t in zeros if 1200 <= t < 1600][:1] + and 1499 <= nth([t for t in zeros if 1200 <= t < 1600], 0) <= 1502) + nevers(r, f"hold [1 phase, {mode}]") + sim = SimCharger(setpoint_a=0) + if kw.get("beside"): + sim.lag_s = 1.0 + # 3 phases: 7 A, then the spare under 6 A worth from 600 s: 6 A, 0 A at + # 900 s (+2), not before. + r = S.drive(jit(const(500.0)), step_fn((600, 600.0 + 2500.0), + base=600.0 + 6000.0), + dur=1100, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_phases": "3"}, phases=3, sim=sim, **kw) + w = [(t, a) for t, a, _ in cur_writes(r)] + zeros = [t for t, a in w if a == 0.0 and t > 200] + check(f"[3 phases, {mode}] the hold from 600 s: 6 A, then 0 A at 900 s " + f"(+2), not before ({w})", + present(nth(zeros, 0)) and 899 <= nth(zeros, 0) <= 902 + and 6.0 in [a for t, a in w if 600 <= t < 900]) + nevers(r, f"hold [3 phases, {mode}]") + +# A healthy meter on ha_signed: Home Assistant publishes it only on a change, +# so at a flat load the value may stand longer than stale_input_s (15 s); here +# 25 s at a time, under the source's meter_max_age_s (30 s). The spare stays +# known and the car is not paused. +r = S.drive(const(500.0), lambda t: 2900.0 + (15.0 if int(t // 25) % 2 + else 0.0), + dur=1200, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_phases": "1"}, meter_change=True) +w = cur_writes(r) +unk = [x["t"] for x in r["trace"] if x["spare"] is None and x["t"] > 5] +check(f"ha_signed, a healthy meter whose value stands 25 s at a time: the " + f"spare stays known, the car starts by the start rule and is never " + f"paused ({w}, unknown {unk[:3]})", + not [x for x in w if x[1] == 0.0 and x[0] > 5] and not unk + and present(nth(w, 0)) and nth(w, 0)[1] > 0.0 + and nth(w, 0)[0] <= 125) +# A silent meter on ha_signed: unknown from the source's own meter_max_age_s +# (30 s), then 0 A after ev_pause_min (300 s). +r = S.drive(const(500.0), const(2900.0), dur=900, first="car", + socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"}, + events={300: lambda p, c: setattr(p, "meter_on", False)}) +w = cur_writes(r) +z = [t for t, a, _ in w if a == 0.0] +check(f"ha_signed, the meter silent from 300 s: 0 A at 30 + 300 s (+2), " + f"never from a stale value ({w})", + present(nth(z, 0)) and 629 <= nth(z, 0) <= 633 + and [a for t, a, _ in w if 300 <= t < 629] == []) + +# =========================================================================== # +print("\n6. SPIKE-06: C12, C13 AND THE RACE AS THE FORMAL REPLAY PLAYS IT") +# =========================================================================== # + + +def race_hook(p, c): + """The race exactly as production interleaves it (SPIKE-06 replay): the + driver's read-back wait runs the next cycle's charger read, so the tracker + files the post-write reading before `note_write`.""" + orig = c.charger._sleep + + async def sleep(s): + await orig(s) + await c._read_charger(p.clock[0]) + c.charger._sleep = sleep + + +def stuck_ts(r): + return [x["t"] for x in r["trace"] if x["fault"] == "stuck"] + + +# C10/C11 replays (ctl A: the charger's power-on 10 A, Solar's D2 0 A; ctl B: +# Solar's 10 A start on a charging car), each with the race. +sim = SimCharger(setpoint_a=10) +sim.lag_s = 1.0 +r = S.drive(const(500.0), const(2900.0), dur=900, first="car", + socs={"a": 100.0, "b": 100.0}, sim=sim, events={0: race_hook}) +w = cur_writes(r) +check(f"race replay ctl A: D2 0 A, then the start at 120 s, never stuck " + f"({w[:3]}, stuck {stuck_ts(r)[:1]}, tracker {r['c'].car.stuck_now})", + present(nth(w, 1)) and nth(w, 0)[1] == 0.0 and nth(w, 1)[1] > 0.0 + and 119 <= nth(w, 1)[0] <= 125 and not stuck_ts(r) + and not r["c"].car.stuck_now) +nevers(r, "race replay ctl A") +sim = SimCharger(setpoint_a=0) +sim.lag_s = 1.0 +r = S.drive(const(500.0), const(2900.0), dur=900, first="car", + socs={"a": 100.0, "b": 100.0}, sim=sim, events={0: race_hook}) +w = cur_writes(r) +check(f"race replay ctl B: one start write, the car charges to the end, " + f"never stuck ({w[:3]}, stuck {stuck_ts(r)[:1]})", + len(w) == 1 and w[0][1] > 0.0 and not stuck_ts(r) + and not r["c"].car.stuck_now and r["sim"].power_w > 2000.0) +nevers(r, "race replay ctl B") + +# C12: a paused (full) car, a live charger ignores Solar's start write once. +# No life (0 W, flat energy), so the refusal arms and is stuck 60 s later; +# Solar's 0 A then stands. Option 2: the stuck verdict no longer holds the +# car at 0 A; the start rule writes again within 2 min, the reading moves. +for race in (False, True): + sim = TSim(setpoint_a=0, windows=[(100.0, 135.0, "ignore")]) + sim.car_full() + if race: + sim.lag_s = 1.0 + r = S.drive(const(500.0), const(2900.0), dur=900, first="car", + socs={"a": 100.0, "b": 100.0}, sim=sim, + events={0: race_hook} if race else None) + w = cur_writes(r) + tr = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] + st = r["c"].car + z = [t for t, a, _ in w if a == 0.0 and t > 125] + nz = [t for t, a, _ in w if a > 0.0 and present(nth(z, 0)) and t > z[0]] + check(f"C12 [race={race}] a live charger ignores one start write on a " + f"paused car: after Solar's 0 A the start rule writes again within " + f"125 s and the stuck verdict clears (writes {w[:6]}, 0 A at " + f"{z[:1]}, again at {nz[:1]}, stuck now {st.stuck_now})", + present(nth(z, 0)) and present(nth(nz, 0)) + and nth(nz, 0) - nth(z, 0) <= 125 and not st.stuck_now + and r["trace"][-1]["fault"] is None) + nevers(r, f"C12 [race={race}]") + +# C12's cap and backoff (PM decision): a charger whose reading is really +# frozen (at 300 s, with the values it will show when it comes back). Solar's +# own 0 A stands, so the start rule runs; each start is not taken and the 0 A +# follows. At most MAX_TRIES starts under one verdict, then ONE +# CHARGER_REFUSED; then one more start 15 min later, then one every 30 min +# (each by the start rule), never the 72 s flapping. +def frozen_run(dur, events=None): + n0 = LOG.mark() + ev = {300: lambda p, c: p.ch.freeze()} + ev.update(events or {}) + r = S.drive(const(600.0), lambda t: 600.0 + (1000.0 if 200 <= t < 330 + else 2300.0 if t < 200 + else 6000.0), + dur=dur, first="car", socs={"a": 100.0, "b": 100.0}, + opts={"ev_pause_min": 1, "ev_start_min": 1}, events=ev) + r["_log"] = n0 + st = [x["t"] for x in r["trace"] if x["fault"] == "stuck"] + t0 = nth(st, 0) if st else 1e9 + w = cur_writes(r) + starts = [t for t, a, _ in w if a > 0.0 and t >= t0] + warn = [m for m in LOG.since(n0, "WARNING") if "CHARGER_REFUSED" in m] + return r, w, starts, warn + + +r, w, starts, warn = frozen_run(4000) +first3, later = starts[:3], starts[3:] +t3 = nth(first3, 2) +gaps = [b - a for a, b in zip(later, later[1:])] +check(f"cap: a frozen charger: 3 starts under the verdict ({first3}), then " + f"one CHARGER_REFUSED ({len(warn)})", + len(first3) == carmode.MAX_TRIES and len(warn) == 1 + and all(b - a < 120 for a, b in zip(first3, first3[1:]))) +check(f"backoff: one more start 15 min after the 3rd (+ the start rule), " + f"then one every 30 min (+ the start rule): {later} (gaps {gaps})", + present(t3) and len(later) == 2 + and 900 <= nth(later, 0) - t3 <= 900 + 80 + and all(1800 <= g <= 1800 + 80 for g in gaps)) +nevers(r, "cap and backoff") + +# Recovery: the reading comes back at 1200 s with the values it froze with, +# so nothing moves by itself; the next backoff start is taken, the reading +# follows it, the episode ends (warning cleared) and the car charges. +r, w, starts, warn = frozen_run(2400, {1200: lambda p, c: p.ch.freeze(False)}) +t3 = nth(starts, 2) +rec = [t for t in starts if t > 1200] +check(f"recovery: the fault clears at 1200 s; the next backoff start " + f"({rec[:1]}, 15 min after the 3rd at {t3}) is taken and the car " + f"charges to the end, warning cleared, not stuck", + present(nth(rec, 0)) and present(t3) + and 900 <= nth(rec, 0) - t3 <= 980 + and r["sim"].power_w > 1000.0 and not r["c"].car.stuck_now + and not r["c"].car_solar.gave_up) +nevers(r, "recovery") + +# A press of Solar during the backoff starts the episode afresh: a start by +# the start rule after the press, not 15 min later. +r, w, starts, warn = frozen_run(1400, {1000: act("car_mode", "solar")}) +after = [t for t in starts if t >= 1000] +check(f"press: Solar pressed at 1000 s during the backoff: a start by the " + f"start rule after the press ({after[:1]})", + present(nth(after, 0)) and nth(after, 0) <= 1000 + 75) + +# The episode ends on Off, Manual and shadow: counter, wait and warning +# cleared (read 5 s after the switch). +for name, fn in (("Off", act("car_mode", "off")), + ("Manual", act("car_mode", "manual")), + ("shadow", lambda p, c: c.o.__setitem__("shadow_mode", + "on"))): + seen = {} + + def look(p, c, seen=seen): + sw = c.car_solar + seen.update(starts=sw.stuck_starts, gave_up=sw.gave_up, + wait=getattr(sw, "stuck_wait", None), + warned=getattr(sw, "stuck_warned", None)) + before = {} + + def look0(p, c, before=before): + before.update(starts=c.car_solar.stuck_starts, + gave_up=c.car_solar.gave_up) + r, w, starts, warn = frozen_run(900, {790: look0, 800: fn, 805: look}) + check(f"episode end on {name}: before {before}, after {seen}", + before.get("starts") == carmode.MAX_TRIES and before.get("gave_up") + and seen.get("starts") == 0 and seen.get("gave_up") is False + and seen.get("wait") is None and seen.get("warned") is False) + +# C14: Manual's refused writes leave a stuck verdict on a paused, live car, +# then the user presses Solar. No current of Solar's own may stand, so the +# verdict does not hold Solar: its 0 A first (over Manual's 6 A), then the +# start rule with spare sun; the start moves the reading, the verdict clears. +for name, win, t_s in (("Manual's 12 A refused 3 times, Solar at 400 s", + (99.5, 250.0), 400),): + sim = TSim(setpoint_a=0, windows=[(win[0], win[1], "ignore")]) + sim.car_full() + seen = {} + r = S.drive(const(500.0), const(2900.0), dur=1200, first="car", + socs={"a": 100.0, "b": 100.0}, sim=sim, mode="manual", + events={100: act("car_current", 12), + t_s - 1: lambda p, c: seen.update( + armed=c.car.armed_at, stuck=c.car.stuck_now), + t_s: act("car_mode", "solar")}) + w = cur_writes(r) + nz = [(t, a) for t, a, _ in w if a > 0.0] + check(f"C14 [{name}]: the check armed by Manual's refusal before the " + f"press ({seen})", seen.get("armed") is not None) + check(f"C14 [{name}]: Solar writes 0 A first, then a start within the " + f"start rule, and the verdict clears ({w[:4]}, stuck now " + f"{r['c'].car.stuck_now})", + present(nth(w, 0)) and nth(w, 0)[1] == 0.0 + and nth(w, 0)[0] <= t_s + 2 and present(nth(nz, 0)) + and nth(nz, 0)[0] <= t_s + 125 and not r["c"].car.stuck_now + and r["trace"][-1]["fault"] is None) + nevers(r, f"C14 [{name}]") + +# C13: a car that draws less than allowed (an on-board limit of 1380 W, or a +# taper). Tracker level: a raise 6 -> 10 A, the post-write reading filed +# during the wait (race) or not: never stuck. +for race in (True, False): + tr = CH.CarTracker() + tr.observe(rd(power=1380.0, allowed=6.0), TS, UTC, DAY) + tr.begin_write() + if race: + tr.observe(rd(power=1380.0, allowed=10.0), TS + 1, UTC, DAY) + tr.note_write(TS, 6.0, 10.0, True) + tr.end_write(TS + 1.5) + first = None + for i in range(2, 301): + tr.observe(rd(power=1380.0, allowed=10.0), TS + i, UTC, DAY) + if first is None and tr.stuck(TS + i): + first = i + check(f"C13 tracker [race={race}] a capped car (1380 W), raised 6 -> 10 " + f"A: never stuck (first at {first})", first is None) + + +class CapSim(SimCharger): + """A car whose on-board charger draws at most `cap_w`.""" + cap_w = 1380.0 + + def target_w(self): + return min(super().target_w(), self.cap_w) + + +for race in (True, False): + sim = CapSim(setpoint_a=0) + sim.lag_s = 1.0 + r = S.drive(const(500.0), lambda t: 3600.0 if t >= 300 else 2900.0, + dur=900, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim, + events={0: race_hook} if race else None) + w = cur_writes(r) + up = [(t, a) for t, a, _ in w if t >= 300] + check(f"C13 controller [race={race}] a capped car, Solar raises the " + f"current at 300 s: never stuck, no 0 A after it ({w[:5]}, stuck " + f"{stuck_ts(r)[:1]})", + present(nth(up, 0)) and nth(up, 0)[1] > 10.0 and not stuck_ts(r) + and not [a for _, a in up if a == 0.0]) + nevers(r, f"C13 controller [race={race}]") + + +report() diff --git a/goodwe_controller/tools/ev20_sun.py b/goodwe_controller/tools/ev20_sun.py index f64623d..2d2c0bf 100644 --- a/goodwe_controller/tools/ev20_sun.py +++ b/goodwe_controller/tools/ev20_sun.py @@ -141,13 +141,18 @@ 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): + rows=False, plant_cls=None, beside=False, meter_change=False): """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 levels stand still. `finale(plant, c)` (a coroutine) runs after the last cycle, on the model clock (a shutdown, for instance); `rows=True` keeps - the ids of the amber and red rows of every cycle in the trace.""" + the ids of the amber and red rows of every cycle in the trace. + `beside=True` plays the production interleave the rig showed (EV-20 rig + 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.""" 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) @@ -205,6 +210,19 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, plant.t = clock[0] c.charger._sleep = sleep c.charger._clock = lambda: clock[0] + if beside: + gate = asyncio.Event() + + async def bsleep(_s): + gate.clear() + await gate.wait() + + async def settle(): + gate.set() + for _ in range(8): + await asyncio.sleep(0) + c.charger._sleep = bsleep + c.car_settle = settle real_dt = main_files.live.datetime class _DT(real_dt): @@ -224,7 +242,10 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, await r sim.tick(1.0) ts = t - SAMPLE_LEAD_S - if plant.meter_on and not plant.ha_down: + if plant.meter_on and not plant.ha_down and not ( + meter_change + and round(plant.grid(ts)) == round(plant.meter) + and t > t0): plant.meter = plant.grid(ts) imp, exp = split_signed(plant.meter) c.p1.submit(make_sample(