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
+20 -11
View File
@@ -5,8 +5,8 @@ actuator per site, a census key, a read, a clamped write that says whether the
charger took it, and a hand-back. A charger is a modulated actuator with a fail
state, not one of DEV-01's on/off loads.
EV-04 IS THE FIRST CARD THAT WRITES TO THE CHARGER, and only in Manual
(`app/carmode.py` is the one caller). `write_current` is clamped to
EV-04 IS THE FIRST CARD THAT WRITES TO THE CHARGER, in Manual and (EV-20) in
Solar (`app/carmode.py` is the one caller). `write_current` is clamped to
`min(ev_max_a, the station limit the charger reports, the entity's own range)`
and a value above that is NEVER SENT: it is a software fault, logged in the
OUTPUT_CLAMP shape. It says True only when the charger's read-back followed
@@ -42,7 +42,13 @@ PHASES_CHOICES = ("1", "3", "auto")
# config.yaml's shipped defaults, mirrored (test_defaults_pin.py checks it).
EV_OPTION_DEFAULTS = {"ev_charger": "off", "ev_current_entity": "",
"ev_max_a": 16, "ev_phases": "auto",
"ev_batt_cover": True, "ev_mode_start": "keep"}
"ev_batt_cover": True, "ev_mode_start": "keep",
# EV-20, Solar: the sun kept back and the two dwells
"ev_margin_w": 100, "ev_pause_min": 5,
"ev_start_min": 2}
#: EV-20: the ranges config.yaml's schema and the validator both hold.
SOLAR_RANGES = {"ev_margin_w": (0, 1000), "ev_pause_min": (1, 30),
"ev_start_min": (1, 30)}
def max_a(opts: dict):
@@ -396,7 +402,7 @@ class ChargerDriver:
from the charger, the entity's own range max)`."""
raise NotImplementedError
async def write_current(self, a: float) -> bool:
async def write_current(self, a: float, took_s: float = TOOK_S) -> bool:
raise NotImplementedError
async def write_phases(self, n: int) -> bool:
@@ -503,9 +509,10 @@ class AlfenHaDriver(ChargerDriver):
pass
return min(x for x in (self.max_a, station, rng) if x is not None)
async def write_current(self, a: float) -> bool:
async def write_current(self, a: float, took_s: float = TOOK_S) -> bool:
"""Set the current, once. True only when the charger took it: the
read-back followed within `TOOK_S`. A value above `clamp_a()` is a
read-back followed within `took_s` (`TOOK_S`; EV-20's shutdown 0 A
waits less, so three tries fit its 15 s). A value above `clamp_a()` is a
SOFTWARE FAULT: nothing is sent, it is logged (the clamp watchdog's
shape) and the answer is False."""
self.polls = []
@@ -527,10 +534,10 @@ class AlfenHaDriver(ChargerDriver):
del self.sent[:-50]
if not await hass.set_number(self.current_entity, a):
return False
return await self._took(a)
return await self._took(a, took_s)
async def _took(self, a: float) -> bool:
"""Did the read-back follow the write, within `TOOK_S`?"""
async def _took(self, a: float, took_s: float = TOOK_S) -> bool:
"""Did the read-back follow the write, within `took_s`?"""
t0 = self._clock()
while True:
st = await self._states(("readback", "current") + _LIFE_ROLES)
@@ -538,7 +545,7 @@ class AlfenHaDriver(ChargerDriver):
seen = _first(_amps(st["readback"]), _amps(st["current"]))
if seen is not None and abs(seen - a) <= TOOK_TOL_A:
return True
if self._clock() - t0 >= TOOK_S:
if self._clock() - t0 >= took_s:
return False
await self._sleep(1.0)
@@ -576,7 +583,9 @@ class AlfenHaDriver(ChargerDriver):
async def release(self, mode: str) -> bool:
"""The mode's fail state. Manual and Off keep the current (the charger
is a stand-alone device and the current is the user's setting)."""
is a stand-alone device and the current is the user's setting).
Solar's 0 A goes through `carmode.SolarWriter.release`, the one write
site, so nothing is written here."""
return True
+297 -28
View File
@@ -1,9 +1,12 @@
"""EV-04: the Controller's side of the car's Manual mode.
"""EV-04 and EV-20: the Controller's side of the car's Manual and Solar modes.
The writes themselves are `carmode.ManualWriter`'s; this mixin owns the state
(mode, current, phases: runtime state in the store, like OPT-11's modes), the
actions, the background step that never holds up a control cycle, and what the
car means for the peak guard's ALARM PATH. DECISIONS/EV-04-manual-mode.md.
The writes themselves are `carmode.ManualWriter`'s and `carmode.SolarWriter`'s;
this mixin owns the state (mode, current, phases, where spare sun goes first:
runtime state in the store, like OPT-11's modes), the actions, the background
step that never holds up a control cycle, and what the car means for the peak
guard's ALARM PATH. DECISIONS/EV-04-manual-mode.md, DECISIONS/EV-20-solar-mode.md
(Solar's inputs, its 0 A before the inverters at shutdown, today's solar kWh;
the guard treats a Solar car exactly as a Manual car).
"""
import asyncio
@@ -11,7 +14,7 @@ import dataclasses
import logging
from datetime import timezone
from . import carmode, chargers, messages, peakguard
from . import carmode, chargers, messages, packshare, peakguard
from .tariff import QUARTER_S
_LOG = logging.getLogger("goodwe")
@@ -34,6 +37,13 @@ OWN_PAUSE_TAIL_S = chargers.CORR_WINDOW_S
# EV-19: the meter's house side (held - car) moved no more than this since the
# last cycle: it has not shown a battery rise the reading already shows.
RISE_STILL_W = 50.0
# EV-20: today's kWh from the sun, {day, kwh}; and a shutdown whose 0 A the
# charger did not take (D3), so the next start can take its notice down.
CAR_SUN_KEY = "car_sun"
CAR_RELEASE_KEY = "car_release_failed"
# EV-20 (D3): at shutdown in Solar the charger's 0 A waits at most this long,
# then the inverters are released whatever the charger did.
RELEASE_WAIT_S = 15.0
class CarMixin:
@@ -55,6 +65,23 @@ class CarMixin:
self.car_n = n if n in ok else ok[0]
self.car_rev = 0
self.car_writer = carmode.ManualWriter()
self.car_solar = carmode.SolarWriter() # EV-20
first = data.get(carmode.KEY_FIRST)
self.car_first = first if first in carmode.FIRSTS \
else carmode.DEFAULT_FIRST
self._car_late_s = None # EV-20: the cycle's late verdict
self._car_sun_now = None # ... and Solar's inputs of that cycle
sun = data.get(CAR_SUN_KEY)
self.car_sun = {"day": None, "kwh": 0.0}
if isinstance(sun, dict):
try:
self.car_sun = {"day": sun.get("day"),
"kwh": max(0.0, float(sun.get("kwh") or 0.0))}
except (TypeError, ValueError):
pass
self._car_sun_mono = None
self._car_sun_saved = round(self.car_sun["kwh"], 2)
self._car_release_failed = bool(data.get(CAR_RELEASE_KEY))
self._car_task = None
self._car_step_failed = False
self.car_explains = False # the car alone explains the excess
@@ -89,6 +116,23 @@ class CarMixin:
return (self.charger.configured()
and self.car_mode == carmode.MANUAL)
def car_solar_mode(self) -> bool:
"""EV-20: a charger is set up and the mode is Solar."""
ch = getattr(self, "charger", None)
return bool(ch is not None and ch.configured()
and getattr(self, "car_mode", None) == carmode.SOLAR)
def car_controlled(self) -> bool:
"""EV-20: Manual or Solar. The peak guard's alarm path treats a Solar
car exactly as a Manual car (Expected 8)."""
return self.car_manual() or self.car_solar_mode()
def car_solar_engaged(self) -> bool:
"""EV-20: Solar is the mode, or its way-out 0 A is still owed."""
w = getattr(self, "car_solar", None)
return bool(self.charger.configured() and w is not None
and (self.car_mode == carmode.SOLAR or w.engaged))
def car_clamp(self):
return carmode.clamp_for(self.o, self.car.reading)
@@ -110,8 +154,23 @@ class CarMixin:
if what == "car_mode":
if value not in carmode.MODES:
return {"error": messages.car_refused("value")}
if value == carmode.SOLAR and self.car_mode != carmode.SOLAR:
# A Manual phase change in the middle is not restored: Solar
# starts from the 0 A it stands at.
self.car_writer.seq = None
self.car_mode = value
self.store.set(carmode.KEY_MODE, value)
elif what == "car_sun_first":
# EV-20: arithmetic only, from the next cycle; not a change of the
# writers (the 30 s rule and another writer's hold stand).
if value not in carmode.FIRSTS:
return {"error": messages.car_refused("value")}
self.car_first = value
self.store.set(carmode.KEY_FIRST, value)
self.log_event(f"car sun first set to {value} by operator",
hint=messages.hint("car_sun_first"))
return {"mode": self.car_mode, "current": self.car_a,
"phases": self.car_n, "sun_first": self.car_first}
elif what == "car_current":
clamp = self.car_clamp()
if isinstance(value, bool):
@@ -134,6 +193,11 @@ class CarMixin:
self.store.set(carmode.KEY_PHASES, value)
self.car_rev += 1
self.car_writer.user_changed()
if what == "car_mode" and value == carmode.SOLAR:
# EV-20: only pressing Solar lifts Solar's other-writer hold.
# Leaving Solar, or Manual's current or phases, is not the user
# handing the charger back to Solar (N10).
self.car_solar.user_changed()
self.log_event(f"car {what[4:]} set to {value} by operator",
hint=messages.hint(what))
return {"mode": self.car_mode, "current": self.car_a,
@@ -143,7 +207,8 @@ class CarMixin:
"""The MQTT state of the three car entities."""
return {"car_mode": carmode.MODE_LABELS[self.car_mode],
"car_current": round(self.car_a),
"car_phases": str(self.car_n)}
"car_phases": str(self.car_n),
"car_sun_first": carmode.FIRST_LABELS[self.car_first]}
# ------------------------------------------------------------- the writer
def car_kick(self) -> None:
@@ -155,8 +220,20 @@ class CarMixin:
t = self._car_task
if t is not None and not t.done():
return
# EV-20: Solar's inputs as this cycle read them. The step runs beside
# the next read, which must not hand it a new meter reading with an
# old car reading (or the other way round).
self._car_sun_now = (self.car_sun_inputs(self.car_now())
if self.car_solar_mode() else None)
self._car_task = asyncio.ensure_future(self._car_run())
def _car_hold_kick(self) -> None:
"""EV-20: a cycle that holds for a missing or late reading returns
before `car_kick()`. Solar still steps (it holds, counts its dwell,
and a way out still writes its 0 A); Manual is left as it was."""
if self.car_solar_engaged():
self.car_kick()
async def car_settle(self) -> None:
"""Wait for the writer step in flight (the checks use it)."""
t = self._car_task
@@ -180,13 +257,29 @@ class CarMixin:
self._car_step_failed = False
async def car_shutdown(self) -> None:
"""The add-on stops: no new write, and a phase change in the middle is
undone by giving the car its current back. The current stands
otherwise (Manual's fail state)."""
"""The add-on stops: no new write. Manual: a phase change in the middle
is undone by giving the car its current back; the current stands
otherwise (Manual's fail state). Solar (EV-20, D3): 0 A, waited for at
most `RELEASE_WAIT_S` (`Controller.shutdown` calls this BEFORE the
inverters go to 0 W in Solar)."""
t, self._car_task = getattr(self, "_car_task", None), None
if t is not None and not t.done():
t.cancel()
await asyncio.gather(t, return_exceptions=True)
if self.car_solar_engaged():
try:
done = await asyncio.wait_for(self.car_solar.release(
self.charger, self.car.reading, self.car_now(), self.car),
RELEASE_WAIT_S)
except Exception: # noqa: BLE001
done = False
if done is False:
self._car_release_failed = True
self.store.set(CAR_RELEASE_KEY, True)
_LOG.warning("The charger did not take 0 A before the add-on "
"stopped, so the car may still be charging: "
"CHARGER_RELEASE.")
return
if not self.charger.configured() \
or getattr(self, "car_writer", None) is None \
or self.car_writer.seq is None:
@@ -199,25 +292,171 @@ class CarMixin:
_LOG.warning("The car could not be given its current back "
"before the add-on stopped: CHARGER_RESTORE.")
async def car_release_notice(self) -> None:
"""D3: after the inverters are released, one warning notice that the
car may still be charging. Bounded: the add-on is stopping."""
if not self._car_release_failed or not self.car_solar_engaged():
return
try:
await asyncio.wait_for(self.hass.call(
"persistent_notification", "create",
messages.car_release_failed().data()), 3.0)
except Exception: # noqa: BLE001
_LOG.debug("The car notice could not be raised at shutdown",
exc_info=True)
async def check_car_release(self) -> None:
"""D3: the notice of a shutdown whose 0 A was not taken comes down once
Solar has confirmed its start-up 0 A."""
w = self.car_solar
if self._car_release_failed and w.engaged and not w.fresh_start \
and w.sent_a == 0.0 and w.taken:
self._car_release_failed = False
self.store.set(CAR_RELEASE_KEY, False)
await self.hass.call("persistent_notification", "dismiss",
messages.car_release_gone().data())
async def car_step(self) -> None:
"""One step of Manual. Reads nothing from the world (the cycle's read
did) and writes only through `carmode.ManualWriter`."""
"""One step of Manual or Solar. Reads nothing from the world (the
cycle's read did) and writes only through `carmode`'s writers."""
if not self.charger.configured():
return
now = self.car_now()
await self.car_writer.step(
self.charger, self.car.reading, mode=self.car_mode,
want_a=self.car_a, want_phases=self.car_n, rev=self.car_rev,
clamp=self.car_clamp(), now=now, tracker=self.car,
writing=self.car_writing(), shadow=bool(self.shadow),
status=self.car.status(now, True), clock=self.car_now)
if self.car_mode != carmode.SOLAR:
await self.car_writer.step(
self.charger, self.car.reading, mode=self.car_mode,
want_a=self.car_a, want_phases=self.car_n, rev=self.car_rev,
clamp=self.car_clamp(), now=now, tracker=self.car,
writing=self.car_writing(), shadow=bool(self.shadow),
status=self.car.status(now, True), clock=self.car_now)
w = self.car_solar
if self.car_mode == carmode.SOLAR or w.engaged:
sun = None
if self.car_mode == carmode.SOLAR:
sun = getattr(self, "_car_sun_now", None) \
or self.car_sun_inputs(now)
await w.step(
self.charger, self.car.reading, mode=self.car_mode,
sun=sun,
clamp=self.car_clamp(), now=now, tracker=self.car,
writing=self.car_writing(), status=self.car.status(now, True),
clock=self.car_now)
# ------------------------------------------------------- EV-20: Solar
def car_may_charge(self, inv) -> bool:
"""May this battery take the sun? On (battery modes), not refusing a
charge, not under a sign stop, its level read and under full."""
if self.modes_on and not self.pack_mode(inv).use:
return False
refused = inv.refused if len(self.inverters) > 1 \
else self.batt_refused
if (refused or 0) < 0 or inv.sign_wd.tripped:
return False
return inv.soc is not None and float(inv.soc) < packshare.FULL_PCT
def car_room_w(self) -> float:
"""Batteries first: the RATINGS of the batteries that may charge."""
return float(sum(inv.rating_w() for inv in self.inverters
if self.car_may_charge(inv)))
def car_spare_w(self, mono):
"""The signed spare sun now, or None when it cannot be measured: a
missing meter or battery figure, a meter older than `stale_input_s`,
readings late past it, or a charging car whose figure is stale, stuck
or not corroborated. A paused or idle car with a fresh reading counts
as 0 W."""
if not self.inputs_ok:
return None
stale = float(self.o.get("stale_input_s", 15))
late = self._car_late_s
if late is not None and late >= stale:
return None
if self.p1_enabled:
# The meter's own bound (`meter_max_age_s`) may be longer than
# `stale_input_s`; a car write never comes from an older reading.
age = self.p1.age_s()
if age is None or age > stale:
return None
r = self.car.reading
if r is None or not r.available or not self.car.fresh(mono):
return None
car = self.car.car_w_trusted(mono) if r.charging is True else 0.0
return carmode.spare_w(car, self.site_batt_w, self.grid)
def car_sun_inputs(self, mono) -> "carmode.SunInputs":
o = self.o
spare = self.car_spare_w(mono)
late = self._car_late_s
hold = late is not None and late < float(o.get("stale_input_s", 15))
room = self.car_room_w()
margin = carmode.solar_option(o, "ev_margin_w")
ph = str(o.get("ev_phases", chargers.EV_OPTION_DEFAULTS["ev_phases"]))
return carmode.SunInputs(
target_w=carmode.car_target_w(spare, room, margin, self.car_first),
hold=hold, auto=ph not in ("1", "3"),
start_s=60.0 * carmode.solar_option(o, "ev_start_min"),
pause_s=60.0 * carmode.solar_option(o, "ev_pause_min"),
spare_w=spare, room_w=room, margin_w=margin, first=self.car_first)
def _car_sun_tick(self, mono) -> None:
"""Solar kWh: per cycle, in Solar only, the car's power up to the sun
it may take (`spare - room` Batteries first, `spare` Car first). The
hold's battery or grid share and Manual do not count."""
if not self.car_solar_mode():
self._car_sun_mono = None
return
day = self.car.day
if day is not None and self.car_sun.get("day") != day:
self.car_sun = {"day": day, "kwh": 0.0}
self.store.set(CAR_SUN_KEY, dict(self.car_sun))
self._car_sun_saved = 0.0
last, self._car_sun_mono = self._car_sun_mono, mono
if last is None:
return
dt = min(max(mono - last, 0.0), 5.0)
p = self.car.car_w(mono)
spare = self.car_spare_w(mono)
if p is None or spare is None or dt <= 0.0:
return
sun = spare - (self.car_room_w() if self.car_first == carmode.FIRST_BATT
else 0.0)
share = min(float(p), max(0.0, sun))
if share <= 0.0:
return
self.car_sun["kwh"] += share * dt / 3.6e6
if round(self.car_sun["kwh"], 2) != self._car_sun_saved:
self._car_sun_saved = round(self.car_sun["kwh"], 2)
self.store.set(CAR_SUN_KEY, {"day": self.car_sun["day"],
"kwh": round(self.car_sun["kwh"], 4)})
def car_sun_kwh(self):
"""Today's kWh from the sun, never above today's kWh; None without a
reading of today."""
if self.car.today_kwh is None:
return None
if self.car_sun.get("day") != self.car.day:
return 0.0
return max(0.0, min(float(self.car_sun["kwh"]),
float(self.car.today_kwh)))
def car_amps_now(self):
"""D1: the current Solar charges the car at now: the read-back, else
what Solar sent. Never Manual's stored value."""
r = self.car.reading
if r is not None and r.available:
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
if cur is not None:
return float(cur)
w = self.car_solar
return float(w.sent_a or 0.0)
# ------------------------------------------- the car and the peak guard
def car_alarm_w(self):
"""The car's power for the guard's alarm path: Manual only, fresh, not
stuck (`CarTracker.car_w_trusted`), and never above what the read-back
allows. None otherwise, and then the normal alarms stand."""
if not self.car_manual():
"""The car's power for the guard's alarm path: Manual and (EV-20)
Solar, fresh, not stuck (`CarTracker.car_w_trusted`), and never above
what the read-back allows. None otherwise, and then the normal alarms
stand."""
if not self.car_controlled():
return None
return self.car.car_w_trusted(self.car_now())
@@ -226,13 +465,21 @@ class CarMixin:
the moment its 0 A write is SENT (the cycle runs beside the write)
until the current is set again, then at most one corroboration window.
No when it was aborted (Off, Stop, shadow, unplug, another writer), a
write was refused, or it ran past its own maximum."""
wr = getattr(self, "car_writer", None)
write was refused, or it ran past its own maximum.
EV-20: Solar's own phase change the same way, and Solar's own 0 A
pause from the moment it is sent, at most `OWN_PAUSE_MAX_S`, and only
while the read-back still shows that 0 A (a car another writer starts
is never Solar's pause)."""
solar = self.car_solar_mode()
wr = getattr(self, "car_solar" if solar else "car_writer", None)
own_zero = solar and wr is not None and self._car_solar_zero(wr)
if wr is None or (wr.seq is None and wr.phase_done_at is None
and wr.zero_sent_at is None) or wr.hold:
and wr.zero_sent_at is None and not own_zero) \
or wr.hold:
return False
r = self.car.reading
if not (self.car_manual() and self.car_writing()
if not (self.car_controlled() and self.car_writing()
and r is not None and r.available and r.state != "A"):
return False
q = wr.seq
@@ -241,7 +488,21 @@ class CarMixin:
if q is not None:
return not q.get("failed") and 0.0 <= mono - q["t0"] \
<= OWN_PAUSE_MAX_S
return 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S
if own_zero and 0.0 <= mono - wr.zero_at <= OWN_PAUSE_MAX_S:
return True
return wr.phase_done_at is not None \
and 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S
def _car_solar_zero(self, wr) -> bool:
"""EV-20: is Solar's own latest write a 0 A the charger took, and does
the read-back still show it? (Another writer's current ends it.)"""
if wr.zero_at is None or wr.sent_a != 0.0 or not wr.taken:
return False
r = self.car.reading
if r is None or not r.available:
return False
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
return cur is not None and cur <= carmode.TOL_A
def _car_contradicted(self, mono) -> bool:
"""EV-18 (owner 2026-11-19): did the charger's energy meter answer
@@ -251,7 +512,7 @@ class CarMixin:
contradicts nothing."""
r = getattr(self.car, "reading", None)
if r is None or not r.available or r.charging is not True \
or not self.car_manual():
or not self.car_controlled():
return False
return (self.car.car_w(mono) is not None and not self.car.stuck(mono)
and self.car.contradicted(mono))
@@ -348,6 +609,7 @@ class CarMixin:
"""After the guard has decided: does the car alone explain the excess?
`real_proj` is the projection WITH the car, whatever the guard saw."""
mono = self.car_now()
self._car_sun_tick(mono) # EV-20: today's solar kWh
w = self.car_alarm_w()
# EV-15: the figure for grading only. Our own phase change holds the
# car at 0 A and the energy meter cannot corroborate it then, so for
@@ -538,6 +800,13 @@ class CarMixin:
if not self.car_over or self._car_over_notified == self._car_session:
return
self._car_over_notified = self._car_session
if self.car_solar_mode(): # EV-20, D1
_LOG.info("Solar's car charge takes this 15-minute period over "
"the peak limit: CAR_OVER_PEAK.")
await self.hass.call("persistent_notification", "create",
messages.car_over_solar(
f"{self.car_amps_now():.0f}").data())
return
_LOG.info("The car charge you set takes this 15-minute period over "
"the peak limit: CAR_OVER_PEAK.")
await self.hass.call("persistent_notification", "create",
+7 -2
View File
@@ -253,6 +253,7 @@ class CycleMixin:
stale_after = float(self.o.get("stale_input_s", 15))
late_s = self._readings_late(site_standing) # SAFETY-128
self._car_late_s = late_s # EV-20: Solar holds, then the stale rule
self._late_zero = late_s is not None and late_s >= stale_after
# ⚠️ `any`, NOT the sole unit's. The hold exists so a single missed
# poll does not become a fault; a LATCHED inverter must still reach the
@@ -272,6 +273,7 @@ class CycleMixin:
# this cycle's. (DECISIONS/MAIN-orchestration-archive.md)
self.why_words = messages.why_waiting(bad_for)
self._why_waiting_since = now - timedelta(seconds=bad_for)
self._car_hold_kick() # EV-20: Solar counts from now
return
if late_s is not None and late_s < stale_after and self.inputs_ok \
and (self.auto or self.shadow) \
@@ -279,6 +281,7 @@ class CycleMixin:
and not (n_units > 1 and self.site_sign_wd.tripped):
self.reason = f"readings late {late_s:.0f}s" # SAFETY-128: hold
self.why_words = messages.why_late()
self._car_hold_kick() # EV-20: Solar holds its current
return
claims = []
@@ -396,8 +399,9 @@ class CycleMixin:
# `_peak_proj_real` keeps the quarter as the meter will bill it, for
# the car's own words. Only a fresh, trusted car reading is left out.
self._peak_proj_real = self._peak_proj
# EV-20: a Solar car exactly as a Manual car.
if (self._peak_proj is not None and not self.car_cover
and self.car_manual()):
and self.car_controlled()):
self._peak_proj = self.car_exclude(self._peak_proj,
self.car_alarm_w())
self.peak_guard = None if not self.p1_enabled else peakguard.decide(
@@ -1065,7 +1069,8 @@ class CycleMixin:
await self.check_price_gap()
await self.check_charger()
await self.check_car_over()
self.car_kick() # EV-04: Manual, in the background
await self.check_car_release() # EV-20 (D3)
self.car_kick() # EV-04/20: in the background
await self.check_fixed_note()
# SAFETY-31's alarm, and its boundary is the LATCH, not a number: it
+21 -3
View File
@@ -205,7 +205,19 @@ class StatusMixin:
"text": messages.row_charger_unreach(
f"{brussels(self.car.bad_since_utc):%H:%M}")})
w = self.car_writer
if self.car_mode == "manual":
sw = self.car_solar
if self.car_mode == "solar" or (sw.engaged and sw.gave_up):
# EV-20: in Solar another writer stops the add-on's writes: amber.
if sw.other and self.car_mode == "solar":
out.append({"ok": False, "warn": True, "id": "charger_other",
"text": messages.row_charger_other_solar()})
if sw.gave_up:
out.append({"ok": False, "warn": True, "id": "charger_refused",
"text": messages.row_charger_refused()})
if sw.phases_gave_up and self.car_mode == "solar":
out.append({"ok": False, "warn": True, "id": "charger_phases",
"text": messages.row_charger_phases()})
elif self.car_mode == "manual":
# EV-04: in Manual the add-on's own writes are not "another
# writer"; its own detector (a read-back that differs from the
# last write for 30 s) says so, in grey.
@@ -230,7 +242,10 @@ class StatusMixin:
"text": messages.row_charger_error(r.error)})
if self.car_over:
out.append({"ok": True, "warn": True, "id": "car_over",
"text": messages.row_car_over()})
"text": (messages.row_car_over_solar(
f"{self.car_amps_now():.0f}")
if self.car_solar_mode()
else messages.row_car_over())})
return out
def car_values(self) -> dict:
@@ -250,6 +265,9 @@ class StatusMixin:
or r.power_w is None else round(r.power_w, 1)),
"car_today_kwh": (PAYLOAD_NONE if self.car.today_kwh is None
else round(self.car.today_kwh, 3)),
# EV-20: today's kWh from the sun (Solar only adds to it)
"car_today_solar_kwh": (PAYLOAD_NONE if self.car_sun_kwh() is None
else round(self.car_sun_kwh(), 3)),
}
# -- UI ------------------------------------------------------------------
@@ -922,7 +940,7 @@ class StatusMixin:
now = datetime.now(timezone.utc)
if what in ("pack_use", "pack_mode", "pack_sell"):
return self._pack_action(what, unit, value, now)
if what in ("car_mode", "car_current", "car_phases"):
if what in ("car_mode", "car_current", "car_phases", "car_sun_first"):
return self._car_action(what, value, now)
if what == "auto_toggle":
self.auto = not self.auto
+68 -7
View File
@@ -1134,7 +1134,7 @@ def month_peak(c, now):
ceiling = pg.ceiling_w or limit_w
real = getattr(c, "_peak_proj_real", None)
if getattr(c, "car_enabled", False) and c.charger.configured() \
and not c.car_cover and c.car_manual() and real is not None \
and not c.car_cover and c.car_controlled() and real is not None \
and getattr(real, "block_start", None) is not None:
# EV-04, decision 1 off: the guard's own projection leaves the car
# out; the period as the meter will bill it does not.
@@ -1374,6 +1374,54 @@ def _car_manual_why(c, key):
return _t("car.why.manual_set", a=a, phases=car_phases_word(c.car_n))
def _car_solar_why(c, key):
"""EV-20: the Why of Solar, from what the writer and its plan did this
cycle. Plan lines: two sentences of at most 12 words."""
w = c.car_solar
p = w.plan
o = getattr(c, "o", {}) or {}
if c.car_over: # D1
return _t("car.why.solar_over", a=f"{c.car_amps_now():.0f}")
if w.hold:
return _t("car.why.solar_other")
if w.zero_owed:
# The way-out 0 A is not taken yet: never "paused".
return _t("car.why.solar_zero_failed" if w.gave_up
else "car.why.solar_zeroing")
if w.gave_up:
return _t("car.why.solar_refused")
if c.shadow:
a, n = w.would if w.would is not None else (0.0, p.n)
if a and a >= 6:
return _t("car.why.manual_would", a=f"{float(a):.0f}",
phases=car_phases_word(n))
return _t("car.why.solar_would")
if not c.auto or not c.car_writing():
return _t("car.why.solar_stopped")
if w.fault in ("error", "stuck"):
return _t("car.why.solar_" + w.fault)
if key == "none":
return _t("car.why.none")
why = p.why
sun = w.sun
if why == "running":
if sun is None or sun.spare_w is None:
return _t("car.why.solar_unknown")
if sun.first == carmode.FIRST_CAR:
return _t("car.why.solar_car",
kw=_kw(max(0.0, sun.spare_w - sun.margin_w)))
return _t("car.why.solar_batt",
kw=_kw(max(0.0, sun.spare_w - sun.room_w - sun.margin_w)))
if why == "hold":
return _t("car.why.solar_hold", s=f"{carmode.solar_option(o, 'ev_pause_min'):.0f}")
if why == "unknown":
return _t("car.why.solar_unknown")
s = f"{carmode.solar_option(o, 'ev_start_min'):.0f}"
if why == "start":
return _t("car.why.solar_start", s=s)
return _t("car.why.solar_paused", s=s)
def car_block(c, now):
"""The Car card for `/status`, or None when no charger is switched on (the
page then draws nothing, as before)."""
@@ -1386,12 +1434,21 @@ def car_block(c, now):
good = c.car.last_good
fresh = configured and c.car.fresh(mono)
today = None
if configured and c.car.today_kwh is not None:
today = _t("car.today", kwh=_kwh(c.car.today_kwh))
mode = getattr(c, "car_mode", "off") if configured else "off"
if configured and c.car.today_kwh is not None:
sun = c.car_sun_kwh() if mode == "solar" else None
today = (_t("car.today_sun", kwh=_kwh(c.car.today_kwh),
sun=_kwh(sun)) if sun is not None
else _t("car.today", kwh=_kwh(c.car.today_kwh)))
why = _car_why(key, c, good)
if mode == "manual" and key in ("charging", "waiting", "none", "full"):
why = _car_manual_why(c, key)
if mode == "solar" and key in ("charging", "waiting", "none", "full",
"fault"):
why = _car_solar_why(c, key)
# EV-20: a car Solar holds at 0 A is waiting for the sun.
if key == "waiting" and c.car_solar.plan.a <= 0.0:
key = "paused"
out = {
"state": key or "wait",
"chip": car_state_word(key),
@@ -1404,11 +1461,14 @@ def car_block(c, now):
else round(float(r.power_w), 1)),
}
if configured:
# EV-04: what the page can set. Off and Manual only (Solar and Night
# are later cards, so they are not offered).
# EV-04: what the page can set. EV-20 adds Solar and where its spare
# sun goes first (Night is a later card, so it is not offered).
clamp = c.car_clamp()
hi = int(clamp) if clamp is not None and clamp >= 6 else 6
out["modes"] = ["off", "manual"]
out["modes"] = list(carmode.MODES)
out["first"] = {"value": getattr(c, "car_first",
carmode.DEFAULT_FIRST),
"choices": list(carmode.FIRSTS)}
out["current"] = {"value": round(float(c.car_a)), "min": 6,
"max": hi}
out["phases"] = {"value": c.car_n,
@@ -1928,12 +1988,13 @@ def _samples() -> list:
words["car"]["big"]]
out += [("plan", _t("car.why." + k, a="10", brand="Alfen", kw="8.6 kW",
pct="20 %", phases=car_phases_word(3),
real=car_phases_word(1)))
real=car_phases_word(1), s="5"))
for k in words["car"]["why"]]
out += [("plan", _t("peak.car", kw="12.1 kW", car="11.0 kW",
cov="8.6 kW")),
("plan", _t("peak.set_by_car", t="19:45"))]
out += [("plan", _t("car.today", kwh="14.2 kWh")),
("plan", _t("car.today_sun", kwh="14.2 kWh", sun="3.1 kWh")),
("plan", "11.0 kW · 16 A · " + _t("car.phase_many", n=3))]
out += [("plan", line_no_trade(k)) for k in
("not_covered", "no_prices", "peak", "not_firm", "not_worth",
+10 -1
View File
@@ -1040,8 +1040,17 @@ class Controller(InputsMixin, WritesMixin, TradeMixin, CycleMixin, AlarmsMixin,
self.stopping = True
_LOG.info(handback.log_shutdown(handback.current())
or "shutting down - commanding 0 W on every inverter")
# EV-20 (D3): Solar's fail state is 0 A, and it goes out BEFORE the
# inverters go to 0 W, bounded by `ctl_car.RELEASE_WAIT_S`. Manual
# keeps EV-04's order: the inverters first, then undo a phase change.
solar = self.car_solar_engaged()
if solar:
await self.car_shutdown()
await self.command_site_release()
await self.car_shutdown() # EV-04: undo a phase change half way
if solar:
await self.car_release_notice()
else:
await self.car_shutdown() # EV-04: undo a phase change half way
self.mqtt.close()
+61
View File
@@ -190,6 +190,8 @@ T_CHARGER_UNREACH = "Charger not reachable"
T_CHARGER_UNREACH_NL = "Laadpaal onbereikbaar"
T_CAR_OVER = "Car over the peak limit"
T_CAR_OVER_NL = "Auto boven de piekgrens"
T_CAR_RELEASE = "Car may still be charging"
T_CAR_RELEASE_NL = "Auto laadt mogelijk nog"
T_NO_PRICES = "No prices"
T_NO_PRICES_NL = "Prijzen ontbreken"
@@ -204,6 +206,7 @@ ID_MAINT_FAILED = "goodwe_maint_failed_{slug}"
ID_NO_PRICES = "goodwe_no_prices"
ID_CHARGER_UNREACH = "goodwe_charger_unreachable"
ID_CAR_OVER = "goodwe_car_over"
ID_CAR_RELEASE = "goodwe_car_release"
# PRICE-01: an earlier build raised a card with this id. Nothing raises it now;
# the add-on only dismisses it at start.
OLD_FIXED_CARD_ID = "goodwe_fixed_tariff_unused"
@@ -518,6 +521,44 @@ def row_car_over() -> str:
"piekgrens.")
def _solar_over(a_text):
# D1's words, in the one sentence STYLE.md allows a grey note and row; the
# card's Why has them as two (`car.why.solar_over`).
return (f"Solar charges the car at {a_text} A, which sets the peak.",
f"Zon laadt de auto met {a_text} A, wat de piek bepaalt.")
def car_over_solar(a_text) -> Notice:
"""EV-20 (D1): in Solar the car's charge takes the 15-minute period over
the peak limit and the batteries cannot hold it. Grey, once per charging
session, as Manual's; `a_text` is Solar's current at that moment."""
en, nl = _solar_over(a_text)
return Notice(ID_CAR_OVER, INFO, T_CAR_OVER, en,
body_nl=f"{T_CAR_OVER_NL}. {nl}")
def row_car_over_solar(a_text) -> str:
"""EV-20 (D1): the grey row while Solar's charge is over the peak limit."""
return Bi(*_solar_over(a_text))
def car_release_failed() -> Notice:
"""EV-20 (D3): at shutdown in Solar the charger did not take 0 A, and the
inverters were released on time anyway. Taken down when the next start's
0 A is taken."""
en = ("The add-on stopped before the charger took 0 A, so check the "
"charger.")
nl = ("De add-on stopte voor de laadpaal 0 A overnam, dus controleer de "
"laadpaal.")
return Notice(ID_CAR_RELEASE, WARNING, T_CAR_RELEASE, en,
body_nl=f"{T_CAR_RELEASE_NL}. {nl}")
def car_release_gone() -> Dismiss:
"""EV-20 (D3): takes the 'Car may still be charging' notice down."""
return Dismiss(ID_CAR_RELEASE)
def row_charger_other() -> str:
"""EV-04: the grey row, in Manual, while something else sets the current."""
return Bi("Something else changes the charger, so the add-on writes "
@@ -526,6 +567,15 @@ def row_charger_other() -> str:
"tot u iets wijzigt.")
def row_charger_other_solar() -> str:
"""EV-20: the amber row, in Solar, while something else sets the current:
Solar writes nothing until you press Solar or the read-back matches."""
return Bi("Something else changes the charger, so Solar writes nothing "
"until you press it.",
"Iets anders wijzigt de laadpaal, dus Zon schrijft niets tot u "
"erop drukt.")
def row_charger_stuck() -> str:
"""EV-04: the amber row when the charger's reading does not move."""
return Bi("The charger reading may be stuck, so check the charger.",
@@ -1484,6 +1534,7 @@ HINTS = {
"car_mode": "Car mode set",
"car_current": "Car current set",
"car_phases": "Car phases set",
"car_sun_first": "Where spare sun goes first set",
"settings_saved": "Settings saved, they apply after a restart",
"restart_requested": "Restart requested from the settings page",
"setup_only": "In setup, nothing is sent to any inverter",
@@ -1780,6 +1831,8 @@ def status_samples() -> list:
("row_charger_writer", GREEN, row_charger_writer()),
("row_car_over", GREEN, row_car_over()),
("row_charger_other", GREEN, row_charger_other()),
("row_charger_other_solar", AMBER, row_charger_other_solar()),
("row_car_over_solar", GREEN, row_car_over_solar("8")),
("row_charger_error", GREEN, row_charger_error("Socket error")),
("row_charger_stuck", AMBER, row_charger_stuck()),
("row_charger_refused", AMBER, row_charger_refused()),
@@ -1822,6 +1875,8 @@ def samples() -> list:
no_prices(),
charger_unreachable("09:12"),
car_over("16"),
car_over_solar("8"),
car_release_failed(),
]
@@ -1890,6 +1945,9 @@ LABELS = {
"ev_max_a": "Charger limit",
"ev_batt_cover": "Batteries help with the peak",
"ev_mode_start": "Mode after a restart",
"ev_margin_w": "Sun kept back",
"ev_pause_min": "Pause after",
"ev_start_min": "Start after",
"ev_phases": "Phases",
}
@@ -1976,6 +2034,9 @@ LABELS_NL = {
"ev_max_a": "Laadpaalgrens",
"ev_batt_cover": "Batterijen helpen met de piek",
"ev_mode_start": "Modus na een herstart",
"ev_margin_w": "Zon achtergehouden",
"ev_pause_min": "Pauzeren na",
"ev_start_min": "Starten na",
"ev_phases": "Fasen",
}
# The inverter list shows two of them under a shorter name.
+23 -7
View File
@@ -144,6 +144,8 @@ OPTIONAL_SENSORS = [
("car_power", "goodwe_car_power", "Car power", "W", "power", "measurement", "mdi:car-electric"),
("car_state", "goodwe_car_state", "Car state", None, None, None, "mdi:ev-station"),
("car_today_kwh", "goodwe_car_today_kwh", "Car energy today", "kWh", "energy", "total_increasing", "mdi:ev-station"),
# EV-20: what of today's charge came from the sun (Solar mode only).
("car_today_solar_kwh", "goodwe_car_today_solar_kwh", "Car solar energy today", "kWh", "energy", "total_increasing", "mdi:solar-power"),
]
# ⚠️ HA's OWN "this sensor has no value" PAYLOAD, and the one place this add-on
@@ -200,7 +202,8 @@ def optional_keys(opts: dict) -> tuple:
from . import chargers as _ch # EV-03: same reason
out = ("pv",) if _pv.entities(opts) else ()
if _ch.census_entity(opts):
out += ("car_power", "car_state", "car_today_kwh")
out += ("car_power", "car_state", "car_today_kwh",
"car_today_solar_kwh")
return out
@@ -524,25 +527,32 @@ def mode_payloads(units, modes) -> list:
# --- EV-04: the car's mode, current and phases, as HA entities ----------------
# Announced only with a charger switched on, after every other row. A command
# goes through Controller.handle_action(); a retained one is dropped.
CAR_MODE_LABELS = {"off": "Off", "manual": "Manual"} # English, pinned
CAR_MODE_LABELS = {"off": "Off", "manual": "Manual", # English, pinned
"solar": "Solar"} # EV-20
# EV-20: where spare sun goes first; mirrors carmode.FIRST_LABELS (this module
# imports nothing from the package; test_ev20.py checks the two agree).
CAR_FIRST_LABELS = {"batteries": "Batteries", "car": "Car"}
CAR_MODES = tuple(CAR_MODE_LABELS)
CAR_CONFIGS_KEY = "mqtt_car_configs"
CAR_MIN_A = 6
_CAR_CMD_RE = re.compile(rf"{BASE}/car/(mode|current|phases)/set")
_CAR_CMD_RE = re.compile(rf"{BASE}/car/(mode|current|phases|sun_first)/set")
_CAR_CONFIG_RE = re.compile(
rf"homeassistant/(select|number)/{BASE}_car_(mode|current|phases)/config")
rf"homeassistant/(select|number)/{BASE}_car_(mode|current|phases|sun_first)"
rf"/config")
# (key, component, name, icon)
CAR_ENTITIES = [
("mode", "select", "Car mode", "mdi:car-electric"),
("current", "number", "Car current", "mdi:current-ac"),
("phases", "select", "Car phases", "mdi:sine-wave"),
("sun_first", "select", "Car spare sun first", "mdi:solar-power"), # EV-20
]
def car_payloads(car) -> list:
"""The `(topic, payload)` for `select.goodwe_car_mode`,
`number.goodwe_car_current` and `select.goodwe_car_phases`. `car` is
`(max_a, phases)`; empty when it is None."""
`number.goodwe_car_current`, `select.goodwe_car_phases` and (EV-20)
`select.goodwe_car_sun_first`. `car` is `(max_a, phases)`; empty when it
is None."""
if not car:
return []
max_a, phases = car
@@ -560,6 +570,8 @@ def car_payloads(car) -> list:
cfg["options"] = list(CAR_MODE_LABELS.values())
elif key == "phases":
cfg["options"] = [str(n) for n in phases]
elif key == "sun_first":
cfg["options"] = list(CAR_FIRST_LABELS.values())
else:
cfg.update({"min": CAR_MIN_A, "max": int(max_a), "step": 1,
"unit_of_measurement": "A", "device_class": "current",
@@ -584,7 +596,8 @@ def car_configs(car, stored) -> tuple:
def parse_car_command(topic, payload, retained):
"""`(action, value, reject)` for one message on a car command topic.
`action` is `car_mode`, `car_current` or `car_phases`. A value that is
`action` is `car_mode`, `car_current`, `car_phases` or (EV-20)
`car_sun_first`. A value that is
none of the entity's own is None (the action then refuses it)."""
m = _CAR_CMD_RE.fullmatch(topic) if isinstance(topic, str) else None
if m is None:
@@ -607,6 +620,9 @@ def parse_car_command(topic, payload, retained):
None)
elif key == "phases":
value = {"1": 1, "3": 3}.get(text)
elif key == "sun_first":
value = next((k for k, v in CAR_FIRST_LABELS.items() if v == text),
None)
else:
try:
f = float(text)
+10 -2
View File
@@ -160,8 +160,9 @@
$("#car-why").textContent = c.why;
renderCarControls(c);
}
// EV-04: Off and Manual. The mode and the phases send at once; the current
// sends after two seconds of rest. A slider being dragged is left alone.
// EV-04: Off and Manual; EV-20: Solar and where its spare sun goes first.
// The mode, the phases and the choice send at once; the current sends after
// two seconds of rest. A slider being dragged is left alone.
let carTouch = 0, carTimer = null, carBusy = false;
async function carAct(what, value) {
if (carBusy) return;
@@ -182,6 +183,13 @@
type: "button", role: "radio", "aria-checked": String(c.mode === m),
onclick: () => carAct("car_mode", m) }, t("car.mode_" + m))));
$("#car-help").textContent = t("car.help_" + c.mode + ".description") || "";
const sol = c.mode === "solar" && !!c.first;
$("#car-solar").hidden = !sol;
if (sol) {
$("#car-first").replaceChildren(...c.first.choices.map((f) => h("button", {
type: "button", role: "radio", "aria-checked": String(c.first.value === f),
onclick: () => carAct("car_sun_first", f) }, t("car.first_" + f))));
}
const on = c.mode === "manual" && !!c.current;
$("#car-manual").hidden = !on;
if (!on) return;
+5
View File
@@ -52,6 +52,11 @@
<div class="small car-lab" data-t="car.phases"></div>
<div class="seg" role="radiogroup" id="car-phases" data-t-label="car.phases"></div>
</div>
<div id="car-solar" hidden>
<div class="small car-lab" data-t="car.first"></div>
<div class="seg" role="radiogroup" id="car-first" data-t-label="car.first"></div>
<p class="tiny muted" style="margin:6px 0 0" data-t="car.first_help.description"></p>
</div>
<div class="car-why small"><span class="muted" data-t="car.why"></span><span id="car-why"></span></div>
</div>
+20 -4
View File
@@ -91,7 +91,7 @@
"loading": "Loading the forecast."
},
"peak": {"name": "Peak limit", "this_month": "This month's peak", "limit": "Limit", "none": "None recorded yet", "unreadable": "Cannot be read now"},
"car": {"name": "Car", "mode": "Mode", "mode_off": "Off", "mode_manual": "Manual", "help_off": {"description": "The add-on leaves the charger alone."}, "help_manual": {"description": "Charges at the current you set, whatever the sun or the peak limit do."}, "current": "Current", "phases": "Phases", "phases_1": "1 phase", "phases_3": "3 phases", "why": "Why"},
"car": {"name": "Car", "mode": "Mode", "mode_off": "Off", "mode_manual": "Manual", "help_off": {"description": "The add-on leaves the charger alone."}, "help_manual": {"description": "Charges at the current you set, whatever the sun or the peak limit do."}, "current": "Current", "phases": "Phases", "phases_1": "1 phase", "phases_3": "3 phases", "why": "Why", "mode_solar": "Solar", "help_solar": {"description": "Charges only from spare sun and pauses when there is too little."}, "first": "Spare sun goes first to", "first_batteries": "Batteries", "first_car": "Car", "first_help": {"description": "Batteries: the car gets the sun the batteries cannot take."}},
"attention": {"name": "Needs attention", "nothing": "Nothing to look at", "to_look": "to look at", "details": "Details", "alarm": "Alarm", "warning": "Warning", "info": "Info"},
"control": {"name": "Control", "stop": "Stop control", "start": "Start control", "maint_start": "Start a battery cycle now", "maint_abort": "Stop the battery cycle", "docs": "Add-on documentation", "more": "More actions"},
"details": {"name": "Details for installers", "rows": "Status rows", "checks": "Checks", "event": "Last event"},
@@ -302,11 +302,12 @@
"warning": "See Needs attention below."
},
"car": {
"state": {"charging": "Charging", "waiting": "Connected, waiting", "none": "No car connected", "full": "Car is full", "unreach": "Charger not reachable", "setup": "Charger not set up", "fault": "Charger fault", "wait": "No reading yet"},
"big": {"waiting": "Connected, not charging.", "none": "Nothing to charge.", "full": "The car is full.", "seen": "Last seen at {t}.", "no_reading": "No reading.", "setup": "Not set up.", "fault": "The charger reports a fault.", "wait": "No reading yet."},
"state": {"charging": "Charging", "waiting": "Connected, waiting", "none": "No car connected", "full": "Car is full", "unreach": "Charger not reachable", "setup": "Charger not set up", "fault": "Charger fault", "wait": "No reading yet", "paused": "Waiting for sun"},
"big": {"waiting": "Connected, not charging.", "none": "Nothing to charge.", "full": "The car is full.", "seen": "Last seen at {t}.", "no_reading": "No reading.", "setup": "Not set up.", "fault": "The charger reports a fault.", "wait": "No reading yet.", "paused": "Waiting for spare sun."},
"phase_one": "1 phase",
"phase_many": "{n} phases",
"today": "{kwh} charged today.",
"today_sun": "{kwh} charged today, {sun} from the sun.",
"why": {
"charging": "The charger is charging the car. The add-on leaves it alone.",
"waiting": "The car is connected and not charging. The add-on leaves the charger alone.",
@@ -332,7 +333,22 @@
"manual_shadow_over": "Shadow mode: the add-on would set {a} A, {phases}. This charge would set the peak.",
"manual_phases": "You set {a} A, {phases}. The charger stays on {real}.",
"manual_other": "Something else set the charger. The add-on leaves it until you change something.",
"manual_blocked": "The phases change once per 10 minutes at most. This waits."
"manual_blocked": "The phases change once per 10 minutes at most. This waits.",
"solar_batt": "Batteries first. The car gets the {kw} of sun they cannot take.",
"solar_car": "Car first: the car takes {kw} of spare sun. The batteries get the rest.",
"solar_paused": "Too little spare sun for 6 A. The car starts after {s} minutes of enough sun.",
"solar_hold": "Too little spare sun, so the car holds 6 A. It pauses after {s} minutes.",
"solar_start": "There is enough spare sun now. The car starts after {s} minutes of it.",
"solar_unknown": "The spare sun cannot be measured now. The car pauses if this lasts.",
"solar_would": "Shadow mode: the add-on would keep the car paused.",
"solar_stopped": "Control is stopped, so the add-on set the car to 0 A.",
"solar_error": "The charger reports an error. The car is set to 0 A.",
"solar_stuck": "The charger reading may be stuck. The car is set to 0 A.",
"solar_other": "Something else changes the charger. Press Solar to give it back.",
"solar_zeroing": "The charger has not taken 0 A yet. The add-on tries again.",
"solar_zero_failed": "The charger did not take 0 A. Check it at the charger.",
"solar_refused": "The charger did not take the current. Press Solar to try again.",
"solar_over": "Solar charges the car at {a} A. This sets the peak."
}
},
"peak": {
+20 -4
View File
@@ -88,7 +88,7 @@
"loading": "De prognose wordt geladen."
},
"peak": {"name": "Piekgrens", "this_month": "Piek van deze maand", "limit": "Grens", "none": "Nog niets gemeten", "unreadable": "Nu niet leesbaar"},
"car": {"name": "Auto", "mode": "Modus", "mode_off": "Uit", "mode_manual": "Handmatig", "help_off": {"description": "De add-on laat de laadpaal met rust."}, "help_manual": {"description": "Laadt met de stroom die u instelt, wat de zon of de piekgrens ook doen."}, "current": "Stroom", "phases": "Fasen", "phases_1": "1 fase", "phases_3": "3 fasen", "why": "Waarom"},
"car": {"name": "Auto", "mode": "Modus", "mode_off": "Uit", "mode_manual": "Handmatig", "help_off": {"description": "De add-on laat de laadpaal met rust."}, "help_manual": {"description": "Laadt met de stroom die u instelt, wat de zon of de piekgrens ook doen."}, "current": "Stroom", "phases": "Fasen", "phases_1": "1 fase", "phases_3": "3 fasen", "why": "Waarom", "mode_solar": "Zon", "help_solar": {"description": "Laadt alleen met zonne-overschot en pauzeert als er te weinig is."}, "first": "Zonne-overschot gaat eerst naar", "first_batteries": "Batterijen", "first_car": "Auto", "first_help": {"description": "Batterijen: de auto krijgt de zon die de batterijen niet kunnen opnemen."}},
"attention": {"name": "Vraagt aandacht", "nothing": "Niets om na te kijken", "to_look": "na te kijken", "details": "Details", "alarm": "Alarm", "warning": "Waarschuwing", "info": "Info"},
"control": {"name": "Regeling", "stop": "Regeling stoppen", "start": "Regeling starten", "maint_start": "Nu een batterijcyclus starten", "maint_abort": "Batterijcyclus stoppen", "docs": "Documentatie van de add-on", "more": "Meer acties"},
"details": {"name": "Details voor installateurs", "rows": "Statusregels", "checks": "Controles", "event": "Laatste gebeurtenis"},
@@ -256,11 +256,12 @@
"pill": {"running": "Actief", "shadow": "Schaduwmodus", "stopped": "Gestopt", "alarm": "Heeft u nu nodig", "waiting": "Wacht op Home Assistant", "warning": "Actief, met een waarschuwing"},
"banner_sub": {"running": "De batterijen volgen het plan hieronder.", "shadow": "De plannen hieronder tonen wat de add-on zou doen.", "stopped": "Start de regeling hieronder als u klaar bent.", "alarm": "Zie Vraagt aandacht hieronder voor wat u moet doen.", "waiting": "De regeling gaat vanzelf verder zodra Home Assistant antwoordt.", "warning": "Zie Vraagt aandacht hieronder."},
"car": {
"state": {"charging": "Laadt", "waiting": "Aangesloten, wacht", "none": "Geen auto aangesloten", "full": "Auto is vol", "unreach": "Laadpaal onbereikbaar", "setup": "Laadpaal niet ingesteld", "fault": "Laadpaalstoring", "wait": "Nog geen meting"},
"big": {"waiting": "Aangesloten, laadt niet.", "none": "Niets te laden.", "full": "De auto is vol.", "seen": "Laatst gezien om {t}.", "no_reading": "Geen meting.", "setup": "Niet ingesteld.", "fault": "De laadpaal meldt een storing.", "wait": "Nog geen meting."},
"state": {"charging": "Laadt", "waiting": "Aangesloten, wacht", "none": "Geen auto aangesloten", "full": "Auto is vol", "unreach": "Laadpaal onbereikbaar", "setup": "Laadpaal niet ingesteld", "fault": "Laadpaalstoring", "wait": "Nog geen meting", "paused": "Wacht op zon"},
"big": {"waiting": "Aangesloten, laadt niet.", "none": "Niets te laden.", "full": "De auto is vol.", "seen": "Laatst gezien om {t}.", "no_reading": "Geen meting.", "setup": "Niet ingesteld.", "fault": "De laadpaal meldt een storing.", "wait": "Nog geen meting.", "paused": "Wacht op zonne-overschot."},
"phase_one": "1 fase",
"phase_many": "{n} fasen",
"today": "Vandaag {kwh} geladen.",
"today_sun": "Vandaag {kwh} geladen, {sun} van de zon.",
"why": {
"charging": "De laadpaal laadt de auto. De add-on laat haar met rust.",
"waiting": "De auto is aangesloten en laadt niet. De add-on laat de laadpaal met rust.",
@@ -286,7 +287,22 @@
"manual_shadow_over": "Schaduwmodus: de add-on zou {a} A instellen, {phases}. Deze lading zou de piek bepalen.",
"manual_phases": "U stelde {a} A in, {phases}. De laadpaal blijft op {real}.",
"manual_other": "Iets anders heeft de laadpaal ingesteld. De add-on laat dit zo tot u iets wijzigt.",
"manual_blocked": "De fasen wisselen hooguit eens per 10 minuten. Dit wacht."
"manual_blocked": "De fasen wisselen hooguit eens per 10 minuten. Dit wacht.",
"solar_batt": "Eerst de batterijen. De auto krijgt de {kw} zon die ze niet opnemen.",
"solar_car": "Eerst de auto: die neemt {kw} zonne-overschot. De batterijen krijgen de rest.",
"solar_paused": "Te weinig zonne-overschot voor 6 A. De auto start na {s} minuten genoeg zon.",
"solar_hold": "Te weinig zonne-overschot, dus de auto houdt 6 A. Ze pauzeert na {s} minuten.",
"solar_start": "Er is nu genoeg zonne-overschot. De auto start na {s} minuten daarvan.",
"solar_unknown": "Het zonne-overschot is nu niet te meten. De auto pauzeert als dit duurt.",
"solar_would": "Schaduwmodus: de add-on zou de auto gepauzeerd houden.",
"solar_stopped": "De regeling is gestopt, dus de auto staat op 0 A.",
"solar_error": "De laadpaal meldt een fout. De auto staat op 0 A.",
"solar_stuck": "De meting van de laadpaal staat mogelijk vast. De auto staat op 0 A.",
"solar_other": "Iets anders wijzigt de laadpaal. Druk op Zon om ze terug te geven.",
"solar_zeroing": "De laadpaal nam 0 A nog niet over. De add-on probeert opnieuw.",
"solar_zero_failed": "De laadpaal nam 0 A niet over. Controleer ze aan de laadpaal.",
"solar_refused": "De laadpaal nam de stroom niet over. Druk op Zon om opnieuw te proberen.",
"solar_over": "Zon laadt de auto met {a} A. Dit bepaalt de piek."
}
},
"peak": {
+3
View File
@@ -234,6 +234,9 @@ GROUPS = (
Field("ev_phases", SEGMENTED, simple=True, show=_CAR),
Field("ev_batt_cover", TOGGLE, simple=True, show=_CAR),
Field("ev_mode_start", SEGMENTED, simple=True, show=_CAR),
Field("ev_margin_w", SLIDER, "W", step=10, show=_CAR),
Field("ev_start_min", SLIDER, "min", show=_CAR),
Field("ev_pause_min", SLIDER, "min", show=_CAR),
)),
)),
Group("maintenance", (
+13
View File
@@ -677,6 +677,19 @@ def _charger_problems(opts: dict, writers: dict) -> list[str]:
out.append(f"{S('ev_charger')} is {messages.shown(raw)}. Choose "
f"{', '.join(chargers.SELECTABLE)}.")
return out
# EV-20: Solar's sun kept back and its two dwells, each in its range (as
# config.yaml's schema holds them, with or without a charger).
for key, (lo, hi) in chargers.SOLAR_RANGES.items():
raw = opts.get(key, chargers.EV_OPTION_DEFAULTS[key])
try:
v = float(raw)
ok = not isinstance(raw, bool) and v == v and v == int(v) \
and lo <= v <= hi
except (TypeError, ValueError, OverflowError):
ok = False
if not ok:
out.append(f"{S(key)} is {messages.shown(raw)}. Set it from {lo} "
f"to {hi}.")
if chargers.mode_of(opts) == chargers.OFF:
return out
ph = opts.get("ev_phases", chargers.EV_OPTION_DEFAULTS["ev_phases"])
+1 -1
View File
@@ -62,7 +62,7 @@ _LOG = logging.getLogger("goodwe.web")
# OPT-11: the per-battery actions, which name a battery and a value.
PACK_ACTIONS = ("pack_use", "pack_mode", "pack_sell")
CAR_ACTIONS = ("car_mode", "car_current", "car_phases")
CAR_ACTIONS = ("car_mode", "car_current", "car_phases", "car_sun_first")
# MAINT-11: start or stop one battery's maintenance cycle (the unit is optional).
MAINT_ACTIONS = ("maint_start", "maint_abort")