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
+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",