EV-20: Car Solar mode, spare sun to the car (charging only)
checks / unit (pull_request) Successful in 57m6s
infra-pin / fresh (pull_request) Successful in 3s

Solar as a second writer next to Manual (carmode.SolarPlan, SolarWriter on
ManualWriter's one write site, safe phase sequence and other-writer watch):
signed spare, Batteries first on the batteries' ratings, the margin, whole
amps rounded down, the 30 s / 1 A rule, start and pause dwells, auto phases,
a one-phase car. Every way out ends at 0 A, retried by EV-04's rule; at
shutdown before the inverters, three tries inside 15 s (D3); start-up and a
returning charger or HA write 0 A first (D2); never over another writer's
hold. The peak guard treats a Solar car as a Manual car (D1 wording). Solar
kWh sensor and card line; select.goodwe_car_sun_first; ev_margin_w,
ev_start_min, ev_pause_min with config, validator, translations, DOCS,
DECISIONS and CHANGELOG.

Checks: test_ev20.py, test_ev20_exits.py, test_ev20_writers.py,
test_ev20_guard.py, test_ev20_long.py, test_ev20_long_car.py,
test_ev20_fuzz.py (harness tools/ev20_sun.py, ev20_kit.py, ev20_day.py);
test_ev03/test_ev04 no longer use Solar as the refused example.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
This commit is contained in:
Claude
2026-11-22 20:31:26 +01:00
parent 885528ab48
commit 226e5a1e8b
35 changed files with 4647 additions and 123 deletions
+692 -7
View File
@@ -25,22 +25,33 @@ THE RULES, each tested in test_ev04.py:
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 = "off", "manual"
#: the modes this card offers. Solar and Night are later cards (EV-05, EV-02).
MODES = (OFF, MANUAL)
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"}
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
@@ -250,10 +261,11 @@ class ManualWriter:
"the add-on set %.0f A), so the add-on stops writing "
"to it until you change it.", cur, known[0])
async def _write(self, drv, a, was, now, tracker) -> bool:
async def _write(self, drv, a, was, now, tracker, **kw) -> bool:
tracker.begin_write() # EV-12: the read-back is ours
try:
ok = await drv.write_current(a)
# 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)
@@ -379,7 +391,10 @@ class ManualWriter:
if now - q["t1"] < SETTLE_S:
return
hi = CH.ENTITY_MAX_A if clamp is None else float(clamp)
a = min(max(float(want_a), CH.MIN_A), hi)
# 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.
@@ -397,3 +412,673 @@ class ManualWriter:
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
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
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:
return self.set_at is None or now - self.set_at >= SOLAR_WRITE_S
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.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 (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 = float(hi), now
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 abs(want - self.a) >= SOLAR_STEP_A and self._gate(now):
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.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 = CH.MIN_A, now
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
# ------------------------------------------------------------- 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
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 zero:
self.zero_at = self.zero_sent_at = now
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
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."""
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)
async def _zero(self, drv, cur, now, tracker, stuck=False) -> None:
"""A way out: 0 A while Solar's own current may stand, never over
another writer's hold."""
self.seq = None
self.plan.end_switch(False)
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.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:
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):
"""The current that ends a phase change: for the new phases, or for
the old ones when the select did not happen."""
def want(q):
before = self.plan._before
if q.get("failed") and before is not None:
return before[0] if before[0] >= CH.MIN_A else CH.MIN_A
return self.amps_out(clamp) or CH.MIN_A
return want
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: # 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 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
await self._advance(drv, r, cur, now, tracker,
self._seq_want(clamp), clamp, None)
if self.seq is None:
# Done when the phases were selected and the current is back;
# otherwise the plan returns to its old phases.
self.plan.end_switch(not q.get("failed"))
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