Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2f55732b6 | ||
|
|
956711b801 | ||
|
|
88b9cd470a | ||
|
|
1bf6b7f9a7 | ||
|
|
1d28daf8a0 | ||
|
|
0b6b34f563 | ||
|
|
08fb1235fc | ||
|
|
7ef73474dc | ||
|
|
2f5ab1f378 | ||
|
|
fbdd552555 | ||
|
|
02c0a3dd7b |
@@ -0,0 +1,67 @@
|
||||
# MAINT-10 — the maintenance start hour is local time, default 19:00
|
||||
|
||||
Owner decision 2026-09-29 (option A). `maintenance_start_hour` was compared
|
||||
with the UTC hour, so the shipped 10 started at 12:00 in a Belgian summer and
|
||||
11:00 in winter. It is now read on the site's local clock, and the default moves
|
||||
to 19 so the drain runs into the evening and night rather than the solar day.
|
||||
|
||||
Evening drains meet higher house loads; SAFETY-83 (merged first) lets the
|
||||
peak guard outrank the drain.
|
||||
|
||||
## 1. Which zone
|
||||
|
||||
Home Assistant's `time_zone` (`GET /core/api/config`, 3 s budget) at startup,
|
||||
else the container's `TZ`, else UTC. One log line says which (WARNING only for
|
||||
UTC). Resolved once per start: a zone change in HA takes effect on the next
|
||||
add-on restart. HA can still be starting when the add-on starts (502 from the
|
||||
proxy, 2026-10-05); then `TZ` holds. HA pushes its zone to the Supervisor
|
||||
(hassio `push_config`), which stores it and sets it as the add-on's `TZ`
|
||||
(`docker/app.py`, Supervisor 2026.08.0), so the hour stays right. Only a `TZ` of
|
||||
UTC there logs a WARNING asking for a restart. No later re-resolve: the fallback
|
||||
already is HA's zone, so the rare UTC case gets a warning rather than more code.
|
||||
The add-on image has tzdata (checked in `amd64-base:3.20`); the CI image does
|
||||
not, so the tests grade DST on `tariff._EUTimezone` too.
|
||||
|
||||
## 2. DST
|
||||
|
||||
`maintenance.in_start_slot()` works from UTC instants only, so it does not
|
||||
depend on how a tzinfo resolves a missing or doubled wall time:
|
||||
|
||||
- normally the slot is the local hour `start_hour`;
|
||||
- clocks forward and the hour does not exist: the first hour after the jump;
|
||||
- clocks back and the hour happens twice: the first pass only. Without this an
|
||||
aborted start (90 min cooldown) would start again in the 120 min repeated hour.
|
||||
|
||||
Every day has exactly one 60 min slot for every hour 0-23: checked against
|
||||
zoneinfo for Europe/Brussels, America/New_York, America/Santiago (midnight
|
||||
transitions), Asia/Kathmandu (+05:45) and Australia/Lord_Howe (30 min DST)
|
||||
over all of 2026.
|
||||
|
||||
## 3. Existing installs
|
||||
|
||||
The Supervisor merges the shipped defaults under the STORED options, and saving
|
||||
the settings stores every key (the reference install's blob has all 76). So
|
||||
almost every existing install keeps its stored 10, which now means 10:00 local
|
||||
instead of 12:00 (summer) or 11:00 (winter). Only a blob without the key gets 19.
|
||||
The add-on does not rewrite a stored option: a silent migration would override
|
||||
an operator's choice with no way to tell it apart from the old default. A site
|
||||
that set an earlier hour to make up for UTC (17 for 19:00 summer) must set it
|
||||
back to 19 after the upgrade, or it starts two hours early. DOCS and the release
|
||||
note (drafted on the PR, for the version bump) say this.
|
||||
`tools/supervisor_shape_probe.py` §I measures this on Supervisor 2026.08.0.
|
||||
|
||||
## 4. Two inverters
|
||||
|
||||
`Controller` hands the same zone to every pack's `Maintenance`, so every pack's
|
||||
`wants_start()` reads the local hour. `arbitrate()` is unchanged: one pack
|
||||
cycles at a time, and the one that lost the slot starts in the first start
|
||||
slot after the other is done (a later day: a cycle outlasts its start hour). On the day the clocks go back, a pack freed during the second pass of
|
||||
a repeated hour does not start there. `test_maint10.py` part 10.
|
||||
|
||||
## 5. What does not change
|
||||
|
||||
Only the start decision (`Maintenance.wants_start`) and the Home screen's shown
|
||||
start time read the zone. `test_maint10.py` parts 9 and 10 run the real
|
||||
Controller at N=1 and N=2 with start hour 11 UTC against 13 Europe/Brussels (the
|
||||
same instant): every command, claim, reason and log line is identical. A
|
||||
`Maintenance` built without a zone reads UTC, as before.
|
||||
@@ -0,0 +1,59 @@
|
||||
# SAFETY-96 - a battery the loop cannot move does not freeze it
|
||||
|
||||
**Status: implemented 2026-10-06, for review.** Tests: `test_safety96.py`.
|
||||
|
||||
**The defect** (SAFETY-93 rig test). At N=2 the saturation freeze compares
|
||||
the site target with the site sum of the readings. After A's link went
|
||||
stale, A was out of the split but its reading (-2000 W, still charging) was
|
||||
in the sum: "saturation freeze (800 W vs -1903 W)", B held at 1200 W for
|
||||
~236 cycles until the circulation trip. After a charge timeout or Off at
|
||||
6000 W the loop froze ~14 s at 800 W while A came out of its charge. At a
|
||||
drop, B also took A's whole share in one step.
|
||||
|
||||
**The rule** (`main.py`, `_held_out_w()`, `_reseed_drop()`, N>=2 only).
|
||||
A battery is held out of the freeze test, counted at its command instead of
|
||||
its reading, while:
|
||||
|
||||
- it is out of the split (writes refused for `LINK_STALE_S`);
|
||||
- its last write was refused (its board may have gone to 0 W on its own
|
||||
watchdog);
|
||||
- it settles after a step the loop did not make: a charge end (SAFETY-93:
|
||||
HOLD, timeout, Off, refusal, stale link) or a rejoin (then every battery,
|
||||
as the split is made again). Settling ends when its reading is within the
|
||||
deadband of its command, or after `PLANT_SETTLE_DOWN_S` (23 s, the
|
||||
measured plant settle).
|
||||
|
||||
Its real power is not lost and not counted twice: the meter sees it, and
|
||||
the loop follows the meter. Only the freeze stops reading it as the loop's.
|
||||
The freeze still fires on the other batteries' own lag and on unplaced
|
||||
watts.
|
||||
|
||||
At a drop the battery's share leaves the loop's start point, so the others
|
||||
take over one slew step a cycle. At a rejoin it enters at its reading.
|
||||
|
||||
**Not a drop.** A missing reading or a stale register stops the site
|
||||
(`inputs_ok`), as before. A refused battery (SAFETY-73) stays in the sum:
|
||||
it is asked ~0 W and reads ~0 W. A watchdog-stopped battery (SAFETY-02/30)
|
||||
is pinned at 0 W and stays in the sum. New: no refusal is learned on a
|
||||
battery whose writes are refused; its board going to 0 W is no refusal. Its
|
||||
count is kept, not reset, so a link that refuses 1 write in 3 does not hide
|
||||
a battery that really refuses (review).
|
||||
|
||||
**Before -> after** (2 x 2500 W, 10 s lag, 2 s meter; freeze cycles not
|
||||
about the remaining battery's own lag):
|
||||
|
||||
| case | before | after |
|
||||
|---|---|---|
|
||||
| A drops while giving, A holds 1200 W | 128, B steps 1210 W | 0, B stays |
|
||||
| A drops while charging, A holds -2000 W | 78 | 0 (circulation trip stays: 4 kW goes round) |
|
||||
| A drops while charging, board to 0 W | 5 | 0 |
|
||||
| A drops then comes back, A holds 1200 W | 46, grid +1.1 kW | 0, grid within 250 W |
|
||||
| charge timeout at 6000 W | 7, B held at 400 W | 0, B climbs |
|
||||
| A switched Off at 6000 W | 6, B held at 800 W | 0, B climbs |
|
||||
| N=1, N=2 with no drop | | byte-identical |
|
||||
|
||||
**Not changed.** At a rejoin the allocator splits again at once (A 0 ->
|
||||
1205, B 2410 -> 1205 W); the site total does not step. A battery that keeps
|
||||
charging on its own after its link drops still trips the circulation check
|
||||
(it is real circulation). A trade end (`_reseed_run_edge`) still starts
|
||||
from the full site sum.
|
||||
@@ -230,7 +230,7 @@ The label and description each setting shows on the Configuration tab, in tab or
|
||||
| Tariff | Trading charges at most (%) | `arbitrage_soc_ceiling` | Price trading will not charge the battery above this level. |
|
||||
| Maintenance | Run the monthly battery cycle | `maintenance_enabled` | Once a month, empty the battery deeply, charge it full and hold it there, so its level reading stays accurate. Off by default. |
|
||||
| Maintenance | Minimum days between cycles | `maintenance_interval_days` | The shortest gap between two maintenance cycles. |
|
||||
| Maintenance | Start hour | `maintenance_start_hour` | The local hour, 0 to 23, at which a due cycle starts. |
|
||||
| Maintenance | Start hour (local time) | `maintenance_start_hour` | The hour on your local clock, 0 to 23, when a due cycle starts. 19 means 19:00. |
|
||||
| Maintenance | Draw-down rate (W) | `maintenance_discharge_w` | How fast the cycle empties the battery. Above “Inverter rating” it is cut back to the rating, and the cycle just takes longer. |
|
||||
| Maintenance | Recharge rate (W) | `maintenance_charge_w` | How fast the cycle recharges the battery. It must be at or below “Inverter rating”, or the add-on will not start. |
|
||||
| Maintenance | Draw down to (%) | `maintenance_soc_floor` | The level the monthly cycle empties the battery to. It is not the “Peak reserve”, and the two differ on purpose. |
|
||||
@@ -1643,13 +1643,30 @@ help - see "Why the tuning is what it is".
|
||||
|---|---|---|
|
||||
| `maintenance_enabled` | false | Enable the monthly cycle |
|
||||
| `maintenance_interval_days` | 28 | Minimum gap between cycles |
|
||||
| `maintenance_start_hour` | 10 | Hour of day a due cycle begins |
|
||||
| `maintenance_start_hour` | 19 | Local hour a due cycle begins (see below) |
|
||||
| `maintenance_discharge_w` | 2000 | Drain rate (exports the surplus). The peak guard may ask for more (SAFETY-83; at N≥2 while another battery is at its peak reserve, SAFETY-87), and at N≥2 so may the house while another battery is at its peak reserve (SAFETY-91). Above `max_w` it is **clamped** to `max_w` — the drain phase SETs the setpoint and the arbiter bounds it, saying so on the status page (`limited by supervised(max_w)`). Warned about, not refused: the cycle still completes, just slower |
|
||||
| `maintenance_charge_w` | 2000 | Charge ceiling, capped again by peak headroom. Must stay **at or below `max_w`** or the cheap-window shaping (`hi = -maintenance_charge_w`) contradicts the supervised limit (`lo = -max_w`), the arbiter resolves it to **0 W**, and maintenance silently never charges in a cheap window — **the add-on refuses to start** |
|
||||
| `maintenance_soc_floor` | 11 | Drain target — stay just above the inverter's own floor. ⚠️ **This is not `peak_soc_floor`.** It is the depth the monthly recalibration deliberately goes to, once, on purpose; `peak_soc_floor` is the depth a money-saving discharge may never reach on any day. The right values differ (11 vs 20 as shipped), which is why they are two keys |
|
||||
| `maintenance_soc_target` | 99 | Charge target |
|
||||
| `maintenance_hold_min` | 120 | Hold at full so the BMS can balance |
|
||||
|
||||
**The start hour is local time.** The add-on reads Home Assistant's time zone
|
||||
(Settings → System → General) at startup. If Home Assistant does not answer,
|
||||
it uses the add-on's own time zone, and failing that UTC. The log says which
|
||||
one it used, and warns if it is UTC: then restart the add-on once Home Assistant
|
||||
is up. On the day the clocks go forward, a start hour that does not exist
|
||||
starts at the first hour after the jump. On the day they go back, a repeated
|
||||
hour starts only once, in its first pass. With two inverters both batteries use
|
||||
the same local hour; one cycles at a time, and the other starts at that hour on
|
||||
a later day.
|
||||
|
||||
**Upgrading.** The hour used to be read as UTC. An existing install keeps its
|
||||
saved hour, and that hour now means local time: a saved 10 now starts at 10:00,
|
||||
not 12:00 in summer. The new default, 19, only reaches installs that have no
|
||||
hour saved. If you set an earlier hour to get an evening start in UTC (for
|
||||
example 17 for 19:00 in summer), set it to 19. The add-on never changes a saved
|
||||
value. *For installers:* DECISIONS/MAINT-10-local-start-hour.md.
|
||||
|
||||
### Tariff (all optional)
|
||||
|
||||
| option | meaning |
|
||||
@@ -1683,6 +1700,8 @@ batteries the other one gives first. The hold still ends on its clock
|
||||
(SAFETY-86).
|
||||
When a charge ends, the other batteries take over one slew step a cycle,
|
||||
and none starts charging from the grid (SAFETY-93).
|
||||
When a battery's link drops, the others take over one slew step a cycle,
|
||||
and control does not stall on the dropped battery's power (SAFETY-96).
|
||||
|
||||
#### Capacity-tariff exposure of the grid-following loop
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ from datetime import datetime, timedelta, timezone
|
||||
|
||||
from . import arbitrage, messages, peakguard, uitext
|
||||
from .maintenance import CHARGE as M_CHARGE, DRAIN as M_DRAIN, HOLD as M_HOLD
|
||||
from .maintenance import IDLE as M_IDLE
|
||||
from .maintenance import IDLE as M_IDLE, next_slot_start
|
||||
from .packmode import CHEAP_HOURS, GRID_CHARGE_MODES, LEFTOVER_SOLAR, SOLAR_FIRST
|
||||
from .price import Absence, Uncertainty, brussels
|
||||
from .static_tariff import static_plan
|
||||
@@ -439,8 +439,8 @@ def solar_block(c, now):
|
||||
|
||||
def maintenance_runs(c, day0, day1, now, shadow):
|
||||
"""The monthly battery cycle: under way now, or starting later today.
|
||||
The cycle starts in the hour `maintenance_start_hour` names, read as the
|
||||
control cycle reads it (UTC hour of `now`), shown in local time."""
|
||||
The cycle starts in the hour `maintenance_start_hour` names, read in the
|
||||
site's zone exactly as the control cycle reads it (MAINT-10)."""
|
||||
runs, lines = [], []
|
||||
waiting = []
|
||||
for i, (inv, m) in enumerate(zip(c.inverters, c.maints)):
|
||||
@@ -459,10 +459,9 @@ def maintenance_runs(c, day0, day1, now, shadow):
|
||||
if not m.due(now) and (m.next_due(now) is None
|
||||
or m.next_due(now) >= day1):
|
||||
continue
|
||||
start = now.replace(hour=cfg.start_hour, minute=0, second=0,
|
||||
microsecond=0)
|
||||
if start + timedelta(hours=1) <= now:
|
||||
start += timedelta(days=1)
|
||||
start = next_slot_start(now, cfg.start_hour, m.tz)
|
||||
if start is None:
|
||||
continue
|
||||
due_at = m.next_due(now)
|
||||
if due_at is not None and due_at > start:
|
||||
continue
|
||||
|
||||
@@ -30,6 +30,7 @@ import functools
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import signal
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
@@ -68,7 +69,7 @@ from . import messages
|
||||
from .freeze import (
|
||||
FreezeWatchdog, FreezeWatchdogConfig, looks_frozen, rail_unreachable, rail_w,
|
||||
)
|
||||
from .hass import HomeAssistant
|
||||
from .hass import CORE_API, HomeAssistant
|
||||
# ⚠️ `LINK_STALE_S` IS RE-EXPORTED DELIBERATELY. `live_units()` reasons about it
|
||||
# and two checks read `app.main.LINK_STALE_S` to build a stale link, so the
|
||||
# window an operator would look up here is the one the roster actually uses.
|
||||
@@ -76,7 +77,7 @@ from .inverter import (LINK_STALE_S, UNIT_A, build_roster,
|
||||
roster_entries, roster_names)
|
||||
from .maintenance import (
|
||||
CHARGE, DRAIN, HOLD, IDLE, POWER_MOVING, MaintConfig, Maintenance,
|
||||
MaintResult, arbitrate as maint_arbitrate,
|
||||
MaintResult, arbitrate as maint_arbitrate, site_zone,
|
||||
)
|
||||
from .mqtt import (MODE_CONFIGS_KEY, MODE_LABELS, USE_OFF, USE_ON,
|
||||
MqttPublisher, announced_units, mode_configs,
|
||||
@@ -424,7 +425,8 @@ def arbitrage_row(*, on: bool, decision, decided_at, cycle_at, now,
|
||||
class Controller:
|
||||
def __init__(self, opts: dict, hass: HomeAssistant, store, mqtt_pub, *, stop,
|
||||
peak_db_path: str = "/data/tariff.db",
|
||||
price_history_path: str = "/data/price_history.json"):
|
||||
price_history_path: str = "/data/price_history.json",
|
||||
site_tz=None):
|
||||
# UX-15: a read-only HomeAssistant belongs to setup-only mode, which
|
||||
# builds no controller. Refused here so no controller can hold one.
|
||||
if getattr(hass, "read_only", False) is True:
|
||||
@@ -665,7 +667,8 @@ class Controller:
|
||||
name=inv.name,
|
||||
# The rollback view, and only ever the first pack's: the flat
|
||||
# keys mean `inverters[0]` on every install that has them.
|
||||
mirror_flat=(not _one_pack and i == 0))
|
||||
mirror_flat=(not _one_pack and i == 0),
|
||||
tz=site_tz) # MAINT-10: the start hour's zone, from amain()
|
||||
for i, inv in enumerate(self.inverters)]
|
||||
|
||||
# SAFETY-02. ONE INSTANCE PER ACTUATOR - which is what watchdog.py's own
|
||||
@@ -1022,6 +1025,12 @@ class Controller:
|
||||
# cycle, and those whose charge ended since the loop last ran.
|
||||
self._charging_was = frozenset()
|
||||
self._charge_ended = frozenset()
|
||||
# SAFETY-96: last cycle's commandable batteries, this cycle's start
|
||||
# point per battery where a reseed moved it, and batteries settling
|
||||
# after a step the loop did not make ({name: since, monotonic}).
|
||||
self._live_was = None
|
||||
self._loop_start = {}
|
||||
self._settle = {}
|
||||
# Set by amain() once the transport is built, so the status page can show
|
||||
# what only the transport knows (homewizard_local's unchanged_s). Stays
|
||||
# None when P1 is off, or under a transport that has no such counter.
|
||||
@@ -1390,6 +1399,12 @@ class Controller:
|
||||
self._unit_refusal_end(
|
||||
inv, "the battery takes power the other way")
|
||||
continue
|
||||
if inv.rejected_since is not None:
|
||||
# SAFETY-96: its writes are refused, so its board may have
|
||||
# gone to 0 W on its own; that is no refusal by the battery.
|
||||
# The count is kept, as across a gap, so a link that refuses
|
||||
# now and then does not hide a battery that does refuse.
|
||||
continue
|
||||
sign = self._gave_nothing(inv)
|
||||
if sign:
|
||||
self._unit_refusal_start(
|
||||
@@ -2453,9 +2468,69 @@ class Controller:
|
||||
continue
|
||||
now_w = (float(res.setpoint_w or 0.0) if res.owns_setpoint
|
||||
else max(float(inv.target), 0.0))
|
||||
if not inv.is_live(datetime.now(timezone.utc))[0]:
|
||||
now_w = 0.0 # SAFETY-96: out of the split, it is sent 0 W
|
||||
self.target += now_w - float(inv.target)
|
||||
# SAFETY-96: it settles from its charge to that command.
|
||||
self._loop_start[inv.name] = now_w
|
||||
self._settle[inv.name] = self._now_mono
|
||||
self.i_w = self.target
|
||||
|
||||
def _reseed_drop(self, live) -> None:
|
||||
"""SAFETY-96, N>=2: a battery that drops out of the split (stale
|
||||
link) leaves the loop's start point, so the others take over at one
|
||||
slew step a cycle instead of taking its share at once. One that comes
|
||||
back enters it at its reading, and every battery settles while the
|
||||
split is made again (`_held_out_w`).
|
||||
DECISIONS/SAFETY-96-dropped-battery.md.
|
||||
"""
|
||||
was, self._live_was = self._live_was, frozenset(live)
|
||||
if len(self.inverters) < 2 or was is None or was == live:
|
||||
return
|
||||
for inv in self.inverters:
|
||||
if inv.name in self._charge_ended:
|
||||
continue # SAFETY-93's edge: `_reseed_charge_end()`
|
||||
if inv.name in was and inv.name not in live:
|
||||
now_w = 0.0
|
||||
elif inv.name in live and inv.name not in was:
|
||||
now_w = float(inv.batt)
|
||||
# The split is made again, so every battery's command steps.
|
||||
self._settle.update(
|
||||
{u: self._now_mono for u in live})
|
||||
else:
|
||||
continue
|
||||
self.target += now_w - float(inv.target)
|
||||
self._loop_start[inv.name] = now_w
|
||||
self.i_w = self.target
|
||||
|
||||
def _held_out_w(self, live) -> float:
|
||||
"""SAFETY-96, N>=2: what to add to the site sum so that a battery
|
||||
the loop cannot move right now counts at its command, not at its
|
||||
reading. That is a battery out of the split, one whose writes are
|
||||
refused, or one settling after a step the loop did not make (a charge
|
||||
end, a rejoin) until its reading is within the deadband of its
|
||||
command or PLANT_SETTLE_DOWN_S has passed. Its real power still
|
||||
reaches the loop through the meter, so it is neither lost nor counted
|
||||
twice; only the saturation freeze stops seeing it as the loop's.
|
||||
"""
|
||||
if len(self.inverters) < 2:
|
||||
return 0.0
|
||||
out = 0.0
|
||||
for inv in self.inverters:
|
||||
cmd = self._loop_start.get(inv.name, float(inv.target))
|
||||
since = self._settle.get(inv.name)
|
||||
age = (None if since is None or self._now_mono is None
|
||||
else self._now_mono - since)
|
||||
if since is not None and (
|
||||
age is None or age >= _ctl.PLANT_SETTLE_DOWN_S
|
||||
or (age > 0 and abs(float(inv.batt) - cmd)
|
||||
< self.tuning.deadband_w)):
|
||||
del self._settle[inv.name]
|
||||
if (inv.name not in live or inv.rejected_since is not None
|
||||
or inv.name in self._settle):
|
||||
out += cmd - float(inv.batt)
|
||||
return out
|
||||
|
||||
def _mode_fault_log(self, resolution) -> None:
|
||||
"""OPT-11: say once, per battery, that its mode was dropped as a fault.
|
||||
|
||||
@@ -4727,6 +4802,8 @@ class Controller:
|
||||
mode_trade = self._mode_trade(claims, now)
|
||||
self._mode_trade_was = mode_trade
|
||||
self._charge_track(claims, maint_results)
|
||||
_live96 = set(self.live_units())
|
||||
self._loop_start = {}
|
||||
if (self.auto or self.shadow) and self.inputs_ok:
|
||||
# ⚠️ prev is the ARBITER's last output, not the loop's own last
|
||||
# wish. If something outranked the loop, that is what the hardware
|
||||
@@ -4753,6 +4830,9 @@ class Controller:
|
||||
# is what seeds it, and dropping it there restarts the ~70 s cycle.
|
||||
if self.loop_w is not None and self.target != self.loop_w:
|
||||
self._refusal_end("another writer")
|
||||
# SAFETY-96: a battery that dropped out of the split leaves the
|
||||
# loop's start point (SAFETY-93's own if its charge ended too).
|
||||
self._reseed_drop(_live96)
|
||||
# SAFETY-93: a charge that ended leaves the loop's start point.
|
||||
self._reseed_charge_end(maint_results)
|
||||
probe = self._refusal_probe()
|
||||
@@ -4772,6 +4852,9 @@ class Controller:
|
||||
# level: the two halves of §6.2's identity break in opposite
|
||||
# directions. See `site_batt_w` and test_alloc.py part 8.
|
||||
site_batt = self.site_batt_w
|
||||
# SAFETY-96: a battery the loop cannot move counts at its command,
|
||||
# so its own power does not freeze the loop (the meter has it).
|
||||
site_batt += self._held_out_w(_live96)
|
||||
# TEL-10. ⚠️ ONE NAME FOR THE COMMAND THE LOOP WAS MEASURED
|
||||
# AGAINST. `self.target` is reassigned further down this method, so
|
||||
# a `decision.i_w - self.target` written at publish time would
|
||||
@@ -4880,6 +4963,7 @@ class Controller:
|
||||
# Stopped or blind: no accumulation may survive the outage.
|
||||
self.i_w = 0.0
|
||||
self.loop_w = None
|
||||
self._live_was = frozenset(_live96)
|
||||
# TEL-10, and it is the same zero the line above writes rather than
|
||||
# a second opinion about it. ⚠️ `not-running` rather than a stale
|
||||
# `tracking`: a reason row that keeps repeating the last word the
|
||||
@@ -7250,6 +7334,47 @@ async def docs_link_facts(session, token: str) -> dict:
|
||||
return out
|
||||
|
||||
|
||||
async def ha_time_zone(session, token: str) -> tuple:
|
||||
"""MAINT-10: `(zone, why)` - Home Assistant's configured time zone, or None
|
||||
and a short reason. Same 3 s budget as the docs link: never holds up start."""
|
||||
try:
|
||||
async with session.get(f"{CORE_API}/config", timeout=DOCS_LINK_TIMEOUT_S,
|
||||
headers={"Authorization": f"Bearer {token}"}) as r:
|
||||
body = await r.json(content_type=None)
|
||||
zone = body.get("time_zone") if isinstance(body, dict) else None
|
||||
return (zone, "") if zone else (None, "no time_zone in its answer")
|
||||
except Exception as err: # noqa: BLE001 - a fallback exists, never a stop
|
||||
text = str(err).strip()
|
||||
return None, f"{type(err).__name__}: {text}" if text else type(err).__name__
|
||||
|
||||
|
||||
_UTC_NAMES = {"UTC", "ETC/UTC", "GMT", "ETC/GMT", "UCT", "ETC/UCT",
|
||||
"UNIVERSAL", "ETC/UNIVERSAL", "ZULU", "ETC/ZULU"}
|
||||
|
||||
|
||||
async def maint_site_tz(session, token: str):
|
||||
"""MAINT-10: the zone the maintenance start hour is read in, logged once."""
|
||||
zone, why = await ha_time_zone(session, token)
|
||||
tz, name, source, why = site_zone(zone, why, os.environ.get("TZ"))
|
||||
if source == "ha":
|
||||
_LOG.info("Maintenance start hour is local time in %s, from Home "
|
||||
"Assistant.", name)
|
||||
elif source == "tz" and name.strip().upper() in _UTC_NAMES:
|
||||
# The Supervisor sets TZ to its copy of HA's zone, or to UTC if it has
|
||||
# none: HA did not answer here, and UTC may not be the site's clock.
|
||||
_LOG.warning("Maintenance start hour uses UTC, because Home Assistant "
|
||||
"did not answer. Restart the add-on when it is up.")
|
||||
_LOG.debug("maintenance time zone: %s", why)
|
||||
elif source == "tz":
|
||||
_LOG.info("Maintenance start hour is local time in %s, from the "
|
||||
"add-on's time zone. Home Assistant gave none: %s.", name, why)
|
||||
else:
|
||||
_LOG.warning("Maintenance start hour uses UTC, because no time zone "
|
||||
"was found. Set the time zone in Home Assistant.")
|
||||
_LOG.debug("maintenance time zone: %s", why)
|
||||
return tz
|
||||
|
||||
|
||||
async def amain() -> None:
|
||||
opts = load_options()
|
||||
logging.basicConfig(
|
||||
@@ -7359,7 +7484,8 @@ async def amain() -> None:
|
||||
pub = _NoMqtt()
|
||||
|
||||
stop = asyncio.Event()
|
||||
controller = Controller(opts, hass, store, pub, stop=stop)
|
||||
controller = Controller(opts, hass, store, pub, stop=stop,
|
||||
site_tz=await maint_site_tz(session, _tok))
|
||||
if callable(getattr(pub, "bind", None)):
|
||||
pub.bind(asyncio.get_running_loop(), controller.mqtt_command)
|
||||
runner = await web.start(controller, port=INGRESS_PORT)
|
||||
|
||||
@@ -34,7 +34,7 @@ simply not do.
|
||||
import logging
|
||||
import math
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timedelta, timezone, tzinfo
|
||||
|
||||
from .store import MAINT_UNIT_KEYS, unit_key
|
||||
|
||||
@@ -112,7 +112,9 @@ RESTART_COOLDOWN_MIN = 90
|
||||
MAINT_OPTION_DEFAULTS = {
|
||||
"maintenance_enabled": False,
|
||||
"maintenance_interval_days": 28,
|
||||
"maintenance_start_hour": 10,
|
||||
# MAINT-10: a LOCAL hour (site_zone() below), 19:00 so the drain runs
|
||||
# into the night rather than through the solar day.
|
||||
"maintenance_start_hour": 19,
|
||||
# ⚠️ 2000, NOT THE 2500 THIS SHIPPED AS, and config.yaml carries the
|
||||
# argument: both rates must stay at or below `max_w` (2000) or the
|
||||
# cheap-window charge shaping asks the arbiter for `hi = -charge_w` against
|
||||
@@ -177,6 +179,69 @@ class MaintConfig:
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# MAINT-10: the start hour is local time. See DECISIONS/MAINT-10-local-start-hour.md.
|
||||
# --------------------------------------------------------------------------- #
|
||||
def _load_zone(name):
|
||||
"""A tzinfo for an IANA name, or `(None, why)`."""
|
||||
if not name or not isinstance(name, str):
|
||||
return None, "none given"
|
||||
try:
|
||||
from zoneinfo import ZoneInfo
|
||||
return ZoneInfo(name.strip()), ""
|
||||
except Exception as err: # noqa: BLE001 - any failure
|
||||
return None, f"{name!r} is not a known zone ({type(err).__name__})"
|
||||
|
||||
|
||||
def site_zone(ha_zone, ha_why: str, env_tz) -> tuple:
|
||||
"""`(tzinfo, name, source, why)`: Home Assistant's zone (source "ha"), else
|
||||
the container's TZ ("tz"), else UTC ("utc"). `why` says what was missing."""
|
||||
tz, why = _load_zone(ha_zone)
|
||||
if tz is not None:
|
||||
return tz, ha_zone, "ha", ""
|
||||
ha_why = ha_why or why
|
||||
tz, env_why = _load_zone(env_tz)
|
||||
if tz is not None:
|
||||
return tz, env_tz, "tz", ha_why
|
||||
return timezone.utc, "UTC", "utc", f"Home Assistant: {ha_why}, TZ: {env_why}"
|
||||
|
||||
|
||||
def in_start_slot(now: datetime, start_hour: int, tz: tzinfo) -> bool:
|
||||
"""Is `now` inside today's one-hour start slot, read on the local clock?
|
||||
|
||||
Normally the slot is the local hour `start_hour`. On the day the clocks go
|
||||
forward and that hour does not exist, it is the first hour after the jump.
|
||||
On the day they go back and it happens twice, only the first one counts.
|
||||
Worked from UTC instants only (`astimezone`), so it does not depend on how
|
||||
a tzinfo resolves a wall time that is missing or doubled.
|
||||
"""
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=timezone.utc)
|
||||
here = now.astimezone(tz).replace(tzinfo=None)
|
||||
before = (now - timedelta(hours=1)).astimezone(tz).replace(tzinfo=None)
|
||||
if here.hour == start_hour:
|
||||
# the second pass through a repeated hour: an hour ago read the same
|
||||
return not (before.date() == here.date() and before.hour == start_hour)
|
||||
slot = here.replace(hour=start_hour, minute=0, second=0, microsecond=0)
|
||||
# the clock jumped over the start of the slot within the last hour
|
||||
return before < slot and here >= slot + timedelta(hours=1)
|
||||
|
||||
|
||||
def next_slot_start(now: datetime, start_hour: int, tz: tzinfo):
|
||||
"""The start of the slot `now` is in, or else of the next one; None if
|
||||
there is none within 50 h (no real zone does that)."""
|
||||
step = timedelta(minutes=15)
|
||||
t = now.replace(minute=now.minute - now.minute % 15, second=0,
|
||||
microsecond=0) - timedelta(hours=1)
|
||||
for _ in range(4 * 50):
|
||||
if (in_start_slot(t, start_hour, tz)
|
||||
and not in_start_slot(t - step, start_hour, tz)
|
||||
and t + timedelta(hours=1) > now):
|
||||
return t
|
||||
t += step
|
||||
return None
|
||||
|
||||
|
||||
@dataclass
|
||||
class MaintResult:
|
||||
phase: str
|
||||
@@ -256,8 +321,12 @@ class Maintenance:
|
||||
"""
|
||||
|
||||
def __init__(self, cfg: MaintConfig, store, unit: str | None = None,
|
||||
name: str = "", mirror_flat: bool = False):
|
||||
name: str = "", mirror_flat: bool = False,
|
||||
tz: tzinfo | None = None):
|
||||
self.cfg = cfg
|
||||
# MAINT-10: the zone `cfg.start_hour` is read in - main.py resolves it
|
||||
# once at startup (`site_zone()`). UTC when nobody says, as before.
|
||||
self.tz = tz or timezone.utc
|
||||
# ⚠️ `self.store` IS THE VIEW, NOT THE Store. Everything in this class
|
||||
# names an UNQUALIFIED key - "phase", "last_completed" - and the view is
|
||||
# the one place that turns it into the key this pack owns. A raw
|
||||
@@ -331,7 +400,8 @@ class Maintenance:
|
||||
about who was asking - so the IDLE branch of `tick()` calls this one.
|
||||
"""
|
||||
return (self.phase == IDLE and self.cfg.enabled
|
||||
and now.hour == self.cfg.start_hour and self.due(now)
|
||||
and in_start_slot(now, self.cfg.start_hour, self.tz)
|
||||
and self.due(now)
|
||||
and self._cooled(now))
|
||||
|
||||
# -- operations ----------------------------------------------------------
|
||||
|
||||
@@ -630,7 +630,8 @@ options:
|
||||
# contradiction. Changing one of these numbers now moves every consumer.
|
||||
maintenance_enabled: false
|
||||
maintenance_interval_days: 28
|
||||
maintenance_start_hour: 10
|
||||
# MAINT-10: a LOCAL hour, in Home Assistant's time zone.
|
||||
maintenance_start_hour: 19
|
||||
|
||||
# ⚠️ BOTH MUST STAY AT OR BELOW max_w, and that is why they are 2000 rather
|
||||
# than the 2500 they shipped as. The cheap-window charge shaping asks the
|
||||
|
||||
@@ -400,6 +400,15 @@ check("...with its duration from the battery's capacity and the cycle's rates "
|
||||
"and hold time",
|
||||
present(nth(_cyc)) and _cyc[0]["amount"].startswith("Takes about ")
|
||||
and _cyc[0]["end_h"] > _cyc[0]["start_h"] + 2)
|
||||
# MAINT-10: with the site's zone set, the hour is read on the local clock.
|
||||
from app.tariff import _EUTimezone # noqa: E402
|
||||
c_ml = make(dict(MAINT, maintenance_start_hour=14))
|
||||
for _mm in c_ml.maints:
|
||||
_mm.tz = _EUTimezone()
|
||||
_cyc_l = [r for r in status(c_ml)["plan"]["runs"] if r["kind"] == "cycle"]
|
||||
check("MAINT-10: start hour 14 in the local zone is drawn at 14:00, the "
|
||||
"instant the cycle starts", len(_cyc_l) == 1
|
||||
and field(nth(_cyc_l), "from") == "14:00")
|
||||
c_m.maints[0].store.set("phase", "drain")
|
||||
s_md = status(c_m)
|
||||
check("a cycle under way is drawn from now, and the battery's now line says "
|
||||
|
||||
@@ -0,0 +1,543 @@
|
||||
"""MAINT-10: the maintenance start hour is LOCAL time. `python3 test_maint10.py`
|
||||
|
||||
Graded here: the slot on ordinary days and on both DST change days, the zone
|
||||
source and its fallbacks, the 19:00 default, the startup wiring, and that the
|
||||
controller's commands are unchanged once the start instant is the same.
|
||||
See DECISIONS/MAINT-10-local-start-hour.md.
|
||||
|
||||
Mutating what this file grades? Read MUTATION.md first (stale bytecode).
|
||||
|
||||
⚠️ The CI image has no tzdata, so every DST check runs on tariff.py's encoded
|
||||
EU rule and, where zoneinfo works, on Europe/Brussels from tzdata as well.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import functools
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools"))
|
||||
|
||||
import app.main as M # noqa: E402
|
||||
from app import maintenance as MT # noqa: E402
|
||||
from app.maintenance import ( # noqa: E402
|
||||
DRAIN, IDLE, MAINT_OPTION_DEFAULTS, MaintConfig, Maintenance,
|
||||
in_start_slot, next_slot_start, site_zone,
|
||||
)
|
||||
from app.tariff import _EUTimezone # noqa: E402
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
UTC = timezone.utc
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
ZONES = [("encoded EU rule", _EUTimezone())]
|
||||
try:
|
||||
from zoneinfo import ZoneInfo
|
||||
ZONES.append(("zoneinfo Europe/Brussels", ZoneInfo("Europe/Brussels")))
|
||||
except Exception as err: # noqa: BLE001
|
||||
print(f" zoneinfo unavailable here ({err}); graded on the EU rule only")
|
||||
|
||||
SPRING = datetime(2026, 3, 29, tzinfo=UTC) # 02:00 CET -> 03:00 CEST
|
||||
SPRING27 = datetime(2027, 3, 28, tzinfo=UTC) # the next one, last Sunday of March
|
||||
AUTUMN = datetime(2026, 10, 25, tzinfo=UTC) # 03:00 CEST -> 02:00 CET
|
||||
SUMMER = datetime(2026, 7, 15, tzinfo=UTC)
|
||||
WINTER = datetime(2026, 1, 15, tzinfo=UTC)
|
||||
|
||||
|
||||
def slot_minutes(day_utc, hour, tz):
|
||||
"""UTC minutes in the slot, over the LOCAL day of that date."""
|
||||
t, out = day_utc - timedelta(hours=3), []
|
||||
while t < day_utc + timedelta(hours=27):
|
||||
if (t.astimezone(tz).date() == day_utc.date()
|
||||
and in_start_slot(t, hour, tz)):
|
||||
out.append(t)
|
||||
t += timedelta(minutes=1)
|
||||
return out
|
||||
|
||||
|
||||
def one_block(mins):
|
||||
"""`(start, minutes)` when the minutes form one contiguous run, else None."""
|
||||
if not mins:
|
||||
return None
|
||||
for a, b in zip(mins, mins[1:]):
|
||||
if b - a != timedelta(minutes=1):
|
||||
return None
|
||||
return mins[0], len(mins)
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
print("1. UTC stays what it was: the slot IS `now.hour == start_hour`")
|
||||
t, same = datetime(2026, 1, 1, tzinfo=UTC), True
|
||||
while t < datetime(2027, 1, 1, tzinfo=UTC):
|
||||
for h in range(24):
|
||||
if in_start_slot(t, h, UTC) != (t.hour == h):
|
||||
same = False
|
||||
t += timedelta(minutes=37)
|
||||
check("over a year of instants, every hour 0-23: identical to the old test",
|
||||
same)
|
||||
check("a naive `now` is read as UTC, as before",
|
||||
in_start_slot(datetime(2026, 7, 1, 19, 5), 19, UTC)
|
||||
and not in_start_slot(datetime(2026, 7, 1, 18, 5), 19, UTC))
|
||||
|
||||
# =========================================================================== #
|
||||
print("2. local time: 19 means 19:00 on the site's clock")
|
||||
for label, tz in ZONES:
|
||||
s = one_block(slot_minutes(SUMMER, 19, tz))
|
||||
w = one_block(slot_minutes(WINTER, 19, tz))
|
||||
check(f"[{label}] summer: 17:00-18:00 UTC (CEST), one hour",
|
||||
s == (SUMMER + timedelta(hours=17), 60))
|
||||
check(f"[{label}] winter: 18:00-19:00 UTC (CET), one hour",
|
||||
w == (WINTER + timedelta(hours=18), 60))
|
||||
check(f"[{label}] the old reading is gone: 19:00 UTC is not the slot "
|
||||
f"in summer", not in_start_slot(SUMMER + timedelta(hours=19, minutes=5),
|
||||
19, tz))
|
||||
|
||||
# =========================================================================== #
|
||||
print("3. the DST change days, every start hour")
|
||||
for label, tz in ZONES:
|
||||
for name, day in (("spring", SPRING), ("spring 2027", SPRING27),
|
||||
("autumn", AUTUMN)):
|
||||
bad = []
|
||||
for h in range(24):
|
||||
b = one_block(slot_minutes(day, h, tz))
|
||||
# the local day runs 23:00 UTC the day before to 22:00/23:00 UTC
|
||||
if b is None or b[1] != 60:
|
||||
bad.append((h, b))
|
||||
check(f"[{label}] {name}: every hour 0-23 gives ONE slot of exactly "
|
||||
f"60 minutes that day {bad or ''}", not bad)
|
||||
sp2 = one_block(slot_minutes(SPRING, 2, tz))
|
||||
check(f"[{label}] spring, hour 2 does not exist: it starts at 03:00 CEST "
|
||||
f"(01:00 UTC), once", sp2 == (SPRING + timedelta(hours=1), 60))
|
||||
check(f"[{label}] spring 2027 (28 March), hour 2: 01:00 UTC as well",
|
||||
one_block(slot_minutes(SPRING27, 2, tz))
|
||||
== (SPRING27 + timedelta(hours=1), 60))
|
||||
check(f"[{label}] the evening before spring 2027, hour 19: 18:00 UTC "
|
||||
f"(CET); that day, 17:00 UTC (CEST)",
|
||||
one_block(slot_minutes(SPRING27 - timedelta(days=1), 19, tz))
|
||||
== (SPRING27 - timedelta(hours=6), 60)
|
||||
and one_block(slot_minutes(SPRING27, 19, tz))
|
||||
== (SPRING27 + timedelta(hours=17), 60))
|
||||
au2 = one_block(slot_minutes(AUTUMN, 2, tz))
|
||||
check(f"[{label}] autumn, hour 2 happens twice: only the first, 02:00 CEST "
|
||||
f"(00:00 UTC)", au2 == (AUTUMN, 60))
|
||||
check(f"[{label}] autumn: the second 02:xx (CET) is not a slot",
|
||||
not in_start_slot(AUTUMN + timedelta(hours=1, minutes=30), 2, tz))
|
||||
check(f"[{label}] autumn, hour 19 still 18:00 UTC (CET)",
|
||||
one_block(slot_minutes(AUTUMN, 19, tz))
|
||||
== (AUTUMN + timedelta(hours=18), 60))
|
||||
check(f"[{label}] spring, hour 19 already 17:00 UTC (CEST)",
|
||||
one_block(slot_minutes(SPRING, 19, tz))
|
||||
== (SPRING + timedelta(hours=17), 60))
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
class FakeStore:
|
||||
def __init__(self):
|
||||
self.data = {"phase": IDLE, "phase_started": None,
|
||||
"last_completed": None, "last_start_attempt": None}
|
||||
|
||||
def set(self, k, v):
|
||||
self.data[k] = v
|
||||
|
||||
def set_time(self, k, when):
|
||||
self.data[k] = when
|
||||
|
||||
def get_time(self, k):
|
||||
return self.data.get(k)
|
||||
|
||||
def get(self, k, default=None):
|
||||
return self.data.get(k, default)
|
||||
|
||||
def save(self):
|
||||
pass
|
||||
|
||||
|
||||
def starts(day, hour, tz, *, abort_after=None, blocked=None):
|
||||
"""Tick a due pack each minute around a day; the UTC instants in that
|
||||
LOCAL day at which it entered DRAIN. `abort_after` aborts each drain that many minutes in (interlock);
|
||||
`blocked(t)` defers it."""
|
||||
m = Maintenance(MaintConfig(enabled=True, start_hour=hour), FakeStore(),
|
||||
tz=tz)
|
||||
out, since = [], None
|
||||
t = day - timedelta(hours=2)
|
||||
while t < day + timedelta(hours=26):
|
||||
why = ""
|
||||
if since is not None and abort_after is not None \
|
||||
and t - since >= timedelta(minutes=abort_after):
|
||||
why = "a test interlock"
|
||||
if blocked is not None and blocked(t):
|
||||
why = "the other battery is cycling"
|
||||
was = m.phase
|
||||
m.tick(t, soc=80, blocked_by=why)
|
||||
if m.phase == DRAIN and was != DRAIN:
|
||||
out.append(t)
|
||||
since = t
|
||||
if m.phase == IDLE:
|
||||
since = None
|
||||
t += timedelta(minutes=1)
|
||||
return [x for x in out if x.astimezone(tz).date() == day.date()]
|
||||
|
||||
|
||||
print("4. the state machine: one start per day, DST days included")
|
||||
for label, tz in ZONES:
|
||||
check(f"[{label}] spring, hour 2: one start, at 01:00 UTC (03:00 CEST)",
|
||||
starts(SPRING, 2, tz, abort_after=5)
|
||||
== [SPRING + timedelta(hours=1)])
|
||||
# An aborted start waits RESTART_COOLDOWN_MIN (90). The repeated hour is
|
||||
# 120 minutes long, so without the first-pass rule it would start again.
|
||||
check(f"[{label}] autumn, hour 2, aborted after 5 min: NO second start "
|
||||
f"in the repeated hour",
|
||||
starts(AUTUMN, 2, tz, abort_after=5) == [AUTUMN])
|
||||
check(f"[{label}] autumn, hour 2, deferred for the whole first pass: it "
|
||||
f"does not start in the second pass either",
|
||||
starts(AUTUMN, 2, tz, blocked=lambda t: t < AUTUMN + timedelta(hours=1))
|
||||
== [])
|
||||
check(f"[{label}] summer, hour 19: one start at 17:00 UTC",
|
||||
starts(SUMMER, 19, tz, abort_after=5)
|
||||
== [SUMMER + timedelta(hours=17)])
|
||||
|
||||
# =========================================================================== #
|
||||
print("5. where the start is shown (homeview) is where it happens")
|
||||
for label, tz in ZONES:
|
||||
ok = True
|
||||
for day in (SPRING, AUTUMN, SUMMER):
|
||||
for h in (0, 2, 3, 10, 19, 23):
|
||||
first = next(iter(slot_minutes(day, h, tz)), None)
|
||||
if first is None:
|
||||
continue
|
||||
for probe in (first - timedelta(hours=5), first,
|
||||
first + timedelta(minutes=59)):
|
||||
if next_slot_start(probe, h, tz) != first:
|
||||
ok = False
|
||||
check(f"[{label}] next_slot_start() lands on the slot's first minute, "
|
||||
f"from before it and from inside it", ok)
|
||||
|
||||
# =========================================================================== #
|
||||
print("6. which zone: Home Assistant, else the container's TZ, else UTC")
|
||||
_FAKE = {"Europe/Brussels": ZONES[-1][1], "America/New_York": object(),
|
||||
"UTC": UTC}
|
||||
_real_load = MT._load_zone
|
||||
MT._load_zone = lambda n: ((_FAKE[n], "") if n in _FAKE
|
||||
else (None, f"{n!r} is not a known zone"
|
||||
if n else "none given"))
|
||||
try:
|
||||
tz, name, src, _ = site_zone("Europe/Brussels", "", "America/New_York")
|
||||
check("Home Assistant's zone wins over the container's TZ",
|
||||
name == "Europe/Brussels" and src == "ha"
|
||||
and tz is _FAKE["Europe/Brussels"])
|
||||
tz, name, src, why = site_zone(None, "ClientConnectorError",
|
||||
"America/New_York")
|
||||
check("Home Assistant unavailable: the container's TZ, and why",
|
||||
name == "America/New_York" and src == "tz"
|
||||
and why == "ClientConnectorError")
|
||||
tz, name, src, why = site_zone("Mars/Base", "", "Europe/Brussels")
|
||||
check("an unknown Home Assistant zone falls back too",
|
||||
name == "Europe/Brussels" and src == "tz" and "Mars/Base" in why)
|
||||
tz, name, src, why = site_zone(None, "no answer", None)
|
||||
check("neither: UTC", tz is UTC and src == "utc" and "no answer" in why)
|
||||
finally:
|
||||
MT._load_zone = _real_load
|
||||
if len(ZONES) > 1:
|
||||
check("the real loader resolves a real name and refuses a made-up one",
|
||||
MT._load_zone("Europe/Brussels")[0] is not None
|
||||
and MT._load_zone("Mars/Base")[0] is None)
|
||||
check("the real loader refuses an empty name without raising",
|
||||
MT._load_zone("")[0] is None and MT._load_zone(None)[0] is None)
|
||||
|
||||
# =========================================================================== #
|
||||
print("7. the default is 19, an explicit value is honoured")
|
||||
cfg_text = (HERE / "config.yaml").read_text()
|
||||
opts_block = cfg_text.split("\nschema:")[0]
|
||||
check("config.yaml options: ships 19",
|
||||
re.search(r"^ maintenance_start_hour: 19$", opts_block, re.M) is not None)
|
||||
check("config.yaml schema: still int(0,23)",
|
||||
re.search(r"^ maintenance_start_hour: int\(0,23\)$", cfg_text, re.M)
|
||||
is not None)
|
||||
check("the in-code mirror says 19",
|
||||
MAINT_OPTION_DEFAULTS["maintenance_start_hour"] == 19
|
||||
and MaintConfig().start_hour == 19
|
||||
and MaintConfig.from_options({}).start_hour == 19)
|
||||
check("an explicit 10 stays 10 (a stored option is never rewritten)",
|
||||
MaintConfig.from_options({"maintenance_start_hour": 10}).start_hour == 10)
|
||||
_eu = ZONES[0][1]
|
||||
_m10 = Maintenance(MaintConfig.from_options(
|
||||
{"maintenance_enabled": True, "maintenance_start_hour": 10}),
|
||||
FakeStore(), tz=_eu)
|
||||
check("...and now means 10:00 local: 08:00 UTC in summer, not 10:00 UTC",
|
||||
_m10.wants_start(SUMMER + timedelta(hours=8, minutes=1))
|
||||
and not _m10.wants_start(SUMMER + timedelta(hours=10, minutes=1)))
|
||||
check("a Maintenance built with no zone reads UTC, as before",
|
||||
Maintenance(MaintConfig(), FakeStore()).tz is UTC)
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
print("8. startup: Home Assistant's zone is asked for and reaches the machines")
|
||||
|
||||
|
||||
class _Resp:
|
||||
def __init__(self, body, status=200):
|
||||
self.body, self.status = body, status
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
async def json(self, content_type=None):
|
||||
if isinstance(self.body, Exception):
|
||||
raise self.body
|
||||
return self.body
|
||||
|
||||
async def text(self):
|
||||
return "{}"
|
||||
|
||||
|
||||
class _Session:
|
||||
def __init__(self, zone_body):
|
||||
self.zone_body, self.asked = zone_body, []
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
def get(self, url, **kw):
|
||||
self.asked.append(url)
|
||||
self.timeouts = getattr(self, "timeouts", []) + [kw.get("timeout")]
|
||||
if url.endswith("/core/api/config"):
|
||||
return _Resp(self.zone_body)
|
||||
return _Resp({"data": {}})
|
||||
|
||||
|
||||
s = _Session({"time_zone": "Europe/Brussels"})
|
||||
check("ha_time_zone() reads /core/api/config's time_zone",
|
||||
asyncio.run(M.ha_time_zone(s, "tok")) == ("Europe/Brussels", "")
|
||||
and s.asked == [M.CORE_API + "/config"])
|
||||
# Review: HA can take minutes to start (2026-10-05); the ask must not wait on it.
|
||||
check("...with a time budget of at most 3 s, so a slow HA cannot hold up start",
|
||||
s.timeouts == [M.DOCS_LINK_TIMEOUT_S] and 0 < M.DOCS_LINK_TIMEOUT_S <= 3)
|
||||
check("...and a failure is None plus the reason, never a raise",
|
||||
asyncio.run(M.ha_time_zone(_Session(OSError("down")), "tok"))
|
||||
== (None, "OSError: down")
|
||||
and asyncio.run(M.ha_time_zone(_Session({}), "tok"))[0] is None)
|
||||
|
||||
|
||||
class _Built(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def amain_zone(zone_body, env_tz):
|
||||
"""Run the real amain() up to the Controller; the tz its machines get."""
|
||||
got, logs = {}, []
|
||||
|
||||
class _Capture(logging.Handler):
|
||||
def emit(self, rec):
|
||||
logs.append((rec.levelname, rec.getMessage()))
|
||||
|
||||
class _Hass:
|
||||
async def limits(self, e):
|
||||
return (-5000.0, 5000.0, 1.0)
|
||||
|
||||
async def mqtt_service(self):
|
||||
raise RuntimeError("no broker in this test")
|
||||
|
||||
real = {k: getattr(M, k) for k in ("load_options", "HomeAssistant",
|
||||
"validate_startup_config",
|
||||
"mode_announcement", "Controller")}
|
||||
real_session, real_store = M.aiohttp.ClientSession, None
|
||||
import app.store
|
||||
real_store = app.store.Store
|
||||
|
||||
def _controller(opts, hass, store, pub, *, stop, site_tz=None, **kw):
|
||||
got["tz"] = site_tz
|
||||
raise _Built()
|
||||
|
||||
M.load_options = lambda: {"setpoint_entity": "number.sp"}
|
||||
M.HomeAssistant = lambda session, **kw: _Hass()
|
||||
M.validate_startup_config = lambda *a, **k: []
|
||||
M.mode_announcement = lambda opts, store: ((), ())
|
||||
M.Controller = _controller
|
||||
M.aiohttp.ClientSession = lambda *a, **k: _Session(zone_body)
|
||||
app.store.Store = lambda *a, **k: object()
|
||||
old_tz = os.environ.pop("TZ", None)
|
||||
if env_tz:
|
||||
os.environ["TZ"] = env_tz
|
||||
h = _Capture()
|
||||
logging.getLogger("goodwe").addHandler(h)
|
||||
try:
|
||||
asyncio.run(M.amain())
|
||||
except _Built:
|
||||
pass
|
||||
finally:
|
||||
logging.getLogger("goodwe").removeHandler(h)
|
||||
for k, v in real.items():
|
||||
setattr(M, k, v)
|
||||
M.aiohttp.ClientSession = real_session
|
||||
app.store.Store = real_store
|
||||
os.environ.pop("TZ", None)
|
||||
if old_tz is not None:
|
||||
os.environ["TZ"] = old_tz
|
||||
return got.get("tz"), [m for lvl, m in logs if "Maintenance start" in m], logs
|
||||
|
||||
|
||||
MT._load_zone = lambda n: ((_FAKE[n], "") if n in _FAKE
|
||||
else (None, "none given"))
|
||||
try:
|
||||
tz, lines, _ = amain_zone({"time_zone": "Europe/Brussels"}, "America/New_York")
|
||||
check("amain(): Home Assistant's zone reaches the Controller",
|
||||
tz is _FAKE["Europe/Brussels"])
|
||||
check("...logged once, naming the zone and the source",
|
||||
lines == ["Maintenance start hour is local time in Europe/Brussels, "
|
||||
"from Home Assistant."])
|
||||
tz, lines, _ = amain_zone(OSError("down"), "America/New_York")
|
||||
check("amain(), Home Assistant unavailable: the container's TZ, said "
|
||||
"plainly", tz is _FAKE["America/New_York"]
|
||||
and lines == ["Maintenance start hour is local time in "
|
||||
"America/New_York, from the add-on's time zone. Home "
|
||||
"Assistant gave none: OSError: down."])
|
||||
tz, lines, logs = amain_zone(OSError("down"), None)
|
||||
check("amain(), neither: UTC, with a WARNING line",
|
||||
tz is UTC and any(lvl == "WARNING" and "uses UTC" in m
|
||||
for lvl, m in logs))
|
||||
# Review: HA still starting (502) and the Supervisor's TZ is UTC.
|
||||
tz, lines, logs = amain_zone(OSError("502"), "UTC")
|
||||
check("amain(), Home Assistant unavailable and TZ is UTC: a WARNING "
|
||||
"that says to restart", tz is UTC
|
||||
and [(lvl, m) for lvl, m in logs if "Maintenance start" in m]
|
||||
== [("WARNING", "Maintenance start hour uses UTC, because Home "
|
||||
"Assistant did not answer. Restart the add-on when it is up.")])
|
||||
tz, lines, logs = amain_zone(OSError("502"), "America/New_York")
|
||||
check("...but a real TZ is used without a warning",
|
||||
not any(lvl == "WARNING" for lvl, m in logs
|
||||
if "Maintenance start" in m))
|
||||
finally:
|
||||
MT._load_zone = _real_load
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
print("9. nothing else in control moves: the same start instant, the same "
|
||||
"commands")
|
||||
import opt11_identity as rig # noqa: E402
|
||||
import safety78_identity as s78 # noqa: E402
|
||||
|
||||
# rig's clock starts 2026-09-20 11:00 UTC = 13:00 CEST. The same drain,
|
||||
# asked for as UTC hour 11 (the old reading) and as local hour 13 (the new).
|
||||
|
||||
|
||||
def rows_with(start_hour, tz, n=1, both=False):
|
||||
"""The rig's rows; `both=True` also returns the Controller."""
|
||||
real_drain, real_ctl = s78.DRAIN, rig.Controller
|
||||
s78.DRAIN = {"maintenance_enabled": True,
|
||||
"maintenance_start_hour": start_hour}
|
||||
rig.Controller = functools.partial(real_ctl, site_tz=tz)
|
||||
try:
|
||||
# s78.run() wraps rig.Controller once more for its own tariff db.
|
||||
rows, c = s78.run(n, dur=600.0)
|
||||
return (rows, c) if both else rows
|
||||
finally:
|
||||
s78.DRAIN, rig.Controller = real_drain, real_ctl
|
||||
|
||||
|
||||
_utc11 = rows_with(11, None)
|
||||
_loc13 = rows_with(13, _eu)
|
||||
check("precondition: the drain really starts in the UTC-11 run",
|
||||
any("drain" in r[-1][4] for r in _utc11))
|
||||
check(f"start hour 11 UTC and 13 Europe/Brussels: every command, claim, "
|
||||
f"reason and log line identical over {len(_utc11)} cycles",
|
||||
_utc11 == _loc13)
|
||||
_utc12 = rows_with(12, None)
|
||||
_loc14 = rows_with(14, _eu)
|
||||
check("precondition: no drain in the not-yet-due-hour run",
|
||||
not any("drain" in r[-1][4] for r in _utc12))
|
||||
check("outside the start hour (12 UTC / 14 local): identical as well",
|
||||
_utc12 == _loc14)
|
||||
check("...and the zone matters: hour 11 read in Brussels does NOT start",
|
||||
not any("drain" in r[-1][4] for r in rows_with(11, _eu)))
|
||||
|
||||
# =========================================================================== #
|
||||
print("10. two inverters: every pack reads the start hour in local time")
|
||||
_r2u, _c2u = rows_with(11, None, n=2, both=True)
|
||||
_r2l, _c2l = rows_with(13, _eu, n=2, both=True)
|
||||
check("N=2: both packs get the site's zone, not just the first",
|
||||
len(_c2l.maints) == 2 and all(mm.tz is _eu for mm in _c2l.maints))
|
||||
check("N=2 precondition: a drain starts in the UTC-11 run",
|
||||
any(DRAIN in r[-1][4] for r in _r2u))
|
||||
check(f"N=2: start hour 11 UTC and 13 Europe/Brussels identical over "
|
||||
f"{len(_r2u)} cycles", _r2u == _r2l)
|
||||
check("N=2: hour 11 read in Brussels does NOT start either pack",
|
||||
not any(DRAIN in r[-1][4] for r in rows_with(11, _eu, n=2)))
|
||||
|
||||
|
||||
def pair_starts(day0, days, hour, tz, cycle_min=70):
|
||||
"""Two due packs, ticked each minute through `arbitrate()` as main.py
|
||||
does; a cycle takes about `cycle_min` minutes. `(pack, "DD HH:MM" UTC)`s."""
|
||||
cfg = MaintConfig(enabled=True, start_hour=hour, hold_min=10)
|
||||
ms = [Maintenance(cfg, FakeStore(), name=u, tz=tz)
|
||||
for u in ("A", "B")]
|
||||
ms[0].store.set_time("last_completed", day0 - timedelta(days=60))
|
||||
ms[1].store.set_time("last_completed", day0 - timedelta(days=40))
|
||||
half = (cycle_min - 10) // 2
|
||||
soc, out = [80.0, 80.0], []
|
||||
t = day0 - timedelta(hours=3)
|
||||
while t < day0 + timedelta(days=days):
|
||||
blocks = MT.arbitrate(ms, t)
|
||||
for i, mm in enumerate(ms):
|
||||
was = mm.phase
|
||||
mm.tick(t, soc=soc[i], blocked_by=blocks[i])
|
||||
if mm.phase == DRAIN:
|
||||
soc[i] -= (80.0 - cfg.soc_floor) / half
|
||||
elif mm.phase == MT.CHARGE:
|
||||
soc[i] += (cfg.soc_target - cfg.soc_floor) / half
|
||||
if mm.phase == DRAIN and was != DRAIN:
|
||||
out.append((mm.name, t))
|
||||
t += timedelta(minutes=1)
|
||||
return [(n, x.strftime("%d %H:%M")) for n, x in out]
|
||||
|
||||
|
||||
def _at(*pairs):
|
||||
return [(n, x.strftime("%d %H:%M")) for n, x in pairs]
|
||||
|
||||
|
||||
for label, tz in ZONES:
|
||||
# 24 Oct (CEST) and 25 Oct (CET): 19:00 local is 17:00 then 18:00 UTC.
|
||||
got = pair_starts(AUTUMN - timedelta(days=1), 2, 19, tz)
|
||||
check(f"[{label}] N=2 across the autumn change, hour 19: A at 19:00 "
|
||||
f"local on the 24th, B at 19:00 local on the 25th {got}",
|
||||
got == _at(("A", AUTUMN - timedelta(hours=7)),
|
||||
("B", AUTUMN + timedelta(hours=18))))
|
||||
got = pair_starts(SPRING27 - timedelta(days=1), 2, 19, tz)
|
||||
check(f"[{label}] N=2 across the spring 2027 change, hour 19: 18:00 UTC "
|
||||
f"then 17:00 UTC {got}",
|
||||
got == _at(("A", SPRING27 - timedelta(hours=6)),
|
||||
("B", SPRING27 + timedelta(hours=17))))
|
||||
# Hour 2 on 25 Oct: A takes the first pass (00:00 UTC) and is done in its
|
||||
# second pass. B must not start there - it waits for the next day.
|
||||
got = pair_starts(AUTUMN, 2, 2, tz)
|
||||
check(f"[{label}] N=2, autumn, hour 2: B does not start in the repeated "
|
||||
f"hour after A is done; it starts at 02:00 CET on the 26th {got}",
|
||||
got == _at(("A", AUTUMN),
|
||||
("B", AUTUMN + timedelta(days=1, hours=1))))
|
||||
got = pair_starts(SPRING27, 2, 2, tz)
|
||||
check(f"[{label}] N=2, spring 2027, hour 2: A at 03:00 CEST (01:00 UTC), "
|
||||
f"B the next night at 02:00 CEST (00:00 UTC) {got}",
|
||||
got == _at(("A", SPRING27 + timedelta(hours=1)),
|
||||
("B", SPRING27 + timedelta(days=1))))
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"{len(fails)} FAILED: {', '.join(fails)}")
|
||||
sys.exit(1)
|
||||
print("all checks passed")
|
||||
@@ -716,10 +716,11 @@ check("the drain's commitment window is DERIVED from the phase machine's own "
|
||||
"timeout, so the gate and maintenance.py cannot drift apart",
|
||||
near(MAINTENANCE_DRAIN.commits_h, DRAIN_TIMEOUT_MIN / 60.0)
|
||||
and near(MAINTENANCE_CHARGE.commits_h, CHARGE_TIMEOUT_MIN / 60.0))
|
||||
# The shipped `maintenance_start_hour` is 10:00 local, so a drain started on
|
||||
# schedule runs into the evening - hours a morning-only day-ahead print has not
|
||||
# covered. That is the ticket's scenario and it is where the window is placed.
|
||||
START = D0 + timedelta(hours=MaintConfig().start_hour)
|
||||
# A drain started at 10:00 local runs into the evening - hours a morning-only
|
||||
# day-ahead print has not covered. That is the ticket's scenario, so the hour is
|
||||
# pinned here: 10 was the shipped default until MAINT-10 moved it to 19, and an
|
||||
# install that stored 10 still starts then.
|
||||
START = D0 + timedelta(hours=10)
|
||||
_hours = derived(lambda: committed_hours(START, MAINTENANCE_DRAIN))
|
||||
check(f"...and it commits {len(_hours) if not isinstance(_hours, _Raised) else _hours} "
|
||||
f"whole hours, one per hour of the timeout",
|
||||
|
||||
@@ -187,7 +187,7 @@ check("⭐ a draining battery that is dropped (stale link) adds no floor: B "
|
||||
"covers the 1500 W house, not the 2000 W drain rate, and the wait is "
|
||||
"logged once",
|
||||
"dropped inverter-a" in _l_rows[-1][7]
|
||||
and cmd(_l_rows[-1])["b"] == 1500.0
|
||||
and cmd(_l_rows[-1])["b"] == 1510.0
|
||||
and sum("cannot give power now" in e for e in _l.events) == 1)
|
||||
|
||||
# ============================================================================ #
|
||||
|
||||
@@ -0,0 +1,573 @@
|
||||
"""Runnable check for SAFETY-96: a battery the loop cannot move does not
|
||||
freeze the loop. `python3 test_safety96.py`
|
||||
|
||||
At N=2, after A's link went stale the site sum still counted A's power, so
|
||||
`compute()` saw the site "not following" and froze B (SAFETY-93 rig test:
|
||||
B held at 1200 W for ~236 cycles). After a charge timeout or Off at 6000 W
|
||||
it froze ~14 s while A came out of its charge. Now a battery out of the
|
||||
split, with refused writes, or settling after a step the loop did not make
|
||||
counts at its command; its real power reaches the loop through the meter.
|
||||
Drives the REAL Controller on a lagging battery (10 s, 2 s meter).
|
||||
DECISIONS/SAFETY-96-dropped-battery.md.
|
||||
|
||||
1. A's link drops while it discharges: A holds its last command (stuck), or
|
||||
its board goes to 0 W 25 s after the first refused write.
|
||||
2. A's link drops while it charges (maintenance).
|
||||
3. B's link drops; both drop.
|
||||
4. A drops, then comes back.
|
||||
5. A's charge times out, or A is switched Off, at 6000 W.
|
||||
6. N=1 is untouched; the rule's parts one by one.
|
||||
|
||||
Mutations (MUTATION.md, purged copies) are listed in the pull request.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
logging.disable(logging.WARNING)
|
||||
|
||||
import opt11_identity as rig # noqa: E402
|
||||
import safety79_identity as s79 # noqa: E402
|
||||
import safety84_identity as s84 # noqa: E402
|
||||
from app import packmode # noqa: E402
|
||||
from app.main import Controller # noqa: E402
|
||||
from app.maintenance import CHARGE_TIMEOUT_MIN, IDLE, MaintResult # noqa: E402
|
||||
from app.store import unit_key # noqa: E402
|
||||
from named_absence import first, present # noqa: E402
|
||||
|
||||
fails = []
|
||||
SLEW = 400.0
|
||||
FROZEN = ("saturated-freeze", "freeze-released")
|
||||
OPT = dict(s84.OPT, peak_cap_w=3500)
|
||||
PLAIN = dict(s79.P1, peak_cap_w=3500)
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
# None on a tree without the fix, where this file prints the base numbers
|
||||
# and runs red.
|
||||
fixed = getattr(Controller, "_held_out_w", None)
|
||||
real_drop = getattr(Controller, "_reseed_drop", None)
|
||||
|
||||
|
||||
def without(fn):
|
||||
"""Run `fn` with SAFETY-96 taken out (the base behaviour)."""
|
||||
if fixed is None:
|
||||
return fn()
|
||||
Controller._held_out_w = lambda self, live: 0.0
|
||||
Controller._reseed_drop = lambda self, live: setattr(
|
||||
self, "_live_was", frozenset(live))
|
||||
try:
|
||||
return fn()
|
||||
finally:
|
||||
Controller._held_out_w, Controller._reseed_drop = fixed, real_drop
|
||||
|
||||
|
||||
def run(n=2, *, house=lambda t: 2400.0, dur=600.0, store=None, opt=None,
|
||||
soc=None, reject=None, back=None, wd=None, before=None, lag=10.0,
|
||||
blind=None, flaky=None, dead=None):
|
||||
"""Rows of one run. Writes to the units in `reject` (name -> from s) are
|
||||
refused from that time until `back` s; the add-on sees the refusal at
|
||||
once (a heartbeat write). A refused unit holds its last command, or with
|
||||
`wd` its board goes to 0 W `wd` s after the first refused write. B's
|
||||
reading is missing in the `blind` (from, to) window. `flaky(u, t)`:
|
||||
writes to u refused at t, each cycle's verdict seen (a heartbeat).
|
||||
`dead` (u, from s): u gives nothing from then on, whatever it is told.
|
||||
Each row: (t, plant commands, add-on commands, loop reason, site target,
|
||||
grid, circulation tripped)."""
|
||||
reject = reject or {}
|
||||
real_p, real_s, real_tick = rig._Hass.power, rig._Hass.set_number, rig.TICK
|
||||
|
||||
def refused(u, t):
|
||||
if flaky is not None:
|
||||
return flaky(u, t)
|
||||
return u in reject and t >= reject[u] and (back is None or t < back)
|
||||
|
||||
def power(self, u):
|
||||
st = self.__dict__.setdefault("_plant", {})
|
||||
a, tgt, tl = st.get(u, (0.0, 0.0, self.t))
|
||||
for k in range(int(round((self.t - tl) / 0.1))):
|
||||
now = tl + (k + 1) * 0.1
|
||||
c = self.cmd[u]
|
||||
if wd is not None and refused(u, now) and now - reject[u] >= wd:
|
||||
c = 0.0
|
||||
if dead is not None and u == dead[0] and now >= dead[1]:
|
||||
c = 0.0
|
||||
d = c - tgt
|
||||
tgt += math.copysign(min(abs(d), 80.0), d)
|
||||
a += (tgt - a) * (1 - math.exp(-0.1 / lag))
|
||||
st[u] = (a, tgt, self.t)
|
||||
return float(round(a))
|
||||
|
||||
async def set_number(self, e, v):
|
||||
if refused(e[-1], self.t):
|
||||
return False
|
||||
self.cmd[e[-1]] = float(v)
|
||||
return True
|
||||
|
||||
rows = []
|
||||
|
||||
def hook(c, t):
|
||||
for inv in c.inverters:
|
||||
if flaky is not None:
|
||||
inv.note_write(not flaky(inv.name[-1], t),
|
||||
rig.BASE + timedelta(seconds=t))
|
||||
elif refused(inv.name[-1], t) and inv.rejected_since is None:
|
||||
inv.rejected_since = rig.BASE + timedelta(seconds=t)
|
||||
if before is not None:
|
||||
before(c, t)
|
||||
if blind is not None and not getattr(c.hass, "_s96", False):
|
||||
read = c.hass.number
|
||||
|
||||
async def number(e, invert=False):
|
||||
if e == "sensor.batt_b" and blind[0] <= c.hass.t < blind[1]:
|
||||
return None
|
||||
return await read(e, invert)
|
||||
c.hass.number, c.hass._s96 = number, True
|
||||
(s84.feed(True) if opt is not None else s79._feed)(c, t)
|
||||
|
||||
def on_cycle(c, t):
|
||||
rows.append((t, tuple(sorted(c.hass.cmd.items())),
|
||||
tuple(inv.target for inv in c.inverters), c.loop_reason,
|
||||
c.target, c.hass.grid(), c.circ_wd.tripped,
|
||||
tuple(inv.batt for inv in c.inverters)))
|
||||
rig._Hass.power, rig._Hass.set_number, rig.TICK = power, set_number, 2.0
|
||||
try:
|
||||
_r, ctl = rig.run(n, extra=dict(opt if opt is not None else PLAIN),
|
||||
dur=dur, load=house, soc=soc or (lambda u, t: 60.0),
|
||||
cut=lambda u, t: False, before=hook,
|
||||
on_cycle=on_cycle, store=store or rig._Store())
|
||||
finally:
|
||||
rig._Hass.power, rig._Hass.set_number, rig.TICK = real_p, real_s, \
|
||||
real_tick
|
||||
return rows, ctl
|
||||
|
||||
|
||||
def freeze(rows, lo, hi=1e9):
|
||||
return sum(1 for r in rows if lo <= r[0] < hi and r[3] in FROZEN)
|
||||
|
||||
|
||||
def phantom(rows, k, lo, hi=1e9):
|
||||
"""Freeze cycles while battery `k` (the one taking over) reads within
|
||||
saturation_w (500 W) of what the loop last asked of it plus anything
|
||||
unplaced (last site target less the other's command): the freeze is
|
||||
then about the other battery, not about `k`'s own lag."""
|
||||
return sum(1 for a, b in zip(rows, rows[1:]) if lo <= b[0] < hi
|
||||
and b[3] in FROZEN
|
||||
and abs(a[4] - a[2][1 - k] - b[7][k]) <= 500.0)
|
||||
|
||||
|
||||
def ramp(rows, k, lo, hi=1e9):
|
||||
"""The largest change of unit `k`'s command (0 = A) between cycles."""
|
||||
return max(abs(b[2][k] - a[2][k]) for a, b in zip(rows, rows[1:])
|
||||
if lo < b[0] <= hi)
|
||||
|
||||
|
||||
def site_step(rows, lo, hi=1e9):
|
||||
return max(abs(b[4] - a[4]) for a, b in zip(rows, rows[1:])
|
||||
if lo < b[0] <= hi)
|
||||
|
||||
|
||||
def grid_err(rows, lo, hi=1e9):
|
||||
"""Mean |grid - aim| over [lo, hi) (aim -10 W)."""
|
||||
xs = [abs(r[5] + 10.0) for r in rows if lo <= r[0] < hi]
|
||||
return sum(xs) / len(xs)
|
||||
|
||||
|
||||
def trip_at(rows):
|
||||
"""When the circulation guard tripped (its own 0 W step is no ramp)."""
|
||||
return next((r[0] for r in rows if r[6]), 1e9)
|
||||
|
||||
|
||||
def tripped(rows):
|
||||
return rows[-1][6]
|
||||
|
||||
|
||||
def at(rows, t, k):
|
||||
return first((r[2][k] for r in rows if r[0] == t), f"row {t}")
|
||||
|
||||
|
||||
TABLE = []
|
||||
LAST = [None] # the controller of the last run with the fix
|
||||
|
||||
|
||||
def case(name, fn, lo, k, hi=1e9):
|
||||
"""Run `fn` with and without SAFETY-96, print and record the numbers:
|
||||
freeze cycles (and those not about `k`'s own lag), `k`'s largest step,
|
||||
the mean grid error, a circulation trip."""
|
||||
(now, LAST[0]), old = fn(), without(fn)[0]
|
||||
row = (name, freeze(now, lo, hi), freeze(old, lo, hi),
|
||||
phantom(now, k, lo, hi), phantom(old, k, lo, hi),
|
||||
ramp(now, k, lo, min(hi, trip_at(now) - 1)),
|
||||
ramp(old, k, lo, min(hi, trip_at(old) - 1)),
|
||||
grid_err(now, lo, hi), grid_err(old, lo, hi),
|
||||
tripped(now), tripped(old))
|
||||
TABLE.append(row)
|
||||
print(f" {name}: freeze {row[1]} (base {row[2]}), not about its own lag "
|
||||
f"{row[3]} (base {row[4]}); step {row[5]:.0f} (base {row[6]:.0f}) "
|
||||
f"W/cycle; grid error {row[7]:.0f} (base {row[8]:.0f}) W; "
|
||||
f"circulation trip {row[9]} (base {row[10]})")
|
||||
return now, old
|
||||
|
||||
|
||||
STUCK, BOARD = ("stuck", None), ("board 0 W", 25.0)
|
||||
|
||||
# ============================================================================ #
|
||||
print("1. A's link drops while it discharges (house 2400 W, each 1200 W)")
|
||||
for v, w in (STUCK, BOARD):
|
||||
now, old = case(f"A drop discharging, {v}",
|
||||
lambda w=w: run(reject={"a": 300.0}, wd=w), 300.0, 1)
|
||||
check(f"⭐ {v}: no freeze about A, B moves at most one slew step a "
|
||||
f"cycle, no circulation trip", phantom(now, 1, 300) == 0
|
||||
and ramp(now, 1, 300) <= SLEW and not tripped(now))
|
||||
check(f"non-vacuous ({v}): without the fix the loop freezes about A, or "
|
||||
f"B jumps more than a slew step at the drop",
|
||||
phantom(old, 1, 300) >= 10 or ramp(old, 1, 300) > SLEW)
|
||||
if w is None:
|
||||
check("stuck: B stays at its share, since A still gives its 1200 W "
|
||||
"(no freeze at all, grid within 15 W on average)",
|
||||
freeze(now, 300) == 0 and grid_err(now, 300) < 15.0
|
||||
and freeze(old, 300) >= 100)
|
||||
else:
|
||||
check("board 0 W: B ends up carrying the whole house (2410 W)",
|
||||
abs(now[-1][2][1] - 2410.0) <= 20.0)
|
||||
|
||||
# ============================================================================ #
|
||||
print("\n2. A's link drops while it charges (maintenance, house 1200 W)")
|
||||
|
||||
|
||||
def charging(**kw):
|
||||
return run(house=lambda t: 1200.0, dur=1500.0,
|
||||
store=s79.store_charging(2), opt=dict(
|
||||
OPT, maintenance_hold_min=600),
|
||||
soc=lambda u, t: 90.0 if u == "a" else 60.0, **kw)
|
||||
|
||||
|
||||
for v, w in (STUCK, BOARD):
|
||||
now, old = case(f"A drop charging, {v}",
|
||||
lambda w=w: charging(reject={"a": 1300.0}, wd=w),
|
||||
1300.0, 1)
|
||||
trip = trip_at(now)
|
||||
check(f"⭐ {v}: no freeze about A, and B climbs at most one slew step a "
|
||||
f"cycle and never charges (until any circulation trip)",
|
||||
phantom(now, 1, 1300, trip) == 0
|
||||
and ramp(now, 1, 1300, trip - 1) <= SLEW
|
||||
and min(r[2][1] for r in now if r[0] >= 1300) >= 0.0)
|
||||
check(f"non-vacuous ({v}): without the fix the loop freezes about A",
|
||||
phantom(old, 1, 1300) >= 3)
|
||||
if w is None:
|
||||
check("stuck (A charges 2000 W on its own): B reaches its 2500 W "
|
||||
"before the circulation trip, which still trips on the real "
|
||||
"4000 W going round (as on base)",
|
||||
max(r[2][1] for r in now if r[0] < trip) == 2500.0
|
||||
and tripped(now) and tripped(old))
|
||||
else:
|
||||
check("board 0 W: B carries the house (grid within 50 W from 100 s "
|
||||
"after the drop), no circulation trip",
|
||||
grid_err(now, 1400) < 50.0 and not tripped(now))
|
||||
|
||||
# ============================================================================ #
|
||||
print("\n3. B's link drops; both drop")
|
||||
for v, w in (STUCK, BOARD):
|
||||
now, old = case(f"B drop discharging, {v}",
|
||||
lambda w=w: run(reject={"b": 300.0}, wd=w), 300.0, 0)
|
||||
check(f"⭐ B drops ({v}): no freeze about B, A moves at most one slew "
|
||||
f"step a cycle, no circulation trip", phantom(now, 0, 300) == 0
|
||||
and ramp(now, 0, 300) <= SLEW and not tripped(now))
|
||||
for v, w in (STUCK, BOARD):
|
||||
now, old = case(f"both drop, {v}",
|
||||
lambda w=w: run(reject={"a": 300.0, "b": 300.0}, wd=w),
|
||||
300.0, 1)
|
||||
check(f"⭐ both drop ({v}): no freeze; both are commanded 0 W once "
|
||||
f"nothing can be placed", freeze(now, 300) == 0
|
||||
and now[-1][2] == (0.0, 0.0) and not tripped(now))
|
||||
|
||||
# ============================================================================ #
|
||||
print("\n4. A drops, then comes back")
|
||||
|
||||
|
||||
def rejoined(rows):
|
||||
return next((r[0] for r in rows if r[0] > 420 and r[2][0] != 0.0), 1e9)
|
||||
|
||||
|
||||
for v, w in (STUCK, BOARD):
|
||||
now, old = case(f"A drop and rejoin, {v}",
|
||||
lambda w=w: run(reject={"a": 300.0}, back=420.0, wd=w,
|
||||
dur=700.0), 300.0, 1)
|
||||
back = rejoined(now)
|
||||
check(f"rejoin ({v}): A is back in the split within 4 s of its link "
|
||||
f"returning (no refusal was learned while its writes were refused)",
|
||||
back <= 424.0 and not any("REFUSES" in e for e in LAST[0].events))
|
||||
print(f" A back in the split at {back:.0f} s; A "
|
||||
f"{[r[2][0] for r in now if back - 2 <= r[0] <= back + 6]}, B "
|
||||
f"{[r[2][1] for r in now if back - 2 <= r[0] <= back + 6]}; grid "
|
||||
f"{[round(r[5]) for r in now if back - 2 <= r[0] <= back + 6]}; "
|
||||
f"base grid {[round(r[5]) for r in old if back - 2 <= r[0] <= back + 6]}")
|
||||
a0 = first((r for r in now if r[0] == back - 2), "row before the rejoin")
|
||||
a1 = first((r for r in now if r[0] == back), "the rejoin row")
|
||||
check(f"⭐ rejoin ({v}): no freeze after it; the site target takes in only "
|
||||
f"A's own reading, then moves at most one slew step a cycle; the "
|
||||
f"grid stays within 250 W of its aim; no circulation trip",
|
||||
present(a0) and present(a1) and freeze(now, back) == 0
|
||||
and abs(a1[4] - a0[4] - a0[7][0]) <= SLEW
|
||||
and site_step(now, back) <= SLEW
|
||||
and max((abs(r[5] + 10.0) for r in now if r[0] >= back),
|
||||
default=1e9) < 250.0
|
||||
and not tripped(now))
|
||||
if w is None:
|
||||
check("non-vacuous (stuck): without the fix the grid swings over "
|
||||
"1000 W after the rejoin", max((abs(r[5] + 10.0) for r in old
|
||||
if r[0] >= back), default=0.0)
|
||||
>= 1000.0)
|
||||
|
||||
|
||||
|
||||
# Review: a battery that does refuse, behind a link that refuses one write
|
||||
# in three, is still found out (the count is kept over a refused write).
|
||||
_fl_rows, _fl = run(dur=700.0, dead=("a", 300.0),
|
||||
flaky=lambda u, t: u == "a" and t >= 300.0
|
||||
and int(t / 2) % 3 == 0)
|
||||
_fl_at = next((r[0] for r in _fl_rows if r[2][0] == 0.0 and r[0] > 300.0),
|
||||
None)
|
||||
_fl_end = first((r[2] for r in _fl_rows[-1:]), "the last row")
|
||||
print(f" A gives nothing from 300 s, 1 write in 3 refused: A's share is "
|
||||
f"taken off at {_fl_at} s; A {_fl.inverters[0].refused}, last "
|
||||
f"commands {_fl_end}")
|
||||
check("⭐ a battery that refuses behind a link refusing 1 write in 3: its "
|
||||
"refusal is still learned and B carries the house",
|
||||
_fl.inverters[0].refused == 1 and _fl_at is not None
|
||||
and _fl_at <= 400.0 and present(_fl_end)
|
||||
and abs(_fl_end[1] - 2410.0) <= 20.0)
|
||||
|
||||
# Review: a fast battery whose board goes to 0 W 1 s after the first refused
|
||||
# write reads ~0 W long before its link is stale (30 s): no refusal either.
|
||||
_ref5 = []
|
||||
_e5_rows, _e5 = run(reject={"a": 300.0}, back=420.0, wd=1.0, lag=1.0,
|
||||
dur=700.0,
|
||||
before=lambda c, t: _ref5.append(c.inverters[0].refused))
|
||||
check("fast battery, board 0 W 1 s after the first refused write: no "
|
||||
"refusal is learned, A is back in the split within 4 s of its link "
|
||||
"returning",
|
||||
not any(_ref5) and rejoined(_e5_rows) <= 424.0)
|
||||
|
||||
_seen = []
|
||||
|
||||
|
||||
def blind_seen(c, t):
|
||||
"""Record the last cycle: whether the loop ran, is A live, what settles."""
|
||||
if t > 340.0:
|
||||
_seen.append((t - 2.0, c.loop_reason, "inverter-a" in c.live_units(),
|
||||
dict(c._settle)))
|
||||
|
||||
|
||||
run(reject={"a": 300.0}, back=420.0, blind=(340.0, 470.0), dur=490.0,
|
||||
before=blind_seen)
|
||||
_back = first((x for x in _seen if x[1] != "not-running" and x[0] > 400),
|
||||
"the restart")
|
||||
print(f" B's reading missing 340-470 s, A back at 420 s: control holds from "
|
||||
f"{first((x[0] for x in _seen if x[1] == 'not-running'), '?')} s, "
|
||||
f"restarts at {_back[0]:.0f} s, settling then: {_back[3]}")
|
||||
check("A drops, then comes back while control holds (a reading missing): no "
|
||||
"rejoin at the restart, which starts from what is on the wire",
|
||||
any(x[1] == "not-running" and x[2] for x in _seen) and _back[3] == {})
|
||||
|
||||
|
||||
# ============================================================================ #
|
||||
print("\n5. A's charge times out, or A is switched Off, at a 6000 W house")
|
||||
|
||||
|
||||
def timed_out(end):
|
||||
"""A's charge passes CHARGE_TIMEOUT_MIN at `end` s; A then stays free
|
||||
(its cycle started today, so no restart) and B is not due."""
|
||||
s = s79.store_charging(2)
|
||||
s.data[unit_key("inverter-a", "phase_started")] = (
|
||||
rig.BASE + timedelta(seconds=end - CHARGE_TIMEOUT_MIN * 60 - 1)
|
||||
).isoformat()
|
||||
s.data[unit_key("inverter-a", "last_start_attempt")] = rig.BASE.isoformat()
|
||||
s.data[unit_key("inverter-b", "last_completed")] = rig.BASE.isoformat()
|
||||
return s
|
||||
|
||||
|
||||
def b_done():
|
||||
s = s79.store_charging(2)
|
||||
s.data[unit_key("inverter-b", "last_completed")] = rig.BASE.isoformat()
|
||||
return s
|
||||
|
||||
|
||||
def switch_off(at_t):
|
||||
def before(c, t):
|
||||
if t >= at_t:
|
||||
c.store.data[unit_key("inverter-a", packmode.USE_KEY)] = False
|
||||
return before
|
||||
|
||||
|
||||
def high(t):
|
||||
return 6000.0 if t >= 1760.0 else 1200.0
|
||||
|
||||
|
||||
ENDS = {
|
||||
"timeout": lambda: run(house=high, dur=1798.0, store=timed_out(1780.0),
|
||||
opt=dict(OPT, maintenance_hold_min=600),
|
||||
soc=lambda u, t: 90.0 if u == "a" else 60.0),
|
||||
"Off": lambda: run(house=high, dur=1798.0, store=b_done(),
|
||||
before=switch_off(1780.0),
|
||||
opt=dict(OPT, maintenance_hold_min=600,
|
||||
battery_modes_enabled=True),
|
||||
soc=lambda u, t: 90.0 if u == "a" else 60.0),
|
||||
}
|
||||
for k, fn in ENDS.items():
|
||||
now, old = case(f"{k} at 6000 W", fn, 1780.0, 1)
|
||||
print(f" B {[r[2][1] for r in now if 1778 <= r[0] <= 1796]}, base "
|
||||
f"{[r[2][1] for r in old if 1778 <= r[0] <= 1796]}")
|
||||
check(f"⭐ {k}: no freeze about A while it comes out of its charge; B "
|
||||
f"climbs one slew step a cycle and never charges",
|
||||
phantom(now, 1, 1780) == 0 and ramp(now, 1, 1780) <= SLEW
|
||||
and min(r[2][1] for r in now if r[0] >= 1780) >= 0.0)
|
||||
check(f"non-vacuous ({k}): without the fix the loop freezes about A and "
|
||||
f"B ends lower", phantom(old, 1, 1780) >= 3
|
||||
and at(now, 1796.0, 1) > at(old, 1796.0, 1))
|
||||
|
||||
# ============================================================================ #
|
||||
print("\n6. N=1 is untouched; the rule's parts")
|
||||
|
||||
|
||||
def digest(rows):
|
||||
return hashlib.sha256(repr(rows).encode()).hexdigest()
|
||||
|
||||
|
||||
def wave(t):
|
||||
return 2400.0 + 1500 * math.sin(t / 40)
|
||||
|
||||
|
||||
_n1 = [lambda: run(1, reject={"a": 300.0}, back=420.0, wd=25.0),
|
||||
lambda: run(1, house=high, dur=1798.0, store=timed_out(1780.0),
|
||||
opt=dict(OPT, maintenance_hold_min=600)),
|
||||
lambda: run(1, house=wave)]
|
||||
check("⭐ N=1 (a refused link that comes back, a charge timeout, a moving "
|
||||
"house): every row byte-identical with and without SAFETY-96",
|
||||
[digest(f()[0]) for f in _n1] == [digest(without(f)[0]) for f in _n1])
|
||||
check("N=2 healthy (a moving house, no drop): every row byte-identical with "
|
||||
"and without SAFETY-96",
|
||||
digest(run(house=wave)[0]) == digest(without(lambda: run(
|
||||
house=wave))[0]))
|
||||
|
||||
if fixed is None:
|
||||
print(f"\n{len(fails)} FAILED (no _held_out_w): " + ", ".join(fails))
|
||||
sys.exit(1)
|
||||
|
||||
_c = run(dur=4.0)[1]
|
||||
AB = ("inverter-a", "inverter-b")
|
||||
|
||||
|
||||
def held(batts, targets, live=AB, rejected=(), settle=None, now=100.0,
|
||||
start=None):
|
||||
for inv, b, t in zip(_c.inverters, batts, targets):
|
||||
inv.batt, inv.target = b, t
|
||||
inv.rejected_since = rig.BASE if inv.name in rejected else None
|
||||
_c._settle = dict(settle or {})
|
||||
_c._loop_start = dict(start or {})
|
||||
_c._now_mono = now
|
||||
return _c._held_out_w(set(live))
|
||||
|
||||
|
||||
check("a healthy pair: nothing held out, however far a reading lags",
|
||||
held((-2000.0, 400.0), (0.0, 400.0)) == 0.0)
|
||||
check("a dropped battery counts at its command (0 W), not its reading",
|
||||
held((-2000.0, 800.0), (0.0, 800.0), live=("inverter-b",)) == 2000.0)
|
||||
check("a battery whose writes are refused counts at its command",
|
||||
held((900.0, 800.0), (1200.0, 800.0), rejected=("inverter-a",))
|
||||
== 300.0)
|
||||
check("a settling battery counts at its command until its reading is within "
|
||||
"the deadband (15 W) of it, then it is the loop's again",
|
||||
held((-20.0, 800.0), (0.0, 800.0), settle={"inverter-a": 95.0})
|
||||
== 20.0 and "inverter-a" in _c._settle
|
||||
and held((-10.0, 800.0), (0.0, 800.0), settle={"inverter-a": 95.0})
|
||||
== 0.0 and "inverter-a" not in _c._settle)
|
||||
check("...but not on the cycle it starts",
|
||||
held((-10.0, 800.0), (0.0, 800.0), settle={"inverter-a": 100.0})
|
||||
== 10.0 and "inverter-a" in _c._settle)
|
||||
check("...or until PLANT_SETTLE_DOWN_S (23 s) has passed, whichever is first",
|
||||
held((-2000.0, 800.0), (0.0, 800.0), settle={"inverter-a": 77.1})
|
||||
== 2000.0 and held((-2000.0, 800.0), (0.0, 800.0),
|
||||
settle={"inverter-a": 77.0}) == 0.0)
|
||||
check("a reseeded start (SAFETY-93's charge end) is the command it counts at",
|
||||
held((-2000.0, 800.0), (-2000.0, 800.0), settle={"inverter-a": 99.0},
|
||||
start={"inverter-a": 0.0}) == 2000.0)
|
||||
|
||||
|
||||
def dropped(was, live, target, shares, batts=(0.0, 0.0), start=None):
|
||||
_c._live_was, _c.target, _c.i_w = (None if not was else frozenset(was),
|
||||
target, 123.0)
|
||||
_c._loop_start, _c._settle, _c._now_mono = dict(start or {}), {}, 50.0
|
||||
for inv, b in zip(_c.inverters, batts):
|
||||
inv.target, inv.batt = shares[inv.name[-1]], b
|
||||
_c._reseed_drop(set(live))
|
||||
return _c.target, _c.i_w
|
||||
|
||||
|
||||
check("a drop: the dropped battery's share leaves the start point, the "
|
||||
"integrator with it", dropped(AB, ("inverter-b",), 2400.0,
|
||||
{"a": 1200.0, "b": 1200.0})
|
||||
== (1200.0, 1200.0) and _c._live_was == frozenset({"inverter-b"}))
|
||||
_c._charge_ended = frozenset({"inverter-a"})
|
||||
check("...but a battery whose charge ended too is left to SAFETY-93's reseed",
|
||||
dropped(AB, ("inverter-b",), -2000.0, {"a": -2000.0, "b": 0.0})
|
||||
== (-2000.0, -2000.0))
|
||||
_c._charge_ended = frozenset()
|
||||
_free = MaintResult(IDLE, False, None, False, [])
|
||||
|
||||
|
||||
def charge_end(rejected_s):
|
||||
"""SAFETY-93's reseed for A (giving 1385 W under the loop, its charge
|
||||
suspended), A's writes refused for `rejected_s` s: (target, start)."""
|
||||
_c.target, _c.i_w, _c._charge_ended = 2770.0, 0.0, frozenset({AB[0]})
|
||||
_c._loop_start, _c._settle = {}, {}
|
||||
for inv in _c.inverters:
|
||||
inv.target, inv.rejected_since = 1385.0, None
|
||||
_c.inverters[0].rejected_since = datetime.now(timezone.utc) - timedelta(
|
||||
seconds=rejected_s)
|
||||
_c._reseed_charge_end([_free, _free])
|
||||
_c.inverters[0].rejected_since = None
|
||||
return _c.target, _c._loop_start[AB[0]]
|
||||
|
||||
|
||||
check("a charge that ends as its battery drops: the battery's start is 0 W "
|
||||
"(it is sent 0 W), not its last give; still live, its give stays",
|
||||
charge_end(31.0) == (1385.0, 0.0) and charge_end(5.0) == (2770.0, 1385.0))
|
||||
check("a rejoin: the battery enters the start point at its reading, and "
|
||||
"both settle while the split is made again",
|
||||
dropped(("inverter-b",), AB, 1200.0, {"a": 0.0, "b": 1200.0},
|
||||
batts=(-700.0, 1200.0)) == (500.0, 500.0)
|
||||
and _c._settle == {"inverter-a": 50.0, "inverter-b": 50.0})
|
||||
check("no change: nothing moves (the integrator either)",
|
||||
dropped(AB, AB, 1200.0, {"a": 600.0, "b": 600.0}) == (1200.0, 123.0)
|
||||
and dropped((), ("inverter-b",), 1200.0, {"a": 0.0, "b": 1200.0})
|
||||
== (1200.0, 123.0))
|
||||
_n1c = run(1, dur=4.0)[1]
|
||||
_n1c._live_was, _n1c.target, _n1c.i_w = frozenset({"inverter-a"}), 900.0, 5.0
|
||||
_n1c._reseed_drop(set())
|
||||
check("N=1: nothing moves and nothing is held out",
|
||||
(_n1c.target, _n1c.i_w) == (900.0, 5.0)
|
||||
and _n1c._held_out_w(set()) == 0.0)
|
||||
|
||||
print("\n case | freeze head/base | not about its own lag head/base | "
|
||||
"step W head/base | grid error W head/base | circulation trip head/base")
|
||||
for r in TABLE:
|
||||
print(f" {r[0]} | {r[1]}/{r[2]} | {r[3]}/{r[4]} | {r[5]:.0f}/{r[6]:.0f} |"
|
||||
f" {r[7]:.0f}/{r[8]:.0f} | {r[9]}/{r[10]}")
|
||||
print()
|
||||
if fails:
|
||||
print(f"{len(fails)} FAILED: " + ", ".join(fails))
|
||||
sys.exit(1)
|
||||
print("all SAFETY-96 checks passed")
|
||||
@@ -749,6 +749,24 @@ show("(d) GLOBAL `pv_invert: bool` validates too - it loses on SEMANTICS (one "
|
||||
"sign for a mixed roster), not on the schema", ok_d, "" if ok_d else out_d)
|
||||
|
||||
|
||||
print("\n== I. MAINT-10: `maintenance_start_hour` now defaults to 19 ==")
|
||||
_mk = "maintenance_start_hour"
|
||||
ok_i, out_i = validate(defaults)
|
||||
show("the shipped `options:` block validates and carries 19",
|
||||
ok_i and out_i.get(_mk) == 19, "" if ok_i else out_i)
|
||||
# What the Supervisor hands the add-on is deepmerge(options:, stored).
|
||||
_stored10 = dict(defaults, **{_mk: 10})
|
||||
ok_i2, out_i2 = validate(MERGER.merge(copy.deepcopy(defaults), _stored10))
|
||||
show("a stored explicit 10 (what a blob saved before MAINT-10 holds) stays 10",
|
||||
ok_i2 and out_i2.get(_mk) == 10, "" if ok_i2 else out_i2)
|
||||
_absent = {k: v for k, v in defaults.items() if k != _mk}
|
||||
ok_i3, out_i3 = validate(MERGER.merge(copy.deepcopy(defaults), _absent))
|
||||
show("a stored blob WITHOUT the key gets the new default, 19",
|
||||
ok_i3 and out_i3.get(_mk) == 19, "" if ok_i3 else out_i3)
|
||||
ok_i4, out_i4 = validate(dict(defaults, **{_mk: 24}))
|
||||
show("the range is unchanged: 24 is refused (`at most 23`)",
|
||||
(not ok_i4) and "at most 23" in str(out_i4), out_i4)
|
||||
|
||||
# ⚠️ THE EXIT CODE IS PART OF THE INSTRUMENT. Without it the probe prints FAIL
|
||||
# and still succeeds, and a transcript is only evidence if a wrong answer is
|
||||
# distinguishable from a right one by something other than reading it.
|
||||
|
||||
@@ -224,8 +224,8 @@ configuration:
|
||||
name: "Maintenance · Minimum days between cycles"
|
||||
description: "The shortest gap between two maintenance cycles."
|
||||
maintenance_start_hour:
|
||||
name: "Maintenance · Start hour"
|
||||
description: "The local hour, 0 to 23, at which a due cycle starts."
|
||||
name: "Maintenance · Start hour (local time)"
|
||||
description: "The hour on your local clock, 0 to 23, when a due cycle starts. 19 means 19:00."
|
||||
maintenance_discharge_w:
|
||||
name: "Maintenance · Draw-down rate (W)"
|
||||
description: "How fast the cycle empties the battery. Above “Inverter rating” it is cut back to the rating, and the cycle just takes longer."
|
||||
|
||||
@@ -205,8 +205,8 @@ configuration:
|
||||
name: "Onderhoud · Minimum dagen tussen cycli"
|
||||
description: "De kortste tijd tussen twee onderhoudscycli."
|
||||
maintenance_start_hour:
|
||||
name: "Onderhoud · Startuur"
|
||||
description: "Het lokale uur, 0 tot 23, waarop een geplande cyclus begint."
|
||||
name: "Onderhoud · Startuur (lokale tijd)"
|
||||
description: "Het uur op je lokale klok, 0 tot 23, waarop een geplande cyclus begint. 19 is 19:00."
|
||||
maintenance_discharge_w:
|
||||
name: "Onderhoud · Ontlaadvermogen (W)"
|
||||
description: "Hoe snel de cyclus de batterij leegmaakt. Boven het vermogen van de omvormer wordt het daartoe beperkt, en duurt de cyclus gewoon langer."
|
||||
|
||||
Reference in New Issue
Block a user