EV-21: Solar cuts the car first for the quarter peak
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Failing after 1h10m59s

In Solar, when the 15-minute period heads over the aim and the batteries
would have to give more, the car is lowered first: floor((car - excess) /
(230 x phases)) A, 0 under 6 A. At once without real headroom (saturated,
floor-limited, excess beyond what the batteries can add, no battery figure,
cover off, last 120 s), else after at most 15 s. One cut per episode from
its start, deeper only on a growing excess; restart with the start power
under the aim for the start time; none after a 2nd cut in the period.

Grading (formal C2): a Solar car Solar cannot cut is graded, banked and
left in the guard as in Off. A Solar car is never banked. Grey note and Why
"Solar lowered the car for the peak." Manual and Off unchanged.

Tests: test_ev21.py, test_ev21_paths.py, test_ev21_same.py; T49 in
tools/ev20_day.py; T50 in test_ev20_fuzz.py; test_ev20_guard section 8
moved from "as Manual" to "as Off" where Solar cannot cut (T51).

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
ems-agent
2026-11-25 17:01:07 +01:00
co-authored by Claude
parent a8e4ceb859
commit 7bc8988be0
17 changed files with 2175 additions and 85 deletions
+311 -12
View File
@@ -16,7 +16,7 @@ import logging
from datetime import timezone
from . import carmode, chargers, messages, packshare, peakguard
from .tariff import QUARTER_S
from .tariff import QUARTER_S, next_quarter
_LOG = logging.getLogger("goodwe")
@@ -48,6 +48,18 @@ CAR_EXIT_KEY = "car_exit_0a_pending"
# 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
# EV-21: Solar's car is cut first for the quarter peak. The cut waits at most
# CUT_WAIT_S, and only while the batteries can still raise their output; with
# CUT_NEAR_END_S or less of the period left it comes at once (waiting 15 s
# with R s left raises what must come off by R / (R - 15), at most 8/7 at
# 120 s). After CUT_MAX_Q cuts in one period, no restart until the next.
# DECISIONS/EV-21-car-cut-first.md.
CUT_WAIT_S = 15.0
CUT_NEAR_END_S = 120.0
CUT_MAX_Q = 2
# A lowering Solar sent counts as its own this long before its read-back:
# one cycle beside the write (the alarm still comes within 2 s of Off's).
CUT_SENT_S = 2.0
class CarMixin:
@@ -118,6 +130,245 @@ class CarMixin:
self._peak_proj_real = None
saved = data.get(CAR_PEAK_KEY)
self.car_peak_q = dict(saved) if isinstance(saved, dict) else {}
self._cut = self._cut_fresh(None) # EV-21: in memory only
self._car_cut_notified = None # EV-21: the session noted
self._car_can = False # EV-21: can-cut as graded
# ------------------------------------------------- EV-21: the peak cut
@staticmethod
def _cut_fresh(key) -> dict:
"""EV-21: no cut state, for period `key`. `since`: the episode began
(the cut first due); `car0`: the car's W then; `ex`: the largest
excess seen in it; `cap`: the cut's current, None while none stands;
`cuts`: cuts in this period; `under`: the projection with the start
power has been under the aim since."""
return {"key": key, "since": None, "car0": None, "ex": 0.0,
"cap": None, "wait": None, "cuts": 0, "under": None,
"base": None, "at": None}
def _car_cut_ramp_w(self, mono):
"""EV-21: for grading only, the car's real power while it comes down
after a cut the charger took: fresh, not stuck, never above the
current before the cut, at most `CORR_WINDOW_S` after the cut. (Its
trusted figure is capped by the new, lower read-back meanwhile.) None
otherwise: a car that does not follow is graded as in Off after
that window (T45)."""
st = self._cut
if st["cap"] is None or st["at"] is None or st["base"] is None \
or not 0.0 <= mono - st["at"] <= chargers.CORR_WINDOW_S \
or not self.car_solar_can_cut() or self.car.stuck(mono):
return None
raw = self.car.car_w(mono)
if raw is None:
return None
n = self._car_cut_n()
return min(float(raw), float(st["base"]) * chargers.CEILING_V * n)
def car_solar_can_cut(self) -> bool:
"""EV-21 (Q5): can Solar really cut the car now? Solar writes (no
shadow, Stop, safety stop or shutdown), the charger is read fresh with
no fault and no stuck reading, no other writer (no hold, no
difference) and the read-back shows the current Solar sent. A cut
written but not read back is not a cut."""
if not self.car_solar_mode() or not self.car_writing():
return False
w = self.car_solar
mono = self.car_now()
r = self.car.reading
if r is None or not r.available or r.error \
or r.state in ("E", "F") or not self.car.fresh(mono) \
or self.car.stuck(mono):
return False
if w.hold or w.mismatch_since is not None or w.fault is not None \
or w.gave_up or w.sent_a is None:
return False
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
if cur is None:
return False
if abs(cur - w.sent_a) <= carmode.TOL_A:
return True
# A lowering of Solar's own on its way: the cycle beside the write
# reads the charger before it answers. For CUT_SENT_S at most, and
# never once the charger refused it.
at = getattr(w, "sent_at", None)
return bool(w.sent_a < cur - carmode.TOL_A and at is not None
and 0.0 <= mono - at <= CUT_SENT_S
and (w.fail_at is None or w.fail_at < at))
def car_cut_standing(self) -> bool:
"""EV-21: a peak cut lowered the car and the charger shows it."""
st = getattr(self, "_cut", None)
w = getattr(self, "car_solar", None)
if not st or st["cap"] is None or st["base"] is None or w is None \
or st["cap"] >= float(st["base"]) - carmode.TOL_A:
return False
return bool(self.car_solar_can_cut() and w.sent_a is not None
and w.sent_a <= st["cap"] + carmode.TOL_A)
async def check_car_cut(self) -> None:
"""EV-21 (OQ5): one grey note per charging session once a cut is
taken: "Solar lowered the car for the peak.\""""
if not self.car_cut_standing() \
or self._car_cut_notified == self._car_session:
return
self._car_cut_notified = self._car_session
_LOG.info("Solar lowered the car for the peak: CAR_CUT.")
await self.hass.call("persistent_notification", "create",
messages.car_cut().data())
def _car_cut_meter_fresh(self) -> bool:
"""EV-21 (N9): the meter's own age allows sizing a cut: within
`stale_input_s`, or on `ha_signed` (whose age counts from the last
change) within `meter_max_age_s`."""
if not self.p1_enabled:
return False
age = self.p1.age_s()
if age is None:
return False
if str(self.o.get("meter_source") or "") == "ha_signed":
bound = float(self.o.get("meter_max_age_s", 30) or 30)
else:
bound = float(self.o.get("stale_input_s", 15))
return age <= bound
def _car_cut_headroom(self, guard):
"""EV-21 (Q2-Q4): the watts the batteries can still ADD, or None when
a battery figure is missing (then they count as adding nothing). A
battery adds nothing at or under its cut-out level or its peak
reserve (the guard's `held`), while it refuses to give, under a
safety stop, or switched off in battery modes; the guard's `able_w`
caps the rest. 0 while the guard is saturated or floor-limited."""
if self.site_batt_w is None \
or any(inv.batt is None for inv in self.inverters):
return None
if guard is None or guard.saturated or guard.floor_limited:
return 0.0
n = len(self.inverters)
if self.circ_wd.tripped or (n > 1 and self.site_sign_wd.tripped):
return 0.0
held = set(getattr(guard, "held", ()) or ())
top = given = stop = 0.0
for inv in self.inverters:
refused = inv.refused if n > 1 else self.batt_refused
if inv.sign_wd.tripped \
or (self.modes_on and not self.pack_mode(inv).use):
continue
if (refused or 0) > 0 or inv.name in held or inv.soc is None \
or inv.bms_soc_floor is None \
or float(inv.soc) <= float(inv.bms_soc_floor):
# Gives nothing more; a charge it takes can still stop.
stop += max(0.0, -float(inv.batt))
continue
top += float(inv.rating_w())
given += float(inv.batt)
if guard.able_w is not None:
top = min(top, float(guard.able_w))
return max(0.0, top - given) + stop
def _car_cut_n(self):
"""The phases the car draws on: 1 for a one-phase car."""
r = self.car.reading
if self.car_solar.single:
return 1
n = getattr(r, "phases_allowed", None)
return n if n in (1, 3) else self.car_solar.plan.n
def _car_cut_tick(self, real_proj, guard, target_w, mono) -> None:
"""EV-21: decide the peak cut for the writer step that follows this
cycle (`car_kick`), from the projection WITH the car. Due: Solar, a
fresh projection heading over the aim (`excess_w` > 0) and a car that
draws. Taken at once without real headroom (saturated, floor-limited,
the excess beyond what the batteries can add, no battery figure, the
cover off, the period's last 120 s), else after CUT_WAIT_S. One cut
per episode, sized from its start: `car0` less the largest excess
so far, never re-subtracted from the lowered car. While it is due or
stands, the writer's plan goes no higher (the cap). It is lifted when
the projection with the start power has been under the aim for the
start rule's time (not after CUT_MAX_Q cuts in the period), and at
the period's end."""
w = self.car_solar
if not self.car_solar_mode():
self._cut = self._cut_fresh(None)
w.cut_a = None
return
key = None if real_proj is None else real_proj.block_start
st = self._cut
if key is not None and key != st["key"]:
st = self._cut = self._cut_fresh(key) # no state over the edge
blind = guard is not None and guard.blind is not None
if key is None or target_w is None or blind \
or not self._car_cut_meter_fresh():
# N9: nothing sized from a stale projection; what stands stays.
w.cut_a = st["cap"] if st["cap"] is not None else st["wait"]
return
ex = peakguard.excess_w(real_proj, target_w)
left = QUARTER_S - float(real_proj.elapsed_s)
r = self.car.reading
cur = None if r is None or not r.available else (
r.allowed_a if r.allowed_a is not None else r.setpoint_a)
car_w = self.car.car_w_trusted(mono)
drawing = (car_w is not None and car_w > 0.0) or (
car_w is None and r is not None and r.available
and r.charging is True)
running = w.plan.a > 0.0 or (cur is not None and cur > carmode.TOL_A)
# C12: Solar's own phase change holds the car at 0 A on its way to a
# current: a cut due then ends it at that 0 A (no closing current).
seq_on = w.seq is not None and w.plan.a > 0.0
# The batteries would have to give more than now (the guard's
# `wanted_w`, on the projection WITH the car): a charge that only
# has to slow down is the loop's, not a cut. Unknown: they add
# nothing (Q4).
batt = self.site_batt_w
wants = batt is None or float(batt) + ex > 0.0
due = ex > 0.0 and wants and running and (drawing or seq_on)
n = self._car_cut_n()
if st["cap"] is not None:
# A cut stands: deeper only if the excess grows (OQ7); the
# restart rule lifts it.
if due and ex > st["ex"]:
st["ex"] = ex
a = carmode.cut_amps(st["car0"], ex, n, st["base"])
if a is not None and a < st["cap"]:
st["cap"] = a
start_w = chargers.MIN_A * carmode.VOLTS * n # OQ4
now_w = 0.0 if car_w is None else float(car_w)
plus = float(real_proj.projected_w) \
+ max(0.0, start_w - now_w) * max(0.0, left) / QUARTER_S
if plus < float(target_w):
if st["under"] is None:
st["under"] = mono
else:
st["under"] = None
start_s = 60.0 * carmode.solar_option(self.o, "ev_start_min")
if st["under"] is not None and mono - st["under"] >= start_s \
and st["cuts"] < CUT_MAX_Q:
cuts = st["cuts"]
st = self._cut = self._cut_fresh(key)
st["cuts"] = cuts
w.cut_a = st["cap"]
return
if not due:
st["since"], st["wait"] = None, None # the batteries caught it
w.cut_a = None
return
if st["since"] is None:
st["since"], st["car0"], st["ex"] = mono, car_w, ex
st["base"] = w.plan.a if w.plan.a > 0.0 else cur
st["ex"] = max(st["ex"], ex)
room = self._car_cut_headroom(guard)
now_ = (room is None or room <= 0.0 or ex > room
or not self.car_cover or left <= CUT_NEAR_END_S)
if now_ or mono - st["since"] >= CUT_WAIT_S:
a = carmode.cut_amps(st["car0"], st["ex"], n, st["base"])
st["cap"] = 0.0 if a is None else a
st["cuts"] += 1
st["wait"], st["at"] = None, mono
w.cut_a = st["cap"]
return
# C4: due and waiting: no raise meanwhile.
st["wait"] = w.plan.a if st["wait"] is None \
else min(st["wait"], w.plan.a)
w.cut_a = st["wait"]
@property
def car_cover(self) -> bool:
@@ -276,13 +527,37 @@ class CarMixin:
if self.car_solar_mode() else None)
self._car_task = asyncio.ensure_future(self._car_run())
def _car_hold_kick(self) -> None:
def _car_hold_kick(self, now=None) -> 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."""
and a way out still writes its 0 A); Manual is left as it was.
EV-21 (Q4): the peak cut is still decided, on the meter's own
projection: without a battery figure the batteries add nothing."""
if now is not None and self.car_solar_mode():
self._car_cut_hold(now)
if self.car_solar_engaged():
self.car_kick()
def _car_cut_hold(self, now) -> None:
"""EV-21: the cut in a cycle that returns before the guard: the
meter's projection (no gap filling, which has its own state; a
blind one sizes nothing), no guard, so no headroom."""
if not self.p1_enabled:
self._car_cut_tick(None, None, None, self.car_now())
return
proj = self.peak.project(self.p1.averager, now, roll=self.modes_on)
hold_s = self.p1.averager.max_hold_s
if proj is not None and len(self.inverters) > 1:
proj = next_quarter(proj, hold_s)
if proj is not None and peakguard.blindness(
proj, hold_s, False) is not None:
proj = None
reading = self.peak.peak(now)
target = peakguard.quarter_target_w(
float(self.o.get("peak_cap_w", 3500)), self.peak_margin_w,
reading)
self._car_cut_tick(proj, None, target, self.car_now())
async def car_settle(self) -> None:
"""Wait for the writer step in flight (the checks use it)."""
t = self._car_task
@@ -613,12 +888,14 @@ class CarMixin:
# ------------------------------------------- the car and the peak guard
def car_alarm_w(self):
"""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."""
"""The car's power for the guard's alarm path: Manual, and Solar only
while it can cut the car (EV-21, Q5: otherwise as Off), 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
if self.car_solar_mode() and not self.car_solar_can_cut():
return None
return self.car.car_w_trusted(self.car_now())
def _car_own_pause(self, mono) -> bool:
@@ -698,11 +975,15 @@ class CarMixin:
last = q["mono"]
if key != q["key"]:
self._car_bank(q)
q["key"], q["ws"], q["ws_p"] = key, 0.0, 0.0
q["key"], q["ws"], q["ws_p"], q["ws_b"] = key, 0.0, 0.0, 0.0
if key is not None and last is not None:
dt = min(max(mono - last, 0.0), 5.0)
if w is not None:
q["ws"] += float(w) * dt
if not self.car_solar_mode():
# EV-21: a Solar car is cut first, so a period is never
# banked as its own (N4); one it cannot cut is as Off.
q["ws_b"] = q.get("ws_b", 0.0) + float(w) * dt
elif wg is not None:
q["ws_p"] = q.get("ws_p", 0.0) + float(wg) * dt
q["mono"] = mono
@@ -712,7 +993,7 @@ class CarMixin:
key = q["key"]
if key is None:
return
avg = q["ws"] / QUARTER_S
avg = q.get("ws_b", q["ws"]) / QUARTER_S
if avg < CAR_PEAK_MIN_W:
return
self.car_peak_q[key.astimezone(timezone.utc).isoformat()] = round(avg)
@@ -770,15 +1051,24 @@ 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_cut_tick(real_proj, guard, target_w, mono) # EV-21
self._car_sun_tick(mono) # EV-20: today's solar kWh
solar = self.car_solar_mode()
can = solar and self.car_solar_can_cut()
self._car_can = can # what grading saw (checks)
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
# that bounded time its fresh, not stuck figure stands in.
own = (w is None or float(w) <= 0.0) and self._car_own_pause(mono)
# that bounded time its fresh, not stuck figure stands in. EV-21: in
# Solar only while it can cut the car.
own = (w is None or float(w) <= 0.0) and (can or not solar) \
and self._car_own_pause(mono)
wg = w
if w is None and own:
wg = self.car.car_w_paused(mono)
ramp = self._car_cut_ramp_w(mono) if can else None
if ramp is not None and ramp > float(wg or 0.0):
wg, own = ramp, True # EV-21: the cut's own ramp-down
self._car_quarter(real_proj, w, mono, wg)
self._car_session_tick(mono)
# EV-18 (owner 2026-11-19): a figure the meter contradicted grades no
@@ -803,7 +1093,16 @@ class CarMixin:
if contra or idle or (w is not None and float(w) <= 0.0
and not own):
graded = False
if self.car_cover:
if solar:
# EV-21 (Q5, OQ5, OQ8): graded out only while Solar can cut
# the car, and then no car-over row: the cut works. Else as
# Off; the row and notice say the car sets the peak.
explains = graded and can
wd = None if can else self.car.car_w_trusted(mono)
if wd is not None:
ex = float(real_proj.projected_w) - float(target_w)
over = ex > 0.0 and self.car_avg_w(real_proj, wd) >= ex
elif self.car_cover:
explains = over = graded
elif w is not None:
ex = float(real_proj.projected_w) - float(target_w)