EV-03: car charger seam, Alfen HA driver, read-only Car card
Read-only: nothing in this change writes to the charger. - app/chargers.py: ChargerDriver, AlfenHaDriver, UnavailableCharger, ChargerReading, CarTracker - options ev_charger/ev_current_entity/ev_max_a/ev_phases (default off), Settings group, validator, census - Car card on Home, unreachable row and notification, two-writer info row, MQTT sensors - car out of the House tile and the house profile - tools/chargersim.py charger model, test_ev03.py Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,261 @@
|
||||
#!/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 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 != "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"}[self.state]),
|
||||
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()
|
||||
@@ -36,7 +36,7 @@ sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from aiohttp import web as aioweb # noqa: E402
|
||||
|
||||
from app import homeview, packmode, web # noqa: E402
|
||||
from app import chargers, freshness, homeview, packmode, web # noqa: E402
|
||||
from app.main import Controller # noqa: E402
|
||||
from app.maintenance import DRAIN # noqa: E402
|
||||
from app.setuponly import SetupOnly # noqa: E402
|
||||
@@ -44,6 +44,7 @@ from app.peakguard import PeakDecision # noqa: E402
|
||||
from app.price import PricePoint, PriceProduct, PriceRead # noqa: E402
|
||||
from app.static_tariff import TariffPlan # noqa: E402
|
||||
import translations_lint as TL # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
|
||||
PRICES = [.24, .22, .21, .20, .21, .22, .24, .27, .26, .22, .18, .16, .15,
|
||||
.14, .16, .19, .23, .28, .33, .36, .34, .29, .26, .24]
|
||||
@@ -104,6 +105,61 @@ class Hass:
|
||||
return STATES
|
||||
|
||||
|
||||
# EV-03: the car states. A charger model behind the demo's Home Assistant; the
|
||||
# real `Controller._read_charger()` reads it, so the card is what the add-on
|
||||
# draws, not a picture.
|
||||
CAR_STATES = ("car", "car_none", "car_waiting", "car_full", "car_unreach",
|
||||
"car_setup")
|
||||
CAR_ENTITY = "number.wallbox_power_connector_max_current_socket_1"
|
||||
SIM = SimCharger()
|
||||
|
||||
|
||||
class CarHass(Hass):
|
||||
async def state(self, e):
|
||||
return SIM.states().get(e) or await super().state(e)
|
||||
|
||||
async def states(self):
|
||||
return list(STATES) + list(SIM.states().values())
|
||||
|
||||
|
||||
def car_setup(state):
|
||||
"""Put the model in the state's situation."""
|
||||
global SIM
|
||||
SIM = SimCharger(name="other" if state == "car_setup" else "wallbox")
|
||||
if state in ("car", "car_unreach"):
|
||||
SIM.plug_in()
|
||||
SIM.set_phases(3)
|
||||
SIM.set_current(16)
|
||||
elif state == "car_waiting":
|
||||
SIM.plug_in()
|
||||
SIM.set_current(0)
|
||||
elif state == "car_full":
|
||||
SIM.plug_in()
|
||||
SIM.set_current(10)
|
||||
SIM.car_full()
|
||||
SIM.tick(12)
|
||||
|
||||
|
||||
async def car_feed(c, state):
|
||||
"""The cycle's own read, once a second, like the control loop."""
|
||||
backdated = False
|
||||
n = 0
|
||||
while True:
|
||||
n += 1
|
||||
if state == "car_unreach" and n == 4:
|
||||
SIM.go_unavailable()
|
||||
SIM.tick(1)
|
||||
await c._read_charger(freshness.monotonic())
|
||||
if state == "car_unreach" and c.car.bad_since is not None \
|
||||
and not backdated:
|
||||
backdated = True # 12 minutes in, so the row and the note show
|
||||
c.car.bad_since -= 720.0
|
||||
c.car.bad_since_utc -= timedelta(seconds=720)
|
||||
if state == "car_full" and c.car.b_since is not None and n < 3:
|
||||
c.car.b_since -= 120.0 # the full dwell has passed
|
||||
await asyncio.sleep(1.0)
|
||||
|
||||
|
||||
KETTLE_READS = (-10, 1990, 1990, -10)
|
||||
KETTLE_COUNT = [0]
|
||||
|
||||
@@ -244,7 +300,13 @@ def controller(state):
|
||||
opts = dict(OPTS, shadow_mode="on" if state == "shadow" else "off")
|
||||
if state in P3:
|
||||
opts["battery_modes_enabled"] = True
|
||||
c = Controller(opts, Hass(), Store(), Pub(), stop=asyncio.Event())
|
||||
hass = Hass()
|
||||
if state in CAR_STATES:
|
||||
car_setup(state)
|
||||
opts.update(ev_charger="alfen_ha", ev_current_entity=CAR_ENTITY,
|
||||
ev_max_a=16, ev_phases="auto")
|
||||
hass = CarHass()
|
||||
c = Controller(opts, hass, Store(), Pub(), stop=asyncio.Event())
|
||||
c.auto = True
|
||||
now = datetime.now(timezone.utc)
|
||||
day0, _day1 = homeview.local_day(now)
|
||||
@@ -264,6 +326,12 @@ def controller(state):
|
||||
inv.last_write = 0.0
|
||||
c.grid = -10.0 if state != "shadow" else -2810.0
|
||||
c.pv_w = 3900.0
|
||||
if state in CAR_STATES:
|
||||
# 11 kW to the car on top of a 1.6 kW house, all from the roof
|
||||
c.grid, c.pv_w = 0.0, (12600.0 if state == "car" else 2400.0)
|
||||
for inv in c.inverters:
|
||||
inv.batt = 0.0
|
||||
c.car.stale_s = 15.0
|
||||
if state == "alarm":
|
||||
c.inverters[0].sign_wd.tripped = True
|
||||
if state in P3:
|
||||
@@ -327,9 +395,17 @@ async def main(state, port, host="127.0.0.1"):
|
||||
battery_modes_enabled=state in P3,
|
||||
inverters=[dict(i, bms_soc_floor=10)
|
||||
for i in OPTS["inverters"]])
|
||||
runner = aioweb.AppRunner(web.build_app(c, Supervisor(stored)))
|
||||
stored.update(ev_charger=c.o.get("ev_charger", "off"),
|
||||
ev_current_entity=c.o.get("ev_current_entity", ""),
|
||||
ev_max_a=c.o.get("ev_max_a", 16),
|
||||
ev_phases=c.o.get("ev_phases", "auto"))
|
||||
app = web.build_app(c, Supervisor(stored))
|
||||
runner = aioweb.AppRunner(app)
|
||||
await runner.setup()
|
||||
await aioweb.TCPSite(runner, host, port).start()
|
||||
if state in CAR_STATES:
|
||||
asyncio.get_running_loop().create_task(car_feed(c, state))
|
||||
main.app = app
|
||||
print(f"serving {state} on http://127.0.0.1:{port}/", flush=True)
|
||||
await asyncio.Event().wait()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user