"""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` (mode3 leaving C only without a power reading; at most `ZERO_WAIT_S`, then the current comes back and it counts as a failed try), 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. EV-20 adds Solar (`SolarPlan`, `SolarWriter`, below): spare sun to the car, charging only. DECISIONS/EV-20-solar-mode.md. """ from __future__ import annotations import asyncio import logging import math from . import chargers as CH _LOG = logging.getLogger("goodwe") OFF, MANUAL, SOLAR = "off", "manual", "solar" #: the modes offered. Night is a later card (EV-02). MODES = (OFF, MANUAL, SOLAR) #: Home Assistant's select labels, English and pinned. MODE_LABELS = {OFF: "Off", MANUAL: "Manual", SOLAR: "Solar"} START_KEEP, START_OFF = "keep", "off" #: EV-20: where Solar's spare sun goes first, runtime state in the store. FIRST_BATT, FIRST_CAR = "batteries", "car" FIRSTS = (FIRST_BATT, FIRST_CAR) FIRST_LABELS = {FIRST_BATT: "Batteries", FIRST_CAR: "Car"} DEFAULT_FIRST = FIRST_BATT KEY_FIRST = "car_sun_first" 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 self.nonzero_at = None # EV-20 C6: the latest non-zero write sent # ------------------------------------------------------------------ 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, **kw) -> bool: tracker.begin_write() # EV-12: the read-back is ours if float(a) > TOL_A: # EV-20 C6, THE ONE WRITE CLOCK: every non-zero current either # writer sends, whatever path it comes from, is stamped here (the # one write_current call). Solar's 30 s gate reads this stamp. self.nonzero_at = now try: # EV-20: `kw` is only Solar's shorter read-back wait at shutdown. ok = await drv.write_current(a, **kw) finally: self._stamp(now) tracker.end_write(self.last_done) tracker.note_write(now, was, a, ok, getattr(drv, "polls", ())) 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": # A power reading decides; only without one does mode3 (not C, # not D) say the car is quiet. Still drawing at the timeout: no # select, the current comes back (EV-28). if r.power_w is not None: quiet = r.power_w < QUIET_W else: quiet = r.state is not None and r.state not in ("C", "D") if not quiet: if now - q["t0"] < ZERO_WAIT_S: return self.last_switch = now self.phase_fails += 1 q["failed"] = True # EV-15: no grace for the alarm q["stage"], q["t1"] = "settle", now - SETTLE_S # restore now _LOG.warning("The car kept drawing, so the phases were not " "changed.") 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.") else: 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) # EV-20: Solar hands a function of the sequence (its current depends # on whether the phases changed); Manual a number, as before. want = want_a(q) if callable(want_a) else want_a a = min(max(float(want), 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 # =========================================================================== # # EV-20: Solar. `SolarPlan` decides what the car should get from the spare sun; # `SolarWriter` makes the charger match it through ManualWriter's write, phase # sequence and other-writer watch. DECISIONS/EV-20-solar-mode.md. # =========================================================================== # VOLTS = 230.0 # per phase: what an amp is worth in watts SOLAR_WRITE_S = 30.0 # at most one current change per this ... SOLAR_STEP_A = 1.0 # ... and only on a change of this or more UP_W, UP_S = 4500.0, 180.0 # auto phases: to 3 at this for this long DOWN_W, DOWN_S = 4000.0, 300.0 # ... back to 1 under this for this long # Rig round 1: after a step down, a step back up needs this much more than the # amp boundary, so a spare that dithers on a boundary is one change, not 10 / # 9 / 10 every 30 s (N5's intent). UP_HYST_W = 100.0 ONE_PHASE_S = 10.0 # one phase drawing while 3 are allowed this long ONE_PHASE_MIN_W = 500.0 # ... with the car drawing at least this # D3: at shutdown the 0 A is tried this many times, this far apart, each # waiting this long for its read-back: inside `ctl_car.RELEASE_WAIT_S`. RELEASE_TRIES = 3 RELEASE_GAP_S = 5.0 RELEASE_TOOK_S = 4.0 def _num(v): try: f = float(v) except (TypeError, ValueError): return None return f if math.isfinite(f) else None def spare_w(car_w, batt_w, grid_w): """The spare sun, SIGNED and not clipped: `car + battery charge - grid import`, which is the solar production less the house. `batt_w` is the add-on's site battery figure (discharge positive), so it is subtracted. A grid charge of the batteries, or batteries giving more than the house uses, is never spare sun. None when a figure is missing or not a number.""" c, b, g = _num(car_w), _num(batt_w), _num(grid_w) if c is None or b is None or g is None: return None return c - b - g def car_target_w(spare, room_w, margin_w, first): """What the car may take: Batteries first `spare - room - margin`, Car first `spare - margin`. None while the spare is unknown.""" s = _num(spare) if s is None: return None room = float(_num(room_w) or 0.0) if first == FIRST_BATT else 0.0 return s - room - float(_num(margin_w) or 0.0) def amps_for(car_w, n, clamp=None): """Whole amps for `car_w` on `n` phases, ROUNDED DOWN, never above the clamp, never below 0. None for a figure that is not a number.""" w = _num(car_w) if w is None or n not in (1, 3): return None a = math.floor(w / (VOLTS * n) + 1e-9) hi = CH.ENTITY_MAX_A if _num(clamp) is None else float(clamp) return float(max(0, min(a, math.floor(hi)))) def solar_option(opts: dict, key: str) -> float: """`ev_margin_w`, `ev_pause_min` or `ev_start_min` as a number; the shipped default when it is not one (the validator refuses it anyway).""" v = _num((opts or {}).get(key)) return float(CH.EV_OPTION_DEFAULTS[key]) if v is None else v class SunInputs: """One cycle's inputs for Solar, built by the Controller.""" def __init__(self, target_w=None, hold=False, auto=True, start_s=120.0, pause_s=300.0, spare_w=None, room_w=0.0, margin_w=100.0, first=DEFAULT_FIRST): self.target_w, self.hold, self.auto = target_w, hold, auto self.start_s, self.pause_s = start_s, pause_s self.spare_w, self.room_w, self.margin_w = spare_w, room_w, margin_w self.first = first class SolarPlan: """What Solar wants set, one `step()` per cycle. Pure: monotonic `now` from the caller and no driver, so shadow mode runs it the same and the card says what it would set. `a` is the current wanted (0: paused), `n` the phases it is meant for; `switch` is a phase change it decided that the writer has not finished.""" def __init__(self, n=1): self.reset(n) def reset(self, n=1, why="paused"): self.a = 0.0 self.n = n if n in (1, 3) else 1 self.switch = False self.set_at = None # the latest non-zero change (30 s rule) self.ok_since = None # enough sun to start, since self.low_since = None # under 6 A worth, holding 6 A, since self.unknown_since = None # the spare cannot be measured, since self.up_since = self.down_since = None self.why = why self.target_w = None self._before = None # the state before a phase change self.ext_at = None # C6: Manual's latest non-zero write self.last_dir = 0 # the latest change: +1 up, -1 down def pause(self, why="paused"): self.a = 0.0 self.switch, self._before = False, None self.ok_since = self.low_since = self.unknown_since = None self.up_since = self.down_since = None self.why = why def _gate(self, now) -> bool: """30 s since the latest non-zero write, Solar's or (C6) Manual's.""" return all(t is None or now - t >= SOLAR_WRITE_S for t in (self.set_at, self.ext_at)) def _set(self, a, now, n=None): if n is not None and n != self.n: self._before = (self.a, self.n, self.set_at, self.low_since, self.why) self.n, self.switch = n, True self.a, self.set_at, self.why = float(a), now, "running" self.last_dir = 0 self.ok_since = self.low_since = None self.up_since = self.down_since = None def end_switch(self, done: bool) -> None: """The writer finished (`done`) or gave up the phase change. Given up, the plan is back where it was before it: its current for the old phases, its hold count (N3), so nothing meant for the new phases is written on the old ones.""" if self.switch and not done and self._before is not None: self.a, self.n, self.set_at, self.low_since, self.why = \ self._before self.switch, self._before = False, None def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s, hold=False, gap_ok=True): """`n_now`: the phases the car draws on now (1 for a one-phase car); `auto`: Solar may choose the phases; `gap_ok`: a phase change is allowed now (EV-04's one per `PHASE_GAP_S`); `hold`: readings late under the stale bound, everything stands.""" if hold: # Readings late under the stale bound: nothing changes, but a # hold or an unknown spare that has run its time still pauses # (N3: never 6 A past `pause_s`, however often the verdict # comes back). if self.a > 0.0 and any( since is not None and now - since >= pause_s for since in (self.low_since, self.unknown_since)): self.pause("unknown") return self.target_w = target_w if not self.switch and n_now in (1, 3): self.n = n_now # the phases are what the charger has if target_w is None: # the sun cannot be measured: hold, then 0 self.ok_since = None if self.a > 0.0: if self.unknown_since is None: self.unknown_since = now # A hold that began on a known low spare still ends on time. if now - self.unknown_since >= pause_s or ( self.low_since is not None and now - self.low_since >= pause_s): self.pause("unknown") else: self.why = "unknown" return self.unknown_since = None if self.a <= 0.0: # paused: the start rule n0 = 1 if auto else self.n if target_w >= (CH.MIN_A + 1.0) * VOLTS * n0: if self.ok_since is None: self.ok_since = now self.why = "start" if now - self.ok_since >= start_s and self._gate(now) \ and (n0 == self.n or gap_ok): a = amps_for(target_w, n0, clamp) if a is not None and a >= CH.MIN_A: self._set(a, now, n0) else: self.ok_since = None self.why = "paused" return hi = None if _num(clamp) is None else math.floor(float(clamp)) if hi is not None and self.a > hi: # the clamp came down if hi < CH.MIN_A: self.pause() return self.a, self.set_at, self.last_dir = float(hi), now, -1 if auto and not self.switch: # auto phases, by dwells if self.n == 1: self.down_since = None if target_w >= UP_W: if self.up_since is None: self.up_since = now else: self.up_since = None if self.up_since is not None and now - self.up_since >= UP_S \ and gap_ok and self._gate(now): a = amps_for(target_w, 3, clamp) if a is not None and a >= CH.MIN_A: self._set(a, now, 3) return else: self.up_since = None if target_w < DOWN_W: if self.down_since is None: self.down_since = now else: self.down_since = None if self.down_since is not None \ and now - self.down_since >= DOWN_S \ and gap_ok and self._gate(now): a = amps_for(target_w, 1, clamp) if a is not None and a >= CH.MIN_A: self._set(a, now, 1) return want = amps_for(target_w, self.n, clamp) if want is not None and want >= CH.MIN_A: self.low_since = None self.why = "running" if want > self.a and self.last_dir < 0: # Up again after a step down: only past the boundary plus # `UP_HYST_W` (no ping-pong on an amp boundary). up = amps_for(target_w - UP_HYST_W, self.n, clamp) or 0.0 want = max(self.a, up) if abs(want - self.a) >= SOLAR_STEP_A and self._gate(now): self.last_dir = 1 if want > self.a else -1 self.a, self.set_at = want, now return if auto and self.n == 3 and target_w >= DOWN_W and not self.switch: # Inside the phase hysteresis (4.0 kW up to 6 A on 3 phases): 6 A # on 3 phases stands until the down dwell, with no pause count. self.low_since = None self.why = "running" if self.a != CH.MIN_A and self._gate(now): self.last_dir = 1 if CH.MIN_A > self.a else -1 self.a, self.set_at = CH.MIN_A, now return if self.low_since is None: self.low_since = now self.why = "hold" if now - self.low_since >= pause_s: self.pause() return if self.a != CH.MIN_A and self._gate(now): self.a, self.set_at, self.last_dir = CH.MIN_A, now, -1 class SolarWriter(ManualWriter): """What Solar does to the charger, one `step()` per cycle. It shares ManualWriter's write, phase sequence and other-writer watch. ONE RULE FOR EVERY WRITE (EV-05 review rounds 2-9): Solar writes a value when it DECIDES a new one (`sent_a` differs), and tries a value the charger did not take again after `RETRY_S`, `MAX_TRIES` times, then the gave-up row and warning. A read-back that shows the value Solar sent confirms it, however late (`_adopt`). A read-back that differs from what Solar sent is never written over: `_watch` judges it (EV-04's 30 s other-writer rule), and while its hold stands nothing at all is written. WAYS OUT (Off, Stop, shadow, a safety stop, a charger error or stuck reading, no car, shutdown) write 0 A only while Solar's own current may stand on the charger (`live`): a non-zero value it sent, or a 0 A not yet confirmed. Once that 0 A is confirmed nothing more is written, and a start in shadow or with control stopped writes nothing. THE START-UP and a charger (or Home Assistant) that comes back write 0 A first whatever the charger shows, then the start rule (D2). An interrupted phase change ends at the 0 A it began with; nothing is restored.""" def __init__(self): super().__init__() self.plan = SolarPlan() self.engaged = False # Solar ran since it was chosen self.sent_a = None # the current Solar last decided to write self.taken = True # ... and the charger confirmed it self.fresh_start = True # start-up or back: 0 A first (D2) self.restart = True # writing again: the plan starts paused self.out = False # not writing now (shadow, Stop, latch) self.fault = None # "error" | "stuck" while it stands self.single = False # a one-phase car on a 3-phase allowance self._one_since = None self.zero_at = None # EV-15: our own latest 0 A was sent then self.sun = None # the last `SunInputs`, for the card self._would_n = None # shadow: the phases the plan believes self._would_switch = None # ... and when it last changed them self.released = None # D3: True / False once shutdown tried self.mode_was = None # the mode of the previous step self.start_owed = False # C1: a start in Off with a 0 A pending self.other_at = None # C6: Manual's latest non-zero write self.on_owed = None # C1: told when an own 0 A is out / back self.stuck_starts = 0 # SPIKE-06 C12: starts under one stuck verdict def owe_start(self) -> None: """C1: the add-on starts in Off while an exit 0 A of its own was still pending at the stop: the current the charger shows is the add-on's, so the 0 A is owed (once it may write), retried by the exit rule.""" self.start_owed = self.engaged = True def _owed(self, pending: bool) -> None: if self.on_owed is not None: self.on_owed(pending) # ------------------------------------------------------------- state @property def live(self) -> bool: """May a current of Solar's own stand on the charger? A non-zero value it sent (taken or not), or a 0 A not yet confirmed. Only then does a way out write its 0 A.""" return self.sent_a is not None and (self.sent_a > TOL_A or not self.taken) @property def zero_owed(self) -> bool: """A way-out 0 A the charger has not confirmed yet (for the card).""" return bool(self.engaged and self.sent_a is not None and self.sent_a <= TOL_A and not self.taken and not self.hold) def amps_out(self, clamp) -> float: """The plan's current, never above the clamp; 0 when under 6 A.""" a = float(self.plan.a) if _num(clamp) is not None: a = min(a, float(math.floor(float(clamp)))) return a if a >= CH.MIN_A else 0.0 def user_changed(self) -> None: """The user PRESSED SOLAR: another writer's hold is lifted and Solar takes the charger as it is (its value is no longer a difference); Solar's own value is decided and written afresh.""" held = self.hold or self.mismatch_since is not None super().user_changed() self.gave_up, self.fails, self.fail_at = False, 0, None self.stuck_starts = 0 if held: self.last_a = None self.sent_a, self.taken = None, True # ------------------------------------------------------------- writes async def _write(self, drv, a, was, now, tracker, **kw) -> bool: """ManualWriter's one write site. What Solar SENT is recorded before the write goes out, so a write cancelled while it waits for its read-back is never trusted (`live`).""" self.sent_a, self.taken = float(a), False zero = float(a) <= TOL_A if not zero and tracker is not None and tracker.stuck(now): self.stuck_starts += 1 # C12: a start under a stuck verdict if zero: self.zero_at = self.zero_sent_at = now self._owed(True) # C1: kept with the mode until back try: ok = await super()._write(drv, a, was, now, tracker, **kw) finally: if zero: self.zero_sent_at = None if ok: self.taken = True self.fails, self.fail_at, self.gave_up = 0, None, False if zero: self._owed(False) else: self._failed(now) return ok def _failed(self, now) -> None: self.fails += 1 self.fail_at = now if self.fails >= MAX_TRIES and not self.gave_up: self.gave_up = True _LOG.warning("The charger did not take the current, so the add-on " "stops asking until you press Solar: " "CHARGER_REFUSED.") def _adopt(self, cur) -> None: """The read-back shows what Solar sent: taken, however late.""" if self.sent_a is not None and self.sent_a <= TOL_A: self._owed(False) self.taken = True self.last_a = cur self.attempted_a = self.prior_a = None self.fails, self.fail_at, self.gave_up = 0, None, False async def _put(self, drv, want, cur, now, tracker, stuck=False) -> None: """Make the charger match `want`: write a new decision, try one the charger did not take again after `RETRY_S`. A new 0 A gets its own `MAX_TRIES` and never waits (0 A is the safe side).""" if self.hold: return if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A: if self.taken or self.gave_up or ( self.fail_at is not None and now - self.fail_at < RETRY_S): return await self._write(drv, want, cur, now, tracker) return if not stuck and cur is not None and abs(cur - want) <= TOL_A: self.sent_a = want # it already stands self._adopt(cur) return if want <= TOL_A: self.fails, self.fail_at, self.gave_up = 0, None, False elif self.gave_up or (self.fail_at is not None and now - self.fail_at < RETRY_S): return await self._write(drv, want, cur, now, tracker) def _own_readback(self, cur) -> bool: """C9: does the read-back show a current of Solar's own (sent, confirmed, tried, or shown when a try was refused)?""" if cur is None or cur <= TOL_A: return False return any(k is not None and k > TOL_A and abs(cur - k) <= TOL_A for k in (self.sent_a, self.last_a, self.attempted_a, self.prior_a)) async def _zero(self, drv, cur, now, tracker, stuck=False) -> None: """A way out: 0 A while Solar's own current may stand (its own bookkeeping, or C9 the read-back showing its value), never over another writer's hold.""" self.seq = None self.plan.end_switch(False) if not self.live and self._own_readback(cur) and not stuck: self.taken = False # C9: a 0 A is owed if self.live and not self.hold: await self._put(drv, 0.0, cur, now, tracker, stuck) def _watch(self, cur, now) -> None: was = self.hold super()._watch(cur, now) if self.hold and not was: _LOG.warning("Something else changes the charger, so the add-on " "stops writing to it until you press Solar: " "CHARGER_OTHER.") def _mark(self, r, now) -> None: """A car that draws one phase while 3 are allowed is a one-phase car for the session: the sun arithmetic then uses 1 phase.""" if r.state == "A": if self.single: _LOG.info("The car was unplugged, so the add-on counts the " "phases the charger allows again.") self.single, self._one_since = False, None return amps = [x for x in (r.current_a or ()) if x is not None] drawing = [x for x in amps if x >= CH.IDLE_A] one = (r.phases_allowed == 3 and r.charging is True and r.power_w is not None and r.power_w >= ONE_PHASE_MIN_W and len(amps) >= 3 and len(drawing) == 1) if not one: self._one_since = None return if self._one_since is None: self._one_since = now if now - self._one_since >= ONE_PHASE_S and not self.single: self.single = True _LOG.info("The car draws one phase while three are allowed, so " "the add-on counts one phase for this charge.") def _leave(self) -> None: """Solar is no longer the mode and owes nothing.""" self.engaged, self.seq, self.would = False, None, None self.start_owed = False self.out, self.fault = False, None self.restart = True self.mismatch_since = None self.plan.reset(self.plan.n) def _gap_ok(self, now) -> bool: return self.last_switch is None or now - self.last_switch \ >= PHASE_GAP_S def _plan_step(self, sun, now, clamp, n_now, gap_ok) -> None: # C6: the write clock, Solar's own latest non-zero write and Manual's. self.plan.ext_at = max((t for t in (self.nonzero_at, self.other_at) if t is not None), default=None) self.plan.step( now, target_w=sun.target_w, hold=sun.hold, n_now=n_now, auto=sun.auto and not self.single and not self.phases_gave_up, clamp=clamp, start_s=sun.start_s, pause_s=sun.pause_s, gap_ok=gap_ok) @staticmethod def _drawing(r) -> bool: """EV-04's test of a car that has not stopped (`_advance`).""" if r.power_w is not None: return r.power_w >= QUIET_W return r.state in ("C", "D") def _hold_over(self, now, sun) -> bool: """Has the hold the plan was in before its phase change run out?""" before = self.plan._before return bool(before is not None and before[3] is not None and sun is not None and now - before[3] >= sun.pause_s) def _seq_want(self, clamp, n_reported): """The current that ends a phase change. No select went out (EV-28's cap): the old current, on the old phases. A select went out, taken or not (its read-back may be late): the lower of the current for the new phases and for the phases the charger reports, so nothing meant for 1 phase is ever written on 3 (review round 1, Major 1).""" def want(q): if "close_a" in q: return q["close_a"] # one value per sequence, its retries too q["close_a"] = a = self._close_a(q, clamp, n_reported) return a return want def _close_a(self, q, clamp, n_reported): """`_seq_want`'s value, worked out once per sequence.""" before = self.plan._before if q.get("failed") and not q.get("sel") and before is not None: return before[0] if before[0] >= CH.MIN_A else CH.MIN_A a = self.amps_out(clamp) or CH.MIN_A tgt = self.plan.target_w for n in (q.get("n"), n_reported): b = amps_for(tgt, n, clamp) if n in (1, 3) else None if b is not None: a = min(a, max(b, CH.MIN_A)) return a async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None: """Step 1 of the safe sequence: 0 A (kept when it already stands). A 0 A the charger does not take ends the change; tried again later by the plan's own dwell.""" self.phase_done_at = None if not (cur is not None and cur <= TOL_A and self.sent_a == 0.0 and self.taken): if not await self._write(drv, 0.0, cur, now, tracker): self.plan.end_switch(False) return self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, "prev": None, "from": r.phases_allowed} # ------------------------------------------------------------- step async def step(self, drv, r, *, mode, sun, clamp, now, tracker, writing, status, clock=None): """One cycle. `sun` is `SunInputs` (None outside Solar); `writing` is False in shadow mode, while control is stopped, under a safety stop and while stopping.""" self._clock = clock or (lambda: now) entering = mode == SOLAR and self.mode_was != SOLAR self.mode_was = mode if entering: # Chosen (or the start-up): the plan starts paused, 0 A first. self.engaged, self.restart = True, True self.sent_a, self.taken = None, True self.fails, self.fail_at, self.gave_up = 0, None, False if not self.engaged: return if sun is not None: self.sun = sun if r is None or not r.available: self.was_available = False # nothing is tried while it is down return 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: # A reading older than our latest write says nothing about it: # no write and no watch, but the plan's dwells go on counting. if mode == SOLAR and sun is not None and writing \ and self.seq is None and not self.plan.switch \ and not self.restart and self.fault is None \ and not self.hold and self.mismatch_since is None: self._plan_step(sun, now, clamp, self.plan.n, self._gap_ok(now)) return if not self.was_available: # Start-up, or back after the charger or Home Assistant was gone: # the charger's current is its own, not another writer's, and the # first write is 0 A whatever it shows (D2, round 9). self.was_available = True self.fresh_start = self.restart = True self.mismatch_since = None self.last_a = self.attempted_a = self.prior_a = None cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a stuck = bool(tracker is not None and tracker.stuck(now)) if not self.taken and self.sent_a is not None and not stuck \ and cur is not None and abs(cur - self.sent_a) <= TOL_A: self._adopt(cur) # round 9: a late read-back self._mark(r, now) if mode != SOLAR: self.would = None if mode == OFF and self.start_owed: if not writing: return # C1: waits; the start warning says so self.start_owed = False if cur is not None and cur > TOL_A and not self.hold: self.sent_a, self.taken = cur, True # ours, from before else: self._owed(False) if mode == OFF: # 0 A while owed, then nothing await self._zero(drv, cur, now, tracker, stuck) if self.live and not self.hold: return # tried again (or gave up) self._leave() # Manual writes its own current return n_real = r.phases_allowed if r.phases_allowed in (1, 3) \ else self.plan.n n_now = 1 if self.single else n_real if not writing: # Shadow, Stop, a safety stop, stopping: the way-out 0 A while # owed, then nothing. The watch goes on (another writer is held # for every reader) and so does the plan, for the card. self.out = True await self._zero(drv, cur, now, tracker, stuck) self._watch(cur, now) self._shadow_plan(sun, now, clamp, n_now) self.restart = True return self.out = False self._would_n = self._would_switch = None self.would = None fault = ("error" if (r.error or r.state in ("E", "F")) else "stuck" if stuck else None) if not stuck: if self.stuck_starts >= MAX_TRIES and self.gave_up: self.gave_up = False # the reading moved: start afresh self.stuck_starts = 0 if fault == "stuck" and not self.live: # SPIKE-06 C12/C14 (option 2): no current of Solar's own may stand # (its own 0 A stands, or Solar was just chosen), so a stuck # verdict no longer holds the car: Solar's normal step writes its # 0 A first over a current that is not its own, then the start # rule. A start moves the reading (the verdict clears) or is not # taken: then the 0 A again, and after MAX_TRIES such starts under # one verdict, CHARGER_REFUSED and the 0 A stands (EV-04's rule). if self.stuck_starts < MAX_TRIES: fault = None elif not self.gave_up: self.gave_up = True _LOG.warning("The charger did not take the current, so the " "add-on stops asking until you press Solar: " "CHARGER_REFUSED.") if fault is not None: # 0 A while owed, then no write until it clears; then the start # rule. A stuck reading cannot confirm the 0 A. if self.fault != fault: self.fault = fault if fault == "error": _LOG.warning("The charger reports an error, so the add-on " "sets the car to 0 A: CHARGER_ERROR.") await self._zero(drv, cur, now, tracker, stuck) self.plan.reset(n_now, why=fault) self.restart = True return if self.fault is not None: self.fault = None if r.state == "A" or status == CH.NONE_: # No car: 0 A while owed, then nothing until a car is plugged in # and the start rule passes. await self._zero(drv, cur, now, tracker) self.plan.reset(n_now, why="none") self.restart = True return if self.restart: self.restart = False self.seq = None self.plan.reset(n_now) if self.fresh_start: self.fresh_start = False self.sent_a, self.taken = None, True # 0 A first (D2) if self.seq is None: self._watch(cur, now) if self.hold or self.mismatch_since is not None: # Another writer's value, held or not yet: nothing is written # over it; the plan goes on for the card. self._plan_step(sun, now, clamp, n_now, False) return gap = self._gap_ok(now) if self.sent_a == 0.0 and not self.taken: self.plan.ok_since = None # 0 A first, then the start rule if self.seq is not None: self._plan_step(sun, now, clamp, self.plan.n, gap) if self.plan.a < CH.MIN_A: self.seq = None # paused: it stays at 0 A self.plan.end_switch(True) return q = self.seq if q["stage"] == "zero" and now - q["t0"] >= ZERO_WAIT_S \ and self._drawing(r) and self._hold_over(now, sun): # The car still draws at the cap and the hold the plan came # from has run its time: no select and no current back (N3); # the 0 A stands as the pause. EV-04 counts the try. self.seq = None self.last_switch = now self.phase_fails += 1 if self.phase_fails >= MAX_TRIES: self.phases_gave_up = True _LOG.warning("The car kept drawing, so the phases were not " "changed.") self.plan.end_switch(False) self.plan.pause() return n_log = len(self.log) await self._advance(drv, r, cur, now, tracker, self._seq_want(clamp, r.phases_allowed), clamp, None) if any(x[0] == "phases" for x in self.log[n_log:]): q["sel"] = True # a select went out, taken or not if self.seq is None: # Back on the old phases only when no select went out; after # one the plan keeps the current it wrote (the lower one) and # takes the phases the charger reports from the next cycle. done = not q.get("failed") or bool(q.get("sel")) self.plan.end_switch(done) close = q.get("close_a") if close is not None and close >= CH.MIN_A: # The sequence ended on this current: the plan's current # now (its 30 s count is the write clock's, `_write`). self.plan.a = float(close) return self._plan_step(sun, now, clamp, n_now, gap) want = self.amps_out(clamp) if want >= CH.MIN_A and self.plan.switch \ and self.plan.n != n_now and not self.single: if self.gave_up or (self.fail_at is not None and now - self.fail_at < RETRY_S): return await self._begin_solar(drv, r, cur, self.plan.n, now, tracker) return if self.plan.switch: self.plan.end_switch(self.plan.n == n_now) await self._put(drv, want, cur, now, tracker) def _shadow_plan(self, sun, now, clamp, n_now) -> None: """Not writing: the plan runs on the phases it believes, a phase change it decides counting as done, so the card says what Solar would set (`would`).""" n = self._would_n if self._would_n in (1, 3) else n_now gap = self._would_switch is None or now - self._would_switch \ >= PHASE_GAP_S if sun is not None: self._plan_step(sun, now, clamp, n, gap) if self.plan.switch: self.plan.end_switch(True) self._would_n, self._would_switch = self.plan.n, now elif self._would_n is None: self._would_n = self.plan.n self.would = (self.amps_out(clamp), self.plan.n) async def release(self, drv, r, now, tracker) -> bool | None: """The add-on stops in Solar (D3): 0 A while Solar's own current may stand (a write cancelled while it waited counts), never over another writer's hold. Up to `RELEASE_TRIES` tries `RELEASE_GAP_S` apart, each waiting `RELEASE_TOOK_S` for its read-back. True: taken; False: not taken (the caller warns); None: nothing was owed. Nothing is restored of an interrupted phase change.""" self.seq = None self.plan.end_switch(False) self._clock = self._clock or (lambda: now) if not self.engaged or not self.live or self.hold: return None if r is not None and r.available: cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a else: cur = None clock = getattr(drv, "_clock", None) or (lambda: now) sleep = getattr(drv, "_sleep", None) or asyncio.sleep t0 = clock() for k in range(RELEASE_TRIES): if k: wait = t0 + k * RELEASE_GAP_S - clock() if wait > 0: await sleep(wait) if await self._write(drv, 0.0, cur, clock(), tracker, took_s=RELEASE_TOOK_S): self.released = True return True self.released = False return False