Compare commits

..
47 Commits
Author SHA1 Message Date
glenn schrooyenandClaude Opus 5.5 bbbc89b235 MAINT-20 part 2 review: comment-only fixes in main.py and the MAIN notes
checks / unit (pull_request) Successful in 30m13s
infra-pin / fresh (pull_request) Successful in 1s
- check_peak_floor_limited: restore the SAFETY-25 line (the reserve sentence is
  in messages.peak_reserve() on every branch, unreadable SoC included).
- Three status-page comments that no longer said anything (SAFETY-20 row,
  AC 5 delivery row, banner-vs-text) now say their rule in one line.
- tariff_refresh_wanted docstring: no orphan "TARIFF-24)" line.
- MAIN-orchestration.md: blank line before the first heading.
- MAIN-orchestration-archive.md: refilled intro; says how to find a section
  from a main.py pointer.

No code change: maint20_same_code.py 16029d7 -> SAME CODE, -OO same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 19:25:37 +01:00
glenn schrooyenandClaude f8df7cd860 MAINT-20 part 2 r2: DECISIONS MAIN-orchestration-archive intro
checks / unit (pull_request) Successful in 25m14s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:01 +01:00
glenn schrooyenandClaude f5714248f6 MAINT-20 part 2 r2: app/main.py comments, lines 6001-6185 (amain .. main)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:01 +01:00
glenn schrooyenandClaude 40ef27c367 MAINT-20 part 2 r2: app/main.py comments, lines 5501-6000 (status_payload .. maint_site_tz)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:01 +01:00
glenn schrooyenandClaude b05ad2b273 MAINT-20 part 2 r2: app/main.py comments, lines 5001-5500 (shutdown .. checks)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:01 +01:00
glenn schrooyenandClaude 31d13ee8bb MAINT-20 part 2 r2: app/main.py comments, lines 4501-5000 (check_peak_saturated .. publish)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude 47e99a37bc MAINT-20 part 2 r2: app/main.py comments, lines 4001-4500 (_shadow_settle .. check_output_clamp)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude d298f8aa4f MAINT-20 part 2 r2: app/main.py comments, lines 3501-4000 (module level)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude 391c4b4411 MAINT-20 part 2 r2: app/main.py comments, lines 3001-3500 (shadow .. cycle)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude 6f94944e44 MAINT-20 part 2 r2: app/main.py comments, lines 2501-3000 (_peak_over_drain .. _read_unit)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude 56d5532b83 MAINT-20 part 2 r2: app/main.py comments, lines 2001-2500 (_reseed_drain_end .. _fill_peak_gaps)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude 9ec0a84129 MAINT-20 part 2 r2: app/main.py comments, lines 1501-2000 (pack_floor_soc .. _reseed_charge_end)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude 6492d179d6 MAINT-20 part 2 r2: app/main.py comments, lines 1001-1500 (_refusal_from_stale .. site_circulating_w)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude f114a19dcc MAINT-20 part 2 r2: app/main.py comments, lines 501-1000 (_refusal_probe .. _refusal_update)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude a5fec377ad MAINT-20 part 2 r2: app/main.py comments, lines 1-500 (tariff_refresh_wanted .. __init__)
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 18:06:00 +01:00
glenn schrooyenandClaude 8fc5f15b03 MAINT-20 part 2 r2: cut the comments that came in with SMA-2, SMA-10, SAFETY-128 and SAFETY-137
Word for word in MAIN-orchestration-archive.md, keyed by the line at 16029d7.
No code change.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 17:29:27 +01:00
glenn schrooyenandClaude c2b4302dcf Merge release/1.0 (16029d7) into MAINT-20-2
Nine conflicts in app/main.py, all in comments around new code: every code
line is release/1.0's, every comment follows the part 2 rule.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 17:28:03 +01:00
admin 16029d7cb8 Merge pull request 'Release 0.21.0' (#241) from release-0.21.0 into release/1.0
infra-pin / fresh (push) Successful in 2s
checks / unit (pull_request) Successful in 23m41s
infra-pin / fresh (pull_request) Successful in 2s
2026-11-08 10:46:27 +01:00
Claude review 8e26574b03 Release 0.21.0: CHANGELOG wording (SAFETY-136, SAFETY-138 known issues)
checks / unit (pull_request) Successful in 24m11s
infra-pin / fresh (pull_request) Successful in 2s
SAFETY-136: the line said 10 to 15 s late is not caught, then that 15 s late
is caught after about 4 minutes. It now says 10 s is not caught and 15 s only
after about 4 minutes, as the card says.
SAFETY-138: the 30 s timer that zeroes a late write is the ESPHome board's
watchdog (README), not the inverter's own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 10:20:46 +01:00
Claude 0f208a0500 Release 0.21.0: version bump and CHANGELOG
checks / unit (pull_request) Successful in 33m53s
infra-pin / fresh (pull_request) Successful in 2s
Minor bump, no option changes. Folds "Not in a release yet" into a new
0.21.0 section, adds the contents table for the nine merges on release/1.0
since master 0.20.1, updates the known issues, and rewrites the 0.20.1
SAFETY-128 known issue to say it ships in 0.21.0.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 09:08:59 +01:00
admin b3cfcf2df4 Merge pull request 'SAFETY-137: the shutdown 0 W must be the last write every unit hears' (#240) from SAFETY-137 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-08 04:20:04 +01:00
Claude 8953be0362 SAFETY-137: the shutdown and Stop 0 W is the last write every unit hears
checks / unit (pull_request) Successful in 22m59s
infra-pin / fresh (pull_request) Successful in 1s
The 0 W of shutdown and of the Stop button now waits (bounded, 2 s) for a
write already on its way to the same unit, for every driver, GoodWe included.
Once shutdown has begun, cycle, heartbeat and safety-stop writes are dropped
right before the write is created. One shared wait (_await_inflight) serves
the 0 W and SMA-10's _release_last.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 02:39:38 +01:00
admin dbdc37b959 Merge pull request 'SMA-10: two idle states, hold 0 W or hand the inverter back' (#239) from SMA-10 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-07 23:43:14 +01:00
glenn schrooyenandClaude 6cae5a2f8f SMA-10 round 4: pin the Dutch default "de eigen sturing"
checks / unit (pull_request) Successful in 30m41s
infra-pin / fresh (pull_request) Successful in 2s
The NL default for a hand-back driver without words (handback._BACK_NL) was
changed to "de eigen sturing" in round 2 at the PR #239 review's request
(comment 2495: the article as in the generic clause). The brief does not name
it, so DECISIONS now says where it came from and a test checks the exact Dutch
sentence. No app code change.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 22:45:08 +01:00
glenn schrooyenandClaude 313503724d SMA-10 round 3: Start clears a failed hand-back streak; the hook is tested
checks / unit (pull_request) Successful in 23m23s
infra-pin / fresh (pull_request) Successful in 2s
When control takes the unit again, release_fails, release_retry_at and
release_zero_sent are reset, so the next Stop is a new streak with its own one
0 W, error line and event. Tests: a streak that Start interrupts without a
recovery; a driver that overrides release_fallback(). _BACK_NL "de eigen
sturing" (round 2) is kept.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 21:31:28 +01:00
glenn schrooyenandClaude d26cc573fe SMA-10 round 2: a failed release sends 0 W once, retries at heartbeat pace
checks / unit (pull_request) Successful in 23m37s
infra-pin / fresh (pull_request) Successful in 2s
When release() fails (False, raises or hangs past RELEASE_BUDGET_S) the unit
gets one bounded write(0) through the new Driver.release_fallback() hook
(default write(0)), then nothing more, so the inverter's own fallback timer is
not reset. The release is retried once per heartbeat, not on every idle
write. One error line and one action-log event per failure streak, one line on
recovery. Dutch default "terug naar de eigen sturing". DECISIONS says what a
unit is left at.

test_messages.py: the RELEASE_BUDGET_S data entry is gone again (the line
that needed it is gone).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 20:17:01 +01:00
glenn schrooyenandClaude a1be9c48b3 SMA-10: two idle states, hold 0 W or hand the inverter back
checks / unit (pull_request) Successful in 24m9s
infra-pin / fresh (pull_request) Successful in 1s
A driver now says whether its release() hands the inverter back
(Driver.hands_back; GoodWe is False, so release() stays write(0) and the
Controller never calls it). command_site_release() sits next to
command_site_zero(): the Stop button and shutdown() (so SIGTERM, restart,
control task death and a late config refusal) hand a hand-back unit back,
once, and zero every other unit as before. Safety stops and refusals still
hold 0 W for every unit. Shadow mode releases a hand-back unit. After a
release nothing is written to the unit (heartbeat and cycle included) until
control starts again. release() is bounded by RELEASE_BUDGET_S (= the write
budget), runs concurrently per unit, and a raising or hanging release on one
unit does not stop the others.

The "set to 0 W" sentences for Stop, restart, shadow mode and the stopped
banner are built from the roster (app/handback.py, EN and NL, words from the
driver); a GoodWe-only roster keeps every old literal. A handed-back unit
shows "Back under <its control>" on Home.

Existing test edited: test_messages.py (two classification entries for the
CRITICAL line that moved into a roster builder, and the new release bound).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 18:21:28 +01:00
admin 57c8d1b912 Merge pull request 'SMA-2: each inverter is reached through a driver; GoodWe behaviour unchanged' (#238) from SMA-2 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-07 14:46:58 +01:00
glenn schrooyenandClaude c015230452 SMA-2 round 2: keep the driver keys out of the schema, translations and labels
checks / unit (pull_request) Successful in 23m13s
infra-pin / fresh (pull_request) Successful in 1s
Owner decision 2026-11-07: clients see nothing new until SMA-4. config.yaml,
translations, labels and the page layout are back to 23ff9d0's. The validation
of the keys stays for callers that skip the schema.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 13:09:31 +01:00
glenn schrooyenandClaude 0b20f53cf8 SMA-2 round 2: census keeps ACTUATOR_WRITE_KEYS, setters, NaN/inf port refused, tests
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 12:20:56 +01:00
glenn schrooyenandClaude e56eeef8f0 SMA-2: each inverter is reached through a driver; GoodWe behaviour unchanged
checks / unit (pull_request) Successful in 23m14s
infra-pin / fresh (pull_request) Successful in 2s
app/drivers.py holds one Driver per roster entry (configured, actuator_id,
limits, read, write, release, probe, link_stale_s, batt_bound, settle_s, brand,
words). GoodWeEsphomeDriver makes the calls the code it replaced made, in the
same order. Inverter gets driver; has_writer, is_live and link_note read it. The
SoC/power read, the write, the device range (run_control, amain, the settings
panel), rule 2 per unit and the SAFETY-28 census go through it.

setpoint_entity is optional per entry beside driver, host, port, unit_id and
maintenance; only goodwe_esphome is selectable, the rest are checked and unused.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 11:28:47 +01:00
admin 23ff9d0920 Merge pull request 'OPT-38: keep tomorrow's solar forecast when one sensor goes stale in the afternoon' (#237) from OPT-38 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-07 06:56:10 +01:00
glenn schrooyenandClaude 0bacafadf0 OPT-38 round 2: a kept tomorrow reading is flagged kept only from 20:00
checks / unit (pull_request) Successful in 23m11s
infra-pin / fresh (pull_request) Successful in 1s
Before the bell ends it replaced today's Home line and the event log with
the kept-for-tonight wording. stand_in() docstring covers the tomorrow case.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 06:02:00 +01:00
glenn schrooyenandClaude c43873b142 OPT-38: a kept tomorrow forecast reading stands in at any hour
checks / unit (pull_request) Successful in 22m54s
infra-pin / fresh (pull_request) Successful in 1s
One stale Forecast.Solar tomorrow sensor dropped the whole OPT-17 sum from
17:54 to 20:00. Today readings and the OPT-34 morning rules are unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 04:24:01 +01:00
admin b291262ee1 Merge pull request 'SAFETY-129: find late Home Assistant readings sooner at a 5 s meter' (#236) from SAFETY-129 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-07 01:24:39 +01:00
glenn schrooyenandClaude c70eeb6916 SAFETY-129 round 3: the real reason for the 16 s limit, a slow-start check, the row's tail
checks / unit (pull_request) Successful in 23m1s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-07 00:12:33 +01:00
glenn schrooyenandClaude 03541a1eee SAFETY-129 round 2: next() with a default in test_safety129
checks / unit (pull_request) Successful in 23m26s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-06 22:12:39 +01:00
glenn schrooyenandClaude 85433edac6 SAFETY-129 round 2: shorter test_safety129, pinned 5 s row, 100 s bound
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-06 21:24:37 +01:00
glenn schrooyenandClaude 2667cf0dda SAFETY-129: the 5 s row no longer waits for the batteries' figure
checks / unit (pull_request) Successful in 23m52s
infra-pin / fresh (pull_request) Successful in 1s
At a 5 s meter the slow meter fit now finds 30 s late first, and the hold leaves
the batteries' fit nothing to measure, so the row says it without a figure.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-06 20:04:08 +01:00
glenn schrooyenandClaude 5b6cb0bf08 SAFETY-129: find readings 30 s late within about 90 s at a 5 s meter
The meter's delay fit needed 16 new values in 60 s, so at the owner's 5 s P1
only the batteries' fit ran and 30 s late was found after about 3 minutes
(export to -420 W). A meter that slow is now also fitted over 120 s; it calls
a delay late only over 16 s, on two fits in a row, with the same corroboration
as before, and never ends a verdict, so a slow battery (R2-1) runs as before.
Found about 90 s after the start, export above -200 W. 10 s late at a 5 s
meter is not found (nothing swings; it cannot be told from a 10 s battery).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-06 19:38:21 +01:00
admin c66aa7f69a Merge pull request 'UX-77 round 2: Home's roll shares the peak room by room left, as control does' (#235) from UX-77-2 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-06 11:19:20 +01:00
glenn schrooyenandClaude 6d2b9b5335 UX-77: Home's roll shares the peak room by room left to full, as control does
checks / unit (pull_request) Successful in 26m34s
infra-pin / fresh (pull_request) Successful in 2s
The cheap-run roll (cheaproll._Charge) shared the peak room by rating, control
shares it by room left to full (packshare.weights). With unequal levels one
battery's drawn block ended too early (rig F-1). The roll now uses
packshare.weights over the simulated levels, each battery capped at its rating,
a full one dropping out. test_ux77 gains two unequal-level walks and a
by-rating mutant; its walks model control's split by room too.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-06 09:11:00 +01:00
admin 47c89a13d0 Merge pull request 'UX-77: Home draws today's grid charge for the hours control will really charge' (#234) from UX-77 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-06 00:11:03 +01:00
glenn schrooyenandClaude 2bbf88862a MAINT-20 part 2: main.py keeps the FCST-04 windowing caveat a test pins
checks / unit (pull_request) Successful in 25m56s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-01 04:00:00 +01:00
glenn schrooyenandClaude 3d31b679eb MAINT-20 part 2: main.py: keep whole sentences, no truncated warnings; refresh archive
checks / unit (pull_request) Failing after 24m55s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-01 03:33:54 +01:00
glenn schrooyenandClaude 6889667fcd MAINT-20 part 2: main.py comments and docstrings cut to a line and a pointer; DECISIONS MAIN-orchestration and its archive
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-01 03:32:54 +01:00
glenn schrooyenandClaude 0fb4c2b5e2 MAINT-20 part 2: same-code script checks -OO code, added/removed files, allowed paths, docstring list
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-01 03:27:45 +01:00
36 changed files with 8692 additions and 3943 deletions
+118 -4
View File
@@ -1,9 +1,123 @@
# Changelog
### Not in a release yet
## 0.21.0
**A minor bump: control now holds the batteries when Home Assistant readings come late, Home draws the whole night's grid charge, and the shutdown 0 W is sent last. No option changes.**
No option was added, removed or renamed, and no default changed (86 options). **Existing installs need no option change:** options that start 0.20.1 also start 0.21.0, and the Supervisor form is the same. It is a minor bump because control acts differently when readings come late and when the add-on stops; every saved setting still starts.
**Late Home Assistant readings are held, not followed.** When Home Assistant passes readings on late, control used to correct a mistake its last command had already fixed, so the give run could swing and send power to the grid. It now waits until the battery shows its last power request, and the peak limit no longer asks for full power on late readings. A row on the page says so, and if the readings stay too late every inverter goes to 0 W. With readings on time, the commands are the same as before.
- With a 2 s meter, readings 10 s late were found in 43 s in a rig test.
- With a 5 s meter, readings 30 s late are now found in about 90 s (88 s in a simulation, 75 s in a rig test), where they took about 3 minutes. Readings 10 s late at a 5 s meter are not found ([[SAFETY-136]]).
**Home draws the whole night's grid charge.** Home used to draw a battery's grid charge only for the cheap run under way. It now draws every hour the add-on will charge it tonight, and shares the peak room between batteries as control does. It shows the plan and changes no command.
**Tomorrow's forecast stays in the afternoon.** If one of the tomorrow solar forecast sensors stops updating, tomorrow's forecast now stays instead of vanishing until 20:00.
**The shutdown 0 W is sent last.** When the add-on stops, the 0 W now waits up to 2 s for a command already on its way, so it is the last thing each inverter hears. A command slower than that can still land after it ([[SAFETY-138]]).
Contents of this release, in merge order since 0.20.1 (`d53f70f`):
| | |
|---|---|
| `371961e` | When Home Assistant passes readings on late, control no longer corrects a mistake its last command has already fixed. It waits until the battery shows its last power request, and the peak limit no longer asks for full power on late readings. The page says so, and if the readings stay too late every inverter goes to 0 W ([[SAFETY-128]], #228) |
| `af2d0d2` | History only: brings 0.20.1, already live, into this branch. Nothing else is new (#233) |
| `47c89a1`, `c66aa7f` | Home draws a battery's grid charge for every hour the add-on will charge it tonight, not only the cheap run under way, and shares the peak room between batteries as control does. It shows the plan and changes no command ([[UX-77]], #234, with its second round #235) |
| `b291262` | With a 5 s meter, readings 30 s late are found in about 90 s, not about 3 minutes. Readings 10 s late are not found at a 5 s meter; the owner accepted this and it has its own card ([[SAFETY-129]], #236, [[SAFETY-136]]) |
| `23ff9d0` | If one of the tomorrow solar forecast sensors stops updating in the afternoon, tomorrow's forecast now stays on the Forecast tab instead of vanishing until 20:00. The night plan can use it in that time ([[OPT-38]], #237) |
| `57c8d1b` | Each inverter is now reached through a driver. This prepares support for other inverter makes; there is no change for GoodWe sites ([[SMA-2]], #238) |
| `dbdc37b` | When the add-on stops, an inverter that can steer itself can be handed back instead of held at 0 W. This prepares support for other inverter makes; there is no change for GoodWe sites ([[SMA-10]], #239) |
| `b3cfcf2` | When the add-on stops, the 0 W now waits up to 2 s for a command already on its way, so it is the last thing each inverter hears. In a rig test, 0 of 111 stops ended on a value other than 0 W, against 4 of 110 before. A slower command can still land after it ([[SAFETY-137]], #240, [[SAFETY-138]]) |
### Known issues
- A false "Battery is not keeping up" can still show when the peak guard pauses a maintenance charge ([[SAFETY-92]]).
- A battery capped at a low limit with a perfectly flat reading can still trip the stale check ([[SAFETY-74]]).
- A battery whose reading at rest is beyond about ±175 W is still not caught when it refuses ([[SAFETY-97]]).
- The peak guard can still back off near the end of a 15-minute period when a meter reading is late, by less than 30 s. This is about the guard's discharge only; a grid charge is cut back since 0.19.2 ([[SAFETY-99]]).
- Two inverters: the maintenance charge can switch on and off while the house is above the peak aim ([[SAFETY-88]]).
- Two inverters: the "circulating" figure counts a battery's reading at rest ([[SAFETY-98]]).
- Two inverters: a drain that starts during a big step in house use can send the other battery to full power, and about 1 kW goes to the grid for about 10 s ([[SAFETY-104]]).
- Two inverters: when a battery comes back during a maintenance charge, the grid can step by several kW at once ([[SAFETY-101]]).
- Two inverters: when a battery drops out during a solar surplus, the others can swing by up to 1.5 kW in a simulation ([[SAFETY-105]]).
- Two inverters: after a drain ends, a change in house use can go unanswered for about 9 s, because some readings are old ([[SAFETY-106]]).
- Two inverters: when one battery's level is missing, both batteries are held at 0 W, and for about 15 s the last command stays on ([[SAFETY-108]]).
- Two inverters: if one battery's level stays missing for 12 h, the other battery's cycle can be marked failed, with a 7-day wait and a notice, though it is healthy. This comes from reading the code; it has not been seen on a site ([[MAINT-17]]).
- When the 15-minute demand forecast sensor counts the battery's own charge, the maintenance charge runs at about half the power the peak limit leaves, so it takes about twice as long. Seen on a site: about 1.2 kW instead of 2.5 kW, and the peak limit was kept ([[SAFETY-111]]).
- One inverter: after a link drop, the battery's own safety stop to 0 W can be taken as a refusal, and the site stays at 0 W for up to 15 min ([[SAFETY-102]]).
- After a Home Assistant restart, control still waits until Home Assistant has finished starting, which can take several minutes, though the readings are already there ([[SAFETY-115]]).
- While Home Assistant is not answering, the page can list inverters as refusing commands and sensors as missing, and send you to Developer Tools, though they are fine ([[UX-37]]).
- If Home Assistant hangs or stops, the page keeps saying "Waiting for Home Assistant" and never turns into an alarm ([[SAFETY-113]]).
- Right after Home Assistant has started, the page can say for about 4 s that an inverter cannot be controlled, and the first command can come late ([[SAFETY-114]]).
- After a Home Assistant restart, the controller status sensor can still say "running" while the add-on cannot control. It was seen once, and the cause is not known ([[SAFETY-116]]).
- Battery modes on: after a planned top-up from the grid, the Batteries screen can say "Enough sun is forecast" ([[UX-32]]).
- Battery modes on: the forecast line "we count on" can show more sun than the plan counts, because the plan takes house use off first ([[UX-33]]).
- Battery modes on: before a planned top-up, the Today list shows a smaller "gives" amount than the plan will use; it grows as the charge happens ([[UX-34]]).
- Two inverters, battery modes on: while the other battery is in its maintenance charge, a battery's card can say it charges from the grid while it stays at 0 W ([[OPT-18]]).
- Two inverters, battery modes on: while a battery refuses to charge in a cheap run, the action log on the page gets about 8 lines an hour for its retries, and the page hint says "waiting for a better price" ([[UX-38]]).
- A battery in a safety stop, or one the add-on cannot reach, can still be started for a cycle, and its drain then waits about 12 h and ends in a failed-cycle notice. This comes from reading the code; it has not been seen on a site ([[MAINT-19]]).
- On the Settings page, the rows of the solar forecast lists are labelled "Phase 1", "Phase 2" instead of "Sensor 1", "Sensor 2" ([[UX-27]]).
- In the solar forecast list, a blank or repeated row makes "source 2 of 2" count differently from the rows on the Settings page ([[UX-28]]).
- The solar forecast message says "has no reading" also when the sensor shows a number that is too old or in the wrong unit ([[UX-29]]).
- If you use only the forecast lists, two Settings notes sit on the single-sensor field, and one of them tells you to set that field ([[UX-30]]).
- After a restart during a price outage, the "No prices" message can say "yet" when prices did come in earlier ([[UX-39]]).
- On the new settings page, you cannot see whether a price service token is set. Check the Configuration tab ([[UX-41]]).
- On the classic settings page, the first click on Save after editing a field can do nothing. Click again ([[UX-42]]).
- A steady overload on a 1 s meter can warn, and send the Home Assistant notification, 2 or 3 times at the start of each 15-minute period instead of once. The peak limit is still kept ([[SAFETY-122]]).
- A fixed tariff is priced once per hour, so a price window that starts or ends at :15, :30 or :45 gets the wrong price for part of that hour. Windows that start and end on the hour are right ([[TARIFF-23]]).
- Step 6 of the setup wizard stays empty because of an error in the page, in English and in Dutch ([[UX-51]]).
- On Dutch pages, refusal texts, the last-event line under the Home buttons, the installer details and the trading status sentences are still English, and a few Dutch texts read badly, such as "1 metingen geweigerd" ([[UX-52]]).
- Some price texts say "hour" where the add-on acts on a 15-minute period, such as "cheapest hour" ([[UX-47]]).
- After the add-on restarts, the Home price chart shows no price for the earlier part of today, and the setup check can say "12 of 24 hours", though the prices are known ([[UX-48]]).
- With battery modes on and only batteries on "Leftover solar", the Home price chart can mark a cheap period where no battery charges ([[UX-49]]).
- On a phone, the bars of the Home price chart are too thin to tap one 15-minute period. The arrow keys work ([[UX-50]]).
- In the last second of a 15-minute period, being a few watts over the aim can make the peak guard ask a battery for full power for one second. When a charge ends on a period edge, the last-second give can fade out over about 10 s, and a rig test exported up to 7.4 kW for about 8 s ([[SAFETY-124]]).
- During the night grid charge, a 15-minute period can end 6 to 14 W over the peak aim, because the battery charges harder than asked. This was seen in simulation; a rig test saw 2 to 8 W ([[OPT-35]]).
- The test rig could not bring back the false peak alarm that [[SAFETY-126]] fixes, so that fix is shown in simulation only. Watch the notifications for a few nights ([[TEST-35]]).
- The night cheap run is sized for the batteries' full charging power, not for what the peak limit leaves. Under a tight limit the run can end before the batteries reach their level, and Home can show a level they do not reach (79.9 % against a shown 95 % in a rig test) ([[OPT-25]]).
- By day, a Leftover solar plan that has only a daily forecast figure counts the sun from now, not from when the figure was read. It counts about 22 % too much for a figure one hour old; the night plan is not affected ([[OPT-30]]).
- The night charge can buy too much in a house that uses more at night than by day, such as one with a car charger or heat pump, and on a sunny day, because spare sun in one expensive hour does not count for the later ones ([[OPT-31]]).
- A cheap run that has already started can overlap a new give run after a re-plan, so a battery can charge from the grid at the dearest price for part of an hour. This was seen in a test case, not on a site. Also in 0.19.2 ([[OPT-32]]).
- If the solar forecast sensors stop updating before 17:00, as in winter or further north, there is no forecast from three hours after their last update until 20:00 ([[OPT-33]]).
- With a forecast that gives only a daily total, the sun is spread an hour off on the two clock-change days after the change. The day's total is right ([[OPT-24]]).
- The add-on learns the house's use only once a solar forecast is set, so a site that adds a forecast later waits one more day for its first plan ([[OPT-26]]).
- Home says "No trading on price yet: no prices have arrived" when every battery is on Solar first, though the prices are shown ([[UX-55]]).
- The Home plan header can say "Charges in the cheapest hour, gives power in the dearest" when Home draws no charge, and it says "hour" for 15-minute prices ([[UX-56]]).
- While the peak guard holds back charging, Home hides the rest of the cheap run and gives no reason. The charge starts again when the guard lets go ([[UX-57]]).
- With battery modes on and selling on, Home can draw a "Sells up to" block when the add-on judges the trade not worth it, and then it will not sell ([[UX-58]]).
- Home, the plan and the Forecast tab stop drawing a battery's give at the trading floor, though control goes on giving down to the battery's cut-out ([[UX-59]]).
- During a price outage, the Batteries screen says "Prices differ too little" and Home says "The price gap is too small" ([[UX-60]]).
- With battery modes on and no meter, or a meter that is a Home Assistant entity, a grid charge is not possible and nothing says so ([[UX-61]]).
- On the Batteries screen, a charge the add-on refused in a cheap run reads as "Saves its power for ...", for up to 15 minutes ([[UX-62]]).
- A Leftover solar battery with no capacity set never charges from the grid when a solar forecast is set, and nothing warns about it ([[UX-63]]).
- The "How the modes work" box on the Batteries screen does not describe Cheap hours only ([[UX-64]]).
- With battery modes on, Settings still shows "Trade on the price spread", which the modes ignore. A site with modes on and no price source starts, and the Batteries screen says "No prices, so it follows the house" without pointing to Settings ([[UX-65]]).
- With battery modes off and several equal prices in a row, Home and the Forecast tab draw one price quarter, while the add-on trades every quarter of the run ([[UX-67]]).
- Late in the day, the Forecast tab's "now" line and last bars sit over the axis labels at the right edge ([[UX-68]]).
- The Forecast tab's level curve charges at each battery's full rating. Under a peak limit the levels it draws are too high and a charge block can end early (54.6 % shown against 39.7 % in a rig test) ([[UX-70]]).
- The peak forecast check says maintenance charging is not kept under the peak limit when no peak forecast is set, but since 0.19.2 it is ([[UX-73]]).
- The peak guard row can show the same figure twice, such as "at this rate 3 500 W, over 3 500 W". Also in 0.19.2 ([[UX-74]]).
- If the inverter's setpoint entity appears in Home Assistant after the add-on has started, the page keeps saying "Inverter control: not found in Home Assistant" and the batteries say "An alarm stopped control" until a restart, though control runs ([[UX-75]]).
- In the last minute of a 15-minute period, with Home Assistant readings 30 s late, the period can end about 80 W over the peak aim and over the limit: 3 530 W against a 3 450 W aim and a 3 500 W limit in a rig test with a 2 kW load added 45 s before the end. The peak guard sees the load too late to hold it back ([[SAFETY-133]]).
- With Home Assistant readings 10 s late, the grid charge in a cheap run can swing by several kW. In a test the add-on asked for an 8.7 kW charge (9.6 kW on 0.20.0) ([[SAFETY-132]]).
- A plan rebuilt while the battery levels are missing for a moment can drop a cheap run that has not started yet, so the battery does not charge that day. Seen in a replay of real prices, where it cost about EUR 0.40 of extra grid use; the Leftover solar change in 0.20.1 no longer triggers it in those replays, but the cause stays ([[OPT-37]]).
- On a 5 s meter, Home Assistant readings 10 s late are not caught, and readings 15 s late only after about 4 minutes. With a changing load such as an oven or a kettle, 21 to 142 Wh can go to the grid in a simulation, against 2 to 27 Wh with readings on time ([[SAFETY-136]]).
- With readings 10 to 15 s late, the hold can end in the middle of the delay and the swing can come back. Seen in rig tests with a 2 s and a 5 s meter ([[SAFETY-134]]).
- With readings 10 s late on a 1 s meter, the grid can still move between -422 and +340 W while the batteries are held. With a very long delay (30 to 90 s) the request can swing by about 900 W every few seconds. Seen in review tests ([[SAFETY-130]]).
- A battery that answers very slowly (10 s or more) can be taken for late Home Assistant readings and held, and the page then blames Home Assistant. A GoodWe battery settles in about 6 s and this has not been seen on one ([[SAFETY-131]]).
- The page row for late readings reads awkwardly in English ("Home Assistant readings show requests about N seconds late, so control holds the batteries"), and the Dutch text misses a word ([[UX-78]]).
- On a night grid charge held to the peak limit, the peak guard can stop the charge 1 to 3 s into a 15-minute period and keep it paused for that whole period. In a rig test this cost up to about 0.27 kWh of grid charge per run; it may come from the sped-up rig clock ([[SAFETY-135]]).
- When the add-on stops, a write that takes more than 2 s can still land after the 0 W, and the 30 s safety timer on the ESPHome board then sets 0 W. After the Stop button, a cycle that had already decided can send its share (560 to 670 W) just after the 0 W; the next cycle sends 0 W again ([[SAFETY-138]]).
- In the last hour of a cheap run, Home can draw a battery's grid charge up to an hour past the time control stops charging it. It only draws too much, never too little ([[UX-79]]).
- A tomorrow solar forecast sensor that reports just after midnight with yesterday's value can be used as the new day's forecast for up to 12 hours. This has not been seen on a site ([[OPT-39]]).
- During a cheap-hours charge, at some 15-minute boundaries the add-on sends 0 W for one tick ("no trade (headroom)") and then goes on. Seen in a rig test, in 5 of 8 cases; once, with a frozen battery reading, it left a battery at 0 W until 23:45 ([[OPT-40]]).
### If you are crossing from a version older than 0.10.0
`## 0.10.0` below can refuse an old config: `slew_w` above its limit, and the
withdrawn `price_provider` ids `engie_dynamic`, `totalenergies_dynamic` and
`eneco_eddy`. Read it before you update. Run `tools/predeploy_check.py` with the
bare options (`jq '.data.options'`) first.
- Home now draws today's charge from the grid for every hour the add-on will really charge, not only the run under way ([[UX-77]]).
- When Home Assistant passes readings on late, control no longer swings on them: it waits until the battery shows its last power request, and the peak limit no longer asks for full power on them. The page says so, and if the readings stay too late every inverter goes to 0 W ([[SAFETY-128]]).
## 0.20.1
@@ -60,7 +174,7 @@ Contents of this release, in merge order since 0.20.0 (`01e88a2`):
- After the add-on restarts, the Home price chart shows no price for the earlier part of today, and the setup check can say "12 of 24 hours", though the prices are known ([[UX-48]]).
- With battery modes on and only batteries on "Leftover solar", the Home price chart can mark a cheap period where no battery charges ([[UX-49]]).
- On a phone, the bars of the Home price chart are too thin to tap one 15-minute period. The arrow keys work ([[UX-50]]).
- Control acts on Home Assistant readings that arrive late. With readings 10 s behind, the give run can swing and send up to 1.9 kW to the grid for about 50 s in a rig test; with readings 30 s behind, a battery can charge from the grid in an expensive period. Also in 0.19.2. A fix is made for the next release and is not in 0.20.1 ([[SAFETY-128]]).
- Control acts on Home Assistant readings that arrive late. With readings 10 s behind, the give run can swing and send up to 1.9 kW to the grid for about 50 s in a rig test; with readings 30 s behind, a battery can charge from the grid in an expensive period. Also in 0.19.2. The fix is not in 0.20.1; it ships in 0.21.0 ([[SAFETY-128]]).
- In the last second of a 15-minute period, being a few watts over the aim can make the peak guard ask a battery for full power for one second. When a charge ends on a period edge, the last-second give can fade out over about 10 s, and a rig test exported up to 7.4 kW for about 8 s ([[SAFETY-124]]).
- During the night grid charge, a 15-minute period can end 6 to 14 W over the peak aim, because the battery charges harder than asked. This was seen in simulation; a rig test saw 2 to 8 W ([[OPT-35]]).
- The test rig could not bring back the false peak alarm that [[SAFETY-126]] fixes, so that fix is shown in simulation only. Watch the notifications for a few nights ([[TEST-35]]).
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,52 @@
# MAIN - why app/main.py is built the way it is
**Status: SHIPPED.** Written down by MAINT-20 part 2 from the long comments and
docstrings of `app/main.py`, so the module can keep one line and a pointer. The
comments that were shortened but not rewritten here are kept word for word in
[[MAIN-orchestration-archive]], by their line in `app/main.py` at release/1.0
`d4c01da`. Related: [[SAFETY-07-peak-guard]], [[FCST-04-the-day-that-is-carried]],
[[SAFETY-30-per-unit-sign]], [[SAFETY-73-refusal-per-inverter]],
[[SAFETY-121-bound-every-quarter]], [[TARIFF-10-fetching-is-not-trading]],
[[TARIFF-24-modes-need-the-tariff-task]], [[OPT-34-the-night-charge-keeps-its-level]].
## Controller construction
- **Per-write budget (DEV-02).** Each write is dispatched concurrently and bounded, so one hung `hass.call()` cannot eat a sibling's layer-1 budget (the ESP32 zeroes after about 30 s, and a fault on A could zero a healthy B). The number is derived: `heartbeat_s` max 25 s, layer-1 veto `validate.FIRMWARE_INGEST_VETO_S` 30 s, so 25 + 4 < 30. test_inverter.py grades the inequality, so raising the heartbeat ceiling goes red instead of taking an inverter to zero. Below hass.py's 10 s HTTP timeout on purpose: abandon the write and re-issue it next tick, since `last_write` moves only on an accepted write.
- **Tariff refresh (OPT-04).** `resolve_tariff()` may do an HTTPS fetch. The tick feeds the ESP32 heartbeat, so a supplier's TLS timeout on the tick would push the add-on into layer 1. The tick never awaits a fetch. The 30 min cadence is not about price change (day-ahead publishes once at 14-16 h CET and 8.3's carried hours go firm then); it picks the switch up within the hour at 48 fetches a day. The age bound answers another question: a failed refresh still stores a plan (the 11.4 static fallback), the bound covers the refresh task dying while a plan from hours ago stands as current. Three missed refreshes, for `p1.max_age_s`'s reason.
- **Status rows (TARIFF-11).** The Tariff row used to be `static_status()`'s sentence alone and never saw the provider plan (read 'no static profile' at all 802 samples of a 40 h soak with a live feed). `tick_words` and `plan` are two clocks and the row says so; the plan is stamped with its own age from `tariff_at` (TARIFF-12 does not move it on a kept plan), and `age_s` is the caller's measurement. The Arbitrage row used to be `"off (arbitrage_enabled)" if self.arb is None`, under a comment saying `arb is None` iff trading was off; false, since `cycle()` returns at the input hold before `self.arb = None`: `arbitrage_enabled: true` plus a sensor answering None rendered 'off (arbitrage_enabled)', naming an option that is on, and past the first cycle the previous decision stood as current. Three states: off, armed with no decision this cycle, a decision with its age (always printed: a row that reports staleness only once stale cannot be told from one that never does).
- **`stop` is required (review catch).** `stop=None` made a Controller that cannot stop itself the default: on the late-refusal path in `run_control()` it logged the banner, returned and left the process alive forever with no loop and no output.
- **Action log first.** The store migration can log to it (15: how an operator finds a latch was re-armed); an AttributeError on the way to saying so would stop the add-on booting.
- **Roster and migrations (DEV-02, SAFETY-44, MAINT-05).** Every per-device value lives on the roster objects (app/inverter.py); a `Tuning` and an integrator are deliberately not per device (6.2: one integrator on P1 above the split; a second regulating the same meter is the two-writers failure). The SAFETY-02 key migration runs before the first `Inverter` reads its latch, else a tripped install comes up armed with a green banner. SAFETY-44: it is handed `roster_names(opts)[0]`, never `UNIT_A` (on a declared roster the flat latch landed under `unit/inverter-a/`, read back under the name it was handed, stamping the marker); `roster_names()` returns `[UNIT_A]` on the flat shape so today's path is byte-identical. `misdirected` is unreachable from that call site (`unit` is a roster member by construction; dropping the `roster` argument survives 28/28), so the claim that the call site buys the refusal is gone; the argument stays for new callers and is graded in test_maintenance.py. The maintenance migration targets `self.inverters[0].name`, not `UNIT_A`: with `UNIT_A` the history would sit under a name on no roster (a nameless entry falls back to a positional `inverter-1`). Every two-pack fixture once named its first entry `inverter-a`, so swapping them left 19 files green; `migrate_maint_keys()` now grades the namespace it wrote against the names the machines read, and test_maintenance.py sections 9 and 11 use `["garage", "shed"]`.
- **CFG-04 disclosure.** A declared `inverters:` roster ignores `soc_entity`, `batt_entity`, `batt_invert` and `max_w`, which the UI still shows. Rule 9(e) refuses the dangerous one (a flat `setpoint_entity`); the rest cannot be refused (the schema has no blank value) so one action-log line at every start names the roster and the ignored keys.
- **Site bound.** Summed from the roster, not `opts["max_w"]`: it is the integrator bound and rail of the site loop, then split. Identical at N=1; a per-unit `max_w` binds each share through its `supervised` claim.
- **SAFETY-39 slew fallback** is 0 ("follow the rail"); it was 1000, a stale third copy. `control.slew_limit_w()` is the one reader.
- **CFG-03 in main.py.** Eight `opts.get(key, <literal>)` calls used to live in the maintenance setup and two disagreed with config.yaml (2500 against 2000). `MaintConfig.from_options()` reads them. A ninth key goes in config.yaml `options:`/`schema:` and `maintenance.MAINT_OPTION_DEFAULTS` only.
- **Watchdog thresholds (SAFETY-30).** The per-unit pair is re-derived at two inverters, not carried (it grades a command against one unit's own power). The site pair is used only at N>=2: the 300 W threshold carries (meter noise, deadband), the window does not (110 s at one inverter, 215 s at two, against a 180 s hold).
- **Latches (SAFETY-02, -31, -34, -42, -18).** SAFETY-02: one per actuator, restored from namespaced keys; graded on every start (a latch that failed to move namespace, or was taken by an older add-on in a rollback, is a disarmed guard, so a disagreement re-arms by hand and shouts). SAFETY-31: site-level, flat keys (circulating power is defined over the roster), restored because it acts. SAFETY-42's delivery latch does not act, so it is restored only so the ALARM survives (the 2026-09-02 outage went unseen 6 h 25 m with the detector correct). SAFETY-18 is not restored (does not act). SAFETY-30's site check is armed only at N>=2.
- **PV (TEL-11).** Instrumentation only; wiring it in would be an unrequested behaviour change and would destroy the measurement.
- **Peak guard setup (SAFETY-07, TARIFF-01, FCST-04).** See SAFETY-07-peak-guard.md and FCST-04. The windowing caveat for FCST-04: hours already elapsed leave the spread, so a cheap night that has gone no longer sets the day's cheapest hour.
## Cycle state and latch repair
- **Allocation record (SAFETY-28).** The tick that mints a record increments once per resolution, not per loop iteration. A cycle with no resolution (the "inputs missing, not yet stale" hold) must not bump it: that hold returns before the allocator so one missed poll does not zero the inverter, and the heartbeat re-affirms `self.target` through the write path; bumping would make that heartbeat unauthorised and drop the site to 0 W. The record is superseded, never expired.
- **`self.arb` (TARIFF-11).** See "Status rows" above; `arb_at < cycle_at` is the derived "the latest cycle did not reach the arbitrage step".
- **Shadow (SAFETY-10, SAFETY-47).** `shadow_would_w` is what a live controller would have put on the wire; `self.target` is what is standing on the wire (held at `shadow.WIRE_W`, re-seeded each shadow cycle). Folding them shows an operator a number nothing is doing. The "sized from the billed-quarter meter" flag is recorded where the decision was taken (the page runs on its own task); False, not None, before the first shadow cycle.
- **ARB-03.** `units` is a property derived from the roster so a site cannot claim two actuators while holding one writer. At N=1 (6.2) the grid connection and the only inverter are one actuator; a second entry makes per-inverter claims stop being site claims (ALLOC-01).
- **DEV-02 latch guard (`_check_sign_latch...`).** Runs on every start: gating on `rep.ran` swallowed store.py's rule-2 round trip (upgrade, downgrade with a trip in the window, upgrade; the controller came up untripped while state.json said `sign_tripped: true`; a firmware rollback path was performed on this site on 2026-09-02). The gate could go because `handle_action()` clears the flat keys with the namespaced ones and the trip mirrors them. SAFETY-44 second half: the question is whether a namespaced latch THAT A MACHINE READS is set. An earlier version accepted any `unit/*/sign_tripped`, which blinded the guard on exactly the installs the broken migration had put the latch under `unit/inverter-a/` (a key nothing reads). The first blunt fix (every off-roster latch is litter) re-armed a healthy A off B's mirrored flat key (test_inverter.py DEV-02 restart case). `UNIT_A` is the discriminator: the only name the broken migration wrote. A single flag written for two intents was defeated by one removed unit's key (roster ['garage','shed'] with `unit/old-shed/sign_tripped` drove on a state file reading `sign_tripped: true`; `tools/rehearse_roster.py` exit 1); the fixtures now hold both arrangements. Residual: a first unit really named `inverter-a`, latched and removed from the roster is re-armed on `inverters[0]` (conservative). The printed reason is the flat mirror's (whatever tripped last), so on a multi-unit site one inverter's evidence may appear under another's name; test_maintenance.py's check that the reason is not the removed unit's depends on that fixture's flat string, not on this code.
- **Maintenance views (MAINT-05).** `maints` is one FSM per roster entry; `maint`, `maint_unit` and the button target are views of the one that holds the slot (`maintenance.arbitrate()` allows at most one out of IDLE). validate.py rule 6 grades `maintenance_charge_w` against the weakest cap on the roster.
- **N=1 views.** Properties, not fields, and they refuse at N>=2 (6.2's identity is false there). Nothing inside main.py may read them (test_inverter.py AST scan).
- **`_arm_sign_watchdogs` (SAFETY-30).** Called every cycle because fixtures append an `Inverter` after construction; a detector frozen at construction would be graded against the meter at a roster of two. `arm()` touches no timer or latch.
- **Per-inverter refusal (SAFETY-73).** The probe ask is PROBE_W, not `saturation_w`: a unit's share is often small (a 400 W night load split two ways) and SAFETY-43 would name the empty battery as not delivering. The site target is restarted from the watts on the wire when a unit reopens (phase A: -1059 W).
## Write path and cycle
- **The write gate (SAFETY-28).** specs 1.5 makes two writers on one actuator a non-goal. `len(validate.ACTUATOR_WRITE_KEYS) == 1` is a fact about the options schema, not the writes, and goes false when CFG-04 adds per-inverter config. So the enforcement is on the write: a number reaches the wire only if the single allocator placed it, on this tick, for this unit (`Allocation.authorises()`); a second writer must file a Claim. 0 W is always authorised and the test for zero comes first and reads nothing: the failsafe branches write 0 W while the allocator has refused (`Allocation.ok` False, no shares), and a gate asking its permission would deadlock the failsafe behind the component it answers; at S = 0 broadcast and allocation coincide, so there is no over-command (the hazard is N-times loop gain from broadcast, TEST-19's `N=2 gain 1.0` limit cycle). The predicate is `value == 0.0`, not a `failsafe=True` flag, which a second writer would pass; -0.0 == 0.0 and a nan never gets here. DEV-02: the unit is an argument, not the N=1 view; the default refuses at N>=2. The refusal sits above the clamp and below the non-finite coercion.
- **Clamp (SAFETY-03)** is on the only path to the wire, so no optimizer, maintenance or manual path routes around it. A non-finite value is loss of input (11.1), coerced to 0 W. Every engagement goes to the action log undeduplicated; the notification is deduplicated.
- **Shadow (SAFETY-10)** suppresses in the same method, below the gate and the clamp, as a substitution not a return. It is not a second writer.
- **Reads (DEV-02, TEL-12).** Each inverter's readings are gathered concurrently across units and sequentially within one; PV entities ride in the same gather (a slow sensor must not push a healthy battery toward layer 1's veto). P1 has no inverter-side fallback: the inverter's AC power correlates 0.998 with battery power and 0.09 with the real meter.
- **Stale reading (SAFETY-37/56/57).** The power reading goes through the freshness gate, the SoC does not (the power feeds the sign and delivery checks, which a frozen register fools). SAFETY-57 rewrote the escape clause: "it clears itself when the register reports a different value" was false for the state announced, because the 0 W it announces is what stops the value changing. The release is reported, never silent (it withdraws a SITE STOP).
- **TARIFF-03.** The one shiftable load is the maintenance cycle's cheap-window top-up; the static window is synchronous and I/O-free, and validate.py refuses `static_profile` together with the price entities.
- **Cycle ordering (SAFETY-02/31/42).** The watchdog evaluations run every cycle, before the input hold, so a run of held cycles cannot leave their timers resuming from a start that predates the gap. Reason first, flag second (each `set` writes the file): a crash between persists a reason nothing reads, not a latch with no explanation. The per-unit trip mirrors the legacy flat keys (store.py rule 2 covered only the latch present at migration time). The site check is flat-keyed, armed only at N>=2. SAFETY-31's input is MEASURED power (`inv.batt`), never the allocation record, which has sign-coherence by construction.
- **Maintenance FSMs (MAINT-05).** Each pack is ticked with its own SoC (a minimum would abort a cycle on a sibling's state, an average would declare a pack full that is not); `arbitrate()` runs first. A deferral is carried to the status page because the edge-logged line scrolls out of the 40-row log.
- **Aggregates.** SUM for the site bound, achievable rating and the battery power the site loop regulates against (`compute()`'s saturation test compares against the site target; one unit's power trips the freeze permanently, up to 510 W of split-dependence at gain 0.2, test_alloc.py part 8). MINIMUM for the discharge permission (the emptiest pack). MEASURED power for circulating power. Unknown bounds stay unknown when any unit is silent.
- **Trade sizing (OPT-09).** `trade_sizing` uses arbitrage's own SoC bounds, not the BMS cut-out (SAFETY-25): sizing is the trade's business, the pack envelope is the pack's. Weights are a preference, so a pack between its arbitrage floor and its cut-out can still take part of a sell; fixing it needs a per-pack envelope depending on which claim won the tick.
@@ -44,3 +44,5 @@ tonight." (`home_words.solar.kept`, EN and NL). The event log says
**Not changed.** Control with modes off: it does not use the forecast. The
screens still show the line, so it says "kept", not "used for the plan". A
forecast that stays fresh. The hold does not look at the weather, only at the clock and the day.
**OPT-38 (2026-11-07).** A kept TOMORROW reading (at most `KEPT_MAX_AGE_S` old, same `day0`) now stands in at any hour, not only from `BELL_TO_H`: one sensor that stopped at 14:54 had dropped the whole sum (OPT-17) from 17:54 to 20:00. Today readings and the OPT-34 morning rules are unchanged; `test_opt38.py`.
@@ -31,7 +31,12 @@ inverter limit in its last seconds (OPT-34 rig F-2).
- **Meter** (`MeterFit`, round 1's fit): `meter(t) + request(t - d)` is the
house alone at the right `d`. Quick, but confounded by the house. Needs
16 new values in 60 s, so only a meter of about 3.5 s or faster: at 5 s
it gave false delays. Late over 8 s.
it gave false delays. Late over 8 s. At a slower meter (a 5 s P1) the
same fit runs over 120 s and calls only a delay over 16 s late, on 2 fits
in a row, and never ends a verdict (SAFETY-129). Alone it reads 35-90 s on healthy
runs, a few times in a row; only the slow-start and battery-fit check
below keeps those from a verdict. 10 s late is not found: it cannot be
told from a 10 s slow battery, and it does not swing at 5 s.
- A meter fit says late only with evidence from the batteries' side too:
a request more than 100 W from the battery reading took 3 s or more to
move a reading towards it (`SLOW_START_S`; on time they start within
@@ -64,9 +69,12 @@ house at 1, 2 and 5 s ticks, so the commands are the same as without the gate.
The fits run all the time; the pull request has the counts.
**What it costs.**
- Found 36-68 s after a lag starts at 1-2 s meters, about 3 minutes at a 5 s
meter (battery fit only; the meter fit needs a faster meter). Until then control is as before. At 5 s and 30 s
late the export is cut to about a third, not removed.
- Found 36-68 s after a lag starts at 1-2 s meters; at a 5 s meter 30 s late
is found within 100 s after it starts (88 s measured) (the loop first moves 100 W after 60 s,
SAFETY-129) with the export above -200 W, and 10 s late is not found. Until
then control is as before. In a quiet house the "readings late" row stays
about 2 minutes longer after the lag ends (126 s against 32 s on base); no
harm measured, and it clears as early as on base when the load changes.
- A battery that answers slowly is read as late readings and held: a dead
time of 10 s or more (8 s reads 7-8; 10 s reads 10 at 1-2 s meters, 9 at
5 s), or a 15-20 s lag (review round 2). The GoodWe measured settles in 6 s
@@ -0,0 +1,21 @@
# SAFETY-137 - the shutdown 0 W is the last write every unit hears
SMA-10 made a hand-back release wait for a write already on its way
(`_release_last`, `Inverter.inflight`). A GoodWe unit skipped that, and rig 5b
saw a cycle write (-2 823 W) land after the shutdown 0 W and stay until relaunch.
Now the 0 W of shutdown and of the Stop button is a *last* write
(`_write_unit(last=True)`), for every driver:
- It first waits, at most `SETTLE_BUDGET_S` (2 s), for the writes already on
its way to that unit (`_await_inflight`, shared with `_release_last`). A hung
write is not waited out and not cancelled; the 0 W goes anyway.
- Once shutdown has begun (`stopping`), every other write (cycle, heartbeat,
safety stop) is dropped at the same place, right before the write is created.
That is the gate that keeps the control cycle quiet; the cycle itself needs
no cancelling.
- Worst case for a GoodWe unit is 2 s + `WRITE_BUDGET_S` (4 s) = 6 s, the same
as `HAND_BACK_WORST_S`; the units are handled together.
Not touched: the heartbeat's own timing, safety-stop paths, the maintenance
abort (still a plain 0 W).
@@ -0,0 +1,62 @@
# SMA-10 - two idle states: hold 0 W, or hand the inverter back
**Status: for review.** Tests: `test_sma10_two_idle_states.py`. Source: SMA-9
report sections 1.4, 3.2; owner decision 2026-10-20 (Q1, "as proposed").
A unit is idle in one of two ways, and the driver says which:
`Driver.hands_back`. **False (GoodWe):** the add-on holds 0 W, `release()` is
`write(0)` and the Controller never calls it, so Stop keeps today's 0 W write and
today's 0 W heartbeat. **True:** `release()` gives the unit back to whatever
steers it by itself (SMA energy management), once, and then nothing is written
to it until control starts again.
**Why two.** When the add-on goes away (Stop, shutdown, SIGTERM, restart, task
death, a config refusal) nobody is left to hold a number, so the unit goes back
to its own controller. When the add-on itself decides to stop (sign trip, site
sign, circulating power, a refused or non-finite write, missing readings,
another writer, an inverter fault) it has just said it cannot trust that
battery, and handing it to something else would let that something do what it
likes with it. Those hold 0 W through `write(0)` for every unit, whatever its
driver. Shadow mode on a unit that hands back uses `release()`: it must leave
the unit alone, and 0 W would be a command.
**Where.** `Controller.command_site_release()` sits beside `command_site_zero()`
(unchanged). Stop and `shutdown()` call it; the two maintenance-abort paths keep
zero (the add-on runs on, the sentence says 0 W for a moment). With no
hand-back unit it is `command_site_zero()`. `_write_unit()` also refuses to write
a hand-back unit while the add-on is idle (stopping, stopped, or shadow mode): it
releases once and returns, so the heartbeat and the cycle's own "stopped" 0 W
cannot reach it. A safety stop runs while control runs, so it falls through to
the write. Start re-arms: `released` drops and `last_write` clears.
**Bounds.** `RELEASE_BUDGET_S` equals `WRITE_BUDGET_S` (4 s): units are released
together, so one slow unit costs the kill window no more than a hung GoodWe
write does. A release at the bound is abandoned, not awaited. A release that
raises, hangs or returns false leaves that unit un-handed (the next idle write
tries again) and does not touch the others. Exit 78 before the Controller
exists has no driver to release and keeps today's path.
**Words.** Every sentence that said "set to 0 W" for the add-on going away or
for shadow mode is built from the roster in `app/handback.py` (EN and NL): a
roster with no hand-back unit gets None and keeps its old literal, so a GoodWe
site sees no changed byte. A hand-back unit's words (`Driver.words`: `back`,
`back_nl`) come from its driver; one without them gets "its own control" /
"de eigen sturing" (the article as in the generic clause; PR #239 review
comment 2495, not the brief). MQTT `status` is unchanged; the Home battery
row of a handed-back unit says "Back under SMA control" and carries
`handed_back`.
**Not done here (SMA-4, SMA-5, SMA-11):** any SMA/FoxESS driver, the read-back
after `release()`, per-driver timing, DOCS.md's safety model and the
"control stalled" sentence, the site-level "Held at 0 W" tiles in shadow mode on
a mixed roster, and the MQTT per-unit setpoint of a handed-back unit (it still
publishes 0).
**After a failed release** (returns False, raises or hangs past the bound) the
unit gets one `write(0)` through `Driver.release_fallback()` (default
`write(0)`; a driver where 0 W is not always safe overrides it), then nothing:
a repeated 0 W would keep resetting the inverter's own fallback timer, so after
that the unit is left to its own fallback. The release is retried once per
heartbeat; one error line and one action-log event per failure streak, one line
on recovery. Worst case at shutdown is `RELEASE_BUDGET_S` + `FALLBACK_BUDGET_S`
(6 s).
@@ -0,0 +1,55 @@
# SMA-2 - each inverter is reached through a driver
**Status: for review.** Tests: `test_sma2_driver.py`. Source: SMA-9 report
section 1.1. A pure refactor: no behaviour change for GoodWe, no change to a
command, a log line or a sentence the add-on shows.
Every place that read or steered an inverter used the GoodWe ESPHome entities
directly, so a second make meant touching all of them. `app/drivers.py` now
holds one `Driver` per roster entry (`Inverter.driver`): `configured()`,
`actuator_id()`, `limits()`, `read()`, `write()`, `release()`, `probe()`, and
`link_stale_s`, `batt_bound`, `settle_s`, `brand`, `words`. `GoodWeEsphomeDriver`
makes the same calls in the same order as the code it replaced; its
`release()` is `write(0)`.
**Moved to the driver:** the SoC and power read (`_read_unit`), the write
(`_write_unit`, still under the SAFETY-28 gate, the clamp, shadow mode and the
write budget), the device range (`run_control`, `amain`, the settings panel),
liveness and its window (`has_writer`, `is_live`, `link_note`), the freshness
bound, the status rows' "is a source set" test, rule 2's per-unit range check
and SAFETY-28's census. **Not moved:** the clamp, the gate, the heartbeat and
`command_site_zero()`; stop is still 0 W for every unit, and nothing calls
`release()` yet (SMA-10). `settle_s` and the control constants are not read
from the driver yet either: with only GoodWe they would change nothing.
**The seam is not TCP-shaped.** The census asks each entry's driver for its
actuator id: the setpoint entity for GoodWe, `host:port:unit_id` for a driver
reached over a socket, so two units behind one gateway are two actuators and
one unit named twice is the SAFETY-28 refusal. The census still counts every
`setpoint_entity` key as before and adds the driver's own actuator to it (parity
with 23ff9d0 on 349 option shapes is a test). The driver binds its Home
Assistant on first use by the Controller, so a unit added later is wired too.
**Schema, and why the new keys are not in it.** The brief asks for
`driver`, `host`, `port`, `unit_id`, `maintenance` per entry and for
`setpoint_entity` to become optional. Owner decision 2026-11-07: clients see
nothing new until SMA-4/SMA-7 use the keys. The Supervisor form shows every
schema key (and marks required ones), and a nested entry with a key the schema
lacks has that key silently dropped (measured, shape probe section K), so the
only way to hide them is to keep them out of config.yaml. So for now config.yaml, the
translations and the labels are exactly 23ff9d0's, and `setpoint_entity` stays
required there: until a driver without one is selectable, no entry can lack it.
The code underneath is the brief's: the driver defaults to `goodwe_esphome`,
rule 9(d) is per driver (a GoodWe entry without a setpoint entity is refused,
same sentence), and rule 9(h) checks `driver`, `host`, `port`, `unit_id`,
`maintenance` when a caller that skips the schema (the panel's save path,
sim/inject, the checks) supplies them; those sentences name the key, having no
label. When SMA-4 needs them: add them to the schema as optional with
translations, make `setpoint_entity` `str?`, and add them to `uilayout` as card
fields or a hidden list.
**Checked against 23ff9d0:** replay digests and a log of every Home Assistant
call are byte-identical at N=1 and N=2; the TEL-07 announce diff is 0/0/0; a
fake driver beside a GoodWe unit allocates, grades, drops and publishes per
unit; a call site that goes round the seam is caught.
@@ -101,8 +101,9 @@ is `SolarToday.add()` after the solar read, in a `try`, in memory.
control will stop charging, as the tab does for tomorrow's: the cheap run
rolls on at its end while a battery is short (`cheaproll.roll_end()`, the
same loop as `dayview._levels()`), the level read at the charge power the
peak limit leaves (peak aim less the house, else the rating), and each
battery's block ends at its own stop. The curve stops charging at its level
peak limit leaves (peak aim less the house, else the rating) and shared by
room left to full as control shares it (`packshare.weights()`, re-read as
the levels move), and each battery's block ends at its own stop. The curve stops charging at its level
(`charge_to()`) and giving at the floor.
- Today, a give run in the plan on a battery that is empty now has no block on
Home (no energy to give). The tab equals Home, and says so: "The add-on plans
+36 -5
View File
@@ -10,8 +10,10 @@ that goes on until the batteries are at their level or the cheap hours end.
(`modetrade.energy()`, `priceruns.plan()`), until nothing is short or the next
run does not follow on. `for_today()` reads the batteries at the level they
will have by then: the charge power is the peak limit's room (peak aim minus
the house, as `dayplan` counts it), shared by rating. Where that room is not
known (no house profile or no aim), the rating is used.
the house, as `dayplan` counts it), shared as control shares it: by room
left to full (`packshare.weights()`), read again as the levels move, so a
battery that fills drops out and its share goes to the others. Where that
room is not known (no house profile or no aim), the rating is used.
DECISIONS/UX-54-forecast-tab.md has the record.
"""
@@ -20,7 +22,7 @@ import math
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from . import arbitrage, dayplan, modetrade, priceruns
from . import arbitrage, dayplan, modetrade, packshare, priceruns
from .dayplan import EFF
from .price import required_spread, uncertainty_of
@@ -85,7 +87,7 @@ def _ceil_slot(t):
class _Charge:
"""The batteries' levels followed from `t0` while the chargers charge at
the room the peak limit leaves: `min(sum of ratings, aim - house)`, shared
by rating, each stopping at `modetrade.charge_to()`."""
by room left to full as control does (`_shares()`), each stopping at `modetrade.charge_to()`."""
def __init__(self, packs, t0, ceiling_pct, targets, aim_w, house):
self.packs = {p.name: p for p in packs}
@@ -115,6 +117,34 @@ class _Charge:
self._charge(s, e, hour)
self.t = nxt
def _shares(self, ch, w):
"""Watts per charger: `w` shared by `packshare.weights()` over all
packs (room left to full, as control passes it), no charger above its
rating, the surplus going to the others. By rating where the room left
is not known (no capacity)."""
wt = packshare.weights(list(self.packs.values()), -1.0)
if wt is None:
wt = {p.name: abs(p.rating_w) for p in ch}
wt = {p.name: wt.get(p.name, 0.0) for p in ch}
cap = {p.name: abs(p.rating_w) for p in ch}
out, open_, left = {}, set(wt), float(w)
while open_:
tot = sum(wt[n] for n in open_)
if tot <= 0.0:
for n in open_:
out[n] = 0.0
break
over = [n for n in open_ if left * wt[n] / tot > cap[n] + 1e-9]
if not over:
for n in open_:
out[n] = left * wt[n] / tot
break
for n in over:
out[n] = cap[n]
left -= cap[n]
open_.discard(n)
return out
def _charge(self, s, e, hour):
ch = modetrade.chargers(list(self.packs.values()), self.ceil,
targets=self.targets)
@@ -123,12 +153,13 @@ class _Charge:
return
w = self._room_w(hour, total)
hrs = (e - s).total_seconds() / 3600.0
share = self._shares(ch, w)
for p in ch:
self.stops.setdefault(p.name, None)
if not p.capacity_kwh:
continue
to = modetrade.charge_to(p, self.ceil, self.targets)
kwh = w * abs(p.rating_w) / total * hrs / 1000.0 * EFF
kwh = share[p.name] * hrs / 1000.0 * EFF
room = (to - p.soc) / 100.0 * float(p.capacity_kwh)
if kwh <= 0.0:
continue
+320
View File
@@ -0,0 +1,320 @@
"""The inverter driver seam (SMA-2): how this add-on reads and steers ONE inverter.
Before this, every place that read or steered an inverter talked to the GoodWe
ESPHome entities itself (`hass.limits`, `hass.number`, `hass.set_number`, the
SAFETY-28 census, selfconfig, validate), so a second brand meant touching all of
them. Now each `Inverter` holds a `Driver`, and those places ask it. This card
is a pure refactor: `GoodWeEsphomeDriver` does exactly what the code it replaced
did, in the same order, with the same arguments. DECISIONS/SMA-2-driver-seam.md.
THE SEAM IS NOT TCP-SHAPED. Nothing here assumes a connection, or one connection
per host: a later FoxESS unit is RTU framing over a TCP socket, and its
`actuator_id()` is host:port:unit_id, so two units behind one gateway are two
actuators and one unit named twice is the SAFETY-28 refusal.
WHAT STAYS OUTSIDE THE DRIVER, on purpose. The gate (SAFETY-28), the clamp
(SAFETY-03), shadow mode and the write budget all sit above `write()` in
`Controller._write_unit`, and the freshness gate sits above `read()`; a driver
never sees a value those did not pass. A driver moves one number to or from one
inverter and says whether it worked.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from .control import PLANT_SETTLE_S
from .freshness import BOUNDS
# How long every write to one GoodWe inverter must have been REJECTED before
# this controller stops claiming it can command it. Layer 1's own window: the
# ESP32 commands 0 W after ~30 s without a refresh (`validate.
# FIRMWARE_INGEST_VETO_S`). `inverter.LINK_STALE_S` is this number, re-exported.
GOODWE_LINK_STALE_S = 30.0
# `driver` when an entry does not say: every install that exists today.
DEFAULT_DRIVER = "goodwe_esphome"
# The `driver` values the options accept. Only the GoodWe one for now; the
# registry below may hold more (a test registers a fake), but this tuple is
# what validate.py rule 9 lets through and what config.yaml's schema lists.
SELECTABLE = (DEFAULT_DRIVER,)
class DriverNotBound(RuntimeError):
"""A driver was asked to talk to the world before it was given a Home
Assistant. A wiring bug, so it is loud rather than a quiet "no answer"."""
@dataclass(frozen=True)
class Probe:
"""What a read-only look at one inverter found. None means "did not answer"."""
dev_min: float | None = None
dev_max: float | None = None
soc: float | None = None
batt_w: float | None = None
extra: dict = field(default_factory=dict)
def census_key(actuator_id: str) -> str:
"""The form SAFETY-28 compares: stripped and lowercase, so a config cannot
name one actuator twice by changing its case (`Number.X` vs `number.x`)."""
return str(actuator_id or "").strip().lower()
class Driver:
"""One inverter's I/O. Subclasses set the class attributes and the methods.
Constructed once per roster entry, with no Home Assistant: `bind()` gives
it one (the Controller does, and so does the settings panel, which has no
Controller). Everything that talks to the world is a coroutine.
"""
#: the `driver` option value that selects this class
name = ""
#: the option key that names the actuator in an entry (the census reads it)
writer_key = ""
#: the brand word the per-driver sentences and device names use
brand = ""
#: SMA-10. Does `release()` give the inverter BACK to something that steers
#: it by itself (SMA energy management)? False: `release()` is `write(0)`,
#: the add-on goes on holding 0 W, and the Controller never calls it.
hands_back = False
#: per-driver sentences. A driver that hands back says whose control the
#: unit returns to: `{"back": "SMA control", "back_nl": "de sturing van SMA"}`
#: ("goes back to SMA control"). Missing words fall back to a plain phrase.
words: dict = {}
#: how long all-rejected writes last before the unit stops being live
link_stale_s = GOODWE_LINK_STALE_S
#: this driver's `freshness.Bound` for the battery power reading
batt_bound = BOUNDS["batt"]
#: the plant's settling time after a step, in s (control.PLANT_SETTLE_S)
settle_s = PLANT_SETTLE_S
# -- from the options ----------------------------------------------------
@classmethod
def from_entry(cls, entry: dict) -> "Driver":
raise NotImplementedError
@classmethod
def actuator_id_of(cls, entry: dict) -> str:
"""The actuator an options entry names, or "" for none. Pure: the
SAFETY-28 census runs on options, before any driver exists."""
raise NotImplementedError
# -- wiring --------------------------------------------------------------
def bind(self, hass) -> "Driver":
"""Give this driver its Home Assistant (or whatever it talks through)."""
return self
def bind_getter(self, getter) -> "Driver":
"""Like `bind()`, but looked up at each use: the Controller passes
`lambda: self.hass`, so replacing `controller.hass` is seen at once."""
return self
def bound(self) -> bool:
"""Has it been given what it talks through? A driver that talks
through nothing the Controller owns is always bound."""
return True
# -- what it is ----------------------------------------------------------
def configured(self) -> bool:
"""Is there any way to reach this inverter at all?"""
raise NotImplementedError
def actuator_id(self) -> str:
"""What this driver writes to. Two units with one id are one actuator."""
raise NotImplementedError
def soc_source(self) -> str:
"""Where the pack level is read from; "" when nowhere. Status rows only."""
return ""
def batt_source(self) -> str:
"""Where the battery power is read from; "" when nowhere."""
return ""
# -- what it does --------------------------------------------------------
async def limits(self) -> tuple:
"""`(dev_min, dev_max)` in W the device accepts; (None, None) unread."""
raise NotImplementedError
async def read(self) -> tuple:
"""`(soc, batt_w, extra)`. A value that did not arrive is None. `batt_w`
is the RAW power, in the sign the controller uses; the freshness gate
is the caller's."""
raise NotImplementedError
async def write(self, w: float) -> bool:
"""Put `w` on the inverter. True only when it took it."""
raise NotImplementedError
async def release(self) -> bool:
"""Stop steering this inverter. For a driver with nothing better, 0 W.
SMA-10. Only a driver with `hands_back = True` has this called by the
Controller, and only when the add-on goes away (Stop, shutdown, restart,
task death) or sits in shadow mode. After it the Controller writes
nothing more to the unit until control starts again. A safety stop is
never a release: that is `write(0)`."""
return await self.write(0.0)
async def release_fallback(self) -> bool:
"""SMA-10 round 2. What to send, ONCE, when `release()` has failed
(False, raised, or hung past the bound), so the unit does not carry its
last command while nothing else steers it. Default: `write(0)`. It is
not repeated: a repeat would keep resetting the inverter's own fallback
timer. A driver for which 0 W is not always a safe hold overrides this."""
return await self.write(0.0)
async def probe(self) -> Probe:
"""A read-only look, usable without a Controller (panel, wizard)."""
raise NotImplementedError
class GoodWeEsphomeDriver(Driver):
"""The GoodWe behind the ESP32: three Home Assistant entities.
A transcription of what `main.py` and `selfconfig.py` did inline: `limits()`
is `hass.limits(setpoint)`, `read()` is `hass.number(soc)` then
`hass.number(batt, invert)`, `write()` is `hass.set_number(setpoint, w)`.
`release()` is `write(0)` and `hands_back` is False: the board's own watchdog
is what hands back, so after Stop the unit keeps its 0 W write and heartbeat.
"""
name = DEFAULT_DRIVER
writer_key = "setpoint_entity"
brand = "GoodWe"
def __init__(self, setpoint_entity="", soc_entity="", batt_entity="",
batt_invert=False):
self.setpoint_entity = str(setpoint_entity or "")
self.soc_entity = str(soc_entity or "")
self.batt_entity = str(batt_entity or "")
self.batt_invert = bool(batt_invert)
self._hass = None
self._getter = None
@classmethod
def from_entry(cls, entry: dict) -> "GoodWeEsphomeDriver":
return cls(setpoint_entity=entry.get("setpoint_entity", ""),
soc_entity=entry.get("soc_entity", ""),
batt_entity=entry.get("batt_entity", ""),
batt_invert=bool(entry.get("batt_invert")))
@classmethod
def actuator_id_of(cls, entry: dict) -> str:
return str(entry.get("setpoint_entity") or "").strip()
def bind(self, hass) -> "GoodWeEsphomeDriver":
self._hass, self._getter = hass, None
return self
def bind_getter(self, getter) -> "GoodWeEsphomeDriver":
self._hass, self._getter = None, getter
return self
def bound(self) -> bool:
return self._hass is not None or self._getter is not None
def _h(self):
hass = self._getter() if self._getter is not None else self._hass
if hass is None:
raise DriverNotBound(f"{self.brand} driver for "
f"{self.setpoint_entity!r} has no Home Assistant")
return hass
def configured(self) -> bool:
return bool(self.setpoint_entity)
def actuator_id(self) -> str:
return self.setpoint_entity
def soc_source(self) -> str:
return self.soc_entity
def batt_source(self) -> str:
return self.batt_entity
async def limits(self) -> tuple:
dev_min, dev_max, _step = await self._h().limits(self.setpoint_entity)
return dev_min, dev_max
async def read(self) -> tuple:
hass = self._h()
soc = await hass.number(self.soc_entity)
raw = await hass.number(self.batt_entity, self.batt_invert)
return soc, raw, {}
async def write(self, w: float) -> bool:
return await self._h().set_number(self.setpoint_entity, w)
async def probe(self) -> Probe:
dev_min, dev_max = await self.limits()
soc, raw, extra = await self.read()
return Probe(dev_min, dev_max, soc, raw, extra)
class UnavailableDriver(Driver):
"""What an entry naming a driver this build does not have gets. Validation
refuses such an entry before a Controller exists; this is only what
`build_roster()` (which refuses nothing) builds meanwhile: a unit that is
not configured, so the refusal branch names it and commands 0 W."""
name = ""
# The census still counts a `setpoint_entity` on such an entry: refusing
# too much is the safe direction for SAFETY-28.
writer_key = "setpoint_entity"
brand = ""
def __init__(self, wanted=""):
self.wanted = str(wanted or "")
@classmethod
def from_entry(cls, entry: dict) -> "UnavailableDriver":
return cls(entry.get("driver"))
@classmethod
def actuator_id_of(cls, entry: dict) -> str:
return str(entry.get("setpoint_entity") or "").strip()
def configured(self) -> bool:
return False
def actuator_id(self) -> str:
return ""
async def limits(self) -> tuple:
return None, None
async def read(self) -> tuple:
return None, None, {}
async def write(self, w: float) -> bool:
return False
async def probe(self) -> Probe:
return Probe()
# name -> class. The options' `driver` value picks one. A test may add a fake;
# `SELECTABLE` (not this) is what the options accept.
REGISTRY = {GoodWeEsphomeDriver.name: GoodWeEsphomeDriver}
def driver_name(entry) -> str:
"""The `driver` an options entry selects; blank or absent is the default."""
raw = entry.get("driver") if isinstance(entry, dict) else None
return str(raw).strip() if raw not in (None, "") else DEFAULT_DRIVER
def driver_class(entry):
"""The class an options entry selects, `UnavailableDriver` if none."""
return REGISTRY.get(driver_name(entry), UnavailableDriver)
def build_driver(entry) -> Driver:
"""The driver for ONE options entry (or the flat options, for one inverter)."""
entry = entry if isinstance(entry, dict) else {}
return driver_class(entry).from_entry(entry)
+386
View File
@@ -0,0 +1,386 @@
"""SMA-10: the two idle states, in words.
A unit is either HELD at 0 W (GoodWe: the add-on goes on writing 0 W) or
HANDED BACK (its driver has `hands_back = True`: `release()` gives it back to
whatever steers it by itself, and the add-on then writes nothing to it). So every
sentence that said "every inverter is set to 0 W" for the add-on going away or
for shadow mode has to be built from the roster. DECISIONS/SMA-10-two-idle-
states.md.
THE RULE FOR EVERY BUILDER HERE: a roster with no hand-back unit gets None, and
the caller then uses the sentence it always used, untouched. So a GoodWe-only
site cannot see a changed byte; test_sma10_two_idle_states.py renders each one
and compares it with the literal from before this card.
The words for a hand-back unit come from its driver (`Driver.words`), not from
here: `back` is "SMA control" in "goes back to SMA control", `back_nl` is the
Dutch noun phrase after "terug naar". A driver without them gets a plain,
brand-free phrase.
Safety stops and refusals are not in this file on purpose: they hold 0 W for
every unit, and their sentences say so.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
_BACK_EN = "its own control"
_BACK_NL = "de eigen sturing"
@dataclass(frozen=True)
class Unit:
name: str
hands_back: bool = False
back_en: str = _BACK_EN
back_nl: str = _BACK_NL
def unit_of(inv) -> Unit:
"""One roster entry's view: its name, and (for a hand-back driver) the
words of whose control it returns to."""
drv = inv.driver
back = bool(getattr(drv, "hands_back", False))
words = getattr(drv, "words", None) or {}
return Unit(str(inv.name), back,
str(words.get("back") or _BACK_EN),
str(words.get("back_nl") or _BACK_NL))
def units_of(inverters) -> tuple:
return tuple(unit_of(i) for i in inverters)
# The roster of the Controller that is running, for the callers that have no
# Controller in hand (the page, the banner). One process runs one Controller.
_CURRENT: list = [()]
def set_roster(units) -> None:
_CURRENT[0] = tuple(units)
def current() -> tuple:
return _CURRENT[0]
def active(units) -> bool:
"""Is any unit handed back? False is every GoodWe-only roster."""
return any(u.hands_back for u in units)
# --------------------------------------------------------------------------- #
# The grammar. English and Dutch, a few verb forms each.
# --------------------------------------------------------------------------- #
def _join(names, lang) -> str:
names = list(names)
word = " en " if lang == "nl" else " and "
if len(names) <= 1:
return "".join(names)
return ", ".join(names[:-1]) + word + names[-1]
def _forms(lang):
"""kind -> (zero template, back template); `{n}` the names, `{b}` the words.
`one`/`many` pick the verb by how many units the clause is about."""
if lang == "nl":
return {
"set": (("{n} gaat naar 0 W", "{n} gaan naar 0 W"),
("{n} gaat terug naar {b}", "{n} gaan terug naar {b}")),
"at": (("{n} op 0 W",) * 2, ("{n} onder {b}",) * 2),
"is": (("{n} staat op 0 W", "{n} staan op 0 W"),
("{n} staat onder {b}", "{n} staan onder {b}")),
"stays": (("{n} blijft op 0 W", "{n} blijven op 0 W"),
("{n} blijft onder {b}", "{n} blijven onder {b}")),
}
return {
"set": (("{n} is set to 0 W", "{n} are set to 0 W"),
("{n} goes back to {b}", "{n} go back to {b}")),
"at": (("{n} at 0 W",) * 2, ("{n} under {b}",) * 2),
"is": (("{n} is at 0 W", "{n} are at 0 W"),
("{n} is under {b}", "{n} are under {b}")),
"stays": (("{n} stays at 0 W", "{n} stay at 0 W"),
("{n} stays under {b}", "{n} stay under {b}")),
}
def _groups(units, lang):
"""`(zero names, [(names, back words)])`: the held units, and the handed-back
ones grouped by whose control they return to, in roster order."""
zeros = [u.name for u in units if not u.hands_back]
groups: dict = {}
for u in units:
if u.hands_back:
groups.setdefault(u.back_nl if lang == "nl" else u.back_en,
[]).append(u.name)
return zeros, [(names, back) for back, names in groups.items()]
# A clause may not eat the sentence it sits in: STYLE.md allows 25 words, and
# the longest tail after a clause is about 11.
CLAUSE_MAX_WORDS = 14
def _count_txt(n, lang) -> str:
if lang == "nl":
return f"{n} omvormer" if n == 1 else f"{n} omvormers"
return f"{n} inverter" if n == 1 else f"{n} inverters"
def _clause(units, lang, kind, sep, generic, counted) -> str:
forms = _forms(lang)[kind]
zeros, groups = _groups(units, lang)
if generic: # one group, and no make named
names = [n for g, _b in groups for n in g]
own = ("de eigen sturing" if lang == "nl" else
"their own control" if len(names) > 1 else "its own control")
groups = [(names, own)] if names else []
subject = ("de omvormers", "de omvormer") if lang == "nl" else (
"the inverters", "the inverter")
parts = []
if zeros:
parts.append(forms[0][1 if len(zeros) > 1 else 0].format(
n=(str(len(zeros)) if groups else _count_txt(len(zeros), lang))
if counted else _join(zeros, lang)))
for names, back in groups:
if not zeros and len(groups) == 1:
names_txt = subject[0 if len(names) > 1 else 1]
elif counted:
# the bare number after a counted first clause: "1 inverter is set
# to 0 W and 2 go back to their own control"
names_txt = (str(len(names)) if zeros
else _count_txt(len(names), lang))
else:
names_txt = _join(names, lang)
parts.append(forms[1][1 if len(names) > 1 else 0].format(
n=names_txt, b=back))
if sep:
return sep.join(parts)
word = " en " if lang == "nl" else " and "
return (", ".join(parts[:-1]) + word + parts[-1]) if len(parts) > 1 \
else "".join(parts)
def clause(units, lang, kind, sep=None) -> str:
"""One clause about the whole roster, `kind` one of set/at/is/stays.
Held units first, then the handed-back ones, joined by "and" (or `sep`).
When EVERY unit is handed back to the same control the subject is "the
inverters", not their names, as the card's table has it.
A long roster would break the 25-word rule, so a clause over
CLAUSE_MAX_WORDS is said again without naming the make (one "own control"
for all), and then by counting units instead of naming them."""
text = _clause(units, lang, kind, sep, False, False)
if sep or _words(text) <= CLAUSE_MAX_WORDS:
return text
text = _clause(units, lang, kind, sep, True, False)
if _words(text) <= CLAUSE_MAX_WORDS:
return text
return _clause(units, lang, kind, sep, True, True)
def _cap(text) -> str:
return text[:1].upper() + text[1:]
def _bi(en, nl):
from .messages import Bi
return Bi(en, nl)
def _words(text) -> int:
return len([w for w in re.findall(r"\S+", text)
if re.search(r"[A-Za-z0-9]", w)])
# --------------------------------------------------------------------------- #
# The sentences. Each returns None for a roster with no hand-back unit.
# --------------------------------------------------------------------------- #
def stop_dialog(units, lang):
"""Stop control? (was "Every inverter is set to 0 W until you start
control again.")"""
if not active(units):
return None
c = clause(units, lang, "set")
return (f"{_cap(c)} tot u de regeling opnieuw start." if lang == "nl"
else f"{_cap(c)} until you start control again.")
def restart_dialog(units, lang):
"""Restart now? / Save and restart? (live)"""
if not active(units):
return None
c = clause(units, lang, "set")
return (f"{_cap(c)} terwijl de add-on herstart, daarna gelden de nieuwe "
f"instellingen." if lang == "nl" else
f"{_cap(c)} while the add-on restarts, and then the new settings "
f"apply.")
def restart_dialog_shadow(units, lang):
"""Save and restart? when shadow mode keeps the units idle afterwards."""
if not active(units):
return None
c = clause(units, lang, "set")
return (f"{_cap(c)} terwijl de add-on herstart, en de schaduwmodus houdt "
f"het zo." if lang == "nl" else
f"{_cap(c)} while the add-on restarts, and shadow mode keeps it "
f"that way.")
def setup_dialog_shadow(units, lang):
"""Save and restart? in setup, shadow mode on."""
if not active(units):
return None
c = clause(units, lang, "at")
return (f"De add-on herstart met deze instellingen, en de schaduwmodus "
f"houdt {c}." if lang == "nl" else
f"The add-on restarts with these settings, and shadow mode keeps "
f"{c}.")
def control_stopped(units, lang):
"""The page's control line when stopped."""
if not active(units):
return None
c = clause(units, lang, "is")
return (f"De regeling is gestopt. {_cap(c)}." if lang == "nl"
else f"Control is stopped. {_cap(c)}.")
def control_shadow(units, lang):
"""The page's control line in shadow mode."""
if not active(units):
return None
c = clause(units, lang, "stays")
return (f"Schaduwmodus: {c}." if lang == "nl" else f"Shadow mode: {c}.")
def attn_shadow_body(units, lang):
"""The attention card's body in shadow mode."""
if not active(units):
return None
c = clause(units, lang, "stays")
return (f"De add-on beslist alles, maar {c}." if lang == "nl" else
f"The add-on decides everything, but {c}.")
def shadow_state(units, lang, many=True):
"""The tail of a notification: "Shadow mode is on, so <this>." For the
three output-clamp sentences that said every inverter stays at 0 W."""
if not active(units):
return None
return clause(units, lang, "stays")
def banner_stopped(units):
"""Stopped. 12 words at most (STYLE.md)."""
if not active(units):
return None
out = {}
for lang, stopped in (("en", "Stopped"), ("nl", "Gestopt")):
text = f"{stopped} — {clause(units, lang, 'at', sep=', ')}"
if _words(text) > 12:
text = _banner_counts(units, lang, stopped)
out[lang] = text
return _bi(out["en"], out["nl"])
def _banner_counts(units, lang, stopped) -> str:
"""The long-roster form: how many, not which."""
zeros, groups = _groups(units, lang)
if len(groups) == 1:
back = groups[0][1]
n_back = len(groups[0][0])
if lang == "nl":
held = f"{len(zeros)} op 0 W, " if zeros else ""
return f"{stopped} — {held}{n_back} onder {back}"
held = f"{len(zeros)} at 0 W, " if zeros else ""
return f"{stopped} — {held}{n_back} under {back}"
return (f"{stopped} — omvormers op 0 W of teruggegeven" if lang == "nl"
else f"{stopped} — inverters at 0 W or handed back")
def banner_shadow(units):
"""Shadow mode, nothing standing. The GoodWe sentence adds "Inverters stay
at 0 W." which is false for a unit that hands back, and a banner is 12
words, so the unit-by-unit state is left to the control line."""
if not active(units):
return None
return _bi("Shadow mode: the battery is not controlled.",
"Schaduwmodus: de batterij wordt niet geregeld.")
def hint_shadow_on(units):
""""Shadow mode on, inverters stay at 0 W" for the Last event line."""
if not active(units):
return None
return "Shadow mode on, " + clause(units, "en", "at", sep=", ")
def unit_state(unit, lang):
"""One handed-back unit's own state, in place of "Held at 0 W"."""
if lang == "nl":
return f"Terug onder {unit.back_nl}"
return f"Back under {unit.back_en}"
def log_shutdown(units):
"""The INFO line at shutdown (was "shutting down - commanding 0 W on every
inverter")."""
if not active(units):
return None
zeros, groups = _groups(units, "en")
held = f"commanding 0 W on {_join(zeros, 'en')}" if zeros else ""
back = " and ".join(f"handing back {_join(n, 'en')} to {b}"
for n, b in groups)
return "shutting down - " + " and ".join(x for x in (held, back) if x)
def task_died_state(units) -> str:
"""The part of the CRITICAL line after "so" when the control task dies.
For a roster with no hand-back unit it is the sentence it always was."""
if not active(units):
return "every inverter is set to 0 W"
zeros, groups = _groups(units, "en")
backs = [n for names, _b in groups for n in names]
parts = []
if zeros:
parts.append(f"{_join(zeros, 'en')} "
f"{'are' if len(zeros) > 1 else 'is'} set to 0 W")
parts.append(f"{_join(backs, 'en')} "
f"{'are' if len(backs) > 1 else 'is'} handed back")
return " and ".join(parts)
# --------------------------------------------------------------------------- #
# The page words: the ui_text sentences that move with the roster, by language.
# --------------------------------------------------------------------------- #
def overlay(units) -> dict:
"""`{lang: nested dict}` of ui_text paths to replace; {} when no unit is
handed back, so the page is the file as it always was."""
if not active(units):
return {}
out = {}
for lang in ("en", "nl"):
out[lang] = {
"home": {"dialog": {"stop": {
"description": stop_dialog(units, lang)}}},
"settings": {
"dialog": {"description": restart_dialog(units, lang)},
"setup": {
"dialog": {"description":
restart_dialog_shadow(units, lang)},
"dialog_live": {"description":
restart_dialog(units, lang)},
"dialog_setup": {"description":
setup_dialog_shadow(units, lang)}}},
"home_words": {
"attn_shadow_body": attn_shadow_body(units, lang),
"control": {"shadow": control_shadow(units, lang),
"stopped": control_stopped(units, lang)}},
}
return out
+11 -1
View File
@@ -19,7 +19,7 @@ section at the bottom and is held to STYLE.md by test_messages.py.
import contextlib
from datetime import datetime, timedelta, timezone
from . import arbitrage, cheaproll, messages, peakguard, priceruns, uitext
from . import arbitrage, cheaproll, handback, messages, peakguard, priceruns, uitext
from .dayplan import EFF
from .maintenance import CHARGE as M_CHARGE, DRAIN as M_DRAIN, HOLD as M_HOLD
from .maintenance import IDLE as M_IDLE, next_slot_start
@@ -936,6 +936,13 @@ def battery_rows(c, shadow, running, held=False):
else other, at=at,
**plan_words(c, inv.name, why)),
})
if getattr(inv, "released", False):
# SMA-10. A unit handed back says so, in its driver's words, not
# "Held at 0 W": nothing is written to it. The key exists only for
# such a unit, so a GoodWe-only page is unchanged.
rows[-1]["now"] = handback.unit_state(handback.unit_of(inv),
_LANG[0])
rows[-1]["handed_back"] = True
if modes_on:
# OPT-11 P1: the battery's switch and mode, for the Batteries
# screen. Only with battery modes on, so the page is unchanged
@@ -1211,6 +1218,9 @@ _WORDS: dict = {}
def _hw() -> dict:
lang = _LANG[0]
if _WORDS.get("") != uitext.generation(): # SMA-10: the roster's words moved
_WORDS.clear()
_WORDS[""] = uitext.generation()
if lang not in _WORDS:
_WORDS[lang] = uitext.words(lang)
return _WORDS[lang]
+91 -20
View File
@@ -124,9 +124,12 @@ from datetime import datetime
from .clamp import ClampResult
from .delivery import DeliveryConfig, DeliveryWatchdog
from . import messages
# SMA-2. The driver seam: how this unit's inverter is read and steered.
from .drivers import (GOODWE_LINK_STALE_S, GoodWeEsphomeDriver,
build_driver)
# SAFETY-37. The freshness policy, and the ONE place its bounds are written.
# freshness.py imports nothing from this package, so the direction is one-way.
from .freshness import BOUNDS, Freshness
from .freshness import Freshness
from .idle import IdleReading
# CFG-03's ONE in-code mirror of config.yaml's SAFETY-24 defaults. Imported
# rather than retyped: the flat-keys path below needs `bms_soc_floor`'s
@@ -149,7 +152,11 @@ from .watchdog import SignWatchdog, SignWatchdogConfig
# decided it will not. No config key: CFG-03 tracks three places a default has
# to be kept in step and this does not earn a fourth - it is derived from a
# constant the firmware and validate.py already share.
LINK_STALE_S = 30.0
#
# SMA-2. This is the GoodWe driver's `link_stale_s` (drivers.py), kept under its
# old name for the checks and for main.py. `is_live()` and `link_note()` now ask
# each unit's DRIVER for its window; a driver for another make states its own.
LINK_STALE_S = GOODWE_LINK_STALE_S
# The name of the inverter a SINGLE-INVERTER config describes. ⚠️ A NAME, NOT A
# CONFIGURATION - it exists so that a per-inverter claim has an actuator to be
@@ -195,12 +202,14 @@ class Inverter:
def __init__(self, name, *, setpoint_entity="", soc_entity="",
batt_entity="", batt_invert=False, max_w=2000.0,
bms_soc_floor=None, capacity_kwh=None, store=None,
sign_cfg=None, delivery_cfg=None):
sign_cfg=None, delivery_cfg=None, driver=None):
self.name = str(name)
self.setpoint_entity = str(setpoint_entity or "")
self.soc_entity = str(soc_entity or "")
self.batt_entity = str(batt_entity or "")
self.batt_invert = bool(batt_invert)
# SMA-2. HOW THIS UNIT IS READ AND STEERED. The entity keywords above
# are the GoodWe driver's, kept so every existing caller builds the
# same unit; a roster entry that selects another driver passes
# `driver` and the entity keywords stay empty.
self.driver = driver if driver is not None else GoodWeEsphomeDriver(
setpoint_entity, soc_entity, batt_entity, batt_invert)
# The supervised cap on what may be written to THIS setpoint entity.
# See the module docstring on why this is a number and not a `Tuning`.
self.max_w = float(max_w)
@@ -256,7 +265,7 @@ class Inverter:
# constructed here: SoC's obligation term is energy through the pack, not
# command travel, and the constant it needs has not been measured. That
# is TEL-08's, and freshness.py's docstring says exactly what it owes.
self.batt_fresh = Freshness(BOUNDS["batt"])
self.batt_fresh = Freshness(self.driver.batt_bound)
# --- what this unit was last told, and what it last accepted ---------
# `target` is THIS unit's share of the site target from the last
@@ -266,6 +275,21 @@ class Inverter:
self.target = 0.0
self.last_write = None
self.last_write_at = None
# SMA-10. True from the moment this unit is handed back (`release()`)
# until control starts again. While it is True nothing is written to the
# unit - not the heartbeat, not the cycle - so the unit's own
# controller keeps what it was given. Only a driver with
# `hands_back = True` ever sets it.
self.released = False
# SMA-10. Writes to a hand-back driver that are on their way (see
# Controller._write_unit), so the release can wait for them and be LAST.
self.inflight: set = set()
# SMA-10 round 2. A failed hand-back: how many tries in a row failed
# (the log is written at the first and on recovery only), when the next
# try is due (monotonic s), and whether the one fallback 0 W was sent.
self.release_fails = 0
self.release_retry_at = 0.0
self.release_zero_sent = False
self.last_write_ok = None
# ⚠️ TWO TIMESTAMPS, NOT ONE FLAG. `last_write_ok` is the last write's
# verdict and it flips on a single transient 400; liveness needs a RUN
@@ -338,6 +362,50 @@ class Inverter:
def idle_w(self) -> float:
return self.idle.w
# -- the GoodWe driver's entities, read through for the callers that name
# them (the panel's range check, the status rows, the checks). A driver
# without such an entity answers "" - the same as "not set".
@property
def setpoint_entity(self) -> str:
return getattr(self.driver, "setpoint_entity", "")
@property
def soc_entity(self) -> str:
return getattr(self.driver, "soc_entity", "")
@property
def batt_entity(self) -> str:
return getattr(self.driver, "batt_entity", "")
@property
def batt_invert(self) -> bool:
return bool(getattr(self.driver, "batt_invert", False))
# Assigning one writes through to the driver, as the attributes did before
# SMA-2 (nothing in the repo assigns them today; this keeps it working).
# A driver that has no such field refuses, rather than losing the value.
def _set_driver_field(self, name, value):
if not hasattr(self.driver, name):
raise AttributeError(
f"{type(self.driver).__name__} has no {name}")
setattr(self.driver, name, value)
@setpoint_entity.setter
def setpoint_entity(self, v):
self._set_driver_field("setpoint_entity", str(v or ""))
@soc_entity.setter
def soc_entity(self, v):
self._set_driver_field("soc_entity", str(v or ""))
@batt_entity.setter
def batt_entity(self, v):
self._set_driver_field("batt_entity", str(v or ""))
@batt_invert.setter
def batt_invert(self, v):
self._set_driver_field("batt_invert", bool(v))
# -- store ---------------------------------------------------------------
def key(self, name: str) -> str:
"""This unit's namespaced Store key for `name`. See store.unit_key()."""
@@ -387,7 +455,7 @@ class Inverter:
return out
def has_writer(self) -> bool:
return bool(self.setpoint_entity)
return self.driver.configured()
# -- liveness ------------------------------------------------------------
def note_write(self, ok: bool, now: datetime) -> None:
@@ -398,7 +466,7 @@ class Inverter:
elif self.rejected_since is None:
self.rejected_since = now
def is_live(self, now: datetime, stale_s: float = LINK_STALE_S):
def is_live(self, now: datetime, stale_s: float | None = None):
"""`(live, why_not)` - may this controller command this unit THIS TICK?
Read the module docstring before widening this - in particular on why a
@@ -411,7 +479,11 @@ class Inverter:
⚠️ ANSWERED PER TICK, NEVER CACHED, for `allocator.plan()`'s reason: a
link goes stale between one cycle and the next.
`stale_s` is the driver's `link_stale_s` unless a caller passes one.
"""
if stale_s is None:
stale_s = self.driver.link_stale_s
if self.rejected_since is not None:
held = (now - self.rejected_since).total_seconds()
if held >= float(stale_s):
@@ -451,9 +523,11 @@ class Inverter:
held = (0.0 if self.rejected_since is None
else (now - self.rejected_since).total_seconds())
if not live:
return messages.row_not_controllable(self.name, held, LINK_STALE_S)
return messages.row_not_controllable(self.name, held,
self.driver.link_stale_s)
if self.rejected_since is not None:
return messages.row_commands_refused(self.name, held, LINK_STALE_S)
return messages.row_commands_refused(self.name, held,
self.driver.link_stale_s)
return ""
def __repr__(self) -> str:
@@ -556,10 +630,8 @@ def build_roster(opts: dict, store, sign_cfg=None,
# identically, which is AC 3.
return [Inverter(
UNIT_A,
setpoint_entity=opts.get("setpoint_entity", ""),
soc_entity=opts.get("soc_entity", ""),
batt_entity=opts.get("batt_entity", ""),
batt_invert=bool(opts.get("batt_invert")),
# SMA-2. The flat keys are the GoodWe shape and only that.
driver=GoodWeEsphomeDriver.from_entry(opts),
max_w=_flat_max_w(opts),
# SAFETY-32. THE FLAT KEY, because this IS the single-inverter shape
# - the one pack the flat options describe is the one pack whose
@@ -588,10 +660,9 @@ def build_roster(opts: dict, store, sign_cfg=None,
entry = entry if isinstance(entry, dict) else {}
roster.append(Inverter(
name,
setpoint_entity=entry.get("setpoint_entity", ""),
soc_entity=entry.get("soc_entity", ""),
batt_entity=entry.get("batt_entity", ""),
batt_invert=bool(entry.get("batt_invert")),
# SMA-2. The entry's `driver` (default goodwe_esphome) picks the
# class; the entry itself says where its entities are.
driver=build_driver(entry),
# ⚠️ NOT `opts["max_w"]`. See the docstring: a rating an entry did
# not state is not the flat one, it is a rating rule 9 refuses.
max_w=_entry_max_w(entry),
+52 -15
View File
@@ -10,7 +10,8 @@ already fixed. The readings show it: they answer each power request late.
house does not move that reading, so a repeating load cannot fool it. It
needs the request to move FIT_MOVE_W; one reading per 10 s makes it slow.
- `MeterFit`: how long after the site request the meter shows it. Quick at a
1-3 s meter, none at a slower one, and a house load that repeats can fool it.
1-3 s meter, slower and for long lags only at a 5 s one (SAFETY-129), and a
house load that repeats can fool it.
The meter counts only when an ask was slow to start and no battery fit said
"on time"; with hysteresis (ON_S / OFF_S) the result is `late_seen`. Then (`observe()`, each cycle):
- a new command more than ANSWER_W from the battery reading is PENDING until
@@ -163,13 +164,22 @@ class Delay:
# The meter's delay: fitted over this much history, from this many new
# values (a meter of about 3.5 s or faster: a slower one gives too few to
# fit without false delays); late over M_LATE_S (the plant's 6 s settle and one 2 s meter tick),
# but only when the batteries' own readings have not just shown them on time.
# values (a meter of about 3.5 s or faster; a slower one see M_SLOW_FIT_S);
# late over M_LATE_S (the plant's 6 s settle and one 2 s meter tick), but only
# when the batteries' own readings have not just shown them on time.
M_FIT_S = 60.0
M_ROWS = 16
M_LATE_S = freshness.PLANT_SETTLE_S + 2.0 # 8.0
M_SHARE, M_BETTER = 0.4, 0.7
# SAFETY-129: a meter slower than that (a 5 s P1) has fewer than M_ROWS values
# in M_FIT_S, so it is fitted over M_SLOW_FIT_S instead, from the same M_ROWS
# values. It calls a delay late only over M_SLOW_LATE_S and on ON_FITS fits in
# a row. Alone it reads 35-90 s on healthy runs, a few times in a row; what
# keeps those from a verdict is the slow-start and battery-fit check in
# watch(), not the limit. A 10 s lag is not found: it cannot be told from a
# slow battery (R2-1), nor does it swing at 5 s.
M_SLOW_FIT_S = 120.0
M_SLOW_LATE_S = 16.0
# A meter fit counts only after an ask that took this long to start moving a
# reading: on time they start within 1-2 s (the recorded house, at 1-5 s).
SLOW_START_S = 3.0
@@ -183,19 +193,30 @@ class MeterFit:
up with an earlier request, so it only counts while the batteries' own
fit is not on time (`Answer.watch`)."""
def __init__(self):
def __init__(self, fit_s=M_FIT_S, late_s=M_LATE_S):
self.fit_s, self.late_s = fit_s, late_s
self.cmds = deque() # (t, request) when it changed
self.grid = deque() # (t, meter) new values only
def slow(self):
"""The meter is too slow for M_ROWS values in `fit_s`: the usual gap
between its new values (median, so a pause does not count) is over
fit_s / M_ROWS."""
ts = [t for t, _g in self.grid]
if len(ts) < 5:
return False
gaps = sorted(b - a for a, b in zip(ts, ts[1:]))
return gaps[len(gaps) // 2] * M_ROWS > self.fit_s
def add(self, now, cmd, grid):
if cmd is not None and (not self.cmds or self.cmds[-1][1] != cmd):
self.cmds.append((now, float(cmd)))
if grid is not None and (not self.grid or self.grid[-1][1] != grid):
self.grid.append((now, float(grid)))
while self.grid and self.grid[0][0] < now - M_FIT_S:
while self.grid and self.grid[0][0] < now - self.fit_s:
self.grid.popleft()
while (len(self.cmds) > 1
and self.cmds[1][0] <= now - M_FIT_S - MAX_DELAY_S):
and self.cmds[1][0] <= now - self.fit_s - MAX_DELAY_S):
self.cmds.popleft()
def estimate(self):
@@ -214,9 +235,9 @@ class MeterFit:
best = min(range(len(pure)), key=lambda d: (pure[d], d))
if g_var <= 0 or pure[best] > (1 - M_SHARE) * g_var:
return None
if best <= M_LATE_S:
if best <= self.late_s:
return float(best)
if pure[best] > M_BETTER * min(pure[:int(M_LATE_S) + 1]):
if pure[best] > M_BETTER * min(pure[:int(self.late_s) + 1]):
return None
return float(best)
@@ -236,6 +257,8 @@ class Answer:
self._was = None # (command, reading, meter) at the last call
self.delay = Delay()
self.meter = MeterFit()
self.meter_slow = MeterFit(M_SLOW_FIT_S, M_SLOW_LATE_S) # SAFETY-129
self._ms_run = 0 # late slow-meter fits in a row
self._batt_fit = None # (when, d): the batteries' last fit
self._b_run = 0 # late battery fits in a row
self._start_age = None # (when, how long the last ask took to start)
@@ -279,14 +302,18 @@ class Answer:
delays. Late on ON_FITS battery fits from ON_S, or on a meter fit
over M_LATE_S when an ask was slow to start (SLOW_START_S) and no
battery fit within FIT_S said on time: a house load that repeats can
fool the meter fit, not these. On time again on a battery fit under
OFF_S, or a meter fit within M_LATE_S unless a battery fit said late.
fool the meter fit, not these. A meter too slow for M_ROWS values in
M_FIT_S (a 5 s P1) is fitted over M_SLOW_FIT_S and counts only over
M_SLOW_LATE_S, on ON_FITS fits in a row. On time again on a battery fit
under OFF_S, or a meter fit within M_LATE_S unless a battery fit said
late.
"""
if self._start is None:
self._start = now
for name, cmd, reading in units:
self.delay.add(now, name, cmd, reading)
self.meter.add(now, standing_w, grid_w)
self.meter_slow.add(now, standing_w, grid_w)
if self._fit_at is not None and now - self._fit_at < FIT_EVERY_S:
return
self._fit_at = now
@@ -295,6 +322,9 @@ class Answer:
and now - self._exempt_at <= FIT_S:
b = None # a battery that stopped following: no late fit
m = self.meter.estimate()
ms = None
if self.meter.slow():
ms = self.meter_slow.estimate()
if b is not None:
self._batt_fit = (now, b)
self.shown_s = b if b >= ON_S else None
@@ -304,7 +334,13 @@ class Answer:
b_late = recent and self._batt_fit[1] >= ON_S
self._b_run = self._b_run + 1 if (b or 0.0) >= ON_S else 0
d = b if b is not None else m
self._ms_run = self._ms_run + 1 if (ms or 0.0) > M_SLOW_LATE_S else 0
# A slow-meter fit only ever adds a late verdict: it counts as a fit
# when it is late on ON_FITS in a row, and never ends one, so a slow
# battery (R2-1) runs exactly as before.
if self._ms_run < ON_FITS:
ms = None
d = b if b is not None else m if m is not None else ms
if d is None:
if self._fit_ok is None or now - self._fit_ok > FIT_GONE_S:
self.late_seen = False # nothing to tell it by
@@ -312,12 +348,13 @@ class Answer:
self.fits += 1
self.delay_s, self._fit_ok = d, now
warm = now - self._start >= MAX_DELAY_S + FIT_S
m_late = (m or 0.0) > M_LATE_S
m_late = ((m or 0.0) > M_LATE_S and warm) or (
self._ms_run >= ON_FITS
and now - self._start >= MAX_DELAY_S + M_SLOW_FIT_S)
slow = (self._start_age is not None
and now - self._start_age[0] <= M_FIT_S
and self._start_age[1] >= SLOW_START_S)
if self._b_run >= ON_FITS or (
m_late and warm and slow and not b_fresh):
if self._b_run >= ON_FITS or (m_late and slow and not b_fresh):
self.late_seen = True
elif (b is not None and b < OFF_S) or (
m is not None and m <= M_LATE_S and not b_late):
+1675 -3839
View File
File diff suppressed because it is too large Load Diff
+30 -3
View File
@@ -12,6 +12,8 @@ import re
from dataclasses import dataclass
from datetime import datetime
from . import handback
# Severity (STYLE.md section 3). An ALARM may use up to three sentences so
# that no action a person must take is lost; everything else gets one.
ALARM, WARNING, INFO, RESOLVED = "alarm", "warning", "info", "resolved"
@@ -228,6 +230,19 @@ class Clamp:
limit: str # a key of LIMIT_WORDS
def _shadow_so(held: str) -> str:
""""Shadow mode is on, so <held>." SMA-10: with a unit handed back, the
roster's own words say where each unit stays; otherwise `held`, as ever."""
moved = handback.shadow_state(handback.current(), "en")
return f"Shadow mode is on, so {moved or held}."
def _shadow_keeps(held: str) -> str:
moved = handback.clause(handback.current(), "en", "at") \
if handback.active(handback.current()) else None
return moved or held
def output_clamp(clamps, *, shadow: bool = False) -> Notice:
"""SAFETY-03: a computed command above the limit. A software fault.
@@ -238,7 +253,7 @@ def output_clamp(clamps, *, shadow: bool = False) -> Notice:
fault = "This is a software fault, so please report it to your installer."
if not clamps:
cut = ("would have been cut back" if shadow else "was cut back")
state = ("Shadow mode is on, so every inverter stays at 0 W." if shadow
state = ((_shadow_so("every inverter stays at 0 W")) if shadow
else "Control is still running.")
return Notice(ID_OUTPUT_CLAMP, ALARM, T_OUTPUT_CLAMP,
f"The add-on asked for more power than {RATING} allows "
@@ -250,11 +265,11 @@ def output_clamp(clamps, *, shadow: bool = False) -> Notice:
if others:
verb = "was" if len(others) == 1 else "were"
state = (f"{names(others)} would have been cut too, and shadow mode "
f"keeps every inverter at 0 W." if shadow else
f"keeps {_shadow_keeps('every inverter at 0 W')}." if shadow else
f"{names(others)} {verb} cut too, and control is still "
f"running.")
else:
state = ("Shadow mode is on, so the inverter stays at 0 W." if shadow
state = (_shadow_so("the inverter stays at 0 W") if shadow
else "Control is still running.")
return Notice(ID_OUTPUT_CLAMP, ALARM, T_OUTPUT_CLAMP,
f"{who} add-on asked for {watts(c.asked_w)}, above "
@@ -576,6 +591,9 @@ def banner_running() -> str:
def banner_stopped() -> str:
moved = handback.banner_stopped(handback.current())
if moved is not None: # SMA-10: a unit is handed back, not held
return moved
return Bi("Stopped — the inverters are set to 0 W",
"Gestopt — de omvormers staan op 0 W")
@@ -601,6 +619,9 @@ def banner_shadow(latched: bool) -> str:
mode. Each stop has its own red row below, which names it and says how it
clears.
"""
moved = None if latched else handback.banner_shadow(handback.current())
if moved is not None: # SMA-10: a unit is handed back, not held
return moved
if latched:
return Bi("Shadow mode: battery not controlled. A safety stop stays "
"on, see below.",
@@ -1367,6 +1388,8 @@ HINTS = {
"setup_only": "In setup, nothing is sent to any inverter",
"roster": "Inverter list read: {n} inverters",
"maint_history": "Maintenance history did not move over cleanly",
"handed_back": "{unit}: handed back, the add-on writes nothing to it",
"hand_back_failed": "{unit}: could not be handed back, set to 0 W once, trying again",
"stop_restored": "{unit}: an earlier safety stop is back, it stays at 0 W",
"readings_late": "Home Assistant readings arrive late, control holds",
"readings_back": "Home Assistant readings are on time again",
@@ -1470,6 +1493,10 @@ def hint(key: str, **kw) -> str:
kw["w"] = watts(kw["w"])
if "sw" in kw:
kw["sw"] = signed_watts(kw["sw"])
if key == "shadow_on": # SMA-10: a unit handed back is not at 0 W
moved = handback.hint_shadow_on(handback.current())
if moved is not None:
return moved
return HINTS[key].format(**kw)
+7 -5
View File
@@ -343,10 +343,12 @@ async def problems_and_ranges(opts: dict, hass=None, notes=None):
f"disagreement between the two and should be reported."]
return found, []
if hass is not None:
# SMA-2. Each unit's driver, bound to the panel's own (read-only)
# Home Assistant: there is no Controller here.
async def _limits(unit):
if unit.setpoint_entity:
unit.dev_min, unit.dev_max, _ = await hass.limits(
unit.setpoint_entity)
if unit.driver.configured():
unit.dev_min, unit.dev_max = await unit.driver.bind(
hass).limits()
await asyncio.gather(*(_limits(unit) for unit in units))
dev_min = dev_max = None
@@ -357,8 +359,8 @@ async def problems_and_ranges(opts: dict, hass=None, notes=None):
problems = list(validate_startup_config(opts, dev_min, dev_max,
notes=notes))
problems += validate_unit_ranges(units, skip_entity=flat)
unread = [unit.setpoint_entity for unit in units
if unit.setpoint_entity and unit.dev_min is None
unread = [unit.driver.actuator_id() for unit in units
if unit.driver.configured() and unit.dev_min is None
and unit.dev_max is None]
return problems, unread
+12 -6
View File
@@ -34,7 +34,9 @@ evening and api.forecast.solar is sometimes out for a poll. A kept reading
stands in for its sensor (a) for up to `FRESH_S` when the sensor is missing
or unavailable, as a sensor that merely stopped updating is already
tolerated, and (b) from the end of the bell (`BELL_TO_H`) until local
midnight, if it is at most `KEPT_MAX_AGE_S` old when used.
midnight, if it is at most `KEPT_MAX_AGE_S` old when used. A TOMORROW
reading needs no evening for (b), at any hour (OPT-38: one Forecast.Solar
sensor stopped at 14:54 and tomorrow vanished from 17:54 to 20:00).
Never beyond that, and never for another day: a today figure is only today's,
a tomorrow figure is tomorrow's until midnight and then, until the bell starts
(`BELL_FROM_H`, 06:00 local), today's (OPT-34: at most `KEPT_MORNING_MAX_AGE_S`
@@ -330,8 +332,9 @@ class Hold:
The kept reading must be for `day0`, and either (a) at most `FRESH_S`
old, or (b) used at night: from the end of the bell to local midnight,
at most `KEPT_MAX_AGE_S` old. `kept` is true when (b) was needed,
or `as_today` (OPT-34: a tomorrow figure standing in for today, after
at most `KEPT_MAX_AGE_S` old; a "tomorrow" reading at any hour
(OPT-38; `read_sum()` flags it kept only from the end of the bell).
`kept` is true when (b) was needed, or `as_today` (OPT-34: a tomorrow figure standing in for today, after
midnight and until the bell starts, `KEPT_MORNING_MAX_AGE_S`)."""
rec = self._r.get((kind, entity, day0))
if rec is None:
@@ -347,8 +350,8 @@ class Hold:
return (day, at, True) if ok else None
if age > KEPT_MAX_AGE_S:
return None
# A tomorrow sensor is asked with day0 = the next midnight, which is
# in the future all day, so the evening ends at that day's end.
if kind == "tomorrow":
return day, at, True # OPT-38: no evening needed
evening = _local_hour(now) >= BELL_TO_H and now < _bounds(day0)[1]
return (day, at, True) if evening else None
@@ -556,6 +559,9 @@ def read_sum(today, tomorrow, now: datetime, hold: Hold | None = None):
if why0 is not None:
return None, why0, gaps
tday = _sum(tdays) if tomorrow and len(tdays) == len(tomorrow) else None
kept = kept or (tday is not None and tkept)
# OPT-38: before the bell ends a kept tomorrow reading is no "kept for
# tonight": it must not replace today's line or the log.
kept = kept or (tday is not None and tkept
and _local_hour(now) >= BELL_TO_H)
# The oldest member's report is when the sum was last fully known.
return Forecast(_sum(days), tday, min(ats), kept), None, gaps
+29 -2
View File
@@ -13,6 +13,11 @@ import os
DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ui_text")
LANGS = ("en", "nl")
_CACHE: dict = {}
# SMA-10. The sentences that move with the roster (handback.overlay): empty for
# every GoodWe-only roster, and then `raw()` is the file as it always was.
_IDLE: dict = {}
_GEN = [0]
_MERGED: dict = {}
def lang_of(value) -> str:
@@ -21,14 +26,36 @@ def lang_of(value) -> str:
return head if head in LANGS else "en"
def raw(lang: str) -> dict:
"""One language file as written, without the English fallback."""
def _file(lang: str) -> dict:
if lang not in _CACHE:
with io.open(os.path.join(DIR, f"{lang}.json"), encoding="utf-8") as f:
_CACHE[lang] = json.load(f)
return _CACHE[lang]
def set_idle(overlay: dict) -> None:
"""SMA-10: the roster-built sentences, `{lang: nested dict}` (or {})."""
_IDLE.clear()
_IDLE.update(overlay or {})
_MERGED.clear()
_GEN[0] += 1
def generation() -> int:
"""Changes whenever `set_idle()` does, so a cache of words can tell."""
return _GEN[0]
def raw(lang: str) -> dict:
"""One language file as written, without the English fallback (and with the
roster's own sentences laid over it when a unit is handed back)."""
if lang not in _IDLE:
return _file(lang)
if lang not in _MERGED:
_MERGED[lang] = _merge(_file(lang), _IDLE[lang])
return _MERGED[lang]
def _merge(base, over):
if not (isinstance(base, dict) and isinstance(over, dict)):
return copy.deepcopy(over)
+82 -5
View File
@@ -328,12 +328,14 @@ WHAT IS DELIBERATELY *NOT* REFUSED, because it is untidy rather than unsafe:
"""
import logging
import math
import re
from typing import NamedTuple
from . import dayplan, messages, pv, solarfc
from .arbitrage import enabled as arbitrage_on
from .control import SLEW_RAIL_FRAC, LOOP_TICK_S, PLANT_SETTLE_S
from . import drivers
from .custom_formula import (
EXPORT_FORMULA_OPTION, FormulaInvalid, implausible_all_in,
parse_export_formula, parse_price_formula, stale_card)
@@ -457,13 +459,28 @@ def _collect_writers(node, path: str, out: list) -> None:
however deeply nested and under whatever container.
"""
if isinstance(node, dict):
# SMA-2. THE DRIVER NAMES THE ACTUATOR. An entry's `driver` (default
# goodwe_esphome) says which key declares its writer - `setpoint_entity`
# for GoodWe, `host` for a driver reached over a socket - and what that
# entry's `actuator_id()` is. The walk is as structural as before: it
# still finds an entry wherever the options keep it.
cls = drivers.driver_class(node)
for k, v in node.items():
here = f"{path}.{k}" if path else str(k)
# Every key in ACTUATOR_WRITE_KEYS declares a writer, as before
# SMA-2 and whatever the entry's driver; PLUS the entry driver's
# own writer key. The second is added to the first, never in place
# of it (census parity with 23ff9d0 is graded in test_sma2_driver).
if k in ACTUATOR_WRITE_KEYS:
entity = str(v or "").strip()
if entity:
out.append((here, entity))
continue
if k == cls.writer_key:
actuator = cls.actuator_id_of(node)
if actuator:
out.append((here, actuator))
continue
_collect_writers(v, here, out)
elif isinstance(node, (list, tuple)):
for i, v in enumerate(node):
@@ -498,7 +515,7 @@ def actuator_writers(opts: dict) -> dict:
_collect_writers(opts, "", found)
census: dict = {}
for where, entity in found:
census.setdefault(entity.lower(), []).append(where)
census.setdefault(drivers.census_key(entity), []).append(where)
return census
@@ -729,11 +746,16 @@ def _roster_problems(opts: dict) -> list[str]:
else:
seen[name] = where
who = f"{where} ({name})" if name else where
if not str(entry.get("setpoint_entity") or "").strip():
# SMA-2. WHETHER THE ENTRY REACHES ITS INVERTER IS THE DRIVER'S TO SAY.
# For goodwe_esphome that is a setpoint entity, and the sentence is the
# one it always was. An unknown driver is refused by (h) below.
_cls = drivers.driver_class(entry)
if _cls is not drivers.UnavailableDriver and not _cls.actuator_id_of(entry):
problems.append(
f"{who} has no {S('setpoint_entity')}, so the add-on cannot "
"control it. Set its ESPHome number entity, or remove the "
"entry.")
problems += _driver_problems(entry, who)
if _number(entry, "max_w", None) is None or (_number(entry, "max_w", None) or 0) <= 0:
problems.append(
f"{who} has no usable {S('max_w')}: it is "
@@ -775,6 +797,56 @@ def _roster_problems(opts: dict) -> list[str]:
return problems
def _whole(raw, lo: int, hi: int):
"""`raw` as an int in [lo, hi], or None. A bool or a fraction is not one."""
if isinstance(raw, bool):
return None
try:
val = float(raw)
# NaN and infinity: int() raises on them, so refuse them first.
if not math.isfinite(val) or val != int(val):
return None
except (TypeError, ValueError, OverflowError):
return None
return int(val) if lo <= val <= hi else None
def _driver_problems(entry: dict, who: str) -> list[str]:
"""Rule 9(h) (SMA-2): the keys that choose and address an inverter driver.
NOT IN config.yaml's SCHEMA, so the Supervisor form and its validator never
see them (owner decision 2026-11-07: clients see nothing new until SMA-4).
They can still reach this rule from callers that skip the schema (the
panel's save path, sim/inject, the checks), so they are graded here, and
named by key because they have no label.
Only `goodwe_esphome` is selectable for now. `host`, `port`, `unit_id` and
`maintenance` are accepted and checked for shape, and nothing reads them
yet: a later driver's entry must not be refused for carrying them.
"""
out: list[str] = []
raw = entry.get("driver")
if raw not in (None, "") and str(raw).strip() not in drivers.SELECTABLE:
out.append(
f"{who} has `inverters.driver` {messages.shown(raw)}. Use "
f"{', '.join(drivers.SELECTABLE)}, or leave it empty.")
host = entry.get("host")
if host not in (None, "") and (not isinstance(host, str)
or re.search(r"\s", host.strip())):
out.append(f"{who} has `inverters.host` {messages.shown(host)}, which is "
"not an address. Use a name or an IP address.")
for key, lo, hi in (("port", 1, 65535), ("unit_id", 0, 247)):
val = entry.get(key)
if val not in (None, "") and _whole(val, lo, hi) is None:
out.append(f"{who} has `inverters.{key}` {messages.shown(val)}. Use a "
f"whole number from {lo} to {hi}.")
maint = entry.get("maintenance")
if maint is not None and not isinstance(maint, bool):
out.append(f"{who} has `inverters.maintenance` {messages.shown(maint)}. "
"Use on or off.")
return out
def validate_unit_ranges(units, *, skip_entity: str = "") -> list[str]:
"""Rule 2, per inverter, against each unit's OWN reported device range.
@@ -787,8 +859,8 @@ def validate_unit_ranges(units, *, skip_entity: str = "") -> list[str]:
2's own failure mode restored by a config shape: the operator's stated
ceiling is not the ceiling and nothing says which won.
`units` is the roster (anything with `.name`, `.setpoint_entity`, `.max_w`,
`.dev_min`, `.dev_max`). A unit whose device did not answer is SKIPPED, not
`units` is the roster (anything with `.name`, `.driver` or `.setpoint_entity`,
`.max_w`, `.dev_min`, `.dev_max`). A unit whose device did not answer is SKIPPED, not
guessed at, for the reason in this module's docstring: ESPHome is often not
up when the add-on boots and (None, None) means "not read", not "zero".
@@ -800,7 +872,12 @@ def validate_unit_ranges(units, *, skip_entity: str = "") -> list[str]:
problems: list[str] = []
skip = str(skip_entity or "").strip().lower()
for unit in units:
entity = str(getattr(unit, "setpoint_entity", "") or "").strip()
# SMA-2. THE DRIVER'S ACTUATOR, not a GoodWe key: a unit reached some
# other way is graded too. A bare object with only `.setpoint_entity`
# (the checks pass some) is read as it always was.
drv = getattr(unit, "driver", None)
entity = str((drv.actuator_id() if drv is not None
else getattr(unit, "setpoint_entity", "")) or "").strip()
if not entity or entity.lower() == skip:
continue
cap = float(getattr(unit, "max_w", 0.0) or 0.0)
+2 -1
View File
@@ -442,7 +442,8 @@ def build_app(controller, selfcfg=None) -> web.Application:
"""Restart the add-on, at the operator's explicit request.
⚠️ THIS IS THE ONE ROUTE ON THIS SURFACE THAT COSTS ANYTHING. The
wind-down commands 0 W on every inverter (`Controller.shutdown()`), so
wind-down commands 0 W on every inverter, or hands a unit back when its
driver does (`Controller.shutdown()`, SMA-10), so
the request must carry the intent token; a reload, a retry or a stray
POST cannot spend a control interruption. It restarts THIS ADD-ON and
nothing else: no setpoint is written from here, and a latched failsafe
+1 -1
View File
@@ -1,5 +1,5 @@
name: GoodWe RS485 Controller
version: "0.20.1"
version: "0.21.0"
slug: goodwe_controller
description: >-
Drives a GoodWe ES/BP battery inverter over its RS485 EMS port by sending it a
+1 -1
View File
@@ -790,7 +790,7 @@ print(f" BOUNDS['soc'] subscripted in CODE by: {_uses_soc or 'nothing'}")
check("⚠️ `wired=True` MEANS SOMETHING CONSUMES IT. A policy table nobody "
"checks is a comment; this is the row `batt` claims and the module that "
"claims it",
BOUNDS["batt"].wired is True and _uses_batt == ["inverter.py"])
BOUNDS["batt"].wired is True and _uses_batt == ["drivers.py"])
check("⚠️ AND `wired=False` MEANS NOTHING DOES. SoC is TEL-08's and it is "
"STATED here rather than wired, because its obligation term is energy "
"through the pack and the constant that needs has never been measured on "
+7
View File
@@ -793,6 +793,7 @@ from datetime import datetime as _dt, timedelta as _td, timezone as _tz # noqa:
from app import clamp as _clamp, freshness as _fresh, peakguard as _pg # noqa: E402
from app import store as _store # noqa: E402
from app import handback # noqa: E402
from app.circulation import CirculationConfig, CirculationWatchdog # noqa: E402
from app.control import Tuning, compute # noqa: E402
from app.delivery import (DeliveryConfig, DeliveryWatchdog, UnitDelivery, # noqa: E402
@@ -1058,6 +1059,12 @@ TEXT = {
"main.py:messages.reason_code(inv.batt_fresh.reason)": _coded(_stale_texts),
"main.py:rep.explain()": _migration_texts,
"store.py:rep.explain()": _migration_texts,
# SMA-10: the control-task CRITICAL line's state, for a GoodWe-only roster
# (the sentence it always was) and a mixed one.
"main.py:handback.task_died_state(handback.current())": lambda: [
handback.task_died_state(()),
handback.task_died_state((handback.Unit("inverter-a"),
handback.Unit("inverter-b", True)))],
"main.py:plan.words": _tariff_texts,
# OPT-11 P2: why an MQTT command was ignored.
"main.py:why": lambda: list(messages.PACK_REFUSED.values()),
+3 -2
View File
@@ -144,8 +144,9 @@ rs(st(5.0, at(4, 9, 5)), st(12.0, at(4, 9, 5)), at(4, 9, 6), h9)
for label, tm in (("stale", st(12.0, at(4, 9, 5))), ("unavailable", GONE)):
fd = rs(st(3.0, at(4, 13, 55)), tm, at(4, 14, 0), h9)[0]
check(f"14:00, today fresh, tomorrow {label} since 09:05 (over 3 h): "
"no tomorrow, nothing kept",
fd is not None and fd.tomorrow is None and not fd.kept)
"the 09:05 figure covers it, kept (OPT-38: at any hour)",
fd is not None and fd.tomorrow is not None
and fd.tomorrow.kwh == 12.0 and not fd.kept)
fn = rs(st(0.1, at(4, 20, 55)), tm, at(4, 21, 0), h9)[0]
check(f"21:00, tomorrow {label}: the 09:05 figure covers it, kept",
fn is not None and fn.tomorrow is not None
+3 -2
View File
@@ -186,8 +186,9 @@ check("a fresh figure replaces the kept one at once (04:00: 5.0 today, "
and fy.today.kwh == 5.0 and fy.tomorrow.kwh == 9.0)
fy2 = rs(st(5.0, at(4, 7, 55)), GONE, at(4, 8, 0), hd)[0]
check("... and at 08:00, today fresh and tomorrow's sensor down for over 3 h: "
"no tomorrow (the 3rd's figure is not the 5th's)",
fy2 is not None and fy2.tomorrow is None and fy2.today.kwh == 5.0)
"tomorrow is the 03:50 figure for the 5th (9.0, not flagged kept before 20:00: OPT-38), never "
"the 3rd's 12.0", fy2 is not None and fy2.today.kwh == 5.0
and fy2.tomorrow is not None and fy2.tomorrow.kwh == 9.0 and not fy2.kept)
# Restart: the saved hold keeps the figure.
for label, now in (("01:00", at(4, 1, 0)), ("04:00", at(4, 4, 0))):
+159
View File
@@ -0,0 +1,159 @@
"""Runnable check for OPT-38. `python3 test_opt38.py`
Live 0.20.1, 2026-11-06: one of three Forecast.Solar tomorrow sensors last
reported 14:54. From 17:54 (over FRESH_S) to 20:00 (BELL_TO_H) nothing stood in
for it, the OPT-17 sum was dropped and the Forecast tab had no tomorrow. A kept
tomorrow reading now stands in at any hour (`Hold.stand_in()`). Today members,
and the OPT-34 morning rules, are as before.
Mutations (MUTATION.md, purged copies): see the pull request.
"""
import os
import sys
from datetime import datetime, timedelta, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from app import homeview, solarfc # noqa: E402
fails = []
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
L = timezone(timedelta(hours=1)) # Brussels in winter (CET)
def at(day, hh, mm=0):
return datetime(2026, 11, day, hh, mm, tzinfo=L).astimezone(timezone.utc)
def st(kwh, when):
return {"state": f"{kwh}", "attributes": {"unit_of_measurement": "kWh"},
"last_updated": when.isoformat(), "last_reported": when.isoformat()}
TODAY = [("sensor.t", None)]
M = ["sensor.m1", "sensor.m2", "sensor.m3"]
def run(hold, readings, now, today_at=None):
t = [("sensor.t", st(0.5, today_at or now - timedelta(minutes=5)))]
return solarfc.read_sum(
t, [(e, st(k, w)) for e, (k, w) in zip(M, readings)], now, hold)
# The live day: m2 last reported 14:54, the others keep reporting.
h = solarfc.Hold()
run(h, [(4.0, at(6, 14, 0)), (5.0, at(6, 14, 54)), (6.0, at(6, 14, 0))],
at(6, 14, 55))
fresh = lambda w: [(4.0, w), (5.0, at(6, 14, 54)), (6.0, w)] # noqa: E731
f, why, gaps = run(h, fresh(at(6, 18, 20)), at(6, 18, 30))
check("18:30, one member last reported 14:54: tomorrow sum is there (not "
"flagged kept before 20:00)",
f is not None and f.tomorrow is not None and f.tomorrow.kwh == 15.0
and not f.kept and gaps == ())
f, _w, _g = run(h, fresh(at(6, 17, 40)), at(6, 17, 50))
check("17:50 (just under 3 h): fresh, not kept",
f is not None and f.tomorrow.kwh == 15.0 and not f.kept)
f, _w, _g = run(h, fresh(at(6, 17, 55)), at(6, 18, 0))
check("18:00 (stale since 17:54): tomorrow there",
f is not None and f.tomorrow is not None and not f.kept)
f, _w, _g = run(h, fresh(at(6, 19, 50)), at(6, 19, 55))
check("19:55 (before the bell ends): tomorrow there", f.tomorrow is not None)
# Too old: over KEPT_MAX_AGE_S (12 h) when used.
h2 = solarfc.Hold()
run(h2, [(4.0, at(6, 5, 0)), (5.0, at(6, 5, 0)), (6.0, at(6, 5, 0))],
at(6, 5, 5))
w = at(6, 16, 50)
f, why, gaps = run(h2, [(4.0, w), (5.0, at(6, 5, 0)), (6.0, w)],
at(6, 17, 10))
check("member 12 h 10 min old: no tomorrow sum (OPT-17 rule), today stays",
f is not None and f.tomorrow is None
and [g[0] for g in gaps] == ["tomorrow"])
f, _w, _g = run(h2, [(4.0, w), (5.0, at(6, 5, 0)), (6.0, w)],
at(6, 16, 50))
check("... and 11 h 50 min old is still kept",
f is not None and f.tomorrow is not None and not f.kept)
# Not a partial sum: a member never read has nothing to stand in.
f, _w, gaps = run(solarfc.Hold(), [(4.0, at(6, 18, 0)),
(5.0, at(6, 14, 54)),
(6.0, at(6, 18, 0))], at(6, 18, 30))
check("a member with no kept reading: no tomorrow sum, no partial sum",
f is not None and f.tomorrow is None and len(gaps) == 1)
# Today members are as before: a stale today member at 18:30 is not kept.
h3 = solarfc.Hold()
solarfc.read_sum([("sensor.t", st(1.0, at(6, 14, 54)))],
[(M[0], st(9.0, at(6, 14, 54)))], at(6, 14, 55), h3)
f, why, _g = solarfc.read_sum([("sensor.t", st(1.0, at(6, 14, 54)))],
[(M[0], st(9.0, at(6, 18, 20)))],
at(6, 18, 30), h3)
check("stale today member at 18:30: not kept, no forecast",
f is None and why == solarfc.STALE)
f, _w, _g = solarfc.read_sum([("sensor.t", st(1.0, at(6, 14, 54)))],
[(M[0], st(9.0, at(6, 20, 0)))],
at(6, 20, 30), h3)
check("... and at 20:30 it is kept, as before (the bell has ended)",
f is not None and f.kept)
# After midnight: a tomorrow reading from before midnight is never tomorrow's.
h4 = solarfc.Hold()
run(h4, [(4.0, at(6, 14, 0)), (5.0, at(6, 14, 0)), (6.0, at(6, 14, 0))],
at(6, 14, 5))
for label, now in (("00:30", at(7, 0, 30)), ("10:00", at(7, 10, 0)),
("15:00", at(7, 15, 0))):
f, _w, _g = solarfc.read_sum(
[("sensor.t", st(2.0, now - timedelta(minutes=5)))],
[(e, st(k, at(6, 14, 0))) for e, k in zip(M, (4.0, 5.0, 6.0))],
now, h4)
check(f"{label} on the 7th: the 6th's tomorrow figure is not the "
"7th's tomorrow", f is not None and f.tomorrow is None)
# Before 20:00 a kept tomorrow reading is not "kept for tonight": today's
# line stays the normal one (EN and NL) and the event log (main.py, from
# `fc.kept`) has no "kept".
h5 = solarfc.Hold()
solarfc.read_sum([("t", st(3.0, at(6, 9, 0)))], [("m", st(12.0, at(6, 9, 5)))],
at(6, 9, 6), h5)
for hh in (14, 18, 19):
f, _w, _g = solarfc.read_sum([("t", st(2.5, at(6, hh - 1, 55)))],
[("m", st(12.0, at(6, 9, 5)))],
at(6, hh, 0), h5)
check(f"{hh}:00, today fresh, tomorrow kept from 09:05: tomorrow there, "
"not flagged kept", f is not None and f.tomorrow is not None
and f.tomorrow.kwh == 12.0 and f.kept is False)
f, _w, _g = solarfc.read_sum([("t", st(2.5, at(6, 13, 55)))],
[("m", st(12.0, at(6, 9, 5)))], at(6, 14, 0), h5)
for lang in ("en", "nl"):
with homeview.in_lang(lang):
line = homeview.line_solar(f.today.kwh, f.today.kwh * 0.7,
homeview.hhmm(f.at), kept=f.kept)
kept_line = homeview.line_solar(1, 1, homeview.hhmm(f.at), kept=True)
print(f" {lang}: {line!r}")
if lang == "en":
check("... EN says 'Solar still to come today'",
line.startswith("Solar still to come today"))
check(f"14:00 Home line ({lang}) is the normal line, not the kept one",
line != kept_line and "2,5" in line.replace(".", ",")
and "13:55" in line)
f, _w, _g = solarfc.read_sum([("t", st(0.2, at(6, 20, 55)))],
[("m", st(12.0, at(6, 9, 5)))], at(6, 21, 0), h5)
check("21:00 as before: tomorrow kept from 09:05 is flagged kept",
f is not None and f.kept and f.tomorrow.kwh == 12.0)
print()
if fails:
print(f"{len(fails)} FAILED:")
for f in fails:
print(" -", f)
sys.exit(1)
print("all checks passed")
+5 -3
View File
@@ -229,9 +229,11 @@ late5 = R.Rig(lag_s=30.0, lag_on=ON, lag_off=ON + 300.0, p1_s=5.0)
late5.run(ON + 300.0, lambda rig, c, t: rows5.extend(
str(r["text"]) for r in c.checks() if r.get("id") == "late"))
print(f" 5 s meter, 30 s late: {sorted(set(rows5))}")
check("at a 5 s meter (the batteries' fit) the row names the delay: about "
"20-32 s for 30 s late",
rows5 and set(rows5) <= _ok_texts and any("about" in x for x in rows5))
# SAFETY-129: the 5 s meter's fit finds it first (no figure); the hold then
# leaves the batteries' fit nothing to measure, so the row names no delay.
check("at a 5 s meter the row says the readings are late, with no figure "
"(the meter alone found it)",
rows5 and set(rows5) == {str(messages.row_readings_late(None))})
check("logged once for the episode, and once when it ends, not per cycle",
n_late == 1 and n_back == 1)
check("the row goes once a fit shows the readings on time, or 2 minutes "
+238
View File
@@ -0,0 +1,238 @@
"""Runnable check for SAFETY-129: late Home Assistant readings found at a 5 s meter.
`python3 test_safety129.py`
SAFETY-128 fitted the meter's delay only at a meter of about 3.5 s or faster
(16 new values in 60 s). The owner's P1 reports every 5 s, so there only the
batteries' fit ran: with readings 30 s late the loop swung to -420 W export
and was found after about 3 minutes (-1 325 W before the hold).
`lateness.MeterFit` now also runs at a slow meter over 120 s, and calls a
delay late only over `M_SLOW_LATE_S` on two fits in a row, with the same
corroboration as before (an ask slow to start, no battery fit on time).
DECISIONS/SAFETY-128-late-readings.md.
The REAL Controller on TEST-23's plant (tools/safety128_rig.py).
1. 5 s meter, readings 30 s late (N=2 house 1 800 W, N=1 house 1 500 W): found
within 100 s, and the export never goes below -200 W (red on c66aa7f: found
after 190 s, export to -420 W).
2. 5 s meter, readings 10 s late: no swing, nothing to hold; and the limit that
goes with it: a battery that answers in 10 s (R2-1) is still not read as
late at a 5 s meter, which a lower slow-meter threshold would break.
3. No false holds at a slow meter: the owner's shape at 2, 5 and 10 s, HA
restarts and meter pauses at 2 and 5 s, 8-10 s dead times: never
late, so the commands are those of the run without the gate.
4. The slow-meter fit at its edges.
Mutations (MUTATION.md, purged copies) are listed in the pull request.
"""
import logging
import os
import sys
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 safety128_rig as R # noqa: E402
import app.main as app_main # noqa: E402
from app import lateness # noqa: E402
fails = []
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
def no_gate(fn):
"""`fn()` with the answer gate off: the tree before SAFETY-128."""
real = app_main.Controller._readings_late
app_main.Controller._readings_late = lambda self, standing_w: None
try:
return fn()
finally:
app_main.Controller._readings_late = real
def run_late(**kw):
"""Run the rig; (rig, seconds the verdict stood, first second it stood)."""
dur = kw.pop("dur")
seen = []
r = R.Rig(**kw)
r.run(dur, lambda rig, c, t: seen.append(t) if c.answer.late_seen
else None)
return r, len(seen), min(seen) if seen else None
def grid_min(rows, t0, t1):
return min(r[1] for r in rows if t0 <= r[0] < t1)
AB, A = ("a", "b"), ("a",)
ON = 300.0
# --------------------------------------------------------------------------- #
print("1. 5 s meter, readings 30 s late for 300 s")
for units, house in ((AB, 1800.0), (A, 1500.0)):
n = f"N={len(units)}"
r, secs, first = run_late(house=house, lag_s=30.0, lag_on=ON,
lag_off=ON + 300.0, units=units, p1_s=5.0,
dur=ON + 420.0)
low = grid_min(r.rows, ON, ON + 300.0)
print(f" {n}: found {None if first is None else first - ON:.0f} s "
f"after the start, export to {low:.0f} W")
check(f"{n}: found within 100 s of the lag starting",
first is not None and first - ON <= 100.0)
check(f"{n}: the export never goes below -200 W", low >= -200.0)
if len(units) == 2:
old = R.Rig(house=house, lag_s=30.0, lag_on=ON, lag_off=ON + 300.0,
units=units, p1_s=5.0)
no_gate(lambda: old.run(ON + 300.0))
check(f"{n}: without the gate the export goes below -1 kW",
grid_min(old.rows, ON, ON + 300.0) < -1000.0)
# --------------------------------------------------------------------------- #
print("\n2. 5 s meter, readings 10 s late; a battery that answers in 10 s")
r, secs, first = run_late(house=1800.0, lag_s=10.0, lag_on=ON,
lag_off=ON + 150.0, units=AB, p1_s=5.0,
dur=ON + 200.0)
low = grid_min(r.rows, ON, ON + 150.0)
print(f" 10 s late: export to {low:.0f} W, verdict stood {secs} s")
check("10 s late: no swing, the export never goes below -200 W", low >= -200.0)
def owner(t):
w = 400.0
if 600 <= t < 780:
w += 2200
if 1200 <= t < 2400 and ((t - 1200) % 105) < 45:
w += 2000
return w
for dead in (8.0, 10.0):
r, secs, first = run_late(house=owner, noise=80.0, units=AB, p1_s=5.0,
dead_s=dead, dur=800.0)
print(f" {dead:.0f} s dead time, 5 s meter: late {secs} s")
check(f"{dead:.0f} s dead time at a 5 s meter is not read as late "
f"(R2-1 does not get worse)", secs == 0)
# At a 6 s meter an 8 s dead time reads late on the slow fit alone; only the
# slow-start and battery-fit check keeps it from a verdict (122 s late
# without the check, from 1 084 s).
r, secs, first = run_late(house=owner, noise=80.0, units=AB, p1_s=6.0,
dead_s=8.0, dur=1500.0)
print(f" 8 s dead time, 6 s meter: late {secs} s")
check("an 8 s dead time at a 6 s meter is never late (the slow fit needs an "
"ask slow to start and no battery fit on time)", secs == 0)
# A 12 s dead time is already read as late (R2-1, SAFETY-128); the slow-meter
# fit must not make that longer. The same run with the slow fit off is the
# tree before this card.
_slow = lateness.MeterFit.slow
secs = {}
for label in ("with", "without"): # 12 s dead time: late from about 140 s
lateness.MeterFit.slow = _slow if label == "with" else (lambda self: False)
try:
secs[label] = run_late(house=owner, noise=80.0, units=A, p1_s=5.0,
dead_s=12.0, dur=900.0)[1]
finally:
lateness.MeterFit.slow = _slow
print(f" 12 s dead time, N=1, 5 s meter: late {secs['with']} s, with the "
f"slow fit off {secs['without']} s")
check("a 12 s dead time at a 5 s meter is late no longer than before "
"(R2-1 does not get worse)", secs["with"] <= secs["without"])
# --------------------------------------------------------------------------- #
print("\n3. no false holds")
_view = R.Plant.view
def frozen(windows, meter_only):
def view(self, t, lag_s, lag_on, lag_off):
cur = _view(self, t, lag_s, lag_on, lag_off)
for a, b in windows:
if a <= t < b:
for row in reversed(self.hist):
if row[0] <= a + 1e-9:
old = row[1:]
return (old[0], old[1], cur[2], cur[3]) \
if meter_only else old
return cur
return view
for p1 in (2.0, 5.0, 10.0):
kw = dict(house=owner, noise=80.0, units=AB, p1_s=p1)
r, secs, first = run_late(dur=800.0, **kw)
new = r
old = R.Rig(**kw)
no_gate(lambda: old.run(800.0))
same = max(abs(x[2] - y[2]) for x, y in zip(new.rows, old.rows))
print(f" owner shape, {p1:.0f} s meter: late {secs} s, command "
f"difference {same:.0f} W")
check(f"{p1:.0f} s meter, owner shape: never late, same commands",
secs == 0 and same == 0)
for label, windows, meter_only in (
("HA restart", ((650.0, 710.0),), False),
("meter pause", ((640.0, 700.0),), True)):
for p1 in (2.0, 5.0):
R.Plant.view = frozen(windows, meter_only)
try:
r, secs, first = run_late(house=owner, noise=80.0, units=AB,
p1_s=p1, dur=800.0)
finally:
R.Plant.view = _view
check(f"{label} at a {p1:.0f} s meter: never late", secs == 0)
# --------------------------------------------------------------------------- #
print("\n4. the slow-meter fit at its edges")
def meter_with(period, pause_after=None, pause_s=40.0, n=24):
f = lateness.MeterFit()
f.add(0.0, 100.0, 0.0)
for k in range(1, n):
gap = pause_s if pause_after is not None and k > pause_after else 0.0
f.add(period * k + gap, None, float(k))
return f
check("a 5 s and a 10 s meter are slow",
meter_with(5.0).slow() and meter_with(10.0).slow())
check("a 1 s, a 2 s and a 3 s meter are not slow",
not any(meter_with(p, n=60).slow() for p in (1.0, 2.0, 3.0)))
check("a pause in a 2 s meter does not make it slow",
not meter_with(2.0, pause_after=10, n=40).slow())
def fed(values):
"""Answer.watch() with the slow fit reading `values`, one per fit."""
a = lateness.Answer()
a.meter.slow = lambda: True
a.meter.estimate = a.delay.estimate = lambda: None
it = iter(values)
a.meter_slow.estimate = lambda: next(it, None)
for k in range(len(values)):
a.watch(2.0 * k, [], 0.0, 0.0)
return a
check("one late slow-meter fit is no fit; two in a row are one, and "
"one on time or in between is none",
fed([30.0]).fits == 0 and fed([30.0, 30.0]).fits == 1
and fed([30.0, None, 30.0]).fits == 0 and fed([30.0, 12.0]).fits == 0
and fed([3.0, 3.0]).fits == 0 and not fed([30.0, 30.0]).late_seen)
check("the slow fit asks for a longer window and a later delay than the "
"fast one", lateness.M_SLOW_FIT_S > lateness.M_FIT_S
and lateness.M_SLOW_LATE_S > lateness.M_LATE_S)
check("the slow fit's late limit is above the fast one's and above a "
"10 s lag", lateness.M_SLOW_LATE_S >= 16.0)
print()
if fails:
print(f"{len(fails)} FAILED: " + ", ".join(fails))
sys.exit(1)
print("all checks passed")
@@ -0,0 +1,332 @@
"""SAFETY-137: the 0 W of shutdown and of the Stop button is the last write every
unit hears. `python3 test_safety137_last_write.py`
A cycle write already on its way (0.3-0.6 s, or hung) must not land after the
0 W, for a GoodWe unit and for a fake unit that does not hand back, at N=1 and
N=2, at shutdown and at Stop. The control cycle (and the heartbeat) issue no
new write once shutdown has begun. The whole wind-down stays inside
HAND_BACK_WORST_S (6 s) when a write hangs.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
The mutants this file was run against are listed at the end.
"""
import asyncio
import sys
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from app import main as M # noqa: E402
from app.drivers import Driver, Probe, REGISTRY # noqa: E402
from app.main import Controller # noqa: E402
from app.store import DEFAULTS # noqa: E402
fails = []
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
class PlainFake(Driver):
"""A unit that does not hand back (so, like GoodWe, no release()). A write
of anything but 0 W takes `delay` s to land; every write is logged when it
LANDS (`landed`) and when it STARTS (`started`)."""
name = "plainfake"
writer_key = "host"
brand = "Fake"
hands_back = False
delay = 0.0
def __init__(self, host="", port=502, unit_id=1, rating=2000.0):
self.host, self.port, self.unit_id = host, port, unit_id
self.rating, self.power = rating, 0.0
self.landed, self.started = [], []
@classmethod
def from_entry(cls, entry):
return cls(entry.get("host", ""), entry.get("port", 502),
entry.get("unit_id", 1))
@classmethod
def actuator_id_of(cls, entry):
host = str(entry.get("host") or "").strip()
return f"{host}:{entry.get('port', 502)}:{entry.get('unit_id', 1)}" \
if host else ""
def configured(self):
return bool(self.host)
def actuator_id(self):
return f"{self.host}:{self.port}:{self.unit_id}"
def soc_source(self):
return "fake-soc"
def batt_source(self):
return "fake-power"
async def limits(self):
return -self.rating, self.rating
async def read(self):
return 60.0, self.power, {}
async def write(self, w):
self.started.append((time.monotonic(), float(w)))
if w != 0 and self.delay:
await asyncio.sleep(self.delay)
self.landed.append((time.monotonic(), float(w)))
self.power = w
return True
async def probe(self):
return Probe(-self.rating, self.rating, 60.0, self.power, {})
REGISTRY["plainfake"] = PlainFake
class MemStore:
def __init__(self):
self.data = dict(DEFAULTS)
def set(self, k, v):
self.data[k] = v
def get_time(self, *a):
return None
def set_time(self, *a):
pass
class Pub:
enabled = False
def publish(self, values):
pass
def close(self):
pass
class SlowHass:
"""Home Assistant for the GoodWe units. A set_number of anything but 0 W
takes `delay` s to land; the log gets the write when it lands."""
def __init__(self):
self.delay = 0.0
self.landed, self.started = [], [] # (t, entity, value)
self.numbers = {"sensor.grid": 3000.0, "sensor.soc_a": 50.0,
"sensor.batt_a": 0.0, "sensor.soc_b": 50.0,
"sensor.batt_b": 0.0}
async def number(self, entity, invert=False):
return self.numbers.get(entity)
async def limits(self, entity):
return (-3000.0, 3000.0, 1.0)
async def set_number(self, entity, value):
self.started.append((time.monotonic(), entity, value))
if value != 0 and self.delay:
await asyncio.sleep(self.delay)
self.landed.append((time.monotonic(), entity, value))
return True
async def state(self, entity):
return None
async def call(self, *a):
return True
def gw(name, suffix):
return dict(name=name, setpoint_entity=f"number.sp_{suffix}",
soc_entity=f"sensor.soc_{suffix}",
batt_entity=f"sensor.batt_{suffix}", max_w=3000,
bms_soc_floor=10)
def fk(name):
return dict(name=name, driver="plainfake", host="10.9.9.9", port=502,
unit_id=3, max_w=2000, bms_soc_floor=10)
ROSTERS = {
"N=1 GoodWe": [gw("inverter-a", "a")],
"N=1 fake": [fk("inverter-a")],
"N=2 GoodWe+GoodWe": [gw("inverter-a", "a"), gw("inverter-b", "b")],
"N=2 GoodWe+fake": [gw("inverter-a", "a"), fk("inverter-b")],
}
def site(inverters, delay):
opts = dict(meter_source="off", meter_entity="sensor.grid", max_w=5000,
gain=0.6, slew_w=0, deadband_w=15, target_grid_w=0, step_w=10,
heartbeat_s=10, stale_input_s=15, shadow_mode="off",
inverters=inverters)
hass = SlowHass()
hass.delay = delay
c = Controller(opts, hass, MemStore(), Pub(), stop=asyncio.Event())
for inv in c.inverters:
inv.dev_min, inv.dev_max = -3000.0, 3000.0
if isinstance(inv.driver, PlainFake):
inv.driver.delay = delay
c.auto = True
return c, hass
def per_unit(c, hass, kind="landed"):
"""name -> [(t, value)] in the order the writes LANDED (or started)."""
out = {}
for inv in c.inverters:
d = inv.driver
if isinstance(d, PlainFake):
out[inv.name] = list(getattr(d, kind))
else:
ent = d.setpoint_entity
out[inv.name] = [(t, v) for t, e, v in getattr(hass, kind)
if e == ent]
return out
async def cycles(c, n=2):
for _ in range(n):
await c.read_inputs()
await c.cycle()
async def in_flight(c):
"""A cycle write on its way to every unit (what rig 5b had): the real
cycle, whose writes are authorised and take `delay` s to land."""
tasks = [asyncio.ensure_future(cycles(c, 1))]
await asyncio.sleep(0.1)
assert all(not t.done() for t in tasks)
return tasks
async def finish(tasks):
for t in tasks:
t.cancel()
for t in tasks:
try:
await t
except BaseException: # noqa: BLE001 - cancelled or timed out
pass
def last_is_zero(c, hass):
got = per_unit(c, hass)
return all(w and w[-1][1] == 0.0 for w in got.values()), got
def scenario(label, inverters, how, delay):
"""how: 'shutdown' or 'stop'. Returns (seconds, ok, detail)."""
c, hass = site(inverters, delay)
async def go():
tasks = await in_flight(c)
t0 = time.monotonic()
if how == "shutdown":
await c.shutdown()
else:
await c.handle_action("auto_toggle") # Stop
dt = time.monotonic() - t0
# let a write that is still on its way land, to see if it overtakes
await asyncio.sleep(0.8 if delay < 5 else 0.0)
await finish(tasks)
return dt
dt = asyncio.run(go())
ok, got = last_is_zero(c, hass)
n_sent = {n: len(w) for n, w in got.items()}
check(f"{label}: the cycle write was on its way at {how} (test sees it)",
all(len(w) >= 2 for w in per_unit(c, hass, "started").values()))
print(f" {label}: {how}, delay {delay} s: {dt:.2f} s, "
f"landed per unit {n_sent}, last "
f"{ {n: (w[-1][1] if w else None) for n, w in got.items()} }")
return dt, ok, got
print("SAFETY-137 - the 0 W is the last write")
print("1. a slow write on its way (0.3 s, 0.6 s) when shutdown / Stop starts")
for label, roster in ROSTERS.items():
for how in ("shutdown", "stop"):
for delay in (0.3, 0.6):
dt, ok, got = scenario(label, roster, how, delay)
check(f"{label}, {how}, {delay} s in flight: the last write per "
f"unit is 0 W", ok)
check(f"{label}, {how}, {delay} s in flight: the slow write "
f"landed first, then the 0 W (not dropped, not overtaken)",
all(len(w) >= 2 and w[-2][1] != 0.0
for w in got.values()))
check(f"{label}, {how}: took about the write, not the budget "
f"({dt:.2f} s)", dt < delay + 1.0)
print("2. a hung write on its way: the 0 W still reaches every unit, in time")
for label, roster in ROSTERS.items():
for how in ("shutdown", "stop"):
dt, ok, got = scenario(label, roster, how, 3600.0)
check(f"{label}, {how}, hung write: 0 W landed on every unit and is "
f"its last write", ok)
check(f"{label}, {how}, hung write: inside HAND_BACK_WORST_S "
f"({dt:.2f} s <= {M.HAND_BACK_WORST_S:.0f} s)",
dt <= M.HAND_BACK_WORST_S)
check(f"{label}, {how}, hung write: the 0 W goes after the settle "
f"wait ({M.SETTLE_BUDGET_S:.0f} s), not after the write's own "
f"budget ({dt:.2f} s)", dt <= M.SETTLE_BUDGET_S + 0.5)
print("3. no new write once shutdown has begun (cycle, heartbeat)")
for label, roster in ROSTERS.items():
c, hass = site(roster, 0.4)
async def go3():
tasks = await in_flight(c)
s = asyncio.ensure_future(c.shutdown())
await asyncio.sleep(0) # shutdown has begun
begun = time.monotonic()
await cycles(c, 3) # would write: grid 3000 W
await c.send_heartbeats(10 ** 9, 10) # every unit is due
await asyncio.wait_for(s, 10)
await asyncio.sleep(0.8)
await finish(tasks)
return begun
begun = asyncio.run(go3())
starts = per_unit(c, hass, "started")
late = {n: [v for t, v in w if t >= begun and v != 0.0]
for n, w in starts.items()}
check(f"{label}: no non-zero write started after shutdown began "
f"({late})", all(not v for v in late.values()))
ok, got = last_is_zero(c, hass)
check(f"{label}: and the last write per unit is 0 W", ok)
# sanity: the same cycles DO write before shutdown
c2, hass2 = site(roster, 0.0)
asyncio.run(cycles(c2, 3))
before = per_unit(c2, hass2, "started")
check(f"{label}: control, same cycles before shutdown, write non-zero "
f"(the test can see a write)",
all(any(v != 0.0 for _t, v in w) for w in before.values()))
print()
if fails:
print(f"FAILED {len(fails)}:")
for f in fails:
print(" -", f)
sys.exit(1)
print("all ok")
# MUTANTS this file was run against (each must turn it red):
# (a) _await_inflight does nothing (no wait for in-flight writes), GoodWe too
# (b) the `elif self.stopping: return` gate removed (cycle not stopped)
# (c) `last=True` not passed by command_site_release (Stop/shutdown 0 W is a
# plain write)
# (d) the wait unbounded (no timeout): red on the settle-bound check
File diff suppressed because it is too large Load Diff
+750
View File
@@ -0,0 +1,750 @@
"""SMA-2: the inverter driver seam. `python3 test_sma2_driver.py`
Part 1 grades the GoodWe driver against a Home Assistant that logs every call:
it must make exactly the calls the code it replaced made, in the same order.
Part 2 grades what `Inverter` reads from its driver. Part 3 drives a REAL
Controller with a roster of one fake-driver unit and one GoodWe unit and
checks that it writes, reads, limits, grades, drops and publishes each by its
own driver, with a Home Assistant that records every entity it is asked about
so a call site that goes round the seam is seen. Part 4 is the SAFETY-28
census and rule 9 on the new keys. Part 5 is the schema.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
The seam mutants this file was run against are listed at the end.
"""
import asyncio
import io
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
from app import drivers
from app.drivers import (DEFAULT_DRIVER, REGISTRY, SELECTABLE, Driver,
DriverNotBound, GoodWeEsphomeDriver, Probe,
UnavailableDriver, build_driver, census_key)
from app.freshness import BOUNDS, Bound
from app.inverter import LINK_STALE_S, Inverter, build_roster
from app.main import Controller
from app.store import DEFAULTS
from app.validate import (actuator_writers, validate_startup_config,
validate_unit_ranges)
fails = []
HERE = Path(__file__).resolve().parent
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
class MemStore:
def __init__(self):
self.data = dict(DEFAULTS)
def set(self, k, v):
self.data[k] = v
def get_time(self, *a):
return None
def set_time(self, *a):
pass
class Pub:
"""Keeps the last published values, like test_mqtt.py's."""
enabled = False
def __init__(self):
self.last = {}
def publish(self, values):
self.last = dict(values)
def close(self):
pass
class LogHass:
"""Home Assistant for the GoodWe unit. EVERY call is logged with its entity,
so a path that talks to Home Assistant about anything else is on record."""
def __init__(self, numbers=None, limits=None, accept=True):
self.numbers = dict(numbers or {})
self.limits_by = dict(limits or {})
self.accept = accept
self.log = [] # (method, entity, extra)
async def number(self, entity, invert=False):
self.log.append(("number", entity, invert))
v = self.numbers.get(entity)
return None if v is None else (-v if invert else v)
async def limits(self, entity):
self.log.append(("limits", entity, None))
return self.limits_by.get(entity, (None, None, None))
async def set_number(self, entity, value):
self.log.append(("set_number", entity, value))
if self.accept:
self.numbers[entity.replace("number.sp", "sensor.batt")] = value
return self.accept
async def state(self, entity):
self.log.append(("state", entity, None))
return None
async def call(self, *a):
self.log.append(("call", repr(a), None))
return True
def entities(self):
"""Every entity name Home Assistant was asked about (service calls
like notifications name none)."""
return {e for m, e, _x in self.log if m != "call"}
def run(coro):
return asyncio.run(coro)
def raises(exc, make):
"""Does `run(make())` raise `exc`? `make` builds the coroutine."""
try:
run(make())
except exc:
return True
except Exception:
return False
return False
# ---------------------------------------------------------------------------
# a fake driver: a unit reached by host:port:unit, no Home Assistant at all
# ---------------------------------------------------------------------------
FAKE_BOUND = Bound(signal="fake", unchanged_s=11.0, move_w=100.0,
release_s=5.0, wired=True, derivation="test")
class FakeDriver(Driver):
name = "fake"
writer_key = "host"
brand = "Fake"
link_stale_s = 7.0
batt_bound = FAKE_BOUND
settle_s = 3.0
words = {"idle": "handed back"}
def __init__(self, host="", port=502, unit_id=1, rating=1000.0, soc=60.0):
self.host, self.port, self.unit_id = host, port, unit_id
self.rating, self.soc, self.power = rating, soc, 0.0
self.accept = True
self.calls = [] # (what, arg)
@classmethod
def from_entry(cls, entry):
return cls(entry.get("host", ""), entry.get("port", 502),
entry.get("unit_id", 1), rating=entry.get("_rating", 1000.0))
@classmethod
def actuator_id_of(cls, entry):
host = str(entry.get("host") or "").strip()
return (f"{host}:{entry.get('port', 502)}:{entry.get('unit_id', 1)}"
if host else "")
def configured(self):
return bool(self.host)
def actuator_id(self):
return f"{self.host}:{self.port}:{self.unit_id}"
def soc_source(self):
return "fake-soc"
def batt_source(self):
return "fake-power"
async def limits(self):
self.calls.append(("limits", None))
return -self.rating, self.rating
async def read(self):
self.calls.append(("read", None))
return self.soc, self.power, {"state": "ok"}
async def write(self, w):
self.calls.append(("write", w))
if self.accept:
self.power = w # the battery follows its command
return self.accept
async def release(self):
self.calls.append(("release", None))
return True
async def probe(self):
self.calls.append(("probe", None))
return Probe(-self.rating, self.rating, self.soc, self.power, {})
def calls(drv, what):
return [a for w, a in drv.calls if w == what]
print("SMA-2 - the inverter driver seam")
print()
# ==============================================================================
print("1. the GoodWe driver makes the calls the code it replaced made")
GW = dict(setpoint_entity="number.sp_a", soc_entity="sensor.soc_a",
batt_entity="sensor.batt_a")
h1 = LogHass({"sensor.soc_a": 55.0, "sensor.batt_a": 700.0},
{"number.sp_a": (-5000.0, 4000.0, 1.0)})
d1 = GoodWeEsphomeDriver(**GW).bind(h1)
check("a driver built from an entry names its three entities and is configured",
GoodWeEsphomeDriver.from_entry(dict(GW)).setpoint_entity == "number.sp_a"
and d1.configured() and d1.actuator_id() == "number.sp_a"
and (d1.soc_source(), d1.batt_source())
== ("sensor.soc_a", "sensor.batt_a"))
check("...and one with no setpoint entity is not",
not GoodWeEsphomeDriver().configured()
and not GoodWeEsphomeDriver(soc_entity="sensor.soc_a").configured())
check("limits() is hass.limits(setpoint) and hands back (min, max)",
run(d1.limits()) == (-5000.0, 4000.0)
and h1.log == [("limits", "number.sp_a", None)])
h1.log.clear()
check("read() asks for the SoC first, then the power, with the invert flag, "
"and nothing else",
run(d1.read()) == (55.0, 700.0, {})
and h1.log == [("number", "sensor.soc_a", False),
("number", "sensor.batt_a", False)])
h1.log.clear()
d1i = GoodWeEsphomeDriver(batt_invert=True, **GW).bind(h1)
check("...and a reversed power sensor is reversed by hass.number, as before",
run(d1i.read()) == (55.0, -700.0, {})
and h1.log[1] == ("number", "sensor.batt_a", True))
h1.log.clear()
check("write(w) is hass.set_number(setpoint, w) and says whether it took it",
run(d1.write(-250.0)) is True and h1.log == [("set_number", "number.sp_a",
-250.0)])
h1.log.clear()
h1.accept = False
check("...and False when Home Assistant refuses",
run(d1.write(10.0)) is False)
h1.accept = True
h1.log.clear()
check("release() is write(0): GoodWe is handed back by its board's own watchdog",
run(d1.release()) is True
and h1.log == [("set_number", "number.sp_a", 0.0)])
h1.log.clear()
h1.numbers.update({"sensor.soc_a": 55.0, "sensor.batt_a": 700.0})
pr = run(d1.probe())
check("probe() reads the range, the SoC and the power and WRITES NOTHING",
pr == Probe(-5000.0, 4000.0, 55.0, 700.0, {})
and all(m != "set_number" for m, _e, _x in h1.log))
check("a driver with no Home Assistant is loud, not a silent 'no answer'",
raises(DriverNotBound, GoodWeEsphomeDriver(**GW).limits)
and raises(DriverNotBound, GoodWeEsphomeDriver(**GW).read)
and raises(DriverNotBound, lambda: GoodWeEsphomeDriver(**GW).write(1.0))
and not GoodWeEsphomeDriver(**GW).bound())
_swap = {"h": h1}
d1g = GoodWeEsphomeDriver(**GW).bind_getter(lambda: _swap["h"])
h1b = LogHass({"sensor.soc_a": 1.0, "sensor.batt_a": 2.0})
_swap["h"] = h1b
check("bind_getter() looks Home Assistant up at each use, so a Controller whose "
".hass is replaced afterwards is followed",
d1g.bound() and run(d1g.read()) == (1.0, 2.0, {}) and h1b.log)
check("its numbers are the ones the code it replaced used",
(d1.link_stale_s, d1.batt_bound, d1.brand)
== (LINK_STALE_S, BOUNDS["batt"], "GoodWe") and LINK_STALE_S == 30.0
and d1.settle_s == 18.0 and d1.words == {})
# ==============================================================================
print()
print("2. what Inverter reads from its driver")
NOW = datetime(2026, 11, 7, 12, 0, tzinfo=timezone.utc)
fk = FakeDriver(host="10.9.9.9", unit_id=3)
inv_f = Inverter("fake-a", driver=fk, max_w=2000.0)
inv_g = Inverter("inverter-b", max_w=3000.0, **{
"setpoint_entity": "number.sp_b", "soc_entity": "sensor.soc_b",
"batt_entity": "sensor.batt_b"})
check("an Inverter built from the old keywords gets the GoodWe driver, with "
"the same entities on the same attributes",
isinstance(inv_g.driver, GoodWeEsphomeDriver)
and (inv_g.setpoint_entity, inv_g.soc_entity, inv_g.batt_entity,
inv_g.batt_invert) == ("number.sp_b", "sensor.soc_b",
"sensor.batt_b", False))
check("...and one given another driver has none of those entities",
(inv_f.setpoint_entity, inv_f.soc_entity, inv_f.batt_entity) == ("", "", ""))
check("has_writer() is the driver's configured()",
inv_f.has_writer() and inv_g.has_writer()
and not Inverter("x", driver=FakeDriver(host="")).has_writer()
and not Inverter("y").has_writer())
check("the freshness gate is built on the DRIVER's bound",
inv_f.batt_fresh.bound is FAKE_BOUND
and inv_g.batt_fresh.bound is BOUNDS["batt"])
for u in (inv_f, inv_g):
u.note_write(False, NOW - timedelta(seconds=10))
check("is_live() takes its window from the driver: 10 s of rejected writes "
"drops a 7 s unit and not a GoodWe one",
inv_f.is_live(NOW)[0] is False and inv_g.is_live(NOW)[0] is True)
check("...and an explicit window still wins",
inv_f.is_live(NOW, stale_s=60.0)[0] is True
and inv_g.is_live(NOW, stale_s=5.0)[0] is False)
inv_f5 = Inverter("fake-5", driver=FakeDriver(host="h"), max_w=2000.0)
inv_f5.note_write(False, NOW - timedelta(seconds=5))
check("link_note() says the driver's window: 'after 7 seconds' for the fake "
"unit, 'after 30 seconds' for the GoodWe one, and nothing for a healthy unit",
"after 7 seconds" in inv_f5.link_note(NOW)
and "after 30 seconds" in inv_g.link_note(NOW)
and "cannot be controlled" in inv_f.link_note(NOW)
and Inverter("z", driver=FakeDriver(host="h")).link_note(NOW) == "")
check("an unconfigured unit gets the no-setpoint row, as before",
Inverter("x", driver=FakeDriver(host="")).link_note(NOW).startswith("x: ")
and Inverter("x", driver=FakeDriver(host="")).link_note(NOW)
== Inverter("x").link_note(NOW) != "")
check("an entry that names a driver this build lacks is an unconfigured unit, "
"not a crash and not GoodWe",
isinstance(build_driver({"driver": "nope", "setpoint_entity": "number.x"}),
UnavailableDriver)
and not build_driver({"driver": "nope"}).configured()
and build_roster({"inverters": [{"name": "n", "driver": "nope",
"setpoint_entity": "number.x",
"max_w": 1000}]}, None)[0].has_writer()
is False)
# ==============================================================================
print()
print("3. a roster of one fake unit and one GoodWe unit, in a real Controller")
REGISTRY["fake"] = FakeDriver
OPTS = dict(meter_source="off", meter_entity="sensor.grid", max_w=5000,
gain=0.6, slew_w=0, deadband_w=15, target_grid_w=0, step_w=10,
heartbeat_s=10, stale_input_s=15, shadow_mode="off",
inverters=[
dict(name="fake-a", driver="fake", host="10.9.9.9", port=502,
unit_id=3, max_w=2000, bms_soc_floor=10),
dict(name="inverter-b", setpoint_entity="number.sp_b",
soc_entity="sensor.soc_b", batt_entity="sensor.batt_b",
max_w=3000, bms_soc_floor=15)])
B_ENT = {"number.sp_b", "sensor.soc_b", "sensor.batt_b"}
def site(rating_f=1000.0, **over):
hass = LogHass({"sensor.grid": 3000.0, "sensor.soc_b": 50.0,
"sensor.batt_b": 0.0},
{"number.sp_b": (-3000.0, 3000.0, 1.0)})
pub = Pub()
c = Controller(dict(OPTS, **over), hass, MemStore(), pub,
stop=asyncio.Event())
f = c.inverters[0].driver
f.rating = rating_f
c.inverters[0].dev_min, c.inverters[0].dev_max = -rating_f, rating_f
c.inverters[1].dev_min, c.inverters[1].dev_max = -3000.0, 3000.0
c.auto = True
return c, hass, pub, f
async def cycles(c, n=6):
for _ in range(n):
await c.read_inputs()
await c.cycle()
c3, h3, p3, f3 = site()
check("the roster is built through the registry: a fake unit and a GoodWe unit",
isinstance(c3.inverters[0].driver, FakeDriver)
and isinstance(c3.inverters[1].driver, GoodWeEsphomeDriver)
and f3.actuator_id() == "10.9.9.9:502:3")
run(cycles(c3))
fa, fb = c3.inverters
print(f" after 6 cycles: fake-a wrote {calls(f3, 'write')}, GoodWe wrote "
f"{[x for m, e, x in h3.log if m == 'set_number']}, shares "
f"{c3.allocation.shares if c3.allocation else None}")
check("READ: the unit's SoC and power come from its driver, the GoodWe unit's "
"from its entities",
calls(f3, "read") and fa.soc == 60.0 and fb.soc == 50.0
and ("number", "sensor.soc_b", False) in h3.log)
check("WRITE: the fake unit's share went to ITS driver and the GoodWe unit's to "
"ITS entity, each non-zero, the same direction",
calls(f3, "write") and calls(f3, "write")[-1] > 0
and [x for m, e, x in h3.log if m == "set_number" and e == "number.sp_b"][-1] > 0)
check("ALLOCATE: each unit holds a share inside its own rating, and the shares "
"are the site's (3000 W of grid, fake capped at 1000 W by its driver)",
c3.allocation is not None
and set(c3.allocation.shares) == {"fake-a", "inverter-b"}
and 0 < c3.allocation.shares["fake-a"] <= 1000.0
and 0 < c3.allocation.shares["inverter-b"] <= 3000.0
and calls(f3, "write")[-1] == c3.allocation.shares["fake-a"])
check("GRADE: the fake unit's rating is the driver's range (1000 W), the "
"GoodWe unit's is its entry's (3000 W), each from its own source",
(fa.rating_w(), fb.rating_w()) == (1000.0, 3000.0))
check("the fake's power follows its command, so the freshness gate (the fake's "
"own bound) lets the reading through",
fa.batt == calls(f3, "write")[-1] and fa.batt_fresh.bound is FAKE_BOUND)
run(c3.send_heartbeats(10_000.0, 10.0))
n_before = len(calls(f3, "write"))
check("HEARTBEAT: it re-emits the fake unit's standing command through its driver",
n_before >= 2 and calls(f3, "write")[-1] == calls(f3, "write")[-2])
run(c3.command_site_zero())
check("STOP: command_site_zero() reaches the fake unit through its driver, as "
"0 W (the hand-back is SMA-10's, and release() has no caller yet)",
calls(f3, "write")[-1] == 0.0 and not calls(f3, "release"))
c3.publish()
print(f" published unit rows: "
f"{sorted(k for k in p3.last if k.startswith('unit/'))}")
check("PUBLISH: one set of rows per unit, with that unit's own numbers",
p3.last.get("unit/fake_a/soc") == 60.0
and p3.last.get("unit/inverter_b/soc") == 50.0
and "unit/fake_a/battery" in p3.last and "unit/inverter_b/battery" in p3.last)
rows = c3.checks()
check("STATUS: the fake unit's sensor rows are not 'unset' (its driver has a "
"source), and it has the control row",
not [r for r in rows if r.get("id") == "sensor" and not r["ok"]
and "fake" in r["text"]])
# liveness: the fake's 7 s window, the GoodWe unit's 30 s
c4, h4, p4, f4 = site()
run(cycles(c4, 2))
f4.accept = False # the fake's link is down; GoodWe's is fine
_now = datetime.now(timezone.utc)
for u in c4.inverters:
u.note_write(False, _now - timedelta(seconds=10))
check("LIVENESS: after 10 s of rejected writes the fake unit is left out of the "
"split and the GoodWe unit stays in it, per its driver's window",
c4.live_units() == ("inverter-b",))
run(cycles(c4, 4))
check("...and the survivor carries the site: the allocation names only it",
c4.allocation is not None and set(c4.allocation.shares) == {"inverter-b"}
and c4.allocation.shares["inverter-b"] > 1000.0)
# the tripwire: nothing in the world was asked about the fake unit
asked = h3.entities() | h4.entities()
print(f" Home Assistant was asked about: {sorted(asked)}")
check("TRIPWIRE: Home Assistant was only ever asked about the GoodWe unit's "
"entities and the meter - no empty name, no host - on read, write, "
"heartbeat, stop and limits alike",
asked <= B_ENT | {"sensor.grid"} and "" not in asked
and not any("10.9.9.9" in e or "fake" in e for e in asked))
check("...and the GoodWe unit was never touched through the fake",
not [1 for w, a in f3.calls + f4.calls
if isinstance(a, str) and "number.sp_b" in a])
# limits and the per-unit range check, through run_control()
async def drive(c, secs):
try:
await asyncio.wait_for(c.run_control(), timeout=secs)
except asyncio.TimeoutError:
pass
c5, h5, p5, f5 = site(rating_f=2500.0)
f5.rating = 2500.0
c5.inverters[0].dev_min = c5.inverters[0].dev_max = None
c5.inverters[1].dev_min = c5.inverters[1].dev_max = None
run(drive(c5, 3.0))
check("LIMITS: run_control() reads the fake unit's range from its driver and "
"the GoodWe unit's from its entity",
calls(f5, "limits")
and (c5.inverters[0].dev_min, c5.inverters[0].dev_max) == (-2500.0, 2500.0)
and (c5.inverters[1].dev_min, c5.inverters[1].dev_max) == (-3000.0, 3000.0)
and [e for m, e, x in h5.log if m == "limits"] == ["number.sp_b"])
c6, h6, p6, f6 = site()
f6.rating = 1500.0 # the entry says 2000 W
c6.inverters[0].dev_min = c6.inverters[0].dev_max = None
run(drive(c6, 10.0))
check("RULE 2 PER UNIT: a fake unit rated above what its driver says it accepts "
"is refused by name, as a GoodWe one is",
c6.refused and any("fake-a" in p and "10.9.9.9:502:3" in p
for p in c6.refused)
and not calls(f6, "write"))
# the settings panel has no Controller: it binds each unit's driver itself
from app import selfconfig # noqa: E402
hs = LogHass({}, {"number.sp_b": (-3000.0, 3000.0, 1.0)})
_ps, _unread = run(selfconfig.problems_and_ranges(
dict(OPTS, inverters=[dict(OPTS["inverters"][0], _rating=1500.0),
OPTS["inverters"][1]]), hs))
check("PANEL: the settings panel reads the fake unit's range from its driver "
"and the GoodWe unit's from its entity, and grades the fake unit by name",
any("fake-a" in p and "10.9.9.9:502:3 accepts at most 1500" in p
for p in _ps)
and [e for m, e, x in hs.log if m == "limits"] == ["number.sp_b"]
and _unread == [])
# the seam is the only way in: a fake-only roster touches Home Assistant for
# nothing but the meter
hz = LogHass({"sensor.grid": 800.0})
cz = Controller(dict(OPTS, inverters=[OPTS["inverters"][0]]), hz, MemStore(),
Pub(), stop=asyncio.Event())
cz.inverters[0].dev_min, cz.inverters[0].dev_max = -1000.0, 1000.0
cz.auto = True
run(cycles(cz, 3))
check("A FAKE-ONLY ROSTER never asks Home Assistant for anything but the "
"meter, and still reads and writes (nothing on the control path is "
"keyed on a GoodWe entity)",
hz.entities() <= {"sensor.grid"} and calls(cz.inverters[0].driver, "read")
and calls(cz.inverters[0].driver, "write"))
# ==============================================================================
print()
print("4. SAFETY-28's census counts actuator ids; rule 9 on the new keys")
def entry(**kw):
return dict(name="u", max_w=3000, bms_soc_floor=10, **kw)
check("GoodWe entries are counted as before: one entity named twice is one "
"actuator with two writers, whatever its case",
{k: len(v) for k, v in actuator_writers({"inverters": [
entry(setpoint_entity="number.X"),
entry(setpoint_entity=" number.x ")]}).items()} == {"number.x": 2}
and actuator_writers({"setpoint_entity": "number.a", "inverters": [
entry(setpoint_entity="number.a")]})["number.a"]
== ["setpoint_entity", "inverters[0].setpoint_entity"])
cen = actuator_writers({"inverters": [
entry(driver="fake", host="gw", port=502, unit_id=1),
entry(driver="fake", host="gw", port=502, unit_id=2),
entry(driver="fake", host="gw", port=503, unit_id=1),
entry(driver="fake", host="GW", port=502, unit_id=1)]})
print(f" census {cen}")
check("another driver's actuator is host:port:unit: two units behind one "
"gateway are two actuators, and one unit named twice is one",
set(cen) == {"gw:502:1", "gw:502:2", "gw:503:1"}
and cen["gw:502:1"] == ["inverters[0].host", "inverters[3].host"])
check("a GoodWe key on a fake entry STILL declares a writer (the pre-SMA-2 "
"census kept, the driver's actuator added to it), and a `host` on a "
"GoodWe entry declares none",
actuator_writers({"inverters": [entry(driver="fake", host="gw",
setpoint_entity="number.x")]})
== {"number.x": ["inverters[0].setpoint_entity"],
"gw:502:1": ["inverters[0].host"]}
and actuator_writers({"inverters": [entry(setpoint_entity="number.x",
host="gw")]})
== {"number.x": ["inverters[0].setpoint_entity"]})
check("an entry naming a driver this build lacks still counts its setpoint "
"entity - refusing too much is the safe direction",
actuator_writers({"inverters": [entry(driver="nope",
setpoint_entity="number.q")]})
== {"number.q": ["inverters[0].setpoint_entity"]})
check("census_key() folds case and space",
census_key(" Number.X ") == "number.x")
GOOD = dict(entry(setpoint_entity="number.sp_a", soc_entity="sensor.soc_a",
batt_entity="sensor.batt_a"))
BASEOPTS = {"meter_source": "off", "meter_entity": "sensor.grid"}
base_problems = validate_startup_config(dict(BASEOPTS, inverters=[dict(GOOD)]))
print(f" baseline problems for a plain GoodWe roster: {base_problems}")
def prob(**kw):
return validate_startup_config(dict(BASEOPTS, inverters=[dict(GOOD, **kw)]))
check("an existing entry (no new key) is graded exactly as before",
prob() == base_problems)
check("...and so is one that says driver goodwe_esphome, or carries every new "
"key in a valid shape",
prob(driver="goodwe_esphome") == base_problems
and prob(driver="", host="", maintenance=False) == base_problems
and prob(host="inv.local", port=502, unit_id=3, maintenance=True)
== base_problems)
def named(problems, key):
return [p for p in problems if f"inverters.{key}" in p or f"({key})" in p]
check("only goodwe_esphome can be selected for now",
named(prob(driver="sma_modbus"), "driver")
and named(prob(driver="fake"), "driver")
and SELECTABLE == (DEFAULT_DRIVER,))
check("a host with a space, a bad port or unit number and a non-boolean "
"maintenance are each refused by key; the right shapes are not",
named(prob(host="a b"), "host")
and named(prob(port=0), "port") and named(prob(port=70000), "port")
and named(prob(port="x"), "port") and named(prob(port=True), "port")
and named(prob(unit_id=248), "unit_id")
and named(prob(unit_id=1.5), "unit_id")
and named(prob(maintenance="yes"), "maintenance")
and not named(prob(port=65535, unit_id=0, host="10.0.0.1"), "port"))
check("a GoodWe entry with no setpoint entity is refused with the same sentence "
"as before",
any("has no" in p and "setpoint entity" in p.lower()
for p in validate_startup_config(dict(BASEOPTS, inverters=[
dict(GOOD, setpoint_entity="")]))))
fu = FakeDriver(host="gw")
check("rule 2 grades any unit by its driver's actuator id, so a unit with no "
"setpoint entity is no longer skipped",
validate_unit_ranges([Inverter("a", driver=fu, max_w=2000.0)])
== [] and validate_unit_ranges([_u := Inverter("a", driver=fu,
max_w=2000.0)]) == []
and (setattr(_u, "dev_max", 1000.0) or True)
and len(validate_unit_ranges([_u])) == 1
and "gw:502:1" in validate_unit_ranges([_u])[0])
# ==============================================================================
print()
print("5. the schema")
cfg = io.open(HERE / "config.yaml", encoding="utf-8").read()
sch = cfg[cfg.index("\nschema:"):]
ent = sch[sch.index("\n inverters:"):]
ent = ent[:ent.index("\n\n")]
decl = dict(ln.strip().lstrip("- ").split(": ", 1)
for ln in ent.splitlines()[1:] if ": " in ln)
NEW_KEYS = ("driver", "host", "port", "unit_id", "maintenance")
check("HIDDEN FROM CLIENTS (owner, 2026-11-07): config.yaml's per-entry schema "
"is what it was on 23ff9d0 - the five driver keys are not in it, and "
"setpoint_entity is still required - so the Supervisor form shows "
"nothing new",
not set(NEW_KEYS) & set(decl) and not decl["setpoint_entity"].endswith("?")
and set(decl) == {"name", "setpoint_entity", "max_w", "bms_soc_floor",
"soc_entity", "batt_entity", "batt_invert",
"capacity_kwh"})
_tr = {lg: io.open(HERE / "translations" / f"{lg}.yaml", encoding="utf-8").read()
for lg in ("en", "nl")}
from app import messages as _msgs # noqa: E402
check("...and no translation, label or description was added for them",
not any(f" {k}:\n" in t.split(" estop_fitted:")[0].split(" inverters:")[1]
for t in _tr.values() for k in NEW_KEYS)
and not set(NEW_KEYS) & (set(_msgs.LABELS) | set(_msgs.LABELS_NL)))
# ==============================================================================
print()
print("6. round 2: census parity, setters, rule 9(d), NaN ports, hidden keys")
import copy, itertools, math # noqa: E402
from app import uimodel # noqa: E402
from app.validate import ACTUATOR_WRITE_KEYS # noqa: E402
def old_census(opts):
"""23ff9d0's census, copied: every ACTUATOR_WRITE_KEYS key, wherever it is."""
found = []
def walk(node, path):
if isinstance(node, dict):
for k, v in node.items():
here = f"{path}.{k}" if path else str(k)
if k in ACTUATOR_WRITE_KEYS:
e = str(v or "").strip()
if e:
found.append((here, e))
continue
walk(v, here)
elif isinstance(node, (list, tuple)):
for i, v in enumerate(node):
walk(v, f"{path}[{i}]")
walk(opts, "")
cen = {}
for where, e in found:
cen.setdefault(e.lower(), []).append(where)
return cen
check("ACTUATOR_WRITE_KEYS is exactly ('setpoint_entity',): the parity below "
"is about that key", tuple(ACTUATOR_WRITE_KEYS) == ("setpoint_entity",))
SP = ["number.a", "Number.A", " number.b ", "", None, 5, ["x"]]
shapes = []
for flat, e0, e1 in itertools.product(SP, SP, SP):
shapes.append({"setpoint_entity": flat, "inverters": [
{"name": "a", "setpoint_entity": e0}, {"name": "b", "setpoint_entity": e1}]})
shapes += [{"x": {"y": [{"setpoint_entity": "number.z"}]}, "setpoint_entity": "n.q"},
{"inverters": "junk"}, {"inverters": [{"driver": "nope",
"setpoint_entity": "n.k"}]},
{"inverters": [{"driver": "goodwe_esphome", "setpoint_entity": "n.k"}]},
{}, {"inverters": []}]
bad = [i for i, o in enumerate(shapes) if actuator_writers(o) != old_census(o)]
check(f"CENSUS PARITY: on {len(shapes)} flat/roster/odd option shapes the "
"census equals 23ff9d0's, keys, order and all", not bad)
mixed = {"setpoint_entity": "number.a", "inverters": [
{"name": "a", "setpoint_entity": "number.a"},
{"name": "f", "driver": "fake", "host": "gw", "port": 502, "unit_id": 1,
"setpoint_entity": "number.ignored"},
{"name": "g", "setpoint_entity": "number.g"}]}
new_c, old_c = actuator_writers(mixed), old_census(mixed)
check("...and on a mixed config (a fake-driver entry too) the census is a "
"SUPERSET of the pre-SMA-2 one: every old writer is still counted, "
"plus the driver's own actuator",
all(new_c.get(k) and set(v) <= set(new_c[k]) for k, v in old_c.items())
and "gw:502:1" in new_c)
gi = Inverter("s", setpoint_entity="number.s", soc_entity="sensor.a",
batt_entity="sensor.b")
gi.setpoint_entity, gi.soc_entity, gi.batt_entity, gi.batt_invert = (
"number.t", "sensor.c", "sensor.d", True)
check("SETTERS: assigning setpoint_entity/soc_entity/batt_entity/batt_invert "
"on an Inverter writes through to its GoodWe driver, as it did before",
(gi.driver.setpoint_entity, gi.driver.soc_entity, gi.driver.batt_entity,
gi.driver.batt_invert) == ("number.t", "sensor.c", "sensor.d", True)
and gi.has_writer() and gi.driver.actuator_id() == "number.t")
def _assign():
inv_f.setpoint_entity = "x"
try:
_assign()
_refused = False
except AttributeError:
_refused = True
check("...and on a driver that has no such field it refuses, not loses the value",
_refused)
nogood = validate_startup_config(dict(BASEOPTS, inverters=[
{k: v for k, v in GOOD.items() if k != "setpoint_entity"}]))
check("RULE 9(d): a GoodWe entry with no setpoint_entity is refused, by name "
"and by position, with the sentence it always had",
any(p.startswith("inverters[0] (u) has no") and "setpoint entity" in p.lower()
and "Set its ESPHome number entity, or remove the entry." in p
for p in nogood)
and nogood != base_problems)
check("...also with `driver: goodwe_esphome` said out loud",
any("has no" in p for p in validate_startup_config(dict(
BASEOPTS, inverters=[{k: v for k, v in dict(GOOD, driver="goodwe_esphome").items()
if k != "setpoint_entity"}]))))
nan, inf = float("nan"), float("inf")
for key in ("port", "unit_id"):
for bad_v, nm in ((nan, "NaN"), (inf, "inf"), (-inf, "-inf")):
try:
got = prob(**{key: bad_v})
ok_ = bool(named(got, key))
except Exception as e: # noqa: BLE001
got, ok_ = repr(e), False
check(f"{key} = {nm} is refused by key and does not raise", ok_)
ent = dict(name="a", setpoint_entity="number.a", max_w=3000, bms_soc_floor=10,
soc_entity="sensor.s", batt_entity="sensor.b", driver="goodwe_esphome",
host="h", port=502, unit_id=3, maintenance=False)
opts_rt = {"inverters": [ent, dict(ent, name="b", setpoint_entity="number.b")]}
back = uimodel.ui_to_options(uimodel.options_to_ui(copy.deepcopy(opts_rt)))
check("an entry that carries the driver keys (from a caller that skips the "
"schema) comes back from a save through the page model unchanged",
back.get("inverters") == opts_rt["inverters"])
del REGISTRY["fake"]
# THE SEAM MUTANTS THIS FILE WAS RUN AGAINST (twelve, each one edit to a copy of
# the tree; all twelve turn it red):
# write_unit calls hass.set_number itself -> part 3 WRITE (and the tripwire)
# _read_unit calls hass.number(soc/batt entity) -> part 3 READ
# run_control's limits keyed on setpoint_entity -> part 3 LIMITS
# the panel's range check keyed on setpoint_entity -> part 3 PANEL
# has_writer() back to bool(setpoint_entity) -> part 2 has_writer
# is_live() window back to LINK_STALE_S -> part 2 is_live
# link_note() window back to LINK_STALE_S -> part 2 link_note
# Freshness built on BOUNDS["batt"] -> part 2 freshness bound
# _write_unit's guard keyed on setpoint_entity -> part 3 WRITE
# the census back to the GoodWe key only -> part 4 census
# rule 2 per unit back to .setpoint_entity -> part 3 RULE 2 PER UNIT
# the status rows' source test back to the entities -> part 3 STATUS
# NOT COVERED: the call in amain() that reads the flat setpoint entity's range
# before any Controller exists. It runs only inside amain(), which no check
# starts; it is two lines and the GoodWe driver's own limits(), graded in part 1.
print()
if fails:
print(f"{len(fails)} FAILED")
sys.exit(1)
print("all passed")
+63 -12
View File
@@ -22,7 +22,7 @@ sys.path.insert(0, os.path.join(HERE, "tools"))
logging.disable(logging.WARNING)
import ux54_scenarios as S # noqa: E402
from app import dayplan, homeview, modetrade, packmode # noqa: E402
from app import dayplan, homeview, modetrade, packmode, packshare # noqa: E402
from app.main import Controller # noqa: E402
from app.peakguard import PeakDecision # noqa: E402
from app.static_tariff import static_plan # noqa: E402
@@ -38,6 +38,7 @@ UTC = timezone.utc
EFF = 0.95
AIM = 3450.0
SLOT = timedelta(hours=1) # the price slot of the day/night tariff
QUARTER = timedelta(minutes=15) # the run's own slot
SAMPLES = ("23:30", "00:30", "01:30", "02:30", "04:30")
OLD = ("leftover_solar", "cheap_hours") # the owner's old shape
NOW = ("leftover_solar", "leftover_solar") # the current one
@@ -83,8 +84,27 @@ def hm(s, day):
return day.replace(hour=h, minute=m)
def split_by_room(w, ch, rating, wt, invs):
"""Control's split of `w` over the chargers `ch`: by `packshare.weights()`,
no battery over its rating, the surplus to the others."""
p, open_, left = [0.0, 0.0], set(ch), w
while open_:
tot = sum(wt[invs[i].name] for i in open_)
over = [i for i in open_
if left * wt[invs[i].name] / tot > rating[i] + 1e-9]
if not over:
for i in open_:
p[i] = left * wt[invs[i].name] / tot
break
for i in over:
p[i] = rating[i]
left -= rating[i]
open_.discard(i)
return p
def walk(modes, soc0, house_w, night=None, dynamic=False, samples=SAMPLES,
start_h=22, end_h=7, plain=None):
start_h=22, end_h=7, plain=None, by_room=True, fc=(10.2, 10.0)):
"""Walk 22:00-07:15. Returns (charging, homes, commands):
charging[minute] = set of batteries control charges (power > 0),
homes[sample] = Home's `/status` plan at that minute, commands = the
@@ -116,7 +136,7 @@ def walk(modes, soc0, house_w, night=None, dynamic=False, samples=SAMPLES,
charging, homes, cmds = {}, {}, []
while now < end:
lt = loc(now)
today, tomorrow = (10.2, 10.0) if lt.hour < 12 else (10.0, 10.2)
today, tomorrow = fc if lt.hour < 12 else fc[::-1]
c.solar_fc = S.forecast(now, today, tomorrow, members=3)
c.solar_fc_why = None
if plan_at is None or (now - plan_at).total_seconds() >= 1800:
@@ -137,9 +157,13 @@ def walk(modes, soc0, house_w, night=None, dynamic=False, samples=SAMPLES,
if tick.roles.get(inv.name) == modetrade.CHARGE]
p = [0.0, 0.0]
if size < 0 and ch:
tot = sum(rating[i] for i in ch)
for i in ch:
p[i] = -size * rating[i] / tot
if by_room: # as control: room left to full, rating caps
wt = packshare.weights(c.pack_energy, -1.0)
p = split_by_room(-size, ch, rating, wt, c.inverters)
else:
tot = sum(rating[i] for i in ch)
for i in ch:
p[i] = -size * rating[i] / tot
for i in range(2):
soc[i] = min(100.0, soc[i] + p[i] / 1000.0 / 60.0 * EFF
/ caps[i] * 100.0)
@@ -175,7 +199,7 @@ def today_of(st, i):
return [(t["from"], t["to"]) for t in st["batteries"][i]["today"]]
def violations(charging, homes):
def violations(charging, homes, slot=SLOT):
"""What is wrong with Home's drawing at each sample."""
bad = []
for t, st in sorted(homes.items()):
@@ -191,8 +215,10 @@ def violations(charging, homes):
break
if mine:
stop = mine[-1] + timedelta(minutes=1)
if slot == QUARTER: # the last charging quarter's end
stop += timedelta(minutes=-stop.minute % 15)
for a, z in bl:
if z > stop + SLOT:
if z > stop + slot:
bad.append(f"{t:%H:%M} battery {i}: block to "
f"{z:%H:%M}, stops {stop:%H:%M}")
# the Today line says the same as the block
@@ -215,8 +241,8 @@ def violations(charging, homes):
# --------------------------------------------------------------------------- #
# Run
# --------------------------------------------------------------------------- #
def show(tag, ch, homes, want_bad):
bad = violations(ch, homes)
def show(tag, ch, homes, want_bad, slot=SLOT):
bad = violations(ch, homes, slot)
if want_bad:
check(f"{tag}: red", bool(bad), "no violation found")
else:
@@ -240,6 +266,11 @@ def main():
("current shape, no bind", NOW, (20.0, 20.0), 584.0, None),
("old shape, peak-bound", OLD, (40.0, 90.0), 2850.0, 2850.0),
("current shape, peak-bound", NOW, (40.0, 90.0), 2850.0, 2850.0))
# the rig's checks 2 and 3 (UX-77 round 2): room left and rating disagree
UNEQUAL = (("unequal levels, A+B Leftover solar, no bind", NOW,
(30.0, 20.0), 584.0, None, (5.0, 5.0)),
("unequal levels, A Leftover solar + B Cheap hours", OLD,
(40.0, 88.0), 2850.0, 2850.0, (10.2, 10.0)))
walked = {}
for tag, modes, soc, hw, night in CASES:
ch, homes, _cmds = walk(modes, soc, hw, night=night)
@@ -251,7 +282,7 @@ def main():
charged(ch, 0, day) or charged(ch, 1, day)))
print("2. a battery with nothing to charge gets no block")
ch, homes = walked["old shape, peak-bound"]
ch, homes, _c = walk(OLD, (40.0, 94.0), 2850.0, night=2850.0)
st = homes[datetime(2026, 11, 2, 2, 30, tzinfo=BILLING_TZ)]
check("B is at its level at 02:30: no block", blocks_of(st, 1) == [],
str(blocks_of(st, 1)))
@@ -281,7 +312,27 @@ def main():
any(r["kind"] == "grid" for st in homes.values()
for r in st["plan"]["runs"]))
print("5. the pieces")
print("5. unequal levels: the roll shares the room as control does")
for tag, modes, soc, hw, night, fc in UNEQUAL:
ch, homes, _c = walk(modes, soc, hw, night=night, fc=fc)
show(tag, ch, homes, False, QUARTER)
day = datetime(2026, 11, 2, 0, 30, tzinfo=BILLING_TZ)
check(f"{tag}: control charges after 00:30", bool(
charged(ch, 0, day) or charged(ch, 1, day)))
if hasattr(cheaproll, "_Charge") \
and hasattr(cheaproll._Charge, "_shares"):
real = cheaproll._Charge._shares
cheaproll._Charge._shares = lambda self, ch, w: {
p.name: w * abs(p.rating_w) / sum(abs(q.rating_w) for q in ch)
for p in ch}
try:
for tag, modes, soc, hw, night, fc in UNEQUAL:
ch, homes, _c = walk(modes, soc, hw, night=night, fc=fc)
show(f"mutant by rating, {tag}", ch, homes, True, QUARTER)
finally:
cheaproll._Charge._shares = real
print("6. the pieces")
if hasattr(cheaproll, "Roll"):
t = datetime(2026, 11, 2, 1, 46, tzinfo=UTC)
check("a stop is rounded up to the slot", cheaproll._ceil_slot(t)
+75 -10
View File
@@ -5,12 +5,19 @@
For each FILE (default: every goodwe_controller/app/*.py that differs from
BASE_REF, default release/1.0) the ast.dump() of the tree with docstrings
removed must be identical at BASE_REF and in the working tree. Also prints
code lines vs comment-only + docstring lines (whole lines, via tokenize) before
and after. Run from the repository root. Exit 1 on any code difference.
removed must be identical at BASE_REF and in the working tree, and so must
the `python -OO` compiled code (a wholly removed docstring leaves a no-op
there). An added or removed app/*.py file is a code difference. The diff
against BASE_REF may touch only goodwe_controller/app/*.py,
goodwe_controller/DECISIONS/*.md and this script. Also prints code lines vs
comment-only + docstring lines (whole lines, via tokenize) before and after,
and the docstrings removed entirely or added. Run from the repository root.
Exit 1 on any difference.
"""
import ast
import io
import os
import re
import subprocess
import sys
import tokenize
@@ -53,29 +60,87 @@ def counts(src):
return len(code), len(doc) + len(com - code - doc)
def qualnames(src):
out = {}
def walk(node, prefix):
for n in ast.iter_child_nodes(node):
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef,
ast.ClassDef)):
q = prefix + n.name
out[q] = docstring(n) is not None
walk(n, q + ".")
out["<module>"] = docstring(ast.parse(src)) is not None
walk(ast.parse(src), "")
return out
def code_sig(co):
consts = tuple(code_sig(c) if hasattr(c, "co_code") else c
for c in co.co_consts)
return (co.co_name, co.co_code, consts, co.co_names, co.co_varnames,
co.co_freevars, co.co_cellvars, co.co_flags, co.co_argcount,
co.co_stacksize, co.co_exceptiontable)
def oo_same(old, new):
return (code_sig(compile(old, "f", "exec", optimize=2))
== code_sig(compile(new, "f", "exec", optimize=2)))
def git(*a):
return subprocess.run(["git", *a], check=True, capture_output=True,
text=True).stdout
def exists(base, f):
return subprocess.run(["git", "cat-file", "-e", f"{base}:{f}"],
capture_output=True).returncode == 0
ALLOWED = re.compile(r"^goodwe_controller/(app/[^/]+\.py|DECISIONS/[^/]+\.md|"
r"tools/maint20_same_code\.py)$")
def ratio(m, c):
return f"{m / c:.2f}" if c else "n/a"
def main(argv):
base = argv[0] if argv else "release/1.0"
files = argv[1:] or [
f for f in git("diff", "--name-only", base, "--",
"goodwe_controller/app").split()
if f.endswith(".py")]
bad = 0
print(f"base {base} = {git('rev-parse', base).strip()}")
changed = git("diff", "--name-only", base).split()
for f in changed:
if not ALLOWED.match(f):
print(f"FAIL: diff touches {f}, outside app/*.py, DECISIONS/*.md "
"and this script")
bad += 1
files = argv[1:] or [f for f in changed if re.match(
r"^goodwe_controller/app/[^/]+\.py$", f)]
for f in files:
in_base, in_head = exists(base, f), os.path.exists(f)
if in_base != in_head:
print(f"CODE DIFFERS {f} "
f"{'removed' if in_base else 'added'} file")
bad += 1
continue
old = git("show", f"{base}:{f}")
new = open(f, encoding="utf-8").read()
same = dump(old) == dump(new)
oo = oo_same(old, new)
(c0, m0), (c1, m1) = counts(old), counts(new)
print(f"{'SAME CODE' if same else 'CODE DIFFERS'} {f} "
f"code {c0}->{c1} comment+doc {m0}->{m1} "
f"ratio {m0 / c0:.2f}->{m1 / c1:.2f}")
bad += not same
print("OK: no code change" if not bad else f"FAIL: {bad} file(s) differ")
f"ratio {ratio(m0, c0)}->{ratio(m1, c1)} "
f"-OO {'same' if oo else 'DIFFERS'}")
bad += (not same) + (not oo)
qo, qn = qualnames(old), qualnames(new)
for q in sorted(q for q in qo if qo[q] and not qn.get(q, True)):
print(f" docstring REMOVED: {f}:{q}")
for q in sorted(q for q in qn if qn[q] and not qo.get(q, True)):
print(f" docstring ADDED: {f}:{q}")
print("OK: no code change" if not bad else f"FAIL: {bad} problem(s)")
return 1 if bad else 0
@@ -257,6 +257,23 @@ for title, entry, expect in (
ok, out = validate(dict(D_BASE, inverters="[]"))
show("a JSON STRING where the list belongs is refused", not ok, out)
print("\n== K. SMA-2: the driver keys are NOT in the schema (owner, 2026-11-07) ==")
# `driver`, `host`, `port`, `unit_id` and `maintenance` are graded by validate.py
# rule 9(h) but kept out of config.yaml so the Configuration tab shows nothing
# new. This pins both halves: the shipped entry is the one it always was, and the
# Supervisor (measured) silently DROPS an unknown key from an entry, so they
# cannot arrive by the form or by YAML.
ok, out = validate(dict(D_BASE, inverters=[D_FULL]))
show("the pre-SMA-2 entry is ACCEPTED unchanged", ok and out["inverters"] == [D_FULL], out)
for _k in ("driver", "host", "port", "unit_id", "maintenance"):
ok, out = validate(dict(D_BASE, inverters=[dict(D_FULL, **{_k: "x"})]))
show(f"an entry carrying `{_k}` is accepted and the key is dropped",
ok and out["inverters"] == [D_FULL], out)
show("the per-entry schema has exactly the eight keys it had",
sorted(schema["inverters"][0]) == sorted(["name", "setpoint_entity", "max_w",
"bms_soc_floor", "soc_entity", "batt_entity", "batt_invert", "capacity_kwh"]),
json.dumps(schema["inverters"]))
print("\n== E. the ROLLBACK direction, and the operator's UI ==")
# The old (flat) schema, i.e. what an operator would be running after a