"""EV-03: the car charger seam, and the Alfen driver behind Home Assistant. SHAPED LIKE `app/drivers.py`'s `Driver` (DECISIONS/EV-03-charger-seam.md): one actuator per site, a census key, a read, a clamped write that says whether the charger took it, and a hand-back. A charger is a modulated actuator with a fail state, not one of DEV-01's on/off loads. THIS CARD NEVER WRITES TO THE CHARGER. `write_current`, `write_phases` and `release` are defined so the seam is whole, and NOTHING in the controller calls them: Off is the only mode. test_ev03.py greps the controller for a call and proves a full cycle makes no service call that names a charger entity. VALUES ARE BELIEVED ONLY IN THEIR OWN UNIT (as TEL-11 does for power): power in a power unit, energy in a kWh unit, current in A. A reading in another unit is absent, never converted by a guess. ABSENCE IS NEVER ZERO. The pure half (`CarTracker`, the state words, the entity table) takes its clock as an argument, so the checks need no sleep. """ from __future__ import annotations import re from dataclasses import dataclass from .hass import BAD_STATES from .solarfc import KWH_PER OFF = "off" ALFEN_HA = "alfen_ha" #: the `ev_charger` values the options accept SELECTABLE = (OFF, ALFEN_HA) PHASES_CHOICES = ("1", "3", "auto") # config.yaml's shipped defaults, mirrored (test_defaults_pin.py checks it). EV_OPTION_DEFAULTS = {"ev_charger": "off", "ev_current_entity": "", "ev_max_a": 16, "ev_phases": "auto"} def max_a(opts: dict): """`ev_max_a` as a float, or None when it is not a number.""" raw = opts.get("ev_max_a", EV_OPTION_DEFAULTS["ev_max_a"]) if raw is None or raw == "": raw = EV_OPTION_DEFAULTS["ev_max_a"] try: return float(raw) except (TypeError, ValueError): return None MIN_A = 6.0 # IEC 61851: no car charges below 6 A ENTITY_MAX_A = 40.0 # the Alfen current entity's own range # Reachability and the car card's timers, in seconds. UNREACHABLE_S = 30.0 # entities unavailable / login off this long NOTIFY_S = 300.0 # then one warning notification FULL_B_S = 60.0 # mode3 B with current allowed this long: car full FULL_C_S = 600.0 # mode3 C under FULL_C_W this long: car full FULL_C_W = 200.0 WRITER_HOLD_S = 3600.0 # "another controller" stays shown this long IDLE_A = 1.0 # a phase under this draws nothing # role -> (entity domain, suffix after `_`). `current` is the setpoint, the # one the installer names; the rest are derived by swapping its suffix. SETPOINT_SUFFIX = "power_connector_max_current_socket_1" ROLES = { "current": ("number", SETPOINT_SUFFIX), "readback": ("sensor", "main_active_max_current_socket_1"), "state": ("sensor", "mode3_state_socket_1"), "display": ("sensor", "display_state_socket_1"), "power": ("sensor", "active_power_total_socket_1"), "energy": ("sensor", "meter_reading_socket_1"), "l1": ("sensor", "current_l1_socket_1"), "l2": ("sensor", "current_l2_socket_1"), "l3": ("sensor", "current_l3_socket_1"), "station": ("number", "max_station_current"), "station_active": ("sensor", "main_station_active_max_current_socket_1"), "phases_set": ("select", "installation_max_allowed_phases"), "phases_read": ("sensor", "connector_1_max_allowed_of_phases"), "error": ("sensor", "display_error_number_socket_1"), "login": ("binary_sensor", "https_api_login_status"), } #: a missing one of these refuses the charger (not the add-on). `power` is one #: of them: without it the car's power is unknown for good, House would show no #: reading for ever and the house profile would drop every sample. #: The power entity must also read in a Home Assistant power unit (`POWER_UNITS`). REQUIRED = ("current", "readback", "state", "power") _SETPOINT_RE = re.compile(r"^number\.(?P.+)_" + SETPOINT_SUFFIX + "$") _ROLE_ORDER = tuple(ROLES) POWER_UNITS = ("mW", "W", "kW", "MW") # every HA power unit, converted def census_key(entity) -> str: """The SAFETY-28 form: stripped, lowercase.""" return str(entity or "").strip().lower() def entities_for(setpoint) -> dict: """role -> entity id, derived from the setpoint entity by its suffix. Empty when the setpoint does not end the way the Alfen integration names it.""" m = _SETPOINT_RE.match(str(setpoint or "").strip()) if not m: return {} x = m.group("x") return {role: f"{dom}.{x}_{suffix}" for role, (dom, suffix) in ROLES.items()} # --------------------------------------------------------------------------- # # What a read gives # --------------------------------------------------------------------------- # @dataclass(frozen=True) class ChargerReading: """One read of the charger. None means "did not answer", never zero.""" available: bool = False # the integration answers state: str | None = None # mode3: "A", "B", "C", ... or None connected: bool | None = None charging: bool | None = None power_w: float | None = None energy_kwh: float | None = None # the meter, total increasing current_a: tuple = () # per phase, as many as read setpoint_a: float | None = None # the entity the installer named allowed_a: float | None = None # read-back of the limit the charger applies phases_allowed: int | None = None station_a: float | None = None # the charger's own station limit error: str | None = None # None: no error (or not read) display: str | None = None why: str = "" # for the log only, "" when available def _state_obj(obj): """(text, unit, attributes) of a state object, or (None, "", {}).""" if not isinstance(obj, dict): return None, "", {} raw = str(obj.get("state", "")).strip() attrs = obj.get("attributes") if isinstance(obj.get("attributes"), dict) else {} unit = str(attrs.get("unit_of_measurement") or "").strip() return (None if raw.lower() in BAD_STATES else raw), unit, attrs def _amps(obj): raw, unit, _ = _state_obj(obj) if raw is None: return None try: v = float(raw) except ValueError: return None if v != v: return None if unit == "A": return v if unit == "mA": return v / 1000.0 return None _W_PER = {"mW": 0.001, "W": 1.0, "kW": 1000.0, "MW": 1000000.0} def _watts(obj): """Power in W, believed only in a power unit (its own copy of the rule: the PV channel's reader stays out of the charger's, test_pv.py part 6).""" raw, unit, _ = _state_obj(obj) if raw is None or unit not in _W_PER: return None try: v = float(raw) * _W_PER[unit] except ValueError: return None return v if v == v else None def _kwh(obj): raw, unit, _ = _state_obj(obj) if raw is None or unit not in KWH_PER: return None try: v = float(raw) * KWH_PER[unit] except ValueError: return None return v if v == v and v >= 0 else None def _phases(obj): raw, _u, _ = _state_obj(obj) m = re.match(r"\s*([13])\s*phase", raw or "", re.I) return int(m.group(1)) if m else None _MODE3 = re.compile(r"^(?:STATE[_ ]?)?([A-F])$", re.I) def mode3_letter(text) -> str | None: m = _MODE3.match(str(text or "").strip()) return m.group(1).upper() if m else None def display_class(text) -> str | None: """The fallback when mode3 is missing: firmware wording, so only the words the owner's automation keys on. `connected`, `charging`, `none` or None.""" t = str(text or "").lower() if not t: return None if "wait vehicle" in t or "ev connected" in t or "cable connected" in t: return "connected" if "charging" in t: return "charging" if t in ("available", "ready", "idle"): return "none" return None def reading_from_states(states: dict) -> ChargerReading: """A `ChargerReading` from `{role: state object or None}`. Pure.""" def txt(role): return _state_obj(states.get(role))[0] login, state_o = txt("login"), states.get("state") # Reachable: the three entities the card cannot do without answer, and the # login sensor is not off. gone = [r for r in REQUIRED if txt(r) is None] if gone or (login or "").lower() == "off": why = ("login off" if not gone else "no answer from " + ", ".join(gone)) return ChargerReading(available=False, why=why) # A power entity that answers but cannot be believed (a unit the add-on # cannot convert, no unit, not a number) makes the reading UNAVAILABLE, so # it goes down the visible "Charger not reachable" path instead of leaving # the car's power unknown for good with nothing said. if _watts(states.get("power")) is None: return ChargerReading(available=False, why="power unit") letter = mode3_letter(txt("state")) disp = txt("display") cls = display_class(disp) power = _watts(states.get("power")) currents = tuple(a for a in (_amps(states.get(k)) for k in ("l1", "l2", "l3")) if a is not None) if letter is not None: connected, charging = letter in "BCD", letter in "CD" elif cls is not None: connected, charging = cls in ("connected", "charging"), cls == "charging" else: connected = charging = None err = txt("error") err_none = err is None or err.strip().startswith("0") return ChargerReading( available=True, state=letter, connected=connected, charging=charging, power_w=power, energy_kwh=_kwh(states.get("energy")), current_a=currents, setpoint_a=_amps(states.get("current")), allowed_a=_amps(states.get("readback")), phases_allowed=_phases(states.get("phases_read")), station_a=_first(_amps(states.get("station_active")), _amps(states.get("station"))), error=None if err_none else err, display=disp) def _first(*vals): return next((v for v in vals if v is not None), None) @dataclass(frozen=True) class ChargerProbe: """A read-only look: which derived entities exist.""" setpoint: str = "" found: tuple = () # ((role, entity), ...) missing: tuple = () station_a: float | None = None derived: bool = True # False: the setpoint's name does not fit power_unit: str | None = None # the power entity's unit, when it is # reading a number and that unit is not W or kW (an unavailable entity # has no unit to judge: that is the unreachable path, not a refusal) @property def required_missing(self) -> tuple: return tuple(r for r, _e in self.missing if r in REQUIRED) @property def ok(self) -> bool: return (self.derived and not self.required_missing and self.power_unit is None) def probe_from(setpoint, exists) -> ChargerProbe: """`exists(entity) -> state object or None`. Pure; the caller reads.""" ents = entities_for(setpoint) if not ents: return ChargerProbe(setpoint=str(setpoint or ""), derived=False) found, missing = [], [] for role in _ROLE_ORDER: (found if exists(ents[role]) is not None else missing).append( (role, ents[role])) st = {r: exists(e) for r, e in ents.items()} raw, unit, _ = _state_obj(st.get("power")) bad_unit = None if raw is not None and unit not in POWER_UNITS: try: float(raw) bad_unit = unit or "none" except ValueError: pass return ChargerProbe(str(setpoint), tuple(found), tuple(missing), station_a=_first(_amps(st.get("station_active")), _amps(st.get("station"))), power_unit=bad_unit) # --------------------------------------------------------------------------- # # The seam # --------------------------------------------------------------------------- # class ChargerNotBound(RuntimeError): pass class ChargerDriver: """One charger's I/O. Constructed from the options with no Home Assistant; `bind()` gives it one. Everything that talks to the world is a coroutine.""" name = "" writer_key = "ev_current_entity" brand = "" words: dict = {} @classmethod def from_options(cls, opts: dict) -> "ChargerDriver": raise NotImplementedError def bind(self, hass) -> "ChargerDriver": return self def bind_getter(self, getter) -> "ChargerDriver": return self def bound(self) -> bool: return True def configured(self) -> bool: raise NotImplementedError def actuator_id(self) -> str: raise NotImplementedError def entities(self) -> dict: return {} async def limits(self) -> tuple: """`(min_a, max_a, phases)`; None where unread.""" raise NotImplementedError async def read(self) -> ChargerReading: raise NotImplementedError # --- the write side. DEFINED, UNUSED BY THE CONTROLLER IN THIS CARD. ---- async def write_current(self, a: float) -> bool: raise NotImplementedError async def write_phases(self, n: int) -> bool: raise NotImplementedError async def release(self, mode: str) -> bool: raise NotImplementedError async def probe(self) -> ChargerProbe: raise NotImplementedError class AlfenHaDriver(ChargerDriver): """The Alfen behind its Home Assistant integration (`alfen_wallbox`).""" name = ALFEN_HA brand = "Alfen" def __init__(self, current_entity="", limit_a=16.0): self.current_entity = str(current_entity or "").strip() self.max_a = float(limit_a) self._ents = entities_for(self.current_entity) self._hass = None self._getter = None @classmethod def from_options(cls, opts: dict) -> "AlfenHaDriver": amps = max_a(opts) return cls(opts.get("ev_current_entity", ""), EV_OPTION_DEFAULTS["ev_max_a"] if amps is None else amps) @classmethod def actuator_id_of(cls, opts: dict) -> str: return str(opts.get("ev_current_entity") or "").strip() def bind(self, hass): self._hass, self._getter = hass, None return self def bind_getter(self, getter): self._hass, self._getter = None, getter return self def bound(self) -> bool: return self._hass is not None or self._getter is not None def _h(self): hass = self._getter() if self._getter is not None else self._hass if hass is None: raise ChargerNotBound("the charger has no Home Assistant") return hass def configured(self) -> bool: return bool(self._ents) def actuator_id(self) -> str: return self.current_entity def entities(self) -> dict: return dict(self._ents) async def _states(self, roles=_ROLE_ORDER) -> dict: import asyncio hass = self._h() got = await asyncio.gather(*(hass.state(self._ents[r]) for r in roles)) return dict(zip(roles, got)) async def limits(self) -> tuple: st = await self._states(("station", "station_active", "phases_read")) return (MIN_A, _first(_amps(st["station_active"]), _amps(st["station"])), _phases(st["phases_read"])) async def read(self) -> ChargerReading: if not self.configured(): return ChargerReading(why="not set up") return reading_from_states(await self._states()) async def probe(self) -> ChargerProbe: st = await self._states() by_ent = {self._ents[r]: o for r, o in st.items()} return probe_from(self.current_entity, by_ent.get) # --- the write side, UNUSED in EV-03 -------------------------------------- async def write_current(self, a: float) -> bool: a = max(0.0, min(float(a), self.max_a, ENTITY_MAX_A)) return await self._h().set_number(self.current_entity, a) async def write_phases(self, n: int) -> bool: if n not in (1, 3): return False return await self._h().call("select", "select_option", { "entity_id": self._ents["phases_set"], "option": "1 Phase" if n == 1 else "3 Phases"}) async def release(self, mode: str) -> bool: return await self.write_current(0.0) if mode == "solar" else True class UnavailableCharger(ChargerDriver): """No charger: `ev_charger` is off, or the charger is refused. `why` says which, for the Car card; nothing is read and nothing is written.""" name = OFF def __init__(self, why="off", wanted=""): self.why = why self.wanted = wanted @classmethod def from_options(cls, opts: dict): return cls() def configured(self) -> bool: return False def actuator_id(self) -> str: return "" async def limits(self) -> tuple: return None, None, None async def read(self) -> ChargerReading: return ChargerReading(why=self.why) async def write_current(self, a): return False async def write_phases(self, n): return False async def release(self, mode): return False async def probe(self) -> ChargerProbe: return ChargerProbe() def mode_of(opts: dict) -> str: v = str((opts or {}).get("ev_charger") or OFF).strip() return v if v in SELECTABLE else OFF def build(opts: dict) -> ChargerDriver: """The driver the options name. Off, or a name this build lacks, is `UnavailableCharger`; nothing here touches Home Assistant.""" which = mode_of(opts) if which == ALFEN_HA: drv = AlfenHaDriver.from_options(opts) if drv.configured(): return drv return UnavailableCharger("not set up", which) return UnavailableCharger("off") def census_entity(opts: dict) -> str: """The charger setpoint the SAFETY-28 census counts: only while a charger is switched on (an off charger writes nothing).""" if mode_of(opts) == OFF: return "" return str(opts.get("ev_current_entity") or "").strip() # --------------------------------------------------------------------------- # # The car's state, kept over time # --------------------------------------------------------------------------- # CHARGING, WAITING, NONE_, FULL, UNREACH, SETUP, FAULT = ( "charging", "waiting", "none", "full", "unreach", "setup", "fault") @dataclass class CarTracker: """What the cycle learns about the car from the readings. Pure, clocked by the caller (monotonic seconds for timers, UTC datetimes for the words). FRESHNESS (the rule applied, and the one decision EV-03 makes about a stale car reading): the car's power counts only while the last GOOD reading is not older than `stale_s`, the same `stale_input_s` bound the meter reading has. Older than that, `fresh()` is False and the House tile and the house profile say they do not know, instead of keeping the last car figure.""" stale_s: float = 15.0 reading: ChargerReading | None = None last_ok: float | None = None bad_since: float | None = None bad_since_utc: object = None notified: bool = False state_since_utc: object = None last_status: str | None = None last_good: ChargerReading | None = None last_good_utc: object = None b_since: float | None = None c_low_since: float | None = None writer_at_utc: object = None _prev: tuple | None = None # today's energy day: str | None = None today_kwh: float | None = None last_kwh: float | None = None persist: bool = False # set when `today` changed, for the store def observe(self, r: ChargerReading, now: float, now_utc, day: str): self.reading = r usable = r.available and r.power_w is not None if r.available: self.bad_since = None self.bad_since_utc = None elif self.bad_since is None: self.bad_since, self.bad_since_utc = now, now_utc if usable: self.last_ok = now self.last_good, self.last_good_utc = r, now_utc if r.available: self._writer(r, now_utc) self._energy(r, day) self._timers(r, now) self._status_edge(now, now_utc) # -- reachability ---------------------------------------------------------- def unreachable(self, now: float) -> bool: return self.bad_since is not None and now - self.bad_since >= UNREACHABLE_S def notify_due(self, now: float) -> bool: return (self.bad_since is not None and not self.notified and now - self.bad_since >= NOTIFY_S) def fresh(self, now: float) -> bool: return self.last_ok is not None and now - self.last_ok <= self.stale_s def car_w(self, now: float): """The car's power now, or None (unknown) when the reading is not fresh OR the current reading carries no power. Never the last good figure: a read that says "no power" contradicts it, and absence is never zero. It never raises (telemetry has no foot in the control path).""" r = self.reading if not self.fresh(now) or r is None or not r.available \ or r.power_w is None: return None try: return max(0.0, float(r.power_w)) except (TypeError, ValueError): return None # -- the two-writer detector ---------------------------------------------- def _writer(self, r, now_utc): cur = (r.setpoint_a, r.allowed_a) prev = self._prev if prev is not None: for a, b in zip(prev, cur): if a is not None and b is not None and a != b: self.writer_at_utc = now_utc # keep the last known value where one read came back empty self._prev = tuple(b if b is not None else (prev[i] if prev else None) for i, b in enumerate(cur)) def other_writer(self, now_utc) -> bool: t = self.writer_at_utc return t is not None and (now_utc - t).total_seconds() <= WRITER_HOLD_S # -- today's kWh ----------------------------------------------------------- def load(self, saved): if isinstance(saved, dict): try: self.day = str(saved["day"]) self.today_kwh = float(saved["kwh"]) self.last_kwh = (None if saved.get("last") is None else float(saved["last"])) except (KeyError, TypeError, ValueError): self.day = self.today_kwh = self.last_kwh = None def dump(self) -> dict: return {"day": self.day, "kwh": round(self.today_kwh or 0.0, 3), "last": self.last_kwh} def _energy(self, r, day): e = r.energy_kwh if self.day != day: self.day, self.today_kwh = day, 0.0 self.last_kwh = e self.persist = True return if e is None: return if self.last_kwh is not None: # a meter that goes back has been reset: count from its new zero d = e - self.last_kwh if e >= self.last_kwh else e if d: self.today_kwh = (self.today_kwh or 0.0) + d self.persist = True self.last_kwh = e if self.today_kwh is None: self.today_kwh = 0.0 # -- the car's state ------------------------------------------------------- def _timers(self, r, now): allowed = r.allowed_a is not None and r.allowed_a >= MIN_A self.b_since = (self.b_since if self.b_since is not None else now) \ if (r.state == "B" and allowed) else None low = (r.state == "C" and allowed and r.power_w is not None and r.power_w < FULL_C_W) self.c_low_since = (self.c_low_since if self.c_low_since is not None else now) if low else None def status(self, now: float, configured: bool = True): """One of the state words, or None before the first reading.""" if not configured: return SETUP if self.unreachable(now): return UNREACH r = self.reading if r is None or not r.available: return None if self.last_good is None else self.last_status if r.state in ("E", "F"): # the charger's own error states return FAULT if r.state == "A" or (r.state is None and r.connected is False): return NONE_ if r.state in ("B", "C", "D") or r.connected: if self.b_since is not None and now - self.b_since >= FULL_B_S: return FULL if self.c_low_since is not None and \ now - self.c_low_since >= FULL_C_S: return FULL return CHARGING if r.charging else WAITING return None def _status_edge(self, now, now_utc): s = self.status(now) if s != self.last_status and s is not None: self.last_status, self.state_since_utc = s, now_utc elif s is None and self.last_status is None: pass def phases_in_use(self) -> int | None: r = self.reading if r is None or not r.current_a: return None n = sum(1 for a in r.current_a if a >= IDLE_A) return n or None