Files
goodwe-addon/goodwe_controller/app/carmode.py
T
Claude 009393a5ee EV-59: Manual gives one value at most MAX_TRIES tries per user change
A refused phase-change close ended its sequence with one `_failed`, so the
same value got 5 tries (3 closes, then 2 on the normal path). Manual now
counts the not-taken closes of the value owed since the last user change
(`_close_k`); at the capped close end `fails` = that count, so `gave_up` and
CHARGER_REFUSED come at the 3rd refused close, and a value changed during the
retries still gets 3 tries. SolarWriter overrides the end hook and is
unchanged (EV-60).

Tests: new test_ev59.py; test_ev56 T5, T5b and the T20 T5 [R] golden,
test_ev28 T15 and the test_ev13 T13 text per the brief rulings.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 02:40:49 +01:00

1645 lines
78 KiB
Python

"""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
STUCK_BACKOFF_FIRST_S = 900.0 # Solar under a stuck verdict, its starts used
STUCK_BACKOFF_S = 1800.0 # up: one more after 15 min, then every 30 min
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
# EV-52: what the one info line per taken write needs.
self.boot = True # no user change since the process started
self._seen = False # the charger was available once
self._returned = False # ... and came back after being gone
self._r = None # the latest reading, for the phase count
self._late = None # (a, was, why, n) of a write not taken
self._rec_a = None # EV-56: the raised value already logged
self._close_k = 0 # EV-59: not-taken closes of the value owed
# ------------------------------------------------------------------ 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.boot = False
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._close_k = 0 # EV-59
self.phase_fails, self.phases_gave_up = 0, False
self.attempted_a = self.prior_a = None
self._late = None # EV-52: that request is not current now
self._rec_a = None # EV-56 (G2): a raise is logged again
# ------------------------------------------------------------------ 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
self._r = r
# 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._returned = self._returned or self._seen
self._seen = True
self.was_available = True
self.reapply = True # on return: only if it differs
self._rec_a = None # EV-56 (G2): logged again
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:
self._late = None # EV-52: another mode: that try is history
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
self._close_k = 0
if cur is not None:
self.last_a = cur # adopt what is already set
# EV-52 (PM Q2): a write taken late is logged once, here.
late, self._late = self._late, None
if late is not None and abs(cur - float(late[0])) <= TOL_A:
self._log_set(*late)
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
self._close_k = 0
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 _close_end(self, now) -> None:
"""EV-59: the closing current was refused MAX_TRIES times in this
sequence. The value owed has had `_close_k` not-taken closes since the
last user change: `fails` is that count, so the give-up comes only
when the value has used all its tries; else the normal path gives the
rest."""
self.fails = max(min(self._close_k, MAX_TRIES) - 1, 0)
self._failed(now)
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])
# ----------------------------------------------------- EV-52: the info line
def _why_default(self) -> str:
"""The reason of a write nobody named: Manual's own, or `start-up`
while nothing was changed since the process started."""
return "start-up" if self.boot and not self._returned else "Manual"
def _close_why(self, q):
return None
def _phases_of(self, n=None):
"""The phase count a current is written for: the one the caller
names, else what the charger reports. None when unknown."""
if n in (1, 3):
return n
if getattr(self, "single", False):
return 1
p = getattr(self._r, "phases_allowed", None)
return p if p in (1, 3) else None
def _log_set(self, a, was, why, n) -> None:
"""One plain INFO line for a current the charger took. Never raises:
a line is not worth a failed write."""
try:
new, old, ph = _num(a), _num(was), self._phases_of(n)
if new is None:
return
head = f"Car: set to {new:.0f} A"
if old is not None:
if abs(old - new) <= TOL_A:
return # it stood there: not a change
head = f"Car: set from {old:.0f} A to {new:.0f} A"
tail = "" if ph is None else (
" on 1 phase" if ph == 1 else " on 3 phases")
_LOG.info("%s%s (%s).", head, tail, why)
except Exception: # noqa: BLE001
pass
async def _write(self, drv, a, was, now, tracker, **kw) -> bool:
why = kw.pop("why", None) or self._why_default()
n = kw.pop("n", None)
# EV-56: a raise at shutdown is left to the caller (CHARGER_RESTORE).
strict = kw.pop("strict", False)
self._late = None
if self._rec_a is not None and abs(self._rec_a - float(a)) > TOL_A:
self._rec_a = None # EV-56 (G2): another value
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
err = None
try:
# EV-20: `kw` is only Solar's shorter read-back wait at shutdown.
ok = await drv.write_current(a, **kw)
except Exception as e: # noqa: BLE001
if strict:
raise
ok, err = False, e
finally:
self._stamp(now)
tracker.end_write(self.last_done)
if err is not None:
self._raised(err, a, was, now, why, n)
return False
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
self._rec_a = None # EV-56 (G2): a taken write
self._log_set(a, was, why, n)
else:
self.attempted_a, self.prior_a = a, was
self._late = (a, was, why, n) # logged if it is adopted later
return ok
def _raised(self, err, a, was, now, why, n) -> None:
"""EV-56: a write that raised (an HA call error, a setup error, a bug)
is a try the charger did not take, counted by the caller as a refusal
is. It is no charger answer, so the tracker is not told (Q2). Its
ERROR record, with the traceback, comes once per raised value (Q1)."""
self.log.append(("current", a, now, False))
self.attempted_a, self.prior_a = a, was
self._late = (a, was, why, n) # logged if it is adopted later
if self._rec_a is None:
self._rec_a = float(a)
_LOG.error("The car charger step failed", exc_info=err)
else:
_LOG.debug("The car charger write failed again: %s", err)
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, why="Manual")
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, why="shutdown",
strict=True)
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"])
q["sel_ok"] = bool(ok) # EV-52: the close's phase count
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,
why=self._close_why(q),
n=q["n"] if q.get("sel_ok") else None):
# 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
self._close_k = 0
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
self._close_k += 1 # EV-59: read by Manual's end only
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._close_end(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 cut_amps(car_w, excess_w, n, now_a=None):
"""EV-21: the current a peak cut leaves the car, or None when there is
nothing to cut (no excess). `floor((car_w - excess_w) / (230 x n))`,
0 when that is under 6 A, never above `now_a` (the setpoint now). An
unknown car figure cuts to 0 A (PM OQ2)."""
ex = _num(excess_w)
if ex is None or ex <= 0.0 or n not in (1, 3):
return None
w = _num(car_w)
a = 0.0 if w is None else float(max(
0, math.floor((w - ex) / (VOLTS * n) + 1e-9)))
if a < CH.MIN_A:
a = 0.0
top = _num(now_a)
if top is not None:
a = min(a, max(0.0, top))
return a
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, unknown_s=0.0, silent=False,
meter_back=False, age_s=None):
self.target_w, self.hold, self.auto = target_w, hold, auto
# EV-51: the meter's own age at the writer step (None: no reading), and
# `meter_back`: the cycle's snapshot said "meter too old" but the step's
# own age says a new reading came, so no unknown timer is carried over.
self.meter_back, self.age_s = meter_back, age_s
# EV-20 rig round 2: how long the sun has already been unknown when
# the cause is the meter's own age (`ha_signed`): the pause is timed
# from that age, not from the cycle that noticed it.
self.unknown_s = unknown_s
# EV-20 SPIKE-06 C17 (N8): the meter is known silent (its age past
# `meter_max_age_s`): no non-zero current goes out, only 0 A.
self.silent = silent
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 _cut(self, cap) -> None:
"""EV-21: the peak cut lowers the current to `cap` at once, past the
30 s gate and the 6 A hold; under 6 A it is the pause."""
if cap < CH.MIN_A:
self.pause("peak")
return
self.a, self.last_dir, self.low_since = float(cap), -1, None
def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s,
hold=False, gap_ok=True, unknown_s=0.0, meter_back=False,
cap=None):
"""`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. `meter_back` (EV-51): the
meter's own age is fresh again at this step: the unknown timer that
counted its silence starts over. `cap` (EV-21): a peak cut is due or
stands: the current goes no higher than `cap` (lowered at once), no
start and no phase change; the plan may still lower."""
if meter_back:
self.unknown_since = None
if cap is not None and self.a > cap + 1e-9:
self._cut(cap)
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
if unknown_s > 0.0:
# ha_signed: unknown since the meter's age passed its
# bound, so the pause comes at that age + `pause_s`.
self.unknown_since = min(self.unknown_since,
now - unknown_s)
# 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"
# EV-21: under a peak cut no start (the restart rule lifts
# the cap); the start count goes on.
if cap is None and 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 and cap is None: # 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 cap is not None:
want = min(want, self.a) # EV-21: no raise (C10)
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
self.stuck_wait = None # ... used up: the next start not before
self.stuck_warned = False # ... and its one CHARGER_REFUSED was given
self.nz_block = False # C17/C18: this step writes 0 A at most
self.held_step = False # C18: a held read: only a NEW 0 A goes out
self.cut_a = None # EV-21: the peak cut's cap, set per cycle
self.sent_at = None # EV-21: when `sent_a` went out
self.startup_zero = False # EV-52: the 0 A the start itself caused
self.sent_why = None # EV-52: the reason of `sent_a`'s write
# EV-54: the peak cut's refused tries, per quarter key, in memory only
# (DECISIONS/EV-54-refused-cut-retry.md).
self.cut_on = False # a cut stands (its cap), set per cycle
self.cut_blind = False # ... sized on a stale or blind meter now
self.cut_key = None # the quarter key the count is for
self.cut_fails = 0 # cut tries the charger did not take in it
self.cut_fail_at = None # ... the latest of them
self.cut_warned = False # ... and its one CHARGER_REFUSED was given
self.sent_cut = False # `sent_a` went out as a cut try
self.refused_cut = None # a cut value the charger did not take
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
self.startup_zero = True
def _stuck_end(self) -> None:
"""SPIKE-06: a stuck episode ends (the reading followed a start, a
press of Solar, Off, Manual or shadow): starts counted afresh, and
its CHARGER_REFUSED is cleared."""
if self.stuck_warned:
self.gave_up = False
self.stuck_starts, self.stuck_wait = 0, None
self.stuck_warned = False
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)
@property
def cut_refused(self) -> bool:
"""EV-54: the quarter's cut tries are used up and the charger still
shows more than the cut (the amber row and the card's Why)."""
return bool(self.cut_fails >= MAX_TRIES
and self.refused_cut is not None and not self.taken)
def cut_quarter(self, key) -> None:
"""EV-54 (Q1, Q8): a new quarter key gives the cut MAX_TRIES tries
again. Only a known key counts: a cycle without a projection keeps
the count."""
if key is not None and key != self.cut_key:
self.cut_key, self.cut_fails = key, 0
def _cut_try(self, a) -> bool:
"""EV-54 (Q6): a write while a cut is due or stands, at or under its
cap, is a cut try (the cut, a retry, a 0 A of a way out or of a phase
change)."""
return self.cut_a is not None and float(a) <= self.cut_a + TOL_A
def _forget_refused(self) -> None:
"""EV-54 (PM, review r2): a refused cut value is no longer owed and
is not dropped (the charger's return, another value written): its
refusals leave `fails` with it. `cut_fails`, the quarter's cap, stays."""
if self.refused_cut is not None:
self.refused_cut = None
self.fails = 0
def drop_ready(self, cur, stuck) -> bool:
"""EV-54 (drop rule): a cut value the charger did not take, no cut
stands any more (lifted, or a new quarter's cut waits), and a known
read-back that is not stuck and not another writer's: Solar takes
the charger as it is instead of sending that value again."""
return bool(self.refused_cut is not None and not self.taken
and not self.cut_on and not stuck and cur is not None
and not self.hold and self.mismatch_since is None
and not self.fresh_start)
def _drop(self, cur, now) -> None:
"""EV-54: `sent_a` = the read-back, taken (an adopt: `gave_up` and the
try count cleared), and the plan's current = the read-back, timed as
a new decision. Nothing is written. The retry clock stays: no
non-zero write reaches the charger within RETRY_S of its refusal."""
if self.sent_a is not None and self.sent_a <= TOL_A:
self._owed(False) # that 0 A is no longer owed
at = self.fail_at
self.sent_a, self.sent_cut = float(cur), False
self._adopt(cur)
self.fail_at = at
if float(cur) >= CH.MIN_A:
self.plan._set(float(cur), now)
else:
self.plan.pause()
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_end()
if held:
self.last_a = None
self.sent_a, self.taken = None, True
self.refused_cut = None
# ------------------------------------------------------------- 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`)."""
prev = self.sent_a
strict = kw.pop("strict", False) # EV-56: `release` (H1)
why = kw.get("why")
if why is None:
# EV-52: the 0 A the start caused is `start-up`, else Solar's own.
why = "start-up" if self.startup_zero and float(a) <= TOL_A \
and self.boot else "Solar"
kw["why"] = why
self.sent_why = why
cut_try = self.sent_cut = self._cut_try(a)
if self.refused_cut is not None \
and abs(self.refused_cut - float(a)) > TOL_A:
self._forget_refused() # EV-54: another value, not that one
self.sent_a, self.taken = float(a), False
if prev is None or abs(prev - float(a)) > TOL_A:
# EV-21 (PM Q1, formal C15): the 2 s grace of a lowering on its
# way is once per value; a re-send of the same value (a retry)
# gets none.
self.sent_at = now
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 self.stuck_wait is not None:
self.stuck_wait = now + STUCK_BACKOFF_S # a backoff try
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,
strict=True, **kw)
except Exception as e: # noqa: BLE001
if not cut_try:
if strict:
raise # EV-56 (H1): shutdown as before
# EV-56: a try the charger did not take, counted below as a
# refusal is; the tracker is not told (Q2).
self._raised(e, a, was, now, why, kw.get("n"))
else:
# EV-54 (T15): a cut write that raises is a refused cut try,
# so it is spaced and capped like one, not tried once per
# cycle.
_LOG.debug("The peak cut write failed: %s", e)
self.log.append(("current", a, now, False))
self.attempted_a, self.prior_a = a, was
ok = False
finally:
if zero:
self.zero_sent_at = None
if ok:
self.taken = True
self.startup_zero = False
self.fails, self.fail_at, self.gave_up = 0, None, False
self.refused_cut = None
if cut_try:
self.cut_warned = False # EV-54: a taken cut re-arms it
if zero:
self._owed(False)
else:
self._failed(now)
return ok
def _close_why(self, q):
"""EV-52: a phase change's closing current: capped by the peak cut,
or Solar's."""
return "peak cut" if q.get("cut") else "Solar"
def _close_end(self, now) -> None:
self._failed(now) # EV-59: Solar stays as it was (EV-60)
def _failed(self, now) -> None:
if self.sent_cut:
# EV-54 (Q1, F7): a refused cut try counts against the quarter's
# MAX_TRIES and never stops Solar; the next quarter tries again.
# `fails` counts it as before, so a way out of Off that follows
# is tried as often as before (N10).
self.fails += 1
self.fail_at = self.cut_fail_at = now
self.cut_fails += 1
self.refused_cut = self.sent_a
if self.cut_fails >= MAX_TRIES:
if not self.cut_warned:
self.cut_warned = True
_LOG.warning("The charger did not take the peak cut, so "
"the add-on tries again next quarter: "
"CHARGER_REFUSED.")
else:
_LOG.debug("The charger did not take the peak cut, %d "
"tries this quarter.", self.cut_fails)
return
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.startup_zero = False
self.last_a = cur
self.attempted_a = self.prior_a = None
self.fails, self.fail_at, self.gave_up = 0, None, False
self.refused_cut = None
if self.sent_cut:
self.cut_warned = False # EV-54: a cut taken late re-arms it
# EV-52 (PM Q2): a write the charger took late is logged once, here.
late, self._late = self._late, None
if late is not None and cur is not None \
and abs(float(cur) - float(late[0])) <= TOL_A:
self._log_set(*late)
async def _put(self, drv, want, cur, now, tracker, stuck=False,
out=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). EV-54: a cut try
is capped per quarter, never stopped by `gave_up`; a refused cut
value no cut needs is dropped (`_drop`), never sent again, except as
a way out's 0 A (`out`)."""
if self.hold:
return
if want > TOL_A and self.nz_block:
return # C17/C18: 0 A only, no retry or raise
# EV-54: refused cut tries count in `fails` without `gave_up`; outside
# the cut they stop a write as `gave_up` did before, but only while
# that refused value is still owed. Once it is gone (the charger's
# return, another write) no stale count blocks Solar (review r1).
# The quarter's cut count (`cut_fails`) is not touched.
stopped = self.gave_up or (self.fails >= MAX_TRIES
and self.refused_cut is not None
and not self.taken)
cut_try = self._cut_try(want)
if cut_try and self.cut_fails >= MAX_TRIES:
return # EV-54 (Q1): this quarter's tries used
if cut_try and self.cut_blind and self.refused_cut is not None \
and abs(want - self.refused_cut) <= TOL_A:
return # EV-54 (N7): no retry on a stale meter
if not out and self.refused_cut is not None and not self.taken \
and not self.cut_on and (
want > TOL_A or abs(want - self.refused_cut) <= TOL_A):
return # EV-54: the drop waits for a reading
if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A:
if self.held_step:
return # C18: no retry to a charger not answering
if self.taken or (stopped and not cut_try) or (
self.fail_at is not None
and now - self.fail_at < RETRY_S):
return
# EV-52: a retry keeps the reason of the first try.
await self._write(drv, want, cur, now, tracker,
why=self.sent_why)
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
cut = (self.cut_a is not None and want <= self.cut_a + TOL_A
and self.sent_a is not None and want < self.sent_a - TOL_A)
if cut_try and self.refused_cut is None \
and self.cut_fail_at is not None \
and now - self.cut_fail_at < RETRY_S:
return # EV-54 (F6): a new episode's try
if want <= TOL_A or cut:
# A new 0 A, or EV-21's new lower cut value: its own tries, at once.
self.fails, self.fail_at, self.gave_up = 0, None, False
elif (stopped and not cut_try) or (
self.fail_at is not None and now - self.fail_at < RETRY_S):
return
# EV-54 (review r1): a new cut value under the read-back is a peak cut,
# also when it lies above the refused one (`cut` compares with
# `sent_a`, which is that refused value).
peak = cut or (cut_try and self.refused_cut is not None
and cur is not None and want < cur - TOL_A)
await self._write(drv, want, cur, now, tracker,
why="peak cut" if peak else None)
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, out=True)
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._late = None # EV-52: no late accept after leaving
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, unknown_s=getattr(sun, "unknown_s", 0.0),
meter_back=getattr(sun, "meter_back", False), cap=self.cut_a)
@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" not in q:
q["close_a"] = self._close_a(q, clamp, n_reported)
a = q["close_a"] # one value per sequence, its retries too
cap = self.cut_a # EV-21: never above a peak cut's cap
if cap is not None and cap >= CH.MIN_A and a > cap:
q["close_a"] = a = float(cap)
q["cut"] = True # EV-52: the close is a peak cut
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 held_pause(self, drv, r, *, sun, now, tracker) -> None:
"""EV-20 (C18, PM design r3): on a held charger read only the pause by
the meter's age may come (0 A): nothing else in the plan moves, no
phase change begins or goes on, no retry. Called instead of `step`."""
if not self.engaged or self.seq is not None or self.hold \
or self.fault is not None or self.restart \
or self.plan.a <= 0.0 or self.plan.switch:
return
if not getattr(sun, "silent", False) \
or getattr(sun, "unknown_s", 0.0) < sun.pause_s:
return
self.nz_block = self.held_step = True
try:
self.plan.pause("unknown")
cur = None if r is None else (
r.allowed_a if r.allowed_a is not None else r.setpoint_a)
await self._put(drv, 0.0, cur, now, tracker)
finally:
self.nz_block = self.held_step = False
async def step(self, drv, r, *, mode, sun, clamp, now, tracker, writing,
status, clock=None, held=False):
"""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. `held`: the charger missed this read and the last
reading stands in (EV-20 round 2): the step may pause, never raise.
`ctl_car.car_step` no longer passes it (review r3): on a held cycle
only `held_pause` runs."""
self._clock = clock or (lambda: now)
# SPIKE-06 C17/C18: while the meter is silent, or on a held read, no
# non-zero current goes out (no retry, no raise, no closing current
# of a phase change); 0 A always may.
self.nz_block = bool(held or (sun is not None
and getattr(sun, "silent", False)))
self.held_step = bool(held)
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
# EV-54: nothing refused is pending; a mode change re-arms the
# notice. The quarter's try count stays (Q5).
self.refused_cut, self.sent_cut, self.cut_warned = None, False, \
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
self._r = r
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._returned = self._returned or self._seen
self._seen = True
# EV-52: only the process's own start owes a `start-up` 0 A.
self.startup_zero = self.boot and not self._returned
self.fresh_start = self.restart = True
self.mismatch_since = None
self.last_a = self.attempted_a = self.prior_a = None
self._rec_a = None # EV-56 (G2): logged again
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._stuck_end()
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:
self._stuck_end()
# 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
if self.refused_cut is not None and not self.taken \
and not self.cut_on and self.sent_cut:
# EV-54 (QC): no cut stands, so a value still owed is Solar's own
# (a stuck reading's way out), not a peak cut: its reason is
# Solar's and it gets Solar's own tries.
self.sent_why, self.sent_cut, self.fails = "Solar", False, 0
fault = ("error" if (r.error or r.state in ("E", "F")) else
"stuck" if stuck else None)
if not stuck:
self._stuck_end() # the reading moved: start afresh
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 episode ends) or is not
# taken: then the 0 A again. After MAX_TRIES such starts, one
# CHARGER_REFUSED, then one more start after 15 min and one every
# 30 min (PM decision): a fault that clears is found again.
if self.stuck_starts < MAX_TRIES:
fault = None
else:
if self.stuck_wait is None:
self.stuck_wait = now + STUCK_BACKOFF_FIRST_S
if not self.stuck_warned:
self.stuck_warned = True
_LOG.warning("The charger did not take the current, so "
"the add-on tries again in 15 min, then "
"every 30 min: CHARGER_REFUSED.")
if now >= self.stuck_wait:
self.gave_up = False
fault = None
else:
self.gave_up = True
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)
self._forget_refused()
if self.drop_ready(cur, stuck):
# EV-54 (drop rule): the refused cut value is not sent again.
self._drop(cur, now)
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 and self.held_step:
# SPIKE-06 C19: a held read decides nothing for a phase change
# under way (no write, no pause); it goes on at the next real
# reading. A gap that reaches `stale_input_s` takes the safe path.
return
if self.seq is not None and self.nz_block:
# C17: a phase change under way ends at its 0 A; no select and no
# closing current while the meter is silent. The plan pauses and
# starts again by the start rule.
self.seq = None
self.plan.end_switch(False)
self.plan.pause("unknown")
await self._put(drv, 0.0, cur, now, tracker)
return
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 not self.nz_block \
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:
self._r = r
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, why="shutdown",
strict=True):
self.released = True
return True
self.released = False
return False