"""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, and only in Manual (`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"} 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 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) #: 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 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")), 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) -> 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 @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) -> bool: """Set the current, once. True only when the charger took it: the read-back followed within `TOOK_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.""" 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) async def _took(self, a: float) -> bool: """Did the read-back follow the write, within `TOOK_S`?""" t0 = self._clock() while True: st = await self._states(("readback", "current")) 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) 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).""" 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): 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 # EV-04: our own writes, and the stuck-reading rule (SAFETY-37's shape) mute_until: float = 0.0 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 _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 r.available: 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`.""" self.mute_until = float("inf") 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) -> None: """The add-on wrote the current. 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.""" self.mute_until = now + OWN_WRITE_MUTE_S try: moved = was_a is None or abs(float(to_a) - float(was_a)) \ >= STUCK_MIN_A except (TypeError, ValueError): moved = False if moved and self.armed_at is None: self.armed_at, self.armed_sig = now, self.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 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.""" w = self.car_w(now) if w is None or self.stuck(now) or 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