Files
goodwe-addon/goodwe_controller/app/carmode.py
T
ems-agentandClaude 29480fda47
checks / unit (pull_request) Failing after 24m58s
infra-pin / fresh (pull_request) Successful in 1s
EV-05: car Solar mode (spare sun to the car, Batteries or Car first, cut first for the peak)
Solar charges the car from the signed spare sun (car + battery charge - grid
import), less the batteries' room (Batteries first) and the sun kept back,
whole amps rounded down, at most one change per 30 s and only on 1 A. It
starts after ev_start_min of enough sun, holds 6 A for ev_pause_min, then 0 A.
Auto phases through EV-04's safe sequence (4.5 kW / 3 min up, 4.0 kW / 5 min
down, one switch per 10 min). What the peak guard would ask the batteries for
is taken off the car first, at once. Every way out of Solar ends at 0 A,
written once; at shutdown before the inverters go to 0 W.

- app/carmode.py: SolarPlan (pure) and SolarWriter (ManualWriter's one write
  site, its sequence and watch); spare_w, car_target_w, amps_for.
- app/ctl_car.py: Solar inputs, the cut, the solar kWh, EV-15's grace for
  Solar's own 0 A, no "set by the car" for Solar; main.py: shutdown order.
- Home card, HA select.goodwe_car_sun_first, sensor car_today_solar_kwh,
  three options with defaults, strings EN/NL, DOCS, DECISIONS, CHANGELOG.
- test_ev05.py, test_ev05_long.py, tools/ev05_sun.py; test_ev03/ev04 checks
  that pinned "Solar is refused" / "three entities" updated.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-17 23:54:06 +01:00

881 lines
38 KiB
Python

