Files
goodwe-addon/goodwe_controller/test_ev20.py
T
Claude cd8c393161
checks / unit (pull_request) Successful in 30m56s
infra-pin / fresh (pull_request) Successful in 2s
EV-20 review round 2: one write clock for every non-zero current (C6, N5)
ManualWriter._write, the one write_current call, stamps every non-zero
current either writer sends; Solar's 30 s gate reads that stamp (its own and
Manual's), so the step back up after a phase change's closing write waits 30
s on every path. The closing current is fixed once per sequence, retries too.
Rows: every select shape (refused, ignored, late; settle refused three times;
T7 1 -> 3 and T22 3 -> 1) with nevers().

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-23 01:25:06 +01:00

825 lines
39 KiB
Python

"""EV-20: the car charger's Solar mode, spare sun to the car: the arithmetic,
the modes, the start, the hold and the pause, the phases (T1-T20, T56).
`python3 -B test_ev20.py`
The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and
`chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit
rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section
names the T-ids and N-ids of reports/EV-20-test-plan.md it implements.
"Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare
2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start.
Times are the cycle's second; `race` runs use the production order (read, the
writer settles, the cycle).
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import json
import math
import os
import random
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402
from app import mqtt, validate, web, main as app_main # noqa: E402
from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402
import ev20_sun as S # noqa: E402
from chargersim import SimCharger # noqa: E402
from ev20_kit import * # noqa: E402,F401,F403
from ev20_kit import LOG, check, fails, report # noqa: E402,F401
from named_absence import given, nth, present # noqa: E402,F401
from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401
_until)
# =========================================================================== #
print("1. THE ARITHMETIC (T3, T9, T10, N11)")
# =========================================================================== #
# T3: signed spare. `spare_w(car, site battery W (discharge +), grid)`.
T3 = {"a": ((0.0, -5000.0, -2000.0), 7000.0),
"b": ((0.0, -6000.0, 6900.0), -900.0),
"c": ((1380.0, 9600.0, -5220.0), -3000.0),
"d": ((1380.0, 9600.0, -7220.0), -1000.0),
"e": ((0.0, 0.0, -3000.0), 3000.0)}
got = {k: spare_w(*a) for k, (a, _) in T3.items()}
check(f"T3: the signed spare, (a) to (e) = 7000, -900, -3000, -1000, 3000 W "
f"within 1 W ({got})",
all(got[k] is not None and abs(got[k] - w) <= 1.0
for k, (_, w) in T3.items()))
clip = {k: max(0.0, a[0] + max(0.0, -a[1]) - max(0.0, a[2]))
for k, (a, _) in T3.items()}
check("T3/N11: a clipped formula fails (a), (c) and (e); ours does not: no "
"positive spare from a grid charge or from batteries giving more than "
"the house uses",
all(abs(clip[k] - T3[k][1]) > 1.0 for k in "ace")
and got["b"] < 0 and got["c"] < 0 and got["d"] < 0)
check("T3/T4: a missing or non-numeric figure is no spare (None, NaN, "
"'unavailable')",
spare_w(0.0, None, 100.0) is None
and spare_w(0.0, float("nan"), 100.0) is None
and spare_w(0.0, 100.0, "unavailable") is None
and spare_w(None, 0.0, 0.0) is None)
# T9: the margin, both priorities, Car first on a 2400 W spare, 1 phase.
t9 = {m: amps_for(carmode.car_target_w(2400.0, 0.0, m, carmode.FIRST_CAR), 1,
16) for m in (0, 100, 300, 1000)}
check(f"T9: ev_margin_w 0, 100, 300, 1000 on a 2400 W spare: 10, 10, 9, 6 A "
f"({t9})", t9 == {0: 10.0, 100: 10.0, 300: 9.0, 1000: 6.0})
check("T9: the margin is taken once, in both priorities (Batteries first with "
"the room 0 is the same as Car first)",
carmode.car_target_w(2400.0, 0.0, 300, carmode.FIRST_BATT)
== carmode.car_target_w(2400.0, 5000.0, 300, carmode.FIRST_CAR)
== 2100.0)
# T10: rounded down, clamped.
t10 = (amps_for(1900, 1), amps_for(2299, 1), amps_for(6900, 3),
amps_for(6899, 3))
check(f"T10: 1900 and 2299 W on 1 phase, 6900 and 6899 W on 3: 8, 9, 10, 9 A "
f"({t10}); a rounding would give 10 at 2299 W",
t10 == (8.0, 9.0, 10.0, 9.0) and round(2299 / 230) == 10)
check("T10: ev_max_a 10 with 6.9 kW on 1 phase is 10 A; a 13 A station limit "
"bounds it to 13 A", amps_for(6900, 1, 10) == 10.0
and amps_for(6900, 1, 13) == 13.0)
rnd = random.Random(20)
bad10 = []
for _ in range(1000):
tw = rnd.choice([float("nan"), -rnd.uniform(0, 5000), 1e9,
rnd.uniform(0, 12000), None])
n = rnd.choice([1, 3])
clamp = rnd.choice([None, 6.0, 10.0, 13.0, 16.0, 32.0, 40.0])
p = SolarPlan(n)
for k in range(400):
p.step(float(k), target_w=tw, n_now=n, auto=False, clamp=clamp,
start_s=120.0, pause_s=300.0)
if p.a > 0.0:
hi = math.floor(clamp) if clamp is not None else CH.ENTITY_MAX_A
want = amps_for(tw, p.n, clamp)
if not (CH.MIN_A <= p.a <= hi) or (
p.why == "running" and p.a != want):
bad10.append((tw, n, clamp, p.a, want))
break
check(f"T10/N1 property: 1000 random spares (NaN, negative, 1e9, None), "
f"phases and limits: every non-zero current is floor(target / (230 x "
f"n)) inside [6 A, clamp] ({bad10[:2]})", not bad10)
# =========================================================================== #
print("\n2. MODE SOLAR AND WHERE SPARE SUN GOES FIRST (T1, T2, T56)")
# =========================================================================== #
res1 = {}
async def _web(p, c):
import socket
import aiohttp
from aiohttp import web as aioweb
app = web.build_app(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()
try:
async with aiohttp.ClientSession() as s:
for key, body in (("solar", {"action": "car_mode",
"value": "solar"}),
("night", {"action": "car_mode",
"value": "night"}),
("first", {"action": "car_sun_first",
"value": "car"})):
async with s.post(f"http://127.0.0.1:{port}/action",
json=body) as rr:
res1[key] = (rr.status, await rr.json(content_type=None))
async with s.get(f"http://127.0.0.1:{port}/status?lang=en") as rr:
res1["status"] = await rr.json(content_type=None)
finally:
await runner.cleanup()
r1 = run("T1", std, 400, mode="off", first="batteries", events={
10: _web,
200: act("car_mode", "night", res1, "night_a"),
201: act("car_mode", "bogus", res1, "bogus_a")})
c1 = r1["c"]
w1 = cur_writes(r1)
check(f"T1: POST /action car_mode solar from the page is stored at once "
f"(car_mode=solar) and answers 200 ({res1.get('solar')})",
res1.get("solar", (0,))[0] == 200
and r1["store"].data.get("car_mode") == "solar")
check(f"T1: the next writer steps run Solar with no restart: the start rule "
f"from the choice, 10 A at 10 + 120 s ({w1[:2]})",
bool(w1) and w1[0][1] == 10.0 and 128 <= w1[0][0] <= 132)
check("T1: Night and Bogus are refused (page and action), nothing changes",
res1.get("night", (0,))[0] == 400 and "error" in res1.get("night_a", {})
and "error" in res1.get("bogus_a", {}) and c1.car_mode == "solar"
and r1["store"].data.get("car_mode") == "solar")
pl = dict(mqtt.car_payloads((16, (1, 3))))
sel = pl.get("homeassistant/select/goodwe_ctl_car_mode/config", {})
sf = pl.get("homeassistant/select/goodwe_ctl_car_sun_first/config", {})
check(f"T1: select.goodwe_car_mode options are exactly Off, Manual, Solar "
f"({sel.get('options')})", sel.get("options") == ["Off", "Manual",
"Solar"])
check(f"T2: select.goodwe_car_sun_first is announced with Batteries and Car "
f"({sf.get('options')}), labels as carmode's",
sf.get("object_id") == "goodwe_car_sun_first"
and sf.get("options") == ["Batteries", "Car"]
and mqtt.CAR_FIRST_LABELS == carmode.FIRST_LABELS
and mqtt.CAR_MODE_LABELS == carmode.MODE_LABELS)
check("T1: /status offers Off, Manual and Solar, and where spare sun goes "
"first", res1.get("status", {}).get("car", {}).get("modes")
== ["off", "manual", "solar"]
and res1["status"]["car"].get("first", {}).get("choices")
== ["batteries", "car"])
cmd = mqtt.parse_car_command
check("T1/T2: MQTT parses Solar and the two priorities; Night, Bogus, an "
"unknown label and a retained command are refused",
cmd("goodwe_ctl/car/mode/set", b"Solar", False)[:2]
== ("car_mode", "solar")
and cmd("goodwe_ctl/car/sun_first/set", b"Car", False)[:2]
== ("car_sun_first", "car")
and cmd("goodwe_ctl/car/sun_first/set", b"Batteries", False)[1]
== "batteries"
and cmd("goodwe_ctl/car/mode/set", b"Night", False)[1] is None
and cmd("goodwe_ctl/car/mode/set", b"Bogus", False)[1] is None
and cmd("goodwe_ctl/car/sun_first/set", b"Sun", False)[1] is None
and cmd("goodwe_ctl/car/sun_first/set", b"Car", True)[2] == "retained")
# T1 from MQTT, and T2: the priority from HA, a retained and an unknown one.
r2 = run("T2", S.drive, const(900.0), const(7900.0), dur=260, mode="off",
first="batteries", socs={"a": 71.0, "b": 100.0}, events={
5: mqtt_cmd("goodwe_ctl/car/mode/set", b"Solar"),
160: mqtt_cmd("goodwe_ctl/car/sun_first/set", b"Car", True),
161: mqtt_cmd("goodwe_ctl/car/sun_first/set", b"Sun"),
200: mqtt_cmd("goodwe_ctl/car/sun_first/set", b"Car")})
c2, tr2 = r2["c"], r2["trace"]
w2 = cur_writes(r2)
check(f"T1: MQTT 'Solar' is applied: the store says solar and Batteries "
f"first writes 8 A (scenario 2) after the start rule ({w2[:1]})",
r2["store"].data.get("car_mode") == "solar" and bool(w2)
and w2[0][1] == 8.0)
check("T2: a retained command and an unknown label change nothing (Batteries "
"until 200 s)", all(x["why"] for x in tr2)
and c2.car_sun_inputs is not None
and [x for x in w2 if x[0] < 200] == w2[:1])
check(f"T2: Car at 200 s: the arithmetic changes next cycle and the new "
f"current (16 A) is written at once, the 30 s rule passed ({w2})",
any(t in (200.0, 201.0) and a == 16.0 for t, a, _ in w2)
and r2["store"].data.get("car_sun_first") == "car")
async def _rebuild():
st = r2["store"]
from app.main import Controller
import opt11_identity as rig
c = Controller(dict(c2.o), r2["plant"], st, rig._Pub(),
stop=asyncio.Event())
return c.car_first, c.car_mode
check(f"T2: the priority is runtime state in the store and survives a "
f"rebuild of the Controller on it ({asyncio.run(_rebuild())})",
asyncio.run(_rebuild()) == ("car", "solar"))
# T2: the 30 s rule still applies after a priority change.
r2b = run("T2b", S.drive, const(900.0), const(7900.0), dur=200,
first="batteries", socs={"a": 71.0, "b": 100.0},
events={130: act("car_sun_first", "car")})
w2b = cur_writes(r2b)
check(f"T2: Car chosen 10 s after Batteries first wrote 8 A: 16 A waits for "
f"the 30 s rule (at 150 s, not before) ({w2b})",
[a for _, a, _ in w2b] == [8.0, 16.0] and w2b[1][0] == w2b[0][0] + 30)
# T56: rollback. The base build has no Solar in MODES; with it taken out, the
# stored mode reads as Off and the action is refused.
keep_modes = carmode.MODES
carmode.MODES = (carmode.OFF, carmode.MANUAL)
try:
t56 = carmode.start_mode({}, "solar")
finally:
carmode.MODES = keep_modes
check("T56: a build without Solar reads a stored car_mode=solar as Off "
"(start_mode); on head unknown modes still map to Off",
t56 == "off" and carmode.start_mode({}, "night") == "off"
and carmode.start_mode({}, "bogus") == "off"
and carmode.start_mode({}, "solar") == "solar")
# =========================================================================== #
print("\n3. THE SPARE, THE ROOM, THE START (T5, T6, T7, T8, T9, T13)")
# =========================================================================== #
for race in (False, True):
tag = "race" if race else "step"
r6 = run("T6", S.drive, const(900.0), const(7900.0), dur=600,
first="batteries", socs={"a": 71.0, "b": 100.0}, race=race)
c6, tr6 = r6["c"], r6["trace"]
w6 = cur_writes(r6)
batt = [r6["plant"].batt_of("a", t) for t in range(400, 600)]
exp = [r6["plant"].grid(t) for t in range(400, 600)]
ok6 = next((x["ok"] for x in tr6 if x["ok"] is not None), None)
check(f"T6 [{tag}]: scenario 2, Batteries first: spare 7000, room 5000, "
f"car 1900 W -> 8 A on 1 phase after the 120 s dwell ({w6}, the "
f"dwell from {ok6})",
[a for _, a, _ in w6] == [8.0] and ok6 is not None
and 120 <= w6[0][0] - ok6 <= 121
and tr6[300]["spare"] is not None
and abs(tr6[300]["spare"] - 7000.0) <= 50.0
and selects(r6) == [])
check(f"T6 [{tag}]: steady: A charges 5000 +-100 W, export about 160 W, "
f"no drift ({min(batt):.0f}..{max(batt):.0f} W, grid "
f"{min(exp):.0f}..{max(exp):.0f} W)",
all(-5100.0 <= b <= -4900.0 for b in batt)
and all(-260.0 <= g <= -60.0 for g in exp))
nevers(r6, f"T6 [{tag}]")
blk6 = homeview.car_block(c6, None)
check(f"T6: the Why is why.solar_batt ({blk6['why']!r})",
blk6["why"].startswith("Batteries first."))
check("T6: v1 room (rating - charge now) would give 16 A on this spare: the "
"rating rule is what makes it 8 A",
amps_for(carmode.car_target_w(7000.0, 5000.0 - 5000.0, 100,
carmode.FIRST_BATT), 1, 16) == 16.0
and amps_for(carmode.car_target_w(7000.0, 5000.0, 100,
carmode.FIRST_BATT), 1, 16) == 8.0)
r7 = run("T7", S.drive, const(900.0), const(7900.0), dur=700, first="car",
socs={"a": 71.0, "b": 100.0})
c7 = r7["c"]
w7, s7 = cur_writes(r7), selects(r7)
check(f"T7: scenario 2, Car first, auto: starts on 1 phase at the clamp "
f"(16 A) ({w7[:1]})", bool(w7) and w7[0][1] == 16.0
and r7["trace"][150]["ph"] == 1)
check(f"T7: after 180 s at >= 4.5 kW the safe sequence to 3 phases, then "
f"floor(6900/690) = 10 A ({w7}, selects {[(x[0], x[2]) for x in s7]})",
[a for _, a, _ in w7] == [16.0, 0.0, 10.0] and len(s7) == 1
and s7[0][2] == 3 and 298 <= w7[1][0] <= 303)
bt7 = [r7["plant"].batt(t) for t in range(500, 700)]
check(f"T7: the batteries charge 100 +-50 W ({min(bt7):.0f}..{max(bt7):.0f})",
all(-150.0 <= b <= -50.0 for b in bt7))
check(f"T7: the Why is why.solar_car "
f"({homeview.car_block(c7, None)['why']!r})",
homeview.car_block(c7, None)["why"].startswith("Car first:"))
nevers(r7, "T7")
# T8: the room.
r8a = run("T8a", S.drive, const(500.0), step_fn((200, 4500.0), base=8000.0),
dur=560, first="car", socs={"a": 60.0, "b": 100.0},
events={200: act("car_sun_first", "batteries")})
w8a = cur_writes(r8a)
check(f"T8 (a): Batteries first, spare 4000 W, A may charge (5000 W), B full: "
f"4000 - 5000 - 100 < 0: the 6 A hold, then 0 A at the pause ({w8a})",
[a for _, a, _ in w8a][-2:] == [6.0, 0.0]
and 499 <= w8a[-1][0] <= 502)
r8b = run("T8b", std, 200, sun=const(3500.0), first="batteries")
check(f"T8 (b): both full, spare 3000 W: 2900 W, 12 A "
f"({cur_writes(r8b)})", [a for _, a, _ in cur_writes(r8b)] == [12.0])
def _room(socs, **setup):
out = {}
def probe(p, c):
for k, v in setup.items():
v(c)
out["room"] = c.car_room_w()
S.drive(const(500.0), const(7500.0), dur=3, first="batteries",
socs=socs, events={2: probe})
return out["room"]
def _a_off(c):
from app import packmode
from app.store import unit_key
c.store.data[unit_key("inverter-a", packmode.USE_KEY)] = False
def _a_refuse(c):
c.inverters[0].refused = -1
rooms = {"off": _room({"a": 60.0, "b": 60.0}, x=_a_off),
"refusing": _room({"a": 60.0, "b": 60.0}, x=_a_refuse),
"ceiling": _room({"a": 100.0, "b": 60.0}),
"both": _room({"a": 60.0, "b": 60.0})}
check(f"T8 (c): A Off, refusing a charge or at its ceiling leaves B's 4600 W "
f"as the room; both able gives 9600 W ({rooms})",
rooms == {"off": 4600.0, "refusing": 4600.0, "ceiling": 4600.0,
"both": 9600.0})
r8c = run("T8c", S.drive, const(500.0), const(7500.0), dur=200,
first="batteries", socs={"a": 100.0, "b": 60.0})
check(f"T8 (c): spare 7000, room 4600: 2300 W, 10 A ({cur_writes(r8c)})",
[a for _, a, _ in cur_writes(r8c)] == [10.0])
r8d = run("T8d", S.drive, const(900.0), step_fn((300, 1600.0), base=7900.0),
dur=700, first="batteries", socs={"a": 71.0, "b": 100.0})
w8d = cur_writes(r8d)
check(f"T8 (d): scenario 2's cloud (sun 1.6 kW, spare 700): 6 A for 300 s, "
f"then 0 A ({w8d})", [a for _, a, _ in w8d] == [8.0, 6.0, 0.0]
and 599 <= w8d[-1][0] <= 602)
# T9 through the real Controller: Car first, spare 2400 W.
t9r = {}
for m in (0, 100, 300, 1000):
rr = S.drive(const(500.0), step_fn((200, 2900.0), base=5000.0), dur=260,
first="car", socs=dict(FULL), opts={"ev_margin_w": m})
t9r[m] = [a for t, a, _ in cur_writes(rr) if t >= 200]
check(f"T9: running, then a 2400 W spare: the Controller writes 10, 10, 9, "
f"6 A for margins 0, 100, 300, 1000 W ({t9r}; 1400 W is 6 A, not a "
f"hold)", t9r == {0: [10.0], 100: [10.0], 300: [9.0], 1000: [6.0]})
# T10 through the Controller: a 13 A station limit with plenty of sun.
sim10 = SimCharger(setpoint_a=0)
r10 = run("T10", std, 300, sun=const(9000.0), sim=sim10,
opts={"ev_phases": "1"},
events={200: lambda p, c: setattr(p.ch, "station_a", 13.0)})
check(f"T10: 16 A, then the station limit comes down to 13 A: Solar writes "
f"13 A and never more, clamp_faults == [] ({cur_writes(r10)})",
[a for _, a, _ in cur_writes(r10)] == [16.0, 13.0]
and r10["c"].charger.clamp_faults == [])
# T5: the car's figure.
p5 = {}
r5 = run("T5", std, 200, events={50: lambda p, c: p5.update(
trusted=c.car.car_w_trusted(c.car_now()), spare=c.car_spare_w(
c.car_now()))})
tr5 = r5["trace"]
check(f"T5 (i)(ii): paused/idle, state B at 0 A, a fresh 0 W: the car counts "
f"0 W and the spare is computed (car_w_trusted is None there) ({p5})",
tr5[50]["st"] == "B" and p5.get("spare") is not None
and abs(p5["spare"] - 2400.0) < 1.0 and p5.get("trusted", 1) is None)
check(f"T5 (i)(ii): the start rule passes on it: 10 A at 120 s "
f"({cur_writes(r5)[:1]})", cur_writes(r5)[:1]
and cur_writes(r5)[0][1] == 10.0)
def _stop_car_keep_c(p, c):
"""The car stops drawing while mode3 stays C, and the power sensor
sticks at what it read."""
p.ch.freeze_power()
p.ch.stop_delay_s = 1e9
p.ch.full = True
sim5 = SimCharger(setpoint_a=0)
r5c = run("T5c", std, 900, sim=sim5, sun=const(2900.0),
events={300: _stop_car_keep_c})
tr5c = r5c["trace"]
gone = next((x["t"] for x in tr5c if x["t"] > 300 and x["spare"] is None),
None)
w5c = cur_writes(r5c)
check(f"T5 (iii): a frozen 2300 W figure after the car stopped (mode3 C): "
f"dropped once the energy meter does not corroborate it (<= 110 s; "
f"at {gone})", gone is not None and gone - 300 <= 110)
check(f"T5 (iii): then the hold: no new current once it is dropped, 0 A by "
f"300 + 2 s after it ({w5c})",
gone is not None and w5c[-1][1] == 0.0
and gone + 299 <= w5c[-1][0] <= gone + 302
and not [x for x in w5c if gone <= x[0] and x[1] > 0.0])
def _down(p, c):
p.ch.go_unavailable(True)
r5d = run("T5d", std, 500, events={300: _down})
check("T5 (iv): a charger reading older than 15 s (this driver: the charger "
"does not answer) is no spare, and nothing is written while it is down",
r5d["trace"][330]["spare"] is None
and [a for _, a, _ in cur_writes(r5d)] == [10.0])
# C6: one write clock. A plan whose start dwell is done waits 30 s from
# Manual's latest non-zero write (`ext_at`), and from its own.
p6 = SolarPlan(1)
starts6 = []
for k in range(300):
p6.ext_at = 150.0
p6.step(float(k), target_w=3000.0, n_now=1, auto=False, clamp=16,
start_s=120.0, pause_s=300.0)
if p6.a > 0.0 and not starts6:
starts6.append(k)
check(f"C6: Manual wrote at 150 s; Solar's start dwell is done at 120 s but "
f"its first current waits for 180 s ({starts6})", starts6 == [180])
r6m = std(400, mode="manual", sim=SimCharger(setpoint_a=0),
opts={"ev_start_min": 1},
events={100: act("car_current", 12), 105: act("car_mode", "solar")})
w6m = [(t, a) for t, a, _ in cur_writes(r6m)]
man = [x[0] for x in r6m["sim"].log if x[2] > 0.0 and x[0] <= 106]
check(f"C6: Manual writes 12 A, then Solar is chosen: Solar's own first "
f"write is 0 A, and no current of Solar's within 30 s of Manual's "
f"({man}, Solar {w6m})",
w6m[:1] and w6m[0][1] == 0.0 and present(nth(man, -1))
and not [t for t, a in w6m if a > 0.0 and t - nth(man, -1) < 30.0])
# T13: the start rule.
for race in (False, True):
tag = "race" if race else "step"
d = 1 if race else 0
ra = std(900, sun=const(500.0 + 100.0 + 1609.0), race=race)
rb = std(200, sun=const(500.0 + 100.0 + 1610.0), race=race)
rc = std(300, sun=lambda t: 500.0 + 100.0 + (1500.0 if at_s(t) == 60
else 1610.0), race=race)
check(f"T13 (a) [{tag}]: 1609 W on 1 phase for 900 s: no start",
cur_writes(ra) == [])
# `race`: the writer's step runs a second later, the meter's sample not.
check(f"T13 (b) [{tag}]: 1610 W: 7 A at 120 s, not 119 s "
f"({cur_writes(rb)})", [(t, a) for t, a, _ in cur_writes(rb)]
in ([(120.0, 7.0)], [(120.0 + d, 7.0)]))
check(f"T13 (c) [{tag}]: a 1-cycle dip to 1500 W at 60 s: the start at "
f"181 s ({cur_writes(rc)})", [(t, a) for t, a, _ in cur_writes(rc)]
in ([(181.0, 7.0)], [(181.0 + d, 7.0)]))
rd = run("T13d", std, 300, sun=const(500.0 + 100.0 + 6900.0), phases=3)
wd, sd = cur_writes(rd), selects(rd)
check(f"T13 (d): auto, 6900 W, the charger left on 3 phases: 0 A kept, "
f"select 1, then the current; no non-zero write on 3 phases first "
f"({wd}, {[(x[0], x[2], x[4]) for x in sd]})",
len(sd) == 1 and sd[0][2] == 1 and sd[0][4] == 0.0
and wd and wd[0][1] == 16.0 and wd[0][0] >= sd[0][0] - 1 + 10)
nevers(rd, "T13 (d)")
re1 = std(600, sun=const(500.0 + 100.0 + 4829.0), phases=3,
opts={"ev_phases": "3"})
re2 = std(200, sun=const(500.0 + 100.0 + 4830.0), phases=3,
opts={"ev_phases": "3"})
check(f"T13 (e): ev_phases 3: none at 4829 W; 7 A at 120 s for 4830 W "
f"({cur_writes(re2)})", cur_writes(re1) == []
and [(t, a) for t, a, _ in cur_writes(re2)] == [(120.0, 7.0)]
and selects(re2) == [])
# =========================================================================== #
print("\n4. THE 30 s / 1 A RULE, THE HOLD AND THE PAUSE (T11, T12, T14-T16)")
# =========================================================================== #
# T11: 8 A worth, write at t; at t+5 10 A worth.
for race in (False, True):
tag = "race" if race else "step"
r11 = std(300, sun=step_fn((125, 600.0 + 2300.0), base=600.0 + 1840.0),
race=race)
w11 = cur_writes(r11)
check(f"T11 (a) [{tag}]: 8 A at t, 10 A worth from t+5: 10 A at t+30 "
f"(+-1 cycle), not before ({w11})",
[a for _, a, _ in w11] == [8.0, 10.0]
and 29 <= w11[1][0] - w11[0][0] <= 31)
r11b = std(800, sun=step_fn((130, 600.0 + 8.9 * 230.0),
base=600.0 + 1840.0), race=race)
check(f"T11 (b) [{tag}]: 8 -> 8.9 A worth for 600 s: no write "
f"({cur_writes(r11b)})", [a for _, a, _ in cur_writes(r11b)]
== [8.0])
# T12: an exit 2 s after a normal write: the 0 A within 1 cycle.
T12 = {
"Stop": lambda p, c: setattr(c, "auto", False),
"Off": act("car_mode", "off"),
"shadow": lambda p, c: c.o.__setitem__("shadow_mode", "on"),
"unplug": lambda p, c: p.ch.unplug(),
"latch": lambda p, c: setattr(c.circ_wd, "tripped", True),
"error": lambda p, c: (setattr(p.ch, "error", "12: Socket error"),
p.ch.fault("E")),
}
t12 = {}
for name, fn in T12.items():
rr = std(260, sun=step_fn((150, 600.0 + 2760.0), base=600.0 + 2300.0),
events={152: fn})
w = cur_writes(rr)
t12[name] = w
check(f"T12: every exit 2 s after a normal write (12 A at 150 s) gets its "
f"0 A within 1 cycle, the 30 s gate never delays it "
f"({ {k: v[-2:] for k, v in t12.items()} })",
all(len(v) >= 2 and v[-2][:2] == (150.0, 12.0) and v[-1][1] == 0.0
and v[-1][0] - 152 <= 1 for v in t12.values()))
p12 = SolarPlan(1)
p12.a, p12.set_at, p12.low_since, p12.why = 6.0, 98.0, -200.0, "hold"
p12.step(100.0, target_w=1000.0, n_now=1, auto=False, clamp=16, start_s=120,
pause_s=300)
check("T12: the pause is never gated: a plan whose last change was 2 s ago "
"pauses at its 300 s (0 A)", p12.a == 0.0)
# T14: at 8 A, the target drops to 1200 W (5.2 A).
for race in (False, True):
tag = "race" if race else "step"
d = 1 if race else 0
r14 = std(800, sun=step_fn((200, 600.0 + 1200.0), base=600.0 + 1840.0),
race=race, rows=False)
w14 = cur_writes(r14)
check(f"T14 (a) [{tag}]: 6 A written, then 0 A once at 300 s, not 299 s "
f"({w14})", [a for _, a, _ in w14] == [8.0, 6.0, 0.0]
and w14[2][0] in (500.0, 500.0 + d))
r14b = std(1100, sun=lambda t: 600.0 + (1840.0 if at_s(t) < 200 else
1500.0 if 499 <= at_s(t) < 510
else 1200.0),
race=race)
w14b = cur_writes(r14b)
check(f"T14 (b) [{tag}]: back >= 6 A at 299 s, then low again: no 0 A "
f"then; the next dip needs a fresh 300 s ({w14b})",
[a for _, a, _ in w14b][-1:] == [0.0]
and w14b[-1][0] in (810.0, 810.0 + d)
and not any(a == 0.0 and t < 800 for t, a, _ in w14b))
blk14 = homeview.car_block(r14["c"], None)
check(f"T14: the card says Waiting for sun and why.solar_paused "
f"({blk14['chip']!r}, {blk14['why']!r})",
blk14["chip"] == "Waiting for sun"
and blk14["why"].startswith("Too little spare sun for 6 A."))
# T15: the hold at the peak reserve.
r15a = run("T15a", S.drive, const(500.0), step_fn((200, 1000.0),
base=3000.0),
dur=600, first="car", socs={"a": 19.0, "b": 19.0},
opts={"peak_soc_floor": 20})
tr = r15a["trace"]
imp = sum(max(0.0, min(x["car"], x["grid"])) for x in tr if x["t"] >= 200)
w15a = cur_writes(r15a)
check(f"T15 (a): A and B at the peak reserve: the car's grid import in the "
f"hold is at most 1380 W x 302 s (116 Wh), then 0 A ({imp / 3600:.0f} "
f"Wh, {w15a})", imp <= 1380.0 * 302.0 and w15a[-1][1] == 0.0
and 499 <= w15a[-1][0] <= 502)
r15b = run("T15b", S.drive, const(500.0), step_fn((200, 1000.0),
base=3000.0),
dur=600, first="car", socs={"a": 19.0, "b": 60.0},
opts={"peak_soc_floor": 20})
gr = [x["grid"] for x in r15b["trace"] if 240 <= x["t"] < 495]
check(f"T15 (b): A at the reserve, B at 60 %: B covers the car, the grid "
f"is about 0 in the hold ({min(gr):.0f}..{max(gr):.0f} W)",
all(abs(g) <= 150.0 for g in gr))
# T16: the wall clock jumps; the dwells are monotonic.
for jump in (3600.0, -3600.0):
def jmp(p, c, jump=jump):
p.utc_off = jump
r16 = std(800, sun=step_fn((200, 600.0 + 1200.0), base=600.0 + 1840.0),
events={60: jmp, 300: jmp})
w16 = cur_writes(r16)
check(f"T16 ({jump:+.0f} s): a start dwell and a hold across a wall-clock "
f"jump: start at 120 s, pause at 300 s, monotonic ({w16})",
[(t, a) for t, a, _ in w16][:1] == [(120.0, 8.0)]
and w16[-1] == (500.0, 0.0, True))
# =========================================================================== #
print("\n5. AUTO PHASES, THE SAFE SEQUENCE, A ONE-PHASE CAR (T17-T20)")
# =========================================================================== #
for race in (False, True):
tag = "race" if race else "step"
d = 1 if race else 0
r17 = std(800, sun=step_fn((400, 600.0 + 4500.0), base=600.0 + 3000.0),
race=race)
w17, s17 = cur_writes(r17), selects(r17)
z = [t for t, a, _ in w17 if a == 0.0]
check(f"T17 [{tag}]: 4500 W from 400 s: the sequence starts (its 0 A) at "
f"580 s, not 579 s ({w17}, {[x[0] for x in s17]})",
z[:1] in ([580.0], [580.0 + d]) and len(s17) == 1
and s17[0][2] == 3)
r17b = std(3600, sun=step_fn((400, 600.0 + 4499.0), base=600.0 + 3000.0))
check("T17: 4499 W for an hour on 1 phase: never a select",
selects(r17b) == [])
r17c = std(1900, sun=step_fn((400, 600.0 + 4500.0), (1000, 600.0 + 3999.0),
base=600.0 + 3000.0))
s17c = selects(r17c)
check(f"T17: on 3 phases, 3999 W from 1000 s: to 1 phase at 1300 s "
f"({[(x[0], x[2]) for x in s17c]}, {cur_writes(r17c)[-2:]})",
len(s17c) == 2 and s17c[1][2] == 1 and 1300 <= s17c[1][0] <= 1312
and cur_writes(r17c)[-1][1] == 16.0)
r17d = std(4600, sun=step_fn((400, 600.0 + 4500.0), (1000, 600.0 + 4000.0),
base=600.0 + 3000.0))
check(f"T17: on 3 phases, 4000 W for an hour: never back to 1 phase, no "
f"pause ({[(x[0], x[2]) for x in selects(r17d)]})",
len(selects(r17d)) == 1 and r17d["sim"].setpoint_a == 6.0)
r17e = std(3600, sun=lambda t: 600.0 + 4000.0 + 499.0 * (t % 2))
check("T17: the 4.0-4.5 kW band for an hour: never a select",
selects(r17e) == [])
nevers(r17c, "T17")
# T18: up, down, up within 10 minutes.
r18 = std(2400, sun=step_fn((400, 600.0 + 4600.0), (700, 600.0 + 3000.0),
(1100, 600.0 + 4600.0), base=600.0 + 3000.0))
s18 = [x[0] for x in selects(r18)]
check(f"T18: crossings up, down, up: at most one select per 600 s, the "
f"second waits for 600 s after the first ({s18})",
len(s18) >= 2 and all(b - a >= 600.0 for a, b in zip(s18, s18[1:]))
and s18[1] - s18[0] < 620)
nevers(r18, "T18")
# T19: every Solar phase change, a slow car among them.
for slow in (False, True):
sim19 = SimCharger(setpoint_a=0)
if slow:
sim19.stop_delay_s = 15.0
sim19.ramp_w_s = 300.0
r19 = std(1600, sun=step_fn((400, 600.0 + 6900.0), (1000, 600.0 + 3000.0),
base=600.0 + 3000.0), sim=sim19)
seq_bad = []
log19 = r19["sim"].log
for i, (t, what, v, pw, sp) in enumerate(log19):
if what != "phases":
continue
before = [x for x in log19[:i] if x[1] == "current"]
after = [x for x in log19[i + 1:] if x[1] == "current"]
if not before or before[-1][2] != 0.0:
seq_bad.append(("no 0 A first", t))
if pw >= carmode.QUIET_W and before \
and t - before[-1][0] < carmode.ZERO_WAIT_S:
seq_bad.append(("select while drawing", t, pw))
if not after or after[0][0] - t < carmode.SETTLE_S:
seq_bad.append(("no 10 s settle", t))
n = v
if after and after[0][2] not in (amps_for(
r19["plant"].sun(after[0][0]) - 500.0 - 100.0, n, 16),
CH.MIN_A):
seq_bad.append(("not floor(car_w/(230 x n))", after[0]))
check(f"T19 ({'slow car' if slow else 'quick car'}): every select comes "
f"after the 0 A, under 100 W or out of C (or the 20 s cap), then "
f"10 s, then floor(target/(230 x new n)) ({seq_bad}, "
f"{[(x[0], x[2]) for x in selects(r19)]})",
not seq_bad and len(selects(r19)) == 2)
nevers(r19, f"T19 {'slow' if slow else 'quick'}")
# A car that is still drawing at EV-04's 20 s cap (200 W/s from 6 A on 3
# phases): no select, the current back on the old phases, and the plan back
# where it was (nothing meant for 1 phase is written on 3).
for pmin, back in ((10, 6.0), (5, 0.0)):
sim19f = SimCharger(setpoint_a=0)
sim19f.stop_delay_s, sim19f.ramp_w_s = 15.0, 200.0
r19f = std(1500, sun=step_fn((400, 600.0 + 6900.0),
(1000, 600.0 + 3000.0),
base=600.0 + 3000.0), sim=sim19f,
opts={"ev_pause_min": pmin})
w19f = [(t, a) for t, a, _ in cur_writes(r19f) if t >= 1290]
check(f"T19 (failed, ev_pause_min {pmin}): the car still draws at the "
f"20 s cap: no select to 1 phase; "
f"{'the hold 6 A back on 3 phases' if back else 'the hold has run out, so the 0 A stands (N3)'}"
f"; no 1-phase current on 3 phases "
f"({w19f}, selects {[(x[0], x[2]) for x in selects(r19f)]})",
len(selects(r19f)) == 1 and w19f[:1] == [(1300.0, 0.0)]
and (nth(w19f, 1)[1] == 6.0 if back else len(w19f) == 1)
and not [a for t, a in w19f if a > 6.0])
nevers(r19f, f"T19 (failed, {pmin} min)")
# Review round 1, Major 1: Solar's own 1 -> 3 change (the T7 shape) where the
# select went out but (i) the settle current write is refused once, or (ii)
# the select's read-back comes later than 10 s. Every current written after the
# select is floor(car_w / (230 x the phases the charger reports)): 10 A, never
# the 1-phase 16 A on 3 phases.
class LateSel(SimCharger):
"""The phases select shows in the read-back 12 s late (HA took it)."""
def request_phases(self, n):
keep, self.lag_s = self.lag_s, 12.0
try:
return super().request_phases(n)
finally:
self.lag_s = keep
r7b = S.drive(const(900.0), const(7900.0), dur=500, first="car",
socs={"a": 71.0, "b": 100.0})
ts7 = [x[0] for x in r7b["sim"].log if x[1] == "current"
and x[2] not in (0.0, 16.0)]
for how, sim_ in (("settle write refused once",
TSim(setpoint_a=0, windows=[(nth(ts7, 0) - 1,
nth(ts7, 0) + 1, "error")])),
("settle write ignored once",
TSim(setpoint_a=0, windows=[(nth(ts7, 0) - 1,
nth(ts7, 0) + 2, "ignore")])),
("select confirmed late", LateSel(setpoint_a=0))):
rm1 = S.drive(const(900.0), const(7900.0), dur=600, first="car",
socs={"a": 71.0, "b": 100.0}, sim=sim_)
over = [(x["t"], x["sp"]) for x in rm1["trace"]
if x["ph"] == 3 and x["sp"] > 10.0]
after = [a for t, e, a in rm1["plant"].sets
if e == SET and t > 290.0]
check(f"T19/T33 [{how}]: after the select every current is 10 A for 3 "
f"phases, never 1-phase 16 A on 3 ({len(over)} s over 10 A on 3: "
f"{over[:3]}; currents tried after 290 s {after})",
present(nth(ts7, 0)) and not over and 16.0 not in after
and rm1["sim"].phases_allowed == 3
and rm1["sim"].setpoint_a == 10.0)
nevers(rm1, f"T19/T33 [{how}]")
# Review round 2 (C6, N5): every select shape, 1 -> 3 (T7) and 3 -> 1 (T22):
# no current meant for fewer phases than the charger has, and never two
# different non-zero currents under 30 s apart (the one write clock).
class PhSim(TSim):
"""The phases select: 'lag' (read-back 12 s late), 'error' (HA refuses
it), 'ignore' (HA says yes, the charger keeps its phases)."""
ph_mode = None
def request_phases(self, n):
if self.ph_mode == "lag":
keep, self.lag_s = self.lag_s, 12.0
try:
return super().request_phases(n)
finally:
self.lag_s = keep
keep, self.refuse = self.refuse, self.ph_mode or self.refuse
try:
return super().request_phases(n)
finally:
self.refuse = keep
def _phsim(windows=(), ph=None):
s_ = PhSim(setpoint_a=0, windows=list(windows))
s_.ph_mode = ph
return s_
sun31 = step_fn((300, 600.0 + 4600.0), (700, 600.0 + 3700.0),
base=600.0 + 3000.0)
for how, shape, sim_, back in (
("select refused", "T7", _phsim(ph="error"), 16.0),
("select ignored", "T7", _phsim(ph="ignore"), 16.0),
("select late", "T7", _phsim(ph="lag"), 10.0),
("settle refused 3 times", "T7", _phsim([(313, 330, "error")]), None),
("normal", "T22", _phsim(), None),
("select refused", "T22", _phsim(ph="error"), None),
("select ignored", "T22", _phsim(ph="ignore"), None),
("select late", "T22", _phsim(ph="lag"), None)):
if shape == "T7":
rs_ = S.drive(const(900.0), const(7900.0), dur=900, sim=sim_,
first="car", socs={"a": 71.0, "b": 100.0})
cap3 = 10.0
else:
rs_ = S.drive(const(600.0), sun31, dur=1500, sim=sim_, first="car",
socs={"a": 19.0, "b": 19.0})
cap3 = 5.0 # 3700 - 600 - 100 W on 3 phases, under 6 A
over = [(x["t"], x["sp"]) for x in rs_["trace"]
if x["ph"] == 3 and x["sp"] > max(cap3, 6.0) and x["t"] > 300]
bad_ = nevers(rs_, f"round 2 [{shape}, {how}]")
end = rs_["trace"][-1]
check(f"round 2 [{shape}, {how}]: no current meant for fewer phases on "
f"the charger's ({over[:3]}); end {end['sp']} A on {end['ph']} "
f"phases ({[(x[0], x[1], x[2]) for x in rs_['sim'].log]})",
not over and not bad_
and (back is None or (end["sp"] == back)))
r19a = std(1800, sun=const(600.0 + 6900.0), opts={"ev_phases": "1"})
check(f"T19: fixed 1 with 6.9 kW for 30 min: no select, 16 A "
f"({cur_writes(r19a)})", selects(r19a) == []
and [a for _, a, _ in cur_writes(r19a)] == [16.0])
r19b = std(900, sun=const(600.0 + 3000.0), opts={"ev_phases": "3"},
phases=3)
check("T19: fixed 3 with 3 kW: no select, no start (4830 W needed)",
selects(r19b) == [] and cur_writes(r19b) == [])
r19c = std(1000, sun=step_fn((400, 600.0 + 3000.0), base=600.0 + 5600.0),
opts={"ev_phases": "3"}, phases=3)
check(f"T19: fixed 3 running, then 3 kW: no select, the hold, then the "
f"pause ({cur_writes(r19c)})", selects(r19c) == []
and [a for _, a, _ in cur_writes(r19c)] == [8.0, 6.0, 0.0])
# T20: a one-phase car on a 3-phase allowance.
sim20 = SimCharger(setpoint_a=0)
r20 = run("T20", std, 900, sim=sim20, phases=3, car_phases=1,
opts={"ev_phases": "3"},
sun=step_fn((400, 600.0 + 2900.0 - 100.0), base=600.0 + 4900.0),
events={700: lambda p, c: p.ch.unplug(),
710: lambda p, c: p.ch.plug_in(car_phases=3)})
tr20 = r20["trace"]
marked = next((x["t"] for x in tr20 if x["single"]), None)
w20 = cur_writes(r20)
check(f"T20: the one-phase car is marked within 30 s of drawing (start "
f"{w20[:1]}, marked at {marked})",
marked is not None and w20 and marked - w20[0][0] <= 30)
check(f"T20: on 1-phase arithmetic: 16 A on 4.8 kW, then floor(2800/230) = "
f"12 A on 2.9 kW, no pause from the 4.2 A 3-phase figure ({w20})",
12.0 in [a for t, a, _ in w20 if 400 <= t < 700]
and not any(a == 0.0 for t, a, _ in w20 if t < 700))
check("T20: cleared on unplug; a balanced 3-phase car is never marked",
not tr20[705]["single"] and not any(x["single"] for x in tr20
if x["t"] >= 700))
report()