Compare commits

...
13 Commits
Author SHA1 Message Date
ems-agentandClaude a33eb8ef1c EV-51 round 1: C23 (no spare/target from data the own age calls old), N5 label, T44
infra-pin / fresh (pull_request) Waiting to run
checks / unit (pull_request) In progress
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
ems-agent 5bff894cca Merge pull request 'EV-20 rig round 2: no pause on a short charger read gap; ha_signed pause timed from the meter age' (#274) from EV-20-r2 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-24 10:10:11 +01:00
Claude 4dc030929a EV-20 review r4: wording only (DECISIONS held-read sentence, step docstring)
checks / unit (pull_request) Successful in 29m14s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-24 09:40:31 +01:00
Claude 0cfb99ed65 EV-20 review r3: a held read moves no plan count; only the meter-age pause may fire
checks / unit (pull_request) Successful in 54m0s
infra-pin / fresh (pull_request) Successful in 1s
On a held charger read no writer steps and the Solar plan does nothing: no
phase change or switching start begins, no _set or end_switch, ok_since,
up_since, down_since, low_since and set_at stay, and the hold pause does not
fire; a decision due then runs on the next real reading. The one exception
is the pause by the meter's age (C18, SolarWriter.held_pause). Rows: the
reviewer's three shapes with 1- and 2-read gaps on and before the decision
cycle, and the hold pause on a held cycle. DECISIONS wording fixed.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 06:54:07 +01:00
Claude a60ebd3286 Merge release/1.0 (2768755, infra pin bump #273) into EV-20-r2
checks / unit (pull_request) Successful in 31m32s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 05:53:46 +01:00
ems-agent 2768755400 Merge pull request 'infra-pin: bump to admin/goodwe e4e8897' (#273) from infra-pin-e4e8897 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-24 05:53:29 +01:00
Claude 6fbf2600f9 EV-20 C19: a held read does nothing to a phase change under way
checks / unit (pull_request) Successful in 33m15s
infra-pin / fresh (pull_request) Failing after 2s
The C17 branch (end a phase change at its 0 A and pause) ran on a held read
too, so one failed read just after a select stopped the car for the 600 s
phase gap. A held read now leaves the change alone; it goes on at the next
real reading. The silent meter still ends it at its 0 A. Rows: test_ev20_rig
section 9.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 03:19:19 +01:00
Claude 0ef8de26cb EV-20 round 3: on a held read Solar writes only a new 0 A, no retry
checks / unit (pull_request) Successful in 35m24s
infra-pin / fresh (pull_request) Failing after 2s
A retry on a held cycle went to a charger that was not answering and changed
the try count (test_ev20_fuzz T54 N14, seed 1). Held cycles now allow only a
new 0 A decision, such as the age pause.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 02:05:05 +01:00
Claude 3083093e22 EV-20 round 3: no non-zero write while the meter is silent (C17); the age pause on a held read (C18)
checks / unit (pull_request) Successful in 35m34s
infra-pin / fresh (pull_request) Failing after 2s
While the meter's age is past meter_max_age_s, or on a held charger read,
Solar sends no non-zero current: no retry, no raise, no phase change begun,
and a phase change under way ends at its 0 A. 0 A is always allowed. On a
held read Solar still steps (Manual does not), so a pause due then is not
slipped. Rows in test_ev20_rig.py section 8.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 01:24:36 +01:00
Claude f62501174d EV-20 rig round 2: hold only real read gaps, not a reading's own unavailable cause
checks / unit (pull_request) Successful in 40m43s
infra-pin / fresh (pull_request) Failing after 1s
A failed read or every required entity unavailable is a gap and keeps the
last reading; one entity missing, a wrong power unit or login off stay the
reading they are (EV-03 round 4 rows green again).

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 00:46:34 +01:00
Claude 49e010fdfb EV-20 rig round 2: the age row notices the stale meter late, as the rig's cycle does
checks / unit (pull_request) Successful in 41m15s
infra-pin / fresh (pull_request) Failing after 1s
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-23 23:55:17 +01:00
Claude 8d62abe36b EV-20 rig round 2: a short charger read gap keeps the last reading; ha_signed pause timed from the meter age
checks / unit (pull_request) Failing after 43m21s
infra-pin / fresh (pull_request) Failing after 2s
A charger reading missing for less than stale_input_s keeps the last trusted
reading in CarTracker (shared by Solar, Manual and the peak guard): no
decision or write in that cycle, no stuck arm or clear. At stale_input_s the
safe path is unchanged. This also stops the false PEAK_GUARD_FLOOR_LIMITED
after one gap (EV-18 T10(b) updated). On ha_signed Solar's unknown-sun pause
comes at meter age meter_max_age_s + ev_pause_min, checked every cycle.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-23 23:46:48 +01:00
9 changed files with 1526 additions and 19 deletions
@@ -144,3 +144,54 @@ one small set of facts and derives every path from them:
`meter_max_age_s` is the bound (a silent meter: 0 A at
`meter_max_age_s` + `ev_pause_min`).
## Rig round 2 (rig FAIL on 09b6af9), PM rulings
- **A short charger read gap** (chargers.py `CarTracker.observe`, shared by
Solar, Manual and the peak guard): a reading missing for less than
`stale_input_s` keeps the last trusted reading (`held`). A gap is a read
that got no answer, or every required entity unavailable; one entity
missing, a wrong power unit or the login off stay readings of their own
(EV-03 round 4, unchanged); nothing is decided
or written in that cycle: no writer steps (`ctl_car.car_step` returns), no
plan count moves (start, phase change, hold, `set_at`) and a decision due
then runs on the next real reading (review r3, PM design). The one
exception is Solar's pause by the meter's age (C18, `held_pause`). A held
read neither arms nor clears the stuck check. At `stale_input_s` the
missing reading is taken as before (the safe path: the charger is gone, 0 A first on its return).
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 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; `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.
- **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
under way ends at its 0 A (no select after that, no closing current); the
plan pauses. 0 A is always allowed. Also on a held read (`nz_block`).
- **The age pause on a held read (C18):** on a held cycle Solar does not step
(review r3, PM design); only `held_pause` runs: while the meter is silent
and its age has reached `meter_max_age_s` + `ev_pause_min`, the plan pauses
and a NEW 0 A goes out (no retry to a charger that is not answering). No
phase change, start, hold pause or other count moves on a held cycle.
- **Accepted (PM, P9g):** a frozen charger that also stops answering is
flagged only once it answers again; the 15 s safe path covers the gap.
- **A held read during a phase change (SPIKE-06 C19):** a phase change under
way does nothing on a held read (no write, no pause) and goes on at the next
real reading; it ends at its 0 A only while the meter is silent (C17). No
phase change begins on a held cycle; a gap of `stale_input_s` or more takes
the safe path unchanged. Accepted by design (PM): a one-sample partial
reading (only power unavailable, say) still gives the D2 0 A.
+78 -7
View File
@@ -498,8 +498,20 @@ 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):
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.
self.unknown_s = unknown_s
# EV-20 SPIKE-06 C17 (N8): the meter is known silent (its age past
# `meter_max_age_s`): no non-zero current goes out, only 0 A.
self.silent = silent
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
@@ -563,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):
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
@@ -586,6 +602,11 @@ class SolarPlan:
if self.a > 0.0:
if self.unknown_since is None:
self.unknown_since = now
if unknown_s > 0.0:
# ha_signed: unknown since the meter's age passed its
# bound, so the pause comes at that age + `pause_s`.
self.unknown_since = min(self.unknown_since,
now - unknown_s)
# 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
@@ -721,6 +742,8 @@ class SolarWriter(ManualWriter):
self.stuck_starts = 0 # SPIKE-06 C12: starts under one stuck verdict
self.stuck_wait = None # ... used up: the next start not before
self.stuck_warned = False # ... and its one CHARGER_REFUSED was given
self.nz_block = False # C17/C18: this step writes 0 A at most
self.held_step = False # C18: a held read: only a NEW 0 A goes out
def owe_start(self) -> None:
"""C1: the add-on starts in Off while an exit 0 A of its own was still
@@ -828,7 +851,11 @@ class SolarWriter(ManualWriter):
`MAX_TRIES` and never waits (0 A is the safe side)."""
if self.hold:
return
if want > TOL_A and self.nz_block:
return # C17/C18: 0 A only, no retry or raise
if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A:
if self.held_step:
return # C18: no retry to a charger not answering
if self.taken or self.gave_up or (
self.fail_at is not None
and now - self.fail_at < RETRY_S):
@@ -919,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)
gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0),
meter_back=getattr(sun, "meter_back", False))
@staticmethod
def _drawing(r) -> bool:
@@ -975,12 +1003,41 @@ class SolarWriter(ManualWriter):
"prev": None, "from": r.phases_allowed}
# ------------------------------------------------------------- step
async def held_pause(self, drv, r, *, sun, now, tracker) -> None:
"""EV-20 (C18, PM design r3): on a held charger read only the pause by
the meter's age may come (0 A): nothing else in the plan moves, no
phase change begins or goes on, no retry. Called instead of `step`."""
if not self.engaged or self.seq is not None or self.hold \
or self.fault is not None or self.restart \
or self.plan.a <= 0.0 or self.plan.switch:
return
if not getattr(sun, "silent", False) \
or getattr(sun, "unknown_s", 0.0) < sun.pause_s:
return
self.nz_block = self.held_step = True
try:
self.plan.pause("unknown")
cur = None if r is None else (
r.allowed_a if r.allowed_a is not None else r.setpoint_a)
await self._put(drv, 0.0, cur, now, tracker)
finally:
self.nz_block = self.held_step = False
async def step(self, drv, r, *, mode, sun, clamp, now, tracker, writing,
status, clock=None):
status, clock=None, held=False):
"""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."""
and while stopping. `held`: the charger missed this read and the last
reading stands in (EV-20 round 2): the step may pause, never raise.
`ctl_car.car_step` no longer passes it (review r3): on a held cycle
only `held_pause` runs."""
self._clock = clock or (lambda: now)
# SPIKE-06 C17/C18: while the meter is silent, or on a held read, no
# non-zero current goes out (no retry, no raise, no closing current
# of a phase change); 0 A always may.
self.nz_block = bool(held or (sun is not None
and getattr(sun, "silent", False)))
self.held_step = bool(held)
entering = mode == SOLAR and self.mode_was != SOLAR
self.mode_was = mode
if entering:
@@ -1121,6 +1178,20 @@ class SolarWriter(ManualWriter):
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 and self.held_step:
# SPIKE-06 C19: a held read decides nothing for a phase change
# under way (no write, no pause); it goes on at the next real
# reading. A gap that reaches `stale_input_s` takes the safe path.
return
if self.seq is not None and self.nz_block:
# C17: a phase change under way ends at its 0 A; no select and no
# closing current while the meter is silent. The plan pauses and
# starts again by the start rule.
self.seq = None
self.plan.end_switch(False)
self.plan.pause("unknown")
await self._put(drv, 0.0, cur, now, tracker)
return
if self.seq is not None:
self._plan_step(sun, now, clamp, self.plan.n, gap)
if self.plan.a < CH.MIN_A:
@@ -1163,7 +1234,7 @@ class SolarWriter(ManualWriter):
return
self._plan_step(sun, now, clamp, n_now, gap)
want = self.amps_out(clamp)
if want >= CH.MIN_A and self.plan.switch \
if want >= CH.MIN_A and self.plan.switch and not self.nz_block \
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):
+34
View File
@@ -255,6 +255,18 @@ def display_class(text) -> str | None:
return None
def _is_gap(why) -> bool:
"""EV-20: does this unavailable reading's cause mean "no answer" (a read
gap), not a reading the charger gave?"""
why = why or ""
if why == "no answer":
return True
if why.startswith("no answer from "):
gone = {x.strip() for x in why[len("no answer from "):].split(",")}
return set(REQUIRED) <= gone
return False
def reading_from_states(states: dict) -> ChargerReading:
"""A `ChargerReading` from `{role: state object or None}`. Pure."""
def txt(role):
@@ -719,6 +731,7 @@ class CarTracker:
# write went out, kept at `begin_write` (the arming baseline). Empty: no
# write begun, and `note_write` uses `sig`.
pre_sig: tuple = ()
held: bool = False # EV-20: the last reading stands in for a gap
armed_at: float | None = None
armed_sig: tuple | None = None
sig: tuple | None = None
@@ -735,6 +748,17 @@ class CarTracker:
persist: bool = False # set when `today` changed, for the store
def observe(self, r: ChargerReading, now: float, now_utc, day: str):
if not r.available and self.bad_since is None:
self.bad_since, self.bad_since_utc = now, now_utc
if self._held(r, now):
# EV-20 rig round 2 (PM): a reading missing for less than
# `stale_s` keeps the last trusted figure and decides nothing:
# no write, no pause, and it neither arms nor clears the stuck
# check. At `stale_s` the missing reading is taken as before.
self.held = True
self._status_edge(now, now_utc)
return
self.held = False
self.reading = r
self.obs_at = now
self._corr_note(r, now)
@@ -757,6 +781,16 @@ class CarTracker:
self._timers(r, now)
self._status_edge(now, now_utc)
def _held(self, r, now: float) -> bool:
"""Is this missing reading a short gap behind a usable one? A gap is
a read that failed (no answer at all) or Home Assistant showing every
required entity unavailable. One entity missing, a wrong unit or the
login off are readings of their own (EV-03), never held."""
last = self.reading
return (not r.available and _is_gap(r.why) and last is not None
and last.available and self.last_ok is not None
and now - self.last_ok < self.stale_s)
# -- reachability ----------------------------------------------------------
def unreachable(self, now: float) -> bool:
return self.bad_since is not None and now - self.bad_since >= UNREACHABLE_S
+106 -6
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}
@@ -368,8 +370,88 @@ class CarMixin:
cycle's read did) and writes only through `carmode`'s writers."""
if not self.charger.configured():
return
held = bool(self.car.held)
now = self.car_now()
if self.car_mode != carmode.SOLAR:
sun = None
if self.car_mode == carmode.SOLAR:
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. 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; 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
# decided or written from the gap. No writer steps and no plan
# count (start, phase change, hold) moves (review r3, PM design);
# a decision due now runs on the next real reading. The one
# exception: Solar's pause by the meter's age (C18).
if sun is not None and self.car_writing():
await self.car_solar.held_pause(
self.charger, self.car.reading, sun=sun, now=now,
tracker=self.car)
return
if self.car_mode != carmode.SOLAR and not held:
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,
@@ -380,10 +462,6 @@ class CarMixin:
if self.car_mode == carmode.SOLAR or w.engaged:
# C6: one write clock: Manual's latest non-zero write counts.
w.other_at = self.car_writer.nonzero_at
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,
@@ -452,7 +530,29 @@ class CarMixin:
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)
spare_w=spare, room_w=room, margin_w=margin, first=self.car_first,
unknown_s=self._car_meter_over_s() if spare is None else 0.0,
silent=self._car_meter_silent())
def _car_meter_silent(self) -> bool:
"""SPIKE-06 C17 (N8): is the meter known silent (its age past
`meter_max_age_s`)? Then Solar writes no non-zero current."""
if not self.p1_enabled:
return False
age = self.p1.age_s()
bound = float(self.o.get("meter_max_age_s", 30) or 30)
return age is not None and age > bound
def _car_meter_over_s(self) -> float:
"""EV-20 rig round 2 (PM): on `ha_signed`, how far the meter's age is
past `meter_max_age_s`, so Solar's pause comes at that age +
`ev_pause_min` (checked every cycle), not a cycle or two later."""
if not self.p1_enabled \
or str(self.o.get("meter_source") or "") != "ha_signed":
return 0.0
age = self.p1.age_s()
bound = float(self.o.get("meter_max_age_s", 30) or 30)
return 0.0 if age is None else max(0.0, age - bound)
def _car_sun_tick(self, mono) -> None:
"""Solar kWh: per cycle, in Solar only, the car's power up to the sun
+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
+22 -4
View File
@@ -605,11 +605,14 @@ for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))),
r10b, tr10b = H.run(a=ZERO, extra=unavailable(E + 1, E + 2), **kw)
summary(f"T10(b) {nm}", r10b, tr10b)
if nm == "T2":
# EV-20 rig round 2 (PM): a charger read missing for less than
# stale_input_s keeps the last trusted figure, so this one-cycle gap
# is no longer an unknown car figure (was: the alarm for that cycle).
check("T10(b) T2: the charger unavailable for one cycle (E+1): the "
"alarm stands for that cycle only (Expected 5)",
H.edges(tr10b) == [E + 1]
and all(not x["alarm"] for x in H.window(tr10b, E + 2, E + 899))
and all(x["explains"] for x in H.window(tr10b, E + 2, E + 899)
"last trusted figure stands (EV-20), no alarm edge, the car "
"explains every limited cycle",
H.edges(tr10b) == [] and quiet(r10b, tr10b)
and all(x["explains"] for x in H.window(tr10b, E, E + 899)
if x["lim"]))
else:
check("T10(b) T5: the alarm at the base second and it stands",
@@ -813,6 +816,21 @@ def per_quarter(ts):
return out
# EV-20 rig round 2: ONE failed charger read in the T2 shape. The tracker keeps
# the last trusted figure for a gap under `stale_input_s`, so the car still
# explains the peak and no floor alarm comes (rig: a false FLOOR_LIMITED 1-2 s
# after a single read gap, on base and head).
for gap in (1, 2):
rg, trg = H.run(H.shape(14000.0), a=ZERO, b=const(800.0),
extra={E + 30: lambda p, c: p.ch.go_unavailable(),
E + 30 + gap: lambda p, c: p.ch.go_unavailable(
False)})
wg, limg = summary(f"T-gap {gap} s", rg, trg)
check(f"T-gap: {gap} missed charger read(s) at E+30: no "
f"goodwe_peak_soc_floor, no FLOOR_LIMITED ERROR, no red peak_guard "
f"row, the car explains every limited cycle",
quiet(rg, trg) and all_explained(limg))
# Cover off, the T9(c) liar at the reserve: the guard's own engagement flips
# as the liar's figure is corroborated now and then (its input is
# `car_exclude`), pre-existing (base: 4 edges). Printed, not graded here.
+285
View File
@@ -502,4 +502,289 @@ for race in (True, False):
nevers(r, f"C13 controller [race={race}]")
# =========================================================================== #
print("\n7. RIG ROUND 2: A SHORT CHARGER READ GAP; THE ha_signed PAUSE BY AGE")
# =========================================================================== #
# Full sun, Car first, charging 10 A from 120 s; the charger does not answer
# for 1, 2 or 16 cycles at 600 s (Home Assistant shows it unavailable).
def gap_run(n, beside=False):
sim = SimCharger(setpoint_a=0)
if beside:
sim.lag_s = 1.0
return S.drive(const(500.0), const(2900.0), dur=1100, first="car",
socs={"a": 100.0, "b": 100.0}, sim=sim, beside=beside,
events={600: lambda p, c: p.ch.go_unavailable(),
600 + n: lambda p, c: p.ch.go_unavailable(False)})
for n in (1, 2):
for beside in (False, True):
r = gap_run(n, beside)
w = cur_writes(r)
late = [(t, a) for t, a, _ in w if t >= 590]
unk = [x["t"] for x in r["trace"] if 590 <= x["t"] < 1100
and x["spare"] is None]
check(f"read gap of {n} sample(s) at 600 s [beside={beside}]: no "
f"write and no pause after it, the spare stays known (writes "
f"from 590 s {late}, unknown {unk[:3]})",
late == [] and unk == [] and r["sim"].power_w > 2000.0)
nevers(r, f"read gap {n} [beside={beside}]")
# 16 s (>= stale_input_s): the safe path as before. The charger is taken as
# gone; on its return Solar writes 0 A first (D2), then the start rule.
r = gap_run(16)
w = cur_writes(r)
late = [(t, a) for t, a, _ in w if t >= 590]
check(f"read gap of 16 s: the safe path, 0 A first on the return, then the "
f"start rule ({late[:3]})",
present(nth(late, 0)) and nth(late, 0)[1] == 0.0
and 616 <= nth(late, 0)[0] <= 620 and present(nth(late, 1))
and nth(late, 1)[1] > 0.0)
# The held figure neither arms nor clears the stuck check: a frozen reading
# after an accepted write is still stuck, with a 2-sample gap inside the 60 s
# (flagged at the first real reading at or after +60 s).
tr = CH.CarTracker()
for i in range(-5, 1):
tr.observe(rd(), TS + i, UTC, DAY)
tr.begin_write()
tr.end_write(TS + 1)
tr.note_write(TS, 10.0, 0.0, True)
gone = CH.ChargerReading(why="no answer")
st_at = None
for i in range(1, 90):
if i in (59, 60):
tr.observe(gone, TS + i, UTC, DAY)
else:
tr.observe(rd(), TS + i, UTC, DAY)
if st_at is None and tr.stuck(TS + i):
st_at = i
check(f"frozen reading with a 2-sample gap at +59/+60: still stuck, at the "
f"first real reading after +60 (+{st_at})", st_at == 61)
tr = CH.CarTracker()
for i in range(-5, 1):
tr.observe(rd(), TS + i, UTC, DAY)
tr.begin_write()
tr.end_write(TS + 1)
tr.note_write(TS, 10.0, 0.0, True)
for i in range(1, 70):
tr.observe(rd(), TS + i, UTC, DAY)
tr.observe(gone, TS + 70, UTC, DAY)
check("a held gap does not clear a stuck verdict (+70 s gap, still stuck)",
tr.stuck(TS + 70) and getattr(tr, "held", None) is True)
# ha_signed: the pause is timed from the meter's age (PM): unknown since the
# age passed meter_max_age_s, so 0 A when the age reaches 330 s. A plan
# stepped every 10 s (the rig's cycle) that first sees the unknown sun at age
# 57 (a cycle or two after the bound passed) still pauses at the first step at
# or after age 330 (bound: 330 + one cycle); timed from the noticing step it
# would be age 357.
plan = carmode.SolarPlan()
plan.reset(1)
kw = dict(n_now=1, auto=False, clamp=16.0, start_s=120.0, pause_s=300.0)
t = 0.0
while plan.a <= 0.0 and t < 400:
plan.step(t, target_w=2900.0, **kw)
t += 10.0
age0 = t + 3.0 # the meter's last reading; the bound passes at +30
paused_at = None
while t < age0 + 400:
age = t - age0
over = max(0.0, age - 30.0)
try:
plan.step(t, target_w=None if age > 50.0 else 2900.0,
unknown_s=over if age > 50.0 else 0.0, **kw)
except TypeError: # a build without the age rule
plan.step(t, target_w=None if age > 50.0 else 2900.0, **kw)
if plan.a == 0.0 and paused_at is None:
paused_at = age
break
t += 10.0
check(f"ha_signed pause by age, plan stepped every 10 s: 0 A at meter age "
f"{paused_at} (330 <= age <= 340)",
paused_at is not None and 330.0 <= paused_at <= 340.0)
# The controller hands Solar that age: 40 s after the meter went silent at
# 300 s, `unknown_s` is 10 (age 40 - 30).
seen = {}
r = S.drive(const(500.0), const(2900.0), dur=360, first="car",
socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"},
events={300: lambda p, c: setattr(p, "meter_on", False),
340: lambda p, c: seen.update(
u=getattr(c.car_sun_inputs(p.clock[0]),
"unknown_s", None))})
check(f"ha_signed: 40 s after the meter went silent Solar is told the sun "
f"has been unknown for 10 s ({seen})",
seen.get("u") is not None and 9.0 <= seen["u"] <= 12.0)
# =========================================================================== #
print("\n8. SPIKE-06 ROUND 3: NO NON-ZERO WRITE WHILE THE METER IS SILENT (C17);")
print(" THE AGE PAUSE ON A HELD READ (C18)")
# =========================================================================== #
# C17 (a): 7 A, a raise to 10 A at 340 s that the charger ignores, the meter
# silent from 345 s (ha_signed). No re-send of the 10 A (the retry would come
# at 400 s, meter age 55 s); 0 A when the age reaches 330 s.
sim = TSim(setpoint_a=0, windows=[(335.0, 350.0, "ignore")])
r = S.drive(const(500.0), lambda t: 3000.0 if t >= 340 else 2300.0,
dur=900, first="car", socs={"a": 100.0, "b": 100.0}, sim=sim,
opts={"ev_phases": "1"},
events={345: lambda p, c: setattr(p, "meter_on", False)})
w = cur_writes(r)
nz = [(t, a) for t, a, _ in w if a > 0.0 and t > 345 + 30]
z = [t for t, a, _ in w if a == 0.0 and t > 345]
raise_ = [(t, a, ok) for t, a, ok in w if 330 <= t <= 345]
check(f"C17 (a): an ignored raise ({raise_}), then the meter silent from "
f"345 s: no re-send while it is silent ({nz}), 0 A at meter age 330 "
f"(+2) ({z[:1]})",
present(nth(raise_, 0)) and nth(raise_, 0)[2] is False and nz == []
and present(nth(z, 0)) and 345 + 329 <= nth(z, 0) <= 345 + 333)
nevers(r, "C17 (a)")
# C17 (b): a 1 -> 3 phase change starts at 301 s (its 0 A); the meter has been
# silent since 276 s, so its age passes 30 s at 307 s, before the closing
# current (313 s without silence). The change ends at its 0 A: no closing
# current, nothing non-zero until the meter is back.
r = S.drive(const(500.0), const(7600.0), dur=900, first="car",
socs={"a": 100.0, "b": 100.0}, car_phases=3,
events={276: lambda p, c: setattr(p, "meter_on", False),
800: lambda p, c: setattr(p, "meter_on", True)})
w = cur_writes(r)
seq0 = [t for t, a, _ in w if a == 0.0 and 295 <= t <= 305]
nz = [(t, a) for t, a, _ in w if a > 0.0 and 306 < t < 800]
check(f"C17 (b): a phase change under way when the meter goes silent ends at "
f"its 0 A ({seq0}): no closing current, no non-zero write while silent "
f"({nz}); writes {w[:6]}",
present(nth(seq0, 0)) and nz == []
and [a for t, a, _ in w if 301 <= t < 800][-1:] == [0.0])
nevers(r, "C17 (b)")
# C18: a charger read gap on the very cycle the age pause is due (ha_signed,
# meter silent from 300 s: due at 629 s without a gap, the meter's last sample
# being at 299 s). The held cycle still steps Solar's pause: 0 A at 629 s, at
# most one cycle later (f625011: 631 s with the gap from 629 s).
for gap_at in (629, 630):
r = S.drive(const(500.0), const(2900.0), dur=760, first="car",
socs={"a": 100.0, "b": 100.0}, opts={"ev_phases": "1"},
events={300: lambda p, c: setattr(p, "meter_on", False),
gap_at: lambda p, c: p.ch.go_unavailable(),
gap_at + 2: lambda p, c: p.ch.go_unavailable(False)})
w = cur_writes(r)
z = [t for t, a, _ in w if a == 0.0 and t > 300]
check(f"C18: a 2-sample read gap from {gap_at} s, the age pause due at "
f"629 s: 0 A at {z[:1]} (629-630)",
present(nth(z, 0)) and 629 <= nth(z, 0) <= 630)
# =========================================================================== #
print("\n9. SPIKE-06 C19: A READ GAP DURING A PHASE CHANGE")
# =========================================================================== #
# The C17 (b) shape without the silent meter: a 1 -> 3 change, its 0 A at
# 301 s, select 3, closing current at 313 s. One to six failed charger reads
# right after the select change nothing: the closing current comes on time
# and no pause follows (0ef8de2: paused, no current until about 914 s).
def phase_run(events):
return S.drive(const(500.0), const(7600.0), dur=700, first="car",
socs={"a": 100.0, "b": 100.0}, car_phases=3,
events=events)
for n in (1, 2, 6):
r = phase_run({305: lambda p, c: p.ch.go_unavailable(),
305 + n: lambda p, c: p.ch.go_unavailable(False)})
w = cur_writes(r)
close = [(t, a) for t, a, _ in w if a > 0.0 and 301 < t < 700]
check(f"C19: {n} failed read(s) at 305 s, just after the select: the "
f"closing current on time ({close[:2]}), no pause ({w[:5]})",
present(nth(close, 0)) and 312 <= nth(close, 0)[0] <= 313 + n
and [a for t, a, _ in w if 301 < t < 700 and a == 0.0] == [])
nevers(r, f"C19 gap {n}")
# A gap of stale_input_s or more during the change: the safe path as before.
# The charger is taken as gone: nothing while it is away and no closing
# current; on its return the change is dropped and Solar starts over (0 A
# first, already standing here, so nothing is written; then the start rule,
# which on the 3 phases the select left waits for the phase gap).
r = phase_run({305: lambda p, c: p.ch.go_unavailable(),
322: lambda p, c: p.ch.go_unavailable(False)})
w = cur_writes(r)
during = [(t, a) for t, a, _ in w if 305 <= t < 322]
after = [(t, a) for t, a, _ in w if t >= 322]
check(f"C19: a 17 s gap during the change takes the safe path: nothing while "
f"away ({during}), no closing current, nothing non-zero before the "
f"start rule after the return ({after[:2]})",
during == [] and not [1 for t, a in after if a > 0.0 and t < 322 + 115]
and r["c"].car_solar.seq is None)
nevers(r, "C19 long gap")
# =========================================================================== #
print("\n10. REVIEW R3: A HELD READ ON A DECISION CYCLE (PM design)")
# =========================================================================== #
# The reviewer's three shapes (house 500 W, Car first, 3-phase car). A 1- or
# 2-sample read gap on the cycle a phase change or a switching start is due,
# or on the cycle before it: the decision waits for the next real reading and
# every write lands within 2 s of the run without the gap (a60ebd3: the wait
# restarted, and 3 -> 1 became a 0 A pause in full sun).
def sun_b(t):
return 7600.0 if t < 1000 else (300.0 if t < 1400 else 2600.0)
SHAPES = (("A 1 -> 3", const(7600.0), 700, 301),
("B a start that needs 3 -> 1", sun_b, 1900, 1521),
("C 3 -> 1", lambda t: 7600.0 if t < 1000 else 4300.0, 1700, 1301))
def shape_run(sunf, dur, events=None):
return S.drive(const(500.0), sunf, dur=dur, first="car",
socs={"a": 100.0, "b": 100.0}, car_phases=3,
events=events or {})
def after(r, t0, t1):
return [(t, a) for t, a, _ in cur_writes(r) if t0 <= t < t1]
for name, sunf, dur, d in SHAPES:
twin = after(shape_run(sunf, dur), d - 5, d + 200)
for off in (-1, 0):
for n in (1, 2):
g = d + off
r = shape_run(sunf, dur,
{g: lambda p, c: p.ch.go_unavailable(),
g + n: lambda p, c: p.ch.go_unavailable(False)})
got = after(r, d - 5, d + 200)
same = (len(got) == len(twin) and all(
a1 == a2 and abs(t1 - t2) <= 2.0
for (t1, a1), (t2, a2) in zip(got, twin)))
check(f"review r3 [{name}] {n}-read gap at {g} (decision due "
f"{d}): the writes of the run without the gap, within 2 s "
f"({got[:4]} vs {twin[:4]})", same and bool(twin))
nevers(r, f"review r3 [{name}] gap {n} at {g}")
# The hold's pause (low_since past ev_pause_min) never fires on a held cycle:
# it comes on the next real reading, and only if that reading still says low.
base = S.drive(const(500.0), lambda t: 900.0 if t >= 400 else 2900.0,
dur=900, first="car", socs={"a": 100.0, "b": 100.0},
opts={"ev_phases": "1"})
z0 = nth([t for t, a, _ in cur_writes(base) if a == 0.0 and t > 400], 0)
check(f"hold twin: 0 A at {z0} (300 s from the drop at 400, +2)",
present(z0) and 699 <= z0 <= 702)
if present(z0):
zi = int(z0)
r = S.drive(const(500.0), lambda t: 900.0 if t >= 400 else 2900.0,
dur=900, first="car", socs={"a": 100.0, "b": 100.0},
opts={"ev_phases": "1"},
events={zi: lambda p, c: p.ch.go_unavailable(),
zi + 1: lambda p, c: p.ch.go_unavailable(False)})
z = [t for t, a, _ in cur_writes(r) if a == 0.0 and t > 400]
check(f"hold pause due on a held read ({zi}): 0 A on the next real "
f"reading ({z[:1]}), not on the held cycle",
present(nth(z, 0)) and nth(z, 0) == zi + 1)
r = S.drive(const(500.0),
lambda t: 900.0 if 400 <= t < zi else 2900.0,
dur=900, first="car", socs={"a": 100.0, "b": 100.0},
opts={"ev_phases": "1"},
events={zi: lambda p, c: p.ch.go_unavailable(),
zi + 1: lambda p, c: p.ch.go_unavailable(False)})
z = [t for t, a, _ in cur_writes(r) if a == 0.0 and t > 400]
check(f"hold pause due on a held read ({zi}), the sun back from that "
f"second, so the next real reading ({zi + 1}) is not low: no pause "
f"({z[:1]})", z == [])
report()
+904
View File
@@ -0,0 +1,904 @@
"""EV-51: every meter-age decision of a Solar writer step is judged on the
step's OWN age (T1-T43; N1-N12 of reports/EV-51-test-plan.md).
`python3 -B test_ev51.py`
The real Controller on `tools/ev20_sun.py` (the harness now takes a cycle
length, phase, jitter and the production order). "Plain" order: the cycle,
then the writer settles. "Race" order (`race=True`): the production order, the
writer step of a cycle runs beside the NEXT read, so its snapshot is one cycle
old. "Own age" = now minus the meter's last-reading stamp, taken in the writer
step (recorded here by wrapping `Controller.car_step`).
Shared setup: `ha_signed`, `meter_max_age_s` 30, `ev_pause_min` 5 (bound 330 s),
Car first, both batteries full, house 500 W, sun 2900 W, 1 phase, the car at
10 A from 120 s, the meter silent from t = 300. The last sample before the
silence is ingested at 298.7 (the event runs before that second's submit): the
test takes ages from the steps, not from a constant.
DEBUG format (T28): one line per Solar writer step, held steps included,
Solar step: t=630.0 age=331.3 decision=pause write=sent 0 A confirmed
decision: steady, wait-unknown, hold, start, raise, lower, pause, wait-held;
write: none, or "sent X A" (a refused try) / "sent X A confirmed", joined by "; ".
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import dataclasses
import logging
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode # noqa: E402
from app.carmode import SolarPlan # noqa: E402
from app.main import Controller # noqa: E402
import ev20_sun as S # noqa: E402
from chargersim import SimCharger # noqa: E402
from ev20_kit import * # noqa: E402,F401,F403
from ev20_kit import LOG, check, fails, report # noqa: E402,F401
from ev20_kit import TSim, cur_writes, selects # noqa: E402,F401
from named_absence import nth, present # noqa: E402,F401
GOOGLE = logging.getLogger("goodwe")
STEPS = []
SNAP = {}
_orig_step = Controller.car_step
_orig_kick = Controller.car_kick
async def _rec_step(self):
"""Records every writer step: its own age (taken before it runs), the
snapshot's, whether the read was held and the current writes it made."""
w = self.car_solar
snap = getattr(self, "_car_sun_now", None)
age = self.p1.age_s() if self.p1_enabled else None
held = bool(self.car.held)
a0, n0 = w.plan.a, len(w.log)
solar = self.car_mode == carmode.SOLAR
now = self.car_now()
await _orig_step(self)
STEPS.append(dict(
now=now, age=age, held=held, a0=a0, a1=w.plan.a, solar=solar,
snap_age=SNAP.get(id(snap), (None, None))[1],
snap_sil=None if snap is None else snap.silent,
snap_tgt=None if snap is None else snap.target_w,
snap_hold=None if snap is None else snap.hold,
writes=[(x[1], x[2], x[3]) for x in w.log[n0:] if x[0] == "current"],
phases=[x for x in w.log[n0:] if x[0] == "phases"]))
def _rec_kick(self):
_orig_kick(self)
sun = getattr(self, "_car_sun_now", None)
if sun is not None:
SNAP[id(sun)] = (sun, self.p1.age_s() if self.p1_enabled else None)
Controller.car_step = _rec_step
Controller.car_kick = _rec_kick
SIL = 300
FULLB = dict(FULL)
OPT1 = {"ev_phases": "1"}
def go(onset=SIL, dur=760, *, sun=2900.0, house=500.0, events=None, opts=None,
first="car", **kw):
"""The shared setup: the meter off from `onset`, plain unless race=True.
Returns (run, steps)."""
STEPS.clear()
SNAP.clear()
ev = {} if onset is None else {
onset: lambda p, c: setattr(p, "meter_on", False)}
ev.update(events or {})
r = S.drive(house if callable(house) else S.const(house),
sun if callable(sun) else S.const(sun), dur=dur, first=first,
socs=dict(FULLB), opts=dict(OPT1, **(opts or {})), events=ev,
**kw)
return r, list(STEPS)
def cyc_t(t0, cyc, phase, after):
"""The first cycle second at or after `after`."""
t = t0 + phase
while t < after:
t += cyc
return t
def pause_step(steps, bound=330.0, since=SIL):
"""(S, previous): S = the first Solar step with own age >= bound."""
ss = [s for s in steps if s["solar"] and s["age"] is not None
and s["now"] > since]
for i, s in enumerate(ss):
if s["age"] >= bound:
return s, (ss[i - 1] if i else None)
return None, None
def timing(steps, bound=330.0, exp_age=None, since=SIL):
"""Pass: the plan's current goes from > 0 to 0 in the first step S with
own age >= bound; the step before has age < bound; the 0 A is sent in S
(N2, N7)."""
s, prev = pause_step(steps, bound, since)
if s is None or prev is None:
return False
ok = (s["a0"] > 0.0 and s["a1"] == 0.0
and any(a == 0.0 for a, _t, _o in s["writes"]) and prev["age"] < bound)
if exp_age is not None:
ok = ok and abs(s["age"] - exp_age) < 0.05
return ok
def n8(steps, limit=30.0):
"""N8: non-zero current writes at a step whose own age is > limit."""
return [(round(s["now"], 1), round(s["age"], 1), a) for s in steps
if s["age"] is not None and s["age"] > limit
for a, _t, _o in s["writes"] if a > 0.0]
def common(tag, r, steps, *, solar_steps=True, silent_from=SIL, back=None):
"""Every row: cycles > 0 (not vacuous), N8, N1, N4 (no select while the
meter is silent), N6 (no Traceback, no step failure)."""
bad = []
if not [s for s in steps if s["solar"]]:
bad.append("no Solar step ran")
if n8(steps):
bad.append(("N8", n8(steps)[:2]))
if r["c"].charger.clamp_faults:
bad.append("N1 clamp fault")
over = [x for x in r["sim"].log if x[1] == "current" and x[2] > 16.0]
if over:
bad.append(("N1", over[:1]))
end = back if back is not None else 1e9
sel = [x[0] for x in selects(r) if silent_from + 31 < x[0] < end]
if sel:
bad.append(("N4", sel[:2]))
n = r.get("_log", 0)
if LOG.tracebacks(n) or [m for m in LOG.since(n)
if "car charger step failed" in m]:
bad.append("N6")
check(f"{tag}: N1, N4, N6, N8 hold, cycles > 0 ({bad[:2]})", not bad)
return not bad
def run_log(fn, *a, **kw):
n = LOG.mark()
r, st = fn(*a, **kw)
r["_log"] = n
return r, st
def jit():
return (4, 6, 5, 4, 6, 5, 6)
def jit_set(dur):
t, out, i = 0, [], 0
while t < dur:
out.append(t)
t += jit()[i % len(jit())]
i += 1
return out
def lines(n0=0):
"""The parsed DEBUG step lines: [{t, age, decision, write}]."""
out = []
for lv, m, _x in LOG.rec[n0:]:
g = re.match(r"Solar step: t=(\S+) age=(\S+) decision=(\S+) "
r"write=(.*)$", m)
if lv == "DEBUG" and g:
out.append(dict(t=float(g[1]),
age=None if g[2] == "none" else float(g[2]),
decision=g[3], write=g[4]))
return out
def late_at(l0, l1):
"""T10/T43: the late verdict stands from l0 (late_s = now - l0) until l1,
set where the controller reads it (`answer.late_s`), not as a constant."""
def f(p, c):
c.answer.late_s = lambda now: (now - l0) if l0 <= now < l1 else None
return f
# =========================================================================== #
print("1. THE PAUSE ON THE FIRST STEP AT OWN AGE >= 330 (T1-T10, T20, T23)")
# =========================================================================== #
for race in (False, True):
tag = "race" if race else "plain"
ok, ages = True, []
for ph in range(5):
r, st = run_log(go, cyc=5, phase=ph, race=race)
t = cyc_t(0, 5, ph, SIL + 30 + 300 - 1.3) # 628.7
ok = ok and timing(st, exp_age=t - 298.7) and common(
f"T1 [{tag} ph{ph}]", r, st)
s, _ = pause_step(st)
ages.append(s and round(s["age"], 1))
check(f"T1 [{tag}]: 5 s cycles, phases 0-4: the 0 A in the first step at "
f"own age >= 330 ({ages}; 331.3 332.3 333.3 334.3 330.3)",
ok and ages == [331.3, 332.3, 333.3, 334.3, 330.3])
R3 = {"F-silent-1": (32, [327, 332, 337, 343], 333.3),
"F-silent-2": (35, [327, 332, 336, 340, 345], 333.3),
"F-silent-3": (36, [324, 330, 335, 341], 331.3),
"F-exit": (33, [328, 334, 338], 335.3)}
for name, (first, tail, want) in R3.items():
ages = list(range(first, tail[0], 5)) + tail + list(range(tail[-1] + 5, 460, 5))
cset = set(range(0, SIL, 5)) | {int(round(SIL - 1 + 0.7 + a)) for a in ages}
for race in (False, True):
r, st = run_log(go, cset=cset, race=race)
s, _ = pause_step(st)
check(f"T2 [{name} {'race' if race else 'plain'}]: round-3 cadence: "
f"0 A at own age {s and round(s['age'], 1)} (want {want})",
timing(st, exp_age=want) and common("T2", r, st))
for race in (False, True):
tag = "race" if race else "plain"
ok = True
for cyc, phs in ((10, range(10)), (14, (0, 7))):
for ph in phs:
r, st = run_log(go, cyc=cyc, phase=ph, race=race, dur=720)
t = cyc_t(0, cyc, ph, 628.7)
ok = ok and timing(st, exp_age=t - 298.7)
check(f"T3 [{tag}]: 10 s cycles phases 0-9, 14 s cycles phases 0 and 7: "
f"the first step at own age >= 330 pauses", ok)
for race in (False, True):
r, st = run_log(go, cset=set(jit_set(800)), race=race)
check(f"T4 [{'race' if race else 'plain'}]: jittered cycles 4/6/5/4/6/5/6 s: "
f"0 A at own age 332.3 (the silence's first steps do not move it)",
timing(st, exp_age=332.3) and common("T4", r, st))
# T5: the boundary: >= and not >, at the plan and at the controller.
def _plan_at(unknown_s, now):
p = SolarPlan(1)
p.a, p.n, p.set_at = 10.0, 1, 0.0
p.step(now, target_w=None, n_now=1, auto=False, clamp=16.0, start_s=120.0,
pause_s=300.0, unknown_s=unknown_s)
return p.a
check("T5 (plan): own age 329.9 over a 30 s bound (unknown 299.9): no pause; "
"own age 330.0 (unknown 300.0): the pause",
_plan_at(299.9, 630.0) == 10.0 and _plan_at(300.0, 630.0) == 0.0)
for race in (False, True):
for ingest, want_t, tag in ((299.1, 629, "329.9"), (300.0, 630, "330.0")):
def _stamp(p, c, ingest=ingest):
c.p1._last = dataclasses.replace(c.p1._last, ingest_mono=ingest)
r, st = run_log(go, dur=700, race=race,
events={SIL: lambda p, c, f=_stamp: (
setattr(p, "meter_on", False), f(p, c))})
s, prev = pause_step(st)
z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0
and x["now"] > SIL]
# ingest 299.1: the step at 629 has age 329.9 (no pause); 630 has 330.9.
# ingest 300.0: the step at 629 has age 329.0, 630 has exactly 330.0.
first_z = z[0]["now"] if z else None
check(f"T5 (controller, {'race' if race else 'plain'}): the sample "
f"stamped {ingest}: the pause is in the step at {want_t + (1 if tag == '329.9' else 0)} "
f"(first 0 A step {first_z}); ages seen {[round(x['age'], 1) for x in st if x['now'] in (629.0, 630.0)]}",
first_z == (630.0 if tag == "329.9" else 630.0) and bool(z))
for race in (False, True):
for ret_age, back_at, off_at in ((329, 628, 629), (200, 500, 501)):
r, st = run_log(go, dur=1400, cyc=5, phase=0, race=race,
events={back_at: lambda p, c: setattr(p, "meter_on", True),
off_at: lambda p, c: setattr(p, "meter_on", False)})
ing = back_at - 0.3
z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0 and x["now"] > SIL]
want = cyc_t(0, 5, 0, ing + 330.0)
check(f"T6 [{'race' if race else 'plain'}]: the meter back for one "
f"sample at age ~{ret_age}, silent again: no 0 A from the old "
f"silence, the pause at the first step at new own age >= 330 "
f"(t {z[0]['now'] if z else None}, want {want})",
bool(z) and z[0]["now"] == want
and abs(z[0]["age"] - (want - ing)) < 0.05)
# T7, T8: C18, a held read.
for race in (False, True):
tag = "race" if race else "plain"
g0, g1 = (625, 626) if race else (630, 633)
r, st = run_log(go, dur=760, cyc=5, phase=0, race=race,
events={g0: lambda p, c: p.ch.go_unavailable(),
g1: lambda p, c: p.ch.go_unavailable(False)})
s, prev = pause_step(st)
check(f"T7 [{tag}]: the charger read held on the step at 630 (own age "
f"331.3): the 0 A in that step ({s and (s['now'], round(s['age'], 1), s['held'], s['writes'])}), "
f"a NEW 0 A, no phase select, nothing else sent",
s is not None and s["held"] and s["now"] == 630.0
and s["a0"] > 0.0 and s["a1"] == 0.0
and [a for a, _t, _o in s["writes"]] == [0.0] and not s["phases"])
common(f"T7 [{tag}]", r, st)
r, st = run_log(go, dur=760, cyc=5, phase=0, race=race,
events={330: lambda p, c: p.ch.go_unavailable(),
333: lambda p, c: p.ch.go_unavailable(False)})
check(f"T8 [{tag}] (Q3): the charger away on the first silent cycles "
f"(own age 31-34): the pause at own age 331.3",
timing(st, exp_age=331.3) and common(f"T8 [{tag}]", r, st))
r, st = run_log(go, dur=760, cyc=5, phase=0,
events={624: lambda p, c: p.ch.go_unavailable(),
641: lambda p, c: p.ch.go_unavailable(False)})
w = [(t, a) for t, a, _ in cur_writes(r)]
away = [x for x in w if 624 <= x[0] < 641]
after = [x for x in w if x[0] >= 641]
check(f"T9: the charger away 17 s from 624 (own age 325-342): the step at 630 is "
f"a held read (6 s, under stale_input_s), so its pause is C18's one 0 A; "
f"nothing else while away ({away}); no non-zero write on the return "
f"({after[:1]}), the 0 A already standing (D2: 0 A first, kept)",
away == [(630.0, 0.0)] and not [x for x in after if x[1] > 0.0]
and common("T9", r, st))
for ph in (0, 2, 4):
for race in (False, True):
r, st = run_log(go, dur=760, cyc=5, phase=ph, race=race,
events={0: late_at(600, 700)})
t = cyc_t(0, 5, ph, 628.7)
check(f"T10 [{'race' if race else 'plain'} ph{ph}]: late readings (5 s) "
f"over 600-700: the hold branch pauses at own age {t - 298.7:.1f}",
timing(st, exp_age=t - 298.7) and common("T10", r, st))
# =========================================================================== #
print("\n2. PHASES, GAPS, RETURNS (T11-T19)")
# =========================================================================== #
r = S.drive(S.const(500.0), S.const(7600.0), dur=1100, first="car",
socs=dict(FULLB), car_phases=3,
events={276: lambda p, c: setattr(p, "meter_on", False),
800: lambda p, c: setattr(p, "meter_on", True)})
w = cur_writes(r)
seq0 = [t for t, a, _ in w if a == 0.0 and 295 <= t <= 305]
nz = [(t, a) for t, a, _ in w if a > 0.0 and 306 < t < 800]
back = [(t, a) for t, a, _ in w if a > 0.0 and t >= 800]
check(f"T11 (C17 b): a 1 -> 3 change at 301 s with the meter silent from 276: "
f"it ends at its 0 A ({seq0}), no non-zero write 306-800 ({nz}), after "
f"the return only by the start rule ({back[:1]}, >= 920)",
bool(seq0) and not nz and (not back or back[0][0] >= 920 - 1)
and not [x for x in selects(r) if 306 < x[0] < 800])
for race in (False, True):
r, st = run_log(go, onset=320, dur=800, cyc=5, phase=0, race=race,
sun=7600.0, car_phases=3, opts={"ev_phases": "auto"})
s, _ = pause_step(st, since=320)
check(f"T12 [{'race' if race else 'plain'}]: 3-phase car, the meter silent "
f"from 320 s: 3 phases stand; the pause at own age 331.3 (step at 650)",
timing(st, exp_age=331.3, since=320) and common(
"T12", r, st, silent_from=320)
and r["sim"].phases_allowed == 3 and s["now"] == 650.0)
sim13 = TSim(setpoint_a=0, windows=[(335.0, 350.0, "ignore")])
for race in (False, True):
r, st = run_log(go, onset=345, dur=900, cyc=5, phase=0, race=race,
sim=TSim(setpoint_a=0, windows=[(335.0, 350.0, "ignore")]),
sun=lambda t: 3000.0 if t >= 340 else 2300.0)
nzr = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > 345 + 30]
check(f"T13 [{'race' if race else 'plain'}]: an ignored raise to 10 A at "
f"340, the meter silent from 345: no re-send ({nzr}), the pause at "
f"the first step at own age >= 330",
not nzr and timing(st, since=345) and common(
"T13", r, st, silent_from=345))
for n in (1, 2, 6):
r = S.drive(S.const(500.0), S.const(7600.0), dur=700, first="car",
socs=dict(FULLB), car_phases=3,
events={305: lambda p, c: p.ch.go_unavailable(),
305 + n: lambda p, c: p.ch.go_unavailable(False)})
w = cur_writes(r)
close = [(t, a) for t, a, _ in w if a > 0.0 and 301 < t < 700]
check(f"T14 (C19): {n} failed read(s) at 305 s: the closing current on "
f"time ({close[:1]}), no pause",
bool(close) and 312 <= close[0][0] <= 313 + n
and not [1 for t, a, _ in w if 301 < t < 700 and a == 0.0])
# T15: unavailable = nothing ingested (the state is rejected before ingest).
for race in (False, True):
r, st = run_log(go, dur=1000, cyc=5, phase=0, race=race)
check(f"T15 [{'race' if race else 'plain'}]: meter unavailable from 300: "
f"the same age rule as silent", timing(st, exp_age=331.3))
r, st = run_log(go, dur=1000, cyc=5, phase=0, race=race,
events={450: lambda p, c: setattr(p, "meter_on", False),
900: lambda p, c: setattr(p, "meter_on", True)})
z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0 and x["now"] > SIL]
zw = [t for t, a, _ in cur_writes(r) if a == 0.0 and 300 < t < 900]
check(f"T15 [{'race' if race else 'plain'}]: silent, then unavailable at "
f"450, back at 900: unavailable does not reset the age; exactly one "
f"0 A ({zw})", len(zw) == 1 and len(z) == 1
and abs(z[0]["age"] - 331.3) < 0.05 and common(
"T15", r, st, back=900))
# T16: arrival sources keep the cycle's age (and the 15 s + 300 s rule).
ARRIVAL = {}
for src in ("homewizard_local", "mqtt_p1"):
for race in (False, True):
for cyc in (1, 5):
r, st = run_log(go, dur=760, cyc=cyc, phase=0, race=race,
opts={"meter_source": src})
z = [t for t, a, _ in cur_writes(r) if a == 0.0 and t > SIL]
nz16 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > SIL + 30]
ARRIVAL[(src, race, cyc)] = z[:1]
check(f"T16 [{src} {'race' if race else 'plain'} cyc {cyc}]: "
f"arrival source: p1 on {r['c'].p1_enabled}; first 0 A at "
f"{z[:1]} (spare unknown at 15 s, then 300 s), no non-zero "
f"while silent ({nz16})",
r["c"].p1_enabled and not nz16 and bool(z)
and 300 + 15 + 300 - 1 <= z[0] <= 300 + 15 + 300 + 8)
# T17, T18: an add-on restart: a new Controller, the store and charger kept.
for restart_at in (500, 640):
r1, _ = go(dur=restart_at)
n = LOG.mark()
STEPS.clear()
n_dbg = LOG.mark()
r2 = S.drive(S.const(500.0), S.const(2900.0), dur=500, first="car",
socs=dict(FULLB), opts=dict(OPT1), sim=r1["sim"],
store=r1["store"], t0=float(restart_at),
events={restart_at: lambda p, c: setattr(p, "meter_on", False),
restart_at + 300: lambda p, c: setattr(p, "meter_on", True)})
w = [(t, a) for t, a, _ in cur_writes(r2)]
pre = [x for x in w if x[0] < restart_at + 300]
nzr = [x for x in pre if x[1] > 0.0]
after = [x for x in w if x[1] > 0.0 and x[0] >= restart_at + 300]
dl = lines(n_dbg)
none_age = [x for x in dl if x["age"] is None]
check(f"T17: restart at own age {restart_at - 298.7:.0f} with the meter "
f"still silent: the first write before the return is 0 A or none, "
f"the 0 A already standing ({pre[:1]}), 0 "
f"non-zero until it returns ({nzr}), then the start rule "
f"(>= +120: {after[:1]}); the age counts from the first reading: "
f"DEBUG shows age none until then ({len(none_age)} lines)",
(not pre or pre[0][1] == 0.0) and not nzr
and (not after or after[0][0] >= restart_at + 300 + 120 - 1)
and len(none_age) > 0
and not LOG.tracebacks(n))
r1, _ = go(dur=500)
n = LOG.mark()
r2 = S.drive(S.const(500.0), S.const(2900.0), dur=900, first="car",
socs=dict(FULLB), opts=dict(OPT1), sim=r1["sim"],
store=r1["store"], t0=500.0,
events={500: lambda p, c: setattr(p, "meter_on", False)})
check("T18: restart, the meter never returns (900 s): 0 non-zero writes, no "
"Traceback, no 'car charger step failed'",
not [1 for t, a, _ in cur_writes(r2) if a > 0.0]
and not LOG.tracebacks(n)
and not [m for m in LOG.since(n) if "car charger step failed" in m])
for race in (False, True):
r, st = run_log(go, dur=1500, cyc=5, phase=0, race=race,
events={1100: lambda p, c: setattr(p, "meter_on", True)})
nz19 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > 1000]
check(f"T19 [{'race' if race else 'plain'}]: the pause, the meter back at "
f"1100: the first non-zero write {nz19[:1]} within [1220, 1226]",
bool(nz19) and 1220 <= nz19[0][0] <= 1226 and 10.0 <= nz19[0][1] <= 12.0)
# =========================================================================== #
print("\n3. BOUNDS, QUARTER START, OTHER WRITERS (T20-T24)")
# =========================================================================== #
for ma, pm, bound in ((5, 1, 65), (30, 1, 90), (300, 1, 360), (300, 30, 2100)):
for race in (False, True):
r, st = run_log(go, dur=SIL + bound + 120, cyc=5, phase=0, race=race,
opts={"meter_max_age_s": ma, "ev_pause_min": pm})
t = cyc_t(0, 5, 0, 298.7 + bound)
ok = timing(st, bound=float(bound), exp_age=t - 298.7)
check(f"T20 [{ma},{pm}] {'race' if race else 'plain'}: the pause at the "
f"first step at own age >= {bound} ({t - 298.7:.1f}); no non-zero "
f"write past {ma} s",
ok and not n8(st, float(ma)))
r = S.drive(S.const(500.0), S.const(300.0), dur=900, first="car",
socs=dict(FULLB), opts=dict(OPT1),
events={SIL: lambda p, c: setattr(p, "meter_on", False)})
check(f"T21: a paused car (0 W, 0 A) when the meter goes silent: no write at "
f"all ({cur_writes(r)[:2]})", cur_writes(r) == [])
r = S.drive(S.const(500.0), S.const(2900.0), dur=1000, first="car",
socs=dict(FULLB), opts=dict(OPT1),
events={SIL: lambda p, c: setattr(p, "meter_on", False),
310: lambda p, c: p.ch.freeze()})
check(f"T21: a frozen car reading during the silence: nothing non-zero past "
f"30 s of silence ({[(t, a) for t, a, _ in cur_writes(r) if a > 0 and t > 330]})",
not [1 for t, a, _ in cur_writes(r) if a > 0 and t > 330])
r = S.drive(S.const(500.0), S.const(2900.0), dur=760, first="car",
socs=dict(FULLB), opts=dict(OPT1),
events={200: lambda p, c: p.ch.set_current(13),
SIL: lambda p, c: setattr(p, "meter_on", False)})
check(f"T22 (N3): another writer's 13 A at 200, the meter silent from 300: "
f"nothing written over it ({[x for x in r['plant'].sets if x[1] == S.SET and x[0] >= 200]}), "
f"it stands at {r['sim'].setpoint_a}",
not [x for x in r["plant"].sets if x[1] == S.SET and x[0] >= 200]
and r["sim"].setpoint_a == 13.0)
for race in (False, True):
r, st = run_log(go, onset=570, dur=1100, cyc=5, phase=0, race=race)
s, _ = pause_step(st, since=570)
check(f"T23 [{'race' if race else 'plain'}]: silence from 570: the first "
f"step at own age >= 330 is the quarter start t=900 "
f"({s and s['now']}); the peak guard never limits",
timing(st, exp_age=331.3, since=570) and s["now"] == 900.0
and not [x for x in r["trace"] if x["lim"]])
# T24: battery setpoints are the same with the age rule at the cycle's age (the
# base behaviour) as with the step's own age: the car's rules never touch them.
def _sets(r):
return [(t, e, v) for t, e, v in r["plant"].sets if e.startswith("number.sp_")]
_real_own = getattr(Controller, "car_sun_own", None)
for first, sun, soc in (("car", 2900.0, 100.0), ("car", 2900.0, 50.0),
("batteries", 7900.0, 50.0)):
sets = []
for own in (True, False):
if _real_own is not None:
Controller.car_sun_own = _real_own if own else (lambda self, s, n: s)
try:
kw = dict(first=first, sun=sun, dur=760, cyc=5, phase=0, race=True)
STEPS.clear()
r = S.drive(S.const(500.0), S.const(sun), dur=760, first=first,
socs={"a": soc, "b": soc}, opts=dict(OPT1),
events={SIL: lambda p, c: setattr(p, "meter_on", False)},
cyc=5, phase=0, race=True)
finally:
if _real_own is not None:
Controller.car_sun_own = _real_own
sets.append(_sets(r))
sa, sb = sets
sil_a = [x for x in sa if x[0] >= SIL]
sil_b = [x for x in sb if x[0] >= SIL]
check(f"T24 / N5 [{first} first, sun {sun:.0f}, SoC {soc:.0f}]: the batteries' setpoints "
f"are the same on every cycle, and in the silence from {SIL} s, "
f"whichever age the writer step uses ({len(sa)} writes, "
f"{len(sil_a)} in the silence)",
sa == sb and sil_a == sil_b and (soc >= 100.0 or bool(sil_a)))
# =========================================================================== #
print("\n4. DOCS (T26)")
# =========================================================================== #
doc = open(os.path.join(HERE, "DECISIONS", "EV-20-solar-mode.md")).read()
check("T26: DECISIONS states the rule once: 0 A on the first car step whose own "
"meter age is >= meter_max_age_s + ev_pause_min, held steps included; the "
"'(bound 330 s + one cycle)' wording is gone",
"bound 330 s + one cycle" not in doc
and doc.count("EV-51: decided at the step's own meter age") == 1
and "held steps included" in doc)
# =========================================================================== #
print("\n5. THE DEBUG LINE (T28-T34; N9, N10, N11)")
# =========================================================================== #
n = LOG.mark()
r, st = run_log(go, dur=760, cyc=5, phase=0, race=True)
dl = lines(n)
solar_steps = [s for s in st if s["solar"]]
pre = [x for x in dl if x["age"] is not None and x["age"] < 330.0]
at = [x for x in dl if x["age"] is not None and x["age"] >= 330.0]
at0 = nth(at, 0)
check(f"T28: one DEBUG line per Solar writer step ({len(dl)} lines, "
f"{len(solar_steps)} steps); steps under 330: steady or wait-unknown, "
f"write none; the step at own age 331.3: pause, sent 0 A, confirmed; "
f"later steps write nothing",
len(dl) == len(solar_steps) and bool(pre)
and all(x["decision"] in ("steady", "wait-unknown") and x["write"] == "none"
for x in pre if x["t"] > 130)
and present(at0) and at0["decision"] == "pause"
and abs(at0["age"] - 331.3) < 0.05
and at0["write"] == "sent 0 A confirmed"
and all(x["write"] == "none" for x in at[1:]))
check("T28: the line's fields are the record time t and the meter age, the "
"decision word and the write",
all(set(x) == {"t", "age", "decision", "write"} for x in dl))
n = LOG.mark()
r, st = run_log(go, dur=760, cyc=10, phase=3, race=True)
dl = lines(n)
bad = [x for x in dl if x["t"] > SIL + 1 and (
x["age"] is None or abs(x["age"] - (x["t"] - 298.7)) > 0.05)]
check(f"T29: race order, 10 s cycles, phase 3: the logged age is the step's own "
f"(now - 298.7), never the snapshot's (10 s less) ({bad[:1]})",
bool(dl) and not bad and len([x for x in dl if x["t"] > SIL]) > 30)
# T30 / N9: nothing new at info. The records of the run on 5bff894 (measured
# there, pinned): none at INFO or above for this run.
GOOGLE.setLevel(logging.INFO)
try:
n = LOG.mark()
r, st = run_log(go, dur=760, cyc=5, phase=0, race=True)
info = [(lv, m) for lv, m, _x in LOG.rec[n:]]
finally:
GOOGLE.setLevel(logging.DEBUG)
# Measured on 5bff894 (same run, INFO), pinned:
BASE_INFO = [
('INFO', 'maintenance history: moved 5 saved values to one part per inverter: unit/inverter-a/last_completed, unit/inverter-a/last_failed, unit/inverter-a/last_start_attempt, unit/inverter-a/phase, unit/inverter-a/phase_started'),
('INFO', 'Month peak store: fresh start, nothing saved'),
('INFO', "No price history is kept (no durable volume at /data), so missing hours are not filled from yesterday's prices."),
('INFO', 'Price history: unavailable - no durable volume at /data'),
('WARNING', 'No meter reading for over 30 seconds, so control waits and then sets the battery to 0 W.'),
]
check(f"T30 (N9): at INFO the new line is not there ({len(lines(n))} lines) and "
f"the INFO+ records equal the run on 5bff894 ({info[:3]})",
lines(n) == [] and not [m for lv, m in info if "Solar step" in m]
and info == BASE_INFO)
# T31: Nones in the line.
n = LOG.mark()
r, st = run_log(go, onset=0, dur=400, cyc=5, phase=0, race=True)
dl = lines(n)
check(f"T31 (a): no reading since boot: age none ({len(dl)} lines), no failure",
bool(dl) and all(x["age"] is None for x in dl)
and not LOG.tracebacks(n)
and not [m for m in LOG.since(n) if "car charger step failed" in m])
n = LOG.mark()
r, st = run_log(go, dur=400, cyc=5, phase=0,
events={0: lambda p, c: p.ch.go_unavailable()})
check(f"T31 (b): the charger unavailable the whole run: lines still print, no "
f"failure ({len(lines(n))} lines)",
bool(lines(n)) and not LOG.tracebacks(n)
and not [m for m in LOG.since(n) if "car charger step failed" in m])
n = LOG.mark()
r = S.drive(S.const(500.0), S.const(2900.0), dur=500, first="car",
socs=dict(FULLB), opts=dict(OPT1), mode="manual",
events={200: act("car_mode", "solar")})
check(f"T31 (c): Solar engaged after Manual (sent_a None): the line prints "
f"({len(lines(n))} lines), no failure",
bool(lines(n)) and not LOG.tracebacks(n)
and not [m for m in LOG.since(n) if "car charger step failed" in m])
def _same_at_levels(tag, mk):
"""DEBUG vs INFO: the same writes and the same Home Assistant calls (N11)."""
outs = []
for lvl in (logging.DEBUG, logging.INFO):
GOOGLE.setLevel(lvl)
try:
n = LOG.mark()
r = mk()
outs.append((r["plant"].sets, r["raised"], r["sim"].log,
len(lines(n))))
finally:
GOOGLE.setLevel(logging.DEBUG)
return outs
outs = _same_at_levels("T31", lambda: go(dur=300, cyc=5, phase=0, onset=0)[0])
o_dbg, o_inf = outs
same = o_dbg[:3] == o_inf[:3]
check("T31 (N11): no reading since boot: the writes and Home Assistant calls "
"are the same at DEBUG and INFO",
same and o_dbg[3] > 0 and o_inf[3] == 0)
# T32: the pause's 0 A refused.
def _t32(plant_cls=None, sim=None):
return go(dur=760, cyc=5, phase=0, sim=sim, plant_cls=plant_cls)[0]
class RefusePlant(S.SunPlant):
async def set_number(self, e, v):
if e == S.SET and float(v) == 0.0 and 630 <= self.t <= 700:
self.sets.append((self.t, e, float(v)))
return False
return await super().set_number(e, v)
for what, mk in (("the charger ignores it", lambda: _t32(
sim=TSim(setpoint_a=0, windows=[(629.5, 700, "ignore")]))),
("Home Assistant refuses it", lambda: _t32(plant_cls=RefusePlant))):
outs = _same_at_levels("T32", mk)
o_dbg, o_inf = outs
same32 = o_dbg[:3] == o_inf[:3]
GOOGLE.setLevel(logging.DEBUG)
n = LOG.mark()
mk()
sent = [x for x in lines(n) if x["write"].startswith("sent 0 A")
and x["t"] >= 630]
unconf = [x for x in sent if "confirmed" not in x["write"]]
check(f"T32 [{what}]: DEBUG shows 'sent 0 A' without 'confirmed' for each "
f"refused try ({[(x['t'], x['write']) for x in sent[:4]]}); the "
f"writes and Home Assistant calls equal the INFO run (N11)",
bool(unconf) and same32)
# T33 / N10: secrets.
SENT = {"price_service_token": "SENTINEL-TOKEN-3317",
"mqtt_password": "SENTINEL-MQTT-3317", "api_key": "SENTINEL-KEY-3317",
"ha_token": "SENTINEL-HA-3317"}
n = LOG.mark()
r, st = run_log(go, dur=760, cyc=5, phase=0, race=True, opts=dict(SENT))
check("T33 (N10): sentinel values in every secret-like option never reach a "
"log record",
not [m for _lv, m, _x in LOG.rec[n:] if "SENTINEL" in m]
and len(lines(n)) > 0)
# T34: volume.
n = LOG.mark()
r, st = run_log(go, dur=760)
dl = lines(n)
check(f"T34: 1 s cycles, 760 s: the new lines equal the Solar writer steps "
f"({len(dl)} vs {len([s for s in st if s['solar']])}), none per poll",
0 < len(dl) <= 760 and len(dl) == len([s for s in st if s["solar"]]))
# =========================================================================== #
print("\n6. THE HARNESS CADENCE (T35-T39)")
# =========================================================================== #
def _sig(r):
return ([(x["t"], x["a"], x["why"], x["sp"]) for x in r["trace"]],
list(r["sim"].log), list(r["plant"].sets))
for tag, kw in (("silent car-first", dict()),
("batteries first, sun 4.4 kW", dict(first="batteries", sun=4400.0))):
a, _ = go(dur=500, **kw)
b, _ = go(dur=500, cyc=1, phase=0, jitter=None, race=False, **kw)
check(f"T35 [{tag}]: the default call equals an explicit cyc=1, phase=0, "
f"jitter=None, race=False (same trace, writes and sets)",
_sig(a) == _sig(b) and len(a["trace"]) == 500)
for cyc in (5, 10):
badph = []
for ph in range(cyc):
r, st = go(dur=60, cyc=cyc, phase=ph, onset=None)
ts = [x["t"] for x in r["trace"]]
if ts != [float(t) for t in range(ph, 60, cyc)] or [
s["now"] for s in st] != ts:
badph.append((ph, ts[:3]))
check(f"T36: cyc {cyc}, every phase: trace rows and writer steps only at "
f"seconds with (t - t0) mod cyc == phase ({badph[:2]})", not badph)
r, st = go(dur=60, cyc=5, phase=2, onset=20)
check(f"T36: the meter and the charger still tick every second: the meter "
f"samples {r['c'].p1.samples} (20 s on) and {len(r['trace'])} rows",
r["c"].p1.samples == 20 and len(r["trace"]) == 12)
r, st = go(dur=60, jitter=(4, 6, 5), onset=None)
check(f"T37: jitter 4/6/5: rows at {[x['t'] for x in r['trace']][:6]}",
[x["t"] for x in r["trace"]]
== [0.0, 4.0, 10.0, 15.0, 19.0, 25.0, 30.0, 34.0, 40.0, 45.0, 49.0,
55.0])
r, st = go(dur=40, cset=[3, 7, 8, 39, 40, 99], onset=None, t0=0.0)
check(f"T37: an explicit set of cycle seconds: rows exactly at those inside "
f"[t0, t0 + dur) ({[x['t'] for x in r['trace']]})",
[x["t"] for x in r["trace"]] == [3.0, 7.0, 8.0, 39.0])
for race in (False, True):
r, st = go(dur=700, cyc=10, phase=3, race=race)
# (the run's last settle runs one step off the cycle grid: left out)
st2 = [s for s in st if s["solar"] and s["now"] > SIL + 40
and s["snap_age"] is not None and s["now"] % 10 == 3]
d = [round(s["age"] - s["snap_age"], 1) for s in st2]
want = 10.0 if race else 0.0
check(f"T38 [{'race' if race else 'plain'}]: the snapshot's age is the "
f"step's own age minus {want:.0f} s ({sorted(set(d))[:3]})",
bool(st2) and all(abs(x - want) <= 0.05 for x in d))
bads = 0
for kw in (dict(cyc=0), dict(cyc=-5), dict(cyc=5, phase=5), dict(cyc=5, phase=-1),
dict(cset=[900]), dict(cset=[]), dict(jitter=()), dict(jitter=(0,))):
try:
go(dur=20, onset=None, **kw)
except ValueError:
bads += 1
check(f"T39: a cycle length of 0 or less, a phase outside [0, cyc), a set with "
f"no second in the run, an empty jitter: ValueError ({bads} of 8)",
bads == 8)
# =========================================================================== #
print("\n7. THE METER BACK; THE SWEEPS; THE HOLD (T40-T43; N12)")
# =========================================================================== #
r, st = run_log(go, dur=900, cyc=5, phase=0, race=True,
events={630: lambda p, c: setattr(p, "meter_on", True)})
s630 = [s for s in st if s["now"] == 630.0][0]
w40 = [(t, a) for t, a, _ in cur_writes(r) if t > SIL]
check(f"T40: race, the meter back at 630 (sample ingested before the step, "
f"snapshot 625 said silent at {s630['snap_age']:.1f}): own age "
f"{s630['age']:.1f}, no pause, no current write 300-900 ({w40}); the "
f"plan keeps 10 A ({r['c'].car_solar.plan.a})",
abs(s630["age"] - 0.3) < 0.05 and w40 == []
and r["c"].car_solar.plan.a == 10.0 and common("T40", r, st, back=630))
for back_at in (631, 635):
r, st = run_log(go, dur=1100, cyc=5, phase=0, race=True,
events={back_at: lambda p, c: setattr(p, "meter_on", True)})
s, _ = pause_step(st)
nzb = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and t > 630]
check(f"T41: race, the meter back at {back_at}: the 0 A in the step at 630 "
f"(own age {s and round(s['age'], 1)}); after the return only the "
f"start rule ({nzb[:1]}, >= {back_at + 120})",
timing(st, exp_age=331.3) and s["now"] == 630.0
and (not nzb or nzb[0][0] >= back_at + 120 - 1))
def sweep(kind, cyc, race, onsets):
"""T42: the silence onset swept; the non-zero writes at a step whose own
age is > 30."""
hits = []
for s in onsets:
if kind == "starts":
r, st = go(onset=s, dur=s + 120, cyc=cyc, phase=0, race=race)
else:
r, st = go(onset=s, dur=min(s + 130, 760), cyc=cyc, phase=0,
race=race,
sun=lambda t: 4400.0 if t >= 200 else 2900.0)
b = n8(st)
if b:
hits.append((s, b[0]))
return hits
for cyc in (5, 10):
for race in (False, True):
h = sweep("starts", cyc, race, range(60, 126))
check(f"T42 starts [{cyc} s {'race' if race else 'plain'}]: a start due "
f"just after the silence onset (onset 60-125): 0 of 66 onsets "
f"with a non-zero write at own age > 30 ({len(h)}: {h[:2]})",
not h)
for race in (False, True):
h = sweep("raises", 5, race, range(200, 330))
check(f"T42 raises [5 s {'race' if race else 'plain'}]: a raise due "
f"(sun 4.4 kW from 200), onset 200-329: 0 of 130 onsets with a "
f"non-zero write at own age > 30 ({len(h)}: {h[:2]})", not h)
for l0, want in ((598, 915.0), (602, 920.0)):
for race in (False, True):
r, st = run_log(go, onset=None, dur=1100, cyc=5, phase=0, race=race,
events={0: late_at(l0, 1000)})
z = [x for x in st if x["a0"] > 0.0 and x["a1"] == 0.0]
nz43 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and 600 <= t < 1000]
cross = [s for s in st if s["now"] >= l0 + 15][0]
check(f"T43 (a) [L0 {l0} {'race' if race else 'plain'}]: running at 10 A, "
f"late from {l0}: the crossing step (own late >= 15) takes the "
f"stale rule, the 0 A at {z[0]['now'] if z else None} "
f"(want {want}); no non-zero write 600-1000 ({nz43})",
bool(z) and z[0]["now"] == want and not nz43)
n = LOG.mark()
run_log(go, onset=None, dur=640, cyc=5, phase=0, race=race,
events={0: late_at(l0, 1000)})
dl = lines(n)
cr = [x for x in dl if x["t"] == float(cross["now"])]
before = [x for x in dl if x["t"] == float(cross["now"]) - 5]
check(f"T43 (a) DEBUG [{'race' if race else 'plain'} L0 {l0}]: the step "
f"before the crossing holds, the crossing step does not "
f"({before and before[0]['decision']} -> {cr and cr[0]['decision']})",
bool(cr) and bool(before) and before[0]["decision"] == "hold"
and cr[0]["decision"] == "wait-unknown")
for l0 in (101, 103, 105):
for race in (False, True):
r, st = run_log(go, onset=None, dur=500, cyc=5, phase=0, race=race,
events={0: late_at(l0, 400)})
nz43 = [(t, a) for t, a, _ in cur_writes(r) if a > 0.0 and 116 <= t < 400]
cross = [s for s in st if s["now"] >= l0 + 15][0]
check(f"T43 (b) (N12) [L0 {l0} {'race' if race else 'plain'}]: paused "
f"with a start due, late from {l0}: the crossing step at "
f"{cross['now']} writes nothing ({cross['writes']}) from its "
f"snapshot ({cross['snap_tgt']} W); no non-zero write 116-400 "
f"({nz43})", cross["now"] == 120.0 and not cross["writes"]
and not nz43)
# T44 (C23, PM): a start due just after the silence begins. No plan start and
# no non-zero write from data the step's own age calls old (> 30 s); after the
# meter returns the start comes only from a fresh reading, with its dwell.
def _c23(cyc):
bad = []
for onset in range(88, 100):
back = onset + 60
r, st = run_log(go, onset=onset, dur=back + 200, cyc=cyc, phase=0,
race=True,
events={back: lambda p, c: setattr(p, "meter_on", True)})
stale_start = [(x["now"], round(x["age"], 1)) for x in st
if x["age"] is not None and x["age"] > 30.0
and x["a0"] <= 0.0 < x["a1"]]
nzw = [(x["now"], w[0], x["snap_tgt"]) for x in st for w in x["writes"]
if w[0] > 0.0]
late_nz = [x for x in nzw if x[2] is None] # from a None target
if stale_start or n8(st) or late_nz:
bad.append((onset, stale_start[:1], nzw[:1]))
return bad
for cyc in (5, 10):
bad = _c23(cyc)
check(f"T44 (C23) [{cyc} s race]: a start due just after the silence "
f"(onset 88-99, back 60 s later): no plan start at own age > 30, no "
f"non-zero write from old data; the start only from a fresh reading "
f"(a start at own age <= 30 is the normal dwell) ({len(bad)} bad: {bad[:2]})", not bad)
report()
+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()