OPT-34: the night charge keeps its level when the kept forecast ends
checks / unit (pull_request) Successful in 18m59s
infra-pin / fresh (pull_request) Successful in 1s

With the forecast sensors silent from 17:05 the kept evening figure ended at
midnight + 3 h, in the middle of the night grid charge, and Leftover solar's
planned level went with it (rig: A 49.8 % against 79.9 %).

- A night grid charge that has started keeps its planned level when the forecast
  goes (Controller._latch_charge, store key night_charge_latch), and the narrow
  price gap with it (weather_held). A fresh figure still moves the level.
- The evening's tomorrow figure is today's until the bell starts (06:00 local),
  up to 15 h old but only if it was usable at midnight (solarfc.Hold.stand_in).
- Screen: "No solar forecast now. The charge under way goes on to its planned
  level." (EN/NL) while a latched battery is below its level.
- test_opt34.py (whole nights through the real control cycle, mutants), test_opt27
  and test_modes_p4 adjusted to the new window and the kept level.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Bdqr7PiaHcBnzPituu2yTC
This commit is contained in:
glenn schrooyen
2026-10-31 17:00:31 +01:00
co-authored by Claude
parent deee98d352
commit 412e47f111
12 changed files with 783 additions and 64 deletions
+71 -5
View File
@@ -211,9 +211,30 @@ HOUSE_PROFILE_KEY = "house_profile"
# OPT-27: the forecast sensors' last fresh readings (`solarfc.Hold`), so an
# evening restart keeps the figure the night plan uses.
FC_HOLD_KEY = "solar_fc_hold"
# OPT-34: the level of a night grid charge that has started, so it does not
# drop when the forecast goes (`Controller._latch_charge()`).
CHARGE_LATCH_KEY = "night_charge_latch"
# OPT-34: a latch outlives the cheap run it was last used in by one price
# slot, because the next run is planned at the slot edge, in the cycle after
# the old one ended.
CHARGE_LATCH_GRACE_S = 900.0
FORECAST_READ_S = 60.0
def _load_latch(data):
"""`(until, {name: level %})` from the store, or None if it is not a
well-formed latch (OPT-34)."""
try:
until = datetime.fromisoformat(data["until"])
levels = {str(n): float(v) for n, v in data["levels"].items()}
except (TypeError, KeyError, ValueError, AttributeError):
return None
if until.tzinfo is None or not levels or not all(
math.isfinite(v) and 0.0 <= v <= 100.0 for v in levels.values()):
return None
return until, levels
def why_raised(resolution, claims) -> bool:
"""F2 (OPT-11 P1 test): did the limit that bound the site target push it
ABOVE what the winner asked (the peak floor asking for more power)? Then
@@ -1005,6 +1026,9 @@ class Controller:
(getattr(store, "data", None) or {}).get(FC_HOLD_KEY))
self.day_plan = None
self._plan_targets = None
# OPT-34: `(until, {name: level %})` of a night charge under way.
self._charge_latch = _load_latch(
(getattr(store, "data", None) or {}).get(CHARGE_LATCH_KEY))
self.house_profile = None
if self.fc_entity is not None:
self.house_profile = dayplan.HouseProfile(
@@ -2265,9 +2289,13 @@ class Controller:
def weather_held(self, now) -> bool:
"""TARIFF-24: no forecast now, but a run planned with one is under
way: it keeps its gap to its end. The wider gap applies from the next
run. Pure; Home asks the same (`homeview.trade_verdict()`)."""
return (self.solar_fc is None and self._wx_free_to is not None
and now < self._wx_free_to)
run. OPT-34: a night charge that keeps its level (`_latch_charge()`)
keeps the gap too, run after run, or the next slice of it would be
refused. Pure; Home asks the same (`homeview.trade_verdict()`)."""
return self.solar_fc is None and (
(self._wx_free_to is not None and now < self._wx_free_to)
or (self._charge_latch is not None
and now < self._charge_latch[0]))
def _price_runs(self, now, packs, floor_pct, ceiling_pct):
"""The kept run plan, rebuilt at most once per price slot (15 min) or
@@ -2352,11 +2380,48 @@ class Controller:
def plan_targets(self):
"""P4: each battery's planned level, or None (no day plan). Dropped
at once when the forecast goes (stale or missing)."""
at once when the forecast goes (stale or missing), except the level
of a night charge that has started (OPT-34): it keeps that level."""
if self.solar_fc is None:
return None
lt = self._charge_latch
return None if lt is None else dict(lt[1])
return self._plan_targets
def _latch_charge(self, now, runs, targets) -> None:
"""OPT-34, once per cycle after `modetrade.decide()`. A night grid
charge that has started keeps its planned level when the forecast goes
mid-charge (the kept figure ends and the sensors are still silent).
While there is a forecast, fresh or kept, each battery that charges
from the grid in the cheap run takes its planned level into the latch;
a fresh figure moves it up or down, as it moves the plan. While there
is none, `plan_targets()` gives the latched levels, so the charge goes
on to them, and `weather_held()` keeps the narrow price gap. The latch
lasts through every cheap run on and one price slot after the last
(`CHARGE_LATCH_GRACE_S`); a charge that never started has none."""
old = lt = self._charge_latch
tick = self.mode_tick
run = None if runs is None else runs.cheap
in_run = run is not None and run.holds(now)
if lt is not None:
if in_run:
lt = (max(lt[0], run.end + timedelta(
seconds=CHARGE_LATCH_GRACE_S)), lt[1])
elif now >= lt[0]:
lt = None
if (in_run and self.solar_fc is not None and targets
and tick is not None and tick.action == modetrade.CHARGE):
lv = dict(lt[1]) if lt is not None else {}
lv.update({n: float(targets[n]) for n, r in tick.roles.items()
if r == modetrade.CHARGE and n in targets})
if lv:
until = run.end + timedelta(seconds=CHARGE_LATCH_GRACE_S)
lt = (max(until, lt[0]) if lt is not None else until, lv)
if lt != old:
self._charge_latch = lt
self.store.set(CHARGE_LATCH_KEY, None if lt is None else {
"until": lt[0].isoformat(), "levels": lt[1]})
def _mode_roles(self, now, maint_results):
"""OPT-11 P3: each battery's role and range this tick. Grid charging
and selling need a fresh plan that `TariffPlan.arbitrage()` allows
@@ -2429,6 +2494,7 @@ class Controller:
blocked=self._charge_blocked_q == quarter,
done_charge=done_c, done_sell=done_s, targets=targets,
draining=any(r.phase == DRAIN for r in maint_results or ()))
self._latch_charge(now, runs, targets)
# A charge the guard or the headroom stopped stays off this period.
# OPT-15: only a MEASURED stop latches; the first unmeasured headroom
# (None) in a quarter stops this tick only, so a gap cannot cost the