"""EV-04 and EV-05: the car charger's Manual and Solar modes, the one place the
add-on WRITES to it.
Pure but for the driver it is handed: no clock of its own (`now` is monotonic
seconds from the caller), no Home Assistant, no store. DECISIONS/EV-04-manual-
mode.md has the record; the design is reports/EV-01-design-report.md sections
2, 3 and 4.
THE RULES, each tested in test_ev04.py:
* Off writes NOTHING. Manual writes the current (6 A to the clamp) and the
phases (1 or 3), each ONCE PER USER CHANGE, and only with a car connected
and not full: with no car, or a full one, the current stands and the write
waits for the car.
* Every current is clamped to `min(ev_max_a, the station limit the charger
reports, the entity's own range)`. The driver refuses anything above it; this
module never asks for more.
* Phases change only through the SAFE SEQUENCE: 0 A, wait until the charger
reports under `QUIET_W` or mode3 leaves C (at most `ZERO_WAIT_S`), select the
phases, wait `SETTLE_S`, write the current again. At most one switch per
`PHASE_GAP_S`. A sequence that has begun is always finished, because it
leaves the car at 0 A otherwise.
* A read-back that differs from the add-on's own last write for `WRITER_S` is
ANOTHER WRITER: an info row, and no write over it until the user changes the
mode or a value again.
* A charger that comes back after being unavailable gets the setting again only
if its read-back differs.
EV-05, SOLAR (`SolarPlan` decides, `SolarWriter` writes; test_ev05.py,
DECISIONS/EV-05-solar-mode.md): the car gets the spare sun, `spare = car +
battery charge - grid import`, less the batteries' room (Batteries first) and
the margin. Whole amps rounded down, at most one write per 30 s and only on a
1 A change. Start after `ev_start_min` of enough sun, hold 6 A for
`ev_pause_min` below it, then 0 A. The peak guard's excess is taken off the
car first, at once. Every way out of Solar leaves the charger at 0 A, written
once. Both writers share `ManualWriter._write`, so there is still one
`write_current` and one `write_phases` call in the add-on.
"""
from __future__ import annotations
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"}
#: EV-05: where the spare sun goes first (`select.goodwe_car_sun_first`).
KEY_FIRST = "car_sun_first"
FIRST_BATT, FIRST_CAR = "batteries", "car"
FIRSTS = (FIRST_BATT, FIRST_CAR)
FIRST_LABELS = {FIRST_BATT: "Batteries", FIRST_CAR: "Car"}
DEFAULT_FIRST = FIRST_BATT
START_KEEP, START_OFF = "keep", "off"
KEY_MODE, KEY_A, KEY_PHASES = "car_mode", "car_current", "car_phases"
DEFAULT_A = 6.0
DEFAULT_PHASES = 1
QUIET_W = 100.0 # "paused": under this, or mode3 has left C
ZERO_WAIT_S = 20.0 # at most this long for the car to stop drawing
SETTLE_S = 10.0 # after the phases select, before the current
PHASE_GAP_S = 600.0 # at most one phase switch per this
WRITER_S = 30.0 # a differing read-back this long is another writer
RETRY_S = 60.0 # a write the charger did not take, tried again after
MAX_TRIES = 3 # ... this many times, then it waits for the user
TOL_A = CH.TOOK_TOL_A
def allowed_phases(opts: dict) -> tuple:
"""The phase counts the user may pick: the `ev_phases` setting says what
the installation allows (`auto` is 1 and 3)."""
v = str((opts or {}).get("ev_phases", CH.EV_OPTION_DEFAULTS["ev_phases"]))
return (1,) if v == "1" else (3,) if v == "3" else (1, 3)
def start_mode(opts: dict, stored) -> str:
"""The mode after a restart: the stored one (`keep`), or Off."""
if str((opts or {}).get("ev_mode_start")
or CH.EV_OPTION_DEFAULTS["ev_mode_start"]) == START_OFF:
return OFF
return stored if stored in MODES else OFF
def clamp_for(opts: dict, reading) -> float | None:
"""The most a write may ask for, from the options and the last reading:
`min(ev_max_a, the station limit, 40 A)`. None when the limit setting is
not a number. (The driver reads the entity's own range as well.)"""
amps = CH.max_a(opts)
if amps is None:
return None
lim = [amps, CH.ENTITY_MAX_A]
st = getattr(reading, "station_a", None)
if st is not None:
lim.append(float(st))
return min(lim)
def value_a(raw, clamp: float | None):
"""A current the user asked for, as a whole number of amps inside
`[6, clamp]`, or None when it is not a number. Above the clamp is the
clamp: the user's value never reaches the driver bigger than it."""
try:
v = float(raw)
except (TypeError, ValueError):
return None
if v != v:
return None
v = round(v)
hi = CH.ENTITY_MAX_A if clamp is None else max(CH.MIN_A, float(clamp))
return float(min(max(v, CH.MIN_A), hi))
class ManualWriter:
"""What Manual does to the charger, one `step()` per cycle."""
def __init__(self):
self.rev_applied = None # the user's last change we have acted on
self.last_a = None # the last current the charger took from us
self.attempted_a = None # a write it did not take ...
self.prior_a = None # ... and what the charger showed before it
self.mismatch_since = None
self.hold = False # another writer: no write until the user
self.other = False # ... and the info row says so
self.reapply = True # first reading, or the charger came back
self.was_available = False
self.fails = 0
self.fail_at = None
self.gave_up = False
self.seq = None # a phase change under way
self.last_switch = None
self.blocked = False # a phase change waits for PHASE_GAP_S
self.would = None # (amps, phases): what it would set
self.log = [] # (kind, value, now, ok), for the checks
self.last_done = None # when our latest write was confirmed
self._clock = None
self.phase_fails = 0 # phase selects the charger did not take
self.phases_gave_up = False
self.undone = 0 # sequences undone before the select
self.phase_done_at = None # EV-15: our phase change ended well then
self.zero_sent_at = None # EV-15: our 0 A write is out, not yet back
# ------------------------------------------------------------------ user
def user_changed(self) -> None:
"""The user changed the mode or a value: one more write is allowed,
and another writer's hold is lifted."""
self.rev_applied = None
self.hold = self.other = False
self.mismatch_since = None
self.fails, self.fail_at, self.gave_up = 0, None, False
self.phase_fails, self.phases_gave_up = 0, False
self.attempted_a = self.prior_a = None
# ------------------------------------------------------------------ step
async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp,
now, tracker, writing, status, shadow=False, clock=None):
"""One cycle. `r` is the latest `ChargerReading`; `writing` is False in
shadow mode and while control is stopped (the step then only works out
what it WOULD set, in `self.would`)."""
self._clock = clock or (lambda: now)
if r is None or not r.available:
self.was_available = False
return
# A reading taken before our latest write was confirmed says nothing
# about it (the writer runs beside the cycle and can finish between a
# read and the step that follows): wait for one taken after.
if self.last_done is not None and tracker is not None \
and tracker.obs_at is not None \
and tracker.obs_at <= self.last_done:
return
if not self.was_available:
self.was_available = True
self.reapply = True # on return: only if it differs
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
if self.seq is not None:
if self.seq["stage"] in ("zero", "select") \
and (mode != MANUAL or not writing):
await self._undo(drv, now, tracker, clamp, shadow)
return
await self._advance(drv, r, cur, now, tracker, want_a, clamp, rev)
return
self.would = None
if mode != MANUAL:
return
if clamp is None or clamp < CH.MIN_A:
return
n_eff = want_phases if want_phases in (1, 3) else DEFAULT_PHASES
target = min(max(float(want_a), CH.MIN_A), float(clamp))
self.would = (target, n_eff)
# No car, or a full one: the current stands, nothing is written. The
# setting waits (rev stays unapplied) until a car is there.
if r.state == "A" or status in (CH.NONE_, CH.FULL):
self.mismatch_since = None
return
if not writing:
return
self._watch(cur, now)
if self.hold:
return
phases_need = (r.phases_allowed is not None
and r.phases_allowed != n_eff
and not self.phases_gave_up)
cur_need = cur is None or abs(cur - target) > TOL_A
need_user = rev != self.rev_applied
if not (phases_need or cur_need):
self.rev_applied, self.reapply = rev, False
self.fails, self.blocked = 0, False
if cur is not None:
self.last_a = cur # adopt what is already set
return
if not (need_user or self.reapply):
return # a difference nobody asked for: `_watch()` judges
if self.gave_up or (self.fail_at is not None
and now - self.fail_at < RETRY_S):
return
if phases_need:
if self.last_switch is not None \
and now - self.last_switch < PHASE_GAP_S:
self.blocked = True
else:
self.blocked = False
await self._begin(drv, r, cur, n_eff, now, tracker)
return
if cur_need:
ok = await self._write(drv, target, cur, now, tracker)
if not ok:
self._failed(now)
return
self.fails, self.fail_at = 0, None
if not phases_need:
self.rev_applied, self.reapply = rev, False
# ------------------------------------------------------------- internals
def _failed(self, now) -> None:
self.fails += 1
self.fail_at = now
if self.fails >= MAX_TRIES:
self.gave_up = True
_LOG.warning("The charger did not take the current, so the add-on "
"stops asking until you change it: CHARGER_REFUSED.")
_LOG.debug("The charger refused the current %d times.", self.fails)
def _watch(self, cur, now) -> None:
"""Is the read-back what we wrote? A difference that stands for
`WRITER_S` is another writer."""
known = [x for x in (self.last_a, self.attempted_a, self.prior_a)
if x is not None]
if not known or cur is None:
self.mismatch_since = None
return
if any(abs(cur - k) <= TOL_A for k in known):
self.mismatch_since = None
if self.hold:
self.hold = self.other = False
return
if self.mismatch_since is None:
self.mismatch_since = now
elif now - self.mismatch_since >= WRITER_S and not self.hold:
self.hold = self.other = True
_LOG.info("Something else changes the charger (read-back %.0f A, "
"the add-on set %.0f A), so the add-on stops writing "
"to it until you change it.", cur, known[0])
async def _write(self, drv, a, was, now, tracker) -> bool:
tracker.begin_write() # EV-12: the read-back is ours
try:
ok = await drv.write_current(a)
finally:
self._stamp(now)
tracker.end_write(self.last_done)
tracker.note_write(now, was, a)
tracker.end_write(self.last_done)
self.log.append(("current", a, now, ok))
if ok:
self.last_a = a
self.attempted_a = self.prior_a = None
else:
self.attempted_a, self.prior_a = a, was
return ok
def _stamp(self, now) -> None:
self.last_done = (self._clock or (lambda: now))()
@staticmethod
def _restore_a(prev, clamp):
"""The current to give back: what it was, never above the clamp."""
if prev is None:
return None
hi = CH.ENTITY_MAX_A if clamp is None else float(clamp)
a = min(float(prev), hi)
return a if a >= CH.MIN_A else None
async def _undo(self, drv, now, tracker, clamp, shadow) -> None:
"""Off, shadow mode or a stopped control while the car is paused and the
phases have NOT been selected: no switch. The old current comes back
(clamped), in shadow mode too: it undoes the add-on's own half-done
change (as the shutdown restore does) and is the one write shadow mode
allows. Nothing else is written afterwards."""
q, self.seq = self.seq, None
self.undone += 1
self.rev_applied, self.reapply = None, True
a = self._restore_a(q.get("prev"), clamp)
if a is not None:
await self._write(drv, a, 0.0, now, tracker)
async def _begin(self, drv, r, cur, n, now, tracker) -> None:
"""Step 1 of the safe sequence: 0 A. A charger that does not take it
stops the sequence before the phases are touched."""
self.phase_done_at = None
# EV-15: the car stops while the write waits for its read-back, and the
# cycle runs beside it: the window opens when the write is SENT.
self.zero_sent_at = now
try:
ok = await self._write(drv, 0.0, cur, now, tracker)
finally:
self.zero_sent_at = None
if not ok:
self._failed(now)
return
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
"prev": cur}
async def abandon(self, drv, now, tracker, clamp=None) -> None:
"""The add-on is stopping in the middle of a phase change: give the car
its current back (a stopped add-on must not leave it at 0 A), clamped
like every write. The phases stay as the select left them."""
q, self.seq = self.seq, None
a = None if q is None else self._restore_a(q.get("prev"), clamp)
if a is not None:
self._clock = self._clock or (lambda: now)
await self._write(drv, a, 0.0, now, tracker)
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
q = self.seq
if q["stage"] in ("zero", "select") and cur is not None \
and cur >= CH.MIN_A:
# Something else raised the current while the car was being
# paused. The phases are never selected under that: give up the
# change, and leave the charger to whoever set it until the user
# changes something.
self.seq = None
self.hold = self.other = True
self.last_a = self.attempted_a = self.prior_a = None
_LOG.info("Something else raised the charger's current during a "
"phase change, so the phases were not touched.")
return
if q["stage"] == "zero":
quiet = ((r.power_w is not None and r.power_w < QUIET_W)
or (r.state is not None and r.state != "C"))
if not quiet and now - q["t0"] < ZERO_WAIT_S:
return
q["stage"] = "select"
if q["stage"] == "select":
ok = await drv.write_phases(q["n"])
self._stamp(now)
self.last_switch = now
self.log.append(("phases", q["n"], now, ok))
q["stage"], q["t1"] = "settle", self.last_done # from its return
if not ok:
q["failed"] = True # EV-15: no grace for the alarm
# The charger did not take it: the car gets its current back
# on the old phases after the same SETTLE_S as a taken select
# (HA may have taken it and only the read-back be late), and
# the change is tried again after PHASE_GAP_S, MAX_TRIES times.
self.phase_fails += 1
if self.phase_fails >= MAX_TRIES:
self.phases_gave_up = True
_LOG.warning("The charger did not take the phases, so the "
"add-on stops trying until you change "
"something: CHARGER_PHASES.")
return
if now - q["t1"] < SETTLE_S:
return
hi = CH.ENTITY_MAX_A if clamp is None else float(clamp)
a = min(max(float(want_a), CH.MIN_A), hi)
if await self._write(drv, a, 0.0, now, tracker):
# Judged afresh next cycle: a value the user changed meanwhile is
# still wanted, and one that is in place is adopted.
self.seq, self.rev_applied, self.reapply = None, None, False
self.fails, self.blocked = 0, False
if not q.get("failed"):
self.phase_done_at = self.last_done # EV-15
return
q["failed"] = True # EV-15: a refused write ends it
q["tries"] += 1
if q["tries"] >= MAX_TRIES:
# Left at 0 A is the safe side; the next reading re-applies.
self.seq, self.last_a, self.reapply = None, None, True
self._failed(now)
self.rev_applied = None
return
q["t1"] = now - SETTLE_S + 5.0 # again in 5 s
# =========================================================================== #
# EV-05: Solar. `SolarPlan` decides what the car should get, `SolarWriter`
# makes the charger match it through ManualWriter's one write site.
# =========================================================================== #
MIN_A = CH.MIN_A
VOLTS = 230.0 # per phase: the amps a figure in watts is worth
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
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: what the car takes, plus what the
batteries charge, less what the grid gives. `batt_w` is the add-on's own
battery figure (discharge positive) and `grid_w` the meter (import
positive), so this is `car - batt - grid` = solar production less the
house. 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(room_w or 0.0) if first == FIRST_BATT else 0.0
return s - room - float(margin_w)
def amps_for(car_w, n, clamp=None):
"""Whole amps for `car_w` on `n` phases, ROUNDED DOWN, never above the
clamp. 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, cut_w=0.0, car_w=None,
key=None, auto=True, fixed_n=1, 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.cut_w = target_w, hold, cut_w
self.car_w, self.key, self.auto, self.fixed_n = car_w, key, auto, \
fixed_n
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 in shadow mode it runs the same and the card
says what it would set. `a` is the current wanted (0: paused), `n` the
phases it is meant for."""
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.set_at = None # when `a` last changed (the 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.cap_a = self.cap_key = None # the peak cut, for this period
self.why = self.pause_why = why
self.target_w = None
def _pause(self, why):
self.a, self.set_at = 0.0, None
self.ok_since = self.low_since = self.unknown_since = None
self.up_since = self.down_since = None
self.why = self.pause_why = why
def _gate(self, now) -> bool:
return self.set_at is None or now - self.set_at >= SOLAR_WRITE_S
def _switch(self, n, target_w, now, clamp):
self.n = n
a = amps_for(target_w, n, clamp) or 0.0
if a >= MIN_A:
self.low_since = None
elif self.low_since is None:
self.low_since = now
a = max(a, MIN_A)
if self.cap_a is not None:
a = max(MIN_A, min(a, self.cap_a))
self.a, self.set_at = a, now
self.up_since = self.down_since = None
self.why = "running"
def step(self, now, *, target_w, n_calc, auto, fixed_n, clamp,
start_s, pause_s, hold=False, cut_w=0.0, car_w=None, key=None,
gap_ok=True):
if key != self.cap_key:
self.cap_a = self.cap_key = None
if hold: # readings late, under the stale bound
return
self.target_w = target_w
# The peak guard's excess comes off the car first, at once (no 30 s
# rule, no hold). Nothing starts while the period heads over the aim.
if cut_w and cut_w > 0.0:
self.ok_since = None
if self.a > 0.0:
base = self.a * VOLTS * n_calc
cw = _num(car_w)
if cw is not None:
base = min(base, cw)
new = amps_for(base - float(cut_w), n_calc, clamp)
if new is None or new < MIN_A:
self._pause("cut")
elif new < self.a:
self.a, self.set_at, self.why = new, now, "cut"
self.cap_a, self.cap_key = new, key
return
if target_w is None: # the sun cannot be measured: hold, then 0 A
self.ok_since = None
if self.a > 0.0:
if self.unknown_since is None:
self.unknown_since = now
if now - self.unknown_since >= pause_s:
self._pause("unknown")
else:
self.why = "unknown"
return
self.unknown_since = None
hi = None if _num(clamp) is None else math.floor(float(clamp))
if self.a <= 0.0: # paused: the start rule
n0 = 1 if auto else fixed_n
if target_w >= (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:
a = amps_for(target_w, n0, clamp)
if a is not None and self.cap_a is not None:
a = min(a, self.cap_a)
if a is not None and a >= MIN_A:
self.a, self.n, self.set_at = a, n0, now
self.ok_since = self.low_since = None
self.up_since = self.down_since = None
self.why = "running"
else:
self.ok_since = None
self.why = self.pause_why
return
if hi is not None and self.a > hi: # the clamp came down
if hi < MIN_A:
self._pause("paused")
return
self.a, self.set_at = float(hi), now
if auto: # auto phases, by their own dwells
if self.n == 1:
self.down_since = None
if target_w >= UP_W:
self.up_since = self.up_since if self.up_since is not None \
else 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):
self._switch(3, target_w, now, clamp)
return
else:
self.up_since = None
if target_w < DOWN_W:
self.down_since = self.down_since \
if self.down_since is not None else 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):
self._switch(1, target_w, now, clamp)
return
want = amps_for(target_w, n_calc, clamp)
if want is not None and want >= MIN_A:
self.low_since = None
if self.cap_a is not None:
want = min(want, self.cap_a)
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:
# Inside the phase hysteresis (4.0 kW to 6 A x 690 W): 3 phases at
# 6 A stand, as the switch rule says; no pause count.
self.low_since = None
self.why = "running"
if self.a != MIN_A and self._gate(now):
self.a, self.set_at = 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("paused")
return
if self.a != MIN_A and self._gate(now):
self.a, self.set_at = 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; what differs
is that every way out ends at 0 A, written once, and that an interrupted
phase change is never undone to the old current."""
def __init__(self):
super().__init__()
self.plan = SolarPlan()
self.engaged = False # Solar has run since it was chosen
self.reinit = True # start again from 0 A and the start rule
self.out = False # not writing: the 0 A has been tried
self.stand = False # no car: the standing 0 A has been tried
self.fault = None # "error" | "stuck" while it holds
self.fault_done = False
self.warned = False # the charger error warning, once
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, sent then
self.sent_a = None # the current we last decided to write
# ------------------------------------------------------------------ help
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":
self.single, self._one_since = False, None
return
drawing = [x for x in (r.current_a or ()) 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(r.current_a or ()) >= 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 _watch(self, cur, now) -> None:
"""As Manual's, and in Solar the hold is a warning: the add-on stops
writing until you press the mode or the read-back matches again."""
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: CHARGER_OTHER.")
@property
def n_calc(self) -> int:
return 1 if self.single else self.plan.n
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:
"""As Manual's, and Solar says its current again (another writer's
hold is lifted by pressing the mode)."""
super().user_changed()
self.sent_a = None
async def _zero_once(self, drv, cur, now, tracker, force=False) -> None:
"""One try of 0 A on the way out. Never over another writer, and not
when the charger already shows 0 A (unless the reading is stuck, so
its 0 A means nothing: `force`)."""
if self.hold or (not force and cur is not None and cur <= TOL_A):
return
self.zero_at, self.sent_a = now, 0.0
await self._write(drv, 0.0, cur, now, tracker)
def _leave(self) -> None:
self.engaged, self.seq, self.would = False, None, None
self.out = self.stand = False
self.fault, self.fault_done = None, False
self.reinit = True
self.sent_a = None
self.plan.reset(self.plan.n)
def _plan_step(self, sun, now, clamp) -> None:
gap = self.last_switch is None or now - self.last_switch >= PHASE_GAP_S
self.plan.step(
now, target_w=sun.target_w, hold=sun.hold, n_calc=self.n_calc,
auto=sun.auto and not self.single,
fixed_n=1 if self.single else sun.fixed_n, clamp=clamp,
cut_w=sun.cut_w, car_w=sun.car_w, key=sun.key,
start_s=sun.start_s, pause_s=sun.pause_s,
gap_ok=gap and not self.phases_gave_up)
# ------------------------------------------------------------------ step
async def step(self, drv, r, *, mode, sun, clamp, now, tracker, writing,
status, clock=None):
"""One cycle. `sun` is `SunInputs`; `writing` is False in shadow mode,
while control is stopped, under a safety stop and while stopping."""
self._clock = clock or (lambda: now)
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:
return
self._mark(r, now)
if not self.was_available:
self.was_available = True
self.reinit = True # back: 0 A first, then the rules
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
if mode != SOLAR:
self.would = None
if not self.engaged:
return
if mode != MANUAL: # Off: 0 A once, then nothing
self.seq = None
await self._zero_once(drv, cur, now, tracker)
self._leave() # Manual writes its own current
return
self.engaged = True
if sun is None:
return
if not writing:
# Shadow, Stop, a safety stop, stopping: 0 A once, then nothing.
# The plan goes on, so the card says what it would set.
self.seq = None
if not self.out:
self.out = True
await self._zero_once(drv, cur, now, tracker)
self._plan_step(sun, now, clamp)
self.would = (self.amps_out(clamp), self.n_calc)
self.reinit = True
return
self.out = False
self.would = None
fault = ("error" if (r.error or r.state in ("E", "F")) else
"stuck" if tracker is not None and tracker.stuck(now)
else None)
if fault is not None:
# 0 A once, then no write until it clears; then the start rule.
self.seq = None
if self.fault != fault:
self.fault, self.fault_done = fault, False
if fault == "error" and not self.warned:
self.warned = True
_LOG.warning("The charger reports an error, so the add-on "
"sets the car to 0 A: CHARGER_ERROR.")
if not self.fault_done:
self.fault_done = True
await self._zero_once(drv, cur, now, tracker,
force=fault == "stuck")
self.plan.reset(self.plan.n, why=fault)
self.reinit = True
return
if self.fault is not None:
self.fault, self.fault_done = None, False
self.warned = False
if r.state == "A" or status == CH.NONE_:
# No car: the standing current is 0 A, written once.
self.seq = None
if not self.stand:
self.stand = True
await self._zero_once(drv, cur, now, tracker)
self.plan.reset(self.plan.n, why="none")
self.reinit = False
return
self.stand = False
if self.reinit:
self.reinit = False
self.seq = None
self.mismatch_since = None
self.sent_a = None
n = r.phases_allowed if r.phases_allowed in (1, 3) else self.plan.n
self.plan.reset(n)
if status == CH.FULL: # the car is full: nothing written
self.plan.why = "full"
return
if self.seq is None:
self._watch(cur, now)
if self.hold:
return
self._plan_step(sun, now, clamp)
if self.seq is not None:
q = self.seq
if self.plan.a < CH.MIN_A:
self.seq = None # paused or cut: it stays at 0 A
return
pf = self.phase_fails
await self._advance(drv, r, cur, now, tracker, self.amps_out(clamp)
or CH.MIN_A, clamp, None)
if self.phase_fails > pf and q.get("from") in (1, 3):
self.plan.n = q["from"] # the select was not taken
if self.seq is None:
self.sent_a = self.last_a
return
want = self.amps_out(clamp)
if want >= CH.MIN_A and not self.single and not self.phases_gave_up \
and r.phases_allowed in (1, 3) \
and r.phases_allowed != self.plan.n:
if self.last_switch is not None \
and now - self.last_switch < PHASE_GAP_S:
self.blocked = True
return
self.blocked = False
self.zero_at, self.sent_a = now, 0.0
await self._begin(drv, r, cur, self.plan.n, now, tracker)
if self.seq is not None:
self.seq["from"] = r.phases_allowed
return
if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A \
and self.fail_at is None:
return # nothing new: a read-back that differs is `_watch`'s
if cur is not None and abs(cur - want) <= TOL_A:
self.sent_a = want
self.fails, self.fail_at = 0, None
if self.last_a is None or abs(self.last_a - cur) > TOL_A:
self.last_a = cur
return
if self.gave_up or (self.fail_at is not None
and now - self.fail_at < RETRY_S):
return
if want <= 0.0:
self.zero_at = now
self.sent_a = want
if await self._write(drv, want, cur, now, tracker):
self.fails, self.fail_at = 0, None
else:
self._failed(now)
async def release(self, drv, r, now, tracker) -> None:
"""The add-on stops in Solar: 0 A, once, before the inverters go to
0 W. A phase change in the middle is not undone to the old current."""
self.seq = 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
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:
cur = self.last_a # the reading predates our own write
self._clock = self._clock or (lambda: now)
await self._zero_once(drv, cur, now, tracker)
self.out = True