Compare commits

..
27 Commits
Author SHA1 Message Date
ems-agent 64991d7cde EV-52 review round 2: test row for Solar's late try cleared on leave
infra-pin / fresh (pull_request) Waiting to run
checks / unit (pull_request) In progress
Test only. Kills a mutant that drops the _late clear in SolarWriter._leave(), which no row covered.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-29 14:08:48 +01:00
ems-agent 2931e6e852 EV-52 round 2: a refused Manual try is not logged later by another source's value
checks / unit (pull_request) Successful in 44m13s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 11:55:51 +01:00
ems-agent fd1cb423b1 EV-52 round 1: Manual late-accept line (Q2), N5, N8, T44 rows
checks / unit (pull_request) Successful in 44m57s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 09:49:52 +01:00
ems-agent ca06456ffa EV-52: charger-less stubs, CHANGELOG, EV-28/EV-51 log rows set the two new lines aside
checks / unit (pull_request) Successful in 47m21s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 07:47:17 +01:00
ems-agent c1536b0e93 EV-52: log one plain line for a new car current and for a car mode change
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-29 06:48:52 +01:00
ems-agent 02166e28eb Merge pull request 'EV-21: Solar cuts the car first for the quarter peak' (#278) from EV-21 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-29 03:24:38 +01:00
ems-agentandClaude 1c7761d2c2 EV-21 fix round 3 (re-review, tests only): refused-close retry under a cut under 6 A; R1 standing cut
checks / unit (pull_request) Successful in 46m15s
infra-pin / fresh (pull_request) Successful in 2s
test_ev21_fix2.py: N6/P27 (a) writer-level cuts of 3 A and 0 A, no write after the cut and the charger at 0 A; N6/P27 (b) controller level (close refused at 313, house 18 kW at 315: cut 0 A at once, no retry); R1 standing cut unit row on _car_cut_tick. Red with seq_nopause_retry and r1_nostand. No app/ change.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-29 02:29:25 +01:00
ems-agentandClaude 83e5b9c51f EV-21 fix round 2 (review): a cut during Solar's own phase change ends it; wait cap in watts
checks / unit (pull_request) Successful in 46m35s
infra-pin / fresh (pull_request) Successful in 2s
PM R1: a cut due while Solar's own phase change is under way (seq set or plan.switch) is 0 A at once and ends the change at its 0 A; the 15 s wait cap is held in watts and converted with the phases at the write. test_ev21_fix2.py: T34 (iv) red at 5759e9d, T34 (v) 3->1, N6/P27 refused close red with seq_uncapped, N9 standing cap red with stale_drop. test_ev21_fix1.py: C18 now R1; C16 and Q1 accepted as coded (R5).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-28 18:27:18 +01:00
ems-agentandClaude 5759e9dc9f EV-21 fix round 1 (formal round 4): C14 cut due while batteries charge; C15 grace once per value
checks / unit (pull_request) Successful in 46m9s
infra-pin / fresh (pull_request) Successful in 1s
C14 (PM Q2): slowing a battery charge counts as the batteries taking more, so the cut is due whatever the batteries do; their charge counts only as headroom for the 15 s wait. C15 (PM Q1): sent_at is renewed only for a new value, so a retry of a refused cut gets no new 2 s grace. test_ev21_fix1.py: both red on 36e9dd7; C16, C18 and Q1's other writer pinned as the code has them. Test shapes: slow batteries and refusals start after Solar's own start, which C14 would otherwise cut on its start blip; T38 cover off from 300 s; T46 bounds the excess; T39 counts writes after the cut.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-27 01:33:41 +01:00
ems-agentandClaude 36e9dd765e EV-21: test fixes (T41/T46 on base, test_ev20_writers T46 with the cut first)
checks / unit (pull_request) Successful in 47m29s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-25 17:26:38 +01:00
ems-agentandClaude 7bc8988be0 EV-21: Solar cuts the car first for the quarter peak
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Failing after 1h10m59s
In Solar, when the 15-minute period heads over the aim and the batteries
would have to give more, the car is lowered first: floor((car - excess) /
(230 x phases)) A, 0 under 6 A. At once without real headroom (saturated,
floor-limited, excess beyond what the batteries can add, no battery figure,
cover off, last 120 s), else after at most 15 s. One cut per episode from
its start, deeper only on a growing excess; restart with the start power
under the aim for the start time; none after a 2nd cut in the period.

Grading (formal C2): a Solar car Solar cannot cut is graded, banked and
left in the guard as in Off. A Solar car is never banked. Grey note and Why
"Solar lowered the car for the peak." Manual and Off unchanged.

Tests: test_ev21.py, test_ev21_paths.py, test_ev21_same.py; T49 in
tools/ev20_day.py; T50 in test_ev20_fuzz.py; test_ev20_guard section 8
moved from "as Manual" to "as Off" where Solar cannot cut (T51).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-25 17:01:07 +01:00
admin a8e4ceb859 Merge back 0.25.0 into release/1.0 (#277)
infra-pin / fresh (push) Successful in 1s
2026-11-25 16:47:13 +01:00
glenn schrooyenandClaude b640ac198f Merge master (release 0.25.0) back into release/1.0
checks / unit (pull_request) Successful in 49m9s
infra-pin / fresh (pull_request) Successful in 2s
Brings the 0.25.0 version bump and CHANGELOG section to release/1.0. No conflicts; the empty 'Not in a release yet' heading stays above 0.25.0. Known issues unchanged: the SAFETY-97 and SAFETY-136 Trello cards could not be read.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-25 15:55:29 +01:00
ems-agent fcc73d071d Merge pull request 'Release 0.25.0' (#276) from cut-0.25.0 into master 2026-11-25 15:38:14 +01:00
ems-agentandClaude 0862d87c8a Release 0.25.0: CHANGELOG wording (release review)
checks / unit (pull_request) Successful in 44m20s
infra-pin / fresh (pull_request) Successful in 2s
Move the tests-only note for EV-14, EV-18 and EV-19 out of Known issues into the car charger fixes paragraph: it cites only closed tickets and has no open card. Name the Pause after option (ev_pause_min) behind the 5 minutes in the Solar paragraph. CHANGELOG.md only.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-25 14:52:33 +01:00
ems-agentandClaude Opus 5.5 37b85fffb5 Release 0.25.0: keep the empty "Not in a release yet" heading; cite SAFETY-143
checks / unit (pull_request) Successful in 45m14s
infra-pin / fresh (pull_request) Successful in 1s
test_ev20_guard T51 needs the heading (PM ruling, option a). CHANGELOG.md only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-25 14:01:42 +01:00
ems-agentandClaude Opus 5.5 550d2d3934 Release 0.25.0: version bump and CHANGELOG
checks / unit (pull_request) Failing after 53m4s
infra-pin / fresh (pull_request) Successful in 2s
Pinned to EV-51's merge c79eb37 on release/1.0 (TOOL-51, go #62).
Only goodwe_controller/config.yaml (version) and CHANGELOG.md change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-25 12:57:38 +01:00
ems-agent c79eb37392 Merge pull request 'EV-51: Solar decides every meter-age rule on the writer step's own age; DEBUG line per step' (#275) from EV-51 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-25 01:19:19 +01:00
ems-agentandClaude 45df1ac549 EV-51 review: T45 sweeps N8 on own age for retries and phase-change closing currents; docs name the decision words and C23
checks / unit (pull_request) Successful in 54m7s
infra-pin / fresh (pull_request) Successful in 2s
T45: race order, 5 s and 10 s cycles, silence onset swept 1 s at a time,
(a) a raise the charger ignores (re-sends) and (b) a 1 -> 3 phase change
(closing current): no non-zero current write at own age > 30 s. Red on
5bff894 and on the reviewer's R4 (nz_block from the snapshot, C23 on own
age), green on head. T26 also checks the DECISIONS entry names every
decision word and the C23 value rule.

DECISIONS and the car_sun_own / _car_step_debug docstrings: snapshot values
are used only while the step's own age says fresh (C23); the decision words
are listed. No code change.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-25 00:04:10 +01:00
ems-agentandClaude 6412d00783 EV-51 round 2: T44 checks the start after the meter returns; T24 SoC 100 no longer carries N5
checks / unit (pull_request) Successful in 37m42s
infra-pin / fresh (pull_request) Successful in 2s
T44 (C23) now also asserts that a start and a non-zero write come, either
before the silence passes 30 s (from fresh data) or after the meter is back
at a step with own age <= 30, between the first fresh step + ev_start_min
and that + 2 cycles, and that the car is still charging at the end. A fix
that blocks every start after a silence fails it.

T24: the SoC 100 run (no battery write in the silence) is checked for T24
only; N5 rides on the SoC 50 runs, which must have writes in the silence.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-24 22:05:33 +01:00
ems-agentandClaude a33eb8ef1c EV-51 round 1: C23 (no spare/target from data the own age calls old), N5 label, T44
checks / unit (pull_request) Successful in 38m23s
infra-pin / fresh (pull_request) Successful in 2s
car_sun_own now sets spare_w / target_w to None while the step's own meter age
says silent, so no plan start or raise comes from a snapshot value over
meter_max_age_s old; the start comes from a fresh reading after the meter
returns, with its dwell. T44 sweeps a start due just after the silence (red on
68856bc, green now). T24 is labelled N5 and also runs at SoC 50 so the
batteries' setpoints in the silence are compared.

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 19:52:36 +01:00
ems-agentandClaude 68856bc3a0 EV-51: Solar decides every meter-age rule on the writer step's own age; DEBUG line per step
checks / unit (pull_request) Successful in 41m26s
infra-pin / fresh (pull_request) Successful in 2s
The writer step took the meter age from the snapshot of the previous cycle
(silent / unknown_s / hold), so in production order the silent-meter pause
came one cycle late (C21) and a start or raise could still be written at an own
age of 31-39 s (C22, N8). The step now judges its own age: the pause timing and
held_pause, the non-zero write block (nz_block), and the late-readings hold with
its stale rule. Meter values stay from the snapshot; car.held / car.reading and
the arrival sources' spare-unknown check are unchanged.

Also: one DEBUG line per Solar writer step (time, meter age, decision, write);
tools/ev20_sun.drive takes cyc / phase / jitter / cset (default unchanged);
test_ev51.py (T1-T43, N1-N12); DECISIONS states the rule once.

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-24 17:26:03 +01:00
ems-agent 5bff894cca Merge pull request 'EV-20 rig round 2: no pause on a short charger read gap; ha_signed pause timed from the meter age' (#274) from EV-20-r2 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-24 10:10:11 +01:00
admin d615508128 Release 0.24.0: release/1.0 -> master (#261) 2026-11-17 09:01:07 +01:00
admin 5f9ac66a26 Release 0.23.0: release/1.0 -> master (#256) 2026-11-16 04:20:23 +01:00
admin 10ee2baf91 Merge pull request 'Release 0.22.0: release/1.0 -> master' (#251) from release/1.0 into master
Reviewed-on: #251
2026-11-14 15:58:33 +01:00
admin 5e00cbbd79 Merge pull request 'Release 0.21.0: release/1.0 -> master' (#242) from release/1.0 into master
Reviewed-on: #242
2026-11-08 17:27:32 +01:00
26 changed files with 5052 additions and 109 deletions
+131 -4
View File
@@ -2,10 +2,137 @@
### Not in a release yet
- **The car can now charge from spare sun (Solar mode).** Choose *Solar* on the Car card or in Home Assistant: the car gets only the sun the house does not use, after the batteries (or before them, your choice), and pauses when there is too little. Every way out of Solar, a stop and a restart set the charger to 0 A. Three new options, all with defaults: `ev_margin_w`, `ev_start_min`, `ev_pause_min`. See "Car charger" in DOCS ([[EV-20]]).
- When the car charger does not take a current setting but is plainly working, you now see one amber row ("did not take the setting"), not a second "reading may be stuck" ([[EV-13]]).
- The add-on no longer changes the car's phases while the car still draws: it waits until the charger reads under 100 W, and if the car is still drawing after 20 s it gives the current back and tries again after 10 minutes ([[EV-28]]).
- When the add-on changes the car's phases while the batteries are at the peak reserve, there is no longer a false "Battery stopped limiting the peak" for a moment ([[EV-15]]).
- **The add-on log now says when the add-on sets a new car current or the car mode changes.** One line each, for example "Car: set from 10 A to 6 A on 1 phase (Manual)." and "Car mode is now Manual." It names the reason: Manual, Solar, peak cut, start-up or shutdown. A refused write adds no such line, and nothing is written or timed differently ([[EV-52]]).
- **Solar now lowers the car first for the peak limit.** When the 15-minute period heads over the limit, Solar lowers the car before the batteries give more, and brings it back when the period allows. One grey note says "Solar lowered the car for the peak." A Solar car the add-on cannot lower (another writer, shadow mode, a stop) no longer hides a peak alarm. Manual and Off do not change. See "Car charger" in DOCS ([[EV-21]]).
## 0.25.0
**A minor bump: the car can now charge from spare sun (Solar mode), and the Car card raises fewer false alarms. Three new options were added, all with defaults, and none needs setting.**
Three options were added (`ev_margin_w`, `ev_start_min` and `ev_pause_min`), none was removed or renamed, and no default changed (95 options, 92 before). **Existing installs need no option change:** the new options have defaults, and `ev_charger` is still off, so an install that does not use the car charger runs as 0.24.0 did. It is a minor bump because it adds a feature and new options. Every saved setting still starts.
**The car can charge from spare sun (Solar mode).** Choose *Solar* on the Car card or in Home Assistant. The car gets only the sun the house does not use, after the batteries or before them (your choice), and pauses when there is too little. When the sun cannot be measured, for example when the meter goes silent, the current stands for 5 minutes (*Pause after*, `ev_pause_min`) and then goes to 0 A. Every way out of Solar, a stop and a restart set the charger to 0 A. See "Car charger" in DOCS ([[EV-20]], [[EV-51]]).
**Car charger fixes.** The add-on no longer changes the car's phases while the car still draws. Fewer false "Battery stopped limiting the peak" alarms while the car charges. A current the charger does not take shows one amber row, not two. The Car card's *Why* line says what the charger does and no longer switches between two wordings ([[EV-28]], [[EV-15]], [[EV-18]], [[EV-19]], [[EV-13]], [[EV-14]], [[EV-16]]). The fixes for [[EV-14]], [[EV-18]] and [[EV-19]] are shown in tests only: the test rig could not run them or could not show a difference. Watch the Car card and the notifications for a few nights.
**No change in behaviour:** the build checks now test against a newer copy of the shared test tools.
Contents of this release, in merge order since 0.24.0 (`f66048b`):
| | |
|---|---|
| `9fdce02` | When the add-on changes the car's phases while the batteries are at the peak reserve, there is no longer a false "Battery stopped limiting the peak" for a moment ([[EV-15]], #262) |
| `43b0db7` | While the car explains why the house is over the peak limit, the alarm no longer fires at the start of a 15-minute period and stays red for the whole period ([[EV-18]], #264) |
| `8150608` | No alarm for a moment when the batteries first reach the peak reserve early in a Manual car session ([[EV-19]], #265) |
| `00b116e` | With *Batteries help with the peak* on, the Car card's *Why* line no longer switches between two wordings while the car is over the peak limit ([[EV-16]], #266) |
| `4eba2d9` | The build checks test against a newer copy of the shared test tools. There is no change in behaviour ([[CI-20]], #267) |
| `76f4de2` | The add-on no longer changes the car's phases while the car still draws. It waits until the charger reads under 100 W, and if the car still draws after 20 s it gives the current back and tries again after 10 minutes ([[EV-28]], #268) |
| `c8f5292` | When the charger does not take a current setting but is plainly working, you see one amber row ("did not take the setting"), not a second "reading may be stuck" ([[EV-13]], #269) |
| `885528a` | In shadow mode, and after a phase change was given up, the Car card's *Why* line says what the charger does, not what you set ([[EV-14]], #270) |
| `cc8c0dc` | The car can charge from spare sun (Solar mode), with three new options: `ev_margin_w`, `ev_start_min` and `ev_pause_min` ([[EV-20]], #271) |
| `09b6af9` | Solar mode: no false "charger reading may be stuck" after the add-on's own write, no back and forth between two currents, and the waits count from when the sun drops ([[EV-20]], #272) |
| `2768755` | The build checks test against a newer copy of the shared test tools. There is no change in behaviour (#273) |
| `5bff894` | Solar mode: one failed charger reading no longer pauses the car in full sun ([[EV-20]], #274) |
| `c79eb37` | Solar mode: when the meter goes silent, the car goes to 0 A at the first check once the meter reading is 330 s old ([[EV-51]], #275) |
### 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; the peak limit was kept). At the start of a month, before a peak above the limit, that is about 2 kWh a night in a rig test: the cycle can reach its 36 h limit after about 4 nights and fail, and since 0.22.0 the other battery gets no grid charge on those nights ([[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 heat pump or a car charger that is not set up in the add-on, 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 still not caught, and readings 15 s late only after about 4 minutes. Control now follows the meter more gently, so less goes to the grid: in a simulation with a changing load, 340 Wh became 189 Wh at 10 s late and 363 Wh became 296 Wh at 15 s late. In a rig test, 15 s late exported 13 to 19 % more than before ([[SAFETY-136]], [[SAFETY-134]]).
- 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]]).
- 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]]).
- While one battery's monthly cycle charges, the other battery's card on Home says "Saves its power for higher prices", and the plan still shows its grid charge in the cheap hours, though it will not charge ([[UX-80]]).
- After a failed monthly cycle, the plan line shows the day the wait ends, such as 18 November, not when the cycle tries again, such as 19 November at 19:00 ([[MAINT-26]]).
- At the start of a cheap window the peak guard can step once although the period is under the aim, and the step can land on a battery in its monthly charge. In a rig test it gave 1.7 to 2.3 kW for 6 s ([[SAFETY-140]]).
- A grid charge at full power in the last seconds of a 15-minute period can run into the next period, where the peak guard cuts it back ([[SAFETY-139]]).
- In a long real peak, the peak guard can end a 15-minute period up to 10 W over its aim, as 0.22.0 does (up to 31 W there). In a rig test the month's highest peak did not rise ([[SAFETY-141]]).
- The peak reserve notification can be created again and again, 24 to 47 times in 2 hours in a rig test, while the guard holds a battery at its reserve. 0.22.0 does the same ([[MAINT-29]]).
- When you switch the car charger off, its three sensors stay in Home Assistant with their last values. From reading the code, the PV power sensor does the same when it is switched off ([[TEL-19]]).
- In Settings, the choice for no car charger says "None", while its help says "Off" ([[UX-81]]).
- DOCS names the car's energy sensor `goodwe_car_today_kwh`, but Home Assistant creates it as `sensor.goodwe_car_energy_today` ([[TEL-20]]).
- While the car charges in Manual mode, a false "Battery stopped limiting the peak" can still show in the first minutes of a 15-minute period, though the period is heading under the limit. Seen in rig tests, also on builds before this one ([[SAFETY-143]]).
### 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.
## 0.24.0
@@ -161,9 +161,26 @@ one small set of facts and derives every path from them:
This also ends the false PEAK_GUARD_FLOOR_LIMITED after one gap (EV-18
T10(b) changed accordingly).
- **Silent meter on `ha_signed`:** Solar's unknown-sun pause is timed from the
meter's age: unknown since the age passed `meter_max_age_s`, so 0 A when the
age reaches `meter_max_age_s` + `ev_pause_min` (330 s), checked every
control cycle (bound 330 s + one cycle). Arrival sources are unchanged.
meter's age: unknown since the age passed `meter_max_age_s`, so 0 A on the
first car step whose own meter age (now minus the last reading, at that
step) is >= `meter_max_age_s` + `ev_pause_min` (330 s), held steps included.
Arrival sources are unchanged.
- **EV-51: decided at the step's own meter age.** Every decision that rests on
the meter's AGE is taken at the writer step's own age, not at the age the
cycle saw one step earlier: the pause above, the write block while the meter
is silent (no non-zero current, C17), the held-read pause (C18) and the
late-readings hold with its stale rule (a spare read while the hold was on
is not used once the step's own late time reaches `stale_input_s`). The
meter's VALUES (spare, target) stay the cycle's, one cycle of sensor latency
being normal, but only while the step's own age says the meter is fresh:
once it is past `meter_max_age_s` the spare is unknown, so nothing starts or
rises from it (C23). `car.held` and `car.reading` are unchanged. Arrival
sources keep the cycle's age for their "spare unknown" check. At log level
debug each Solar step logs one line: time, the meter age at the step, the
decision and the write. The decision is one word: `steady`, `start`,
`raise`, `lower`, `pause`, `hold` (the late-readings hold), `wait-unknown`
(the spare is unknown and the pause timer counts) or `wait-held` (a held
charger read).
- **No non-zero write while the meter is silent (SPIKE-06 C17, N8 strict):**
while the meter's age is past `meter_max_age_s`, Solar sends no non-zero
current: no retry, no raise, no phase change begun, and a phase change
@@ -0,0 +1,90 @@
# EV-21 — Solar: the car is cut first for the quarter peak
Part 2 of the split of cancelled EV-05 (owner 2026-11-19). EV-20 made Solar
and graded a Solar car exactly as a Manual car; this card lets Solar lower the
car before the batteries give more for the peak. Manual and Off do not change.
The rules are the PM rulings Q1-Q6, OQ1-OQ10 and Q-A to Q-D (brief v2); the
formal check is reports/EV-21-formal-report.md. EV-05's review rounds 2-9 are
the failure catalogue it answers.
## The rule, in plain words
- **Solar only.** When the 15-minute period heads over the aim (cap less
margin), the car is lowered first. Slowing a battery charge counts as the
batteries taking more (PM Q2), so a charge they could slow down only counts
as headroom for the 15 s wait.
- **How far.** `floor((car W - excess W) / (230 x phases))` A, with the phases
the car draws on (1 for a one-phase car). Under 6 A it is 0 A, never between.
Never above the current Solar has set. An untrusted car figure cuts to 0 A.
- **When.** At once without real headroom: the guard is saturated or at the
peak reserve, the excess is more than the batteries can still add, a battery
figure is missing, the cover option is off, or 120 s or less of the period
is left. Otherwise after at most 15 s, so a cloud edge the batteries catch is
not a cut. A refusing or sign-stopped battery, one at its cut-out or reserve,
and one switched off in battery modes add nothing (a charge it takes can
still stop).
- **Once per episode.** The cut is sized from the episode's start: the car's
power then, less the largest excess seen in it. A lagging meter never takes
it again from the lowered car. A growing excess makes it deeper, never
shallower.
- **Back up.** While a cut is due or stands, Solar does not raise the car, start
it or change its phases; it may still lower it. The car comes back when the
period's projection with the car's start power (6 A) has been under the aim
for the start rule's time (`ev_start_min`), counted from when it went under.
After a second cut in one period it waits for the next period. Then Solar's
own start rule runs as before.
- **The period's end.** No cut state goes over the edge: no cut at :15:00 for
the old period's energy; a new period heading over is cut in its first cycle.
- **Grading.** Solar takes the car out of the alarm grading only while it can
really cut it: Solar writes (no shadow, Stop, safety stop or shutdown), no
other writer, no charger fault or stuck reading, and the read-back shows the
current Solar sent. A cut written but not read back is not a cut. In every
other case the car figure is None for the alarm, the banking and the guard,
exactly as in Off. A Solar car is never banked as the period's cause.
- **The cover option keeps its meaning.** Off: while Solar can cut the car the
guard leaves it out, and the cut comes at once. While Solar cannot cut it,
the guard keeps it in (as Off).
- **What the user sees.** While the cut works: no car-over row and no "Car over
the peak limit" note, the card's Why says "Solar lowered the car for the
peak.", and one grey note with the same words per charging session. When
Solar cannot cut the car, the row and note say the car sets the peak.
## Where it lives
- `app/ctl_car.py` decides, in `car_cycle` (after the guard) and in a cycle
that holds before the guard (missing or late readings, Q4): `_car_cut_tick`.
The state is in memory only (`_cut`): a restart starts afresh, no store key.
- `app/carmode.py` writes: the decision is a cap on Solar's plan
(`SolarWriter.cut_a`, `SolarPlan.step(cap=...)`). The plan lowers to it at
once, past the 30 s gate and the 6 A hold, and starts nothing under it. A
phase change under way closes no higher than the cap. The write goes through
Solar's one write rule: never over another writer's value; a refused cut is
tried again as the same value after 60 s, three times.
- The seam is unchanged: `write_current` and `write_phases` are still called
only from `ManualWriter`; a cut never selects phases.
## Choices the rulings left open
- **A lowering on its way** (`CUT_SENT_S`, 2 s) counts as Solar's own for
grading, once per value (PM Q1): a re-send of the same value, a retry
included, gets no new grace; after it, not read back is not cut.
- **While the 15 s wait runs** the cap is the power Solar gives the car then
(C4: no raise while due), held in watts and turned into amps with the
phases Solar writes on (PM R1).
- **A cut due during Solar's own phase change ends the change** at its 0 A,
at once (PM R1, C12): no select after it and no closing current. The
read-back may still show the old phases, so a cut is never sized there.
- **Under a cut the plan may lower** (formal C10), by its own 30 s rule.
- **The cut's own ramp-down.** The trusted car figure is capped by the new,
lower read-back, so for one corroboration window (60 s) after a cut the
charger took, the car's real power (fresh, not stuck, never above the current
before the cut) stands in for grading only. A car that does not come down is
graded as in Off after that window (T45).
- **Freshness (N9).** A cut is sized only from a projection that is not blind,
with the meter's own age within `stale_input_s` (`meter_max_age_s` on
`ha_signed`, whose age counts from the last change).
## Rollback
No new option, no store key, no migration. An older build ignores nothing it
does not know; it grades a Solar car as Manual again.
+26 -3
View File
@@ -3374,13 +3374,26 @@ changes at most once per 30 seconds and only by 1 A or more.
seconds, Solar writes nothing over it (also no 0 A), shows an amber row and
logs one warning, until you press Solar again or the charger shows Solar's
value.
- **The peak limit** treats a Solar car exactly as a Manual car (below). Solar
does not slow the car for the peak in this version.
- **The peak limit: the car is cut first.** When the 15-minute period heads
over the peak limit, Solar lowers the car first, also while the batteries
could instead charge less: by the excess, to 0 A when less than 6 A would be left.
It waits at most 15 seconds, and only while the batteries can still give
more; it does not wait when they are at full power or at the peak reserve,
when a battery reading is missing, with `ev_batt_cover` off, or in the last 2
minutes of the period. One cut per excess; it goes deeper only if the excess
grows. The car comes back when the period, with the car at 6 A, has been
under the limit for the start time (`ev_start_min`); after a second cut in a
period, it waits for the next period. While this works, the card says
"Solar lowered the car for the peak." and one grey note says the same. When
Solar cannot lower the car (another writer, shadow mode, a stop, a charger
fault, or a lower current the charger has not shown yet), the peak alarms
treat the car as in Off. A Solar charge is never counted as setting the
month's peak.
- **Energy.** The card says "{kWh} charged today, {kWh} from the sun", and the
sensor `goodwe_car_today_solar_kwh` has the sun's part. Only Solar's own
share of spare sun counts, not the hold's battery or grid power.
**The car is never slowed for the peak limit.** A Manual charge goes on whatever
**Manual: the car is never slowed for the peak limit.** A Manual charge goes on whatever
the 15-minute peak does. With the default `ev_batt_cover` on, the batteries help
cover it down to the peak reserve; a 3-phase 16 A charge (11 kW) can empty two
batteries to the reserve in about 1.5 hours, and the month's peak then rises by
@@ -3576,6 +3589,15 @@ alarm. It is raised once per charging session. To stay under the limit, lower th
current. In Solar it says "Solar charges the car at {a} A, which sets the
peak.": the same case, with the current the charger has.
### Car lowered for the peak
In Solar mode the 15-minute period was heading over the peak limit, and the
add-on lowered the car first, before the batteries gave more. Nothing needs
doing: the car comes back by itself when the period allows it. It is raised
once per charging session.
*For installers: card EV-21.*
### Charger kept its current
The add-on started without writing to the charger (shadow mode, or control
@@ -3618,6 +3640,7 @@ default `info` hides it.
| No prices | warning | `goodwe_no_prices` | PRICE-01 |
| Charger not reachable | warning | `goodwe_charger_unreachable` | EV-03 |
| Car over the peak limit | info | `goodwe_car_over` | EV-04 |
| Car lowered for the peak | info | `goodwe_car_cut` | EV-21 |
**The Details link.** Home Assistant 2026.2 and newer show add-on pages at
`/config/app/<slug>/documentation`; 2026.5 removed the old
+171 -17
View File
@@ -142,17 +142,25 @@ class ManualWriter:
self.phase_done_at = None # EV-15: our phase change ended well then
self.zero_sent_at = None # EV-15: our 0 A write is out, not yet back
self.nonzero_at = None # EV-20 C6: the latest non-zero write sent
# EV-52: what the one info line per taken write needs.
self.boot = True # no user change since the process started
self._seen = False # the charger was available once
self._returned = False # ... and came back after being gone
self._r = None # the latest reading, for the phase count
self._late = None # (a, was, why, n) of a write not taken
# ------------------------------------------------------------------ user
def user_changed(self) -> None:
"""The user changed the mode or a value: one more write is allowed,
and another writer's hold is lifted."""
self.boot = False
self.rev_applied = None
self.hold = self.other = False
self.mismatch_since = None
self.fails, self.fail_at, self.gave_up = 0, None, False
self.phase_fails, self.phases_gave_up = 0, False
self.attempted_a = self.prior_a = None
self._late = None # EV-52: that request is not current now
# ------------------------------------------------------------------ step
async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp,
@@ -164,6 +172,7 @@ class ManualWriter:
if r is None or not r.available:
self.was_available = False
return
self._r = r
# A reading taken before our latest write was confirmed says nothing
# about it (the writer runs beside the cycle and can finish between a
# read and the step that follows): wait for one taken after.
@@ -172,6 +181,8 @@ class ManualWriter:
and tracker.obs_at <= self.last_done:
return
if not self.was_available:
self._returned = self._returned or self._seen
self._seen = True
self.was_available = True
self.reapply = True # on return: only if it differs
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
@@ -184,6 +195,7 @@ class ManualWriter:
return
self.would = None
if mode != MANUAL:
self._late = None # EV-52: another mode: that try is history
return
if clamp is None or clamp < CH.MIN_A:
return
@@ -210,6 +222,10 @@ class ManualWriter:
self.fails, self.blocked = 0, False
if cur is not None:
self.last_a = cur # adopt what is already set
# EV-52 (PM Q2): a write taken late is logged once, here.
late, self._late = self._late, None
if late is not None and abs(cur - float(late[0])) <= TOL_A:
self._log_set(*late)
return
if not (need_user or self.reapply):
return # a difference nobody asked for: `_watch()` judges
@@ -264,7 +280,47 @@ class ManualWriter:
"the add-on set %.0f A), so the add-on stops writing "
"to it until you change it.", cur, known[0])
# ----------------------------------------------------- EV-52: the info line
def _why_default(self) -> str:
"""The reason of a write nobody named: Manual's own, or `start-up`
while nothing was changed since the process started."""
return "start-up" if self.boot and not self._returned else "Manual"
def _close_why(self, q):
return None
def _phases_of(self, n=None):
"""The phase count a current is written for: the one the caller
names, else what the charger reports. None when unknown."""
if n in (1, 3):
return n
if getattr(self, "single", False):
return 1
p = getattr(self._r, "phases_allowed", None)
return p if p in (1, 3) else None
def _log_set(self, a, was, why, n) -> None:
"""One plain INFO line for a current the charger took. Never raises:
a line is not worth a failed write."""
try:
new, old, ph = _num(a), _num(was), self._phases_of(n)
if new is None:
return
head = f"Car: set to {new:.0f} A"
if old is not None:
if abs(old - new) <= TOL_A:
return # it stood there: not a change
head = f"Car: set from {old:.0f} A to {new:.0f} A"
tail = "" if ph is None else (
" on 1 phase" if ph == 1 else " on 3 phases")
_LOG.info("%s%s (%s).", head, tail, why)
except Exception: # noqa: BLE001
pass
async def _write(self, drv, a, was, now, tracker, **kw) -> bool:
why = kw.pop("why", None) or self._why_default()
n = kw.pop("n", None)
self._late = None
tracker.begin_write() # EV-12: the read-back is ours
if float(a) > TOL_A:
# EV-20 C6, THE ONE WRITE CLOCK: every non-zero current either
@@ -283,8 +339,10 @@ class ManualWriter:
if ok:
self.last_a = a
self.attempted_a = self.prior_a = None
self._log_set(a, was, why, n)
else:
self.attempted_a, self.prior_a = a, was
self._late = (a, was, why, n) # logged if it is adopted later
return ok
def _stamp(self, now) -> None:
@@ -310,7 +368,7 @@ class ManualWriter:
self.rev_applied, self.reapply = None, True
a = self._restore_a(q.get("prev"), clamp)
if a is not None:
await self._write(drv, a, 0.0, now, tracker)
await self._write(drv, a, 0.0, now, tracker, why="Manual")
async def _begin(self, drv, r, cur, n, now, tracker) -> None:
"""Step 1 of the safe sequence: 0 A. A charger that does not take it
@@ -337,7 +395,7 @@ class ManualWriter:
a = None if q is None else self._restore_a(q.get("prev"), clamp)
if a is not None:
self._clock = self._clock or (lambda: now)
await self._write(drv, a, 0.0, now, tracker)
await self._write(drv, a, 0.0, now, tracker, why="shutdown")
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
q = self.seq
@@ -379,6 +437,7 @@ class ManualWriter:
q["stage"] = "select"
if q["stage"] == "select":
ok = await drv.write_phases(q["n"])
q["sel_ok"] = bool(ok) # EV-52: the close's phase count
self._stamp(now)
self.last_switch = now
self.log.append(("phases", q["n"], now, ok))
@@ -403,7 +462,9 @@ class ManualWriter:
# on whether the phases changed); Manual a number, as before.
want = want_a(q) if callable(want_a) else want_a
a = min(max(float(want), CH.MIN_A), hi)
if await self._write(drv, a, 0.0, now, tracker):
if await self._write(drv, a, 0.0, now, tracker,
why=self._close_why(q),
n=q["n"] if q.get("sel_ok") else None):
# Judged afresh next cycle: a value the user changed meanwhile is
# still wanted, and one that is in place is adopted.
self.seq, self.rev_applied, self.reapply = None, None, False
@@ -486,6 +547,25 @@ def amps_for(car_w, n, clamp=None):
return float(max(0, min(a, math.floor(hi))))
def cut_amps(car_w, excess_w, n, now_a=None):
"""EV-21: the current a peak cut leaves the car, or None when there is
nothing to cut (no excess). `floor((car_w - excess_w) / (230 x n))`,
0 when that is under 6 A, never above `now_a` (the setpoint now). An
unknown car figure cuts to 0 A (PM OQ2)."""
ex = _num(excess_w)
if ex is None or ex <= 0.0 or n not in (1, 3):
return None
w = _num(car_w)
a = 0.0 if w is None else float(max(
0, math.floor((w - ex) / (VOLTS * n) + 1e-9)))
if a < CH.MIN_A:
a = 0.0
top = _num(now_a)
if top is not None:
a = min(a, max(0.0, top))
return a
def solar_option(opts: dict, key: str) -> float:
"""`ev_margin_w`, `ev_pause_min` or `ev_start_min` as a number; the shipped
default when it is not one (the validator refuses it anyway)."""
@@ -498,8 +578,13 @@ class SunInputs:
def __init__(self, target_w=None, hold=False, auto=True, start_s=120.0,
pause_s=300.0, spare_w=None, room_w=0.0, margin_w=100.0,
first=DEFAULT_FIRST, unknown_s=0.0, silent=False):
first=DEFAULT_FIRST, unknown_s=0.0, silent=False,
meter_back=False, age_s=None):
self.target_w, self.hold, self.auto = target_w, hold, auto
# EV-51: the meter's own age at the writer step (None: no reading), and
# `meter_back`: the cycle's snapshot said "meter too old" but the step's
# own age says a new reading came, so no unknown timer is carried over.
self.meter_back, self.age_s = meter_back, age_s
# EV-20 rig round 2: how long the sun has already been unknown when
# the cause is the meter's own age (`ha_signed`): the pause is timed
# from that age, not from the cycle that noticed it.
@@ -569,12 +654,29 @@ class SolarPlan:
self._before
self.switch, self._before = False, None
def _cut(self, cap) -> None:
"""EV-21: the peak cut lowers the current to `cap` at once, past the
30 s gate and the 6 A hold; under 6 A it is the pause."""
if cap < CH.MIN_A:
self.pause("peak")
return
self.a, self.last_dir, self.low_since = float(cap), -1, None
def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s,
hold=False, gap_ok=True, unknown_s=0.0):
hold=False, gap_ok=True, unknown_s=0.0, meter_back=False,
cap=None):
"""`n_now`: the phases the car draws on now (1 for a one-phase car);
`auto`: Solar may choose the phases; `gap_ok`: a phase change is
allowed now (EV-04's one per `PHASE_GAP_S`); `hold`: readings late
under the stale bound, everything stands."""
under the stale bound, everything stands. `meter_back` (EV-51): the
meter's own age is fresh again at this step: the unknown timer that
counted its silence starts over. `cap` (EV-21): a peak cut is due or
stands: the current goes no higher than `cap` (lowered at once), no
start and no phase change; the plan may still lower."""
if meter_back:
self.unknown_since = None
if cap is not None and self.a > cap + 1e-9:
self._cut(cap)
if hold:
# Readings late under the stale bound: nothing changes, but a
# hold or an unknown spare that has run its time still pauses
@@ -613,8 +715,10 @@ class SolarPlan:
if self.ok_since is None:
self.ok_since = now
self.why = "start"
if now - self.ok_since >= start_s and self._gate(now) \
and (n0 == self.n or gap_ok):
# EV-21: under a peak cut no start (the restart rule lifts
# the cap); the start count goes on.
if cap is None and now - self.ok_since >= start_s \
and self._gate(now) and (n0 == self.n or gap_ok):
a = amps_for(target_w, n0, clamp)
if a is not None and a >= CH.MIN_A:
self._set(a, now, n0)
@@ -628,7 +732,7 @@ class SolarPlan:
self.pause()
return
self.a, self.set_at, self.last_dir = float(hi), now, -1
if auto and not self.switch: # auto phases, by dwells
if auto and not self.switch and cap is None: # auto phases, by dwells
if self.n == 1:
self.down_since = None
if target_w >= UP_W:
@@ -665,6 +769,8 @@ class SolarPlan:
# `UP_HYST_W` (no ping-pong on an amp boundary).
up = amps_for(target_w - UP_HYST_W, self.n, clamp) or 0.0
want = max(self.a, up)
if cap is not None:
want = min(want, self.a) # EV-21: no raise (C10)
if abs(want - self.a) >= SOLAR_STEP_A and self._gate(now):
self.last_dir = 1 if want > self.a else -1
self.a, self.set_at = want, now
@@ -735,12 +841,17 @@ class SolarWriter(ManualWriter):
self.stuck_warned = False # ... and its one CHARGER_REFUSED was given
self.nz_block = False # C17/C18: this step writes 0 A at most
self.held_step = False # C18: a held read: only a NEW 0 A goes out
self.cut_a = None # EV-21: the peak cut's cap, set per cycle
self.sent_at = None # EV-21: when `sent_a` went out
self.startup_zero = False # EV-52: the 0 A the start itself caused
self.sent_why = None # EV-52: the reason of `sent_a`'s write
def owe_start(self) -> None:
"""C1: the add-on starts in Off while an exit 0 A of its own was still
pending at the stop: the current the charger shows is the add-on's,
so the 0 A is owed (once it may write), retried by the exit rule."""
self.start_owed = self.engaged = True
self.startup_zero = True
def _stuck_end(self) -> None:
"""SPIKE-06: a stuck episode ends (the reading followed a start, a
@@ -795,7 +906,20 @@ class SolarWriter(ManualWriter):
"""ManualWriter's one write site. What Solar SENT is recorded before
the write goes out, so a write cancelled while it waits for its
read-back is never trusted (`live`)."""
prev = self.sent_a
why = kw.get("why")
if why is None:
# EV-52: the 0 A the start caused is `start-up`, else Solar's own.
why = "start-up" if self.startup_zero and float(a) <= TOL_A \
and self.boot else "Solar"
kw["why"] = why
self.sent_why = why
self.sent_a, self.taken = float(a), False
if prev is None or abs(prev - float(a)) > TOL_A:
# EV-21 (PM Q1, formal C15): the 2 s grace of a lowering on its
# way is once per value; a re-send of the same value (a retry)
# gets none.
self.sent_at = now
zero = float(a) <= TOL_A
if not zero and tracker is not None and tracker.stuck(now):
self.stuck_starts += 1 # C12: a start under a stuck verdict
@@ -811,6 +935,7 @@ class SolarWriter(ManualWriter):
self.zero_sent_at = None
if ok:
self.taken = True
self.startup_zero = False
self.fails, self.fail_at, self.gave_up = 0, None, False
if zero:
self._owed(False)
@@ -818,6 +943,11 @@ class SolarWriter(ManualWriter):
self._failed(now)
return ok
def _close_why(self, q):
"""EV-52: a phase change's closing current: capped by the peak cut,
or Solar's."""
return "peak cut" if q.get("cut") else "Solar"
def _failed(self, now) -> None:
self.fails += 1
self.fail_at = now
@@ -832,9 +962,15 @@ class SolarWriter(ManualWriter):
if self.sent_a is not None and self.sent_a <= TOL_A:
self._owed(False)
self.taken = True
self.startup_zero = False
self.last_a = cur
self.attempted_a = self.prior_a = None
self.fails, self.fail_at, self.gave_up = 0, None, False
# EV-52 (PM Q2): a write the charger took late is logged once, here.
late, self._late = self._late, None
if late is not None and cur is not None \
and abs(float(cur) - float(late[0])) <= TOL_A:
self._log_set(*late)
async def _put(self, drv, want, cur, now, tracker, stuck=False) -> None:
"""Make the charger match `want`: write a new decision, try one the
@@ -851,18 +987,24 @@ class SolarWriter(ManualWriter):
self.fail_at is not None
and now - self.fail_at < RETRY_S):
return
await self._write(drv, want, cur, now, tracker)
# EV-52: a retry keeps the reason of the first try.
await self._write(drv, want, cur, now, tracker,
why=self.sent_why)
return
if not stuck and cur is not None and abs(cur - want) <= TOL_A:
self.sent_a = want # it already stands
self._adopt(cur)
return
if want <= TOL_A:
cut = (self.cut_a is not None and want <= self.cut_a + TOL_A
and self.sent_a is not None and want < self.sent_a - TOL_A)
if want <= TOL_A or cut:
# A new 0 A, or EV-21's new lower cut value: its own tries, at once.
self.fails, self.fail_at, self.gave_up = 0, None, False
elif self.gave_up or (self.fail_at is not None
and now - self.fail_at < RETRY_S):
return
await self._write(drv, want, cur, now, tracker)
await self._write(drv, want, cur, now, tracker,
why="peak cut" if cut else None)
def _own_readback(self, cur) -> bool:
"""C9: does the read-back show a current of Solar's own (sent,
@@ -919,6 +1061,7 @@ class SolarWriter(ManualWriter):
def _leave(self) -> None:
"""Solar is no longer the mode and owes nothing."""
self.engaged, self.seq, self.would = False, None, None
self._late = None # EV-52: no late accept after leaving
self.start_owed = False
self.out, self.fault = False, None
self.restart = True
@@ -937,7 +1080,8 @@ class SolarWriter(ManualWriter):
now, target_w=sun.target_w, hold=sun.hold, n_now=n_now,
auto=sun.auto and not self.single and not self.phases_gave_up,
clamp=clamp, start_s=sun.start_s, pause_s=sun.pause_s,
gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0))
gap_ok=gap_ok, unknown_s=getattr(sun, "unknown_s", 0.0),
meter_back=getattr(sun, "meter_back", False), cap=self.cut_a)
@staticmethod
def _drawing(r) -> bool:
@@ -960,9 +1104,13 @@ class SolarWriter(ManualWriter):
new phases and for the phases the charger reports, so nothing meant
for 1 phase is ever written on 3 (review round 1, Major 1)."""
def want(q):
if "close_a" in q:
return q["close_a"] # one value per sequence, its retries too
q["close_a"] = a = self._close_a(q, clamp, n_reported)
if "close_a" not in q:
q["close_a"] = self._close_a(q, clamp, n_reported)
a = q["close_a"] # one value per sequence, its retries too
cap = self.cut_a # EV-21: never above a peak cut's cap
if cap is not None and cap >= CH.MIN_A and a > cap:
q["close_a"] = a = float(cap)
q["cut"] = True # EV-52: the close is a peak cut
return a
return want
@@ -1042,6 +1190,7 @@ class SolarWriter(ManualWriter):
if r is None or not r.available:
self.was_available = False # nothing is tried while it is down
return
self._r = r
if self.last_done is not None and tracker is not None \
and tracker.obs_at is not None \
and tracker.obs_at <= self.last_done:
@@ -1059,6 +1208,10 @@ class SolarWriter(ManualWriter):
# the charger's current is its own, not another writer's, and the
# first write is 0 A whatever it shows (D2, round 9).
self.was_available = True
self._returned = self._returned or self._seen
self._seen = True
# EV-52: only the process's own start owes a `start-up` 0 A.
self.startup_zero = self.boot and not self._returned
self.fresh_start = self.restart = True
self.mismatch_since = None
self.last_a = self.attempted_a = self.prior_a = None
@@ -1264,6 +1417,7 @@ class SolarWriter(ManualWriter):
if not self.engaged or not self.live or self.hold:
return None
if r is not None and r.available:
self._r = r
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
else:
cur = None
@@ -1276,7 +1430,7 @@ class SolarWriter(ManualWriter):
if wait > 0:
await sleep(wait)
if await self._write(drv, 0.0, cur, clock(), tracker,
took_s=RELEASE_TOOK_S):
took_s=RELEASE_TOOK_S, why="shutdown"):
self.released = True
return True
self.released = False
+407 -14
View File
@@ -10,12 +10,14 @@ the guard treats a Solar car exactly as a Manual car).
"""
import asyncio
import copy
import dataclasses
import logging
import math
from datetime import timezone
from . import carmode, chargers, messages, packshare, peakguard
from .tariff import QUARTER_S
from .tariff import QUARTER_S, next_quarter
_LOG = logging.getLogger("goodwe")
@@ -47,6 +49,18 @@ CAR_EXIT_KEY = "car_exit_0a_pending"
# EV-20 (D3): at shutdown in Solar the charger's 0 A waits at most this long,
# then the inverters are released whatever the charger did.
RELEASE_WAIT_S = 15.0
# EV-21: Solar's car is cut first for the quarter peak. The cut waits at most
# CUT_WAIT_S, and only while the batteries can still raise their output; with
# CUT_NEAR_END_S or less of the period left it comes at once (waiting 15 s
# with R s left raises what must come off by R / (R - 15), at most 8/7 at
# 120 s). After CUT_MAX_Q cuts in one period, no restart until the next.
# DECISIONS/EV-21-car-cut-first.md.
CUT_WAIT_S = 15.0
CUT_NEAR_END_S = 120.0
CUT_MAX_Q = 2
# A lowering Solar sent counts as its own this long before its read-back:
# one cycle beside the write (the alarm still comes within 2 s of Off's).
CUT_SENT_S = 2.0
class CarMixin:
@@ -74,6 +88,10 @@ class CarMixin:
ok = carmode.allowed_phases(opts)
self.car_n = n if n in ok else ok[0]
self.car_rev = 0
ch = getattr(self, "charger", None)
if ch is not None and ch.configured(): # EV-52: the mode at the start
_LOG.info("Car mode is now %s.",
carmode.MODE_LABELS[self.car_mode])
self.car_writer = carmode.ManualWriter()
self.car_solar = carmode.SolarWriter() # EV-20
self.car_solar.on_owed = self._car_owed
@@ -83,6 +101,7 @@ class CarMixin:
self.car_first = first if first in carmode.FIRSTS \
else carmode.DEFAULT_FIRST
self._car_late_s = None # EV-20: the cycle's late verdict
self._car_late_mono = None # ... and the time it was read (EV-51)
self._car_sun_now = None # ... and Solar's inputs of that cycle
sun = data.get(CAR_SUN_KEY)
self.car_sun = {"day": None, "kwh": 0.0}
@@ -116,6 +135,262 @@ class CarMixin:
self._peak_proj_real = None
saved = data.get(CAR_PEAK_KEY)
self.car_peak_q = dict(saved) if isinstance(saved, dict) else {}
self._cut = self._cut_fresh(None) # EV-21: in memory only
self._car_cut_notified = None # EV-21: the session noted
self._car_can = False # EV-21: can-cut as graded
# ------------------------------------------------- EV-21: the peak cut
@staticmethod
def _cut_fresh(key) -> dict:
"""EV-21: no cut state, for period `key`. `since`: the episode began
(the cut first due); `car0`: the car's W then; `ex`: the largest
excess seen in it; `cap`: the cut's current, None while none stands;
`cuts`: cuts in this period; `under`: the projection with the start
power has been under the aim since."""
return {"key": key, "since": None, "car0": None, "ex": 0.0,
"cap": None, "wait": None, "cuts": 0, "under": None,
"base": None, "at": None}
def _car_cut_ramp_w(self, mono):
"""EV-21: for grading only, the car's real power while it comes down
after a cut the charger took: fresh, not stuck, never above the
current before the cut, at most `CORR_WINDOW_S` after the cut. (Its
trusted figure is capped by the new, lower read-back meanwhile.) None
otherwise: a car that does not follow is graded as in Off after
that window (T45)."""
st = self._cut
if st["cap"] is None or st["at"] is None or st["base"] is None \
or not 0.0 <= mono - st["at"] <= chargers.CORR_WINDOW_S \
or not self.car_solar_can_cut() or self.car.stuck(mono):
return None
raw = self.car.car_w(mono)
if raw is None:
return None
n = self._car_cut_n()
return min(float(raw), float(st["base"]) * chargers.CEILING_V * n)
def car_solar_can_cut(self) -> bool:
"""EV-21 (Q5): can Solar really cut the car now? Solar writes (no
shadow, Stop, safety stop or shutdown), the charger is read fresh with
no fault and no stuck reading, no other writer (no hold, no
difference) and the read-back shows the current Solar sent. A cut
written but not read back is not a cut."""
if not self.car_solar_mode() or not self.car_writing():
return False
w = self.car_solar
mono = self.car_now()
r = self.car.reading
if r is None or not r.available or r.error \
or r.state in ("E", "F") or not self.car.fresh(mono) \
or self.car.stuck(mono):
return False
if w.hold or w.mismatch_since is not None or w.fault is not None \
or w.gave_up or w.sent_a is None:
return False
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
if cur is None:
return False
if abs(cur - w.sent_a) <= carmode.TOL_A:
return True
# A lowering of Solar's own on its way: the cycle beside the write
# reads the charger before it answers. For CUT_SENT_S at most, and
# never once the charger refused it.
at = getattr(w, "sent_at", None)
return bool(w.sent_a < cur - carmode.TOL_A and at is not None
and 0.0 <= mono - at <= CUT_SENT_S
and (w.fail_at is None or w.fail_at < at))
def car_cut_standing(self) -> bool:
"""EV-21: a peak cut lowered the car and the charger shows it."""
st = getattr(self, "_cut", None)
w = getattr(self, "car_solar", None)
if not st or st["cap"] is None or st["base"] is None or w is None \
or st["cap"] >= float(st["base"]) - carmode.TOL_A:
return False
return bool(self.car_solar_can_cut() and w.sent_a is not None
and w.sent_a <= st["cap"] + carmode.TOL_A)
async def check_car_cut(self) -> None:
"""EV-21 (OQ5): one grey note per charging session once a cut is
taken: "Solar lowered the car for the peak.\""""
if not self.car_cut_standing() \
or self._car_cut_notified == self._car_session:
return
self._car_cut_notified = self._car_session
_LOG.info("Solar lowered the car for the peak: CAR_CUT.")
await self.hass.call("persistent_notification", "create",
messages.car_cut().data())
def _car_cut_meter_fresh(self) -> bool:
"""EV-21 (N9): the meter's own age allows sizing a cut: within
`stale_input_s`, or on `ha_signed` (whose age counts from the last
change) within `meter_max_age_s`."""
if not self.p1_enabled:
return False
age = self.p1.age_s()
if age is None:
return False
if str(self.o.get("meter_source") or "") == "ha_signed":
bound = float(self.o.get("meter_max_age_s", 30) or 30)
else:
bound = float(self.o.get("stale_input_s", 15))
return age <= bound
def _car_cut_headroom(self, guard):
"""EV-21 (Q2-Q4): the watts the batteries can still ADD, or None when
a battery figure is missing (then they count as adding nothing). A
battery adds nothing at or under its cut-out level or its peak
reserve (the guard's `held`), while it refuses to give, under a
safety stop, or switched off in battery modes; the guard's `able_w`
caps the rest. 0 while the guard is saturated or floor-limited."""
if self.site_batt_w is None \
or any(inv.batt is None for inv in self.inverters):
return None
if guard is None or guard.saturated or guard.floor_limited:
return 0.0
n = len(self.inverters)
if self.circ_wd.tripped or (n > 1 and self.site_sign_wd.tripped):
return 0.0
held = set(getattr(guard, "held", ()) or ())
top = given = stop = 0.0
for inv in self.inverters:
refused = inv.refused if n > 1 else self.batt_refused
if inv.sign_wd.tripped \
or (self.modes_on and not self.pack_mode(inv).use):
continue
if (refused or 0) > 0 or inv.name in held or inv.soc is None \
or inv.bms_soc_floor is None \
or float(inv.soc) <= float(inv.bms_soc_floor):
# Gives nothing more; a charge it takes can still stop.
stop += max(0.0, -float(inv.batt))
continue
top += float(inv.rating_w())
given += float(inv.batt)
if guard.able_w is not None:
top = min(top, float(guard.able_w))
return max(0.0, top - given) + stop
def _car_cut_n(self):
"""The phases the car draws on: 1 for a one-phase car."""
r = self.car.reading
if self.car_solar.single:
return 1
n = getattr(r, "phases_allowed", None)
return n if n in (1, 3) else self.car_solar.plan.n
def _car_cut_tick(self, real_proj, guard, target_w, mono) -> None:
"""EV-21: decide the peak cut for the writer step that follows this
cycle (`car_kick`), from the projection WITH the car. Due: Solar, a
fresh projection heading over the aim (`excess_w` > 0) and a car that
draws. Taken at once without real headroom (saturated, floor-limited,
the excess beyond what the batteries can add, no battery figure, the
cover off, the period's last 120 s), else after CUT_WAIT_S. One cut
per episode, sized from its start: `car0` less the largest excess
so far, never re-subtracted from the lowered car. While it is due or
stands, the writer's plan goes no higher (the cap). It is lifted when
the projection with the start power has been under the aim for the
start rule's time (not after CUT_MAX_Q cuts in the period), and at
the period's end."""
w = self.car_solar
if not self.car_solar_mode():
self._cut = self._cut_fresh(None)
w.cut_a = None
return
key = None if real_proj is None else real_proj.block_start
st = self._cut
if key is not None and key != st["key"]:
st = self._cut = self._cut_fresh(key) # no state over the edge
blind = guard is not None and guard.blind is not None
if key is None or target_w is None or blind \
or not self._car_cut_meter_fresh():
# N9: nothing sized from a stale projection; what stands stays.
w.cut_a = st["cap"] if st["cap"] is not None \
else self._car_wait_a(st)
return
ex = peakguard.excess_w(real_proj, target_w)
left = QUARTER_S - float(real_proj.elapsed_s)
r = self.car.reading
cur = None if r is None or not r.available else (
r.allowed_a if r.allowed_a is not None else r.setpoint_a)
car_w = self.car.car_w_trusted(mono)
drawing = (car_w is not None and car_w > 0.0) or (
car_w is None and r is not None and r.available
and r.charging is True)
running = w.plan.a > 0.0 or (cur is not None and cur > carmode.TOL_A)
# C12: Solar's own phase change holds the car at 0 A on its way to a
# current: a cut due then ends it at that 0 A (no closing current).
seq_on = w.seq is not None and w.plan.a > 0.0
# PM Q2 (formal C14): slowing a battery charge counts as the
# batteries taking more, so a cut is due whatever they do now; their
# charge only counts as headroom for the 15 s wait.
due = ex > 0.0 and running and (drawing or seq_on)
n = self._car_cut_n()
# PM R1 (review r1): a cut due while Solar's own phase change is
# under way (its 0 A sent, or the plan decided it) ends the change at
# its 0 A, at once: never sized on phases the read-back may not show.
change_on = w.seq is not None or w.plan.switch
if st["cap"] is not None:
# A cut stands: deeper only if the excess grows (OQ7); the
# restart rule lifts it.
if due and change_on and st["cap"] > 0.0:
st["cap"] = 0.0
if due and ex > st["ex"]:
st["ex"] = ex
a = carmode.cut_amps(st["car0"], ex, n, st["base"])
if a is not None and a < st["cap"]:
st["cap"] = a
start_w = chargers.MIN_A * carmode.VOLTS * n # OQ4
now_w = 0.0 if car_w is None else float(car_w)
plus = float(real_proj.projected_w) \
+ max(0.0, start_w - now_w) * max(0.0, left) / QUARTER_S
if plus < float(target_w):
if st["under"] is None:
st["under"] = mono
else:
st["under"] = None
start_s = 60.0 * carmode.solar_option(self.o, "ev_start_min")
if st["under"] is not None and mono - st["under"] >= start_s \
and st["cuts"] < CUT_MAX_Q:
cuts = st["cuts"]
st = self._cut = self._cut_fresh(key)
st["cuts"] = cuts
w.cut_a = st["cap"]
return
if not due:
st["since"], st["wait"] = None, None # the batteries caught it
w.cut_a = None
return
if st["since"] is None:
st["since"], st["car0"], st["ex"] = mono, car_w, ex
st["base"] = w.plan.a if w.plan.a > 0.0 else cur
st["ex"] = max(st["ex"], ex)
room = self._car_cut_headroom(guard)
now_ = (room is None or room <= 0.0 or ex > room
or not self.car_cover or left <= CUT_NEAR_END_S)
if now_ or change_on or mono - st["since"] >= CUT_WAIT_S:
a = 0.0 if change_on else carmode.cut_amps(
st["car0"], st["ex"], n, st["base"])
st["cap"] = 0.0 if a is None else a
st["cuts"] += 1
st["wait"], st["at"] = None, mono
w.cut_a = st["cap"]
return
# C4: due and waiting: no raise meanwhile. PM R1: held in watts (the
# plan's current on its phases), turned into amps with the phases at
# the write.
p = w.plan
now_w = float(p.a) * carmode.VOLTS * (p.n if p.n in (1, 3) else n)
st["wait"] = now_w if st["wait"] is None else min(st["wait"], now_w)
w.cut_a = self._car_wait_a(st)
def _car_wait_a(self, st):
"""PM R1: the 15 s wait's cap, held in watts, as amps on the phases
Solar writes on now (the plan's), rounded down. None: no wait."""
if st["wait"] is None:
return None
n = self.car_solar.plan.n
n = n if n in (1, 3) else self._car_cut_n()
return float(math.floor(st["wait"] / (carmode.VOLTS * n) + 1e-9))
@property
def car_cover(self) -> bool:
@@ -205,6 +480,8 @@ class CarMixin:
# A Manual phase change in the middle is not restored: Solar
# starts from the 0 A it stands at.
self.car_writer.seq = None
if value != self.car_mode: # EV-52: one plain line
_LOG.info("Car mode is now %s.", carmode.MODE_LABELS[value])
self.car_mode = value
self.store.set(carmode.KEY_MODE, value)
elif what == "car_sun_first":
@@ -274,13 +551,37 @@ class CarMixin:
if self.car_solar_mode() else None)
self._car_task = asyncio.ensure_future(self._car_run())
def _car_hold_kick(self) -> None:
def _car_hold_kick(self, now=None) -> None:
"""EV-20: a cycle that holds for a missing or late reading returns
before `car_kick()`. Solar still steps (it holds, counts its dwell,
and a way out still writes its 0 A); Manual is left as it was."""
and a way out still writes its 0 A); Manual is left as it was.
EV-21 (Q4): the peak cut is still decided, on the meter's own
projection: without a battery figure the batteries add nothing."""
if now is not None and self.car_solar_mode():
self._car_cut_hold(now)
if self.car_solar_engaged():
self.car_kick()
def _car_cut_hold(self, now) -> None:
"""EV-21: the cut in a cycle that returns before the guard: the
meter's projection (no gap filling, which has its own state; a
blind one sizes nothing), no guard, so no headroom."""
if not self.p1_enabled:
self._car_cut_tick(None, None, None, self.car_now())
return
proj = self.peak.project(self.p1.averager, now, roll=self.modes_on)
hold_s = self.p1.averager.max_hold_s
if proj is not None and len(self.inverters) > 1:
proj = next_quarter(proj, hold_s)
if proj is not None and peakguard.blindness(
proj, hold_s, False) is not None:
proj = None
reading = self.peak.peak(now)
target = peakguard.quarter_target_w(
float(self.o.get("peak_cap_w", 3500)), self.peak_margin_w,
reading)
self._car_cut_tick(proj, None, target, self.car_now())
async def car_settle(self) -> None:
"""Wait for the writer step in flight (the checks use it)."""
t = self._car_task
@@ -372,8 +673,76 @@ class CarMixin:
now = self.car_now()
sun = None
if self.car_mode == carmode.SOLAR:
sun = getattr(self, "_car_sun_now", None) \
or self.car_sun_inputs(now)
sun = self.car_sun_own(getattr(self, "_car_sun_now", None)
or self.car_sun_inputs(now), now)
w0 = self.car_solar
a0, n_log = w0.plan.a, len(w0.log)
await self._car_step_run(held, now, sun)
if sun is not None and _LOG.isEnabledFor(logging.DEBUG):
self._car_step_debug(held, now, sun, a0, n_log)
def _car_step_debug(self, held, now, sun, a0, n_log) -> None:
"""EV-51: one DEBUG line per Solar writer step: the time, the meter's
age at the step, what was decided and what was written. The decision
is one word: steady, start, raise, lower, pause, hold (the
late-readings hold), wait-unknown (the spare is unknown and the pause
timer counts) or wait-held (a held charger read). Nothing at info and
above; no secrets in it."""
w = self.car_solar
a1 = w.plan.a
if a0 > 0.0 and a1 <= 0.0:
what = "pause"
elif held:
what = "wait-held"
elif sun.hold:
what = "hold"
elif a0 <= 0.0 and a1 > 0.0:
what = "start"
elif a1 > a0 + carmode.TOL_A:
what = "raise"
elif a1 < a0 - carmode.TOL_A:
what = "lower"
elif sun.target_w is None:
what = "wait-unknown"
else:
what = "steady"
sent = []
for kind, v, _t, ok in w.log[n_log:]:
if kind == "current":
sent.append(f"sent {v:g} A" + (" confirmed" if ok else ""))
else:
sent.append(f"phases {v}" + (" confirmed" if ok else ""))
age = sun.age_s
_LOG.debug("Solar step: t=%.1f age=%s decision=%s write=%s", now,
"none" if age is None else f"{age:.1f}", what,
"; ".join(sent) or "none")
def car_sun_own(self, snap, now):
"""EV-51 (PM): every decision on the meter's AGE is taken at the writer
step's own age (now minus the meter's last reading), not the age the
cycle saw one step earlier: the write block while the meter is silent
(N8), the unknown/pause timing (held reads too) and the late-readings
hold with its stale rule. The meter's VALUES (spare, target) stay the
cycle's only while the step's own age says the meter is fresh; once it
is past `meter_max_age_s` they are unknown (C23). Arrival sources'
`car_spare_w` keeps the cycle's age."""
own = copy.copy(snap)
own.silent = self._car_meter_silent()
own.unknown_s = self._car_meter_over_s()
own.age_s = self.p1.age_s() if self.p1_enabled else None
own.meter_back = snap.unknown_s > 0.0 and own.unknown_s <= 0.0
stale = float(self.o.get("stale_input_s", 15))
late = self._car_late_s # the verdict stands: it has aged since
if late is not None and self._car_late_mono is not None:
late += max(0.0, now - self._car_late_mono)
own.hold = late is not None and late < stale
if own.silent or (late is not None and late >= stale):
# The stale rule on the step's own age / own late (C23): a spare
# read from data the own age calls old starts or raises nothing.
own.spare_w = own.target_w = None
return own
async def _car_step_run(self, held, now, sun) -> None:
if held:
# EV-20 rig round 2 (PM): the charger missed a read for less than
# `stale_input_s`; the last trusted figure stands and nothing is
@@ -543,12 +912,14 @@ class CarMixin:
# ------------------------------------------- the car and the peak guard
def car_alarm_w(self):
"""The car's power for the guard's alarm path: Manual and (EV-20)
Solar, fresh, not stuck (`CarTracker.car_w_trusted`), and never above
what the read-back allows. None otherwise, and then the normal alarms
stand."""
"""The car's power for the guard's alarm path: Manual, and Solar only
while it can cut the car (EV-21, Q5: otherwise as Off), fresh, not
stuck (`CarTracker.car_w_trusted`), and never above what the
read-back allows. None otherwise, and then the normal alarms stand."""
if not self.car_controlled():
return None
if self.car_solar_mode() and not self.car_solar_can_cut():
return None
return self.car.car_w_trusted(self.car_now())
def _car_own_pause(self, mono) -> bool:
@@ -628,11 +999,15 @@ class CarMixin:
last = q["mono"]
if key != q["key"]:
self._car_bank(q)
q["key"], q["ws"], q["ws_p"] = key, 0.0, 0.0
q["key"], q["ws"], q["ws_p"], q["ws_b"] = key, 0.0, 0.0, 0.0
if key is not None and last is not None:
dt = min(max(mono - last, 0.0), 5.0)
if w is not None:
q["ws"] += float(w) * dt
if not self.car_solar_mode():
# EV-21: a Solar car is cut first, so a period is never
# banked as its own (N4); one it cannot cut is as Off.
q["ws_b"] = q.get("ws_b", 0.0) + float(w) * dt
elif wg is not None:
q["ws_p"] = q.get("ws_p", 0.0) + float(wg) * dt
q["mono"] = mono
@@ -642,7 +1017,7 @@ class CarMixin:
key = q["key"]
if key is None:
return
avg = q["ws"] / QUARTER_S
avg = q.get("ws_b", q["ws"]) / QUARTER_S
if avg < CAR_PEAK_MIN_W:
return
self.car_peak_q[key.astimezone(timezone.utc).isoformat()] = round(avg)
@@ -700,15 +1075,24 @@ class CarMixin:
"""After the guard has decided: does the car alone explain the excess?
`real_proj` is the projection WITH the car, whatever the guard saw."""
mono = self.car_now()
self._car_cut_tick(real_proj, guard, target_w, mono) # EV-21
self._car_sun_tick(mono) # EV-20: today's solar kWh
solar = self.car_solar_mode()
can = solar and self.car_solar_can_cut()
self._car_can = can # what grading saw (checks)
w = self.car_alarm_w()
# EV-15: the figure for grading only. Our own phase change holds the
# car at 0 A and the energy meter cannot corroborate it then, so for
# that bounded time its fresh, not stuck figure stands in.
own = (w is None or float(w) <= 0.0) and self._car_own_pause(mono)
# that bounded time its fresh, not stuck figure stands in. EV-21: in
# Solar only while it can cut the car.
own = (w is None or float(w) <= 0.0) and (can or not solar) \
and self._car_own_pause(mono)
wg = w
if w is None and own:
wg = self.car.car_w_paused(mono)
ramp = self._car_cut_ramp_w(mono) if can else None
if ramp is not None and ramp > float(wg or 0.0):
wg, own = ramp, True # EV-21: the cut's own ramp-down
self._car_quarter(real_proj, w, mono, wg)
self._car_session_tick(mono)
# EV-18 (owner 2026-11-19): a figure the meter contradicted grades no
@@ -733,7 +1117,16 @@ class CarMixin:
if contra or idle or (w is not None and float(w) <= 0.0
and not own):
graded = False
if self.car_cover:
if solar:
# EV-21 (Q5, OQ5, OQ8): graded out only while Solar can cut
# the car, and then no car-over row: the cut works. Else as
# Off; the row and notice say the car sets the peak.
explains = graded and can
wd = None if can else self.car.car_w_trusted(mono)
if wd is not None:
ex = float(real_proj.projected_w) - float(target_w)
over = ex > 0.0 and self.car_avg_w(real_proj, wd) >= ex
elif self.car_cover:
explains = over = graded
elif w is not None:
ex = float(real_proj.projected_w) - float(target_w)
+6 -3
View File
@@ -254,6 +254,7 @@ class CycleMixin:
stale_after = float(self.o.get("stale_input_s", 15))
late_s = self._readings_late(site_standing) # SAFETY-128
self._car_late_s = late_s # EV-20: Solar holds, then the stale rule
self._car_late_mono = self._now_mono # EV-51: when that verdict was read
self._late_zero = late_s is not None and late_s >= stale_after
# ⚠️ `any`, NOT the sole unit's. The hold exists so a single missed
# poll does not become a fault; a LATCHED inverter must still reach the
@@ -273,7 +274,7 @@ class CycleMixin:
# this cycle's. (DECISIONS/MAIN-orchestration-archive.md)
self.why_words = messages.why_waiting(bad_for)
self._why_waiting_since = now - timedelta(seconds=bad_for)
self._car_hold_kick() # EV-20: Solar counts from now
self._car_hold_kick(now) # EV-20: Solar counts from now
return
if late_s is not None and late_s < stale_after and self.inputs_ok \
and (self.auto or self.shadow) \
@@ -281,7 +282,7 @@ class CycleMixin:
and not (n_units > 1 and self.site_sign_wd.tripped):
self.reason = f"readings late {late_s:.0f}s" # SAFETY-128: hold
self.why_words = messages.why_late()
self._car_hold_kick() # EV-20: Solar holds its current
self._car_hold_kick(now) # EV-20: Solar holds its current
return
claims = []
@@ -399,7 +400,8 @@ class CycleMixin:
# `_peak_proj_real` keeps the quarter as the meter will bill it, for
# the car's own words. Only a fresh, trusted car reading is left out.
self._peak_proj_real = self._peak_proj
# EV-20: a Solar car exactly as a Manual car.
# EV-20/EV-21: a Solar car as a Manual car while Solar can cut it
# (`car_alarm_w` is None otherwise, so the car stays in, as Off).
if (self._peak_proj is not None and not self.car_cover
and self.car_controlled()):
self._peak_proj = self.car_exclude(self._peak_proj,
@@ -1069,6 +1071,7 @@ class CycleMixin:
await self.check_price_gap()
await self.check_charger()
await self.check_car_over()
await self.check_car_cut() # EV-21 (OQ5)
await self.check_car_release() # EV-20 (D3)
await self.check_car_start() # EV-20 (C1)
self.car_kick() # EV-04/20: in the background
+2
View File
@@ -1382,6 +1382,8 @@ def _car_solar_why(c, key):
o = getattr(c, "o", {}) or {}
if c.car_over: # D1
return _t("car.why.solar_over", a=f"{c.car_amps_now():.0f}")
if getattr(c, "car_cut_standing", lambda: False)(): # EV-21
return _t("car.why.solar_peak")
if w.hold:
return _t("car.why.solar_other")
if w.zero_owed:
+13
View File
@@ -190,6 +190,8 @@ T_CHARGER_UNREACH = "Charger not reachable"
T_CHARGER_UNREACH_NL = "Laadpaal onbereikbaar"
T_CAR_OVER = "Car over the peak limit"
T_CAR_OVER_NL = "Auto boven de piekgrens"
T_CAR_CUT = "Car lowered for the peak"
T_CAR_CUT_NL = "Auto verlaagd voor de piek"
T_CAR_RELEASE = "Car may still be charging"
T_CAR_START = "Charger kept its current"
T_CAR_START_NL = "Laadpaal hield haar stroom"
@@ -209,6 +211,7 @@ ID_NO_PRICES = "goodwe_no_prices"
ID_CHARGER_UNREACH = "goodwe_charger_unreachable"
ID_CAR_OVER = "goodwe_car_over"
ID_CAR_RELEASE = "goodwe_car_release"
ID_CAR_CUT = "goodwe_car_cut"
ID_CAR_START = "goodwe_car_start_current"
# PRICE-01: an earlier build raised a card with this id. Nothing raises it now;
# the add-on only dismisses it at start.
@@ -545,6 +548,15 @@ def row_car_over_solar(a_text) -> str:
return Bi(*_solar_over(a_text))
def car_cut() -> Notice:
"""EV-21 (OQ5): Solar cut the car first for the peak, and the charger
took it. Grey, once per charging session."""
return Notice(ID_CAR_CUT, INFO, T_CAR_CUT,
"Solar lowered the car for the peak.",
body_nl=f"{T_CAR_CUT_NL}. Zon verlaagde de auto voor de "
"piek.")
def car_release_failed() -> Notice:
"""EV-20 (D3): at shutdown in Solar the charger did not take 0 A, and the
inverters were released on time anyway. Taken down when the next start's
@@ -1894,6 +1906,7 @@ def samples() -> list:
charger_unreachable("09:12"),
car_over("16"),
car_over_solar("8"),
car_cut(),
car_release_failed(),
car_start_current("10"),
]
+2 -1
View File
@@ -348,7 +348,8 @@
"solar_zeroing": "The charger has not taken 0 A yet. The add-on tries again.",
"solar_zero_failed": "The charger did not take 0 A. Check it at the charger.",
"solar_refused": "The charger did not take the current. Press Solar to try again.",
"solar_over": "Solar charges the car at {a} A. This sets the peak."
"solar_over": "Solar charges the car at {a} A. This sets the peak.",
"solar_peak": "Solar lowered the car for the peak."
}
},
"peak": {
+2 -1
View File
@@ -302,7 +302,8 @@
"solar_zeroing": "De laadpaal nam 0 A nog niet over. De add-on probeert opnieuw.",
"solar_zero_failed": "De laadpaal nam 0 A niet over. Controleer ze aan de laadpaal.",
"solar_refused": "De laadpaal nam de stroom niet over. Druk op Zon om opnieuw te proberen.",
"solar_over": "Zon laadt de auto met {a} A. Dit bepaalt de piek."
"solar_over": "Zon laadt de auto met {a} A. Dit bepaalt de piek.",
"solar_peak": "Zon verlaagde de auto voor de piek."
}
},
"peak": {
+1 -1
View File
@@ -1,5 +1,5 @@
name: GoodWe RS485 Controller
version: "0.24.0"
version: "0.25.0"
slug: goodwe_controller
description: >-
Drives a GoodWe ES/BP battery inverter over its RS485 EMS port by sending it a
+40 -4
View File
@@ -5,6 +5,12 @@ writers (while stopped and in shadow too), a silent meter, shadow and Stop
toggles mid-sequence, Solar / Off / Manual changes; half in the production
cycle order. N1-N3, N5, N9, N10, N12-N14 and N16 on every step (N4 is
EV-21's; N6-N8, N11 and N15 are rows of test_ev20_*.py).
EV-21 (T50) adds house loads that take the period over the aim (the peak
cut) and the cover option toggled, and on every step: graded out only while
Solar can cut (N8/T35), no write above a standing cut (N6), one cut decision
per episode at a constant or falling excess (N10 of EV-21). A cut lowers past
the 30 s rule on purpose (T3), so EV-20's N5 counts no cut write.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
@@ -85,7 +91,7 @@ def fuzz_site(seed):
sim.ramp_w_s, sim.stop_delay_s = 300.0, 4.0
state = {"sun": rnd.uniform(3000, 11000),
"house": rnd.uniform(300, 2000)}
bad, counts, snap = [], {}, {}
bad, counts, snap, cuts = [], {}, {}, {}
seen = {"exit_since": None, "avail": None, "back": []}
def bump(k):
@@ -158,6 +164,12 @@ def fuzz_site(seed):
elif x < 0.0365:
await c.handle_action("car_sun_first", value=rnd.choice(
["batteries", "car"]))
elif x < 0.0395: # EV-21: a load over the aim
state["house"] = rnd.uniform(4000, 14000)
bump("excess")
elif x < 0.0400: # EV-21: the cover option
c.o["ev_batt_cover"] = not c.car_cover
bump("cover")
if p.ch.refuse is not None and rnd.random() < 0.02:
p.ch.refuse = None
# What the step of this second starts from (it runs after this, in
@@ -170,6 +182,21 @@ def fuzz_site(seed):
def on_cycle(p, c, t):
w, sim = c.car_solar, p.ch
r = c.car.reading
# EV-21: the cut's own checks, on every step.
st = getattr(c, "_cut", None) or {}
cuts[t] = st.get("cap")
if st.get("cap") is not None:
bump("cut")
key = (st.get("key"), st.get("since"), st.get("at"))
prev = seen.get("cut")
if prev is not None and prev[0] == key and st["cap"] < prev[1] \
and st.get("ex", 0.0) <= prev[2] + 1e-9:
bad.append((seed, t, "N10 (EV-21) a 2nd cut at a falling "
"excess", prev, st["cap"]))
seen["cut"] = (key, st["cap"], st.get("ex", 0.0))
if c.car_mode == "solar" and c.car_explains \
and not getattr(c, "_car_can", True):
bad.append((seed, t, "N8 (EV-21) graded out, Solar cannot cut"))
avail = bool(r is not None and r.available)
if avail and seen["avail"] is False:
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
@@ -231,6 +258,10 @@ def fuzz_site(seed):
bad.append((seed, x[0], "N2 select with the setpoint up", x))
log = [x for x in c.car_solar.log if x[0] == "current"]
for kind, a, t, ok in log:
# EV-21 N6: never above a cut that stands.
cap = cuts.get(t)
if cap is not None and a > cap + 1e-9:
bad.append((seed, t, "N6 (EV-21) a write above the cut", a, cap))
s = snap.get(t) or snap.get(t - 1)
if s is None:
continue
@@ -260,7 +291,10 @@ def fuzz_site(seed):
and not dec[i - 1][2]) else 1
if tries > carmode.MAX_TRIES:
bad.append((seed, t, "N14 more than 3 tries", a))
nz = [(t, a) for t, a, ok in dec if a > 0.0]
# EV-21: a cut's own write (at the cut's value) lowers past the 30 s
# rule on purpose (T3); every other change keeps it.
nz = [(t, a) for t, a, ok in dec if a > 0.0
and not (cuts.get(t) is not None and abs(a - cuts[t]) < 1e-9)]
for (t0, a0), (t1, a1) in zip(nz, nz[1:]):
if a1 != a0 and t1 - t0 < carmode.SOLAR_WRITE_S - 1e-9 \
and not [1 for t, a, ok in dec if t0 < t < t1 and a == 0.0]:
@@ -290,10 +324,12 @@ for seed in range(SITES):
n_sel, n_zero = tally["sel"], tally["zero"]
print(f" {SITES} sites x {STEPS_PER} steps, {n_writes} charger writes; "
f"disturbances {sorted(all_counts.items())}")
check(f"T54: N1, N2, N3, N5, N9, N10, N12, N14 and N16 hold on every step "
check(f"T54: N1, N2, N3, N5, N9, N10, N12, N14 and N16 hold on every step; "
f"EV-21 T50: N6, N8 and one cut per episode "
f"({all_bad[:3]})", not all_bad)
need = ("spare", "outage", "ha", "unplug", "refuse", "refuse_exit", "other",
"other_out", "meter", "stop", "shadow", "mode")
"other_out", "meter", "stop", "shadow", "mode", "excess", "cover",
"cut")
check(f"T54: each disturbance happened, mid-sequence ones too "
f"({[k for k in need if not all_counts.get(k)]})",
all(all_counts.get(k) for k in need)
+57 -48
View File
@@ -1,4 +1,5 @@
"""EV-20: the peak guard treats a Solar car as a Manual car; Solar kWh; what
"""EV-20: the peak guard and a Solar car (EV-21: as Off where Solar cannot cut
it, as Manual's grading otherwise); Solar kWh; what
stays unchanged; the strings, docs and settings; the write seam (T21, T22,
T47-T52, T55, T57-T60).
`python3 -B test_ev20_guard.py`
@@ -38,7 +39,8 @@ from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E40
# =========================================================================== #
print("\n8. THE PEAK GUARD: A SOLAR CAR IS A MANUAL CAR (T21, T22, T47, T48)")
print("\n8. THE PEAK GUARD: A SOLAR CAR SOLAR CANNOT CUT IS OFF'S (T21, T22, "
"T47, T48; EV-21)")
# =========================================================================== #
ALARMS = S.ALARMS
@@ -48,17 +50,12 @@ def twin(mode, **kw):
**kw)
def manual_twin(rs, **kw):
"""The Manual twin of a Solar run: the same plant and events, Manual with
its writer held still, and Solar's own writes put on the charger at the
same seconds, so both runs have the same charger trace and only the mode
differs for the peak guard."""
def off_twin(rs, **kw):
"""EV-21: the Off twin of a Solar run: the same plant and events, and
Solar's own writes put on the charger at the same seconds. Where Solar
cannot cut the car (another writer, Stop, shadow, a safety stop), the
alarm path, the banking and the guard are this twin's (Q5, OQ8, C2)."""
ev = dict(kw.pop("events", None) or {})
def inert(p, c):
async def nop(*a, **k):
return None
c.car_writer.step = nop
rep_ = {}
for t_sim, what, v, _pw, _sp in rs["sim"].log:
rep_.setdefault(int(round(t_sim)), []).append((what, v))
@@ -67,13 +64,23 @@ def manual_twin(rs, **kw):
for what, v in acts:
(p.ch.set_current if what == "current" else p.ch.set_phases)(v)
ev[t] = both(ev[t], put) if t in ev else put
ev[0] = both(ev[0], inert) if 0 in ev else inert
return twin("manual", events=ev, **kw)
return twin("off", events=ev, **kw)
def guard_view(r, t0=0):
return [(x["t"], x["explains"], x["over"], tuple(x["red"]),
x["alarm_w"] is None) for x in r["trace"] if x["t"] >= t0]
def alarm_view(r, t0=0):
"""EV-21: the alarm path only (car_explains, red rows, the car figure);
the car-over row is display and shows when Solar cannot cut (OQ5)."""
return [(x["t"], x["explains"], tuple(x["red"]), x["alarm_w"] is None)
for x in r["trace"] if x["t"] >= t0]
def alarms_of(r):
return [(t, n) for t, n in r["raised"] if n in ALARMS]
def same_alarms(a, b):
return len(a) == len(b) and all(abs(x[0] - y[0]) <= 2 and x[1] == y[1]
for x, y in zip(a, b))
def notes(r):
@@ -88,44 +95,45 @@ for cover in (True, False):
opts={"ev_phases": "3", "ev_batt_cover": cover},
events={600: lambda p, c: p.ch.set_current(16)})
rs = twin("solar", **dict(kw))
rm = manual_twin(rs, **dict(kw))
gs, gm = guard_view(rs, 640), guard_view(rm, 640)
rm = off_twin(rs, **dict(kw))
gs, gm = alarm_view(rs, 640), alarm_view(rm, 640)
diff = [(a, b) for a, b in zip(gs, gm) if a[1:] != b[1:]]
check(f"T21 (b{'' if cover else ', c'}) cover {'on' if cover else 'off'}:"
f" another writer's 16 A in Solar is graded, shown and notified as "
f"the Manual car at 16 A, every cycle from 640 s ({len(diff)} "
f" another writer's 16 A in Solar (Solar cannot cut it) is graded "
f"as the Off twin, every cycle from 640 s (EV-21; {len(diff)} "
f"differ: {diff[:2]})", not diff)
ns, nm = notes(rs), notes(rm)
check(f"T21 (b) cover {'on' if cover else 'off'}: the same notices at the "
f"same seconds +2 s, never silent ({ns} vs {nm})",
len(ns) == len(nm) and all(abs(a[0] - b[0]) <= 2 and a[1] == b[1]
for a, b in zip(ns, nm))
and (ns or any(x[2] for x in gs)))
check(f"T21: the car's banked quarters are the Manual twin's "
ns, nm = alarms_of(rs), alarms_of(rm)
over_s = [t for t, n in rs["raised"] if n == messages.ID_CAR_OVER]
check(f"T21 (b) cover {'on' if cover else 'off'}: the Off twin's alarms "
f"at the same seconds +2 s, never silent ({ns} vs {nm}); the "
f"car-over note shows, as Solar cannot cut ({over_s[:1]})",
same_alarms(ns, nm) and bool(ns) and bool(over_s))
check(f"T21: the car's banked quarters are the Off twin's "
f"({rs['c'].car_peak_q} vs {rm['c'].car_peak_q})",
rs["c"].car_peak_q == rm["c"].car_peak_q)
if not cover:
pj = [(round(a["proj"] or 0), round(b["proj"] or 0))
for a, b in zip(rs["trace"], rm["trace"]) if a["t"] >= 640
and round(a["proj"] or 0) != round(b["proj"] or 0)]
check(f"T21 (c): with the cover off, the guard's own projection "
f"(the car left out) is the Manual twin's ({pj[:2]})", not pj)
check(f"T21 (c): with the cover off and Solar unable to cut, the "
f"guard keeps the car in, as the Off twin (Q-A; {pj[:2]})",
not pj)
# T21 (a): car_cycle itself, fed the same projection, guard and reading on
# two Controllers that differ only in the mode (the twins of (c), now).
cs, cm = rs["c"], rm["c"]
proj_s, guard_s = cs._peak_proj_real, cs.peak_guard
same_in = (proj_s == cm._peak_proj_real
and repr(guard_s) == repr(cm.peak_guard)
and cs.car.reading == cm.car.reading)
cs.car_cycle(proj_s, guard_s, 3400.0, None)
cm.car_cycle(proj_s, guard_s, 3400.0, None)
check(f"T21 (a): car_cycle on the same projection, guard and reading gives "
f"the same car_alarm_w, car_explains and car_over in Solar and Manual "
f"(inputs equal {same_in}; {cs.car_alarm_w()} {cs.car_explains} "
f"{cs.car_over} vs {cm.car_alarm_w()} {cm.car_explains} {cm.car_over})",
same_in and (cs.car_alarm_w(), cs.car_explains, cs.car_over)
== (cm.car_alarm_w(), cm.car_explains, cm.car_over)
and cs.car_alarm_w() is not None)
check(f"T21 (a): car_cycle on the same projection and reading gives the "
f"same car_alarm_w (None) and car_explains in Solar, under another "
f"writer, as in Off (EV-21, C2; inputs equal {same_in}; "
f"{cs.car_alarm_w()} {cs.car_explains} vs {cm.car_alarm_w()} "
f"{cm.car_explains})",
same_in and (cs.car_alarm_w(), cs.car_explains)
== (cm.car_alarm_w(), cm.car_explains)
and cs.car_alarm_w() is None)
over_note = [x for x in rs["plant"].notes if x[1] == messages.ID_CAR_OVER]
check("T21 D1: Solar's car-over notice reads 'Solar charges the car at 16 A' "
"(the charger's current), never Manual's stored value",
@@ -145,13 +153,14 @@ for name, fn, opts in (("Stop (auto)", lambda p, c: setattr(c, "auto", False),
opts=dict({"ev_phases": "3"}, **opts),
events={500: fn, 600: lambda p, c: p.ch.set_current(16)})
rs = twin("solar", **dict(kw))
rm = manual_twin(rs, **dict(kw))
gs, gm = guard_view(rs, 640), guard_view(rm, 640)
rm = off_twin(rs, **dict(kw))
gs, gm = alarm_view(rs, 640), alarm_view(rm, 640)
diff = [(a, b) for a, b in zip(gs, gm) if a[1:] != b[1:]]
check(f"T21 (d) [{name}]: graded and shown as the Manual twin each cycle "
f"({len(diff)} differ: {diff[:1]}); notices "
f"{notes(rs)} vs {notes(rm)}",
not diff and [n for _, n in notes(rs)] == [n for _, n in notes(rm)])
check(f"T21 (d) [{name}]: graded as the Off twin each cycle (EV-21; "
f"{len(diff)} differ: {diff[:1]}); alarms "
f"{alarms_of(rs)} vs {alarms_of(rm)}; banked as Off",
not diff and same_alarms(alarms_of(rs), alarms_of(rm))
and rs["c"].car_peak_q == rm["c"].car_peak_q)
# T22: EV-15 shapes in Solar: Solar's own 3 -> 1 sequence and own 0 A pause
# with both batteries at the reserve.
@@ -202,15 +211,15 @@ for T in (615, 640, 680):
opts={"ev_phases": "3"},
events={T: lambda p, c: p.ch.set_current(16)})
rs = twin("solar", **dict(kw))
rm = manual_twin(rs, **dict(kw))
gs, gm = guard_view(rs, T), guard_view(rm, T)
rm = off_twin(rs, **dict(kw))
gs, gm = alarm_view(rs, T), alarm_view(rm, T)
diff = [(a, b) for a, b in zip(gs, gm) if a[1:] != b[1:]]
own = [x["t"] for x in rs["trace"] if x["t"] >= T and x["own"]]
z = [t for t, a, _ in cur_writes(rs) if a == 0.0]
check(f"T47 [T={T}]: Solar's own 0 A at {z[:1]}; the other writer's car "
f"never counts as Solar's own pause (own-pause seconds from T: "
f"{own[:3]}), rows and car_explains as the Manual twin "
f"({len(diff)} differ: {diff[:1]})",
f"{own[:3]}), rows and car_explains as the Off twin (EV-21; "
f"{len(diff)} differ: {diff[:1]})",
bool(z) and not own and not diff)
# Solar's own pause is graded as its own for at most OWN_PAUSE_MAX_S.
kw = dict(house=const(500.0), sun=step_fn((300, 0.0), base=7000.0), dur=1200,
+9 -3
View File
@@ -218,10 +218,16 @@ check(f"T46: Solar starts on 1 phase (select at the start), then another "
s46[:1] and s46[0][2] == 1
and not [x for x in s46 if 140 < x[0] < 700])
low = [x for x in w46 if 140 < x[0] < 700]
# EV-21: with both batteries at the cut-out, the other writer's 3 phases
# take the period over the aim, so Solar's peak cut lowers the car first,
# within 1 cycle and at 690 W/A (EV-21 T34 (ii)); the 6 A hold and the pause
# follow. Every write in the stretch lowers; none waits for PHASE_GAP_S.
six = [x for x in low if x[1] == 6.0]
check(f"T46 (a)(b): the arithmetic uses the 3 phases the car draws on, and a "
f"lower current (the 6 A hold, the pause) is written within the 30 s "
f"rule, never blocked by PHASE_GAP_S ({w46})",
low and low[0][1] == 6.0 and low[0][0] <= 171
f"lower current (EV-21's cut, the 6 A hold, the pause) is written "
f"within the 30 s rule, never blocked by PHASE_GAP_S ({w46})",
low and six and six[0][0] <= 171 and low[0][0] <= 171
and all(b[1] < a[1] for a, b in zip(low, low[1:]))
and [a for _, a, _ in low][-1:] == [0.0])
imp46 = sum(max(0.0, x["grid"]) for x in r46["trace"]
if x["t"] > 140 and x["sp"] > 0)
+406
View File
@@ -0,0 +1,406 @@
"""EV-21: Solar's car is cut first for the quarter peak. The amount, when it
comes (at once or after the 15 s wait), and what counts as headroom.
`python3 -B test_ev21.py`
Rows T1-T3, T7-T10, T12-T21, T28 and T35 of reports/EV-21-test-plan.md, on
the real Controller (`tools/ev20_sun.py` through `tools/ev21_kit.py`). The
second period runs 900-1800; a step at t = 960 is elapsed 60 s. "Within 1
cycle": the writer step that follows the cycle that first sees the cut due,
logged at that cycle's second (`race` runs: one second later). Every run
also carries the Never checks of `ev21_kit.never` (N1, N2, N6, T35).
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import os
import sys
import types
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode, ctl_car, peakguard # noqa: E402
import ev20_sun as S # noqa: E402
from chargersim import SimCharger # noqa: E402
from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402
from ev21_kit import (AIM, CUT_WAIT_S, after, alarms, first_alarm, # noqa: E402
merge, never, quarter_avg, shape, twin, drive,
_cutamps, set_resp, notes, replay_twin, near_end)
from app import messages # noqa: E402
n_log0 = LOG.mark()
def zero_at(r, t0):
"""The second of the first 0 A write at or after t0, or None."""
z = [t for t, a, _ in after(r, t0) if a == 0.0]
return z[0] if z else None
def first_want(r, t0):
w = [x["t"] for x in r["rec"].rows if x["t"] >= t0 and (x["want"] or 0) > 0]
return w[0] if w else None
def banked(r, q0=900):
return any(k.startswith(S.rig.BASE.replace(minute=15).isoformat()[:16])
for k in r["c"].car_peak_q) if q0 == 900 else bool(
r["c"].car_peak_q)
# =========================================================================== #
print("\n1. THE CUT AMOUNT (T1)")
# =========================================================================== #
cut = _cutamps()
rows = [((6900, 2700, 3), 6.0), ((6900, 3800, 3), 0.0), ((2300, 800, 1), 6.0),
((2300, 920, 1), 6.0), ((2300, 921, 1), 0.0),
((11040, 2498, 3), 12.0), ((11040, 998, 3), 14.0),
((3680, 1, 1), 15.0)]
got = [(a, cut(*a)) for a, _ in rows]
check(f"T1: floor((car - excess) / (230 x n)), 0 under 6 A: {got}",
all(g == want for (_a, g), (_b, want) in zip(got, rows)))
check(f"T1: a car at a 10 A setpoint drawing 2530 W (253 V), excess 100 W, "
f"stays at 10 A, never above the setpoint ({cut(2530, 100, 1, 10.0)})",
cut(2530, 100, 1, 10.0) == 10.0)
check(f"T1: excess <= 0 is no cut ({cut(6900, 0, 3)}, {cut(6900, -50, 3)})",
cut(6900, 0, 3) is None and cut(6900, -50, 3) is None)
check(f"T1: an unknown car figure cuts to 0 A (OQ2) ({cut(None, 500, 3)})",
cut(None, 500, 3) == 0.0)
# =========================================================================== #
print("\n2. SHAPE C: NOTHING CAN GIVE, THE CUT AT ONCE (T2, T28)")
# =========================================================================== #
tw_c = twin("C", dur=1800)
q_tw = quarter_avg(tw_c, 900)
for first in ("car", "batteries"):
for race in (False, True):
tag = f"{first} first{', race' if race else ''}"
r = shape("C", first=first, race=race, dur=1800)
w = after(r, 960)
z = zero_at(r, 960)
q = quarter_avg(r, 900)
check(f"T2 [{tag}]: the first write after the step is 0 A within 1 "
f"cycle, no 6 A first ({w[:3]})",
bool(w) and w[0][1] == 0.0 and w[0][0] <= 960 + int(race))
check(f"T2 [{tag}]: the period lands {q:.0f} W <= {AIM:.0f} W; the "
f"Off twin {q_tw:.0f} W > it", q <= AIM and q_tw > AIM)
check(f"T2 [{tag}]: nothing banked as the car's "
f"({r['c'].car_peak_q})", not r["c"].car_peak_q)
if first == "car":
# T28 is on the plan's shapes (Car first). Batteries first: see
# the dev report's Findings (EV-18's grading in the step's cycle).
check(f"T28 [C, {tag}]: no peak alarm or red row while the "
f"house alone is under the aim ({alarms(r, 900)}, "
f"{[x['t'] for x in r['trace'] if x['red'] and x['t'] >= 900][:3]})",
not alarms(r, 900)
and not [x for x in r["trace"] if x["red"]
and x["t"] >= 900])
never(f"T2 [{tag}]", r)
note = notes(r, messages.ID_CAR_CUT) if hasattr(messages, "ID_CAR_CUT") \
else []
check(f"OQ5: one grey note 'Solar lowered the car for the peak.' ({note})",
len(note) == 1 and messages.car_cut().body
== "Solar lowered the car for the peak.")
check("OQ5: no car_over row and no CAR_OVER_PEAK while the cut works",
not [x for x in r["trace"] if x["over"]]
and not notes(r, messages.ID_CAR_OVER))
# =========================================================================== #
print("\n3. THE 30 s GATE AND THE 6 A HOLD NEVER DELAY A CUT (T3, T27)")
# =========================================================================== #
def stamp(p, c):
c.car_solar.nonzero_at = p.t # a non-zero write 2 s before the step
for race in (False, True):
r = shape("C", step=1200, house_w=800.0, race=race, dur=1500,
events={1198: stamp})
w = after(r, 1200)
check(f"T3 [{'race' if race else 'step'}]: excess about 2700 W at elapsed "
f"300 s, a write 2 s before: the partial cut 6 A goes within 1 "
f"cycle, not at the 30 s gate ({w[:3]})",
bool(w) and w[0][1] == 6.0 and w[0][0] <= 1200 + int(race))
never(f"T3 [{'race' if race else 'step'}]", r)
# T27: Solar holds 6 A since t-100 (a cloud), both at the cut-out, then a
# house step heads the period over: 0 A within 1 cycle, not after the hold.
sun27 = step_fn((960, 900.0 + 4140.0), (1060, 0.0), base=7900.0)
r = drive(step_fn((1060, 3000.0), base=900.0), sun27, dur=1300, first="car",
phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"})
held6 = [x["t"] for x in r["trace"] if 1000 <= x["t"] < 1060
and x["a"] == 6.0]
w = after(r, 1060)
check(f"T27: Solar held 6 A before the step ({held6[:1]}..{held6[-1:]}); the "
f"step writes 0 A within 1 cycle ({w[:2]})",
len(held6) > 30 and bool(w) and w[0] == (1060, 0.0, True))
# =========================================================================== #
print("\n4. A CAR THAT DRAWS NOTHING, A HOUSE OVERLOAD (T7, T8, T9)")
# =========================================================================== #
H9 = step_fn((960, 9000.0), base=900.0)
# (i) Solar's own pause at 0 A (too little sun ever), (ii) an idle car (B).
for name, kw in (("own 0 A pause", {}),
("idle car, state B", {"events": {5: lambda p, c:
p.ch.car_full()}})):
r = drive(H9, const(900.0), dur=1100, first="car", phases=3,
socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"}, **kw)
o = drive(H9, const(900.0), dur=1100, first="car", phases=3, mode="off",
socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"}, **kw)
a_s, a_o = first_alarm(r, 900), first_alarm(o, 900)
check(f"T7 [{name}]: no cut write ({after(r, 960)}), car_explains never "
f"True, the alarm at the Off twin's second ({a_s} vs {a_o})",
not [x for x in after(r, 960) if x[1] > 0 or x[0] > 961]
and not any(x["explains"] for x in r["trace"])
and a_s is not None and a_o is not None and abs(a_s - a_o) <= 2)
class Draws50(SimCharger):
"""EV-10's shape: a car in state C that draws 50 W at any current."""
def target_w(self):
return 50.0 if super().target_w() > 0 else 0.0
for name, kw, sim_cls in (
("T8: a trusted 50 W car in state C",
dict(phases=3, opts={"ev_phases": "3"}), Draws50),
("T9: the car on 1 phase, the house alone 9 kW",
dict(phases=1, opts={"ev_phases": "1"}), SimCharger)):
sun = step_fn((960, 0.0), base=900.0 + 1610.0 + 100.0) \
if sim_cls is SimCharger else step_fn((960, 0.0), base=7900.0)
r = drive(H9, sun, dur=1100, first="car", socs={"a": 10.0, "b": 10.0},
sim=sim_cls(setpoint_a=0), **kw)
o = drive(H9, sun, dur=1100, first="car", socs={"a": 10.0, "b": 10.0},
mode="off", sim=sim_cls(setpoint_a=7), **kw)
w = after(r, 960)
a_s, a_o = first_alarm(r, 900), first_alarm(o, 900)
check(f"{name}: 0 A within 1 cycle ({w[:2]}); the alarm at the Off "
f"twin's second +2 ({a_s} vs {a_o}); car_explains never True",
bool(w) and w[0][1] == 0.0 and w[0][0] <= 961
and a_s is not None and a_o is not None and a_s - a_o <= 2
and not any(x["explains"] for x in r["trace"] if x["t"] >= 960))
never(name[:3], r)
# =========================================================================== #
print("\n5. REAL HEADROOM: THE 15 s WAIT (T10), NONE WITHOUT IT (T12-T15)")
# =========================================================================== #
for race in (False, True):
tag = "race" if race else "step"
r = shape("W", race=race, dur=1100)
fw = first_want(r, 960)
z = zero_at(r, 960)
early = [x for x in after(r, 960) if x[1] < 6.0 and x[0] < (fw or 0)
+ CUT_WAIT_S]
check(f"T10 [{tag}]: the guard first wants power at {fw}; the cut (0 A: "
f"car 6900 W less an excess over 6900 W) at {z}, 15-16 s later, "
f"not before ({after(r, 960)[:3]})",
fw is not None and z is not None
and fw + CUT_WAIT_S <= z <= fw + CUT_WAIT_S + 1 + int(race)
and not early)
never(f"T10 [{tag}]", r)
check(f"T28 [W, {tag}]: no peak alarm or red row, nothing banked "
f"({alarms(r, 900)}, {r['c'].car_peak_q})",
not alarms(r, 900) and not r["c"].car_peak_q
and not [x for x in r["trace"] if x["red"] and x["t"] >= 900])
r = shape("S", race=race, dur=1100)
z = zero_at(r, 960)
check(f"T12 [{tag}]: saturated (house 16 kW): the cut at once ({z})",
z is not None and z <= 960 + int(race))
r = shape("F", race=race, dur=1100,
sun_w=None, events={})
z = zero_at(r, 960)
check(f"T13 [{tag}]: floor-limited (19 % against a 20 % reserve): the "
f"cut at once ({z}; {after(r, 900)[:3]})",
z is not None and z <= 960 + int(race))
never(f"T13 [{tag}]", r)
# T12, EV-05 r3: the car at 16 A on 3 phases, sun 13 kW, the house steps to
# H at elapsed 5 s; the car-Off twin (no car) lands at or under the aim.
for H in (25900.0, 25950.0):
kw = dict(dur=1810, first="car", phases=3, socs={"a": 60.0, "b": 60.0},
opts={"ev_phases": "3"})
house = step_fn((905, H), base=900.0)
r = drive(house, const(13000.0), **kw)
o = drive(house, const(13000.0), plug=False, mode="off", **kw)
q, qo = quarter_avg(r, 900), quarter_avg(o, 900)
check(f"T12 [H={H:.0f}]: the car-Off twin lands {qo:.0f} W <= aim, the "
f"Solar car's period {q:.0f} W too (cut at {zero_at(r, 905)})",
qo <= AIM and q <= AIM)
class RefusesA(S.SunPlant):
"""Battery A never gives (the plant gives min(cmd, 0))."""
def batt_of(self, u, at):
w = super().batt_of(u, at)
return min(w, 0.0) if u == "a" else w
def refuse_a(p, c):
c.inverters[0].refused = 1
# A's refusal and B's 5 s response from 900 (after Solar's own start, which
# PM Q2 / formal C14 would otherwise cut on its start blip).
ev14 = {t: refuse_a for t in range(900, 1100)}
ev14[901] = lambda p, c: (refuse_a(p, c), set_resp(5.0)(p, c))
r = shape("W", events=ev14, plant_cls=RefusesA, dur=1100, rows=False)
z = zero_at(r, 960)
check(f"T14: N=2, A refuses to give, B has 4600 W: the excess is beyond "
f"what B can add, so the cut at once ({z}), never after the wait",
z is not None and z <= 961)
def refuse_n1(p, c):
c.batt_refused, c.batt_refused_at = 1, p.t
r = shape("W", n=1, house_w=900.0, dur=1100, rows=False,
events=merge({t: refuse_n1 for t in range(1, 1100)}, 0,
lambda p, c: (refuse_n1(p, c), set_resp(20.0)(p, c))))
z = zero_at(r, 960)
r0 = shape("W", n=1, house_w=900.0, dur=1100)
z0 = zero_at(r0, 960)
check(f"T15: N=1, the sole unit refuses to give: the cut at once ({z}); the "
f"same unit giving waits ({z0})",
z is not None and z <= 961 and z0 is not None and z0 >= 960 + 15)
# =========================================================================== #
print("\n6. WHAT COUNTS AS HEADROOM (T16, T17, T18)")
# =========================================================================== #
c = r0["c"]
G = peakguard.PeakDecision(engaged=True, floor_w=1.0, ceiling_w=3500.0,
ceiling_from="cap", wanted_w=4000.0)
fake = types.SimpleNamespace(
inverters=[types.SimpleNamespace(name="inverter-a", batt=2500.0, soc=60.0,
bms_soc_floor=10.0, refused=0,
sign_wd=types.SimpleNamespace(
tripped=False),
rating_w=lambda: 5000.0),
types.SimpleNamespace(name="inverter-b", batt=2500.0, soc=60.0,
bms_soc_floor=10.0, refused=0,
sign_wd=types.SimpleNamespace(
tripped=False),
rating_w=lambda: 4600.0)],
site_batt_w=5000.0, circ_wd=types.SimpleNamespace(tripped=False),
site_sign_wd=types.SimpleNamespace(tripped=False), batt_refused=0,
modes_on=False)
head = getattr(ctl_car.CarMixin, "_car_cut_headroom", None)
h_free = head(fake, G) if head else "absent"
h_able = head(fake, __import__("dataclasses").replace(G, able_w=4600.0)) \
if head else "absent"
check(f"T16 (a): two units above the cut-out giving 2500 W each: headroom "
f"{h_free} W with able_w None, {h_able} W with the guard's able_w 4600 "
f"(so the cut comes at once)", h_free == 4600.0 and h_able == 0.0)
rep = __import__("dataclasses").replace
h_sat = head(fake, rep(G, saturated=True)) if head else "absent"
h_flim = head(fake, rep(G, floor_limited=True)) if head else "absent"
check(f"T12/T13 (unit): the same batteries with real watts to add count as "
f"adding nothing while the guard is saturated ({h_sat}) or "
f"floor-limited ({h_flim}): the cut at once",
h_sat == 0.0 and h_flim == 0.0)
fake.inverters[0].refused = 1
h_ref = head(fake, G) if head else "absent"
fake.inverters[0].refused = 0
fake.inverters[0].sign_wd.tripped = True
h_sig = head(fake, G) if head else "absent"
fake.inverters[0].sign_wd.tripped = False
fake.inverters[0].batt = None
h_none = head(fake, G) if head else "absent"
check(f"T16/T17/T21: a refusing unit adds nothing ({h_ref}), a sign-stopped "
f"one nothing ({h_sig}); an unknown battery figure is None, the cut at "
f"once ({h_none})", h_ref == 2100.0 and h_sig == 2100.0
and h_none is None)
r = shape("W", socs={"a": 19.0, "b": 60.0}, dur=1100,
opts={"peak_soc_floor": 20})
z = zero_at(r, 960)
rw = r["rec"].at(961) or {}
check(f"T16 (b): A at 19 % (held at its reserve), B at 60 %: the cut at "
f"once ({z}); floor-limited at the cut: {rw.get('flim')}",
z is not None and z <= 961)
# T17: a unit's sign stop while a cut is due: Solar cannot write, so it
# cannot cut: the alarm and banking as Off.
for n in (1, 2):
def trip(p, c):
c.inverters[0].sign_wd.tripped = True
kw = dict(n=n, dur=1100, events={955: trip})
r = shape("C", **kw)
o = replay_twin(r, "C", **kw)
a_s, a_o = first_alarm(r, 950), first_alarm(o, 950)
check(f"T17 [N={n}]: a sign stop: car_explains never True, the alarm at "
f"the Off twin's second, the same charger writes replayed "
f"({a_s} vs {a_o}; Solar's way-out {after(r, 950)[:1]}), nothing banked "
f"({r['c'].car_peak_q})",
not any(x["explains"] for x in r["trace"] if x["t"] >= 955)
and (a_s == a_o or (a_s is not None and a_o is not None
and abs(a_s - a_o) <= 2))
and r["c"].car_peak_q == o["c"].car_peak_q)
# T18: battery modes: A switched Off counts for nothing; both Off: at once.
def mode_off(*units):
def f(p, c):
from app import packmode
from app.store import unit_key
for u in units:
c.store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = False
return f
ra = shape("W", house_w=900.0, dur=1100,
events={0: lambda p, c: (set_resp(20.0)(p, c),
mode_off("a")(p, c))})
rb = shape("W", house_w=900.0, dur=1100,
events={0: lambda p, c: (set_resp(20.0)(p, c),
mode_off("a", "b")(p, c))})
za, zb = zero_at(ra, 960), zero_at(rb, 960)
check(f"T18: A switched Off counts for nothing (cut at {za}, a partial cut "
f"or a wait on B's 4600 W); both Off: at once ({zb}; "
f"{after(rb, 960)[:2]})",
bool(after(ra, 960)) and bool(after(rb, 960))
and after(rb, 960)[0][0] <= 961)
# =========================================================================== #
print("\n7. THE PERIOD'S LAST 120 s (T19, T20) AND NO BATTERY FIGURE (T21)")
# =========================================================================== #
r = near_end(1700)
fw = first_want(r, 1700)
z = zero_at(r, 1700)
check(f"T19: a step 100 s before the end with real headroom: the cut within "
f"1 cycle of the first want ({fw} -> {z}; {after(r, 1690)[:2]})",
fw is not None and z is not None and z <= fw + 1)
never("T19", r)
r = near_end(1670)
fw = first_want(r, 1670)
cuts = [t for t, a, _ in after(r, 1670) if a < 10.0]
check(f"T20: first want at {fw} (130 s left): the cut at 1680 (120 s left), "
f"not at 1669-1679 and not at 1685 ({cuts[:2]})",
fw in (1670, 1671) and bool(cuts) and cuts[0] == 1680
and fw + CUT_WAIT_S > 1681)
for name, units in (("(a) A's figure None", {"a"}),
("(b) both None", {"a", "b"})):
for past in (False, True):
t_nan = 959 if not past else 930
def nan(p, c, units=units):
p.batt_nan = set(units)
r = shape("W", dur=1100, events={0: set_resp(20.0), t_nan: nan})
z = zero_at(r, 960)
check(f"T21 {name}, {'past' if past else 'inside'} the 15 s "
f"inputs-missing hold: the cut within 2 s of the excess, never "
f"after the wait ({z}; {after(r, 955)[:2]})",
z is not None and z <= 962)
# =========================================================================== #
print("\n8. NO TRACEBACK (N11)")
# =========================================================================== #
tb = LOG.tracebacks(n_log0)
check(f"N11: no traceback in this file's runs ({tb[:1]})", not tb)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)
+183
View File
@@ -0,0 +1,183 @@
"""EV-21 fix round 1 (formal round 4): C14 and C15, and pins of the code's
current answer to three questions the owner has not ruled (C16, C18, Q1's
other writer). `python3 -B test_ev21_fix1.py`
- C14 (PM Q2): slowing a battery charge counts as the batteries taking more,
so a cut is due while the batteries charge at least the excess: after
CUT_WAIT_S with real headroom, at once with the cover off.
- C15 (PM Q1): the 2 s grace of a lowering on its way is once per value; a
retry of a refused cut gets none.
- C16, C18, Q1-other-writer: what the code does today, pinned so a ruling
that changes it shows here. These are not rulings.
The real Controller on `tools/ev20_sun.py` through `tools/ev21_kit.py`.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import dataclasses
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import ctl_car # noqa: E402
import ev20_sun as S # noqa: E402
from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402
from ev21_kit import (AIM, after, drive, shape, _mode, set_resp, # noqa: E402
merge, never)
n_log0 = LOG.mark()
CUT_WAIT_S = getattr(ctl_car, "CUT_WAIT_S", 15.0)
def tick_case(cover, elapsed):
"""`_car_cut_tick` itself, on a real Controller: Shape W just before its
step (Solar runs the car at 10 A on 3 phases, both batteries at 60 %),
then the batteries set to CHARGE 3 kW and a projection with the car
whose excess is 1 kW at `elapsed` s; the guard does not engage
(battery + excess = -2 kW). Returns (cap, wait) after the first tick
and the cap after a second tick CUT_WAIT_S later."""
# The run itself with the cover on: with it off, Solar's own start at
# 120 s already meets C14's rule (see the dev report's Findings).
r = shape("W", dur=959)
c = r["c"]
c.o["ev_batt_cover"] = cover
t = c.car_now()
for inv in c.inverters:
inv.batt = -1500.0 # 3 kW of charge, site sum
c._car_cut_meter_fresh = lambda: True # the meter is fresh (N9 aside)
left = 900.0 - elapsed
proj = dataclasses.replace(
c._peak_proj_real, elapsed_s=elapsed,
projected_w=AIM + 1000.0 * left / 900.0)
guard = dataclasses.replace(
c.peak_guard, engaged=False, floor_w=None, saturated=False,
floor_limited=False, blind=None, wanted_w=-2000.0, able_w=None,
held=())
c._cut = c._cut_fresh(None)
c.car_now = lambda: t
c._car_cut_tick(proj, guard, AIM, t)
first = (c._cut["cap"], c._cut["wait"], c._cut["since"])
c.car_now = lambda: t + CUT_WAIT_S
c._car_cut_tick(proj, guard, AIM, t + CUT_WAIT_S)
return first, c._cut["cap"], c.site_batt_w
# =========================================================================== #
print("\n1. C14: A CUT IS DUE WHILE THE BATTERIES CHARGE (PM Q2)")
# =========================================================================== #
for name, cover, el, at_once in (
("cover on, real headroom", True, 300.0, False),
("cover off (OQ3)", False, 300.0, True),
("the last 120 s", True, 800.0, True)):
first, later, batt = tick_case(cover, el)
cap0, wait0, since0 = first
if at_once:
ok = cap0 is not None
how = "at once"
else:
ok = cap0 is None and since0 is not None and later is not None
how = f"after the {CUT_WAIT_S:.0f} s wait"
check(f"C14 [{name}]: the batteries charge {-(batt or 0):.0f} W against "
f"an excess of 1000 W; the cut is due all the same, {how} (first "
f"tick cap {cap0}, wait {wait0}, episode since {since0}; "
f"{CUT_WAIT_S:.0f} s later cap {later})", ok)
# =========================================================================== #
print("\n2. C15: THE 2 s GRACE IS ONCE PER VALUE (PM Q1)")
# =========================================================================== #
def ignore(p, c):
p.ch.refuse = "ignore"
r = shape("C", dur=1120, beside=True, events={959: ignore})
sends = [(t, v) for t, e, v in r["plant"].sets if e == S.SET and t >= 959]
rec = r["rec"].rows
t_first = sends[0][0] if sends else None
late = [x["t"] for x in rec if t_first is not None
and x["t"] > t_first + 2.0 and x["can"] and x["rb"] > 0.0]
check(f"C15: the cut 0 A is ignored and tried again ({sends}); while the "
f"read-back still shows the old current, Solar counts as able to cut "
f"for the first 2 s of the first send only, never on a retry "
f"({late[:4]})", len(sends) >= 2 and not late)
# =========================================================================== #
print("\n3. OPEN QUESTIONS, PINNED AS THE CODE HAS THEM (C16, C18, Q1)")
# =========================================================================== #
# C16: after a partial cut, the restart adds only max(0, start power - the
# car's power now) to the projection. A car still at 6 A adds nothing, so
# the car may come back while the period with a FULL 6 A on top would not
# be under the aim.
sun16 = step_fn((1200, 0.0), (1260, 5000.0), base=7900.0)
r = drive(step_fn((1200, 800.0), base=900.0), sun16, dur=1700, first="car",
phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
events={1198: lambda p, c: setattr(c.car_solar, "nonzero_at",
p.t)})
rows = r["rec"].rows
part = [x for x in rows if x["t"] >= 1200 and x["cap"] is not None]
und = [x for x in rows if x["t"] > 1200 and x["under"] is not None]
u = und[0] if und else {}
left = 900.0 - (u.get("t", 0) - 900.0)
full = (u.get("proj") or 0) + 4140.0 * left / 900.0
check(f"C16 (accepted as coded, PM R5): a partial cut to "
f"{part[0]['cap'] if part else None} A; the restart clock starts at "
f"{u.get('t')} with the projection {u.get('proj') or 0:.0f} W under "
f"the aim while the car still draws {u.get('car')} W; with a full 6 A "
f"on top it would be {full:.0f} W",
bool(part) and 0 < part[0]["cap"] < 10 and bool(und)
and (u.get("car") or 0) >= 4000.0 and (u.get("proj") or 0) < AIM
and full >= AIM)
# C18: Solar's own 1 -> 3 change under way when a cut becomes due WITH
# headroom (the 15 s wait). Pinned: the change may close during the wait, at
# no more than the current the wait holds, on the phases it selected.
kw = dict(dur=700, first="car", phases=1, socs={"a": 60.0, "b": 60.0},
opts={"ev_phases": "auto"})
r0 = drive(const(900.0), const(9280.0), **kw)
log0 = r0["c"].car_solar.log
sel_t = [t for k, a, t, ok in log0 if k == "phases"]
zero_b = [t for k, a, t, ok in log0 if k == "current" and a == 0.0
and sel_t and t <= sel_t[0]]
tb = int(zero_b[-1]) if zero_b else 400
kw["dur"] = tb + 60
r = drive(step_fn((tb + 1, 9280.0 + 3400.0 + 1500.0), base=900.0),
const(9280.0), **dict(kw, events={0: set_resp(20.0)}))
rows = r["rec"].rows
wait = [x for x in rows if x["t"] >= tb + 1 and x["wait"] is not None]
close = [(t, a) for t, a, _ in after(r, tb + 1) if a > 0.0]
caps = [(x["t"], x["cap"]) for x in rows if x["t"] >= tb + 1
and x["cap"] is not None]
sel = [(x[0], x[2]) for x in r["sim"].log if x[1] == "phases"
and caps and x[0] > caps[0][0]]
check(f"C18 (PM R1, ruled): Solar's change began at {tb}; a cut due during "
f"it does not wait (wait rows {[x['t'] for x in wait][:2]}): it ends "
f"the change at its 0 A at once (cut {caps[:1]}); no select after it "
f"({sel[:1]}), no closing current ({close[:1]})",
not wait and bool(caps) and caps[0][1] == 0.0
and caps[0][0] <= tb + 2 and not sel and not close)
# Q1 (other writer): another writer raises the current inside the 2 s grace
# of Solar's lowering. Pinned: until the next writer step marks the
# difference (`mismatch_since`), car_solar_can_cut() stays True.
r = shape("C", dur=950)
c = r["c"]
w = c.car_solar
rd = c.car.reading
w.sent_a, w.sent_at, w.fail_at, w.mismatch_since = 0.0, c.car_now(), None, \
None
c.car.reading = dataclasses.replace(rd, allowed_a=16.0, setpoint_a=16.0)
in_grace = c.car_solar_can_cut()
w.mismatch_since = c.car_now()
marked = c.car_solar_can_cut()
check(f"Q1 other writer (accepted as coded, PM R5): Solar sent 0 A, another "
f"writer shows 16 A inside the 2 s grace: can-cut {in_grace} until the "
f"difference is marked, then {marked}", in_grace is True
and marked is False)
tb_ = LOG.tracebacks(n_log0)
check(f"N11: no traceback in this file's runs ({tb_[:1]})", not tb_)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)
+290
View File
@@ -0,0 +1,290 @@
"""EV-21 fix round 2 (review of 5759e9d, PM rulings R1-R5).
`python3 -B test_ev21_fix2.py`
- T34 (iv), R1: the reviewer's repro. Solar's own 1 -> 3 change has sent
its 0 A, the read-back is 4 s late (still 16 A on 1 phase), the house
heads the period over with no battery headroom. A cut due during Solar's
own change ENDS the change at its 0 A: no select after it, no closing
current, the car never draws more than before the cut.
- T34 (v), R1: the same for a change from 3 phases to 1.
- N6 / P27, R2: a refused closing write retried under a cut that came in
between is never above the cut's cap (the `_seq_want` cap); under 6 A
(3 A, 0 A) nothing is written after the cut (fix round 3, row (a)), also
at controller level with the house heading over before the retry (b).
- N9: a standing cap survives a cycle with a blind guard or a stale meter.
- R1 standing cut (fix round 3): a standing partial cut goes to 0 A when a
cut is due during Solar's own change.
The real Controller on `tools/ev20_sun.py` through `tools/ev21_kit.py`, and
for the N6/P27 row the real `SolarWriter` on a stub charger.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import dataclasses
import os
import sys
from datetime import datetime, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode, chargers as CH # noqa: E402
from ev20_kit import LOG, check, fails, const, step_fn, TSim # noqa: E402
from ev21_kit import AIM, after, drive, both, _mode, shape, never # noqa: E402
n_log0 = LOG.mark()
def lag(s):
def f(p, c):
p.ch.lag_s = s
return f
def own_change_run(sun, kw, house_w, find):
"""Run once to find Solar's own change (`find(log)` gives the second of
its 0 A), then again with the house at `house_w` from one second
later. Both batteries switched off in battery modes (no headroom), the
read-back 4 s late, the write beside the cycle."""
ev = {0: both(lag(4.0), _mode("ab", False))}
r0 = drive(const(900.0), sun, **dict(kw, events=ev))
tb = find(r0["c"].car_solar.log)
kw = dict(kw, dur=(tb or 400) + 120)
r = drive(step_fn(((tb or 400) + 1, house_w), base=900.0), sun,
**dict(kw, events=ev))
return tb, r
def zero_before_select(log, n_to):
"""The 0 A that began Solar's change to `n_to` phases."""
sel = [t for k, a, t, ok in log if k == "phases" and a == n_to]
z = [t for k, a, t, ok in log if k == "current" and a == 0.0
and sel and t <= sel[0]]
return int(z[-1]) if z else None
def judge(name, tb, r):
rows = r["rec"].rows
t1 = (tb or 0) + 1
pre = [x["car"] for x in rows if x["t"] == t1 - 1]
car_pre = pre[0] if pre else None
first = next((x for x in rows if x["t"] >= t1 and x["cap"] is not None),
{})
nz = [(t, a) for t, a, _ in after(r, t1) if a > 0.0]
sel = [(x[0], x[2]) for x in r["sim"].log
if x[1] == "phases" and x[0] > first.get("t", 1e9)]
more = [(x["t"], x["car"], round(x["proj"] or 0)) for x in rows
if x["t"] > t1 and x["cap"] is not None
and x["car"] > (car_pre or 0.0) + 50.0]
check(f"{name}: Solar's change began at {tb}; the house heads over at "
f"{t1}; the cut at {first.get('t')} is {first.get('cap')} A (the "
f"change ends at its 0 A); no select after it ({sel[:2]}), no "
f"non-zero write ({nz[:3]}), the car never above its "
f"{car_pre} W before the cut ({more[:3]})",
tb is not None and first.get("cap") == 0.0
and first.get("t", 1e9) <= t1 + 1 and not sel and not nz
and not more)
never(name, r)
# =========================================================================== #
print("\n1. T34 (iv), (v): A CUT DURING SOLAR'S OWN CHANGE ENDS IT (PM R1)")
# =========================================================================== #
# (iv) 1 -> 3: the reviewer's repro (review of 5759e9d, Major 1).
kw = dict(dur=700, first="car", phases=1, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "auto"}, beside=True)
tb, r = own_change_run(const(9280.0), kw, 11500.0,
lambda log: zero_before_select(log, 3))
judge("T34 (iv) 1 -> 3, late 0 A read-back", tb, r)
# (v) 3 -> 1: Solar runs 3 phases (up at about 300 s), the sun falls to a
# target under 4 kW at 700 s, the change down comes after the 300 s dwell
# and the 600 s phase gap; the house heads over during it.
sun5 = step_fn((700, 900.0 + 3500.0 + 100.0), base=9280.0)
kw = dict(dur=1200, first="car", phases=1, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "auto"}, beside=True)
tb, r = own_change_run(sun5, kw, 11500.0,
lambda log: zero_before_select(log, 1))
judge("T34 (v) 3 -> 1, late 0 A read-back", tb, r)
# =========================================================================== #
print("\n2. N6 / P27: A REFUSED CLOSE RETRIED UNDER A CUT (PM R2)")
# =========================================================================== #
UTC = datetime(2026, 11, 23, 12, 0, tzinfo=timezone.utc)
class Drv:
"""A charger whose read-back follows at once; `refuse` makes it refuse a
current write."""
polls = ()
def __init__(self):
self.a, self.n, self.refuse = 0.0, 1, False
async def write_current(self, a, **kw):
if self.refuse:
return False
self.a = float(a)
return True
async def write_phases(self, n):
self.n = n
return True
def rd(a, n, e):
return CH.ChargerReading(
available=True, state="C" if a > 0 else "B", connected=True,
charging=a > 0, power_w=a * 230.0 * n, energy_kwh=e,
current_a=tuple(a if i < n else 0.0 for i in range(3)),
setpoint_a=a, allowed_a=a, phases_allowed=n)
async def refused_close(cap):
"""Solar's own 1 -> 3 change; its closing write is refused; then a cut
of `cap` A comes before the retry 5 s later. Returns (the refused
close, the writes after the cut)."""
w, tr, drv = carmode.SolarWriter(), CH.CarTracker(), Drv()
e = [4000.0]
sun = carmode.SunInputs(target_w=9180.0, auto=True, spare_w=9280.0,
margin_w=100.0)
refused, t = None, 0.0
async def step(t, cut=None):
r = rd(drv.a, drv.n, e[0])
e[0] += drv.a * 230.0 * drv.n / 3.6e6
tr.observe(r, t, UTC, "2026-11-23")
w.cut_a = cut
await w.step(drv, r, mode=carmode.SOLAR, sun=sun, clamp=16.0, now=t,
tracker=tr, writing=True, status=CH.CHARGING,
clock=lambda: t)
while t < 900.0 and refused is None:
q = w.seq
drv.refuse = bool(q is not None and q.get("stage") == "settle"
and drv.n == 3)
n0 = len(w.log)
await step(t)
bad = [x for x in w.log[n0:] if x[0] == "current" and not x[3]
and x[1] > 0.0]
if bad:
refused = bad[0]
t += 1.0
drv.refuse = False
n1 = len(w.log)
for _ in range(12):
await step(t, cut=cap)
t += 1.0
return refused, [(x[2], x[1]) for x in w.log[n1:]
if x[0] == "current"], drv.a
refused, later, _end = asyncio.run(refused_close(6.0))
check(f"N6/P27: Solar's closing write {refused} is refused; a cut to 6 A "
f"comes before its retry: the retry is never above 6 A ({later})",
refused is not None and refused[1] > 6.0 and bool(later)
and all(a <= 6.0 for _t, a in later))
# Fix round 3 (re-review Major 1): a cut under 6 A before the retry ends the
# change in the writer (carmode.py, `plan.a < MIN_A` in the change): no
# write after the cut at all, and the charger stays at 0 A.
for cap in (3.0, 0.0):
refused, later, end = asyncio.run(refused_close(cap))
check(f"N6/P27 (a) [cut {cap:.0f} A]: Solar's closing write {refused} is "
f"refused; the cut comes before its retry: no write after it "
f"({later}), the charger ends at {end} A",
refused is not None and refused[1] > 6.0 and not later
and end == 0.0)
# (b) The same at controller level (the re-reviewer's row B): Solar 16 A on
# 1 phase, auto, sun 9280 W, both batteries switched off in battery modes.
# Solar's own 1 -> 3 change; its close is refused (a 2 s "error" window);
# the house steps to 18 kW one second after the window, before the retry
# (5 s after the close). Expected: a 0 A cut at once, no retry, no car power
# under the cut.
kw = dict(dur=700, first="car", phases=1, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "auto"}, beside=True)
ev = {0: both(lag(0.0), _mode("ab", False))}
r0 = drive(const(900.0), const(9280.0), **dict(kw, events=ev))
log0 = r0["c"].car_solar.log
sel = [t for k, a, t, ok in log0 if k == "phases" and a == 3]
close = [(t, a) for k, a, t, ok in log0 if k == "current" and a > 0.0
and sel and t > sel[0]]
tc = close[0][0] if close else None
if tc is not None:
sim = TSim(setpoint_a=0, windows=[(tc - 1.0, tc + 1.0, "error")])
r = drive(step_fn((tc + 2, 18000.0), base=900.0), const(9280.0),
**dict(kw, events=ev, sim=sim, dur=tc + 200))
log = r["c"].car_solar.log
tried = [(t, a, ok) for k, a, t, ok in log if k == "current"
and t >= tc - 1]
retry = [(t, a) for t, a, ok in tried if a > 0.0 and t >= tc + 2]
rows = r["rec"].rows
caps = [(x["t"], x["cap"]) for x in rows if x["t"] >= tc + 2
and x["cap"] is not None]
car_hi = [(x["t"], x["car"]) for x in rows if x["t"] > tc + 2
and x["cap"] is not None and (x["car"] or 0) > 50.0]
ok_b = (bool(caps) and caps[0] == (tc + 2, 0.0) and not retry
and not car_hi)
else:
tried, retry, caps, car_hi, ok_b, r = [], [], [], [], False, None
check(f"N6/P27 (b): Solar's change selects at {sel[:1]}, its close at {tc} "
f"is refused, the house is at 18 kW from {tc and tc + 2}: the cut "
f"{caps[:1]} (0 A at once), no non-zero retry after it ({retry[:2]}), "
f"no car power under it ({car_hi[:2]}); writes {tried[:5]}", ok_b)
if r is not None:
never("N6/P27 (b)", r)
# =========================================================================== #
print("\n3. N9: A STANDING CUT SURVIVES A STALE CYCLE")
# =========================================================================== #
r = shape("C", dur=1000)
c = r["c"]
st = c._cut
cap0 = st.get("cap")
t = c.car_now()
blind = dataclasses.replace(c.peak_guard, blind="meter gap")
c.car_solar.cut_a = None
c._car_cut_tick(c._peak_proj_real, blind, AIM, t)
a_blind = c.car_solar.cut_a
c.car_solar.cut_a = None
c._car_cut_meter_fresh = lambda: False
c._car_cut_tick(c._peak_proj_real, c.peak_guard, AIM, t)
a_stale = c.car_solar.cut_a
check(f"N9: a cut of {cap0} A stands; a cycle with a blind guard gives the "
f"writer {a_blind} A, one with a stale meter {a_stale} A: the cap "
f"stays", cap0 is not None and a_blind == cap0 and a_stale == cap0)
# =========================================================================== #
print("\n4. PM R1: A STANDING PARTIAL CUT GOES TO 0 A IF A CHANGE IS UNDER WAY")
# =========================================================================== #
# Fix round 3 (re-review Minor): `_car_cut_tick` itself. A partial cut of
# 8 A stands, Solar's plan has decided a phase change (`plan.switch`) and a
# cut is due again (the car draws, the projection is over the aim): the
# standing cap goes to 0 A, which ends the change at its 0 A (R1).
r = shape("C", dur=950)
c = r["c"]
w = c.car_solar
t = c.car_now()
c._car_cut_meter_fresh = lambda: True
left = 900.0 - 300.0
proj = dataclasses.replace(c._peak_proj_real, elapsed_s=300.0,
projected_w=AIM + 1000.0 * left / 900.0)
st = c._cut = c._cut_fresh(proj.block_start)
st.update(cap=8.0, ex=1e9, car0=6900.0, base=10.0, cuts=1, at=t, since=t)
w.plan.switch = True
c._car_cut_tick(proj, c.peak_guard, AIM, t)
cap_switch = c._cut["cap"]
w.plan.switch = False
st = c._cut = c._cut_fresh(proj.block_start)
st.update(cap=8.0, ex=1e9, car0=6900.0, base=10.0, cuts=1, at=t, since=t)
c._car_cut_tick(proj, c.peak_guard, AIM, t)
cap_plain = c._cut["cap"]
check(f"R1 standing cut: a cut of 8 A stands and a cut is due again; with "
f"Solar's own change decided it becomes {cap_switch} A, without one "
f"it stays {cap_plain} A", cap_switch == 0.0 and cap_plain == 8.0)
tb_ = LOG.tracebacks(n_log0)
check(f"N11: no traceback in this file's runs ({tb_[:1]})", not tb_)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)
+554
View File
@@ -0,0 +1,554 @@
"""EV-21: the peak cut's paths: one cut per episode, the restart, the
period's edge, a restart of the add-on, and every case where Solar cannot
cut (then the alarm, the banking and the guard are as in Off).
`python3 -B test_ev21_paths.py`
Rows T22-T26, T29-T34, T36, T39-T46 and T48 of reports/EV-21-test-plan.md,
and the formal check's C2 (a named bug at c79eb37). The real Controller on
`tools/ev20_sun.py` through `tools/ev21_kit.py`; the second period runs
900-1800. "Twin": the same run in Off, the charger held at the same current
and given the same other-writer events.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode, ctl_car # noqa: E402
import ev20_sun as S # noqa: E402
from chargersim import SimCharger # noqa: E402
from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402
from ev21_kit import (AIM, after, alarms, first_alarm, merge, # noqa: E402
never, quarter_avg, shape, twin, drive, _cutamps,
replay_twin, near_end, refuse_n1)
n_log0 = LOG.mark()
SET = S.SET
def stamp(p, c):
"""A non-zero write now on Solar's one write clock: its 30 s gate is
closed for 30 s (a stand-in for a write it just made)."""
c.car_solar.nonzero_at = p.t
def zero_at(r, t0):
z = [t for t, a, _ in after(r, t0) if a == 0.0]
return z[0] if z else None
def nonzero_after(r, t0):
return [(t, a) for t, a, _ in after(r, t0) if a > 0.0]
def attempts(r, t0=0):
return [(t, v) for t, e, v in r["plant"].sets if e == SET and t >= t0]
def close(a, b, s=2):
if a is None or b is None:
return a is None and b is None
return abs(a - b) <= s
def off_alarm_like(name, r, o, t0, extra="", ex_from=None):
"""The alarm at the Off twin's second (+2 s), car_explains never True
from `ex_from` (default t0), and the same banked periods."""
a_s, a_o = first_alarm(r, t0), first_alarm(o, t0)
t1 = t0 if ex_from is None else ex_from
ex = [x["t"] for x in r["trace"] if x["t"] >= t1 and x["explains"]]
check(f"{name}: the alarm at the Off twin's second +2 ({a_s} vs {a_o}); "
f"car_explains never True ({ex[:2]}); banked as Off "
f"({r['c'].car_peak_q} vs {o['c'].car_peak_q}){extra}",
close(a_s, a_o) and not ex
and r["c"].car_peak_q == o["c"].car_peak_q)
# =========================================================================== #
print("\n1. NO CUT FROM A STALE PROJECTION (T22, N9)")
# =========================================================================== #
def silent(p, c):
p.meter_on = False
r = shape("C", dur=1400, events={940: silent})
caps = [x["t"] for x in r["rec"].rows if x["t"] >= 940
and x["cap"] is not None]
w = after(r, 940)
check(f"T22: the meter silent from 940 s, the step at 960: no cut sized "
f"({caps[:2]}); only Solar's unknown rule acts, its pause at the "
f"meter's own age 330 s ({w[:2]})",
not caps and all(t >= 940 + 325 for t, _a, _ok in w))
# =========================================================================== #
print("\n2. ONE CUT PER EPISODE, DEEPER ONLY ON A GROWING EXCESS (T23, T24)")
# =========================================================================== #
for lag in (0.0, 3.0):
def slow(p, c, lag=lag):
p.ch.ramp_w_s, p.ch.lag_s = 700.0, lag
# The 30 s gate is closed at the step (a write at 908), so Solar's own
# sun rule cannot lower the car first: only the cut can.
r = drive(step_fn((910, 8300.0), (970, 900.0), base=900.0),
const(13000.0), dur=1100, first="car", phases=3,
socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
events={0: slow, 908: stamp})
low = [(t, a) for t, a, _ in after(r, 905) if t < 938 and a < 16.0]
ep = [x for x in r["rec"].rows if 905 <= x["t"] < 970 and x["cap"]
is not None]
want = _cutamps()(ep[0]["car0"], ep[0]["ex"], 3) if ep else None
check(f"T23 [lag {lag:.0f} s]: the car at 16 A on 3 phases (ramp 700 "
f"W/s), the house +7400 W at 910: exactly one cut write in the "
f"episode ({low}), sized from its start ({want} A)",
len(low) == 1 and low[0][1] == want)
never(f"T23 [lag {lag:.0f}]", r)
# T24: a growing excess in one episode: the second, deeper cut is measured
# from the episode's start (car0 less the largest excess), never from the
# lowered car.
r = drive(step_fn((960, 900.0 + 5700.0), (966, 900.0 + 9000.0), base=900.0),
const(13000.0), dur=1100, first="car", phases=3,
socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
events={958: stamp})
rows24 = [x for x in r["rec"].rows if 958 <= x["t"] <= 980]
caps = []
for x in rows24:
if x["cap"] is not None and (not caps or x["cap"] != caps[-1][1]):
caps.append((x["t"], x["cap"], x["ex"], x["car0"]))
w = [(t, a) for t, a, _ in after(r, 958) if t <= 980 and a < 16.0]
ok_from_start = all(cp == _cutamps()(c0, ex, 3) for _t, cp, ex, c0 in caps)
check(f"T24: two cuts as the excess grows ({caps}); each is "
f"floor((car0 - largest excess) / 690), never re-subtracted from the "
f"lowered car; writes {w}",
len(caps) == 2 and caps[1][1] < caps[0][1] and ok_from_start
and [a for _t, a in w] == [cp for _t, cp, _e, _c in caps])
# =========================================================================== #
print("\n3. THE RESTART (T25, T26, T41)")
# =========================================================================== #
sun25 = step_fn((960, 0.0), (990, 9000.0), base=7900.0)
r = drive(step_fn((960, 3000.0), base=900.0), sun25, dur=1500, first="car",
phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"})
cut_t = zero_at(r, 960)
und = [x["under"] for x in r["rec"].rows if x["t"] > 960
and x["under"] is not None]
t_under = und[0] if und else None
nz = nonzero_after(r, 961)
lo = max(t_under + 120.0, cut_t + 120.0) if t_under and cut_t else None
check(f"T25/OQ6: the cut at {cut_t}; the projection with the start power "
f"under the aim from {t_under}; the first non-zero write {nz[:1]} not "
f"before {lo} and within 10 s of it",
bool(nz) and lo is not None and lo <= nz[0][0] <= lo + 10)
never("T25", r)
house26 = step_fn((960, 30000.0), (1020, 900.0), base=900.0)
sun26 = step_fn((960, 0.0), (1020, 9000.0), base=7900.0)
r = drive(house26, sun26, dur=1700, first="car", phases=3,
socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"})
over_nz = [(t, a) for t, a in nonzero_after(r, 961)
if (r["rec"].at(t) or {}).get("proj", 0) >= AIM]
und = [x["under"] for x in r["rec"].rows if x["t"] > 1020
and x["under"] is not None]
nz = nonzero_after(r, 961)
check(f"T26: the projection stays over long after the cut: no non-zero "
f"write while it is over the aim ({over_nz[:2]}); the first {nz[:1]} "
f"120 s or more after it went under with the start power "
f"({und[:1]})",
not over_nz and bool(nz) and bool(und) and nz[0][0] >= und[0] + 120)
# T41: a cut, a restart, a second cut in one period; then no restart until
# the next period (OQ4).
sun41 = step_fn((960, 0.0), (990, 9000.0), (1400, 0.0), (1430, 9000.0),
base=7900.0)
r = drive(step_fn((960, 3000.0), base=900.0), sun41, dur=2100,
first="car", phases=3, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "3"})
w = [(t, a) for t, a, _ in after(r, 950)]
cuts = [x["cuts"] or 0 for x in r["rec"].rows if 900 <= x["t"] < 1800]
second = [t for t, a in w if 1400 <= t < 1800 and a == 0.0]
re2 = [t for t, a in w if 1401 <= t < 1800 and a > 0.0]
q = quarter_avg(r, 900)
nxt = [t for t, a in w if 1800 <= t <= 1800 + 130 and a > 0.0]
check(f"T41/OQ4: after the second cut the car comes back in the next "
f"period, by the start rule ({nxt[:1]})", bool(nxt))
check(f"T41: writes {w[:6]}: a restart between the cuts, the second cut "
f"within 1 cycle of 1400 ({second[:1]}), {max(cuts, default=0)} cuts in the "
f"period, no restart after it until 1800 ({re2[:1]}); the period "
f"{q:.0f} W <= aim, nothing banked ({r['c'].car_peak_q})",
any(960 < t < 1400 and a > 0 for t, a in w) and second
and second[0] <= 1401 and max(cuts, default=0) == 2 and not re2 and q <= AIM
and not r["c"].car_peak_q)
never("T41", r)
# =========================================================================== #
print("\n4. SOLAR CANNOT CUT: AS OFF (T29-T33, C2)")
# =========================================================================== #
# C2, the named bug: every cannot-cut Solar case gave the car's figure to the
# alarm path at c79eb37; Off gives None.
r = shape("C", dur=950)
c = r["c"]
cases = []
for name, on, off in (
("shadow", lambda: c.o.__setitem__("shadow_mode", "on"),
lambda: c.o.__setitem__("shadow_mode", "off")),
("Stop", lambda: setattr(c, "auto", False),
lambda: setattr(c, "auto", True)),
("circuit latch", lambda: setattr(c.circ_wd, "tripped", True),
lambda: setattr(c.circ_wd, "tripped", False)),
("shutting down", lambda: setattr(c, "stopping", True),
lambda: setattr(c, "stopping", False)),
("another writer", lambda: setattr(c.car_solar, "mismatch_since",
1.0),
lambda: setattr(c.car_solar, "mismatch_since", None))):
on()
cases.append((name, c.car_alarm_w()))
off()
base_w = c.car_alarm_w()
check(f"C2: in every cannot-cut Solar case car_alarm_w is None, as Off "
f"({cases}); while Solar can cut it is the car's figure ({base_w})",
all(v is None for _n, v in cases) and base_w is not None)
# T29: another writer sets 16 A; the house steps 5 s later.
for T in (950,):
ev = {T: lambda p, c: p.ch.set_current(16)}
kw = dict(dur=1300, step=T + 5)
r = shape("C", events=ev, **kw)
o = twin("C", events=ev, **kw)
mism = [x["t"] for x in r["rec"].rows if x["t"] >= T
and x["mism"] is not None]
ex = [x["t"] for x in r["trace"] if x["t"] >= T and x["explains"]]
off_alarm_like(f"T29 [other writer at {T}]", r, o, T)
check(f"T29: car_explains False from the first cycle of the difference "
f"({mism[:1]}, explains {ex[:1]}); no Solar write over it "
f"({after(r, T)})", bool(mism) and mism[0] <= T + 1 and not ex
and not after(r, T))
# EV-05 r8 M2: another writer starts the car soon after Solar's own 0 A.
sun_p = step_fn((700, 900.0), base=7900.0)
ev = {760: lambda p, c: p.ch.set_current(16)}
r = drive(step_fn((765, 9000.0), base=900.0), sun_p, dur=1000, first="car",
phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
events=ev)
o = drive(step_fn((765, 9000.0), base=900.0), sun_p, dur=1000, first="car",
phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
events=ev, mode="off", setpoint=10)
off_alarm_like("T29 [r8 M2: another writer after Solar's own 0 A]", r, o,
760)
# T30: the cut refused ("error", "ignore"); retried only as 0 A, 60 s apart,
# 3 tries at most; lifted before the 3rd: taken, and graded from then.
for kind in ("error", "ignore"):
def refuse(p, c, kind=kind):
p.ch.refuse = kind
def lift(p, c):
p.ch.refuse = None
r = shape("C", dur=1300, events={959: refuse, 1050: lift})
o = twin("C", dur=1300)
# Graded out only in the cut's own cycle (nothing written yet); from the
# cycle after its write, as Off until the read-back shows it.
off_alarm_like(f"T30 [{kind}]", r, o, 955, ex_from=961)
at = attempts(r, 959)
gaps = [b[0] - a[0] for a, b in zip(at, at[1:])]
rb0 = [x["t"] for x in r["trace"] if x["t"] > 960 and x["rb"] == 0.0]
fl = [(x["t"], x["floor"], y["floor"]) for x, y in
zip(r["trace"], o["trace"])
if 961 <= x["t"] < (rb0[0] if rb0 else 1300)
and abs((x["floor"] or 0.0) - (y["floor"] or 0.0)) > 50.0]
can_back = [x["t"] for x in r["rec"].rows if x["t"] >= (rb0[0] if rb0
else 1e9)
and x["can"]]
check(f"T30 [{kind}]: tries {at}: only 0 A, at least 60 s apart "
f"({gaps}), at most 3; after the lift taken (read back 0 at "
f"{rb0[:1]}), graded from that cycle ({can_back[:1]})",
at and all(v == 0.0 for _t, v in at) and len(at) <= 3
and all(g >= 60 for g in gaps) and bool(rb0) and bool(can_back)
and can_back[0] <= rb0[0] + 1)
check(f"T30 [{kind}]: until the read-back shows the cut, the guard's "
f"floor is the Off twin's within 50 W ({fl[:2]})", not fl)
# T31: a late read-back (12 s): as Off until it shows, can cut from then.
def lag12(p, c):
p.ch.lag_s = 12.0
r = shape("C", dur=1200, events={950: lag12})
o = twin("C", dur=1200)
rb0 = [x["t"] for x in r["trace"] if x["t"] > 960 and x["rb"] == 0.0]
early = [x["t"] for x in r["rec"].rows if 962 <= x["t"] < (rb0[0] if rb0
else 0)
and x["can"]]
back = [x["t"] for x in r["rec"].rows if rb0 and x["t"] >= rb0[0]
and x["can"]]
check(f"T31: a cut read back 12 s late (at {rb0[:1]}): not graded before "
f"({early[:2]}), can cut from the first cycle that shows it "
f"({back[:1]}); car_peak_q {r['c'].car_peak_q}",
bool(rb0) and not early and bool(back) and back[0] <= rb0[0] + 1
and r["c"].car_peak_q == {})
# T32: not writing (shadow, Stop, circuit latch), then another writer's 16 A
# after Solar's way-out 0 A, then the house step (EV-05 r6).
for name, fn, opts in (("Stop", lambda p, c: setattr(c, "auto", False),
{"shadow_mode": "auto"}),
("shadow on", lambda p, c: c.o.__setitem__(
"shadow_mode", "on"), {}),
("circuit latch", lambda p, c: setattr(
c.circ_wd, "tripped", True), {})):
ev = {930: fn, 940: lambda p, c: p.ch.set_current(16)}
r = shape("C", dur=1300, events=ev, opts=opts)
o = twin("C", dur=1300, events=ev, opts=opts)
off_alarm_like(f"T32 [{name}]", r, o, 935)
# T33: a charger fault (mode3 E) and a stuck reading while a cut is due.
for name, fn in (("mode3 E", lambda p, c: p.ch.fault("E")),
("stuck reading", lambda p, c: p.ch.freeze())):
r = shape("C", house_w=9000.0, dur=1300, events={955: fn})
o = replay_twin(r, "C", house_w=9000.0, dur=1300, events={955: fn})
flt = [x["t"] for x in r["rec"].rows if x["fault"] is not None]
off_alarm_like(f"T33 [{name}]", r, o, 950,
ex_from=flt[0] if flt else 950,
extra=f"; Solar's fault from {flt[:1]}")
# =========================================================================== #
print("\n5. PHASES: A CUT NEVER SELECTS, A PHASE GAP NEVER BLOCKS IT (T34)")
# =========================================================================== #
# (i) Solar's own 1 -> 3 select, then a partial cut 140 s later.
kw = dict(dur=700, first="car", phases=1, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "auto"})
r0 = drive(const(900.0), const(9280.0), **kw)
sel = [x[0] for x in r0["sim"].log if x[1] == "phases"]
t0 = int(sel[0]) if sel else 400
ts = t0 + 140
kw["dur"] = ts + 60
r = drive(step_fn((ts, 900.0 + 4100.0), base=900.0), const(9280.0), **kw)
w = [(t, a) for t, a, _ in after(r, ts)]
ph = [x for x in r["sim"].log if x[1] == "phases" and x[0] >= ts]
ep = [x for x in r["rec"].rows if x["t"] >= ts and x["cap"] is not None]
check(f"T34 (i): Solar's select at {t0}, a partial cut at {ts}: written "
f"within 1 cycle ({w[:2]}; cap {ep[0]['cap'] if ep else None}), the "
f"600 s gap does not block it, no select in the cut ({ph})",
bool(w) and w[0][0] <= ts + 1 and 6.0 <= w[0][1] < 12.0 and not ph)
# (ii) Another writer selects 3 phases while Solar's plan says 1.
kw = dict(dur=1100, first="car", phases=1, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "auto"})
ev = {940: lambda p, c: p.ch.set_phases(3)}
r = drive(step_fn((960, 3000.0), base=900.0),
step_fn((960, 0.0), base=900.0 + 2300.0 + 100.0), events=ev, **kw)
w = [(t, a) for t, a, _ in after(r, 960)]
rec960 = r["rec"].at(960) or {}
check(f"T34 (ii): another writer's 3 phases under Solar's 10 A: within 1 "
f"cycle the cut at 690 W/A ({w[:1]}) or Solar unable to cut (can "
f"{rec960.get('can')}, explains {rec960.get('explains')}); never "
f"graded out without a write",
(bool(w) and w[0][0] <= 961) or (not rec960.get("explains")))
# (iii) Formal C12: the cut comes DURING Solar's own 1 -> 3 change (the car
# held at its 0 A, the select out or not yet): the change ends at that 0 A,
# no closing current goes out into the excess, no select after the cut.
log0 = [x for x in r0["c"].car_solar.log]
sel_t = [t for k, a, t, ok in log0 if k == "phases"]
zero_b = [t for k, a, t, ok in log0 if k == "current" and a == 0.0
and sel_t and t <= sel_t[0]]
tb = int(zero_b[-1]) if zero_b else 400
kw = dict(dur=tb + 120, first="car", phases=1, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "auto"})
r = drive(step_fn((tb + 3, 9280.0 + 3400.0 + 2000.0), base=900.0),
const(9280.0), **kw)
w = [(t, a) for t, a, _ in after(r, tb + 3)]
sel_after = [x for x in r["sim"].log if x[1] == "phases" and x[0] > tb + 4]
caps = [x["t"] for x in r["rec"].rows if x["t"] >= tb + 3
and x["cap"] is not None]
check(f"T34 (iii) / C12: Solar's own change began at {tb}; the house heads "
f"the period over at {tb + 3}: the cut is due at {caps[:1]}, no closing "
f"current goes out ({w[:2]}), no select after it ({sel_after[:1]})",
bool(caps) and caps[0] <= tb + 4 and not [a for _t, a in w if a > 0.0]
and not sel_after)
never("T34 (iii)", r)
# =========================================================================== #
print("\n6. THE COVER OFF (T36) AND THE PERIOD'S EDGE (T39, T40)")
# =========================================================================== #
for kind in ("M", "C"):
r = shape(kind, cover=False, dur=1300)
q = quarter_avg(r, 900)
w = after(r, 960)
over = [x["t"] for x in r["rec"].rows if 960 <= x["t"] < 1000
and (x["proj"] or 0) > AIM and x["cap"] is None
and x["car"] > 100]
check(f"T36 [{kind}, cover off]: the cut first, at once where it is due "
f"({w[:2]}; uncut seconds over the aim with the car {over[:3]}); "
f"the period {q:.0f} W", not over and (q <= AIM or kind == "M"))
for n in (2, 1):
# The old period heads over at 1700 (100 s left: at once); the house is
# back to 900 W at 1790, so the new period starts under the aim.
r = near_end(1700, n=n, house_after=12000.0, sun_back=1810, dur=2100,
house_more=((1790, 900.0),))
w = [(t, a) for t, a, _ in after(r, 1695)]
cut = [t for t, a in w if a == 0.0]
# Non-zero writes after the cut only (Solar's own steps before the step
# at 1700 are not a restart).
nz = [t for t, a in w if a > 0.0 and cut and t > cut[0]]
new_q = [x["t"] for x in r["rec"].rows if 1800 <= x["t"] < 1930
and x["cap"] is not None]
check(f"T39 [N={n}]: the old period's cut at {cut[:1]}; none at or "
f"after :15:00 for the old excess (cut state in the new period "
f"{new_q[:1]}); the restart by the start rule only (sun back at "
f"1810, start at {nz[:1]}) ({w[:4]})",
bool(cut) and cut[0] <= 1701 and len(cut) == 1 and not new_q
and bool(nz) and nz[0] >= 1810 + 120)
for n in (2, 1):
ev = {t: refuse_n1 for t in range(0, 1901)} if n == 1 else {}
r = drive(step_fn((1750, 3000.0), base=900.0),
step_fn((1750, 0.0), base=900.0 + 3680.0 + 100.0),
dur=1900, first="car", phases=1, events=ev, rows=n == 2,
ratings={"a": 5000.0, "b": 4600.0} if n == 2
else {"a": 5000.0},
socs={u: 10.0 for u in ("ab" if n == 2 else "a")},
opts={"ev_phases": "1"})
hold_s = r["c"].p1.averager.max_hold_s
cut = zero_at(r, 1740)
check(f"T40 [N={n}]: the old period stays under the aim; the new one "
f"heads over: the cut in its first cycle ({cut}), at N=2 up to "
f"max_hold_s ({hold_s:.0f} s) before the edge, never later",
cut is not None and 1800 - (hold_s if n == 2 else 0) - 1 <= cut
<= 1801)
# =========================================================================== #
print("\n7. ADD-ON RESTART (T42), UNTRUSTED CAR (T43), HA DOWN (T44)")
# =========================================================================== #
# (a) a cut at 960, the add-on restarts at 1000 on the same store and charger.
r1 = shape("C", house_w=9000.0, dur=1000 - 0)
sim, store = r1["sim"], r1["store"]
r2 = drive(step_fn((0, 9000.0), base=9000.0), const(0.0), t0=1000.0, dur=200,
first="car", phases=3, socs={"a": 10.0, "b": 10.0},
opts={"ev_phases": "3"}, sim=sim, store=store, plug=False)
w2 = [(t, a) for t, a, _ in after(r2, 1000)]
keys = [k for k in store.data if "cut" in str(k).lower()]
check(f"T42 (a): after a restart in an over period, D2's 0 A first and no "
f"non-zero write ({w2[:3]}); no store key carries a cut ({keys})",
(not w2 or w2[0][1] == 0.0) and not [a for _t, a in w2 if a > 0]
and not keys)
# (b) a stop at :14:30, back at :15:30, the new period under the aim.
r1 = shape("C", step=1770, dur=1770)
r2 = drive(const(900.0), const(7900.0), t0=1830.0, dur=120, first="car",
phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
sim=r1["sim"], store=r1["store"], plug=False)
caps = [x["t"] for x in r2["rec"].rows if x["cap"] is not None]
check(f"T42 (b): back in a new period under the aim: no cut ({caps[:1]})",
not caps)
# T43: a car figure the energy meter cannot corroborate (no energy entity):
# a cut due writes 0 A (OQ2); the alarm as Off.
def no_energy(p, c):
p.ch.no_energy = True
H9 = 9000.0
r = shape("C", house_w=H9, dur=1100, events={950: no_energy})
o = twin("C", house_w=H9, dur=1100, events={950: no_energy})
w = after(r, 960)
check(f"T43: an untrusted car figure: the cut is 0 A ({w[:1]}); the alarm "
f"at the Off twin's second +2 ({first_alarm(r, 900)} vs "
f"{first_alarm(o, 900)})", bool(w) and w[0][1] == 0.0
and first_alarm(r, 900) is not None
and first_alarm(r, 900) - first_alarm(o, 900) <= 2)
def ha(on):
def f(p, c):
p.ha_down = on
return f
r = shape("C", dur=1200, events={960: ha(True), 1020: ha(False)},
rows=False)
during = attempts(r, 960)
during = [x for x in during if x[0] < 1020]
back = [(t, a) for t, a, _ in after(r, 1020)]
check(f"T44: Home Assistant down 60 s from the step: nothing tried while "
f"down ({during}); back: 0 A first, never higher ({back[:2]})",
not during and bool(back) and back[0][1] == 0.0)
# =========================================================================== #
print("\n8. A CAR THAT DOES NOT FOLLOW (T45) AND THE FLOOR AFTER A CUT (T46)")
# =========================================================================== #
def freeze_p(p, c):
p.ch.freeze_power()
r = shape("C", house_w=9000.0, dur=1200, events={959: freeze_p})
o = twin("C", house_w=9000.0, dur=1200)
a_s, a_o = first_alarm(r, 900), first_alarm(o, 900)
check(f"T45: the read-back says 0 A, the power stays: the alarm no later than "
f"the Off twin + 62 s ({a_s} vs {a_o})",
a_s is not None and a_o is not None and a_s - a_o <= 62)
r = shape("W", dur=1100)
z = zero_at(r, 960)
rec = r["rec"]
dec = (rec.at(z) or {}) if z is not None else {}
rb = [x["t"] for x in r["trace"] if z and x["t"] > z and x["rb"] == 0.0]
car_b = (rec.at(z - 1) or {}).get("car", 0.0) if z is not None else 0.0
lim = None
bad = []
if rb:
car_a = (rec.at(rb[0] + 5) or {}).get("car", 0.0)
# Fix round 1: the bound is on the guard's EXCESS (what the site must
# still shed: wanted_w less the batteries' own output). In Shape W the
# batteries answer 20 s late, so the commands sent before the cut reach
# them after it and `wanted_w` (battery + excess) rises with that late
# output while the excess is negative: not a floor raised for the car.
tr_ = {x["t"]: x for x in r["trace"]}
ex_dec = (tr_.get(z) or {}).get("excess") or 0.0
lim = max(0.0, ex_dec - (car_b - car_a)) + 150.0
bad = [(x["t"], round(x["excess"] or 0), round(x["want"] or 0))
for x in r["trace"]
if rb[0] + 5 <= x["t"] <= rb[0] + 60 and (x["excess"] or 0) > lim]
check(f"T46: from 5 s after the cut's read-back the excess the guard asks the "
f"batteries for is no more than at the cut less what the car gave "
f"back, +150 W ({lim}; (t, excess, wanted_w) over it: {bad[:3]})",
bool(rb) and not bad)
# =========================================================================== #
print("\n9. THE WALL CLOCK JUMPS (T48)")
# =========================================================================== #
def jump(dt):
def f(p, c):
p.utc_off = dt
return f
r0 = shape("W", dur=1100)
r = shape("W", dur=1100, events={965: jump(-3600.0)})
check(f"T48 [-3600 s during the wait]: the 15 s wait runs on the monotonic "
f"clock: the cut at the same second ({zero_at(r, 960)} vs "
f"{zero_at(r0, 960)})", zero_at(r, 960) == zero_at(r0, 960)
and zero_at(r0, 960) is not None)
r = shape("W", dur=1100, events={965: jump(3600.0)})
blind = [x["t"] for x in r["rec"].rows if x["t"] >= 965
and x["cap"] is not None]
z = zero_at(r, 960)
check(f"T48 [+3600 s during the wait]: the wall clock jumps into a period "
f"the meter has not covered, so the guard is blind "
f"({r['c'].peak_guard.blind!r:.40}); no cut is sized from that "
f"projection (N9; cut state {blind[:1]}, writes {after(r, 965)[:2]})",
r["c"].peak_guard.blind is not None and not blind
and not [a for _t, a, _ok in after(r, 965) if a > 6.0])
for dt in (3600.0, -3600.0):
r0 = near_end(1700)
r = near_end(1700, events={1702: jump(dt)})
z, z0 = zero_at(r, 1700), zero_at(r0, 1700)
up = [(t, a) for t, a, _ok in after(r, 1701) if a > 0.0]
check(f"T48 [{dt:+.0f} s just after a near-end cut]: the cut at the same "
f"second ({z} vs {z0}), never undone by the jump ({up[:2]})",
z == z0 and z is not None and not [t for t, a in up if t < 1800])
tb = LOG.tracebacks(n_log0)
check(f"N11: no traceback in this file's runs ({tb[:1]})", not tb)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)
+314
View File
@@ -0,0 +1,314 @@
"""EV-21: what must NOT change (Manual, Off, no excess, cloud edges the
batteries catch), the cut amount over a table of sites, the write seam, and
the docs and strings.
`python3 -B test_ev21_same.py`
Rows T4-T6, T11, T36 (the guard's floor), T37, T38, T47, T52, T53 of
reports/EV-21-test-plan.md. "Identical to c79eb37": each run's writes,
notices with their second, and per-second guard view (floor, car_explains,
car_over, red rows) are hashed (`ev21_kit.digest`); GOLDEN holds the hashes
the same runs give on c79eb37 (release/1.0 before EV-21), taken with
`EV21_GOLDEN=1 python3 -B test_ev21_same.py` on that tree. A hash that
differs fails, and the line prints what this tree gives.
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import ast
import io
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
import opt11_identity as rig # noqa: E402
from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402
from ev21_kit import (AIM, after, digest, drive, shape, view_guard, # noqa: E402
view_writes, _cutamps, refuse_n1, merge)
n_log0 = LOG.mark()
TAKE = os.environ.get("EV21_GOLDEN") == "1"
GOLDEN = {
'T4 [Manual, cover on]': {
'writes': 'f391f105a59891b9',
'notes': '2e109ddce05805c1',
'guard': 'e9f0a5079393d301',
'floor': 'ee3dd0b6ddcda88a',
'batt': '0f657edaab7156ef'},
'T4 [Manual, cover off]': {
'writes': 'f391f105a59891b9',
'notes': '2e109ddce05805c1',
'guard': '461119b75fbb738a',
'floor': 'ee3dd0b6ddcda88a',
'batt': '0f657edaab7156ef'},
'T5 [Off]': {
'writes': '4f53cda18c2baa0c',
'notes': '346a74064b62c0f5',
'guard': '165d51d07b84c233',
'floor': 'ee3dd0b6ddcda88a',
'batt': 'a91930f22238e925'},
'T6 [Shape M: the batteries cover house and car]': {
'writes': '385ae1fbf07b25d6',
'notes': '4f53cda18c2baa0c',
'guard': 'a52b1c929747cd07',
'floor': 'f62cb235198fa562',
'batt': '26965ed24b700eae'},
'T11 (a) [the batteries catch it in a few seconds]': {
'writes': '2feff2d70bc160e2',
'notes': '4f53cda18c2baa0c',
'guard': '58bb40545886af53',
'floor': '547335adccb04a76',
'batt': '0954ff4dd06faae5'},
'T11 (b) [EV-05 T21b cloud edge, 16 A on 3 phases]': {
'writes': '65a8a3fa50b4d81c',
'notes': 'c70d97f8902a82a0',
'guard': '269d88368a15b2d9',
'floor': '309fe221f371aa6f',
'batt': '4719e28af092fdbe'},
'T38 [cover on]': {
'writes': '324aac021ce35055',
'notes': '4f53cda18c2baa0c',
'guard': '86809c51ba676e49',
'floor': 'f0e12bc7f14924dc',
'batt': '3ce6bd3c1711cc3b'},
'T38 [cover off]': {
'writes': '324aac021ce35055',
'notes': '4f53cda18c2baa0c',
'guard': '86809c51ba676e49',
'floor': 'f0e12bc7f14924dc',
'batt': '3ce6bd3c1711cc3b'},
'T36 [Shape M, cover off]': {
'writes': '385ae1fbf07b25d6',
'notes': '4f53cda18c2baa0c',
'guard': '912e434b12e20f7e',
'floor': 'bbb7dc2b3e81dba8',
'batt': 'c262ee254e496a16'},
}
got = {}
def same(name, r, t0=0, parts=("writes", "notes", "guard", "batt"),
t1=1e9):
"""The run against c79eb37, part by part: its charger writes, the
notices with their second, the per-second guard view (floor,
car_explains, car_over, red rows) and the battery commands."""
d = {"writes": digest(view_writes(r)), "notes": digest(r["raised"]),
"guard": digest(view_guard(r, t0)),
"floor": digest([(x["t"], round(x["floor"] or 0.0))
for x in r["trace"] if t0 <= x["t"] < t1]),
"batt": digest([(round(t), e, v) for t, e, v in r["plant"].sets
if e.startswith("number.sp_")])}
got[name] = d
if TAKE:
print(f"GOLDEN {name!r}: {d!r},")
return
want = GOLDEN.get(name) or {}
diff = [k for k in parts if want.get(k) != d[k]]
check(f"{name}: identical to c79eb37 in {', '.join(parts)} (differs in: "
f"{diff})", bool(want) and not diff)
def manual_store(a=10.0, n=3):
st = rig._Store()
st.data["car_current"], st.data["car_phases"] = a, n
return st
# =========================================================================== #
print("\n1. MANUAL AND OFF DO NOT CHANGE (T4, T5, T37)")
# =========================================================================== #
for cover in (True, False):
r = shape("C", mode="manual", cover=cover, dur=1300, store=manual_store(),
setpoint=0)
same(f"T4 [Manual, cover {'on' if cover else 'off'}]", r)
r = shape("C", mode="off", dur=1300)
check(f"T5 [Off]: zero charger writes ({r['sim'].log[:2]})", not r["sim"].log)
same("T5 [Off]", r)
# =========================================================================== #
print("\n2. NO CUT WHERE NONE IS DUE (T6, T11, T38)")
# =========================================================================== #
r = shape("M", dur=1300)
same("T6 [Shape M: the batteries cover house and car]", r)
check(f"T6: no cut state in Shape M "
f"({[x['t'] for x in r['rec'].rows if x['cap'] is not None][:2]})",
not [x for x in r["rec"].rows if x["cap"] is not None])
# (a) A house step of 5 kW the batteries (60 %, 1 s to respond) take over
# within a few seconds: the guard wants power briefly, no cut.
r = drive(step_fn((960, 5900.0), base=900.0), const(7900.0), dur=1300,
first="car", phases=3, socs={"a": 60.0, "b": 60.0},
opts={"ev_phases": "3"},
events={1: lambda p, c: setattr(p, "response_s", 1.0)})
wants = [x["t"] for x in r["rec"].rows if (x["want"] or 0) > 0]
check(f"T11 (a): the guard wants power {len(wants)} s ({wants[:1]}..."
f"{wants[-1:]}), no cut state "
f"({[x['t'] for x in r['rec'].rows if x['cap'] is not None][:2]})",
0 < len(wants) <= 8
and not [x for x in r["rec"].rows if x["cap"] is not None])
same("T11 (a) [the batteries catch it in a few seconds]", r)
r = drive(const(900.0), step_fn((910, 3000.0), (1030, 13000.0),
base=13000.0),
dur=1300, first="car", phases=3, socs={"a": 60.0, "b": 60.0},
opts={"ev_phases": "3"})
same("T11 (b) [EV-05 T21b cloud edge, 16 A on 3 phases]", r)
check(f"T11 (b): no cut state ({[x['t'] for x in r['rec'].rows if x['cap'] is not None][:2]})",
not [x for x in r["rec"].rows if x["cap"] is not None])
def house_trace(t):
"""A 1 h house trace, 600 to 1500 W, deterministic."""
k = int(t) // 37
return 600.0 + (k * 7919 % 900)
def cover_off(p, c):
c.o["ev_batt_cover"] = False
for cover in (True, False):
# Cover off from 300 s, once Solar's own start is past: with it off from
# the start, PM Q2 / formal C14 with OQ3 cut Solar's own start blip at
# once (dev report, Findings). On c79eb37 both hours hash the same.
r = drive(house_trace, lambda t: house_trace(t) + 7000.0, dur=3600,
first="car", phases=3, socs={"a": 60.0, "b": 60.0},
opts={"ev_phases": "3"},
events={} if cover else {300: cover_off})
caps = [x["t"] for x in r["rec"].rows if x["cap"] is not None]
check(f"T38 [cover {'on' if cover else 'off'}]: no cut in an hour with no "
f"excess ({caps[:2]})", not caps)
same(f"T38 [cover {'on' if cover else 'off'}]", r)
# =========================================================================== #
print("\n3. THE COVER OFF: THE GUARD'S FLOOR (T36)")
# =========================================================================== #
r = shape("M", cover=False, dur=1300)
# Up to the cut. From it the car is lowered, so the plant differs from
# c79eb37's (there the car runs on); the cut itself is T36 in
# test_ev21_paths.py.
same("T36 [Shape M, cover off]", r, parts=("floor",), t1=960)
# =========================================================================== #
print("\n4. THE CUT AMOUNT OVER A TABLE OF SITES (T47)")
# =========================================================================== #
cut = _cutamps()
rows47 = []
def stamp(p, c):
c.car_solar.nonzero_at = p.t # Solar's own 30 s gate is closed
for n in (2, 1):
for cover in (True, False):
for ph, car_ph in (("3", 3), ("1", 3), ("auto", 3), ("3", 1)):
for first in (("car", "batteries") if ph == "3" and car_ph == 3
else ("car",)):
ratings = {"a": 5000.0, "b": 4600.0} if n == 2 \
else {"a": 5000.0}
room = 0.0 if first == "car" else 9600.0
if ph == "3" and car_ph == 3:
car_w, n_draw = 6900.0, 3 # 10 A on 3 phases
elif ph == "3":
car_w, n_draw = 3680.0, 1 # a 1-phase car, 16 A
else:
car_w, n_draw = 2300.0 if ph == "1" else 3680.0, 1
sun0 = 900.0 + max(car_w, 4830.0 + 500.0 if car_ph == 1
else car_w) + 100.0 + room
# The house steps so about 6.4 A is left after the cut.
d = 3400.0 + car_w - 6.4 * 230.0 * n_draw + 150.0 + room
ev = {t: refuse_n1 for t in range(0, 1001)} if n == 1 else {}
ev = merge(ev, 958, stamp)
r = drive(step_fn((960, 900.0 + d), base=900.0),
const(sun0), dur=1000,
first=first, phases=1 if ph == "1" else 3,
car_phases=car_ph, ratings=ratings,
socs={u: 10.0 for u in ratings}, events=ev,
rows=False,
opts={"ev_phases": ph, "ev_batt_cover": cover})
w = after(r, 958)
ep = [x for x in r["rec"].rows if x["t"] >= 958
and x["cap"] is not None]
want = cut(ep[0]["car0"], ep[0]["ex"], n_draw) if ep \
else "none"
ok = bool(w) and w[0][0] <= 961 and bool(ep) \
and ep[0]["cap"] == want and w[0][1] == want
rows47.append(((n, cover, ph, car_ph, first), w[:1],
ep[0]["cap"] if ep else None, want, ok))
bad47 = [x for x in rows47 if not x[-1]]
check(f"T47: over N=1/2, cover on/off, ev_phases 1/3/auto, a 1-phase car on "
f"3, Car/Batteries first ({len(rows47)} sites): the cut within 1 cycle "
f"and floor((car0 - excess) / (230 x the phases the car draws on)) "
f"({bad47[:3]})", rows47 and not bad47)
# =========================================================================== #
print("\n5. THE WRITE SEAM (T52) AND THE DOCS AND STRINGS (T53)")
# =========================================================================== #
def seam_callers():
out = []
for f in sorted(os.listdir(os.path.join(HERE, "app"))):
if not f.endswith(".py") or f == "chargers.py":
continue
tree = ast.parse(io.open(os.path.join(HERE, "app", f),
encoding="utf-8").read())
for n in ast.walk(tree):
if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) \
and n.func.attr in ("write_current", "write_phases"):
out.append((f, n.func.attr))
return sorted(out)
def calls_in(path, fn_names):
tree = ast.parse(io.open(os.path.join(HERE, "app", path),
encoding="utf-8").read())
out = []
for n in ast.walk(tree):
if isinstance(n, ast.FunctionDef) and n.name in fn_names:
for m in ast.walk(n):
if isinstance(m, ast.Call) and isinstance(m.func,
ast.Attribute):
out.append(m.func.attr)
return out
cut_calls = calls_in("ctl_car.py", {"_car_cut_tick", "_car_cut_hold",
"_car_cut_headroom"}) \
+ calls_in("carmode.py", {"_cut"})
check(f"T52: the write seam is still carmode.py's write_current and "
f"write_phases ({seam_callers()}); the cut's own code writes nothing and "
f"selects no phases ({sorted(set(cut_calls))})",
seam_callers() == [("carmode.py", "write_current"),
("carmode.py", "write_phases")]
and bool(cut_calls)
and not {"write_current", "write_phases", "_write", "_begin",
"_begin_solar", "_put"} & set(cut_calls))
def read(*p):
path = os.path.join(HERE, *p)
return io.open(path, encoding="utf-8").read() if os.path.exists(path) \
else ""
dec = " ".join(read("DECISIONS", "EV-21-car-cut-first.md").split())
docs = " ".join(read("DOCS.md").split())
chlog = read("CHANGELOG.md")
need = ["cut first", "15 s", "120 s", "Once per episode", "start power",
"can really cut"]
check(f"T53: DECISIONS/EV-21-car-cut-first.md states the rule in plain words "
f"({[w for w in need if w.lower() not in dec.lower()]} missing)",
bool(dec) and all(w.lower() in dec.lower() for w in need))
check("T53: DOCS 'Car charger' Solar section says the car is cut first, and "
"documents the grey note; the CHANGELOG has an EV-21 line",
"the car is cut first" in docs and "### Car lowered for the peak"
in docs and "`goodwe_car_cut`" in docs and "[[EV-21]]" in chlog)
tb = LOG.tracebacks(n_log0)
check(f"N11: no traceback in this file's runs ({tb[:1]})", not tb)
if TAKE:
print("(golden taken; no checks graded)")
sys.exit(0)
print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}")
sys.exit(1 if fails else 0)
+6 -2
View File
@@ -57,8 +57,12 @@ class _Cap(logging.Handler):
self.rec.append((r.levelno, r.getMessage()))
def loud(self, since=0):
"""INFO and above from `since` on."""
return [m for lv, m in self.rec[since:] if lv >= logging.INFO]
"""INFO and above from `since` on, but for EV-52's two plain lines
("Car: set ..." for a taken write, "Car mode is now ..."): they are
asserted in test_ev52.py (T11, T13); this file's rows are about every
OTHER line a phase change may log."""
return [m for lv, m in self.rec[since:] if lv >= logging.INFO
and not m.startswith(("Car: set", "Car mode is now"))]
CAP = _Cap()
File diff suppressed because it is too large Load Diff
+939
View File
@@ -0,0 +1,939 @@
"""EV-52: one plain info line when the add-on writes a new car current, and one
when the car mode changes. `python3 -B test_ev52.py`
Logging only: no write, no time and no notification changes (T43-T45 pin that
against golden lists taken on the base build 02166e2). The real Controller on
`tools/ev20_sun.py` (a model clock, the charger model, one 1 s cycle), as
test_ev20.py and test_ev21_paths.py use it; a few rows call the writer's own
`_write` from the run's finale or on a stub driver. Time is the model clock
throughout, never x10 and never wall time.
Rows T1-T45 and N1-N11 of reports/EV-52-test-plan.md, with T23 as PM ruling Q2
changed it: a write the charger took late logs its line ONCE, at the accept.
A "line" is an INFO record that starts `Car: set`; a "mode line" one that
starts `Car mode is now`; each is placed on the cycle second it was logged in
(None: before the first cycle or in the finale).
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import os
import re
import sys
from types import SimpleNamespace
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "tools"))
from app import carmode, chargers as CH, ctl_car # noqa: E402
import ev20_sun as S # noqa: E402
import ev21_kit as K # noqa: E402
from chargersim import SimCharger # noqa: E402
from ev20_kit import (LOG, check, fails, const, step_fn, act, # noqa: E402
report)
SET = S.SET
SETP = "Car: set"
MODEP = "Car mode is now"
MOPT = {"ev_phases": "1"} # a one-phase installation
ALL = [] # every run of this file, for N2 / N10
# The reason a caller names; the base build (no line) takes no such argument,
# so its rows read red there instead of crashing.
WHY = {"why": "Manual"} if hasattr(carmode.ManualWriter, "_log_set") else {}
# ------------------------------------------------------------------ helpers
def _stamp():
n0, stamps = LOG.mark(), {}
def oc(p, c, t):
stamps[t] = LOG.mark()
return n0, stamps, oc
def _tag(r, n0, stamps):
ts = sorted(stamps)
out = []
for i in range(n0, len(LOG.rec)):
lv, m, _x = LOG.rec[i]
out.append((next((t for t in ts if stamps[t] > i), None), lv, m))
r["lines"], r["n0"], r["end"] = out, n0, len(LOG.rec)
ALL.append(r)
return r
def run(mode, dur, house=900.0, sun=0.0, events=None, **kw):
n0, stamps, oc = _stamp()
r = S.drive(house if callable(house) else const(house),
sun if callable(sun) else const(sun), dur=dur, mode=mode,
events=events, on_cycle=oc, **kw)
return _tag(r, n0, stamps)
def kdrive(house, sun, **kw):
n0, stamps, oc = _stamp()
r = K.drive(house, sun, on_cycle=oc, **kw)
return _tag(r, n0, stamps)
def kshape(kind, **kw):
n0, stamps, oc = _stamp()
r = K.shape(kind, on_cycle=oc, **kw)
return _tag(r, n0, stamps)
def sets(r, lo=None, hi=None):
return [(t, m) for t, lv, m in r["lines"]
if m.startswith(SETP)
and (lo is None or (t if t is not None else 1e12) >= lo)
and (hi is None or (t if t is not None else 1e12) < hi)]
def texts(r, **kw):
return [m for _t, m in sets(r, **kw)]
def modes(r):
return [(t, m) for t, lv, m in r["lines"] if m.startswith(MODEP)]
def taken(r):
"""Every current write the charger took, Manual's and Solar's."""
return [x for w in (r["c"].car_writer, r["c"].car_solar) for x in w.log
if x[0] == "current" and x[3]]
def warns(r, text):
return [m for _t, lv, m in r["lines"] if lv == "WARNING" and text in m]
def wlist(r):
return [(round(t), v) for t, v in S.writes(r)]
def amps_in(m):
return float(re.search(r" to (\d+) A", m).group(1))
MANUAL = {10: act("car_phases", 1), 15: act("car_current", 6),
20: act("car_mode", "manual")}
def manual(dur, events=None, **kw):
ev = dict(MANUAL)
ev.update(events or {})
kw.setdefault("setpoint", 10)
kw.setdefault("phases", 1)
kw.setdefault("car_phases", 1)
kw.setdefault("opts", MOPT)
return run("off", dur, events=ev, **kw)
def solar(dur, house=900.0, sun=7900.0, **kw):
kw.setdefault("first", "car")
kw.setdefault("phases", 1)
kw.setdefault("car_phases", 1)
kw.setdefault("opts", MOPT)
return run("solar", dur, house=house, sun=sun, **kw)
def both(*fns):
async def f(p, c):
for fn in fns:
x = fn(p, c)
if asyncio.iscoroutine(x):
await x
return f
async def _shutdown(p, c):
await c.shutdown()
def refuse(kind):
def f(p, c):
p.ch.refuse = kind
return f
def lift(p, c):
p.ch.refuse = None
# =========================================================================== #
print("1. MANUAL: A NEW CURRENT LOGS ONE LINE (T1-T3)")
# =========================================================================== #
r1 = manual(500, events={200: act("car_current", 8),
300: act("car_current", 8)})
s1 = sets(r1)
check(f"T1: Manual 10 -> 6 A (user set 6 A, then Manual), 180 cycles: exactly "
f"1 line, old 10 A, 1 phase, Manual ({texts(r1, hi=200)})",
texts(r1, hi=200) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."])
check(f"T1: logged in the writer's own step at the action's cycle "
f"({s1[:1]}) at INFO, and it equals what was sent "
f"({r1['c'].charger.sent[:1]})",
[t for t, _m in s1[:1]] == [20] and r1["c"].charger.sent[0] == 6.0
and all(lv == "INFO" for _t, lv, m in r1["lines"]
if m.startswith(SETP)))
check(f"T2: the user sets 8 A: exactly 1 more line, 6 -> 8, Manual "
f"({texts(r1, lo=200)})",
texts(r1, lo=200) == ["Car: set from 6 A to 8 A on 1 phase (Manual)."])
check(f"T3: the same 8 A again and 200 more cycles: 0 new lines and 0 new "
f"writes ({len(s1)} lines, {len(wlist(r1))} writes)",
len(sets(r1, lo=300)) == 0 and len(wlist(r1)) == 2)
check("T3/N4: one line per taken write, none per cycle",
len(s1) == len(taken(r1)) == 2)
check("T1: the mode line comes with the action",
[m for t, m in modes(r1) if t == 20] == ["Car mode is now Manual."])
# T24 / T25: the old value, or the phases, unknown. The writer's own `_write`
# from the finale: no old value, then no reading at all.
async def _unknown(p, c):
w = c.car_writer
await w._write(c.charger, 7.0, None, 400.0, c.car, **WHY)
w._r = None
await w._write(c.charger, 9.0, None, 401.0, c.car, **WHY)
r24 = manual(150, finale=_unknown)
check(f"T24/T25: the old value unknown: 'set to 7 A on 1 phase'; no reading, "
f"so no phase count either: 'set to 9 A (Manual)'; no exception "
f"({[m for t, m in sets(r24) if t is None]})",
[m for t, m in sets(r24) if t is None] == [
"Car: set to 7 A on 1 phase (Manual).",
"Car: set to 9 A (Manual)."])
def _odd():
w = carmode.ManualWriter()
n0 = LOG.mark()
for a, was, n in ((float("nan"), 6.0, 1), (None, 6.0, 1),
("x", None, 3), (6.0, float("inf"), "1"),
(6.0, 6.0, 1)):
if hasattr(w, "_log_set"): # the base build has none: red, not a crash
w._log_set(a, was, "Manual", n)
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check(f"N9: a NaN, None, text or infinite figure never raises and logs "
f"nothing wrong; an unchanged value logs nothing ({_odd()})",
_odd() == ["Car: set to 6 A (Manual)."])
# =========================================================================== #
print("\n2. THE MODE (T4-T6, T31)")
# =========================================================================== #
r4 = manual(200, events={100: act("car_mode", "manual"),
110: act("car_current", 9),
120: act("car_phases", 1),
130: act("car_sun_first", "car"),
140: act("car_mode", "bogus"),
150: act("car_current", 9)})
check(f"T4: Off -> Manual: exactly 1 mode line at the action ({modes(r4)})",
[m for t, m in modes(r4) if t == 20] == ["Car mode is now Manual."])
check(f"T4: the add-on's start logs the mode it started in, once "
f"({modes(r4)[:1]})", modes(r4)[:1] == [(0.0, "Car mode is now Off.")])
check(f"T5: Manual picked again, a value, the phases, Sun first and a bad "
f"mode: no mode line ({modes(r4)})", len(modes(r4)) == 2)
r6 = run("off", 300, events={20: act("car_mode", "manual"),
40: act("car_current", 9)},
opts={"ev_charger": "off"})
check(f"T6/N6: no charger: no car line, no mode line, not at start-up "
f"either ({[m for _t, _l, m in r6['lines'] if m.startswith(('Car:', MODEP))]})",
not [m for _t, _l, m in r6["lines"]
if m.startswith(("Car:", MODEP))] and not wlist(r6))
r31 = run("solar", 60, opts=dict(MOPT, ev_mode_start="off"), first="car",
phases=1, car_phases=1)
check(f"T31: ev_mode_start off with Solar stored: one mode line, Off "
f"({modes(r31)})",
[m for _t, m in modes(r31)] == ["Car mode is now Off."])
# =========================================================================== #
print("\n3. SOLAR (T7-T10, T14, T26)")
# =========================================================================== #
r7 = solar(700)
t7 = sets(r7)[0][0] if sets(r7) else -10 ** 6
check(f"T7: Solar, Car first, spare sun, charger at 0 A: exactly 1 line for "
f"the start current ({texts(r7)})",
texts(r7) == ["Car: set from 0 A to 16 A on 1 phase (Solar)."])
check(f"T7: the line is in the step of the write ({t7}; write {wlist(r7)})",
wlist(r7) == [(t7 + 1, 16)])
check("T9: Solar steady, 580 cycles after the start: 0 new lines",
len(sets(r7, lo=t7 + 1)) == 0)
check("T7: the mode line once, at start-up",
[m for _t, m in modes(r7)] == ["Car mode is now Solar."])
def cloud_house(t):
return 900.0 + 800.0 if 300 <= t < 720 else 900.0
r8 = solar(900, house=cloud_house, sun=3400.0)
check(f"T8: Solar steady, a cloud (the house imports 800 W for 420 s): one "
f"line per taken write, each Solar ({texts(r8)}, taken "
f"{len(taken(r8))})",
len(sets(r8)) == len(taken(r8)) and len(sets(r8)) >= 2
and all(m.endswith("(Solar).") for m in texts(r8)))
def dither(t):
return 900.0 + 2300.0 + 100.0 + (0.0 if int(t // 7) % 2 else -10.0)
r10 = solar(900, sun=dither)
ln = [t for t, _m in sets(r10)]
gaps = [b - a for a, b in zip(ln, ln[1:])]
check(f"T10: spare dithering on an amp boundary: lines == taken writes "
f"({len(ln)}), at most one per SOLAR_WRITE_S ({gaps}); it fired "
f"{len(ln)} times in 900 s",
len(ln) == len(taken(r10)) and all(g >= carmode.SOLAR_WRITE_S - 1
for g in gaps))
r14 = run("solar", 900, sun=9600.0, first="car", phases=1, car_phases=3)
t14 = texts(r14)
z14 = [m for m in t14 if " to 0 A on 1 phase (Solar)" in m]
c14 = [m for m in t14 if "on 3 phases (Solar)" in m]
check(f"T14: Solar auto 1 -> 3 phases: one 0 A line on 1 phase, one close on "
f"3 phases, nothing else ({t14}; selects {S.writes(r14, 'phases')})",
len(S.writes(r14, "phases")) == 1 and len(z14) == 1 and len(c14) == 1
and len(t14) == 3 and t14.index(z14[0]) < t14.index(c14[0]))
check("T12: the select itself logs nothing: one line per taken current write",
len(sets(r14)) == len(taken(r14)))
r26 = solar(300, sun=0.0, setpoint=0)
check(f"T26: Solar, the charger already shows the 0 A Solar wants: no write, "
f"0 lines ({texts(r26)}, writes {wlist(r26)})",
not texts(r26) and not wlist(r26))
# =========================================================================== #
print("\n4. MANUAL PHASE CHANGE (T11-T13, T42)")
# =========================================================================== #
r11 = manual(300, events={200: act("car_phases", 3)}, car_phases=3, opts={})
t11 = texts(r11, lo=200)
s11 = [t for t, _m in sets(r11, lo=200)]
check(f"T11: Manual 6 A on 1 phase, the user picks 3 phases, the car stops: "
f"exactly 2 lines, the 0 A on 1 phase and the 6 A on 3 ({t11})",
t11 == ["Car: set from 6 A to 0 A on 1 phase (Manual).",
"Car: set from 0 A to 6 A on 3 phases (Manual)."])
check(f"T11/T12: the 0 A logs as a write; the close comes after the select "
f"and the 10 s settle, the select itself logs nothing ({s11}; selects "
f"{S.writes(r11, 'phases')})",
len(s11) == 2 and s11[1] - s11[0] >= carmode.SETTLE_S
and len(S.writes(r11, "phases")) == 1)
def drawing(p, c):
p.ch.ramp_w_s = 0.0001 # the car does not let go
r13 = manual(400, events={200: both(drawing, act("car_phases", 3))},
car_phases=3, opts={})
t13 = texts(r13, lo=200)
check(f"T13: the car keeps drawing: the 0 A line, the existing warning once, "
f"the restore line on 1 phase ({t13})",
t13 == ["Car: set from 6 A to 0 A on 1 phase (Manual).",
"Car: set from 0 A to 6 A on 1 phase (Manual)."]
and len(warns(r13, "The car kept drawing, so the phases were not "
"changed.")) == 1)
def shadow_on(p, c):
c.o["shadow_mode"] = "on"
r42 = manual(260, events={200: act("car_phases", 3), 201: shadow_on},
car_phases=3, opts={})
t42 = texts(r42, lo=200)
check(f"T42: shadow mode in the middle of a phase change: the 0 A and the one "
f"write shadow allows, Manual's undo: 2 lines, then none ({t42})",
t42 == ["Car: set from 6 A to 0 A on 1 phase (Manual).",
"Car: set from 0 A to 6 A on 1 phase (Manual)."]
and not S.writes(r42, "phases"))
# =========================================================================== #
print("\n5. THE PEAK CUT (T15-T17, T41)")
# =========================================================================== #
r15 = kdrive(step_fn((960, 900.0 + 5700.0), (966, 900.0 + 9000.0), base=900.0),
const(13000.0), dur=1100, first="car", phases=3,
socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"},
events={958: lambda p, c: setattr(c.car_solar, "nonzero_at",
p.t)})
cuts = sets(r15, lo=958)
wcut = [v for t, v in S.writes(r15) if t >= 958]
check(f"T15: the EV-21 cut (two cuts as the excess grows): one line per cut, "
f"each 'peak cut' with the value written ({[m for _t, m in cuts]}; "
f"writes {wcut})",
len(cuts) == len(wcut) >= 1
and all(m.endswith("(peak cut).") for _t, m in cuts)
and [amps_in(m) for _t, m in cuts] == wcut)
cut_note = [m for _t, lv, m in r15["lines"]
if m == "Solar lowered the car for the peak: CAR_CUT."]
check(f"T15: the existing CAR_CUT info line and notice once per session, "
f"unchanged ({len(cut_note)}, notices "
f"{[n for _t, n in r15['raised'] if 'cut' in n]})", len(cut_note) == 1)
check("T15: the 16 A before the cut was Solar's own line, not a cut",
texts(r15, hi=958)[-1].endswith("(Solar).") if texts(r15, hi=958)
else False)
r16 = kshape("C", dur=1300)
c16 = texts(r16, lo=950)
check(f"T16: a cut deeper than the car can follow (to 0 A): the line says "
f"'to 0 A' and 'peak cut' ({c16})",
c16 == ["Car: set from 10 A to 0 A on 3 phases (peak cut)."])
r18 = kshape("C", dur=1300,
events={959: lambda p, c: setattr(p.ch, "refuse", "ignore")})
check(f"T18: the cut refused (3 tries 60 s apart): the existing CHARGER_REFUSED "
f"once, 0 lines for the cut ({texts(r18, lo=950)}, "
f"{len(warns(r18, 'CHARGER_REFUSED'))}, tries "
f"{[round(t) for t, v in S.writes(r18) if t >= 959]})",
not texts(r18, lo=950) and len(warns(r18, "CHARGER_REFUSED")) == 1
and len([1 for t, v in S.writes(r18) if t >= 959]) == 3)
class Drv:
"""A driver that takes, or not, what it is given, for the writer's own
steps. `write_current` notes how many log records existed when it
returned (N3: the line follows the write)."""
def __init__(self, ok=True):
self.ok, self.sent, self.marks = ok, [], []
async def write_current(self, a, **kw):
self.sent.append(a)
self.marks.append(LOG.mark())
return self.ok
async def write_phases(self, n):
return True
def reading(**kw):
base = dict(available=True, state="C", power_w=0.0, phases_allowed=3,
allowed_a=0.0, setpoint_a=0.0)
base.update(kw)
return CH.ChargerReading(**base)
def tracker():
return CH.CarTracker()
def go(coro):
return asyncio.run(coro)
# T17: the cut's cap lowers the closing current of a phase change.
async def t17():
w = carmode.SolarWriter()
drv, tr = Drv(), tracker()
w.plan.a, w.plan.target_w, w.plan.n = 16.0, 16.0 * 230.0 * 3, 3
w.cut_a = 8.0
w.seq = {"stage": "settle", "t0": 0.0, "t1": 0.0, "n": 3, "tries": 0,
"prev": None, "sel_ok": True}
n0 = LOG.mark()
await w._advance(drv, reading(), 0.0, 20.0, tr, w._seq_want(16.0, 3),
16.0, None)
return drv, [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
d17, l17 = go(t17())
check(f"T17: a cut due while Solar's phase change is under way: the close "
f"carries 'peak cut' and the capped value, no extra line ({l17}, sent "
f"{d17.sent})",
l17 == ["Car: set from 0 A to 8 A on 3 phases (peak cut)."]
and d17.sent == [8.0])
async def t17b():
w = carmode.SolarWriter()
drv, tr = Drv(), tracker()
w.plan.a, w.plan.target_w, w.plan.n = 10.0, 10.0 * 230.0 * 3, 3
w.seq = {"stage": "settle", "t0": 0.0, "t1": 0.0, "n": 3, "tries": 0,
"prev": None, "sel_ok": True}
n0 = LOG.mark()
await w._advance(drv, reading(), 0.0, 20.0, tr, w._seq_want(16.0, 3),
16.0, None)
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check(f"T17: the same close with no cut: 'Solar', the plan's value "
f"({go(t17b())})",
go(t17b()) == ["Car: set from 0 A to 10 A on 3 phases (Solar)."])
# T41: a write either side of the quarter boundary (900): one line each.
sun41 = step_fn((899, 4760.0), (931, 4100.0), base=4300.0)
r41 = solar(1000, sun=sun41)
l41 = sets(r41, lo=890, hi=960)
check(f"T41: Solar writes at 899 and 931 across the quarter boundary: one "
f"line each, no duplicate ({l41}, writes "
f"{[x for x in wlist(r41) if x[0] > 890]})",
len(l41) == 2 and len({m for _t, m in l41}) == 2
and len(l41) == len([1 for t, v in S.writes(r41) if t > 890]))
# =========================================================================== #
print("\n6. FAILED OR LATE WRITES (T19-T23, T33, T37, T39, N2, N3)")
# =========================================================================== #
REF = "The charger did not take the current, so the add-on stops asking"
for kind in ("ignore", "error"):
r19 = manual(400, events={19: refuse(kind)})
check(f"T19 [{kind}]: Manual write refused, 3 tries 60 s apart: 0 lines, "
f"CHARGER_REFUSED once, text unchanged ({texts(r19)}, "
f"{len(warns(r19, REF))})",
not texts(r19) and len(warns(r19, REF)) == 1)
r20 = manual(300, events={19: refuse("ignore"), 40: lift})
t20 = sets(r20)
check(f"T20: refused once, the charger takes it at the retry: exactly 1 line, "
f"at the retry, 60 s or more after the fail ({t20})",
len(t20) == 1 and t20[0][0] >= 20 + 60
and t20[0][1] == "Car: set from 10 A to 6 A on 1 phase (Manual).")
async def _clamp(p, c):
p.clamp_ok = await c.car_writer._write(c.charger, 30.0, 10.0, 400.0, c.car)
r21 = manual(120, finale=_clamp)
fin = [(lv, m) for t, lv, m in r21["lines"] if t is None]
check(f"T21: a write above the clamp: CHARGER_CLAMP error unchanged, nothing "
f"sent, no line ({[(lv, m[:30]) for lv, m in fin]})",
any(lv == "ERROR" and m.endswith("CHARGER_CLAMP.") for lv, m in fin)
and not [m for lv, m in fin if m.startswith(SETP)]
and r21["plant"].clamp_ok is False)
class RaisingPlant(S.SunPlant):
"""Home Assistant whose call on the current entity raises, from 19 s."""
async def set_number(self, e, v):
if e == SET and self.t >= 19.0:
raise RuntimeError("HA call error")
return await super().set_number(e, v)
r22 = manual(200, plant_cls=RaisingPlant)
check(f"T22: the driver raises in write_current: 0 lines, the existing 'step "
f"failed' error once, no new exception from the log path "
f"({texts(r22)})",
not texts(r22) and len([1 for _t, lv, m in r22["lines"]
if lv == "ERROR"
and m == "The car charger step failed"]) == 1)
def slow(p, c):
p.ch.lag_s = 12.0 # over TOOK_S (10 s)
r23 = solar(400, events={100: slow})
w23 = [(round(t), v) for t, v in S.writes(r23)]
check(f"T23 (Q2): a late read-back (12 s, over TOOK_S): the write is not "
f"taken at once, then adopted; exactly 1 'set' line, at the accept "
f"({sets(r23)}, write {w23})",
texts(r23) == ["Car: set from 0 A to 16 A on 1 phase (Solar)."]
and sets(r23)[0][0] >= 120 + 10
and len(taken(r23)) == 0)
check("T23 (Q2): no line at the write itself, none for the failed try",
not sets(r23, hi=130))
async def t23b():
"""The accept after the warning: three refused tries, then the charger
shows the value (late): the warning is the existing one, then one line."""
w = carmode.SolarWriter()
drv, tr = Drv(ok=False), tracker()
w.engaged = True
n0 = LOG.mark()
for k in range(3):
await w._write(drv, 16.0, 0.0, 100.0 + 70 * k, tr)
mid = [m for _lv, m, _x in LOG.rec[n0:]]
w._adopt(16.0)
w._adopt(16.0) # a second read-back: nothing again
end = [m for _lv, m, _x in LOG.rec[n0:]]
return mid, end
mid, end = go(t23b())
check(f"T23 (Q2): three tries not taken give the existing CHARGER_REFUSED "
f"warning and no line; the accept then gives exactly one line "
f"({mid} -> {end})",
len(mid) == 1 and mid[0].endswith("CHARGER_REFUSED.")
and end[1:] == ["Car: set from 0 A to 16 A (Solar)."])
async def t23c():
w = carmode.SolarWriter()
drv, tr = Drv(ok=False), tracker()
n0 = LOG.mark()
await w._write(drv, 16.0, 0.0, 100.0, tr)
w._adopt(10.0) # shows something else: not our write
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check("T23/M4: a read-back that shows another value is not an accept: 0 lines",
go(t23c()) == [])
# Q2 for Manual: a write taken late logs its line once, at the accept.
r23m = manual(200, events={10: slow})
w23m = [(round(t), v) for t, v in S.writes(r23m)]
check(f"T23 Manual (Q2): a late read-back (12 s): no line at the write, "
f"exactly 1 line at the accept, a few seconds later ({sets(r23m)}, "
f"write {w23m})",
texts(r23m) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."]
and sets(r23m)[0][0] >= 20 + 10 and len(taken(r23m)) == 0)
async def t23m():
"""Three tries not taken: the existing CHARGER_REFUSED warning, no line;
the charger then shows the value: exactly one line, once."""
w = carmode.ManualWriter()
w.boot = False
drv, tr = Drv(ok=False), tracker()
async def step(a, now):
await w.step(drv, reading(state="C", allowed_a=a, setpoint_a=a,
phases_allowed=1), mode=carmode.MANUAL,
want_a=6.0, want_phases=1, rev=1, clamp=16.0, now=now,
tracker=tr, writing=True, status="charging")
n0 = LOG.mark()
for k in range(3):
await step(10.0, 100.0 + 70 * k)
mid = [m for lv, m, _x in LOG.rec[n0:] if lv != "DEBUG"]
await step(6.0, 300.0)
await step(6.0, 310.0) # the next read-back: nothing again
return mid, [m for lv, m, _x in LOG.rec[n0:] if lv != "DEBUG"]
mid, end = go(t23m())
check(f"T23 Manual (Q2): three tries not taken give the existing Manual "
f"CHARGER_REFUSED warning and no line; the accept then gives exactly "
f"one line ({mid} -> {end})",
len(mid) == 1 and mid[0].endswith("CHARGER_REFUSED.")
and end[1:] == ["Car: set from 10 A to 6 A on 1 phase (Manual)."])
async def stale(shape):
"""Review round 2: a refused Manual try is not a request any more once
the user changed something or another mode ran. Another source then
shows the same value; Manual's adopt must log nothing."""
w = carmode.ManualWriter()
w.boot = False
drv, tr = Drv(ok=False), tracker()
async def step(a, now, mode=carmode.MANUAL, rev=1):
await w.step(drv, reading(state="C", allowed_a=a, setpoint_a=a,
phases_allowed=1), mode=mode,
want_a=6.0, want_phases=1, rev=rev, clamp=16.0, now=now,
tracker=tr, writing=True, status="charging")
n0 = LOG.mark()
await step(10.0, 100.0) # refused
if shape == "solar": # the user picks Solar, then Manual
w.user_changed()
await step(10.0, 200.0, mode=carmode.SOLAR, rev=2)
await step(6.0, 300.0, mode=carmode.SOLAR, rev=2) # Solar's own 6 A
w.user_changed()
await step(6.0, 500.0, rev=3)
elif shape == "off": # Off, the wallbox app sets 6 A
await step(10.0, 150.0, mode=carmode.OFF)
await step(6.0, 400.0, mode=carmode.OFF)
await step(6.0, 500.0)
else: # the user changed the value
w.user_changed()
await step(6.0, 500.0, rev=2)
return [m for lv, m, _x in LOG.rec[n0:]
if lv != "DEBUG" and m.startswith(SETP)]
for shape in ("solar", "off", "user"):
check(f"T23 Manual (review round 2, N2) [{shape}]: a refused try is not "
f"logged later when the same value comes from another source",
go(stale(shape)) == [])
async def t23l():
"""Review round 2: Solar's refused try is history once Solar is left;
a later read-back of that value logs nothing."""
w = carmode.SolarWriter()
drv, tr = Drv(ok=False), tracker()
w.engaged = True
n0 = LOG.mark()
await w._write(drv, 16.0, 0.0, 100.0, tr)
w._leave()
w._adopt(16.0)
return [m for _lv, m, _x in LOG.rec[n0:] if m.startswith(SETP)]
check("T23 (review round 2, N2) [solar leave]: a refused Solar try is not "
"logged after Solar is left: 0 lines", go(t23l()) == [])
# T33: shutdown, the charger refuses all 3 release tries.
async def _refuse_shutdown(p, c):
p.ch.refuse = "ignore"
await c.shutdown()
r33 = solar(300, finale=_refuse_shutdown)
check(f"T33: Solar shutdown, the charger refuses all 3 release tries: "
f"CHARGER_RELEASE unchanged once, 0 shutdown lines "
f"({texts(r33, lo=121)}, {len(warns(r33, 'CHARGER_RELEASE'))})",
len(warns(r33, "CHARGER_RELEASE")) == 1 and not texts(r33, lo=121)
and not [m for t, m in sets(r33) if "(shutdown)" in m])
# T37: stale charger reads with no write due.
r37 = solar(500, events={300: lambda p, c: p.ch.freeze(),
308: lambda p, c: p.ch.freeze(False)})
check(f"T37: a frozen charger reading for 8 s with no write due: 0 lines "
f"({texts(r37, lo=125)}, writes {wlist(r37)})",
not texts(r37, lo=125) and len(wlist(r37)) == 1)
# T39: a stuck (frozen) charger, Solar's starts are not taken.
r39 = solar(1300, events={100: lambda p, c: p.ch.freeze()})
check(f"T39: a stuck charger reading, the 3 starts not taken: 0 lines, the "
f"stuck CHARGER_REFUSED once, unchanged "
f"({texts(r39)}, {len(warns(r39, 'CHARGER_REFUSED'))}, "
f"{len([1 for t, v in S.writes(r39) if v > 0])} starts)",
not texts(r39) and len(warns(r39, "CHARGER_REFUSED")) == 1)
# N3: the line follows the write: nothing is logged before it returns.
async def n3():
w = carmode.ManualWriter()
drv, tr = Drv(), tracker()
n0 = LOG.mark()
await w._write(drv, 7.0, 10.0, 50.0, tr, **WHY)
rec = LOG.rec[n0:]
first = next((i for i, x in enumerate(rec) if x[1].startswith(SETP)),
10 ** 9)
return n0 + first, drv.marks[0]
at, ret = go(n3())
check(f"N3: the line is logged after write_current returned (record {at} vs "
f"the driver's return at {ret})", ret <= at < 10 ** 8)
# =========================================================================== #
print("\n7. START-UP, SHUTDOWN, WAYS OUT (T27-T30, T32, T34-T36, T38, T40)")
# =========================================================================== #
st27 = S.rig._Store()
st27.data["car_current"] = 6.0
r27 = run("manual", 120, store=st27, setpoint=10, phases=1, car_phases=1,
opts=MOPT)
check(f"T27: restart in Manual, stored 6 A, the charger shows 10 A: 1 mode "
f"line at start-up, exactly 1 line, 'start-up' "
f"({modes(r27)}, {texts(r27)})",
[m for _t, m in modes(r27)] == ["Car mode is now Manual."]
and texts(r27) == ["Car: set from 10 A to 6 A on 1 phase (start-up)."])
r28 = solar(400, setpoint=10)
check(f"T28: restart in Solar, the charger shows its own 10 A (D2): the mode "
f"line, the 0 A as 'start-up', the start current as 'Solar' "
f"({texts(r28)})",
[m for _t, m in modes(r28)] == ["Car mode is now Solar."]
and texts(r28) == ["Car: set from 10 A to 0 A on 1 phase (start-up).",
"Car: set from 0 A to 16 A on 1 phase (Solar)."])
st29 = S.rig._Store()
st29.data[ctl_car.CAR_EXIT_KEY] = True
r29 = run("off", 120, store=st29, setpoint=10, phases=1, car_phases=1,
opts=MOPT)
check(f"T29: restart in Off with the exit 0 A owed (C1), charger 10 A: the "
f"mode line Off and 1 line 'to 0 A (start-up)' "
f"({modes(r29)}, {texts(r29)})",
[m for _t, m in modes(r29)] == ["Car mode is now Off."]
and texts(r29) == ["Car: set from 10 A to 0 A on 1 phase (start-up)."])
r30 = run("off", 2000, events={1800: act("car_mode", "manual")}, setpoint=10,
phases=1, car_phases=1, opts=MOPT)
check(f"T30: restart in Off, nothing owed; 30 min later the user picks "
f"Manual: the start mode line once, the later write is 'Manual', not "
f"'start-up' ({modes(r30)}, {texts(r30)})",
[m for _t, m in modes(r30)] == ["Car mode is now Off.",
"Car mode is now Manual."]
and texts(r30) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."])
check("T30: the Manual line is not 'start-up' even for the first write of "
"the process (M9)", bool(texts(r30))
and "start-up" not in " ".join(texts(r30)))
r32 = solar(300, finale=_shutdown)
check(f"T32: Solar shutdown, 0 A taken: 1 line 'to 0 A ... (shutdown)' "
f"({texts(r32, lo=121)}, {[t for t, m in sets(r32)]})",
[m for t, m in sets(r32) if t is None] == [
"Car: set from 16 A to 0 A on 1 phase (shutdown)."])
r34 = manual(205, events={200: act("car_phases", 3)}, car_phases=3, opts={},
finale=_shutdown)
check(f"T34: Manual shutdown in the middle of a phase change (abandon), the "
f"give-back taken: 1 line, 'shutdown' ({texts(r34, lo=200)})",
[m for t, m in sets(r34) if t is None] == [
"Car: set from 0 A to 6 A on 3 phases (shutdown)."])
r35 = solar(400, events={300: act("car_mode", "off")})
check(f"T35: Solar -> Off while Solar's 16 A stands: 1 mode line Off, 1 line "
f"'to 0 A (Solar)' (Q3), then nothing ({modes(r35)[-1:]}, "
f"{texts(r35, lo=300)})",
[m for _t, m in modes(r35)[-1:]] == ["Car mode is now Off."]
and texts(r35, lo=300) == [
"Car: set from 16 A to 0 A on 1 phase (Solar)."])
r36 = solar(400, events={300: act("car_mode", "manual")})
check(f"T36: Solar -> Manual (user 6 A, charger 16 A): 1 mode line and 1 line "
f"for Manual's 6 A, reason Manual ({modes(r36)[-1:]}, "
f"{texts(r36, lo=300)})",
[m for _t, m in modes(r36)[-1:]] == ["Car mode is now Manual."]
and texts(r36, lo=300) == [
"Car: set from 16 A to 6 A on 1 phase (Manual)."])
r38 = kshape("C", dur=1400, events={940: lambda p, c: setattr(p, "meter_on",
False)})
check(f"T38: the meter silent past meter_max_age_s: Solar's pause, exactly 1 "
f"line 'to 0 A (Solar)' ({texts(r38, lo=940)})",
texts(r38, lo=940) == [
"Car: set from 10 A to 0 A on 3 phases (Solar)."])
class Liar(SimCharger):
"""The read-back shows what was asked; the car draws a third more."""
def target_w(self):
w = super().target_w()
return w * 8.0 / 6.0 if self.setpoint_a == 6.0 else w
r40 = manual(120, sim=Liar(setpoint_a=10))
check(f"T40: the read-back shows 6 A but the car draws 8 A (1840 W): the line "
f"says 6 A, what was written ({texts(r40)}, car "
f"{round(r40['trace'][-1]['car'])} W)",
texts(r40) == ["Car: set from 10 A to 6 A on 1 phase (Manual)."]
and round(r40["trace"][-1]["car"]) == 1840)
# =========================================================================== #
print("\n8. NOTHING ELSE MOVES (T43-T45, N1, N2, N7, N8, N10, N11)")
# =========================================================================== #
# N5: a mode line only for a mode change (and the one at start-up).
chg4 = 1 + 1 # r4: the start, then Off -> Manual
check(f"N5: no mode line without a change: {len(modes(r4))} in r4 (start + "
f"the one change, six more same-mode or refused actions), "
f"{len(modes(r7))} in a 700 s Solar run with no action, "
f"{len(modes(r1))} in r1 (start + Manual, two same-value actions)",
len(modes(r4)) == chg4 and len(modes(r7)) == 1 and len(modes(r1)) == 2
and len(modes(r30)) == 2)
# N8: the existing warning and info texts are the base's, word for word.
EXACT = {
"The charger did not take the current, so the add-on stops asking until "
"you change it: CHARGER_REFUSED.",
"The charger did not take the current, so the add-on stops asking until "
"you press Solar: CHARGER_REFUSED.",
"The charger did not take the current, so the add-on tries again in 15 "
"min, then every 30 min: CHARGER_REFUSED.",
"The charger did not take 0 A before the add-on stopped, so the car may "
"still be charging: CHARGER_RELEASE.",
"Software fault: the add-on was about to ask the charger for more than "
"its limit, so nothing was sent: CHARGER_CLAMP.",
"Solar lowered the car for the peak: CAR_CUT.",
"The car kept drawing, so the phases were not changed."}
seen8 = {m for r in ALL for _t, lv, m in r["lines"] if lv != "DEBUG"
and ("CHARGER_" in m or "CAR_CUT" in m or "kept drawing" in m)}
check(f"N8: every CHARGER_* / CAR_CUT / kept-drawing line seen in any run is "
f"one of base's texts, and each of the seven was seen "
f"({sorted(seen8 - EXACT)[:2]}, missing {sorted(EXACT - seen8)[:2]})",
seen8 == EXACT)
# T44: the existing suites run unedited in CI (checks / unit) and were run
# here (the report lists them). What a unit row can pin: the two existing
# files this ticket had to touch still hold their own assertions and set
# aside ONLY the two new prefixes.
_here = os.path.dirname(os.path.abspath(__file__))
_t28 = open(os.path.join(_here, "test_ev28.py")).read()
_t51 = open(os.path.join(_here, "test_ev51.py")).read()
check("T44: test_ev28 and test_ev51 keep their pinned rows and filter only "
"'Car: set' and 'Car mode is now'",
'check(f"T13: a clean change logs nothing at INFO or above' in _t28
and "CAP.loud(MARK[0]) == []" in _t28
and "info == BASE_INFO" in _t51
and _t28.count('("Car: set", "Car mode is now")') == 1
and _t51.count('("Car: set", "Car mode is now")') == 1)
# Taken on the base build 02166e2 with EV52_GOLDEN=1 (the same scenarios).
_CAR1 = ["car current set to 8 by operator", "car current set to 8 by operator",
"car mode set to manual by operator", "car current set to 6 by operator",
"car phases set to 1 by operator"]
GOLDEN = {
"T1": {"cur": [(21, 6.0), (201, 8.0)], "events": _CAR1,
"keys": "bb1fe135bd15690c", "notes": [], "ph": [],
"sent": [6.0, 8.0]},
"T11": {"cur": [(21, 6.0), (201, 0.0), (212, 6.0)],
"events": ["car phases set to 3 by operator",
"car mode set to manual by operator",
"car current set to 6 by operator",
"car phases set to 1 by operator"],
"keys": "bb1fe135bd15690c", "notes": [], "ph": [(202, 3)],
"sent": [6.0, 0.0, 6.0]},
"T15": {"cur": [(121, 16.0), (961, 13.0), (967, 12.0), (997, 6.0)],
"events": [], "keys": "00425fef63358fa7",
"notes": [(13, "goodwe_integrator_bound"), (961, "goodwe_car_cut")],
"ph": [], "sent": [16.0, 13.0, 12.0, 6.0]},
"T28": {"cur": [(1, 0.0), (121, 16.0)], "events": [],
"keys": "642fc116d64d9487", "notes": [], "ph": [],
"sent": [0.0, 16.0]},
"T32": {"cur": [(121, 16.0), (300, 0.0)], "events": [],
"keys": "642fc116d64d9487", "notes": [], "ph": [],
"sent": [16.0, 0.0]},
"T7": {"cur": [(121, 16.0)], "events": [], "keys": "00425fef63358fa7",
"notes": [], "ph": [], "sent": [16.0]},
}
def view(r):
return {"cur": wlist(r), "ph": [(round(t), n) for t, n in
S.writes(r, "phases")],
"sent": list(r["c"].charger.sent),
"notes": [(round(t), n) for t, n in r["raised"]],
"events": [e[9:] for e in r["c"].events if e[9:].startswith("car ")],
"keys": K.digest(sorted(r["store"].data))}
SCEN = {"T1": r1, "T7": r7, "T11": r11, "T15": r15, "T28": r28, "T32": r32}
if os.environ.get("EV52_GOLDEN"):
import json
print("GOLDEN", json.dumps({k: view(v) for k, v in SCEN.items()},
sort_keys=True))
for k, r in SCEN.items():
check(f"T43/T45 {k}: the writes (value, second, phases), the notices, the "
f"action log and the store keys are those of the base build",
view(r) == GOLDEN.get(k))
check("N7: no new store key, notification or option (the key lists above are "
"base's)", all(view(r)["keys"] == GOLDEN.get(k, {}).get("keys")
for k, r in SCEN.items()))
bad = [m for r in ALL for _t, lv, m in r["lines"]
if m.startswith((SETP, MODEP)) and (
lv != "INFO" or re.search(r"number\.|select\.|sensor\.|http|token",
m))]
check(f"N10: every new line is INFO, with no entity id or secret ({bad[:2]})",
not bad)
n2 = []
for r in ALL:
sent = {v for _t, v in S.writes(r)} | set(
getattr(r["c"].charger, "sent", ()))
n2 += [m for _t, m in sets(r) if amps_in(m) not in sent]
check(f"N2: every line's value is a value the add-on sent ({n2[:2]})", not n2)
n11 = []
for r in ALL:
if r.get("sim") is None:
continue
n11 += [x for x in r["sim"].log if x[1] == "current" and x[2] > 16.0]
n11 += [x for x in r["sim"].log if x[1] == "phases" and x[3] >= 100.0
and x[4] > 0.0]
check(f"N1/N11: no write above the clamp and no select under load in any "
f"run ({n11[:2]})", not n11)
tb = [i for r in ALL if r is not r22
for _lv, _m, x in LOG.rec[r["n0"]:r["end"]] if x]
check(f"N9: no exception from the log path in any run but T22's own "
f"({len(tb)})", not tb)
report()
+32 -3
View File
@@ -16,7 +16,10 @@ What is checked, per priority and cycle order:
- the car's grid energy outside its holds: SETTLED (not within 20 s of a step
of the sun, the house or the car's own current) at most 10 Wh; the zero-grid
loop's slew after such a step (500 W per cycle) is reported apart;
- house-caused alarms at the same seconds as the car-Off twin, +2 s.
- house-caused alarms at the same seconds as the car-Off twin, +2 s;
- EV-21 (T49): no peak cut on this day (the batteries catch every cloud edge
and house step), no period over the aim that the car's energy alone takes
over (N4), and no period banked as the car's.
"""
import math
@@ -25,6 +28,7 @@ import random
import ev20_sun as S
DAY = 36000 # 08:00 to 18:00, 1 s cycles
AIM = 3400.0 # the harness's cap 3500 less its margin 100
PAUSE_S = 300.0
MARGIN = 100.0
_rnd = random.Random(53)
@@ -113,11 +117,36 @@ def run_day(first, check):
long_c = [(a, b) for a, b in CLOUDS if b - a > PAUSE_S]
short_c = [(a, b) for a, b in CLOUDS if b - a <= PAUSE_S]
print(f" clouds (start, length): {[(a, b - a) for a, b in CLOUDS]}")
cutlog = {"step": [], "race": []}
def cut_rec(tag):
def f(p, c, t):
st = getattr(c, "_cut", None) or {}
if st.get("cap") is not None and st.get("at") == t:
cutlog[tag].append((t, st["cap"]))
return f
runs = {"step": S.drive(house, sun, dur=DAY, first=first, socs=dict(SOCS),
race=False),
race=False, on_cycle=cut_rec("step")),
"race": S.drive(house, sun, dur=RACE[1] - RACE[0], t0=RACE[0],
first=first, socs=dict(SOCS), race=True)}
first=first, socs=dict(SOCS), race=True,
on_cycle=cut_rec("race"))}
for tag, r in runs.items():
# EV-21, T49: N4 per period, and no cut on this day.
per = {}
for x in r["trace"]:
q = int(x["t"]) // 900
per.setdefault(q, [0.0, 0.0, 0])
per[q][0] += x["grid"]
per[q][1] += x["grid"] - x["car"]
per[q][2] += 1
n4 = [(q * 900, round(a / n), round(b / n))
for q, (a, b, n) in per.items() if n == 900
and a / n > AIM and b / n <= AIM]
check(f"T49 (EV-21) [{first} first, {tag}]: no period over the aim "
f"that the car alone takes over (N4: {n4[:3]}), none banked as "
f"the car's ({r['c'].car_peak_q}), no peak cut on this day "
f"({cutlog[tag][:3]})",
not n4 and not r["c"].car_peak_q and not cutlog[tag])
w = cur_writes(r)
# A pause: a 0 A that is not a phase change's (no select within
# 30 s); a start: the first current after a pause or at the start.
+45 -2
View File
@@ -137,11 +137,41 @@ class SunPlant:
return True
def _cycle_seconds(t0, dur, cyc, phase, jitter, cset):
"""EV-51: the seconds a cycle runs, or None for every second."""
if cset is not None:
due = {int(x) for x in cset if t0 <= x < t0 + dur}
if not due:
raise ValueError("cset has no second inside the run")
return due
if jitter is not None:
gaps = [int(g) for g in jitter]
if not gaps or min(gaps) <= 0:
raise ValueError("jitter needs gaps above 0")
due, t, i = set(), int(t0), 0
while t < t0 + dur:
due.add(t)
t += gaps[i % len(gaps)]
i += 1
return due
if cyc != int(cyc) or cyc <= 0:
raise ValueError("cyc must be a whole number of seconds above 0")
if not 0 <= phase < cyc:
raise ValueError("phase must be in [0, cyc)")
if cyc == 1:
return None
due = {int(t0) + k for k in range(int(phase), int(dur), int(cyc))}
if not due:
raise ValueError("no cycle inside the run")
return due
def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0,
margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar",
first="batteries", events=None, sim=None, store=None, race=False,
on_cycle=None, car_phases=3, t0=0.0, caps=None, finale=None,
rows=False, plant_cls=None, beside=False, meter_change=False):
rows=False, plant_cls=None, beside=False, meter_change=False,
cyc=1, phase=0, jitter=None, cset=None):
"""Run it. Returns a dict: plant, controller, charger, notifications with
their second, and a per-second trace. `caps` ({unit: kWh}) lets each
battery's level move with what it charges or gives; without it the
@@ -152,7 +182,14 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0,
round 1): a write that waits for its read-back is still waiting when the
next cycle reads the charger; it resumes after that read.
`meter_change=True` publishes the meter as Home Assistant does on
`ha_signed`: only when the whole-watt value changes."""
`ha_signed`: only when the whole-watt value changes.
EV-51, the cycle's cadence (the meter and the charger model still tick
every 1 s; only the control cycle is thinned): `cyc` seconds between
cycles and `phase` (the first cycle at t0 + phase), or `jitter`, a
tuple of gaps used in turn (the first cycle at t0), or `cset`, the
cycle seconds. The default (1 s) runs every second as before. A cadence
that would run no cycle is a ValueError, never a vacuous pass."""
due = _cycle_seconds(t0, dur, cyc, phase, jitter, cset)
ratings = ratings or {"a": 5000.0, "b": 4600.0}
socs = socs or {u: 50.0 for u in ratings}
sim = sim or SimCharger(setpoint_a=setpoint)
@@ -252,6 +289,12 @@ def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0,
"ha_signed", imp, exp, phases=1,
ingest_ts=rig.BASE + timedelta(seconds=ts),
ingest_mono=ts))
if due is not None and int(t) not in due:
for u, kwh in (caps or {}).items():
lv = plant.socs[u] - plant.batt_of(u, t) / 36000.0 / kwh
plant.socs[u] = max(0.0, min(100.0, lv))
t += 1.0
continue
await c.read_inputs(now_mono=t)
if race:
await c.car_settle()
+298
View File
@@ -0,0 +1,298 @@
"""EV-21: shared pieces of the peak-cut checks (test_ev21*.py): the shapes of
reports/EV-21-test-plan.md, the Off twin, a per-cycle recorder and the Never
checks every run carries.
The plant is `ev20_sun` (the real Controller, N batteries, the sun, the house
and `chargersim.SimCharger` on one meter, a 1 s cycle on a model clock).
`rig.BASE` is on a quarter boundary, so the second period runs 900-1800 and
"elapsed 60 s" is t = 960. Units: A = 5000 W, B = 4600 W. Aim = 3500 - 100.
Each check file imports `check`, `fails` and `LOG` from `ev20_kit`."""
import hashlib
import json
import os
import sys
_KIT = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _KIT)
sys.path.insert(0, os.path.dirname(_KIT))
from app import carmode, ctl_car, messages # noqa: E402
import ev20_sun as S # noqa: E402
from chargersim import SimCharger # noqa: E402
from ev20_kit import LOG, check, const, step_fn # noqa: E402,F401
AIM = 3400.0
Q = 900
ALARMS = S.ALARMS
CUT_WAIT_S = getattr(ctl_car, "CUT_WAIT_S", 15.0)
CUT_NEAR_END_S = getattr(ctl_car, "CUT_NEAR_END_S", 120.0)
def _cutamps():
"""carmode.cut_amps, or a stand-in that says "no cut" on a tree without
it (c79eb37), so a red row reads as FAIL, never as a crash."""
return getattr(carmode, "cut_amps", lambda *a, **k: "absent")
def both(*fns):
async def f(p, c):
for fn in fns:
x = fn(p, c)
if hasattr(x, "__await__"):
await x
return f
def merge(events, t, fn):
ev = dict(events or {})
ev[t] = both(ev[t], fn) if t in ev else fn
return ev
def set_resp(s):
def f(p, c):
p.response_s = s
return f
class Rec:
"""Per cycle: can-cut, the cut state, the guard's floor and want, the
car's read-back and power. Read after the cycle and its writer step."""
def __init__(self):
self.rows = []
def __call__(self, p, c, t):
st = getattr(c, "_cut", None) or {}
cc = getattr(c, "car_solar_can_cut", None)
graded = getattr(c, "_car_can", None)
g = c.peak_guard
w = c.car_solar
self.rows.append(dict(
t=t, can=graded, can_now=bool(cc()) if cc else None,
cap=st.get("cap"), wait=st.get("wait"), cuts=st.get("cuts"),
ex=st.get("ex"), car0=st.get("car0"), under=st.get("under"),
since=st.get("since"),
proj=None if c._peak_proj_real is None
else c._peak_proj_real.projected_w,
explains=c.car_explains, floor=None if g is None else g.floor_w,
want=None if g is None else g.wanted_w,
sat=bool(g is not None and g.saturated),
flim=bool(g is not None and g.floor_limited),
writing=c.car_writing(), hold=w.hold, mism=w.mismatch_since,
fault=w.fault, sent=w.sent_a, rb=p.ch.readback_a,
car=p.ch.power_w, mode=c.car_mode, plan=w.plan.a))
def at(self, t):
for r in self.rows:
if r["t"] == t:
return r
return None
def drive(house, sun, *, rec=True, **kw):
"""`ev20_sun.drive` with a recorder (`out["rec"]`)."""
r_ = Rec() if rec else None
oc = kw.pop("on_cycle", None)
def on_cycle(p, c, t):
if r_ is not None:
r_(p, c, t)
if callable(oc):
oc(p, c, t)
kw.setdefault("rows", True)
out = S.drive(house, sun, on_cycle=on_cycle, **kw)
out["rec"] = r_
return out
# --------------------------------------------------------------- the shapes
def shape(kind, *, step=960, mode="solar", first="car", n=2, cover=True,
dur=None, events=None, opts=None, socs=None, house_w=None,
sun_w=None, setpoint=None, **kw):
"""The test plan's shapes C, W, S, F and M (N=2 unless `n`=1, Car first,
car 10 A on 3 phases, the step at `step`). The Off twin runs `mode="off"`
with the charger held at the same current from the start."""
car_a = 6.0 if kind == "F" else 10.0
car_w = car_a * 690.0
soc = {"C": 10.0, "W": 60.0, "S": 60.0, "F": 19.0, "M": 60.0}[kind]
h_after = house_w if house_w is not None else {
"C": 3000.0, "W": 3000.0, "S": 16000.0, "F": 9000.0,
"M": 3000.0}[kind]
room = 0.0 if first == "car" else 9600.0
s_before = sun_w if sun_w is not None else 900.0 + car_w + 100.0 + room
ratings = {"a": 5000.0, "b": 4600.0} if n == 2 else {"a": 5000.0}
o = dict({"ev_phases": "3", "ev_batt_cover": cover}, **(opts or {}))
ev = dict(events or {})
if kind in ("W", "S"):
# Slow batteries from 60 s before the step: Solar's own start at
# 120 s runs on quick ones (with slow ones its own start blip lasts
# past the 15 s wait and is cut, PM Q2 / formal C14).
ev = merge(ev, max(0, int(step) - 60), set_resp(20.0))
sp = setpoint if setpoint is not None else (car_a if mode != "solar"
else 0)
if kind == "F" and sun_w is None:
# The start rule needs 7 A worth: start at 7 A, then 6 A from 600 s.
sun = step_fn((600, s_before), (step, 0.0), base=s_before + 760.0)
else:
sun = step_fn((step, 0.0), base=s_before)
return drive(step_fn((step, h_after), base=900.0), sun,
dur=dur or (step + 240), first=first, phases=3, mode=mode,
socs=socs or {u: soc for u in ratings}, ratings=ratings,
opts=o, events=ev, setpoint=sp, **kw)
def twin(kind, **kw):
"""Shape `kind` in Off, the charger held at Solar's current."""
kw = dict(kw)
kw["mode"] = "off"
return shape(kind, **kw)
def replay_twin(r, kind, **kw):
"""Shape `kind` in Off with Solar's own charger writes of run `r` put on
the charger at the same seconds (as test_ev20_guard's Manual twin), so
both runs have the same car and only the mode differs."""
ev = dict(kw.pop("events", None) or {})
for t_sim, what, v, _pw, _sp in r["sim"].log:
def put(p, c, what=what, v=v):
(p.ch.set_current if what == "current" else p.ch.set_phases)(v)
ev = merge(ev, int(round(t_sim)), put)
return twin(kind, events=ev, **kw)
def _mode(units, on):
def f(p, c):
from app import packmode
from app.store import unit_key
for u in units:
c.store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = on
return f
class NoGive(S.SunPlant):
"""Every battery refuses to give: the plant gives min(command, 0)."""
def batt_of(self, u, at):
return min(super().batt_of(u, at), 0.0)
def refuse_n1(p, c):
"""N=1: the sole battery refuses to give (SAFETY-73's latch, held)."""
c.batt_refused, c.batt_refused_at = 1, p.t
def near_end(step, *, n=2, house_after=3000.0, sun_back=None, dur=1800,
house_more=(), **kw):
"""The period sits near the aim before the step: 900-1500 the house draws
3350 W and nothing covers it (N=2: both batteries switched off in battery
modes until 1500; N=1: the battery refuses to give throughout), then the
sun is back and Solar starts the car at 10 A on 3 phases; at `step` the
sun goes and the house is `house_after`. The batteries (N=2: 60 %) take
20 s to respond from 30 s before the step (Solar's own start runs on
quick ones: PM Q2 / formal C14 would cut its own start blip otherwise).
`sun_back`: the sun returns then."""
ev = dict(kw.pop("events", None) or {})
ev = merge(ev, max(0, int(step) - 30), set_resp(20.0))
if n == 2:
ev = merge(merge(ev, 899, _mode("ab", False)), 1500,
_mode("ab", True))
ratings = {"a": 5000.0, "b": 4600.0}
else:
for t in range(0, int(dur) + 1):
ev = merge(ev, t, refuse_n1)
ratings = {"a": 5000.0}
kw.setdefault("rows", False)
# The harness plant gives what it is asked; a refusing battery
# gives nothing (it still takes a charge).
kw.setdefault("plant_cls", NoGive)
house = step_fn((900, 3350.0), (1500, 900.0), (step, house_after),
*house_more, base=900.0)
pairs = [(900, 0.0), (1500, 7900.0), (step, 0.0)]
if sun_back is not None:
pairs.append((sun_back, 9000.0))
sun = step_fn(*pairs, base=7900.0)
return drive(house, sun, dur=dur, first="car", phases=3,
ratings=ratings, socs={u: 60.0 for u in ratings},
opts={"ev_phases": "3"}, events=ev, **kw)
# ------------------------------------------------------------- reading runs
def cur_writes(r):
"""(cycle second, amps, ok) of every current write Solar made."""
return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log
if x[0] == "current"]
def after(r, t0):
return [(t, a, ok) for t, a, ok in cur_writes(r) if t >= t0]
def alarms(r, t0=0):
return [(t, n) for t, n in r["raised"] if n in ALARMS and t >= t0]
def first_alarm(r, t0=0):
a = alarms(r, t0)
return a[0][0] if a else None
def notes(r, *ids):
return [(t, n) for t, n in r["raised"] if n in ids]
def quarter_avg(r, q0):
"""The period's real average import, W: the meter of every cycle in it
(the trace's `grid`; `plant.grid(t)` would use the car's power at the
end of the run)."""
g = [x["grid"] for x in r["trace"] if q0 <= x["t"] < q0 + Q]
return sum(g) / len(g) if g else float("nan")
def peak_key(q0):
return (S.rig.BASE.replace(microsecond=0)
+ __import__("datetime").timedelta(seconds=q0)).isoformat()
def digest(obj):
return hashlib.sha256(json.dumps(obj, default=str, sort_keys=True)
.encode()).hexdigest()[:16]
def view_writes(r):
return [(round(t), a) for t, a in S.writes(r)] + [
("ph", round(t), n) for t, n in S.writes(r, "phases")]
def view_guard(r, t0=0):
return [(x["t"], round(x["floor"] or 0.0), x["explains"], x["over"],
tuple(x["red"])) for x in r["trace"] if x["t"] >= t0]
# ------------------------------------------------------------- the Never
def never(name, r, *, clamp=16.0, solar=True):
"""N1, N2, N6 (with N3's cut value), N8's grading half (T35) and N11 on
one run; each a check line. N8's "+2 s" half and N4/N5 are per row."""
sim = r["sim"]
tr = r["trace"]
rec = r.get("rec")
bad1 = [x for x in sim.log if x[1] == "current" and x[2] > clamp + 1e-9]
# N2: a select under load (>= 100 W, mode3 C, non-zero setpoint).
bad2 = [x for x in sim.log if x[1] == "phases" and x[3] >= 100.0
and x[4] > 0.0]
check(f"{name}: N1 no write above the clamp ({bad1[:2]}); N2 no phase "
f"select under load ({bad2[:2]})", not bad1 and not bad2)
if rec is not None and solar:
# T35 / N8: graded out in Solar only while Solar can cut.
bad8 = [x["t"] for x in rec.rows if x["mode"] == "solar"
and x["explains"] and not x["can"]]
check(f"{name}: T35 car_explains only while Solar can cut "
f"({bad8[:3]})", not bad8)
# N6 / P17: no non-zero write above a standing cut's value.
caps = {x["t"]: x["cap"] for x in rec.rows}
bad6 = [(t, a) for t, a, _ok in cur_writes(r) if a > 0.0
and caps.get(t) is not None and a > caps[t] + 1e-9]
check(f"{name}: N6 no write above a standing cut ({bad6[:3]})",
not bad6)
del tr