Compare commits

..
13 Commits
Author SHA1 Message Date
ems-agentandClaude 36e9dd765e EV-21: test fixes (T41/T46 on base, test_ev20_writers T46 with the cut first)
infra-pin / fresh (pull_request) Waiting to run
checks / unit (pull_request) In progress
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
checks / unit (pull_request) In progress
infra-pin / fresh (pull_request) Successful in 2s
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
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
19 changed files with 2313 additions and 93 deletions
+130 -4
View File
@@ -2,10 +2,136 @@
### 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]]).
- **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
@@ -0,0 +1,87 @@
# 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) and the batteries would have to give more than now for it, the car is
lowered first. A charge the batteries only have to slow down is not a cut.
- **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
- **"The batteries would have to give more than now"** is `battery W + excess
> 0` on the projection with the car: the guard's `wanted_w` with the cover on,
the same test on the real period with it off. Without it, Solar's own start
on slow batteries cut the car for the seconds the batteries took to stop
charging.
- **While the 15 s wait runs** the cap is the current Solar has then (C4: no
raise while due).
- **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 and the batteries would have to give more for it, Solar
lowers the car first: 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
+55 -10
View File
@@ -486,6 +486,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)."""
@@ -574,16 +593,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, meter_back=False):
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. `meter_back` (EV-51): the
meter's own age is fresh again at this step: the unknown timer that
counted its silence starts over."""
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
@@ -622,8 +654,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)
@@ -637,7 +671,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:
@@ -674,6 +708,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
@@ -744,6 +780,8 @@ 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
def owe_start(self) -> None:
"""C1: the add-on starts in Off while an exit 0 A of its own was still
@@ -805,6 +843,7 @@ class SolarWriter(ManualWriter):
the write goes out, so a write cancelled while it waits for its
read-back is never trusted (`live`)."""
self.sent_a, self.taken = float(a), False
self.sent_at = now # EV-21: a lowering on its way
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
@@ -866,7 +905,10 @@ class SolarWriter(ManualWriter):
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):
@@ -947,7 +989,7 @@ class SolarWriter(ManualWriter):
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),
meter_back=getattr(sun, "meter_back", False))
meter_back=getattr(sun, "meter_back", False), cap=self.cut_a)
@staticmethod
def _drawing(r) -> bool:
@@ -970,9 +1012,12 @@ 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)
return a
return want
+311 -12
View File
@@ -16,7 +16,7 @@ import logging
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")
@@ -48,6 +48,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:
@@ -118,6 +130,245 @@ 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 st["wait"]
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
# The batteries would have to give more than now (the guard's
# `wanted_w`, on the projection WITH the car): a charge that only
# has to slow down is the loop's, not a cut. Unknown: they add
# nothing (Q4).
batt = self.site_batt_w
wants = batt is None or float(batt) + ex > 0.0
due = ex > 0.0 and wants and running and (drawing or seq_on)
n = self._car_cut_n()
if st["cap"] is not None:
# A cut stands: deeper only if the excess grows (OQ7); the
# restart rule lifts it.
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 mono - st["since"] >= CUT_WAIT_S:
a = 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.
st["wait"] = w.plan.a if st["wait"] is None \
else min(st["wait"], w.plan.a)
w.cut_a = st["wait"]
@property
def car_cover(self) -> bool:
@@ -276,13 +527,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
@@ -613,12 +888,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:
@@ -698,11 +975,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
@@ -712,7 +993,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)
@@ -770,15 +1051,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
@@ -803,7 +1093,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)
+5 -3
View File
@@ -274,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) \
@@ -282,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 = []
@@ -400,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,
@@ -1070,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)
+404
View File
@@ -0,0 +1,404 @@
"""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
ev14 = {t: refuse_a for t in range(1, 1100)}
ev14[0] = 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)
+548
View File
@@ -0,0 +1,548 @@
"""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=9000.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]
nz = [t for t, a in w if a > 0.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)
lim = max(0.0, (dec.get("want") or 0.0) - (car_b - car_a)) + 150.0
# A cycle whose battery reading moved since the last one reads the
# battery a cycle before the meter (want = battery + excess): a skew of
# the measurement, not a floor raised for the car; those are skipped.
tb = {x["t"]: x["batt"] for x in r["trace"]}
bad = [(x["t"], round(x["want"] or 0)) for x in rec.rows
if rb[0] + 5 <= x["t"] <= rb[0] + 60 and (x["want"] or 0) > lim
and abs(tb.get(x["t"], 0.0) - tb.get(x["t"] - 1, 0.0)) < 50.0]
check(f"T46: from 5 s after the cut's read-back the guard wants no more than "
f"its want at the cut less what the car gave back, +150 W ({lim}; "
f"{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)
+306
View File
@@ -0,0 +1,306 @@
"""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)
for cover in (True, False):
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", "ev_batt_cover": cover})
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)
+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.
+283
View File
@@ -0,0 +1,283 @@
"""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"):
ev = merge(ev, 0, 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
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. `sun_back`: the sun returns then."""
ev = dict(kw.pop("events", None) or {})
ev = merge(ev, 0, 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)
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