EV-51: Solar decides every meter-age rule on the writer step's own age; DEBUG line per step #275

Merged
ems-agent merged 4 commits from EV-51 into release/1.0 2026-11-25 01:19:20 +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
T10(b) changed accordingly).
- **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
age reaches `meter_max_age_s` + `ev_pause_min` (330 s), checked every
control cycle (bound 330 s + one cycle). Arrival sources are unchanged.
meter's age: unknown since the age passed `meter_max_age_s`, so 0 A on the
first car step whose own meter age (now minus the last reading, at that
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):**
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
+14 -4
View File
@@ -498,8 +498,13 @@ class SunInputs:
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, 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
# 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
# the cause is the meter's own age (`ha_signed`): the pause is timed
# from that age, not from the cycle that noticed it.
@@ -570,11 +575,15 @@ class SolarPlan:
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, 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);
`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."""
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:
# Readings late under the stale bound: nothing changes, but a
# 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,
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, 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
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 copy
import dataclasses
import logging
from datetime import timezone
@@ -83,6 +84,7 @@ class CarMixin:
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_late_mono = None # ... and the time it was read (EV-51)
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}
@@ -372,8 +374,76 @@ class CarMixin:
now = self.car_now()
sun = None
if self.car_mode == carmode.SOLAR:
sun = getattr(self, "_car_sun_now", None) \
or self.car_sun_inputs(now)
sun = self.car_sun_own(getattr(self, "_car_sun_now", None)
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:
# 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
+1
View File
@@ -254,6 +254,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._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
# ⚠️ `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
File diff suppressed because it is too large Load Diff
+45 -2
View File
@@ -137,11 +137,41 @@ class SunPlant:
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,
margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar",
first="batteries", events=None, sim=None, store=None, race=False,
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
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
@@ -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
next cycle reads the charger; it resumes after that read.
`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}
socs = socs or {u: 50.0 for u in ratings}
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,
ingest_ts=rig.BASE + timedelta(seconds=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)
if race:
await c.car_settle()