M1 the writer ignores a reading taken before its latest confirmed write. M2 a refused phase select gives the current back and stops after 3 tries (amber row). M3 Off, shadow mode or a control/safety stop before the select undoes the change. M4 the restore on shutdown (and the undo) is clamped. M5 the car's power reaches the alarm path only while the charger's energy meter agrees with it. L1 fuzz other-writer branch reachable and shown to run. L2 one wording. L3 Batteries-help-off text. Co-Authored-By: Claude <noreply@anthropic.com>
379 lines
15 KiB
Python
379 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""EV-03: a model of an Alfen car charger behind Home Assistant, for the unit
|
|
tests and, later, for TEST-23.
|
|
|
|
EV-04 ADDS THE WRITE SIDE: `request_current()` and `request_phases()` are what
|
|
the add-on's writes reach. The new state is taken after `lag_s` seconds of
|
|
model time (the read-back lag), the power RAMPS to it, and `refuse` makes the
|
|
charger ignore a write ("ignore": Home Assistant says yes, the charger does not
|
|
change) or Home Assistant refuse it ("error"). `log` records every write with
|
|
the model's clock and the power and setpoint at that moment, so a test can
|
|
prove the safe phase sequence (0 A first, under 100 W before the phases move).
|
|
|
|
WHERE IT LIVES, AND WHY. The rig's hardware sims (`hwsim.py`, `plantsim.py`) are
|
|
in the infra repo admin/goodwe under `sim/`, pinned by `.gitea/infra-pin`; there
|
|
is no `sim/` in this repository. This card may write only to this repository, so
|
|
the model sits beside the add-on's other tools. Moving it next to `hwsim.py` is a
|
|
copy: it imports nothing from the add-on.
|
|
|
|
WHAT IT MODELS (every entity the add-on's Alfen driver reads, with the names and
|
|
units the leeyuentuen/alfen_wallbox integration gives, from the owner's export):
|
|
|
|
* mode3 state A (no car), B (connected, not charging), C (charging)
|
|
* power that RAMPS to what the car takes (`RAMP_W_S`), 1 or 3 phases
|
|
* the current setpoint, its read-back, the station limit (16 A at the owner's)
|
|
* a full car (it stops by itself: state B with the current still allowed)
|
|
* the integration going unavailable, and the login sensor off
|
|
|
|
from chargersim import SimCharger, FakeHa
|
|
c = SimCharger("wallbox"); c.plug_in(); c.set_current(10); c.tick(30)
|
|
ha = FakeHa(c) # a Home Assistant that serves its states
|
|
|
|
`FakeHa` has the methods the add-on calls (`state`, `number`, `states`,
|
|
`set_number`, `call`) and RECORDS every write, so a test can prove none happened.
|
|
`python3 chargersim.py --selftest` runs the model's own checks. `serve(port)`
|
|
answers the REST calls the add-on makes (`GET /api/states[/<id>]`), for a rig.
|
|
"""
|
|
|
|
import json
|
|
import sys
|
|
|
|
VOLTS = 230.0
|
|
RAMP_W_S = 3000.0 # how fast the power follows its target
|
|
MIN_A = 6.0
|
|
|
|
|
|
class SimCharger:
|
|
def __init__(self, name="wallbox", station_a=16.0, setpoint_a=10.0,
|
|
phases_allowed=1, kwh=4004.85):
|
|
self.x = name
|
|
self.station_a = float(station_a)
|
|
self.setpoint_a = float(setpoint_a)
|
|
self.readback_a = float(setpoint_a)
|
|
self.phases_allowed = phases_allowed
|
|
self.car_phases = 3 # what the car can use
|
|
self.state = "A"
|
|
self.full = False
|
|
self.power_w = 0.0
|
|
self.kwh = float(kwh)
|
|
self.unavailable = False
|
|
self.login_on = True
|
|
self.error = "0: No Error"
|
|
# EV-04: the write side
|
|
self.t = 0.0 # model seconds
|
|
self.lag_s = 0.0 # a write shows in the read-back this late
|
|
self.refuse = None # None | "ignore" | "error"
|
|
self._snap = None # `freeze()`: the readings stop moving
|
|
self._frozen_w = None # `freeze_power()`: only the power does
|
|
self.no_energy = False # a charger with no energy entity
|
|
self.ramp_w_s = RAMP_W_S # how fast the power follows its target
|
|
self.stop_delay_s = 0.0 # mode3 stays C this long after 0 A
|
|
self._c_hold = 0.0
|
|
self.log = [] # (t, what, value, power_w, setpoint_a)
|
|
self._pending = []
|
|
|
|
# -- the world acts on it -------------------------------------------------
|
|
def plug_in(self, car_phases=3):
|
|
self.car_phases = car_phases
|
|
self.full = False
|
|
self.state = "B"
|
|
|
|
def unplug(self):
|
|
self.state, self.power_w = "A", 0.0
|
|
|
|
def car_full(self):
|
|
self.full = True
|
|
|
|
def set_current(self, a):
|
|
"""What an automation (or, later, this add-on) does to the setpoint."""
|
|
a = max(0.0, min(float(a), self.station_a))
|
|
self.setpoint_a = self.readback_a = a
|
|
|
|
def set_phases(self, n):
|
|
self.phases_allowed = 3 if n == 3 else 1
|
|
|
|
def fault(self, letter="E"):
|
|
"""mode3 E or F: the charger's own error states."""
|
|
self.state, self.power_w = letter, 0.0
|
|
|
|
# -- what the add-on's writes reach (EV-04) ----------------------------------
|
|
def request_current(self, a):
|
|
"""`number.set_value` on the current. False: Home Assistant refused it
|
|
(out of the entity's 0-40 A range, or `refuse == "error"`)."""
|
|
a = float(a)
|
|
if a != a or a < 0.0 or a > 40.0 or self.refuse == "error":
|
|
return False
|
|
self.log.append((self.t, "current", a, self.power_w, self.setpoint_a))
|
|
if self.refuse == "ignore":
|
|
return True
|
|
self._later("current", a)
|
|
return True
|
|
|
|
def request_phases(self, n):
|
|
"""`select.select_option` on the installation's allowed phases."""
|
|
if self.refuse == "error" or n not in (1, 3):
|
|
return False
|
|
self.log.append((self.t, "phases", n, self.power_w, self.setpoint_a))
|
|
if self.refuse == "ignore":
|
|
return True
|
|
self._later("phases", n)
|
|
return True
|
|
|
|
def _later(self, what, v):
|
|
if self.lag_s <= 0:
|
|
self._apply(what, v)
|
|
else:
|
|
self._pending.append((self.t + self.lag_s, what, v))
|
|
|
|
def _apply(self, what, v):
|
|
if what == "current":
|
|
self.setpoint_a = self.readback_a = max(0.0, min(v, self.station_a))
|
|
else:
|
|
self.phases_allowed = 3 if v == 3 else 1
|
|
|
|
def writes(self, what=None):
|
|
return [x for x in self.log if what in (None, x[1])]
|
|
|
|
def go_unavailable(self, on=True):
|
|
self.unavailable = bool(on)
|
|
|
|
def login(self, on=True):
|
|
self.login_on = bool(on)
|
|
|
|
# -- time -----------------------------------------------------------------
|
|
@property
|
|
def phases_used(self):
|
|
return min(self.car_phases, self.phases_allowed)
|
|
|
|
def target_w(self):
|
|
if self.state == "A" or self.full or self.setpoint_a < MIN_A:
|
|
return 0.0
|
|
return self.setpoint_a * VOLTS * self.phases_used
|
|
|
|
def tick(self, seconds=1.0):
|
|
for _ in range(int(max(1, round(seconds)))):
|
|
self.t += 1.0
|
|
for p in [x for x in self._pending if x[0] <= self.t]:
|
|
self._pending.remove(p)
|
|
self._apply(p[1], p[2])
|
|
if self.state in ("E", "F"): # a fault: nothing flows, it stays
|
|
self.power_w = 0.0
|
|
continue
|
|
if self.state != "A":
|
|
if self.target_w() > 0:
|
|
self.state, self._c_hold = "C", 0.0
|
|
elif self.state == "C" and self._c_hold < self.stop_delay_s:
|
|
self._c_hold += 1.0 # the car has not let go yet
|
|
else:
|
|
self.state = "B"
|
|
tgt = self.target_w()
|
|
step = self.ramp_w_s
|
|
if self.power_w < tgt:
|
|
self.power_w = min(tgt, self.power_w + step)
|
|
else:
|
|
self.power_w = max(tgt, self.power_w - step)
|
|
self.kwh += self.power_w / 3.6e6
|
|
|
|
# -- what Home Assistant would serve ---------------------------------------
|
|
def _amps(self):
|
|
per = (self.power_w / (VOLTS * self.phases_used)
|
|
if self.phases_used and self.power_w else 0.0)
|
|
return [per if i < self.phases_used else 0.0 for i in range(3)]
|
|
|
|
def freeze(self, on=True):
|
|
"""A stuck sensor: Home Assistant goes on serving the readings of this
|
|
moment, whatever the charger does after it."""
|
|
self._snap = self._build() if on else None
|
|
|
|
def freeze_power(self, on=True):
|
|
"""Only the power sensor sticks, at what it reads now; the energy meter
|
|
and the rest go on telling the truth."""
|
|
self._frozen_w = self.power_w if on else None
|
|
|
|
def states(self) -> dict:
|
|
return self._snap if self._snap is not None else self._build()
|
|
|
|
def _build(self) -> dict:
|
|
x = self.x
|
|
bad = "unavailable" if self.unavailable else None
|
|
|
|
def st(eid, value, unit=None, **attrs):
|
|
a = dict(attrs)
|
|
if unit:
|
|
a["unit_of_measurement"] = unit
|
|
return eid, {"entity_id": eid,
|
|
"state": bad or str(value), "attributes": a}
|
|
amps = self._amps()
|
|
rows = [
|
|
st(f"number.{x}_power_connector_max_current_socket_1",
|
|
f"{self.setpoint_a:g}", "A", min=0, max=40, step=1),
|
|
st(f"sensor.{x}_main_active_max_current_socket_1",
|
|
f"{self.readback_a:g}", "A"),
|
|
st(f"sensor.{x}_mode3_state_socket_1", f"STATE_{self.state}"),
|
|
st(f"sensor.{x}_display_state_socket_1",
|
|
{"A": "Available", "B": "EV Connected",
|
|
"C": "Charging Normal"}.get(self.state, "Error")),
|
|
st(f"sensor.{x}_active_power_total_socket_1",
|
|
f"{self.power_w if self._frozen_w is None else self._frozen_w:.0f}",
|
|
"W"),
|
|
st(f"sensor.{x}_meter_reading_socket_1", f"{self.kwh:.2f}",
|
|
"kWh"),
|
|
st(f"sensor.{x}_current_l1_socket_1", f"{amps[0]:.1f}", "A"),
|
|
st(f"sensor.{x}_current_l2_socket_1", f"{amps[1]:.1f}", "A"),
|
|
st(f"sensor.{x}_current_l3_socket_1", f"{amps[2]:.1f}", "A"),
|
|
st(f"number.{x}_max_station_current", f"{self.station_a:g}", "A"),
|
|
st(f"sensor.{x}_main_station_active_max_current_socket_1",
|
|
f"{self.station_a:g}", "A"),
|
|
st(f"select.{x}_installation_max_allowed_phases",
|
|
"3 Phases" if self.phases_allowed == 3 else "1 Phase"),
|
|
st(f"sensor.{x}_connector_1_max_allowed_of_phases",
|
|
"3 Phases" if self.phases_allowed == 3 else "1 Phase"),
|
|
st(f"sensor.{x}_display_error_number_socket_1", self.error),
|
|
(f"binary_sensor.{x}_https_api_login_status",
|
|
{"entity_id": f"binary_sensor.{x}_https_api_login_status",
|
|
"state": bad or ("on" if self.login_on else "off"),
|
|
"attributes": {"device_class": "connectivity"}}),
|
|
]
|
|
out = dict(rows)
|
|
if self.no_energy:
|
|
out.pop(f"sensor.{x}_meter_reading_socket_1", None)
|
|
return out
|
|
|
|
|
|
class FakeHa:
|
|
"""A Home Assistant that serves a `SimCharger` (and any `extra` states) and
|
|
records every service call and number write it is given."""
|
|
|
|
session = None
|
|
token = ""
|
|
read_only = False
|
|
|
|
def __init__(self, charger=None, extra=None):
|
|
self.charger = charger
|
|
self.extra = dict(extra or {})
|
|
self.calls = [] # (domain, service, data)
|
|
self.sets = [] # (entity, value)
|
|
|
|
def _all(self):
|
|
out = dict(self.extra)
|
|
if self.charger is not None:
|
|
out.update(self.charger.states())
|
|
return out
|
|
|
|
async def state(self, entity_id):
|
|
return self._all().get(entity_id)
|
|
|
|
async def states(self):
|
|
return list(self._all().values())
|
|
|
|
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 limits(self, _entity_id):
|
|
return (-5000.0, 5000.0, 1.0)
|
|
|
|
async def set_number(self, entity_id, value):
|
|
self.sets.append((entity_id, value))
|
|
c = self.charger
|
|
if c is not None and entity_id == \
|
|
f"number.{c.x}_power_connector_max_current_socket_1":
|
|
return c.request_current(value)
|
|
return True
|
|
|
|
async def call(self, domain, service, data=None):
|
|
self.calls.append((domain, service, data))
|
|
c = self.charger
|
|
if c is not None and domain == "select" and service == "select_option" \
|
|
and (data or {}).get("entity_id") == \
|
|
f"select.{c.x}_installation_max_allowed_phases":
|
|
return c.request_phases(
|
|
3 if "3" in str((data or {}).get("option")) else 1)
|
|
return True
|
|
|
|
def charger_writes(self):
|
|
"""Every write or service call that names a charger entity."""
|
|
x = self.charger.x if self.charger else "\0"
|
|
hits = [s for s in self.sets if x in s[0]]
|
|
hits += [c for c in self.calls if x in json.dumps(c[2] or {})]
|
|
return hits
|
|
|
|
|
|
def serve(sim, port=8123):
|
|
"""Answer `GET /api/states` and `GET /api/states/<id>` from `sim`, for a
|
|
rig. Reads only: any POST answers 405, so nothing can write the model."""
|
|
import http.server
|
|
|
|
class H(http.server.BaseHTTPRequestHandler):
|
|
def do_GET(self):
|
|
rows = sim.states()
|
|
path = self.path.split("?")[0].rstrip("/")
|
|
if path.endswith("/api/states"):
|
|
body = list(rows.values())
|
|
else:
|
|
body = rows.get(path.rsplit("/api/states/", 1)[-1])
|
|
self.send_response(200 if body is not None else 404)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.end_headers()
|
|
self.wfile.write(json.dumps(body).encode())
|
|
|
|
def do_POST(self):
|
|
self.send_response(405)
|
|
self.end_headers()
|
|
|
|
def log_message(self, *_a):
|
|
pass
|
|
|
|
srv = http.server.ThreadingHTTPServer(("0.0.0.0", port), H)
|
|
return srv
|
|
|
|
|
|
def _selftest():
|
|
c = SimCharger()
|
|
assert c.states()[f"sensor.wallbox_mode3_state_socket_1"]["state"] == "STATE_A"
|
|
c.plug_in(); c.tick(1)
|
|
assert c.state == "B" or c.state == "C"
|
|
c.set_current(10); c.set_phases(3); c.tick(5)
|
|
assert c.state == "C" and abs(c.power_w - 10 * 230 * 3) < 1, c.power_w
|
|
c.set_phases(1); c.tick(5)
|
|
assert abs(c.power_w - 2300) < 1
|
|
c.set_current(5); c.tick(5)
|
|
assert c.state == "B" and c.power_w == 0 # under 6 A: paused
|
|
c.set_current(10); c.car_full(); c.tick(5)
|
|
assert c.state == "B" and c.power_w == 0 and c.readback_a == 10
|
|
# EV-04: writes, the read-back lag, a refusal
|
|
w = SimCharger(); w.plug_in(); w.tick(1)
|
|
assert w.request_current(12) and w.setpoint_a == 12
|
|
assert not w.request_current(41) and not w.request_current(-1)
|
|
w.lag_s = 3.0
|
|
assert w.request_current(8) and w.readback_a == 12
|
|
w.tick(2); assert w.readback_a == 12
|
|
w.tick(1); assert w.readback_a == 8
|
|
w.refuse = "ignore"
|
|
assert w.request_current(6) and w.readback_a == 8
|
|
w.refuse = "error"
|
|
assert not w.request_current(6) and not w.request_phases(3)
|
|
w.refuse = None; w.lag_s = 0.0
|
|
assert w.request_phases(3) and w.phases_allowed == 3
|
|
assert [x[1] for x in w.writes()] == ["current", "current", "current",
|
|
"phases"], w.writes()
|
|
c.go_unavailable()
|
|
assert c.states()[f"sensor.wallbox_active_power_total_socket_1"]["state"] \
|
|
== "unavailable"
|
|
c.go_unavailable(False); c.login(False)
|
|
assert c.states()["binary_sensor.wallbox_https_api_login_status"]["state"] == "off"
|
|
print("chargersim selftest ok")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if "--selftest" in sys.argv:
|
|
_selftest()
|
|
else:
|
|
srv = serve(SimCharger(), int(sys.argv[1]) if len(sys.argv) > 1 else 8123)
|
|
print("serving the charger model, GET only; Ctrl-C stops it")
|
|
srv.serve_forever()
|