Files
goodwe-addon/goodwe_controller/tools/chargersim.py
T
ev03-devandClaude 678ea13895
checks / unit (pull_request) Successful in 26m50s
infra-pin / fresh (pull_request) Successful in 2s
EV-03 round 2: a missing car power is unknown, and mode3 E/F has a state
- CarTracker.car_w returns None when the current reading carries no power
  (power entity unavailable or in a non-power unit); it can no longer raise
  into the control cycle, /status or the MQTT values.
- mode3 E and F are the card state "fault" (EN and NL).
- chargersim gains fault().

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 12:02:17 +01:00

269 lines
10 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.
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"
# -- 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
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)))):
if self.state in ("E", "F"): # a fault: nothing flows, it stays
self.power_w = 0.0
continue
if self.state != "A":
self.state = "C" if self.target_w() > 0 else "B"
tgt = self.target_w()
step = 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 states(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:.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"}}),
]
return dict(rows)
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))
return True
async def call(self, domain, service, data=None):
self.calls.append((domain, service, data))
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
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()