- every HA power unit is accepted and converted (mW, W, kW, MW), in the probe and in the reading - a power entity that answers in another unit, with no unit, or not as a number makes the reading unavailable: after 30 s it is "Charger not reachable" (amber row, WARNING, notification after 5 min), with a Why that names the cause (EN and NL) Co-Authored-By: Claude <noreply@anthropic.com>
1261 lines
53 KiB
Python
1261 lines
53 KiB
Python
"""EV-03: the car charger seam, read only. `python3 -B test_ev03.py`
|
|
|
|
1. This card never writes to the charger: a full set of cycles with a charger
|
|
configured makes no write and no service call that names a charger entity,
|
|
and nothing in the add-on calls the seam's write methods.
|
|
2. The seam: entities derived by suffix, a reading believes a value only in its
|
|
own unit, mode3 is the primary car state and the display text a fallback.
|
|
3. Default off changes nothing: the same cycles with the new options at their
|
|
defaults give the same writes, status, rows and sensors as without them.
|
|
4. Options and validator: the census, the refusals, the live limit, the probe.
|
|
5. Unreachable: 30 s, one amber row, one notification after 5 minutes, one
|
|
WARNING; back again, and it is taken down.
|
|
6. The Car card: its states, the today figure and a meter reset, EN and NL.
|
|
7. The car is not the house: the House tile and the house profile, and what a
|
|
stale car reading does (not guessed).
|
|
8. The two-writer detector.
|
|
9. The MQTT sensors.
|
|
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
|
"""
|
|
|
|
import ast
|
|
import asyncio
|
|
import io
|
|
import json
|
|
import logging
|
|
import os
|
|
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 chargers as CH, homeview, messages, mqtt, validate # noqa: E402
|
|
from app.main import Controller # noqa: E402
|
|
from app import freshness, selfconfig # noqa: E402
|
|
import chargersim # 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 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)
|
|
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):
|
|
self.sets.append((entity_id, float(value)))
|
|
if entity_id == "number.sp":
|
|
self.batt = float(value)
|
|
return True
|
|
|
|
|
|
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"]}
|
|
CAR = dict(BASE, ev_charger="alfen_ha", ev_max_a=16, ev_phases="auto",
|
|
ev_current_entity="number.wallbox_power_connector_max_current_socket_1")
|
|
SET = "number.wallbox_power_connector_max_current_socket_1"
|
|
|
|
|
|
CLOCK = [1000.0]
|
|
freshness.monotonic = lambda: CLOCK[0] # one clock for the whole file
|
|
|
|
|
|
async def rin(c, t):
|
|
"""`read_inputs` at monotonic second `t`, on the file's one clock."""
|
|
CLOCK[0] = t
|
|
await c.read_inputs(now_mono=t)
|
|
|
|
|
|
def build(opts, site, store=None):
|
|
c = Controller(dict(opts), site, store or _Store(), _Pub(),
|
|
stop=asyncio.Event())
|
|
c.auto = True
|
|
c.dev_min, c.dev_max = -5000.0, 5000.0
|
|
return c
|
|
|
|
|
|
async def run_cycles(c, site, n=12, tick=1.0, sim=None):
|
|
for i in range(n):
|
|
if sim is not None:
|
|
sim.tick(tick)
|
|
await rin(c, 1000.0 + i * tick)
|
|
await c.cycle()
|
|
|
|
|
|
def now_utc():
|
|
return datetime(2026, 11, 15, 9, 30, tzinfo=timezone.utc)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("1. THIS CARD NEVER WRITES TO THE CHARGER")
|
|
# --------------------------------------------------------------------------- #
|
|
sim = SimCharger()
|
|
sim.plug_in()
|
|
sim.set_current(10)
|
|
sim.set_phases(3)
|
|
site = Site(sim, grid=800.0)
|
|
c = build(CAR, site)
|
|
asyncio.run(run_cycles(c, site, n=40, sim=sim))
|
|
print(f" {len(site.sets)} number writes, {len(site.calls)} service calls; "
|
|
f"charger power {sim.power_w:.0f} W, state {sim.state}")
|
|
check("PRECONDITION: the charger was read (the car is charging and the card "
|
|
"knows it)", c.car.status(CLOCK[0]) == "charging"
|
|
and c.car.reading.power_w > 1000)
|
|
check("PRECONDITION: the controller did write the inverter (the cycles are "
|
|
"real)", any(e == "number.sp" for e, _v in site.sets))
|
|
check("no number write names a charger entity",
|
|
not [s for s in site.sets if "wallbox" in s[0]])
|
|
check("no service call names a charger entity",
|
|
not [x for x in site.calls if "wallbox" in json.dumps(x[2] or {})])
|
|
check("no service call of any kind is made but a notification",
|
|
all(x[0] == "persistent_notification" for x in site.calls))
|
|
check("the model's own setpoint is where it was (10 A)", sim.setpoint_a == 10)
|
|
check("charger_writes() finds nothing", site.charger_writes() == [])
|
|
|
|
|
|
def callers_of_writes():
|
|
"""(file, line, name) of every call of the seam's write methods outside
|
|
chargers.py itself."""
|
|
out = []
|
|
for root, _d, files in os.walk(os.path.join(HERE, "app")):
|
|
for f in files:
|
|
if not f.endswith(".py") or f == "chargers.py":
|
|
continue
|
|
tree = ast.parse(io.open(os.path.join(root, f),
|
|
encoding="utf-8").read())
|
|
for n in ast.walk(tree):
|
|
if isinstance(n, ast.Call) and isinstance(n.func,
|
|
ast.Attribute):
|
|
if 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.lineno, n.func.attr))
|
|
return out
|
|
|
|
|
|
check(f"nothing in the add-on calls write_current, write_phases or the "
|
|
f"charger's release ({callers_of_writes()})", not callers_of_writes())
|
|
check("the seam does define them (the next cards use them)",
|
|
all(hasattr(CH.ChargerDriver, m) for m in
|
|
("write_current", "write_phases", "release")))
|
|
_ha = FakeHa(SimCharger())
|
|
asyncio.run(CH.AlfenHaDriver(SET, 16).bind(_ha).write_current(99))
|
|
check("the Alfen driver's write (a later card's) is clamped to the charger "
|
|
"limit, 16 A and not 99", _ha.sets == [(SET, 16.0)])
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n2. THE SEAM")
|
|
# --------------------------------------------------------------------------- #
|
|
ents = CH.entities_for(SET)
|
|
check("the entities come from the setpoint by suffix",
|
|
ents["readback"] == "sensor.wallbox_main_active_max_current_socket_1"
|
|
and ents["state"] == "sensor.wallbox_mode3_state_socket_1"
|
|
and ents["login"] == "binary_sensor.wallbox_https_api_login_status"
|
|
and ents["station"] == "number.wallbox_max_station_current"
|
|
and ents["phases_set"] == "select.wallbox_installation_max_allowed_phases"
|
|
and CH.entities_for(SET.replace("wallbox", "garage_wallbox"))["power"]
|
|
== "sensor.garage_wallbox_active_power_total_socket_1")
|
|
check("a setpoint named otherwise derives nothing",
|
|
CH.entities_for("number.foo") == {} and CH.entities_for("") == {})
|
|
check("the census key is stripped and lowercase",
|
|
CH.census_key(" Number.X ") == "number.x")
|
|
|
|
|
|
def st(eid, state, unit=None):
|
|
a = {"unit_of_measurement": unit} if unit else {}
|
|
return {"entity_id": eid, "state": state, "attributes": a}
|
|
|
|
|
|
def states(**over):
|
|
s = SimCharger()
|
|
s.plug_in()
|
|
s.set_current(0) # connected, no current allowed: mode3 B
|
|
s.tick(5)
|
|
d = {r: s.states()[e] for r, e in CH.entities_for(SET).items()}
|
|
d.update(over)
|
|
return d
|
|
|
|
|
|
r = CH.reading_from_states(states())
|
|
check("a good set of states reads: available, connected, not charging (B)",
|
|
r.available and r.state == "B" and r.connected and not r.charging)
|
|
sim2 = SimCharger()
|
|
sim2.plug_in()
|
|
sim2.set_current(10)
|
|
sim2.set_phases(3)
|
|
sim2.tick(5)
|
|
d = {r_: sim2.states()[e] for r_, e in CH.entities_for(SET).items()}
|
|
rc = CH.reading_from_states(d)
|
|
check("charging: C, 6.9 kW, 3 phases of 10 A, read-back 10 A, station 16 A",
|
|
rc.charging and abs(rc.power_w - 6900) < 1 and len(rc.current_a) == 3
|
|
and abs(rc.current_a[0] - 10) < 0.1 and rc.allowed_a == 10
|
|
and rc.station_a == 16 and rc.phases_allowed == 3)
|
|
rk = CH.reading_from_states(dict(d, power=st("x", "6.9", "kW")))
|
|
check("a power in kW is believed in kW (6 900 W)", abs(rk.power_w - 6900) < 1)
|
|
rn = CH.reading_from_states(dict(d, power=st("x", "6900")))
|
|
check("a power with no unit is NOT believed: the reading is unavailable "
|
|
"(cause 'power unit'), never a guess",
|
|
rn.power_w is None and not rn.available and rn.why == "power unit")
|
|
rn = CH.reading_from_states(dict(d, power=st("x", "6900", "V")))
|
|
check("a power in the wrong unit is not believed either (unavailable)",
|
|
rn.power_w is None and not rn.available and rn.why == "power unit")
|
|
re_ = CH.reading_from_states(dict(d, energy=st("x", "4004850", "Wh")))
|
|
check("energy in Wh is believed in Wh (4004.85 kWh)",
|
|
abs(re_.energy_kwh - 4004.85) < 1e-6)
|
|
re_ = CH.reading_from_states(dict(d, energy=st("x", "4004.85", "W")))
|
|
check("energy in a power unit is absent", re_.energy_kwh is None)
|
|
ra = CH.reading_from_states(dict(d, readback=st("x", "10000", "mA")))
|
|
check("a current in mA is believed in mA (10 A)", abs(ra.allowed_a - 10) < 1e-9)
|
|
ra = CH.reading_from_states(dict(d, readback=st("x", "10")))
|
|
check("a current with no unit is absent", ra.allowed_a is None)
|
|
rf = CH.reading_from_states(dict(d, state=st("x", "unknown"),
|
|
display=st("x", "Wait Vehicle Charging")))
|
|
check("mode3 missing: the entity is not there, so the charger is not available",
|
|
not rf.available)
|
|
rf = CH.reading_from_states(dict(d, state=st("x", "STATE_A"),
|
|
display=st("x", "Charging Normal")))
|
|
check("mode3 wins over the display text (A says no car, whatever the text says)",
|
|
rf.state == "A" and rf.connected is False and rf.charging is False)
|
|
for text, want in (("Wait Vehicle Charging", "connected"),
|
|
("EV Connected", "connected"),
|
|
("Cable connected", "connected"),
|
|
("Charging Normal", "charging"),
|
|
("Available", "none"), ("Booting", None)):
|
|
check(f"display fallback: {text!r} is {want}",
|
|
CH.display_class(text) == want)
|
|
check("mode3 letters: STATE_C, C and 'State C' all read C",
|
|
CH.mode3_letter("STATE_C") == "C" and CH.mode3_letter("C") == "C"
|
|
and CH.mode3_letter("State C") == "C")
|
|
check("login off makes the charger unavailable",
|
|
not CH.reading_from_states(dict(d, login=st("x", "off"))).available)
|
|
check("an unavailable required entity makes it unavailable",
|
|
not CH.reading_from_states(dict(d, readback=st("x", "unavailable"))
|
|
).available)
|
|
check("a charger error is carried (0: No Error is none)",
|
|
CH.reading_from_states(d).error is None
|
|
and CH.reading_from_states(dict(d, error=st("x", "17: Overcurrent"))
|
|
).error == "17: Overcurrent")
|
|
check("a missing optional entity (energy) does not make it unavailable",
|
|
CH.reading_from_states(dict(d, energy=None)).available)
|
|
check("UnavailableCharger reads nothing and writes nothing",
|
|
not CH.UnavailableCharger().configured()
|
|
and not asyncio.run(CH.UnavailableCharger().read()).available
|
|
and not asyncio.run(CH.UnavailableCharger().write_current(10)))
|
|
check("build(): off and a missing entity give UnavailableCharger, alfen_ha "
|
|
"with its entity the Alfen driver",
|
|
isinstance(CH.build(BASE), CH.UnavailableCharger)
|
|
and isinstance(CH.build(dict(BASE, ev_charger="alfen_ha")),
|
|
CH.UnavailableCharger)
|
|
and isinstance(CH.build(CAR), CH.AlfenHaDriver)
|
|
and isinstance(CH.build(dict(CAR, ev_charger="nope")),
|
|
CH.UnavailableCharger))
|
|
pr = asyncio.run(CH.build(CAR).bind(FakeHa(SimCharger())).probe())
|
|
check("the probe finds every entity of the model", pr.ok and not pr.missing
|
|
and pr.station_a == 16)
|
|
pr = asyncio.run(CH.build(CAR).bind(FakeHa(SimCharger(name="other"))).probe())
|
|
check("the probe lists what it does not find, and refuses the charger",
|
|
not pr.ok and "state" in pr.required_missing)
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n3. DEFAULT OFF CHANGES NOTHING")
|
|
# --------------------------------------------------------------------------- #
|
|
DEFAULTS = dict(BASE, ev_charger="off", ev_current_entity="", ev_max_a=16,
|
|
ev_phases="auto")
|
|
|
|
|
|
def outcome(opts):
|
|
simx = SimCharger()
|
|
simx.plug_in()
|
|
simx.set_current(10)
|
|
sitex = Site(simx, grid=900.0, pv=3000.0)
|
|
cx = build(opts, sitex)
|
|
asyncio.run(run_cycles(cx, sitex, n=15, sim=simx))
|
|
p = cx.status_payload()
|
|
p.pop("events", None)
|
|
chk = cx.checks()
|
|
return {"sets": list(sitex.sets), "calls": list(sitex.calls),
|
|
"targets": cx.target, "payload_now": p.get("now"),
|
|
"car": p.get("car"),
|
|
"rows": [(x["id"], x["ok"], x["warn"]) for x in chk
|
|
if x["id"] not in ("controller",)],
|
|
"attn": [a["id"] for a in p.get("attention", [])],
|
|
"mqtt": sorted(cx.mqtt.values[-1]) if cx.mqtt.values else None,
|
|
"optional": mqtt.optional_keys(opts),
|
|
"census": validate.actuator_writers(opts),
|
|
"problems": validate.validate_startup_config(opts),
|
|
"hp": cx.house_profile is None}
|
|
|
|
|
|
a, b = outcome(BASE), outcome(DEFAULTS)
|
|
check("with the defaults (charger off) the writes are the same as without "
|
|
"the options", a["sets"] == b["sets"] and a["calls"] == b["calls"]
|
|
and a["targets"] == b["targets"])
|
|
check("...the Home `now` block, the rows and the attention list are the same",
|
|
a["payload_now"] == b["payload_now"] and a["rows"] == b["rows"]
|
|
and a["attn"] == b["attn"])
|
|
check("...there is no Car card, no charger row and no car sensor",
|
|
b["car"] is None and a["car"] is None
|
|
and not [r_ for r_ in b["rows"] if r_[0].startswith("charger")]
|
|
and b["optional"] == ("pv",)
|
|
and not any(str(k).startswith("car") for k in (b["mqtt"] or [])))
|
|
check("...the census and the validator say the same",
|
|
a["census"] == b["census"] and a["problems"] == b["problems"] == [])
|
|
check("...the House tile is grid + solar + battery, the car taken out of "
|
|
"nothing", b["payload_now"]["house_w"] is not None)
|
|
check("a Controller with the charger off holds the null charger and reads it "
|
|
"never",
|
|
isinstance(build(DEFAULTS, Site(SimCharger())).charger,
|
|
CH.UnavailableCharger))
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n4. OPTIONS AND VALIDATOR")
|
|
# --------------------------------------------------------------------------- #
|
|
check("a charger on with a good entity and 16 A is accepted",
|
|
validate.validate_startup_config(CAR) == [])
|
|
check("an unknown charger is refused, naming the setting",
|
|
any("ev_charger" in p for p in validate.validate_startup_config(
|
|
dict(CAR, ev_charger="tesla"))))
|
|
check("ev_max_a out of 6-40 A is refused (and 5 and 41)",
|
|
all(any("ev_max_a" in p for p in validate.validate_startup_config(
|
|
dict(CAR, ev_max_a=v))) for v in (5, 41, "x")))
|
|
check("ev_phases that is not 1, 3 or auto is refused",
|
|
any("ev_phases" in p for p in validate.validate_startup_config(
|
|
dict(CAR, ev_phases="2"))))
|
|
check("an inverter's setpoint named as the charger is refused (the census)",
|
|
any("ev_current_entity" in p and "number.sp" in p for p in
|
|
validate.validate_startup_config(
|
|
dict(CAR, ev_current_entity="number.sp"))))
|
|
_inv = dict(CAR, setpoint_entity="", inverters=[
|
|
{"name": "a", "setpoint_entity": SET, "max_w": 2500, "bms_soc_floor": 10}])
|
|
check("...also one that sits in the inverter list",
|
|
any("ev_current_entity" in p for p in
|
|
validate.validate_startup_config(_inv)))
|
|
check("...and the same entity with the charger OFF is not a writer, so not "
|
|
"refused", not any("ev_current_entity" in p for p in
|
|
validate.validate_startup_config(
|
|
dict(_inv, ev_charger="off"))))
|
|
check("the charger is not in the inverter census (setup-only still reads 'no "
|
|
"inverter')", SET.lower() not in validate.actuator_writers(CAR)
|
|
and CH.census_entity(CAR) == SET
|
|
and CH.census_entity(dict(CAR, ev_charger="off")) == "")
|
|
msgs = validate.validate_startup_config(dict(CAR, ev_current_entity="number.sp"))
|
|
check("the refusal is at most 30 words and names the label and the key",
|
|
all(len(p.split()) <= 30 for p in msgs)
|
|
and any("“Current setting entity” (ev_current_entity)" in p
|
|
for p in msgs))
|
|
|
|
rows = {eid: {"entity_id": eid, "state": s["state"],
|
|
"unit": s["attributes"].get("unit_of_measurement")}
|
|
for eid, s in SimCharger().states().items()}
|
|
look = validate.charger_probe_for(SET, rows)
|
|
check("the probe lists every entity found, with the limit",
|
|
look["ok"] and look["state"] == "ok" and not look["missing"]
|
|
and look["limit_a"] == 16 and len(look["found"]) == len(CH.ROLES))
|
|
gone = {k: v for k, v in rows.items() if "mode3" not in k}
|
|
look = validate.charger_probe_for(SET, gone)
|
|
check("...and what it does not find (the car state entity)",
|
|
not look["ok"] and ["state", "sensor.wallbox_mode3_state_socket_1"]
|
|
in look["missing"])
|
|
check("...nothing is read when Home Assistant did not answer",
|
|
validate.charger_probe_for(SET, None)["state"] == "unread")
|
|
check("...a setpoint named otherwise says so",
|
|
validate.charger_probe_for("number.foo", rows)["state"] == "no_name")
|
|
notes = validate.config_notes(CAR, entities=gone)
|
|
txt = [n.text for n in notes if "ev_current_entity" in n.keys]
|
|
check("the settings notes name the missing entity",
|
|
any("sensor.wallbox_mode3_state_socket_1" in t for t in txt))
|
|
notes = validate.config_notes(CAR, entities=rows)
|
|
txt = [(n.tier, n.text) for n in notes if "ev_current_entity" in n.keys]
|
|
check("...and say what was found when all is well",
|
|
any(t == "ok" and t2.startswith("Found:") and "16 A" in t2
|
|
for t, t2 in txt))
|
|
nl = [validate.note_text(n, "nl") for n in notes
|
|
if "ev_current_entity" in n.keys]
|
|
check("...in Dutch too", any(t.startswith("Gevonden:") for t in nl))
|
|
lim_notes = validate.config_notes(dict(CAR, ev_max_a=20), entities=rows)
|
|
check("an ev_max_a above the station limit is a note on the settings page",
|
|
any("ev_max_a" in n.keys and "16 A" in n.text for n in lim_notes))
|
|
|
|
# the live refusal of the limit, on the save path
|
|
problems, _unread = asyncio.run(selfconfig.problems_and_ranges(
|
|
dict(CAR, ev_max_a=20), Site(SimCharger())))
|
|
check("saving ev_max_a 20 A with a 16 A station limit is refused, naming the "
|
|
"limit", any("ev_max_a" in p and "16 A" in p for p in problems))
|
|
problems, _unread = asyncio.run(selfconfig.problems_and_ranges(
|
|
dict(CAR), Site(SimCharger())))
|
|
check("...16 A is accepted", not [p for p in problems if "ev_max_a" in p])
|
|
problems, _unread = asyncio.run(selfconfig.problems_and_ranges(
|
|
dict(CAR, ev_max_a=20), Site(SimCharger(name="none"))))
|
|
check("...a charger that cannot be read skips the check (never a guess)",
|
|
not [p for p in problems if "ev_max_a" in p])
|
|
|
|
# run-time: a missing entity refuses the CHARGER, not the add-on
|
|
sim3 = SimCharger(name="other")
|
|
site3 = Site(sim3)
|
|
c3 = build(CAR, site3)
|
|
asyncio.run(run_cycles(c3, site3, n=3, sim=sim3))
|
|
check("a charger whose entities are missing is refused and the add-on runs on "
|
|
"(the inverter is still written)",
|
|
c3.charger_refused == "not_found" and not c3.charger.configured()
|
|
and any(e == "number.sp" for e, _v in site3.sets) and not c3.refused)
|
|
p3 = c3.status_payload()
|
|
check("the Car card says 'Charger not set up', and one amber row",
|
|
p3["car"]["state"] == "setup" and p3["car"]["chip"]
|
|
== "Charger not set up" and p3["car"]["kind"] == "warn"
|
|
and [(x["id"], x["warn"], x["ok"]) for x in c3.checks()
|
|
if x["id"].startswith("charger")] == [("charger_setup", True,
|
|
False)])
|
|
simL = SimCharger(station_a=10)
|
|
siteL = Site(simL)
|
|
cL = build(CAR, siteL)
|
|
asyncio.run(run_cycles(cL, siteL, n=3, sim=simL))
|
|
check("a limit above the charger's station limit refuses the charger too",
|
|
cL.charger_refused == "limit" and cL.status_payload()["car"]["state"]
|
|
== "setup")
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n5. UNREACHABLE: 30 s, ONE ROW, ONE NOTIFICATION AFTER 5 MINUTES")
|
|
# --------------------------------------------------------------------------- #
|
|
sim = SimCharger()
|
|
sim.plug_in()
|
|
sim.set_current(10)
|
|
site = Site(sim)
|
|
logs = []
|
|
|
|
|
|
class _Cap(logging.Handler):
|
|
def emit(self, rec):
|
|
logs.append((rec.levelname, rec.getMessage()))
|
|
|
|
|
|
log = logging.getLogger("goodwe")
|
|
cap = _Cap()
|
|
log.addHandler(cap)
|
|
log.setLevel(logging.DEBUG)
|
|
c = build(CAR, site)
|
|
|
|
|
|
async def at(t):
|
|
sim.tick(1)
|
|
await rin(c, t)
|
|
await c.cycle()
|
|
|
|
|
|
def mine():
|
|
"""The calls about the charger's notification (the inverter's own clamp
|
|
notices are not what this is grading)."""
|
|
return [x for x in site.calls if (x[2] or {}).get("notification_id")
|
|
== "goodwe_charger_unreachable"]
|
|
|
|
|
|
async def story():
|
|
out = {}
|
|
t = 2000.0
|
|
for _ in range(5):
|
|
await at(t)
|
|
t += 1
|
|
out["ok_state"] = c.car.status(t - 1)
|
|
sim.go_unavailable()
|
|
for k in range(29):
|
|
await at(t)
|
|
t += 1
|
|
out["t29"] = (c.car.status(t - 1), len(mine()))
|
|
for k in range(3):
|
|
await at(t)
|
|
t += 1
|
|
out["t32"] = (c.car.status(t - 1), [x["id"] for x in c.checks()
|
|
if x["id"].startswith("charger")])
|
|
out["card32"] = c.status_payload()["car"]
|
|
out["attn32"] = [(a["id"], a["severity"]) for a in
|
|
c.status_payload()["attention"]
|
|
if a["id"].startswith("charger")]
|
|
for k in range(250):
|
|
await at(t)
|
|
t += 1
|
|
out["t282"] = len([x for x in mine() if x[1] == "create"])
|
|
for k in range(60):
|
|
await at(t)
|
|
t += 1
|
|
out["t342"] = len([x for x in mine() if x[1] == "create"])
|
|
sim.go_unavailable(False)
|
|
for k in range(3):
|
|
await at(t)
|
|
t += 1
|
|
out["back"] = (c.car.status(t - 1), [x[1] for x in mine()])
|
|
return out
|
|
|
|
|
|
S = asyncio.run(story())
|
|
log.removeHandler(cap)
|
|
check("PRECONDITION: while it answers, the car is charging (10 A allowed)",
|
|
S["ok_state"] == "charging")
|
|
check("29 s of unavailable is not yet 'not reachable' and raises nothing",
|
|
S["t29"][0] == "charging" and S["t29"][1] == 0)
|
|
check("32 s: the state is 'unreach' and there is one amber row",
|
|
S["t32"][0] == "unreach" and S["t32"][1] == ["charger"])
|
|
check("the card chip is amber 'Charger not reachable' with the Why that says "
|
|
"what the charger does meanwhile",
|
|
S["card32"]["chip"] == "Charger not reachable"
|
|
and S["card32"]["kind"] == "warn"
|
|
and "keeps its last setting, 10 A" in S["card32"]["why"]
|
|
and "Alfen" in S["card32"]["why"])
|
|
check("Needs attention lists it as a warning",
|
|
S["attn32"] == [("charger", "warning")])
|
|
check("after 4.5 minutes there is still no notification, at 5 there is "
|
|
"exactly one", S["t282"] == 0 and S["t342"] == 1)
|
|
check("...and no second one follows (one notification in all)",
|
|
S["t342"] == 1)
|
|
check("the notification is the 'Charger not reachable' warning",
|
|
any(x[0] == "persistent_notification" and x[1] == "create"
|
|
and x[2]["title"] == "Charger not reachable"
|
|
and x[2]["notification_id"] == "goodwe_charger_unreachable"
|
|
for x in site.calls))
|
|
warns = [m for lv, m in logs if lv == "WARNING" and "charger" in m.lower()]
|
|
check(f"exactly one WARNING line, with its reason code ({warns})",
|
|
len(warns) == 1 and "CHARGER_UNREACHABLE" in warns[0]
|
|
and len(warns[0].split()) <= 25)
|
|
check("when it answers again the notification is taken down and the card "
|
|
"recovers", S["back"][0] == "charging"
|
|
and S["back"][1][-1] == "dismiss")
|
|
check("nothing was written to the charger through all of it",
|
|
site.charger_writes() == [])
|
|
|
|
# the 5-minute rule on its own, with a stale clock
|
|
t = CH.CarTracker()
|
|
bad = CH.ChargerReading(available=False, why="x")
|
|
t.observe(bad, 0.0, now_utc(), "d")
|
|
check("tracker: not unreachable at 29.9 s, unreachable at 30 s, notify at "
|
|
"300 s", not t.unreachable(29.9) and t.unreachable(30.0)
|
|
and not t.notify_due(299.9) and t.notify_due(300.0))
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n6. THE CAR CARD")
|
|
# --------------------------------------------------------------------------- #
|
|
|
|
|
|
def card(setup, lang="en", **kw):
|
|
sim_ = SimCharger()
|
|
setup(sim_)
|
|
site_ = Site(sim_)
|
|
c_ = build(CAR, site_)
|
|
asyncio.run(run_cycles(c_, site_, n=kw.get("n", 8), sim=sim_))
|
|
if "after" in kw:
|
|
kw["after"](sim_, site_, c_)
|
|
return c_.status_payload(lang=lang), c_
|
|
|
|
|
|
def charging3(s):
|
|
s.plug_in()
|
|
s.set_phases(3)
|
|
s.set_current(16)
|
|
|
|
|
|
p, c6 = card(charging3)
|
|
car = p["car"]
|
|
check("charging: chip Charging, big line '11.0 kW · 16 A · 3 phases'",
|
|
car["chip"] == "Charging" and car["big"] == "11.0 kW · 16 A · 3 phases"
|
|
and car["kind"] == "ok")
|
|
check("...the mode is Off only", car["mode"] == "off")
|
|
check("...Why says the add-on leaves it alone",
|
|
"leaves it alone" in car["why"])
|
|
pn, _c = card(charging3, "nl")
|
|
check("...in Dutch: Laadt, 11,0 kW · 16 A · 3 fasen",
|
|
pn["car"]["chip"] == "Laadt" and pn["car"]["big"]
|
|
== "11,0 kW · 16 A · 3 fasen")
|
|
p, _c = card(lambda s: (s.plug_in(), s.set_current(0)))
|
|
check("connected with no current allowed: 'Connected, waiting'",
|
|
p["car"]["chip"] == "Connected, waiting"
|
|
and p["car"]["big"] == "Connected, not charging.")
|
|
p, _c = card(lambda s: None)
|
|
check("no car: 'No car connected', 'Nothing to charge.'",
|
|
p["car"]["chip"] == "No car connected"
|
|
and p["car"]["big"] == "Nothing to charge."
|
|
and p["car"]["why"] == "No car is connected.")
|
|
pn, _c = card(lambda s: None, "nl")
|
|
check("...in Dutch", pn["car"]["chip"] == "Geen auto aangesloten"
|
|
and pn["car"]["big"] == "Niets te laden.")
|
|
|
|
|
|
def full_car(s):
|
|
s.plug_in()
|
|
s.set_current(10)
|
|
s.car_full()
|
|
|
|
|
|
async def _full_story():
|
|
sim_ = SimCharger()
|
|
full_car(sim_)
|
|
site_ = Site(sim_)
|
|
c_ = build(CAR, site_)
|
|
out = []
|
|
t = 3000.0
|
|
for i in range(130):
|
|
sim_.tick(1)
|
|
await rin(c_, t)
|
|
await c_.cycle()
|
|
if i in (30, 70, 120):
|
|
out.append(c_.car.status(t))
|
|
t += 1
|
|
return out, c_
|
|
|
|
|
|
(early, mid, late), cf = asyncio.run(_full_story())
|
|
check("a car that stopped by itself (B with current allowed) reads 'Connected, "
|
|
"waiting' for 60 s, then 'Car is full'",
|
|
early == "waiting" and mid == "full" and late == "full")
|
|
check("...the card says 'Car is full'",
|
|
cf.status_payload()["car"]["chip"] == "Car is full")
|
|
|
|
|
|
def _slow_c(sim_):
|
|
sim_.plug_in()
|
|
sim_.set_current(10)
|
|
|
|
|
|
async def _c_low():
|
|
sim_ = SimCharger()
|
|
sim_.plug_in()
|
|
sim_.set_current(10)
|
|
sim_.tick(5)
|
|
site_ = Site(sim_)
|
|
c_ = build(CAR, site_)
|
|
t = 5000.0
|
|
seen = []
|
|
for i in range(700):
|
|
sim_.state = "C"
|
|
sim_.power_w = 120.0 # C, under 200 W, 10 A allowed
|
|
await rin(c_, t)
|
|
if i in (300, 650):
|
|
seen.append(c_.car.status(t))
|
|
t += 1
|
|
return seen
|
|
|
|
|
|
check("mode3 C under 200 W for 10 minutes with 6 A or more allowed is full "
|
|
"(not before)", asyncio.run(_c_low()) == ["charging", "full"])
|
|
|
|
# today's energy
|
|
t = CH.CarTracker()
|
|
D = "2026-11-15"
|
|
|
|
|
|
def rd(kwh):
|
|
return CH.ChargerReading(available=True, state="C", power_w=5000.0,
|
|
energy_kwh=kwh, allowed_a=10.0, setpoint_a=10.0)
|
|
|
|
|
|
t.observe(rd(4000.0), 1.0, now_utc(), D)
|
|
t.observe(rd(4001.5), 2.0, now_utc(), D)
|
|
t.observe(rd(4003.0), 3.0, now_utc(), D)
|
|
check("today kWh counts what the meter went up since the day began (3.0)",
|
|
abs(t.today_kwh - 3.0) < 1e-9)
|
|
t.observe(rd(0.4), 4.0, now_utc(), D)
|
|
check("a meter that resets to near zero counts from its new zero (3.4), not a "
|
|
"negative", abs(t.today_kwh - 3.4) < 1e-9)
|
|
t.observe(rd(1.4), 5.0, now_utc(), D)
|
|
check("...and goes on from there (4.4)", abs(t.today_kwh - 4.4) < 1e-9)
|
|
t.observe(rd(1.4), 6.0, now_utc(), "2026-11-16")
|
|
check("a new day starts again at 0", t.today_kwh == 0.0)
|
|
t2 = CH.CarTracker()
|
|
t2.load(t.dump())
|
|
check("it survives a restart through the store", t2.day == "2026-11-16"
|
|
and t2.today_kwh == 0.0 and t2.last_kwh == 1.4)
|
|
t3 = CH.CarTracker()
|
|
t3.observe(CH.ChargerReading(available=True, state="B", power_w=0.0,
|
|
energy_kwh=None), 1.0, now_utc(), D)
|
|
check("a charger with no energy meter has no figure (not 0)",
|
|
t3.today_kwh == 0.0 and t3.last_kwh is None)
|
|
p, c6 = card(charging3)
|
|
check("the card says how much was charged today when it knows",
|
|
p["car"]["today"] is not None and "charged today" in p["car"]["today"])
|
|
check("...and the store holds it", "car_today" in c6.store.data
|
|
and c6.store.data["car_today"]["day"])
|
|
|
|
# the states have words in both languages, and the long ones are split
|
|
with homeview.in_lang("nl"):
|
|
nlw = {k: homeview.car_state_word(k) for k in
|
|
("charging", "waiting", "none", "full", "unreach", "setup", None)}
|
|
check("every state has a Dutch chip", all(nlw.values())
|
|
and nlw["unreach"] == "Laadpaal onbereikbaar")
|
|
check("no entity id is on the card or in its words",
|
|
"wallbox" not in json.dumps(p["car"]) and "sensor." not in json.dumps(
|
|
p["car"]))
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n7. THE CAR IS NOT THE HOUSE")
|
|
# --------------------------------------------------------------------------- #
|
|
nb = homeview.now_block(grid_w=7000.0, pv_w=1000.0, batt_w=-1000.0,
|
|
has_solar=True, shadow=False)
|
|
nc = homeview.now_block(grid_w=7000.0, pv_w=1000.0, batt_w=-1000.0,
|
|
has_solar=True, shadow=False, car_w=6900.0)
|
|
check("without a charger House is grid + solar + battery (7.0 kW)",
|
|
nb["house_w"] == 7000.0)
|
|
check("with a charger the car's 6.9 kW is not in House (100 W)",
|
|
abs(nc["house_w"] - 100.0) < 1e-9)
|
|
nu = homeview.now_block(grid_w=7000.0, pv_w=1000.0, batt_w=-1000.0,
|
|
has_solar=True, shadow=False, car_unknown=True)
|
|
check("a car that cannot be read leaves House with no figure ('No reading')",
|
|
nu["house_w"] is None and nu["lines"]["house"] == "No reading")
|
|
|
|
sim = SimCharger()
|
|
sim.plug_in()
|
|
sim.set_phases(3)
|
|
sim.set_current(10)
|
|
site = Site(sim, grid=7500.0, batt=0.0, pv=500.0)
|
|
c = build(CAR, site)
|
|
asyncio.run(run_cycles(c, site, n=12, sim=sim))
|
|
n_ = c.status_payload()["now"]
|
|
car_w = c.car.reading.power_w
|
|
check(f"in the real controller House excludes the {car_w:.0f} W car "
|
|
f"(House {n_['house_w']:.0f} W)",
|
|
car_w > 5000 and abs(n_["house_w"] - (site.grid + site.pv + c.site_batt_w
|
|
- car_w)) < 1.0)
|
|
|
|
# the house profile's sample
|
|
samples = []
|
|
|
|
|
|
class _HP:
|
|
def add(self, now, w):
|
|
samples.append(w)
|
|
return False
|
|
|
|
def estimator(self):
|
|
return None
|
|
|
|
|
|
def profile_sample(setup):
|
|
del samples[:]
|
|
sim_ = SimCharger()
|
|
setup(sim_)
|
|
site_ = Site(sim_, grid=7500.0, batt=0.0, pv=500.0)
|
|
opts = dict(CAR, pv_forecast_entity="sensor.fc", battery_modes_enabled=True)
|
|
c_ = build(opts, site_)
|
|
c_.house_profile = _HP()
|
|
asyncio.run(run_cycles(c_, site_, n=12, sim=sim_))
|
|
return c_, site_, list(samples)
|
|
|
|
|
|
c_p, site_p, got = profile_sample(lambda s: (s.plug_in(), s.set_phases(3),
|
|
s.set_current(10)))
|
|
want = site_p.grid + c_p.site_batt_w - c_p.car.reading.power_w
|
|
check(f"the house profile's sample leaves the car out (last sample "
|
|
f"{got[-1]:.0f} W, want {want:.0f} W; the car is "
|
|
f"{c_p.car.reading.power_w:.0f} W)",
|
|
len(got) >= 10 and abs(got[-1] - want) < 1.0
|
|
and c_p.car.reading.power_w > 5000)
|
|
c_q, site_q, got = profile_sample(lambda s: None)
|
|
check(f"with no car the sample is the whole load, as before "
|
|
f"({got[-1]:.0f} W = grid + battery)",
|
|
abs(got[-1] - (site_q.grid + c_q.site_batt_w)) < 1.0)
|
|
# not fresh: the last good reading is long ago and the charger now fails
|
|
c_r, site_r, _g = profile_sample(lambda s: (s.plug_in(), s.set_phases(3),
|
|
s.set_current(10)))
|
|
del samples[:]
|
|
c_r.car.last_ok = 0.0
|
|
site_r.charger.go_unavailable()
|
|
|
|
|
|
async def _stale_cycle():
|
|
await rin(c_r, 1013.0)
|
|
await c_r.cycle()
|
|
|
|
|
|
asyncio.run(_stale_cycle())
|
|
check("a car reading older than stale_input_s: the House profile skips that "
|
|
"moment (None), it does not keep the last car figure",
|
|
samples and samples[-1] is None)
|
|
mono_now = c_r.car_now()
|
|
check("...and the House tile shows no reading, as the rule says "
|
|
"(freshness: the car's power counts only while the last good reading "
|
|
"is within stale_input_s, the meter's own bound)",
|
|
c_r.car.car_w(mono_now) is None and c_r.car_term() == (0.0, True)
|
|
and c_r.status_payload()["now"]["house_w"] is None)
|
|
check("the stale bound is the meter's own (15 s from stale_input_s)",
|
|
CH.CarTracker(stale_s=15.0).stale_s == 15.0
|
|
and build(dict(CAR, stale_input_s=40), Site(SimCharger())
|
|
).car.stale_s == 40.0)
|
|
tt = CH.CarTracker(stale_s=15.0)
|
|
tt.observe(rd(1.0), 100.0, now_utc(), D)
|
|
check("tracker: fresh at 15 s, not at 15.1 s",
|
|
tt.car_w(115.0) == 5000.0 and tt.car_w(115.1) is None)
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n8. THE TWO-WRITER DETECTOR")
|
|
# --------------------------------------------------------------------------- #
|
|
sim = SimCharger()
|
|
sim.plug_in()
|
|
sim.set_current(10)
|
|
site = Site(sim)
|
|
c = build(CAR, site)
|
|
|
|
|
|
async def writer_story():
|
|
t = 7000.0
|
|
out = {}
|
|
for _ in range(5):
|
|
await rin(c, t)
|
|
t += 1
|
|
out["quiet"] = [x["id"] for x in c.checks() if x["id"] == "charger_writer"]
|
|
sim.set_current(12) # the owner's automation
|
|
await rin(c, t)
|
|
t += 1
|
|
out["changed"] = [(x["id"], x["ok"], x["warn"]) for x in c.checks()
|
|
if x["id"] == "charger_writer"]
|
|
out["attn"] = [(a["id"], a["severity"], a["title"])
|
|
for a in c.status_payload()["attention"]
|
|
if a["id"] == "charger_writer"]
|
|
return out
|
|
|
|
|
|
W = asyncio.run(writer_story())
|
|
check("with nothing changing the charger there is no row", W["quiet"] == [])
|
|
check("a change of the setpoint (another writer) shows the grey info row",
|
|
W["changed"] == [("charger_writer", True, True)])
|
|
check("...in Needs attention as info, titled in plain words",
|
|
W["attn"] == [("charger_writer", "info",
|
|
"Something else changes the charger")])
|
|
check("...in Dutch too", messages.row_charger_writer().nl
|
|
== "Iets anders wijzigt de laadpaal en deze add-on leest alleen.")
|
|
tw = CH.CarTracker()
|
|
tw.observe(CH.ChargerReading(available=True, setpoint_a=10, allowed_a=10), 1,
|
|
now_utc(), D)
|
|
tw.observe(CH.ChargerReading(available=True, setpoint_a=None, allowed_a=10), 2,
|
|
now_utc(), D)
|
|
check("a reading that did not answer (None) is not a change",
|
|
tw.writer_at_utc is None)
|
|
tw.observe(CH.ChargerReading(available=True, setpoint_a=10, allowed_a=8), 3,
|
|
now_utc(), D)
|
|
check("a change of the read-back alone is another writer",
|
|
tw.writer_at_utc is not None)
|
|
check("it stays for an hour and then goes",
|
|
tw.other_writer(now_utc() + timedelta(minutes=59))
|
|
and not tw.other_writer(now_utc() + timedelta(minutes=61)))
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n9. THE MQTT SENSORS")
|
|
# --------------------------------------------------------------------------- #
|
|
check("the three car sensors are announced only with a charger on",
|
|
mqtt.optional_keys(CAR) == ("pv", "car_power", "car_state",
|
|
"car_today_kwh")
|
|
and mqtt.optional_keys(BASE) == ("pv",))
|
|
pl = dict(mqtt.discovery_payloads(include=mqtt.optional_keys(CAR)))
|
|
names = sorted(k for k in pl if "_car_" in k)
|
|
check(f"discovery announces three sensors, goodwe_car_power, "
|
|
f"goodwe_car_state and goodwe_car_today_kwh ({names})",
|
|
[pl[k]["object_id"] for k in names] == [
|
|
"goodwe_car_power", "goodwe_car_state", "goodwe_car_today_kwh"]
|
|
and all(k.startswith("homeassistant/sensor/") for k in names))
|
|
check("...and no command entity (no select, number or switch for the car)",
|
|
not [k for k in pl if "car" in k and not k.startswith(
|
|
"homeassistant/sensor/")])
|
|
sim = SimCharger()
|
|
sim.plug_in()
|
|
sim.set_phases(3)
|
|
sim.set_current(10)
|
|
site = Site(sim)
|
|
c = build(CAR, site)
|
|
asyncio.run(run_cycles(c, site, n=10, sim=sim))
|
|
c.publish()
|
|
sent = c.mqtt.values[-1]
|
|
check("publish() sends the three car values on their topics",
|
|
sent.get("car_state") == "Charging" and sent["car_power"] > 5000
|
|
and "car_today_kwh" in sent)
|
|
c0 = build(BASE, Site(SimCharger()))
|
|
c0.publish()
|
|
check("...and none of them without a charger",
|
|
not [k for k in c0.mqtt.values[-1] if k.startswith("car_")])
|
|
vals = c.car_values()
|
|
check("published values: state text, power in W, today kWh",
|
|
vals["car_state"] == "Charging" and vals["car_power"] > 5000
|
|
and vals["car_today_kwh"] is not None)
|
|
sim.go_unavailable()
|
|
asyncio.run(run_cycles(c, site, n=40, sim=sim))
|
|
vals = c.car_values()
|
|
check("unreachable: the state says so, power and today are not zero but "
|
|
"absent for power (HA's None payload)",
|
|
vals["car_state"] == "Charger not reachable"
|
|
and vals["car_power"] == mqtt.PAYLOAD_NONE)
|
|
check("an absent number goes out as HA's own 'None' payload, and the PV rule "
|
|
"(ABSENT_AS_UNKNOWN is one key) is not widened",
|
|
mqtt.ABSENT_AS_UNKNOWN == frozenset({"pv"}))
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n10. ROUND 2: A MISSING POWER READING IS AN UNKNOWN TERM, NEVER AN ERROR")
|
|
# --------------------------------------------------------------------------- #
|
|
import traceback # noqa: E402
|
|
from named_absence import nth # noqa: E402
|
|
|
|
|
|
def bad_power(kind):
|
|
"""A controller with one good reading, then (inside stale_s) an AVAILABLE
|
|
reading whose power is missing: `unavailable`, or in a non-power unit."""
|
|
sim_ = SimCharger()
|
|
sim_.plug_in()
|
|
sim_.set_phases(3)
|
|
sim_.set_current(10)
|
|
site_ = Site(sim_, grid=7500.0, batt=0.0, pv=500.0)
|
|
opts = dict(CAR, pv_forecast_entity="sensor.fc", battery_modes_enabled=True)
|
|
c_ = build(opts, site_)
|
|
del samples[:]
|
|
c_.house_profile = _HP()
|
|
asyncio.run(run_cycles(c_, site_, n=8, sim=sim_))
|
|
good_w = c_.car.reading.power_w
|
|
pw = f"sensor.{sim_.x}_active_power_total_socket_1"
|
|
orig = site_._all
|
|
|
|
def broken():
|
|
out = orig()
|
|
if kind == "unavailable":
|
|
out[pw] = dict(out[pw], state="unavailable")
|
|
else:
|
|
out[pw] = dict(out[pw], attributes={"unit_of_measurement": "V"})
|
|
return out
|
|
site_._all = broken
|
|
del samples[:]
|
|
res = {"good_w": good_w, "err": None}
|
|
try:
|
|
CLOCK[0] = 1000.0 + 8
|
|
asyncio.run(rin(c_, 1008.0)) # 1 s after the good one
|
|
res["fresh"] = c_.car.fresh(CLOCK[0])
|
|
res["avail"] = c_.car.reading.power_w is None
|
|
res["reachable"] = c_.car.reading.available
|
|
res["why"] = c_.car.reading.why
|
|
res["term"] = c_.car_term()
|
|
res["now"] = c_.status_payload()["now"]
|
|
res["card"] = c_.status_payload()["car"]
|
|
asyncio.run(c_.cycle()) # the trade cycle's profile step
|
|
res["sample"] = samples[-1] if samples else "none"
|
|
res["vals"] = c_.car_values()
|
|
except Exception: # noqa: BLE001
|
|
res["err"] = traceback.format_exc().strip().splitlines()[-1]
|
|
return res
|
|
|
|
|
|
for kind in ("unavailable", "wrong unit"):
|
|
r_ = bad_power(kind)
|
|
check(f"{kind}: EXPECTED BEHAVIOUR (round 4): the reading is UNAVAILABLE "
|
|
f"(not 'available without power'), so it goes down the unreachable "
|
|
f"path; its cause is {r_.get('why')!r}, and it is still inside "
|
|
f"stale_s on this first read", r_["err"] is None
|
|
and r_.get("reachable") is False and r_.get("fresh") is True
|
|
and r_.get("avail") is True
|
|
and r_.get("why") == ("power unit" if kind == "wrong unit"
|
|
else "no answer from power"))
|
|
check(f"{kind}: car_term, /status, the trade cycle and the MQTT values do "
|
|
f"not raise ({r_['err']})", r_["err"] is None)
|
|
check(f"{kind}: the term is UNKNOWN (never 0 W): House shows no reading and "
|
|
f"the profile sample is None", r_["err"] is None
|
|
and r_["term"] == (0.0, True) and r_["now"]["house_w"] is None
|
|
and r_["sample"] is None)
|
|
check(f"{kind}: the card shows no power figure and the MQTT power is the "
|
|
f"None payload", r_["err"] is None
|
|
and r_["card"]["power_w"] is None
|
|
and r_["vals"]["car_power"] == mqtt.PAYLOAD_NONE)
|
|
|
|
# E and F: the charger's own error states
|
|
for letter in ("E", "F"):
|
|
rr = CH.ChargerReading(available=True, state=letter, power_w=0.0,
|
|
allowed_a=10.0, setpoint_a=10.0)
|
|
tk = CH.CarTracker()
|
|
tk.observe(rr, 1.0, now_utc(), D)
|
|
check(f"mode3 {letter} is the defined state 'fault', not a blank",
|
|
tk.status(1.0) == "fault")
|
|
sim_f = SimCharger()
|
|
sim_f.plug_in()
|
|
sim_f.set_current(10)
|
|
site_f = Site(sim_f)
|
|
c_f = build(CAR, site_f)
|
|
asyncio.run(run_cycles(c_f, site_f, n=4, sim=sim_f))
|
|
sim_f.fault("E")
|
|
sim_f.tick(1)
|
|
asyncio.run(rin(c_f, 1010.0))
|
|
pf = c_f.status_payload()
|
|
check("fault card (EN): chip, big line, Why, amber",
|
|
pf["car"]["chip"] == "Charger fault" and pf["car"]["kind"] == "warn"
|
|
and pf["car"]["big"] == "The charger reports a fault."
|
|
and pf["car"]["why"] == "The charger reports a fault. Check it at the "
|
|
"charger itself.")
|
|
pfn = c_f.status_payload(lang="nl")
|
|
check("fault card (NL)", pfn["car"]["chip"] == "Laadpaalstoring"
|
|
and pfn["car"]["big"] == "De laadpaal meldt een storing."
|
|
and pfn["car"]["why"] == "De laadpaal meldt een storing. Controleer ze "
|
|
"aan de laadpaal zelf.")
|
|
check("the MQTT state says it too", c_f.car_values()["car_state"]
|
|
== "Charger fault")
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n11. ROUND 3: THE POWER ENTITY IS REQUIRED, AND READS IN W OR kW")
|
|
# --------------------------------------------------------------------------- #
|
|
PW = "sensor.wallbox_active_power_total_socket_1"
|
|
rows_all = {eid: {"entity_id": eid, "state": s["state"],
|
|
"unit": s["attributes"].get("unit_of_measurement")}
|
|
for eid, s in SimCharger().states().items()}
|
|
no_power = {k: v for k, v in rows_all.items() if k != PW}
|
|
look = validate.charger_probe_for(SET, no_power)
|
|
check("the probe refuses a charger with no power entity",
|
|
not look["ok"] and ["power", PW] in look["missing"])
|
|
look = validate.charger_probe_for(SET, dict(rows_all, **{PW: dict(
|
|
rows_all[PW], unit="V")}))
|
|
check("...and one whose power reads in a wrong unit (V)",
|
|
not look["ok"] and look["power_unit"] == "V")
|
|
check("...and one with no unit at all",
|
|
validate.charger_probe_for(SET, dict(rows_all, **{PW: dict(
|
|
rows_all[PW], unit=None)}))["power_unit"] == "none")
|
|
check("kW is accepted (converted), W too",
|
|
validate.charger_probe_for(SET, dict(rows_all, **{PW: dict(
|
|
rows_all[PW], unit="kW")}))["ok"]
|
|
and validate.charger_probe_for(SET, rows_all)["ok"])
|
|
look = validate.charger_probe_for(SET, dict(rows_all, **{PW: dict(
|
|
rows_all[PW], state="unavailable", unit=None)}))
|
|
check("a power entity that is UNAVAILABLE at probe time is not a refusal (it "
|
|
"is the unreachable path)", look["ok"] and not look["missing"])
|
|
nts = validate.config_notes(CAR, entities=no_power)
|
|
check("the settings note for the missing power entity says the charger is not "
|
|
"used (a warning, not info)",
|
|
any(n.tier == "warn" and PW in n.text and "not used" in n.text
|
|
for n in nts))
|
|
nts = validate.config_notes(CAR, entities=dict(rows_all, **{PW: dict(
|
|
rows_all[PW], unit="V")}))
|
|
check("...and so does a wrong unit",
|
|
any(n.tier == "warn" and "power unit" in n.text for n in nts))
|
|
|
|
|
|
class Hide(Site):
|
|
"""The site, with some of the charger's entities hidden or changed."""
|
|
|
|
def __init__(self, charger, hide=(), unit=None, **kw):
|
|
super().__init__(charger, **kw)
|
|
self.hide, self.unit = set(hide), unit
|
|
|
|
def _all(self):
|
|
out = {k: v for k, v in super()._all().items() if k not in self.hide}
|
|
if self.unit and PW in out:
|
|
out[PW] = dict(out[PW], attributes={"unit_of_measurement":
|
|
self.unit})
|
|
return out
|
|
|
|
|
|
def world(site_factory, opts, n=10):
|
|
"""(controller, the Home now block, the last profile sample)."""
|
|
del samples[:]
|
|
sim_ = SimCharger()
|
|
sim_.plug_in()
|
|
sim_.set_phases(3)
|
|
sim_.set_current(10)
|
|
site_ = site_factory(sim_)
|
|
c_ = build(dict(opts, pv_forecast_entity="sensor.fc",
|
|
battery_modes_enabled=True), site_)
|
|
c_.house_profile = _HP()
|
|
asyncio.run(run_cycles(c_, site_, n=n, sim=sim_))
|
|
return c_, c_.status_payload(), samples[-1] if samples else "none"
|
|
|
|
|
|
c_none, p_none, s_none = world(lambda s_: Site(s_, grid=7500.0, pv=500.0),
|
|
BASE)
|
|
for why, factory, want in (
|
|
("no power entity", lambda s_: Hide(s_, hide={PW}, grid=7500.0,
|
|
pv=500.0), "not_found"),
|
|
("a power entity in V", lambda s_: Hide(s_, unit="V", grid=7500.0,
|
|
pv=500.0), "unit")):
|
|
c_x, p_x, s_x = world(factory, CAR)
|
|
check(f"{why}: the charger is refused as 'not set up' ({c_x.charger_refused})",
|
|
c_x.charger_refused == want and not c_x.charger.configured()
|
|
and p_x["car"]["state"] == "setup"
|
|
and p_x["car"]["chip"] == "Charger not set up")
|
|
check(f"{why}: House and the house profile are as with no charger at all "
|
|
f"(House {p_x['now']['house_w']}, sample {s_x})",
|
|
p_x["now"] == p_none["now"] and s_x == s_none
|
|
and p_x["now"]["house_w"] is not None and s_x is not None)
|
|
check(f"{why}: the add-on still runs (the inverter is written) and one "
|
|
f"amber row says so", any(e == "number.sp" for e, _v in
|
|
c_x.hass.sets)
|
|
and [x["id"] for x in c_x.checks() if x["id"].startswith("charger")]
|
|
== ["charger_setup"])
|
|
check("the unit refusal's Why is plain and in both languages",
|
|
"no power unit" in p_x["car"]["why"]
|
|
and "geen vermogenseenheid" in c_x.status_payload(lang="nl")["car"]["why"])
|
|
# unavailable at start: NOT refused, the unreachable path
|
|
c_u, p_u, _s = world(lambda s_: Hide(s_, grid=7500.0, pv=500.0), CAR, n=3)
|
|
sim_u = SimCharger()
|
|
sim_u.plug_in()
|
|
sim_u.go_unavailable()
|
|
site_u = Site(sim_u)
|
|
c_u2 = build(CAR, site_u)
|
|
asyncio.run(run_cycles(c_u2, site_u, n=40, sim=sim_u))
|
|
check("a charger that is unavailable from the first read is not refused; it "
|
|
"is the unreachable path", c_u2.charger_refused is None
|
|
and c_u2.charger.configured()
|
|
and c_u2.status_payload()["car"]["state"] == "unreach")
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
print("\n12. ROUND 4: A POWER ENTITY THAT CANNOT BE BELIEVED IS UNREACHABLE")
|
|
# --------------------------------------------------------------------------- #
|
|
class PowerSite(Site):
|
|
"""The site, with the charger's power entity overridden: `pw` is
|
|
(state, unit) or None for the model's own."""
|
|
|
|
pw = None
|
|
|
|
def _all(self):
|
|
out = super()._all()
|
|
if self.pw is not None and PW in out:
|
|
st_, un_ = self.pw
|
|
a = {"unit_of_measurement": un_} if un_ else {}
|
|
out[PW] = dict(out[PW], state=st_, attributes=a)
|
|
return out
|
|
|
|
|
|
def story4(segments):
|
|
"""Run (pw override, cycles) segments on one controller. -> what was
|
|
visible at the END of each segment, and the controller."""
|
|
sim_ = SimCharger()
|
|
sim_.plug_in()
|
|
sim_.set_phases(3)
|
|
sim_.set_current(10)
|
|
site_ = PowerSite(sim_, grid=7500.0, batt=0.0, pv=500.0)
|
|
c_ = build(dict(CAR, pv_forecast_entity="sensor.fc",
|
|
battery_modes_enabled=True), site_)
|
|
c_.house_profile = _HP()
|
|
seen, t_ = [], [3000.0]
|
|
|
|
async def go():
|
|
for pw_, n_ in segments:
|
|
site_.pw = pw_
|
|
del samples[:]
|
|
for _ in range(n_):
|
|
sim_.tick(1)
|
|
await rin(c_, t_[0])
|
|
await c_.cycle()
|
|
t_[0] += 1
|
|
p_ = c_.status_payload()
|
|
seen.append({
|
|
"state": p_["car"]["state"], "why": p_["car"]["why"],
|
|
"house": p_["now"]["house_w"], "sample": nth(samples, -1),
|
|
"rows": [x["id"] for x in c_.checks()
|
|
if x["id"].startswith("charger")],
|
|
"car_w": c_.car.car_w(c_.car_now()),
|
|
"notes": len([x for x in site_.calls if (x[2] or {}).get(
|
|
"notification_id") == "goodwe_charger_unreachable"])})
|
|
asyncio.run(go())
|
|
return seen, c_
|
|
|
|
|
|
UNAV, V6900, NOUNIT = ("unavailable", None), ("6900", "V"), ("6900", None)
|
|
for label, bad in (("in V", V6900), ("with no unit", NOUNIT)):
|
|
seen, c4 = story4([(UNAV, 3), (bad, 35), (None, 5)])
|
|
check(f"unavailable at start-up (found, not refused), then back {label}: "
|
|
f"after 30 s the visible state is 'Charger not reachable', with the "
|
|
f"amber row, House 'No reading' and the profile sample None",
|
|
c4.charger_refused is None and nth(seen, 1)["state"] == "unreach"
|
|
and nth(seen, 1)["rows"] == ["charger"] and nth(seen, 1)["house"] is None
|
|
and nth(seen, 1)["sample"] is None and nth(seen, 1)["car_w"] is None)
|
|
check(f"...and the Why names the cause (a unit the add-on cannot use)",
|
|
"unit the add-on cannot use" in nth(seen, 1)["why"])
|
|
check(f"...and it recovers when a good unit returns (Charging, House and "
|
|
f"the profile back)", nth(seen, 2)["state"] == "charging"
|
|
and nth(seen, 2)["rows"] == [] and nth(seen, 2)["house"] is not None
|
|
and nth(seen, 2)["sample"] is not None)
|
|
seen, c4 = story4([(None, 10), (V6900, 40), (None, 5)])
|
|
check("unit changed W -> V at run time: before, Charging; after 30 s, "
|
|
"'Charger not reachable', the row, House and profile unknown",
|
|
nth(seen, 0)["state"] == "charging" and nth(seen, 1)["state"] == "unreach"
|
|
and nth(seen, 1)["rows"] == ["charger"] and nth(seen, 1)["house"] is None
|
|
and nth(seen, 1)["sample"] is None and nth(seen, 2)["state"] == "charging")
|
|
_c_nl = story4([(None, 10), (V6900, 40)])[1]
|
|
check("...and the Dutch Why names it too", "onbruikbare eenheid"
|
|
in _c_nl.status_payload(lang="nl")["car"]["why"])
|
|
seen, c4 = story4([(None, 10), (V6900, 320)])
|
|
check("...and after 5 minutes there is exactly one notification",
|
|
nth(seen, 1)["notes"] == 1)
|
|
seen, c4 = story4([(None, 6), (("6900000", "mW"), 10)])
|
|
check("W -> mW is accepted, converted exactly (6 900 000 mW is 6 900 W): "
|
|
"still Charging, no row, House excludes the car, the profile too",
|
|
nth(seen, 1)["state"] == "charging" and nth(seen, 1)["rows"] == []
|
|
and abs(nth(seen, 1)["car_w"] - 6900.0) < 1e-6 and nth(seen, 1)["house"] is not None
|
|
and nth(seen, 1)["sample"] is not None)
|
|
seen, c4 = story4([(("0.0069", "MW"), 10)])
|
|
check("MW is accepted (0.0069 MW is 6 900 W)",
|
|
abs(nth(seen, 0)["car_w"] - 6900.0) < 1e-6 and nth(seen, 0)["state"] == "charging")
|
|
seen, c4 = story4([(("6.9", "kW"), 10)])
|
|
check("kW still is (6.9 kW is 6 900 W)", abs(nth(seen, 0)["car_w"] - 6900.0) < 1e-6)
|
|
check("the start-up probe accepts every HA power unit and refuses V",
|
|
all(validate.charger_probe_for(SET, dict(rows_all, **{PW: dict(
|
|
rows_all[PW], unit=u)}))["ok"] for u in ("mW", "W", "kW", "MW"))
|
|
and not validate.charger_probe_for(SET, dict(rows_all, **{PW: dict(
|
|
rows_all[PW], unit="V")}))["ok"])
|
|
|
|
print()
|
|
if fails:
|
|
print(f"{len(fails)} FAILED")
|
|
for f_ in fails:
|
|
print(" -", f_)
|
|
sys.exit(1)
|
|
print("all passed")
|