"""EV-04: the car charger's Manual mode, the one place the add-on WRITES to it. Pure but for the driver it is handed: no clock of its own (`now` is monotonic seconds from the caller), no Home Assistant, no store. DECISIONS/EV-04-manual- mode.md has the record; the design is reports/EV-01-design-report.md sections 2, 3 and 4. THE RULES, each tested in test_ev04.py: * Off writes NOTHING. Manual writes the current (6 A to the clamp) and the phases (1 or 3), each ONCE PER USER CHANGE, and only with a car connected and not full: with no car, or a full one, the current stands and the write waits for the car. * Every current is clamped to `min(ev_max_a, the station limit the charger reports, the entity's own range)`. The driver refuses anything above it; this module never asks for more. * Phases change only through the SAFE SEQUENCE: 0 A, wait until the charger reports under `QUIET_W` or mode3 leaves C (at most `ZERO_WAIT_S`), select the phases, wait `SETTLE_S`, write the current again. At most one switch per `PHASE_GAP_S`. A sequence that has begun is always finished, because it leaves the car at 0 A otherwise. * A read-back that differs from the add-on's own last write for `WRITER_S` is ANOTHER WRITER: an info row, and no write over it until the user changes the mode or a value again. * A charger that comes back after being unavailable gets the setting again only if its read-back differs. """ from __future__ import annotations import logging from . import chargers as CH _LOG = logging.getLogger("goodwe") OFF, MANUAL = "off", "manual" #: the modes this card offers. Solar and Night are later cards (EV-05, EV-02). MODES = (OFF, MANUAL) #: Home Assistant's select labels, English and pinned. MODE_LABELS = {OFF: "Off", MANUAL: "Manual"} START_KEEP, START_OFF = "keep", "off" KEY_MODE, KEY_A, KEY_PHASES = "car_mode", "car_current", "car_phases" DEFAULT_A = 6.0 DEFAULT_PHASES = 1 QUIET_W = 100.0 # "paused": under this, or mode3 has left C ZERO_WAIT_S = 20.0 # at most this long for the car to stop drawing SETTLE_S = 10.0 # after the phases select, before the current PHASE_GAP_S = 600.0 # at most one phase switch per this WRITER_S = 30.0 # a differing read-back this long is another writer RETRY_S = 60.0 # a write the charger did not take, tried again after MAX_TRIES = 3 # ... this many times, then it waits for the user TOL_A = CH.TOOK_TOL_A def allowed_phases(opts: dict) -> tuple: """The phase counts the user may pick: the `ev_phases` setting says what the installation allows (`auto` is 1 and 3).""" v = str((opts or {}).get("ev_phases", CH.EV_OPTION_DEFAULTS["ev_phases"])) return (1,) if v == "1" else (3,) if v == "3" else (1, 3) def start_mode(opts: dict, stored) -> str: """The mode after a restart: the stored one (`keep`), or Off.""" if str((opts or {}).get("ev_mode_start") or CH.EV_OPTION_DEFAULTS["ev_mode_start"]) == START_OFF: return OFF return stored if stored in MODES else OFF def clamp_for(opts: dict, reading) -> float | None: """The most a write may ask for, from the options and the last reading: `min(ev_max_a, the station limit, 40 A)`. None when the limit setting is not a number. (The driver reads the entity's own range as well.)""" amps = CH.max_a(opts) if amps is None: return None lim = [amps, CH.ENTITY_MAX_A] st = getattr(reading, "station_a", None) if st is not None: lim.append(float(st)) return min(lim) def value_a(raw, clamp: float | None): """A current the user asked for, as a whole number of amps inside `[6, clamp]`, or None when it is not a number. Above the clamp is the clamp: the user's value never reaches the driver bigger than it.""" try: v = float(raw) except (TypeError, ValueError): return None if v != v: return None v = round(v) hi = CH.ENTITY_MAX_A if clamp is None else max(CH.MIN_A, float(clamp)) return float(min(max(v, CH.MIN_A), hi)) class ManualWriter: """What Manual does to the charger, one `step()` per cycle.""" def __init__(self): self.rev_applied = None # the user's last change we have acted on self.last_a = None # the last current the charger took from us self.attempted_a = None # a write it did not take ... self.prior_a = None # ... and what the charger showed before it self.mismatch_since = None self.hold = False # another writer: no write until the user self.other = False # ... and the info row says so self.reapply = True # first reading, or the charger came back self.was_available = False self.fails = 0 self.fail_at = None self.gave_up = False self.seq = None # a phase change under way self.last_switch = None self.blocked = False # a phase change waits for PHASE_GAP_S self.would = None # (amps, phases): what it would set self.log = [] # (kind, value, now, ok), for the checks self.last_done = None # when our latest write was confirmed self._clock = None self.phase_fails = 0 # phase selects the charger did not take self.phases_gave_up = False self.undone = 0 # sequences undone before the select self.phase_done_at = None # EV-15: our phase change ended well then self.zero_sent_at = None # EV-15: our 0 A write is out, not yet back # ------------------------------------------------------------------ user def user_changed(self) -> None: """The user changed the mode or a value: one more write is allowed, and another writer's hold is lifted.""" self.rev_applied = None self.hold = self.other = False self.mismatch_since = None self.fails, self.fail_at, self.gave_up = 0, None, False self.phase_fails, self.phases_gave_up = 0, False self.attempted_a = self.prior_a = None # ------------------------------------------------------------------ step async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp, now, tracker, writing, status, shadow=False, clock=None): """One cycle. `r` is the latest `ChargerReading`; `writing` is False in shadow mode and while control is stopped (the step then only works out what it WOULD set, in `self.would`).""" self._clock = clock or (lambda: now) if r is None or not r.available: self.was_available = False return # A reading taken before our latest write was confirmed says nothing # about it (the writer runs beside the cycle and can finish between a # read and the step that follows): wait for one taken after. if self.last_done is not None and tracker is not None \ and tracker.obs_at is not None \ and tracker.obs_at <= self.last_done: return if not self.was_available: self.was_available = True self.reapply = True # on return: only if it differs cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a if self.seq is not None: if self.seq["stage"] in ("zero", "select") \ and (mode != MANUAL or not writing): await self._undo(drv, now, tracker, clamp, shadow) return await self._advance(drv, r, cur, now, tracker, want_a, clamp, rev) return self.would = None if mode != MANUAL: return if clamp is None or clamp < CH.MIN_A: return n_eff = want_phases if want_phases in (1, 3) else DEFAULT_PHASES target = min(max(float(want_a), CH.MIN_A), float(clamp)) self.would = (target, n_eff) # No car, or a full one: the current stands, nothing is written. The # setting waits (rev stays unapplied) until a car is there. if r.state == "A" or status in (CH.NONE_, CH.FULL): self.mismatch_since = None return if not writing: return self._watch(cur, now) if self.hold: return phases_need = (r.phases_allowed is not None and r.phases_allowed != n_eff and not self.phases_gave_up) cur_need = cur is None or abs(cur - target) > TOL_A need_user = rev != self.rev_applied if not (phases_need or cur_need): self.rev_applied, self.reapply = rev, False self.fails, self.blocked = 0, False if cur is not None: self.last_a = cur # adopt what is already set return if not (need_user or self.reapply): return # a difference nobody asked for: `_watch()` judges if self.gave_up or (self.fail_at is not None and now - self.fail_at < RETRY_S): return if phases_need: if self.last_switch is not None \ and now - self.last_switch < PHASE_GAP_S: self.blocked = True else: self.blocked = False await self._begin(drv, r, cur, n_eff, now, tracker) return if cur_need: ok = await self._write(drv, target, cur, now, tracker) if not ok: self._failed(now) return self.fails, self.fail_at = 0, None if not phases_need: self.rev_applied, self.reapply = rev, False # ------------------------------------------------------------- internals def _failed(self, now) -> None: self.fails += 1 self.fail_at = now if self.fails >= MAX_TRIES: self.gave_up = True _LOG.warning("The charger did not take the current, so the add-on " "stops asking until you change it: CHARGER_REFUSED.") _LOG.debug("The charger refused the current %d times.", self.fails) def _watch(self, cur, now) -> None: """Is the read-back what we wrote? A difference that stands for `WRITER_S` is another writer.""" known = [x for x in (self.last_a, self.attempted_a, self.prior_a) if x is not None] if not known or cur is None: self.mismatch_since = None return if any(abs(cur - k) <= TOL_A for k in known): self.mismatch_since = None if self.hold: self.hold = self.other = False return if self.mismatch_since is None: self.mismatch_since = now elif now - self.mismatch_since >= WRITER_S and not self.hold: self.hold = self.other = True _LOG.info("Something else changes the charger (read-back %.0f A, " "the add-on set %.0f A), so the add-on stops writing " "to it until you change it.", cur, known[0]) async def _write(self, drv, a, was, now, tracker) -> bool: tracker.begin_write() # EV-12: the read-back is ours try: ok = await drv.write_current(a) finally: self._stamp(now) tracker.end_write(self.last_done) tracker.note_write(now, was, a) tracker.end_write(self.last_done) self.log.append(("current", a, now, ok)) if ok: self.last_a = a self.attempted_a = self.prior_a = None else: self.attempted_a, self.prior_a = a, was return ok def _stamp(self, now) -> None: self.last_done = (self._clock or (lambda: now))() @staticmethod def _restore_a(prev, clamp): """The current to give back: what it was, never above the clamp.""" if prev is None: return None hi = CH.ENTITY_MAX_A if clamp is None else float(clamp) a = min(float(prev), hi) return a if a >= CH.MIN_A else None async def _undo(self, drv, now, tracker, clamp, shadow) -> None: """Off, shadow mode or a stopped control while the car is paused and the phases have NOT been selected: no switch. The old current comes back (clamped), in shadow mode too: it undoes the add-on's own half-done change (as the shutdown restore does) and is the one write shadow mode allows. Nothing else is written afterwards.""" q, self.seq = self.seq, None self.undone += 1 self.rev_applied, self.reapply = None, True a = self._restore_a(q.get("prev"), clamp) if a is not None: await self._write(drv, a, 0.0, now, tracker) async def _begin(self, drv, r, cur, n, now, tracker) -> None: """Step 1 of the safe sequence: 0 A. A charger that does not take it stops the sequence before the phases are touched.""" self.phase_done_at = None # EV-15: the car stops while the write waits for its read-back, and the # cycle runs beside it: the window opens when the write is SENT. self.zero_sent_at = now try: ok = await self._write(drv, 0.0, cur, now, tracker) finally: self.zero_sent_at = None if not ok: self._failed(now) return self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, "prev": cur} async def abandon(self, drv, now, tracker, clamp=None) -> None: """The add-on is stopping in the middle of a phase change: give the car its current back (a stopped add-on must not leave it at 0 A), clamped like every write. The phases stay as the select left them.""" q, self.seq = self.seq, None a = None if q is None else self._restore_a(q.get("prev"), clamp) if a is not None: self._clock = self._clock or (lambda: now) await self._write(drv, a, 0.0, now, tracker) async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev): q = self.seq if q["stage"] in ("zero", "select") and cur is not None \ and cur >= CH.MIN_A: # Something else raised the current while the car was being # paused. The phases are never selected under that: give up the # change, and leave the charger to whoever set it until the user # changes something. self.seq = None self.hold = self.other = True self.last_a = self.attempted_a = self.prior_a = None _LOG.info("Something else raised the charger's current during a " "phase change, so the phases were not touched.") return if q["stage"] == "zero": quiet = ((r.power_w is not None and r.power_w < QUIET_W) or (r.state is not None and r.state != "C")) if not quiet and now - q["t0"] < ZERO_WAIT_S: return q["stage"] = "select" if q["stage"] == "select": ok = await drv.write_phases(q["n"]) self._stamp(now) self.last_switch = now self.log.append(("phases", q["n"], now, ok)) q["stage"], q["t1"] = "settle", self.last_done # from its return if not ok: q["failed"] = True # EV-15: no grace for the alarm # The charger did not take it: the car gets its current back # on the old phases after the same SETTLE_S as a taken select # (HA may have taken it and only the read-back be late), and # the change is tried again after PHASE_GAP_S, MAX_TRIES times. self.phase_fails += 1 if self.phase_fails >= MAX_TRIES: self.phases_gave_up = True _LOG.warning("The charger did not take the phases, so the " "add-on stops trying until you change " "something: CHARGER_PHASES.") return if now - q["t1"] < SETTLE_S: return hi = CH.ENTITY_MAX_A if clamp is None else float(clamp) a = min(max(float(want_a), CH.MIN_A), hi) if await self._write(drv, a, 0.0, now, tracker): # Judged afresh next cycle: a value the user changed meanwhile is # still wanted, and one that is in place is adopted. self.seq, self.rev_applied, self.reapply = None, None, False self.fails, self.blocked = 0, False if not q.get("failed"): self.phase_done_at = self.last_done # EV-15 return q["failed"] = True # EV-15: a refused write ends it q["tries"] += 1 if q["tries"] >= MAX_TRIES: # Left at 0 A is the safe side; the next reading re-applies. self.seq, self.last_a, self.reapply = None, None, True self._failed(now) self.rev_applied = None return q["t1"] = now - SETTLE_S + 5.0 # again in 5 s