"""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. EV-04 IS THE FIRST CARD THAT WRITES TO THE CHARGER, in Manual and (EV-20) in Solar (`app/carmode.py` is the one caller). `write_current` is clamped to `min(ev_max_a, the station limit the charger reports, the entity's own range)` and a value above that is NEVER SENT: it is a software fault, logged in the OUTPUT_CLAMP shape. It says True only when the charger's read-back followed within `TOOK_S`. Off writes nothing (EV-03's no-write test still holds for it). 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 asyncio import logging import re import time from dataclasses import dataclass, field from .hass import BAD_STATES from .solarfc import KWH_PER _LOG = logging.getLogger("goodwe") 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", "ev_batt_cover": True, "ev_mode_start": "keep", # EV-20, Solar: the sun kept back and the two dwells "ev_margin_w": 100, "ev_pause_min": 5, "ev_start_min": 2} #: EV-20: the ranges config.yaml's schema and the validator both hold. SOLAR_RANGES = {"ev_margin_w": (0, 1000), "ev_pause_min": (1, 30), "ev_start_min": (1, 30)} 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 TOOK_S = 10.0 # a write is "taken" when the read-back follows by then TOOK_TOL_A = 0.5 # ... to within this STUCK_S = 60.0 # EV-04: power and read-back unchanged after a write STUCK_MIN_A = 1.0 # ... that moved the setpoint by at least this LIFE_KEEP_S = 40.0 # EV-13: samples kept to date a refused write's life OWN_WRITE_MUTE_S = 15.0 # the tracker's two-writer detector ignores our own # Volts used to bound a car figure by what the read-back allows (a physical # ceiling for the alarm path, never a setpoint). CEILING_V = 253.0 # EV-04 round 2: the car's power may be used by the peak guard's alarm path only # while the charger's energy meter CORROBORATES it. Looking back over readings # (all in mode3 C, no gap) to the shortest stretch that is at least CORR_WINDOW_S # long AND over which the reported power adds up to at least CORR_MIN_WH, the # meter must have advanced by at least CORR_RATIO of that, less CORR_SLACK_WH (the # meter shows 10 Wh steps, so at 40 Wh expected it must show one step). Readings # are kept for CORR_KEEP_S. Until such a stretch exists (a session just began, or # the add-on just started) the figure is believed, as it was before. A frozen # figure of P watts on a car that has really stopped is caught within # max(CORR_WINDOW_S, CORR_MIN_WH / P) seconds: 60 s at 2.4 kW and up, 104 s at # 1.38 kW (6 A, 1 phase). Below CORR_MIN_WH over CORR_KEEP_S (about 0.8 kW) the # figure is believed; it cannot hide an overload that matters. CORR_WINDOW_S = 60.0 CORR_RATIO = 0.5 CORR_SLACK_WH = 15.0 CORR_MIN_WH = 40.0 CORR_KEEP_S = 180.0 # 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) _LIFE_ROLES = ("power", "energy", "l1", "l2", "l3") # EV-13 #: power unit -> W. The probe and the reading both use this one table. _W_PER = {"mW": 0.001, "W": 1.0, "kW": 1000.0, "MW": 1000000.0} POWER_UNITS = tuple(_W_PER) 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 # EV-13: when the sample was TAKEN, on the tracker's clock. None: the # caller's `now` (in the cycle that is the read's start, `now_mono`). taken_at: float | None = None phase_a: tuple = () # EV-13: L1, L2, L3 each, None if not read 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 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")), phase_a=tuple(_amps(states.get(k)) for k in ("l1", "l2", "l3")), 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 (EV-04). `app/carmode.py` is the one caller. --------- async def clamp_a(self) -> float: """The most a write may ask for: `min(ev_max_a, the station limit read from the charger, the entity's own range max)`.""" raise NotImplementedError async def write_current(self, a: float, took_s: float = TOOK_S) -> 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 # Seams for the checks: how a write waits for the read-back, and the # clock it counts on. self._sleep = asyncio.sleep self._clock = time.monotonic self.clamp_faults = [] # (asked, clamp), newest last, for the log self.sent = [] # every number value actually sent # EV-13: what the latest write saw while it waited for the read-back, # [(time, ChargerReading)]: the cycle's reads do not run inside it. self.polls = [] @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: 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 ------------------------------------------------------- async def clamp_a(self) -> float: """`min(ev_max_a, station limit, entity range max)`. A limit the charger did not answer is not a limit (the other two still bound the write).""" st = await self._states(("current", "station", "station_active")) station = _first(_amps(st["station_active"]), _amps(st["station"])) rng = ENTITY_MAX_A attrs = (st["current"] or {}).get("attributes") \ if isinstance(st.get("current"), dict) else None if isinstance(attrs, dict): try: rng = min(rng, float(attrs["max"])) except (KeyError, TypeError, ValueError): pass return min(x for x in (self.max_a, station, rng) if x is not None) async def write_current(self, a: float, took_s: float = TOOK_S) -> bool: """Set the current, once. True only when the charger took it: the read-back followed within `took_s` (`TOOK_S`; EV-20's shutdown 0 A waits less, so three tries fit its 15 s). A value above `clamp_a()` is a SOFTWARE FAULT: nothing is sent, it is logged (the clamp watchdog's shape) and the answer is False.""" self.polls = [] try: a = float(a) except (TypeError, ValueError): a = float("nan") clamp = await self.clamp_a() if a != a or a < 0.0 or a > clamp + 1e-9: self.clamp_faults.append((a, clamp)) del self.clamp_faults[:-20] _LOG.error("Software fault: the add-on was about to ask the charger " "for more than its limit, so nothing was sent: " "CHARGER_CLAMP.") _LOG.debug("Asked for %.1f A against a limit of %.1f A.", a, clamp) return False hass = self._h() self.sent.append(a) del self.sent[:-50] if not await hass.set_number(self.current_entity, a): return False return await self._took(a, took_s) async def _took(self, a: float, took_s: float = TOOK_S) -> bool: """Did the read-back follow the write, within `took_s`?""" t0 = self._clock() while True: st = await self._states(("readback", "current") + _LIFE_ROLES) self._poll(st) seen = _first(_amps(st["readback"]), _amps(st["current"])) if seen is not None and abs(seen - a) <= TOOK_TOL_A: return True if self._clock() - t0 >= took_s: return False await self._sleep(1.0) def _poll(self, st: dict) -> None: """EV-13: keep what this wait saw of energy, power and phase currents (never raises: a write does not depend on it).""" try: self.polls.append((self._clock(), ChargerReading( available=True, power_w=_watts(st.get("power")), energy_kwh=_kwh(st.get("energy")), phase_a=tuple(_amps(st.get(k)) for k in ("l1", "l2", "l3"))))) except Exception: # noqa: BLE001 pass async def write_phases(self, n: int) -> bool: """Select 1 or 3 phases. ONLY THROUGH `carmode`'s safe sequence: the setting moves the contactors, so it is touched with the car paused.""" if n not in (1, 3): return False want = "1 Phase" if n == 1 else "3 Phases" if not await self._h().call("select", "select_option", { "entity_id": self._ents["phases_set"], "option": want}): return False t0 = self._clock() while True: st = await self._states(("phases_read", "phases_set")) seen = _phases(st["phases_read"]) if seen is None: seen = _phases(st["phases_set"]) if seen == n: return True if self._clock() - t0 >= TOOK_S: return False await self._sleep(1.0) async def release(self, mode: str) -> bool: """The mode's fail state. Manual and Off keep the current (the charger is a stand-alone device and the current is the user's setting). Solar's 0 A goes through `carmode.SolarWriter.release`, the one write site, so nothing is written here.""" return 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 clamp_a(self) -> float: return 0.0 async def read(self) -> ChargerReading: return ChargerReading(why=self.why) async def write_current(self, a, took_s=TOOK_S): 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") def _life_vals(r) -> tuple: """EV-13: what shows a charger is alive: energy, power, three phase currents. None is "not read".""" cur = tuple(r.phase_a or ()) if len(cur) != 3: # Only `current_a`, which leaves out a phase that is not read: which # phase is which is then known only when all three are there. cur = tuple(r.current_a or ()) cur = cur if len(cur) == 3 else (None,) * 3 return (r.energy_kwh, r.power_w) + cur def _alive(vals: tuple, pre: list) -> bool: """A value that is present now, was present before the write, and differs from every value before it. Present but unchanged, or not there before, is no life.""" for i, v in enumerate(vals): if v is None: continue old = [p[i] for p in pre if p[i] is not None] if old and all(v != o for o in old): return True return False @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 # EV-04: our own writes, and the stuck-reading rule (SAFETY-37's shape) mute_until: float = 0.0 # EV-20 rig round 1: the signature of the latest reading taken BEFORE our # write went out, kept at `begin_write` (the arming baseline). Empty: no # write begun, and `note_write` uses `sig`. pre_sig: tuple = () armed_at: float | None = None armed_sig: tuple | None = None sig: tuple | None = None stuck_now: bool = False obs_at: float | None = None # monotonic second of the latest reading # EV-13: a REFUSED write waits to see if the charger shows life (below) _pend: dict | None = None _ring: list = field(default_factory=list) # (taken-at, life values) _hist: list = field(default_factory=list) # (t, power W, energy Wh) # 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 self.obs_at = now self._corr_note(r, now) 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 not r.available: self._pend_lapse(now) if r.available: self._life(r, now) self._sig(r, now) self._writer(r, now_utc, now) 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 # -- EV-04: the stuck-reading rule ------------------------------------------- def begin_write(self) -> None: """EV-12: a write of ours is in flight. Its read-back can reach the tracker before `note_write` runs (the write waits for it), so the mute is open until `end_write`. EV-20 (rig round 1, EV-32; SPIKE-06 option 2): the stuck check's baseline is the signature kept HERE, before the send. The write waits for its read-back and the cycle reads the charger meanwhile, so `sig` can already be the car's answer by `note_write`; armed on that, an unchanged car was called stuck 60 s later.""" self.mute_until = float("inf") self.pre_sig = (self.sig,) def end_write(self, now: float) -> None: """EV-12: the write returned (or failed). The mute runs `OWN_WRITE_MUTE_S` from now, not from before the write.""" self.mute_until = now + OWN_WRITE_MUTE_S def note_write(self, now: float, was_a, to_a, ok: bool = True, polls=()) -> None: """The add-on wrote the current at `now`. Its own change is not "another writer" for `OWN_WRITE_MUTE_S`, and a write that moved the setpoint by `STUCK_MIN_A` or more arms the stuck check: power and read-back that have not changed `STUCK_S` later are a stuck reading, not a car. EV-13: a write the charger REFUSED (`ok` False) arms it only when the charger shows no life: the energy, a phase current or the power changed in a sample taken after `now` and within `TOOK_S` of it, against the last values before. A refused write on a charger that is plainly alive is not a stuck reading. `polls` are the samples the write itself saw while it waited, `[(time, ChargerReading)]`.""" self.mute_until = now + OWN_WRITE_MUTE_S # The baseline: the reading before the send (`begin_write`), never one # that arrived while the write waited (no `begin_write`: `sig`). base = self.pre_sig[0] if self.pre_sig else self.sig self.pre_sig = () try: moved = was_a is None or abs(float(to_a) - float(was_a)) \ >= STUCK_MIN_A except (TypeError, ValueError): moved = False if self._pend is not None and now > self._pend["t"] + TOOK_S: self._pend_arm() # the old window ran out if not moved or self.armed_at is not None: return if ok: self._pend = None self.armed_at, self.armed_sig = now, base return if self._pend is not None: return # an earlier refusal's window before = [x for x in self._ring if x[0] <= now] pre = [max(before, key=lambda x: x[0])[1]] if before else [] self._pend = {"t": now, "pre": pre, "sig": base, "first": None} later = [(t, _life_vals(r)) for t, r in polls] later += [(t, v) for t, v in self._ring if t > now] for t, v in sorted(later, key=lambda x: x[0]): self._pend_feed(t, v, t) def _life(self, r, now: float) -> None: """EV-13: file this sample (by when it was TAKEN) and let a refused write's open window look at it.""" t = now if r.taken_at is None else r.taken_at v = _life_vals(r) self._ring.append((t, v)) top = max(x[0] for x in self._ring) self._ring = [x for x in self._ring if top - x[0] <= LIFE_KEEP_S] self._pend_feed(t, v, now) def _pend_feed(self, t: float, vals: tuple, arrival: float) -> None: p = self._pend if p is None: return if t <= p["t"]: p["pre"] = (p["pre"] + [vals])[-8:] # taken before the send elif p.get("first") is None: # EV-36 (SPIKE-05 C4): the first sample after the send may carry a # value newer than the cycle's last read but frozen since; it is # not life by itself, and life must differ from it as well. p["first"] = vals elif t <= p["t"] + TOOK_S and _alive(vals, p["pre"]) \ and _alive(vals, [p["first"]]): self._pend = None # life: nothing to arm return if max(t, arrival) > p["t"] + TOOK_S: self._pend_arm() def _pend_lapse(self, now: float) -> None: """A reading that did not answer shows no life either: once the window has run out the refusal arms, dated the send, as it did before.""" p = self._pend if p is not None and now > p["t"] + TOOK_S: self._pend_arm() def _pend_arm(self) -> None: """No life in the window: arm as the write would have, dated its send.""" p, self._pend = self._pend, None if p is not None and self.armed_at is None: self.armed_at, self.armed_sig = p["t"], p["sig"] def _sig(self, r, now: float) -> None: sig = (r.power_w, r.allowed_a) if self.armed_at is not None and self.armed_sig is not None \ and sig != self.armed_sig: self.armed_at = self.armed_sig = None # it moved: alive self.stuck_now = False elif self.armed_at is not None and self.armed_sig is None: self.armed_sig = sig self.sig = sig if self.armed_at is not None and now - self.armed_at >= STUCK_S: self.stuck_now = True def _corr_note(self, r, now: float) -> None: """Keep the last `CORR_WINDOW_S` of (power, energy) while the charger is charging. Any gap, a car that is not in mode3 C, a reading without power or energy, or a meter that goes back starts the window again.""" h = self._hist ok = (r.available and r.charging is True and r.power_w is not None and r.energy_kwh is not None) if not ok or (h and r.energy_kwh * 1000.0 < h[-1][2] - 0.5): h.clear() if not ok: return h.append((now, float(r.power_w), r.energy_kwh * 1000.0)) while len(h) > 2 and now - h[1][0] >= CORR_KEEP_S: h.pop(0) def corroborated(self, now: float) -> bool: """Does the charger's energy meter agree with the power it reports? No energy entity, or not charging: no. Less than a window of readings: yes (the first minute of a session is believed). Otherwise the energy the meter gained over the window must be at least `CORR_RATIO` of what the power adds up to, less `CORR_SLACK_WH`. A frozen power figure on a car that has stopped fails this within a window, and so does everything frozen together.""" r = self.reading h = self._hist if r is None or not r.available or r.charging is not True \ or r.energy_kwh is None or not h: return False exp_wh = 0.0 for k in range(len(h) - 1, 0, -1): (t0, p0, e0), (t1, _p1, _e1) = h[k - 1], h[k] exp_wh += p0 * (t1 - t0) / 3600.0 if h[-1][0] - t0 >= CORR_WINDOW_S - 5.0 and exp_wh >= CORR_MIN_WH: got_wh = h[-1][2] - e0 return got_wh >= CORR_RATIO * exp_wh - CORR_SLACK_WH return True def contradicted(self, now: float) -> bool: """EV-18: did the energy meter answer over a whole window and fall short (`corroborated` compared and failed)? Not when the energy reading is unknown, the window is empty or still short, or the car is not charging: those are unknown, not contradicted.""" r = self.reading if r is None or not r.available or r.charging is not True \ or r.energy_kwh is None or not self._hist: return False return not self.corroborated(now) def stuck(self, now: float) -> bool: """Power and read-back unchanged `STUCK_S` after a write that moved the setpoint. Cleared the moment either moves.""" return self.stuck_now def car_w_trusted(self, now: float): """The car's power for the peak guard's ALARM PATH, or None. Fresh (the EV-03 rules), not stuck after a write, corroborated by the energy meter (`corroborated`), and never above what the read-back allows the car to draw: an old or frozen figure must not hide a house overload.""" return self._capped_w(now, True) def car_w_paused(self, now: float): """EV-15: the same figure as `car_w_trusted` without the energy-meter corroboration, which a car held at 0 A by the add-on's own phase change cannot give (the meter's window restarts when it stops charging). Fresh, not stuck, and capped by the read-back. Only for grading the alarm during that sequence (`ctl_car._car_own_pause`).""" return self._capped_w(now, False) def _capped_w(self, now: float, corroborate: bool): w = self.car_w(now) if w is None or self.stuck(now) \ or (corroborate and not self.corroborated(now)): return None r = self.reading a = r.allowed_a if r.allowed_a is not None else r.setpoint_a if a is not None: n = r.phases_allowed if r.phases_allowed in (1, 3) else 3 w = min(w, max(0.0, float(a)) * CEILING_V * n) return w # -- the two-writer detector ---------------------------------------------- def _writer(self, r, now_utc, now=None): cur = (r.setpoint_a, r.allowed_a) prev = self._prev muted = now is not None and now < self.mute_until if prev is not None and not muted: 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