"""EV-04: the car charger's Manual mode, the first card that WRITES to a charger. `python3 -B test_ev04.py` 1. Off writes nothing (EV-03's no-write test keeps passing for Off), whatever the user sets while Off. 2. Mode, current and phases are runtime state: actions, refusals, the store, the mode after a restart. 3. Manual writes the current once per user change, read back within 10 s. 4. The clamp: nothing above min(ev_max_a, station limit, entity range) is ever sent (property-style), and a value above it is a software fault. 5. Phase changes: the safe sequence in order, one switch per 10 minutes. 6. Shadow mode and a stopped control write nothing; the card says what it would. 7. Fail states, the Manual column. 8. Another writer. 9. The peak guard's alarm path: the car you set is not a false alarm, and a stale or stuck reading never hides a real overload (real Controller, 1 s cycle, the SAFETY-81 plant plus a charger). 10. Decision 1: batteries help on and off. 11. The peak line: set by the car, and the Peak card's car line. 12. Home Assistant entities, strings, the page's /action route. 13. The simulator. Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). """ import asyncio import io import json import logging import os import random import sys from datetime import datetime, timedelta, timezone HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "tools")) from app import carmode, chargers as CH, homeview, messages, mqtt # noqa: E402 from app.main import Controller # noqa: E402 from app import freshness # noqa: E402 from chargersim import FakeHa, SimCharger # noqa: E402 fails = [] def check(name, cond): print(f" {'ok ' if cond else 'FAIL'} {name}") if not cond: fails.append(name) class _Store: def __init__(self): self.data = {} def set(self, k, v): self.data[k] = v def get(self, k, d=None): return self.data.get(k, d) def set_time(self, k, v): self.data[k] = v.isoformat() def get_time(self, k): v = self.data.get(k) return None if v is None else datetime.fromisoformat(v) class _Pub: enabled = False def __init__(self): self.values = [] def publish(self, v): self.values.append(dict(v)) def close(self): pass class _Log(logging.Handler): def __init__(self): super().__init__(logging.DEBUG) self.rec = [] def emit(self, r): self.rec.append((r.levelname, r.getMessage())) def text(self, level=None): return "\n".join(m for lv, m in self.rec if level in (None, lv)) LOG = _Log() logging.getLogger("goodwe").addHandler(LOG) logging.getLogger("goodwe").setLevel(logging.DEBUG) class Site(FakeHa): """The charger model plus a grid, a battery and a solar entity.""" def __init__(self, charger, grid=500.0, batt=0.0, pv=2000.0): super().__init__(charger, None) self.grid, self.batt, self.pv = grid, batt, pv async def limits(self, _e): return (-5000.0, 5000.0, 1.0) def _all(self): out = super()._all() for eid, val, unit in (("sensor.grid", self.grid, "W"), ("sensor.soc", 50.0, "%"), ("sensor.batt", self.batt, "W"), ("sensor.pv", self.pv, "W")): out[eid] = {"entity_id": eid, "state": str(val), "attributes": {"unit_of_measurement": unit}} return out async def number(self, entity_id, invert=False): s = self._all().get(entity_id) try: v = float(s["state"]) except (TypeError, ValueError, KeyError): return None return -v if invert else v async def set_number(self, entity_id, value): if entity_id == "number.sp": self.sets.append((entity_id, float(value))) self.batt = float(value) return True return await super().set_number(entity_id, float(value)) BASE = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid", "soc_entity": "sensor.soc", "batt_entity": "sensor.batt", "meter_source": "off", "max_w": 5000, "gain": 0.6, "slew_w": 500, "deadband_w": 15, "target_grid_w": 0, "step_w": 10, "heartbeat_s": 10, "stale_input_s": 15, "shadow_mode": "off", "peak_cap_w": 3500, "pv_entities": ["sensor.pv"]} SET = "number.wallbox_power_connector_max_current_socket_1" CAR = dict(BASE, ev_charger="alfen_ha", ev_max_a=16, ev_phases="auto", ev_current_entity=SET) CLOCK = [1000.0] freshness.monotonic = lambda: CLOCK[0] # one clock for the whole file class World: """A real Controller on the charger model, one clock for all of it.""" def __init__(self, opts=CAR, sim=None, store=None, plug=True, setpoint=10, grid=800.0, phases=1, **simkw): self.sim = sim or SimCharger(setpoint_a=setpoint, **simkw) if plug: self.sim.plug_in() self.sim.phases_allowed = phases self.site = Site(self.sim, grid=grid) self.store = store or _Store() self.t = 1000.0 CLOCK[0] = self.t self.make(opts) def make(self, opts): self.opts = dict(opts) self.c = Controller(dict(opts), self.site, self.store, _Pub(), stop=asyncio.Event()) self.c.auto = True self.c.dev_min, self.c.dev_max = -5000.0, 5000.0 self.drv = self.c.charger if hasattr(self.drv, "_sleep"): self.drv._sleep = self.sleep self.drv._clock = lambda: CLOCK[0] async def sleep(self, s): self.sim.tick(s) self.t += s CLOCK[0] = self.t async def step(self, n=1, dt=1.0): for _ in range(n): self.sim.tick(dt) self.t += dt CLOCK[0] = self.t await self.c.read_inputs(now_mono=self.t) await self.c.cycle() await self.c.car_settle() async def step_race(self, n=1, dt=1.0): """The production order: the writer task can finish AFTER the cycle's read and BEFORE that cycle's kick (read -> task settles -> cycle), so the step that follows sees a reading older than the write.""" for _ in range(n): self.sim.tick(dt) self.t += dt CLOCK[0] = self.t await self.c.read_inputs(now_mono=self.t) await self.c.car_settle() await self.c.cycle() async def act(self, what, value): return await self.c.handle_action(what, value=value) def writes(self, what=None): return self.sim.writes(what) def rows(self): return {r["id"]: r for r in self.c.checks()} def run(coro): return asyncio.run(coro) # =========================================================================== # print("1. OFF WRITES NOTHING") # =========================================================================== # async def part1(): w = World() await w.step(5) await w.act("car_current", 14) # the user sets values while Off await w.act("car_phases", 3) await w.step(60) return w w1 = run(part1()) check("PRECONDITION: the charger was read and the car is charging", w1.c.car.status(CLOCK[0]) == "charging" and w1.c.car.reading.power_w > 1000) check("PRECONDITION: the mode is Off (the default)", w1.c.car_mode == "off") check("Off: no number write and no service call names a charger entity, " "although the user set 14 A and 3 phases while Off", w1.site.charger_writes() == [] and w1.sim.log == []) check("Off: the driver was never asked to send anything", w1.drv.sent == []) check("Off: the model's own setpoint is where it was (10 A, 1 phase)", w1.sim.setpoint_a == 10 and w1.sim.phases_allowed == 1) check("the user's values were kept for when Manual is chosen", w1.c.car_a == 14 and w1.c.car_n == 3) # =========================================================================== # print("\n2. MODE, CURRENT, PHASES: RUNTIME STATE") # =========================================================================== # async def part2(): w = World() out = {} out["manual"] = await w.act("car_mode", "manual") out["bad_mode"] = await w.act("car_mode", "bogus") # EV-05 accepts Solar out["night"] = await w.act("car_mode", "night") out["a12"] = await w.act("car_current", 12) out["a5"] = await w.act("car_current", 5) out["a17"] = await w.act("car_current", 17) # above ev_max_a out["a_text"] = await w.act("car_current", "x") out["a_bool"] = await w.act("car_current", True) out["a_nan"] = await w.act("car_current", float("nan")) out["a_half"] = await w.act("car_current", 12.5) out["n2"] = await w.act("car_phases", 2) out["n3"] = await w.act("car_phases", 3) return w, out w2, o2 = run(part2()) check("Manual is chosen at once, no restart", o2["manual"] == { "mode": "manual", "current": 6.0, "phases": 1} and w2.c.car_mode == "manual" or w2.c.car_mode == "manual") check("Night (EV-02) and an unknown mode are not accepted", "error" in o2["bad_mode"] and "error" in o2["night"] and w2.c.car_mode == "manual") check("a current between 6 A and the clamp is accepted and stored", "error" not in o2["a12"] and w2.store.data.get("car_current") == 12.0) check("5 A, 17 A (above ev_max_a 16), text, a bool, NaN and 12.5 are refused", all("error" in o2[k] for k in ("a5", "a17", "a_text", "a_bool", "a_nan", "a_half"))) check("the refused values did not change the stored current", w2.c.car_a == 12.0 and w2.store.data["car_current"] == 12.0) check("phases: 2 refused, 3 accepted and stored", "error" in o2["n2"] and w2.store.data.get("car_phases") == 3) check("the three live in the store (like OPT-11's modes)", w2.store.data.get("car_mode") == "manual") check("every refusal is a plain sentence", all(isinstance(o2[k].get("error"), str) for k in ("bad_mode", "a5"))) async def part2b(): out = {} # no charger at all: refused, nothing stored w = World(BASE) out["nocharger"] = await w.act("car_mode", "manual") out["stored"] = dict(w.store.data) # one-phase-only installation w = World(dict(CAR, ev_phases="1")) out["n3"] = await w.act("car_phases", 3) out["n1"] = await w.act("car_phases", 1) return out o2b = run(part2b()) check("with no charger the actions are refused and nothing is stored", "error" in o2b["nocharger"] and "car_mode" not in o2b["stored"]) check("ev_phases 1: 3 phases cannot be chosen, 1 can", "error" in o2b["n3"] and "error" not in o2b["n1"]) async def part2c(): out = {} for start, stored in (("keep", "manual"), ("off", "manual"), ("keep", None), ("keep", "night")): st = _Store() if stored: st.data["car_mode"] = stored w = World(dict(CAR, ev_mode_start=start), store=st) out[(start, stored)] = (w.c.car_mode, st.data.get("car_mode")) return out o2c = run(part2c()) check("ev_mode_start keep: a restart keeps Manual", o2c[("keep", "manual")][0] == "manual") check("ev_mode_start off: a restart starts in Off and the store says so", o2c[("off", "manual")] == ("off", "off")) check("no stored mode, or one this build does not know, is Off", o2c[("keep", None)][0] == "off" and o2c[("keep", "night")][0] == "off") # =========================================================================== # print("\n3. MANUAL WRITES THE CURRENT ONCE PER USER CHANGE") # =========================================================================== # async def part3(): w = World(setpoint=10) await w.step(3) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(30) n1 = len(w.writes("current")) sent1 = list(w.drv.sent) await w.step(60) # nothing asked: nothing written n2 = len(w.writes("current")) await w.act("car_current", 8) await w.step(10) n3 = len(w.writes("current")) await w.act("car_current", 8) # the same value again await w.step(10) n4 = len(w.writes("current")) return w, n1, sent1, n2, n3, n4 w3, n1, sent1, n2, n3, n4 = run(part3()) check("choosing Manual at 12 A writes 12 A once", n1 == 1 and sent1 == [12.0]) check("the charger took it: setpoint and read-back are 12 A (then 8 A)", w3.sim.setpoint_a == 8 and w3.sim.readback_a == 8) check("60 s with nothing asked: no further write", n2 == 1) check("a new value (8 A) is one more write", n3 == 2) check("the same value again is not written (the charger already has it)", n4 == 2) check("the add-on's own write is not 'another writer' in the page", "charger_writer" not in w3.rows() and "charger_other" not in w3.rows()) def spy_on(drv): """Every `write_current` of this driver and what it said.""" res, real = [], drv.write_current async def spy(a): r = await real(a) res.append((a, r)) return r drv.write_current = spy return res async def part3b(): out = {} # the charger takes 4 s to show it: the write is still taken (< 10 s) w = World(setpoint=10) w.sim.lag_s = 4.0 await w.step(2) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(20) out["lag4"] = (w.writes("current"), w.sim.readback_a, w.c.car_writer.last_a, w.c.car_writer.gave_up) # the charger takes 14 s: the write is NOT taken in 10 s, and is not # retried at once w = World(setpoint=10) w.sim.lag_s = 14.0 await w.step(2) res = spy_on(w.drv) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(40) out["lag14"] = (list(res), w.sim.readback_a, w.c.car_writer.gave_up, w.c.car_writer.fails, "charger_other" in w.rows()) # the charger ignores it: tried 3 times, a minute apart, then it waits w = World(setpoint=10) await w.step(2) w.sim.refuse = "ignore" res = spy_on(w.drv) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(5) out["ignore5"] = (list(res), w.c.car_writer.fails) await w.step(200) out["ignore"] = (list(res), w.c.car_writer.gave_up, w.rows()) await w.step(600) out["ignore_later"] = len(res) w.sim.refuse = None await w.act("car_current", 13) await w.step(20) out["after_user"] = (w.sim.readback_a, w.c.car_writer.gave_up) # Home Assistant refuses the call outright w = World(setpoint=10) await w.step(2) w.sim.refuse = "error" res = spy_on(w.drv) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(10) out["error"] = list(res) return out o3b = run(part3b()) check("a charger that shows the change 4 s late still took it (read back " "within 10 s)", len(o3b["lag4"][0]) == 1 and o3b["lag4"][1] == 12 and o3b["lag4"][2] == 12 and not o3b["lag4"][3]) check("a charger that shows it 14 s late did NOT take it: write_current " "says False, and the add-on does not write again at once", o3b["lag14"][0] == [(12.0, False)] and o3b["lag14"][2] is False) check("...and when the late read-back arrives it is adopted, with no 'another " "writer'", o3b["lag14"][1] == 12 and not o3b["lag14"][4]) check("a charger that ignores it: 3 tries a minute apart, then it stops", [r for _a, r in o3b["ignore"][0]] == [False, False, False] and o3b["ignore"][1] is True and o3b["ignore_later"] == 3 and o3b["ignore5"][0] == [(12.0, False)]) check("...and says so: one amber row 'Charger did not take it'", o3b["ignore"][2].get("charger_refused", {}).get("warn") is True and o3b["ignore"][2]["charger_refused"]["ok"] is False) check("...and a new value from the user is tried again (and taken)", o3b["after_user"] == (13.0, False)) check("Home Assistant refusing the call is a False, not an exception", o3b["error"] and all(r is False for _a, r in o3b["error"])) # =========================================================================== # print("\n4. THE CLAMP: NOTHING ABOVE min(ev_max_a, station, entity range) IS SENT") # =========================================================================== # def fast(drv, sim): """A driver whose 10 s wait for a read-back costs no real time.""" clock = [0.0] async def sl(s): clock[0] += s sim.tick(s) drv._sleep, drv._clock = sl, (lambda: clock[0]) return drv async def clamp_prop(): rnd = random.Random(4) bad, faults_ok, n = [], 0, 0 for _ in range(80): station = rnd.choice([6, 10, 13, 16, 20, 25, 32, 40]) max_a = rnd.choice([6, 8, 10, 16, 20, 32, 40]) sim = SimCharger(station_a=station, setpoint_a=min(6, station)) sim.plug_in() ha = FakeHa(sim) drv = fast(CH.AlfenHaDriver(SET, max_a).bind(ha), sim) clamp = min(max_a, station, 40) for a in (0, 6, clamp - 1, clamp, clamp + 0.1, clamp + 1, 40, 41, 99, -1, float("nan"), rnd.uniform(0, 80)): before = len(ha.sets) ok = await drv.write_current(a) n += 1 sent = [v for _e, v in ha.sets[before:]] if any(v > clamp + 1e-9 for v in sent): bad.append((station, max_a, a, sent)) over = a != a or a < 0 or a > clamp if over: if sent or ok: bad.append(("over was sent or said True", station, max_a, a, sent, ok)) else: faults_ok += 1 return bad, faults_ok, n bad4, faults4, n4c = run(clamp_prop()) check(f"property: over {n4c} writes with random station limits, ev_max_a and " f"values, nothing above the clamp is ever sent ({bad4[:2]})", not bad4) check(f"...and every value above the clamp (or negative, or NaN) is a False " f"and a fault ({faults4} of them)", faults4 > 400) async def clamp_log(): sim = SimCharger(station_a=16) sim.plug_in() ha = FakeHa(sim) drv = fast(CH.AlfenHaDriver(SET, 16).bind(ha), sim) LOG.rec.clear() r = await drv.write_current(17) return r, ha.sets, LOG.text("ERROR"), drv.clamp_faults r4, sets4, log4, faults = run(clamp_log()) check("17 A against 16 A: not sent, False, and logged as a software fault with " "its code, at ERROR", r4 is False and sets4 == [] and "CHARGER_CLAMP" in log4 and "Software fault" in log4) check("...and the fault is on the driver for the page and the checks", faults == [(17.0, 16.0)]) async def clamp_world(): # the station limit falls to 10 A after the user set 16 A: the writer never # asks for more than the charger reports w = World(setpoint=6) await w.step(3) await w.act("car_mode", "manual") await w.act("car_current", 16) await w.step(10) first = w.sim.readback_a w.sim.station_a = 10.0 await w.act("car_current", 16) await w.step(10) return w, first w4, first4 = run(clamp_world()) check("the user's 16 A is written at 16 A while the station limit is 16 A", first4 == 16) check("the station limit falling to 10 A: the next write is 10 A, never 16 A", w4.sim.readback_a == 10 and w4.drv.sent[-1] == 10.0 and max(v for _e, v in w4.site.sets if "wallbox" in _e) <= 16) _s40 = SimCharger(station_a=40) check("the entity's own range (0-40 A) bounds a write too", run(fast(CH.AlfenHaDriver(SET, 40).bind(FakeHa(_s40)), _s40 ).write_current(41)) is False) # =========================================================================== # print("\n5. PHASE CHANGES: THE SAFE SEQUENCE") # =========================================================================== # async def phase_story(**simkw): w = World(setpoint=10, phases=1, **simkw) await w.step(8) await w.act("car_mode", "manual") await w.act("car_current", 10) await w.step(5) n0 = len(w.writes()) t0 = w.sim.t await w.act("car_phases", 3) await w.step(45) return w, n0, t0 w5, n05, t05 = run(phase_story()) seq5 = w5.writes()[n05:] check("the sequence is exactly 0 A, phases 3, then the current again " f"({[(x[1], x[2]) for x in seq5]})", [(x[1], x[2]) for x in seq5] == [("current", 0.0), ("phases", 3), ("current", 10.0)]) check("the phases were selected only with the car paused: under 100 W " f"({seq5[1][3]:.0f} W) and the setpoint at 0 A ({seq5[1][4]})", seq5[1][3] < 100 and seq5[1][4] == 0.0) check("the current was written again 10 s or more after the phases " f"({seq5[2][0] - seq5[1][0]:.0f} s)", seq5[2][0] - seq5[1][0] >= 10.0) check("afterwards the charger is at 10 A on 3 phases and the car draws 3 phases", w5.sim.readback_a == 10 and w5.sim.phases_allowed == 3 and w5.sim.power_w > 6000) check("the phases were written exactly once", len(w5.writes("phases")) == 1) async def phase_gap(): w, n0, _t = await phase_story() await w.act("car_phases", 1) # one minute later: too soon await w.step(120) soon = len(w.writes("phases")) why = homeview.car_block(w.c, datetime.now(timezone.utc))["why"] blocked = w.c.car_writer.blocked await w.step(500) # now more than 10 minutes after later = len(w.writes("phases")) return soon, why, blocked, later, w soon5, why5, blocked5, later5, w5g = run(phase_gap()) check("a second phase change a minute later waits (one per 10 minutes)", soon5 == 1 and blocked5) check("...and the card says it waits", "10 minutes" in why5) check("...and it goes through once 10 minutes have passed, by the same " "sequence", later5 == 2 and w5g.sim.phases_allowed == 1 and [x[1] for x in w5g.writes()][-3:] == ["current", "phases", "current"]) async def slow_stop(): # the car takes 40 s to stop drawing: the add-on waits at most 20 s w = World(setpoint=10, phases=1) w.sim.ramp_w_s = 50.0 w.sim.stop_delay_s = 40.0 await w.step(60) await w.act("car_mode", "manual") await w.act("car_current", 10) await w.step(3) n0 = len(w.writes()) await w.act("car_phases", 3) await w.step(60) return w, n0 w5s, n05s = run(slow_stop()) seq5s = w5s.writes()[n05s:] check("a car that is slow to stop: the phases are selected after 20 s at most " f"({seq5s[1][0] - seq5s[0][0]:.0f} s after the 0 A)", [x[1] for x in seq5s][:2] == ["current", "phases"] and 19.0 <= seq5s[1][0] - seq5s[0][0] <= 22.0) async def zero_refused(): # the charger does not take 0 A: the phases are NOT touched w = World(setpoint=10, phases=1) await w.step(8) await w.act("car_mode", "manual") await w.act("car_current", 10) await w.step(3) w.sim.refuse = "ignore" await w.act("car_phases", 3) await w.step(80) return w w5z = run(zero_refused()) check("a charger that does not take 0 A never gets the phases select", w5z.writes("phases") == [] and w5z.sim.phases_allowed == 1) async def shutdown_mid_sequence(): w = World(setpoint=10, phases=1) w.sim.ramp_w_s = 50.0 w.sim.stop_delay_s = 40.0 await w.step(60) await w.act("car_mode", "manual") await w.act("car_current", 10) await w.step(3) await w.act("car_phases", 3) await w.step(4) # 0 A is written, phases not yet mid = (w.sim.readback_a, w.c.car_writer.seq is not None) await w.c.car_shutdown() return mid, w mid5, w5x = run(shutdown_mid_sequence()) check("the add-on stops in the middle of a phase change: the car gets its " "10 A back, and nothing is left at 0 A", mid5 == (0.0, True) and w5x.sim.readback_a == 10 and w5x.c.car_writer.seq is None) async def other_writer_in_sequence(): w = World(setpoint=10, phases=1) w.sim.ramp_w_s = 50.0 w.sim.stop_delay_s = 40.0 await w.step(60) await w.act("car_mode", "manual") await w.act("car_current", 10) await w.step(3) await w.act("car_phases", 3) await w.step(3) # 0 A written, the car winding down w.sim.set_current(9) # the automation await w.step(60) return w w5o = run(other_writer_in_sequence()) check("something else raises the current while the car is being paused: the " "phases are never selected (the car was drawing), the change is given " "up and the grey row says so", w5o.writes("phases") == [] and w5o.sim.phases_allowed == 1 and w5o.sim.readback_a == 9 and w5o.c.car_writer.seq is None and "charger_other" in w5o.rows()) async def phases_in_off(): w = World(setpoint=10, phases=1) await w.step(5) await w.act("car_phases", 3) await w.step(60) return w check("in Off a phase change writes nothing either", run(phases_in_off()).writes() == []) print("\n5b. ROUND 2: THE SEQUENCE UNDER A RACING WRITER, A REFUSED SELECT, " "A MODE CHANGE, THE CLAMP") async def m1_race(lag): # the writer task finishes between a cycle's read and that cycle's kick w = World(setpoint=10, phases=1) w.sim.lag_s = lag await w.step(8) await w.act("car_mode", "manual") await w.act("car_current", 10) await w.step(10) n0 = len(w.writes()) await w.act("car_phases", 3) await w.step_race(60) seq = [(x[1], x[2]) for x in w.writes()[n0:]] await w.step_race(300) return w, seq for _lag in (0.0, 3.0): w_m1, seq_m1 = run(m1_race(_lag)) check(f"M1 (read -> writer settles -> cycle, read-back lag {_lag:.0f} s): " "the phases are selected and the car gets its 10 A back, with no " f"false 'something else changed the charger' ({seq_m1})", seq_m1 == [("current", 0.0), ("phases", 3), ("current", 10.0)] and w_m1.sim.readback_a == 10 and w_m1.sim.phases_allowed == 3 and not w_m1.c.car_writer.hold and "charger_other" not in w_m1.rows() and w_m1.sim.power_w > 6000) async def m2_refused(): w = World(setpoint=10, phases=1) await w.step(8) await w.act("car_mode", "manual") await w.act("car_current", 10) await w.step(5) sim = w.sim def deaf(n): # Home Assistant says yes, nothing moves sim.log.append((sim.t, "phases", n, sim.power_w, sim.setpoint_a)) return True sim.request_phases = deaf n0 = len(w.writes()) await w.act("car_phases", 3) await w.step(3700) mid = [x for x in w.writes()[n0:]] ph = [x for x in mid if x[1] == "phases"] zeros = [x for x in mid if x[1] == "current" and x[2] == 0.0] out = dict(ph=len(ph), zeros=len(zeros), rb=sim.readback_a, gave=getattr(w.c.car_writer, "phases_gave_up", None), row=w.rows().get( "charger_phases"), power=sim.power_w) await w.act("car_phases", 3) # the user asks again: tried again await w.step(60) out["after_user"] = len([x for x in w.writes() if x[1] == "phases"]) - len(ph) return out m2 = run(m2_refused()) check("M2: a phase select the charger never takes is tried 3 times (10 minutes " "apart), not for ever", m2["ph"] == 3 and m2["zeros"] == 3) check("...each time the car gets its current back on the old phases (10 A, " "drawing), and at the end it is not left paused", m2["rb"] == 10 and m2["power"] > 2000) check("...then an amber row says the charger did not take the phases, and " "the add-on stops trying", m2["gave"] is True and m2["row"]["ok"] is False and m2["row"]["warn"] is True) check("...until the user changes something: then it tries again", m2["after_user"] == 1) async def l4_late(): # Home Assistant takes the select but the read-back is late: the current # must not come back before SETTLE_S has passed w = World(setpoint=10, phases=1) await w.step(8) await w.act("car_mode", "manual") await w.act("car_current", 10) await w.step(5) sim = w.sim def slow(n): sim.log.append((sim.t, "phases", n, sim.power_w, sim.setpoint_a)) sim._pending.append((sim.t + 12.0, "phases", n)) return True sim.request_phases = slow ret = [] real = w.drv.write_phases async def spy(n): r = await real(n) ret.append((sim.t, r)) # model time the select call returned return r w.drv.write_phases = spy n0 = len(w.writes()) await w.act("car_phases", 3) await w.step(60) if not ret: return None, 0.0 t_ret, took = ret[0] t_back = next((x[0] for x in w.writes()[n0:] if x[1] == "current" and x[0] > t_ret - 1), None) return took, (0.0 if t_back is None else t_back - t_ret) took_l4, gap_l4 = run(l4_late()) check(f"L4: after a phase select the charger did not take in time (read-back " f"12 s late), the current comes back only 10 s after the select call " f"returned ({gap_l4:.0f} s)", took_l4 is False and gap_l4 >= 10.0) async def m3(trigger): # the shipped shadow_mode: auto (shadow is on whenever control is stopped) w = World(dict(CAR, shadow_mode="auto"), setpoint=10, phases=1) w.sim.ramp_w_s = 50.0 w.sim.stop_delay_s = 40.0 await w.step(60) await w.act("car_mode", "manual") await w.act("car_current", 10) await w.step(3) await w.act("car_phases", 3) await w.step(3) # 0 A written, the select not yet n0 = len(w.writes()) mid = (w.sim.readback_a, w.c.car_writer.seq["stage"]) if trigger == "off": await w.act("car_mode", "off") elif trigger == "shadow": w.c.o["shadow_mode"] = "on" elif trigger == "stop": await w.c.handle_action("auto_toggle") elif trigger == "safety": w.c.inverters[0].sign_wd.tripped = True await w.step(80) return w, mid, [(x[1], x[2]) for x in w.writes()[n0:]] for _trig, _want in (("off", [("current", 10.0)]), ("shadow", [("current", 10.0)]), ("stop", [("current", 10.0)]), ("safety", [("current", 10.0)])): w_m3, mid_m3, wr_m3 = run(m3(_trig)) check(f"M3 ({_trig} mid-sequence, before the select): no phase switch, " + "the old 10 A comes back, and nothing is written after it " + f"(N1, shipped shadow_mode auto; {wr_m3})", mid_m3[0] == 0.0 and wr_m3 == _want and w_m3.writes("phases") == [] and w_m3.sim.readback_a == 10.0 and w_m3.sim.phases_allowed == 1 and w_m3.c.car_writer.seq is None) async def m4(): w = World(dict(CAR, ev_max_a=10), setpoint=16, phases=1) w.sim.ramp_w_s = 50.0 w.sim.stop_delay_s = 40.0 await w.step(60) await w.act("car_mode", "manual") await w.act("car_phases", 3) await w.step(4) prev = w.c.car_writer.seq["prev"] await w.c.car_shutdown() return w, prev w_m4, prev_m4 = run(m4()) check("M4: the old read-back was 16 A (another writer's) against ev_max_a 10; " "the restore on shutdown is clamped: the car gets 10 A back, no " "software fault is logged", prev_m4 == 16.0 and w_m4.sim.readback_a == 10.0 and w_m4.drv.clamp_faults == [] and w_m4.drv.sent[-1] == 10.0) # --- every write path: who calls the seam, and a fuzz over the lot --------- # def seam_callers(): """(file, name) of every call of the charger's write methods in app/.""" import ast out = [] for f in sorted(os.listdir(os.path.join(HERE, "app"))): if not f.endswith(".py") or f == "chargers.py": continue tree = ast.parse(io.open(os.path.join(HERE, "app", f), encoding="utf-8").read()) for n in ast.walk(tree): if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) \ and (n.func.attr in ("write_current", "write_phases") or (n.func.attr == "release" and "charger" in ast.dump(n.func.value))): out.append((f, n.func.attr)) return sorted(out) check("the write paths are exactly these (all in carmode.py): the current " "(one call), the phases (one call), nothing else " f"({seam_callers()})", seam_callers() == [("carmode.py", "write_current"), ("carmode.py", "write_phases")]) async def fuzz(seed): rnd = random.Random(seed) w = World(setpoint=rnd.choice([6, 10, 16]), phases=rnd.choice([1, 3])) w.sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0]) race = seed % 2 == 1 # half the sites run read -> settle -> cycle bad, seen, others, holds, undos = [], 0, 0, 0, 0 last_switch = None if rnd.random() < 0.8: await w.act("car_mode", "manual") for step in range(400): c, sim = w.c, w.sim wr = c.car_writer stage = wr.seq["stage"] if wr.seq is not None else None seq = stage is not None r = rnd.random() if stage in ("zero", "select") and rnd.random() < 0.15: # the user, a stop or shadow mode arrives mid-sequence pick = rnd.choice(["off", "stop", "shadow"]) if pick == "off": await w.act("car_mode", "off") elif pick == "stop": c.auto = False else: c.o["shadow_mode"] = "on" elif r < 0.02: await w.act("car_mode", rnd.choice(["off", "manual", "manual"])) elif r < 0.07: await w.act("car_current", rnd.randint(6, 16)) elif r < 0.09: await w.act("car_phases", rnd.choice([1, 3])) elif r < 0.093 and not seq: sim.go_unavailable(rnd.random() < 0.5) elif r < 0.096 and not seq: sim.station_a = float(rnd.choice([10, 13, 16])) elif r < 0.099 and not seq: (sim.unplug if sim.state != "A" else sim.plug_in)() elif r < 0.108: sim.set_current(rnd.randint(0, 16)) # another writer others += 1 elif r < 0.112: sim.refuse = rnd.choice([None, None, "ignore", "error"]) elif r < 0.116: c.auto = rnd.random() < 0.8 elif r < 0.12: c.o["shadow_mode"] = rnd.choice(["on", "off", "off"]) mode_now, auto_now, shadow_now = c.car_mode, c.auto, c.shadow n0, u0 = len(sim.log), getattr(wr, "undone", 0) await (w.step_race(1) if race else w.step(1)) undone = getattr(wr, "undone", 0) > u0 undos += undone holds += bool(wr.hold) for t, what, v, power, sp in sim.log[n0:]: clamp = min(16.0, sim.station_a) # a sequence whose select has gone out is finished whatever the # mode says; one undone before it gives the old current back exempt = stage == "settle" or undone if what == "current" and not 0.0 <= v <= clamp + 1e-9: bad.append((seed, step, "over the clamp", v, clamp)) if what == "current" and mode_now != "manual" and not exempt: bad.append((seed, step, "written outside Manual", mode_now)) if what in ("current", "phases") and not auto_now and not exempt: bad.append((seed, step, "written with control stopped")) if what in ("current", "phases") and shadow_now and not exempt: bad.append((seed, step, "written in shadow mode")) if what == "current" and sim.state == "A" and not seq: bad.append((seed, step, "written with no car")) if what == "phases": if mode_now != "manual" or not auto_now or shadow_now: bad.append((seed, step, "phases selected outside Manual")) if sp != 0.0: bad.append((seed, step, "phases with the setpoint up", sp)) if last_switch is not None and t - last_switch < 600.0: bad.append((seed, step, "two switches inside 10 min", t - last_switch)) last_switch = t seen += len(sim.log) - n0 return bad, seen, others, holds, undos fz_bad, fz_n, fz_o, fz_h, fz_u = [], 0, 0, 0, 0 for _seed in range(14): _b, _n, _o, _h, _u = run(fuzz(_seed)) fz_bad += _b fz_n += _n fz_o += _o fz_h += _h fz_u += _u check(f"fuzz: {fz_n} charger writes over 14 random sites and 5600 steps of " f"random user changes, outages, unplugs, refusals, shadow and control " f"stops, in both cycle orders: none over the clamp, none outside " f"Manual, none with control stopped, in shadow mode or with no car, the " f"phases never selected outside Manual or with the car drawing, one " f"switch per 10 minutes ({fz_bad[:3]})", not fz_bad and fz_n > 100) check(f"fuzz: the other-writer branch runs ({fz_o} other writers made, " f"{fz_h} steps with the add-on holding off one, {fz_u} sequences undone)", fz_o > 30 and fz_h > 5 and fz_u > 0) # =========================================================================== # print("\n6. SHADOW MODE AND A STOPPED CONTROL WRITE NOTHING") # =========================================================================== # async def shadow_story(shadow, auto): w = World(dict(CAR, shadow_mode=shadow), setpoint=10, phases=1) w.c.auto = auto await w.step(5) await w.act("car_mode", "manual") await w.act("car_current", 14) await w.act("car_phases", 3) await w.step(80) card = homeview.car_block(w.c, datetime.now(timezone.utc)) return w, card w6, card6 = run(shadow_story("on", True)) check("shadow mode: no write to the charger at all, although Manual, 14 A and " "3 phases are set", w6.sim.log == [] and w6.site.charger_writes() == [] and w6.drv.sent == []) check("shadow mode: the Car card says what it would set", "would set 14 A" in card6["why"] and "3 phases" in card6["why"]) check("shadow mode: the card is in Manual all the same", card6["mode"] == "manual") w6b, card6b = run(shadow_story("off", False)) check("control stopped (shadow off): nothing is written, the card says so", w6b.sim.log == [] and "stopped" in card6b["why"]) async def shadow_off_then_on(): w, _c = await shadow_story("off", False) w.c.auto = True await w.step(60) return w w6c = run(shadow_off_then_on()) check("...and when control starts the waiting setting is written (once, by " "the safe sequence for the phases)", w6c.sim.readback_a == 14 and w6c.sim.phases_allowed == 3) # =========================================================================== # print("\n7. FAIL STATES, THE MANUAL COLUMN") # =========================================================================== # async def restart_story(start): st = _Store() w = World(dict(CAR, ev_mode_start=start), store=st, setpoint=10, phases=1) await w.step(3) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(20) before = list(w.sim.log) # a restart: a new Controller on the same store and the same charger w.make(dict(CAR, ev_mode_start=start)) await w.step(40) return w, before w7, before7 = run(restart_story("keep")) check("a restart (keep): the charger stays at 12 A and nothing is written, " "not even 0 A", w7.sim.log == before7 and w7.sim.readback_a == 12 and w7.c.car_mode == "manual") w7o, before7o = run(restart_story("off")) check("a restart with 'Mode after a restart: Off': the mode is Off, nothing " "is written, the current stands (Manual's own column)", w7o.sim.log == before7o and w7o.sim.readback_a == 12 and w7o.c.car_mode == "off") async def stop_story(): w = World(setpoint=10, phases=1) await w.step(3) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(10) n = len(w.sim.log) await w.c.handle_action("auto_toggle") # the Stop button await w.step(30) stopped = (len(w.sim.log) == n, w.sim.readback_a) # a safety stop: a failsafe latch is up w.c.auto = True w.c.inverters[0].sign_wd.tripped = True await w.step(30) safety = (len(w.sim.log) == n, w.sim.readback_a) return stopped, safety stopped7, safety7 = run(stop_story()) check("control stopped by the button: the current stands, nothing is written", stopped7 == (True, 12)) check("a safety stop (a failsafe latch): the current stands, nothing is " "written", safety7 == (True, 12)) async def return_story(other): w = World(setpoint=10, phases=1) await w.step(3) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(10) n = len(w.sim.log) w.sim.go_unavailable() await w.step(60) if other: w.sim.go_unavailable(False) w.sim.set_current(7) # it came back with another value else: w.sim.go_unavailable(False) await w.step(30) return w, n w7a, n7a = run(return_story(False)) check("the charger comes back with the same read-back: nothing is written", len(w7a.sim.log) == n7a) w7b, n7b = run(return_story(True)) check("it comes back with a different read-back: the setting is written again, " "once", len(w7b.sim.log) == n7b + 1 and w7b.sim.readback_a == 12) async def outage_write(): w = World(setpoint=10, phases=1) await w.step(3) await w.act("car_mode", "manual") await w.step(5) n0 = len(w.sim.log) w.sim.go_unavailable() await w.step(5) await w.act("car_current", 13) # changed while it is away await w.step(40) during = len(w.sim.log) - n0 w.sim.go_unavailable(False) await w.step(10) return during, w.sim.readback_a, w.drv.sent during7, rb7, sent7 = run(outage_write()) check("a value set while the charger is away is written when it answers", during7 == 0 and rb7 == 13 and sent7[-1] == 13.0) async def error_story(): w = World(setpoint=10, phases=1) await w.step(3) await w.act("car_mode", "manual") w.sim.error = "17: Overcurrent" await w.step(5) await w.act("car_current", 12) await w.step(10) return w w7e = run(error_story()) check("a charger error is shown (a grey row) and the writes go on", w7e.rows().get("charger_error", {}).get("ok") is True and "Overcurrent" in w7e.rows()["charger_error"]["text"] and w7e.sim.readback_a == 12) async def nocar_story(): w = World(plug=False, setpoint=10, phases=1) await w.step(5) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.act("car_phases", 3) await w.step(60) none_writes = len(w.sim.log) none_why = homeview.car_block(w.c, datetime.now(timezone.utc))["why"] w.sim.plug_in() await w.step(80) return w, none_writes, none_why w7n, none7, why7n = run(nocar_story()) check("no car: the current stands and nothing is written (not even for the " "user's change)", none7 == 0) check("...and the card says it is set when a car is connected", "when a car is connected" in why7n) check("...when the car is plugged in the waiting setting is written", w7n.sim.readback_a == 12 and w7n.sim.phases_allowed == 3) async def full_story(): w = World(setpoint=10, phases=1) await w.step(3) await w.act("car_mode", "manual") await w.step(5) w.sim.car_full() await w.step(120) state = w.c.car.status(CLOCK[0]) n = len(w.sim.log) await w.act("car_current", 14) await w.step(60) return state, n, len(w.sim.log) state7f, n7f, m7f = run(full_story()) check("a full car: the current stands, nothing is written", state7f == "full" and n7f == m7f) # =========================================================================== # print("\n8. ANOTHER WRITER") # =========================================================================== # async def writer_story(): w = World(setpoint=10, phases=1) await w.step(3) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(10) n = len(w.sim.log) w.sim.set_current(9) # the HA automation await w.step(20) early = ("charger_other" in w.rows(), w.c.car_writer.hold, len(w.sim.log)) await w.step(20) held = ("charger_other" in w.rows(), w.c.car_writer.hold) row = w.rows().get("charger_other") await w.step(200) stays = (len(w.sim.log) == n, w.sim.readback_a) await w.act("car_current", 14) await w.step(10) after = ("charger_other" in w.rows(), w.sim.readback_a, w.c.car_writer.hold) return early, held, row, stays, after, n, w early8, held8, row8, stays8, after8, n8, w8 = run(writer_story()) check("a different read-back for under 30 s is not yet 'another writer'", early8 == (False, False, n8)) check("after 30 s it is: an info row (grey, not amber)", held8 == (True, True) and row8["ok"] is True and row8["warn"] is True) check("...and the add-on does not write over it, for minutes", stays8 == (True, 9)) check("...until the user changes a value: then it writes it, and the row goes", after8 == (False, 14, False)) async def writer_off(): w = World(setpoint=10, phases=1) await w.step(3) await w.act("car_mode", "manual") await w.act("car_current", 12) await w.step(10) await w.act("car_mode", "off") # back to Off after the add-on wrote await w.step(30) own = "charger_writer" in w.rows() w.sim.set_current(7) # now somebody else await w.step(3) return own, "charger_writer" in w.rows(), len(w.writes()) own8, off8, nw8 = run(writer_off()) check("Manual back to Off: the add-on's own writes do not show as another " "writer", own8 is False) check("Off keeps EV-03's grey row for a real other writer", off8 is True and nw8 == 1) # =========================================================================== # print("\n9. THE PEAK GUARD'S ALARM PATH: THE CAR YOU SET IS NOT A FALSE ALARM") # =========================================================================== # import ev04_peak as P # noqa: E402 import safety81_sim as s81 # noqa: E402 import opt11_identity as rig # noqa: E402 LOG.rec.clear() logging.disable(logging.NOTSET) HOUSE = s81.constant(1100.0) def alarms(r): return P.ids(r, *P.ALARMS) def cardwhy(r): return homeview.car_block(r["c"], rig.BASE + timedelta(seconds=299))["why"] r_off = P.drive(HOUSE, dur=240, mode="off") r_man = P.drive(HOUSE, dur=240) check("PRECONDITION: Off, an 11 kW car on a 1.1 kW house and a 2 kW battery " "raises 'Load too high for battery' (the false alarm today)", len(alarms(r_off)) == 1 and alarms(r_off)[0][1] == "goodwe_peak_saturated") check("Manual: the same car raises neither 'Load too high' nor 'Battery " "stopped limiting the peak'", alarms(r_man) == []) check("Manual: one grey notice 'Car over the peak limit', once", len(P.ids(r_man, P.OVER)) == 1) check("...the claim, the floor and the commands are those of Off (the " "battery gives its 2000 W in both)", [s[4] for s in r_man["snaps"]] == [s[4] for s in r_off["snaps"]] and max(s[4] for s in r_man["snaps"]) == 2000.0) check("the car is never throttled: the add-on wrote nothing to the charger " "after choosing Manual", r_man["sim"].setpoint_a == 16 and r_man["sim"].writes() == []) rows_m = {x["id"]: x for x in r_man["c"].checks()} check("no red row for that cause; the peak row is not an alarm", rows_m["peak_guard"]["ok"] is True and not any(x["ok"] is False and not x["warn"] for x in r_man["c"].checks() if x["id"] in ("peak_guard",))) check("one grey row says the car charge you set is over the limit", rows_m.get("car_over", {}).get("ok") is True and rows_m["car_over"]["warn"] is True) check("the Car card's Why says it (the batteries give all they can)", "batteries give all they can" in cardwhy(r_man)) att = homeview.attention(r_man["c"].checks()) check("Needs attention holds the grey note and nothing red", any(a["id"] == "car_over" and a["severity"] == "info" for a in att) and not [a for a in att if a["severity"] == "alarm"]) # the batteries at the peak reserve: 'Battery stopped limiting the peak' r_off_r = P.drive(HOUSE, dur=240, mode="off", soc=15.0) r_man_r = P.drive(HOUSE, dur=240, soc=15.0) check("PRECONDITION: Off, batteries at the reserve: 'Battery stopped limiting " "the peak' fires", [n for _t, n in alarms(r_off_r)] == ["goodwe_peak_soc_floor"]) check("Manual, batteries at the reserve: no alarm, one grey notice", alarms(r_man_r) == [] and len(P.ids(r_man_r, P.OVER)) == 1) check("...and the Why says the batteries are at the reserve", "at 20 %" in cardwhy(r_man_r)) # once per charging session def replug(plant, c): plant.ch.unplug() def plugin(plant, c): plant.ch.plug_in() r_ses = P.drive(HOUSE, dur=400, events={150: replug, 200: plugin}) check("the notice is once per charging session: a second plug-in raises it " "again, a long charge does not", len(P.ids(r_ses, P.OVER)) == 2 and alarms(r_ses) == []) # a car that is not the cause: a house overload on top of a small car def house_overload(plant, c): plant.house = lambda at: 9000.0 + plant.ch.power_w r_both = P.drive(s81.constant(1100.0), dur=240, user_a=6, setpoint=6, phases=1, events={60: lambda p, c: setattr( p, "load", lambda at: 9000.0 + p.ch.power_w)}) check("a 1.4 kW car and a house that steps to 9 kW: the car does not explain " "the excess, so the normal alarm fires", [n for _t, n in alarms(r_both)] == ["goodwe_peak_saturated"]) # --- a stale or stuck car reading must NOT hide a real house overload ------- # def stale_then_overload(plant, c): plant.ch.unplug() # the car goes plant.ch.go_unavailable() # and the charger stops answering plant.load = lambda at: 9000.0 + plant.ch.power_w r_stale = P.drive(HOUSE, dur=300, events={60: stale_then_overload}) check("the charger stops answering and the house steps to 9 kW: the car " "figure is not used (not fresh), so the normal alarm fires", [n for _t, n in alarms(r_stale)] == ["goodwe_peak_saturated"] and 60 < alarms(r_stale)[0][0] < 60 + 15 + 25) def stuck_then_overload(plant, c): plant.ch.freeze() # the reading stops moving plant.ch.unplug() # the car really goes plant.load = lambda at: 9000.0 + plant.ch.power_w run_user_change(c) def run_user_change(c): asyncio.get_event_loop().create_task(c.handle_action("car_current", value=10)) r_stuck = P.drive(HOUSE, dur=400, events={60: stuck_then_overload}) at_stuck = alarms(r_stuck) check("a stuck car figure (11 kW, frozen) and a real house overload: the " "stuck rule (60 s after the write) lets the normal alarm fire", [n for _t, n in at_stuck] == ["goodwe_peak_saturated"] and at_stuck[0][0] < 60 + 60 + 25) check("...and the amber row 'Charger reading may be stuck' says so", "charger_stuck" in {x["id"]: x for x in r_stuck["c"].checks()} and {x["id"]: x for x in r_stuck["c"].checks()}["charger_stuck"]["warn"]) w_ = r_stuck["c"] check("...while stuck, the car figure is not used by the alarm path", w_.car.stuck(w_.car_now()) and w_.car_alarm_w() is None) # a plausible figure is bounded by what the read-back allows (and needs an # energy meter that agrees with it) def corr(tr, t): f = getattr(tr, "corroborated", None) return f(t) if f else True # an old tree has no such rule def charging_reading(e_kwh, w=11000.0, a=6.0): return CH.ChargerReading(available=True, state="C", charging=True, power_w=w, allowed_a=a, setpoint_a=a, phases_allowed=1, energy_kwh=e_kwh) def feed(tr, secs, e_of, w=11000.0, t0=100.0): for i in range(secs): tr.observe(charging_reading(e_of(i), w), t0 + i, datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") return t0 + secs - 1 tr = CH.CarTracker() t_end = feed(tr, 80, lambda i: 1000.0 + i * 11000.0 / 3.6e6) check("an honest 11 kW figure on a 6 A, 1 phase read-back counts for no more " "than that allows (1.5 kW), so an old figure cannot cover a house " "overload", abs(tr.car_w_trusted(t_end) - 6 * 253) < 1 and corr(tr, t_end)) check("...and None when it is not fresh", tr.car_w_trusted(t_end + 16) is None) tr = CH.CarTracker() t_end = feed(tr, 20, lambda i: 1000.0) check("the first minute of readings is believed (a session just began): no " "false alarm while the meter has had no time to show it", corr(tr, t_end) and tr.car_w_trusted(t_end) is not None) t_end = feed(tr, 80, lambda i: 1000.0, t0=t_end + 1) check("M5: a power figure of 11 kW with an energy meter that does not move " "is not corroborated after a window: no car figure for the alarms", not corr(tr, t_end) and tr.car_w_trusted(t_end) is None) tr = CH.CarTracker() t_end = feed(tr, 80, lambda i: 1000.0 + i * 1500.0 / 3.6e6) check("M5: a meter that gains 1.5 kW while the power says 11 kW is not " "corroborated either", not corr(tr, t_end)) tr = CH.CarTracker() t_end = feed(tr, 80, lambda i: None) check("M5: no energy entity: never corroborated, so never used", not corr(tr, t_end) and tr.car_w_trusted(t_end) is None) tr = CH.CarTracker() t_end = feed(tr, 80, lambda i: 1000.0 + i * 5000.0 / 3.6e6, w=5000.0) t_end = feed(tr, 80, lambda i: 1000.0 + i * 11000.0 / 3.6e6, t0=t_end + 1) check("a car that really ramps up (5 kW to 11 kW) stays corroborated", corr(tr, t_end)) # N2: the lowest charge, 6 A on 1 phase (1380 W), honest and frozen def honest_1380(tr, secs, t0=100.0, e0=1000.0, step_wh=10.0): """An honest 1380 W car whose meter shows `step_wh` steps.""" for i in range(secs): wh = 1380.0 * i / 3600.0 tr.observe(charging_reading((e0 + (wh // step_wh) * step_wh) / 1000.0, 1380.0), t0 + i, datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") return t0 + secs - 1 tr = CH.CarTracker() t_end = honest_1380(tr, 400) check("N2: an honest 6 A, 1 phase car (1380 W) with a meter that shows 10 Wh " "steps is believed, minute after minute", corr(tr, t_end) and tr.car_w_trusted(t_end) is not None and all(corr(tr, t) for t in (t_end - 3, t_end - 17))) ok_all = True tr = CH.CarTracker() for i in range(500): # step sizes and phases of the meter vary wh = 1380.0 * i / 3600.0 step_wh = (10.0, 5.0, 20.0)[i // 170] tr.observe(charging_reading((1000.0 + (wh // step_wh) * step_wh) / 1000.0, 1380.0), 100.0 + i, datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") ok_all &= corr(tr, 100.0 + i) check("...at every second of a 500 s charge with 5, 10 and 20 Wh meter steps", ok_all) tr = CH.CarTracker() t_end = honest_1380(tr, 200) frozen_at, caught = t_end, None for i in range(1, 200): # now the figure and the meter freeze tr.observe(charging_reading(tr.reading.energy_kwh, 1380.0), t_end + i, datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") if caught is None and not corr(tr, t_end + i): caught = i check(f"N2: a frozen 1380 W figure is caught {caught} s after the freeze " "(bound: 40 Wh / 1.38 kW = 104 s, and not sooner than the honest run " "allows)", caught is not None and 60 <= caught <= 110) # --- M5 end to end: the meter, the plant and the real controller ------------- # def freeze_all(plant, c): plant.ch.freeze() # every reading sticks plant.ch.set_current(0) # the car really stops plant.load = lambda at: 9000.0 + plant.ch.power_w def freeze_power_only(plant, c): plant.ch.freeze_power() # only the power sensor sticks plant.ch.set_current(6) # the car really draws 1.4 kW plant.ch.set_phases(1) plant.load = lambda at: 9000.0 + plant.ch.power_w r_fz_mid = P.drive(HOUSE, dur=400, events={120: freeze_all}) r_fz_pw = P.drive(HOUSE, dur=400, events={120: freeze_power_only}) r_fz_0 = P.drive(HOUSE, dur=400, events={5: freeze_all}) r_noe = P.drive(HOUSE, dur=240, sim=SimCharger(setpoint_a=16)) for _name, _r, _t0 in (("a freeze in the middle of a session (everything " "stuck, the car stops)", r_fz_mid, 120), ("only the power sensor sticks while the car draws " "1.4 kW", r_fz_pw, 120), ("a freeze from the start", r_fz_0, 5)): _al = alarms(_r) check(f"M5: {_name} and the house steps to 9 kW: after a window the " f"normal alarm fires ({_al})", [n for _t, n in _al] == ["goodwe_peak_saturated"] and _t0 < _al[0][0] < _t0 + 60 + 25) def freeze_1380(plant, c): plant.ch.freeze() plant.ch.set_current(0) # the car really stops plant.load = lambda at: 9000.0 + plant.ch.power_w _s6 = SimCharger(setpoint_a=6) _s6.phases_allowed = 1 r_fz_6a = P.drive(HOUSE, dur=500, sim=_s6, user_a=6, setpoint=6, phases=1, events={150: freeze_1380}) _al6 = alarms(r_fz_6a) check("N2 (probe G): a frozen 6 A, 1 phase figure (1380 W) after the car " "really stops, and the house steps to 9 kW: the normal alarm fires " f"within the stated bound ({_al6})", [n for _t, n in _al6] == ["goodwe_peak_saturated"] and 150 < _al6[0][0] < 150 + 104 + 10 + 25) _s6h = SimCharger(setpoint_a=6) r_6_honest = P.drive(HOUSE, dur=500, sim=_s6h, user_a=6, setpoint=6, phases=1, opts={"peak_cap_w": 1500}) check("an honest 6 A, 1 phase car on the real controller: the corroboration " "never turns the figure off (the car stays trusted to the end)", r_6_honest["c"].car_alarm_w() is not None) r_honest = P.drive(HOUSE, dur=400) check("M5: an honest charging car still suppresses the alarms for the whole " "run, meter and all", alarms(r_honest) == [] and len(P.ids(r_honest, P.OVER)) == 1) class _NoE(SimCharger): pass _sim_noe = SimCharger(setpoint_a=16) _sim_noe.no_energy = True r_noe = P.drive(HOUSE, dur=240, sim=_sim_noe) check("M5: a charger with no energy entity does not suppress: the normal " "alarm fires and there is no car notice", [n for _t, n in alarms(r_noe)] == ["goodwe_peak_saturated"] and P.ids(r_noe, P.OVER) == []) # =========================================================================== # print("\n10. DECISION 1: BATTERIES HELP WITH THE PEAK, ON AND OFF") # =========================================================================== # r_on = P.drive(HOUSE, dur=240, opts={"ev_batt_cover": True}) r_no = P.drive(HOUSE, dur=240, opts={"ev_batt_cover": False}) check("on (the default): the guard asks the batteries for the car's share " "(the battery gives 2000 W) and the guard is engaged", max(s[4] for s in r_on["snaps"]) == 2000.0 and r_on["snaps"][-1][3] is True) check("off: the guard sees the house without the car, is not engaged, and the " "batteries keep their charge (0 W)", max(s[4] for s in r_no["snaps"]) == 0.0 and r_no["snaps"][-1][3] is False) check("off: the quarter goes over by the car alone, and the add-on says so " "(one grey notice), with no alarm", alarms(r_no) == [] and len(P.ids(r_no, P.OVER)) == 1) check("off: the Why says the guard ignores the car (and promises nothing " "about the batteries)", "guard ignores the car" in cardwhy(r_no) and "keep their charge" not in cardwhy(r_no)) check("either way the car is never throttled", r_on["sim"].writes() == [] and r_no["sim"].writes() == [] and r_no["sim"].setpoint_a == 16 and r_no["sim"].power_w > 10000) r_no_h = P.drive(HOUSE, dur=300, opts={"ev_batt_cover": False}, user_a=6, setpoint=6, phases=1, events={60: lambda p, c: setattr( p, "load", lambda at: 9000.0 + p.ch.power_w)}) check("off: a real house overload is still an alarm (the car is only left out " "of the guard's house)", [n for _t, n in alarms(r_no_h)] == ["goodwe_peak_saturated"]) r_no_s = P.drive(HOUSE, dur=300, opts={"ev_batt_cover": False}, events={60: stale_then_overload}) check("off: a house overload with a car that is no longer read still alarms", [n for _t, n in alarms(r_no_s)] == ["goodwe_peak_saturated"]) # =========================================================================== # print("\n11. THE PEAK LINE: SET BY THE CAR, AND THE PEAK CARD'S CAR LINE") # =========================================================================== # def unplug_at(plant, c): plant.ch.unplug() r_pk = P.drive(HOUSE, dur=1900, events={950: unplug_at}) c_pk = r_pk["c"] now_pk = rig.BASE + timedelta(seconds=1899) mp = homeview.month_peak(c_pk, now_pk) check("PRECONDITION: a quarter was banked as this month's peak, with the car " "in it", mp["peak_w"] and mp["peak_w"] > 4000 and c_pk.car_peak_q) check("the Home peak line names the car and the time of that quarter", mp["set_by"].startswith("Set by the car charge you asked for, at ") and mp["set_by"].endswith(".") and ":" in mp["set_by"]) with homeview.in_lang("nl"): mp_nl = homeview.month_peak(c_pk, now_pk) check("...in Dutch too", mp_nl["set_by"].startswith("Bepaald door de " "autolading die u vroeg")) r_pk_off = P.drive(HOUSE, dur=1900, mode="off", events={950: unplug_at}) check("Off: the month's peak is not 'set by the car you asked for'", homeview.month_peak(r_pk_off["c"], now_pk)["set_by"] == "" and r_pk_off["c"].car_peak_q == {}) mp_now = homeview.month_peak(r_man["c"], rig.BASE + timedelta(seconds=239)) check("while the car charges and the guard works, the Peak card says what the " "car takes and the batteries cover", "The car takes 11.0 kW and the batteries cover 2.0 kW" in mp_now["car_line"]) check("a site with no charger has neither line", homeview.month_peak(s81.run(HOUSE, dur=60.0)[2], rig.BASE)["set_by"] == "") # =========================================================================== # print("\n12. HOME ASSISTANT ENTITIES, THE PAGE'S ROUTE, STRINGS") # =========================================================================== # pl = dict(mqtt.car_payloads((16, (1, 3)))) sel = pl["homeassistant/select/goodwe_ctl_car_mode/config"] num = pl["homeassistant/number/goodwe_ctl_car_current/config"] ph = pl["homeassistant/select/goodwe_ctl_car_phases/config"] check("four entities: select.goodwe_car_mode, number.goodwe_car_current, " "select.goodwe_car_phases and (EV-05) select.goodwe_car_sun_first", len(pl) == 4 and sel["object_id"] == "goodwe_car_mode" and num["object_id"] == "goodwe_car_current" and ph["object_id"] == "goodwe_car_phases") check("the mode's labels are English and pinned: Off, Manual, Solar (EV-05; " "Night is not offered)", sel["options"] == ["Off", "Manual", "Solar"]) check("the current is 6 A to the clamp, whole amps", num["min"] == 6 and num["max"] == 16 and num["step"] == 1 and num["unit_of_measurement"] == "A") check("the phases are 1 and 3 (or the one the installation allows)", ph["options"] == ["1", "3"] and dict(mqtt.car_payloads((16, (3,))))[ "homeassistant/select/goodwe_ctl_car_phases/config"][ "options"] == ["3"]) check("commands go to goodwe_ctl/car//set, HA sends them unretained", all(x["command_topic"].startswith("goodwe_ctl/car/") and x["command_topic"].endswith("/set") and x["retain"] is False for x in (sel, num, ph))) check("nothing is announced without a charger (and the default announcement " "is as it was)", mqtt.car_payloads(None) == [] and mqtt.discovery_payloads() == mqtt.discovery_payloads(car=None)) check("the car entities come after every other row", [t for t, _ in mqtt.discovery_payloads(car=(16, (1, 3)))][-4:] == [t for t, _ in mqtt.car_payloads((16, (1, 3)))]) cmd = mqtt.parse_car_command check("a command parses: mode, current, phases", cmd("goodwe_ctl/car/mode/set", b"Manual", False) == ("car_mode", "manual", None) and cmd("goodwe_ctl/car/current/set", b"12", False) == ("car_current", 12.0, None) and cmd("goodwe_ctl/car/phases/set", b"3", False) == ("car_phases", 3, None)) check("a retained command is dropped", cmd("goodwe_ctl/car/mode/set", b"Manual", True)[2] == "retained") check("Night, an unknown mode, junk and a long payload are refused", cmd("goodwe_ctl/car/mode/set", b"Bogus", False)[1] is None and cmd("goodwe_ctl/car/mode/set", b"Night", False)[1] is None and cmd("goodwe_ctl/car/current/set", b"abc", False)[1] is None and cmd("goodwe_ctl/car/phases/set", b"2", False)[1] is None and cmd("goodwe_ctl/car/mode/set", b"x" * 100, False)[2] == "size" and cmd("goodwe_ctl/car/mode/set", b"\xff\xfe", False)[2] == "encoding" and cmd("goodwe_ctl/battery/mode/set", b"Manual", False)[2] == "topic") async def ha_story(): w = World(setpoint=10) await w.step(3) await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Manual", False) await w.c.mqtt_command("goodwe_ctl/car/current/set", b"13", False) await w.step(10) out = {"mode": w.c.car_mode, "a": w.c.car_a, "rb": w.sim.readback_a, "pub": list(w.c.mqtt.values)[-1]} await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Off", True) # retained await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Night", False) await w.c.mqtt_command("goodwe_ctl/car/current/set", b"99", False) await w.c.mqtt_command("goodwe_ctl/car/phases/set", b"2", False) await w.step(5) out["after"] = (w.c.car_mode, w.c.car_a, w.c.car_n) await w.step(2) await w.c.publish_values() if hasattr(w.c, "publish_values") else None w.c.publish() out["state"] = {k: v for k, v in w.c.mqtt.values[-1].items() if k.startswith("car_")} return out ha = run(ha_story()) check("HA commands go through handle_action(): Manual and 13 A are applied " "and written, and the new state is published", ha["mode"] == "manual" and ha["a"] == 13.0 and ha["rb"] == 13 and ha["pub"] == {"car_mode": "Manual", "car_current": 13, "car_phases": "1", "car_sun_first": "Batteries"}) check("a retained command, Night, 99 A and 2 phases change nothing", ha["after"] == ("manual", 13.0, 1)) check("the three states are in the published values", ha["state"].get("car_mode") == "Manual" and ha["state"].get("car_current") == 13 and ha["state"].get("car_phases") == "1") class _S: def __init__(self, d=None): self.data = dict(d or {}) def set(self, k, v): self.data[k] = v from app import main as _main # noqa: E402 st_ = _S() car_, retract_ = _main.car_announcement(CAR, st_) check("with a charger the entities are announced and their topics kept", car_ == (16.0, (1, 3)) and not retract_ and len( st_.data["mqtt_car_configs"]) == 4) car2, retract2 = _main.car_announcement(BASE, st_) check("turning the charger off removes exactly those entities", car2 is None and sorted(retract2) == sorted(st_.data["mqtt_car_configs"]) and len(retract2) == 4) st2 = _S() check("a site that never had a charger publishes nothing and its store is " "not written", _main.car_announcement(BASE, st2) == (None, []) and st2.data == {}) async def web_story(): import socket import aiohttp from aiohttp import web as aioweb from app import web as app_web w = World(setpoint=10) await w.step(3) app = app_web.build_app(w.c, selfcfg=object()) runner = aioweb.AppRunner(app) await runner.setup() sock = socket.socket() sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] sock.close() await aioweb.TCPSite(runner, "127.0.0.1", port).start() out = {} try: async with aiohttp.ClientSession() as s: root = f"http://127.0.0.1:{port}/" for key, body in ( ("manual", {"action": "car_mode", "value": "manual"}), ("a", {"action": "car_current", "value": 12}), ("n", {"action": "car_phases", "value": 3}), ("solar", {"action": "car_mode", "value": "night"}), ("big", {"action": "car_current", "value": 40})): async with s.post(root + "action", json=body) as r: out[key] = (r.status, await r.json(content_type=None)) for lang in ("en", "nl"): async with s.get(root + "status?lang=" + lang) as r: out["status_" + lang] = (await r.json(content_type=None)) async with s.get(root) as r: out["page"] = await r.text() finally: await runner.cleanup() return out, w web, ww = run(web_story()) check("POST /action car_mode, car_current and car_phases store and answer", web["manual"] == (200, {"ok": True, "result": { "mode": "manual", "current": 6.0, "phases": 1}}) and web["a"][0] == 200 and web["n"][0] == 200) check("...Night and 40 A (above the clamp) are a 400 with a plain reason", web["solar"][0] == 400 and web["solar"][1]["ok"] is False and web["solar"][1]["error"] == messages.car_refused("value") and web["big"][0] == 400) car_s = web["status_en"]["car"] check("/status gives the page what it needs: the mode, the modes offered (Off, " "Manual and, EV-05, Solar), the current's range, the phases", car_s["mode"] == "manual" and car_s["modes"] == ["off", "manual", "solar"] and car_s["current"] == {"value": 12, "min": 6, "max": 16} and car_s["phases"] == {"value": 3, "choices": [1, 3]}) check("/status in Dutch has the Dutch Why", web["status_nl"]["car"]["why"].startswith("U stelde 12 A in")) check("the page has the controls and no Night button (EV-05 adds Solar)", 'id="car-manual"' in web["page"] and 'id="car-a"' in web["page"] and "mode_night" not in web["page"]) check("the page names the Manual strings in both languages", "Handmatig" in web["page"] and "Manual" in web["page"]) en = json.load(io.open(os.path.join(HERE, "app", "ui_text", "en.json"), encoding="utf-8")) nl = json.load(io.open(os.path.join(HERE, "app", "ui_text", "nl.json"), encoding="utf-8")) def keys(d, pre=""): out = set() for k, v in d.items(): out |= keys(v, pre + k + ".") if isinstance(v, dict) else {pre + k} return out new_keys = {"home.car.mode_manual", "home.car.help_manual.description", "home.car.current", "home.car.phases", "home.car.phases_1", "home.car.phases_3", "home_words.peak.car", "home_words.peak.set_by_car", "home_words.car.why.manual_set", "home_words.car.why.manual_cover", "home_words.car.why.manual_over", "home_words.car.why.manual_full", "home_words.car.why.manual_nocover", "home_words.car.why.manual_wait", "home_words.car.why.manual_would", "home_words.car.why.manual_stopped", "home_words.car.why.manual_blocked", "home_words.attn.charger_other", "home_words.attn.charger_stuck", "home_words.attn.charger_refused", "home_words.attn.charger_error", "home_words.attn.car_over", "choices.ev_mode_start.keep", "choices.ev_mode_start.off"} ke, kn = keys(en), keys(nl) check("every new Home string exists in English and in Dutch", new_keys <= ke and new_keys <= kn) check("the Dutch is not the English for the sentences", all(en["home_words"]["car"]["why"][k] != nl["home_words"]["car"]["why"][k] for k in ("manual_set", "manual_cover", "manual_over", "manual_full", "manual_nocover", "manual_wait", "manual_would", "manual_stopped", "manual_blocked"))) check("L2: one wording for 'something else changes the charger', in Off and " "Manual, English and Dutch", en["home_words"]["attn"]["charger_other"] == en["home_words"]["attn"]["charger_writer"] and nl["home_words"]["attn"]["charger_other"] == nl["home_words"]["attn"]["charger_writer"] and "changes the charger" in str(messages.row_charger_other()) and "wijzigt de laadpaal" in messages.row_charger_other().nl and "changed" not in str(messages.row_charger_other())) check("L3: with Batteries help off the Why promises nothing about the " "batteries, and DOCS says what it does", "keep their charge" not in json.dumps(en) + json.dumps(nl) .replace("houden hun lading", "keep their charge") and "zero-grid control can still discharge them for the car" in io.open(os.path.join(HERE, "DOCS.md"), encoding="utf-8").read() .replace("\n", " ").replace("Normal zero-grid control can still", "zero-grid control can still")) check("every new row, notice and refusal is bilingual", all(getattr(f, "nl", None) for f in ( messages.row_car_over(), messages.row_charger_other(), messages.row_charger_stuck(), messages.row_charger_refused(), messages.row_charger_error("x"))) and messages.car_over("16").body_nl) check("the page shows the option names and choices in Settings, both languages", messages.LABELS["ev_batt_cover"] and messages.LABELS_NL["ev_mode_start"]) # =========================================================================== # print("\n13. THE SIMULATOR") # =========================================================================== # s = SimCharger(setpoint_a=10) s.plug_in() s.lag_s = 3.0 s.request_current(12) s.tick(2) check("the model shows a write after its read-back lag, not before", s.readback_a == 10) s.tick(1) check("...and after it", s.readback_a == 12) s.refuse = "ignore" check("a refusing charger says yes and does not change", s.request_current(6) and s.readback_a == 12) s.refuse = "error" check("a refusing Home Assistant says no", not s.request_current(6)) s.refuse = None s.freeze() s.set_current(7) check("a frozen model serves the readings of the moment it froze", s.states()[f"sensor.wallbox_main_active_max_current_socket_1"]["state"] == "12") s.freeze(False) print() if fails: print(f"{len(fails)} FAILED") for f in fails: print(" -", f) sys.exit(1) print("all passed")