Compare commits

...
4 Commits
Author SHA1 Message Date
ems-agentandClaude 45df1ac549 EV-51 review: T45 sweeps N8 on own age for retries and phase-change closing currents; docs name the decision words and C23
checks / unit (pull_request) In progress
infra-pin / fresh (pull_request) Waiting to run
T45: race order, 5 s and 10 s cycles, silence onset swept 1 s at a time,
(a) a raise the charger ignores (re-sends) and (b) a 1 -> 3 phase change
(closing current): no non-zero current write at own age > 30 s. Red on
5bff894 and on the reviewer's R4 (nz_block from the snapshot, C23 on own
age), green on head. T26 also checks the DECISIONS entry names every
decision word and the C23 value rule.

DECISIONS and the car_sun_own / _car_step_debug docstrings: snapshot values
are used only while the step's own age says fresh (C23); the decision words
are listed. No code change.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-25 00:04:10 +01:00
ems-agentandClaude 6412d00783 EV-51 round 2: T44 checks the start after the meter returns; T24 SoC 100 no longer carries N5
checks / unit (pull_request) Successful in 37m42s
infra-pin / fresh (pull_request) Successful in 2s
T44 (C23) now also asserts that a start and a non-zero write come, either
before the silence passes 30 s (from fresh data) or after the meter is back
at a step with own age <= 30, between the first fresh step + ev_start_min
and that + 2 cycles, and that the car is still charging at the end. A fix
that blocks every start after a silence fails it.

T24: the SoC 100 run (no battery write in the silence) is checked for T24
only; N5 rides on the SoC 50 runs, which must have writes in the silence.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-24 22:05:33 +01:00
ems-agentandClaude a33eb8ef1c EV-51 round 1: C23 (no spare/target from data the own age calls old), N5 label, T44
checks / unit (pull_request) Successful in 38m23s
infra-pin / fresh (pull_request) Successful in 2s
car_sun_own now sets spare_w / target_w to None while the step's own meter age
says silent, so no plan start or raise comes from a snapshot value over
meter_max_age_s old; the start comes from a fresh reading after the meter
returns, with its dwell. T44 sweeps a start due just after the silence (red on
68856bc, green now). T24 is labelled N5 and also runs at SoC 50 so the
batteries' setpoints in the silence are compared.

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 19:52:36 +01:00
ems-agentandClaude 68856bc3a0 EV-51: Solar decides every meter-age rule on the writer step's own age; DEBUG line per step
checks / unit (pull_request) Successful in 41m26s
infra-pin / fresh (pull_request) Successful in 2s
The writer step took the meter age from the snapshot of the previous cycle
(silent / unknown_s / hold), so in production order the silent-meter pause
came one cycle late (C21) and a start or raise could still be written at an own
age of 31-39 s (C22, N8). The step now judges its own age: the pause timing and
held_pause, the non-zero write block (nz_block), and the late-readings hold with
its stale rule. Meter values stay from the snapshot; car.held / car.reading and
the arrival sources' spare-unknown check are unchanged.

Also: one DEBUG line per Solar writer step (time, meter age, decision, write);
tools/ev20_sun.drive takes cyc / phase / jitter / cset (default unchanged);
test_ev51.py (T1-T43, N1-N12); DECISIONS states the rule once.

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 17:26:03 +01:00
6 changed files with 1156 additions and 11 deletions
@@ -161,9 +161,26 @@ one small set of facts and derives every path from them:
This also ends the false PEAK_GUARD_FLOOR_LIMITED after one gap (EV-18 This also ends the false PEAK_GUARD_FLOOR_LIMITED after one gap (EV-18
T10(b) changed accordingly). T10(b) changed accordingly).
- **Silent meter on `ha_signed`:** Solar's unknown-sun pause is timed from the - **Silent meter on `ha_signed`:** Solar's unknown-sun pause is timed from the
meter's age: unknown since the age passed `meter_max_age_s`, so 0 A when the meter's age: unknown since the age passed `meter_max_age_s`, so 0 A on the
age reaches `meter_max_age_s` + `ev_pause_min` (330 s), checked every first car step whose own meter age (now minus the last reading, at that
control cycle (bound 330 s + one cycle). Arrival sources are unchanged. step) is >= `meter_max_age_s` + `ev_pause_min` (330 s), held steps included.
Arrival sources are unchanged.
- **EV-51: decided at the step's own meter age.** Every decision that rests on
the meter's AGE is taken at the writer step's own age, not at the age the
cycle saw one step earlier: the pause above, the write block while the meter
is silent (no non-zero current, C17), the held-read pause (C18) and the
late-readings hold with its stale rule (a spare read while the hold was on
is not used once the step's own late time reaches `stale_input_s`). The
meter's VALUES (spare, target) stay the cycle's, one cycle of sensor latency
being normal, but only while the step's own age says the meter is fresh:
once it is past `meter_max_age_s` the spare is unknown, so nothing starts or
rises from it (C23). `car.held` and `car.reading` are unchanged. Arrival
sources keep the cycle's age for their "spare unknown" check. At log level
debug each Solar step logs one line: time, the meter age at the step, the
decision and the write. The decision is one word: `steady`, `start`,
`raise`, `lower`, `pause`, `hold` (the late-readings hold), `wait-unknown`
(the spare is unknown and the pause timer counts) or `wait-held` (a held
charger read).
- **No non-zero write while the meter is silent (SPIKE-06 C17, N8 strict):** - **No non-zero write while the meter is silent (SPIKE-06 C17, N8 strict):**
while the meter's age is past `meter_max_age_s`, Solar sends no non-zero while the meter's age is past `meter_max_age_s`, Solar sends no non-zero
current: no retry, no raise, no phase change begun, and a phase change current: no retry, no raise, no phase change begun, and a phase change
+14 -4
View File
@@ -498,8 +498,13 @@ class SunInputs:
def __init__(self, target_w=None, hold=False, auto=True, start_s=120.0, 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, pause_s=300.0, spare_w=None, room_w=0.0, margin_w=100.0,
first=DEFAULT_FIRST, unknown_s=0.0, silent=False): first=DEFAULT_FIRST, unknown_s=0.0, silent=False,
meter_back=False, age_s=None):
self.target_w, self.hold, self.auto = target_w, hold, auto self.target_w, self.hold, self.auto = target_w, hold, auto
# EV-51: the meter's own age at the writer step (None: no reading), and
# `meter_back`: the cycle's snapshot said "meter too old" but the step's
# own age says a new reading came, so no unknown timer is carried over.
self.meter_back, self.age_s = meter_back, age_s
# EV-20 rig round 2: how long the sun has already been unknown when # EV-20 rig round 2: how long the sun has already been unknown when
# the cause is the meter's own age (`ha_signed`): the pause is timed # the cause is the meter's own age (`ha_signed`): the pause is timed
# from that age, not from the cycle that noticed it. # from that age, not from the cycle that noticed it.
@@ -570,11 +575,15 @@ class SolarPlan:
self.switch, self._before = False, None self.switch, self._before = False, None
def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s, def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s,
hold=False, gap_ok=True, unknown_s=0.0): hold=False, gap_ok=True, unknown_s=0.0, meter_back=False):
"""`n_now`: the phases the car draws on now (1 for a one-phase car); """`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 `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 allowed now (EV-04's one per `PHASE_GAP_S`); `hold`: readings late
under the stale bound, everything stands.""" under the stale bound, everything stands. `meter_back` (EV-51): the
meter's own age is fresh again at this step: the unknown timer that
counted its silence starts over."""
if meter_back:
self.unknown_since = None
if hold: if hold:
# Readings late under the stale bound: nothing changes, but a # Readings late under the stale bound: nothing changes, but a
# hold or an unknown spare that has run its time still pauses # hold or an unknown spare that has run its time still pauses
@@ -937,7 +946,8 @@ class SolarWriter(ManualWriter):
now, target_w=sun.target_w, hold=sun.hold, n_now=n_now, 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, 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, clamp=clamp, start_s=sun.start_s, pause_s=sun.pause_s,
gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0)) gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0),
meter_back=getattr(sun, "meter_back", False))
@staticmethod @staticmethod
def _drawing(r) -> bool: def _drawing(r) -> bool:
+72 -2
View File
@@ -10,6 +10,7 @@ the guard treats a Solar car exactly as a Manual car).
""" """
import asyncio import asyncio
import copy
import dataclasses import dataclasses
import logging import logging
from datetime import timezone from datetime import timezone
@@ -83,6 +84,7 @@ class CarMixin:
self.car_first = first if first in carmode.FIRSTS \ self.car_first = first if first in carmode.FIRSTS \
else carmode.DEFAULT_FIRST else carmode.DEFAULT_FIRST
self._car_late_s = None # EV-20: the cycle's late verdict self._car_late_s = None # EV-20: the cycle's late verdict
self._car_late_mono = None # ... and the time it was read (EV-51)
self._car_sun_now = None # ... and Solar's inputs of that cycle self._car_sun_now = None # ... and Solar's inputs of that cycle
sun = data.get(CAR_SUN_KEY) sun = data.get(CAR_SUN_KEY)
self.car_sun = {"day": None, "kwh": 0.0} self.car_sun = {"day": None, "kwh": 0.0}
@@ -372,8 +374,76 @@ class CarMixin:
now = self.car_now() now = self.car_now()
sun = None sun = None
if self.car_mode == carmode.SOLAR: if self.car_mode == carmode.SOLAR:
sun = getattr(self, "_car_sun_now", None) \ sun = self.car_sun_own(getattr(self, "_car_sun_now", None)
or self.car_sun_inputs(now) or self.car_sun_inputs(now), now)
w0 = self.car_solar
a0, n_log = w0.plan.a, len(w0.log)
await self._car_step_run(held, now, sun)
if sun is not None and _LOG.isEnabledFor(logging.DEBUG):
self._car_step_debug(held, now, sun, a0, n_log)
def _car_step_debug(self, held, now, sun, a0, n_log) -> None:
"""EV-51: one DEBUG line per Solar writer step: the time, the meter's
age at the step, what was decided and what was written. The decision
is one word: steady, start, raise, lower, pause, hold (the
late-readings hold), wait-unknown (the spare is unknown and the pause
timer counts) or wait-held (a held charger read). Nothing at info and
above; no secrets in it."""
w = self.car_solar
a1 = w.plan.a
if a0 > 0.0 and a1 <= 0.0:
what = "pause"
elif held:
what = "wait-held"
elif sun.hold:
what = "hold"
elif a0 <= 0.0 and a1 > 0.0:
what = "start"
elif a1 > a0 + carmode.TOL_A:
what = "raise"
elif a1 < a0 - carmode.TOL_A:
what = "lower"
elif sun.target_w is None:
what = "wait-unknown"
else:
what = "steady"
sent = []
for kind, v, _t, ok in w.log[n_log:]:
if kind == "current":
sent.append(f"sent {v:g} A" + (" confirmed" if ok else ""))
else:
sent.append(f"phases {v}" + (" confirmed" if ok else ""))
age = sun.age_s
_LOG.debug("Solar step: t=%.1f age=%s decision=%s write=%s", now,
"none" if age is None else f"{age:.1f}", what,
"; ".join(sent) or "none")
def car_sun_own(self, snap, now):
"""EV-51 (PM): every decision on the meter's AGE is taken at the writer
step's own age (now minus the meter's last reading), not the age the
cycle saw one step earlier: the write block while the meter is silent
(N8), the unknown/pause timing (held reads too) and the late-readings
hold with its stale rule. The meter's VALUES (spare, target) stay the
cycle's only while the step's own age says the meter is fresh; once it
is past `meter_max_age_s` they are unknown (C23). Arrival sources'
`car_spare_w` keeps the cycle's age."""
own = copy.copy(snap)
own.silent = self._car_meter_silent()
own.unknown_s = self._car_meter_over_s()
own.age_s = self.p1.age_s() if self.p1_enabled else None
own.meter_back = snap.unknown_s > 0.0 and own.unknown_s <= 0.0
stale = float(self.o.get("stale_input_s", 15))
late = self._car_late_s # the verdict stands: it has aged since
if late is not None and self._car_late_mono is not None:
late += max(0.0, now - self._car_late_mono)
own.hold = late is not None and late < stale
if own.silent or (late is not None and late >= stale):
# The stale rule on the step's own age / own late (C23): a spare
# read from data the own age calls old starts or raises nothing.
own.spare_w = own.target_w = None
return own
async def _car_step_run(self, held, now, sun) -> None:
if held: if held:
# EV-20 rig round 2 (PM): the charger missed a read for less than # EV-20 rig round 2 (PM): the charger missed a read for less than
# `stale_input_s`; the last trusted figure stands and nothing is # `stale_input_s`; the last trusted figure stands and nothing is
+1
View File
@@ -254,6 +254,7 @@ class CycleMixin:
stale_after = float(self.o.get("stale_input_s", 15)) stale_after = float(self.o.get("stale_input_s", 15))
late_s = self._readings_late(site_standing) # SAFETY-128 late_s = self._readings_late(site_standing) # SAFETY-128
self._car_late_s = late_s # EV-20: Solar holds, then the stale rule self._car_late_s = late_s # EV-20: Solar holds, then the stale rule
self._car_late_mono = self._now_mono # EV-51: when that verdict was read
self._late_zero = late_s is not None and late_s >= stale_after 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 # ⚠️ `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 # poll does not become a fault; a LATCHED inverter must still reach the
File diff suppressed because it is too large Load Diff
+45 -2
View File
@@ -137,11 +137,41 @@ class SunPlant:
return True return True
def _cycle_seconds(t0, dur, cyc, phase, jitter, cset):
"""EV-51: the seconds a cycle runs, or None for every second."""
if cset is not None:
due = {int(x) for x in cset if t0 <= x < t0 + dur}
if not due:
raise ValueError("cset has no second inside the run")
return due
if jitter is not None:
gaps = [int(g) for g in jitter]
if not gaps or min(gaps) <= 0:
raise ValueError("jitter needs gaps above 0")
due, t, i = set(), int(t0), 0
while t < t0 + dur:
due.add(t)
t += gaps[i % len(gaps)]
i += 1
return due
if cyc != int(cyc) or cyc <= 0:
raise ValueError("cyc must be a whole number of seconds above 0")
if not 0 <= phase < cyc:
raise ValueError("phase must be in [0, cyc)")
if cyc == 1:
return None
due = {int(t0) + k for k in range(int(phase), int(dur), int(cyc))}
if not due:
raise ValueError("no cycle inside the run")
return due
def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0, def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0,
margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar", margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar",
first="batteries", events=None, sim=None, store=None, race=False, first="batteries", events=None, sim=None, store=None, race=False,
on_cycle=None, car_phases=3, t0=0.0, caps=None, finale=None, on_cycle=None, car_phases=3, t0=0.0, caps=None, finale=None,
rows=False, plant_cls=None, beside=False, meter_change=False): rows=False, plant_cls=None, beside=False, meter_change=False,
cyc=1, phase=0, jitter=None, cset=None):
"""Run it. Returns a dict: plant, controller, charger, notifications with """Run it. Returns a dict: plant, controller, charger, notifications with
their second, and a per-second trace. `caps` ({unit: kWh}) lets each their second, and a per-second trace. `caps` ({unit: kWh}) lets each
battery's level move with what it charges or gives; without it the battery's level move with what it charges or gives; without it the
@@ -152,7 +182,14 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0,
round 1): a write that waits for its read-back is still waiting when the round 1): a write that waits for its read-back is still waiting when the
next cycle reads the charger; it resumes after that read. next cycle reads the charger; it resumes after that read.
`meter_change=True` publishes the meter as Home Assistant does on `meter_change=True` publishes the meter as Home Assistant does on
`ha_signed`: only when the whole-watt value changes.""" `ha_signed`: only when the whole-watt value changes.
EV-51, the cycle's cadence (the meter and the charger model still tick
every 1 s; only the control cycle is thinned): `cyc` seconds between
cycles and `phase` (the first cycle at t0 + phase), or `jitter`, a
tuple of gaps used in turn (the first cycle at t0), or `cset`, the
cycle seconds. The default (1 s) runs every second as before. A cadence
that would run no cycle is a ValueError, never a vacuous pass."""
due = _cycle_seconds(t0, dur, cyc, phase, jitter, cset)
ratings = ratings or {"a": 5000.0, "b": 4600.0} ratings = ratings or {"a": 5000.0, "b": 4600.0}
socs = socs or {u: 50.0 for u in ratings} socs = socs or {u: 50.0 for u in ratings}
sim = sim or SimCharger(setpoint_a=setpoint) sim = sim or SimCharger(setpoint_a=setpoint)
@@ -252,6 +289,12 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0,
"ha_signed", imp, exp, phases=1, "ha_signed", imp, exp, phases=1,
ingest_ts=rig.BASE + timedelta(seconds=ts), ingest_ts=rig.BASE + timedelta(seconds=ts),
ingest_mono=ts)) ingest_mono=ts))
if due is not None and int(t) not in due:
for u, kwh in (caps or {}).items():
lv = plant.socs[u] - plant.batt_of(u, t) / 36000.0 / kwh
plant.socs[u] = max(0.0, min(100.0, lv))
t += 1.0
continue
await c.read_inputs(now_mono=t) await c.read_inputs(now_mono=t)
if race: if race:
await c.car_settle() await c.car_settle()