Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f9ac66a26 | ||
|
|
10ee2baf91 | ||
|
|
5e00cbbd79 |
@@ -49,12 +49,10 @@ SERIAL="test_loop.py test_freeze.py test_safety87.py"
|
||||
# safety119 704, opt34 515, safety126 402, safety125 388, safety126b 364,
|
||||
# modes_p3 377, safety94 360, modes_p4c 291, modes_p4b 238, tariff24_weather 235,
|
||||
# modes_p4d 196, price_run_fixes 197, safety103 189, safety90 185, safety97 163.
|
||||
# EV-20 (Solar), local runs at 8 workers: ev20_exits ~460, ev20_guard ~450,
|
||||
# ev20 ~350, ev20_fuzz ~300, ev20_long_car ~280, ev20_long ~240, ev20_writers ~230.
|
||||
# CI-18 split test_modes_p4, test_safety126 and test_safety125 so no one file
|
||||
# is much over 400 s; test_opt34 and test_opt36 already fan out inside, and
|
||||
# test_safety119 part 4 is one coupled block, so those three stay whole.
|
||||
HEAVY="test_opt36.py test_safety119.py test_opt34.py test_ev20_exits.py test_ev20_guard.py test_safety126.py test_safety125.py test_safety126b.py test_modes_p3.py test_safety94.py test_ev20.py test_ev20_fuzz.py test_modes_p4c.py test_ev20_long_car.py test_ev20_long.py test_modes_p4b.py test_ev20_writers.py test_tariff24_weather.py test_modes_p4d.py test_safety125b.py test_price_run_fixes.py test_safety103.py test_safety90.py test_safety97.py test_peakguard.py test_opt20.py test_safety81.py"
|
||||
HEAVY="test_opt36.py test_safety119.py test_opt34.py test_safety126.py test_safety125.py test_safety126b.py test_modes_p3.py test_safety94.py test_modes_p4c.py test_modes_p4b.py test_tariff24_weather.py test_modes_p4d.py test_safety125b.py test_price_run_fixes.py test_safety103.py test_safety90.py test_safety97.py test_peakguard.py test_opt20.py test_safety81.py"
|
||||
#
|
||||
JOBS=${CI_JOBS:-10}
|
||||
cd "${TESTS_DIR:-/w/goodwe-addon/goodwe_controller}"
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
# The admin/goodwe commit CI tests against. Bump: set to the full SHA of admin/goodwe release/1.0 HEAD (README.md, "CI and the infra pin").
|
||||
f88461234f3a7d53c025a68beda4cb6e4384cebf
|
||||
3b4ff84757f9c2c5b63a4b4a53e593ccaeafb847
|
||||
|
||||
@@ -1,132 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
### 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]]).
|
||||
|
||||
## 0.24.0
|
||||
|
||||
**A minor bump: the add-on can now charge the car (Manual mode), and a car that alone takes the batteries to the peak reserve no longer raises a false peak alarm. Two new options were added, both with defaults, and none needs setting.**
|
||||
Two options were added (`ev_batt_cover` and `ev_mode_start`), none was removed or renamed, and no default changed (92 options, 90 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.23.0 did. It is a minor bump because it adds a feature and new options; every saved setting still starts.
|
||||
|
||||
**The add-on can now charge the car.** This is the first version that writes to the car charger. On the *Car* card, choose **Manual** and set the current (6 A up to the charger limit) and 1 or 3 phases, on Home, or from Home Assistant when MQTT is on. **Off writes nothing.** The car is never slowed for the peak limit; the batteries help cover it unless you switch *Batteries help with the peak* off. **If your own automation in Home Assistant writes the same charger, switch it off before you choose Manual:** two writers fight over one setting. See "Car charger" in DOCS ([[EV-04]]).
|
||||
|
||||
**Car charger fixes.** When the car alone takes the batteries to the peak reserve, the add-on no longer says "Battery stopped limiting the peak"; a grey "Car over the peak limit" note says it instead, and the note stays steady instead of flickering. A change the add-on makes itself is no longer shown as "Something else changes the charger". A real overload of the house still raises the normal alarm ([[EV-10]], [[EV-11]], [[EV-12]]).
|
||||
|
||||
Contents of this release, in merge order since 0.23.0 (`b656091`):
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `75ebe22` | The add-on can charge the car: choose Manual on the *Car* card and set the current (6 A up to the charger limit) and 1 or 3 phases. Off writes nothing, the car is never slowed for the peak limit, and the batteries help cover it unless you switch that off. This is the first version that writes to the charger, so switch off any other automation that writes it ([[EV-04]], #257) |
|
||||
| `b86c015` | When the car alone takes the batteries to the peak reserve, there is no false "Battery stopped limiting the peak". The "Car over the peak limit" note stays steady, and the add-on's own change is not shown as "Something else changes the charger" ([[EV-10]], [[EV-11]], [[EV-12]], #258) |
|
||||
| `628bde8` | The false "Battery stopped limiting the peak" is now gone also when the batteries cover the car down to the reserve: the check counts the house alone. A real overload of the house still raises the alarm ([[EV-10]], #259, called EV-10b) |
|
||||
|
||||
|
||||
### 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]]).
|
||||
- When the charger refuses a current, the Car card can show two amber rows: "Charger did not take it" and "Charger reading may be stuck" ([[EV-13]]).
|
||||
- In shadow mode, and after a phase change was given up, the Car card's *Why* line says what you set, not what the charger does ([[EV-14]]).
|
||||
- When the add-on changes the car's phases while the batteries are at the peak reserve, "Battery stopped limiting the peak" can show for a moment, with one notification ([[EV-15]]).
|
||||
- With *Batteries help with the peak* on, the Car card's *Why* line can switch between two wordings while the car is over the peak limit ([[EV-16]]).
|
||||
|
||||
### 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.23.0
|
||||
|
||||
**A minor bump: the add-on can now read a car charger (Alfen, through Home Assistant), and with two inverters a maintenance charge stays paused during a real peak. Four new options were added, all with defaults, and none needs setting.**
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
# EV-04 — Manual mode: the first write to a car charger
|
||||
|
||||
The design is `reports/EV-01-design-report.md` (sections 2 to 5), accepted on
|
||||
2026-11-15 with all eight decisions as recommended. This record keeps what the
|
||||
code had to decide that the design left open.
|
||||
|
||||
## What writes, and who may
|
||||
|
||||
`app/carmode.py` `ManualWriter` is the only caller of `write_current` and
|
||||
`write_phases` (test_ev03.py greps for any other). It runs in a background task
|
||||
(`ctl_car.CarMixin.car_kick`), never in the control cycle: a write waits up to
|
||||
10 s for the charger's read-back, and the cycle must never wait for a charger.
|
||||
|
||||
- **Off writes nothing.** The mode is runtime state in the store (`car_mode`,
|
||||
`car_current`, `car_phases`), changed on Home or from Home Assistant with no
|
||||
restart. Solar and Night are not accepted (EV-05, EV-02).
|
||||
- **Once per user change.** A user change sets a flag the writer clears when the
|
||||
charger has what was asked. A difference nobody asked for is the other-writer
|
||||
detector's business, not a reason to write.
|
||||
- **No car or a full car: nothing is written**, and the setting waits for a car.
|
||||
- **Shadow mode and a stopped control write nothing**; the card says what the add-on
|
||||
would set.
|
||||
- **The clamp is the driver's too.** The writer asks for at most the clamp, and
|
||||
`AlfenHaDriver.write_current` refuses anything above
|
||||
`min(ev_max_a, station limit read now, entity range max)`: it sends nothing,
|
||||
logs `CHARGER_CLAMP` at ERROR (the OUTPUT_CLAMP shape) and answers False.
|
||||
- **"Taken"** means the read-back followed within 10 s. A write that was not
|
||||
taken is tried again after a minute, three times, then it waits for the user
|
||||
(an amber row). A late read-back is adopted, never called another writer.
|
||||
|
||||
## The phase sequence
|
||||
|
||||
0 A, wait until the charger reports under 100 W (mode3 leaving C and D counts
|
||||
only when there is no power reading; 20 s at most), select the phases, wait
|
||||
10 s, write the current. One switch per 10 minutes. A charger that does not
|
||||
take the 0 A never gets the phases select. A car still drawing after 20 s gets
|
||||
no select: its current comes back and it counts as a failed try (EV-28). A
|
||||
sequence that has begun is finished whatever the mode, because it leaves the
|
||||
car at 0 A otherwise; a stop of the add-on in the middle gives the car its
|
||||
current back (`car_shutdown`).
|
||||
|
||||
## Another writer
|
||||
|
||||
A read-back that differs from what the add-on last wrote (or tried to write, or
|
||||
saw before a refused write) for 30 s is another writer: a grey row, and no write
|
||||
until the user changes the mode or a value. EV-03's detector still serves Off;
|
||||
the tracker mutes its own detector for 15 s after each of our writes, so Manual
|
||||
back to Off does not show the add-on as a second writer.
|
||||
|
||||
## The peak guard's alarm path
|
||||
|
||||
`Controller` passes the car's power to the guard's alarm path (`car_cycle`).
|
||||
**The car explains the excess when the house alone would land the period under
|
||||
the aim**: the car's average over the whole period (what it drew so far, and its
|
||||
power now for the rest, `car_avg_w`) is at least how far the projected period is
|
||||
over the aim. With decision 1 on it also needs the guard to be unable to hold
|
||||
it (saturated or at the peak reserve). Then "Load too high" and "Battery stopped
|
||||
limiting the peak" are not raised, the rows are not red, and one grey notice per
|
||||
charging session says so. The claim, the floor and the commands are unchanged.
|
||||
|
||||
The brief's wording is `car_w >= projected excess over the aim`. The
|
||||
instantaneous form (`car_w >= excess_w`, the watts to come off the meter now)
|
||||
stops holding late in a period that the car already pushed over, because
|
||||
`excess_w` grows as the seconds run out; the average form does not, and it is the
|
||||
same test for a steady car.
|
||||
|
||||
**A refused write arms the stuck check only when the charger shows no life
|
||||
(EV-13).** A charger that ignores a write keeps its old read-back, so the
|
||||
check would read it as stuck 60 s later and show a second amber row beside
|
||||
"did not take the setting". A refused write now arms only if, within `TOOK_S`
|
||||
of the send, the energy, a phase current or the power changed in a sample taken
|
||||
after the send, against the last value before (`CarTracker.note_write`,
|
||||
`_alive`). Unchanged, absent before, or taken before the send is no life. No
|
||||
life arms as before, dated the send. A write that raised, or was accepted, is
|
||||
unchanged. A frozen charger (every write looks refused) still arms.
|
||||
|
||||
**A stale, stuck or frozen car figure must never hide a real overload.** Only
|
||||
`CarTracker.car_w_trusted` is used: fresh (the EV-03 rules, which also make an
|
||||
unavailable reading None at once), not stuck after a write (SAFETY-37's shape),
|
||||
never above what the read-back allows, and CORROBORATED by the charger's energy
|
||||
meter (round 2). The rule (`CarTracker.corroborated`, constants `CORR_*` in
|
||||
`chargers.py`): the charger reports charging (mode3 C) and has an energy entity,
|
||||
and, looking back over unbroken charging readings to the shortest stretch that
|
||||
is at least 55 s long and over which the reported power adds up to at least
|
||||
40 Wh, the meter has gained at least 50 % of that, less 15 Wh (the meter shows
|
||||
10 Wh steps, so at 40 Wh it must show one step; an honest car can fall one step
|
||||
short and still passes). Readings are kept 180 s. A gap, a state other than C or
|
||||
a meter that goes back starts the history again. With no such stretch yet (a
|
||||
session just began, or the add-on just started) the figure is believed, so a
|
||||
charge does not raise false alarms for its first minute; a frozen figure is
|
||||
believed for that long only. No energy entity: never corroborated, so the normal
|
||||
alarms stand. **Bound:** a frozen figure of P watts on a car that has really
|
||||
stopped is caught within max(60 s, 40 Wh / P): 60 s from 2.4 kW up, 104 s at
|
||||
1.38 kW (6 A, 1 phase, the lowest charge), plus the alarms' own 10 s hold. Below
|
||||
about 0.8 kW (40 Wh over the 180 s kept) the figure is believed; it cannot hide
|
||||
an overload that matters. (Round 2 had a 15 Wh slack that cancelled the 50 % rule
|
||||
up to 1.8 kW; the 40 Wh floor fixes that.)
|
||||
|
||||
## EV-10, EV-11, EV-12: the rig's three findings (EV-04 test F-1 to F-3)
|
||||
|
||||
- **The car is the cause when the alarm's own test says so, on the same
|
||||
landing** (EV-10). `car_cycle` (`_car_explains_alarm`) runs the alarm's test on
|
||||
the period as it is and on the period without the car's fresh, corroborated
|
||||
average (`car_exclude_alarm`, EV-10b below): the car explains the alarm only if it is true with the
|
||||
car and false without it. A saturated guard, and a floor with other batteries
|
||||
left, use `load_too_high` on the landing (the batteries give only what they
|
||||
still can). A floor that leaves nothing uses SAFETY-126's `misses_aim` (the
|
||||
batteries at 0 W from now on), which is latched for the quarter; the add-on keeps
|
||||
that latch twice, with and without the car, from the same readings. Both reset
|
||||
at a new quarter and when the guard stops wanting power, and they run every
|
||||
cycle, so the cover option does not touch them. This holds with the projection
|
||||
still under the aim (rig: 5888 W against 6000 W). A car of 0 W explains
|
||||
nothing; a stale, stuck or uncorroborated figure is `None` and the normal
|
||||
alarms stand while it is (EV-18 below). There is no minimum car power: the
|
||||
comparison itself is what separates car from house.
|
||||
- **The period without the car is not clipped at 0 W** (EV-10b). The rig showed
|
||||
EV-10 failing: house 3 kW, car 11 kW, batteries 8.1 kW, aim 6 kW. The batteries
|
||||
give more than the house uses, so the house alone is an export; `car_exclude`
|
||||
clipped it at 0 W, `misses_aim` added the batteries' full 8.1 kW back, the
|
||||
"house needs the batteries" latch set early in the quarter, and the floor alarm
|
||||
could never be explained. `car_exclude_alarm` (alarm grading only) builds the
|
||||
house alone as: rest of the period `held - car_w`, keeping its sign, so
|
||||
`misses_aim` adds the batteries back to `held - car_w + batt` = the house; done
|
||||
part `max(0, done - car so far)` in Ws (no export is credited that only the
|
||||
car caused); landing `(done + max(held, 0) * left) / 900`. Without a fresh
|
||||
car reading it is the period as it is. `car_exclude` (the projection the guard
|
||||
sees with the cover off) is unchanged, with its clip.
|
||||
- **Steady row, no hold on the alarm** (EV-11). Cause: after the car's own quarter
|
||||
became the month peak, the aim sat on the grid it made (14.04 kW +-40 W), so
|
||||
the test crossed the aim every few seconds. `car_over` (row, card, notice) now
|
||||
stays on until the test has been false for `OVER_OFF_HOLD_S` = 180 s (longer than
|
||||
the gaps seen on the rig, 150 to 250 s at 50 s sampling, and shorter than a
|
||||
quarter) and a gap does not restart the 10 s
|
||||
on-count. `car_explains`, which the alarms read, has no hold.
|
||||
- **Our own phase change is not a reason to alarm** (EV-15). Rig, twice: at the
|
||||
reserve, with the car covering, the add-on's 3 -> 1 switch set the car to 0 A.
|
||||
A car that is not charging has no corroboration (`CarTracker._corr_note` clears
|
||||
the window, `corroborated` is False), so `car_alarm_w()` was None, the car
|
||||
explained nothing and `_car_need_excl` latched for the quarter: one
|
||||
PEAK_GUARD_FLOOR_LIMITED and one `goodwe_peak_soc_floor`. Now, only for grading
|
||||
(`car_cycle`), `ctl_car._car_own_pause` lets the car's fresh, not stuck figure
|
||||
(`CarTracker.car_w_paused`, 0 W while paused) stand in without corroboration:
|
||||
from the moment our 0 A write is SENT (`zero_sent_at`: the cycle runs beside
|
||||
the writer and the car stops before the write returns), until the current is
|
||||
set again, at most
|
||||
`OWN_PAUSE_MAX_S` (85 s, the sequence's own waits), then at most one
|
||||
corroboration window (60 s). It ends at once on Off, Stop, shadow, unplug,
|
||||
another writer, or a refused select or write (`seq["failed"]`). The energy it
|
||||
drew in the pause is kept apart (`ws_p`), so `car_exclude`, the guard's
|
||||
input, the claim, floor and writes are unchanged. A house overload still fails
|
||||
the test without the car, so it alarms as on Off.
|
||||
- **The batteries as they give now, and no latch from an unknown** (EV-18, EV-15
|
||||
rig F-A). At the reserve the loop still gives some battery power; "without the
|
||||
car, batteries at 0 W" counted it as house, `_car_need_excl` latched at the
|
||||
quarter's start and the floor alarm stood for the quarter with the excess
|
||||
smaller than the car. Owner 2026-11-19: without the car the batteries keep
|
||||
giving what they give now (the lower of two readings, every cycle); a miss so
|
||||
(`_car_need_house`) seen with a trusted car figure stays latched to the
|
||||
quarter's end. The car explains where the period with it misses on the same
|
||||
batteries (`_car_over_now`), or by the EV-10 test above. A `None` car figure
|
||||
or battery reading explains nothing in that cycle and latches nothing; a car
|
||||
known to draw nothing (fresh, not charging) still grades the house's need.
|
||||
Owner 2026-11-19: a figure the energy meter contradicted (it answered over a
|
||||
whole window and fell short; an unknown reading is no contradiction) grades
|
||||
no alarm to the quarter's end; the guard's input keeps it. After a restart
|
||||
or a gap the car's earlier energy is not known, so it counts as house.
|
||||
- **A battery rise the meter has not shown is not house yet** (EV-19, EV-15
|
||||
rig F-B). At the reserve inverter-b goes on following the house, so its
|
||||
output rises; the reading shows it one cycle before P1 does, and the house
|
||||
figure (meter + battery) counted that power as house. `_car_need_house`
|
||||
latched and the alarm stood. Now, while the meter's house side (held - car)
|
||||
moved no more than `RISE_STILL_W` since the last cycle, a reading above both
|
||||
earlier ones counts only up to the higher of them. A meter that moved shows
|
||||
the rise (an honest step with a battery burst alarms at once, as before). A
|
||||
rise the meter does not move with at all is graded as F-B: the one case the
|
||||
readings cannot tell apart. The credit stays the lower of the last two
|
||||
readings; `_car_over_now` is unchanged.
|
||||
- **Our own write is ours until its mute ends** (EV-12). The mute of the tracker's
|
||||
own detector opens before the write and runs 15 s from when it returns, because
|
||||
the read-back reaches the cycle while the write still waits for it.
|
||||
|
||||
## The one write shadow mode allows
|
||||
|
||||
When the add-on has paused the car (0 A) for a phase change and has not yet
|
||||
selected the phases, Off, a stop of control, a safety latch or shadow mode ends
|
||||
the change. The old current is given back (clamped, `_restore_a`) in every one of
|
||||
those cases, shadow mode included. With the shipped `shadow_mode: auto`, stopping
|
||||
control turns shadow on, so without this the car would stay at 0 A for as long
|
||||
as control is stopped, while the design's Manual column says the current
|
||||
stands. Undoing our own half-done change is not a new command; it is the same
|
||||
write the shutdown restore makes. Nothing else is written in shadow mode: no
|
||||
phase switch, and no write afterwards.
|
||||
|
||||
## Decision 1 (`ev_batt_cover`)
|
||||
|
||||
On (the default): the guard works as it does and the batteries cover the car down
|
||||
to the peak reserve. Off: the projection the guard sees leaves the car out
|
||||
(`house - car_w`, with the car's average so far), so it does not force the
|
||||
batteries to discharge for it, and the period goes over by the car alone. The
|
||||
car is never throttled either way. The projection the guard sees is also the
|
||||
one `charge_room_w` reads, so with the switch off a grid charge of the batteries
|
||||
sees the room the car leaves; that is the owner's trade and DOCS says so.
|
||||
|
||||
## Deviations from the design text
|
||||
|
||||
- **Titles and setting names** follow STYLE.md (at most 5 and 6 words):
|
||||
"Car over the peak limit" (the design: "Car charge over the peak limit"),
|
||||
setting "Batteries help with the peak" (the design: "... while the car
|
||||
charges", which is in its description).
|
||||
- **No "or choose Solar"** in the Why or the notice: Solar is not in this card.
|
||||
- **The Why lines** are two sentences of at most 12 words, as test_messages.py
|
||||
asks; `peak.car` says "The car takes {car} and the batteries cover {cov}."
|
||||
without "of it".
|
||||
- **`peak.set_by_car`** keeps its first sentence only ("The batteries were at the
|
||||
peak reserve" is not true with decision 1 off). A quarter counts as set by the
|
||||
car when the car drew half the peak or more over it.
|
||||
@@ -1,110 +0,0 @@
|
||||
# EV-20 — Solar mode: spare sun to the car (charging only)
|
||||
|
||||
Part 1 of the split of cancelled EV-05 (owner 2026-11-19). The design is
|
||||
`reports/EV-01-design-report.md` sections 2-5 and decision 5; the rules are
|
||||
EV-20's brief (Expected 1-15, D1-D4). EV-21 (the car cut first for the peak)
|
||||
and EV-22 (another writer's phase change) are separate cards. This record keeps
|
||||
what the code had to decide.
|
||||
|
||||
## Where it lives
|
||||
|
||||
`app/carmode.py`: `SolarPlan` (pure: the spare, the room, the dwells, the auto
|
||||
phases) and `SolarWriter`, a subclass of EV-04's `ManualWriter`. It writes only
|
||||
through `ManualWriter._write` and `_advance`, so the two write call sites stay
|
||||
exactly two (test_ev04 / test_ev20 T55). `app/ctl_car.py` builds the inputs
|
||||
(`car_spare_w`, `car_room_w`), runs the step beside the cycle, the release at
|
||||
shutdown and today's solar kWh.
|
||||
|
||||
## One rule for every write (EV-05 review rounds 2-9)
|
||||
|
||||
EV-05 needed nine review rounds, mostly on exits and other writers. EV-20 keeps
|
||||
one small set of facts and derives every path from them:
|
||||
|
||||
- `sent_a`: the current Solar last decided, recorded BEFORE the write goes out;
|
||||
`taken`: the charger confirmed it. A write cancelled while it waits is never
|
||||
trusted (round 2, T37).
|
||||
- A value is written when Solar DECIDES a new one. One the charger did not take
|
||||
is tried again after 60 s, three times, then the gave-up row and one
|
||||
CHARGER_REFUSED warning (EV-04's rule; round 2's Critical, T36). A new 0 A
|
||||
gets its own three tries and never waits.
|
||||
- A read-back that shows what Solar sent confirms it, however late (round 9's
|
||||
second Major, T48).
|
||||
- A read-back that differs from what Solar sent is never written over:
|
||||
EV-04's `_watch` judges it, and while the difference stands Solar writes
|
||||
nothing in its running state. After 30 s the hold (amber row, one
|
||||
CHARGER_OTHER warning) stops every write, the way-out 0 A and the shutdown's
|
||||
included (N16; rounds 5-7). Only pressing Solar lifts it.
|
||||
- `live`: Solar's own current may stand on the charger (a non-zero value it
|
||||
sent, or a 0 A not yet confirmed). A way out (Off, Stop, shadow, a safety
|
||||
stop, a charger error or stuck reading, no car, shutdown) writes 0 A only
|
||||
then. So a start in shadow writes nothing, and once the way-out 0 A is
|
||||
confirmed nothing more is written, shutdown included (rounds 6 and 7).
|
||||
- The start-up and a charger (or Home Assistant) that comes back write 0 A
|
||||
first whatever the charger shows, with the read-back references cleared, so
|
||||
its own value is never "another writer" (D2; round 9's first Major, T29,
|
||||
T30, T61).
|
||||
|
||||
## Choices the brief left open
|
||||
|
||||
- **Writes over an unexplained read-back stop at once**, not after 30 s: the
|
||||
plan goes on, the next decision waits. A way out still writes its 0 A inside
|
||||
those 30 s (T39 (b)): 0 A is the safe side.
|
||||
- **The phases follow the charger.** Solar's arithmetic uses the phases the
|
||||
charger reports (1 for a one-phase car); its plan adopts them whenever it is
|
||||
not switching. It selects only by its own dwells (and a start from a pause in
|
||||
auto, on 1 phase), never "back" over a change it did not make (D4: EV-22).
|
||||
A lower current is never blocked by the 10-minute phase gap (round 8, T46).
|
||||
- **An interrupted phase change ends at its 0 A.** Manual's restore of the old
|
||||
current stays Manual's.
|
||||
- **Pressing Solar** lifts another writer's hold and takes the charger as it
|
||||
is; Solar's own value is then decided and written afresh. Choosing Solar from
|
||||
another mode starts paused: 0 A, then the start rule.
|
||||
- **Stale and unknown.** The spare is unknown with a meter older than
|
||||
`stale_input_s` (P1's own bound may be longer), readings late past it, a
|
||||
missing or NaN battery or grid figure, or a charging car whose figure is
|
||||
stale, stuck or not corroborated. A paused or idle car counts as 0 W. Unknown
|
||||
holds the current for `ev_pause_min`, then 0 A. A cycle that returns early for
|
||||
missing or late readings still steps Solar (Manual is left as it was).
|
||||
- **The guard treats a Solar car exactly as a Manual car** (Expected 8): every
|
||||
alarm-path test that said "Manual" says "Manual or Solar"
|
||||
(`car_controlled`). Solar's own phase change gets EV-15's grace as Manual's;
|
||||
its own 0 A pause gets it from the send, at most `OWN_PAUSE_MAX_S`, and only
|
||||
while the read-back still shows that 0 A (round 8's second Major).
|
||||
- **D1 wording.** The card's Why says "Solar charges the car at {a} A. This
|
||||
sets the peak."; STYLE.md allows a grey note and a grey row one sentence, so
|
||||
they say "Solar charges the car at {a} A, which sets the peak." `{a}` is the
|
||||
charger's read-back, never Manual's stored current.
|
||||
- **D3 at shutdown.** In Solar the charger's 0 A goes out before the inverters'
|
||||
0 W: up to three tries 5 s apart, each waiting 4 s for its read-back
|
||||
(`write_current(took_s=...)`), all inside `RELEASE_WAIT_S` (15 s, also a
|
||||
wall-clock bound for a charger that hangs). Not taken: one CHARGER_RELEASE
|
||||
warning, the notice *Car may still be charging* after the inverters are
|
||||
released, and the next start writes 0 A first (D2) and takes the notice down.
|
||||
- **A charger error** sets 0 A (while owed) with one CHARGER_ERROR warning
|
||||
and the card's Why; the existing grey error row shows it. No new
|
||||
notification.
|
||||
- **Solar kWh** is counted per cycle in Solar only: `min(car, max(0, spare -
|
||||
room))` Batteries first, `min(car, max(0, spare))` Car first; never above
|
||||
today's kWh; stored with its day, reset at the day's change.
|
||||
- **Rollback.** An older build reads a stored `car_mode = solar` as Off
|
||||
(`start_mode`) and writes nothing; no state migration.
|
||||
|
||||
## SPIKE-05 decisions (brief v4/v5)
|
||||
|
||||
- **C1.** An own 0 A that is out and not read back is kept in the store with
|
||||
the mode (`car_exit_0a_pending`). A start in Off with that flag writes the
|
||||
0 A (when it may write), retried by the exit rule; Off without it writes
|
||||
nothing (N10). A start that will not write (shadow, control stopped) after
|
||||
Manual or Solar, with the charger showing a current, writes nothing and
|
||||
raises one warning, *Charger kept its current*, taken down at 0 A.
|
||||
- **C5.** Each shutdown try waits 4 s for its read-back (D3 above).
|
||||
- **C6.** One write clock: Solar's 30 s gate also counts from Manual's latest
|
||||
non-zero write, the start included. Solar's first write after Manual is its
|
||||
0 A, which is never gated.
|
||||
- **C8.** A charger or HA outage ends a phase change: the return restarts the
|
||||
plan paused, so nothing of the sequence resumes; only a 0 A may come before
|
||||
the start rule.
|
||||
- **C9.** An exit owes its 0 A while Solar's own value may stand: by its own
|
||||
bookkeeping (a 0 A not read back counts) or by the read-back showing a value
|
||||
it sent, confirmed, tried or saw at a refused try.
|
||||
- **C3** is T43-T45; **C7** is EV-22's.
|
||||
+21
-158
@@ -251,15 +251,10 @@ The label and description each setting shows on the Configuration tab, in tab or
|
||||
| Safety | Opposing inverters time (s) | `circulation_hold_s` | For two or more inverters: how long they may push against each other before a safety stop. Derived value, leave it unchanged. |
|
||||
| Safety | Not delivering alarm after (s) | `delivery_hold_s` | For two or more inverters: how long one may fall short of its share before an alarm, which changes nothing. Derived value, leave it unchanged. |
|
||||
| Safety | Shadow mode | `shadow_mode` | The add-on makes every decision but keeps every inverter at 0 W. 'auto' does this while control is stopped, 'on' always, 'off' never. |
|
||||
| Car charger | Charger | `ev_charger` | Which car charger the add-on drives. Off leaves everything as it is. In Off mode the add-on only reads the charger and never changes it. |
|
||||
| Car charger | Charger | `ev_charger` | Which car charger the add-on reads. Off leaves everything as it is. This version only reads the charger and never changes it. |
|
||||
| Car charger | Current setting entity | `ev_current_entity` | The entity that sets the charger's current. The add-on finds the charger's other entities from its name. |
|
||||
| Car charger | Charger limit (A) | `ev_max_a` | The most current the charger may ever be asked for. Never above what the charger reports. Lower it for a weaker fuse or cable. |
|
||||
| Car charger | Phases | `ev_phases` | How many phases the charger may use: 1, 3, or 1 and 3 (auto). |
|
||||
| Car charger | Batteries help with the peak | `ev_batt_cover` | While the car charges. On: the batteries cover it down to the peak reserve. Off: the peak guard leaves the car out, so the car alone can set the peak. |
|
||||
| Car charger | Mode after a restart | `ev_mode_start` | Keep the last mode, or start in Off. A restart in Solar sets the charger to 0 A first, other modes leave its current. |
|
||||
| Car charger | Sun kept back (W) | `ev_margin_w` | Solar: this much spare sun is never given to the car. |
|
||||
| Car charger | Start after (minutes) | `ev_start_min` | Solar: the car starts after this long with enough spare sun. |
|
||||
| Car charger | Pause after (minutes) | `ev_pause_min` | Solar: with too little sun the car holds 6 A this long, then pauses. |
|
||||
| Advanced | Start control on boot | `auto_start` | Off by default. Leave it off until the site is commissioned, so someone presses Start after each restart. |
|
||||
| Advanced | Control gain | `gain` | How much of the remaining error control corrects each cycle. Measured on real hardware, do not raise it. |
|
||||
| Advanced | Largest change per cycle (W) | `slew_w` | How far the command may move in one cycle. 0 follows “Inverter rating” and is recommended. |
|
||||
@@ -3280,11 +3275,9 @@ it.
|
||||
|
||||
### Car charger
|
||||
|
||||
The add-on can drive your car charger and shows it on **Home**, on a *Car* card.
|
||||
The card has three modes in this version: **Off** (the add-on only reads the
|
||||
charger and writes nothing), **Manual** (the add-on sets the current and the
|
||||
phases you choose) and **Solar** (the car charges only from spare sun). Night
|
||||
mode comes in a later version.
|
||||
The add-on can read your car charger and show it on **Home**, on a *Car* card. In
|
||||
this version it only reads. It never changes the charger, so it is safe to run
|
||||
beside your own automation. Later versions will add charging modes.
|
||||
|
||||
| option | meaning |
|
||||
|---|---|
|
||||
@@ -3292,150 +3285,44 @@ mode comes in a later version.
|
||||
| `ev_current_entity` | The charger's current setting, for example `number.wallbox_power_connector_max_current_socket_1`. The add-on finds the charger's other entities from this name. |
|
||||
| `ev_max_a` | The most current the charger may ever be asked for. It cannot be higher than the station limit the charger reports. |
|
||||
| `ev_phases` | `1`, `3` or `auto` (1 and 3). |
|
||||
| `ev_batt_cover` | On (the default): the batteries help cover the car down to the peak reserve. Off: the car is left out of what the peak guard protects. |
|
||||
| `ev_mode_start` | `keep` (the default) or `off`: the mode after a restart. |
|
||||
| `ev_margin_w` | Solar: the spare sun never given to the car, 0 to 1000 W (100). |
|
||||
| `ev_start_min` | Solar: minutes of enough sun before the car starts, 1 to 30 (2). |
|
||||
| `ev_pause_min` | Solar: minutes the car holds 6 A on too little sun before it pauses, 1 to 30 (5). |
|
||||
|
||||
**What the Car card shows.** The state (Charging, Connected waiting, No car
|
||||
connected, Car is full, Charger not reachable), the power and current, and the
|
||||
energy charged today. The car's power is taken out of the **House** tile and out
|
||||
of the house profile that plans the batteries' night charge, so the batteries
|
||||
no longer buy energy for a car that charged last night.
|
||||
|
||||
**Manual mode.** Choose *Manual* on Home, then set the current (6 A up to the
|
||||
charger limit) and 1 or 3 phases. The same three are Home Assistant entities
|
||||
when MQTT is on: `select.goodwe_car_mode` (Off, Manual, Solar), `number.goodwe_car_current`
|
||||
and `select.goodwe_car_phases`. The mode, the current and the phases apply at
|
||||
once, with no restart. The add-on writes each one once, when you change it, and
|
||||
checks within 10 seconds that the charger took it.
|
||||
|
||||
- The current is never higher than the smallest of the charger limit, the station
|
||||
limit the charger reports and the charger's own range. A value above that is a
|
||||
software fault: it is logged and never sent.
|
||||
- With no car connected, or a full car, nothing is written. The setting waits
|
||||
until a car is connected.
|
||||
- A phase change always goes through the same steps: 0 A, wait until the
|
||||
charger draws under 100 W (at most 20 seconds), select the phases, wait 10
|
||||
seconds, set the current again. At most one phase change per 10 minutes.
|
||||
- Shadow mode keeps the charger alone, as it keeps the inverters alone: the card
|
||||
says what the add-on *would* set. Nothing is written either while control is
|
||||
stopped.
|
||||
- A restart, stopping control and a safety stop leave the charger at its
|
||||
current. When the charger answers again after being away, the add-on sets your
|
||||
current again only if the charger shows a different one.
|
||||
- Off writes nothing, ever.
|
||||
|
||||
**Solar mode.** Choose *Solar* on Home, or `Solar` in `select.goodwe_car_mode`.
|
||||
The car charges only from the spare sun: what the solar panels make that the
|
||||
house does not use (the meter, the batteries and the car's own power add up to
|
||||
it). *Spare sun goes first to* (on the card, and `select.goodwe_car_sun_first`)
|
||||
says who gets it first:
|
||||
|
||||
- **Batteries:** the car gets the sun the batteries cannot take. Each battery
|
||||
that may charge from the sun (switched On, not refusing a charge, not full)
|
||||
keeps its whole rating first. With your two batteries and one of them full,
|
||||
7.9 kW of sun and 0.9 kW of house leave 1.9 kW for the car: 8 A on 1 phase.
|
||||
- **Car:** the car takes the spare sun first, the batteries get the rest.
|
||||
|
||||
In both, `ev_margin_w` (100 W) is kept back. The current is the car's share
|
||||
divided by 230 V per phase, rounded down, from 6 A up to the charger limit. It
|
||||
changes at most once per 30 seconds and only by 1 A or more.
|
||||
|
||||
- **Start and pause.** The car starts after `ev_start_min` (2 minutes) with
|
||||
enough sun for 7 A. Under 6 A worth it holds 6 A for `ev_pause_min` (5
|
||||
minutes), from the batteries or the grid, then the charger goes to 0 A and
|
||||
the card says *Waiting for sun*.
|
||||
- **Phases** (`ev_phases` auto): Solar starts on 1 phase, goes to 3 at 4.5 kW for
|
||||
3 minutes and back to 1 under 4.0 kW for 5 minutes, at most once per 10
|
||||
minutes, always through the safe sequence above. With `ev_phases` 1 or 3 it
|
||||
never switches. A car that draws one phase while three are allowed is counted
|
||||
on one phase until it is unplugged.
|
||||
- **When the sun cannot be measured** (the meter older than 15 seconds, a battery
|
||||
or grid reading missing, readings late, a car reading that is stale or not
|
||||
confirmed by the charger's energy meter), the current stands for
|
||||
`ev_pause_min`, then 0 A.
|
||||
- **The fail state is 0 A.** Choosing Off, stopping control, shadow mode, a
|
||||
safety stop, a charger error, a stuck charger reading, unplugging the car and
|
||||
stopping the add-on each set the charger to 0 A once. A 0 A the charger does
|
||||
not take is tried again after a minute, three times, then an amber row says
|
||||
so. After a restart, or when the charger or Home Assistant answers again,
|
||||
Solar sets 0 A first and then starts by its own rules. At a stop of the
|
||||
add-on the charger's 0 A goes out before the batteries go to 0 W, for at
|
||||
most 15 seconds; if the charger does not take it, the notice *Car may still
|
||||
be charging* follows.
|
||||
- **Shadow mode** writes nothing but that one 0 A; a start in shadow mode writes
|
||||
nothing at all. The card says what Solar would set.
|
||||
- **Another writer.** If the charger shows a current Solar did not set for 30
|
||||
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.
|
||||
- **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
|
||||
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
|
||||
what the car drew. When the car alone is why the batteries cannot hold the
|
||||
period, the add-on does **not** raise *Battery stopped limiting the peak* or
|
||||
*Load too high for battery*. It shows a grey note *Car over the peak
|
||||
limit* once per charging session, a grey row, and says so in the car's *Why*.
|
||||
This holds only while the car's reading is fresh and the charger's energy
|
||||
meter confirms it (the meter must have gained at least half of what the power
|
||||
adds up to over the last minute). A stale, stuck or frozen reading, or a
|
||||
charger with no energy entity, never hides a real overload of the house: the
|
||||
normal alarms stand. With `ev_batt_cover` off, the peak
|
||||
guard protects the house without the car, so it does not spend the batteries on
|
||||
it. Normal zero-grid control can still discharge them for the car, and a grid
|
||||
charge of the batteries can bring the period to the peak limit plus the car.
|
||||
The period can go over by the car alone. When the month's peak was set by a car
|
||||
charge, Home's peak line says so.
|
||||
no longer buy energy for a car that charged last night. The peak limit works as
|
||||
before: the car is still part of what the grid meter sees.
|
||||
|
||||
**When the charger does not answer.** After 30 seconds the card says *Charger
|
||||
not reachable* and one amber row appears. After 5 minutes one notification
|
||||
follows. While the car reading is older than 15 seconds the House tile shows no
|
||||
reading, and that moment is left out of the house profile, rather than guessing
|
||||
how much the car took. A reading that does not move for a minute after the
|
||||
add-on changed the current shows the amber row *Charger reading may be stuck*;
|
||||
the add-on goes on writing. If the charger does not take a phase change three
|
||||
times, an amber row says so and the add-on stops trying until you change
|
||||
something; the car gets its current back each time.
|
||||
how much the car took.
|
||||
|
||||
**Another writer.** In Manual, if the charger shows a different current than the
|
||||
add-on set, for 30 seconds, something else is setting it, usually your own
|
||||
automation. The page shows a grey row, and the add-on writes nothing over it until
|
||||
you change the mode or a value. In Off the grey row *Something else changes the
|
||||
charger* shows for an hour after a change. That is expected while you migrate.
|
||||
**Another controller.** If the charger's current changes while the add-on writes
|
||||
nothing, something else sets it, usually your own automation. The page then shows
|
||||
the grey row *Another controller changes the charger*. That is expected while
|
||||
you migrate.
|
||||
|
||||
**Moving your own automation to the add-on.** Each step can be undone.
|
||||
|
||||
1. Install this version and set `ev_charger` to `alfen_ha`. The mode starts in
|
||||
**Off**: the add-on reads the charger and writes nothing. Compare the card
|
||||
with your automation for a few days.
|
||||
2. Cut-over, in the evening with the car unplugged: in Home Assistant switch your
|
||||
automation **off** (do not delete it). On the card choose **Manual** with the
|
||||
current your helper held (`input_number.ev_manual_current`). Plug in and check
|
||||
the current on the card and on the charger's display.
|
||||
1. Install this version and set `ev_charger` to `alfen_ha`. The add-on reads the
|
||||
charger and writes nothing. Compare the card with your automation for a few
|
||||
days.
|
||||
2. When a later version adds charging modes, switch your automation **off**
|
||||
(do not delete it) in the evening with the car unplugged, then choose the
|
||||
add-on's Manual mode with the current your helper held. Plug in and check the
|
||||
current on the card and on the charger's display.
|
||||
3. On the next sunny day, choose Solar, with *spare sun goes first to* set as
|
||||
your priority switch was.
|
||||
4. Keep your Home Assistant helpers for a week. To go back, set the add-on mode
|
||||
to Off and switch the automation on. After that you can delete the helpers and
|
||||
the automation.
|
||||
|
||||
**Never let the automation and the add-on both write the charger.** Two writers
|
||||
fight over the one setting and neither can tell which won. Turn the automation
|
||||
off before you choose Manual, and the add-on off (mode Off) before you turn the
|
||||
automation on.
|
||||
Never let the automation and the add-on both write the charger.
|
||||
|
||||
**Home Assistant entities.** With MQTT the add-on adds the sensors
|
||||
`goodwe_car_power`, `goodwe_car_state`, `goodwe_car_today_kwh` and
|
||||
`goodwe_car_today_solar_kwh`, and the four controls named above. A saved ("retained") command is never applied, so a
|
||||
restart of Home Assistant cannot change the charger.
|
||||
**Home Assistant entities.** With MQTT the add-on adds three sensors:
|
||||
`goodwe_car_power`, `goodwe_car_state` and `goodwe_car_today_kwh`.
|
||||
|
||||
### Site
|
||||
|
||||
@@ -3564,29 +3451,6 @@ last setting. The add-on changes nothing on the charger in any case. Check the
|
||||
charger's integration in Home Assistant. The notification goes by itself when
|
||||
the charger answers again.
|
||||
|
||||
### Car over the peak limit
|
||||
|
||||
The car charge you set (Manual) takes the 15-minute period over the peak limit,
|
||||
and the batteries cannot hold it because they are at the peak reserve or at
|
||||
their full power. The add-on never slows the car, so this is information, not an
|
||||
alarm. It is raised once per charging session. To stay under the limit, lower the
|
||||
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.
|
||||
|
||||
### Charger kept its current
|
||||
|
||||
The add-on started without writing to the charger (shadow mode, or control
|
||||
not started yet), and the charger still has the current the add-on set before
|
||||
it stopped, in Manual or Solar. Nothing changes the charger until you start
|
||||
control or turn shadow mode off. Check the charger if the car should not be
|
||||
charging. The notification goes once the charger shows 0 A.
|
||||
|
||||
### Car may still be charging
|
||||
|
||||
The add-on stopped in Solar mode, and the charger did not take the 0 A it sent
|
||||
first. The batteries were set to 0 W on time anyway. Check the current at the
|
||||
charger. At the next start Solar sets 0 A first and the notification goes.
|
||||
|
||||
### For installers: notifications
|
||||
|
||||
A fixed tariff beside the price service raises no notification: it is the
|
||||
@@ -3614,7 +3478,6 @@ default `info` hides it.
|
||||
| Battery cycle did not finish | warning | `goodwe_maint_failed_<name>` | MAINT-13 |
|
||||
| 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 |
|
||||
|
||||
**The Details link.** Home Assistant 2026.2 and newer show add-on pages at
|
||||
`/config/app/<slug>/documentation`; 2026.5 removed the old
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,12 +5,10 @@ actuator per site, a census key, a read, a clamped write that says whether the
|
||||
charger took it, and a hand-back. A charger is a modulated actuator with a fail
|
||||
state, not one of DEV-01's on/off loads.
|
||||
|
||||
EV-04 IS THE FIRST CARD THAT WRITES TO THE CHARGER, in Manual and (EV-20) in
|
||||
Solar (`app/carmode.py` is the one caller). `write_current` is clamped to
|
||||
`min(ev_max_a, the station limit the charger reports, the entity's own range)`
|
||||
and a value above that is NEVER SENT: it is a software fault, logged in the
|
||||
OUTPUT_CLAMP shape. It says True only when the charger's read-back followed
|
||||
within `TOOK_S`. Off writes nothing (EV-03's no-write test still holds for it).
|
||||
THIS CARD NEVER WRITES TO THE CHARGER. `write_current`, `write_phases` and
|
||||
`release` are defined so the seam is whole, and NOTHING in the controller calls
|
||||
them: Off is the only mode. test_ev03.py greps the controller for a call and
|
||||
proves a full cycle makes no service call that names a charger entity.
|
||||
|
||||
VALUES ARE BELIEVED ONLY IN THEIR OWN UNIT (as TEL-11 does for power): power in
|
||||
a power unit, energy in a kWh unit, current in A. A reading in another unit is
|
||||
@@ -22,17 +20,12 @@ as an argument, so the checks need no sleep.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .hass import BAD_STATES
|
||||
from .solarfc import KWH_PER
|
||||
|
||||
_LOG = logging.getLogger("goodwe")
|
||||
|
||||
OFF = "off"
|
||||
ALFEN_HA = "alfen_ha"
|
||||
#: the `ev_charger` values the options accept
|
||||
@@ -41,14 +34,7 @@ PHASES_CHOICES = ("1", "3", "auto")
|
||||
|
||||
# config.yaml's shipped defaults, mirrored (test_defaults_pin.py checks it).
|
||||
EV_OPTION_DEFAULTS = {"ev_charger": "off", "ev_current_entity": "",
|
||||
"ev_max_a": 16, "ev_phases": "auto",
|
||||
"ev_batt_cover": True, "ev_mode_start": "keep",
|
||||
# EV-20, Solar: the sun kept back and the two dwells
|
||||
"ev_margin_w": 100, "ev_pause_min": 5,
|
||||
"ev_start_min": 2}
|
||||
#: EV-20: the ranges config.yaml's schema and the validator both hold.
|
||||
SOLAR_RANGES = {"ev_margin_w": (0, 1000), "ev_pause_min": (1, 30),
|
||||
"ev_start_min": (1, 30)}
|
||||
"ev_max_a": 16, "ev_phases": "auto"}
|
||||
|
||||
|
||||
def max_a(opts: dict):
|
||||
@@ -72,32 +58,6 @@ FULL_C_S = 600.0 # mode3 C under FULL_C_W this long: car full
|
||||
FULL_C_W = 200.0
|
||||
WRITER_HOLD_S = 3600.0 # "another controller" stays shown this long
|
||||
IDLE_A = 1.0 # a phase under this draws nothing
|
||||
TOOK_S = 10.0 # a write is "taken" when the read-back follows by then
|
||||
TOOK_TOL_A = 0.5 # ... to within this
|
||||
STUCK_S = 60.0 # EV-04: power and read-back unchanged after a write
|
||||
STUCK_MIN_A = 1.0 # ... that moved the setpoint by at least this
|
||||
LIFE_KEEP_S = 40.0 # EV-13: samples kept to date a refused write's life
|
||||
OWN_WRITE_MUTE_S = 15.0 # the tracker's two-writer detector ignores our own
|
||||
# Volts used to bound a car figure by what the read-back allows (a physical
|
||||
# ceiling for the alarm path, never a setpoint).
|
||||
CEILING_V = 253.0
|
||||
# EV-04 round 2: the car's power may be used by the peak guard's alarm path only
|
||||
# while the charger's energy meter CORROBORATES it. Looking back over readings
|
||||
# (all in mode3 C, no gap) to the shortest stretch that is at least CORR_WINDOW_S
|
||||
# long AND over which the reported power adds up to at least CORR_MIN_WH, the
|
||||
# meter must have advanced by at least CORR_RATIO of that, less CORR_SLACK_WH (the
|
||||
# meter shows 10 Wh steps, so at 40 Wh expected it must show one step). Readings
|
||||
# are kept for CORR_KEEP_S. Until such a stretch exists (a session just began, or
|
||||
# the add-on just started) the figure is believed, as it was before. A frozen
|
||||
# figure of P watts on a car that has really stopped is caught within
|
||||
# max(CORR_WINDOW_S, CORR_MIN_WH / P) seconds: 60 s at 2.4 kW and up, 104 s at
|
||||
# 1.38 kW (6 A, 1 phase). Below CORR_MIN_WH over CORR_KEEP_S (about 0.8 kW) the
|
||||
# figure is believed; it cannot hide an overload that matters.
|
||||
CORR_WINDOW_S = 60.0
|
||||
CORR_RATIO = 0.5
|
||||
CORR_SLACK_WH = 15.0
|
||||
CORR_MIN_WH = 40.0
|
||||
CORR_KEEP_S = 180.0
|
||||
|
||||
# role -> (entity domain, suffix after `<x>_`). `current` is the setpoint, the
|
||||
# one the installer names; the rest are derived by swapping its suffix.
|
||||
@@ -127,7 +87,6 @@ REQUIRED = ("current", "readback", "state", "power")
|
||||
_SETPOINT_RE = re.compile(r"^number\.(?P<x>.+)_" + SETPOINT_SUFFIX + "$")
|
||||
|
||||
_ROLE_ORDER = tuple(ROLES)
|
||||
_LIFE_ROLES = ("power", "energy", "l1", "l2", "l3") # EV-13
|
||||
#: power unit -> W. The probe and the reading both use this one table.
|
||||
_W_PER = {"mW": 0.001, "W": 1.0, "kW": 1000.0, "MW": 1000000.0}
|
||||
POWER_UNITS = tuple(_W_PER)
|
||||
@@ -169,10 +128,6 @@ class ChargerReading:
|
||||
error: str | None = None # None: no error (or not read)
|
||||
display: str | None = None
|
||||
why: str = "" # for the log only, "" when available
|
||||
# EV-13: when the sample was TAKEN, on the tracker's clock. None: the
|
||||
# caller's `now` (in the cycle that is the read's start, `now_mono`).
|
||||
taken_at: float | None = None
|
||||
phase_a: tuple = () # EV-13: L1, L2, L3 each, None if not read
|
||||
|
||||
|
||||
def _state_obj(obj):
|
||||
@@ -292,7 +247,6 @@ def reading_from_states(states: dict) -> ChargerReading:
|
||||
available=True, state=letter, connected=connected, charging=charging,
|
||||
power_w=power, energy_kwh=_kwh(states.get("energy")),
|
||||
current_a=currents, setpoint_a=_amps(states.get("current")),
|
||||
phase_a=tuple(_amps(states.get(k)) for k in ("l1", "l2", "l3")),
|
||||
allowed_a=_amps(states.get("readback")),
|
||||
phases_allowed=_phases(states.get("phases_read")),
|
||||
station_a=_first(_amps(states.get("station_active")),
|
||||
@@ -396,13 +350,8 @@ class ChargerDriver:
|
||||
async def read(self) -> ChargerReading:
|
||||
raise NotImplementedError
|
||||
|
||||
# --- the write side (EV-04). `app/carmode.py` is the one caller. ---------
|
||||
async def clamp_a(self) -> float:
|
||||
"""The most a write may ask for: `min(ev_max_a, the station limit read
|
||||
from the charger, the entity's own range max)`."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def write_current(self, a: float, took_s: float = TOOK_S) -> bool:
|
||||
# --- the write side. DEFINED, UNUSED BY THE CONTROLLER IN THIS CARD. ----
|
||||
async def write_current(self, a: float) -> bool:
|
||||
raise NotImplementedError
|
||||
|
||||
async def write_phases(self, n: int) -> bool:
|
||||
@@ -427,15 +376,6 @@ class AlfenHaDriver(ChargerDriver):
|
||||
self._ents = entities_for(self.current_entity)
|
||||
self._hass = None
|
||||
self._getter = None
|
||||
# Seams for the checks: how a write waits for the read-back, and the
|
||||
# clock it counts on.
|
||||
self._sleep = asyncio.sleep
|
||||
self._clock = time.monotonic
|
||||
self.clamp_faults = [] # (asked, clamp), newest last, for the log
|
||||
self.sent = [] # every number value actually sent
|
||||
# EV-13: what the latest write saw while it waited for the read-back,
|
||||
# [(time, ChargerReading)]: the cycle's reads do not run inside it.
|
||||
self.polls = []
|
||||
|
||||
@classmethod
|
||||
def from_options(cls, opts: dict) -> "AlfenHaDriver":
|
||||
@@ -474,6 +414,7 @@ class AlfenHaDriver(ChargerDriver):
|
||||
return dict(self._ents)
|
||||
|
||||
async def _states(self, roles=_ROLE_ORDER) -> dict:
|
||||
import asyncio
|
||||
hass = self._h()
|
||||
got = await asyncio.gather(*(hass.state(self._ents[r]) for r in roles))
|
||||
return dict(zip(roles, got))
|
||||
@@ -493,100 +434,20 @@ class AlfenHaDriver(ChargerDriver):
|
||||
by_ent = {self._ents[r]: o for r, o in st.items()}
|
||||
return probe_from(self.current_entity, by_ent.get)
|
||||
|
||||
# --- the write side -------------------------------------------------------
|
||||
async def clamp_a(self) -> float:
|
||||
"""`min(ev_max_a, station limit, entity range max)`. A limit the charger
|
||||
did not answer is not a limit (the other two still bound the write)."""
|
||||
st = await self._states(("current", "station", "station_active"))
|
||||
station = _first(_amps(st["station_active"]), _amps(st["station"]))
|
||||
rng = ENTITY_MAX_A
|
||||
attrs = (st["current"] or {}).get("attributes") \
|
||||
if isinstance(st.get("current"), dict) else None
|
||||
if isinstance(attrs, dict):
|
||||
try:
|
||||
rng = min(rng, float(attrs["max"]))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
pass
|
||||
return min(x for x in (self.max_a, station, rng) if x is not None)
|
||||
|
||||
async def write_current(self, a: float, took_s: float = TOOK_S) -> bool:
|
||||
"""Set the current, once. True only when the charger took it: the
|
||||
read-back followed within `took_s` (`TOOK_S`; EV-20's shutdown 0 A
|
||||
waits less, so three tries fit its 15 s). A value above `clamp_a()` is a
|
||||
SOFTWARE FAULT: nothing is sent, it is logged (the clamp watchdog's
|
||||
shape) and the answer is False."""
|
||||
self.polls = []
|
||||
try:
|
||||
a = float(a)
|
||||
except (TypeError, ValueError):
|
||||
a = float("nan")
|
||||
clamp = await self.clamp_a()
|
||||
if a != a or a < 0.0 or a > clamp + 1e-9:
|
||||
self.clamp_faults.append((a, clamp))
|
||||
del self.clamp_faults[:-20]
|
||||
_LOG.error("Software fault: the add-on was about to ask the charger "
|
||||
"for more than its limit, so nothing was sent: "
|
||||
"CHARGER_CLAMP.")
|
||||
_LOG.debug("Asked for %.1f A against a limit of %.1f A.", a, clamp)
|
||||
return False
|
||||
hass = self._h()
|
||||
self.sent.append(a)
|
||||
del self.sent[:-50]
|
||||
if not await hass.set_number(self.current_entity, a):
|
||||
return False
|
||||
return await self._took(a, took_s)
|
||||
|
||||
async def _took(self, a: float, took_s: float = TOOK_S) -> bool:
|
||||
"""Did the read-back follow the write, within `took_s`?"""
|
||||
t0 = self._clock()
|
||||
while True:
|
||||
st = await self._states(("readback", "current") + _LIFE_ROLES)
|
||||
self._poll(st)
|
||||
seen = _first(_amps(st["readback"]), _amps(st["current"]))
|
||||
if seen is not None and abs(seen - a) <= TOOK_TOL_A:
|
||||
return True
|
||||
if self._clock() - t0 >= took_s:
|
||||
return False
|
||||
await self._sleep(1.0)
|
||||
|
||||
def _poll(self, st: dict) -> None:
|
||||
"""EV-13: keep what this wait saw of energy, power and phase currents
|
||||
(never raises: a write does not depend on it)."""
|
||||
try:
|
||||
self.polls.append((self._clock(), ChargerReading(
|
||||
available=True, power_w=_watts(st.get("power")),
|
||||
energy_kwh=_kwh(st.get("energy")),
|
||||
phase_a=tuple(_amps(st.get(k)) for k in ("l1", "l2", "l3")))))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# --- the write side, UNUSED in EV-03 --------------------------------------
|
||||
async def write_current(self, a: float) -> bool:
|
||||
a = max(0.0, min(float(a), self.max_a, ENTITY_MAX_A))
|
||||
return await self._h().set_number(self.current_entity, a)
|
||||
|
||||
async def write_phases(self, n: int) -> bool:
|
||||
"""Select 1 or 3 phases. ONLY THROUGH `carmode`'s safe sequence: the
|
||||
setting moves the contactors, so it is touched with the car paused."""
|
||||
if n not in (1, 3):
|
||||
return False
|
||||
want = "1 Phase" if n == 1 else "3 Phases"
|
||||
if not await self._h().call("select", "select_option", {
|
||||
"entity_id": self._ents["phases_set"], "option": want}):
|
||||
return False
|
||||
t0 = self._clock()
|
||||
while True:
|
||||
st = await self._states(("phases_read", "phases_set"))
|
||||
seen = _phases(st["phases_read"])
|
||||
if seen is None:
|
||||
seen = _phases(st["phases_set"])
|
||||
if seen == n:
|
||||
return True
|
||||
if self._clock() - t0 >= TOOK_S:
|
||||
return False
|
||||
await self._sleep(1.0)
|
||||
return await self._h().call("select", "select_option", {
|
||||
"entity_id": self._ents["phases_set"],
|
||||
"option": "1 Phase" if n == 1 else "3 Phases"})
|
||||
|
||||
async def release(self, mode: str) -> bool:
|
||||
"""The mode's fail state. Manual and Off keep the current (the charger
|
||||
is a stand-alone device and the current is the user's setting).
|
||||
Solar's 0 A goes through `carmode.SolarWriter.release`, the one write
|
||||
site, so nothing is written here."""
|
||||
return True
|
||||
return await self.write_current(0.0) if mode == "solar" else True
|
||||
|
||||
|
||||
class UnavailableCharger(ChargerDriver):
|
||||
@@ -612,9 +473,6 @@ class UnavailableCharger(ChargerDriver):
|
||||
async def limits(self) -> tuple:
|
||||
return None, None, None
|
||||
|
||||
async def clamp_a(self) -> float:
|
||||
return 0.0
|
||||
|
||||
async def read(self) -> ChargerReading:
|
||||
return ChargerReading(why=self.why)
|
||||
|
||||
@@ -663,31 +521,6 @@ CHARGING, WAITING, NONE_, FULL, UNREACH, SETUP, FAULT = (
|
||||
"charging", "waiting", "none", "full", "unreach", "setup", "fault")
|
||||
|
||||
|
||||
def _life_vals(r) -> tuple:
|
||||
"""EV-13: what shows a charger is alive: energy, power, three phase
|
||||
currents. None is "not read"."""
|
||||
cur = tuple(r.phase_a or ())
|
||||
if len(cur) != 3:
|
||||
# Only `current_a`, which leaves out a phase that is not read: which
|
||||
# phase is which is then known only when all three are there.
|
||||
cur = tuple(r.current_a or ())
|
||||
cur = cur if len(cur) == 3 else (None,) * 3
|
||||
return (r.energy_kwh, r.power_w) + cur
|
||||
|
||||
|
||||
def _alive(vals: tuple, pre: list) -> bool:
|
||||
"""A value that is present now, was present before the write, and differs
|
||||
from every value before it. Present but unchanged, or not there before, is
|
||||
no life."""
|
||||
for i, v in enumerate(vals):
|
||||
if v is None:
|
||||
continue
|
||||
old = [p[i] for p in pre if p[i] is not None]
|
||||
if old and all(v != o for o in old):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@dataclass
|
||||
class CarTracker:
|
||||
"""What the cycle learns about the car from the readings. Pure, clocked by
|
||||
@@ -713,17 +546,6 @@ class CarTracker:
|
||||
c_low_since: float | None = None
|
||||
writer_at_utc: object = None
|
||||
_prev: tuple | None = None
|
||||
# EV-04: our own writes, and the stuck-reading rule (SAFETY-37's shape)
|
||||
mute_until: float = 0.0
|
||||
armed_at: float | None = None
|
||||
armed_sig: tuple | None = None
|
||||
sig: tuple | None = None
|
||||
stuck_now: bool = False
|
||||
obs_at: float | None = None # monotonic second of the latest reading
|
||||
# EV-13: a REFUSED write waits to see if the charger shows life (below)
|
||||
_pend: dict | None = None
|
||||
_ring: list = field(default_factory=list) # (taken-at, life values)
|
||||
_hist: list = field(default_factory=list) # (t, power W, energy Wh)
|
||||
# today's energy
|
||||
day: str | None = None
|
||||
today_kwh: float | None = None
|
||||
@@ -732,8 +554,6 @@ class CarTracker:
|
||||
|
||||
def observe(self, r: ChargerReading, now: float, now_utc, day: str):
|
||||
self.reading = r
|
||||
self.obs_at = now
|
||||
self._corr_note(r, now)
|
||||
usable = r.available and r.power_w is not None
|
||||
if r.available:
|
||||
self.bad_since = None
|
||||
@@ -743,12 +563,8 @@ class CarTracker:
|
||||
if usable:
|
||||
self.last_ok = now
|
||||
self.last_good, self.last_good_utc = r, now_utc
|
||||
if not r.available:
|
||||
self._pend_lapse(now)
|
||||
if r.available:
|
||||
self._life(r, now)
|
||||
self._sig(r, now)
|
||||
self._writer(r, now_utc, now)
|
||||
self._writer(r, now_utc)
|
||||
self._energy(r, day)
|
||||
self._timers(r, now)
|
||||
self._status_edge(now, now_utc)
|
||||
@@ -778,189 +594,11 @@ class CarTracker:
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
# -- EV-04: the stuck-reading rule -------------------------------------------
|
||||
def begin_write(self) -> None:
|
||||
"""EV-12: a write of ours is in flight. Its read-back can reach the
|
||||
tracker before `note_write` runs (the write waits for it), so the mute
|
||||
is open until `end_write`."""
|
||||
self.mute_until = float("inf")
|
||||
|
||||
def end_write(self, now: float) -> None:
|
||||
"""EV-12: the write returned (or failed). The mute runs
|
||||
`OWN_WRITE_MUTE_S` from now, not from before the write."""
|
||||
self.mute_until = now + OWN_WRITE_MUTE_S
|
||||
|
||||
def note_write(self, now: float, was_a, to_a, ok: bool = True,
|
||||
polls=()) -> None:
|
||||
"""The add-on wrote the current at `now`. Its own change is not
|
||||
"another writer" for `OWN_WRITE_MUTE_S`, and a write that moved the
|
||||
setpoint by `STUCK_MIN_A` or more arms the stuck check: power and
|
||||
read-back that have not changed `STUCK_S` later are a stuck reading,
|
||||
not a car.
|
||||
|
||||
EV-13: a write the charger REFUSED (`ok` False) arms it only when the
|
||||
charger shows no life: the energy, a phase current or the power
|
||||
changed in a sample taken after `now` and within `TOOK_S` of it,
|
||||
against the last values before. A refused write on a charger that is
|
||||
plainly alive is not a stuck reading. `polls` are the samples the
|
||||
write itself saw while it waited, `[(time, ChargerReading)]`."""
|
||||
self.mute_until = now + OWN_WRITE_MUTE_S
|
||||
try:
|
||||
moved = was_a is None or abs(float(to_a) - float(was_a)) \
|
||||
>= STUCK_MIN_A
|
||||
except (TypeError, ValueError):
|
||||
moved = False
|
||||
if self._pend is not None and now > self._pend["t"] + TOOK_S:
|
||||
self._pend_arm() # the old window ran out
|
||||
if not moved or self.armed_at is not None:
|
||||
return
|
||||
if ok:
|
||||
self._pend = None
|
||||
self.armed_at, self.armed_sig = now, self.sig
|
||||
return
|
||||
if self._pend is not None:
|
||||
return # an earlier refusal's window
|
||||
before = [x for x in self._ring if x[0] <= now]
|
||||
pre = [max(before, key=lambda x: x[0])[1]] if before else []
|
||||
self._pend = {"t": now, "pre": pre, "sig": self.sig}
|
||||
later = [(t, _life_vals(r)) for t, r in polls]
|
||||
later += [(t, v) for t, v in self._ring if t > now]
|
||||
for t, v in sorted(later, key=lambda x: x[0]):
|
||||
self._pend_feed(t, v, t)
|
||||
|
||||
def _life(self, r, now: float) -> None:
|
||||
"""EV-13: file this sample (by when it was TAKEN) and let a refused
|
||||
write's open window look at it."""
|
||||
t = now if r.taken_at is None else r.taken_at
|
||||
v = _life_vals(r)
|
||||
self._ring.append((t, v))
|
||||
top = max(x[0] for x in self._ring)
|
||||
self._ring = [x for x in self._ring if top - x[0] <= LIFE_KEEP_S]
|
||||
self._pend_feed(t, v, now)
|
||||
|
||||
def _pend_feed(self, t: float, vals: tuple, arrival: float) -> None:
|
||||
p = self._pend
|
||||
if p is None:
|
||||
return
|
||||
if t <= p["t"]:
|
||||
p["pre"] = (p["pre"] + [vals])[-8:] # taken before the send
|
||||
elif t <= p["t"] + TOOK_S and _alive(vals, p["pre"]):
|
||||
self._pend = None # life: nothing to arm
|
||||
return
|
||||
if max(t, arrival) > p["t"] + TOOK_S:
|
||||
self._pend_arm()
|
||||
|
||||
def _pend_lapse(self, now: float) -> None:
|
||||
"""A reading that did not answer shows no life either: once the window
|
||||
has run out the refusal arms, dated the send, as it did before."""
|
||||
p = self._pend
|
||||
if p is not None and now > p["t"] + TOOK_S:
|
||||
self._pend_arm()
|
||||
|
||||
def _pend_arm(self) -> None:
|
||||
"""No life in the window: arm as the write would have, dated its send."""
|
||||
p, self._pend = self._pend, None
|
||||
if p is not None and self.armed_at is None:
|
||||
self.armed_at, self.armed_sig = p["t"], p["sig"]
|
||||
|
||||
def _sig(self, r, now: float) -> None:
|
||||
sig = (r.power_w, r.allowed_a)
|
||||
if self.armed_at is not None and self.armed_sig is not None \
|
||||
and sig != self.armed_sig:
|
||||
self.armed_at = self.armed_sig = None # it moved: alive
|
||||
self.stuck_now = False
|
||||
elif self.armed_at is not None and self.armed_sig is None:
|
||||
self.armed_sig = sig
|
||||
self.sig = sig
|
||||
if self.armed_at is not None and now - self.armed_at >= STUCK_S:
|
||||
self.stuck_now = True
|
||||
|
||||
def _corr_note(self, r, now: float) -> None:
|
||||
"""Keep the last `CORR_WINDOW_S` of (power, energy) while the charger is
|
||||
charging. Any gap, a car that is not in mode3 C, a reading without
|
||||
power or energy, or a meter that goes back starts the window again."""
|
||||
h = self._hist
|
||||
ok = (r.available and r.charging is True and r.power_w is not None
|
||||
and r.energy_kwh is not None)
|
||||
if not ok or (h and r.energy_kwh * 1000.0 < h[-1][2] - 0.5):
|
||||
h.clear()
|
||||
if not ok:
|
||||
return
|
||||
h.append((now, float(r.power_w), r.energy_kwh * 1000.0))
|
||||
while len(h) > 2 and now - h[1][0] >= CORR_KEEP_S:
|
||||
h.pop(0)
|
||||
|
||||
def corroborated(self, now: float) -> bool:
|
||||
"""Does the charger's energy meter agree with the power it reports? No
|
||||
energy entity, or not charging: no. Less than a window of readings: yes
|
||||
(the first minute of a session is believed). Otherwise the energy the
|
||||
meter gained over the window must be at least `CORR_RATIO` of what the
|
||||
power adds up to, less `CORR_SLACK_WH`. A frozen power figure on a car
|
||||
that has stopped fails this within a window, and so does everything
|
||||
frozen together."""
|
||||
r = self.reading
|
||||
h = self._hist
|
||||
if r is None or not r.available or r.charging is not True \
|
||||
or r.energy_kwh is None or not h:
|
||||
return False
|
||||
exp_wh = 0.0
|
||||
for k in range(len(h) - 1, 0, -1):
|
||||
(t0, p0, e0), (t1, _p1, _e1) = h[k - 1], h[k]
|
||||
exp_wh += p0 * (t1 - t0) / 3600.0
|
||||
if h[-1][0] - t0 >= CORR_WINDOW_S - 5.0 and exp_wh >= CORR_MIN_WH:
|
||||
got_wh = h[-1][2] - e0
|
||||
return got_wh >= CORR_RATIO * exp_wh - CORR_SLACK_WH
|
||||
return True
|
||||
|
||||
def contradicted(self, now: float) -> bool:
|
||||
"""EV-18: did the energy meter answer over a whole window and fall
|
||||
short (`corroborated` compared and failed)? Not when the energy
|
||||
reading is unknown, the window is empty or still short, or the car is
|
||||
not charging: those are unknown, not contradicted."""
|
||||
r = self.reading
|
||||
if r is None or not r.available or r.charging is not True \
|
||||
or r.energy_kwh is None or not self._hist:
|
||||
return False
|
||||
return not self.corroborated(now)
|
||||
|
||||
def stuck(self, now: float) -> bool:
|
||||
"""Power and read-back unchanged `STUCK_S` after a write that moved the
|
||||
setpoint. Cleared the moment either moves."""
|
||||
return self.stuck_now
|
||||
|
||||
def car_w_trusted(self, now: float):
|
||||
"""The car's power for the peak guard's ALARM PATH, or None. Fresh (the
|
||||
EV-03 rules), not stuck after a write, corroborated by the energy meter
|
||||
(`corroborated`), and never above what the read-back allows the car to
|
||||
draw: an old or frozen figure must not hide a house overload."""
|
||||
return self._capped_w(now, True)
|
||||
|
||||
def car_w_paused(self, now: float):
|
||||
"""EV-15: the same figure as `car_w_trusted` without the energy-meter
|
||||
corroboration, which a car held at 0 A by the add-on's own phase change
|
||||
cannot give (the meter's window restarts when it stops charging). Fresh,
|
||||
not stuck, and capped by the read-back. Only for grading the alarm
|
||||
during that sequence (`ctl_car._car_own_pause`)."""
|
||||
return self._capped_w(now, False)
|
||||
|
||||
def _capped_w(self, now: float, corroborate: bool):
|
||||
w = self.car_w(now)
|
||||
if w is None or self.stuck(now) \
|
||||
or (corroborate and not self.corroborated(now)):
|
||||
return None
|
||||
r = self.reading
|
||||
a = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
||||
if a is not None:
|
||||
n = r.phases_allowed if r.phases_allowed in (1, 3) else 3
|
||||
w = min(w, max(0.0, float(a)) * CEILING_V * n)
|
||||
return w
|
||||
|
||||
# -- the two-writer detector ----------------------------------------------
|
||||
def _writer(self, r, now_utc, now=None):
|
||||
def _writer(self, r, now_utc):
|
||||
cur = (r.setpoint_a, r.allowed_a)
|
||||
prev = self._prev
|
||||
muted = now is not None and now < self.mute_until
|
||||
if prev is not None and not muted:
|
||||
if prev is not None:
|
||||
for a, b in zip(prev, cur):
|
||||
if a is not None and b is not None and a != b:
|
||||
self.writer_at_utc = now_utc
|
||||
|
||||
@@ -233,9 +233,6 @@ class AlarmsMixin:
|
||||
# persistent overload is still notified once per quarter.
|
||||
high = bool(
|
||||
g is not None and g.saturated and p is not None
|
||||
# EV-04: not when the car you set explains the excess (a fresh,
|
||||
# trusted car reading only; `ctl_car.car_cycle`).
|
||||
and not getattr(self, "car_explains", False)
|
||||
and p.block_start is not None and not self._peak_rolled
|
||||
and peakguard.load_too_high(
|
||||
p, batt_w=batt, ceiling_w=g.ceiling_w,
|
||||
@@ -279,8 +276,7 @@ class AlarmsMixin:
|
||||
the floor binds this guard only; the loop has no SoC floor and goes on
|
||||
discharging. Edge-triggered. (DECISIONS/MAIN-orchestration-archive.md)"""
|
||||
g = self.peak_guard
|
||||
limited = bool(g is not None and g.floor_limited
|
||||
and not getattr(self, "car_explains", False))
|
||||
limited = bool(g is not None and g.floor_limited)
|
||||
if limited and (g.floor_w or 0.0) > 0.0:
|
||||
limited = self._reserve_short(g)
|
||||
else:
|
||||
|
||||
@@ -1,877 +0,0 @@
|
||||
"""EV-04 and EV-20: the Controller's side of the car's Manual and Solar modes.
|
||||
|
||||
The writes themselves are `carmode.ManualWriter`'s and `carmode.SolarWriter`'s;
|
||||
this mixin owns the state (mode, current, phases, where spare sun goes first:
|
||||
runtime state in the store, like OPT-11's modes), the actions, the background
|
||||
step that never holds up a control cycle, and what the car means for the peak
|
||||
guard's ALARM PATH. DECISIONS/EV-04-manual-mode.md, DECISIONS/EV-20-solar-mode.md
|
||||
(Solar's inputs, its 0 A before the inverters at shutdown, today's solar kWh;
|
||||
the guard treats a Solar car exactly as a Manual car).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import dataclasses
|
||||
import logging
|
||||
from datetime import timezone
|
||||
|
||||
from . import carmode, chargers, messages, packshare, peakguard
|
||||
from .tariff import QUARTER_S
|
||||
|
||||
_LOG = logging.getLogger("goodwe")
|
||||
|
||||
CAR_PEAK_KEY = "car_peak_q" # {quarter start iso: the car's average W}
|
||||
CAR_PEAK_MIN_W = 50.0 # a quarter the car hardly touched is not kept
|
||||
CAR_PEAK_KEEP = 3200 # about a month of quarters
|
||||
OVER_HOLD_S = peakguard.ALARM_HOLD_S
|
||||
# EV-11: the card, the row and Why stay on this long after the car stops being
|
||||
# the cause: longer than the gaps seen on the rig (150 to 250 s at 50 s
|
||||
# sampling) and shorter than a quarter, or until the session really ends.
|
||||
OVER_OFF_HOLD_S = 180.0
|
||||
# EV-15: the longest our own phase change can take (0 A wait, settle, three
|
||||
# tries of a write at 5 s apart and up to 10 s each, the select's own wait);
|
||||
# the grace for the alarm never outlasts it, and after the current is set
|
||||
# again it lasts at most one corroboration window.
|
||||
OWN_PAUSE_MAX_S = (carmode.ZERO_WAIT_S + carmode.SETTLE_S
|
||||
+ carmode.MAX_TRIES * 15.0 + 10.0)
|
||||
OWN_PAUSE_TAIL_S = chargers.CORR_WINDOW_S
|
||||
# EV-19: the meter's house side (held - car) moved no more than this since the
|
||||
# last cycle: it has not shown a battery rise the reading already shows.
|
||||
RISE_STILL_W = 50.0
|
||||
# EV-20: today's kWh from the sun, {day, kwh}; and a shutdown whose 0 A the
|
||||
# charger did not take (D3), so the next start can take its notice down.
|
||||
CAR_SUN_KEY = "car_sun"
|
||||
CAR_RELEASE_KEY = "car_release_failed"
|
||||
# C1 (SPIKE-05): an own 0 A of Solar's is out and not read back yet, kept with
|
||||
# the mode, so a start in Off after a power cut still writes it.
|
||||
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
|
||||
|
||||
|
||||
class CarMixin:
|
||||
# ------------------------------------------------------------------ state
|
||||
def car_init(self, opts, store) -> None:
|
||||
"""Mode, current and phases from the store; `ev_mode_start` says what a
|
||||
restart does with the mode. A site with no charger keeps defaults and
|
||||
writes nothing."""
|
||||
data = getattr(store, "data", None) or {}
|
||||
# C1: the mode before the stop, and an exit 0 A still pending then.
|
||||
stored = data.get(carmode.KEY_MODE)
|
||||
self._car_stored_mode = stored if stored in carmode.MODES \
|
||||
else carmode.OFF
|
||||
self._car_exit_pending = bool(data.get(CAR_EXIT_KEY))
|
||||
self._car_start_seen = False
|
||||
self._car_start_warned = False
|
||||
self.car_mode = carmode.start_mode(opts, data.get(carmode.KEY_MODE))
|
||||
if carmode.start_mode(opts, carmode.MANUAL) == carmode.OFF \
|
||||
and data.get(carmode.KEY_MODE) not in (None, carmode.OFF):
|
||||
store.set(carmode.KEY_MODE, carmode.OFF)
|
||||
clamp = carmode.clamp_for(opts, None)
|
||||
a = carmode.value_a(data.get(carmode.KEY_A, carmode.DEFAULT_A), clamp)
|
||||
self.car_a = carmode.DEFAULT_A if a is None else a
|
||||
n = data.get(carmode.KEY_PHASES, carmode.DEFAULT_PHASES)
|
||||
ok = carmode.allowed_phases(opts)
|
||||
self.car_n = n if n in ok else ok[0]
|
||||
self.car_rev = 0
|
||||
self.car_writer = carmode.ManualWriter()
|
||||
self.car_solar = carmode.SolarWriter() # EV-20
|
||||
self.car_solar.on_owed = self._car_owed
|
||||
if self.car_mode == carmode.OFF and self._car_exit_pending:
|
||||
self.car_solar.owe_start() # C1
|
||||
first = data.get(carmode.KEY_FIRST)
|
||||
self.car_first = first if first in carmode.FIRSTS \
|
||||
else carmode.DEFAULT_FIRST
|
||||
self._car_late_s = None # EV-20: the cycle's late verdict
|
||||
self._car_sun_now = None # ... and Solar's inputs of that cycle
|
||||
sun = data.get(CAR_SUN_KEY)
|
||||
self.car_sun = {"day": None, "kwh": 0.0}
|
||||
if isinstance(sun, dict):
|
||||
try:
|
||||
self.car_sun = {"day": sun.get("day"),
|
||||
"kwh": max(0.0, float(sun.get("kwh") or 0.0))}
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
self._car_sun_mono = None
|
||||
self._car_sun_saved = round(self.car_sun["kwh"], 2)
|
||||
self._car_release_failed = bool(data.get(CAR_RELEASE_KEY))
|
||||
self._car_task = None
|
||||
self._car_step_failed = False
|
||||
self.car_explains = False # the car alone explains the excess
|
||||
self.car_over = False # ... held: the card and row say so
|
||||
self._car_over_since = None
|
||||
self._car_over_gone = None
|
||||
self._car_why_rec = None # EV-16: [shown over, since, episode]
|
||||
self._car_over_ep = 0 # EV-16: bumped when car_over ends
|
||||
self._car_batt_prev = self._car_batt_prev2 = None
|
||||
self._car_hx_prev = None # EV-19: last cycle's (held, car W)
|
||||
self._car_need_real = self._car_need_excl = False # EV-10 latches
|
||||
self._car_need_house = self._car_over_now = False # EV-18 latches
|
||||
self._car_latch_block = None
|
||||
self._car_contra_block = None # EV-18: the quarter it was contradicted
|
||||
self._car_over_notified = None # the session a notice was raised for
|
||||
self._car_session = 0
|
||||
self._car_prev_state = None
|
||||
self._carq = {"key": None, "ws": 0.0, "ws_p": 0.0, "mono": None}
|
||||
self._peak_proj_real = None
|
||||
saved = data.get(CAR_PEAK_KEY)
|
||||
self.car_peak_q = dict(saved) if isinstance(saved, dict) else {}
|
||||
|
||||
@property
|
||||
def car_cover(self) -> bool:
|
||||
"""Decision 1: do the batteries help cover the car down to the peak
|
||||
reserve? Default yes."""
|
||||
v = self.o.get("ev_batt_cover")
|
||||
return bool(chargers.EV_OPTION_DEFAULTS["ev_batt_cover"]
|
||||
if v is None else v)
|
||||
|
||||
def car_manual(self) -> bool:
|
||||
return (self.charger.configured()
|
||||
and self.car_mode == carmode.MANUAL)
|
||||
|
||||
def _car_owed(self, pending) -> None:
|
||||
"""C1: keep "an own 0 A is out, not read back" with the mode."""
|
||||
pending = bool(pending)
|
||||
if pending != self._car_exit_pending:
|
||||
self._car_exit_pending = pending
|
||||
self.store.set(CAR_EXIT_KEY, pending)
|
||||
|
||||
async def check_car_start(self) -> None:
|
||||
"""C1: the first reading after a start that will not write (shadow,
|
||||
control stopped) shows a current the add-on set before the stop
|
||||
(Manual or Solar then): one warning, taken down once it is 0 A."""
|
||||
r = self.car.reading
|
||||
if r is None or not r.available or not self.charger.configured():
|
||||
return
|
||||
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
||||
if not self._car_start_seen:
|
||||
self._car_start_seen = True
|
||||
if self._car_stored_mode in (carmode.MANUAL, carmode.SOLAR) \
|
||||
and not self.car_writing() and cur is not None \
|
||||
and cur > carmode.TOL_A:
|
||||
self._car_start_warned = True
|
||||
_LOG.warning("The charger still has a current from before "
|
||||
"the restart, and the add-on does not write "
|
||||
"now: CHARGER_START_CURRENT.")
|
||||
_LOG.debug("The charger shows %.0f A at the start.", cur)
|
||||
await self.hass.call("persistent_notification", "create",
|
||||
messages.car_start_current(
|
||||
f"{cur:.0f}").data())
|
||||
elif self._car_start_warned and cur is not None \
|
||||
and cur <= carmode.TOL_A:
|
||||
self._car_start_warned = False
|
||||
await self.hass.call("persistent_notification", "dismiss",
|
||||
messages.car_start_current_gone().data())
|
||||
|
||||
def car_solar_mode(self) -> bool:
|
||||
"""EV-20: a charger is set up and the mode is Solar."""
|
||||
ch = getattr(self, "charger", None)
|
||||
return bool(ch is not None and ch.configured()
|
||||
and getattr(self, "car_mode", None) == carmode.SOLAR)
|
||||
|
||||
def car_controlled(self) -> bool:
|
||||
"""EV-20: Manual or Solar. The peak guard's alarm path treats a Solar
|
||||
car exactly as a Manual car (Expected 8)."""
|
||||
return self.car_manual() or self.car_solar_mode()
|
||||
|
||||
def car_solar_engaged(self) -> bool:
|
||||
"""EV-20: Solar is the mode, or its way-out 0 A is still owed."""
|
||||
w = getattr(self, "car_solar", None)
|
||||
return bool(self.charger.configured() and w is not None
|
||||
and (self.car_mode == carmode.SOLAR or w.engaged))
|
||||
|
||||
def car_clamp(self):
|
||||
return carmode.clamp_for(self.o, self.car.reading)
|
||||
|
||||
def car_writing(self) -> bool:
|
||||
"""May the add-on write to the charger now? Control runs, shadow mode is
|
||||
off, no safety stop is latched and the add-on is not shutting down. Shadow mode gates charger
|
||||
writes exactly as it gates inverter writes."""
|
||||
latched = (any(i.sign_wd.tripped for i in self.inverters)
|
||||
or self.site_sign_wd.tripped or self.circ_wd.tripped)
|
||||
return bool(self.auto and not self.shadow and not latched
|
||||
and not getattr(self, "stopping", False))
|
||||
|
||||
# ---------------------------------------------------------------- actions
|
||||
def _car_action(self, what, value, now) -> dict:
|
||||
"""The mode, the current or the phases, from the page or from Home
|
||||
Assistant. Store state, applied by the next step with no restart."""
|
||||
if not self.charger.configured():
|
||||
return {"error": messages.car_refused("off")}
|
||||
if what == "car_mode":
|
||||
if value not in carmode.MODES:
|
||||
return {"error": messages.car_refused("value")}
|
||||
if value == carmode.SOLAR and self.car_mode != carmode.SOLAR:
|
||||
# A Manual phase change in the middle is not restored: Solar
|
||||
# starts from the 0 A it stands at.
|
||||
self.car_writer.seq = None
|
||||
self.car_mode = value
|
||||
self.store.set(carmode.KEY_MODE, value)
|
||||
elif what == "car_sun_first":
|
||||
# EV-20: arithmetic only, from the next cycle; not a change of the
|
||||
# writers (the 30 s rule and another writer's hold stand).
|
||||
if value not in carmode.FIRSTS:
|
||||
return {"error": messages.car_refused("value")}
|
||||
self.car_first = value
|
||||
self.store.set(carmode.KEY_FIRST, value)
|
||||
self.log_event(f"car sun first set to {value} by operator",
|
||||
hint=messages.hint("car_sun_first"))
|
||||
return {"mode": self.car_mode, "current": self.car_a,
|
||||
"phases": self.car_n, "sun_first": self.car_first}
|
||||
elif what == "car_current":
|
||||
clamp = self.car_clamp()
|
||||
if isinstance(value, bool):
|
||||
return {"error": messages.car_refused("value")}
|
||||
a = carmode.value_a(value, clamp)
|
||||
try:
|
||||
inside = a is not None and abs(float(value) - a) < 0.5
|
||||
except (TypeError, ValueError):
|
||||
inside = False
|
||||
if not inside:
|
||||
return {"error": messages.car_refused("value")}
|
||||
self.car_a = a
|
||||
self.store.set(carmode.KEY_A, a)
|
||||
else:
|
||||
if value not in (1, 3) or isinstance(value, bool):
|
||||
return {"error": messages.car_refused("value")}
|
||||
if value not in carmode.allowed_phases(self.o):
|
||||
return {"error": messages.car_refused("phases")}
|
||||
self.car_n = value
|
||||
self.store.set(carmode.KEY_PHASES, value)
|
||||
self.car_rev += 1
|
||||
self.car_writer.user_changed()
|
||||
if what == "car_mode" and value == carmode.SOLAR:
|
||||
# EV-20: only pressing Solar lifts Solar's other-writer hold.
|
||||
# Leaving Solar, or Manual's current or phases, is not the user
|
||||
# handing the charger back to Solar (N10).
|
||||
self.car_solar.user_changed()
|
||||
self.log_event(f"car {what[4:]} set to {value} by operator",
|
||||
hint=messages.hint(what))
|
||||
return {"mode": self.car_mode, "current": self.car_a,
|
||||
"phases": self.car_n}
|
||||
|
||||
def car_command_values(self) -> dict:
|
||||
"""The MQTT state of the three car entities."""
|
||||
return {"car_mode": carmode.MODE_LABELS[self.car_mode],
|
||||
"car_current": round(self.car_a),
|
||||
"car_phases": str(self.car_n),
|
||||
"car_sun_first": carmode.FIRST_LABELS[self.car_first]}
|
||||
|
||||
# ------------------------------------------------------------- the writer
|
||||
def car_kick(self) -> None:
|
||||
"""Start one writer step in the background, unless one is running. A
|
||||
write waits up to 10 s for the charger's read-back, and a control cycle
|
||||
never waits for the charger."""
|
||||
if not self.charger.configured():
|
||||
return
|
||||
t = self._car_task
|
||||
if t is not None and not t.done():
|
||||
return
|
||||
# EV-20: Solar's inputs as this cycle read them. The step runs beside
|
||||
# the next read, which must not hand it a new meter reading with an
|
||||
# old car reading (or the other way round).
|
||||
self._car_sun_now = (self.car_sun_inputs(self.car_now())
|
||||
if self.car_solar_mode() else None)
|
||||
self._car_task = asyncio.ensure_future(self._car_run())
|
||||
|
||||
def _car_hold_kick(self) -> 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."""
|
||||
if self.car_solar_engaged():
|
||||
self.car_kick()
|
||||
|
||||
async def car_settle(self) -> None:
|
||||
"""Wait for the writer step in flight (the checks use it)."""
|
||||
t = self._car_task
|
||||
if t is not None:
|
||||
await asyncio.gather(t, return_exceptions=True)
|
||||
|
||||
async def _car_run(self) -> None:
|
||||
try:
|
||||
await self.car_step()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception: # noqa: BLE001
|
||||
# Once at WARNING-and-above, then quietly: a step that fails
|
||||
# fails every second.
|
||||
if not self._car_step_failed:
|
||||
self._car_step_failed = True
|
||||
_LOG.exception("The car charger step failed")
|
||||
else:
|
||||
_LOG.debug("The car charger step failed again", exc_info=True)
|
||||
else:
|
||||
self._car_step_failed = False
|
||||
|
||||
async def car_shutdown(self) -> None:
|
||||
"""The add-on stops: no new write. Manual: a phase change in the middle
|
||||
is undone by giving the car its current back; the current stands
|
||||
otherwise (Manual's fail state). Solar (EV-20, D3): 0 A, waited for at
|
||||
most `RELEASE_WAIT_S` (`Controller.shutdown` calls this BEFORE the
|
||||
inverters go to 0 W in Solar)."""
|
||||
t, self._car_task = getattr(self, "_car_task", None), None
|
||||
if t is not None and not t.done():
|
||||
t.cancel()
|
||||
await asyncio.gather(t, return_exceptions=True)
|
||||
if self.car_solar_engaged():
|
||||
try:
|
||||
done = await asyncio.wait_for(self.car_solar.release(
|
||||
self.charger, self.car.reading, self.car_now(), self.car),
|
||||
RELEASE_WAIT_S)
|
||||
except Exception: # noqa: BLE001
|
||||
done = False
|
||||
if done is False:
|
||||
self._car_release_failed = True
|
||||
self.store.set(CAR_RELEASE_KEY, True)
|
||||
_LOG.warning("The charger did not take 0 A before the add-on "
|
||||
"stopped, so the car may still be charging: "
|
||||
"CHARGER_RELEASE.")
|
||||
return
|
||||
if not self.charger.configured() \
|
||||
or getattr(self, "car_writer", None) is None \
|
||||
or self.car_writer.seq is None:
|
||||
return
|
||||
try:
|
||||
await asyncio.wait_for(self.car_writer.abandon(
|
||||
self.charger, self.car_now(), self.car, self.car_clamp()),
|
||||
15.0)
|
||||
except Exception: # noqa: BLE001
|
||||
_LOG.warning("The car could not be given its current back "
|
||||
"before the add-on stopped: CHARGER_RESTORE.")
|
||||
|
||||
async def car_release_notice(self) -> None:
|
||||
"""D3: after the inverters are released, one warning notice that the
|
||||
car may still be charging. Bounded: the add-on is stopping."""
|
||||
if not self._car_release_failed or not self.car_solar_engaged():
|
||||
return
|
||||
try:
|
||||
await asyncio.wait_for(self.hass.call(
|
||||
"persistent_notification", "create",
|
||||
messages.car_release_failed().data()), 3.0)
|
||||
except Exception: # noqa: BLE001
|
||||
_LOG.debug("The car notice could not be raised at shutdown",
|
||||
exc_info=True)
|
||||
|
||||
async def check_car_release(self) -> None:
|
||||
"""D3: the notice of a shutdown whose 0 A was not taken comes down once
|
||||
Solar has confirmed its start-up 0 A."""
|
||||
w = self.car_solar
|
||||
if self._car_release_failed and w.engaged and not w.fresh_start \
|
||||
and w.sent_a == 0.0 and w.taken:
|
||||
self._car_release_failed = False
|
||||
self.store.set(CAR_RELEASE_KEY, False)
|
||||
await self.hass.call("persistent_notification", "dismiss",
|
||||
messages.car_release_gone().data())
|
||||
|
||||
async def car_step(self) -> None:
|
||||
"""One step of Manual or Solar. Reads nothing from the world (the
|
||||
cycle's read did) and writes only through `carmode`'s writers."""
|
||||
if not self.charger.configured():
|
||||
return
|
||||
now = self.car_now()
|
||||
if self.car_mode != carmode.SOLAR:
|
||||
await self.car_writer.step(
|
||||
self.charger, self.car.reading, mode=self.car_mode,
|
||||
want_a=self.car_a, want_phases=self.car_n, rev=self.car_rev,
|
||||
clamp=self.car_clamp(), now=now, tracker=self.car,
|
||||
writing=self.car_writing(), shadow=bool(self.shadow),
|
||||
status=self.car.status(now, True), clock=self.car_now)
|
||||
w = self.car_solar
|
||||
if self.car_mode == carmode.SOLAR or w.engaged:
|
||||
# C6: one write clock: Manual's latest non-zero write counts.
|
||||
w.other_at = max((t for kind, a, t, ok in self.car_writer.log
|
||||
if kind == "current" and a > carmode.TOL_A),
|
||||
default=None)
|
||||
sun = None
|
||||
if self.car_mode == carmode.SOLAR:
|
||||
sun = getattr(self, "_car_sun_now", None) \
|
||||
or self.car_sun_inputs(now)
|
||||
await w.step(
|
||||
self.charger, self.car.reading, mode=self.car_mode,
|
||||
sun=sun,
|
||||
clamp=self.car_clamp(), now=now, tracker=self.car,
|
||||
writing=self.car_writing(), status=self.car.status(now, True),
|
||||
clock=self.car_now)
|
||||
|
||||
# ------------------------------------------------------- EV-20: Solar
|
||||
def car_may_charge(self, inv) -> bool:
|
||||
"""May this battery take the sun? On (battery modes), not refusing a
|
||||
charge, not under a sign stop, its level read and under full."""
|
||||
if self.modes_on and not self.pack_mode(inv).use:
|
||||
return False
|
||||
refused = inv.refused if len(self.inverters) > 1 \
|
||||
else self.batt_refused
|
||||
if (refused or 0) < 0 or inv.sign_wd.tripped:
|
||||
return False
|
||||
return inv.soc is not None and float(inv.soc) < packshare.FULL_PCT
|
||||
|
||||
def car_room_w(self) -> float:
|
||||
"""Batteries first: the RATINGS of the batteries that may charge."""
|
||||
return float(sum(inv.rating_w() for inv in self.inverters
|
||||
if self.car_may_charge(inv)))
|
||||
|
||||
def car_spare_w(self, mono):
|
||||
"""The signed spare sun now, or None when it cannot be measured: a
|
||||
missing meter or battery figure, a meter older than `stale_input_s`,
|
||||
readings late past it, or a charging car whose figure is stale, stuck
|
||||
or not corroborated. A paused or idle car with a fresh reading counts
|
||||
as 0 W."""
|
||||
if not self.inputs_ok:
|
||||
return None
|
||||
stale = float(self.o.get("stale_input_s", 15))
|
||||
late = self._car_late_s
|
||||
if late is not None and late >= stale:
|
||||
return None
|
||||
if self.p1_enabled:
|
||||
# The meter's own bound (`meter_max_age_s`) may be longer than
|
||||
# `stale_input_s`; a car write never comes from an older reading.
|
||||
age = self.p1.age_s()
|
||||
if age is None or age > stale:
|
||||
return None
|
||||
r = self.car.reading
|
||||
if r is None or not r.available or not self.car.fresh(mono):
|
||||
return None
|
||||
car = self.car.car_w_trusted(mono) if r.charging is True else 0.0
|
||||
return carmode.spare_w(car, self.site_batt_w, self.grid)
|
||||
|
||||
def car_sun_inputs(self, mono) -> "carmode.SunInputs":
|
||||
o = self.o
|
||||
spare = self.car_spare_w(mono)
|
||||
late = self._car_late_s
|
||||
hold = late is not None and late < float(o.get("stale_input_s", 15))
|
||||
room = self.car_room_w()
|
||||
margin = carmode.solar_option(o, "ev_margin_w")
|
||||
ph = str(o.get("ev_phases", chargers.EV_OPTION_DEFAULTS["ev_phases"]))
|
||||
return carmode.SunInputs(
|
||||
target_w=carmode.car_target_w(spare, room, margin, self.car_first),
|
||||
hold=hold, auto=ph not in ("1", "3"),
|
||||
start_s=60.0 * carmode.solar_option(o, "ev_start_min"),
|
||||
pause_s=60.0 * carmode.solar_option(o, "ev_pause_min"),
|
||||
spare_w=spare, room_w=room, margin_w=margin, first=self.car_first)
|
||||
|
||||
def _car_sun_tick(self, mono) -> None:
|
||||
"""Solar kWh: per cycle, in Solar only, the car's power up to the sun
|
||||
it may take (`spare - room` Batteries first, `spare` Car first). The
|
||||
hold's battery or grid share and Manual do not count."""
|
||||
if not self.car_solar_mode():
|
||||
self._car_sun_mono = None
|
||||
return
|
||||
day = self.car.day
|
||||
if day is not None and self.car_sun.get("day") != day:
|
||||
self.car_sun = {"day": day, "kwh": 0.0}
|
||||
self.store.set(CAR_SUN_KEY, dict(self.car_sun))
|
||||
self._car_sun_saved = 0.0
|
||||
last, self._car_sun_mono = self._car_sun_mono, mono
|
||||
if last is None:
|
||||
return
|
||||
dt = min(max(mono - last, 0.0), 5.0)
|
||||
p = self.car.car_w(mono)
|
||||
spare = self.car_spare_w(mono)
|
||||
if p is None or spare is None or dt <= 0.0:
|
||||
return
|
||||
sun = spare - (self.car_room_w() if self.car_first == carmode.FIRST_BATT
|
||||
else 0.0)
|
||||
share = min(float(p), max(0.0, sun))
|
||||
if share <= 0.0:
|
||||
return
|
||||
self.car_sun["kwh"] += share * dt / 3.6e6
|
||||
if round(self.car_sun["kwh"], 2) != self._car_sun_saved:
|
||||
self._car_sun_saved = round(self.car_sun["kwh"], 2)
|
||||
self.store.set(CAR_SUN_KEY, {"day": self.car_sun["day"],
|
||||
"kwh": round(self.car_sun["kwh"], 4)})
|
||||
|
||||
def car_sun_kwh(self):
|
||||
"""Today's kWh from the sun, never above today's kWh; None without a
|
||||
reading of today."""
|
||||
if self.car.today_kwh is None:
|
||||
return None
|
||||
if self.car_sun.get("day") != self.car.day:
|
||||
return 0.0
|
||||
return max(0.0, min(float(self.car_sun["kwh"]),
|
||||
float(self.car.today_kwh)))
|
||||
|
||||
def car_amps_now(self):
|
||||
"""D1: the current Solar charges the car at now: the read-back, else
|
||||
what Solar sent. Never Manual's stored value."""
|
||||
r = self.car.reading
|
||||
if r is not None and r.available:
|
||||
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
||||
if cur is not None:
|
||||
return float(cur)
|
||||
w = self.car_solar
|
||||
return float(w.sent_a or 0.0)
|
||||
|
||||
# ------------------------------------------- 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."""
|
||||
if not self.car_controlled():
|
||||
return None
|
||||
return self.car.car_w_trusted(self.car_now())
|
||||
|
||||
def _car_own_pause(self, mono) -> bool:
|
||||
"""EV-15: is the car held at 0 A by the add-on's OWN phase change? From
|
||||
the moment its 0 A write is SENT (the cycle runs beside the write)
|
||||
until the current is set again, then at most one corroboration window.
|
||||
No when it was aborted (Off, Stop, shadow, unplug, another writer), a
|
||||
write was refused, or it ran past its own maximum.
|
||||
|
||||
EV-20: Solar's own phase change the same way, and Solar's own 0 A
|
||||
pause from the moment it is sent, at most `OWN_PAUSE_MAX_S`, and only
|
||||
while the read-back still shows that 0 A (a car another writer starts
|
||||
is never Solar's pause)."""
|
||||
solar = self.car_solar_mode()
|
||||
wr = getattr(self, "car_solar" if solar else "car_writer", None)
|
||||
own_zero = solar and wr is not None and self._car_solar_zero(wr)
|
||||
if wr is None or (wr.seq is None and wr.phase_done_at is None
|
||||
and wr.zero_sent_at is None and not own_zero) \
|
||||
or wr.hold:
|
||||
return False
|
||||
r = self.car.reading
|
||||
if not (self.car_controlled() and self.car_writing()
|
||||
and r is not None and r.available and r.state != "A"):
|
||||
return False
|
||||
q = wr.seq
|
||||
if q is None and wr.zero_sent_at is not None: # sent, not yet back
|
||||
return 0.0 <= mono - wr.zero_sent_at <= OWN_PAUSE_MAX_S
|
||||
if q is not None:
|
||||
return not q.get("failed") and 0.0 <= mono - q["t0"] \
|
||||
<= OWN_PAUSE_MAX_S
|
||||
if own_zero and 0.0 <= mono - wr.zero_at <= OWN_PAUSE_MAX_S:
|
||||
return True
|
||||
return wr.phase_done_at is not None \
|
||||
and 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S
|
||||
|
||||
def _car_solar_zero(self, wr) -> bool:
|
||||
"""EV-20: is Solar's own latest write a 0 A the charger took, and does
|
||||
the read-back still show it? (Another writer's current ends it.)"""
|
||||
if wr.zero_at is None or wr.sent_a != 0.0 or not wr.taken:
|
||||
return False
|
||||
r = self.car.reading
|
||||
if r is None or not r.available:
|
||||
return False
|
||||
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
||||
return cur is not None and cur <= carmode.TOL_A
|
||||
|
||||
def _car_contradicted(self, mono) -> bool:
|
||||
"""EV-18 (owner 2026-11-19): did the charger's energy meter answer
|
||||
and fall short of a fresh, not stuck figure of a charging car
|
||||
(`CarTracker.contradicted`)? Then that figure stays untrusted for the
|
||||
alarm to the quarter's end (`car_cycle`). An unknown energy reading
|
||||
contradicts nothing."""
|
||||
r = getattr(self.car, "reading", None)
|
||||
if r is None or not r.available or r.charging is not True \
|
||||
or not self.car_controlled():
|
||||
return False
|
||||
return (self.car.car_w(mono) is not None and not self.car.stuck(mono)
|
||||
and self.car.contradicted(mono))
|
||||
|
||||
def _car_idle(self, mono) -> bool:
|
||||
"""EV-18: is the car known to draw nothing? A fresh reading that says
|
||||
it is not charging (mode3 A or B) at under `CAR_PEAK_MIN_W`. Not an
|
||||
unknown figure: the house's own need is graded in such a cycle."""
|
||||
r = getattr(self.car, "reading", None)
|
||||
if r is None or not r.available or r.charging is not False:
|
||||
return False
|
||||
p = self.car.car_w(mono)
|
||||
return p is not None and p < CAR_PEAK_MIN_W
|
||||
|
||||
def _car_quarter(self, proj, w, mono, wg=None) -> None:
|
||||
"""The car's energy in the open quarter, for the average the guard's
|
||||
house leaves out and for the peak line. `wg` (EV-15) is the figure for
|
||||
grading during our own pause; its energy is kept apart (`ws_p`) so the
|
||||
guard's input is unchanged."""
|
||||
q = self._carq
|
||||
key = None if proj is None else proj.block_start
|
||||
last = q["mono"]
|
||||
if key != q["key"]:
|
||||
self._car_bank(q)
|
||||
q["key"], q["ws"], q["ws_p"] = key, 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
|
||||
elif wg is not None:
|
||||
q["ws_p"] = q.get("ws_p", 0.0) + float(wg) * dt
|
||||
q["mono"] = mono
|
||||
|
||||
def _car_bank(self, q) -> None:
|
||||
"""A closed quarter in which the car drew its share goes on the list."""
|
||||
key = q["key"]
|
||||
if key is None:
|
||||
return
|
||||
avg = q["ws"] / QUARTER_S
|
||||
if avg < CAR_PEAK_MIN_W:
|
||||
return
|
||||
self.car_peak_q[key.astimezone(timezone.utc).isoformat()] = round(avg)
|
||||
if len(self.car_peak_q) > CAR_PEAK_KEEP:
|
||||
for k in sorted(self.car_peak_q)[:-CAR_PEAK_KEEP]:
|
||||
del self.car_peak_q[k]
|
||||
self.store.set(CAR_PEAK_KEY, dict(self.car_peak_q))
|
||||
|
||||
def car_avg_w(self, proj, w, graded=False) -> float:
|
||||
"""The car's average over the whole open quarter: what it drew so far
|
||||
and `w` for the rest. `graded` (EV-15) adds what it drew during our
|
||||
own pause."""
|
||||
if proj is None or w is None:
|
||||
return 0.0
|
||||
left = max(0.0, QUARTER_S - float(proj.elapsed_s))
|
||||
so_far = self._carq["ws"] if self._carq["key"] == proj.block_start \
|
||||
else 0.0
|
||||
if graded and self._carq["key"] == proj.block_start:
|
||||
so_far += self._carq.get("ws_p", 0.0)
|
||||
return (so_far + float(w) * left) / QUARTER_S
|
||||
|
||||
def car_exclude(self, proj, w):
|
||||
"""Decision 1 off: the projection the guard sees without the car
|
||||
(`house - car_w`). Unchanged without a fresh car reading."""
|
||||
if proj is None or w is None or proj.block_start is None:
|
||||
return proj
|
||||
avg = self.car_avg_w(proj, w)
|
||||
return dataclasses.replace(
|
||||
proj, projected_w=max(0.0, float(proj.projected_w) - avg),
|
||||
held_w=max(0.0, float(proj.held_w) - float(w)))
|
||||
|
||||
def car_exclude_alarm(self, proj, w):
|
||||
"""EV-10b: the period as it would be without the car, for grading the
|
||||
alarm. The house alone, the batteries giving only what the house
|
||||
would draw from them: the car's share of their power is not charged to
|
||||
the house. The rest of the period keeps its sign (`held - car`, an
|
||||
export while the batteries give more than the house uses), so
|
||||
`misses_aim` adds the batteries back to exactly the house. What is
|
||||
already done is clipped at 0 Ws: no export is credited for power only
|
||||
the car asked for. Unchanged without a fresh car reading."""
|
||||
if proj is None or w is None or proj.block_start is None:
|
||||
return proj
|
||||
avg = self.car_avg_w(proj, w, graded=True)
|
||||
left = max(0.0, QUARTER_S - float(proj.elapsed_s))
|
||||
held = float(proj.held_w)
|
||||
done_ws = QUARTER_S * float(proj.projected_w) - max(held, 0.0) * left
|
||||
car_ws = avg * QUARTER_S - float(w) * left # the car so far
|
||||
held_x = held - float(w)
|
||||
return dataclasses.replace(
|
||||
proj, held_w=held_x,
|
||||
projected_w=(max(0.0, done_ws - car_ws)
|
||||
+ max(held_x, 0.0) * left) / QUARTER_S)
|
||||
|
||||
def car_cycle(self, real_proj, guard, target_w, now_utc) -> None:
|
||||
"""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_sun_tick(mono) # EV-20: today's solar kWh
|
||||
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)
|
||||
wg = w
|
||||
if w is None and own:
|
||||
wg = self.car.car_w_paused(mono)
|
||||
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
|
||||
# alarm again in that quarter, not even as our own pause's stand-in.
|
||||
# The alarm decision only: the car's energy count, the guard's input
|
||||
# (`car_exclude`) and, with the cover off, the car-over row keep it.
|
||||
key = None if real_proj is None else real_proj.block_start
|
||||
if key is not None and not own and self._car_contradicted(mono):
|
||||
self._car_contra_block = key
|
||||
contra = key is not None and key == self._car_contra_block
|
||||
explains = over = False
|
||||
if real_proj is not None and target_w is not None \
|
||||
and real_proj.block_start is not None:
|
||||
# EV-10: every cycle, so the latches do not depend on the option.
|
||||
# EV-18: a car known to draw nothing counts as 0 W for the latches
|
||||
# (the house's own need); it and a 0 W figure explain nothing,
|
||||
# but in our own pause (EV-15).
|
||||
idle = wg is None and self._car_idle(mono)
|
||||
graded = self._car_explains_alarm(
|
||||
real_proj, guard, target_w,
|
||||
None if contra else 0.0 if idle else wg)
|
||||
if contra or idle or (w is not None and float(w) <= 0.0
|
||||
and not own):
|
||||
graded = False
|
||||
if self.car_cover:
|
||||
explains = over = graded
|
||||
elif w is not None:
|
||||
ex = float(real_proj.projected_w) - float(target_w)
|
||||
over = ex > 0.0 and self.car_avg_w(real_proj, w) >= ex
|
||||
self.car_explains = explains
|
||||
# EV-11: on once the condition has stood for OVER_HOLD_S, a short gap
|
||||
# in it not starting that count again; off only after it has been gone
|
||||
# for OVER_OFF_HOLD_S. `car_explains` (the alarm decision) has no hold.
|
||||
if over:
|
||||
self._car_over_gone = None
|
||||
if self._car_over_since is None:
|
||||
self._car_over_since = mono
|
||||
if mono - self._car_over_since >= OVER_HOLD_S:
|
||||
self.car_over = True
|
||||
else:
|
||||
if self._car_over_gone is None:
|
||||
self._car_over_gone = mono
|
||||
if mono - self._car_over_gone >= OVER_OFF_HOLD_S:
|
||||
self.car_over, self._car_over_since = False, None
|
||||
self._car_over_ep += 1 # EV-16: an episode ends
|
||||
self._car_over_gone = None
|
||||
self._car_why_tick(guard, mono)
|
||||
|
||||
def _car_why_tick(self, guard, mono) -> None:
|
||||
"""EV-16, display only: control writes `_car_why_rec`, never reads it.
|
||||
The Car Why text ("are at" / "give all they can") is held: it changes
|
||||
only when the other state has stood for `OVER_OFF_HOLD_S` of THIS
|
||||
cycle's clock (so reads of /status do not matter). State: floor-limited
|
||||
with the SoC read; a guard of None, or unread SoC, never counts as
|
||||
floor. Cleared when car_over is off or the cover is off."""
|
||||
if not (self.car_over and self.car_cover):
|
||||
self._car_why_rec = None
|
||||
return
|
||||
cand = None if guard is None else bool(
|
||||
getattr(guard, "floor_limited", False)
|
||||
and getattr(guard, "soc", None) is not None)
|
||||
ep = self._car_over_ep
|
||||
r = self._car_why_rec
|
||||
if r is None or r[2] != ep:
|
||||
self._car_why_rec = [bool(cand), None, ep]
|
||||
elif cand is None or cand == r[0]:
|
||||
r[1] = None
|
||||
else:
|
||||
if r[1] is None:
|
||||
r[1] = mono
|
||||
if mono - r[1] >= OVER_OFF_HOLD_S:
|
||||
self._car_why_rec = [cand, None, ep]
|
||||
|
||||
def _car_explains_alarm(self, real_proj, guard, target_w, w) -> bool:
|
||||
"""EV-10: is the alarm's own test true with the car and false without
|
||||
its fresh, corroborated share (`car_exclude_alarm`), on the same landing? The
|
||||
tests are the alarms': a saturated guard and a floor with other
|
||||
batteries left are graded by `load_too_high` on where the period lands
|
||||
(SAFETY-81 / 87); a floor that leaves nothing is graded by SAFETY-126's
|
||||
`misses_aim` (the batteries at 0 W from now on), latched for the
|
||||
quarter (`_car_need_real`, and `_car_need_excl` without the car).
|
||||
EV-18 (owner 2026-11-19): without the car, the batteries keep giving
|
||||
what they give now (the lower of two readings), re-checked every cycle;
|
||||
a miss seen so (`_car_need_house`) never lets the car explain for the
|
||||
rest of the quarter. The car also explains where the period with it,
|
||||
on the same batteries, misses (`_car_over_now`). Only a trusted figure
|
||||
latches: an untrusted car (`w` None) or an unknown battery reading
|
||||
explains nothing in that cycle only. All reset at a new quarter and
|
||||
when the guard no longer wants power, whatever the cover option says
|
||||
(this runs every cycle). DECISIONS/EV-04-manual-mode.md (EV-18)."""
|
||||
now, prev = self.site_batt_w, self._car_batt_prev
|
||||
prev2, self._car_batt_prev2 = self._car_batt_prev2, prev
|
||||
self._car_batt_prev = now
|
||||
wants = bool(guard is not None and guard.engaged
|
||||
and guard.blind is None
|
||||
and (guard.wanted_w or 0.0) > 0.0)
|
||||
if real_proj.block_start != self._car_latch_block or not wants:
|
||||
self._car_latch_block = real_proj.block_start
|
||||
self._car_need_real = self._car_need_excl = False
|
||||
self._car_need_house = self._car_over_now = False
|
||||
batt = now
|
||||
if batt is not None and prev is not None:
|
||||
batt = min(float(batt), float(prev))
|
||||
excl = self.car_exclude_alarm(real_proj, w)
|
||||
# EV-19: the reading can show a rise one cycle before the meter does
|
||||
# (the batteries pick up the house at the reserve). While the meter's
|
||||
# house side (held - car; held alone when a car figure is unknown) has
|
||||
# not moved, a reading above both earlier ones is not yet counted as
|
||||
# house; a meter that moved shows it (no discount).
|
||||
held = float(real_proj.held_w)
|
||||
hp, self._car_hx_prev = self._car_hx_prev, (held, w)
|
||||
still = False
|
||||
if hp is not None:
|
||||
moved = held - hp[0]
|
||||
if w is not None and hp[1] is not None:
|
||||
moved -= float(w) - float(hp[1])
|
||||
still = abs(moved) <= RISE_STILL_W
|
||||
seen = now
|
||||
if still and now is not None and prev is not None \
|
||||
and prev2 is not None:
|
||||
seen = min(float(now), max(float(prev), float(prev2)))
|
||||
if wants and batt is not None:
|
||||
self._car_need_real = self._car_need_real or \
|
||||
peakguard.misses_aim(real_proj, batt_w=batt,
|
||||
target_w=target_w)
|
||||
self._car_over_now = self._car_over_now or \
|
||||
self._car_lands_over(real_proj, now, batt, target_w)
|
||||
if w is not None:
|
||||
self._car_need_excl = self._car_need_excl or \
|
||||
peakguard.misses_aim(excl, batt_w=batt, target_w=target_w)
|
||||
self._car_need_house = self._car_need_house or \
|
||||
self._car_lands_over(excl, seen, batt, target_w)
|
||||
if w is None or batt is None or not wants \
|
||||
or not (guard.saturated or guard.floor_limited):
|
||||
return False
|
||||
if guard.saturated:
|
||||
rating = self.site_rating_w
|
||||
elif (guard.floor_w or 0.0) > 0.0 and guard.able_w is not None:
|
||||
rating = guard.able_w
|
||||
else:
|
||||
return bool(not guard.within_aim and self._car_need_real
|
||||
and not self._car_need_house
|
||||
and (self._car_over_now or not self._car_need_excl))
|
||||
|
||||
def high(p):
|
||||
return peakguard.load_too_high(
|
||||
p, batt_w=batt, ceiling_w=guard.ceiling_w,
|
||||
achievable_w=rating)
|
||||
return bool(high(real_proj) and not high(excl))
|
||||
|
||||
@staticmethod
|
||||
def _car_lands_over(p, now, gives, target_w) -> bool:
|
||||
"""EV-18: does the period end more than `ALARM_MISS_W` over the aim
|
||||
with the batteries giving `gives` W from now on (`now`: what they gave
|
||||
in the meter's figure)? Of what is done, only the car's energy counted
|
||||
since the add-on started is the car's (a restart or a gap leaves the
|
||||
rest with the house)."""
|
||||
return peakguard.load_too_high(p, batt_w=now, ceiling_w=target_w,
|
||||
achievable_w=gives)
|
||||
|
||||
def _car_session_tick(self, mono) -> None:
|
||||
"""A charging session is a plug-in: the state goes from no car to a
|
||||
car. The notice is raised once per session."""
|
||||
s = self.car.status(mono, True)
|
||||
if s in (chargers.NONE_,) and self._car_prev_state not in (
|
||||
None, chargers.NONE_):
|
||||
self._car_over_notified = None
|
||||
# The session is over: that is a real end, with no hold.
|
||||
self.car_over = False
|
||||
self._car_over_since = self._car_over_gone = None
|
||||
self._car_over_ep += 1 # EV-16: an episode ends
|
||||
if s not in (chargers.NONE_, None) and self._car_prev_state in (
|
||||
chargers.NONE_, None):
|
||||
self._car_session += 1
|
||||
self._car_prev_state = s
|
||||
|
||||
async def check_car_over(self) -> None:
|
||||
"""One grey notice per charging session: the charge you set takes the
|
||||
15-minute period over the peak limit. Raised nowhere else."""
|
||||
if not self.car_over or self._car_over_notified == self._car_session:
|
||||
return
|
||||
self._car_over_notified = self._car_session
|
||||
if self.car_solar_mode(): # EV-20, D1
|
||||
_LOG.info("Solar's car charge takes this 15-minute period over "
|
||||
"the peak limit: CAR_OVER_PEAK.")
|
||||
await self.hass.call("persistent_notification", "create",
|
||||
messages.car_over_solar(
|
||||
f"{self.car_amps_now():.0f}").data())
|
||||
return
|
||||
_LOG.info("The car charge you set takes this 15-minute period over "
|
||||
"the peak limit: CAR_OVER_PEAK.")
|
||||
await self.hass.call("persistent_notification", "create",
|
||||
messages.car_over(f"{self.car_a:.0f}").data())
|
||||
|
||||
def car_peak_by_car(self, reading, now):
|
||||
"""`(True, local time)` when the month's peak quarter was one the car
|
||||
mostly made (it drew half the peak or more), else `(False, None)`."""
|
||||
if reading is None or not getattr(reading, "is_observed", False) \
|
||||
or reading.quarter_start is None or not self.car_peak_q:
|
||||
return False, None
|
||||
avg = self.car_peak_q.get(
|
||||
reading.quarter_start.astimezone(timezone.utc).isoformat())
|
||||
if avg is None or reading.peak_w is None \
|
||||
or 2.0 * float(avg) < float(reading.peak_w):
|
||||
return False, None
|
||||
return True, reading.quarter_start
|
||||
@@ -253,7 +253,6 @@ class CycleMixin:
|
||||
|
||||
stale_after = float(self.o.get("stale_input_s", 15))
|
||||
late_s = self._readings_late(site_standing) # SAFETY-128
|
||||
self._car_late_s = late_s # EV-20: Solar holds, then the stale rule
|
||||
self._late_zero = late_s is not None and late_s >= stale_after
|
||||
# ⚠️ `any`, NOT the sole unit's. The hold exists so a single missed
|
||||
# poll does not become a fault; a LATCHED inverter must still reach the
|
||||
@@ -273,7 +272,6 @@ 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
|
||||
return
|
||||
if late_s is not None and late_s < stale_after and self.inputs_ok \
|
||||
and (self.auto or self.shadow) \
|
||||
@@ -281,7 +279,6 @@ 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
|
||||
return
|
||||
|
||||
claims = []
|
||||
@@ -394,16 +391,6 @@ class CycleMixin:
|
||||
if self._peak_proj is not None and len(self.inverters) > 1:
|
||||
self._peak_proj = next_quarter(self._peak_proj,
|
||||
self.p1.averager.max_hold_s)
|
||||
# EV-04, decision 1: with "Batteries help with the peak while the car
|
||||
# charges" OFF, the guard's house leaves the car out (`house - car_w`).
|
||||
# `_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.
|
||||
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,
|
||||
self.car_alarm_w())
|
||||
self.peak_guard = None if not self.p1_enabled else peakguard.decide(
|
||||
self._peak_proj,
|
||||
# ⚠️ THE SITE SUM. The guard sizes a floor from what the battery is
|
||||
@@ -453,13 +440,6 @@ class CycleMixin:
|
||||
self.peak_guard = self._peak_landing(self.peak_guard)
|
||||
self.peak_guard = peakguard.cap_floor( # SAFETY-128
|
||||
self.peak_guard, self.answer.peak_cap(site_standing))
|
||||
# EV-04: does the car alone explain what the guard cannot hold? Fresh
|
||||
# car readings only; the claim, the floor and the commands above are
|
||||
# not touched by it.
|
||||
self.car_cycle(self._peak_proj_real, self.peak_guard,
|
||||
peakguard.quarter_target_w(
|
||||
float(self.o.get("peak_cap_w", 3500)),
|
||||
self.peak_margin_w, _reading), now)
|
||||
# SITE, and peakguard.claim() says so on the object it builds: the
|
||||
# quantity is the 15-minute average OFFTAKE AT THE GRID CONNECTION,
|
||||
# which the capacity tariff bills (one quarter-hour peak per site, not
|
||||
@@ -1068,10 +1048,6 @@ class CycleMixin:
|
||||
# and, on a change only, one Home Assistant call.
|
||||
await self.check_price_gap()
|
||||
await self.check_charger()
|
||||
await self.check_car_over()
|
||||
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
|
||||
await self.check_fixed_note()
|
||||
|
||||
# SAFETY-31's alarm, and its boundary is the LATCH, not a number: it
|
||||
|
||||
@@ -15,8 +15,8 @@ from .freeze import rail_unreachable, rail_w
|
||||
from .hass import OUTAGE
|
||||
from .maintenance import IDLE
|
||||
from .mqtt import (
|
||||
BASE, PAYLOAD_NONE, announced_units, optional_keys, parse_car_command,
|
||||
parse_command, unit_slugs, unit_state_key,
|
||||
PAYLOAD_NONE, announced_units, optional_keys, parse_command, unit_slugs,
|
||||
unit_state_key,
|
||||
)
|
||||
from . import peakguard
|
||||
from . import pv as pv_read
|
||||
@@ -35,9 +35,6 @@ class StatusMixin:
|
||||
already holds the last choice). Never raises: MQTT must not reach
|
||||
control. (DECISIONS/MAIN-orchestration-archive.md)"""
|
||||
try:
|
||||
if isinstance(topic, str) and topic.startswith(f"{BASE}/car/"):
|
||||
await self._car_mqtt_command(topic, payload, retained)
|
||||
return
|
||||
slug, action, value, why = parse_command(
|
||||
topic, payload, retained, packmode.MODES)
|
||||
if why is None:
|
||||
@@ -71,29 +68,6 @@ class StatusMixin:
|
||||
except Exception: # noqa: BLE001
|
||||
_LOG.exception("Home Assistant command could not be handled")
|
||||
|
||||
async def _car_mqtt_command(self, topic, payload, retained) -> None:
|
||||
"""EV-04: one command from the car's HA entities, through
|
||||
handle_action(). A retained command is never applied. Never raises."""
|
||||
action, value, why = parse_car_command(topic, payload, retained)
|
||||
result = None
|
||||
if why is None:
|
||||
result = await self.handle_action(action, value=value)
|
||||
if isinstance(result, dict) and "error" not in result:
|
||||
self.mqtt.publish(self.car_command_values())
|
||||
return
|
||||
why = result["error"] if isinstance(result, dict) else "refused"
|
||||
else:
|
||||
why = messages.car_refused("topic") if why == "topic" else \
|
||||
messages.pack_refused(why)
|
||||
topic_s = "".join(c if c.isprintable() else "?" for c in str(topic)[:128])
|
||||
_LOG.debug("Home Assistant command %s %s refused: %s", topic_s,
|
||||
repr(payload)[:48], why)
|
||||
if (topic_s, why) not in self._mqtt_refused \
|
||||
and len(self._mqtt_refused) < 32:
|
||||
self._mqtt_refused.add((topic_s, why))
|
||||
_LOG.warning("Home Assistant command on %s ignored: %s", topic_s,
|
||||
why)
|
||||
|
||||
@property
|
||||
def why_words(self) -> str:
|
||||
"""The page's "Why" line. While control waits for a missing reading
|
||||
@@ -204,48 +178,9 @@ class StatusMixin:
|
||||
out.append({"ok": False, "warn": True, "id": "charger",
|
||||
"text": messages.row_charger_unreach(
|
||||
f"{brussels(self.car.bad_since_utc):%H:%M}")})
|
||||
w = self.car_writer
|
||||
sw = self.car_solar
|
||||
if self.car_mode == "solar" or (sw.engaged and sw.gave_up):
|
||||
# EV-20: in Solar another writer stops the add-on's writes: amber.
|
||||
if sw.other and self.car_mode == "solar":
|
||||
out.append({"ok": False, "warn": True, "id": "charger_other",
|
||||
"text": messages.row_charger_other_solar()})
|
||||
if sw.gave_up:
|
||||
out.append({"ok": False, "warn": True, "id": "charger_refused",
|
||||
"text": messages.row_charger_refused()})
|
||||
if sw.phases_gave_up and self.car_mode == "solar":
|
||||
out.append({"ok": False, "warn": True, "id": "charger_phases",
|
||||
"text": messages.row_charger_phases()})
|
||||
elif self.car_mode == "manual":
|
||||
# EV-04: in Manual the add-on's own writes are not "another
|
||||
# writer"; its own detector (a read-back that differs from the
|
||||
# last write for 30 s) says so, in grey.
|
||||
if w.other:
|
||||
out.append({"ok": True, "warn": True, "id": "charger_other",
|
||||
"text": messages.row_charger_other()})
|
||||
if w.gave_up:
|
||||
out.append({"ok": False, "warn": True, "id": "charger_refused",
|
||||
"text": messages.row_charger_refused()})
|
||||
if w.phases_gave_up:
|
||||
out.append({"ok": False, "warn": True, "id": "charger_phases",
|
||||
"text": messages.row_charger_phases()})
|
||||
elif self.car.other_writer(datetime.now(timezone.utc)):
|
||||
if self.car.other_writer(datetime.now(timezone.utc)):
|
||||
out.append({"ok": True, "warn": True, "id": "charger_writer",
|
||||
"text": messages.row_charger_writer()})
|
||||
if self.car.stuck(self.car_now()):
|
||||
out.append({"ok": False, "warn": True, "id": "charger_stuck",
|
||||
"text": messages.row_charger_stuck()})
|
||||
r = self.car.reading
|
||||
if r is not None and r.available and r.error:
|
||||
out.append({"ok": True, "warn": True, "id": "charger_error",
|
||||
"text": messages.row_charger_error(r.error)})
|
||||
if self.car_over:
|
||||
out.append({"ok": True, "warn": True, "id": "car_over",
|
||||
"text": (messages.row_car_over_solar(
|
||||
f"{self.car_amps_now():.0f}")
|
||||
if self.car_solar_mode()
|
||||
else messages.row_car_over())})
|
||||
return out
|
||||
|
||||
def car_values(self) -> dict:
|
||||
@@ -257,7 +192,6 @@ class StatusMixin:
|
||||
with homeview.in_lang("en"):
|
||||
word = homeview.car_state_word(state)
|
||||
return {
|
||||
**self.car_command_values(),
|
||||
"car_state": word,
|
||||
# `ABSENT_AS_UNKNOWN` stays the one PV key (test_pv.py): an absent
|
||||
# car figure is HA's own "no value" payload, sent by name.
|
||||
@@ -265,9 +199,6 @@ class StatusMixin:
|
||||
or r.power_w is None else round(r.power_w, 1)),
|
||||
"car_today_kwh": (PAYLOAD_NONE if self.car.today_kwh is None
|
||||
else round(self.car.today_kwh, 3)),
|
||||
# EV-20: today's kWh from the sun (Solar only adds to it)
|
||||
"car_today_solar_kwh": (PAYLOAD_NONE if self.car_sun_kwh() is None
|
||||
else round(self.car_sun_kwh(), 3)),
|
||||
}
|
||||
|
||||
# -- UI ------------------------------------------------------------------
|
||||
@@ -404,13 +335,6 @@ class StatusMixin:
|
||||
if _pg is None:
|
||||
out.append({"ok": True, "warn": True, "id": "peak_guard",
|
||||
"text": messages.row_peak_guard_waiting()})
|
||||
elif self.car_explains and (_pg.saturated or _pg.floor_limited):
|
||||
# EV-04: the car you set is what the batteries cannot hold, so
|
||||
# no red row. The grey row `car_over` says what is going on.
|
||||
out.append({"ok": True, "warn": False, "id": "peak_guard",
|
||||
"text": messages.row_peak_guard_on(
|
||||
_pg.floor_w or 0.0, _pg.ceiling_w,
|
||||
shadow=self.shadow)})
|
||||
elif _pg.saturated and not _pg.within_aim:
|
||||
out.append({"ok": False, "warn": False, "id": "peak_guard",
|
||||
"runs": True,
|
||||
@@ -940,8 +864,6 @@ class StatusMixin:
|
||||
now = datetime.now(timezone.utc)
|
||||
if what in ("pack_use", "pack_mode", "pack_sell"):
|
||||
return self._pack_action(what, unit, value, now)
|
||||
if what in ("car_mode", "car_current", "car_phases", "car_sun_first"):
|
||||
return self._car_action(what, value, now)
|
||||
if what == "auto_toggle":
|
||||
self.auto = not self.auto
|
||||
self.store.set("auto", self.auto)
|
||||
|
||||
@@ -19,8 +19,7 @@ section at the bottom and is held to STYLE.md by test_messages.py.
|
||||
import contextlib
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from . import (arbitrage, carmode, cheaproll, handback, messages, peakguard,
|
||||
priceruns, uitext)
|
||||
from . import arbitrage, cheaproll, handback, messages, peakguard, priceruns, uitext
|
||||
from .dayplan import EFF
|
||||
from .maintenance import CHARGE as M_CHARGE, DRAIN as M_DRAIN, HOLD as M_HOLD
|
||||
from .maintenance import IDLE as M_IDLE, next_slot_start
|
||||
@@ -872,10 +871,8 @@ def peak_engaged(c) -> bool:
|
||||
only), so no battery gives power for it. Nor when the quarter ends on
|
||||
the aim anyway (SAFETY-126, `within_aim`)."""
|
||||
pg = getattr(c, "peak_guard", None)
|
||||
# EV-04: not for a cause the car's own Why explains.
|
||||
return bool(pg is not None and pg.engaged and (pg.floor_w or 0.0) > 0.0
|
||||
and not pg.within_aim
|
||||
and not getattr(c, "car_explains", False))
|
||||
and not pg.within_aim)
|
||||
|
||||
|
||||
def battery_rows(c, shadow, running, held=False):
|
||||
@@ -1132,30 +1129,10 @@ def month_peak(c, now):
|
||||
if pg is not None:
|
||||
out["period_w"] = pg.projected_w
|
||||
ceiling = pg.ceiling_w or limit_w
|
||||
real = getattr(c, "_peak_proj_real", None)
|
||||
if getattr(c, "car_enabled", False) and c.charger.configured() \
|
||||
and not c.car_cover and c.car_controlled() and real is not None \
|
||||
and getattr(real, "block_start", None) is not None:
|
||||
# EV-04, decision 1 off: the guard's own projection leaves the car
|
||||
# out; the period as the meter will bill it does not.
|
||||
out["period_w"] = real.projected_w
|
||||
out["line"] = line_period(out["period_w"], ceiling, c.shadow,
|
||||
unmeasured=getattr(c, "peak_unmeasured_s", 0.0)
|
||||
> 0.0,
|
||||
cut=getattr(c, "room_charge", False))
|
||||
# EV-04: when a car charge you asked for is in this period, and when one
|
||||
# set the month's peak. Both empty without a charger in Manual.
|
||||
out["car_line"] = out["set_by"] = ""
|
||||
if getattr(c, "car_enabled", False) and c.charger.configured():
|
||||
w = c.car_alarm_w()
|
||||
if pg is not None and w is not None and w >= 500.0 \
|
||||
and out["period_w"] is not None and (pg.engaged or c.car_over):
|
||||
out["car_line"] = _t("peak.car", kw=_kw(out["period_w"]),
|
||||
car=_kw(w),
|
||||
cov=_kw(max(0.0, float(c.site_batt_w or 0))))
|
||||
by_car, at = c.car_peak_by_car(reading, now)
|
||||
if by_car:
|
||||
out["set_by"] = _t("peak.set_by_car", t=f"{brussels(at):%H:%M}")
|
||||
return out
|
||||
|
||||
|
||||
@@ -1301,127 +1278,6 @@ def _car_why(key, c, good):
|
||||
return _t("car.why." + (key if key else "wait"))
|
||||
|
||||
|
||||
# EV-16: the Why of "car over the limit" follows the guard's floor flag, which
|
||||
# toggles cycle by cycle at the reserve. The text is held, on the control
|
||||
# cycle's clock (`ctl_car.CarMixin._car_why_tick`, display only: control writes
|
||||
# `_car_why_rec`, never reads it). The Why only reads it.
|
||||
WHY_HOLD_S = 180.0 # = ctl_car.OVER_OFF_HOLD_S (tested)
|
||||
|
||||
|
||||
def _over_why_is_floor(c, pg) -> bool:
|
||||
"""True: "are at {pct}"; False: "give all they can". With no valid held
|
||||
record (not yet ticked, or of an ended episode) the live state, written
|
||||
nowhere."""
|
||||
rec = getattr(c, "_car_why_rec", None)
|
||||
if rec is not None and rec[2] == getattr(c, "_car_over_ep", 0):
|
||||
return rec[0]
|
||||
return bool(pg is not None and pg.floor_limited and pg.soc is not None)
|
||||
|
||||
|
||||
def _real_phases(c):
|
||||
"""EV-14: the phases the charger reports (1 or 3), or None: no fresh
|
||||
reading, or none read. Reads only; unknown is never a difference."""
|
||||
car = getattr(c, "car", None)
|
||||
r = getattr(car, "reading", None)
|
||||
fresh = getattr(car, "fresh", None)
|
||||
if r is None or fresh is None or not getattr(r, "available", False):
|
||||
return None
|
||||
if not fresh(c.car_now()):
|
||||
return None
|
||||
n = getattr(r, "phases_allowed", None)
|
||||
return n if n in (1, 3) else None
|
||||
|
||||
|
||||
def _car_manual_why(c, key):
|
||||
"""The Why of Manual: what you set, and what the peak limit does about it.
|
||||
Plan lines: two sentences of at most 12 words. EV-14: in shadow mode it
|
||||
says what the add-on would set; after a phase change that did not happen
|
||||
it says what the charger does."""
|
||||
a = f"{float(c.car_a):.0f}"
|
||||
w = c.car_writer
|
||||
pct = _pct(c.o.get("peak_soc_floor", peakguard.PEAK_OPTION_DEFAULTS[
|
||||
"peak_soc_floor"]))
|
||||
if c.car_over:
|
||||
if c.shadow:
|
||||
t, n = w.would if w.would is not None else (c.car_a, c.car_n)
|
||||
return _t("car.why.manual_shadow_over", a=f"{float(t):.0f}",
|
||||
phases=car_phases_word(n))
|
||||
pg = getattr(c, "peak_guard", None)
|
||||
if not c.car_cover:
|
||||
return _t("car.why.manual_nocover", a=a)
|
||||
return _t("car.why.manual_over" if _over_why_is_floor(c, pg)
|
||||
else "car.why.manual_full", a=a, pct=pct)
|
||||
if c.shadow:
|
||||
t, n = w.would if w.would is not None else (c.car_a, c.car_n)
|
||||
return _t("car.why.manual_would", a=f"{float(t):.0f}",
|
||||
phases=car_phases_word(n))
|
||||
if not c.auto:
|
||||
return _t("car.why.manual_stopped")
|
||||
if w.hold:
|
||||
return _t("car.why.manual_other")
|
||||
if key in ("none", "full"):
|
||||
return _t("car.why.manual_wait", a=a)
|
||||
if w.blocked:
|
||||
return _t("car.why.manual_blocked")
|
||||
if c.car_cover and peak_engaged(c):
|
||||
giving = max(0.0, float(c.site_batt_w or 0.0))
|
||||
return _t("car.why.manual_cover", a=a, kw=_kw(giving), pct=pct)
|
||||
real = _real_phases(c)
|
||||
if real is not None and real != c.car_n and w.seq is None:
|
||||
return _t("car.why.manual_phases", a=a,
|
||||
phases=car_phases_word(c.car_n),
|
||||
real=car_phases_word(real))
|
||||
return _t("car.why.manual_set", a=a, phases=car_phases_word(c.car_n))
|
||||
|
||||
|
||||
def _car_solar_why(c, key):
|
||||
"""EV-20: the Why of Solar, from what the writer and its plan did this
|
||||
cycle. Plan lines: two sentences of at most 12 words."""
|
||||
w = c.car_solar
|
||||
p = w.plan
|
||||
o = getattr(c, "o", {}) or {}
|
||||
if c.car_over: # D1
|
||||
return _t("car.why.solar_over", a=f"{c.car_amps_now():.0f}")
|
||||
if w.hold:
|
||||
return _t("car.why.solar_other")
|
||||
if w.zero_owed:
|
||||
# The way-out 0 A is not taken yet: never "paused".
|
||||
return _t("car.why.solar_zero_failed" if w.gave_up
|
||||
else "car.why.solar_zeroing")
|
||||
if w.gave_up:
|
||||
return _t("car.why.solar_refused")
|
||||
if c.shadow:
|
||||
a, n = w.would if w.would is not None else (0.0, p.n)
|
||||
if a and a >= 6:
|
||||
return _t("car.why.manual_would", a=f"{float(a):.0f}",
|
||||
phases=car_phases_word(n))
|
||||
return _t("car.why.solar_would")
|
||||
if not c.auto or not c.car_writing():
|
||||
return _t("car.why.solar_stopped")
|
||||
if w.fault in ("error", "stuck"):
|
||||
return _t("car.why.solar_" + w.fault)
|
||||
if key == "none":
|
||||
return _t("car.why.none")
|
||||
why = p.why
|
||||
sun = w.sun
|
||||
if why == "running":
|
||||
if sun is None or sun.spare_w is None:
|
||||
return _t("car.why.solar_unknown")
|
||||
if sun.first == carmode.FIRST_CAR:
|
||||
return _t("car.why.solar_car",
|
||||
kw=_kw(max(0.0, sun.spare_w - sun.margin_w)))
|
||||
return _t("car.why.solar_batt",
|
||||
kw=_kw(max(0.0, sun.spare_w - sun.room_w - sun.margin_w)))
|
||||
if why == "hold":
|
||||
return _t("car.why.solar_hold", s=f"{carmode.solar_option(o, 'ev_pause_min'):.0f}")
|
||||
if why == "unknown":
|
||||
return _t("car.why.solar_unknown")
|
||||
s = f"{carmode.solar_option(o, 'ev_start_min'):.0f}"
|
||||
if why == "start":
|
||||
return _t("car.why.solar_start", s=s)
|
||||
return _t("car.why.solar_paused", s=s)
|
||||
|
||||
|
||||
def car_block(c, now):
|
||||
"""The Car card for `/status`, or None when no charger is switched on (the
|
||||
page then draws nothing, as before)."""
|
||||
@@ -1434,46 +1290,19 @@ def car_block(c, now):
|
||||
good = c.car.last_good
|
||||
fresh = configured and c.car.fresh(mono)
|
||||
today = None
|
||||
mode = getattr(c, "car_mode", "off") if configured else "off"
|
||||
if configured and c.car.today_kwh is not None:
|
||||
sun = c.car_sun_kwh() if mode == "solar" else None
|
||||
today = (_t("car.today_sun", kwh=_kwh(c.car.today_kwh),
|
||||
sun=_kwh(sun)) if sun is not None
|
||||
else _t("car.today", kwh=_kwh(c.car.today_kwh)))
|
||||
why = _car_why(key, c, good)
|
||||
if mode == "manual" and key in ("charging", "waiting", "none", "full"):
|
||||
why = _car_manual_why(c, key)
|
||||
if mode == "solar" and key in ("charging", "waiting", "none", "full",
|
||||
"fault"):
|
||||
why = _car_solar_why(c, key)
|
||||
# EV-20: a car Solar holds at 0 A is waiting for the sun.
|
||||
if key == "waiting" and c.car_solar.plan.a <= 0.0:
|
||||
key = "paused"
|
||||
out = {
|
||||
today = _t("car.today", kwh=_kwh(c.car.today_kwh))
|
||||
return {
|
||||
"state": key or "wait",
|
||||
"chip": car_state_word(key),
|
||||
"kind": _CAR_KIND.get(key, "muted"),
|
||||
"big": _car_big(key, c, r if fresh else None, good),
|
||||
"today": today,
|
||||
"why": why,
|
||||
"mode": mode,
|
||||
"why": _car_why(key, c, good),
|
||||
"mode": "off",
|
||||
"power_w": (None if not fresh or r is None or r.power_w is None
|
||||
else round(float(r.power_w), 1)),
|
||||
}
|
||||
if configured:
|
||||
# EV-04: what the page can set. EV-20 adds Solar and where its spare
|
||||
# sun goes first (Night is a later card, so it is not offered).
|
||||
clamp = c.car_clamp()
|
||||
hi = int(clamp) if clamp is not None and clamp >= 6 else 6
|
||||
out["modes"] = list(carmode.MODES)
|
||||
out["first"] = {"value": getattr(c, "car_first",
|
||||
carmode.DEFAULT_FIRST),
|
||||
"choices": list(carmode.FIRSTS)}
|
||||
out["current"] = {"value": round(float(c.car_a)), "min": 6,
|
||||
"max": hi}
|
||||
out["phases"] = {"value": c.car_n,
|
||||
"choices": list(carmode.allowed_phases(c.o))}
|
||||
return out
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
@@ -1986,15 +1815,9 @@ def _samples() -> list:
|
||||
out += [("title", _t("car.state." + k)) for k in words["car"]["state"]]
|
||||
out += [("plan", _t("car.big." + k, t="09:12")) for k in
|
||||
words["car"]["big"]]
|
||||
out += [("plan", _t("car.why." + k, a="10", brand="Alfen", kw="8.6 kW",
|
||||
pct="20 %", phases=car_phases_word(3),
|
||||
real=car_phases_word(1), s="5"))
|
||||
out += [("plan", _t("car.why." + k, a="10", brand="Alfen"))
|
||||
for k in words["car"]["why"]]
|
||||
out += [("plan", _t("peak.car", kw="12.1 kW", car="11.0 kW",
|
||||
cov="8.6 kW")),
|
||||
("plan", _t("peak.set_by_car", t="19:45"))]
|
||||
out += [("plan", _t("car.today", kwh="14.2 kWh")),
|
||||
("plan", _t("car.today_sun", kwh="14.2 kWh", sun="3.1 kWh")),
|
||||
("plan", "11.0 kW · 16 A · " + _t("car.phase_many", n=3))]
|
||||
out += [("plan", line_no_trade(k)) for k in
|
||||
("not_covered", "no_prices", "peak", "not_firm", "not_worth",
|
||||
|
||||
@@ -42,7 +42,6 @@ from .arbiter import (
|
||||
P_SAFETY, SET, Claim, Resolution, actuator_for, pre_resolve, resolve,
|
||||
)
|
||||
from . import allocator
|
||||
from . import carmode
|
||||
from . import chargers
|
||||
from . import dayplan
|
||||
from . import modetrade
|
||||
@@ -84,9 +83,8 @@ from .maintenance import (
|
||||
CHARGE, DRAIN, HOLD, IDLE, POWER_MOVING, MaintConfig, Maintenance,
|
||||
FAIL_BACKOFF_DAYS, MaintResult, arbitrate as maint_arbitrate, site_zone,
|
||||
)
|
||||
from .mqtt import (CAR_CONFIGS_KEY, MODE_CONFIGS_KEY, MODE_LABELS, USE_OFF,
|
||||
USE_ON, MqttPublisher, announced_units, car_configs,
|
||||
mode_configs,
|
||||
from .mqtt import (MODE_CONFIGS_KEY, MODE_LABELS, USE_OFF, USE_ON,
|
||||
MqttPublisher, announced_units, mode_configs,
|
||||
optional_keys, parse_command, unit_slugs, unit_state_key)
|
||||
from . import peakguard
|
||||
from . import packshare
|
||||
@@ -115,7 +113,6 @@ from . import web
|
||||
# stays importable from `app.main`. DECISIONS/MAIN-orchestration.md.
|
||||
from .ctl_tasks import TasksMixin
|
||||
from .ctl_status import StatusMixin
|
||||
from .ctl_car import CarMixin
|
||||
from .ctl_alarms import (
|
||||
AlarmsMixin, HANDBACK_CYCLES, REANNOUNCE_S, ROLLING_BOUND_CYCLES,
|
||||
ROLLING_S, SHORT_CYCLES, SHORT_SPAN_S,
|
||||
@@ -186,7 +183,7 @@ def _load_latch(data, now=None):
|
||||
|
||||
|
||||
class Controller(InputsMixin, WritesMixin, TradeMixin, CycleMixin, AlarmsMixin,
|
||||
StatusMixin, TasksMixin, CarMixin):
|
||||
StatusMixin, TasksMixin):
|
||||
def __init__(self, opts: dict, hass: HomeAssistant, store, mqtt_pub, *, stop,
|
||||
peak_db_path: str = "/data/tariff.db",
|
||||
price_history_path: str = "/data/price_history.json",
|
||||
@@ -579,8 +576,6 @@ class Controller(InputsMixin, WritesMixin, TradeMixin, CycleMixin, AlarmsMixin,
|
||||
self._charger_probed = False
|
||||
self._car_down_logged = False
|
||||
self._car_announced = False
|
||||
# EV-04: Manual mode's state (runtime, in the store) and its writer.
|
||||
self.car_init(opts, store)
|
||||
self.house_profile = None
|
||||
if self.fc_entity is not None:
|
||||
self.house_profile = dayplan.HouseProfile(
|
||||
@@ -1040,17 +1035,7 @@ class Controller(InputsMixin, WritesMixin, TradeMixin, CycleMixin, AlarmsMixin,
|
||||
self.stopping = True
|
||||
_LOG.info(handback.log_shutdown(handback.current())
|
||||
or "shutting down - commanding 0 W on every inverter")
|
||||
# EV-20 (D3): Solar's fail state is 0 A, and it goes out BEFORE the
|
||||
# inverters go to 0 W, bounded by `ctl_car.RELEASE_WAIT_S`. Manual
|
||||
# keeps EV-04's order: the inverters first, then undo a phase change.
|
||||
solar = self.car_solar_engaged()
|
||||
if solar:
|
||||
await self.car_shutdown()
|
||||
await self.command_site_release()
|
||||
if solar:
|
||||
await self.car_release_notice()
|
||||
else:
|
||||
await self.car_shutdown() # EV-04: undo a phase change half way
|
||||
self.mqtt.close()
|
||||
|
||||
|
||||
@@ -1077,23 +1062,6 @@ def mode_announcement(opts, store) -> tuple:
|
||||
return modes, retract
|
||||
|
||||
|
||||
def car_announcement(opts, store) -> tuple:
|
||||
"""EV-04: `(car, retract)` for the MQTT publisher at start-up: the three car
|
||||
entities while a charger is switched on, and the config topics to remove
|
||||
when it is not (`mqtt.car_configs()`). A site that never had a charger gets
|
||||
nothing and its store is not written."""
|
||||
car = None
|
||||
if chargers.census_entity(opts):
|
||||
amps = chargers.max_a(opts)
|
||||
car = (chargers.EV_OPTION_DEFAULTS["ev_max_a"] if amps is None
|
||||
else amps, carmode.allowed_phases(opts))
|
||||
stored = store.data.get(CAR_CONFIGS_KEY)
|
||||
keep, retract = car_configs(car, stored)
|
||||
if keep and keep != stored:
|
||||
store.set(CAR_CONFIGS_KEY, keep)
|
||||
return car, retract
|
||||
|
||||
|
||||
def control_task_done(task: asyncio.Task, *, controller, stop: asyncio.Event,
|
||||
died: list) -> None:
|
||||
"""Done-callback on the control task: log its death now and wake amain()
|
||||
@@ -1263,7 +1231,6 @@ async def amain() -> None:
|
||||
# OPT-11 P2: each battery's switch and mode list, only while
|
||||
# battery modes are on (`mode_announcement()`).
|
||||
_modes, _retract = mode_announcement(opts, store)
|
||||
_car, _car_retract = car_announcement(opts, store)
|
||||
broker = await hass.mqtt_service()
|
||||
pub = MqttPublisher(
|
||||
broker.get("host") if broker else None,
|
||||
@@ -1283,8 +1250,6 @@ async def amain() -> None:
|
||||
units=roster_names(opts),
|
||||
modes=_modes,
|
||||
retract=_retract,
|
||||
car=_car,
|
||||
car_retract=_car_retract,
|
||||
)
|
||||
except Exception as err: # noqa: BLE001
|
||||
_LOG.warning("MQTT unavailable (%s) - continuing without status entities", err)
|
||||
|
||||
@@ -188,12 +188,6 @@ T_METER_FROZEN_NL = "Meter staat mogelijk vast"
|
||||
TITLE_NL = {T_LOOP_BOUND: T_LOOP_BOUND_NL, T_OUTPUT_CLAMP: T_OUTPUT_CLAMP_NL}
|
||||
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_RELEASE = "Car may still be charging"
|
||||
T_CAR_START = "Charger kept its current"
|
||||
T_CAR_START_NL = "Laadpaal hield haar stroom"
|
||||
T_CAR_RELEASE_NL = "Auto laadt mogelijk nog"
|
||||
T_NO_PRICES = "No prices"
|
||||
T_NO_PRICES_NL = "Prijzen ontbreken"
|
||||
|
||||
@@ -207,9 +201,6 @@ ID_METER_FROZEN = "goodwe_meter_frozen"
|
||||
ID_MAINT_FAILED = "goodwe_maint_failed_{slug}"
|
||||
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_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.
|
||||
OLD_FIXED_CARD_ID = "goodwe_fixed_tariff_unused"
|
||||
@@ -505,123 +496,6 @@ def row_charger_writer() -> str:
|
||||
"Iets anders wijzigt de laadpaal en deze add-on leest alleen.")
|
||||
|
||||
|
||||
def car_over(a_text) -> Notice:
|
||||
"""EV-04: a charge the user set takes the 15-minute period over the peak
|
||||
limit, and the batteries cannot hold it. Grey, once per charging session.
|
||||
Not an alarm: the car is never throttled, the user asked for it."""
|
||||
en = (f"You set {a_text} A, which takes this 15-minute period over the "
|
||||
"peak limit.")
|
||||
nl = f"U stelde {a_text} A in, wat dit kwartier boven de piekgrens brengt."
|
||||
return Notice(ID_CAR_OVER, INFO, T_CAR_OVER, en,
|
||||
body_nl=f"{T_CAR_OVER_NL}. {nl}")
|
||||
|
||||
|
||||
def row_car_over() -> str:
|
||||
"""EV-04: the grey row while the car charge you set is over the peak limit."""
|
||||
return Bi("The car charge you set takes this 15-minute period over the "
|
||||
"peak limit.",
|
||||
"De autolading die u instelde brengt dit kwartier boven de "
|
||||
"piekgrens.")
|
||||
|
||||
|
||||
def _solar_over(a_text):
|
||||
# D1's words, in the one sentence STYLE.md allows a grey note and row; the
|
||||
# card's Why has them as two (`car.why.solar_over`).
|
||||
return (f"Solar charges the car at {a_text} A, which sets the peak.",
|
||||
f"Zon laadt de auto met {a_text} A, wat de piek bepaalt.")
|
||||
|
||||
|
||||
def car_over_solar(a_text) -> Notice:
|
||||
"""EV-20 (D1): in Solar the car's charge takes the 15-minute period over
|
||||
the peak limit and the batteries cannot hold it. Grey, once per charging
|
||||
session, as Manual's; `a_text` is Solar's current at that moment."""
|
||||
en, nl = _solar_over(a_text)
|
||||
return Notice(ID_CAR_OVER, INFO, T_CAR_OVER, en,
|
||||
body_nl=f"{T_CAR_OVER_NL}. {nl}")
|
||||
|
||||
|
||||
def row_car_over_solar(a_text) -> str:
|
||||
"""EV-20 (D1): the grey row while Solar's charge is over the peak limit."""
|
||||
return Bi(*_solar_over(a_text))
|
||||
|
||||
|
||||
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
|
||||
0 A is taken."""
|
||||
en = ("The add-on stopped before the charger took 0 A, so check the "
|
||||
"charger.")
|
||||
nl = ("De add-on stopte voor de laadpaal 0 A overnam, dus controleer de "
|
||||
"laadpaal.")
|
||||
return Notice(ID_CAR_RELEASE, WARNING, T_CAR_RELEASE, en,
|
||||
body_nl=f"{T_CAR_RELEASE_NL}. {nl}")
|
||||
|
||||
|
||||
def car_start_current(a_text) -> Notice:
|
||||
"""EV-20 (C1): the add-on starts without writing (shadow mode, control
|
||||
stopped) and the charger still has a current the add-on set before the
|
||||
stop. Taken down once the charger shows 0 A."""
|
||||
return Notice(ID_CAR_START, WARNING, T_CAR_START,
|
||||
f"Charger still at {a_text} A from before the restart.",
|
||||
body_nl=f"{T_CAR_START_NL}. Laadpaal staat nog op {a_text} A "
|
||||
f"van voor de herstart.")
|
||||
|
||||
|
||||
def car_start_current_gone() -> Dismiss:
|
||||
"""EV-20 (C1): takes the 'Charger kept its current' notice down."""
|
||||
return Dismiss(ID_CAR_START)
|
||||
|
||||
|
||||
def car_release_gone() -> Dismiss:
|
||||
"""EV-20 (D3): takes the 'Car may still be charging' notice down."""
|
||||
return Dismiss(ID_CAR_RELEASE)
|
||||
|
||||
|
||||
def row_charger_other() -> str:
|
||||
"""EV-04: the grey row, in Manual, while something else sets the current."""
|
||||
return Bi("Something else changes the charger, so the add-on writes "
|
||||
"nothing until you change it.",
|
||||
"Iets anders wijzigt de laadpaal, dus de add-on schrijft niets "
|
||||
"tot u iets wijzigt.")
|
||||
|
||||
|
||||
def row_charger_other_solar() -> str:
|
||||
"""EV-20: the amber row, in Solar, while something else sets the current:
|
||||
Solar writes nothing until you press Solar or the read-back matches."""
|
||||
return Bi("Something else changes the charger, so Solar writes nothing "
|
||||
"until you press it.",
|
||||
"Iets anders wijzigt de laadpaal, dus Zon schrijft niets tot u "
|
||||
"erop drukt.")
|
||||
|
||||
|
||||
def row_charger_stuck() -> str:
|
||||
"""EV-04: the amber row when the charger's reading does not move."""
|
||||
return Bi("The charger reading may be stuck, so check the charger.",
|
||||
"De meting van de laadpaal staat mogelijk vast, dus controleer "
|
||||
"de laadpaal.")
|
||||
|
||||
|
||||
def row_charger_refused() -> str:
|
||||
"""EV-04: the amber row when the charger does not take the setting."""
|
||||
return Bi("The charger did not take the setting, so check the charger.",
|
||||
"De laadpaal nam de instelling niet over, dus controleer de "
|
||||
"laadpaal.")
|
||||
|
||||
|
||||
def row_charger_phases() -> str:
|
||||
"""EV-04: the amber row when the charger does not take the phases."""
|
||||
return Bi("The charger did not take the phases, so check the charger.",
|
||||
"De laadpaal nam de fasen niet over, dus controleer de "
|
||||
"laadpaal.")
|
||||
|
||||
|
||||
def row_charger_error(text) -> str:
|
||||
"""EV-04: the grey row while the charger reports an error. Writes go on."""
|
||||
t = " ".join(str(text or "").split())[:60]
|
||||
return Bi(f"The charger reports an error: {t}.",
|
||||
f"De laadpaal meldt een fout: {t}.")
|
||||
|
||||
|
||||
def row_charger_setup() -> str:
|
||||
"""EV-03: the amber row when the charger's entities are not found."""
|
||||
return Bi("The add-on cannot find the charger, so check its entity in "
|
||||
@@ -1549,10 +1423,6 @@ def why_waiting(missing_s) -> str:
|
||||
HINTS = {
|
||||
"control_started": "Control started",
|
||||
"control_stopped": "Control stopped",
|
||||
"car_mode": "Car mode set",
|
||||
"car_current": "Car current set",
|
||||
"car_phases": "Car phases set",
|
||||
"car_sun_first": "Where spare sun goes first set",
|
||||
"settings_saved": "Settings saved, they apply after a restart",
|
||||
"restart_requested": "Restart requested from the settings page",
|
||||
"setup_only": "In setup, nothing is sent to any inverter",
|
||||
@@ -1641,20 +1511,6 @@ def pack_refused(why: str) -> str:
|
||||
return PACK_REFUSED[why]
|
||||
|
||||
|
||||
# EV-04: why a car mode, current or phases change was refused (the page and
|
||||
# Home Assistant show it).
|
||||
CAR_REFUSED = {
|
||||
"off": "The car charger is not set up.",
|
||||
"value": "That choice is not possible for the car charger.",
|
||||
"phases": "The charger limit allows only one number of phases.",
|
||||
"topic": "That is not a car command.",
|
||||
}
|
||||
|
||||
|
||||
def car_refused(why: str) -> str:
|
||||
return CAR_REFUSED[why]
|
||||
|
||||
|
||||
# MAINT-11: why a start or stop of ONE battery's cycle was refused. `{unit}` is
|
||||
# the battery the sentence is about (for "busy", the one that is cycling). The
|
||||
# page shows the same sentences in Dutch from app/ui_text, keyed by the code.
|
||||
@@ -1847,14 +1703,6 @@ def status_samples() -> list:
|
||||
("row_no_prices", AMBER, row_no_prices()),
|
||||
("row_charger_unreach", AMBER, row_charger_unreach("09:12")),
|
||||
("row_charger_writer", GREEN, row_charger_writer()),
|
||||
("row_car_over", GREEN, row_car_over()),
|
||||
("row_charger_other", GREEN, row_charger_other()),
|
||||
("row_charger_other_solar", AMBER, row_charger_other_solar()),
|
||||
("row_car_over_solar", GREEN, row_car_over_solar("8")),
|
||||
("row_charger_error", GREEN, row_charger_error("Socket error")),
|
||||
("row_charger_stuck", AMBER, row_charger_stuck()),
|
||||
("row_charger_refused", AMBER, row_charger_refused()),
|
||||
("row_charger_phases", AMBER, row_charger_phases()),
|
||||
("row_charger_setup", AMBER, row_charger_setup()),
|
||||
]
|
||||
|
||||
@@ -1892,10 +1740,6 @@ def samples() -> list:
|
||||
no_prices(*_SINCE_OLDER),
|
||||
no_prices(),
|
||||
charger_unreachable("09:12"),
|
||||
car_over("16"),
|
||||
car_over_solar("8"),
|
||||
car_release_failed(),
|
||||
car_start_current("10"),
|
||||
]
|
||||
|
||||
|
||||
@@ -1962,11 +1806,6 @@ LABELS = {
|
||||
"ev_charger": "Charger",
|
||||
"ev_current_entity": "Current setting entity",
|
||||
"ev_max_a": "Charger limit",
|
||||
"ev_batt_cover": "Batteries help with the peak",
|
||||
"ev_mode_start": "Mode after a restart",
|
||||
"ev_margin_w": "Sun kept back",
|
||||
"ev_pause_min": "Pause after",
|
||||
"ev_start_min": "Start after",
|
||||
"ev_phases": "Phases",
|
||||
}
|
||||
|
||||
@@ -2051,11 +1890,6 @@ LABELS_NL = {
|
||||
"ev_charger": "Laadpaal",
|
||||
"ev_current_entity": "Entiteit van de laadstroom",
|
||||
"ev_max_a": "Laadpaalgrens",
|
||||
"ev_batt_cover": "Batterijen helpen met de piek",
|
||||
"ev_mode_start": "Modus na een herstart",
|
||||
"ev_margin_w": "Zon achtergehouden",
|
||||
"ev_pause_min": "Pauzeren na",
|
||||
"ev_start_min": "Starten na",
|
||||
"ev_phases": "Fasen",
|
||||
}
|
||||
# The inverter list shows two of them under a shorter name.
|
||||
|
||||
@@ -144,8 +144,6 @@ OPTIONAL_SENSORS = [
|
||||
("car_power", "goodwe_car_power", "Car power", "W", "power", "measurement", "mdi:car-electric"),
|
||||
("car_state", "goodwe_car_state", "Car state", None, None, None, "mdi:ev-station"),
|
||||
("car_today_kwh", "goodwe_car_today_kwh", "Car energy today", "kWh", "energy", "total_increasing", "mdi:ev-station"),
|
||||
# EV-20: what of today's charge came from the sun (Solar mode only).
|
||||
("car_today_solar_kwh", "goodwe_car_today_solar_kwh", "Car solar energy today", "kWh", "energy", "total_increasing", "mdi:solar-power"),
|
||||
]
|
||||
|
||||
# ⚠️ HA's OWN "this sensor has no value" PAYLOAD, and the one place this add-on
|
||||
@@ -202,8 +200,7 @@ def optional_keys(opts: dict) -> tuple:
|
||||
from . import chargers as _ch # EV-03: same reason
|
||||
out = ("pv",) if _pv.entities(opts) else ()
|
||||
if _ch.census_entity(opts):
|
||||
out += ("car_power", "car_state", "car_today_kwh",
|
||||
"car_today_solar_kwh")
|
||||
out += ("car_power", "car_state", "car_today_kwh")
|
||||
return out
|
||||
|
||||
|
||||
@@ -408,7 +405,7 @@ def _unit_places(names):
|
||||
yield slug, device, prefix
|
||||
|
||||
|
||||
def discovery_payloads(units=(), omit=(), include=(), modes=(), car=None) -> list:
|
||||
def discovery_payloads(units=(), omit=(), include=(), modes=()) -> list:
|
||||
"""Every `(topic, payload)` this add-on announces, in announcement order.
|
||||
|
||||
Split out of `_announce()` so that the acceptance criterion can be graded as
|
||||
@@ -424,8 +421,6 @@ def discovery_payloads(units=(), omit=(), include=(), modes=(), car=None) -> lis
|
||||
re-announces every entity on a live install).
|
||||
|
||||
`modes` (OPT-11 P2) is the battery modes offered, empty when they are off.
|
||||
`car` (EV-04) is None, or `(max_a, phases)`: the car's three command
|
||||
entities, announced after everything else so no existing row moves.
|
||||
"""
|
||||
omit = set(omit)
|
||||
include = [k for k in include if k not in omit]
|
||||
@@ -457,7 +452,6 @@ def discovery_payloads(units=(), omit=(), include=(), modes=(), car=None) -> lis
|
||||
DEVICE, unit, dev_class, state_class, icon)))
|
||||
# OPT-11 P2: last, and only when battery modes are on.
|
||||
out.extend(mode_payloads(units, modes))
|
||||
out.extend(car_payloads(car))
|
||||
return out
|
||||
|
||||
|
||||
@@ -524,114 +518,6 @@ def mode_payloads(units, modes) -> list:
|
||||
return out
|
||||
|
||||
|
||||
# --- EV-04: the car's mode, current and phases, as HA entities ----------------
|
||||
# Announced only with a charger switched on, after every other row. A command
|
||||
# goes through Controller.handle_action(); a retained one is dropped.
|
||||
CAR_MODE_LABELS = {"off": "Off", "manual": "Manual", # English, pinned
|
||||
"solar": "Solar"} # EV-20
|
||||
# EV-20: where spare sun goes first; mirrors carmode.FIRST_LABELS (this module
|
||||
# imports nothing from the package; test_ev20.py checks the two agree).
|
||||
CAR_FIRST_LABELS = {"batteries": "Batteries", "car": "Car"}
|
||||
CAR_MODES = tuple(CAR_MODE_LABELS)
|
||||
CAR_CONFIGS_KEY = "mqtt_car_configs"
|
||||
CAR_MIN_A = 6
|
||||
_CAR_CMD_RE = re.compile(rf"{BASE}/car/(mode|current|phases|sun_first)/set")
|
||||
_CAR_CONFIG_RE = re.compile(
|
||||
rf"homeassistant/(select|number)/{BASE}_car_(mode|current|phases|sun_first)"
|
||||
rf"/config")
|
||||
# (key, component, name, icon)
|
||||
CAR_ENTITIES = [
|
||||
("mode", "select", "Car mode", "mdi:car-electric"),
|
||||
("current", "number", "Car current", "mdi:current-ac"),
|
||||
("phases", "select", "Car phases", "mdi:sine-wave"),
|
||||
("sun_first", "select", "Car spare sun first", "mdi:solar-power"), # EV-20
|
||||
]
|
||||
|
||||
|
||||
def car_payloads(car) -> list:
|
||||
"""The `(topic, payload)` for `select.goodwe_car_mode`,
|
||||
`number.goodwe_car_current`, `select.goodwe_car_phases` and (EV-20)
|
||||
`select.goodwe_car_sun_first`. `car` is `(max_a, phases)`; empty when it
|
||||
is None."""
|
||||
if not car:
|
||||
return []
|
||||
max_a, phases = car
|
||||
out = []
|
||||
for key, component, name, icon in CAR_ENTITIES:
|
||||
unique_id = f"{BASE}_car_{key}"
|
||||
cfg = {
|
||||
"name": name,
|
||||
"object_id": f"goodwe_car_{key}",
|
||||
"unique_id": unique_id,
|
||||
"state_topic": f"{BASE}/car_{key}",
|
||||
"command_topic": f"{BASE}/car/{key}/set",
|
||||
}
|
||||
if key == "mode":
|
||||
cfg["options"] = list(CAR_MODE_LABELS.values())
|
||||
elif key == "phases":
|
||||
cfg["options"] = [str(n) for n in phases]
|
||||
elif key == "sun_first":
|
||||
cfg["options"] = list(CAR_FIRST_LABELS.values())
|
||||
else:
|
||||
cfg.update({"min": CAR_MIN_A, "max": int(max_a), "step": 1,
|
||||
"unit_of_measurement": "A", "device_class": "current",
|
||||
"mode": "box"})
|
||||
cfg.update({"retain": False, "availability_topic": AVAILABILITY,
|
||||
"device": DEVICE, "icon": icon})
|
||||
out.append((f"homeassistant/{component}/{unique_id}/config", cfg))
|
||||
return out
|
||||
|
||||
|
||||
def car_configs(car, stored) -> tuple:
|
||||
"""`(keep, retract)` at start-up, as `mode_configs()` does for the battery
|
||||
modes: turning the charger off removes exactly the entities announced
|
||||
before, and a site that never had one publishes nothing."""
|
||||
current = [t for t, _ in car_payloads(car)]
|
||||
old = [t for t in (stored if isinstance(stored, list) else [])
|
||||
if isinstance(t, str) and _CAR_CONFIG_RE.fullmatch(t)
|
||||
and t not in current]
|
||||
old = list(dict.fromkeys(old))
|
||||
return current + old, old
|
||||
|
||||
|
||||
def parse_car_command(topic, payload, retained):
|
||||
"""`(action, value, reject)` for one message on a car command topic.
|
||||
`action` is `car_mode`, `car_current`, `car_phases` or (EV-20)
|
||||
`car_sun_first`. A value that is
|
||||
none of the entity's own is None (the action then refuses it)."""
|
||||
m = _CAR_CMD_RE.fullmatch(topic) if isinstance(topic, str) else None
|
||||
if m is None:
|
||||
return None, None, "topic"
|
||||
key = m.group(1)
|
||||
action = f"car_{key}"
|
||||
if bool(retained):
|
||||
return action, None, "retained"
|
||||
if not isinstance(payload, (bytes, bytearray)):
|
||||
return action, None, "size"
|
||||
if MAX_COMMAND_BYTES < len(payload):
|
||||
return action, None, "size"
|
||||
try:
|
||||
text = bytes(payload).decode(encoding="utf-8").strip()
|
||||
except ValueError: # UnicodeDecodeError is one
|
||||
return action, None, "encoding"
|
||||
value = None
|
||||
if key == "mode":
|
||||
value = next((k for k, v in CAR_MODE_LABELS.items() if v == text),
|
||||
None)
|
||||
elif key == "phases":
|
||||
value = {"1": 1, "3": 3}.get(text)
|
||||
elif key == "sun_first":
|
||||
value = next((k for k, v in CAR_FIRST_LABELS.items() if v == text),
|
||||
None)
|
||||
else:
|
||||
try:
|
||||
f = float(text)
|
||||
value = f if f == f and abs(f) < 1000 else None
|
||||
except ValueError:
|
||||
value = None
|
||||
return action, value, None
|
||||
|
||||
|
||||
def mode_retractions(stored, current) -> list:
|
||||
"""Config topics announced before and not now: each gets an empty
|
||||
retained config, which removes the entity from HA. Anything in the store
|
||||
@@ -688,13 +574,11 @@ class MqttPublisher:
|
||||
# test fixture that builds one with __new__) behaves as before.
|
||||
modes = ()
|
||||
retract = ()
|
||||
car = None # EV-04: `(max_a, phases)` when the charger is on
|
||||
_loop = None
|
||||
_handler = None
|
||||
|
||||
def __init__(self, host, port, username=None, password=None, omit=(),
|
||||
units=(), include=(), modes=(), retract=(), car=None,
|
||||
car_retract=()):
|
||||
units=(), include=(), modes=(), retract=()):
|
||||
# `omit` drops sensor keys from discovery entirely. ⚠️ Announcing a
|
||||
# sensor that nothing will ever publish to is not harmless here:
|
||||
# p1_sample_age_s is a watchdog input, and an entity that exists but is
|
||||
@@ -713,8 +597,7 @@ class MqttPublisher:
|
||||
# OPT-11 P2: the modes offered (empty when battery modes are off), and
|
||||
# the mode config topics to remove (`mode_retractions()`).
|
||||
self.modes = tuple(modes)
|
||||
self.retract = [str(t) for t in retract] + [str(t) for t in car_retract]
|
||||
self.car = tuple(car) if car else None
|
||||
self.retract = [str(t) for t in retract]
|
||||
self.enabled = mqtt is not None and bool(host)
|
||||
self.client = None
|
||||
if not self.enabled:
|
||||
@@ -753,8 +636,7 @@ class MqttPublisher:
|
||||
# diffing what actually goes on the wire - and a payload built here
|
||||
# instead would be one this add-on publishes and no check has ever seen.
|
||||
for topic, cfg in discovery_payloads(self.units, self.omit,
|
||||
self.include, self.modes,
|
||||
self.car):
|
||||
self.include, self.modes):
|
||||
self.client.publish(topic, json.dumps(cfg), retain=True)
|
||||
for topic in self.retract:
|
||||
self.client.publish(topic, "", retain=True)
|
||||
@@ -765,8 +647,6 @@ class MqttPublisher:
|
||||
if self.modes:
|
||||
for key in ("mode", "use"):
|
||||
self.client.subscribe(f"{BASE}/unit/+/{key}/set")
|
||||
if self.car:
|
||||
self.client.subscribe(f"{BASE}/car/+/set")
|
||||
|
||||
def bind(self, loop, handler) -> None:
|
||||
"""OPT-11 P2: hand each command to `handler(topic, payload, retained)`,
|
||||
|
||||
@@ -158,54 +158,6 @@
|
||||
$("#car-today").textContent = c.today || "";
|
||||
$("#car-today").hidden = !c.today;
|
||||
$("#car-why").textContent = c.why;
|
||||
renderCarControls(c);
|
||||
}
|
||||
// EV-04: Off and Manual; EV-20: Solar and where its spare sun goes first.
|
||||
// The mode, the phases and the choice send at once; the current sends after
|
||||
// two seconds of rest. A slider being dragged is left alone.
|
||||
let carTouch = 0, carTimer = null, carBusy = false;
|
||||
async function carAct(what, value) {
|
||||
if (carBusy) return;
|
||||
carBusy = true;
|
||||
try {
|
||||
const r = await fetch("action", { method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: what, value: value }) });
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (!r.ok) toast(j.error || t("toast.failed"));
|
||||
} catch (e) { toast(t("toast.failed")); }
|
||||
finally { carBusy = false; }
|
||||
await refresh(true);
|
||||
}
|
||||
function renderCarControls(c) {
|
||||
const modes = c.modes || [];
|
||||
$("#car-mode").hidden = !modes.length;
|
||||
$("#car-mode").replaceChildren(...modes.map((m) => h("button", {
|
||||
type: "button", role: "radio", "aria-checked": String(c.mode === m),
|
||||
onclick: () => carAct("car_mode", m) }, t("car.mode_" + m))));
|
||||
$("#car-help").textContent = t("car.help_" + c.mode + ".description") || "";
|
||||
const sol = c.mode === "solar" && !!c.first;
|
||||
$("#car-solar").hidden = !sol;
|
||||
if (sol) {
|
||||
$("#car-first").replaceChildren(...c.first.choices.map((f) => h("button", {
|
||||
type: "button", role: "radio", "aria-checked": String(c.first.value === f),
|
||||
onclick: () => carAct("car_sun_first", f) }, t("car.first_" + f))));
|
||||
}
|
||||
const on = c.mode === "manual" && !!c.current;
|
||||
$("#car-manual").hidden = !on;
|
||||
if (!on) return;
|
||||
const a = $("#car-a");
|
||||
if (Date.now() - carTouch > 3000) {
|
||||
a.min = c.current.min; a.max = c.current.max; a.value = c.current.value;
|
||||
}
|
||||
$("#car-a-out").textContent = a.value + " A";
|
||||
a.oninput = () => {
|
||||
carTouch = Date.now(); $("#car-a-out").textContent = a.value + " A";
|
||||
clearTimeout(carTimer);
|
||||
carTimer = setTimeout(() => carAct("car_current", Number(a.value)), 2000);
|
||||
};
|
||||
$("#car-phases").replaceChildren(...c.phases.choices.map((n) => h("button", {
|
||||
type: "button", role: "radio", "aria-checked": String(c.phases.value === n),
|
||||
onclick: () => carAct("car_phases", n) }, t("car.phases_" + n))));
|
||||
}
|
||||
|
||||
/* ---------------- Home: today's plan ---------------- */
|
||||
@@ -336,8 +288,6 @@
|
||||
bar.className = pct >= 100 ? "bad" : pct >= 80 ? "warn" : "";
|
||||
$("#peak-meter").setAttribute("aria-label", t("peak.this_month") + " " + (m.pct == null ? "–" : Math.round(m.pct) + " %"));
|
||||
$("#peak-line").textContent = m.line;
|
||||
$("#peak-car").textContent = m.car_line || ""; $("#peak-car").hidden = !m.car_line;
|
||||
$("#peak-setby").textContent = m.set_by || ""; $("#peak-setby").hidden = !m.set_by;
|
||||
}
|
||||
function renderAttention() {
|
||||
const list = S.attention;
|
||||
|
||||
@@ -44,19 +44,8 @@
|
||||
<div class="car-big" id="car-big"></div>
|
||||
<div class="small muted" id="car-today"></div>
|
||||
<div class="small car-lab" data-t="car.mode"></div>
|
||||
<div class="seg" role="radiogroup" id="car-mode" data-t-label="car.mode"></div>
|
||||
<p class="tiny muted" style="margin:6px 0 0" id="car-help"></p>
|
||||
<div id="car-manual" hidden>
|
||||
<div class="small car-lab" data-t="car.current"></div>
|
||||
<div class="slider"><input type="range" id="car-a" min="6" max="16" step="1" data-t-label="car.current"><output class="small" id="car-a-out"></output></div>
|
||||
<div class="small car-lab" data-t="car.phases"></div>
|
||||
<div class="seg" role="radiogroup" id="car-phases" data-t-label="car.phases"></div>
|
||||
</div>
|
||||
<div id="car-solar" hidden>
|
||||
<div class="small car-lab" data-t="car.first"></div>
|
||||
<div class="seg" role="radiogroup" id="car-first" data-t-label="car.first"></div>
|
||||
<p class="tiny muted" style="margin:6px 0 0" data-t="car.first_help.description"></p>
|
||||
</div>
|
||||
<div class="seg" role="radiogroup" id="car-mode" data-t-label="car.mode"><button type="button" role="radio" aria-checked="true" data-t="car.mode_off"></button></div>
|
||||
<p class="tiny muted" style="margin:6px 0 0" data-t="car.help_off.description"></p>
|
||||
<div class="car-why small"><span class="muted" data-t="car.why"></span><span id="car-why"></span></div>
|
||||
</div>
|
||||
|
||||
@@ -82,8 +71,6 @@
|
||||
<div class="row spread small" id="peak-figures"><span><span data-t="peak.this_month"></span>: <strong id="peak-now"></strong></span><span class="muted"><span data-t="peak.limit"></span> <span id="peak-limit"></span></span></div>
|
||||
<div class="meter" id="peak-meter" role="img"><i style="width:0%"></i></div>
|
||||
<div class="tiny muted" id="peak-line"></div>
|
||||
<div class="tiny muted" id="peak-car" hidden></div>
|
||||
<div class="tiny muted" id="peak-setby" hidden></div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="c-attn">
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"inverters": {"name": "Inverters and batteries", "description": "The inverters the add-on controls, and your solar."},
|
||||
"tariff": {"name": "Tariff and prices", "description": "What you pay and are paid per kWh."},
|
||||
"safety": {"name": "Safety limits", "description": "The peak limit, starting and stopping, and the safety stops."},
|
||||
"car": {"name": "Car charger", "description": "Which charger the add-on drives, its limits and the mode defaults."},
|
||||
"car": {"name": "Car charger", "description": "Which charger the add-on reads, and its limits."},
|
||||
"maintenance": {"name": "Maintenance", "description": "The monthly battery cycle and the log."},
|
||||
"tuning": {"name": "Control tuning", "description": "For support only, because these were measured on real hardware."}
|
||||
},
|
||||
@@ -36,7 +36,6 @@
|
||||
"meter_source": {"off": "One grid power entity", "ha_dsmr": "Import and export entities", "mqtt_p1": "Meter over MQTT", "ha_signed": "One net power entity", "homewizard_local": "HomeWizard meter on the network"},
|
||||
"ev_charger": {"off": "None", "alfen_ha": "Alfen (Home Assistant integration)"},
|
||||
"ev_phases": {"1": "1 phase", "3": "3 phases", "auto": "1 and 3"},
|
||||
"ev_mode_start": {"keep": "Keep the last mode", "off": "Off"},
|
||||
"meter_phases": {"1": "1 phase", "3": "3 phases"},
|
||||
"shadow_mode": {"auto": "Automatic", "on": "Always on", "off": "Off"},
|
||||
"price_provider": {"generic_dayahead": "Day-ahead market price", "custom_formula": "Your own price formula", "manual_csv": "A price file", "price_service": "Your own price service"},
|
||||
@@ -91,7 +90,7 @@
|
||||
"loading": "Loading the forecast."
|
||||
},
|
||||
"peak": {"name": "Peak limit", "this_month": "This month's peak", "limit": "Limit", "none": "None recorded yet", "unreadable": "Cannot be read now"},
|
||||
"car": {"name": "Car", "mode": "Mode", "mode_off": "Off", "mode_manual": "Manual", "help_off": {"description": "The add-on leaves the charger alone."}, "help_manual": {"description": "Charges at the current you set, whatever the sun or the peak limit do."}, "current": "Current", "phases": "Phases", "phases_1": "1 phase", "phases_3": "3 phases", "why": "Why", "mode_solar": "Solar", "help_solar": {"description": "Charges only from spare sun and pauses when there is too little."}, "first": "Spare sun goes first to", "first_batteries": "Batteries", "first_car": "Car", "first_help": {"description": "Batteries: the car gets the sun the batteries cannot take."}},
|
||||
"car": {"name": "Car", "mode": "Mode", "mode_off": "Off", "help_off": {"description": "The add-on leaves the charger alone."}, "why": "Why"},
|
||||
"attention": {"name": "Needs attention", "nothing": "Nothing to look at", "to_look": "to look at", "details": "Details", "alarm": "Alarm", "warning": "Warning", "info": "Info"},
|
||||
"control": {"name": "Control", "stop": "Stop control", "start": "Start control", "maint_start": "Start a battery cycle now", "maint_abort": "Stop the battery cycle", "docs": "Add-on documentation", "more": "More actions"},
|
||||
"details": {"name": "Details for installers", "rows": "Status rows", "checks": "Checks", "event": "Last event"},
|
||||
@@ -302,12 +301,11 @@
|
||||
"warning": "See Needs attention below."
|
||||
},
|
||||
"car": {
|
||||
"state": {"charging": "Charging", "waiting": "Connected, waiting", "none": "No car connected", "full": "Car is full", "unreach": "Charger not reachable", "setup": "Charger not set up", "fault": "Charger fault", "wait": "No reading yet", "paused": "Waiting for sun"},
|
||||
"big": {"waiting": "Connected, not charging.", "none": "Nothing to charge.", "full": "The car is full.", "seen": "Last seen at {t}.", "no_reading": "No reading.", "setup": "Not set up.", "fault": "The charger reports a fault.", "wait": "No reading yet.", "paused": "Waiting for spare sun."},
|
||||
"state": {"charging": "Charging", "waiting": "Connected, waiting", "none": "No car connected", "full": "Car is full", "unreach": "Charger not reachable", "setup": "Charger not set up", "fault": "Charger fault", "wait": "No reading yet"},
|
||||
"big": {"waiting": "Connected, not charging.", "none": "Nothing to charge.", "full": "The car is full.", "seen": "Last seen at {t}.", "no_reading": "No reading.", "setup": "Not set up.", "fault": "The charger reports a fault.", "wait": "No reading yet."},
|
||||
"phase_one": "1 phase",
|
||||
"phase_many": "{n} phases",
|
||||
"today": "{kwh} charged today.",
|
||||
"today_sun": "{kwh} charged today, {sun} from the sun.",
|
||||
"why": {
|
||||
"charging": "The charger is charging the car. The add-on leaves it alone.",
|
||||
"waiting": "The car is connected and not charging. The add-on leaves the charger alone.",
|
||||
@@ -321,40 +319,9 @@
|
||||
"limit": "The charger limit is above what the charger allows. Lower it in Settings.",
|
||||
"name": "The current setting entity does not fit the charger. Check it in Settings.",
|
||||
"fault": "The charger reports a fault. Check it at the charger itself.",
|
||||
"wait": "Waiting for the first reading.",
|
||||
"manual_set": "You set {a} A, {phases}. The charger keeps it, whatever the peak limit does.",
|
||||
"manual_cover": "You set {a} A. The batteries give {kw} and help down to {pct}.",
|
||||
"manual_over": "You set {a} A. The batteries are at {pct}, so this charge sets the peak.",
|
||||
"manual_full": "You set {a} A. The batteries give all they can, so this charge sets the peak.",
|
||||
"manual_nocover": "You set {a} A. The guard ignores the car, so this charge can set the peak.",
|
||||
"manual_wait": "You set {a} A. It is set when a car is connected.",
|
||||
"manual_would": "Shadow mode: the add-on would set {a} A, {phases}.",
|
||||
"manual_stopped": "Control is stopped. The charger keeps its last setting.",
|
||||
"manual_shadow_over": "Shadow mode: the add-on would set {a} A, {phases}. This charge would set the peak.",
|
||||
"manual_phases": "You set {a} A, {phases}. The charger stays on {real}.",
|
||||
"manual_other": "Something else set the charger. The add-on leaves it until you change something.",
|
||||
"manual_blocked": "The phases change once per 10 minutes at most. This waits.",
|
||||
"solar_batt": "Batteries first. The car gets the {kw} of sun they cannot take.",
|
||||
"solar_car": "Car first: the car takes {kw} of spare sun. The batteries get the rest.",
|
||||
"solar_paused": "Too little spare sun for 6 A. The car starts after {s} minutes of enough sun.",
|
||||
"solar_hold": "Too little spare sun, so the car holds 6 A. It pauses after {s} minutes.",
|
||||
"solar_start": "There is enough spare sun now. The car starts after {s} minutes of it.",
|
||||
"solar_unknown": "The spare sun cannot be measured now. The car pauses if this lasts.",
|
||||
"solar_would": "Shadow mode: the add-on would keep the car paused.",
|
||||
"solar_stopped": "Control is stopped, so the add-on set the car to 0 A.",
|
||||
"solar_error": "The charger reports an error. The car is set to 0 A.",
|
||||
"solar_stuck": "The charger reading may be stuck. The car is set to 0 A.",
|
||||
"solar_other": "Something else changes the charger. Press Solar to give it back.",
|
||||
"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."
|
||||
"wait": "Waiting for the first reading."
|
||||
}
|
||||
},
|
||||
"peak": {
|
||||
"car": "This 15-minute period is heading for {kw}. The car takes {car} and the batteries cover {cov}.",
|
||||
"set_by_car": "Set by the car charge you asked for, at {t}."
|
||||
},
|
||||
"tile": {
|
||||
"not_set_up": "Not set up",
|
||||
"no_reading": "No reading",
|
||||
@@ -560,12 +527,6 @@
|
||||
"solar_forecast": "Solar forecast",
|
||||
"charger": "Charger not reachable",
|
||||
"charger_writer": "Something else changes the charger",
|
||||
"charger_other": "Something else changes the charger",
|
||||
"charger_phases": "Charger did not take phases",
|
||||
"charger_stuck": "Charger reading may be stuck",
|
||||
"charger_refused": "Charger did not take it",
|
||||
"charger_error": "The charger reports an error",
|
||||
"car_over": "Car over the peak limit",
|
||||
"charger_setup": "Charger not set up",
|
||||
"none": "Inverter connection"
|
||||
},
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"inverters": {"name": "Omvormers en batterijen", "description": "De omvormers die de add-on regelt, en uw zonnepanelen."},
|
||||
"tariff": {"name": "Tarief en prijzen", "description": "Wat u per kWh betaalt en terugkrijgt."},
|
||||
"safety": {"name": "Veiligheidsgrenzen", "description": "De piekgrens, starten en stoppen, en de veiligheidsstops."},
|
||||
"car": {"name": "Laadpaal", "description": "Welke laadpaal de add-on stuurt, haar grenzen en de standaardmodus."},
|
||||
"car": {"name": "Laadpaal", "description": "Welke laadpaal de add-on leest, en haar grenzen."},
|
||||
"maintenance": {"name": "Onderhoud", "description": "De maandelijkse batterijcyclus en het logboek."},
|
||||
"tuning": {"name": "Afstelling van de regeling", "description": "Alleen voor support, want deze zijn gemeten op echte hardware."}
|
||||
},
|
||||
@@ -36,7 +36,6 @@
|
||||
"meter_source": {"off": "Eén entiteit voor netvermogen", "ha_dsmr": "Entiteiten voor afname en injectie", "mqtt_p1": "Meter via MQTT", "ha_signed": "Eén entiteit voor nettovermogen", "homewizard_local": "HomeWizard-meter op het netwerk"},
|
||||
"ev_charger": {"off": "Geen", "alfen_ha": "Alfen (Home Assistant-integratie)"},
|
||||
"ev_phases": {"1": "1 fase", "3": "3 fasen", "auto": "1 en 3"},
|
||||
"ev_mode_start": {"keep": "Laatste modus houden", "off": "Uit"},
|
||||
"meter_phases": {"1": "1 fase", "3": "3 fasen"},
|
||||
"shadow_mode": {"auto": "Automatisch", "on": "Altijd aan", "off": "Uit"},
|
||||
"price_provider": {"generic_dayahead": "Day-aheadprijs van de markt", "custom_formula": "Uw eigen prijsformule", "manual_csv": "Een prijsbestand", "price_service": "Uw eigen prijsdienst"},
|
||||
@@ -88,7 +87,7 @@
|
||||
"loading": "De prognose wordt geladen."
|
||||
},
|
||||
"peak": {"name": "Piekgrens", "this_month": "Piek van deze maand", "limit": "Grens", "none": "Nog niets gemeten", "unreadable": "Nu niet leesbaar"},
|
||||
"car": {"name": "Auto", "mode": "Modus", "mode_off": "Uit", "mode_manual": "Handmatig", "help_off": {"description": "De add-on laat de laadpaal met rust."}, "help_manual": {"description": "Laadt met de stroom die u instelt, wat de zon of de piekgrens ook doen."}, "current": "Stroom", "phases": "Fasen", "phases_1": "1 fase", "phases_3": "3 fasen", "why": "Waarom", "mode_solar": "Zon", "help_solar": {"description": "Laadt alleen met zonne-overschot en pauzeert als er te weinig is."}, "first": "Zonne-overschot gaat eerst naar", "first_batteries": "Batterijen", "first_car": "Auto", "first_help": {"description": "Batterijen: de auto krijgt de zon die de batterijen niet kunnen opnemen."}},
|
||||
"car": {"name": "Auto", "mode": "Modus", "mode_off": "Uit", "help_off": {"description": "De add-on laat de laadpaal met rust."}, "why": "Waarom"},
|
||||
"attention": {"name": "Vraagt aandacht", "nothing": "Niets om na te kijken", "to_look": "na te kijken", "details": "Details", "alarm": "Alarm", "warning": "Waarschuwing", "info": "Info"},
|
||||
"control": {"name": "Regeling", "stop": "Regeling stoppen", "start": "Regeling starten", "maint_start": "Nu een batterijcyclus starten", "maint_abort": "Batterijcyclus stoppen", "docs": "Documentatie van de add-on", "more": "Meer acties"},
|
||||
"details": {"name": "Details voor installateurs", "rows": "Statusregels", "checks": "Controles", "event": "Laatste gebeurtenis"},
|
||||
@@ -256,12 +255,11 @@
|
||||
"pill": {"running": "Actief", "shadow": "Schaduwmodus", "stopped": "Gestopt", "alarm": "Heeft u nu nodig", "waiting": "Wacht op Home Assistant", "warning": "Actief, met een waarschuwing"},
|
||||
"banner_sub": {"running": "De batterijen volgen het plan hieronder.", "shadow": "De plannen hieronder tonen wat de add-on zou doen.", "stopped": "Start de regeling hieronder als u klaar bent.", "alarm": "Zie Vraagt aandacht hieronder voor wat u moet doen.", "waiting": "De regeling gaat vanzelf verder zodra Home Assistant antwoordt.", "warning": "Zie Vraagt aandacht hieronder."},
|
||||
"car": {
|
||||
"state": {"charging": "Laadt", "waiting": "Aangesloten, wacht", "none": "Geen auto aangesloten", "full": "Auto is vol", "unreach": "Laadpaal onbereikbaar", "setup": "Laadpaal niet ingesteld", "fault": "Laadpaalstoring", "wait": "Nog geen meting", "paused": "Wacht op zon"},
|
||||
"big": {"waiting": "Aangesloten, laadt niet.", "none": "Niets te laden.", "full": "De auto is vol.", "seen": "Laatst gezien om {t}.", "no_reading": "Geen meting.", "setup": "Niet ingesteld.", "fault": "De laadpaal meldt een storing.", "wait": "Nog geen meting.", "paused": "Wacht op zonne-overschot."},
|
||||
"state": {"charging": "Laadt", "waiting": "Aangesloten, wacht", "none": "Geen auto aangesloten", "full": "Auto is vol", "unreach": "Laadpaal onbereikbaar", "setup": "Laadpaal niet ingesteld", "fault": "Laadpaalstoring", "wait": "Nog geen meting"},
|
||||
"big": {"waiting": "Aangesloten, laadt niet.", "none": "Niets te laden.", "full": "De auto is vol.", "seen": "Laatst gezien om {t}.", "no_reading": "Geen meting.", "setup": "Niet ingesteld.", "fault": "De laadpaal meldt een storing.", "wait": "Nog geen meting."},
|
||||
"phase_one": "1 fase",
|
||||
"phase_many": "{n} fasen",
|
||||
"today": "Vandaag {kwh} geladen.",
|
||||
"today_sun": "Vandaag {kwh} geladen, {sun} van de zon.",
|
||||
"why": {
|
||||
"charging": "De laadpaal laadt de auto. De add-on laat haar met rust.",
|
||||
"waiting": "De auto is aangesloten en laadt niet. De add-on laat de laadpaal met rust.",
|
||||
@@ -275,40 +273,9 @@
|
||||
"limit": "De laadpaalgrens is hoger dan de laadpaal toestaat. Verlaag ze bij Instellingen.",
|
||||
"name": "De entiteit van de laadstroom past niet bij de laadpaal. Controleer ze bij Instellingen.",
|
||||
"fault": "De laadpaal meldt een storing. Controleer ze aan de laadpaal zelf.",
|
||||
"wait": "Wacht op de eerste meting.",
|
||||
"manual_set": "U stelde {a} A in, {phases}. De laadpaal houdt dit aan, wat de piekgrens ook doet.",
|
||||
"manual_cover": "U stelde {a} A in. De batterijen leveren {kw} en helpen tot {pct}.",
|
||||
"manual_over": "U stelde {a} A in. De batterijen staan op {pct}, dus deze lading bepaalt de piek.",
|
||||
"manual_full": "U stelde {a} A in. De batterijen geven alles, dus deze lading bepaalt de piek.",
|
||||
"manual_nocover": "U stelde {a} A in. De bewaking negeert de auto, dus deze lading kan de piek bepalen.",
|
||||
"manual_wait": "U stelde {a} A in. Het wordt ingesteld zodra een auto is aangesloten.",
|
||||
"manual_would": "Schaduwmodus: de add-on zou {a} A instellen, {phases}.",
|
||||
"manual_stopped": "De regeling is gestopt. De laadpaal houdt haar laatste instelling.",
|
||||
"manual_shadow_over": "Schaduwmodus: de add-on zou {a} A instellen, {phases}. Deze lading zou de piek bepalen.",
|
||||
"manual_phases": "U stelde {a} A in, {phases}. De laadpaal blijft op {real}.",
|
||||
"manual_other": "Iets anders heeft de laadpaal ingesteld. De add-on laat dit zo tot u iets wijzigt.",
|
||||
"manual_blocked": "De fasen wisselen hooguit eens per 10 minuten. Dit wacht.",
|
||||
"solar_batt": "Eerst de batterijen. De auto krijgt de {kw} zon die ze niet opnemen.",
|
||||
"solar_car": "Eerst de auto: die neemt {kw} zonne-overschot. De batterijen krijgen de rest.",
|
||||
"solar_paused": "Te weinig zonne-overschot voor 6 A. De auto start na {s} minuten genoeg zon.",
|
||||
"solar_hold": "Te weinig zonne-overschot, dus de auto houdt 6 A. Ze pauzeert na {s} minuten.",
|
||||
"solar_start": "Er is nu genoeg zonne-overschot. De auto start na {s} minuten daarvan.",
|
||||
"solar_unknown": "Het zonne-overschot is nu niet te meten. De auto pauzeert als dit duurt.",
|
||||
"solar_would": "Schaduwmodus: de add-on zou de auto gepauzeerd houden.",
|
||||
"solar_stopped": "De regeling is gestopt, dus de auto staat op 0 A.",
|
||||
"solar_error": "De laadpaal meldt een fout. De auto staat op 0 A.",
|
||||
"solar_stuck": "De meting van de laadpaal staat mogelijk vast. De auto staat op 0 A.",
|
||||
"solar_other": "Iets anders wijzigt de laadpaal. Druk op Zon om ze terug te geven.",
|
||||
"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."
|
||||
"wait": "Wacht op de eerste meting."
|
||||
}
|
||||
},
|
||||
"peak": {
|
||||
"car": "Dit kwartier gaat richting {kw}. De auto neemt {car} en de batterijen dekken {cov}.",
|
||||
"set_by_car": "Bepaald door de autolading die u vroeg, om {t}."
|
||||
},
|
||||
"tile": {"not_set_up": "Niet ingesteld", "no_reading": "Geen meting", "producing": "Produceert", "not_producing": "Produceert niet", "needs_solar": "Zonnemeting nodig", "not_adding_up": "Metingen kloppen niet", "using": "Verbruikt", "taking": "Neemt af van het net", "feeding": "Injecteert", "balanced": "In evenwicht", "giving": "Levert stroom", "charging": "Laadt", "resting": "Rust"},
|
||||
"now": {
|
||||
"no_reading": "Geen meting van deze batterij.",
|
||||
@@ -481,12 +448,6 @@
|
||||
"solar_forecast": "Zonneprognose",
|
||||
"charger": "Laadpaal onbereikbaar",
|
||||
"charger_writer": "Iets anders wijzigt de laadpaal",
|
||||
"charger_other": "Iets anders wijzigt de laadpaal",
|
||||
"charger_phases": "Laadpaal nam fasen niet over",
|
||||
"charger_stuck": "Laadpaalmeting staat mogelijk vast",
|
||||
"charger_refused": "Laadpaal nam het niet over",
|
||||
"charger_error": "De laadpaal meldt een fout",
|
||||
"car_over": "Auto boven de piekgrens",
|
||||
"charger_setup": "Laadpaal niet ingesteld",
|
||||
"none": "Verbinding met de omvormer"
|
||||
},
|
||||
|
||||
@@ -223,8 +223,8 @@ GROUPS = (
|
||||
Field("delivery_hold_s", LOCKED, "s", step=5, show=_SEVERAL),
|
||||
), collapsed=True),
|
||||
)),
|
||||
# EV-03: the car charger. Everything after the choice shows only while a
|
||||
# charger is switched on. EV-04 adds the battery switch and the restart mode.
|
||||
# EV-03: the car charger, read only. Everything after the choice shows
|
||||
# only while a charger is switched on.
|
||||
Group("car", (
|
||||
Part("", (
|
||||
Field("ev_charger", CHOICE, simple=True),
|
||||
@@ -232,11 +232,6 @@ GROUPS = (
|
||||
show=_CAR),
|
||||
Field("ev_max_a", SLIDER, "A", simple=True, show=_CAR),
|
||||
Field("ev_phases", SEGMENTED, simple=True, show=_CAR),
|
||||
Field("ev_batt_cover", TOGGLE, simple=True, show=_CAR),
|
||||
Field("ev_mode_start", SEGMENTED, simple=True, show=_CAR),
|
||||
Field("ev_margin_w", SLIDER, "W", step=10, show=_CAR),
|
||||
Field("ev_start_min", SLIDER, "min", show=_CAR),
|
||||
Field("ev_pause_min", SLIDER, "min", show=_CAR),
|
||||
)),
|
||||
)),
|
||||
Group("maintenance", (
|
||||
|
||||
@@ -677,19 +677,6 @@ def _charger_problems(opts: dict, writers: dict) -> list[str]:
|
||||
out.append(f"{S('ev_charger')} is {messages.shown(raw)}. Choose "
|
||||
f"{', '.join(chargers.SELECTABLE)}.")
|
||||
return out
|
||||
# EV-20: Solar's sun kept back and its two dwells, each in its range (as
|
||||
# config.yaml's schema holds them, with or without a charger).
|
||||
for key, (lo, hi) in chargers.SOLAR_RANGES.items():
|
||||
raw = opts.get(key, chargers.EV_OPTION_DEFAULTS[key])
|
||||
try:
|
||||
v = float(raw)
|
||||
ok = not isinstance(raw, bool) and v == v and v == int(v) \
|
||||
and lo <= v <= hi
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
ok = False
|
||||
if not ok:
|
||||
out.append(f"{S(key)} is {messages.shown(raw)}. Set it from {lo} "
|
||||
f"to {hi}.")
|
||||
if chargers.mode_of(opts) == chargers.OFF:
|
||||
return out
|
||||
ph = opts.get("ev_phases", chargers.EV_OPTION_DEFAULTS["ev_phases"])
|
||||
|
||||
@@ -62,7 +62,6 @@ _LOG = logging.getLogger("goodwe.web")
|
||||
|
||||
# OPT-11: the per-battery actions, which name a battery and a value.
|
||||
PACK_ACTIONS = ("pack_use", "pack_mode", "pack_sell")
|
||||
CAR_ACTIONS = ("car_mode", "car_current", "car_phases", "car_sun_first")
|
||||
# MAINT-11: start or stop one battery's maintenance cycle (the unit is optional).
|
||||
MAINT_ACTIONS = ("maint_start", "maint_abort")
|
||||
|
||||
@@ -177,15 +176,6 @@ def build_app(controller, selfcfg=None) -> web.Application:
|
||||
return web.json_response({"ok": False,
|
||||
"error": result["error"]},
|
||||
status=400)
|
||||
elif what in CAR_ACTIONS:
|
||||
# EV-04: the car's mode, current or phases. Store state, applied by
|
||||
# the writer's next step; nothing is written to the charger here.
|
||||
result = await controller.handle_action(
|
||||
what, value=body.get("value"))
|
||||
if isinstance(result, dict) and "error" in result:
|
||||
return web.json_response({"ok": False,
|
||||
"error": result["error"]},
|
||||
status=400)
|
||||
elif what in MAINT_ACTIONS and body.get("unit") is not None:
|
||||
# MAINT-11: one battery's cycle. No unit = the old bare call below.
|
||||
result = await controller.handle_action(what, unit=body["unit"])
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
name: GoodWe RS485 Controller
|
||||
version: "0.24.0"
|
||||
version: "0.23.0"
|
||||
slug: goodwe_controller
|
||||
description: >-
|
||||
Drives a GoodWe ES/BP battery inverter over its RS485 EMS port by sending it a
|
||||
@@ -873,25 +873,16 @@ options:
|
||||
shadow_mode: "auto"
|
||||
|
||||
# ==========================================================================
|
||||
# CAR CHARGER (EV-03 reads it, EV-04 adds Manual, EV-20 Solar)
|
||||
# CAR CHARGER - read only (EV-03)
|
||||
# ==========================================================================
|
||||
# `off` is the shipped value and means NO CHANGE AT ALL: nothing is read,
|
||||
# shown or announced, and the House tile and the house profile are as before.
|
||||
# `alfen_ha` drives the charger through its Home Assistant integration. The
|
||||
# mode (Off, Manual or Solar), the current, the phases and where spare sun
|
||||
# goes first are runtime state in the store, not options. `ev_batt_cover`:
|
||||
# the batteries help with the peak while the car charges. `ev_mode_start`:
|
||||
# the mode after a restart. Solar: `ev_margin_w` sun kept back, and the car
|
||||
# starts after `ev_start_min` of enough sun and pauses after `ev_pause_min`.
|
||||
# `alfen_ha` reads the charger through its Home Assistant integration. THIS
|
||||
# VERSION NEVER WRITES TO THE CHARGER; later cards add the modes.
|
||||
ev_charger: "off"
|
||||
ev_current_entity: ""
|
||||
ev_max_a: 16
|
||||
ev_phases: "auto"
|
||||
ev_batt_cover: true
|
||||
ev_mode_start: "keep"
|
||||
ev_margin_w: 100
|
||||
ev_start_min: 2
|
||||
ev_pause_min: 5
|
||||
|
||||
# ==========================================================================
|
||||
# ADVANCED - the control law and diagnostics
|
||||
@@ -1271,7 +1262,7 @@ schema:
|
||||
shadow_mode: list(auto|on|off)
|
||||
|
||||
# ==========================================================================
|
||||
# CAR CHARGER (EV-03 reads it, EV-04 adds Manual, EV-20 Solar)
|
||||
# CAR CHARGER - read only (EV-03)
|
||||
# ==========================================================================
|
||||
# `ev_current_entity` is the charger's current setpoint; the other entities
|
||||
# are found from its name. `ev_max_a` may not exceed the charger's own station
|
||||
@@ -1280,11 +1271,6 @@ schema:
|
||||
ev_current_entity: str?
|
||||
ev_max_a: int(6,40)
|
||||
ev_phases: list(1|3|auto)
|
||||
ev_batt_cover: bool
|
||||
ev_mode_start: list(keep|off)
|
||||
ev_margin_w: int(0,1000)
|
||||
ev_start_min: int(1,30)
|
||||
ev_pause_min: int(1,30)
|
||||
|
||||
# ==========================================================================
|
||||
# ADVANCED - the control law and diagnostics
|
||||
|
||||
@@ -185,9 +185,7 @@ def callers_of_writes():
|
||||
out = []
|
||||
for root, _d, files in os.walk(os.path.join(HERE, "app")):
|
||||
for f in files:
|
||||
# EV-04: carmode.py is the one place that writes, and only in
|
||||
# Manual (test_ev04.py grades it); chargers.py is the seam.
|
||||
if not f.endswith(".py") or f in ("chargers.py", "carmode.py"):
|
||||
if not f.endswith(".py") or f == "chargers.py":
|
||||
continue
|
||||
tree = ast.parse(io.open(os.path.join(root, f),
|
||||
encoding="utf-8").read())
|
||||
@@ -201,17 +199,15 @@ def callers_of_writes():
|
||||
return out
|
||||
|
||||
|
||||
check(f"nothing in the add-on but carmode.py calls write_current, "
|
||||
f"write_phases or the charger's release ({callers_of_writes()})",
|
||||
not callers_of_writes())
|
||||
check(f"nothing in the add-on calls write_current, write_phases or the "
|
||||
f"charger's release ({callers_of_writes()})", not callers_of_writes())
|
||||
check("the seam does define them (the next cards use them)",
|
||||
all(hasattr(CH.ChargerDriver, m) for m in
|
||||
("write_current", "write_phases", "release")))
|
||||
_ha = FakeHa(SimCharger())
|
||||
_took99 = asyncio.run(CH.AlfenHaDriver(SET, 16).bind(_ha).write_current(99))
|
||||
check("the Alfen driver never sends 99 A against a 16 A limit (EV-04: a value "
|
||||
"above the clamp is a software fault, not sent)",
|
||||
_ha.sets == [] and _took99 is False)
|
||||
asyncio.run(CH.AlfenHaDriver(SET, 16).bind(_ha).write_current(99))
|
||||
check("the Alfen driver's write (a later card's) is clamped to the charger "
|
||||
"limit, 16 A and not 99", _ha.sets == [(SET, 16.0)])
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("\n2. THE SEAM")
|
||||
@@ -905,18 +901,16 @@ check("it stays for an hour and then goes",
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("\n9. THE MQTT SENSORS")
|
||||
# --------------------------------------------------------------------------- #
|
||||
check("the car sensors (EV-20: four, with today's solar kWh) are announced "
|
||||
"only with a charger on",
|
||||
check("the three car sensors are announced only with a charger on",
|
||||
mqtt.optional_keys(CAR) == ("pv", "car_power", "car_state",
|
||||
"car_today_kwh", "car_today_solar_kwh")
|
||||
"car_today_kwh")
|
||||
and mqtt.optional_keys(BASE) == ("pv",))
|
||||
pl = dict(mqtt.discovery_payloads(include=mqtt.optional_keys(CAR)))
|
||||
names = sorted(k for k in pl if "_car_" in k)
|
||||
check(f"discovery announces the sensors goodwe_car_power, goodwe_car_state, "
|
||||
f"goodwe_car_today_kwh and (EV-20) goodwe_car_today_solar_kwh ({names})",
|
||||
check(f"discovery announces three sensors, goodwe_car_power, "
|
||||
f"goodwe_car_state and goodwe_car_today_kwh ({names})",
|
||||
[pl[k]["object_id"] for k in names] == [
|
||||
"goodwe_car_power", "goodwe_car_state", "goodwe_car_today_kwh",
|
||||
"goodwe_car_today_solar_kwh"]
|
||||
"goodwe_car_power", "goodwe_car_state", "goodwe_car_today_kwh"]
|
||||
and all(k.startswith("homeassistant/sensor/") for k in names))
|
||||
check("...and no command entity (no select, number or switch for the car)",
|
||||
not [k for k in pl if "car" in k and not k.startswith(
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,562 +0,0 @@
|
||||
"""EV-10, EV-11, EV-12: three rig findings of EV-04's test (F-1, F-2, F-3).
|
||||
`python3 -B test_ev10.py`
|
||||
|
||||
1. EV-10: the car alone takes the batteries to the peak reserve while the period
|
||||
is still projected UNDER the aim: no alarm, one grey notice. A stuck car
|
||||
figure with a house overload, and a house-only drain, still alarm. Mutant:
|
||||
an uncorroborated car figure in the "period without the car" test.
|
||||
2. EV-11: the grey row and the Car Why do not flicker while the car keeps the
|
||||
period over the limit; a real end clears them after OVER_OFF_HOLD_S. The
|
||||
alarm decision (`car_explains`) has no hold.
|
||||
3. EV-12: the add-on's own write, and Off within 15 s of it, is never "another
|
||||
writer"; a real outside change afterwards still shows the row.
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import dataclasses
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import ctl_car, homeview, chargers as CH # noqa: E402
|
||||
from app.main import Controller # noqa: E402
|
||||
from app import freshness # noqa: E402
|
||||
from chargersim import FakeHa, SimCharger # noqa: E402
|
||||
import ev04_peak as P # noqa: E402
|
||||
import safety81_sim as s81 # noqa: E402
|
||||
import opt11_identity as rig # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
class _Log(logging.Handler):
|
||||
def __init__(self):
|
||||
super().__init__(logging.DEBUG)
|
||||
self.rec = []
|
||||
|
||||
def emit(self, r):
|
||||
self.rec.append((r.levelname, r.getMessage()))
|
||||
|
||||
|
||||
LOG = _Log()
|
||||
_lg = logging.getLogger("goodwe")
|
||||
_lg.addHandler(LOG)
|
||||
_lg.setLevel(logging.DEBUG)
|
||||
_lg.propagate = False
|
||||
|
||||
# =========================================================================== #
|
||||
print("1. EV-10: THE CAR ALONE TAKES THE BATTERIES TO THE RESERVE (F-1)")
|
||||
# =========================================================================== #
|
||||
CAP = 4500.0 # the aim is 4450 W (50 W margin)
|
||||
HOUSE = 1100.0
|
||||
|
||||
|
||||
def at_reserve(plant, c):
|
||||
"""The batteries reach the peak reserve late in the period, and the house
|
||||
eases a little: the period is still projected UNDER the aim."""
|
||||
plant.soc = 19.0
|
||||
plant.load = lambda at: 780.0 + plant.ch.power_w
|
||||
|
||||
|
||||
def alarms(r):
|
||||
return P.ids(r, *P.ALARMS)
|
||||
|
||||
|
||||
UNDER = [] # (second, projected W, aim W) while floor-limited
|
||||
|
||||
|
||||
def watch(first, fn):
|
||||
"""Events for seconds 840 to 894: `fn` at `first`, and a note of every
|
||||
cycle in which the guard is floor-limited."""
|
||||
def note(plant, c):
|
||||
g = c.peak_guard
|
||||
if g is not None and g.floor_limited:
|
||||
UNDER.append((plant.t, g.projected_w, g.target_w))
|
||||
ev = {t: note for t in range(first - 10, 895)}
|
||||
ev[first] = lambda plant, c: (fn(plant, c), note(plant, c))
|
||||
return ev
|
||||
|
||||
|
||||
LOG.rec.clear()
|
||||
r10 = P.drive(s81.constant(HOUSE), dur=895, rating=12000.0, soc=60.0,
|
||||
cap=CAP, phases=1, events=watch(850, at_reserve))
|
||||
ERR10 = [m for lv, m in LOG.rec if lv in ("ERROR", "WARNING")]
|
||||
check("PRECONDITION: the guard was floor-limited with the projection UNDER "
|
||||
"the aim (the rig's 5888 W against 6000 W)",
|
||||
any(p < a for _t, p, a in UNDER))
|
||||
check("the car alone: no 'Load too high', no 'Battery stopped limiting the "
|
||||
"peak'", alarms(r10) == [])
|
||||
rows10 = {x["id"]: x for x in r10["c"].checks()}
|
||||
check("...no red row; the grey 'Car over the peak limit' row says it",
|
||||
rows10["peak_guard"]["ok"] is True
|
||||
and not [x for x in r10["c"].checks()
|
||||
if x["ok"] is False and not x["warn"]]
|
||||
and rows10.get("car_over", {}).get("ok") is True)
|
||||
check("...one grey notice for the session", len(P.ids(r10, P.OVER)) == 1)
|
||||
check("...no ERROR (or WARNING) line was logged for it", ERR10 == [])
|
||||
|
||||
|
||||
def house_stuck(plant, c):
|
||||
at_reserve(plant, c)
|
||||
plant.ch.freeze() # the reading stops moving
|
||||
plant.ch.unplug() # the car really goes
|
||||
plant.load = lambda at: 9000.0 + plant.ch.power_w
|
||||
asyncio.get_event_loop().create_task(c.handle_action("car_current",
|
||||
value=10))
|
||||
|
||||
|
||||
r10s = P.drive(s81.constant(HOUSE), dur=895, rating=12000.0, soc=60.0,
|
||||
cap=CAP, phases=1, events=watch(850, house_stuck))
|
||||
check("a stuck car figure and a house overload at the reserve: the normal "
|
||||
"alarm still fires",
|
||||
[n for _t, n in alarms(r10s)]
|
||||
and all(n in P.ALARMS for _t, n in alarms(r10s)))
|
||||
|
||||
|
||||
def house_drain(plant, c):
|
||||
plant.soc = 19.0
|
||||
plant.load = lambda at: 12000.0 + plant.ch.power_w
|
||||
|
||||
|
||||
r10h = P.drive(s81.constant(HOUSE), dur=895, rating=12000.0, soc=60.0,
|
||||
cap=CAP, phases=1, user_a=6, setpoint=6,
|
||||
events=watch(600, house_drain))
|
||||
check("a house-only drain to the reserve with the car charging little: the "
|
||||
"normal alarm still fires",
|
||||
alarms(r10h) != [] and not r10h["c"].car_explains)
|
||||
|
||||
|
||||
|
||||
def plug_late(plant, c):
|
||||
plant.ch.plug_in()
|
||||
|
||||
|
||||
def house_reserve(plant, c):
|
||||
plant.soc = 19.0
|
||||
plant.load = lambda at: 3075.0 + plant.ch.power_w
|
||||
|
||||
|
||||
def swapped_events():
|
||||
ev = watch(850, house_reserve)
|
||||
ev[800] = plug_late
|
||||
return ev
|
||||
|
||||
|
||||
def swapped(mode):
|
||||
return P.drive(s81.constant(6000.0), dur=895, rating=12000.0, soc=60.0,
|
||||
cap=CAP, phases=1, user_a=6, setpoint=6, mode=mode,
|
||||
plug=False, events=swapped_events())
|
||||
|
||||
|
||||
r10x = swapped("manual")
|
||||
r10xo = swapped("off")
|
||||
check("PRECONDITION (review): a 6 kW HOUSE drains the batteries, the car "
|
||||
"plugs in late (a small share); the projection is under the aim at the "
|
||||
"reserve, and Off raises the alarm", alarms(r10xo) != []
|
||||
and any(p < a for _t, p, a in UNDER))
|
||||
check("the house drains the batteries and a small car is plugged in: the "
|
||||
"normal alarm still fires in Manual", alarms(r10x) != [])
|
||||
|
||||
r10off = P.drive(s81.constant(HOUSE), dur=895, rating=12000.0, soc=60.0,
|
||||
cap=CAP, phases=1, mode="off", events=watch(850, at_reserve))
|
||||
check("PRECONDITION: Off, the same case raises the normal alarm (the false "
|
||||
"alarm Manual must not make)", alarms(r10off) != [])
|
||||
|
||||
|
||||
# a direct unit of the rule: the car's average, the period without it
|
||||
class _Car(ctl_car.CarMixin):
|
||||
def __init__(self, cover=True, w=3700.0):
|
||||
self.o = {"ev_batt_cover": cover}
|
||||
self.w = w
|
||||
self._now = 0.0
|
||||
self.site_batt_w, self.site_rating_w = 300.0, 5000.0
|
||||
self.car_init({}, type("S", (), {"data": {}, "set": lambda s, k, v: 0})())
|
||||
|
||||
def car_now(self):
|
||||
return self._now
|
||||
|
||||
def car_alarm_w(self):
|
||||
return self.w
|
||||
|
||||
class car: # noqa: N801
|
||||
@staticmethod
|
||||
def status(*_a):
|
||||
return "charging"
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class _Proj:
|
||||
projected_w: float
|
||||
elapsed_s: float = 850.0
|
||||
held_w: float = 0.0
|
||||
block_start: object = datetime(2026, 11, 16, 20, 0, tzinfo=timezone.utc)
|
||||
|
||||
def __post_init__(self):
|
||||
self.held_w = self.projected_w
|
||||
|
||||
|
||||
class _G:
|
||||
def __init__(self, floor=True, sat=False, within_aim=False):
|
||||
self.floor_limited, self.saturated = floor, sat
|
||||
self.floor_w, self.able_w, self.ceiling_w = 0.0, None, 4500.0
|
||||
self.engaged, self.blind, self.wanted_w = True, None, 300.0
|
||||
self.within_aim = within_aim
|
||||
|
||||
|
||||
def explains(proj_w, car_w, *, floor=True, cover=True, car_so_far_w=None,
|
||||
within_aim=False, earlier=(), block=0, c=None, at=0.0):
|
||||
"""One cycle of `car_cycle` on a stub; `earlier` are projections of
|
||||
cycles before it in the same quarter (they latch SAFETY-126's test)."""
|
||||
c = c or _Car(cover, car_w)
|
||||
c.w = car_w
|
||||
for k, e in enumerate(tuple(earlier) + (proj_w,)):
|
||||
p = _Proj(e)
|
||||
p.block_start = p.block_start + timedelta(minutes=15 * block)
|
||||
c._now = at - len(earlier) + k
|
||||
c._carq = {"key": p.block_start,
|
||||
"ws": ((car_w or 0.0) if car_so_far_w is None else car_so_far_w)
|
||||
* p.elapsed_s, "mono": c._now}
|
||||
c.car_cycle(p, _G(floor, within_aim=within_aim), 4450.0, None)
|
||||
return c.car_explains
|
||||
|
||||
|
||||
check("rule: the alarm's test is true with the car (4468 W, the batteries "
|
||||
"at 0 W land 4485 W) and false without it (768 W): the car explains it, "
|
||||
"with the projection under the aim", explains(4468.0, 3700.0))
|
||||
check("rule: under the aim, the quarter's test latched by the car's share "
|
||||
"(4600 W earlier), the car explains the alarm (the positive under-aim "
|
||||
"case; a single 4300 W cycle has no landing miss to explain, so it "
|
||||
"needs the earlier cycle)", explains(4300.0, 3700.0, earlier=(4600.0,)))
|
||||
check("rule: where the alarm would not fire anyway nothing is explained",
|
||||
not explains(4300.0, 3700.0, within_aim=True))
|
||||
check("rule: without the car it is still over the aim: the car does not "
|
||||
"explain it", not explains(9000.0, 3700.0))
|
||||
check("rule: no car power, no explanation", not explains(4300.0, 0.0))
|
||||
check("rule: ...also when the test was latched earlier in the quarter",
|
||||
not explains(4300.0, 0.0, earlier=(4600.0,))
|
||||
and not explains(9000.0, 0.0))
|
||||
check("rule: an untrusted car figure (None) explains nothing",
|
||||
not explains(4300.0, None, earlier=(4600.0,)))
|
||||
# the latches: per quarter, and independent of the cover option
|
||||
c4 = _Car(True, 3700.0)
|
||||
explains(9000.0, 3700.0, c=c4, block=0) # the house needs it: latched
|
||||
check("latch: in the same quarter the house need stays latched, so the car "
|
||||
"does not explain", not explains(4300.0, 3700.0, c=c4, block=0, at=10.0))
|
||||
check("latch: a new quarter starts clean: the car alone explains it again",
|
||||
explains(4300.0, 3700.0, c=c4, block=1, at=1000.0,
|
||||
earlier=(4600.0,)))
|
||||
c5 = _Car(False, 3700.0) # cover OFF
|
||||
explains(9000.0, 3700.0, c=c5, block=0) # the house needs it
|
||||
c5.o["ev_batt_cover"] = True # ... and the option flips
|
||||
check("latch: the option flipping to ON does not lose a house need seen "
|
||||
"while it was off", not explains(4300.0, 3700.0, c=c5, block=0, at=10.0))
|
||||
c6 = _Car(True, 3700.0)
|
||||
explains(9000.0, 3700.0, c=c6, block=0)
|
||||
c6.o["ev_batt_cover"] = False
|
||||
explains(4300.0, 3700.0, c=c6, block=0, at=10.0)
|
||||
c6.o["ev_batt_cover"] = True
|
||||
check("latch: ... nor does flipping it off and on again",
|
||||
not explains(4300.0, 3700.0, c=c6, block=0, at=20.0))
|
||||
|
||||
check("rule: the guard is not floor-limited or saturated: nothing to explain",
|
||||
not explains(4300.0, 3700.0, floor=False))
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n2. EV-11: THE 'CAR OVER THE PEAK LIMIT' ROW DOES NOT FLICKER (F-2)")
|
||||
# =========================================================================== #
|
||||
# The cause (rig p7off 21:18 to 21:45, plant.csv): after 21:15 the car's own
|
||||
# quarter (14.0 kW) was the month peak, so the aim was that quarter's average
|
||||
# and the grid of the next ones (14.04 kW, +-40 W of noise) sat ON it. The
|
||||
# projection crossed the aim every few seconds, `ex > 0` came and went, and
|
||||
# `car_over` followed it with no hold on the way off.
|
||||
|
||||
|
||||
def over_run(c, secs, proj_of, w_of=lambda t: 11000.0, t0=0.0, target=14000.0,
|
||||
cover=False):
|
||||
"""Run `car_cycle` once a second; returns (car_over, car_explains) per second."""
|
||||
out = []
|
||||
for k in range(secs):
|
||||
t = t0 + k
|
||||
c._now = t
|
||||
c.w = w_of(t)
|
||||
p = _Proj(proj_of(t), elapsed_s=300.0 + (t % 400))
|
||||
c._carq = {"key": p.block_start, "ws": 11000.0 * p.elapsed_s,
|
||||
"mono": t}
|
||||
c.car_cycle(p, _G(True), target, None)
|
||||
out.append((c.car_over, c.car_explains))
|
||||
return out
|
||||
|
||||
|
||||
def noisy(t):
|
||||
"""The projection straddles the aim: +-40 W, a new value every 7 s."""
|
||||
return 14000.0 + (40.0 if int(t // 7) % 2 else -40.0) * (1 + (int(t) % 3))
|
||||
|
||||
|
||||
c11 = _Car(cover=False)
|
||||
o11 = over_run(c11, 1200, noisy)
|
||||
flips = sum(1 for a, b in zip(o11, o11[1:]) if a[0] != b[0])
|
||||
check("while the car keeps the period at the limit the row stays on: one "
|
||||
"switch on in 20 minutes, none off", flips == 1 and len(o11) == 1200 and o11[-1][0] is True)
|
||||
check("it turns on after the existing 10 s hold, not later than the first "
|
||||
"10 s the condition has stood (a gap does not restart the count)",
|
||||
next((i for i, x in enumerate(o11) if x[0]), 10**6) <= 25)
|
||||
|
||||
# the condition on its own, for the PRECONDITION: the same input flips
|
||||
c11o = _Car(cover=False)
|
||||
raw = []
|
||||
for k in range(1200):
|
||||
c11o._now = float(k)
|
||||
p = _Proj(noisy(k), elapsed_s=300.0 + (k % 400))
|
||||
c11o._carq = {"key": p.block_start, "ws": 11000.0 * p.elapsed_s, "mono": k}
|
||||
ex = p.projected_w - 14000.0
|
||||
raw.append(ex > 0.0 and c11o.car_avg_w(p, 11000.0) >= ex)
|
||||
raw_flips = sum(1 for a, b in zip(raw, raw[1:]) if a != b)
|
||||
check("PRECONDITION: the condition itself flips many times in those 20 "
|
||||
"minutes", raw_flips > 20)
|
||||
|
||||
# a real end: the car stops (no trusted power) after 600 s
|
||||
c11e = _Car(cover=False)
|
||||
o11e = over_run(c11e, 1000, lambda t: 14500.0,
|
||||
w_of=lambda t: 11000.0 if t < 600 else None)
|
||||
off_at = next((i for i, x in enumerate(o11e) if i > 600 and not x[0]), -1)
|
||||
check("a real end: the row stays for OVER_OFF_HOLD_S (180 s) and then goes",
|
||||
off_at == 600 + int(ctl_car.OVER_OFF_HOLD_S)
|
||||
and not any(x[0] for x in o11e[off_at:]))
|
||||
o11r = over_run(c11e, 100, lambda t: 14500.0, t0=1000.0)
|
||||
check("it comes back after the usual 10 s if the condition returns after "
|
||||
"it went", len(o11r) == 100 and o11r[9][0] is False and o11r[10][0] is True)
|
||||
|
||||
# the alarm decision has no hold: a real house overload is never delayed
|
||||
c11a = _Car(cover=True)
|
||||
o11a = over_run(c11a, 60, lambda t: 4300.0, target=4450.0)
|
||||
check("decision 1 on: the car explains it at once (no hold)",
|
||||
len(o11a) == 60 and o11a[0][1] is True)
|
||||
c11a.w = None # the figure is not trusted
|
||||
c11a._now = 61.0
|
||||
c11a.car_cycle(_Proj(4300.0), _G(True), 4450.0, None)
|
||||
check("...and the moment the car figure is not trusted it explains nothing, "
|
||||
"so the normal alarms stand at once (the grey row may stay)",
|
||||
c11a.car_explains is False)
|
||||
|
||||
# the whole thing on the real controller: the Why does not flicker either
|
||||
def p7_like(plant, c):
|
||||
plant.load = lambda at: 3000.0 + plant.ch.power_w
|
||||
|
||||
|
||||
r11 = P.drive(s81.constant(HOUSE), dur=700, rating=2000.0, soc=60.0, cap=CAP,
|
||||
phases=3, opts={"ev_batt_cover": False})
|
||||
ov = [s[2] for s in r11["snaps"]]
|
||||
check("real controller, cover off, an 11 kW car: the flag is steady once on",
|
||||
sum(1 for a, b in zip(ov, ov[1:]) if a != b) <= 1 and ov[-1] is True)
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n3. EV-12: OUR OWN WRITE IS NOT ANOTHER WRITER (F-3)")
|
||||
# =========================================================================== #
|
||||
CLOCK = [1000.0]
|
||||
freshness.monotonic = lambda: CLOCK[0]
|
||||
SET = "number.wallbox_power_connector_max_current_socket_1"
|
||||
BASE = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid",
|
||||
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
|
||||
"meter_source": "off", "max_w": 5000, "gain": 0.6, "slew_w": 500,
|
||||
"deadband_w": 15, "target_grid_w": 0, "step_w": 10, "heartbeat_s": 10,
|
||||
"stale_input_s": 15, "shadow_mode": "off", "peak_cap_w": 3500,
|
||||
"pv_entities": ["sensor.pv"], "ev_charger": "alfen_ha", "ev_max_a": 16,
|
||||
"ev_phases": "auto", "ev_current_entity": SET}
|
||||
|
||||
|
||||
class _Store:
|
||||
def __init__(self):
|
||||
self.data = {}
|
||||
|
||||
def set(self, k, v):
|
||||
self.data[k] = v
|
||||
|
||||
def get(self, k, d=None):
|
||||
return self.data.get(k, d)
|
||||
|
||||
def set_time(self, k, v):
|
||||
self.data[k] = v.isoformat()
|
||||
|
||||
def get_time(self, k):
|
||||
v = self.data.get(k)
|
||||
return None if v is None else datetime.fromisoformat(v)
|
||||
|
||||
|
||||
class _Pub:
|
||||
enabled = False
|
||||
|
||||
def publish(self, v):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class Site(FakeHa):
|
||||
def __init__(self, charger):
|
||||
super().__init__(charger, None)
|
||||
|
||||
async def limits(self, _e):
|
||||
return (-5000.0, 5000.0, 1.0)
|
||||
|
||||
def _all(self):
|
||||
out = super()._all()
|
||||
for eid, val, unit in (("sensor.grid", 800.0, "W"),
|
||||
("sensor.soc", 50.0, "%"),
|
||||
("sensor.batt", 0.0, "W"),
|
||||
("sensor.pv", 2000.0, "W")):
|
||||
out[eid] = {"entity_id": eid, "state": str(val),
|
||||
"attributes": {"unit_of_measurement": unit}}
|
||||
return out
|
||||
|
||||
async def number(self, entity_id, invert=False):
|
||||
s = self._all().get(entity_id)
|
||||
try:
|
||||
v = float(s["state"])
|
||||
except (TypeError, ValueError, KeyError):
|
||||
return None
|
||||
return -v if invert else v
|
||||
|
||||
async def set_number(self, entity_id, value):
|
||||
return await super().set_number(entity_id, float(value))
|
||||
|
||||
|
||||
class World:
|
||||
"""A real Controller on the charger model. While a write waits for its
|
||||
read-back, the controller's own reading goes on (as in production, where
|
||||
the cycle runs while the writer task waits): that is how the read-back of
|
||||
our own write reaches the tracker BEFORE the write returns."""
|
||||
|
||||
def __init__(self, setpoint=10):
|
||||
self.sim = SimCharger(setpoint_a=setpoint)
|
||||
self.sim.plug_in()
|
||||
self.sim.lag_s = 2.0 # the rig's read-back lag
|
||||
self.sim.phases_allowed = 1
|
||||
self.t = 1000.0
|
||||
CLOCK[0] = self.t
|
||||
self.c = Controller(dict(BASE), Site(self.sim), _Store(), _Pub(),
|
||||
stop=asyncio.Event())
|
||||
self.c.auto = True
|
||||
self.c.dev_min, self.c.dev_max = -5000.0, 5000.0
|
||||
self.drv = self.c.charger
|
||||
self.drv._sleep = self.sleep
|
||||
self.drv._clock = lambda: CLOCK[0]
|
||||
|
||||
async def sleep(self, s):
|
||||
self.sim.tick(s)
|
||||
self.t += s
|
||||
CLOCK[0] = self.t
|
||||
await self.c.read_inputs(now_mono=self.t) # the cycle reads on
|
||||
|
||||
async def step(self, n=1):
|
||||
for _ in range(n):
|
||||
self.sim.tick(1.0)
|
||||
self.t += 1.0
|
||||
CLOCK[0] = self.t
|
||||
await self.c.read_inputs(now_mono=self.t)
|
||||
await self.c.cycle()
|
||||
await self.c.car_settle()
|
||||
|
||||
def rows(self):
|
||||
return {r["id"]: r for r in self.c.checks()}
|
||||
|
||||
|
||||
async def own_then_off(wait):
|
||||
w = World()
|
||||
await w.step(3)
|
||||
await w.c.handle_action("car_mode", value="manual")
|
||||
await w.c.handle_action("car_current", value=12)
|
||||
await w.step(wait)
|
||||
await w.c.handle_action("car_mode", value="off")
|
||||
await w.step(40)
|
||||
return w
|
||||
|
||||
|
||||
w12 = asyncio.run(own_then_off(2))
|
||||
check("PRECONDITION: the add-on wrote 12 A and the charger took it",
|
||||
w12.sim.readback_a == 12 and len(w12.sim.writes("current")) == 1)
|
||||
check("our own write, then Off 2 s later: no 'Something else changes the "
|
||||
"charger'", "charger_writer" not in w12.rows()
|
||||
and w12.c.car.writer_at_utc is None)
|
||||
w12b = asyncio.run(own_then_off(14))
|
||||
check("...and 14 s later (inside the 15 s)", "charger_writer" not in
|
||||
w12b.rows() and w12b.c.car.writer_at_utc is None)
|
||||
|
||||
|
||||
async def own_then_outside():
|
||||
w = await own_then_off(2)
|
||||
w.sim.set_current(7) # somebody else, afterwards
|
||||
await w.step(3)
|
||||
early = "charger_writer" in w.rows()
|
||||
await w.step(30)
|
||||
return early, "charger_writer" in w.rows()
|
||||
|
||||
|
||||
early12, late12 = asyncio.run(own_then_outside())
|
||||
check("an outside change after that still shows the row (within 30 s)",
|
||||
late12 is True)
|
||||
|
||||
|
||||
async def manual_own():
|
||||
w = World()
|
||||
await w.step(3)
|
||||
await w.c.handle_action("car_mode", value="manual")
|
||||
await w.c.handle_action("car_current", value=12)
|
||||
await w.step(60)
|
||||
await w.c.handle_action("car_current", value=8)
|
||||
await w.step(20)
|
||||
return w
|
||||
|
||||
|
||||
wm = asyncio.run(manual_own())
|
||||
check("Manual: two writes of ours, never 'another writer' in the tracker",
|
||||
wm.c.car.writer_at_utc is None and "charger_other" not in wm.rows())
|
||||
|
||||
|
||||
async def failed_write_then_outside(how):
|
||||
"""A write that RAISES or returns FAILURE must still close the self-mute:
|
||||
it ends 15 s after the write returned, and a later outside change shows
|
||||
the row."""
|
||||
w = World()
|
||||
await w.step(3)
|
||||
await w.c.handle_action("car_mode", value="manual")
|
||||
ret = []
|
||||
|
||||
async def bad(a):
|
||||
await w.sleep(1.0)
|
||||
ret.append(w.t) # when the write came back
|
||||
if how == "raise":
|
||||
raise RuntimeError("the charger link broke")
|
||||
return False
|
||||
w.drv.write_current = bad
|
||||
await w.c.handle_action("car_current", value=12)
|
||||
await w.step(3) # the write is tried
|
||||
closed = (bool(ret) and w.c.car.mute_until <= ret[-1] + 15.0 + 1e-6)
|
||||
await w.c.handle_action("car_mode", value="off")
|
||||
await w.step(20) # past the 15 s mute
|
||||
w.sim.set_current(7) # somebody else
|
||||
await w.step(3)
|
||||
return w, closed
|
||||
|
||||
|
||||
for how in ("raise", "fail"):
|
||||
wf, closed = asyncio.run(failed_write_then_outside(how))
|
||||
check(f"a write that {'raises' if how == 'raise' else 'returns failure'}"
|
||||
": the mute ends within 15 s of the write's return, and a later "
|
||||
"outside change shows the row",
|
||||
closed and "charger_writer" in wf.rows())
|
||||
|
||||
print()
|
||||
print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed")
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -1,176 +0,0 @@
|
||||
"""EV-10b: the period without the car is not clipped at 0 W (rig F-1 again).
|
||||
`python3 -B test_ev10b.py`
|
||||
|
||||
The rig shape: house 3 kW, car 11 kW, batteries 8.1 kW, aim 6 kW. The batteries
|
||||
give more than the house uses, so the house alone is an export; clipping it at
|
||||
0 W charged the car's battery share to the house, latched "the house needs the
|
||||
batteries" for the quarter, and the floor alarm fired once both batteries
|
||||
reached the reserve. Mutating a module this file grades? Read MUTATION.md first.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import dataclasses
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import ctl_car, peakguard, tariff # noqa: E402
|
||||
import ev04_peak as P # noqa: E402
|
||||
import safety81_sim as s81 # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
CAP = 6050.0 # aim 6000 W
|
||||
OPTS = {"inverters": [
|
||||
{"name": f"inverter-{u}", "setpoint_entity": f"number.sp_{u}",
|
||||
"soc_entity": f"sensor.soc_{u}", "batt_entity": f"sensor.batt_{u}",
|
||||
"max_w": 4050, "bms_soc_floor": 10} for u in "ab"]}
|
||||
|
||||
|
||||
def rig_run(house_w, soc_events, dur=895):
|
||||
"""A whole quarter from its start, N=2 (4.05 kW each = 8.1 kW), the car at
|
||||
11 kW; `soc_events` is {second: {"a": soc, "b": soc}}."""
|
||||
def setter(socs):
|
||||
return lambda plant, c: plant.socs.update(socs)
|
||||
return P.drive(s81.constant(house_w), dur=dur, rating=4050.0,
|
||||
soc={"a": 60.0, "b": 60.0}, cap=CAP, phases=3, n=2,
|
||||
plant_cls=P.CarPlantN, opts=OPTS, dev_w=4050.0,
|
||||
events={t: setter(s) for t, s in soc_events.items()})
|
||||
|
||||
|
||||
def summary(r):
|
||||
rows = r["c"].checks()
|
||||
red = [x["id"] for x in rows if x["ok"] is False and not x["warn"]]
|
||||
return (P.ids(r, *P.ALARMS), red, P.ids(r, P.OVER),
|
||||
max(abs(r["plant"].batt(t)) for t in range(0, 30)) if r else 0)
|
||||
|
||||
|
||||
print("1. THE RIG SHAPE, A WHOLE QUARTER (house 3 kW, car 11 kW, batteries 8.1 kW)")
|
||||
r = rig_run(3000.0, {30: {"a": 19.0, "b": 19.0}})
|
||||
al, red, over, _ = summary(r)
|
||||
peak_batt = max(r["plant"].batt(t) for t in range(5, 30))
|
||||
check("PRECONDITION: the batteries gave more than the house uses (8.1 kW "
|
||||
"against 3 kW) before the reserve", peak_batt > 7500.0)
|
||||
check("both batteries reach the reserve early in the quarter: no 'Battery "
|
||||
"stopped limiting the peak', no 'Load too high'", al == [])
|
||||
check("...no red row, and no goodwe_peak_soc_floor", red == [])
|
||||
check("...one car-over notice", len(over) == 1)
|
||||
check("...the car-over row is on at the end", any(
|
||||
x["id"] == "car_over" and x["ok"] is True for x in r["c"].checks()))
|
||||
|
||||
r2 = rig_run(3000.0, {30: {"a": 19.0}, 200: {"b": 19.0}})
|
||||
al2, red2, over2, _ = summary(r2)
|
||||
check("N=2, one battery reaches the reserve first, the other later: no "
|
||||
"alarm, no red row, one car-over notice",
|
||||
al2 == [] and red2 == [] and len(over2) == 1)
|
||||
|
||||
print("\n2. BATTERIES ABOVE THE HOUSE AND THE HOUSE ALONE OVER THE AIM")
|
||||
r3 = rig_run(7000.0, {30: {"a": 19.0, "b": 19.0}})
|
||||
check("house 7 kW, car 11 kW, aim 6 kW, batteries to the reserve: the alarm "
|
||||
"fires (the house alone misses the aim)", summary(r3)[0] != []
|
||||
and not r3["c"].car_explains)
|
||||
|
||||
|
||||
print("\n3. THE COUNTERFACTUAL ITSELF")
|
||||
BS = datetime(2026, 11, 16, 20, 0, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
class _Car(ctl_car.CarMixin):
|
||||
def __init__(self, cover=True):
|
||||
self.o = {"ev_batt_cover": cover}
|
||||
self._carq = {"key": BS, "ws": 0.0, "mono": 0.0}
|
||||
|
||||
|
||||
def proj(grid, elapsed, held=None):
|
||||
return tariff.Projection(
|
||||
projected_w=grid, elapsed_w=grid, elapsed_s=elapsed,
|
||||
covered_frac=1.0, complete=False, block_start=BS,
|
||||
held_w=grid if held is None else held)
|
||||
|
||||
|
||||
def lands(p, batt, aim=5950.0):
|
||||
return peakguard.misses_aim(p, batt_w=batt, target_w=aim)
|
||||
|
||||
|
||||
c = _Car()
|
||||
for el in (10.0, 30.0, 120.0, 300.0, 600.0):
|
||||
c._carq["ws"] = 11040.0 * el
|
||||
p = proj(3000 + 11040 - 8100, el)
|
||||
x = c.car_exclude_alarm(p, 11040.0)
|
||||
check(f"rig numbers at {el:.0f} s: the house alone does not miss the aim "
|
||||
"(no 0 W clip)", not lands(x, 8100.0))
|
||||
check(f"...and the guard-side `car_exclude` is unchanged (still clipped)",
|
||||
c.car_exclude(p, 11040.0).held_w == 0.0)
|
||||
c._carq["ws"] = 11040.0 * 30
|
||||
x = c.car_exclude_alarm(proj(5940.0, 30.0), 11040.0)
|
||||
check("the rest of the period keeps its sign: held = grid - car = -5100 W",
|
||||
abs(x.held_w - (5940.0 - 11040.0)) < 1e-6)
|
||||
check("a fresh car reading is needed: None gives the period back as it is",
|
||||
c.car_exclude_alarm(proj(5940.0, 30.0), None).held_w == 5940.0)
|
||||
# the house alone over the aim still misses
|
||||
c._carq["ws"] = 11040.0 * 30
|
||||
check("house 7 kW alone (batteries 8.1 kW, car 11 kW): the house misses the aim",
|
||||
lands(c.car_exclude_alarm(proj(7000 + 11040 - 8100, 30.0), 11040.0),
|
||||
8100.0))
|
||||
# review: the done part is clipped at 0 Ws. Rig shape for 400 s (grid 5940 W),
|
||||
# then the batteries at the reserve and the house at 12 kW: the house alone
|
||||
# lands 6667 W. Crediting the car-made export (-5100 W x 400 s) would hide it.
|
||||
c._carq["ws"] = 11040.0 * 400
|
||||
held = 12000.0 + 11040.0
|
||||
check("the car's battery share earlier is not credited against a later house "
|
||||
"overload (done part clipped at 0 Ws)",
|
||||
lands(c.car_exclude_alarm(
|
||||
proj((5940.0 * 400 + held * 500) / 900, 400.0, held), 11040.0), 0.0))
|
||||
# review: the rest of the period takes off the car's power NOW, not its
|
||||
# quarter average. Car 11 kW for 500 s, then 1.4 kW; house 7 kW, no batteries.
|
||||
c._carq["ws"] = 11040.0 * 500 + 1380.0 * 100
|
||||
held = 7000.0 + 1380.0
|
||||
check("a car turned down mid-quarter: the rest takes off its power now, so "
|
||||
"the house alone (7 kW) still misses the aim",
|
||||
lands(c.car_exclude_alarm(
|
||||
proj(((7000 + 11040) * 500 + held * 100 + held * 300) / 900, 600.0,
|
||||
held), 1380.0), 0.0))
|
||||
# with the batteries giving less than the house the two agree where the old
|
||||
# clip did not bite
|
||||
p = proj(3000 + 3700 - 300, 300.0)
|
||||
c._carq["ws"] = 3700.0 * 300.0
|
||||
old, new = c.car_exclude(p, 3700.0), c.car_exclude_alarm(p, 3700.0)
|
||||
check("batteries under the house: the same landing as before (no clip bit)",
|
||||
abs(old.projected_w - new.projected_w) < 1e-6
|
||||
and abs(old.held_w - new.held_w) < 1e-6)
|
||||
|
||||
# cover OFF: the projection the guard sees is `car_exclude`, bit for bit what
|
||||
# b86c015 built (a frozen copy of its formula), over a grid of periods
|
||||
def frozen(c, p, w):
|
||||
avg = c.car_avg_w(p, w)
|
||||
return (max(0.0, float(p.projected_w) - avg),
|
||||
max(0.0, float(p.held_w) - float(w)))
|
||||
|
||||
|
||||
same = True
|
||||
for grid in (-3000.0, 0.0, 800.0, 5900.0, 14000.0):
|
||||
for held in (-4000.0, 0.0, 6000.0, 15000.0):
|
||||
for el in (0.0, 30.0, 450.0, 899.0):
|
||||
for w in (1380.0, 3700.0, 11040.0):
|
||||
c._carq["ws"] = w * el * 0.9
|
||||
p = proj(grid, el, held)
|
||||
x = c.car_exclude(p, w)
|
||||
same = same and (x.projected_w, x.held_w) == frozen(c, p, w)
|
||||
check("cover off: the projection the guard sees (`car_exclude`) is bit for "
|
||||
"bit the old formula over 240 periods", same)
|
||||
check("...and `car_exclude` still hands back the period when the car figure "
|
||||
"is None", c.car_exclude(proj(5000.0, 30.0), None).projected_w == 5000.0)
|
||||
|
||||
print()
|
||||
print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed")
|
||||
sys.exit(1 if fails else 0)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,832 +0,0 @@
|
||||
"""EV-14: the Car Why says what happens, not only what the user set.
|
||||
`python3 -B test_ev14.py`
|
||||
|
||||
Display only (homeview._car_manual_why, ui_text en/nl):
|
||||
E1 shadow mode: no Why says "You set"; with the car over the limit it says
|
||||
what the add-on WOULD set and that this charge would set the peak.
|
||||
E2 a phase change that did not happen (read phases differ from the setting):
|
||||
"The charger stays on {real}", never "keeps it".
|
||||
E3 the writer holds for another writer: "Something else set the charger".
|
||||
E4 phases equal or unknown, no hold: exactly as before.
|
||||
E5 texts in en and nl, same keys, UX-08 limits.
|
||||
N2 the render writes nothing; N3 it never sends to the charger.
|
||||
Mutants: see the dev report (M1-M14).
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import dataclasses
|
||||
import itertools
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import carmode, chargers as CH, ctl_car, homeview, uitext # noqa: E402
|
||||
from app.carmode import PHASE_GAP_S, ManualWriter # noqa: E402
|
||||
from app.main import Controller # noqa: E402
|
||||
from app import freshness # noqa: E402
|
||||
from chargersim import FakeHa, SimCharger # noqa: E402
|
||||
from named_absence import nth, present # noqa: E402
|
||||
|
||||
fails = []
|
||||
logging.getLogger("goodwe").setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
def run(coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
# The texts the test holds the page to, written out (T34: base is byte-equal).
|
||||
# =========================================================================== #
|
||||
BASE_EN = {
|
||||
"manual_set": "You set {a} A, {phases}. The charger keeps it, whatever the peak limit does.",
|
||||
"manual_cover": "You set {a} A. The batteries give {kw} and help down to {pct}.",
|
||||
"manual_over": "You set {a} A. The batteries are at {pct}, so this charge sets the peak.",
|
||||
"manual_full": "You set {a} A. The batteries give all they can, so this charge sets the peak.",
|
||||
"manual_nocover": "You set {a} A. The guard ignores the car, so this charge can set the peak.",
|
||||
"manual_wait": "You set {a} A. It is set when a car is connected.",
|
||||
"manual_would": "Shadow mode: the add-on would set {a} A, {phases}.",
|
||||
"manual_stopped": "Control is stopped. The charger keeps its last setting.",
|
||||
"manual_blocked": "The phases change once per 10 minutes at most. This waits.",
|
||||
}
|
||||
BASE_NL = {
|
||||
"manual_set": "U stelde {a} A in, {phases}. De laadpaal houdt dit aan, wat de piekgrens ook doet.",
|
||||
"manual_cover": "U stelde {a} A in. De batterijen leveren {kw} en helpen tot {pct}.",
|
||||
"manual_over": "U stelde {a} A in. De batterijen staan op {pct}, dus deze lading bepaalt de piek.",
|
||||
"manual_full": "U stelde {a} A in. De batterijen geven alles, dus deze lading bepaalt de piek.",
|
||||
"manual_nocover": "U stelde {a} A in. De bewaking negeert de auto, dus deze lading kan de piek bepalen.",
|
||||
"manual_wait": "U stelde {a} A in. Het wordt ingesteld zodra een auto is aangesloten.",
|
||||
"manual_would": "Schaduwmodus: de add-on zou {a} A instellen, {phases}.",
|
||||
"manual_stopped": "De regeling is gestopt. De laadpaal houdt haar laatste instelling.",
|
||||
"manual_blocked": "De fasen wisselen hooguit eens per 10 minuten. Dit wacht.",
|
||||
}
|
||||
NEW_KEYS = ("manual_shadow_over", "manual_phases", "manual_other")
|
||||
LANGS = ("en", "nl")
|
||||
YOU = {"en": "You set", "nl": "U stelde"}
|
||||
KEEPS = {"en": "The charger keeps it,", "nl": "De laadpaal houdt dit aan"}
|
||||
WOULD = {"en": "would set", "nl": "zou"}
|
||||
PEAK = {"en": "would set the peak", "nl": "zou de piek bepalen"}
|
||||
STAYS = {"en": "stays on", "nl": "blijft op"}
|
||||
OTHER = {"en": "Something else set the charger.", "nl": "Iets anders heeft de laadpaal ingesteld."}
|
||||
|
||||
|
||||
def jwords(lang):
|
||||
return uitext.words(lang)["home_words"]["car"]["why"]
|
||||
|
||||
|
||||
def tx(lang, key, **kw):
|
||||
"""Render a car.why text the way the page does (a missing key is a text
|
||||
of its own, so a check on it is a FAIL, not a crash)."""
|
||||
homeview._LANG[0] = uitext.lang_of(lang)
|
||||
try:
|
||||
return homeview._t("car.why." + key, **kw)
|
||||
except Exception as e: # noqa: BLE001
|
||||
return f"<EXC {type(e).__name__} {key}>"
|
||||
finally:
|
||||
homeview._LANG[0] = "en"
|
||||
|
||||
|
||||
def pw(n):
|
||||
homeview._LANG[0] = "en"
|
||||
return homeview.car_phases_word(n)
|
||||
|
||||
|
||||
def pw_l(lang, n):
|
||||
homeview._LANG[0] = uitext.lang_of(lang)
|
||||
try:
|
||||
return homeview.car_phases_word(n)
|
||||
finally:
|
||||
homeview._LANG[0] = "en"
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
# A stub site for the unit rows: what _car_manual_why reads, nothing else.
|
||||
# =========================================================================== #
|
||||
@dataclasses.dataclass
|
||||
class G:
|
||||
floor_limited: bool = True
|
||||
soc: object = 19.0
|
||||
saturated: bool = False
|
||||
floor_w: float = 300.0
|
||||
able_w: object = None
|
||||
ceiling_w: float = 4500.0
|
||||
engaged: bool = True
|
||||
blind: object = None
|
||||
wanted_w: float = 300.0
|
||||
within_aim: bool = False
|
||||
|
||||
|
||||
class Car:
|
||||
def __init__(self, reading, fresh, last_good=None):
|
||||
self.reading, self._fresh, self.last_good = reading, fresh, last_good
|
||||
|
||||
def fresh(self, _now):
|
||||
return self._fresh
|
||||
|
||||
def status(self, *_a):
|
||||
return "charging"
|
||||
|
||||
|
||||
class U(ctl_car.CarMixin):
|
||||
"""The attributes `_car_manual_why` and `_car_why_tick` read."""
|
||||
|
||||
def __init__(self, **kw):
|
||||
self.o = {"ev_batt_cover": kw.get("cover", True)}
|
||||
self._now = 0.0
|
||||
self.w = 11000.0
|
||||
self.site_batt_w, self.site_rating_w = 8100.0, 9600.0
|
||||
self.shadow = kw.get("shadow", False)
|
||||
self.auto = kw.get("auto", True)
|
||||
self.peak_guard = kw.get("pg", G(
|
||||
floor_limited=kw.get("floor", True),
|
||||
floor_w=300.0 if kw.get("eng") else 0.0))
|
||||
self.state = "charging"
|
||||
self.car_init({}, type("St", (), {"data": {}, "set": lambda s, k, v: 0})())
|
||||
self.car_a = kw.get("a", 10.0)
|
||||
self.car_n = kw.get("n", 3)
|
||||
self.car_over = kw.get("over", False)
|
||||
wr = self.car_writer
|
||||
wr.hold = wr.other = kw.get("hold", False)
|
||||
wr.blocked = kw.get("blocked", False)
|
||||
wr.seq = kw.get("seq", None)
|
||||
wr.would = kw.get("would", None)
|
||||
wr.phases_gave_up = kw.get("gave_up", False)
|
||||
if "car" in kw:
|
||||
self.car = kw["car"]
|
||||
else:
|
||||
real = kw.get("real", None)
|
||||
rd = CH.ChargerReading(available=True, state="C", power_w=2300.0,
|
||||
setpoint_a=10.0, allowed_a=10.0,
|
||||
phases_allowed=real)
|
||||
self.car = Car(rd, kw.get("fresh", True))
|
||||
|
||||
def car_now(self):
|
||||
return self._now
|
||||
|
||||
|
||||
def snap(c):
|
||||
"""Everything N2 says a render must not move."""
|
||||
keep = {k: v for k, v in vars(c).items()
|
||||
if k.startswith(("car_", "_car")) and k != "car"}
|
||||
car = getattr(c, "car", None)
|
||||
return repr((vars(c.car_writer), vars(car) if hasattr(car, "__dict__")
|
||||
else None, keep, c.shadow, c.auto))
|
||||
|
||||
|
||||
N2_BAD = []
|
||||
EXC = []
|
||||
|
||||
|
||||
def why(c, lang="en", key="charging"):
|
||||
"""The Why text; an exception becomes a text; N2 is checked on every call."""
|
||||
before = snap(c)
|
||||
homeview._LANG[0] = uitext.lang_of(lang)
|
||||
try:
|
||||
out = homeview._car_manual_why(c, key)
|
||||
except Exception as e: # noqa: BLE001
|
||||
EXC.append(repr(e))
|
||||
out = f"<EXC {type(e).__name__} {e}>"
|
||||
finally:
|
||||
homeview._LANG[0] = "en"
|
||||
if snap(c) != before:
|
||||
N2_BAD.append(out)
|
||||
return out
|
||||
|
||||
|
||||
def exp(lang, key, **kw):
|
||||
return tx(lang, key, **kw)
|
||||
|
||||
|
||||
def a_(c):
|
||||
return f"{float(c.car_a):.0f}"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("1. E1: shadow mode says what the add-on WOULD set")
|
||||
# --------------------------------------------------------------------------- #
|
||||
SHADOW_BAD_CASES = {
|
||||
"T1 floor": dict(floor=True, cover=True),
|
||||
"T2 full": dict(floor=False, cover=True),
|
||||
"T3 cover off": dict(floor=True, cover=False),
|
||||
}
|
||||
for label, kw in SHADOW_BAD_CASES.items():
|
||||
for lang in LANGS:
|
||||
c = U(shadow=True, over=True, a=16.0, n=3, would=(10.0, 3), **kw)
|
||||
t = why(c, lang)
|
||||
check(f"{label} ({lang}): would set 10 A and would set the peak; no "
|
||||
f"'You set', no 16 A: {t!r}",
|
||||
present(t) and WOULD[lang] in t and "10 A" in t
|
||||
and PEAK[lang] in t and YOU[lang] not in t and "16 A" not in t)
|
||||
check(f"{label} ({lang}): exactly the shadow-over text",
|
||||
t == exp(lang, "manual_shadow_over", a="10",
|
||||
phases=pw_l(lang, 3)))
|
||||
|
||||
for lang in LANGS:
|
||||
c = U(shadow=True, over=True, a=12.0, n=3, would=None)
|
||||
t = why(c, lang)
|
||||
check(f"T4 ({lang}): writer not stepped: falls back to (car_a, car_n), "
|
||||
f"12 A, 3 phases, no 'You set': {t!r}",
|
||||
t == exp(lang, "manual_shadow_over", a="12", phases=pw_l(lang, 3))
|
||||
and YOU[lang] not in t)
|
||||
# Review: the phases word is the writer's `would`, as manual_would's.
|
||||
c = U(shadow=True, over=True, a=16.0, n=1, would=(10.0, 3))
|
||||
check(f"T1 phases ({lang}): the phases come from would, not car_n",
|
||||
why(c, lang) == exp(lang, "manual_shadow_over", a="10",
|
||||
phases=pw_l(lang, 3)))
|
||||
c = U(shadow=True, over=False, a=16.0, n=3, would=(10.0, 3))
|
||||
check(f"T5 ({lang}): shadow, not over: exactly today's manual_would",
|
||||
why(c, lang) == BASE_EN["manual_would"].format(
|
||||
a="10", phases="3 phases") if lang == "en" else
|
||||
why(c, lang) == BASE_NL["manual_would"].format(
|
||||
a="10", phases="3 fasen"))
|
||||
|
||||
# T6/T7: the EV-16 episode, 5 s cycles, floor flipping every 10 s.
|
||||
STEP = 5.0
|
||||
|
||||
|
||||
def tick(c, g, t, shadow=None):
|
||||
c._now = t
|
||||
c.peak_guard = g
|
||||
if shadow is not None:
|
||||
c.shadow = shadow
|
||||
c._car_why_tick(g, t)
|
||||
|
||||
|
||||
def episode(c, secs, flip=10.0, shadow_off_at=None):
|
||||
out, t = [], 0.0
|
||||
while t < secs:
|
||||
g = G(floor_limited=(int(t // flip) % 2 == 0))
|
||||
off = shadow_off_at is not None and t >= shadow_off_at
|
||||
tick(c, g, t, shadow=False if off else None)
|
||||
out.append((t, why(c)))
|
||||
t += STEP
|
||||
return out
|
||||
|
||||
|
||||
c = U(shadow=True, over=True, a=16.0, would=(10.0, 3))
|
||||
ep = episode(c, 180.0)
|
||||
texts = {t for _, t in ep}
|
||||
check(f"T6: shadow over, floor flips for 180 s: one constant text, 0 changes "
|
||||
f"({len(ep)} cycles)", len(ep) == 36 and len(texts) == 1
|
||||
and all(PEAK["en"] in t for t in texts))
|
||||
c = U(shadow=True, over=True, a=16.0, would=(10.0, 3))
|
||||
ep = episode(c, 180.0, flip=1000.0, shadow_off_at=90.0)
|
||||
first = [t for tt, t in ep if tt < 90.0]
|
||||
later = [t for tt, t in ep if tt >= 90.0]
|
||||
check("T7: shadow switched off mid-episode with the floor held: the shadow "
|
||||
"text, then exactly today's manual_over (EV-16 hold)",
|
||||
len(first) == 18 and len(later) == 18 and len(set(first)) == 1
|
||||
and PEAK["en"] in nth(first)
|
||||
and set(later) == {BASE_EN["manual_over"].format(a="16", pct=homeview._pct(
|
||||
c.o.get("peak_soc_floor", 20)))})
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("\n2. E2 / E3: units")
|
||||
# --------------------------------------------------------------------------- #
|
||||
for lang in LANGS:
|
||||
c = U(real=1, n=3, a=10.0)
|
||||
t = why(c, lang)
|
||||
check(f"T9 ({lang}): 3 set, charger on 1: 'stays on 1 phase', not 'keeps "
|
||||
f"it': {t!r}",
|
||||
t == exp(lang, "manual_phases", a="10", phases=pw_l(lang, 3),
|
||||
real=pw_l(lang, 1))
|
||||
and STAYS[lang] in t and KEEPS[lang] not in t
|
||||
and pw_l(lang, 1) in t)
|
||||
c = U(real=3, n=1, a=10.0)
|
||||
t = why(c, lang)
|
||||
check(f"T10 ({lang}): 1 set, charger on 3: 'stays on 3 phases': {t!r}",
|
||||
t == exp(lang, "manual_phases", a="10", phases=pw_l(lang, 1),
|
||||
real=pw_l(lang, 3)) and pw_l(lang, 3) in t.split(". ")[-1]
|
||||
and KEEPS[lang] not in t)
|
||||
check("T9: the words are the brief's (EN and NL)",
|
||||
why(U(real=1, n=3)) == "You set 10 A, 3 phases. The charger stays on 1 phase."
|
||||
and why(U(real=1, n=3), "nl") ==
|
||||
"U stelde 10 A in, 3 fasen. De laadpaal blijft op 1 fase.")
|
||||
|
||||
|
||||
def sett(lang, c):
|
||||
return exp(lang, "manual_set", a=a_(c), phases=pw_l(lang, c.car_n))
|
||||
|
||||
|
||||
for lang in LANGS:
|
||||
c = U(real=1, n=3, auto=False)
|
||||
check(f"T13a ({lang}): phases differ, control stopped: manual_stopped",
|
||||
why(c, lang) == exp(lang, "manual_stopped"))
|
||||
c = U(real=1, n=3, shadow=True, would=(10.0, 3))
|
||||
check(f"T13b ({lang}): phases differ, shadow: manual_would",
|
||||
why(c, lang) == exp(lang, "manual_would", a="10",
|
||||
phases=pw_l(lang, 3)))
|
||||
for stage in ("zero", "settle"):
|
||||
c = U(real=1, n=3, seq={"stage": stage})
|
||||
check(f"T14 ({lang}): phases differ, sequence at {stage}: manual_set",
|
||||
why(c, lang) == sett(lang, c))
|
||||
c = U(real=1, n=3, blocked=True)
|
||||
check(f"T15 ({lang}): phases differ, blocked: manual_blocked",
|
||||
why(c, lang) == exp(lang, "manual_blocked"))
|
||||
for key in ("none", "full"):
|
||||
c = U(real=1, n=3)
|
||||
check(f"T16 ({lang}): phases differ, key {key}: manual_wait",
|
||||
why(c, lang, key) == exp(lang, "manual_wait", a="10"))
|
||||
c = U(real=1, n=3, eng=True)
|
||||
giving = max(0.0, float(c.site_batt_w))
|
||||
homeview._LANG[0] = uitext.lang_of(lang)
|
||||
kw_ = homeview._kw(giving)
|
||||
pct_ = homeview._pct(20)
|
||||
homeview._LANG[0] = "en"
|
||||
check(f"T17 ({lang}): phases differ, cover engaged, not over: manual_cover",
|
||||
why(c, lang) == exp(lang, "manual_cover", a="10", kw=kw_, pct=pct_))
|
||||
for label, kw in (("floor", dict(floor=True)), ("full", dict(floor=False)),
|
||||
("nocover", dict(cover=False))):
|
||||
c = U(real=1, n=3, over=True, **kw)
|
||||
want = ("manual_nocover" if label == "nocover" else
|
||||
"manual_over" if label == "floor" else "manual_full")
|
||||
check(f"T18 ({lang}): phases differ, car over ({label}): {want}",
|
||||
why(c, lang) == exp(lang, want, a="10", pct=pct_))
|
||||
|
||||
# T19/T20 are in the World section. T21-T26: the hold, units.
|
||||
for lang in LANGS:
|
||||
c = U(hold=True, real=1, n=3)
|
||||
t = why(c, lang)
|
||||
check(f"T21 ({lang}): hold, phases differ, not given up: the hold text "
|
||||
f"{t!r}", t == exp(lang, "manual_other") and OTHER[lang] in t
|
||||
and STAYS[lang] not in t and YOU[lang] not in t)
|
||||
for key in ("none", "full"):
|
||||
c = U(hold=True, real=3, n=3)
|
||||
check(f"T22 ({lang}): hold, key {key}: the hold text, not 'set when a "
|
||||
f"car is connected'",
|
||||
why(c, lang, key) == exp(lang, "manual_other"))
|
||||
c = U(hold=True, blocked=True, real=3, n=3)
|
||||
check(f"T23a ({lang}): hold with a stale blocked: the hold text",
|
||||
why(c, lang) == exp(lang, "manual_other"))
|
||||
c = U(hold=True, real=3, n=3, eng=True)
|
||||
check(f"T23b ({lang}): hold with the cover engaged: the hold text",
|
||||
why(c, lang) == exp(lang, "manual_other"))
|
||||
for label, kw in (("floor", dict(floor=True)), ("full", dict(floor=False)),
|
||||
("nocover", dict(cover=False))):
|
||||
c = U(hold=True, over=True, real=3, n=3, **kw)
|
||||
want = ("manual_nocover" if label == "nocover" else
|
||||
"manual_over" if label == "floor" else "manual_full")
|
||||
check(f"T24 ({lang}): hold and car over ({label}): {want}, no hold "
|
||||
f"text", why(c, lang) == exp(lang, want, a="10", pct=pct_)
|
||||
and OTHER[lang] not in why(c, lang))
|
||||
for key in ("charging", "none"):
|
||||
c = U(hold=True, auto=False, real=3, n=3)
|
||||
check(f"T25 ({lang}): hold, control stopped, key {key}: manual_stopped",
|
||||
why(c, lang, key) == exp(lang, "manual_stopped"))
|
||||
c = U(hold=True, shadow=True, over=False, would=(10.0, 3))
|
||||
check(f"T26a ({lang}): hold, shadow, not over: manual_would",
|
||||
why(c, lang) == exp(lang, "manual_would", a="10",
|
||||
phases=pw_l(lang, 3)))
|
||||
c = U(hold=True, shadow=True, over=True, would=(10.0, 3))
|
||||
check(f"T26b ({lang}): hold, shadow, over: the shadow-over text",
|
||||
why(c, lang) == exp(lang, "manual_shadow_over", a="10",
|
||||
phases=pw_l(lang, 3)))
|
||||
|
||||
# T29-T32: E4.
|
||||
for lang in LANGS:
|
||||
for n in (1, 3):
|
||||
c = U(real=n, n=n, would=(10.0, 3))
|
||||
want = (BASE_EN if lang == "en" else BASE_NL)["manual_set"].format(
|
||||
a="10", phases=pw_l(lang, n))
|
||||
check(f"T29 ({lang}): {n}/{n} phases: byte-identical manual_set",
|
||||
why(c, lang) == want)
|
||||
c = U(real=None, n=3)
|
||||
check(f"T30 ({lang}): phases_allowed None: manual_set, no exception",
|
||||
why(c, lang) == sett(lang, c))
|
||||
c = U(real=3, n=1, fresh=False)
|
||||
check(f"T32 ({lang}): reading not fresh: manual_set (stale is unknown)",
|
||||
why(c, lang) == sett(lang, c))
|
||||
c = U(car=Car(None, True))
|
||||
check("T31a: reading None: today's text, no exception",
|
||||
why(c) == sett("en", c))
|
||||
rd = CH.ChargerReading(available=False, phases_allowed=1)
|
||||
c = U(car=Car(rd, True, last_good=None), n=3)
|
||||
check("T31b: reading unavailable (phases 1 vs 3): today's text",
|
||||
why(c) == sett("en", c))
|
||||
c = U(real=1, n=3, pg=None)
|
||||
check("T31c: peak_guard None: no exception, the E2 text",
|
||||
why(c) == exp("en", "manual_phases", a="10", phases="3 phases",
|
||||
real="1 phase"))
|
||||
c = U(real=1, n=3)
|
||||
del c.car
|
||||
check("T31d: no car object at all: no exception, today's text",
|
||||
why(c) == sett("en", c))
|
||||
check("T31: no exception from any of the above", not EXC)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("\n3. E5: the texts")
|
||||
# --------------------------------------------------------------------------- #
|
||||
PH = re.compile(r"\{(\w+)\}")
|
||||
JARGON = {
|
||||
"en": r"controllers?|control loop|setpoints?|SoC|state of charge|BMS|PV|"
|
||||
r"failsafe|trip(?:ped)?|parked|discharg\w*|P1 feed|quarter-hour|"
|
||||
r"payload|endpoint|JSON|API|timeout|boolean|config|commands?|"
|
||||
r"charge level|ceiling|billed quarter|quarters?|banked|soft limit|"
|
||||
r"open block|actuator|ESP32|master|meter source|circulating|"
|
||||
r"sign disagreement|rail",
|
||||
"nl": r"setpoints?|setpunt\w*|SoC|laadtoestand|BMS|PV|failsafe|regelaar|"
|
||||
r"regellus|controller|latch|ontlad\w*|payload|endpoint|JSON|API|"
|
||||
r"time-?out|boolean|config|kwartuur\w*|commando\w*|geparkeerd|"
|
||||
r"ESP32|master",
|
||||
}
|
||||
JARGON = {k: re.compile(r"\b(?:" + v + r")\b", re.I) for k, v in JARGON.items()}
|
||||
samples = {lang: [t for k, t in homeview.text_samples(lang) if k == "plan"]
|
||||
for lang in LANGS}
|
||||
for key in NEW_KEYS:
|
||||
en_t = uitext.raw("en")["home_words"]["car"]["why"].get(key)
|
||||
nl_t = uitext.raw("nl")["home_words"]["car"]["why"].get(key)
|
||||
check(f"T33 {key}: in en.json and nl.json with the same placeholders",
|
||||
isinstance(en_t, str) and isinstance(nl_t, str)
|
||||
and set(PH.findall(en_t)) == set(PH.findall(nl_t)))
|
||||
for lang in LANGS:
|
||||
raw = jwords(lang).get(key, "")
|
||||
vals = {k: "10" for k in PH.findall(raw)}
|
||||
vals.update(phases=pw_l(lang, 3), real=pw_l(lang, 1))
|
||||
shown = tx(lang, key, **vals)
|
||||
sents = re.split(r"(?<=[.!?])\s+", shown)
|
||||
nwords = [len(s.split()) for s in sents]
|
||||
check(f"T33 {key} ({lang}): in text_samples as a plan line, no '{{', "
|
||||
f"<=2 sentences of <=12 words ({nwords}), no jargon: {shown!r}",
|
||||
shown in samples[lang] and "{" not in shown
|
||||
and len(sents) <= 2 and max(nwords) <= 12
|
||||
and not JARGON[lang].search(PH.sub("X", shown)))
|
||||
for lang in LANGS:
|
||||
base = BASE_EN if lang == "en" else BASE_NL
|
||||
words = jwords(lang)
|
||||
check(f"T34 ({lang}): the 9 existing manual_* texts are byte-identical",
|
||||
all(words.get(k) == v for k, v in base.items()) and len(base) == 9)
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
print("\n4. T35: the property sweep (both languages)")
|
||||
# --------------------------------------------------------------------------- #
|
||||
n_calls = 0
|
||||
viol = {"i": [], "ii": [], "iii": [], "iv": []}
|
||||
for (sh, ov, cv, fl, hd, au, bl, eg, sq, key, pa, cn, fr) in itertools.product(
|
||||
(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1),
|
||||
(None, {"stage": "zero"}), ("charging", "waiting", "none", "full"),
|
||||
(None, 1, 3), (1, 3), (0, 1)):
|
||||
for lang in LANGS:
|
||||
c = U(shadow=bool(sh), over=bool(ov), cover=bool(cv), floor=bool(fl),
|
||||
hold=bool(hd), auto=bool(au), blocked=bool(bl), eng=bool(eg),
|
||||
seq=sq, real=pa,
|
||||
n=cn, fresh=bool(fr), would=(10.0, 3))
|
||||
t = why(c, lang, key)
|
||||
n_calls += 1
|
||||
if sh and YOU[lang] in t:
|
||||
viol["i"].append((lang, t))
|
||||
known = pa is not None and fr
|
||||
if (not sh and au and not ov
|
||||
and (hd or (known and pa != cn and sq is None))
|
||||
and KEEPS[lang] in t):
|
||||
viol["ii"].append((lang, t))
|
||||
if "{" in t or "<EXC" in t:
|
||||
viol["iii"].append((lang, t))
|
||||
sents = re.split(r"(?<=[.!?])\s+", t)
|
||||
if len(sents) > 2 or max(len(s.split()) for s in sents) > 12:
|
||||
viol["iv"].append((lang, t))
|
||||
check(f"T35 (i): shadow mode, no 'You set' anywhere ({n_calls} calls)",
|
||||
n_calls == 2 * 24576 and not viol["i"])
|
||||
check("T35 (ii): no 'keeps it' under hold or a known, fresh phase difference",
|
||||
not viol["ii"])
|
||||
check("T35 (iii): no '{' left, no exception", not viol["iii"] and not EXC)
|
||||
check("T35 (iv): at most 2 sentences of 12 words (the new texts' share)",
|
||||
not [v for v in viol["iv"]
|
||||
if any(k in v[1] for k in ("stays on", "blijft op", "Something else",
|
||||
"Iets anders", "would set the peak",
|
||||
"zou de piek"))])
|
||||
check("T35 (vi)/N2: no render changed the writer, the car or the controller "
|
||||
f"({len(N2_BAD)} did)", not N2_BAD)
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n5. Integration: a real Controller on the charger model")
|
||||
# =========================================================================== #
|
||||
SET = "number.wallbox_power_connector_max_current_socket_1"
|
||||
BASE = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid",
|
||||
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
|
||||
"meter_source": "off", "max_w": 5000, "gain": 0.6, "slew_w": 500,
|
||||
"deadband_w": 15, "target_grid_w": 0, "step_w": 10, "heartbeat_s": 10,
|
||||
"stale_input_s": 15, "shadow_mode": "off", "peak_cap_w": 3500,
|
||||
"pv_entities": ["sensor.pv"]}
|
||||
CAR = dict(BASE, ev_charger="alfen_ha", ev_max_a=16, ev_phases="auto",
|
||||
ev_current_entity=SET)
|
||||
CLOCK = [1000.0]
|
||||
freshness.monotonic = lambda: CLOCK[0]
|
||||
|
||||
|
||||
class _Store:
|
||||
def __init__(self):
|
||||
self.data = {}
|
||||
|
||||
def set(self, k, v):
|
||||
self.data[k] = v
|
||||
|
||||
def get(self, k, d=None):
|
||||
return self.data.get(k, d)
|
||||
|
||||
def set_time(self, k, v):
|
||||
self.data[k] = v.isoformat()
|
||||
|
||||
def get_time(self, k):
|
||||
v = self.data.get(k)
|
||||
return None if v is None else datetime.fromisoformat(v)
|
||||
|
||||
|
||||
class _Pub:
|
||||
enabled = False
|
||||
|
||||
def publish(self, v):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class Site(FakeHa):
|
||||
def __init__(self, charger, grid=500.0, batt=0.0, pv=2000.0):
|
||||
super().__init__(charger, None)
|
||||
self.grid, self.batt, self.pv = grid, batt, pv
|
||||
|
||||
async def limits(self, _e):
|
||||
return (-5000.0, 5000.0, 1.0)
|
||||
|
||||
def _all(self):
|
||||
out = super()._all()
|
||||
for eid, val, unit_ in (("sensor.grid", self.grid, "W"),
|
||||
("sensor.soc", 50.0, "%"),
|
||||
("sensor.batt", self.batt, "W"),
|
||||
("sensor.pv", self.pv, "W")):
|
||||
out[eid] = {"entity_id": eid, "state": str(val),
|
||||
"attributes": {"unit_of_measurement": unit_}}
|
||||
return out
|
||||
|
||||
async def number(self, entity_id, invert=False):
|
||||
s = self._all().get(entity_id)
|
||||
try:
|
||||
v = float(s["state"])
|
||||
except (TypeError, ValueError, KeyError):
|
||||
return None
|
||||
return -v if invert else v
|
||||
|
||||
async def set_number(self, entity_id, value):
|
||||
if entity_id == "number.sp":
|
||||
self.sets.append((entity_id, float(value)))
|
||||
self.batt = float(value)
|
||||
return True
|
||||
return await super().set_number(entity_id, float(value))
|
||||
|
||||
|
||||
class World:
|
||||
def __init__(self, opts=CAR, setpoint=10, grid=800.0, phases=1):
|
||||
self.sim = SimCharger(setpoint_a=setpoint)
|
||||
self.sim.plug_in()
|
||||
self.sim.phases_allowed = phases
|
||||
self.site = Site(self.sim, grid=grid)
|
||||
self.t = 1000.0
|
||||
CLOCK[0] = self.t
|
||||
self.c = Controller(dict(opts), self.site, _Store(), _Pub(),
|
||||
stop=asyncio.Event())
|
||||
self.c.auto = True
|
||||
self.c.dev_min, self.c.dev_max = -5000.0, 5000.0
|
||||
self.drv = self.c.charger
|
||||
if hasattr(self.drv, "_sleep"):
|
||||
self.drv._sleep = self.sleep
|
||||
self.drv._clock = lambda: CLOCK[0]
|
||||
|
||||
async def sleep(self, s):
|
||||
self.sim.tick(s)
|
||||
self.t += s
|
||||
CLOCK[0] = self.t
|
||||
|
||||
async def step(self, n=1, dt=1.0):
|
||||
for _ in range(n):
|
||||
self.sim.tick(dt)
|
||||
self.t += dt
|
||||
CLOCK[0] = self.t
|
||||
await self.c.read_inputs(now_mono=self.t)
|
||||
await self.c.cycle()
|
||||
await self.c.car_settle()
|
||||
|
||||
async def act(self, what, value):
|
||||
return await self.c.handle_action(what, value=value)
|
||||
|
||||
def writes(self, what=None):
|
||||
return self.sim.writes(what)
|
||||
|
||||
@property
|
||||
def wr(self):
|
||||
return self.c.car_writer
|
||||
|
||||
|
||||
W_BAD = []
|
||||
|
||||
|
||||
def block_why(w, lang="en"):
|
||||
"""car_block's Why, with N2 and N3 held across the call."""
|
||||
c = w.c
|
||||
before = (snap(c), len(w.sim.log), list(w.drv.sent),
|
||||
len(w.site.charger_writes()))
|
||||
homeview._LANG[0] = uitext.lang_of(lang)
|
||||
try:
|
||||
out = homeview.car_block(c, datetime.now(timezone.utc))
|
||||
t = out["why"] if out else "<no block>"
|
||||
except Exception as e: # noqa: BLE001
|
||||
t = f"<EXC {type(e).__name__} {e}>"
|
||||
finally:
|
||||
homeview._LANG[0] = "en"
|
||||
after = (snap(c), len(w.sim.log), list(w.drv.sent),
|
||||
len(w.site.charger_writes()))
|
||||
if before != after:
|
||||
W_BAD.append(t)
|
||||
return t
|
||||
|
||||
|
||||
def set_text(w, lang="en"):
|
||||
return exp(lang, "manual_set", a=f"{float(w.c.car_a):.0f}",
|
||||
phases=pw_l(lang, w.c.car_n))
|
||||
|
||||
|
||||
async def ready(phases, a, to, ramp=200.0, delay=1.0, shadow="off"):
|
||||
w = World(dict(CAR, shadow_mode=shadow), setpoint=a, phases=phases)
|
||||
await w.step(8)
|
||||
await w.act("car_phases", phases)
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", a)
|
||||
await w.step(8)
|
||||
w.sim.ramp_w_s, w.sim.stop_delay_s = ramp, delay
|
||||
await w.act("car_phases", to)
|
||||
return w
|
||||
|
||||
|
||||
async def t8():
|
||||
w = World(dict(CAR, shadow_mode="on"), setpoint=10, phases=3)
|
||||
await w.step(8)
|
||||
await w.act("car_phases", 3)
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", 16)
|
||||
await w.step(80)
|
||||
w.c.car_over = True
|
||||
w.c.peak_guard = G(floor_limited=True)
|
||||
return w, {lg: block_why(w, lg) for lg in LANGS}
|
||||
|
||||
|
||||
w8, t8w = run(t8())
|
||||
would_a = nth(w8.wr.would) if w8.wr.would else None
|
||||
check("T8: shadow world, Manual 16 A, car over: shadow-over text in en and "
|
||||
f"nl, no 'You set': {t8w}",
|
||||
w8.c.shadow and present(would_a) and w8.wr.would is not None
|
||||
and all(PEAK[lg] in t8w[lg] and YOU[lg] not in t8w[lg] for lg in LANGS)
|
||||
and t8w["en"] == exp("en", "manual_shadow_over",
|
||||
a=f"{float(w8.wr.would[0]):.0f}",
|
||||
phases=pw(w8.wr.would[1])))
|
||||
check("T8/N3: shadow world: no simulator log, no driver send, no charger "
|
||||
"write", w8.sim.log == [] and w8.drv.sent == []
|
||||
and w8.site.charger_writes() == [])
|
||||
|
||||
|
||||
async def gave_up(refuse_select):
|
||||
# 3 phases wanted -> the sim is on 1; or the other way, as EV-28's T11.
|
||||
w = await ready(3, 16, 1, ramp=(3000.0 if refuse_select else 200.0))
|
||||
if refuse_select:
|
||||
w.sim.request_phases = lambda n: False
|
||||
texts = {}
|
||||
await w.step(40)
|
||||
texts["try1"] = (w.wr.phases_gave_up, w.wr.phase_fails, block_why(w))
|
||||
await w.step(int(PHASE_GAP_S) + 60)
|
||||
await w.step(int(PHASE_GAP_S) + 60)
|
||||
texts["end"] = (w.wr.phases_gave_up, w.wr.phase_fails, block_why(w),
|
||||
block_why(w, "nl"))
|
||||
return w, texts
|
||||
|
||||
|
||||
for label, refuse in (("T11 the car keeps drawing", False),
|
||||
("T12 the select is refused", True)):
|
||||
w_, tt = run(gave_up(refuse))
|
||||
g1, f1, why1 = tt["try1"]
|
||||
ge, fe, whye, whyn = tt["end"]
|
||||
want = exp("en", "manual_phases", a="16", phases="1 phase",
|
||||
real="3 phases")
|
||||
check(f"{label}: after the 3rd failed try the Why is the E2 text "
|
||||
f"{whye!r}", ge and fe == 3 and whye == want
|
||||
and whyn == exp("nl", "manual_phases", a="16",
|
||||
phases=pw_l("nl", 1), real=pw_l("nl", 3))
|
||||
and w_.sim.phases_allowed == 3 and KEEPS["en"] not in whye)
|
||||
check(f"{label}: before the give-up (gap wait) it is manual_blocked "
|
||||
f"{why1!r}", not g1 and f1 >= 1
|
||||
and why1 == exp("en", "manual_blocked"))
|
||||
|
||||
# T19: another writer raises the current during a phase change.
|
||||
|
||||
|
||||
async def other_in_seq():
|
||||
w = World(CAR, setpoint=10, phases=1)
|
||||
w.sim.ramp_w_s, w.sim.stop_delay_s = 50.0, 40.0
|
||||
await w.step(60)
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", 10)
|
||||
await w.step(3)
|
||||
await w.act("car_phases", 3)
|
||||
await w.step(3)
|
||||
mid = (w.wr.seq is not None, block_why(w))
|
||||
w.sim.set_current(9)
|
||||
got = None
|
||||
for _ in range(60):
|
||||
await w.step(1)
|
||||
if w.wr.other:
|
||||
got = (block_why(w), block_why(w, "nl"))
|
||||
break
|
||||
return w, mid, got
|
||||
|
||||
|
||||
w19, mid19, got19 = run(other_in_seq())
|
||||
check("T19: during the sequence the Why is today's manual_set "
|
||||
f"{mid19[1]!r}", mid19[0] and mid19[1] == set_text(w19))
|
||||
check("T19: the first car_block after w.other turns True is the hold text "
|
||||
f"(en and nl): {got19!r}",
|
||||
got19 is not None and got19[0] == exp("en", "manual_other")
|
||||
and got19[1] == exp("nl", "manual_other")
|
||||
and YOU["en"] not in got19[0] and KEEPS["en"] not in got19[0]
|
||||
and STAYS["en"] not in got19[0])
|
||||
|
||||
|
||||
async def t27():
|
||||
w, _m, _g = await other_in_seq()
|
||||
await w.act("car_current", 12)
|
||||
await w.step(5)
|
||||
return w, block_why(w)
|
||||
|
||||
|
||||
w27, why27 = run(t27())
|
||||
okset = {set_text(w27), exp("en", "manual_blocked"),
|
||||
exp("en", "manual_phases", a="12", phases="3 phases",
|
||||
real="1 phase")}
|
||||
check(f"T27: the user changes the current: the hold is lifted and the hold "
|
||||
f"text is gone ({why27!r})", not w27.wr.hold
|
||||
and why27 != exp("en", "manual_other") and why27 in okset)
|
||||
|
||||
# T20 / T28: the other writer on equal phases.
|
||||
|
||||
|
||||
async def other_equal():
|
||||
w = World(CAR, setpoint=10, phases=1)
|
||||
await w.step(8)
|
||||
await w.act("car_phases", 1)
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", 10)
|
||||
await w.step(10)
|
||||
pre = block_why(w)
|
||||
t0 = w.t
|
||||
w.sim.set_current(8)
|
||||
before, first, secs = [], None, None
|
||||
for _ in range(60):
|
||||
await w.step(1)
|
||||
if w.wr.other:
|
||||
first, secs = block_why(w), w.t - t0
|
||||
break
|
||||
before.append(block_why(w))
|
||||
held_for = None
|
||||
w.sim.set_current(10)
|
||||
after = []
|
||||
for _ in range(40):
|
||||
await w.step(1)
|
||||
after.append((w.wr.hold, block_why(w)))
|
||||
if not w.wr.hold:
|
||||
break
|
||||
return w, pre, before, first, secs, after
|
||||
|
||||
|
||||
w20, pre20, before20, first20, secs20, after20 = run(other_equal())
|
||||
check("T20: before the hold the Why is today's manual_set, every step "
|
||||
f"({len(before20)} steps)", pre20 == set_text(w20) and before20
|
||||
and all(t == set_text(w20) for t in before20))
|
||||
check(f"T20: the hold text from the first call after w.other turns True, "
|
||||
f"{secs20} s after the write (<= WRITER_S + 5 = 35)",
|
||||
first20 == exp("en", "manual_other") and secs20 is not None
|
||||
and secs20 <= carmode.WRITER_S + 5.0)
|
||||
check("T28: the other writer puts the current back: the hold clears and the "
|
||||
"Why is manual_set in the same step",
|
||||
len(after20) >= 1 and not after20[-1][0]
|
||||
and after20[-1][1] == set_text(w20) and len(after20) <= 5)
|
||||
|
||||
# N2/N3 over every World call above.
|
||||
check(f"N2/N3: every car_block call in the World rows changed nothing and "
|
||||
f"sent nothing ({len(W_BAD)} did)", not W_BAD)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"{len(fails)} FAILED")
|
||||
sys.exit(1)
|
||||
print("all ok")
|
||||
@@ -1,344 +0,0 @@
|
||||
"""EV-15: the add-on's own phase change at the peak reserve raises no alarm.
|
||||
`python3 -B test_ev15.py`
|
||||
|
||||
The rig (EV-10 and EV-10b, F-2): cover on, the batteries at the reserve, the car
|
||||
charging and explaining the excess. The add-on's own 3 -> 1 phase switch sets
|
||||
the car to 0 A; with the car not charging its figure is no longer corroborated
|
||||
(`CarTracker.corroborated`), so `car_alarm_w()` is None, nothing is explained,
|
||||
and PEAK_GUARD_FLOOR_LIMITED plus `goodwe_peak_soc_floor` fire. The rule: for
|
||||
the add-on's own sequence only (`ctl_car._car_own_pause`, bounded) the car's
|
||||
fresh, not stuck figure stands in for grading.
|
||||
|
||||
1. The rig shapes end to end through the car cycle: 3 -> 1 and 1 -> 3.
|
||||
2. A house overload that starts during the sequence still alarms, as on Off.
|
||||
3. Aborted (Off, Stop, unplug), refused, an outside writer: no grace.
|
||||
4. The bounds, and the figure that stands in (stale, stuck: nothing).
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import ctl_car, carmode, chargers as CH # noqa: E402
|
||||
import ev04_peak as P # noqa: E402
|
||||
import safety81_sim as s81 # noqa: E402
|
||||
|
||||
logging.disable(logging.CRITICAL)
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
def at(t, fn):
|
||||
return {"t": t, "fn": fn}
|
||||
|
||||
|
||||
def beside(plant, c):
|
||||
"""The writer runs BESIDE the cycle, as in production (`car_kick`): its 1 s
|
||||
poll for the read-back lands after the cycle's own read, and the cycle does
|
||||
not wait for the writer (`ev04_peak.drive` does)."""
|
||||
gate = asyncio.Event()
|
||||
|
||||
async def sleep(_s):
|
||||
gate.clear()
|
||||
await gate.wait()
|
||||
|
||||
async def settle():
|
||||
gate.set()
|
||||
for _ in range(5):
|
||||
await asyncio.sleep(0)
|
||||
c.charger._sleep = sleep
|
||||
c.car_settle = settle
|
||||
|
||||
|
||||
def run(house, cap, t_res, t_sw, new, *, extra=None, mode="manual",
|
||||
sim_fn=None, dur=895, plug=True, side=False):
|
||||
"""Reserve at `t_res`, our phase change to `new` at `t_sw`. Returns the
|
||||
run, a per-second trace (second, own-pause, explains, red rows) and the
|
||||
alarms."""
|
||||
tr = []
|
||||
|
||||
def note(plant, c):
|
||||
red = [x["id"] for x in c.checks()
|
||||
if x["ok"] is False and not x["warn"]] \
|
||||
if t_sw - 5 <= plant.t <= t_sw + 90 else []
|
||||
g = c.peak_guard
|
||||
lim = bool(g is not None and (g.floor_limited or g.saturated))
|
||||
tr.append((plant.t, getattr(c, "_car_own_pause", lambda _t: False)(c.car_now()), c.car_explains,
|
||||
red, plant.ch.power_w, plant.ch.state, lim))
|
||||
|
||||
def reserve(plant, c):
|
||||
plant.soc = 19.0
|
||||
plant.load = lambda t: house + plant.ch.power_w
|
||||
|
||||
def switch(plant, c):
|
||||
asyncio.get_event_loop().create_task(
|
||||
c.handle_action("car_phases", value=new))
|
||||
|
||||
ev = {t: note for t in range(0, dur)}
|
||||
ev[t_res] = lambda p, c: (reserve(p, c), note(p, c))
|
||||
ev[t_sw] = lambda p, c: (switch(p, c), note(p, c))
|
||||
if side:
|
||||
ev[t_sw - 2] = lambda p, c: (beside(p, c), note(p, c))
|
||||
for t, fn in (extra or {}).items():
|
||||
prev = ev.get(t, note)
|
||||
ev[t] = (lambda p, c, prev=prev, fn=fn: (fn(p, c), prev(p, c)))
|
||||
sim = None
|
||||
if sim_fn is not None or side:
|
||||
from chargersim import SimCharger
|
||||
sim = SimCharger(setpoint_a=16)
|
||||
sim_fn = sim_fn or (lambda s: None)
|
||||
sim_fn(sim)
|
||||
r = P.drive(s81.constant(house), dur=dur, rating=12000.0, soc=60.0,
|
||||
cap=cap, phases=(3 if new == 1 else 1), user_a=16, setpoint=16,
|
||||
mode=mode, events=ev, sim=sim, plug=plug)
|
||||
return r, tr, P.ids(r, *P.ALARMS)
|
||||
|
||||
|
||||
def reds(tr):
|
||||
return [x for x in tr if x[3]]
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
print("1. THE RIG SHAPES THROUGH THE CAR CYCLE")
|
||||
# =========================================================================== #
|
||||
SHAPES = (
|
||||
("EV-10 shape: house 3 kW, car 11 kW, aim 6 kW, 3 -> 1",
|
||||
3000.0, 6050.0, 300, 600, 1),
|
||||
("EV-10b shape: a 9411 W limit, 3 -> 1", 2000.0, 9461.0, 300, 600, 1),
|
||||
("1 -> 3 (the car 3.7 kW, then 11 kW), aim 5 kW", 2500.0, 5050.0,
|
||||
100, 600, 3),
|
||||
)
|
||||
for name, house, cap, t_res, t_sw, new in SHAPES:
|
||||
r, tr, al = run(house, cap, t_res, t_sw, new)
|
||||
c, sim = r["c"], r["sim"]
|
||||
sw = [x for x in sim.writes() if x[1] == "phases"]
|
||||
check(f"{name}: the car at the reserve covers, and the add-on's own "
|
||||
f"sequence ran (0 A, select, the current back)",
|
||||
len(sw) == 1 and [x[2] for x in sim.writes("current")][-2:]
|
||||
== [0.0, 16.0] and sim.phases_allowed == new)
|
||||
pause = [x for x in tr if x[1]]
|
||||
check(f"{name}: the own-pause grace was on during it, and ended",
|
||||
len(pause) >= 10 and not any(x[1] for x in tr[-1:])
|
||||
and (pause[-1][0] - pause[0][0])
|
||||
<= getattr(ctl_car, "OWN_PAUSE_MAX_S", 0)
|
||||
+ getattr(ctl_car, "OWN_PAUSE_TAIL_S", 0))
|
||||
check(f"{name}: no PEAK_GUARD_FLOOR_LIMITED / saturated, no "
|
||||
f"goodwe_peak_soc_floor notification", al == [])
|
||||
check(f"{name}: no red row in any sample around the switch",
|
||||
reds(tr) == [])
|
||||
limited = [x for x in tr if x[1] and x[6]]
|
||||
check(f"{name}: in every cycle of the sequence in which the guard is "
|
||||
f"limited (the cycle of the rig's alarm among them) the car "
|
||||
f"explains it", len(limited) >= 1 and all(x[2] for x in limited)
|
||||
and any(x[2] for x in tr if x[0] == t_sw + 1))
|
||||
check(f"{name}: and in every limited cycle after it, to the quarter's end",
|
||||
all(x[2] for x in tr if x[0] >= t_sw and x[6]))
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n2. A HOUSE OVERLOAD DURING THE SEQUENCE STILL ALARMS")
|
||||
# =========================================================================== #
|
||||
def overload(plant, c):
|
||||
plant.load = lambda t: 25000.0 + plant.ch.power_w
|
||||
|
||||
|
||||
r, tr, al = run(3000.0, 6050.0, 300, 600, 1, extra={606: overload})
|
||||
ro, tro, alo = run(3000.0, 6050.0, 300, 600, 1, extra={606: overload},
|
||||
mode="off", plug=False)
|
||||
rn, trn, aln = run(3000.0, 6050.0, 300, 900, 1, extra={606: overload})
|
||||
check("PRECONDITION: on Off (no car) the same load alarms, and in Manual "
|
||||
"with no phase change", alo != [] and aln != [])
|
||||
check("a 25 kW house overload that starts 6 s into the sequence (the car "
|
||||
"paused): the alarm fires", al != [])
|
||||
print(f" alarm seconds: in the sequence {[t for t, _ in al]}, Off without "
|
||||
f"the car {[t for t, _ in alo]}, Manual with no phase change "
|
||||
f"{[t for t, _ in aln]}")
|
||||
check("...at the same second as on Off and as in Manual with no phase change",
|
||||
bool(al) and bool(alo) and bool(aln)
|
||||
and al[0][0] == alo[0][0] == aln[0][0])
|
||||
check("...and the car does not explain it (during the sequence too)",
|
||||
not any(x[2] for x in tr if 640 <= x[0] <= 660))
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n3. ABORTED, REFUSED, OUTSIDE: NO GRACE AFTER IT")
|
||||
# =========================================================================== #
|
||||
def hit(res, t0, secs):
|
||||
return [x for x in res if t0 <= x[0] <= t0 + secs and x[1]]
|
||||
|
||||
|
||||
def off_now(plant, c):
|
||||
asyncio.get_event_loop().create_task(c.handle_action("car_mode",
|
||||
value="off"))
|
||||
|
||||
|
||||
def stop_now(plant, c):
|
||||
c.auto = False
|
||||
|
||||
|
||||
def unplug(plant, c):
|
||||
plant.ch.unplug()
|
||||
|
||||
|
||||
slow = lambda s: setattr(s, "stop_delay_s", 8.0) # noqa: E731
|
||||
for what, fn in (("Off", off_now), ("Stop", stop_now), ("unplug", unplug)):
|
||||
r, tr, al = run(3000.0, 6050.0, 300, 600, 1, extra={602: fn},
|
||||
sim_fn=slow)
|
||||
check(f"{what} 2 s into the sequence: the grace is off from the next "
|
||||
f"cycle on", not hit(tr, 604, 200)
|
||||
and any(x[1] for x in tr if 600 <= x[0] <= 602))
|
||||
|
||||
def refuse_phases(sim):
|
||||
sim.request_phases = lambda n: False
|
||||
|
||||
|
||||
r, tr, al = run(3000.0, 6050.0, 300, 600, 1, sim_fn=refuse_phases)
|
||||
check("the select is refused: the grace ends at once (no cycle of it after "
|
||||
"the refusal), the current comes back",
|
||||
len([x for x in r["sim"].writes("current")]) >= 2
|
||||
and not hit(tr, 606, 200))
|
||||
|
||||
def outside_zero(plant, c):
|
||||
plant.ch.set_current(0.0)
|
||||
|
||||
|
||||
r2, tr2, al2 = run(3000.0, 6050.0, 300, 900, 1, extra={602: outside_zero})
|
||||
check("an outside writer's 0 A: no grace, and the normal grading (no car "
|
||||
"power: nothing explained) raises the alarm as before",
|
||||
not any(x[1] for x in tr2) and not any(x[2] for x in tr2
|
||||
if 610 <= x[0] <= 700)
|
||||
and al2 != [])
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n4. THE BOUNDS AND THE FIGURE THAT STANDS IN")
|
||||
# =========================================================================== #
|
||||
class _C(ctl_car.CarMixin):
|
||||
"""The mixin with just what `_car_own_pause` reads."""
|
||||
def __init__(self):
|
||||
self.o = {}
|
||||
self.car_init({}, type("S", (), {"data": {}, "set": lambda s, k, v: 0})())
|
||||
self.car_mode = carmode.MANUAL
|
||||
self.auto, self.shadow = True, False
|
||||
self.inverters, self.site_sign_wd = [], type("W", (), {"tripped": False})()
|
||||
self.circ_wd = type("W", (), {"tripped": False})()
|
||||
self.charger = type("H", (), {"configured": lambda s: True})()
|
||||
self.car = CH.CarTracker()
|
||||
self.car.reading = CH.ChargerReading(available=True, state="B")
|
||||
|
||||
|
||||
c = _C()
|
||||
c.car_writer.seq = {"stage": "settle", "t0": 100.0, "n": 1, "tries": 0,
|
||||
"prev": 16.0}
|
||||
M = ctl_car.OWN_PAUSE_MAX_S
|
||||
check("bound: the sequence's own maximum is its waits (0 A wait, settle, "
|
||||
"three tries at 15 s, the select) and no more",
|
||||
M == carmode.ZERO_WAIT_S + carmode.SETTLE_S + carmode.MAX_TRIES * 15.0
|
||||
+ 10.0 and ctl_car.OWN_PAUSE_TAIL_S == CH.CORR_WINDOW_S)
|
||||
check("bound: on at the 0 A write and up to the maximum",
|
||||
c._car_own_pause(100.0) and c._car_own_pause(100.0 + M))
|
||||
check("bound: off one second past it", not c._car_own_pause(101.0 + M))
|
||||
c.car_writer.seq = None
|
||||
c.car_writer.phase_done_at = 200.0
|
||||
T = ctl_car.OWN_PAUSE_TAIL_S
|
||||
check("bound: after the current is set again it lasts one corroboration "
|
||||
"window", c._car_own_pause(200.0 + T) and not c._car_own_pause(201.0 + T))
|
||||
c.car_writer.phase_done_at = None
|
||||
check("no sequence and none just done: no grace", not c._car_own_pause(100.0))
|
||||
c.car_writer.seq = {"stage": "settle", "t0": 100.0, "failed": True}
|
||||
check("a refused write marks the sequence: no grace", not c._car_own_pause(110.0))
|
||||
c.car_writer.seq = {"stage": "settle", "t0": 100.0}
|
||||
c.car_mode = carmode.OFF
|
||||
check("Off: no grace", not c._car_own_pause(110.0))
|
||||
c.car_mode, c.shadow = carmode.MANUAL, True
|
||||
check("shadow mode: no grace", not c._car_own_pause(110.0))
|
||||
c.shadow, c.auto = False, False
|
||||
check("control stopped: no grace", not c._car_own_pause(110.0))
|
||||
c.auto = True
|
||||
c.car_writer.hold = True
|
||||
check("another writer (hold): no grace", not c._car_own_pause(110.0))
|
||||
c.car_writer.hold = False
|
||||
c.car_writer.seq, c.car_writer.zero_sent_at = None, 100.0
|
||||
check("0 A sent, not yet back: grace from the send, to the maximum, no more",
|
||||
c._car_own_pause(100.0) and c._car_own_pause(100.0 + M)
|
||||
and not c._car_own_pause(101.0 + M))
|
||||
c.car_writer.zero_sent_at = None
|
||||
c.car_writer.phase_done_at = 200.0
|
||||
c.car_writer.hold = True
|
||||
check("another writer in the 60 s after the current is set: no grace",
|
||||
not c._car_own_pause(210.0))
|
||||
c.car_writer.hold, c.car_writer.phase_done_at = False, None
|
||||
c.car_writer.seq = {"stage": "settle", "t0": 100.0}
|
||||
c.car.reading = CH.ChargerReading(available=True, state="A")
|
||||
check("unplugged: no grace", not c._car_own_pause(110.0))
|
||||
c.car.reading = CH.ChargerReading(available=True, state="B")
|
||||
check("PRECONDITION: the same state is on", c._car_own_pause(110.0))
|
||||
|
||||
tk = CH.CarTracker()
|
||||
tk.reading = CH.ChargerReading(available=True, state="B", power_w=500.0,
|
||||
allowed_a=16.0, phases_allowed=1)
|
||||
tk.last_ok = 0.0
|
||||
check("the stand-in figure is the fresh reading, capped by the read-back",
|
||||
tk.car_w_paused(5.0) == 500.0 and tk.car_w_trusted(5.0) is None)
|
||||
check("a stale reading stands in for nothing", tk.car_w_paused(100.0) is None)
|
||||
tk.stuck_now = True
|
||||
check("a stuck reading stands in for nothing", tk.car_w_paused(5.0) is None)
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n5. THE WRITER RUNS BESIDE THE CYCLE (review F-1)")
|
||||
# =========================================================================== #
|
||||
# The car stops (state B) in the same Home Assistant update as the 0 A
|
||||
# read-back; the write has not returned yet, so no sequence exists. The window
|
||||
# opens when the write is SENT (`ManualWriter.zero_sent_at`).
|
||||
def lagged(lag, delay):
|
||||
def f(s):
|
||||
s.lag_s, s.stop_delay_s = lag, delay
|
||||
return f
|
||||
|
||||
|
||||
for lag, delay in ((2, 0), (0, 0), (2, 3), (5, 2)):
|
||||
r, tr, al = run(3000.0, 6050.0, 300, 600, 1, side=True,
|
||||
sim_fn=lagged(lag, delay))
|
||||
nm = f"beside the cycle, lag {lag} s, stop delay {delay} s"
|
||||
limited = [x for x in tr if x[0] >= 600 and x[6]]
|
||||
check(f"{nm}: our sequence ran (select once, then 16 A again)",
|
||||
len([x for x in r["sim"].writes("phases")]) == 1
|
||||
and r["sim"].phases_allowed == 1
|
||||
and [x[2] for x in r["sim"].writes("current")][-2:] == [0.0, 16.0])
|
||||
check(f"{nm}: no PEAK_GUARD_FLOOR_LIMITED, no goodwe_peak_soc_floor",
|
||||
al == [])
|
||||
check(f"{nm}: no red row, and the car explains every limited cycle",
|
||||
reds(tr) == [] and all(x[2] for x in limited))
|
||||
|
||||
|
||||
def not_taken(plant, c):
|
||||
plant.ch.refuse = "ignore" # HA accepts, the charger does nothing
|
||||
|
||||
|
||||
r, tr, al = run(3000.0, 6050.0, 300, 600, 1, side=True,
|
||||
sim_fn=lagged(0, 0), extra={600: not_taken})
|
||||
check("the 0 A write is not taken (read-back never follows): the window was "
|
||||
"open while it waited", any(x[1] for x in tr if 600 <= x[0] <= 606))
|
||||
own = [x[0] for x in tr if x[1]]
|
||||
runs = 1 + len([1 for a, b in zip(own, own[1:]) if b - a > 1])
|
||||
check("...and no grace after the refusal (the retry, RETRY_S later, opens it "
|
||||
"again only while that write waits: at most 3 runs of 11 s), no "
|
||||
"sequence made", not hit(tr, 613, 40) and r["c"].car_writer.seq is None
|
||||
and 1 <= runs <= 3 and len(own) <= 3 * 11)
|
||||
check("...the car went on charging and nothing was written but the 0 A",
|
||||
r["sim"].power_w > 5000.0 and not r["sim"].writes("phases"))
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"FAIL: {len(fails)} check(s)")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
sys.exit(1)
|
||||
print("ok: EV-15")
|
||||
@@ -1,538 +0,0 @@
|
||||
"""EV-16: the Car Why does not alternate between "are at {pct}" and "give all
|
||||
they can" while the car-over row holds and the guard's floor flag toggles.
|
||||
`python3 -B test_ev16.py`
|
||||
|
||||
Display only: the text is held by `ctl_car._car_why_tick` on the control
|
||||
cycle's clock (control writes `_car_why_rec`, never reads it; /status reads do
|
||||
not move it). `c._car_over_ep` is bumped when car_over ends; a record of
|
||||
another episode is never used.
|
||||
Mutant: pick the text from the live `floor_limited` again (T1, T2, T7, T8, T9
|
||||
go red).
|
||||
Mutating a module this file grades? Read MUTATION.md first.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import ctl_car, homeview, chargers as CH # noqa: E402
|
||||
import ev04_peak as P # noqa: E402
|
||||
import safety81_sim as s81 # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
OVER = "are at"
|
||||
FULL = "give all they can"
|
||||
Q = 900.0
|
||||
STEP = 5.0
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class G:
|
||||
floor_limited: bool = True
|
||||
soc: object = 20.0
|
||||
saturated: bool = False
|
||||
floor_w: float = 0.0
|
||||
able_w: object = None
|
||||
ceiling_w: float = 4500.0
|
||||
engaged: bool = True
|
||||
blind: object = None
|
||||
wanted_w: float = 300.0
|
||||
within_aim: bool = False
|
||||
|
||||
|
||||
class Proj:
|
||||
projected_w = 14500.0
|
||||
held_w = 14500.0
|
||||
elapsed_s = 400.0
|
||||
block_start = None
|
||||
|
||||
|
||||
class S(ctl_car.CarMixin):
|
||||
def __init__(self, cover=True):
|
||||
self.o = {"ev_batt_cover": cover}
|
||||
self._now = 0.0
|
||||
self.w = 11000.0
|
||||
self.site_batt_w, self.site_rating_w = 8100.0, 9600.0
|
||||
self.shadow, self.auto, self.peak_guard = False, True, None
|
||||
self.state = "charging"
|
||||
self.car_init({}, type("St", (), {"data": {}, "set": lambda s, k, v: 0})())
|
||||
self.car_over = True
|
||||
|
||||
def car_now(self):
|
||||
return self._now
|
||||
|
||||
def car_alarm_w(self):
|
||||
return self.w
|
||||
|
||||
@property
|
||||
def car(self):
|
||||
me = self
|
||||
|
||||
class _C:
|
||||
@staticmethod
|
||||
def status(*_a):
|
||||
return me.state
|
||||
return _C
|
||||
|
||||
|
||||
def why(c):
|
||||
return homeview._car_manual_why(c, "charging")
|
||||
|
||||
|
||||
def kind(t):
|
||||
return "over" if OVER in t else "full" if FULL in t else t
|
||||
|
||||
|
||||
def tick(c, g, t):
|
||||
"""One control cycle's display tick (what car_cycle ends with)."""
|
||||
c._now = t
|
||||
c.peak_guard = g
|
||||
c._car_why_tick(g, t)
|
||||
|
||||
|
||||
def run(c, secs, g_of, t0=0.0):
|
||||
"""Read the Why once per 5 s cycle; returns [(t, kind)]."""
|
||||
out = []
|
||||
t = t0
|
||||
while t < t0 + secs:
|
||||
tick(c, g_of(t - t0), t)
|
||||
out.append((t, kind(why(c))))
|
||||
t += STEP
|
||||
return out
|
||||
|
||||
|
||||
def changes(seq):
|
||||
return [i for i in range(1, len(seq)) if seq[i][1] != seq[i - 1][1]]
|
||||
|
||||
|
||||
def toggle(period, first=True):
|
||||
return lambda t: G(floor_limited=(int(t // period) % 2 == 0) == first)
|
||||
|
||||
|
||||
HOUSE = s81.constant(1100.0)
|
||||
|
||||
|
||||
def real_run(read, eventful=True):
|
||||
"""The T1 shape through the real controller: the batteries toggle across
|
||||
the reserve every 10 s. Returns the control digest, the per-cycle rows and
|
||||
flags, and the Why texts read (if `read`)."""
|
||||
texts, rows, flags = [], [], []
|
||||
|
||||
def ev(plant, c):
|
||||
plant.soc = 19.0 if int(plant.t // 10) % 2 == 0 else 60.0
|
||||
pg = c.peak_guard
|
||||
flags.append(None if pg is None else pg.floor_limited)
|
||||
rows.append(tuple((x["id"], x["ok"], x["warn"]) for x in c.checks()
|
||||
if x["id"] in ("peak_guard", "car_over")))
|
||||
if read and c.car_over:
|
||||
texts.append(homeview.car_block(c, None)["why"])
|
||||
r = P.drive(HOUSE, dur=900, events={k: ev for k in range(0, 900)},
|
||||
cap=3500.0)
|
||||
ctl = ([s[1:] for s in r["snaps"]], list(r["raised"]),
|
||||
r["sim"].writes(), r["sim"].setpoint_a)
|
||||
return ctl, rows, flags, texts
|
||||
|
||||
|
||||
def digest(x):
|
||||
return hashlib.sha256(repr(x).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
if "--digest" in sys.argv:
|
||||
ctl, rows, flags, _t = real_run(False)
|
||||
print("DIGEST control", digest(ctl), "rows", digest(rows),
|
||||
"flags", digest(flags))
|
||||
sys.exit(0)
|
||||
|
||||
print("1. the hold: a toggling flag shows one text")
|
||||
c = S()
|
||||
a = run(c, Q, toggle(10.0, True))
|
||||
check("T1 quarter starts floor-limited, toggles every 10 s: one distinct text",
|
||||
len({k for _, k in a}) == 1 and a[0][1] == "over")
|
||||
for per in (20.0, 30.0, 10.0):
|
||||
c = S()
|
||||
a = run(c, Q, toggle(per, False))
|
||||
check(f"T2 starts not limited, toggles every {per:.0f} s: at most one "
|
||||
f"change, none back", len(changes(a)) <= 1)
|
||||
c = S()
|
||||
a = run(c, Q, lambda t: G(floor_limited=False, soc=38.0))
|
||||
check("T3 never limited: 'give all they can' every cycle, never 'are at'",
|
||||
{k for _, k in a} == {"full"})
|
||||
c = S()
|
||||
a = run(c, Q, lambda t: G())
|
||||
check("T4 limited and steady: 'are at' 20 % from the first cycle",
|
||||
{k for _, k in a} == {"over"}
|
||||
and "20 %" in why(c))
|
||||
|
||||
print("\n2. real changes still show")
|
||||
c = S()
|
||||
a = run(c, 300.0, lambda t: G(floor_limited=False, soc=30.0))
|
||||
a += run(c, 600.0, lambda t: G(), t0=300.0)
|
||||
ch = changes(a)
|
||||
check("T5 full for 300 s then steady limited: one change, full -> over, "
|
||||
"within 185 s", len(ch) == 1 and a[ch[0]][1] == "over"
|
||||
and a[ch[0]][0] - 300.0 <= 185.0)
|
||||
c = S()
|
||||
a = run(c, 300.0, lambda t: G())
|
||||
a += run(c, 600.0, lambda t: G(floor_limited=False, soc=30.0), t0=300.0)
|
||||
ch = changes(a)
|
||||
check("T6 limited for 300 s then steady not limited: one change back to "
|
||||
"'give all they can' within 185 s", len(ch) == 1
|
||||
and a[ch[0]][1] == "full" and a[ch[0]][0] - 300.0 <= 185.0)
|
||||
for steady_false in (True, False):
|
||||
c = S()
|
||||
a = run(c, Q, toggle(10.0, True))
|
||||
a += run(c, Q, (lambda t: G(floor_limited=False, soc=30.0))
|
||||
if steady_false else (lambda t: G()), t0=Q)
|
||||
ch = changes(a)
|
||||
first_q = {k for t, k in a if t < Q}
|
||||
check(f"T7 toggling across the edge, new quarter steady "
|
||||
f"{'False' if steady_false else 'True'}: nothing before the edge, "
|
||||
f"at most one change near it, to the new state",
|
||||
len(first_q) == 1 and len(ch) <= 1
|
||||
and all(a[i][0] >= Q for i in ch)
|
||||
and len(a) > 0 and a[-1][1] == ("full" if steady_false else "over"))
|
||||
near = [i for i in ch if abs(a[i][0] - Q) <= 60.0]
|
||||
check("T7 (cont.) at most one change in the 60 s around the edge",
|
||||
len(near) <= 1)
|
||||
|
||||
print("\n3. failure modes")
|
||||
c = S()
|
||||
a = run(c, Q, lambda t: G(soc=None))
|
||||
check("T8 SoC unread, guard limited: never 'are at', one text",
|
||||
{k for _, k in a} == {"full"})
|
||||
c = S()
|
||||
a = run(c, Q, lambda t: G(soc=None if int(t // 10) % 2 == 0 else 20.0))
|
||||
check("T8 SoC toggling None / 20 % every 10 s, starting unread: one text, "
|
||||
"never 'are at'", {k for _, k in a} == {"full"})
|
||||
c = S()
|
||||
seq = []
|
||||
for t in range(0, 900, 5):
|
||||
tick(c, None if 400 <= t < 410 else G(floor_limited=(t // 10) % 2
|
||||
== 0), float(t))
|
||||
try:
|
||||
seq.append((t, kind(why(c))))
|
||||
except Exception as e: # noqa: BLE001
|
||||
seq.append((t, "TRACE " + repr(e)))
|
||||
check("T9 guard None for a cycle: no Traceback, one text through it",
|
||||
not any("TRACE" in k for _, k in seq) and len({k for _, k in seq}) == 1)
|
||||
c = S()
|
||||
tick(c, None, 0.0)
|
||||
check("T9 (cont.) guard None from the very first read: a text, no Traceback",
|
||||
kind(why(c)) in ("full", "over"))
|
||||
|
||||
# T10: the car stops, car_over drops after 180 s, a later episode
|
||||
c = S()
|
||||
run(c, 100.0, lambda t: G())
|
||||
check("T10 held 'are at' to start", kind(why(c)) == "over")
|
||||
for k in range(0, 200):
|
||||
c._now = 100.0 + k
|
||||
c.w = None
|
||||
c.car_cycle(Proj(), G(), 14000.0, None)
|
||||
check("T10 car_over dropped after the stop", c.car_over is False)
|
||||
check("T10 the Why left the over wording", OVER not in why(c)
|
||||
and FULL not in why(c))
|
||||
c.car_over = True # a new episode, later, SoC 60 %
|
||||
tick(c, G(floor_limited=False, soc=60.0), 5000.0)
|
||||
check("T10 the new episode shows 'give all they can' from its first cycle",
|
||||
kind(why(c)) == "full")
|
||||
|
||||
# T10b: no read between the drop and the new episode (the hold is cleared at
|
||||
# the drop, not at a read)
|
||||
c = S()
|
||||
run(c, 100.0, lambda t: G())
|
||||
for k in range(0, 200):
|
||||
c._now = 100.0 + k
|
||||
c.w = None
|
||||
c.car_cycle(Proj(), G(), 14000.0, None)
|
||||
c.car_over = True
|
||||
c.peak_guard = G(floor_limited=False, soc=60.0)
|
||||
c._now = 9000.0
|
||||
check("T10 no /status between the drop and the new episode: still 'full'",
|
||||
kind(why(c)) == "full")
|
||||
|
||||
# T11: unplug
|
||||
c = S()
|
||||
run(c, 100.0, lambda t: G())
|
||||
c._car_prev_state = "charging"
|
||||
c.state = CH.NONE_
|
||||
c._now = 105.0
|
||||
c.car_cycle(Proj(), G(), 14000.0, None)
|
||||
c.car_over = False
|
||||
check("T11 after the unplug cycle there is no over wording",
|
||||
OVER not in homeview._car_manual_why(c, "none")
|
||||
and FULL not in homeview._car_manual_why(c, "none")
|
||||
and "set when a car is connected" in homeview._car_manual_why(c, "none"))
|
||||
c.state = "charging"
|
||||
c.car_over = True
|
||||
tick(c, G(floor_limited=False, soc=60.0), 400.0)
|
||||
check("T11 a replug starts with no held text", kind(why(c)) == "full")
|
||||
# the hold is also gone when the unplug itself ends car_over (no read between)
|
||||
c = S()
|
||||
run(c, 100.0, lambda t: G())
|
||||
c._car_prev_state = "charging"
|
||||
c.state = CH.NONE_
|
||||
c._now = 105.0
|
||||
ep_before = c._car_over_ep
|
||||
c.car_cycle(Proj(), G(), 14000.0, None)
|
||||
check("T11 (cont.) the unplug ends the episode (control bumps it)",
|
||||
c.car_over is False and c._car_over_ep > ep_before)
|
||||
|
||||
# T12: cover off while car_over holds
|
||||
c = S()
|
||||
run(c, 100.0, lambda t: G())
|
||||
c.o["ev_batt_cover"] = False
|
||||
tick(c, G(), 105.0)
|
||||
check("T12 cover off: 'ignores the car' at the next read",
|
||||
"ignores the car" in why(c))
|
||||
c.o["ev_batt_cover"] = True
|
||||
tick(c, G(floor_limited=False, soc=60.0), 110.0)
|
||||
check("T12 cover on again, steady not limited: 'give all they can', not "
|
||||
"the old 'are at'", kind(why(c)) == "full")
|
||||
|
||||
# T13: restart
|
||||
c = S()
|
||||
a = run(c, 450.0, toggle(10.0, True))
|
||||
c2 = S()
|
||||
b = run(c2, 450.0, toggle(10.0, True), t0=450.0)
|
||||
check("T13 restart mid-quarter: no Traceback, a text, at most one change "
|
||||
"after", kind(why(c2)) in ("full", "over") and len(changes(b)) <= 1)
|
||||
|
||||
print("\n4. control unchanged; the rows follow the live flag")
|
||||
ctl1, rows1, flags1, sts = real_run(True)
|
||||
ctl0, rows0, flags0, _t = real_run(False)
|
||||
check("T14 reading the Why every cycle changes no command, alarm or row",
|
||||
ctl1 == ctl0 and rows1 == rows0 and flags1 == flags0)
|
||||
shown = [t for t in sts if OVER in t or FULL in t]
|
||||
flips = sum(1 for a, b in zip(flags1, flags1[1:]) if a != b)
|
||||
BASE_8150608 = ("e6034b0c78f23776", "5ffb80fa428cd6ee", "689a5b0e4bf7c897")
|
||||
check("T14/T15 commands, alarms, charger writes and the peak_guard/car_over "
|
||||
"rows equal those of base 8150608 (digests taken there with --digest)",
|
||||
(digest(ctl1), digest(rows1), digest(flags1)) == BASE_8150608)
|
||||
check("PRECONDITION: the real guard's floor flag toggles many times and "
|
||||
"car_over is on for most of the run", flips > 20 and len(shown) > 200)
|
||||
check("T1/T2 through the real guard: at most one Why change in the quarter",
|
||||
sum(1 for a, b in zip(shown, shown[1:]) if a != b) <= 1)
|
||||
check("T15 the peak_guard row follows the live flag (it changes as often as "
|
||||
"the flag), the hold is only in the Why",
|
||||
sum(1 for a, b in zip(rows1, rows1[1:]) if a != b) >= 1
|
||||
and len({r for r in rows1 if r}) >= 1)
|
||||
print(" DIGEST control", digest(ctl1), "rows", digest(rows1),
|
||||
"flags", digest(flags1))
|
||||
|
||||
print("\n5. text, hold and wiring")
|
||||
check("the hold equals the car_over row's own off hold",
|
||||
homeview.WHY_HOLD_S == ctl_car.OVER_OFF_HOLD_S)
|
||||
src = open(os.path.join(HERE, "app", "homeview.py")).read()
|
||||
check("the live flag is read only by the hold helper, not by the Why branch",
|
||||
'pg.floor_limited else' not in src)
|
||||
import json
|
||||
for lang, over, full in (
|
||||
("en", "You set {a} A. The batteries are at {pct}, so this charge "
|
||||
"sets the peak.",
|
||||
"You set {a} A. The batteries give all they can, so this charge "
|
||||
"sets the peak."),
|
||||
("nl", "U stelde {a} A in. De batterijen staan op {pct}, dus deze "
|
||||
"lading bepaalt de piek.",
|
||||
"U stelde {a} A in. De batterijen geven alles, dus deze lading "
|
||||
"bepaalt de piek.")):
|
||||
d = json.load(open(os.path.join(HERE, "app", "ui_text", lang + ".json")))
|
||||
d = d["home_words"]["car"]["why"]
|
||||
check(f"T17 {lang}.json wording of manual_over / manual_full unchanged",
|
||||
d["manual_over"] == over and d["manual_full"] == full)
|
||||
check("a held peak_guard row is not touched: the module still has no hold "
|
||||
"in ctl_status", "_car_why_rec" not in open(os.path.join(
|
||||
HERE, "app", "ctl_status.py")).read())
|
||||
|
||||
print("\n6. EV-16 review round 1: the race, T16, T18, the N-ids")
|
||||
# the race: a read takes the hold, control ends the episode, the read writes
|
||||
# its old hold back; the next episode must not show it
|
||||
c = S()
|
||||
run(c, 100.0, lambda t: G())
|
||||
stale = c._car_why_rec
|
||||
check("race: the read holds 'are at' before the end", kind(why(c)) == "over")
|
||||
for k in range(0, 200):
|
||||
c._now = 100.0 + k
|
||||
c.w = None
|
||||
c.car_cycle(Proj(), G(), 14000.0, None)
|
||||
c._car_why_rec = stale # the late write-back
|
||||
c.car_over = True
|
||||
c._now = 6000.0
|
||||
c.peak_guard = G(floor_limited=False, soc=60.0)
|
||||
check("N4 race: a read interleaved with the clear cannot bring the old "
|
||||
"'are at' into the next episode", kind(why(c)) == "full")
|
||||
c = S()
|
||||
run(c, 100.0, lambda t: G())
|
||||
stale = c._car_why_rec
|
||||
c._car_prev_state = "charging"
|
||||
c.state = CH.NONE_
|
||||
c._now = 105.0
|
||||
c.car_cycle(Proj(), G(), 14000.0, None)
|
||||
c._car_why_rec = stale # write-back after an unplug
|
||||
c.state = "charging"
|
||||
c.car_over = True
|
||||
c.peak_guard = G(floor_limited=False, soc=60.0)
|
||||
c._now = 110.0
|
||||
check("N4 race (unplug): a stale write-back after the unplug is not used",
|
||||
kind(why(c)) == "full")
|
||||
|
||||
# T16: the existing checks this one must leave alone are present and run in CI
|
||||
for f in ("test_ev04.py", "test_ev10.py", "test_ev10b.py", "test_ev18.py",
|
||||
"test_ev19.py", "test_home.py", "test_named_absence.py",
|
||||
"test_bytecode.py"):
|
||||
check(f"T16 {f} exists (run unchanged by CI's run-tests.sh)",
|
||||
os.path.exists(os.path.join(HERE, f)))
|
||||
t04 = open(os.path.join(HERE, "test_ev04.py")).read()
|
||||
check("T16 test_ev04's Manual Why assertion 'batteries give all they can' "
|
||||
"is still there", 'batteries give all they can" in cardwhy' in t04)
|
||||
|
||||
# T18: the mutant, in process: the live flag picks the text again
|
||||
real = homeview._over_why_is_floor
|
||||
homeview._over_why_is_floor = lambda c, pg: bool(
|
||||
pg is not None and pg.floor_limited)
|
||||
try:
|
||||
m = run(S(), Q, toggle(10.0, True))
|
||||
m8 = run(S(), Q, lambda t: G(soc=None))
|
||||
finally:
|
||||
homeview._over_why_is_floor = real
|
||||
check("T18 mutant (live flag): T1 shape alternates and T8 shows 'are at', so "
|
||||
"T1, T2, T7 and T8 would go red", len(changes(m)) > 20
|
||||
and any(k == "over" for _, k in m8))
|
||||
|
||||
# the N-ids, by name
|
||||
a = run(S(), Q, toggle(10.0, True))
|
||||
check("N1 control: batteries, charger writes and setpoint equal base "
|
||||
"(digests, section 4)", (digest(ctl1), digest(rows1), digest(flags1))
|
||||
== BASE_8150608)
|
||||
check("N2 `floor_limited`, `car_explains`, `car_over`, the peak_guard row "
|
||||
"are not changed by the hold: the guard flag toggles as in base "
|
||||
"(flags digest) and the rows digest equals base",
|
||||
digest(flags1) == BASE_8150608[2] and digest(rows1) == BASE_8150608[1])
|
||||
n3 = run(S(), Q, lambda t: G(soc=None)) + run(
|
||||
S(), Q, lambda t: G(floor_limited=False, soc=40.0))
|
||||
check("N3 never 'are at' with SoC unread or with the guard never limited",
|
||||
{k for _, k in n3} == {"full"})
|
||||
c = S()
|
||||
run(c, 100.0, lambda t: G())
|
||||
c.car_over = False
|
||||
n4 = homeview._car_manual_why(c, "charging")
|
||||
check("N4 no over wording once car_over is off", OVER not in n4
|
||||
and FULL not in n4)
|
||||
check("N5 at most one Why change in a quarter while the guard toggles",
|
||||
len(changes(a)) <= 1)
|
||||
try:
|
||||
for g in (None, G(soc=None), G(), G(floor_limited=False, soc=1.0)):
|
||||
c = S()
|
||||
c.peak_guard = g
|
||||
why(c)
|
||||
n6 = True
|
||||
except Exception: # noqa: BLE001
|
||||
n6 = False
|
||||
check("N6 no Traceback for a guard of None, SoC unread, limited, not "
|
||||
"limited", n6)
|
||||
en = open(os.path.join(HERE, "app", "ui_text", "en.json")).read()
|
||||
nl = open(os.path.join(HERE, "app", "ui_text", "nl.json")).read()
|
||||
check("N7 wording unchanged: the four texts are in the files verbatim",
|
||||
"The batteries are at {pct}, so this charge sets the peak." in en
|
||||
and "The batteries give all they can, so this charge sets the peak."
|
||||
in en and "De batterijen staan op {pct}, dus deze lading bepaalt de "
|
||||
"piek." in nl and "De batterijen geven alles, dus deze lading bepaalt "
|
||||
"de piek." in nl)
|
||||
|
||||
print("\n7. EV-16 review round 2: the hold runs on the control clock")
|
||||
|
||||
|
||||
def gap_run(c, g_of, read_at, end=2300.0):
|
||||
"""Control cycles every 5 s; the Why is read only at the `read_at` times."""
|
||||
out = []
|
||||
t = 0.0
|
||||
while t < end:
|
||||
tick(c, g_of(t), t)
|
||||
if any(a <= t < b for a, b in read_at):
|
||||
out.append((t, kind(why(c))))
|
||||
t += STEP
|
||||
return out
|
||||
|
||||
|
||||
pages = ((0, 60), (2000, 2300))
|
||||
c = S()
|
||||
r = gap_run(c, lambda t: G(floor_limited=t >= 300.0, soc=20.0), pages)
|
||||
late = [(t, k) for t, k in r if t >= 2000]
|
||||
check("review A: drained to the reserve while the page was closed: the "
|
||||
"first read at t=2000 already shows 'are at'",
|
||||
len(late) > 0 and late[0][1] == "over" and {k for _, k in late} == {"over"})
|
||||
c = S()
|
||||
r = gap_run(c, lambda t: G(floor_limited=t < 300.0,
|
||||
soc=20.0 if t < 300.0 else 45.0), pages)
|
||||
late = [(t, k) for t, k in r if t >= 2000]
|
||||
check("review B: off the reserve while the page was closed: the first "
|
||||
"read at t=2000 shows 'give all they can', never a false 'are at'",
|
||||
len(late) > 0 and late[0][1] == "full" and {k for _, k in late} == {"full"})
|
||||
c = S()
|
||||
r = []
|
||||
for t in range(0, 400, 5):
|
||||
cov = not (100 <= t < 200)
|
||||
c.o["ev_batt_cover"] = cov
|
||||
tick(c, G(floor_limited=t < 100, soc=20.0 if t < 100 else 45.0),
|
||||
float(t))
|
||||
if t in (95, 205):
|
||||
r.append(kind(why(c)))
|
||||
check("review: cover off and on with no read between: back on, the state "
|
||||
"now not limited shows 'give all they can' at the first read",
|
||||
r == ["over", "full"])
|
||||
# lower bound of the hold: a real change is NOT shown before the hold ends
|
||||
c = S()
|
||||
r = []
|
||||
for t in range(0, 600, 5):
|
||||
tick(c, G(floor_limited=t >= 300.0, soc=20.0), float(t))
|
||||
r.append((t, kind(why(c))))
|
||||
check("review: a real change is held for the full 180 s: still the old "
|
||||
"text 170 s after it, the new one by 185 s",
|
||||
dict(r)[470] == "full" and dict(r)[485] == "over")
|
||||
# M7: guard None for 180 s or more under car_over
|
||||
for steady, want in ((True, "over"), (False, "full")):
|
||||
c = S()
|
||||
seq = []
|
||||
for t in range(0, 1200, 5):
|
||||
g = G(floor_limited=steady, soc=20.0 if steady else 45.0) \
|
||||
if t < 100 else None
|
||||
tick(c, g, float(t))
|
||||
seq.append(kind(why(c)))
|
||||
check(f"T9 (long) guard None for 1100 s after a steady "
|
||||
f"{'limited' if steady else 'not limited'} state: the text stays "
|
||||
f"'{want}', no flip", set(seq) == {want})
|
||||
c = S()
|
||||
seq = []
|
||||
for t in range(0, 1200, 5):
|
||||
tick(c, None, float(t))
|
||||
seq.append(kind(why(c)))
|
||||
check("T9 (long) guard None from the start for 1200 s: one text, 'full'",
|
||||
set(seq) == {"full"})
|
||||
# review round 2: the live fallback (no record yet, or one of an ended
|
||||
# episode) keeps the unread-SoC rule too
|
||||
for label, rec in (("no record yet", None),
|
||||
("a record of an ended episode", [True, None, -1])):
|
||||
c = S()
|
||||
c._now = 0.0
|
||||
c._car_why_rec = rec
|
||||
c.peak_guard = G(soc=None)
|
||||
check(f"N3 {label}: limited with SoC unread is not 'are at'",
|
||||
kind(why(c)) == "full")
|
||||
c.peak_guard = G()
|
||||
check(f"N3 {label}: limited with SoC read shows 'are at' (live state)",
|
||||
kind(why(c)) == "over")
|
||||
|
||||
print()
|
||||
print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed")
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -1,832 +0,0 @@
|
||||
"""EV-18: no floor alarm at a quarter's start while the car explains the excess
|
||||
(EV-15 rig F-A). `python3 -B test_ev18.py`
|
||||
|
||||
The rig: both batteries at the peak reserve, the car charging, and
|
||||
PEAK_GUARD_FLOOR_LIMITED + `goodwe_peak_soc_floor` at a quarter's start, red
|
||||
for most of the quarter, while the grid excess was smaller than the car. Two
|
||||
causes, both latched for the quarter by `_car_need_excl`:
|
||||
C1 one cycle with no trusted car figure set the latch (T1);
|
||||
C2 "without the car" assumed the batteries give 0 W from now on, so what
|
||||
the loop still gives below the reserve counted as house (T2).
|
||||
The rule now (owner 2026-11-19, Q1-Q3): without the car the batteries keep
|
||||
giving what they give now (the lower of the last two readings, re-checked
|
||||
every cycle); a house need seen with a trusted car figure stays latched to the
|
||||
quarter's end; an unknown car figure keeps the alarm only while it is unknown.
|
||||
|
||||
T-ids are the test plan's (reports/EV-18-test-plan.md). "base" is 9fdce02.
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import chargers as CH, ctl_car, tariff # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
from named_absence import first, nth, present # noqa: E402
|
||||
import ev04_peak as P # noqa: E402
|
||||
import ev18_peak as H # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
AIM = H.AIM
|
||||
CAR = 1380.0
|
||||
E = H.E
|
||||
# Measured on base 9fdce02 with this file's own runs: the seconds of
|
||||
# goodwe_peak_soc_floor in the honest shapes, which must not come later now. An
|
||||
# honest shape steps the house at E, and the meter shows it at E+1.
|
||||
T5_BASE = [E + 1] # also T6 (T5 shape), T8, T9(a), T10(b) T5
|
||||
T7_BASE = E + 72
|
||||
T9B_BASE = [] # 400 W real: never uncorroborated (Findings)
|
||||
T9C_BASE = E + 1 # 100 W real: never trusted at the edge
|
||||
T10A_T5_BASE = [E + 2] # the guard disengages at E+1 (no battery reading)
|
||||
T11_BASE = [E + 13] # SAFETY-87: ALARM_HOLD_S after the step
|
||||
T13_BASE = [E + 301]
|
||||
T15_T5_BASE = [E + 10] # x10: one cycle
|
||||
|
||||
# =========================================================================== #
|
||||
print("1. UNIT: car_cycle ACROSS A QUARTER EDGE (a real `_carq`, not preset)")
|
||||
# =========================================================================== #
|
||||
BS = datetime(2026, 11, 17, 21, 15, tzinfo=timezone.utc) # the edge E
|
||||
|
||||
|
||||
class _Car(ctl_car.CarMixin):
|
||||
def __init__(self):
|
||||
self.o = {"ev_batt_cover": True}
|
||||
self.w = CAR
|
||||
self._now = 0.0
|
||||
self.site_batt_w, self.site_rating_w = 0.0, 9600.0
|
||||
self.store = type("S", (), {"data": {}, "set": lambda s, k, v: 0})()
|
||||
self.car_init({}, self.store)
|
||||
|
||||
def car_now(self):
|
||||
return self._now
|
||||
|
||||
def car_alarm_w(self):
|
||||
return self.w
|
||||
|
||||
class car: # noqa: N801
|
||||
@staticmethod
|
||||
def status(*_a):
|
||||
return "charging"
|
||||
|
||||
|
||||
class _G:
|
||||
"""Floor-limited, the floor leaves nothing (floor_w 0), wants power."""
|
||||
def __init__(self, wants=True, within_aim=False):
|
||||
self.floor_limited, self.saturated = True, False
|
||||
self.floor_w, self.able_w, self.ceiling_w = 0.0, None, AIM + 50.0
|
||||
self.engaged, self.blind = True, None
|
||||
self.wanted_w = 300.0 if wants else 0.0
|
||||
self.within_aim = within_aim
|
||||
|
||||
|
||||
def urun(secs, grid, batt, w, *, x=1, mono_x=None, c=None, guard=None):
|
||||
"""`car_cycle` once per entry of `secs` (seconds from the edge E, `x` fake
|
||||
seconds apart). `grid(t)` is the meter (house + car - batteries),
|
||||
`batt(t)` the site battery reading, `w(t)` the trusted car figure. Returns
|
||||
(car, {t: car_explains})."""
|
||||
c = c or _Car()
|
||||
mono_x = x if mono_x is None else mono_x
|
||||
done, out = {}, {}
|
||||
t0 = nth(list(secs), 0)
|
||||
if c._carq["key"] is None and present(t0) and t0 % 900:
|
||||
# started mid-quarter: the car was counted since its start (no restart)
|
||||
c._carq.update(key=BS + timedelta(seconds=900 * (t0 // 900)),
|
||||
ws=float(w(t0) or 0.0) * (t0 % 900), ws_p=0.0)
|
||||
for t in secs:
|
||||
q = t // 900
|
||||
bs, el = BS + timedelta(seconds=900 * q), t - 900 * q
|
||||
g = float(grid(t))
|
||||
d = done.get(bs, g * el)
|
||||
p = tariff.Projection(
|
||||
projected_w=(d + g * (900 - el)) / 900.0,
|
||||
elapsed_w=(d / el if el else g), elapsed_s=float(el),
|
||||
covered_frac=1.0, complete=False, block_start=bs, held_w=g)
|
||||
done[bs] = d + g * x
|
||||
c._now = 10000.0 + t * mono_x / x
|
||||
c.w, c.site_batt_w = w(t), batt(t)
|
||||
c.car_cycle(p, guard(t) if guard else _G(), AIM, None)
|
||||
out[t] = c.car_explains
|
||||
return c, out
|
||||
|
||||
|
||||
def const(v):
|
||||
return lambda t: v
|
||||
|
||||
|
||||
def run_of(d, t0, t1):
|
||||
return [d[t] for t in sorted(d) if t0 <= t <= t1]
|
||||
|
||||
|
||||
# --- T1: the car figure untrusted for the edge's first cycles --------------- #
|
||||
def t1(x=1, mono_x=None):
|
||||
_c, ex = urun(range(-30, 121, x), const(13000.0 + CAR), const(0.0),
|
||||
lambda t: None if 0 <= t <= 2 * x else CAR, x=x,
|
||||
mono_x=mono_x)
|
||||
return ex
|
||||
|
||||
|
||||
ex = t1()
|
||||
print(f" T1 explains E-1..E+5: {run_of(ex, -1, 5)}")
|
||||
check("T1 PRECONDITION: before the edge the car (trusted) explains the "
|
||||
"excess (house 13 000 W, car 1 380 W, grid 14 380 W)",
|
||||
all(run_of(ex, -30, -1)) and len(run_of(ex, -30, -1)) == 30)
|
||||
check("T1 (Expected 5): while the car figure is unknown (E+0..E+2) it "
|
||||
"explains nothing, so the alarm stands", not any(run_of(ex, 0, 2)))
|
||||
_c1b, ex1b = urun(range(-30, 121), const(12500.0 + CAR - 800.0), const(800.0),
|
||||
lambda t: None if 0 <= t <= 2 else CAR)
|
||||
check("T1b (the EV-10 path: the grid lands under the aim, the batteries at "
|
||||
"0 W would miss; house 12 500 W, b 800 W): unknown E+0..E+2, released "
|
||||
"at E+3 and explained to E+120",
|
||||
not any(run_of(ex1b, 0, 2)) and all(run_of(ex1b, 3, 120))
|
||||
and len(run_of(ex1b, 3, 120)) == 118)
|
||||
check("T1 (Expected 3): released at the first trusted cycle (E+3) and "
|
||||
"explained to E+120 (base: latched False to E+120)",
|
||||
all(run_of(ex, 3, 120)) and len(run_of(ex, 3, 120)) == 118)
|
||||
|
||||
# --- T2c: the battery W boundary, graded on the lower of two readings ------- #
|
||||
def t2c(b_of):
|
||||
_c, ex = urun(range(0, 6), lambda t: 14000.0 + CAR - b_of(t), b_of,
|
||||
const(CAR))
|
||||
return run_of(ex, 0, 5)
|
||||
|
||||
|
||||
e391, e389 = t2c(const(391.0)), t2c(const(389.0))
|
||||
e395 = t2c(lambda t: 395.0 if t == 0 else 385.0)
|
||||
print(f" T2c 391 W {e391}, 389 W {e389}, 395 then 385 W {e395}")
|
||||
check("T2c: b steady at 391 W (house alone with the real batteries lands "
|
||||
"13 609 W, aim + 9 W): the car explains from E+0", all(e391)
|
||||
and len(e391) == 6)
|
||||
check("T2c: b at 389 W (13 611 W, aim + 11 W): it does not, from E+0",
|
||||
not any(e389) and len(e389) == 6)
|
||||
check("T2c: readings 395 then 385 W: graded on 385 W, no explanation from "
|
||||
"the second cycle on", not any(e395[1:]) and len(e395) == 6)
|
||||
# review round 1 (MD): the meter shows the higher output while the readings
|
||||
# are 389 W then 800 W. b gives 800 W; one reading of 389 W at E+3, the meter
|
||||
# still at 800 W. House 14 005 W: at E+4 the house latch grades on the lower
|
||||
# reading (389 W), rest 13 616 W, landing 13 614 W > aim + 10 W; on the
|
||||
# current one (800 W) it would be 13 205 W.
|
||||
_cl, elag = urun(range(0, 12), const(14005.0 + CAR - 800.0),
|
||||
lambda t: 389.0 if t == 3 else 800.0, const(CAR))
|
||||
print(f" T2c lagging meter E+0..E+11: {run_of(elag, 0, 11)}")
|
||||
check("T2c (meter lags, readings 389 then 800 W): explained before, the "
|
||||
"house latch sets on the lower reading at E+4 and holds to E+11",
|
||||
all(run_of(elag, 0, 3)) and not any(run_of(elag, 4, 11))
|
||||
and len(run_of(elag, 4, 11)) == 8)
|
||||
|
||||
# --- T4: ALARM_MISS_W, batteries at 0 W -------------------------------------- #
|
||||
e09 = run_of(urun(range(0, 6), const(13609.0 + CAR), const(0.0),
|
||||
const(CAR))[1], 0, 5)
|
||||
e11 = run_of(urun(range(0, 6), const(13611.0 + CAR), const(0.0),
|
||||
const(CAR))[1], 0, 5)
|
||||
check("T4 unit: the house alone at aim + 9 W: the car explains from E+0; at "
|
||||
"aim + 11 W it does not", all(e09) and len(e09) == 6 and not any(e11))
|
||||
|
||||
# --- T8 / N2: 0 W and tiny cars ---------------------------------------------- #
|
||||
e0 = run_of(urun(range(-5, 30), const(14000.0 - 800.0), const(800.0),
|
||||
const(0.0))[1], -5, 29)
|
||||
e50 = run_of(urun(range(-5, 30), const(14090.0 + 50.0), const(0.0),
|
||||
const(50.0))[1], -5, 29)
|
||||
check("T8 unit: a 0 W car never explains, whatever the batteries give (T2 "
|
||||
"shape, b 800 W)", not any(e0) and len(e0) == 35)
|
||||
check("T8 unit: a 50 W car with the house at 14 090 W never explains",
|
||||
not any(e50) and len(e50) == 35)
|
||||
# N2: a car that drew 11 kW earlier in the quarter and now reports 0 W
|
||||
c0, ex0 = urun(range(0, 400), lambda t: 2600.0 + (11040.0 if t < 300 else 0.0),
|
||||
const(0.0), lambda t: 11040.0 if t < 300 else 0.0)
|
||||
check("N2: a trusted 0 W figure explains nothing, also after the car drew "
|
||||
"earlier in the quarter", not any(run_of(ex0, 300, 399)))
|
||||
|
||||
# --- T8 unit: a car known to draw nothing is not an unknown car ------------- #
|
||||
class _Tracker:
|
||||
"""The two things `_car_idle` reads: the reading, and its fresh power."""
|
||||
def __init__(self, available):
|
||||
self.reading = CH.ChargerReading(available=available, state="B",
|
||||
charging=False, power_w=0.0)
|
||||
|
||||
def car_w(self, _now):
|
||||
return 0.0 if self.reading.available else None
|
||||
|
||||
@staticmethod
|
||||
def status(*_a):
|
||||
return "charging"
|
||||
|
||||
|
||||
def idle_then_charging(available):
|
||||
c = _Car()
|
||||
c.car = _Tracker(available)
|
||||
_c, ex = urun(range(0, 900),
|
||||
lambda t: 14090.0 if t < 60 else 13000.0 + CAR, const(0.0),
|
||||
lambda t: None if t < 60 else CAR, c=c)
|
||||
return ex
|
||||
|
||||
|
||||
exi, exu = idle_then_charging(True), idle_then_charging(False)
|
||||
check("T8 unit: a car known idle (mode3 B, 0 W, fresh) while the house alone "
|
||||
"misses (14 090 W): that house need is latched, so the car charging "
|
||||
"from E+60 does not explain the quarter (test_ev10's `swapped` case)",
|
||||
not any(run_of(exi, 0, 899)))
|
||||
check("T8 unit: the same with the charger unavailable (unknown car): the "
|
||||
"alarm stands while unknown and is released at E+60 (Expected 5)",
|
||||
not any(run_of(exu, 0, 59)) and all(run_of(exu, 60, 899)))
|
||||
|
||||
# --- the contradiction latch (owner 2026-11-19), unit ----------------------- #
|
||||
class _TrackerC:
|
||||
"""A charging car whose energy meter contradicts it when `contra(t)`."""
|
||||
def __init__(self, contra):
|
||||
self.contra = contra
|
||||
self.reading = CH.ChargerReading(available=True, state="C",
|
||||
charging=True, power_w=CAR)
|
||||
|
||||
def car_w(self, _now):
|
||||
return CAR
|
||||
|
||||
def stuck(self, _now):
|
||||
return False
|
||||
|
||||
def contradicted(self, now):
|
||||
return self.contra(now - 10000.0)
|
||||
|
||||
def car_w_paused(self, _now):
|
||||
return CAR
|
||||
|
||||
@staticmethod
|
||||
def status(*_a):
|
||||
return "charging"
|
||||
|
||||
|
||||
class _CarC(_Car):
|
||||
def __init__(self, contra, own):
|
||||
super().__init__()
|
||||
self.car, self.own = _TrackerC(contra), own
|
||||
|
||||
def car_manual(self):
|
||||
return True
|
||||
|
||||
def _car_own_pause(self, mono):
|
||||
return self.own(mono - 10000.0)
|
||||
|
||||
|
||||
def contra_run(contra, own, secs):
|
||||
c = _CarC(contra, own)
|
||||
_c, ex = urun(secs, const(13000.0 + CAR), const(0.0),
|
||||
lambda t: None if contra(t) or own(t) else CAR, c=c)
|
||||
return ex
|
||||
|
||||
|
||||
never = lambda t: False # noqa: E731
|
||||
exg = contra_run(lambda t: 300 <= t < 306, never, range(0, 1100))
|
||||
check("contradiction (T3 shape): the meter contradicts the figure at E+300: "
|
||||
"not explained from E+300 to the quarter's end, though trusted again "
|
||||
"from E+306", all(run_of(exg, 0, 299)) and not any(run_of(exg, 300, 899))
|
||||
and len(run_of(exg, 300, 899)) == 600)
|
||||
check("contradiction: released by the next quarter (review MG): explained "
|
||||
"again from E+900", all(run_of(exg, 900, 1099))
|
||||
and len(run_of(exg, 900, 1099)) == 200)
|
||||
exf = contra_run(lambda t: 100 <= t < 130, lambda t: 100 <= t < 130,
|
||||
range(0, 400))
|
||||
check("contradiction during our own pause (EV-15) latches nothing (review "
|
||||
"MF): the stand-in explains in it, the trusted figure after it",
|
||||
all(run_of(exf, 0, 399)) and len(run_of(exf, 0, 399)) == 400)
|
||||
|
||||
# --- T10(a) unit: the battery reading lost for one cycle --------------------- #
|
||||
cA, eA = urun(range(-3, 10), const(14000.0 + CAR - 800.0),
|
||||
lambda t: None if t == 1 else 800.0, const(CAR))
|
||||
check("T10(a) unit, T2 shape: the cycle with no battery reading explains "
|
||||
"nothing (no last-known W credited); the next ones do",
|
||||
eA.get(1) is False and eA.get(0) is True and all(run_of(eA, 2, 9))
|
||||
and len(run_of(eA, 2, 9)) == 8)
|
||||
|
||||
# --- T13 unit: a house need seen with a trusted car stays latched ----------- #
|
||||
c13, e13 = urun(range(-5, 1000),
|
||||
lambda t: (15500.0 if 300 <= t < 360 else 13000.0) + CAR,
|
||||
const(0.0), const(CAR))
|
||||
check("T13 unit: the house steps to 15 500 W at E+300 for 60 s (landing "
|
||||
"without the car 14 667 W): not explained from E+300 to the quarter's "
|
||||
"end, though the house is back at 13 000 W from E+360",
|
||||
all(run_of(e13, 0, 299)) and not any(run_of(e13, 300, 899))
|
||||
and len(run_of(e13, 300, 899)) == 600)
|
||||
check("T13 unit: ...and released by the new quarter", all(run_of(e13, 900, 999)))
|
||||
c13g, e13g = urun(range(0, 400),
|
||||
lambda t: (15500.0 if 100 <= t < 160 else 13000.0) + CAR,
|
||||
const(0.0), const(CAR),
|
||||
guard=lambda t: _G(wants=not (t == 250)))
|
||||
check("T13 unit: ...or by the guard no longer wanting power (EV-10)",
|
||||
not any(run_of(e13g, 100, 249)) and all(run_of(e13g, 251, 399)))
|
||||
|
||||
# --- T14: no flicker --------------------------------------------------------- #
|
||||
def floor_edges(ex):
|
||||
"""Per quarter, False -> True edges of the floor alarm the stub implies
|
||||
(floor-limited, within_aim False, not explained)."""
|
||||
out, was = {}, False
|
||||
for t in sorted(ex):
|
||||
al = not ex[t]
|
||||
if al and not was:
|
||||
out[t // 900] = out.get(t // 900, 0) + 1
|
||||
was = al
|
||||
return out
|
||||
|
||||
|
||||
_ca, eta = urun(range(0, 1200),
|
||||
lambda t: 13610.0 + (40.0 if int(t // 7) % 2 else -40.0) + CAR,
|
||||
const(0.0), const(CAR))
|
||||
_cb, etb = urun(range(0, 1200),
|
||||
lambda t: 14000.0 + CAR - (400.0 if int(t // 7) % 2 else 800.0),
|
||||
lambda t: 400.0 if int(t // 7) % 2 else 800.0, const(CAR))
|
||||
fa, fb = floor_edges(eta), floor_edges(etb)
|
||||
print(f" T14 alarm edges per quarter: (a) {fa} (b) {fb}")
|
||||
check("T14(a): the house alone straddles aim + 10 W by 40 W every 7 s: at "
|
||||
"most one alarm edge per quarter", all(v <= 1 for v in fa.values()))
|
||||
check("T14(b): T2 shape with b alternating 400 / 800 W every 7 s: no alarm "
|
||||
"edge at all (base: one per quarter)", fb == {})
|
||||
|
||||
# --- T15 unit: x10 ------------------------------------------------------------ #
|
||||
ex10 = t1(x=10)
|
||||
check("T15 unit x10 (wall and mono 10 s a cycle): T1 the same; released "
|
||||
"within 1 cycle (E+30, the first trusted cycle)",
|
||||
not any(run_of(ex10, 0, 20)) and all(run_of(ex10, 30, 120))
|
||||
and all(run_of(ex10, -30, -10)))
|
||||
ex10m = t1(x=10, mono_x=1)
|
||||
check("T15 unit, mono x1 and wall x10: the same verdicts (the edge comes from "
|
||||
"the projection's block_start, not from mono)",
|
||||
not any(run_of(ex10m, 0, 20)) and all(run_of(ex10m, 30, 120)))
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n2. THE REAL CONTROLLER ACROSS THE EDGE (N=2, both at the reserve)")
|
||||
# =========================================================================== #
|
||||
|
||||
|
||||
RUNS = [] # (name, alarm edges) of every run, for N5
|
||||
|
||||
|
||||
def summary(name, r, tr):
|
||||
RUNS.append((name, H.edges(tr)))
|
||||
w = H.window(tr, E - 120, E + 900)
|
||||
lim = [x for x in w if x["lim"]]
|
||||
print(f" {name}: alarms {[t - E for t in H.alarms(r)]} edges "
|
||||
f"{[t - E for t in H.edges(tr)]} red {len(H.red_secs(tr))} s "
|
||||
f"(first {[t - E for t in H.red_secs(tr)[:1]]}) errors "
|
||||
f"{len(H.errors(tr))} limited {len(lim)} explained "
|
||||
f"{sum(1 for x in lim if x['explains'])} cmd {H.commands(r, tr)}")
|
||||
return w, lim
|
||||
|
||||
|
||||
def quiet(r, tr):
|
||||
"""No floor notification, no ERROR, no red peak_guard row, E-120..E+900."""
|
||||
return H.alarms(r) == [] and H.red_secs(tr) == [] and H.errors(tr) == []
|
||||
|
||||
|
||||
def all_explained(lim, t0=E - 120):
|
||||
return bool(lim) and all(x["explains"] for x in lim if x["t"] >= t0)
|
||||
|
||||
|
||||
ZERO = const(0.0)
|
||||
|
||||
|
||||
def honest(w):
|
||||
"""An honest shape steps at the edge, so Off has no alarm before it."""
|
||||
return H.shape(w, at=E)
|
||||
|
||||
# --- T2: the rig F-A shape ---------------------------------------------------- #
|
||||
r2, tr2 = H.run(H.shape(14000.0), a=ZERO, b=const(800.0))
|
||||
w2, lim2 = summary("T2", r2, tr2)
|
||||
check("T2 PRECONDITION: limited at the reserve from the edge, the car trusted, "
|
||||
"b 800 W, grid excess 980 W < car",
|
||||
present(first(x for x in w2 if x["t"] == E and x["lim"]))
|
||||
and all(x["w"] == CAR and x["batt"] == 800.0 for x in lim2))
|
||||
check("T2: no goodwe_peak_soc_floor, no PEAK_GUARD_FLOOR_LIMITED ERROR, no "
|
||||
"red peak_guard row in E-120..E+900 (base: alarm at E+0, red to E+900)",
|
||||
quiet(r2, tr2))
|
||||
check("T2: the car explains every floor-limited cycle, E+0..E+10 among them",
|
||||
all_explained(lim2) and len([x for x in lim2 if x["t"] <= E + 10]) == 11)
|
||||
|
||||
# --- T2b: the batteries give less later --------------------------------------- #
|
||||
r2i, tr2i = H.run(H.shape(14000.0), a=ZERO,
|
||||
b=lambda t: 800.0 if t < E + 300 else 0.0)
|
||||
summary("T2b(i)", r2i, tr2i)
|
||||
a2i = H.alarms(r2i)
|
||||
check("T2b(i): b drops to 0 W at E+300 (landing without the car 13 733 W): "
|
||||
"the alarm fires within 1 cycle of E+300",
|
||||
len(a2i) == 1 and E + 300 <= nth(a2i, 0) <= E + 301)
|
||||
check("T2b(i): ...and stays to the quarter's end (a house need with a "
|
||||
"trusted car is latched)", all(x["alarm"] and x["red"] for x in
|
||||
H.window(tr2i, E + 302, E + 899)))
|
||||
r2ii, tr2ii = H.run(H.shape(14000.0), a=ZERO,
|
||||
b=lambda t: 800.0 if t < E + 300 else 400.0)
|
||||
summary("T2b(ii)", r2ii, tr2ii)
|
||||
check("T2b(ii): b drops to 400 W (landing 13 467 W): no alarm to E+900",
|
||||
quiet(r2ii, tr2ii))
|
||||
|
||||
# --- T3: batteries at 0 W, and the 11 kW car ---------------------------------- #
|
||||
r3, tr3 = H.run(H.shape(13000.0), a=ZERO, b=ZERO)
|
||||
w3, lim3 = summary("T3", r3, tr3)
|
||||
check("T3: batteries 0 W, house 13 000 W, car 1 380 W: no alarm, no red row, "
|
||||
"the car explains every limited cycle incl. E+0..E+10, one car notice",
|
||||
quiet(r3, tr3) and all_explained(lim3)
|
||||
and len(P.ids(r3, P.OVER)) == 1
|
||||
and all(x["explains"] for x in lim3 if x["t"] <= E + 10))
|
||||
|
||||
|
||||
def plug_at(t0):
|
||||
return {t0: lambda p, c: p.ch.plug_in()}
|
||||
|
||||
|
||||
r3k, tr3k = H.run(H.shape(2600.0, before=2600.0), a=ZERO, b=ZERO, car_a=16,
|
||||
phases=3, aim=6344.0, plug=False, extra=plug_at(E - 120))
|
||||
w3k, lim3k = summary("T3 11 kW", r3k, tr3k)
|
||||
check("T3 11 kW: house 2 600 W, car 11 kW, aim 6 344 W (base P 21:30): no "
|
||||
"alarm, the car explains every limited cycle",
|
||||
quiet(r3k, tr3k) and all_explained(lim3k)
|
||||
and len(P.ids(r3k, P.OVER)) == 1)
|
||||
|
||||
# --- T4 controller ------------------------------------------------------------ #
|
||||
r409, tr409 = H.run(H.shape(13609.0), a=ZERO, b=ZERO)
|
||||
summary("T4 13 609", r409, tr409)
|
||||
check("T4: the house alone at aim + 9 W: no alarm", quiet(r409, tr409))
|
||||
r411, tr411 = H.run(H.shape(13611.0), a=ZERO, b=ZERO)
|
||||
r411o, tr411o = H.run(H.shape(13611.0), a=ZERO, b=ZERO, mode="off")
|
||||
summary("T4 13 611", r411, tr411)
|
||||
summary("T4 13 611 Off", r411o, tr411o)
|
||||
check("T4: at aim + 11 W the alarm at the same cycle as Off (and as base, "
|
||||
"E+0)", H.alarms(r411) == H.alarms(r411o) == [E])
|
||||
|
||||
# --- T5: an honest alarm ------------------------------------------------------ #
|
||||
r5, tr5 = H.run(honest(14090.0), a=ZERO, b=ZERO)
|
||||
r5o, tr5o = H.run(honest(14090.0), a=ZERO, b=ZERO, mode="off")
|
||||
summary("T5", r5, tr5)
|
||||
summary("T5 Off", r5o, tr5o)
|
||||
check("T5: grid excess 1 870 W > car 1 380 W: the alarm and the ERROR at the "
|
||||
"same second as Off and as base (E+1, the step's first sample)",
|
||||
H.alarms(r5) == H.alarms(r5o) == T5_BASE
|
||||
and nth(H.errors(tr5), 0) == nth(H.errors(tr5o), 0) == E + 1)
|
||||
check("T5: the car explains no cycle", not any(x["explains"] for x in tr5))
|
||||
|
||||
|
||||
# --- T6: the car figure unknown across the edge ------------------------------- #
|
||||
def unavailable(t0, t1):
|
||||
return {t0: lambda p, c: p.ch.go_unavailable(True),
|
||||
t1: lambda p, c: p.ch.go_unavailable(False)}
|
||||
|
||||
|
||||
r6, tr6 = H.run(H.shape(13000.0), a=ZERO, b=ZERO,
|
||||
extra=unavailable(E - 20, E + 60))
|
||||
summary("T6 T3 shape", r6, tr6)
|
||||
back = first(x["t"] for x in tr6 if x["t"] >= E + 60 and x["w"] is not None)
|
||||
check("T6 T3 shape: while unknown the car explains nothing and the alarm "
|
||||
"stands from E+0, as base",
|
||||
H.alarms(r6) == [E] and not any(
|
||||
x["explains"] for x in H.window(tr6, E - 5, E + 59))
|
||||
and all(x["alarm"] for x in H.window(tr6, E, E + 59)))
|
||||
check("T6 T3 shape: released within 1 cycle of the first trusted cycle after "
|
||||
"E+60, no new alarm edge to E+900 (base: red to E+900)",
|
||||
present(back) and all(not x["alarm"] and x["explains"] for x in
|
||||
H.window(tr6, back + 1, E + 899))
|
||||
and H.edges(tr6) == [E])
|
||||
r6h, tr6h = H.run(honest(14090.0), a=ZERO, b=ZERO,
|
||||
extra=unavailable(E - 20, E + 60))
|
||||
summary("T6 T5 shape", r6h, tr6h)
|
||||
check("T6 T5 shape: the alarm at the base second and it stands throughout",
|
||||
H.alarms(r6h) == T5_BASE and all(x["alarm"] for x in
|
||||
H.window(tr6h, E + 1, E + 899)))
|
||||
|
||||
|
||||
# --- T7: a frozen car figure, the car really stops ---------------------------- #
|
||||
def frozen_stop(p, c):
|
||||
p.ch.freeze()
|
||||
p.ch.car_full()
|
||||
|
||||
|
||||
r7, tr7 = H.run(honest(14090.0), a=ZERO, b=ZERO, extra={E - 30: frozen_stop})
|
||||
summary("T7", r7, tr7)
|
||||
first7 = nth(H.alarms(r7), 0)
|
||||
untr = first(x["t"] for x in tr7 if x["t"] >= E - 30 and x["w"] is None)
|
||||
check("T7: the alarm within 114 s of the stop (max(60, 40 Wh / 1.38 kW) "
|
||||
"+ 10), no later than base",
|
||||
present(first7) and first7 <= E - 30 + 114 and first7 <= T7_BASE)
|
||||
check("T7: never explained after the figure goes untrusted",
|
||||
present(untr) and not any(x["explains"] for x in tr7 if x["t"] >= untr))
|
||||
|
||||
|
||||
# --- T8: a car at 0 W, and a 50 W car ----------------------------------------- #
|
||||
class Draw(SimCharger):
|
||||
"""A charger that draws `real_w` while charging and reports `say_w`."""
|
||||
def __init__(self, real_w, say_w, **kw):
|
||||
super().__init__(**kw)
|
||||
self.real_w, self.say_w = real_w, say_w
|
||||
|
||||
def target_w(self):
|
||||
return 0.0 if super().target_w() <= 0.0 else self.real_w
|
||||
|
||||
def _build(self):
|
||||
keep, self._frozen_w = self._frozen_w, self.say_w
|
||||
try:
|
||||
return super()._build()
|
||||
finally:
|
||||
self._frozen_w = keep
|
||||
|
||||
|
||||
def full(p, c):
|
||||
p.ch.car_full()
|
||||
|
||||
|
||||
for nm, kw in (("house 14 090 W", dict(house=honest(14090.0), b=ZERO)),
|
||||
("T2 shape", dict(house=honest(14000.0), b=const(800.0)))):
|
||||
r8, tr8 = H.run(a=ZERO, extra={1: full}, **kw)
|
||||
r8o, tr8o = H.run(a=ZERO, extra={1: full}, mode="off", **kw)
|
||||
summary(f"T8 0 W, {nm}", r8, tr8)
|
||||
summary(f"T8 0 W, {nm}, Off", r8o, tr8o)
|
||||
check(f"T8: a car plugged at 0 W, {nm}: the alarm at the same second as "
|
||||
f"Off, nothing explained", H.alarms(r8) == H.alarms(r8o)
|
||||
and H.alarms(r8) != [] and not any(x["explains"] for x in tr8))
|
||||
r8s, tr8s = H.run(honest(14090.0), a=ZERO, b=ZERO,
|
||||
sim=Draw(50.0, 50.0, setpoint_a=6))
|
||||
r8so, tr8so = H.run(honest(14090.0), a=ZERO, b=ZERO, mode="off",
|
||||
sim=Draw(50.0, 50.0, setpoint_a=6))
|
||||
summary("T8 50 W", r8s, tr8s)
|
||||
check("T8: a 50 W car, house 14 090 W: the alarm at the same second as Off, "
|
||||
"nothing explained", H.alarms(r8s) == H.alarms(r8so) == T5_BASE
|
||||
and not any(x["explains"] for x in tr8s))
|
||||
|
||||
# --- T9: a wrong charger reply ------------------------------------------------ #
|
||||
r9a, tr9a = H.run(honest(13900.0), a=ZERO, b=ZERO,
|
||||
sim=Draw(1380.0, 11000.0, setpoint_a=6))
|
||||
summary("T9(a)", r9a, tr9a)
|
||||
check("T9(a): reports 11 kW, read-back 6 A 1-ph (cap 1 518 W): the house "
|
||||
"alone misses, the alarm at the base second",
|
||||
H.alarms(r9a) == T5_BASE and all(x["w"] is None or x["w"] <= 1518.0
|
||||
for x in tr9a))
|
||||
r9b, tr9b = H.run(honest(13900.0), a=ZERO, b=ZERO,
|
||||
sim=Draw(400.0, 1380.0, setpoint_a=6))
|
||||
summary("T9(b)", r9b, tr9b)
|
||||
check("T9(b): reports 1 380 W, draws 400 W: the same alarms as base (none: "
|
||||
"400 W corroborates a 1 380 W figure, CORR_RATIO 0.5; see the dev "
|
||||
"report's Findings)", H.alarms(r9b) == T9B_BASE)
|
||||
r9c, tr9c = H.run(honest(13900.0), a=ZERO, b=ZERO,
|
||||
sim=Draw(100.0, 1380.0, setpoint_a=6))
|
||||
summary("T9(c)", r9c, tr9c)
|
||||
a9c = nth(H.alarms(r9c), 0)
|
||||
check("T9(c): reports 1 380 W, draws 100 W: the first alarm once the figure "
|
||||
"is uncorroborated, at most 104 s + 10 s after the edge, no later than "
|
||||
"base", present(a9c) and a9c <= E + 114 and a9c <= T9C_BASE)
|
||||
check("T9(c) (owner 2026-11-19): the meter contradicted the figure, so it "
|
||||
"stays untrusted to the quarter's end: one alarm edge, red and never "
|
||||
"explained to E+899 (the meter's 10 Wh step re-corroborates it every "
|
||||
"360 s)", H.edges(tr9c) == [a9c] and all(
|
||||
x["alarm"] and x["red"] and not x["explains"]
|
||||
for x in H.window(tr9c, a9c, E + 899)))
|
||||
|
||||
# --- T10: a lost battery reading, an unavailable charger ---------------------- #
|
||||
for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))),
|
||||
("T5", dict(house=honest(14090.0), b=ZERO))):
|
||||
r10, tr10 = H.run(a=ZERO, lost={"b": {E + 1}}, **kw)
|
||||
summary(f"T10(a) {nm}", r10, tr10)
|
||||
gap = first(x for x in tr10 if x["t"] == E + 1)
|
||||
nxt = first(x for x in tr10 if x["t"] == E + 2)
|
||||
check(f"T10(a) {nm}: inverter-b's reading lost at E+1: that cycle grades "
|
||||
f"nothing (P_SAFETY owns a missing input), the next one grades on "
|
||||
f"what is measured", present(gap, nxt) and gap["batt"] is None
|
||||
and nxt["batt"] == (800.0 if nm == "T2" else 0.0))
|
||||
if nm == "T2":
|
||||
check("T10(a) T2: no alarm edge (base: E+0)", quiet(r10, tr10))
|
||||
else:
|
||||
check("T10(a) T5: the same alarm seconds as base",
|
||||
H.alarms(r10) == T10A_T5_BASE)
|
||||
r10b, tr10b = H.run(a=ZERO, extra=unavailable(E + 1, E + 2), **kw)
|
||||
summary(f"T10(b) {nm}", r10b, tr10b)
|
||||
if nm == "T2":
|
||||
check("T10(b) T2: the charger unavailable for one cycle (E+1): the "
|
||||
"alarm stands for that cycle only (Expected 5)",
|
||||
H.edges(tr10b) == [E + 1]
|
||||
and all(not x["alarm"] for x in H.window(tr10b, E + 2, E + 899))
|
||||
and all(x["explains"] for x in H.window(tr10b, E + 2, E + 899)
|
||||
if x["lim"]))
|
||||
else:
|
||||
check("T10(b) T5: the alarm at the base second and it stands",
|
||||
H.alarms(r10b) == T5_BASE and all(
|
||||
x["alarm"] for x in H.window(tr10b, E + 1, E + 899)))
|
||||
|
||||
# --- R1 (review round 2): the energy reading unknown for one cycle ----------- #
|
||||
for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))),
|
||||
("T3", dict(house=H.shape(13000.0), b=ZERO))):
|
||||
rg, trg = H.run(a=ZERO, extra=H.energy_gap(E + 200), **kw)
|
||||
summary(f"R1 {nm} energy gap at E+200", rg, trg)
|
||||
check(f"R1 {nm}: the charger's energy entity unknown for one cycle "
|
||||
f"(E+200) on a correct car: unknown, not contradicted, so red for "
|
||||
f"that cycle only and explained from the next (Expected 5)",
|
||||
H.red_secs(trg) == [E + 200] and H.edges(trg) == [E + 200]
|
||||
and all(x["explains"] for x in H.window(trg, E + 201, E + 899)
|
||||
if x["lim"]))
|
||||
|
||||
# --- T11: one battery first (SAFETY-87) --------------------------------------- #
|
||||
for nm, house in (("(i) 17 500 W", 17500.0), ("(ii) 19 000 W", 19000.0)):
|
||||
r11, tr11 = H.run(honest(house), soc={"a": 19.0, "b": 35.0})
|
||||
summary(f"T11{nm}", r11, tr11)
|
||||
if house < 18000.0:
|
||||
check("T11(i): b able, house 17 500 W, car 1 380 W: no alarm across E",
|
||||
H.alarms(r11) == [] and P.ids(r11, *P.ALARMS) == [])
|
||||
else:
|
||||
check("T11(ii): house 19 000 W: the alarm at the base second",
|
||||
[t for t, _n in P.ids(r11, *P.ALARMS)] == T11_BASE)
|
||||
|
||||
# --- T12 (record only): plug-in at E+0, the reserve at E+180 ------------------ #
|
||||
def reserve_at(p, c):
|
||||
p.socs.update({"a": 19.0, "b": 19.0})
|
||||
|
||||
|
||||
r12, tr12 = H.run(H.shape(13000.0), soc={"a": 40.0, "b": 40.0}, plug=False,
|
||||
extra={E: lambda p, c: p.ch.plug_in(), E + 180: reserve_at})
|
||||
summary("T12 (record, F-B)", r12, tr12)
|
||||
|
||||
# --- T13 controller: the latch is kept ---------------------------------------- #
|
||||
r13, tr13 = H.run(H.shape(lambda t: 15500.0 if E + 300 <= t < E + 360
|
||||
else 13000.0), a=ZERO, b=ZERO)
|
||||
summary("T13", r13, tr13)
|
||||
check("T13: the house steps to 15 500 W at E+300 for 60 s: the alarm at "
|
||||
"the base second (E+301, the step's first sample), and red to the "
|
||||
"quarter's end", H.alarms(r13) == T13_BASE and all(
|
||||
x["alarm"] and x["red"] for x in H.window(tr13, E + 301, E + 899)))
|
||||
|
||||
# --- T16: the edge paths ------------------------------------------------------ #
|
||||
for nm, kw in (("(a)(b)(c) SAFETY-91 roll, modes on", {}),
|
||||
("(d) the guard not wanting at the edge",
|
||||
dict(lost={"b": {E}}))):
|
||||
r16, tr16 = H.run(H.shape(13000.0), a=ZERO, b=ZERO, **kw)
|
||||
w16, lim16 = summary(f"T16{nm}", r16, tr16)
|
||||
f16 = first(x for x in tr16 if x["t"] >= E and x["lim"])
|
||||
pre = first(x for x in tr16 if x["t"] == E - 1)
|
||||
check(f"T16{nm}: the car explains from the first limited cycle of the "
|
||||
f"new block, no alarm, no red row, `_carq` key = block_start",
|
||||
present(f16) and quiet(r16, tr16) and all(
|
||||
x["explains"] and x["key"] == x["block"]
|
||||
for x in tr16 if x["t"] >= f16["t"] and x["lim"]))
|
||||
if not kw:
|
||||
print(f" T16(c): within_aim at E-1 {pre['within_aim'] if present(pre) else pre}"
|
||||
" (SAFETY-126's latch carried; not asserted)")
|
||||
else:
|
||||
g0 = first(x for x in tr16 if x["t"] == E)
|
||||
check("T16(d) PRECONDITION: the guard did not want power at E+0",
|
||||
present(g0) and not g0["wants"])
|
||||
|
||||
|
||||
# --- T17: a restart ----------------------------------------------------------- #
|
||||
def restart_at(t0):
|
||||
return {t0: lambda p, c: H.restart(c)}
|
||||
|
||||
|
||||
for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))),
|
||||
("T3", dict(house=H.shape(13000.0), b=ZERO)),
|
||||
("T5", dict(house=honest(14090.0), b=ZERO))):
|
||||
rr0, tr0 = H.run(a=ZERO, **kw)
|
||||
for at in (E + 2, E + 300):
|
||||
rr, trr = H.run(a=ZERO, extra=restart_at(at), **kw)
|
||||
summary(f"T17 {nm} restart at E+{at - E}", rr, trr)
|
||||
if nm == "T5":
|
||||
check(f"T17 T5, restart at E+{at - E}: the alarm at the base "
|
||||
f"second and again on the first cycle after the restart, "
|
||||
f"as base; red throughout",
|
||||
H.alarms(rr) == T5_BASE + [at] and len(H.red_secs(trr))
|
||||
== len(H.red_secs(tr0)))
|
||||
elif nm == "T2" and at == E + 300:
|
||||
# review round 1: the car's energy before a restart is not known,
|
||||
# so it counts as house (never credited to the car). Here that
|
||||
# tips the house alone over the aim: the alarm stands from the
|
||||
# restart, the conservative side (base: red from E+0).
|
||||
check("T17 T2, restart at E+300: quiet before the restart; after "
|
||||
"it the car's unknown earlier share counts as house, so at "
|
||||
"most one alarm edge, at the restart",
|
||||
quiet(rr0, tr0) and H.red_secs(trr, t1=at - 1) == []
|
||||
and H.edges(trr) in ([], [at]))
|
||||
else:
|
||||
check(f"T17 {nm}, restart at E+{at - E}: the same as without "
|
||||
f"(no floor notice, no ERROR, no red row)",
|
||||
quiet(rr, trr) and quiet(rr0, tr0))
|
||||
print(f" T17 {nm} car-over notices: twin "
|
||||
f"{[t - E for t, _n in P.ids(rr0, P.OVER)]}, restarted "
|
||||
f"{[t - E for t, _n in P.ids(rr, P.OVER)]} (EV-11's "
|
||||
f"once-per-session state does not survive a restart, as on "
|
||||
f"base)")
|
||||
|
||||
# --- T17b (review round 1): a house need only the done part shows ----------- #
|
||||
def heavy_then_light(t):
|
||||
"""House 18 000 W for E..E+300, then 12 000 W: alone it lands 14 000 W."""
|
||||
if t < E:
|
||||
return H.PRE_W if t < E - 120 else 12000.0
|
||||
return 18000.0 if t < E + 300 else 12000.0
|
||||
|
||||
|
||||
r17b0, tr17b0 = H.run(heavy_then_light, a=ZERO, b=ZERO)
|
||||
r17b, tr17b = H.run(heavy_then_light, a=ZERO, b=ZERO,
|
||||
extra=restart_at(E + 310))
|
||||
summary("T17b no restart", r17b0, tr17b0)
|
||||
summary("T17b restart at E+310", r17b, tr17b)
|
||||
check("T17b: the house heavy before a restart at E+310 (alone it lands "
|
||||
"14 000 W, excess 1 780 W > car): red to the quarter's end and never "
|
||||
"explained, as without the restart (and as base and Off)",
|
||||
len(H.red_secs(tr17b, E, E + 899)) == len(H.red_secs(tr17b0, E, E + 899))
|
||||
== 899 and not any(x["explains"] for x in H.window(tr17b, E, E + 899)))
|
||||
|
||||
# --- T15 controller: x10 ------------------------------------------------------ #
|
||||
# F2 (out of scope, filed apart): `_car_quarter` caps a cycle's dt at 5 s, so at
|
||||
# 10 s a cycle half the car's energy is counted, and late in the quarter the
|
||||
# house alone seems to miss the aim (T2 from about E+540, T3 E+820, as on base
|
||||
# for T3). The x10 verdicts are graded to E+500; what comes after is printed.
|
||||
F2_FROM = E + 500
|
||||
for nm, kw, want in (
|
||||
("T2", dict(house=H.shape(14000.0), b=const(800.0)), "quiet"),
|
||||
("T3", dict(house=H.shape(13000.0), b=ZERO), "quiet"),
|
||||
("T5", dict(house=honest(14090.0), b=ZERO), "alarm"),
|
||||
("T6", dict(house=H.shape(13000.0), b=ZERO,
|
||||
extra=unavailable(E - 20, E + 60)), "release")):
|
||||
rx, trx = H.run(a=ZERO, x=10, **kw)
|
||||
summary(f"T15 x10 {nm}", rx, trx)
|
||||
early = [x for x in trx if x["t"] < F2_FROM]
|
||||
print(f" T15 x10 {nm}: alarms after E+500 (F2) "
|
||||
f"{[t - E for t in H.alarms(rx) if t >= F2_FROM]}")
|
||||
if want == "quiet":
|
||||
check(f"T15 x10 {nm}: no alarm, no red row, every limited cycle "
|
||||
f"explained, E-120..E+500",
|
||||
not [t for t in H.alarms(rx) if t < F2_FROM]
|
||||
and H.red_secs(trx, t1=F2_FROM - 1) == []
|
||||
and all_explained([x for x in early if x["lim"]]))
|
||||
elif want == "alarm":
|
||||
check("T15 x10 T5: the alarm at the base second (E+10, one cycle)",
|
||||
H.alarms(rx) == T15_T5_BASE)
|
||||
else:
|
||||
bk = first(x["t"] for x in trx if x["t"] >= E + 60
|
||||
and x["w"] is not None)
|
||||
check("T15 x10 T6: the alarm while unknown, released within 1 cycle "
|
||||
"(10 fake s) of the first trusted one, no new edge to E+500",
|
||||
present(bk) and bk <= E + 70
|
||||
and all(not x["alarm"] for x in H.window(trx, bk, F2_FROM - 1))
|
||||
and [t for t in H.edges(trx) if t < F2_FROM] == [E])
|
||||
|
||||
# --- N4: the alarm decision changes no command -------------------------------- #
|
||||
for nm, kw in (("T2", dict(house=H.shape(14000.0), b=const(800.0))),
|
||||
("T5", dict(house=honest(14090.0), b=ZERO))):
|
||||
ra, tra = H.run(a=ZERO, **kw)
|
||||
rb, trb = H.run(a=ZERO, explain_off=True, **kw)
|
||||
check(f"N4 {nm}: the claim, the floor, the battery setpoints and the "
|
||||
f"charger writes are identical whether the car explains or not",
|
||||
H.commands(ra, tra) == H.commands(rb, trb))
|
||||
|
||||
# N4 with "Batteries help with the peak" off (review round 2): the guard's
|
||||
# input is `car_exclude`, which reads the car's energy count. The
|
||||
# contradiction latch must not touch it: the same commands with the latch off.
|
||||
for nm, kw in (
|
||||
("SoC 60 %, energy gap at E+200",
|
||||
dict(house=H.shape(13000.0), soc={"a": 60.0, "b": 60.0},
|
||||
extra=H.energy_gap(E + 200))),
|
||||
("at the reserve, energy gap at E+200",
|
||||
dict(house=H.shape(13000.0), a=ZERO, b=ZERO,
|
||||
extra=H.energy_gap(E + 200))),
|
||||
("SoC 60 %, the T9(c) liar",
|
||||
dict(house=honest(13900.0), soc={"a": 60.0, "b": 60.0},
|
||||
sim=Draw(100.0, 1380.0, setpoint_a=6))),
|
||||
("at the reserve, the T9(c) liar",
|
||||
dict(house=honest(13900.0), a=ZERO, b=ZERO,
|
||||
sim=Draw(100.0, 1380.0, setpoint_a=6)))):
|
||||
ra, tra = H.run(cover=False, **kw)
|
||||
if "sim" in kw:
|
||||
kw = dict(kw, sim=Draw(100.0, 1380.0, setpoint_a=6))
|
||||
rb, trb = H.run(cover=False, latch_off=True, **kw)
|
||||
summary(f"N4 cover off, {nm}", ra, tra)
|
||||
check(f"N4 cover off, {nm}: the claim, the floor, the setpoints and the "
|
||||
f"charger writes are those of the same run without the "
|
||||
f"contradiction latch", H.commands(ra, tra) == H.commands(rb, trb))
|
||||
|
||||
# --- N5: at most one floor-alarm edge per quarter ---------------------------- #
|
||||
def per_quarter(ts):
|
||||
out = {}
|
||||
for t in ts:
|
||||
out[(t - E) // 900] = out.get((t - E) // 900, 0) + 1
|
||||
return out
|
||||
|
||||
|
||||
# Cover off, the T9(c) liar at the reserve: the guard's own engagement flips
|
||||
# as the liar's figure is corroborated now and then (its input is
|
||||
# `car_exclude`), pre-existing (base: 4 edges). Printed, not graded here.
|
||||
LIAR_OFF = "N4 cover off, at the reserve, the T9(c) liar"
|
||||
print(f" {LIAR_OFF}: alarm edges "
|
||||
f"{[[t - E for t in ts] for nm, ts in RUNS if nm == LIAR_OFF]}")
|
||||
many = [(nm, ts) for nm, ts in RUNS
|
||||
if nm != LIAR_OFF and any(v > 1 for v in per_quarter(
|
||||
[t for t in ts if not nm.startswith("T15 x10") or t < F2_FROM])
|
||||
.values())]
|
||||
check(f"N5: at most one floor-alarm edge per quarter in every run "
|
||||
f"({len(RUNS)} runs; x10 to E+500; the cover-off liar apart): "
|
||||
f"{many}", many == [])
|
||||
|
||||
print()
|
||||
print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed")
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -1,654 +0,0 @@
|
||||
"""EV-19: no floor alarm when the batteries first reach the peak reserve early
|
||||
in a Manual car session (EV-15 rig F-B). `python3 -B test_ev19.py`
|
||||
|
||||
The rig: one PEAK_GUARD_FLOOR_LIMITED ERROR, one `goodwe_peak_soc_floor` and
|
||||
one red sample the moment the batteries reached the reserve, while the excess
|
||||
was smaller than the car. Reproduced (T1): at the reserve inverter-b goes on
|
||||
following the house, so its output RISES in that cycle. The battery reading
|
||||
shows the rise one cycle before the P1 sample does, and EV-18's "house"
|
||||
(meter + what the batteries give now) counted the new battery power as house
|
||||
load. That latched `_car_need_house` for the quarter: the alarm stood until
|
||||
the guard stopped wanting power. Now a rise the reading shows above both
|
||||
earlier readings is not counted as house until a second reading confirms it.
|
||||
The credit stays the lower of the last two readings.
|
||||
|
||||
T-ids are the test plan's (reports/EV-19-test-plan.md). "base" is 43b0db7.
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import ctl_car, tariff # noqa: E402
|
||||
from named_absence import first, nth, present # noqa: E402
|
||||
import ev19_reserve as V # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
AIM = V.AIM
|
||||
CAR = V.CAR
|
||||
|
||||
# =========================================================================== #
|
||||
print("1. UNIT: car_cycle in the reserve cycle (a real `_carq`)")
|
||||
# =========================================================================== #
|
||||
BS = datetime(2026, 11, 20, 20, 30, tzinfo=timezone.utc) # a quarter edge
|
||||
|
||||
|
||||
class _Car(ctl_car.CarMixin):
|
||||
def __init__(self):
|
||||
self.o = {"ev_batt_cover": True}
|
||||
self.w = CAR
|
||||
self._now = 0.0
|
||||
self.site_batt_w, self.site_rating_w = 0.0, 9600.0
|
||||
self.store = type("S", (), {"data": {}, "set": lambda s, k, v: 0})()
|
||||
self.car_init({}, self.store)
|
||||
|
||||
def car_now(self):
|
||||
return self._now
|
||||
|
||||
def car_alarm_w(self):
|
||||
return self.w
|
||||
|
||||
class car: # noqa: N801
|
||||
@staticmethod
|
||||
def status(*_a):
|
||||
return "charging"
|
||||
|
||||
|
||||
class _G:
|
||||
"""Floor-limited, the floor leaves nothing (floor_w 0), wants power."""
|
||||
floor_limited, saturated = True, False
|
||||
floor_w, able_w, ceiling_w = 0.0, None, AIM + 50.0
|
||||
engaged, blind, wanted_w, within_aim = True, None, 300.0, False
|
||||
|
||||
|
||||
def urun(secs, grid, batt, w=lambda t: CAR):
|
||||
"""`car_cycle` once per second of `secs` (seconds from the edge). `grid(t)`
|
||||
is the meter, `batt(t)` the site battery reading. {t: car_explains}."""
|
||||
c = _Car()
|
||||
done, out = {}, {}
|
||||
for t in secs:
|
||||
q = t // 900
|
||||
bs, el = BS + timedelta(seconds=900 * q), t - 900 * q
|
||||
g = float(grid(t))
|
||||
d = done.get(bs, g * el)
|
||||
p = tariff.Projection(
|
||||
projected_w=(d + g * (900 - el)) / 900.0,
|
||||
elapsed_w=(d / el if el else g), elapsed_s=float(el),
|
||||
covered_frac=1.0, complete=False, block_start=bs, held_w=g)
|
||||
done[bs] = d + g
|
||||
c._now = 10000.0 + t
|
||||
c.w, c.site_batt_w = w(t), batt(t)
|
||||
c.car_cycle(p, _G(), AIM, None)
|
||||
out[t] = c.car_explains
|
||||
return out
|
||||
|
||||
|
||||
def run_of(d, t0, t1):
|
||||
return [d[t] for t in sorted(d) if t0 <= t <= t1]
|
||||
|
||||
|
||||
def rise(at, lo, hi):
|
||||
"""A battery reading that steps from `lo` to `hi` at `at`."""
|
||||
return lambda t: lo if t < at else hi
|
||||
|
||||
|
||||
def meter(house, b, lag=1):
|
||||
"""The P1 figure: house + car - what the batteries gave `lag` cycles ago
|
||||
(the reading leads the meter by that much)."""
|
||||
return lambda t: house + CAR - b(t - lag)
|
||||
|
||||
|
||||
HB = AIM + 520.0 - CAR # F-B: house + car at batteries 0 W = aim + 520
|
||||
b2 = rise(1, 0.0, 4600.0)
|
||||
u2 = urun(range(-5, 61), meter(HB, b2), b2)
|
||||
print(f" T2 unit E-1..E+3: {run_of(u2, -1, 3)}")
|
||||
check("T2 unit: b starts following the house at the reserve (0 -> 4 600 W) "
|
||||
"and the reading shows it one cycle before the meter: the car explains "
|
||||
"every cycle, the rise cycle E+1 among them (base: not from E+1)",
|
||||
all(run_of(u2, 0, 60)) and len(run_of(u2, 0, 60)) == 61)
|
||||
u2s = urun(range(-5, 61), meter(HB, b2, lag=0), b2)
|
||||
check("T2 unit: the same rise with the meter in step: explained every cycle",
|
||||
all(run_of(u2s, 0, 60)) and len(run_of(u2s, 0, 60)) == 61)
|
||||
|
||||
# T4: the landing without the car at aim + 9 / + 11 W in the rise cycle. The
|
||||
# rise is at the edge, so with the lower reading credited (0 W) the house
|
||||
# alone lands at exactly `house`.
|
||||
b4 = rise(0, 0.0, 800.0)
|
||||
u409 = urun(range(-3, 10), meter(AIM + 9.0, b4), b4)
|
||||
u411 = urun(range(-3, 10), meter(AIM + 11.0, b4), b4)
|
||||
print(f" T4 unit +9 {run_of(u409, 0, 3)} +11 {run_of(u411, 0, 3)}")
|
||||
check("T4 unit: the house alone at aim + 9 W in the rise cycle: the car "
|
||||
"explains from E+0 (base: no)", all(run_of(u409, 0, 9))
|
||||
and len(run_of(u409, 0, 9)) == 10)
|
||||
check("T4 unit: at aim + 11 W it does not, from E+0 (as base)",
|
||||
not any(run_of(u411, 0, 9)) and len(run_of(u411, 0, 9)) == 10)
|
||||
|
||||
# N6 / T7(a): an unknown reading credits nothing; the lower reading is
|
||||
# credited, not the higher or the last known one.
|
||||
b7 = lambda t: None if t == 1 else b2(t) # noqa: E731
|
||||
u7 = urun(range(-5, 30), meter(HB, b2), b7)
|
||||
check("T7(a) unit: the battery reading unknown in the rise cycle: nothing "
|
||||
"explained in that cycle (no last-known W), explained from the next",
|
||||
u7.get(1) is False and u7.get(0) is True and all(run_of(u7, 2, 29)))
|
||||
u6 = urun(range(-5, 30), meter(AIM + 11.0 + 400.0, lambda t: 400.0, lag=0),
|
||||
lambda t: 800.0 if t == 3 else 400.0)
|
||||
check("N6 unit: b at 400 W, the house alone with it at aim + 11 W, one "
|
||||
"reading of 800 W at E+3: not explained in any cycle",
|
||||
not any(run_of(u6, 0, 29)))
|
||||
# A house step that comes with a battery rise: b steps to 800 W and the
|
||||
# meter, one cycle late, shows a house of aim + 811 W, so with b's 800 W the
|
||||
# house alone misses by 11 W. The meter moved, so nothing is discounted.
|
||||
b8 = rise(5, 0.0, 800.0)
|
||||
u8 = urun(range(0, 30), lambda t: (AIM - 500.0 if t < 5 else AIM + 811.0)
|
||||
+ CAR - b8(t - 1), b8)
|
||||
print(f" N6 unit house step with a rise E+4..E+8: {run_of(u8, 4, 8)}")
|
||||
check("N6 unit: a house step that comes with a battery rise is latched in "
|
||||
"the rise cycle (E+5, as base), and stays latched",
|
||||
all(run_of(u8, 0, 4)) and not any(run_of(u8, 5, 29)))
|
||||
|
||||
# Review round 1 (Major): an honest house step at E+5 answered by ONE reading
|
||||
# of battery power, the meter in step (it shows the burst too) or one cycle
|
||||
# late. Not explained from E+5, the step's own cycle, as base.
|
||||
for H, burst, lag in ((2000.0, 4600.0, 0), (1900.0, 3000.0, 0),
|
||||
(5000.0, 4600.0, 0), (2000.0, 4600.0, 1),
|
||||
(1900.0, 3000.0, 1)):
|
||||
hs = (lambda t, H=H: AIM - 500.0 if t < 5 else AIM + H)
|
||||
bb = (lambda t, burst=burst: burst if t == 5 else 0.0)
|
||||
ub = urun(range(0, 15), lambda t, hs=hs, bb=bb, lag=lag:
|
||||
hs(t) + CAR - bb(t - lag), bb)
|
||||
check(f"RB unit: house -> aim + {H:.0f} W at E+5 with one {burst:.0f} W "
|
||||
f"reading, meter {'in step' if lag == 0 else 'one cycle late'}: "
|
||||
f"explained to E+4, not from E+5 (base: the same)",
|
||||
ub.get(4) is True and not any(run_of(ub, 5, 14))
|
||||
and len(run_of(ub, 5, 14)) == 10)
|
||||
|
||||
# The discount needs a still meter: the F-B rise (T2 unit) with the house
|
||||
# side of the meter moving by RISE_STILL_W -/+ 10 W in the rise cycle.
|
||||
STILL = getattr(ctl_car, "RISE_STILL_W", 50.0) # 43b0db7 has none
|
||||
for d, want in ((STILL - 10.0, True), (STILL + 10.0, False)):
|
||||
ud = urun(range(-5, 10), lambda t, d=d: HB + (d if t >= 1 else 0.0)
|
||||
+ CAR - b2(t - 1), b2)
|
||||
check(f"RISE_STILL_W: the meter's house side moves {d:.0f} W in the rise "
|
||||
f"cycle: {'still, the rise is not yet house (explained)' if want else 'moved, the rise counts as house (not explained, as base)'}",
|
||||
ud.get(1) is want and ud.get(0) is True)
|
||||
|
||||
# Review round 2: the blind band in absolute W (the owner's 50 W; change this
|
||||
# check with the owner). An honest step at E+5 (house aim - 500 -> aim + 1 900
|
||||
# W, more than the car) with one burst that leaves the meter's house side
|
||||
# moving d W: at |d| = 60 the alarm cycle is base's (E+5); inside the band
|
||||
# (d = 0) the car explains at most the step's own cycle, never from E+6.
|
||||
for dd in (60.0, -60.0, 0.0):
|
||||
hb = (lambda t: AIM - 500.0 if t < 5 else AIM + 1900.0)
|
||||
bd = (lambda t, B=2400.0 - dd: B if t == 5 else 0.0)
|
||||
ubd = urun(range(0, 15), lambda t, hb=hb, bd=bd: hb(t) + CAR - bd(t), bd)
|
||||
print(f" band d={dd:+.0f} W E+4..E+8: {run_of(ubd, 4, 8)}")
|
||||
t0 = 5 if dd else 6
|
||||
check(f"band: an honest step whose burst moves the meter's house side "
|
||||
f"{dd:+.0f} W: not explained from E+{t0}",
|
||||
ubd.get(4) is True and not any(run_of(ubd, t0, 14))
|
||||
and len(run_of(ubd, t0, 14)) == 15 - t0)
|
||||
|
||||
# Review round 2: the stillness test uses the house side (held - car). The car
|
||||
# steps 1 380 -> 2 760 W, the house aim - 500 -> aim + 3 000 W (more than the
|
||||
# car) and b gives one reading of 4 880 W, all at E+5, meter in step: the
|
||||
# meter's total stays, its house side drops 1 380 W, so nothing is discounted.
|
||||
hc = (lambda t: AIM - 500.0 if t < 5 else AIM + 3000.0)
|
||||
wc = (lambda t: CAR if t < 5 else 2 * CAR)
|
||||
bc5 = (lambda t: 4880.0 if t == 5 else 0.0)
|
||||
ucw = urun(range(0, 15), lambda t: hc(t) + wc(t) - bc5(t), bc5, w=wc)
|
||||
check("car term: the car steps up with the house and a burst, the meter's "
|
||||
"total still: not explained from E+5 (as base)",
|
||||
ucw.get(4) is True and not any(run_of(ucw, 5, 14))
|
||||
and len(run_of(ucw, 5, 14)) == 10)
|
||||
|
||||
# Review round 1 (mC): EV-18's `_car_over_now` keeps the reading as it is. b
|
||||
# gives 2 000 W, the house alone with it lands under the aim and the period
|
||||
# with the car too, so nothing explains; b rises to 4 000 W at E+5 one cycle
|
||||
# before the meter: the period with the car on the reading as it is lands
|
||||
# over, so the car explains from E+5.
|
||||
bc = rise(5, 2000.0, 4000.0)
|
||||
uc = urun(range(0, 15), lambda t: AIM + 500.0 + CAR - bc(t - 1), bc)
|
||||
print(f" over_now unit E+3..E+7: {run_of(uc, 3, 7)}")
|
||||
check("over_now unit: `_car_over_now` grades the undiscounted reading: not "
|
||||
"explained E+0..E+4, explained from the rise cycle E+5",
|
||||
not any(run_of(uc, 0, 4)) and all(run_of(uc, 5, 14))
|
||||
and len(run_of(uc, 5, 14)) == 10)
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n2. THE REAL CONTROLLER AT THE RESERVE (N=2, tools/ev19_reserve.py)")
|
||||
# =========================================================================== #
|
||||
JOBS = V.jobs()
|
||||
RES = V.run_many(JOBS)
|
||||
|
||||
|
||||
def res(name):
|
||||
return RES[name]
|
||||
|
||||
|
||||
def trusted(x):
|
||||
return x["w"] is not None and x["w"] > 0.0 and not x["contra"]
|
||||
|
||||
|
||||
def bad(x):
|
||||
return bool(x["alarm"] or x["red"] or x["err"])
|
||||
|
||||
|
||||
def hits(r, t0=-10, t1=60):
|
||||
"""T1's reproduction: an alarm, red sample or ERROR in R-10..R+60 in a
|
||||
cycle where the car figure is trusted (every T1 shape lands under the aim
|
||||
without the car, so the car explains there)."""
|
||||
return [int(x["t"] - r.R) for x in r.win(t0, t1) if bad(x) and trusted(x)]
|
||||
|
||||
|
||||
def show(name):
|
||||
r = res(name)
|
||||
print(f" {name}: alarms {r.rel_alarms()} edges {r.edges()} errors "
|
||||
f"{r.errors()} red {len(r.red())} s cmd {r.cmd}")
|
||||
|
||||
|
||||
# Measured on base 43b0db7 with this file's own runs: the seconds from R of
|
||||
# goodwe_peak_soc_floor in the honest shapes, which must not come later now.
|
||||
BASE_ALARMS = {
|
||||
"T4 +11 manual": [0, 857], "T5 t1 manual": [2], "T5 t4 manual": [11],
|
||||
"T5 tau5 manual": [2], "T6 step R+0 manual": [2],
|
||||
"T6 step R+1 manual": [2], "T6 step R+5 manual": [6],
|
||||
"T7(a) T5": [2], "T7(b) T5": [2], "T8(c) frozen, the car stops": [2],
|
||||
"T9(a) T5 b lost at R": [2], "T9(a) T5 b lost at R-1": [2],
|
||||
"T9(b) T5 P1 5 s late at R": [5], "T10 T5 twin": [2],
|
||||
"T10 T5 restart R-2": [2], "T10 T5 restart R+2": [2],
|
||||
"T10 T5 restart R-1": [2], "T10 T5 restart R+0": [2],
|
||||
"T10 T2 restart R+0": [1],
|
||||
"T11 T5 R=E-1": [2], "T11 T5 R=E+0": [0, 2], "T11 T5 R=E+1": [0, 2],
|
||||
"T11 T5 R=E+43": [2], "T12 T5 1->3 at R-15": [2],
|
||||
"T12 T5 1->3 at R+5": [2], "T13(a) draws 100 W manual": [0, 857],
|
||||
"T14(c) N=1 T5": [2], "T15 honest manual": [13],
|
||||
"T16 x10 T5 manual": [20], "T16 x10 T6 manual": [20],
|
||||
"T16 mono1 T5 manual": [20], "T16 mono1 T6 manual": [20],
|
||||
"T16 x10 T11 T5 R=E-10": [20], "T16 x10 T11 T5 R=E+0": [0, 20],
|
||||
"T16 x10 T11 T5 R=E+10": [0, 20], "T16 x10 T11 T5 R=E+40": [20],
|
||||
"T16 mono1 T11 T5 R=E-10": [20], "T16 mono1 T11 T5 R=E+0": [0, 20],
|
||||
"T16 mono1 T11 T5 R=E+10": [0, 20], "T16 mono1 T11 T5 R=E+40": [20],
|
||||
"T16 mono1 T3 t1 bw=0": [600], "T16 mono1 T3 t1 bw=2000": [700],
|
||||
"T16 mono1 T3 t1 bw=4250": [800], "T16 mono1 T3 t4 bw=0": [600],
|
||||
"T16 mono1 T3 t4 bw=2000": [700], "T16 mono1 T3 t4 bw=4250": [800],
|
||||
}
|
||||
# The T1 cells that reproduce F-B on base (G0): b following the house from R.
|
||||
BASE_REPRO = [f"T1 core bw={bw} t2 rp={rp}" for bw in (0, 400, 800)
|
||||
for rp in (30, 100, 110, 180, 600)] + [
|
||||
"T1 d: x10 wall+mono t2 bw=1200", "T1 d: x10 wall, mono x1 t2 bw=1200"]
|
||||
|
||||
|
||||
def as_base(k):
|
||||
"""The same alarm seconds as base."""
|
||||
return res(k).rel_alarms() == BASE_ALARMS[k]
|
||||
|
||||
# --- T1: the reproduction grid ------------------------------------------------ #
|
||||
T1 = sorted(k for k in JOBS if k.startswith("T1 "))
|
||||
C5 = [k for k in T1 if k.startswith("T1 b: energy")]
|
||||
rep = {k: hits(res(k)) for k in T1}
|
||||
print(f" T1 cells {len(T1)}; reproducing on this tree: "
|
||||
f"{sorted(k for k in T1 if rep[k])}")
|
||||
check("T1: no grid cell reproduces F-B: no notice, ERROR or red sample in "
|
||||
"R-10..R+60 while the car figure is trusted (base: the "
|
||||
f"{len(BASE_REPRO)} tau2 cells with b at 0-800 W at R)",
|
||||
not [k for k in T1 if rep[k]])
|
||||
for k in C5:
|
||||
show(k)
|
||||
check("T1 C5 cells (the energy meter late or never stepping): the figure is "
|
||||
"untrusted (contradicted or unknown) wherever the alarm stands, as EV-18 "
|
||||
"Expected 5 wants", all(not trusted(x) for k in C5
|
||||
for x in res(k).win(-10, 60) if bad(x)))
|
||||
|
||||
# --- T2: THE red-before test -------------------------------------------------- #
|
||||
T2 = BASE_REPRO
|
||||
for k in T2:
|
||||
r = res(k)
|
||||
lim = [x for x in r.win(0, 60) if x["floor_lim"]]
|
||||
check(f"T2 {k[3:]}: no notice, no ERROR, no red sample R-60..R+900; the "
|
||||
f"car explains every floor-limited cycle of R..R+60",
|
||||
r.quiet(-60, 900) and bool(lim) and all(x["explains"] for x in lim))
|
||||
check("T2 PRECONDITION: every reproducing cell is in the grid (b at 0, 400, "
|
||||
"800 W x 5 plug-in times; x10 and mono x1 with b at 1 200 W)",
|
||||
len(T2) == 17 and all(k in RES for k in T2))
|
||||
r2 = res("T1 core bw=0 t2 rp=180")
|
||||
x1 = r2.at(1)
|
||||
check("T2 PRECONDITION: in the rise cycle the reading shows b's 4 600 W, the "
|
||||
"guard is floor-limited and wants power",
|
||||
present(x1) and x1["batt"] == 4600.0 and x1["floor_lim"]
|
||||
and x1["wants"])
|
||||
|
||||
# --- T3: the battery W sweep --------------------------------------------------- #
|
||||
T3 = sorted(k for k in JOBS if k.startswith("T3 "))
|
||||
loud = [k for k in T3 if not res(k).quiet(-60, 900)]
|
||||
print(f" T3 cells {len(T3)}, with an alarm or red sample: {loud}")
|
||||
check("T3: tau1 and tau2, b at R 0..4 600 W in 200 W steps and 9 600 W "
|
||||
"(tau5): no alarm and no red sample in any cell", loud == [])
|
||||
|
||||
# --- T4 controller ------------------------------------------------------------- #
|
||||
for k in ("T4 +9 manual", "T4 +11 manual", "T4 +11 off"):
|
||||
show(k)
|
||||
check("T4: the house alone at aim + 9 W, b following the house from R: no "
|
||||
"alarm (base: R+1)", res("T4 +9 manual").quiet(-60, 900))
|
||||
check("T4: at aim + 11 W the alarm in the same cycle as base and as Off "
|
||||
"(R+0)", as_base("T4 +11 manual")
|
||||
and res("T4 +11 manual").rel_alarms()[:1]
|
||||
== res("T4 +11 off").rel_alarms()[:1] == [0])
|
||||
|
||||
|
||||
# --- T5 / T6: honest alarms ---------------------------------------------------- #
|
||||
def same_as_off(k):
|
||||
on, off = res(f"{k} manual"), res(f"{k} off")
|
||||
show(f"{k} manual")
|
||||
show(f"{k} off")
|
||||
a = on.rel_alarms()
|
||||
return (bool(a) and a == off.rel_alarms()
|
||||
and on.errors() == off.errors())
|
||||
|
||||
|
||||
for k in ("T5 t1", "T5 t4", "T5 tau5"):
|
||||
check(f"{k}: the excess is more than the car: PEAK_GUARD_FLOOR_LIMITED, "
|
||||
f"the ERROR and the notice at the same second as Off and as base",
|
||||
same_as_off(k) and as_base(f"{k} manual"))
|
||||
check(f"{k}: the car explains no cycle",
|
||||
not any(x["explains"] for x in res(f"{k} manual").tr))
|
||||
for n in (0, 1, 5):
|
||||
k = f"T6 step R+{n}"
|
||||
show(f"{k} manual")
|
||||
check(f"{k}: the house steps to aim + 1 900 W at R+{n}: the alarm and "
|
||||
f"the ERROR at the same second as base, R+{BASE_ALARMS[k + ' manual'][0]}"
|
||||
f" (no grace, no hold; Off alarms from R+0, where the car explains)",
|
||||
as_base(f"{k} manual") and res(f"{k} manual").errors()
|
||||
== BASE_ALARMS[f"{k} manual"])
|
||||
|
||||
|
||||
# --- T7: unknown values -------------------------------------------------------- #
|
||||
def only_while_unknown(r, t0=-60, t1=900):
|
||||
"""Every alarm / red cycle has an untrusted car figure in it or in the
|
||||
cycle before (the alarm clears within 1 cycle of the first trusted one)."""
|
||||
prev = None
|
||||
for x in r.win(t0, t1):
|
||||
if bad(x) and trusted(x) and (prev is None or trusted(prev)):
|
||||
return False
|
||||
prev = x
|
||||
return True
|
||||
|
||||
|
||||
show("T7(a) T2")
|
||||
check("T7(a) T2: inverter-a's reading unknown at R and R+1: no alarm",
|
||||
res("T7(a) T2").quiet(-60, 900))
|
||||
check("T7(a) T5: the alarm at the same second as base and as Off (the "
|
||||
"guard grades nothing without the reading)", as_base("T7(a) T5")
|
||||
and res("T7(a) T5").rel_alarms() == res("T7(a) T5 off").rel_alarms())
|
||||
show("T7(b) T2")
|
||||
check("T7(b) T2: the charger unavailable at R: an alarm only while the "
|
||||
"figure is unknown, cleared within 1 cycle of the first trusted one",
|
||||
only_while_unknown(res("T7(b) T2")))
|
||||
check("T7(b) T5: the alarm at the same second as base and as Off",
|
||||
as_base("T7(b) T5")
|
||||
and res("T7(b) T5").rel_alarms() == res("T7(b) T5 off").rel_alarms())
|
||||
|
||||
# --- T8: a stale car figure ---------------------------------------------------- #
|
||||
r8a = res("T8(a) Off 120 s, Manual R-5")
|
||||
show("T8(a) Off 120 s, Manual R-5")
|
||||
check("T8(a): nothing before Manual is trusted (car_alarm_w None)",
|
||||
all(x["w"] is None for x in r8a.tr if x["t"] < r8a.R - 5))
|
||||
check("T8(a): after Manual, as T2: no alarm R-60..R+900",
|
||||
r8a.quiet(-60, 900))
|
||||
r8b = res("T8(b) stale R-5..R+20")
|
||||
show("T8(b) stale R-5..R+20")
|
||||
check("T8(b) PRECONDITION: the figure goes untrusted (older than 15 s)",
|
||||
any(x["w"] is None for x in r8b.win(0, 25)))
|
||||
check("T8(b): the alarm only while the figure is stale, cleared within 1 "
|
||||
"cycle of the first fresh one", only_while_unknown(r8b))
|
||||
r8c, r8co = res("T8(c) frozen, the car stops"), res("T8(c) off")
|
||||
show("T8(c) frozen, the car stops")
|
||||
a8 = nth(r8c.rel_alarms(), 0)
|
||||
untr = first(int(x["t"] - r8c.R) for x in r8c.tr
|
||||
if x["t"] >= r8c.R - 30 and not trusted(x))
|
||||
check("T8(c): the alarm at base's second, as Off, within 114 s of the stop",
|
||||
present(a8) and a8 <= -30 + 114
|
||||
and as_base("T8(c) frozen, the car stops")
|
||||
and r8c.rel_alarms() == r8co.rel_alarms())
|
||||
check("T8(c): never explained after the figure goes untrusted",
|
||||
present(untr) and not any(x["explains"] for x in r8c.tr
|
||||
if x["t"] >= r8c.R + untr))
|
||||
|
||||
# --- T9: comms ------------------------------------------------------------------ #
|
||||
for nm in ("T2", "T5"):
|
||||
for k in (f"T9(a) {nm} b lost at R", f"T9(a) {nm} b lost at R-1",
|
||||
f"T9(b) {nm} P1 5 s late at R"):
|
||||
show(k)
|
||||
r = res(k)
|
||||
if nm == "T2":
|
||||
check(f"{k}: no alarm edge", r.edges() == [])
|
||||
else:
|
||||
check(f"{k}: the alarm at the base second "
|
||||
f"(R+{BASE_ALARMS[k][0]})", as_base(k))
|
||||
|
||||
# --- T10: a restart ------------------------------------------------------------ #
|
||||
for nm in ("T2", "T5"):
|
||||
tw = res(f"T10 {nm} twin")
|
||||
for k in (-2, -1, 0, 2):
|
||||
r = res(f"T10 {nm} restart R{k:+d}")
|
||||
show(f"T10 {nm} restart R{k:+d}")
|
||||
if nm == "T2" and k == 0:
|
||||
# the rise cycle R+1 has no reading from two cycles back: nothing
|
||||
# is discounted (the old behaviour), so the alarm is base's
|
||||
check("T10 T2 restart at R+0: no reading two cycles back in the "
|
||||
"rise cycle, so no discount: the alarm as base (R+1)",
|
||||
as_base("T10 T2 restart R+0"))
|
||||
elif nm == "T2":
|
||||
check(f"T10 T2 restart at R{k:+d}: no notice, no red sample, as "
|
||||
f"the unrestarted twin", r.quiet(-60, 900)
|
||||
and tw.quiet(-60, 900))
|
||||
else:
|
||||
check(f"T10 T5 restart at R{k:+d}: the alarm at the base second "
|
||||
f"and the twin's, red as the twin",
|
||||
as_base(f"T10 T5 restart R{k:+d}") and as_base("T10 T5 twin")
|
||||
and len(r.red()) == len(tw.red()))
|
||||
|
||||
# --- Review round 1 (Major), controller: the T6 step with a one-cycle burst ---- #
|
||||
for k in (5, 30):
|
||||
for hi in (1900, 2500):
|
||||
for burst in ("3000", "4600"):
|
||||
nm = f"RB step R+{k} aim+{hi} burst {burst} manual"
|
||||
r = res(nm)
|
||||
show(nm)
|
||||
check(f"{nm[:-7]}: P1 and the reading both show the burst: the "
|
||||
f"notice, the ERROR and the first red sample at the step, "
|
||||
f"R+{k}, as base", r.rel_alarms() == [k]
|
||||
and r.errors() == [k] and r.red()[:1] == [k])
|
||||
|
||||
# --- T11: the quarter edge ------------------------------------------------------ #
|
||||
for rr in (-1, 0, 1, 43):
|
||||
r = res(f"T11 T2 R=E{rr:+d}")
|
||||
show(f"T11 T2 R=E{rr:+d}")
|
||||
wa = [(int(x["t"] - r.E), x["within_aim"]) for x in r.tr
|
||||
if r.E - 1 <= x["t"] <= r.E]
|
||||
print(f" T11 T2 R=E{rr:+d}: within_aim at E-1/E+0 {wa} (F1, not "
|
||||
f"asserted)")
|
||||
check(f"T11 T2 R=E{rr:+d}: no alarm across the edge", r.quiet(-60, 900))
|
||||
check(f"T11 T5 R=E{rr:+d}: the alarm at the same seconds as base and "
|
||||
f"as Off", as_base(f"T11 T5 R=E{rr:+d}")
|
||||
and res(f"T11 T5 R=E{rr:+d}").rel_alarms()
|
||||
== res(f"T11 T5 R=E{rr:+d} off").rel_alarms())
|
||||
pre = res("T11 C4 T2 R=E+1")
|
||||
show("T11 C4 T2 R=E+1")
|
||||
wa = [(int(x["t"] - pre.E), x["within_aim"]) for x in pre.tr
|
||||
if pre.E - 1 <= x["t"] <= pre.E]
|
||||
print(f" T11 C4: within_aim at E-1/E+0 {wa} (F1, not asserted)")
|
||||
check("T11 C4 PRECONDITION: the guard wants power in the last 60 s of the "
|
||||
"old quarter (house 13 350 W all along, car 1 380 W)",
|
||||
all(x["wants"] for x in pre.tr if pre.E - 60 <= x["t"] < pre.E))
|
||||
sat = [x for x in pre.win(-60, -1) if x["red"]]
|
||||
print(f" T11 C4: red before R {[int(x['t'] - pre.R) for x in sat]} (near "
|
||||
f"the old quarter's end, the guard saturated: SAFETY-81's row)")
|
||||
check("T11 C4: SAFETY-126's latch carried over the edge, the reserve at "
|
||||
"E+1: no floor notice or ERROR R-60..R+900, no red sample from R; "
|
||||
"before R red only where the guard is saturated (not the floor alarm)",
|
||||
pre.quiet(0, 900) and not [t for t in pre.rel_alarms() if t >= -60]
|
||||
and all(x["lim"] and not x["floor_lim"] and not x["alarm"]
|
||||
for x in sat))
|
||||
|
||||
# --- T12: our own phase change -------------------------------------------------- #
|
||||
for k in (-15, 5):
|
||||
r = res(f"T12 T2 1->3 at R{k:+d}")
|
||||
show(f"T12 T2 1->3 at R{k:+d}")
|
||||
check(f"T12 T2, 1->3 at R{k:+d}: no alarm during our own pause or after",
|
||||
r.quiet(-60, 900))
|
||||
on, off = res(f"T12 T5 1->3 at R{k:+d}"), res(f"T12 T5 1->3 at R{k:+d} off")
|
||||
show(f"T12 T5 1->3 at R{k:+d}")
|
||||
a, ao = nth(on.rel_alarms(), 0), nth(off.rel_alarms(), 0)
|
||||
check(f"T12 T5, 1->3 at R{k:+d}: the alarm at base's second, no later "
|
||||
f"than Off's and within OWN_PAUSE_MAX_S "
|
||||
f"({ctl_car.OWN_PAUSE_MAX_S:.0f} s) of the request",
|
||||
present(a, ao) and a <= ao and as_base(f"T12 T5 1->3 at R{k:+d}")
|
||||
and a <= max(k, 0) + ctl_car.OWN_PAUSE_MAX_S)
|
||||
|
||||
# --- T13: a wrong charger reply ------------------------------------------------- #
|
||||
r13 = res("T13(a) draws 400 W manual")
|
||||
show("T13(a) draws 400 W manual")
|
||||
check("T13(a) 400 W: the energy meter never contradicts a 1 380 W figure "
|
||||
"when 400 W is drawn (CORR_RATIO 0.5 and its slack; EV-18 T9(b)), so "
|
||||
"nothing is uncorroborated and the figure explains; base's R+1 alarm "
|
||||
"was F-B", not any(x["contra"] for x in r13.tr)
|
||||
and all(x["w"] == CAR for x in r13.win(-60, 60)))
|
||||
r13c = res("T13(a) draws 100 W manual")
|
||||
show("T13(a) draws 100 W manual")
|
||||
show("T13(a) draws 100 W off")
|
||||
c0 = first(x["t"] for x in r13c.tr if x["contra"])
|
||||
a13 = nth(r13c.rel_alarms(), 0)
|
||||
check("T13(a) 100 W PRECONDITION: the energy meter contradicts the figure "
|
||||
"within 104 + 10 s of the plug-in (R-180)",
|
||||
present(c0) and c0 <= r13c.R - 180 + 114)
|
||||
check("T13(a) 100 W: the alarm at base's second and Off's, and never "
|
||||
"explained after the contradiction in that quarter",
|
||||
present(a13) and as_base("T13(a) draws 100 W manual")
|
||||
and r13c.rel_alarms() == res("T13(a) draws 100 W off").rel_alarms()
|
||||
and not any(x["explains"] for x in r13c.tr
|
||||
if present(c0) and x["t"] >= c0
|
||||
and x["block"] == r13c.at(0)["block"]))
|
||||
for k in ("T13(b) the write ignored, 0 A", "T14(a) 0 W in C",
|
||||
"T14(a) idle B"):
|
||||
show(f"{k} manual")
|
||||
check(f"{k}: the car at 0 W explains nothing: the alarm as Off",
|
||||
same_as_off(k) and not any(
|
||||
x["explains"] for x in res(f"{k} manual").tr))
|
||||
|
||||
# --- T14: configuration -------------------------------------------------------- #
|
||||
show("T14(b) ev_charger off")
|
||||
check("T14(b) ev_charger off: no explanation, the alarm as Off",
|
||||
res("T14(b) ev_charger off").rel_alarms()
|
||||
== res("T14(b) off").rel_alarms() != []
|
||||
and not any(x["explains"] for x in res("T14(b) ev_charger off").tr))
|
||||
for tj in ("t1", "t4"):
|
||||
show(f"T14(c) N=1 anchor {tj}")
|
||||
check(f"T14(c) N=1 anchor {tj}: no alarm",
|
||||
res(f"T14(c) N=1 anchor {tj}").quiet(-60, 900))
|
||||
check("T14(c) N=1 T5: the alarm at the same second as base and as Off",
|
||||
as_base("T14(c) N=1 T5") and res("T14(c) N=1 T5").rel_alarms()
|
||||
== res("T14(c) N=1 T5 off").rel_alarms())
|
||||
|
||||
# --- T15: one battery first ----------------------------------------------------- #
|
||||
for k in ("T15 anchor manual", "T15 honest manual", "T15 honest off"):
|
||||
show(k)
|
||||
check("T15 anchor: a at the reserve at R, b at R+360: no alarm",
|
||||
res("T15 anchor manual").quiet(-60, 900))
|
||||
check("T15 honest (house 19 000 W): the alarm after ALARM_HOLD_S at the "
|
||||
"base second (R+13; Off R+11, as base)", as_base("T15 honest manual"))
|
||||
|
||||
# --- T16: x10 -------------------------------------------------------------------- #
|
||||
for xn in ("x10", "mono1"):
|
||||
r = res(f"T16 {xn} T2")
|
||||
show(f"T16 {xn} T2")
|
||||
check(f"T16 {xn} T2 PRECONDITION: the rise cycle reads b's 4 600 W",
|
||||
present(r.at(10)) and r.at(10)["batt"] == 4600.0)
|
||||
check(f"T16 {xn} T2: no alarm (base: R+10, 10 red cycles)",
|
||||
r.quiet(-60, 900))
|
||||
t3 = sorted(k for k in JOBS if k.startswith(f"T16 {xn} T3 "))
|
||||
print(f" T16 {xn} T3 alarms "
|
||||
f"{[(k[10:], res(k).rel_alarms()) for k in t3]}")
|
||||
check(f"T16 {xn} T3 ({len(t3)} cells): no alarm R-60..R+300",
|
||||
all(res(k).quiet(-60, 300) for k in t3))
|
||||
# mono x1 / wall x10: the car's energy is counted on the monotonic clock,
|
||||
# a tenth of the wall's, so its share of the quarter is short and the
|
||||
# house latch sets late in the quarter (EV-18 F2, out of scope), as base.
|
||||
check(f"T16 {xn} T3: any later alarm at base's second (EV-18 F2)",
|
||||
all(as_base(k) if k in BASE_ALARMS else res(k).quiet(-60, 900)
|
||||
for k in t3))
|
||||
for k in ("T5", "T6"):
|
||||
show(f"T16 {xn} {k} manual")
|
||||
check(f"T16 {xn} {k}: the alarm at the base second",
|
||||
as_base(f"T16 {xn} {k} manual"))
|
||||
check(f"T16 {xn} T7(b) T2: an alarm only while the figure is unknown",
|
||||
only_while_unknown(res(f"T16 {xn} T7(b) T2")))
|
||||
for rr in (-10, 0, 10, 40):
|
||||
check(f"T16 {xn} T11 T2 R=E{rr:+d}: no alarm",
|
||||
res(f"T16 {xn} T11 T2 R=E{rr:+d}").quiet(-60, 900))
|
||||
check(f"T16 {xn} T11 T5 R=E{rr:+d}: the alarm at the base seconds",
|
||||
as_base(f"T16 {xn} T11 T5 R=E{rr:+d}"))
|
||||
|
||||
# --- T17: no flicker -------------------------------------------------------------- #
|
||||
r17 = res("T17 flicker")
|
||||
print(f" T17 alarm edges per quarter {r17.edges_per_quarter()}")
|
||||
check("T17: the house alone straddles aim + 10 W, the batteries cross the "
|
||||
"reserve 3 times: at most one alarm edge per quarter",
|
||||
all(v <= 1 for v in r17.edges_per_quarter().values()))
|
||||
|
||||
# --- N2: the car explains only with a trusted, non-zero figure ----------------- #
|
||||
bad2 = sorted(k for k, r in RES.items()
|
||||
if any(x["explains"] and not trusted(x) for x in r.tr))
|
||||
check(f"N2: car_explains never True with car_alarm_w None, 0 W or "
|
||||
f"contradicted, in any of the {len(RES)} runs: {bad2}", bad2 == [])
|
||||
|
||||
for k in ("N2 no energy entity", "N2 reports 11 kW at 6 A"):
|
||||
show(f"{k} manual")
|
||||
check(f"{k}: the figure is not trusted for the alarm (no corroboration, "
|
||||
f"or capped by the read-back): nothing explained, the alarm as Off",
|
||||
same_as_off(k) and not any(
|
||||
x["explains"] for x in res(f"{k} manual").tr))
|
||||
check("N2 PRECONDITION: the charger without an energy entity reports a "
|
||||
"fresh 1 380 W", all(x["car_raw"] == CAR for x in
|
||||
res("N2 no energy entity manual").win(-60, 60)))
|
||||
|
||||
# --- N4 / T20: no control change --------------------------------------------- #
|
||||
for nm in ("T2", "T5"):
|
||||
a = res("T1 core bw=0 t2 rp=180") if nm == "T2" else res("T10 T5 twin")
|
||||
check(f"N4 {nm}: the claim, the floor, the setpoints and the charger "
|
||||
f"writes are those of the same run with the car never explaining",
|
||||
a.cmd == res(f"N4 {nm} explain off").cmd)
|
||||
|
||||
# --- N5: at most one floor-alarm edge per quarter ------------------------------ #
|
||||
# Base 43b0db7 has 2 edges in the first quarter of these runs: the guard lets
|
||||
# go for one cycle at R+1 (the battery reads 0 W, the meter does not show it
|
||||
# yet), in Off and in the C5 cells too. Not EV-19's; head must not add one.
|
||||
BASE_TWO = ["T1 b: energy first step late", "T1 b: energy never steps",
|
||||
"T11 T5 R=E+0", "T11 T5 R=E+0 off", "T11 T5 R=E+1",
|
||||
"T11 T5 R=E+1 off", "T16 mono1 T11 T5 R=E+0",
|
||||
"T16 mono1 T11 T5 R=E+10", "T16 mono1 T6 off",
|
||||
"T16 x10 T11 T5 R=E+0", "T16 x10 T11 T5 R=E+10", "T16 x10 T6 off",
|
||||
"T6 step R+0 off", "T6 step R+1 off", "T6 step R+5 off"] + [
|
||||
f"RB step R+{k} aim+{hi} burst {b} off" for k in (5, 30)
|
||||
for hi in (1900, 2500) for b in (3000, 4600)]
|
||||
many = sorted(k for k, r in RES.items()
|
||||
if any(v > (2 if k in BASE_TWO and q == 0 else 1)
|
||||
for q, v in r.edges_per_quarter().items()))
|
||||
check(f"N5: at most one floor-alarm edge per quarter in every run, and no "
|
||||
f"more than base where base has two ({len(RES)} runs): {many}",
|
||||
many == [])
|
||||
|
||||
print()
|
||||
print("FAIL: " + ", ".join(fails) if fails else "PASS: every check passed")
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -1,724 +0,0 @@
|
||||
"""EV-20: the car charger's Solar mode, spare sun to the car: the arithmetic,
|
||||
the modes, the start, the hold and the pause, the phases (T1-T20, T56).
|
||||
`python3 -B test_ev20.py`
|
||||
|
||||
The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and
|
||||
`chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit
|
||||
rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section
|
||||
names the T-ids and N-ids of reports/EV-20-test-plan.md it implements.
|
||||
"Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare
|
||||
2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start.
|
||||
Times are the cycle's second; `race` runs use the production order (read, the
|
||||
writer settles, the cycle).
|
||||
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402
|
||||
from app import mqtt, validate, web, main as app_main # noqa: E402
|
||||
from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402
|
||||
import ev20_sun as S # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
from ev20_kit import * # noqa: E402,F401,F403
|
||||
from ev20_kit import LOG, check, fails, report # noqa: E402,F401
|
||||
from named_absence import given, nth, present # noqa: E402,F401
|
||||
from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401
|
||||
_until)
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
print("1. THE ARITHMETIC (T3, T9, T10, N11)")
|
||||
# =========================================================================== #
|
||||
# T3: signed spare. `spare_w(car, site battery W (discharge +), grid)`.
|
||||
T3 = {"a": ((0.0, -5000.0, -2000.0), 7000.0),
|
||||
"b": ((0.0, -6000.0, 6900.0), -900.0),
|
||||
"c": ((1380.0, 9600.0, -5220.0), -3000.0),
|
||||
"d": ((1380.0, 9600.0, -7220.0), -1000.0),
|
||||
"e": ((0.0, 0.0, -3000.0), 3000.0)}
|
||||
got = {k: spare_w(*a) for k, (a, _) in T3.items()}
|
||||
check(f"T3: the signed spare, (a) to (e) = 7000, -900, -3000, -1000, 3000 W "
|
||||
f"within 1 W ({got})",
|
||||
all(got[k] is not None and abs(got[k] - w) <= 1.0
|
||||
for k, (_, w) in T3.items()))
|
||||
clip = {k: max(0.0, a[0] + max(0.0, -a[1]) - max(0.0, a[2]))
|
||||
for k, (a, _) in T3.items()}
|
||||
check("T3/N11: a clipped formula fails (a), (c) and (e); ours does not: no "
|
||||
"positive spare from a grid charge or from batteries giving more than "
|
||||
"the house uses",
|
||||
all(abs(clip[k] - T3[k][1]) > 1.0 for k in "ace")
|
||||
and got["b"] < 0 and got["c"] < 0 and got["d"] < 0)
|
||||
check("T3/T4: a missing or non-numeric figure is no spare (None, NaN, "
|
||||
"'unavailable')",
|
||||
spare_w(0.0, None, 100.0) is None
|
||||
and spare_w(0.0, float("nan"), 100.0) is None
|
||||
and spare_w(0.0, 100.0, "unavailable") is None
|
||||
and spare_w(None, 0.0, 0.0) is None)
|
||||
|
||||
# T9: the margin, both priorities, Car first on a 2400 W spare, 1 phase.
|
||||
t9 = {m: amps_for(carmode.car_target_w(2400.0, 0.0, m, carmode.FIRST_CAR), 1,
|
||||
16) for m in (0, 100, 300, 1000)}
|
||||
check(f"T9: ev_margin_w 0, 100, 300, 1000 on a 2400 W spare: 10, 10, 9, 6 A "
|
||||
f"({t9})", t9 == {0: 10.0, 100: 10.0, 300: 9.0, 1000: 6.0})
|
||||
check("T9: the margin is taken once, in both priorities (Batteries first with "
|
||||
"the room 0 is the same as Car first)",
|
||||
carmode.car_target_w(2400.0, 0.0, 300, carmode.FIRST_BATT)
|
||||
== carmode.car_target_w(2400.0, 5000.0, 300, carmode.FIRST_CAR)
|
||||
== 2100.0)
|
||||
# T10: rounded down, clamped.
|
||||
t10 = (amps_for(1900, 1), amps_for(2299, 1), amps_for(6900, 3),
|
||||
amps_for(6899, 3))
|
||||
check(f"T10: 1900 and 2299 W on 1 phase, 6900 and 6899 W on 3: 8, 9, 10, 9 A "
|
||||
f"({t10}); a rounding would give 10 at 2299 W",
|
||||
t10 == (8.0, 9.0, 10.0, 9.0) and round(2299 / 230) == 10)
|
||||
check("T10: ev_max_a 10 with 6.9 kW on 1 phase is 10 A; a 13 A station limit "
|
||||
"bounds it to 13 A", amps_for(6900, 1, 10) == 10.0
|
||||
and amps_for(6900, 1, 13) == 13.0)
|
||||
rnd = random.Random(20)
|
||||
bad10 = []
|
||||
for _ in range(1000):
|
||||
tw = rnd.choice([float("nan"), -rnd.uniform(0, 5000), 1e9,
|
||||
rnd.uniform(0, 12000), None])
|
||||
n = rnd.choice([1, 3])
|
||||
clamp = rnd.choice([None, 6.0, 10.0, 13.0, 16.0, 32.0, 40.0])
|
||||
p = SolarPlan(n)
|
||||
for k in range(400):
|
||||
p.step(float(k), target_w=tw, n_now=n, auto=False, clamp=clamp,
|
||||
start_s=120.0, pause_s=300.0)
|
||||
if p.a > 0.0:
|
||||
hi = math.floor(clamp) if clamp is not None else CH.ENTITY_MAX_A
|
||||
want = amps_for(tw, p.n, clamp)
|
||||
if not (CH.MIN_A <= p.a <= hi) or (
|
||||
p.why == "running" and p.a != want):
|
||||
bad10.append((tw, n, clamp, p.a, want))
|
||||
break
|
||||
check(f"T10/N1 property: 1000 random spares (NaN, negative, 1e9, None), "
|
||||
f"phases and limits: every non-zero current is floor(target / (230 x "
|
||||
f"n)) inside [6 A, clamp] ({bad10[:2]})", not bad10)
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n2. MODE SOLAR AND WHERE SPARE SUN GOES FIRST (T1, T2, T56)")
|
||||
# =========================================================================== #
|
||||
res1 = {}
|
||||
|
||||
|
||||
async def _web(p, c):
|
||||
import socket
|
||||
import aiohttp
|
||||
from aiohttp import web as aioweb
|
||||
app = web.build_app(c, selfcfg=object())
|
||||
runner = aioweb.AppRunner(app)
|
||||
await runner.setup()
|
||||
sock = socket.socket()
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
sock.close()
|
||||
await aioweb.TCPSite(runner, "127.0.0.1", port).start()
|
||||
try:
|
||||
async with aiohttp.ClientSession() as s:
|
||||
for key, body in (("solar", {"action": "car_mode",
|
||||
"value": "solar"}),
|
||||
("night", {"action": "car_mode",
|
||||
"value": "night"}),
|
||||
("first", {"action": "car_sun_first",
|
||||
"value": "car"})):
|
||||
async with s.post(f"http://127.0.0.1:{port}/action",
|
||||
json=body) as rr:
|
||||
res1[key] = (rr.status, await rr.json(content_type=None))
|
||||
async with s.get(f"http://127.0.0.1:{port}/status?lang=en") as rr:
|
||||
res1["status"] = await rr.json(content_type=None)
|
||||
finally:
|
||||
await runner.cleanup()
|
||||
|
||||
|
||||
r1 = run("T1", std, 400, mode="off", first="batteries", events={
|
||||
10: _web,
|
||||
200: act("car_mode", "night", res1, "night_a"),
|
||||
201: act("car_mode", "bogus", res1, "bogus_a")})
|
||||
c1 = r1["c"]
|
||||
w1 = cur_writes(r1)
|
||||
check(f"T1: POST /action car_mode solar from the page is stored at once "
|
||||
f"(car_mode=solar) and answers 200 ({res1.get('solar')})",
|
||||
res1.get("solar", (0,))[0] == 200
|
||||
and r1["store"].data.get("car_mode") == "solar")
|
||||
check(f"T1: the next writer steps run Solar with no restart: the start rule "
|
||||
f"from the choice, 10 A at 10 + 120 s ({w1[:2]})",
|
||||
bool(w1) and w1[0][1] == 10.0 and 128 <= w1[0][0] <= 132)
|
||||
check("T1: Night and Bogus are refused (page and action), nothing changes",
|
||||
res1.get("night", (0,))[0] == 400 and "error" in res1.get("night_a", {})
|
||||
and "error" in res1.get("bogus_a", {}) and c1.car_mode == "solar"
|
||||
and r1["store"].data.get("car_mode") == "solar")
|
||||
pl = dict(mqtt.car_payloads((16, (1, 3))))
|
||||
sel = pl.get("homeassistant/select/goodwe_ctl_car_mode/config", {})
|
||||
sf = pl.get("homeassistant/select/goodwe_ctl_car_sun_first/config", {})
|
||||
check(f"T1: select.goodwe_car_mode options are exactly Off, Manual, Solar "
|
||||
f"({sel.get('options')})", sel.get("options") == ["Off", "Manual",
|
||||
"Solar"])
|
||||
check(f"T2: select.goodwe_car_sun_first is announced with Batteries and Car "
|
||||
f"({sf.get('options')}), labels as carmode's",
|
||||
sf.get("object_id") == "goodwe_car_sun_first"
|
||||
and sf.get("options") == ["Batteries", "Car"]
|
||||
and mqtt.CAR_FIRST_LABELS == carmode.FIRST_LABELS
|
||||
and mqtt.CAR_MODE_LABELS == carmode.MODE_LABELS)
|
||||
check("T1: /status offers Off, Manual and Solar, and where spare sun goes "
|
||||
"first", res1.get("status", {}).get("car", {}).get("modes")
|
||||
== ["off", "manual", "solar"]
|
||||
and res1["status"]["car"].get("first", {}).get("choices")
|
||||
== ["batteries", "car"])
|
||||
cmd = mqtt.parse_car_command
|
||||
check("T1/T2: MQTT parses Solar and the two priorities; Night, Bogus, an "
|
||||
"unknown label and a retained command are refused",
|
||||
cmd("goodwe_ctl/car/mode/set", b"Solar", False)[:2]
|
||||
== ("car_mode", "solar")
|
||||
and cmd("goodwe_ctl/car/sun_first/set", b"Car", False)[:2]
|
||||
== ("car_sun_first", "car")
|
||||
and cmd("goodwe_ctl/car/sun_first/set", b"Batteries", False)[1]
|
||||
== "batteries"
|
||||
and cmd("goodwe_ctl/car/mode/set", b"Night", False)[1] is None
|
||||
and cmd("goodwe_ctl/car/mode/set", b"Bogus", False)[1] is None
|
||||
and cmd("goodwe_ctl/car/sun_first/set", b"Sun", False)[1] is None
|
||||
and cmd("goodwe_ctl/car/sun_first/set", b"Car", True)[2] == "retained")
|
||||
|
||||
# T1 from MQTT, and T2: the priority from HA, a retained and an unknown one.
|
||||
r2 = run("T2", S.drive, const(900.0), const(7900.0), dur=260, mode="off",
|
||||
first="batteries", socs={"a": 71.0, "b": 100.0}, events={
|
||||
5: mqtt_cmd("goodwe_ctl/car/mode/set", b"Solar"),
|
||||
160: mqtt_cmd("goodwe_ctl/car/sun_first/set", b"Car", True),
|
||||
161: mqtt_cmd("goodwe_ctl/car/sun_first/set", b"Sun"),
|
||||
200: mqtt_cmd("goodwe_ctl/car/sun_first/set", b"Car")})
|
||||
c2, tr2 = r2["c"], r2["trace"]
|
||||
w2 = cur_writes(r2)
|
||||
check(f"T1: MQTT 'Solar' is applied: the store says solar and Batteries "
|
||||
f"first writes 8 A (scenario 2) after the start rule ({w2[:1]})",
|
||||
r2["store"].data.get("car_mode") == "solar" and bool(w2)
|
||||
and w2[0][1] == 8.0)
|
||||
check("T2: a retained command and an unknown label change nothing (Batteries "
|
||||
"until 200 s)", all(x["why"] for x in tr2)
|
||||
and c2.car_sun_inputs is not None
|
||||
and [x for x in w2 if x[0] < 200] == w2[:1])
|
||||
check(f"T2: Car at 200 s: the arithmetic changes next cycle and the new "
|
||||
f"current (16 A) is written at once, the 30 s rule passed ({w2})",
|
||||
any(t in (200.0, 201.0) and a == 16.0 for t, a, _ in w2)
|
||||
and r2["store"].data.get("car_sun_first") == "car")
|
||||
|
||||
|
||||
async def _rebuild():
|
||||
st = r2["store"]
|
||||
from app.main import Controller
|
||||
import opt11_identity as rig
|
||||
c = Controller(dict(c2.o), r2["plant"], st, rig._Pub(),
|
||||
stop=asyncio.Event())
|
||||
return c.car_first, c.car_mode
|
||||
|
||||
|
||||
check(f"T2: the priority is runtime state in the store and survives a "
|
||||
f"rebuild of the Controller on it ({asyncio.run(_rebuild())})",
|
||||
asyncio.run(_rebuild()) == ("car", "solar"))
|
||||
# T2: the 30 s rule still applies after a priority change.
|
||||
r2b = run("T2b", S.drive, const(900.0), const(7900.0), dur=200,
|
||||
first="batteries", socs={"a": 71.0, "b": 100.0},
|
||||
events={130: act("car_sun_first", "car")})
|
||||
w2b = cur_writes(r2b)
|
||||
check(f"T2: Car chosen 10 s after Batteries first wrote 8 A: 16 A waits for "
|
||||
f"the 30 s rule (at 150 s, not before) ({w2b})",
|
||||
[a for _, a, _ in w2b] == [8.0, 16.0] and w2b[1][0] == w2b[0][0] + 30)
|
||||
|
||||
# T56: rollback. The base build has no Solar in MODES; with it taken out, the
|
||||
# stored mode reads as Off and the action is refused.
|
||||
keep_modes = carmode.MODES
|
||||
carmode.MODES = (carmode.OFF, carmode.MANUAL)
|
||||
try:
|
||||
t56 = carmode.start_mode({}, "solar")
|
||||
finally:
|
||||
carmode.MODES = keep_modes
|
||||
check("T56: a build without Solar reads a stored car_mode=solar as Off "
|
||||
"(start_mode); on head unknown modes still map to Off",
|
||||
t56 == "off" and carmode.start_mode({}, "night") == "off"
|
||||
and carmode.start_mode({}, "bogus") == "off"
|
||||
and carmode.start_mode({}, "solar") == "solar")
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n3. THE SPARE, THE ROOM, THE START (T5, T6, T7, T8, T9, T13)")
|
||||
# =========================================================================== #
|
||||
for race in (False, True):
|
||||
tag = "race" if race else "step"
|
||||
r6 = run("T6", S.drive, const(900.0), const(7900.0), dur=600,
|
||||
first="batteries", socs={"a": 71.0, "b": 100.0}, race=race)
|
||||
c6, tr6 = r6["c"], r6["trace"]
|
||||
w6 = cur_writes(r6)
|
||||
batt = [r6["plant"].batt_of("a", t) for t in range(400, 600)]
|
||||
exp = [r6["plant"].grid(t) for t in range(400, 600)]
|
||||
ok6 = next((x["ok"] for x in tr6 if x["ok"] is not None), None)
|
||||
check(f"T6 [{tag}]: scenario 2, Batteries first: spare 7000, room 5000, "
|
||||
f"car 1900 W -> 8 A on 1 phase after the 120 s dwell ({w6}, the "
|
||||
f"dwell from {ok6})",
|
||||
[a for _, a, _ in w6] == [8.0] and ok6 is not None
|
||||
and 120 <= w6[0][0] - ok6 <= 121
|
||||
and tr6[300]["spare"] is not None
|
||||
and abs(tr6[300]["spare"] - 7000.0) <= 50.0
|
||||
and selects(r6) == [])
|
||||
check(f"T6 [{tag}]: steady: A charges 5000 +-100 W, export about 160 W, "
|
||||
f"no drift ({min(batt):.0f}..{max(batt):.0f} W, grid "
|
||||
f"{min(exp):.0f}..{max(exp):.0f} W)",
|
||||
all(-5100.0 <= b <= -4900.0 for b in batt)
|
||||
and all(-260.0 <= g <= -60.0 for g in exp))
|
||||
nevers(r6, f"T6 [{tag}]")
|
||||
blk6 = homeview.car_block(c6, None)
|
||||
check(f"T6: the Why is why.solar_batt ({blk6['why']!r})",
|
||||
blk6["why"].startswith("Batteries first."))
|
||||
check("T6: v1 room (rating - charge now) would give 16 A on this spare: the "
|
||||
"rating rule is what makes it 8 A",
|
||||
amps_for(carmode.car_target_w(7000.0, 5000.0 - 5000.0, 100,
|
||||
carmode.FIRST_BATT), 1, 16) == 16.0
|
||||
and amps_for(carmode.car_target_w(7000.0, 5000.0, 100,
|
||||
carmode.FIRST_BATT), 1, 16) == 8.0)
|
||||
|
||||
r7 = run("T7", S.drive, const(900.0), const(7900.0), dur=700, first="car",
|
||||
socs={"a": 71.0, "b": 100.0})
|
||||
c7 = r7["c"]
|
||||
w7, s7 = cur_writes(r7), selects(r7)
|
||||
check(f"T7: scenario 2, Car first, auto: starts on 1 phase at the clamp "
|
||||
f"(16 A) ({w7[:1]})", bool(w7) and w7[0][1] == 16.0
|
||||
and r7["trace"][150]["ph"] == 1)
|
||||
check(f"T7: after 180 s at >= 4.5 kW the safe sequence to 3 phases, then "
|
||||
f"floor(6900/690) = 10 A ({w7}, selects {[(x[0], x[2]) for x in s7]})",
|
||||
[a for _, a, _ in w7] == [16.0, 0.0, 10.0] and len(s7) == 1
|
||||
and s7[0][2] == 3 and 298 <= w7[1][0] <= 303)
|
||||
bt7 = [r7["plant"].batt(t) for t in range(500, 700)]
|
||||
check(f"T7: the batteries charge 100 +-50 W ({min(bt7):.0f}..{max(bt7):.0f})",
|
||||
all(-150.0 <= b <= -50.0 for b in bt7))
|
||||
check(f"T7: the Why is why.solar_car "
|
||||
f"({homeview.car_block(c7, None)['why']!r})",
|
||||
homeview.car_block(c7, None)["why"].startswith("Car first:"))
|
||||
nevers(r7, "T7")
|
||||
|
||||
# T8: the room.
|
||||
r8a = run("T8a", S.drive, const(500.0), step_fn((200, 4500.0), base=8000.0),
|
||||
dur=560, first="car", socs={"a": 60.0, "b": 100.0},
|
||||
events={200: act("car_sun_first", "batteries")})
|
||||
w8a = cur_writes(r8a)
|
||||
check(f"T8 (a): Batteries first, spare 4000 W, A may charge (5000 W), B full: "
|
||||
f"4000 - 5000 - 100 < 0: the 6 A hold, then 0 A at the pause ({w8a})",
|
||||
[a for _, a, _ in w8a][-2:] == [6.0, 0.0]
|
||||
and 499 <= w8a[-1][0] <= 502)
|
||||
r8b = run("T8b", std, 200, sun=const(3500.0), first="batteries")
|
||||
check(f"T8 (b): both full, spare 3000 W: 2900 W, 12 A "
|
||||
f"({cur_writes(r8b)})", [a for _, a, _ in cur_writes(r8b)] == [12.0])
|
||||
|
||||
|
||||
def _room(socs, **setup):
|
||||
out = {}
|
||||
|
||||
def probe(p, c):
|
||||
for k, v in setup.items():
|
||||
v(c)
|
||||
out["room"] = c.car_room_w()
|
||||
S.drive(const(500.0), const(7500.0), dur=3, first="batteries",
|
||||
socs=socs, events={2: probe})
|
||||
return out["room"]
|
||||
|
||||
|
||||
def _a_off(c):
|
||||
from app import packmode
|
||||
from app.store import unit_key
|
||||
c.store.data[unit_key("inverter-a", packmode.USE_KEY)] = False
|
||||
|
||||
|
||||
def _a_refuse(c):
|
||||
c.inverters[0].refused = -1
|
||||
|
||||
|
||||
rooms = {"off": _room({"a": 60.0, "b": 60.0}, x=_a_off),
|
||||
"refusing": _room({"a": 60.0, "b": 60.0}, x=_a_refuse),
|
||||
"ceiling": _room({"a": 100.0, "b": 60.0}),
|
||||
"both": _room({"a": 60.0, "b": 60.0})}
|
||||
check(f"T8 (c): A Off, refusing a charge or at its ceiling leaves B's 4600 W "
|
||||
f"as the room; both able gives 9600 W ({rooms})",
|
||||
rooms == {"off": 4600.0, "refusing": 4600.0, "ceiling": 4600.0,
|
||||
"both": 9600.0})
|
||||
r8c = run("T8c", S.drive, const(500.0), const(7500.0), dur=200,
|
||||
first="batteries", socs={"a": 100.0, "b": 60.0})
|
||||
check(f"T8 (c): spare 7000, room 4600: 2300 W, 10 A ({cur_writes(r8c)})",
|
||||
[a for _, a, _ in cur_writes(r8c)] == [10.0])
|
||||
r8d = run("T8d", S.drive, const(900.0), step_fn((300, 1600.0), base=7900.0),
|
||||
dur=700, first="batteries", socs={"a": 71.0, "b": 100.0})
|
||||
w8d = cur_writes(r8d)
|
||||
check(f"T8 (d): scenario 2's cloud (sun 1.6 kW, spare 700): 6 A for 300 s, "
|
||||
f"then 0 A ({w8d})", [a for _, a, _ in w8d] == [8.0, 6.0, 0.0]
|
||||
and 599 <= w8d[-1][0] <= 602)
|
||||
|
||||
# T9 through the real Controller: Car first, spare 2400 W.
|
||||
t9r = {}
|
||||
for m in (0, 100, 300, 1000):
|
||||
rr = S.drive(const(500.0), step_fn((200, 2900.0), base=5000.0), dur=260,
|
||||
first="car", socs=dict(FULL), opts={"ev_margin_w": m})
|
||||
t9r[m] = [a for t, a, _ in cur_writes(rr) if t >= 200]
|
||||
check(f"T9: running, then a 2400 W spare: the Controller writes 10, 10, 9, "
|
||||
f"6 A for margins 0, 100, 300, 1000 W ({t9r}; 1400 W is 6 A, not a "
|
||||
f"hold)", t9r == {0: [10.0], 100: [10.0], 300: [9.0], 1000: [6.0]})
|
||||
|
||||
# T10 through the Controller: a 13 A station limit with plenty of sun.
|
||||
sim10 = SimCharger(setpoint_a=0)
|
||||
r10 = run("T10", std, 300, sun=const(9000.0), sim=sim10,
|
||||
opts={"ev_phases": "1"},
|
||||
events={200: lambda p, c: setattr(p.ch, "station_a", 13.0)})
|
||||
check(f"T10: 16 A, then the station limit comes down to 13 A: Solar writes "
|
||||
f"13 A and never more, clamp_faults == [] ({cur_writes(r10)})",
|
||||
[a for _, a, _ in cur_writes(r10)] == [16.0, 13.0]
|
||||
and r10["c"].charger.clamp_faults == [])
|
||||
|
||||
# T5: the car's figure.
|
||||
p5 = {}
|
||||
r5 = run("T5", std, 200, events={50: lambda p, c: p5.update(
|
||||
trusted=c.car.car_w_trusted(c.car_now()), spare=c.car_spare_w(
|
||||
c.car_now()))})
|
||||
tr5 = r5["trace"]
|
||||
check(f"T5 (i)(ii): paused/idle, state B at 0 A, a fresh 0 W: the car counts "
|
||||
f"0 W and the spare is computed (car_w_trusted is None there) ({p5})",
|
||||
tr5[50]["st"] == "B" and p5.get("spare") is not None
|
||||
and abs(p5["spare"] - 2400.0) < 1.0 and p5.get("trusted", 1) is None)
|
||||
check(f"T5 (i)(ii): the start rule passes on it: 10 A at 120 s "
|
||||
f"({cur_writes(r5)[:1]})", cur_writes(r5)[:1]
|
||||
and cur_writes(r5)[0][1] == 10.0)
|
||||
|
||||
|
||||
def _stop_car_keep_c(p, c):
|
||||
"""The car stops drawing while mode3 stays C, and the power sensor
|
||||
sticks at what it read."""
|
||||
p.ch.freeze_power()
|
||||
p.ch.stop_delay_s = 1e9
|
||||
p.ch.full = True
|
||||
|
||||
|
||||
sim5 = SimCharger(setpoint_a=0)
|
||||
r5c = run("T5c", std, 900, sim=sim5, sun=const(2900.0),
|
||||
events={300: _stop_car_keep_c})
|
||||
tr5c = r5c["trace"]
|
||||
gone = next((x["t"] for x in tr5c if x["t"] > 300 and x["spare"] is None),
|
||||
None)
|
||||
w5c = cur_writes(r5c)
|
||||
check(f"T5 (iii): a frozen 2300 W figure after the car stopped (mode3 C): "
|
||||
f"dropped once the energy meter does not corroborate it (<= 110 s; "
|
||||
f"at {gone})", gone is not None and gone - 300 <= 110)
|
||||
check(f"T5 (iii): then the hold: no new current once it is dropped, 0 A by "
|
||||
f"300 + 2 s after it ({w5c})",
|
||||
gone is not None and w5c[-1][1] == 0.0
|
||||
and gone + 299 <= w5c[-1][0] <= gone + 302
|
||||
and not [x for x in w5c if gone <= x[0] and x[1] > 0.0])
|
||||
|
||||
|
||||
def _down(p, c):
|
||||
p.ch.go_unavailable(True)
|
||||
|
||||
|
||||
r5d = run("T5d", std, 500, events={300: _down})
|
||||
check("T5 (iv): a charger reading older than 15 s (this driver: the charger "
|
||||
"does not answer) is no spare, and nothing is written while it is down",
|
||||
r5d["trace"][330]["spare"] is None
|
||||
and [a for _, a, _ in cur_writes(r5d)] == [10.0])
|
||||
|
||||
# C6: one write clock. A plan whose start dwell is done waits 30 s from
|
||||
# Manual's latest non-zero write (`ext_at`), and from its own.
|
||||
p6 = SolarPlan(1)
|
||||
starts6 = []
|
||||
for k in range(300):
|
||||
p6.ext_at = 150.0
|
||||
p6.step(float(k), target_w=3000.0, n_now=1, auto=False, clamp=16,
|
||||
start_s=120.0, pause_s=300.0)
|
||||
if p6.a > 0.0 and not starts6:
|
||||
starts6.append(k)
|
||||
check(f"C6: Manual wrote at 150 s; Solar's start dwell is done at 120 s but "
|
||||
f"its first current waits for 180 s ({starts6})", starts6 == [180])
|
||||
r6m = std(400, mode="manual", sim=SimCharger(setpoint_a=0),
|
||||
opts={"ev_start_min": 1},
|
||||
events={100: act("car_current", 12), 105: act("car_mode", "solar")})
|
||||
w6m = [(t, a) for t, a, _ in cur_writes(r6m)]
|
||||
man = [x[0] for x in r6m["sim"].log if x[2] > 0.0 and x[0] <= 106]
|
||||
check(f"C6: Manual writes 12 A, then Solar is chosen: Solar's own first "
|
||||
f"write is 0 A, and no current of Solar's within 30 s of Manual's "
|
||||
f"({man}, Solar {w6m})",
|
||||
w6m[:1] and w6m[0][1] == 0.0 and present(nth(man, -1))
|
||||
and not [t for t, a in w6m if a > 0.0 and t - nth(man, -1) < 30.0])
|
||||
|
||||
# T13: the start rule.
|
||||
for race in (False, True):
|
||||
tag = "race" if race else "step"
|
||||
d = 1 if race else 0
|
||||
ra = std(900, sun=const(500.0 + 100.0 + 1609.0), race=race)
|
||||
rb = std(200, sun=const(500.0 + 100.0 + 1610.0), race=race)
|
||||
rc = std(300, sun=lambda t: 500.0 + 100.0 + (1500.0 if at_s(t) == 60
|
||||
else 1610.0), race=race)
|
||||
check(f"T13 (a) [{tag}]: 1609 W on 1 phase for 900 s: no start",
|
||||
cur_writes(ra) == [])
|
||||
# `race`: the writer's step runs a second later, the meter's sample not.
|
||||
check(f"T13 (b) [{tag}]: 1610 W: 7 A at 120 s, not 119 s "
|
||||
f"({cur_writes(rb)})", [(t, a) for t, a, _ in cur_writes(rb)]
|
||||
in ([(120.0, 7.0)], [(120.0 + d, 7.0)]))
|
||||
check(f"T13 (c) [{tag}]: a 1-cycle dip to 1500 W at 60 s: the start at "
|
||||
f"181 s ({cur_writes(rc)})", [(t, a) for t, a, _ in cur_writes(rc)]
|
||||
in ([(181.0, 7.0)], [(181.0 + d, 7.0)]))
|
||||
rd = run("T13d", std, 300, sun=const(500.0 + 100.0 + 6900.0), phases=3)
|
||||
wd, sd = cur_writes(rd), selects(rd)
|
||||
check(f"T13 (d): auto, 6900 W, the charger left on 3 phases: 0 A kept, "
|
||||
f"select 1, then the current; no non-zero write on 3 phases first "
|
||||
f"({wd}, {[(x[0], x[2], x[4]) for x in sd]})",
|
||||
len(sd) == 1 and sd[0][2] == 1 and sd[0][4] == 0.0
|
||||
and wd and wd[0][1] == 16.0 and wd[0][0] >= sd[0][0] - 1 + 10)
|
||||
nevers(rd, "T13 (d)")
|
||||
re1 = std(600, sun=const(500.0 + 100.0 + 4829.0), phases=3,
|
||||
opts={"ev_phases": "3"})
|
||||
re2 = std(200, sun=const(500.0 + 100.0 + 4830.0), phases=3,
|
||||
opts={"ev_phases": "3"})
|
||||
check(f"T13 (e): ev_phases 3: none at 4829 W; 7 A at 120 s for 4830 W "
|
||||
f"({cur_writes(re2)})", cur_writes(re1) == []
|
||||
and [(t, a) for t, a, _ in cur_writes(re2)] == [(120.0, 7.0)]
|
||||
and selects(re2) == [])
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n4. THE 30 s / 1 A RULE, THE HOLD AND THE PAUSE (T11, T12, T14-T16)")
|
||||
# =========================================================================== #
|
||||
# T11: 8 A worth, write at t; at t+5 10 A worth.
|
||||
for race in (False, True):
|
||||
tag = "race" if race else "step"
|
||||
r11 = std(300, sun=step_fn((125, 600.0 + 2300.0), base=600.0 + 1840.0),
|
||||
race=race)
|
||||
w11 = cur_writes(r11)
|
||||
check(f"T11 (a) [{tag}]: 8 A at t, 10 A worth from t+5: 10 A at t+30 "
|
||||
f"(+-1 cycle), not before ({w11})",
|
||||
[a for _, a, _ in w11] == [8.0, 10.0]
|
||||
and 29 <= w11[1][0] - w11[0][0] <= 31)
|
||||
r11b = std(800, sun=step_fn((130, 600.0 + 8.9 * 230.0),
|
||||
base=600.0 + 1840.0), race=race)
|
||||
check(f"T11 (b) [{tag}]: 8 -> 8.9 A worth for 600 s: no write "
|
||||
f"({cur_writes(r11b)})", [a for _, a, _ in cur_writes(r11b)]
|
||||
== [8.0])
|
||||
|
||||
# T12: an exit 2 s after a normal write: the 0 A within 1 cycle.
|
||||
T12 = {
|
||||
"Stop": lambda p, c: setattr(c, "auto", False),
|
||||
"Off": act("car_mode", "off"),
|
||||
"shadow": lambda p, c: c.o.__setitem__("shadow_mode", "on"),
|
||||
"unplug": lambda p, c: p.ch.unplug(),
|
||||
"latch": lambda p, c: setattr(c.circ_wd, "tripped", True),
|
||||
"error": lambda p, c: (setattr(p.ch, "error", "12: Socket error"),
|
||||
p.ch.fault("E")),
|
||||
}
|
||||
t12 = {}
|
||||
for name, fn in T12.items():
|
||||
rr = std(260, sun=step_fn((150, 600.0 + 2760.0), base=600.0 + 2300.0),
|
||||
events={152: fn})
|
||||
w = cur_writes(rr)
|
||||
t12[name] = w
|
||||
check(f"T12: every exit 2 s after a normal write (12 A at 150 s) gets its "
|
||||
f"0 A within 1 cycle, the 30 s gate never delays it "
|
||||
f"({ {k: v[-2:] for k, v in t12.items()} })",
|
||||
all(len(v) >= 2 and v[-2][:2] == (150.0, 12.0) and v[-1][1] == 0.0
|
||||
and v[-1][0] - 152 <= 1 for v in t12.values()))
|
||||
p12 = SolarPlan(1)
|
||||
p12.a, p12.set_at, p12.low_since, p12.why = 6.0, 98.0, -200.0, "hold"
|
||||
p12.step(100.0, target_w=1000.0, n_now=1, auto=False, clamp=16, start_s=120,
|
||||
pause_s=300)
|
||||
check("T12: the pause is never gated: a plan whose last change was 2 s ago "
|
||||
"pauses at its 300 s (0 A)", p12.a == 0.0)
|
||||
|
||||
# T14: at 8 A, the target drops to 1200 W (5.2 A).
|
||||
for race in (False, True):
|
||||
tag = "race" if race else "step"
|
||||
d = 1 if race else 0
|
||||
r14 = std(800, sun=step_fn((200, 600.0 + 1200.0), base=600.0 + 1840.0),
|
||||
race=race, rows=False)
|
||||
w14 = cur_writes(r14)
|
||||
check(f"T14 (a) [{tag}]: 6 A written, then 0 A once at 300 s, not 299 s "
|
||||
f"({w14})", [a for _, a, _ in w14] == [8.0, 6.0, 0.0]
|
||||
and w14[2][0] in (500.0, 500.0 + d))
|
||||
r14b = std(1100, sun=lambda t: 600.0 + (1840.0 if at_s(t) < 200 else
|
||||
1500.0 if 499 <= at_s(t) < 510
|
||||
else 1200.0),
|
||||
race=race)
|
||||
w14b = cur_writes(r14b)
|
||||
check(f"T14 (b) [{tag}]: back >= 6 A at 299 s, then low again: no 0 A "
|
||||
f"then; the next dip needs a fresh 300 s ({w14b})",
|
||||
[a for _, a, _ in w14b][-1:] == [0.0]
|
||||
and w14b[-1][0] in (810.0, 810.0 + d)
|
||||
and not any(a == 0.0 and t < 800 for t, a, _ in w14b))
|
||||
blk14 = homeview.car_block(r14["c"], None)
|
||||
check(f"T14: the card says Waiting for sun and why.solar_paused "
|
||||
f"({blk14['chip']!r}, {blk14['why']!r})",
|
||||
blk14["chip"] == "Waiting for sun"
|
||||
and blk14["why"].startswith("Too little spare sun for 6 A."))
|
||||
|
||||
# T15: the hold at the peak reserve.
|
||||
r15a = run("T15a", S.drive, const(500.0), step_fn((200, 1000.0),
|
||||
base=3000.0),
|
||||
dur=600, first="car", socs={"a": 19.0, "b": 19.0},
|
||||
opts={"peak_soc_floor": 20})
|
||||
tr = r15a["trace"]
|
||||
imp = sum(max(0.0, min(x["car"], x["grid"])) for x in tr if x["t"] >= 200)
|
||||
w15a = cur_writes(r15a)
|
||||
check(f"T15 (a): A and B at the peak reserve: the car's grid import in the "
|
||||
f"hold is at most 1380 W x 302 s (116 Wh), then 0 A ({imp / 3600:.0f} "
|
||||
f"Wh, {w15a})", imp <= 1380.0 * 302.0 and w15a[-1][1] == 0.0
|
||||
and 499 <= w15a[-1][0] <= 502)
|
||||
r15b = run("T15b", S.drive, const(500.0), step_fn((200, 1000.0),
|
||||
base=3000.0),
|
||||
dur=600, first="car", socs={"a": 19.0, "b": 60.0},
|
||||
opts={"peak_soc_floor": 20})
|
||||
gr = [x["grid"] for x in r15b["trace"] if 240 <= x["t"] < 495]
|
||||
check(f"T15 (b): A at the reserve, B at 60 %: B covers the car, the grid "
|
||||
f"is about 0 in the hold ({min(gr):.0f}..{max(gr):.0f} W)",
|
||||
all(abs(g) <= 150.0 for g in gr))
|
||||
|
||||
# T16: the wall clock jumps; the dwells are monotonic.
|
||||
for jump in (3600.0, -3600.0):
|
||||
def jmp(p, c, jump=jump):
|
||||
p.utc_off = jump
|
||||
r16 = std(800, sun=step_fn((200, 600.0 + 1200.0), base=600.0 + 1840.0),
|
||||
events={60: jmp, 300: jmp})
|
||||
w16 = cur_writes(r16)
|
||||
check(f"T16 ({jump:+.0f} s): a start dwell and a hold across a wall-clock "
|
||||
f"jump: start at 120 s, pause at 300 s, monotonic ({w16})",
|
||||
[(t, a) for t, a, _ in w16][:1] == [(120.0, 8.0)]
|
||||
and w16[-1] == (500.0, 0.0, True))
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n5. AUTO PHASES, THE SAFE SEQUENCE, A ONE-PHASE CAR (T17-T20)")
|
||||
# =========================================================================== #
|
||||
for race in (False, True):
|
||||
tag = "race" if race else "step"
|
||||
d = 1 if race else 0
|
||||
r17 = std(800, sun=step_fn((400, 600.0 + 4500.0), base=600.0 + 3000.0),
|
||||
race=race)
|
||||
w17, s17 = cur_writes(r17), selects(r17)
|
||||
z = [t for t, a, _ in w17 if a == 0.0]
|
||||
check(f"T17 [{tag}]: 4500 W from 400 s: the sequence starts (its 0 A) at "
|
||||
f"580 s, not 579 s ({w17}, {[x[0] for x in s17]})",
|
||||
z[:1] in ([580.0], [580.0 + d]) and len(s17) == 1
|
||||
and s17[0][2] == 3)
|
||||
r17b = std(3600, sun=step_fn((400, 600.0 + 4499.0), base=600.0 + 3000.0))
|
||||
check("T17: 4499 W for an hour on 1 phase: never a select",
|
||||
selects(r17b) == [])
|
||||
r17c = std(1900, sun=step_fn((400, 600.0 + 4500.0), (1000, 600.0 + 3999.0),
|
||||
base=600.0 + 3000.0))
|
||||
s17c = selects(r17c)
|
||||
check(f"T17: on 3 phases, 3999 W from 1000 s: to 1 phase at 1300 s "
|
||||
f"({[(x[0], x[2]) for x in s17c]}, {cur_writes(r17c)[-2:]})",
|
||||
len(s17c) == 2 and s17c[1][2] == 1 and 1300 <= s17c[1][0] <= 1312
|
||||
and cur_writes(r17c)[-1][1] == 16.0)
|
||||
r17d = std(4600, sun=step_fn((400, 600.0 + 4500.0), (1000, 600.0 + 4000.0),
|
||||
base=600.0 + 3000.0))
|
||||
check(f"T17: on 3 phases, 4000 W for an hour: never back to 1 phase, no "
|
||||
f"pause ({[(x[0], x[2]) for x in selects(r17d)]})",
|
||||
len(selects(r17d)) == 1 and r17d["sim"].setpoint_a == 6.0)
|
||||
r17e = std(3600, sun=lambda t: 600.0 + 4000.0 + 499.0 * (t % 2))
|
||||
check("T17: the 4.0-4.5 kW band for an hour: never a select",
|
||||
selects(r17e) == [])
|
||||
nevers(r17c, "T17")
|
||||
|
||||
# T18: up, down, up within 10 minutes.
|
||||
r18 = std(2400, sun=step_fn((400, 600.0 + 4600.0), (700, 600.0 + 3000.0),
|
||||
(1100, 600.0 + 4600.0), base=600.0 + 3000.0))
|
||||
s18 = [x[0] for x in selects(r18)]
|
||||
check(f"T18: crossings up, down, up: at most one select per 600 s, the "
|
||||
f"second waits for 600 s after the first ({s18})",
|
||||
len(s18) >= 2 and all(b - a >= 600.0 for a, b in zip(s18, s18[1:]))
|
||||
and s18[1] - s18[0] < 620)
|
||||
nevers(r18, "T18")
|
||||
|
||||
# T19: every Solar phase change, a slow car among them.
|
||||
for slow in (False, True):
|
||||
sim19 = SimCharger(setpoint_a=0)
|
||||
if slow:
|
||||
sim19.stop_delay_s = 15.0
|
||||
sim19.ramp_w_s = 300.0
|
||||
r19 = std(1600, sun=step_fn((400, 600.0 + 6900.0), (1000, 600.0 + 3000.0),
|
||||
base=600.0 + 3000.0), sim=sim19)
|
||||
seq_bad = []
|
||||
log19 = r19["sim"].log
|
||||
for i, (t, what, v, pw, sp) in enumerate(log19):
|
||||
if what != "phases":
|
||||
continue
|
||||
before = [x for x in log19[:i] if x[1] == "current"]
|
||||
after = [x for x in log19[i + 1:] if x[1] == "current"]
|
||||
if not before or before[-1][2] != 0.0:
|
||||
seq_bad.append(("no 0 A first", t))
|
||||
if pw >= carmode.QUIET_W and before \
|
||||
and t - before[-1][0] < carmode.ZERO_WAIT_S:
|
||||
seq_bad.append(("select while drawing", t, pw))
|
||||
if not after or after[0][0] - t < carmode.SETTLE_S:
|
||||
seq_bad.append(("no 10 s settle", t))
|
||||
n = v
|
||||
if after and after[0][2] not in (amps_for(
|
||||
r19["plant"].sun(after[0][0]) - 500.0 - 100.0, n, 16),
|
||||
CH.MIN_A):
|
||||
seq_bad.append(("not floor(car_w/(230 x n))", after[0]))
|
||||
check(f"T19 ({'slow car' if slow else 'quick car'}): every select comes "
|
||||
f"after the 0 A, under 100 W or out of C (or the 20 s cap), then "
|
||||
f"10 s, then floor(target/(230 x new n)) ({seq_bad}, "
|
||||
f"{[(x[0], x[2]) for x in selects(r19)]})",
|
||||
not seq_bad and len(selects(r19)) == 2)
|
||||
nevers(r19, f"T19 {'slow' if slow else 'quick'}")
|
||||
# A car that is still drawing at EV-04's 20 s cap (200 W/s from 6 A on 3
|
||||
# phases): no select, the current back on the old phases, and the plan back
|
||||
# where it was (nothing meant for 1 phase is written on 3).
|
||||
for pmin, back in ((10, 6.0), (5, 0.0)):
|
||||
sim19f = SimCharger(setpoint_a=0)
|
||||
sim19f.stop_delay_s, sim19f.ramp_w_s = 15.0, 200.0
|
||||
r19f = std(1500, sun=step_fn((400, 600.0 + 6900.0),
|
||||
(1000, 600.0 + 3000.0),
|
||||
base=600.0 + 3000.0), sim=sim19f,
|
||||
opts={"ev_pause_min": pmin})
|
||||
w19f = [(t, a) for t, a, _ in cur_writes(r19f) if t >= 1290]
|
||||
check(f"T19 (failed, ev_pause_min {pmin}): the car still draws at the "
|
||||
f"20 s cap: no select to 1 phase; "
|
||||
f"{'the hold 6 A back on 3 phases' if back else 'the hold has run out, so the 0 A stands (N3)'}"
|
||||
f"; no 1-phase current on 3 phases "
|
||||
f"({w19f}, selects {[(x[0], x[2]) for x in selects(r19f)]})",
|
||||
len(selects(r19f)) == 1 and w19f[:1] == [(1300.0, 0.0)]
|
||||
and (nth(w19f, 1)[1] == 6.0 if back else len(w19f) == 1)
|
||||
and not [a for t, a in w19f if a > 6.0])
|
||||
nevers(r19f, f"T19 (failed, {pmin} min)")
|
||||
r19a = std(1800, sun=const(600.0 + 6900.0), opts={"ev_phases": "1"})
|
||||
check(f"T19: fixed 1 with 6.9 kW for 30 min: no select, 16 A "
|
||||
f"({cur_writes(r19a)})", selects(r19a) == []
|
||||
and [a for _, a, _ in cur_writes(r19a)] == [16.0])
|
||||
r19b = std(900, sun=const(600.0 + 3000.0), opts={"ev_phases": "3"},
|
||||
phases=3)
|
||||
check("T19: fixed 3 with 3 kW: no select, no start (4830 W needed)",
|
||||
selects(r19b) == [] and cur_writes(r19b) == [])
|
||||
r19c = std(1000, sun=step_fn((400, 600.0 + 3000.0), base=600.0 + 5600.0),
|
||||
opts={"ev_phases": "3"}, phases=3)
|
||||
check(f"T19: fixed 3 running, then 3 kW: no select, the hold, then the "
|
||||
f"pause ({cur_writes(r19c)})", selects(r19c) == []
|
||||
and [a for _, a, _ in cur_writes(r19c)] == [8.0, 6.0, 0.0])
|
||||
|
||||
# T20: a one-phase car on a 3-phase allowance.
|
||||
sim20 = SimCharger(setpoint_a=0)
|
||||
r20 = run("T20", std, 900, sim=sim20, phases=3, car_phases=1,
|
||||
opts={"ev_phases": "3"},
|
||||
sun=step_fn((400, 600.0 + 2900.0 - 100.0), base=600.0 + 4900.0),
|
||||
events={700: lambda p, c: p.ch.unplug(),
|
||||
710: lambda p, c: p.ch.plug_in(car_phases=3)})
|
||||
tr20 = r20["trace"]
|
||||
marked = next((x["t"] for x in tr20 if x["single"]), None)
|
||||
w20 = cur_writes(r20)
|
||||
check(f"T20: the one-phase car is marked within 30 s of drawing (start "
|
||||
f"{w20[:1]}, marked at {marked})",
|
||||
marked is not None and w20 and marked - w20[0][0] <= 30)
|
||||
check(f"T20: on 1-phase arithmetic: 16 A on 4.8 kW, then floor(2800/230) = "
|
||||
f"12 A on 2.9 kW, no pause from the 4.2 A 3-phase figure ({w20})",
|
||||
12.0 in [a for t, a, _ in w20 if 400 <= t < 700]
|
||||
and not any(a == 0.0 for t, a, _ in w20 if t < 700))
|
||||
check("T20: cleared on unplug; a balanced 3-phase car is never marked",
|
||||
not tr20[705]["single"] and not any(x["single"] for x in tr20
|
||||
if x["t"] >= 700))
|
||||
|
||||
report()
|
||||
@@ -1,731 +0,0 @@
|
||||
"""EV-20: every way out of Solar ends at 0 A (T23-T37, T61; N9, N12, N14).
|
||||
`python3 -B test_ev20_exits.py`
|
||||
|
||||
The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and
|
||||
`chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit
|
||||
rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section
|
||||
names the T-ids and N-ids of reports/EV-20-test-plan.md it implements.
|
||||
"Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare
|
||||
2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start.
|
||||
Times are the cycle's second; `race` runs use the production order (read, the
|
||||
writer settles, the cycle).
|
||||
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402
|
||||
from app import mqtt, validate, web, main as app_main # noqa: E402
|
||||
from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402
|
||||
import ev20_sun as S # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
from ev20_kit import * # noqa: E402,F401,F403
|
||||
from ev20_kit import LOG, check, fails, report # noqa: E402,F401
|
||||
from named_absence import given, nth, present # noqa: E402,F401
|
||||
from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401
|
||||
_until)
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n6. EXIT PATHS END AT 0 A (T23-T37, T61, N9, N12, N14)")
|
||||
# =========================================================================== #
|
||||
|
||||
|
||||
r23 = run("T23", std, 300, finale=_shutdown)
|
||||
o23 = sets_order(r23)
|
||||
z23 = [i for i, (t, e, v) in enumerate(o23) if e == SET and v == 0.0]
|
||||
inv23 = [i for i, (t, e, v) in enumerate(o23)
|
||||
if e.startswith("number.sp_") and i > (z23[0] if z23 else 0)]
|
||||
check(f"T23: Controller.shutdown() in Solar at 10 A: one 0 A, sent BEFORE the "
|
||||
f"first inverter 0 W of command_site_release ({o23[-4:]})",
|
||||
len(z23) == 1 and bool(inv23) and r23["sim"].setpoint_a == 0.0)
|
||||
for start, want in (("keep", "solar"), ("off", "off")):
|
||||
sim23 = r23["sim"]
|
||||
n0 = len(sim23.log)
|
||||
rr = std(200, sim=sim23, store=r23["store"], mode="solar",
|
||||
opts={"ev_mode_start": start})
|
||||
if start == "off":
|
||||
rr["store"].data["car_mode"] = "solar"
|
||||
new = sim23.log[n0:]
|
||||
t_restart = 301.0 if start == "keep" else 0.0
|
||||
check(f"T23: restart on the same store, ev_mode_start {start}: "
|
||||
f"{want}{', paused' if want == 'solar' else ''}, "
|
||||
f"{'no non-zero write for 120 s' if want == 'solar' else 'nothing written'} "
|
||||
f"({[(x[0], x[2]) for x in new]})",
|
||||
rr["c"].car_mode == want
|
||||
and not [x for x in new if x[2] > 0.0 and x[0] - t_restart < 120]
|
||||
and (want == "solar" or new == []))
|
||||
t_restart = sim23.t
|
||||
|
||||
|
||||
for kind in ("error", "ignore"):
|
||||
def mk(kind=kind):
|
||||
return TSim(setpoint_a=0, windows=[(299.5, 306.5, kind)])
|
||||
sim = mk()
|
||||
r23b = run("T23b", std, 300, sim=sim, finale=_shutdown)
|
||||
tries = [(t, v) for t, v in attempts(r23b) if t >= 299]
|
||||
gap = [b[0] - a[0] for a, b in zip(tries, tries[1:])]
|
||||
rel = _until(r23b, 299.0)
|
||||
check(f"T23 (b) D3 [{kind}]: the 0 A refused for 7 s from shutdown: tries "
|
||||
f"about 0, 5, 10 s (3 at most, >= 4 s apart), the third taken, then "
|
||||
f"the inverters 0 W, all within 15 s ({tries}, release +{rel})",
|
||||
len(tries) == 3 and all(g >= 4.0 for g in gap)
|
||||
and r23b["sim"].setpoint_a == 0.0 and rel is not None
|
||||
and rel <= 15.0 and r23b["c"].car_solar.released is True)
|
||||
for kind in ("error", "ignore"):
|
||||
sim = TSim(setpoint_a=0, windows=[(299.5, 1e9, kind)])
|
||||
n = LOG.mark()
|
||||
r23c = run("T23c", std, 300, sim=sim, finale=_shutdown)
|
||||
tries = [(t, v) for t, v in attempts(r23c) if t >= 299]
|
||||
rel = _until(r23c, 299.0)
|
||||
warn = [m for m in LOG.since(n, "WARNING") if "CHARGER_RELEASE" in m]
|
||||
check(f"T23 (c) D3 [{kind}]: refused for the whole shutdown: 3 tries, the "
|
||||
f"inverters' 0 W by 15 s (+{rel}), one warning that the car may still "
|
||||
f"be charging, the notice raised after the inverters ({tries})",
|
||||
len(tries) == 3 and rel is not None and rel <= 15.0
|
||||
and len(warn) == 1 and any(n_ == messages.ID_CAR_RELEASE
|
||||
for _, n_ in r23c["raised"])
|
||||
and r23c["store"].data.get(ctl_car.CAR_RELEASE_KEY) is True)
|
||||
sim.windows = []
|
||||
n0 = len(sim.log)
|
||||
rr = std(300, sim=sim, store=r23c["store"], mode="solar")
|
||||
new = [(x[0], x[2]) for x in sim.log[n0:]]
|
||||
check(f"T23 (c)/D2 [{kind}]: restart on the same store (keep): the first "
|
||||
f"charger write is 0 A, then only the start rule; the notice comes "
|
||||
f"down ({new})", new[:1] and new[0][1] == 0.0
|
||||
and new[0][0] - sim.log[n0][0] <= 1
|
||||
and not [x for x in new[1:] if x[1] > 0 and x[0] - new[0][0] < 119]
|
||||
and any(n_ == messages.ID_CAR_RELEASE
|
||||
for _, n_ in rr["plant"].dismissed))
|
||||
|
||||
|
||||
async def _hang_shutdown(p, c):
|
||||
p.hang = True
|
||||
await c.shutdown()
|
||||
|
||||
keep_wait = ctl_car.RELEASE_WAIT_S
|
||||
ctl_car.RELEASE_WAIT_S = 0.3
|
||||
try:
|
||||
import time as _time
|
||||
t_0 = _time.monotonic()
|
||||
r23u = run("T23u", std, 300, plant_cls=HangPlant, finale=_hang_shutdown)
|
||||
took = _time.monotonic() - t_0
|
||||
finally:
|
||||
ctl_car.RELEASE_WAIT_S = keep_wait
|
||||
inv_u = [v for t, e, v in r23u["plant"].sets if e.startswith("number.sp_")
|
||||
and t >= 299]
|
||||
check(f"T23: a charger that never answers delays the inverter release by "
|
||||
f"RELEASE_WAIT_S at most (15 s; 0.3 s here), then the inverters go to "
|
||||
f"0 W ({inv_u[-2:]}) and the warning stands",
|
||||
ctl_car.RELEASE_WAIT_S == 15.0 and inv_u and inv_u[-1] == 0.0
|
||||
and r23u["c"]._car_release_failed)
|
||||
|
||||
# T24: the control task dies.
|
||||
|
||||
|
||||
r24 = run("T24", std, 300, finale=_dies)
|
||||
o24 = sets_order(r24)
|
||||
z24 = [i for i, (t, e, v) in enumerate(o24) if e == SET and v == 0.0]
|
||||
check(f"T24: the control task dies: 0 A once, before the inverters' 0 W; "
|
||||
f"exit code 70 unchanged ({o24[-3:]})",
|
||||
len(z24) == 1 and app_main.EXIT_CONTROL_DIED == 70
|
||||
and r24["plant"].died == (True, 1)
|
||||
and any(e.startswith("number.sp_") for t, e, v in o24[z24[0]:]))
|
||||
sim24 = TSim(setpoint_a=0, windows=[(299.5, 1e9, "error")])
|
||||
r24c = run("T24c", std, 300, sim=sim24, finale=_dies)
|
||||
check(f"T24 D3: refused throughout: 3 tries about 5 s apart, the inverters "
|
||||
f"by 15 s, the warning ({[t for t, v in attempts(r24c) if t >= 299]})",
|
||||
len([1 for t, v in attempts(r24c) if t >= 299]) == 3
|
||||
and _until(r24c, 299.0) <= 15.0 and r24c["c"]._car_release_failed)
|
||||
sim24b = TSim(setpoint_a=0, windows=[(299.5, 306.5, "error")])
|
||||
r24b = run("T24b", std, 300, sim=sim24b, finale=_dies)
|
||||
check("T24 D3: refused for 7 s: the third try is taken, the inverters after",
|
||||
r24b["sim"].setpoint_a == 0.0 and r24b["c"].car_solar.released is True)
|
||||
|
||||
# T25: Stop, with shadow_mode off and the shipped auto.
|
||||
for sm in ("off", "auto"):
|
||||
r25 = std(800, opts={"shadow_mode": sm},
|
||||
events={300: act("auto_toggle", None),
|
||||
600: act("auto_toggle", None)})
|
||||
w25 = cur_writes(r25)
|
||||
check(f"T25 [shadow_mode {sm}]: Stop at 300 s: 0 A once within 1 cycle, "
|
||||
f"nothing while stopped; after Start only the start rule "
|
||||
f"(10 A at 720 s) ({w25})",
|
||||
[(t, a) for t, a, _ in w25] == [(120.0, 10.0), (300.0, 0.0),
|
||||
(720.0, 10.0)])
|
||||
|
||||
# T26: the safety latches.
|
||||
for name, fn in (("sign_wd", lambda p, c: setattr(c.inverters[0].sign_wd,
|
||||
"tripped", True)),
|
||||
("site_sign_wd", lambda p, c: setattr(c.site_sign_wd,
|
||||
"tripped", True)),
|
||||
("circ_wd", lambda p, c: setattr(c.circ_wd, "tripped",
|
||||
True))):
|
||||
r26 = std(700, events={300: fn})
|
||||
check(f"T26 [{name}]: 0 A once, nothing else while latched "
|
||||
f"({cur_writes(r26)})", [(t, a) for t, a, _ in cur_writes(r26)]
|
||||
== [(120.0, 10.0), (300.0, 0.0)])
|
||||
|
||||
# T27: a charger error.
|
||||
n27 = LOG.mark()
|
||||
blk27 = {}
|
||||
|
||||
|
||||
def _err_card(p, c):
|
||||
blk27["b"] = homeview.car_block(c, None)
|
||||
|
||||
|
||||
def _err_clear(p, c):
|
||||
p.ch.error = "0: No Error"
|
||||
p.ch.state = "B"
|
||||
|
||||
|
||||
r27 = std(900, events={300: _err, 400: _err_card, 600: _err_clear})
|
||||
w27 = cur_writes(r27)
|
||||
warn27 = [m for m in LOG.since(n27, "WARNING") if "CHARGER_ERROR" in m]
|
||||
check(f"T27: a charger error: 0 A once, no write during it, one warning; the "
|
||||
f"start rule after it clears (10 A at 720 s) ({w27}, {len(warn27)})",
|
||||
[(t, a) for t, a, _ in w27] == [(120.0, 10.0), (300.0, 0.0),
|
||||
(720.0, 10.0)] and len(warn27) == 1)
|
||||
check(f"T27: the card shows it ({blk27.get('b', {}).get('why')!r})",
|
||||
blk27.get("b", {}).get("why", "").startswith("The charger reports an "
|
||||
"error"))
|
||||
|
||||
# T28: a stuck reading.
|
||||
blk28 = {}
|
||||
|
||||
|
||||
r28 = std(800, sun=step_fn((125, 600.0 + 2760.0), base=600.0 + 2300.0),
|
||||
events={150: _freeze_after_write,
|
||||
300: lambda p, c: blk28.update(rows=c.checks()),
|
||||
600: lambda p, c: p.ch.freeze(False)},
|
||||
rows=True)
|
||||
w28 = cur_writes(r28)
|
||||
zt = [(t, ok) for t, a, ok in w28 if a == 0.0]
|
||||
check(f"T28: the reading freezes as the 12 A write (150 s) goes out: 0 A at "
|
||||
f"150 + 60 s (+1 cycle +10 s), not confirmed by the frozen read-back, "
|
||||
f"tried 3 times 60 s apart, then the gave-up row ({w28})",
|
||||
len(zt) == 3 and 210 <= zt[0][0] <= 221
|
||||
and all(not ok for _, ok in zt)
|
||||
and [b[0] - a[0] for a, b in zip(zt, zt[1:])] == [60.0, 60.0]
|
||||
and "charger_refused" in r28["trace"][450]["amber"])
|
||||
check("T28: the amber row 'Charger reading may be stuck'",
|
||||
"charger_stuck" in [x["id"] for x in blk28.get("rows", [])])
|
||||
check(f"T28: no non-zero write until a reading moves; then the start rule "
|
||||
f"(0 A confirmed by the moved reading, 10 A 120 s later) ({w28[-1:]})",
|
||||
not [1 for t, a, ok in w28 if a > 0 and 150 < t < 600]
|
||||
and w28[-1][1] == 12.0 and 718 <= w28[-1][0] <= 722
|
||||
if len(w28) > 4 else False)
|
||||
# (b) the frozen read-back shows 0 A while the charger is not at 0 A: a stuck
|
||||
# reading confirms nothing, so the 0 A is written (mutant `stuck_trust`).
|
||||
r28b = std(800, sun=step_fn((200, 600.0 + 1000.0), (330, 600.0 + 6000.0),
|
||||
base=600.0 + 2300.0),
|
||||
opts={"ev_pause_min": 1, "ev_start_min": 1},
|
||||
events={300: _freeze_after_write,
|
||||
700: lambda p, c: p.ch.freeze(False)})
|
||||
w28b = cur_writes(r28b)
|
||||
st28 = [x["t"] for x in r28b["trace"] if x["fault"] == "stuck"]
|
||||
check(f"T28 (b): frozen at 0 A, then Solar starts (the write unconfirmed): "
|
||||
f"once stuck, the 0 A is written, not read off the frozen 0 A, and the "
|
||||
f"charger ends at 0 A ({w28b}, stuck from {st28[:1]})",
|
||||
bool(st28) and [x for x in w28b if x[0] >= st28[0]][:1]
|
||||
and [x for x in w28b if x[0] >= st28[0]][0][1] == 0.0
|
||||
and r28b["sim"].setpoint_a == 0.0)
|
||||
|
||||
# T29: the charger unavailable 300-420 s.
|
||||
T29 = {"i": lambda p, c: None,
|
||||
"ii": lambda p, c: p.ch.set_current(16),
|
||||
"iii": lambda p, c: p.ch.set_current(6),
|
||||
"iv": lambda p, c: p.ch.set_phases(3)}
|
||||
for k, fn in T29.items():
|
||||
n = LOG.mark()
|
||||
rr = std(700, events={300: lambda p, c: p.ch.go_unavailable(True),
|
||||
360: fn,
|
||||
420: lambda p, c: p.ch.go_unavailable(False)},
|
||||
rows=True)
|
||||
w = cur_writes(rr)
|
||||
trr = rr["trace"]
|
||||
other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m]
|
||||
check(f"T29 ({k}): nothing tried while down; the first write after it is "
|
||||
f"0 A within 1 cycle; no CHARGER_OTHER, no hold, no amber row for "
|
||||
f"the charger's own value; then the start rule ({w})",
|
||||
[a for t, a, _ in w if 300 <= t < 420] == []
|
||||
and [x for x in w if x[0] >= 420][:1]
|
||||
and [x for x in w if x[0] >= 420][0][1] == 0.0
|
||||
and [x for x in w if x[0] >= 420][0][0] <= 421
|
||||
and not other and not any(x["hold"] for x in trr)
|
||||
and not any("charger_other" in x["amber"] for x in trr)
|
||||
and (k != "i" or [(t, a) for t, a, _ in w]
|
||||
== [(120.0, 10.0), (420.0, 0.0), (540.0, 10.0)]))
|
||||
|
||||
# T29 (v): Solar paused at 0 A before the charger went away; it comes back
|
||||
# at 16 A (a reboot default): the 0 A is written first all the same.
|
||||
n = LOG.mark()
|
||||
rr = std(900, sun=step_fn((200, 600.0 + 1000.0), (560, 600.0 + 2300.0),
|
||||
base=600.0 + 2300.0),
|
||||
events={540: lambda p, c: p.ch.go_unavailable(True),
|
||||
545: lambda p, c: p.ch.set_current(16),
|
||||
600: lambda p, c: p.ch.go_unavailable(False)})
|
||||
w = cur_writes(rr)
|
||||
after = [x for x in w if x[0] >= 600]
|
||||
other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m]
|
||||
check(f"T29 (v): paused at 0 A, the charger away 540-600 s and back at 16 A: "
|
||||
f"0 A first within 1 cycle, then the start rule; no CHARGER_OTHER ({w})",
|
||||
present(nth(after, 0)) and nth(after, 0)[1] == 0.0
|
||||
and nth(after, 0)[0] <= 601 and not other
|
||||
and [a for t, a, _ in w if t < 600][-1:] == [0.0])
|
||||
|
||||
# T30: Home Assistant not answering 300-420 s.
|
||||
for k, fn in (("i", lambda p, c: None),
|
||||
("ii", lambda p, c: p.ch.set_current(16))):
|
||||
n = LOG.mark()
|
||||
rr = std(700, events={300: lambda p, c: setattr(p, "ha_down", True),
|
||||
360: both(fn, mqtt_cmd("goodwe_ctl/car/current/set",
|
||||
b"14")),
|
||||
420: lambda p, c: setattr(p, "ha_down", False)})
|
||||
w = cur_writes(rr)
|
||||
other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m]
|
||||
after = [x for x in w if x[0] >= 420]
|
||||
check(f"T30 ({k}): HA not answering: nothing written while down (a lost "
|
||||
f"MQTT command changes no current); when back 0 A first, then the "
|
||||
f"start rule; no CHARGER_OTHER ({w})",
|
||||
[x for x in attempts(rr) if 300 <= x[0] < 420] == []
|
||||
and present(nth(after, 0)) and nth(after, 0)[1] == 0.0
|
||||
and nth(after, 0)[0] <= 422
|
||||
and not other and not any(x["hold"] for x in rr["trace"]))
|
||||
|
||||
# T4: battery A's power or the site's battery power missing (None), not a
|
||||
# number (NaN) or "unavailable", at 10 A: one cycle, then 400 s.
|
||||
class NanPlant(S.SunPlant):
|
||||
"""Battery A's power reads NaN (or the text 'unavailable') while set."""
|
||||
bad = None
|
||||
|
||||
async def number(self, e, invert=False):
|
||||
if e == "sensor.batt_a" and self.bad is not None:
|
||||
return float("nan") if self.bad == "nan" else None
|
||||
return await super().number(e, invert)
|
||||
|
||||
async def state(self, entity_id):
|
||||
if entity_id == "sensor.batt_a" and self.bad == "unavailable":
|
||||
return {"entity_id": entity_id, "state": "unavailable",
|
||||
"attributes": {}}
|
||||
return await super().state(entity_id)
|
||||
|
||||
|
||||
def _bad(kind):
|
||||
def f(p, c):
|
||||
p.bad = kind
|
||||
return f
|
||||
|
||||
|
||||
for kind in ("none", "nan", "unavailable"):
|
||||
r1 = std(400, plant_cls=NanPlant,
|
||||
events={300: _bad(kind), 301: _bad(None)})
|
||||
r4 = std(800, plant_cls=NanPlant, events={300: _bad(kind),
|
||||
700: _bad(None)})
|
||||
w4 = cur_writes(r4)
|
||||
sp = [x["spare"] for x in r4["trace"] if 302 <= x["t"] < 700]
|
||||
check(f"T4 [{kind}]: battery A's power bad for 1 cycle: no write "
|
||||
f"({[x for x in cur_writes(r1) if x[0] >= 300]})",
|
||||
[x for x in cur_writes(r1) if x[0] >= 300] == [])
|
||||
check(f"T4 [{kind}]: bad for 400 s: no spare computed, the current held, "
|
||||
f"then 0 A once at 300 s (+2 s) ({w4})",
|
||||
sp and all(v is None for v in sp)
|
||||
and [a for _, a, _ in w4 if _ < 700] == [10.0, 0.0]
|
||||
and 599 <= [t for t, a, _ in w4 if a == 0.0][0] <= 602)
|
||||
|
||||
# T31: the meter goes silent at 10 A.
|
||||
for race in (False, True):
|
||||
tag = "race" if race else "step"
|
||||
d = 1 if race else 0
|
||||
r31 = std(900, events={300: lambda p, c: setattr(p, "meter_on", False)},
|
||||
race=race)
|
||||
w31 = cur_writes(r31)
|
||||
check(f"T31 (a) [{tag}]: silent from 300 s (the last sample 299.7 s): "
|
||||
f"no write until 15 + 300 s, then 0 A once (+2 s) ({w31})",
|
||||
[a for _, a, _ in w31] == [10.0, 0.0]
|
||||
and 614 <= w31[-1][0] <= 617 + d)
|
||||
r31b = std(900, events={300: lambda p, c: setattr(p, "meter_on", False),
|
||||
500: lambda p, c: setattr(p, "meter_on", True)})
|
||||
check(f"T31 (b): back at 200 s: no 0 A ({cur_writes(r31b)})",
|
||||
[a for _, a, _ in cur_writes(r31b)] == [10.0])
|
||||
|
||||
# T32: READINGS_LATE at 10 A.
|
||||
|
||||
|
||||
def _late(fn):
|
||||
def ev(p, c):
|
||||
c._readings_late = lambda standing, p=p: fn(p.t)
|
||||
return ev
|
||||
|
||||
|
||||
r32a = std(700, events={300: _late(lambda t: 10.0 if 300 <= t < 340
|
||||
else None)},
|
||||
sun=step_fn((310, 600.0 + 3000.0), base=600.0 + 2300.0))
|
||||
w32a = cur_writes(r32a)
|
||||
check(f"T32 (a): late_s 10 s, then caught up: held, nothing written during "
|
||||
f"it; the 30 s / 1 A rule after ({w32a})",
|
||||
not [x for x in w32a if 300 <= x[0] < 340] and w32a[0][1] == 10.0)
|
||||
r32b = std(900, events={300: _late(lambda t: (t - 300.0) + 1.0
|
||||
if 300 <= t < 700 else None)})
|
||||
w32b = cur_writes(r32b)
|
||||
w32b = [x for x in w32b if x[0] < 700]
|
||||
check(f"T32 (b): late past 15 s for 400 s: the late hold ends at 15 s, then "
|
||||
f"the stale rule: 0 A once by 15 + 300 + 2 s ({w32b})",
|
||||
[a for _, a, _ in w32b] == [10.0, 0.0]
|
||||
and 612 <= w32b[-1][0] <= 617)
|
||||
|
||||
# T32 (c): a late verdict that keeps coming back under the stale bound (0 to
|
||||
# 10 s, over and over) while Solar holds 6 A: the hold still ends at its 300 s.
|
||||
r32c = std(900, sun=step_fn((200, 600.0 + 1000.0), base=600.0 + 2300.0),
|
||||
events={210: _late(lambda t: float((t - 210.0) % 11.0)
|
||||
if 210 <= t < 800 else None)})
|
||||
w32c = cur_writes(r32c)
|
||||
check(f"T32 (c): a READINGS_LATE verdict that keeps coming back while Solar "
|
||||
f"holds 6 A: the 0 A still comes at the hold's 300 s, +2 s ({w32c})",
|
||||
[a for _, a, _ in w32c] == [10.0, 6.0, 0.0]
|
||||
and 499 <= w32c[-1][0] <= 502)
|
||||
|
||||
# T33: a phase sequence interrupted.
|
||||
INT = {"Off": act("car_mode", "off"),
|
||||
"shadow": lambda p, c: c.o.__setitem__("shadow_mode", "on"),
|
||||
"Stop": lambda p, c: setattr(c, "auto", False),
|
||||
"latch": lambda p, c: setattr(c.circ_wd, "tripped", True),
|
||||
"unplug": lambda p, c: p.ch.unplug()}
|
||||
t33 = {}
|
||||
for stage, dt in (("zero", 2), ("settle", 6)):
|
||||
for name, fn in list(INT.items()) + [("shutdown", None)]:
|
||||
sim33 = SimCharger(setpoint_a=0)
|
||||
sim33.ramp_w_s = 600.0 # under 100 W only after ~5 s
|
||||
ev = {}
|
||||
fin = None
|
||||
if fn is None:
|
||||
fin = _shutdown
|
||||
dur = 580 + dt
|
||||
else:
|
||||
ev = {580 + dt: fn}
|
||||
dur = 700
|
||||
rr = std(dur, sun=step_fn((400, 600.0 + 4500.0), base=600.0 + 3000.0),
|
||||
sim=sim33, events=ev, finale=fin)
|
||||
w = cur_writes(rr)
|
||||
zeros = [x for x in w if x[1] == 0.0]
|
||||
sel = selects(rr)
|
||||
t33[(stage, name)] = (w[-2:], [(x[0], x[2]) for x in sel])
|
||||
ok = rr["sim"].setpoint_a == 0.0 and present(nth(w, -1)) \
|
||||
and nth(w, -1)[1] == 0.0 \
|
||||
and not [x for x in w if x[0] > 580 and x[1] > 0.0]
|
||||
if stage == "zero":
|
||||
ok = ok and sel == []
|
||||
if name in ("Off", "shadow"):
|
||||
ok = ok and len(zeros) == 1
|
||||
check(f"T33 [{stage}, {name}]: ends at 0 A, no select after it, no "
|
||||
f"restore of the old current ({t33[(stage, name)]})", ok)
|
||||
|
||||
# T34: unplug at 10 A; replug.
|
||||
r34 = std(4500, events={800: lambda p, c: p.ch.unplug(),
|
||||
4400: lambda p, c: p.ch.plug_in()})
|
||||
w34 = cur_writes(r34)
|
||||
check(f"T34: unplug at 800 s: one 0 A within 1 cycle (+ read-back), then "
|
||||
f"nothing for 3600 s; replug: no write before the start rule ({w34})",
|
||||
[(t, a) for t, a, _ in w34] == [(120.0, 10.0), (800.0, 0.0)])
|
||||
sim34 = TSim(setpoint_a=0, windows=[(800.0, 806.0, "error")])
|
||||
r34b = std(1000, sim=sim34, events={800: lambda p, c: p.ch.unplug()})
|
||||
check(f"T34 (b): the unplug 0 A refused once: tried again at +60 s, taken, "
|
||||
f"then nothing ({cur_writes(r34b)})",
|
||||
[(t, a, ok) for t, a, ok in cur_writes(r34b)]
|
||||
== [(120.0, 10.0, True), (800.0, 0.0, False), (860.0, 0.0, True)])
|
||||
r34m = std(1000, mode="manual", events={800: lambda p, c: p.ch.unplug()})
|
||||
check("T34 guard: Manual unplug writes nothing",
|
||||
not [x for x in r34m["sim"].log if x[0] > 800])
|
||||
|
||||
# T35: Solar to Off / shadow; the guards.
|
||||
r35a = std(1300, events={600: act("car_mode", "off"),
|
||||
620: act("car_current", 14),
|
||||
630: act("car_phases", 3)})
|
||||
check(f"T35 (a): Solar to Off, then the user sets 14 A and 3 phases while "
|
||||
f"Off for 600 s: one 0 A within 1 cycle, then nothing "
|
||||
f"({cur_writes(r35a)}, sim {len(r35a['sim'].log)})",
|
||||
[(t, a) for t, a, _ in cur_writes(r35a)] == [(120.0, 10.0),
|
||||
(600.0, 0.0)]
|
||||
and len(r35a["sim"].log) == 2)
|
||||
for how, fn in (("option on", lambda p, c: c.o.__setitem__("shadow_mode",
|
||||
"on")),
|
||||
("auto, stopped", lambda p, c: setattr(c, "auto", False))):
|
||||
blk = {}
|
||||
rr = std(1300, opts={"shadow_mode": "auto"} if how != "option on" else {},
|
||||
events={600: fn, 900: lambda p, c: blk.update(
|
||||
b=homeview.car_block(c, None))})
|
||||
check(f"T35 (b) [{how}]: one 0 A within 1 cycle, then nothing; the card "
|
||||
f"says what it would set ({cur_writes(rr)}, "
|
||||
f"{blk.get('b', {}).get('why')!r})",
|
||||
[(t, a) for t, a, _ in cur_writes(rr)] == [(120.0, 10.0),
|
||||
(600.0, 0.0)]
|
||||
and "would set 10 A" in blk.get("b", {}).get("why", ""))
|
||||
for how, fn in (("Off", act("car_mode", "off")),
|
||||
("shadow", lambda p, c: c.o.__setitem__("shadow_mode", "on"))):
|
||||
rr = std(900, sun=step_fn((200, 600.0 + 1000.0), base=600.0 + 2300.0),
|
||||
events={600: fn})
|
||||
check(f"T35 (c): Solar paused at 0 A, then {how}: no write "
|
||||
f"({cur_writes(rr)})", [a for _, a, _ in cur_writes(rr)]
|
||||
== [10.0, 6.0, 0.0] and not [x for x in cur_writes(rr)
|
||||
if x[0] >= 600])
|
||||
for how, ev in (("(d) Manual to Off", {600: act("car_mode", "off")}),
|
||||
("(e) shadow on in Manual",
|
||||
{600: lambda p, c: c.o.__setitem__("shadow_mode", "on")})):
|
||||
rr = std(900, mode="manual", events=ev)
|
||||
check(f"T35 {how}: zero writes, as EV-04",
|
||||
[x for x in rr["sim"].log if x[0] > 600] == [])
|
||||
r35f = std(900, events={600: act("car_mode", "manual"),
|
||||
601: act("car_current", 13)})
|
||||
check(f"T35 (f): Solar to Manual: no Solar 0 A; Manual writes its own "
|
||||
f"current ({[(x[0], x[2]) for x in r35f['sim'].log]})",
|
||||
[x[2] for x in r35f["sim"].log if x[0] > 600][:1] in ([6.0], [13.0])
|
||||
and 0.0 not in [x[2] for x in r35f["sim"].log if x[0] > 600])
|
||||
|
||||
# T36: EV-05 r2 Critical, the exit 0 A refused then taken, on every path.
|
||||
|
||||
|
||||
def _meter_off(p, c):
|
||||
p.meter_on = False
|
||||
|
||||
|
||||
PATHS = {
|
||||
"Stop (shadow_mode off)": (300, {300: lambda p, c: setattr(c, "auto",
|
||||
False)},
|
||||
{"shadow_mode": "off"}),
|
||||
"Stop (auto)": (300, {300: lambda p, c: setattr(c, "auto", False)},
|
||||
{"shadow_mode": "auto"}),
|
||||
"Off": (300, {300: act("car_mode", "off")}, {}),
|
||||
"shadow on": (300, {300: lambda p, c: c.o.__setitem__("shadow_mode",
|
||||
"on")}, {}),
|
||||
"latch": (300, {300: lambda p, c: setattr(c.circ_wd, "tripped", True)},
|
||||
{}),
|
||||
"charger error": (300, {300: _err}, {}),
|
||||
"unplug": (300, {300: lambda p, c: p.ch.unplug()}, {}),
|
||||
"meter stale": (514, {200: _meter_off}, {}),
|
||||
"charger back": (420, {240: lambda p, c: p.ch.go_unavailable(True),
|
||||
300: lambda p, c: p.ch.set_current(16),
|
||||
420: lambda p, c: p.ch.go_unavailable(False)}, {}),
|
||||
"HA back": (420, {240: lambda p, c: setattr(p, "ha_down", True),
|
||||
300: lambda p, c: p.ch.set_current(16),
|
||||
420: lambda p, c: setattr(p, "ha_down", False)}, {}),
|
||||
}
|
||||
for name, (t0, ev, opts) in PATHS.items():
|
||||
for kind in ("error", "ignore"):
|
||||
sim = TSim(setpoint_a=0, windows=[(t0, t0 + 6.0, kind)])
|
||||
rr = std(t0 + 150, sim=sim, events=ev, opts=opts)
|
||||
w = [(t, a, ok) for t, a, ok in cur_writes(rr) if t >= t0 - 1]
|
||||
rel = [(round(t - w[0][0]), a, ok) for t, a, ok in w] if w else []
|
||||
check(f"T36 [{name}, {kind}]: the way-out 0 A not taken at t, tried "
|
||||
f"again at t + 60 s and taken; 0 A and the car at 0 W by "
|
||||
f"t + 70 s; nothing more ({w})",
|
||||
rel == [(0, 0.0, False), (60, 0.0, True)]
|
||||
and present(nth(w, 0)) and abs(nth(w, 0)[0] - t0) <= 1
|
||||
and rr["sim"].setpoint_a == 0.0
|
||||
and rr["sim"].power_w == 0.0)
|
||||
n = LOG.mark()
|
||||
blk = {}
|
||||
sim = TSim(setpoint_a=0, windows=[(t0, t0 + 400.0, "error")])
|
||||
ev2 = dict(ev)
|
||||
ev2[t0 + 190] = lambda p, c: blk.update(b=homeview.car_block(c, None),
|
||||
rows=c.checks())
|
||||
rr = std(t0 + 200, sim=sim, events=ev2, opts=opts)
|
||||
w = [(round(t - t0), a, ok) for t, a, ok in cur_writes(rr) if t >= t0 - 1]
|
||||
warn = [m for m in LOG.since(n, "WARNING") if "CHARGER_REFUSED" in m]
|
||||
check(f"T36 [{name}, kept]: tries at t, t+60, t+120, then the gave-up row "
|
||||
f"and one CHARGER_REFUSED warning; the card does not say paused "
|
||||
f"({w}, {blk.get('b', {}).get('why')!r})",
|
||||
len(w) == 3 and abs(w[0][0]) <= 1
|
||||
and [d - w[0][0] for d, a, ok in w] == [0, 60, 120]
|
||||
and all(a == 0.0 and not ok for _, a, ok in w)
|
||||
and len(warn) == 1
|
||||
and "charger_refused" in [x["id"] for x in blk.get("rows", [])]
|
||||
and "paused" not in blk.get("b", {}).get("why", "paused"))
|
||||
|
||||
# T37: shutdown while a start write waits for its read-back.
|
||||
|
||||
|
||||
async def _start_then_shutdown(p, c):
|
||||
"""The cycle of 120 s starts the 10 A write; the add-on stops while it
|
||||
waits for its read-back (the model's sleep yields, as a real one)."""
|
||||
async def sleep(s):
|
||||
p.ch.tick(s)
|
||||
p.clock[0] += s
|
||||
p.t = p.clock[0]
|
||||
await asyncio.sleep(0)
|
||||
c.charger._sleep = sleep
|
||||
p.ch.tick(1.0)
|
||||
p.clock[0] = p.t = 120.0
|
||||
await c.read_inputs(now_mono=120.0)
|
||||
await c.cycle()
|
||||
for _ in range(200): # the 10 A write is out, unconfirmed
|
||||
await asyncio.sleep(0)
|
||||
if c.car_solar.sent_a == 10.0:
|
||||
break
|
||||
for _ in range(3):
|
||||
await asyncio.sleep(0)
|
||||
p.inflight = (c.car_solar.sent_a, c.car_solar.taken)
|
||||
await c.shutdown()
|
||||
p.ch.tick(30)
|
||||
|
||||
|
||||
sim37 = SimCharger(setpoint_a=0)
|
||||
sim37.lag_s = 8.0
|
||||
r37 = run("T37", std, 120, sim=sim37, finale=_start_then_shutdown)
|
||||
check(f"T37: shutdown while the 0 -> 10 A start write waits for its "
|
||||
f"read-back (lag 8 s): release writes 0 A and the charger ends at 0 A "
|
||||
f"({getattr(r37['plant'], 'inflight', None)}, "
|
||||
f"{[(x[0], x[2]) for x in sim37.log]}, sp {sim37.setpoint_a})",
|
||||
getattr(r37["plant"], "inflight", None) == (10.0, False)
|
||||
and [x[2] for x in sim37.log][-1:] == [0.0]
|
||||
and sim37.setpoint_a == 0.0)
|
||||
|
||||
# C1 (SPIKE-05, brief v5): a start-up after a stop with no release.
|
||||
import opt11_identity as rig # noqa: E402
|
||||
|
||||
|
||||
def _store(mode, pending=None):
|
||||
st = rig._Store()
|
||||
st.data["car_mode"] = mode
|
||||
if pending is not None:
|
||||
st.data[ctl_car.CAR_EXIT_KEY] = pending
|
||||
return st
|
||||
|
||||
|
||||
for pending, name in ((True, "Off, flag set, charger at 10 A -> 0 A written"),
|
||||
(False, "Off, no flag -> nothing")):
|
||||
simc = TSim(setpoint_a=10, windows=[(0.0, 2.5, "error")])
|
||||
rr = std(200, sim=simc, mode="off", store=_store("off", pending))
|
||||
w = cur_writes(rr)
|
||||
if pending:
|
||||
check(f"C1 [{name}]: the 0 A at the first reading, refused, tried "
|
||||
f"again 60 s later and taken; the flag cleared ({w})",
|
||||
[(round(t), a, ok) for t, a, ok in w]
|
||||
in ([(0, 0.0, False), (60, 0.0, True)],
|
||||
[(1, 0.0, False), (61, 0.0, True)])
|
||||
and simc.setpoint_a == 0.0
|
||||
and rr["store"].data.get(ctl_car.CAR_EXIT_KEY) is False)
|
||||
else:
|
||||
check(f"C1 [{name}]: nothing written (N10) ({simc.log})",
|
||||
simc.log == [] and simc.setpoint_a == 10.0)
|
||||
# The PM's shape: Solar at 10 A, Off whose 0 A is refused, a power cut before
|
||||
# the retry; the restart (keep) in Off writes the 0 A.
|
||||
simp = TSim(setpoint_a=0, windows=[(300.0, 1e9, "error")])
|
||||
rp = std(330, sim=simp, events={300: act("car_mode", "off")})
|
||||
flag = rp["store"].data.get(ctl_car.CAR_EXIT_KEY)
|
||||
simp.windows = []
|
||||
n0 = len(simp.log)
|
||||
rq = std(100, sim=simp, store=rp["store"], mode="off")
|
||||
new = [(x[0], x[2]) for x in simp.log[n0:]]
|
||||
check(f"C1: Off whose 0 A was refused, a power cut before its retry: the flag "
|
||||
f"is kept ({flag}), and the restart in Off writes the 0 A at once "
|
||||
f"({new})", flag is True and new[:1] and new[0][1] == 0.0
|
||||
and simp.setpoint_a == 0.0)
|
||||
# Shadow or control stopped at the start: no write, one warning.
|
||||
for stored, opts, ev, warn in (
|
||||
("solar", {"shadow_mode": "on"}, {}, True),
|
||||
("manual", {"shadow_mode": "on"}, {}, True),
|
||||
("solar", {"shadow_mode": "auto"},
|
||||
{0: lambda p, c: setattr(c, "auto", False)}, True),
|
||||
("off", {"shadow_mode": "on"}, {}, False)):
|
||||
n = LOG.mark()
|
||||
simw = SimCharger(setpoint_a=10)
|
||||
rr = std(120, sim=simw, opts=opts, events=ev, mode=stored)
|
||||
wl = [m for m in LOG.since(n, "WARNING") if "CHARGER_START_CURRENT" in m]
|
||||
notes_ = [x for _, x in rr["raised"] if x == messages.ID_CAR_START]
|
||||
check(f"C1 [stored {stored}, {opts.get('shadow_mode')}"
|
||||
f"{', stopped' if ev else ''}]: nothing written; "
|
||||
f"{'one warning' if warn else 'no warning'} "
|
||||
f"({len(wl)} log, {len(notes_)} notice)",
|
||||
simw.log == [] and len(wl) == (1 if warn else 0)
|
||||
and len(notes_) == (1 if warn else 0))
|
||||
check("C1: the warning's words, EN and NL",
|
||||
messages.car_start_current("10").body
|
||||
== "Charger still at 10 A from before the restart."
|
||||
and "10 A" in messages.car_start_current("10").body_nl)
|
||||
|
||||
# C5: each shutdown try waits at most 4 s for its read-back, so three fit in
|
||||
# 15 s against a charger that ignores the write.
|
||||
sim5 = TSim(setpoint_a=0, windows=[(299.5, 1e9, "ignore")])
|
||||
r5 = run("C5", std, 300, sim=sim5, finale=_shutdown)
|
||||
tr5 = [t for t, v in attempts(r5) if t >= 299]
|
||||
check(f"C5: a charger that ignores the 0 A: three tries ({tr5}) about 5 s "
|
||||
f"apart, each waiting 4 s at most, the inverters by 15 s "
|
||||
f"(+{_until(r5, 299.0)})",
|
||||
len(tr5) == 3 and all(4.0 <= b - a <= 6.0 for a, b in zip(tr5, tr5[1:]))
|
||||
and present(given(_until(r5, 299.0)))
|
||||
and _until(r5, 299.0) <= 15.0)
|
||||
|
||||
# C8: a charger outage in the middle of a phase change ends it; the first
|
||||
# write after the return is never a current (N12).
|
||||
for stage, dt in (("zero", 2), ("settle", 6)):
|
||||
sim8 = SimCharger(setpoint_a=0)
|
||||
sim8.ramp_w_s = 600.0
|
||||
rr = std(900, sun=step_fn((400, 600.0 + 4500.0), base=600.0 + 3000.0),
|
||||
sim=sim8, events={580 + dt: lambda p, c: p.ch.go_unavailable(True),
|
||||
620: lambda p, c: p.ch.go_unavailable(False)})
|
||||
w = [(t, a) for t, a, _ in cur_writes(rr) if t >= 620]
|
||||
check(f"C8 [{stage}]: the charger away from 580 + {dt} s to 620 s: the "
|
||||
f"sequence ends, nothing of it resumes: before the start rule's "
|
||||
f"120 s from the return only a 0 A may be written (here the "
|
||||
f"charger came back at the sequence's 0 A) ({w})",
|
||||
not [a for t, a in w if a > 0.0 and t < 740.0]
|
||||
and rr["trace"][625]["sp"] == 0.0)
|
||||
|
||||
# C9: Solar's 6 A lands late, then its 0 A pause is refused, then Off: the
|
||||
# exit 0 A and its retry still come (decided from the read-back).
|
||||
sim9 = SimCharger(setpoint_a=0)
|
||||
r9 = std(500, sim=sim9, sun=step_fn((190, 600.0 + 700.0),
|
||||
base=600.0 + 2300.0),
|
||||
opts={"ev_pause_min": 1},
|
||||
events={185: lambda p, c: setattr(p.ch, "lag_s", 12.0),
|
||||
205: lambda p, c: setattr(p.ch, "lag_s", 0.0),
|
||||
249: lambda p, c: setattr(p.ch, "refuse", "error"),
|
||||
255: act("car_mode", "off"),
|
||||
257: lambda p, c: setattr(p.ch, "refuse", None)})
|
||||
w9 = cur_writes(r9)
|
||||
z9 = [(t, ok) for t, a, ok in w9 if a == 0.0]
|
||||
check(f"C9: the 6 A late, the pause's 0 A refused, then Off: the 0 A is "
|
||||
f"tried again 60 s after the refusal and taken; the charger ends at "
|
||||
f"0 A ({w9})",
|
||||
len(z9) == 2 and present(nth(z9, 0)) and nth(z9, 0)[1] is False
|
||||
and nth(z9, 1)[1] is True and 59 <= nth(z9, 1)[0] - nth(z9, 0)[0] <= 61
|
||||
and sim9.setpoint_a == 0.0)
|
||||
|
||||
# T61: the start-up in Solar after a stop with no release.
|
||||
for k, sp, kw in (("10 A, keep", 10, {}),
|
||||
("16 A by another writer", 16, {}),
|
||||
("shadow on (option)", 16, {"opts": {"shadow_mode": "on"}}),
|
||||
("shadow auto, control stopped", 16,
|
||||
{"opts": {"shadow_mode": "auto"}, "stopped": True}),
|
||||
("ev_mode_start off", 10,
|
||||
{"opts": {"ev_mode_start": "off"}})):
|
||||
n = LOG.mark()
|
||||
sim61 = SimCharger(setpoint_a=sp)
|
||||
opts = kw.get("opts", {})
|
||||
ev = {0: lambda p, c: setattr(c, "auto", False)} if kw.get("stopped") \
|
||||
else {}
|
||||
rr = std(300, sim=sim61, opts=opts, events=ev)
|
||||
w = cur_writes(rr)
|
||||
other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m]
|
||||
if "shadow" in k or "off" in k:
|
||||
check(f"T61 [{k}]: nothing written ({w})", sim61.log == [])
|
||||
else:
|
||||
check(f"T61 [{k}]: D2: the first charger write is 0 A within 1 cycle "
|
||||
f"of the first reading, then only the start rule; no "
|
||||
f"CHARGER_OTHER ({w})",
|
||||
present(nth(w, 0)) and nth(w, 0)[1] == 0.0
|
||||
and nth(w, 0)[0] <= 1.0
|
||||
and [(t, a) for t, a, _ in w[1:]] == [(120.0, 10.0)]
|
||||
and not other)
|
||||
|
||||
report()
|
||||
@@ -1,312 +0,0 @@
|
||||
"""EV-20: T54, the fuzz. `python3 -B test_ev20_fuzz.py`
|
||||
|
||||
14 sites of random spare, outages, unplugs, refusals (at the exits too), other
|
||||
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).
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import carmode # noqa: E402
|
||||
import ev20_sun as S # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
class _Log(logging.Handler):
|
||||
def __init__(self):
|
||||
super().__init__(logging.DEBUG)
|
||||
self.tb = []
|
||||
|
||||
def emit(self, r):
|
||||
if r.exc_info:
|
||||
self.tb.append(r.getMessage())
|
||||
|
||||
|
||||
LOG = _Log()
|
||||
_g = logging.getLogger("goodwe")
|
||||
_g.addHandler(LOG)
|
||||
_g.setLevel(logging.DEBUG)
|
||||
_g.propagate = False
|
||||
|
||||
|
||||
def cur_writes(r):
|
||||
return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log
|
||||
if x[0] == "current"]
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
print("T54: THE FUZZ")
|
||||
# =========================================================================== #
|
||||
SITES = 14
|
||||
STEPS_PER = int(os.environ.get("EV20_FUZZ_STEPS", "2400"))
|
||||
|
||||
|
||||
class FSim(SimCharger):
|
||||
"""The model, knowing who set its current last: the add-on in Solar (or
|
||||
on its way out of Solar), Manual, or another writer."""
|
||||
ctl = None
|
||||
setter = None
|
||||
|
||||
def _apply(self, what, v):
|
||||
if what == "current":
|
||||
c = self.ctl
|
||||
self.setter = ("manual" if c is not None
|
||||
and c.car_mode == "manual" else "solar")
|
||||
super()._apply(what, v)
|
||||
|
||||
def set_current(self, a):
|
||||
self.setter = "other"
|
||||
super().set_current(a)
|
||||
|
||||
|
||||
def fuzz_site(seed):
|
||||
rnd = random.Random(seed)
|
||||
sim = FSim(setpoint_a=rnd.choice([0, 6, 10, 16]))
|
||||
sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0])
|
||||
if seed % 3 == 0:
|
||||
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 = [], {}, {}
|
||||
seen = {"exit_since": None, "avail": None, "back": []}
|
||||
|
||||
def bump(k):
|
||||
counts[k] = counts.get(k, 0) + 1
|
||||
|
||||
async def ev(p, c):
|
||||
sim.ctl = c
|
||||
w = c.car_solar
|
||||
t = p.t
|
||||
# Outages end by themselves.
|
||||
for k, off in (("outage", lambda: p.ch.go_unavailable(False)),
|
||||
("ha", lambda: setattr(p, "ha_down", False)),
|
||||
("meter", lambda: setattr(p, "meter_on", True)),
|
||||
("stop", lambda: setattr(c, "auto", True)),
|
||||
("shadow", lambda: c.o.__setitem__("shadow_mode",
|
||||
"off"))):
|
||||
if state.get(k) is not None and t >= state[k]:
|
||||
off()
|
||||
state[k] = None
|
||||
if state.get("mode") is not None and t >= state["mode"]:
|
||||
state["mode"] = None
|
||||
await c.handle_action("car_mode", value="solar")
|
||||
x = rnd.random()
|
||||
if x < 0.02:
|
||||
state["sun"] = max(0.0, min(12000.0, state["sun"]
|
||||
+ rnd.uniform(-4000, 4000)))
|
||||
bump("spare")
|
||||
elif x < 0.023:
|
||||
state["house"] = rnd.uniform(300, 4000)
|
||||
elif x < 0.0245 and state.get("outage") is None:
|
||||
p.ch.go_unavailable(True)
|
||||
state["outage"] = t + rnd.uniform(5, 120)
|
||||
bump("outage")
|
||||
elif x < 0.0255 and state.get("ha") is None:
|
||||
p.ha_down = True
|
||||
state["ha"] = t + rnd.uniform(5, 120)
|
||||
bump("ha")
|
||||
elif x < 0.0265:
|
||||
(p.ch.unplug if p.ch.state != "A" else p.ch.plug_in)()
|
||||
bump("unplug")
|
||||
elif x < 0.0295:
|
||||
p.ch.refuse = rnd.choice([None, None, "ignore", "error"])
|
||||
bump("refuse" + ("_exit" if not c.car_writing()
|
||||
or c.car_mode != "solar" else ""))
|
||||
elif x < 0.031:
|
||||
p.ch.set_current(rnd.choice([0, 6, 13, 16]))
|
||||
bump("other" + ("_out" if not c.car_writing() else ""))
|
||||
elif (w.hold or w.gave_up) and x < 0.06:
|
||||
bump("press") # the user hands it back to Solar
|
||||
await c.handle_action("car_mode", value="solar")
|
||||
elif x < 0.032 and state.get("meter") is None:
|
||||
p.meter_on = False
|
||||
state["meter"] = t + rnd.uniform(5, 360)
|
||||
bump("meter")
|
||||
elif x < 0.0355 or (w.seq is not None and x < 0.15):
|
||||
k = rnd.choice(["stop", "shadow", "mode"])
|
||||
bump(k + ("_seq" if w.seq is not None else ""))
|
||||
back = t + rnd.uniform(5, 240)
|
||||
if k == "stop":
|
||||
c.auto = False
|
||||
c.o["shadow_mode"] = rnd.choice(["off", "auto"])
|
||||
state["stop"] = back
|
||||
elif k == "shadow":
|
||||
c.o["shadow_mode"] = "on"
|
||||
state["shadow"] = back
|
||||
else:
|
||||
await c.handle_action("car_mode", value=rnd.choice(
|
||||
["off", "manual", "solar"]))
|
||||
state["mode"] = back
|
||||
elif x < 0.0365:
|
||||
await c.handle_action("car_sun_first", value=rnd.choice(
|
||||
["batteries", "car"]))
|
||||
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
|
||||
# both cycle orders).
|
||||
snap[p.t] = dict(mode=c.car_mode, writing=c.car_writing(),
|
||||
live=w.live, hold=w.hold, engaged=w.engaged)
|
||||
bump("s_" + ("hold" if w.hold else "solar" if c.car_mode == "solar"
|
||||
and c.car_writing() else "out"))
|
||||
|
||||
def on_cycle(p, c, t):
|
||||
w, sim = c.car_solar, p.ch
|
||||
r = c.car.reading
|
||||
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
|
||||
seen["back"].append((t, cur))
|
||||
seen["avail"] = avail
|
||||
# N3: Solar never keeps the car at 6 A or more past the pause after
|
||||
# the spare fell under 6 A worth (while it writes and the charger
|
||||
# answers: an unreachable charger is held, then set to 0 A on return).
|
||||
pause_s = 60.0 * carmode.solar_option(c.o, "ev_pause_min")
|
||||
p_ = w.plan
|
||||
if c.car_mode == "solar" and c.car_writing() and avail \
|
||||
and (w.sent_a or 0.0) >= 6.0 and w.taken \
|
||||
and sim.setter == "solar" and sim.setpoint_a >= 6.0 \
|
||||
and p_.low_since is not None \
|
||||
and t - p_.low_since > pause_s + 2.0:
|
||||
bad.append((seed, t, "N3 6 A past the pause"))
|
||||
# N9: an exit from Solar leaves no current of its own standing once
|
||||
# the charger takes writes again (a minute for the retry).
|
||||
out = (c.car_mode == "off" or not c.car_writing()
|
||||
or sim.state in ("A", "E", "F") or bool(r and r.error))
|
||||
quiet = (avail and not p.ha_down and sim.refuse is None
|
||||
and not w.hold and not w.gave_up
|
||||
and c.car_mode != "manual")
|
||||
if out and quiet:
|
||||
seen["exit_since"] = seen["exit_since"] or t
|
||||
if t - seen["exit_since"] > carmode.RETRY_S + 15.0 \
|
||||
and sim.setter == "solar" and sim.setpoint_a > 0.0 \
|
||||
and not sim._pending:
|
||||
bad.append((seed, t, "N9 Solar's current stands after the "
|
||||
"way out", sim.setpoint_a))
|
||||
seen["exit_since"] = t
|
||||
else:
|
||||
seen["exit_since"] = None
|
||||
|
||||
race = seed % 2 == 1
|
||||
evs = {t: ev for t in range(1, STEPS_PER)}
|
||||
r = S.drive(lambda t: state["house"], lambda t: state["sun"],
|
||||
dur=STEPS_PER, first=rnd.choice(["batteries", "car", "car"]),
|
||||
socs={"a": rnd.uniform(40, 100), "b": rnd.uniform(70, 100)},
|
||||
sim=sim, race=race, events=evs, on_cycle=on_cycle,
|
||||
phases=rnd.choice([1, 3]),
|
||||
opts={"ev_start_min": rnd.choice([1, 1, 2]),
|
||||
"ev_pause_min": rnd.choice([1, 2, 5]),
|
||||
"ev_phases": rnd.choice(["auto", "auto", "1", "3"])})
|
||||
c = r["c"]
|
||||
# N1
|
||||
if c.charger.clamp_faults:
|
||||
bad.append((seed, "N1 clamp fault", c.charger.clamp_faults[:1]))
|
||||
for t, what, v, pw, sp in sim.log:
|
||||
if what == "current" and v > min(16.0, sim.station_a) + 1e-9:
|
||||
bad.append((seed, t, "N1 over the clamp", v))
|
||||
# N2
|
||||
sel = [x for x in sim.log if x[1] == "phases"]
|
||||
for a, b in zip(sel, sel[1:]):
|
||||
if b[0] - a[0] < 600.0:
|
||||
bad.append((seed, b[0], "N2 two selects inside 600 s"))
|
||||
for x in sel:
|
||||
if x[4] > 0.0:
|
||||
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:
|
||||
s = snap.get(t) or snap.get(t - 1)
|
||||
if s is None:
|
||||
continue
|
||||
# N16: nothing while EV-04's hold stands.
|
||||
if s["hold"]:
|
||||
bad.append((seed, t, "N16 a write under the hold", a))
|
||||
# N10: off Solar or not writing, only the owed 0 A.
|
||||
if (s["mode"] != "solar" or not s["writing"]) \
|
||||
and (a > 0.0 or not s["live"]):
|
||||
bad.append((seed, t, "N10 a write while out", a, s))
|
||||
# N12: the first write after the charger (or HA) is back is 0 A, unless
|
||||
# the charger came back at 0 A already.
|
||||
for tb, cur in seen["back"]:
|
||||
nxt = [x for x in log if x[2] >= tb]
|
||||
if nxt and nxt[0][1] > 0.0 and (cur is None or cur > 0.5):
|
||||
bad.append((seed, tb, "N12 non-zero first after the return",
|
||||
nxt[0], cur))
|
||||
# N5 / N14 from Solar's own write log: decisions and retries.
|
||||
dec = [(t, a, ok) for kind, a, t, ok in log]
|
||||
for i, (t, a, ok) in enumerate(dec):
|
||||
if i and dec[i - 1][1] == a and not dec[i - 1][2] \
|
||||
and t - dec[i - 1][0] < carmode.RETRY_S - 1e-9:
|
||||
bad.append((seed, t, "N14 a retry under 60 s", a))
|
||||
tries = 0
|
||||
for i, (t, a, ok) in enumerate(dec):
|
||||
tries = tries + 1 if (i and dec[i - 1][1] == a
|
||||
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]
|
||||
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]:
|
||||
bad.append((seed, t1, "N5 two changes under 30 s",
|
||||
(t0, a0), (t1, a1)))
|
||||
for (t0, a0), (t1, a1) in zip(nz, nz[1:]):
|
||||
if a1 != a0 and abs(a1 - a0) < carmode.SOLAR_STEP_A:
|
||||
bad.append((seed, t1, "N5 a change under 1 A"))
|
||||
tally["sel"] += len([x for x in sim.log if x[1] == "phases"])
|
||||
tally["zero"] += len([x for x in log if x[1] == 0.0])
|
||||
print(f" site {seed:2d} ({'race' if race else 'step'}): "
|
||||
f"{len(log)} writes, "
|
||||
f"{len([x for x in sim.log if x[1] == 'phases'])} selects, "
|
||||
f"{len([x for x in log if x[1] == 0.0])} at 0 A")
|
||||
return bad, counts, len(sim.log), r
|
||||
|
||||
|
||||
all_bad, all_counts, n_writes, steps = [], {}, 0, 0
|
||||
tally = {"sel": 0, "zero": 0}
|
||||
for seed in range(SITES):
|
||||
b, cnt, nw, r = fuzz_site(seed)
|
||||
all_bad += b
|
||||
n_writes += nw
|
||||
steps += STEPS_PER
|
||||
for k, v in cnt.items():
|
||||
all_counts[k] = all_counts.get(k, 0) + v
|
||||
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 "
|
||||
f"({all_bad[:3]})", not all_bad)
|
||||
need = ("spare", "outage", "ha", "unplug", "refuse", "refuse_exit", "other",
|
||||
"other_out", "meter", "stop", "shadow", "mode")
|
||||
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)
|
||||
and (all_counts.get("stop_seq", 0) + all_counts.get("shadow_seq", 0)
|
||||
+ all_counts.get("mode_seq", 0)) > 0)
|
||||
check(f"T54: Solar did write, select and pause ({n_writes} writes, "
|
||||
f"{n_sel} selects, {n_zero} at 0 A)",
|
||||
n_writes >= 5 * SITES and n_sel >= 3 and n_zero >= SITES)
|
||||
check(f"T54: at least 1200 steps per site, in both cycle orders ({steps})",
|
||||
STEPS_PER >= 1200)
|
||||
check("T54/N13: no Traceback", LOG.tb == [])
|
||||
|
||||
print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}")
|
||||
for f in fails:
|
||||
print(" FAIL:", f)
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -1,493 +0,0 @@
|
||||
"""EV-20: the peak guard treats a Solar car as a Manual car; 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`
|
||||
|
||||
The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and
|
||||
`chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit
|
||||
rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section
|
||||
names the T-ids and N-ids of reports/EV-20-test-plan.md it implements.
|
||||
"Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare
|
||||
2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start.
|
||||
Times are the cycle's second; `race` runs use the production order (read, the
|
||||
writer settles, the cycle).
|
||||
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402
|
||||
from app import mqtt, validate, web, main as app_main # noqa: E402
|
||||
from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402
|
||||
import ev20_sun as S # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
from ev20_kit import * # noqa: E402,F401,F403
|
||||
from ev20_kit import LOG, check, fails, report # noqa: E402,F401
|
||||
from named_absence import nth, present # noqa: E402,F401
|
||||
from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401
|
||||
_until)
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n8. THE PEAK GUARD: A SOLAR CAR IS A MANUAL CAR (T21, T22, T47, T48)")
|
||||
# =========================================================================== #
|
||||
ALARMS = S.ALARMS
|
||||
|
||||
|
||||
def twin(mode, **kw):
|
||||
return S.drive(kw.pop("house"), kw.pop("sun"), mode=mode, rows=True,
|
||||
**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."""
|
||||
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))
|
||||
for t, acts in rep_.items():
|
||||
def put(p, c, acts=acts):
|
||||
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)
|
||||
|
||||
|
||||
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 notes(r):
|
||||
return [(t, n) for t, n in r["raised"]
|
||||
if n in ALARMS + (messages.ID_CAR_OVER,)]
|
||||
|
||||
|
||||
# (b) EV-05 r5 shape.
|
||||
for cover in (True, False):
|
||||
kw = dict(house=step_fn((1000, 3000.0), base=500.0), sun=const(7000.0),
|
||||
dur=1800, first="car", phases=3, socs={"a": 10.0, "b": 10.0},
|
||||
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)
|
||||
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"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 "
|
||||
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)
|
||||
# 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)
|
||||
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",
|
||||
messages.car_over_solar("16").body.startswith(
|
||||
"Solar charges the car at 16 A")
|
||||
and "You set" not in messages.car_over_solar("16").body)
|
||||
|
||||
# (d) EV-05 r6 shape: Stop / shadow / circ_wd at 500 s, other writer at 600.
|
||||
for name, fn, opts in (("Stop (auto)", lambda p, c: setattr(c, "auto", False),
|
||||
{"shadow_mode": "auto"}),
|
||||
("shadow on", lambda p, c: c.o.__setitem__(
|
||||
"shadow_mode", "on"), {}),
|
||||
("circ_wd", lambda p, c: setattr(c.circ_wd, "tripped",
|
||||
True), {})):
|
||||
kw = dict(house=step_fn((1000, 3000.0), base=500.0), sun=const(7000.0),
|
||||
dur=1500, first="car", phases=3, socs={"a": 10.0, "b": 10.0},
|
||||
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)
|
||||
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)])
|
||||
|
||||
# T22: EV-15 shapes in Solar: Solar's own 3 -> 1 sequence and own 0 A pause
|
||||
# with both batteries at the reserve.
|
||||
for name, sun_fn in (
|
||||
("own 3 -> 1 sequence", step_fn((300, 600.0 + 4600.0),
|
||||
(700, 600.0 + 3700.0),
|
||||
base=600.0 + 3000.0)),
|
||||
("own 0 A pause", step_fn((700, 600.0 + 600.0),
|
||||
base=600.0 + 4600.0))):
|
||||
kw = dict(house=const(600.0), sun=sun_fn, dur=1800, first="car",
|
||||
socs={"a": 19.0, "b": 19.0},
|
||||
opts={"peak_soc_floor": 20, "ev_pause_min": 5})
|
||||
rs = twin("solar", **kw)
|
||||
reds = [(x["t"], x["red"]) for x in rs["trace"] if x["red"]]
|
||||
check(f"T22 [{name}]: no PEAK_GUARD_FLOOR_LIMITED / saturated, no "
|
||||
f"goodwe_peak_soc_floor, no red row in any second "
|
||||
f"({notes(rs)}, {reds[:2]}; writes {cur_writes(rs)[-3:]})",
|
||||
not [n for _, n in notes(rs) if n in ALARMS] and not reds
|
||||
and (name != "own 0 A pause"
|
||||
or [a for _, a, _ in cur_writes(rs)][-1:] == [0.0]))
|
||||
|
||||
|
||||
def _overload(p, c):
|
||||
p.house = const(25000.0)
|
||||
|
||||
|
||||
kw = dict(house=const(600.0), sun=step_fn((300, 600.0 + 4600.0),
|
||||
(700, 600.0 + 3700.0),
|
||||
base=600.0 + 3000.0),
|
||||
dur=1200, first="car", socs={"a": 19.0, "b": 19.0},
|
||||
opts={"peak_soc_floor": 20})
|
||||
rs = twin("solar", **dict(kw, events={1006: _overload}))
|
||||
seq_at = [x[0] for x in selects(rs)]
|
||||
ro = twin("off", **dict(kw, events={1006: _overload}), plug=False)
|
||||
a_s = [t for t, n in notes(rs) if n in ALARMS]
|
||||
a_o = [t for t, n in notes(ro) if n in ALARMS]
|
||||
check(f"T22: a 25 kW house overload 6 s into Solar's sequence (select at "
|
||||
f"{seq_at}): the alarm at the same second as with the car Off (+2 s) "
|
||||
f"({a_s[:1]} vs {a_o[:1]})",
|
||||
a_s and a_o and abs(a_s[0] - a_o[0]) <= 2)
|
||||
|
||||
# T47: EV-05 r7 M2 / r8 M2 / r9 Minor: another writer starts the car after
|
||||
# Solar's own 0 A pause.
|
||||
for T in (615, 640, 680):
|
||||
kw = dict(house=step_fn((T + 5, 3000.0), base=500.0),
|
||||
sun=step_fn((300, 0.0), base=7000.0), dur=T + 200,
|
||||
first="car", phases=3, socs={"a": 10.0, "b": 10.0},
|
||||
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)
|
||||
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]})",
|
||||
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,
|
||||
first="car", phases=3, socs={"a": 10.0, "b": 10.0},
|
||||
opts={"ev_phases": "3"})
|
||||
rs = twin("solar", **kw)
|
||||
z = [t for t, a, _ in cur_writes(rs) if a == 0.0]
|
||||
own = [x["t"] for x in rs["trace"] if x["own"]]
|
||||
check(f"T47: the grace of Solar's own 0 A (at {z[:1]}) lasts at most "
|
||||
f"OWN_PAUSE_MAX_S ({ctl_car.OWN_PAUSE_MAX_S:.0f} s): own-pause seconds "
|
||||
f"{own[:1]}..{own[-1:]}",
|
||||
bool(z) and bool(own) and own[0] >= z[0] - 1
|
||||
and own[-1] - z[0] <= ctl_car.OWN_PAUSE_MAX_S + 1)
|
||||
|
||||
# T48: EV-05 r9 Major 2, a read-back later than TOOK_S.
|
||||
|
||||
|
||||
def _lag(on):
|
||||
def f(p, c):
|
||||
p.ch.lag_s = 12.0 if on else 0.0
|
||||
return f
|
||||
|
||||
|
||||
for race in (False, True):
|
||||
tag = "race" if race else "step"
|
||||
n = LOG.mark()
|
||||
kw = dict(sun=step_fn((200, 3600.0), base=2900.0), race=race,
|
||||
rows=True)
|
||||
rl = std(1300, events={190: _lag(True), 260: _lag(False)}, **kw)
|
||||
r0 = std(1300, **kw)
|
||||
wl = cur_writes(rl)
|
||||
trl = rl["trace"]
|
||||
refused = [m for m in LOG.since(n, "WARNING") if "CHARGER_REFUSED" in m]
|
||||
check(f"T48 [{tag}]: the 13 A write at 200 s is not confirmed in 10 s and "
|
||||
f"shows at ~213 s: within 1 cycle it counts as taken (no retry at "
|
||||
f"260 s, no fail count, no CHARGER_REFUSED, no hold, no amber row) "
|
||||
f"({wl})",
|
||||
[a for _, a, _ in wl] == [10.0, 13.0] and wl[1][2] is False
|
||||
and trl[215]["taken"] and trl[215]["fails"] == 0
|
||||
and not refused and not any(x["hold"] for x in trl)
|
||||
and not [a for x in trl if x["t"] >= 216 for a in x["amber"]
|
||||
if a.startswith(("charger", "car"))])
|
||||
d48 = [(a["t"], a["explains"], a["over"], b["explains"], b["over"])
|
||||
for a, b in zip(trl, r0["trace"]) if a["t"] >= 230
|
||||
and (a["explains"], a["over"]) != (b["explains"], b["over"])]
|
||||
q1, q0 = rl["c"].car_peak_q, r0["c"].car_peak_q
|
||||
check(f"T48 [{tag}]: car_explains and car_over equal the no-lag twin; "
|
||||
f"car_peak_q banks the same quarters, within the 12 s of 10 A the "
|
||||
f"lag cost ({d48[:2]}; {q1} vs {q0})",
|
||||
not d48 and sorted(q1) == sorted(q0)
|
||||
and all(abs(q1[k] - q0[k]) <= 12.0 for k in q0))
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n9. SOLAR kWh (T49), MANUAL, GUARD AND LOOP UNCHANGED (T57-T60)")
|
||||
# =========================================================================== #
|
||||
|
||||
|
||||
def kwh(r):
|
||||
c = r["c"]
|
||||
return c.car_sun_kwh(), c.car.today_kwh
|
||||
|
||||
|
||||
r49a = std(3700, sun=const(3500.0)) # spare 3000: 12 A, 2760 W
|
||||
r49b = S.drive(const(900.0), const(7900.0), dur=3700, first="batteries",
|
||||
socs={"a": 71.0, "b": 100.0})
|
||||
r49c = std(3700, sun=step_fn((130, 1500.0), base=3500.0),
|
||||
opts={"ev_pause_min": 30})
|
||||
r49d = std(3700, sun=step_fn((130, 0.0), base=3500.0),
|
||||
opts={"ev_pause_min": 30})
|
||||
r49e = std(3700, mode="manual", sun=const(3500.0 + 2760.0))
|
||||
k = {x: kwh(r) for x, r in (("a", r49a), ("b", r49b), ("c", r49c),
|
||||
("d", r49d), ("e", r49e))}
|
||||
print(f" kWh (sun, today): {k}")
|
||||
check("T49 (a): Car first, spare 3000, the car 2760 W for ~1 h: the sun share "
|
||||
"is all of it (+-10 Wh of the car's own count)",
|
||||
k["a"][0] is not None and abs(k["a"][0] - k["a"][1]) <= 0.01
|
||||
and abs(k["a"][0] - 2760.0 * (3700 - 121) / 3.6e6) <= 0.02)
|
||||
check("T49 (b): Batteries first, scenario 2 (spare 7000, room 5000, car "
|
||||
"1840 W): all of the car's 1.84 kWh from the sun",
|
||||
abs(k["b"][0] - k["b"][1]) <= 0.01 and 1.75 <= k["b"][0] <= 1.86)
|
||||
hold49 = [x["t"] for x in r49c["trace"] if x["why"] == "hold"]
|
||||
h49 = (hold49[-1] - hold49[0] + 1) if hold49 else 0
|
||||
check(f"T49 (c): Car first hold, spare 1000 W, the car 1380 W: per hour 1.00 "
|
||||
f"of the 1.38 kWh; the hold lasts ev_pause_min, at most 30 min "
|
||||
f"({h49} s here), so 1000/1380 of the hold's energy (the hold's grid or "
|
||||
f"battery share is not counted)",
|
||||
abs(k["c"][0] - 1000.0 * h49 / 3.6e6) <= 0.02
|
||||
and abs((k["c"][1] - k["c"][0]) - 380.0 * h49 / 3.6e6) <= 0.02)
|
||||
check("T49 (d): a negative spare: nothing from the sun (only the 10 A before "
|
||||
"the cloud)", k["d"][0] <= 0.01 + 2300.0 * 15 / 3.6e6)
|
||||
check("T49 (e): Manual at 10 A with 3 kW export: 0 kWh from the sun",
|
||||
k["e"][0] in (None, 0.0) and k["e"][1] > 1.0)
|
||||
check("T49: 0 <= sun <= today, always",
|
||||
all(v[0] is None or 0.0 <= v[0] <= (v[1] or 0.0) + 1e-9
|
||||
for v in k.values()))
|
||||
c49 = r49a["c"]
|
||||
vals = c49.car_values()
|
||||
blk49 = homeview.car_block(c49, None)
|
||||
check(f"T49: the sensor goodwe_car_today_solar_kwh and the card agree "
|
||||
f"({vals.get('car_today_solar_kwh')}, {blk49['today']!r})",
|
||||
vals.get("car_today_solar_kwh") == round(k["a"][0], 3)
|
||||
and blk49["today"].endswith("from the sun.")
|
||||
and f"{k['a'][0]:.1f}" in blk49["today"])
|
||||
c49.car.day = "2099-01-01"
|
||||
c49._car_sun_tick(c49.car_now())
|
||||
check("T49 (f): at day rollover it is back to 0",
|
||||
c49.car_sun["kwh"] == 0.0 and c49.car_sun["day"] == "2099-01-01")
|
||||
|
||||
# T57: Manual ignores Solar's settings; Manual's shutdown fail state.
|
||||
rm1 = std(600, mode="manual", opts={"ev_margin_w": 0, "ev_start_min": 1})
|
||||
rm2 = std(600, mode="manual", first="batteries",
|
||||
events={100: act("car_sun_first", "car")})
|
||||
check("T57: Manual ignores sun_first, the margin and the dwells: the same "
|
||||
"writes", [(x[0], x[2]) for x in rm1["sim"].log]
|
||||
== [(x[0], x[2]) for x in rm2["sim"].log])
|
||||
rm3 = std(300, mode="manual", finale=_shutdown)
|
||||
check("T57: Manual's fail state at shutdown: the current stands (no write)",
|
||||
not [x for x in rm3["plant"].sets if x[1] == SET and x[0] >= 299])
|
||||
|
||||
# T58: Solar with no car vs no charger: the guard and the commands.
|
||||
spikes = step_fn((300, 2500.0), (900, 6500.0), (1500, 1200.0), (2400, 4800.0),
|
||||
base=900.0)
|
||||
g1 = S.drive(spikes, const(0.0), dur=3600, first="car", plug=False,
|
||||
socs={"a": 60.0, "b": 60.0})
|
||||
g2 = S.drive(spikes, const(0.0), dur=3600, first="car", plug=False,
|
||||
socs={"a": 60.0, "b": 60.0}, opts={"ev_charger": "off"})
|
||||
cm1 = [(t, e, v) for t, e, v in g1["plant"].sets if e.startswith("number.sp_")]
|
||||
cm2 = [(t, e, v) for t, e, v in g2["plant"].sets if e.startswith("number.sp_")]
|
||||
pg = [(a["t"], a["floor"], a["want"]) for a, b in zip(g1["trace"],
|
||||
g2["trace"])
|
||||
if (a["floor"], a["want"], a["proj"]) != (b["floor"], b["want"],
|
||||
b["proj"])]
|
||||
check(f"T58: Solar with no car (state A) for an hour of house steps against "
|
||||
f"ev_charger off: the guard's floor, want and projection and every "
|
||||
f"inverter command are bit-identical ({len(cm1)} commands, {pg[:1]})",
|
||||
cm1 == cm2 and not pg and g1["sim"].log == [])
|
||||
|
||||
# T59: the zero-grid loop with the car as a Solar car, or as a house load.
|
||||
l1 = std(1200, sun=step_fn((400, 4500.0), (800, 2500.0), base=3500.0),
|
||||
socs={"a": 60.0, "b": 60.0})
|
||||
car1 = {x["t"]: x["car"] for x in l1["trace"]}
|
||||
|
||||
|
||||
def house2(ts):
|
||||
return 500.0 + car1.get(float(round(ts + S.SAMPLE_LEAD_S)), 0.0)
|
||||
|
||||
|
||||
l2 = S.drive(house2, step_fn((400, 4500.0), (800, 2500.0), base=3500.0),
|
||||
dur=1200, first="car", plug=False, socs={"a": 60.0, "b": 60.0},
|
||||
opts={"ev_charger": "off"})
|
||||
lc1 = [(t, e, v) for t, e, v in l1["plant"].sets if e.startswith("number.sp_")]
|
||||
lc2 = [(t, e, v) for t, e, v in l2["plant"].sets if e.startswith("number.sp_")]
|
||||
dif = [(a, b) for a, b in zip(lc1, lc2) if a != b]
|
||||
check(f"T59: the same meter series with the car as a Solar car and as a "
|
||||
f"house load: the loop's commands are identical ({len(lc1)} vs "
|
||||
f"{len(lc2)}, {dif[:1]}); the batteries charge what the car leaves",
|
||||
lc1 == lc2 and min(v for _, _, v in lc1) < -500.0)
|
||||
|
||||
# T60: the House tile and the profile leave the car out in Solar.
|
||||
r60 = S.drive(const(900.0), const(7900.0), dur=200, first="car",
|
||||
socs={"a": 71.0, "b": 100.0})
|
||||
c60 = r60["c"]
|
||||
check(f"T60: in Solar the House tile and HouseProfile take the car out "
|
||||
f"(car_term {c60.car_term()}, the car {r60['sim'].power_w:.0f} W)",
|
||||
c60.car_term()[1] is False and r60["sim"].power_w > 1000.0
|
||||
and abs(c60.car_term()[0] - r60["sim"].power_w) < 1.0)
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n10. STRINGS, DOCS, SETTINGS (T50, T51, T52), THE SEAM (T55)")
|
||||
# =========================================================================== #
|
||||
from app import uitext # noqa: E402
|
||||
import style_rules # noqa: E402
|
||||
|
||||
KEYS = ("why.solar_batt", "why.solar_car", "why.solar_paused",
|
||||
"help_solar.description", "first", "first_help.description")
|
||||
bad50 = []
|
||||
for lang in ("en", "nl"):
|
||||
words_ = uitext.words(lang)
|
||||
for key in KEYS:
|
||||
node = words_["home_words"]["car"] if key.startswith("why") \
|
||||
else words_["home"]["car"]
|
||||
for part in key.split("."):
|
||||
node = node.get(part, {}) if isinstance(node, dict) else {}
|
||||
text = uitext.say(node, kw="2.0 kW", s="5", a="8") \
|
||||
if isinstance(node, str) else ""
|
||||
n_s = style_rules.sentences(text)
|
||||
long_ = [s for s in text.split(". ")
|
||||
if len(style_rules.words(s)) > 12]
|
||||
if not text or n_s > 2 or long_:
|
||||
bad50.append((lang, key, text))
|
||||
check(f"T50: why.solar_batt, why.solar_car, why.solar_paused, help.solar, "
|
||||
f"first and first.help in EN and NL: <= 2 sentences of <= 12 words "
|
||||
f"({bad50})", not bad50)
|
||||
en_why = uitext.words("en")["home_words"]["car"]["why"]["solar_over"]
|
||||
check(f"T50 D1: the card's Why reads exactly 'Solar charges the car at {{a}} "
|
||||
f"A. This sets the peak.' ({en_why!r}); the notice and row carry the "
|
||||
f"same words in one sentence (STYLE.md's rule for a grey note and row)",
|
||||
en_why == "Solar charges the car at {a} A. This sets the peak."
|
||||
and messages.row_car_over_solar("8").startswith(
|
||||
"Solar charges the car at 8 A")
|
||||
and messages.car_over_solar("8").body_nl)
|
||||
check("T50 guard: Manual's car_over notice and row are unchanged",
|
||||
messages.car_over("16").body == "You set 16 A, which takes this "
|
||||
"15-minute period over the peak limit."
|
||||
and str(messages.row_car_over()) == "The car charge you set takes this "
|
||||
"15-minute period over the peak limit.")
|
||||
check("T50 D3: the shutdown warning in EN and NL",
|
||||
messages.car_release_failed().title == "Car may still be charging"
|
||||
and "0 A" in messages.car_release_failed().body
|
||||
and "0 A" in messages.car_release_failed().body_nl)
|
||||
|
||||
docs = open(os.path.join(HERE, "DOCS.md"), encoding="utf-8").read()
|
||||
chlog = open(os.path.join(HERE, "CHANGELOG.md"), encoding="utf-8").read()
|
||||
nri = chlog.find("Not in a release yet")
|
||||
check("T51: DOCS 'Car charger' has a Solar section, a DECISIONS file for EV-20 "
|
||||
"exists, and a CHANGELOG line under 'Not in a release yet'",
|
||||
"**Solar mode.**" in docs
|
||||
and os.path.exists(os.path.join(HERE, "DECISIONS",
|
||||
"EV-20-solar-mode.md"))
|
||||
and nri >= 0 and "EV-20" in chlog[nri:nri + 4000])
|
||||
check("T51: the shipped defaults ev_margin_w 100, ev_pause_min 5, "
|
||||
"ev_start_min 2, as config.yaml",
|
||||
CH.EV_OPTION_DEFAULTS["ev_margin_w"] == 100
|
||||
and CH.EV_OPTION_DEFAULTS["ev_pause_min"] == 5
|
||||
and CH.EV_OPTION_DEFAULTS["ev_start_min"] == 2)
|
||||
|
||||
cfg = open(os.path.join(HERE, "config.yaml"), encoding="utf-8").read()
|
||||
schema = {k: v for k, v in (("ev_margin_w", "int(0,1000)"),
|
||||
("ev_pause_min", "int(1,30)"),
|
||||
("ev_start_min", "int(1,30)"))}
|
||||
check("T52: config.yaml's schema holds the same ranges as the validator",
|
||||
all(f" {k}: {v}" in cfg for k, v in schema.items())
|
||||
and CH.SOLAR_RANGES == {"ev_margin_w": (0, 1000),
|
||||
"ev_pause_min": (1, 30),
|
||||
"ev_start_min": (1, 30)})
|
||||
base_opts = {"ev_charger": "alfen_ha", "ev_current_entity": SET}
|
||||
bad52, ok52 = [], []
|
||||
for key, vals, good in (("ev_margin_w", (-1, 1001), (0, 1000, 100)),
|
||||
("ev_pause_min", (0, 31), (1, 30, 5)),
|
||||
("ev_start_min", (0, 31), (1, 30, 2))):
|
||||
for v in vals:
|
||||
probs = validate._charger_problems(dict(base_opts, **{key: v}), {})
|
||||
if not any(messages.LABELS[key] in p for p in probs):
|
||||
bad52.append((key, v, probs))
|
||||
for v in good:
|
||||
probs = validate._charger_problems(dict(base_opts, **{key: v}), {})
|
||||
if probs:
|
||||
ok52.append((key, v, probs))
|
||||
check(f"T52: -1/1001, 0/31, 0/31 are refused with a message naming the "
|
||||
f"setting ({bad52[:1]})", not bad52)
|
||||
check(f"T52: the edges and the defaults are accepted ({ok52[:1]})", not ok52)
|
||||
|
||||
|
||||
def seam_callers():
|
||||
import ast
|
||||
import io
|
||||
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")
|
||||
or (n.func.attr == "release"
|
||||
and "charger" in ast.dump(n.func.value))):
|
||||
out.append((f, n.func.attr))
|
||||
return sorted(out)
|
||||
|
||||
|
||||
check(f"T55: the write seam is still exactly carmode.py's write_current and "
|
||||
f"write_phases ({seam_callers()}); Solar and release() go through them",
|
||||
seam_callers() == [("carmode.py", "write_current"),
|
||||
("carmode.py", "write_phases")]
|
||||
and carmode.SolarWriter._write is not carmode.ManualWriter._write
|
||||
and "super()._write" in open(os.path.join(HERE, "app", "carmode.py"),
|
||||
encoding="utf-8").read())
|
||||
|
||||
report()
|
||||
@@ -1,52 +0,0 @@
|
||||
"""EV-20: T53, the acceptance sim day, Batteries first. `python3 -B test_ev20_long.py`
|
||||
|
||||
The day and what is graded are in `tools/ev20_day.py`: the real Controller,
|
||||
N=2, 08:00-18:00 of sun with 12 clouds of 1 to 8 minutes, a house of 0.4 to
|
||||
2.5 kW with three +3 kW steps; `step` over the day, `step_race` over three
|
||||
hours, a car-Off twin around the house steps.
|
||||
Car first is test_ev20_long_car.py.
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
import ev20_day # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
class _Log(logging.Handler):
|
||||
def __init__(self):
|
||||
super().__init__(logging.DEBUG)
|
||||
self.tb = []
|
||||
|
||||
def emit(self, r):
|
||||
if r.exc_info:
|
||||
self.tb.append(r.getMessage())
|
||||
|
||||
|
||||
LOG = _Log()
|
||||
_g = logging.getLogger("goodwe")
|
||||
_g.addHandler(LOG)
|
||||
_g.setLevel(logging.DEBUG)
|
||||
_g.propagate = False
|
||||
|
||||
print("T53: THE SIM DAY, BATTERIES FIRST")
|
||||
ev20_day.run_day("batteries", check)
|
||||
check("T53: no Traceback", LOG.tb == [])
|
||||
|
||||
print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}")
|
||||
for f in fails:
|
||||
print(" FAIL:", f)
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -1,52 +0,0 @@
|
||||
"""EV-20: T53, the acceptance sim day, Car first. `python3 -B test_ev20_long_car.py`
|
||||
|
||||
The day and what is graded are in `tools/ev20_day.py`: the real Controller,
|
||||
N=2, 08:00-18:00 of sun with 12 clouds of 1 to 8 minutes, a house of 0.4 to
|
||||
2.5 kW with three +3 kW steps; `step` over the day, `step_race` over three
|
||||
hours, a car-Off twin around the house steps.
|
||||
Batteries first is test_ev20_long.py.
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
import ev20_day # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
class _Log(logging.Handler):
|
||||
def __init__(self):
|
||||
super().__init__(logging.DEBUG)
|
||||
self.tb = []
|
||||
|
||||
def emit(self, r):
|
||||
if r.exc_info:
|
||||
self.tb.append(r.getMessage())
|
||||
|
||||
|
||||
LOG = _Log()
|
||||
_g = logging.getLogger("goodwe")
|
||||
_g.addHandler(LOG)
|
||||
_g.setLevel(logging.DEBUG)
|
||||
_g.propagate = False
|
||||
|
||||
print("T53: THE SIM DAY, CAR FIRST")
|
||||
ev20_day.run_day("car", check)
|
||||
check("T53: no Traceback", LOG.tb == [])
|
||||
|
||||
print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}")
|
||||
for f in fails:
|
||||
print(" FAIL:", f)
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -1,227 +0,0 @@
|
||||
"""EV-20: Solar in shadow mode and beside another writer (T38-T46; N10, N16).
|
||||
`python3 -B test_ev20_writers.py`
|
||||
|
||||
The real Controller on `tools/ev20_sun.py` (N batteries, the sun, the house and
|
||||
`chargersim.SimCharger` on one meter, a 1 s cycle on a model clock), plus unit
|
||||
rows for the pure parts; shared pieces in `tools/ev20_kit.py`. Each section
|
||||
names the T-ids and N-ids of reports/EV-20-test-plan.md it implements.
|
||||
"Std run": Car first, both batteries full, house 500 W, sun 2900 W: spare
|
||||
2400 W, the car target 2300 W = 10 A on 1 phase, written 120 s after the start.
|
||||
Times are the cycle's second; `race` runs use the production order (read, the
|
||||
writer settles, the cycle).
|
||||
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import carmode, chargers as CH, ctl_car, homeview, messages # noqa: E402
|
||||
from app import mqtt, validate, web, main as app_main # noqa: E402
|
||||
from app.carmode import SolarPlan, amps_for, spare_w # noqa: E402
|
||||
import ev20_sun as S # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
from ev20_kit import * # noqa: E402,F401,F403
|
||||
from ev20_kit import LOG, check, fails, report # noqa: E402,F401
|
||||
from named_absence import nth, present # noqa: E402,F401
|
||||
from ev20_kit import (_dies, _err, _freeze_after_write, _shutdown, # noqa: E402,F401
|
||||
_until)
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n7. SHADOW, ANOTHER WRITER (T38-T46)")
|
||||
# =========================================================================== #
|
||||
cloud = (lambda t: 600.0 + (5200.0 if (t // 400) % 3 == 0 else
|
||||
1200.0 if (t // 400) % 3 == 1 else 2600.0))
|
||||
for how, opts in (("on", {"shadow_mode": "on"}),
|
||||
("auto, stopped", {"shadow_mode": "auto"})):
|
||||
ev = {0: lambda p, c: setattr(c, "auto", False)} \
|
||||
if how != "on" else {}
|
||||
rs = std(3600, sun=cloud, opts=opts, events=ev)
|
||||
rt = std(3600, sun=cloud)
|
||||
sel_t = [x[0] for x in selects(rt)]
|
||||
near = (lambda t: any(st - 10.0 <= t <= st + 15.0 for st in sel_t))
|
||||
diff = [(a["t"], (a["would"] or (0.0,))[0], b["a"])
|
||||
for a, b in zip(rs["trace"], rt["trace"])
|
||||
if (a["would"] or (0.0,))[0] != b["a"]]
|
||||
far = [x for x in diff if not near(x[0])]
|
||||
check(f"T38 [shadow {how}]: a 1 h cloudy run from the start: the charger "
|
||||
f"log is empty, and every cycle's 'would set' is the current of a "
|
||||
f"non-shadow twin, but within seconds of the twin's own phase "
|
||||
f"selects ({len(diff)} differ, {len(far)} away from a select: "
|
||||
f"{far[:3]}; selects {sel_t})",
|
||||
rs["sim"].log == [] and not far and len(diff) <= 20 * len(sel_t)
|
||||
and len(cur_writes(rt)) >= 3)
|
||||
|
||||
# T39: another writer.
|
||||
for race in (False, True):
|
||||
tag = "race" if race else "step"
|
||||
n = LOG.mark()
|
||||
r39 = std(900, sun=const(600.0 + 1840.0), race=race, rows=True,
|
||||
events={300: lambda p, c: p.ch.set_current(13),
|
||||
600: act("car_mode", "solar")})
|
||||
tr39 = r39["trace"]
|
||||
held = next((x["t"] for x in tr39 if x["hold"]), None)
|
||||
other = [m for m in LOG.since(n, "WARNING") if "CHARGER_OTHER" in m]
|
||||
check(f"T39 [{tag}]: sim.set_current(13) at 300 s while Solar set 8 A: "
|
||||
f"the hold at 330 s, not 329 s (at {held}); no write over it",
|
||||
held is not None and 330 <= held <= 331
|
||||
and not [x for x in cur_writes(r39) if 300 <= x[0] < 600])
|
||||
check(f"T39 [{tag}]: the amber charger_other row and one warning until "
|
||||
f"Solar is pressed ({len(other)})", len(other) == 1
|
||||
and "charger_other" in tr39[400]["amber"]
|
||||
and "charger_other" not in tr39[620]["amber"])
|
||||
check(f"T39 [{tag}]: pressing Solar takes the charger as it is and lifts "
|
||||
f"the hold: Solar's own 8 A is written again "
|
||||
f"({cur_writes(r39)[-1:]})",
|
||||
cur_writes(r39)[-1][1] == 8.0 and 600 <= cur_writes(r39)[-1][0]
|
||||
<= 602 and not tr39[700]["hold"])
|
||||
check("T39: the row's text in both languages",
|
||||
messages.row_charger_other_solar().nl != ""
|
||||
and "Solar" in str(messages.row_charger_other_solar())
|
||||
and "Zon" in messages.row_charger_other_solar().nl)
|
||||
for name, fn in (("Stop", lambda p, c: setattr(c, "auto", False)),
|
||||
("Off", act("car_mode", "off"))):
|
||||
rr = std(500, sun=const(600.0 + 1840.0),
|
||||
events={300: lambda p, c: p.ch.set_current(13), 310: fn})
|
||||
check(f"T39 (b): {name} 10 s after the other writer, inside the 30 s: "
|
||||
f"the way-out 0 A is written ({cur_writes(rr)})",
|
||||
cur_writes(rr)[-1][1] == 0.0 and 310 <= cur_writes(rr)[-1][0] <= 311)
|
||||
n = LOG.mark()
|
||||
r39g = std(1500, sun=step_fn((400, 600.0 + 4600.0), (900, 600.0 + 1000.0),
|
||||
base=600.0 + 1840.0))
|
||||
check("T39 guard: Solar's own writes, own 0 A pause and own phase sequence "
|
||||
"are never flagged (no hold, no CHARGER_OTHER)",
|
||||
not any(x["hold"] or x["mismatch"] is not None for x in r39g["trace"])
|
||||
and not [m for m in LOG.since(n) if "CHARGER_OTHER" in m]
|
||||
and selects(r39g) and 0.0 in [a for _, a, _ in cur_writes(r39g)])
|
||||
|
||||
# T40: EV-05 r5 Major 3, the exits under the hold.
|
||||
EXITS = {"Stop": lambda p, c: setattr(c, "auto", False),
|
||||
"shadow on": lambda p, c: c.o.__setitem__("shadow_mode", "on"),
|
||||
"latch": lambda p, c: setattr(c.circ_wd, "tripped", True),
|
||||
"Off": act("car_mode", "off"),
|
||||
"charger error": _err}
|
||||
for name, fn in EXITS.items():
|
||||
rr = std(1000, sun=const(600.0 + 2070.0),
|
||||
opts={"shadow_mode": "off"},
|
||||
events={600: lambda p, c: p.ch.set_current(16), 700: fn})
|
||||
check(f"T40 [{name}]: Solar at 9 A, another writer's 16 A at 600 s (hold "
|
||||
f"at 630 s), {name} at 700 s: nothing written after 600 s; the "
|
||||
f"charger still at 16 A ({cur_writes(rr)})",
|
||||
not [x for x in attempts(rr) if x[0] >= 600]
|
||||
and rr["sim"].setpoint_a == 16.0)
|
||||
|
||||
# T41: the user changes Manual's values while Solar holds.
|
||||
r41 = std(1000, sun=const(600.0 + 2070.0),
|
||||
events={600: lambda p, c: p.ch.set_current(16),
|
||||
700: act("car_current", 12), 710: act("car_phases", 3)})
|
||||
check("T41: Manual's current and phases set while Solar holds: the hold is "
|
||||
"not lifted, nothing written over the 16 A",
|
||||
not [x for x in attempts(r41) if x[0] >= 600]
|
||||
and r41["sim"].setpoint_a == 16.0 and r41["c"].car_solar.hold)
|
||||
|
||||
# T42: EV-05 r6 Major 2, shutdown after an exit and another writer.
|
||||
for name, fn, opts in (("shadow on", lambda p, c: c.o.__setitem__(
|
||||
"shadow_mode", "on"), {}),
|
||||
("Stop (auto)", lambda p, c: setattr(c, "auto", False),
|
||||
{"shadow_mode": "auto"}),
|
||||
("Stop (off)", lambda p, c: setattr(c, "auto", False),
|
||||
{"shadow_mode": "off"}),
|
||||
("guard: writing", lambda p, c: None, {})):
|
||||
rr = std(600, opts=opts, finale=_shutdown,
|
||||
events={300: fn, 400: lambda p, c: p.ch.set_current(16)})
|
||||
shut = [x for x in attempts(rr) if x[0] >= 599]
|
||||
check(f"T42 [{name}]: another writer's 16 A at 400 s, shutdown at 600 s: "
|
||||
f"no charger write at shutdown, 16 A stands ({shut})",
|
||||
shut == [] and rr["sim"].setpoint_a == 16.0
|
||||
and (name != "guard: writing" or rr["c"].car_solar.hold))
|
||||
|
||||
# T43: a start in Solar with shadow on, or stopped, over another writer.
|
||||
for how, opts, ev in (("shadow on", {"shadow_mode": "on"}, {}),
|
||||
("auto, stopped", {"shadow_mode": "auto"},
|
||||
{0: lambda p, c: setattr(c, "auto", False)})):
|
||||
blk = {}
|
||||
ev = dict(ev)
|
||||
ev[250] = lambda p, c: blk.update(b=homeview.car_block(c, None))
|
||||
rr = std(300, sim=SimCharger(setpoint_a=16), opts=opts, events=ev)
|
||||
check(f"T43 [{how}]: a start in Solar while another writer has the car at "
|
||||
f"16 A: nothing written; the card says what it would set "
|
||||
f"({blk.get('b', {}).get('why')!r})",
|
||||
rr["sim"].log == [] and "would" in blk.get("b", {}).get("why", ""))
|
||||
|
||||
# T44: Stop, another writer, Start.
|
||||
r44 = std(900, rows=True, events={300: lambda p, c: setattr(c, "auto", False),
|
||||
400: lambda p, c: p.ch.set_current(16),
|
||||
600: lambda p, c: setattr(c, "auto", True)})
|
||||
check(f"T44: Stop at 300 s (0 A taken), another writer's 16 A at 400 s, "
|
||||
f"Start at 600 s: Solar holds off, amber row, no write "
|
||||
f"({cur_writes(r44)})",
|
||||
[(t, a) for t, a, _ in cur_writes(r44)] == [(120.0, 10.0), (300.0, 0.0)]
|
||||
and "charger_other" in r44["trace"][700]["amber"])
|
||||
|
||||
# T45: EV-05 r7 Major 1, Solar to Off while not writing.
|
||||
T45 = {
|
||||
"a": ({"shadow_mode": "on"}, 16, {200: act("car_mode", "off")}),
|
||||
"b": ({"shadow_mode": "auto"}, 16,
|
||||
{0: lambda p, c: setattr(c, "auto", False),
|
||||
200: act("car_mode", "off")}),
|
||||
"c": ({}, 0, {300: lambda p, c: c.o.__setitem__("shadow_mode", "on"),
|
||||
400: lambda p, c: p.ch.set_current(16),
|
||||
410: act("car_mode", "off")}),
|
||||
"d": ({}, 0, {300: lambda p, c: c.o.__setitem__("shadow_mode", "on"),
|
||||
400: lambda p, c: p.ch.set_current(16),
|
||||
600: act("car_mode", "off")}),
|
||||
}
|
||||
for k, (opts, sp, ev) in T45.items():
|
||||
rr = std(800, sim=SimCharger(setpoint_a=sp), opts=opts, events=ev)
|
||||
late = [x for x in attempts(rr) if x[0] >= 300 or sp]
|
||||
check(f"T45 ({k}): Solar to Off while not writing: no write over the "
|
||||
f"other writer, the charger stays at 16 A ({late})",
|
||||
[x for x in late if not (k in "cd" and x == (300.0, 0.0))] == []
|
||||
and rr["sim"].setpoint_a == 16.0)
|
||||
rr = std(400, sim=SimCharger(setpoint_a=16), opts={"shadow_mode": "on"},
|
||||
events={200: act("car_mode", "manual")})
|
||||
check("T45 guard: a shadow start, then Manual: nothing written",
|
||||
rr["sim"].log == [])
|
||||
|
||||
# T46: EV-05 r8 Major 1, another writer's phases.
|
||||
r46 = run("T46", S.drive, step_fn((300, 700.0), (600, 900.0), base=500.0),
|
||||
const(3500.0), dur=900, first="car", phases=3,
|
||||
socs={"a": 10.0, "b": 10.0}, rows=True,
|
||||
events={140: lambda p, c: p.ch.set_phases(3),
|
||||
300: lambda p, c: p.ch.set_phases(3)})
|
||||
w46, s46 = cur_writes(r46), selects(r46)
|
||||
check(f"T46: Solar starts on 1 phase (select at the start), then another "
|
||||
f"writer selects 3 phases: while Solar runs on them it selects nothing "
|
||||
f"(a select back is EV-22's; the next start from the pause is on 1 "
|
||||
f"phase, Expected 5) ({[(x[0], x[2]) for x in s46]})",
|
||||
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]
|
||||
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
|
||||
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)
|
||||
check(f"T46 (c): the car's grid import only within the hold rule "
|
||||
f"(<= 300 s of 6 A on 3 phases) ({imp46 / 3600:.0f} Wh)",
|
||||
imp46 <= 4140.0 * 302.0)
|
||||
r46h = std(900, sun=const(3500.0), phases=3,
|
||||
events={200: lambda p, c: p.ch.set_current(16),
|
||||
300: lambda p, c: p.ch.set_phases(3)})
|
||||
check("T46 (d)/N16: while EV-04's hold stands Solar writes nothing, a "
|
||||
"select included",
|
||||
not [x for x in attempts(r46h) if x[0] >= 200]
|
||||
and not [x for x in selects(r46h) if x[0] >= 200])
|
||||
|
||||
report()
|
||||
@@ -1,939 +0,0 @@
|
||||
"""EV-28: the phases are never selected while the car still draws.
|
||||
`python3 -B test_ev28.py`
|
||||
|
||||
The stage "zero" of the phase sequence counted mode3 B as quiet whatever the
|
||||
power, and selected anyway after ZERO_WAIT_S. Now: a power reading decides
|
||||
(under QUIET_W); mode3 (not C, not D) only without one; a car still drawing at
|
||||
the timeout gets NO select, its current back at once, and one failed try.
|
||||
|
||||
U = the ManualWriter on a stub driver (exact seconds). W = the real Controller
|
||||
on the charger model (`chargersim`, power ramps down at `ramp_w_s`).
|
||||
|
||||
1. U: what counts as quiet (T1, T3, T4, T6, T7, T8).
|
||||
2. W: the rig shapes (T2, T5, T9, T10, T16, T17).
|
||||
3. W: tries, the amber row, the log (T11, T12, T13).
|
||||
4. W: the other ends of a sequence and the alarm (T14, T15, T18-T21).
|
||||
5. W: the digests of the quiet shapes, from 4eba2d9 (T22).
|
||||
6. Docs and the module docstring (T25). T23 is in test_ev04 (slow_stop), T24
|
||||
its fuzz. Mutants (T26): see the dev report.
|
||||
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||
|
||||
from app import carmode, chargers as CH, ctl_car # noqa: E402
|
||||
from app.carmode import ManualWriter, QUIET_W, ZERO_WAIT_S # noqa: E402
|
||||
from app.carmode import SETTLE_S, PHASE_GAP_S, MAX_TRIES # noqa: E402
|
||||
from app.main import Controller # noqa: E402
|
||||
from app import freshness # noqa: E402
|
||||
from named_absence import nth # noqa: E402
|
||||
from chargersim import FakeHa, SimCharger # noqa: E402
|
||||
import ev04_peak as P # noqa: E402
|
||||
import safety81_sim as s81 # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
class _Cap(logging.Handler):
|
||||
def __init__(self):
|
||||
super().__init__(logging.DEBUG)
|
||||
self.rec = []
|
||||
|
||||
def emit(self, r):
|
||||
self.rec.append((r.levelno, r.getMessage()))
|
||||
|
||||
def loud(self, since=0):
|
||||
"""INFO and above from `since` on."""
|
||||
return [m for lv, m in self.rec[since:] if lv >= logging.INFO]
|
||||
|
||||
|
||||
CAP = _Cap()
|
||||
logging.getLogger("goodwe").addHandler(CAP)
|
||||
logging.getLogger("goodwe").setLevel(logging.DEBUG)
|
||||
|
||||
|
||||
def run(coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
# =========================================================================== #
|
||||
# U: the writer on a stub driver
|
||||
# =========================================================================== #
|
||||
class Drv:
|
||||
def __init__(self, phases=1, a=10.0, ok_phases=True):
|
||||
self.log, self.now, self.phases, self.a = [], 0.0, phases, a
|
||||
self.ok_phases = ok_phases
|
||||
|
||||
async def write_current(self, a):
|
||||
self.log.append((self.now, "current", float(a)))
|
||||
self.a = float(a)
|
||||
return True
|
||||
|
||||
async def write_phases(self, n):
|
||||
self.log.append((self.now, "phases", n))
|
||||
if self.ok_phases:
|
||||
self.phases = n
|
||||
return self.ok_phases
|
||||
|
||||
|
||||
class Trk:
|
||||
obs_at = None
|
||||
|
||||
def begin_write(self):
|
||||
pass
|
||||
|
||||
def end_write(self, *_a):
|
||||
pass
|
||||
|
||||
def note_write(self, *_a):
|
||||
pass
|
||||
|
||||
|
||||
async def unit(fn, times=None, want_phases=3, want_a=10.0, clamp_fn=None,
|
||||
n_phases=1, a0=10.0, ok_phases=True):
|
||||
"""0 A is written at t=0. `fn(dt)` is (mode3, power_w) `dt` s later, or None
|
||||
(unavailable). Returns (writer, driver, abandon time or None)."""
|
||||
w, d = ManualWriter(), Drv(phases=n_phases, a=a0, ok_phases=ok_phases)
|
||||
trk = Trk()
|
||||
|
||||
async def step(t, state, power):
|
||||
d.now = float(t)
|
||||
a = d.a
|
||||
r = CH.ChargerReading(available=state is not None, state=state,
|
||||
power_w=power, setpoint_a=a, allowed_a=a,
|
||||
phases_allowed=d.phases)
|
||||
await w.step(d, r, mode="manual", want_a=want_a,
|
||||
want_phases=want_phases, rev=1,
|
||||
clamp=clamp_fn(t) if clamp_fn else 16.0, now=float(t),
|
||||
tracker=trk, writing=True, status="charging",
|
||||
clock=lambda: float(t))
|
||||
await step(0.0, "C", 2300.0)
|
||||
aband = None
|
||||
for t in (times if times is not None else range(1, 41)):
|
||||
x = fn(t)
|
||||
if x is None:
|
||||
await step(t, None, None)
|
||||
else:
|
||||
await step(t, x[0], x[1])
|
||||
if aband is None and w.seq is not None \
|
||||
and w.seq["stage"] == "settle" and w.seq.get("failed") \
|
||||
and not d.log[-1][1] == "phases":
|
||||
aband = t
|
||||
if aband is None and w.seq is None and w.phase_fails:
|
||||
aband = t
|
||||
return w, d, aband
|
||||
|
||||
|
||||
def phases_at(d):
|
||||
return [x for x in d.log if x[1] == "phases"]
|
||||
|
||||
|
||||
print("1. U: WHAT COUNTS AS QUIET")
|
||||
for p in (600.0, 1200.0, 2152.0, 2200.0):
|
||||
w, d, ab = run(unit(lambda t, p=p: ("B", p), range(1, 20)))
|
||||
check(f"T1: B with {p:.0f} W for 19 s: no select ({d.log})",
|
||||
not phases_at(d) and w.seq is not None
|
||||
and w.seq["stage"] == "zero")
|
||||
|
||||
w, d, ab = run(unit(lambda t: ("B", 40.0 if t >= 10 else 2152.0),
|
||||
range(1, 15)))
|
||||
sel = [x[0] for x in phases_at(d)]
|
||||
check(f"T3: the live Alfen shape (B, 2152 W to t0+9, 40 W at t0+10): select "
|
||||
f"at t0+10 and not before ({sel})", sel == [10.0])
|
||||
|
||||
w, d, ab = run(unit(lambda t: ("B", 100.0), range(1, 20)))
|
||||
check("T4: exactly 100.0 W with B: not quiet, no select (strict <)",
|
||||
not phases_at(d))
|
||||
for p, st in ((99.9, "C"), (0.0, "B"), (-5.0, "C")):
|
||||
w, d, ab = run(unit(lambda t, p=p, st=st: (st, p), range(1, 4)))
|
||||
check(f"T4: {p} W with {st}: select on the first step ({d.log})",
|
||||
[x[0] for x in phases_at(d)] == [1.0])
|
||||
|
||||
w, d, ab = run(unit(lambda t: ("B", 30.0) if t >= 20 else ("C", 2000.0),
|
||||
[19.9, 20.0, 21.0]))
|
||||
check(f"T6: quiet first seen at exactly t0+20: select at 20 ({d.log})",
|
||||
[x[0] for x in phases_at(d)] == [20.0])
|
||||
w, d, ab = run(unit(lambda t: ("B", 500.0), [19.9, 20.0, 21.0]))
|
||||
check("T6: still drawing at 19.9: waits; at 20.0: no select, abandoned "
|
||||
f"({d.log}, abandon {ab})",
|
||||
not phases_at(d) and ab == 20.0 and w.phase_fails == 1
|
||||
and d.log[-1] == (20.0, "current", 10.0))
|
||||
w, d, ab = run(unit(lambda t: ("B", 500.0), [19.9]))
|
||||
check("T6: at 19.9 s the sequence still waits",
|
||||
w.seq is not None and w.seq["stage"] == "zero" and w.phase_fails == 0)
|
||||
|
||||
w, d, ab = run(unit(lambda t: ("B", None), range(1, 4)))
|
||||
check("T7: no power reading and B: select on the first step, as before",
|
||||
[x[0] for x in phases_at(d)] == [1.0])
|
||||
w, d, ab = run(unit(lambda t: ("D", None), range(1, 30)))
|
||||
check("T7/Expected 2: no power reading and D (charging with ventilation) is "
|
||||
"not quiet: no select", not phases_at(d))
|
||||
# state None needs an available reading with state None: own helper
|
||||
async def unit_blind(state):
|
||||
w, d = ManualWriter(), Drv()
|
||||
trk = Trk()
|
||||
for t in range(0, 26):
|
||||
d.now = float(t)
|
||||
a = d.a
|
||||
r = CH.ChargerReading(available=True, state=("C" if t == 0 else state),
|
||||
power_w=2300.0 if t == 0 else None,
|
||||
setpoint_a=a, allowed_a=a,
|
||||
phases_allowed=d.phases)
|
||||
await w.step(d, r, mode="manual", want_a=10.0, want_phases=3, rev=1,
|
||||
clamp=16.0, now=float(t), tracker=trk, writing=True,
|
||||
status="charging", clock=lambda: float(t))
|
||||
return w, d
|
||||
|
||||
|
||||
for st in ("C", None):
|
||||
w, d = run(unit_blind(st))
|
||||
check(f"T8: no power reading, state {st}: no select ever, abandon at "
|
||||
f"t0+20, one restore, one failed try ({d.log})",
|
||||
not phases_at(d) and w.phase_fails == 1 and w.seq is None
|
||||
and d.log == [(0.0, "current", 0.0), (20.0, "current", 10.0)])
|
||||
|
||||
# the abandon is immediate: no SETTLE_S wait (brief answer 1)
|
||||
w, d, ab = run(unit(lambda t: ("C", 900.0), range(1, 26)))
|
||||
check(f"Expected 3: the current comes back at the abandon step itself, not "
|
||||
f"after SETTLE_S ({d.log})",
|
||||
d.log == [(0.0, "current", 0.0), (20.0, "current", 10.0)]
|
||||
and w.last_switch == 20.0)
|
||||
w, d, ab = run(unit(lambda t: ("C", 900.0), range(1, 26),
|
||||
clamp_fn=lambda t: 16.0 if t < 10 else 8.0, want_a=16.0))
|
||||
check(f"N2: the restore is clamped at the abandon ({d.log[-1]})",
|
||||
d.log[-1] == (20.0, "current", 8.0))
|
||||
|
||||
# =========================================================================== #
|
||||
# W: the real Controller on the charger model
|
||||
# =========================================================================== #
|
||||
freshness.monotonic = lambda: CLOCK[0]
|
||||
CLOCK = [1000.0]
|
||||
SET = "number.wallbox_power_connector_max_current_socket_1"
|
||||
BASE = {"setpoint_entity": "number.sp", "meter_entity": "sensor.grid",
|
||||
"soc_entity": "sensor.soc", "batt_entity": "sensor.batt",
|
||||
"meter_source": "off", "max_w": 5000, "gain": 0.6, "slew_w": 500,
|
||||
"deadband_w": 15, "target_grid_w": 0, "step_w": 10, "heartbeat_s": 10,
|
||||
"stale_input_s": 15, "shadow_mode": "off", "peak_cap_w": 3500,
|
||||
"pv_entities": ["sensor.pv"]}
|
||||
CAR = dict(BASE, ev_charger="alfen_ha", ev_max_a=16, ev_phases="auto",
|
||||
ev_current_entity=SET)
|
||||
|
||||
|
||||
class _Store:
|
||||
def __init__(self):
|
||||
self.data = {}
|
||||
|
||||
def set(self, k, v):
|
||||
self.data[k] = v
|
||||
|
||||
def get(self, k, d=None):
|
||||
return self.data.get(k, d)
|
||||
|
||||
def set_time(self, k, v):
|
||||
self.data[k] = v.isoformat()
|
||||
|
||||
def get_time(self, k):
|
||||
v = self.data.get(k)
|
||||
return None if v is None else datetime.fromisoformat(v)
|
||||
|
||||
|
||||
class _Pub:
|
||||
enabled = False
|
||||
|
||||
def publish(self, v):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class Site(FakeHa):
|
||||
def __init__(self, charger, grid=500.0, batt=0.0, pv=2000.0):
|
||||
super().__init__(charger, None)
|
||||
self.grid, self.batt, self.pv = grid, batt, pv
|
||||
|
||||
async def limits(self, _e):
|
||||
return (-5000.0, 5000.0, 1.0)
|
||||
|
||||
def _all(self):
|
||||
out = super()._all()
|
||||
for eid, val, unit_ in (("sensor.grid", self.grid, "W"),
|
||||
("sensor.soc", 50.0, "%"),
|
||||
("sensor.batt", self.batt, "W"),
|
||||
("sensor.pv", self.pv, "W")):
|
||||
out[eid] = {"entity_id": eid, "state": str(val),
|
||||
"attributes": {"unit_of_measurement": unit_}}
|
||||
return out
|
||||
|
||||
async def number(self, entity_id, invert=False):
|
||||
s = self._all().get(entity_id)
|
||||
try:
|
||||
v = float(s["state"])
|
||||
except (TypeError, ValueError, KeyError):
|
||||
return None
|
||||
return -v if invert else v
|
||||
|
||||
async def set_number(self, entity_id, value):
|
||||
if entity_id == "number.sp":
|
||||
self.sets.append((entity_id, float(value)))
|
||||
self.batt = float(value)
|
||||
return True
|
||||
return await super().set_number(entity_id, float(value))
|
||||
|
||||
|
||||
class World:
|
||||
def __init__(self, opts=CAR, sim=None, store=None, setpoint=10, grid=800.0,
|
||||
phases=1):
|
||||
self.sim = sim or SimCharger(setpoint_a=setpoint)
|
||||
self.sim.plug_in()
|
||||
self.sim.phases_allowed = phases
|
||||
self.site = Site(self.sim, grid=grid)
|
||||
self.store = store or _Store()
|
||||
self.t = 1000.0
|
||||
CLOCK[0] = self.t
|
||||
self.make(opts)
|
||||
|
||||
def make(self, opts):
|
||||
self.opts = dict(opts)
|
||||
self.c = Controller(dict(opts), self.site, self.store, _Pub(),
|
||||
stop=asyncio.Event())
|
||||
self.c.auto = True
|
||||
self.c.dev_min, self.c.dev_max = -5000.0, 5000.0
|
||||
self.drv = self.c.charger
|
||||
if hasattr(self.drv, "_sleep"):
|
||||
self.drv._sleep = self.sleep
|
||||
self.drv._clock = lambda: CLOCK[0]
|
||||
|
||||
async def sleep(self, s):
|
||||
self.sim.tick(s)
|
||||
self.t += s
|
||||
CLOCK[0] = self.t
|
||||
|
||||
async def step(self, n=1, dt=1.0):
|
||||
for _ in range(n):
|
||||
self.sim.tick(dt)
|
||||
self.t += dt
|
||||
CLOCK[0] = self.t
|
||||
await self.c.read_inputs(now_mono=self.t)
|
||||
await self.c.cycle()
|
||||
await self.c.car_settle()
|
||||
|
||||
async def step_race(self, n=1, dt=1.0):
|
||||
for _ in range(n):
|
||||
self.sim.tick(dt)
|
||||
self.t += dt
|
||||
CLOCK[0] = self.t
|
||||
await self.c.read_inputs(now_mono=self.t)
|
||||
await self.c.car_settle()
|
||||
await self.c.cycle()
|
||||
|
||||
async def act(self, what, value):
|
||||
return await self.c.handle_action(what, value=value)
|
||||
|
||||
def writes(self, what=None):
|
||||
return self.sim.writes(what)
|
||||
|
||||
def rows(self):
|
||||
return {r["id"]: r for r in self.c.checks()}
|
||||
|
||||
@property
|
||||
def wr(self):
|
||||
return self.c.car_writer
|
||||
|
||||
|
||||
async def ready(phases=1, a=10, to=3, ramp=200.0, delay=1.0, opts=CAR,
|
||||
station=None):
|
||||
"""The car draws `a` A on `phases`; the add-on is in Manual at `a`; the
|
||||
sim's power then falls at `ramp` W/s and B comes `delay` s after 0 A."""
|
||||
w = World(opts, setpoint=a, phases=phases)
|
||||
if station:
|
||||
w.sim.station_a = float(station)
|
||||
await w.step(8)
|
||||
await w.act("car_phases", phases) # the wish is what the car has
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", a)
|
||||
await w.step(8)
|
||||
w.sim.ramp_w_s, w.sim.stop_delay_s = ramp, delay
|
||||
w.n0 = len(w.writes())
|
||||
MARK[0] = len(CAP.rec)
|
||||
await w.act("car_phases", to)
|
||||
return w
|
||||
|
||||
|
||||
def t_zero(w):
|
||||
z = [x for x in w.writes("current")[w.n0 // 1:] if x[2] == 0.0]
|
||||
z = [x for x in w.writes("current") if x[2] == 0.0]
|
||||
return z[-1][0] if z else None
|
||||
|
||||
|
||||
def seqw(w):
|
||||
return [(x[1], x[2]) for x in w.writes()[w.n0:]]
|
||||
|
||||
|
||||
print("\n2. W: THE RIG SHAPES")
|
||||
|
||||
|
||||
MARK = [0]
|
||||
|
||||
|
||||
async def t2():
|
||||
w = await ready(1, 10, 3)
|
||||
await w.step(60)
|
||||
return w
|
||||
|
||||
|
||||
w = run(t2())
|
||||
t0 = t_zero(w)
|
||||
ph = w.writes("phases")
|
||||
check(f"T2: 1 ph 10 A at 2300 W -> 3 ph: writes are exactly [0, phases 3, "
|
||||
f"10] ({seqw(w)})", seqw(w) == [("current", 0.0), ("phases", 3),
|
||||
("current", 10.0)])
|
||||
check(f"T2: select with power under 100 W ({ph[0][3]:.0f}) and the setpoint "
|
||||
f"at 0 A, at t0+{ph[0][0] - t0:.0f} s",
|
||||
ph[0][3] < QUIET_W and ph[0][4] == 0.0 and 11 <= ph[0][0] - t0 <= 15)
|
||||
check("T2: ends on 3 phases, 10 A, the car draws",
|
||||
w.sim.phases_allowed == 3 and w.sim.readback_a == 10
|
||||
and w.sim.power_w > 6000)
|
||||
check(f"T13: a clean change logs nothing at INFO or above ({CAP.loud(MARK[0])})",
|
||||
CAP.loud(MARK[0]) == [])
|
||||
|
||||
|
||||
async def t5a():
|
||||
w = await ready(1, 16, 3)
|
||||
await w.step(60)
|
||||
return w
|
||||
|
||||
|
||||
w = run(t5a())
|
||||
t0, ph = t_zero(w), w.writes("phases")
|
||||
check(f"T5a: 1 ph 16 A 3680 W -> 3 ph: select at t0+{ph[0][0] - t0:.0f} s "
|
||||
f"with {ph[0][3]:.0f} W, then 16 A ({seqw(w)})",
|
||||
17 <= ph[0][0] - t0 <= 20 and ph[0][3] < QUIET_W
|
||||
and seqw(w)[-1] == ("current", 16.0) and w.sim.phases_allowed == 3)
|
||||
|
||||
|
||||
async def t5b():
|
||||
w = await ready(3, 6, 1)
|
||||
await w.step(60)
|
||||
return w
|
||||
|
||||
|
||||
w = run(t5b())
|
||||
t0 = t_zero(w)
|
||||
rest = [x for x in w.writes("current") if x[2] == 6.0 and x[0] > t0]
|
||||
check(f"T5b: 3 ph 6 A 4140 W -> 1 ph: still 140 W at t0+20: no select, "
|
||||
f"abandon at t0+{nth(rest)[0] - t0:.0f}, restore to 6 A",
|
||||
not w.writes("phases") and 20 <= nth(rest)[0] - t0 <= 21
|
||||
and w.sim.readback_a == 6 and w.wr.phase_fails == 1)
|
||||
|
||||
|
||||
async def t9(extra=None, steps=70, **kw):
|
||||
w = await ready(3, 16, 1, **kw)
|
||||
await w.step(steps)
|
||||
return w
|
||||
|
||||
|
||||
w9 = run(t9())
|
||||
t0 = t_zero(w9)
|
||||
cw = [x for x in w9.writes("current")]
|
||||
rest = [x for x in cw if x[0] > t0]
|
||||
check(f"T9: 3 ph 16 A -> 1 ph, car still ~7 kW at t0+20: no phases write, "
|
||||
f"abandon at t0+{nth(rest)[0] - t0:.0f}, one restore of 16 A "
|
||||
f"({seqw(w9)})",
|
||||
not w9.writes("phases") and 20 <= nth(rest)[0] - t0 <= 21
|
||||
and seqw(w9) == [("current", 0.0), ("current", 16.0)]
|
||||
and nth(rest)[0] <= t0 + 20 + SETTLE_S + 2)
|
||||
check("T9: phases stay 3, the car draws again, one failed try, not given up, "
|
||||
"no amber row, sequence over",
|
||||
w9.sim.phases_allowed == 3 and w9.sim.power_w > 6000
|
||||
and w9.wr.phase_fails == 1 and not w9.wr.phases_gave_up
|
||||
and "charger_phases" not in w9.rows() and w9.wr.seq is None)
|
||||
check("Expected 3: the next try counts PHASE_GAP_S from the abandon",
|
||||
w9.wr.last_switch is not None
|
||||
and abs(w9.wr.last_switch - (nth(rest)[0] + w9.t - w9.sim.t)) <= 1.5)
|
||||
|
||||
|
||||
async def t10():
|
||||
w = await ready(3, 16, 1)
|
||||
await w.step(10)
|
||||
w.sim.station_a = 10.0
|
||||
await w.step(60)
|
||||
return w
|
||||
|
||||
|
||||
w = run(t10())
|
||||
t0 = t_zero(w)
|
||||
after = [x for x in w.writes("current") if x[0] > t0]
|
||||
check(f"T10/N2: the station limit drops to 10 A during zero: the restore is "
|
||||
f"10 A and nothing above it ({[x[2] for x in after]})",
|
||||
after and after[0][2] == 10.0 and all(x[2] <= 10.0 for x in after)
|
||||
and not w.writes("phases"))
|
||||
|
||||
|
||||
async def t16():
|
||||
w = await ready(1, 10, 3)
|
||||
await w.step(1) # 0 A is written, the car at 2300 W
|
||||
w.sim.freeze_power()
|
||||
await w.step(60)
|
||||
return w
|
||||
|
||||
|
||||
w = run(t16())
|
||||
t0 = t_zero(w)
|
||||
rest = [x for x in w.writes("current") if x[0] > t0]
|
||||
check(f"T16/N5: the power sensor stuck at 2300 W while the car stops: no "
|
||||
f"select, abandon at t0+{nth(rest)[0] - t0:.0f}, restore 10 A",
|
||||
not w.writes("phases") and 20 <= nth(rest)[0] - t0 <= 21
|
||||
and nth(rest)[2] == 10.0 and w.wr.phase_fails == 1)
|
||||
|
||||
|
||||
async def t17(ramp):
|
||||
w = await ready(1, 10, 3, ramp=ramp, delay=1.0)
|
||||
await w.step(1)
|
||||
w.sim.go_unavailable()
|
||||
n = len(w.sim.log)
|
||||
await w.step(28) # t0+2 .. t0+30
|
||||
during = len(w.sim.log) - n
|
||||
w.sim.go_unavailable(False)
|
||||
n1 = len(w.writes())
|
||||
await w.step(3)
|
||||
first = w.writes()[n1:]
|
||||
await w.step(40)
|
||||
return w, during, first
|
||||
|
||||
|
||||
w, during, first = run(t17(50.0))
|
||||
check(f"T17a: back after 30 s at ~800 W: no write while unavailable, no "
|
||||
f"select, the restore on the first available step "
|
||||
f"({[x[1:3] for x in first]})",
|
||||
during == 0 and not w.writes("phases") and w.sim.readback_a == 10
|
||||
and w.wr.phase_fails == 1
|
||||
and [x[1:3] for x in first][:1] == [("current", 10.0)])
|
||||
w, during, first = run(t17(200.0))
|
||||
ph = w.writes("phases")
|
||||
check(f"T17b: back at 0 W: the select at the first available step "
|
||||
f"({first[0][1:3] if first else None}), power {ph[0][3]:.0f} W",
|
||||
during == 0 and first and first[0][1] == "phases"
|
||||
and ph[0][3] < QUIET_W and w.sim.phases_allowed == 3)
|
||||
|
||||
print("\n3. W: TRIES, THE AMBER ROW, THE LOG")
|
||||
|
||||
|
||||
async def t11():
|
||||
w = await ready(3, 16, 1)
|
||||
mark = len(CAP.rec)
|
||||
await w.step(1900)
|
||||
zeros = [x[0] for x in w.writes("current") if x[2] == 0.0]
|
||||
rests = [x[0] for x in w.writes("current") if x[2] == 16.0
|
||||
and x[0] > nth(zeros)]
|
||||
out = dict(zeros=zeros, rests=rests, ph=len(w.writes("phases")),
|
||||
gave=w.wr.phases_gave_up, row=w.rows().get("charger_phases"),
|
||||
loud=CAP.loud(mark), w=w)
|
||||
await w.step(1200)
|
||||
out["more"] = len([x for x in w.writes("current") if x[2] == 0.0])
|
||||
n = len([x for x in w.writes("current") if x[2] == 0.0])
|
||||
await w.act("car_phases", 1) # same wish, a user change
|
||||
await w.act("car_phases", 3)
|
||||
await w.act("car_phases", 1)
|
||||
await w.step(60)
|
||||
out["after_user"] = len([x for x in w.writes("current")
|
||||
if x[2] == 0.0]) - n
|
||||
return out
|
||||
|
||||
|
||||
o = run(t11())
|
||||
z, rs = o["zeros"], o["rests"]
|
||||
check(f"T11: 3 zero writes, 0 phases writes, 3 restores ({len(z)}, {o['ph']},"
|
||||
f" {len(rs)})", len(z) == 3 and o["ph"] == 0 and len(rs) == 3)
|
||||
check("T11: the 2nd and 3rd 0 A come PHASE_GAP_S after the abandon of the "
|
||||
"one before",
|
||||
len(z) == 3 and len(rs) == 3 and all(z[i] - z[i - 1] >= PHASE_GAP_S
|
||||
and z[i] <= rs[i - 1] + PHASE_GAP_S + SETTLE_S + 2
|
||||
for i in (1, 2)))
|
||||
check("T11: after the 3rd the add-on gives up: amber row, no 4th 0 A in "
|
||||
"1200 s", o["gave"] and o["row"] is not None and o["row"]["ok"] is False
|
||||
and o["row"]["warn"] is True and o["more"] == 3)
|
||||
check("T11: a user change after the give-up tries again at once (one 0 A)",
|
||||
o["after_user"] == 1)
|
||||
check(f"T13: one 'kept drawing' line per abandon (3) plus the one "
|
||||
f"CHARGER_PHASES warning, nothing else, no ERROR ({o['loud']})",
|
||||
len(o["loud"]) == 4 and sum("CHARGER_PHASES" in m for m in o["loud"]) == 1
|
||||
and not [1 for lv, _m in CAP.rec if lv >= logging.ERROR])
|
||||
|
||||
|
||||
async def t12():
|
||||
w = await ready(3, 16, 1)
|
||||
await w.step(40) # try 1: abandoned
|
||||
real = w.sim.request_phases
|
||||
w.sim.ramp_w_s = 3000.0
|
||||
w.sim.request_phases = lambda n: False # refused select
|
||||
await w.step(int(PHASE_GAP_S) + 60) # try 2
|
||||
mid = w.wr.phase_fails
|
||||
w.sim.request_phases = real
|
||||
w.sim.ramp_w_s = 200.0
|
||||
await w.step(int(PHASE_GAP_S) + 60) # try 3: abandoned
|
||||
n = len(w.writes("current"))
|
||||
await w.step(1500)
|
||||
return w, mid, len(w.writes("current")) - n
|
||||
|
||||
|
||||
w, mid, extra = run(t12())
|
||||
check(f"T12: abandon, refused select, abandon share one count: 2 after try 2 "
|
||||
f"({mid}), given up after try 3, amber row, no 4th try",
|
||||
mid == 2 and w.wr.phases_gave_up and w.wr.phase_fails == 3
|
||||
and "charger_phases" in w.rows() and extra == 0)
|
||||
|
||||
print("\n4. W: THE OTHER ENDS OF A SEQUENCE, THE ALARM")
|
||||
|
||||
|
||||
async def t18():
|
||||
w = await ready(3, 16, 1)
|
||||
await w.step(5)
|
||||
await w.c.car_shutdown()
|
||||
n = len(w.writes())
|
||||
mark = w.writes()[w.n0:]
|
||||
st = (w.wr.seq, w.wr.phase_fails, w.sim.readback_a)
|
||||
w.make(w.opts)
|
||||
await w.step(60)
|
||||
return w, st, mark, w.writes()[n:]
|
||||
|
||||
|
||||
w, st, mark, later = run(t18())
|
||||
check(f"T18: shutdown at t0+5 with the car drawing: one clamped restore (16 "
|
||||
f"A), no select, sequence over, no failed try ({mark})",
|
||||
[(x[1], x[2]) for x in mark] == [("current", 0.0), ("current", 16.0)]
|
||||
and st == (None, 0, 16.0))
|
||||
ok = True
|
||||
for i, x in enumerate(later):
|
||||
if x[1] == "phases":
|
||||
ok = ok and any(y[1] == "current" and y[2] == 0.0
|
||||
for y in later[:i]) and x[3] < QUIET_W
|
||||
check(f"T18: after the restart no select unless a new 0 A came first and the "
|
||||
f"car was quiet ({[x[1:3] for x in later]})", ok)
|
||||
|
||||
|
||||
async def t19(how):
|
||||
w = await ready(3, 16, 1)
|
||||
await w.step(5)
|
||||
n = len(w.writes())
|
||||
mark = len(CAP.rec)
|
||||
if how == "off":
|
||||
await w.act("car_mode", "off")
|
||||
elif how == "stop":
|
||||
w.c.auto = False
|
||||
else:
|
||||
w.c.o["shadow_mode"] = "on"
|
||||
await w.step(80)
|
||||
return w, w.writes()[n:], CAP.loud(mark)
|
||||
|
||||
|
||||
for how in ("off", "stop", "shadow"):
|
||||
w, after, loud = run(t19(how))
|
||||
check(f"T19: {how} at t0+5 with the car drawing: `_undo` as before: one "
|
||||
f"restore, no select, nothing after it, not a failed try "
|
||||
f"({[x[1:3] for x in after]})",
|
||||
[(x[1], x[2]) for x in after] == [("current", 16.0)]
|
||||
and not w.writes("phases") and w.wr.phase_fails == 0
|
||||
and not [m for m in loud if "drawing" in m.lower()])
|
||||
|
||||
|
||||
async def t20():
|
||||
w = await ready(3, 16, 1)
|
||||
await w.step(5)
|
||||
mark = len(CAP.rec)
|
||||
n = len(w.writes())
|
||||
w.sim.set_current(9)
|
||||
await w.step(80)
|
||||
return w, w.writes()[n:], CAP.loud(mark)
|
||||
|
||||
|
||||
w, after, loud = run(t20())
|
||||
check(f"T20: another writer sets 9 A at t0+5: hold, grey row, no select, no "
|
||||
f"restore by the add-on, no failed try, no abandon line ({after})",
|
||||
not w.writes("phases") and after == [] and w.wr.hold
|
||||
and "charger_other" in w.rows() and w.wr.phase_fails == 0
|
||||
and not [m for m in loud if "drawing" in m.lower()])
|
||||
|
||||
|
||||
async def t21():
|
||||
w = await ready(3, 16, 1)
|
||||
await w.step(5)
|
||||
await w.act("car_phases", 3) # back to what the car has
|
||||
await w.act("car_current", 12)
|
||||
await w.step(80)
|
||||
return w
|
||||
|
||||
|
||||
w = run(t21())
|
||||
bad = [x for x in w.writes("phases") if x[3] >= QUIET_W]
|
||||
check(f"T21: the user changes phases back and the current at t0+5: no select "
|
||||
f"under load, the new current ends up, nothing above the clamp "
|
||||
f"({seqw(w)})",
|
||||
not bad and w.sim.readback_a == 12 and w.sim.phases_allowed == 3
|
||||
and all(x[2] <= 16.0 for x in w.writes("current")) and w.wr.seq is None)
|
||||
|
||||
|
||||
async def t15():
|
||||
w = await ready(3, 16, 1)
|
||||
calls = []
|
||||
real = w.drv.write_current
|
||||
|
||||
async def spy(a):
|
||||
r = await real(a)
|
||||
calls.append((w.sim.t, a, r))
|
||||
return r
|
||||
w.drv.write_current = spy
|
||||
await w.step(19)
|
||||
w.sim.refuse = "error"
|
||||
await w.step(40)
|
||||
mid = (list(calls), w.wr.seq is None and w.wr.fails == 1,
|
||||
bool(w.writes("phases")))
|
||||
w.sim.refuse = None
|
||||
await w.step(int(carmode.RETRY_S) + 10)
|
||||
return w, mid
|
||||
|
||||
|
||||
w, (calls, over, anyph) = run(t15())
|
||||
tries = [c for c in calls if c[1] == 16.0]
|
||||
gaps = [round(b[0] - a[0]) for a, b in zip(tries, tries[1:])]
|
||||
check(f"T15: the restore is refused: tried {len(tries)} times ~5 s apart "
|
||||
f"({gaps}), no select, sequence ends, one failed write counted",
|
||||
len(tries) == MAX_TRIES and all(4 <= g <= 6 for g in gaps) and over
|
||||
and not anyph and not w.writes("phases"))
|
||||
check("T15: after the refusal ends the current is back at 16 A, never a "
|
||||
"select", w.sim.readback_a == 16 and not w.writes("phases"))
|
||||
|
||||
|
||||
# --- T14: the controller level (the EV-15 harness) ------------------------- #
|
||||
def ctl(extra=None, t_sw=600, new=1):
|
||||
tr = []
|
||||
|
||||
def note(plant, c):
|
||||
tr.append((plant.t, c._car_own_pause(c.car_now()), c.car_explains,
|
||||
c.car_writer.phase_done_at, plant.ch.power_w,
|
||||
c.car_writer.phase_fails))
|
||||
|
||||
def reserve(plant, c):
|
||||
plant.soc = 19.0
|
||||
plant.load = lambda t: 3000.0 + plant.ch.power_w
|
||||
|
||||
def switch(plant, c):
|
||||
asyncio.get_event_loop().create_task(
|
||||
c.handle_action("car_phases", value=new))
|
||||
ev = {t: note for t in range(0, 720)}
|
||||
ev[300] = lambda p, c: (reserve(p, c), note(p, c))
|
||||
ev[t_sw] = lambda p, c: (switch(p, c), note(p, c))
|
||||
for t, fn in (extra or {}).items():
|
||||
prev = ev.get(t, note)
|
||||
ev[t] = (lambda p, c, prev=prev, fn=fn: (fn(p, c), prev(p, c)))
|
||||
sim = SimCharger(setpoint_a=16)
|
||||
sim.ramp_w_s, sim.stop_delay_s = 200.0, 1.0
|
||||
r = P.drive(s81.constant(3000.0), dur=720, rating=12000.0, soc=60.0,
|
||||
cap=6050.0, phases=3, user_a=16, setpoint=16, mode="manual",
|
||||
events=ev, sim=sim)
|
||||
return r, tr, P.ids(r, *P.ALARMS)
|
||||
|
||||
|
||||
logging.disable(logging.CRITICAL)
|
||||
r, tr, al = ctl()
|
||||
logging.disable(logging.NOTSET)
|
||||
ab = [x[0] for x in tr if x[0] > 600 and x[5] == 1]
|
||||
a0 = ab[0] if ab else None
|
||||
check(f"T14: the car keeps drawing: abandon at {a0}; the own-pause grace is "
|
||||
f"on before it and off from the abandon step on, phase_done_at stays "
|
||||
f"None", a0 is not None and any(x[1] for x in tr if 602 <= x[0] < a0)
|
||||
and not any(x[1] for x in tr if x[0] >= a0)
|
||||
and all(x[3] is None for x in tr) and not r["sim"].writes("phases"))
|
||||
|
||||
|
||||
def overload(plant, c):
|
||||
plant.load = lambda t: 25000.0 + plant.ch.power_w
|
||||
|
||||
|
||||
logging.disable(logging.CRITICAL)
|
||||
r2, tr2, al2 = ctl(extra={640: overload})
|
||||
r3, tr3, al3 = ctl(extra={640: overload}, t_sw=900) # no phase change
|
||||
logging.disable(logging.NOTSET)
|
||||
check(f"T14: a house overload after the abandon alarms, as with no car "
|
||||
f"change ({[t for t, _ in al2]} vs {[t for t, _ in al3]}), and the car "
|
||||
f"does not explain it",
|
||||
bool(al2) and bool(al3) and al2[0][0] == al3[0][0]
|
||||
and not any(x[2] for x in tr2 if x[0] >= 642))
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n5. W: THE DIGESTS OF THE QUIET SHAPES, PINNED FROM 4eba2d9")
|
||||
# =========================================================================== #
|
||||
|
||||
|
||||
async def d_story(lag=0.0, race=False):
|
||||
w = World(setpoint=10, phases=1)
|
||||
w.sim.lag_s = lag
|
||||
await w.step(8)
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", 10)
|
||||
await w.step(5)
|
||||
await w.act("car_phases", 3)
|
||||
await (w.step_race(60) if race else w.step(60))
|
||||
return w
|
||||
|
||||
|
||||
async def d_gap():
|
||||
w = await d_story()
|
||||
await w.act("car_phases", 1)
|
||||
await w.step(620)
|
||||
return w
|
||||
|
||||
|
||||
async def d_zero_refused():
|
||||
w = World(setpoint=10, phases=1)
|
||||
await w.step(8)
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", 10)
|
||||
await w.step(3)
|
||||
w.sim.refuse = "ignore"
|
||||
await w.act("car_phases", 3)
|
||||
await w.step(80)
|
||||
return w
|
||||
|
||||
|
||||
async def d_m2():
|
||||
w = World(setpoint=10, phases=1)
|
||||
await w.step(8)
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", 10)
|
||||
await w.step(5)
|
||||
sim = w.sim
|
||||
|
||||
def deaf(n):
|
||||
sim.log.append((sim.t, "phases", n, sim.power_w, sim.setpoint_a))
|
||||
return True
|
||||
sim.request_phases = deaf
|
||||
await w.act("car_phases", 3)
|
||||
await w.step(3700)
|
||||
return w
|
||||
|
||||
|
||||
async def d_l4():
|
||||
w = World(setpoint=10, phases=1)
|
||||
await w.step(8)
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", 10)
|
||||
await w.step(5)
|
||||
sim = w.sim
|
||||
|
||||
def slow(n):
|
||||
sim.log.append((sim.t, "phases", n, sim.power_w, sim.setpoint_a))
|
||||
sim._pending.append((sim.t + 12.0, "phases", n))
|
||||
return True
|
||||
sim.request_phases = slow
|
||||
await w.act("car_phases", 3)
|
||||
await w.step(60)
|
||||
return w
|
||||
|
||||
|
||||
async def d_mid(kind):
|
||||
"""The slow-stop car (ramp 50 W/s, C held 40 s) cut short before 20 s."""
|
||||
w = World(dict(CAR, shadow_mode="auto"), setpoint=10, phases=1)
|
||||
w.sim.ramp_w_s, w.sim.stop_delay_s = 50.0, 40.0
|
||||
await w.step(60)
|
||||
await w.act("car_mode", "manual")
|
||||
await w.act("car_current", 10)
|
||||
await w.step(3)
|
||||
await w.act("car_phases", 3)
|
||||
await w.step(3)
|
||||
if kind == "off":
|
||||
await w.act("car_mode", "off")
|
||||
elif kind == "shadow":
|
||||
w.c.o["shadow_mode"] = "on"
|
||||
elif kind == "stop":
|
||||
await w.c.handle_action("auto_toggle")
|
||||
elif kind == "shutdown":
|
||||
await w.c.car_shutdown()
|
||||
elif kind == "other":
|
||||
w.sim.set_current(9)
|
||||
await w.step(80)
|
||||
return w
|
||||
|
||||
|
||||
async def d_off():
|
||||
w = World(setpoint=10, phases=1)
|
||||
await w.step(5)
|
||||
await w.act("car_phases", 3)
|
||||
await w.step(60)
|
||||
return w
|
||||
|
||||
|
||||
def digest(w):
|
||||
s = repr([(x[0], x[1], x[2]) for x in w.sim.log])
|
||||
return hashlib.sha256(s.encode()).hexdigest()[:12]
|
||||
|
||||
|
||||
SHAPES = [("phase_story", lambda: d_story()),
|
||||
("phase_story lag 3", lambda: d_story(lag=3.0)),
|
||||
("m1 race", lambda: d_story(race=True)),
|
||||
("phase_gap", d_gap), ("zero_refused", d_zero_refused),
|
||||
("m2_refused", d_m2), ("l4_late", d_l4), ("phases_in_off", d_off)] \
|
||||
+ [(f"mid {k}", (lambda k=k: d_mid(k)))
|
||||
for k in ("off", "shadow", "stop", "shutdown", "other")]
|
||||
# Pinned from 4eba2d9 (python3 -B on the base tree). Two shapes CHANGE by
|
||||
# design, because the base selected under load in them: `phase_gap` (second
|
||||
# switch: base selected at t0+1 with 3900 W, now t0+3 under 100 W, the same
|
||||
# writes otherwise) and `mid shutdown` (the restarted sequence met a car at
|
||||
# 1250 W: base selected at the timeout, now abandons and restores). Their pins
|
||||
# are the new digests; the facts are asserted below.
|
||||
PINS = {"phase_story": "9e7d818e1304", "phase_story lag 3": "13bba7ca8427",
|
||||
"m1 race": "0f845c466111", "phase_gap": "467fad0b4ebe",
|
||||
"zero_refused": "041e96466f8e", "m2_refused": "5ea1b28f8c3a",
|
||||
"l4_late": "50248d297e1d", "phases_in_off": "4f53cda18c2b",
|
||||
"mid off": "b62df7ce65eb", "mid shadow": "b62df7ce65eb",
|
||||
"mid stop": "b62df7ce65eb", "mid shutdown": "5cae419f3e9f",
|
||||
"mid other": "0f43ad8a061a"}
|
||||
got = {name: digest(run(fn())) for name, fn in SHAPES}
|
||||
_g = run(d_gap())
|
||||
_p = _g.writes("phases")
|
||||
check("T22: the changed shapes are changed only where base selected under "
|
||||
f"load: phase_gap's 2nd select is under 100 W ({_p[1][3]:.0f} W)",
|
||||
len(_p) == 2 and _p[1][3] < QUIET_W)
|
||||
check("T22: digests: " + ", ".join(f"{k}={v}" for k, v in got.items()),
|
||||
all(PINS.get(k) == v for k, v in got.items()) and set(PINS) == set(got))
|
||||
|
||||
# =========================================================================== #
|
||||
print("\n6. DOCS (T25)")
|
||||
# =========================================================================== #
|
||||
doc = open(os.path.join(HERE, "DECISIONS", "EV-04-manual-mode.md"),
|
||||
encoding="utf-8").read()
|
||||
phase = doc.split("## The phase sequence")[1].split("\n## ")[0]
|
||||
flat = " ".join(phase.split())
|
||||
check("T25: DECISIONS says: under 100 W with a power reading, mode3 leaving C "
|
||||
"only without one, still drawing at 20 s gives the current back and "
|
||||
"counts as a failed try",
|
||||
"under 100 W" in flat and "no power reading" in flat
|
||||
and "failed try" in flat and "current comes back" in flat
|
||||
and "or mode3 leaves C (20 s at most)" not in flat)
|
||||
src = carmode.__doc__
|
||||
check("T25: the module docstring matches (power reading first, then mode3, "
|
||||
"then the failed try)",
|
||||
"without a power reading" in " ".join(src.split())
|
||||
and "failed" in src and "or mode3 leaves C" not in src)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print(f"FAIL: {len(fails)} check(s)")
|
||||
for f in fails:
|
||||
print(" -", f)
|
||||
sys.exit(1)
|
||||
print("ok: EV-28")
|
||||
@@ -2,14 +2,6 @@
|
||||
"""EV-03: a model of an Alfen car charger behind Home Assistant, for the unit
|
||||
tests and, later, for TEST-23.
|
||||
|
||||
EV-04 ADDS THE WRITE SIDE: `request_current()` and `request_phases()` are what
|
||||
the add-on's writes reach. The new state is taken after `lag_s` seconds of
|
||||
model time (the read-back lag), the power RAMPS to it, and `refuse` makes the
|
||||
charger ignore a write ("ignore": Home Assistant says yes, the charger does not
|
||||
change) or Home Assistant refuse it ("error"). `log` records every write with
|
||||
the model's clock and the power and setpoint at that moment, so a test can
|
||||
prove the safe phase sequence (0 A first, under 100 W before the phases move).
|
||||
|
||||
WHERE IT LIVES, AND WHY. The rig's hardware sims (`hwsim.py`, `plantsim.py`) are
|
||||
in the infra repo admin/goodwe under `sim/`, pinned by `.gitea/infra-pin`; there
|
||||
is no `sim/` in this repository. This card may write only to this repository, so
|
||||
@@ -59,18 +51,6 @@ class SimCharger:
|
||||
self.unavailable = False
|
||||
self.login_on = True
|
||||
self.error = "0: No Error"
|
||||
# EV-04: the write side
|
||||
self.t = 0.0 # model seconds
|
||||
self.lag_s = 0.0 # a write shows in the read-back this late
|
||||
self.refuse = None # None | "ignore" | "error"
|
||||
self._snap = None # `freeze()`: the readings stop moving
|
||||
self._frozen_w = None # `freeze_power()`: only the power does
|
||||
self.no_energy = False # a charger with no energy entity
|
||||
self.ramp_w_s = RAMP_W_S # how fast the power follows its target
|
||||
self.stop_delay_s = 0.0 # mode3 stays C this long after 0 A
|
||||
self._c_hold = 0.0
|
||||
self.log = [] # (t, what, value, power_w, setpoint_a)
|
||||
self._pending = []
|
||||
|
||||
# -- the world acts on it -------------------------------------------------
|
||||
def plug_in(self, car_phases=3):
|
||||
@@ -96,44 +76,6 @@ class SimCharger:
|
||||
"""mode3 E or F: the charger's own error states."""
|
||||
self.state, self.power_w = letter, 0.0
|
||||
|
||||
# -- what the add-on's writes reach (EV-04) ----------------------------------
|
||||
def request_current(self, a):
|
||||
"""`number.set_value` on the current. False: Home Assistant refused it
|
||||
(out of the entity's 0-40 A range, or `refuse == "error"`)."""
|
||||
a = float(a)
|
||||
if a != a or a < 0.0 or a > 40.0 or self.refuse == "error":
|
||||
return False
|
||||
self.log.append((self.t, "current", a, self.power_w, self.setpoint_a))
|
||||
if self.refuse == "ignore":
|
||||
return True
|
||||
self._later("current", a)
|
||||
return True
|
||||
|
||||
def request_phases(self, n):
|
||||
"""`select.select_option` on the installation's allowed phases."""
|
||||
if self.refuse == "error" or n not in (1, 3):
|
||||
return False
|
||||
self.log.append((self.t, "phases", n, self.power_w, self.setpoint_a))
|
||||
if self.refuse == "ignore":
|
||||
return True
|
||||
self._later("phases", n)
|
||||
return True
|
||||
|
||||
def _later(self, what, v):
|
||||
if self.lag_s <= 0:
|
||||
self._apply(what, v)
|
||||
else:
|
||||
self._pending.append((self.t + self.lag_s, what, v))
|
||||
|
||||
def _apply(self, what, v):
|
||||
if what == "current":
|
||||
self.setpoint_a = self.readback_a = max(0.0, min(v, self.station_a))
|
||||
else:
|
||||
self.phases_allowed = 3 if v == 3 else 1
|
||||
|
||||
def writes(self, what=None):
|
||||
return [x for x in self.log if what in (None, x[1])]
|
||||
|
||||
def go_unavailable(self, on=True):
|
||||
self.unavailable = bool(on)
|
||||
|
||||
@@ -152,22 +94,13 @@ class SimCharger:
|
||||
|
||||
def tick(self, seconds=1.0):
|
||||
for _ in range(int(max(1, round(seconds)))):
|
||||
self.t += 1.0
|
||||
for p in [x for x in self._pending if x[0] <= self.t]:
|
||||
self._pending.remove(p)
|
||||
self._apply(p[1], p[2])
|
||||
if self.state in ("E", "F"): # a fault: nothing flows, it stays
|
||||
self.power_w = 0.0
|
||||
continue
|
||||
if self.state != "A":
|
||||
if self.target_w() > 0:
|
||||
self.state, self._c_hold = "C", 0.0
|
||||
elif self.state == "C" and self._c_hold < self.stop_delay_s:
|
||||
self._c_hold += 1.0 # the car has not let go yet
|
||||
else:
|
||||
self.state = "B"
|
||||
self.state = "C" if self.target_w() > 0 else "B"
|
||||
tgt = self.target_w()
|
||||
step = self.ramp_w_s
|
||||
step = RAMP_W_S
|
||||
if self.power_w < tgt:
|
||||
self.power_w = min(tgt, self.power_w + step)
|
||||
else:
|
||||
@@ -180,20 +113,7 @@ class SimCharger:
|
||||
if self.phases_used and self.power_w else 0.0)
|
||||
return [per if i < self.phases_used else 0.0 for i in range(3)]
|
||||
|
||||
def freeze(self, on=True):
|
||||
"""A stuck sensor: Home Assistant goes on serving the readings of this
|
||||
moment, whatever the charger does after it."""
|
||||
self._snap = self._build() if on else None
|
||||
|
||||
def freeze_power(self, on=True):
|
||||
"""Only the power sensor sticks, at what it reads now; the energy meter
|
||||
and the rest go on telling the truth."""
|
||||
self._frozen_w = self.power_w if on else None
|
||||
|
||||
def states(self) -> dict:
|
||||
return self._snap if self._snap is not None else self._build()
|
||||
|
||||
def _build(self) -> dict:
|
||||
x = self.x
|
||||
bad = "unavailable" if self.unavailable else None
|
||||
|
||||
@@ -214,8 +134,7 @@ class SimCharger:
|
||||
{"A": "Available", "B": "EV Connected",
|
||||
"C": "Charging Normal"}.get(self.state, "Error")),
|
||||
st(f"sensor.{x}_active_power_total_socket_1",
|
||||
f"{self.power_w if self._frozen_w is None else self._frozen_w:.0f}",
|
||||
"W"),
|
||||
f"{self.power_w:.0f}", "W"),
|
||||
st(f"sensor.{x}_meter_reading_socket_1", f"{self.kwh:.2f}",
|
||||
"kWh"),
|
||||
st(f"sensor.{x}_current_l1_socket_1", f"{amps[0]:.1f}", "A"),
|
||||
@@ -234,10 +153,7 @@ class SimCharger:
|
||||
"state": bad or ("on" if self.login_on else "off"),
|
||||
"attributes": {"device_class": "connectivity"}}),
|
||||
]
|
||||
out = dict(rows)
|
||||
if self.no_energy:
|
||||
out.pop(f"sensor.{x}_meter_reading_socket_1", None)
|
||||
return out
|
||||
return dict(rows)
|
||||
|
||||
|
||||
class FakeHa:
|
||||
@@ -279,20 +195,10 @@ class FakeHa:
|
||||
|
||||
async def set_number(self, entity_id, value):
|
||||
self.sets.append((entity_id, value))
|
||||
c = self.charger
|
||||
if c is not None and entity_id == \
|
||||
f"number.{c.x}_power_connector_max_current_socket_1":
|
||||
return c.request_current(value)
|
||||
return True
|
||||
|
||||
async def call(self, domain, service, data=None):
|
||||
self.calls.append((domain, service, data))
|
||||
c = self.charger
|
||||
if c is not None and domain == "select" and service == "select_option" \
|
||||
and (data or {}).get("entity_id") == \
|
||||
f"select.{c.x}_installation_max_allowed_phases":
|
||||
return c.request_phases(
|
||||
3 if "3" in str((data or {}).get("option")) else 1)
|
||||
return True
|
||||
|
||||
def charger_writes(self):
|
||||
@@ -345,22 +251,6 @@ def _selftest():
|
||||
assert c.state == "B" and c.power_w == 0 # under 6 A: paused
|
||||
c.set_current(10); c.car_full(); c.tick(5)
|
||||
assert c.state == "B" and c.power_w == 0 and c.readback_a == 10
|
||||
# EV-04: writes, the read-back lag, a refusal
|
||||
w = SimCharger(); w.plug_in(); w.tick(1)
|
||||
assert w.request_current(12) and w.setpoint_a == 12
|
||||
assert not w.request_current(41) and not w.request_current(-1)
|
||||
w.lag_s = 3.0
|
||||
assert w.request_current(8) and w.readback_a == 12
|
||||
w.tick(2); assert w.readback_a == 12
|
||||
w.tick(1); assert w.readback_a == 8
|
||||
w.refuse = "ignore"
|
||||
assert w.request_current(6) and w.readback_a == 8
|
||||
w.refuse = "error"
|
||||
assert not w.request_current(6) and not w.request_phases(3)
|
||||
w.refuse = None; w.lag_s = 0.0
|
||||
assert w.request_phases(3) and w.phases_allowed == 3
|
||||
assert [x[1] for x in w.writes()] == ["current", "current", "current",
|
||||
"phases"], w.writes()
|
||||
c.go_unavailable()
|
||||
assert c.states()[f"sensor.wallbox_active_power_total_socket_1"]["state"] \
|
||||
== "unavailable"
|
||||
|
||||
@@ -1,189 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""EV-04: the real Controller on the SAFETY-81 plant, plus a car charger.
|
||||
|
||||
python3 tools/ev04_peak.py # a few runs and what they raised
|
||||
|
||||
A 1 s cycle, a 3500 W cap, one battery switched Off (so only the peak guard
|
||||
makes it give, at most `rating` W), a P1 meter that publishes 0.3 s before each
|
||||
cycle, and `chargersim.SimCharger` behind the same Home Assistant: its power
|
||||
is part of the load the meter sees, and the add-on reads and writes it through
|
||||
the real driver. `events` is `{second: fn(plant, controller)}`, run before that
|
||||
cycle: unplug, freeze the reading, step the house, change the user's current.
|
||||
|
||||
Used by test_ev04.py (sections 9 to 11) and, later, by the rig test."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from datetime import timedelta
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import opt11_identity as rig # noqa: E402
|
||||
import main_files # noqa: E402
|
||||
import safety81_sim as s81 # noqa: E402
|
||||
from app import packmode # noqa: E402
|
||||
from app.main import Controller # noqa: E402
|
||||
from app.p1 import make_sample, split_signed # noqa: E402
|
||||
from app.store import unit_key # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
|
||||
SET = "number.wallbox_power_connector_max_current_socket_1"
|
||||
PHASES = "select.wallbox_installation_max_allowed_phases"
|
||||
ALARMS = ("goodwe_peak_saturated", "goodwe_peak_soc_floor")
|
||||
OVER = "goodwe_car_over"
|
||||
|
||||
|
||||
class CarPlant(s81._Plant):
|
||||
"""The SAFETY-81 plant with a charger on the same meter: the grid sees the
|
||||
house, the car and what the battery does."""
|
||||
|
||||
def __init__(self, house, rating, soc, charger):
|
||||
super().__init__(lambda at: house(at) + charger.power_w, rating, soc)
|
||||
self.ch = charger
|
||||
|
||||
async def state(self, entity_id):
|
||||
return self.ch.states().get(entity_id)
|
||||
|
||||
async def set_number(self, e, v):
|
||||
if e == SET:
|
||||
return self.ch.request_current(float(v))
|
||||
return await super().set_number(e, v)
|
||||
|
||||
async def call(self, domain, service, data=None):
|
||||
if domain == "select" and service == "select_option":
|
||||
n = 3 if "3" in str((data or {}).get("option")) else 1
|
||||
return self.ch.request_phases(n)
|
||||
return await super().call(domain, service, data)
|
||||
|
||||
|
||||
class CarPlantN(CarPlant):
|
||||
"""EV-10b: N batteries, each its own setpoint, power and SoC (`soc` is a
|
||||
dict {"a": %, "b": %}); `rating` is per battery. The grid sees them all."""
|
||||
|
||||
def __init__(self, house, rating, soc, charger):
|
||||
super().__init__(house, rating, 0.0, charger)
|
||||
self.socs = dict(soc)
|
||||
self.hists = {u: [(-1e9, 0.0)] for u in self.socs}
|
||||
|
||||
def batt_of(self, u, at):
|
||||
w = 0.0
|
||||
for when, v in self.hists[u]:
|
||||
if when <= at:
|
||||
w = v
|
||||
return max(-self.rating, min(self.rating, float(round(w))))
|
||||
|
||||
def batt(self, at):
|
||||
return sum(self.batt_of(u, at) for u in self.socs)
|
||||
|
||||
async def number(self, e, invert=False):
|
||||
for u in self.socs:
|
||||
if e == "sensor.soc_" + u:
|
||||
return self.socs[u]
|
||||
if e == "sensor.batt_" + u:
|
||||
return self.batt_of(u, self.t)
|
||||
return await super().number(e, invert)
|
||||
|
||||
async def set_number(self, e, v):
|
||||
if e.startswith("number.sp_"):
|
||||
self.hists[e[-1]].append((self.t + s81.RESPONSE_S, float(v)))
|
||||
return True
|
||||
return await super().set_number(e, v)
|
||||
|
||||
|
||||
def drive(house, *, dur=300.0, rating=2000.0, soc=60.0, cap=3500.0, margin=50,
|
||||
opts=None, plug=True, setpoint=16, phases=3, mode="manual",
|
||||
user_a=16, events=None, sim=None, store=None, n=1, plant_cls=None,
|
||||
dev_w=5000.0):
|
||||
"""Run it. Returns a namespace-like dict: plant, controller, charger, the
|
||||
notification ids raised with their second, and the controller's rows."""
|
||||
sim = sim or SimCharger(setpoint_a=setpoint)
|
||||
if plug:
|
||||
sim.plug_in()
|
||||
sim.phases_allowed = phases
|
||||
o = rig._options(n, dict({
|
||||
"meter_source": "ha_signed", "p1_net_entity": "sensor.net",
|
||||
"meter_phases": 1, "peak_cap_w": cap, "peak_margin_w": margin,
|
||||
"battery_modes_enabled": True, "max_w": rating,
|
||||
"ev_charger": "alfen_ha", "ev_max_a": 16, "ev_phases": "auto",
|
||||
"ev_current_entity": SET}, **(opts or {})))
|
||||
store = store or rig._Store()
|
||||
for u in "ab"[:n]:
|
||||
store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = False
|
||||
store.data[packmode.USE_KEY] = False
|
||||
db = os.path.join(tempfile.mkdtemp(prefix="ev4-"), "tariff.db")
|
||||
out = {}
|
||||
|
||||
async def go():
|
||||
plant = (plant_cls or CarPlant)(house, rating, soc, sim)
|
||||
c = Controller(o, plant, store, rig._Pub(), stop=asyncio.Event(),
|
||||
peak_db_path=db)
|
||||
for i in c.inverters:
|
||||
i.dev_min, i.dev_max = -dev_w, dev_w
|
||||
c.auto = True
|
||||
clock = [0.0]
|
||||
c.car_now = lambda: clock[0]
|
||||
if hasattr(c.charger, "_sleep"):
|
||||
async def sleep(s):
|
||||
sim.tick(s)
|
||||
clock[0] += s
|
||||
c.charger._sleep = sleep
|
||||
c.charger._clock = lambda: clock[0]
|
||||
real_dt = main_files.live.datetime
|
||||
|
||||
class _DT(real_dt):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return rig.BASE + timedelta(seconds=clock[0])
|
||||
main_files.live.datetime = _DT
|
||||
c.car_mode, c.car_n, c.car_a = mode, phases, float(user_a)
|
||||
snaps = []
|
||||
try:
|
||||
t = 0.0
|
||||
while t < dur:
|
||||
plant.t = clock[0] = t
|
||||
fn = events_in.get(int(t)) if t == int(t) else None
|
||||
if fn is not None:
|
||||
fn(plant, c)
|
||||
sim.tick(1.0)
|
||||
ts = t - s81.SAMPLE_LEAD_S
|
||||
plant.meter = plant.grid(ts)
|
||||
imp, exp = split_signed(plant.meter)
|
||||
c.p1.submit(make_sample(
|
||||
"ha_signed", imp, exp, phases=1,
|
||||
ingest_ts=rig.BASE + timedelta(seconds=ts),
|
||||
ingest_mono=time.monotonic()))
|
||||
await c.read_inputs(now_mono=t)
|
||||
await c.cycle()
|
||||
await c.car_settle()
|
||||
snaps.append((t, c.car_explains, c.car_over,
|
||||
(c.peak_guard.engaged if c.peak_guard else None),
|
||||
plant.batt(t), sim.power_w))
|
||||
t += s81.TICK
|
||||
finally:
|
||||
main_files.live.datetime = real_dt
|
||||
raised = [(at, nid) for at, nid in plant.notes]
|
||||
out.update(plant=plant, c=c, sim=sim, raised=raised, snaps=snaps,
|
||||
store=store)
|
||||
events_in = events or {}
|
||||
asyncio.run(go())
|
||||
return out
|
||||
|
||||
|
||||
def ids(out, *wanted):
|
||||
return [(t, n) for t, n in out["raised"] if n in wanted]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.disable(logging.CRITICAL)
|
||||
for name, kw in (
|
||||
("car 11 kW, house 1.1 kW, Manual",
|
||||
dict(house=s81.constant(1100.0))),
|
||||
("same, Off", dict(house=s81.constant(1100.0), mode="off"))):
|
||||
r = drive(**kw)
|
||||
print(f"{name:34s} alarms {ids(r, *ALARMS)} "
|
||||
f"car notice {ids(r, OVER)}")
|
||||
@@ -1,223 +0,0 @@
|
||||
"""EV-18: the real Controller across one quarter edge `E`, N=2, both units at
|
||||
the peak reserve and the car charging (`ev04_peak.drive`). Used by test_ev18.py.
|
||||
|
||||
The run starts `E` s before an edge (rig.BASE is moved back for the run), with
|
||||
a light house so the first quarter does not raise the month's peak (the aim
|
||||
stays `AIM`). At `E - 120` the house steps to the shape, so the guard first
|
||||
wants power at the edge, as on the rig (EV-15 F-A). `force` makes a unit give
|
||||
what the loop gives below the reserve whatever it is told; `lost` drops its
|
||||
reading for some seconds (the grid still sees it). The trace is one dict per
|
||||
cycle, taken after it.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from datetime import timedelta
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import ev04_peak as P # noqa: E402
|
||||
import opt11_identity as rig # noqa: E402
|
||||
import safety81_sim as s81 # noqa: E402
|
||||
from app import peakguard # noqa: E402
|
||||
|
||||
E = 150 # the edge, in run seconds
|
||||
AIM = 13600.0
|
||||
MARGIN = 50.0
|
||||
PRE_W = 5000.0 # the first quarter's house: under the cap
|
||||
FLOOR = "goodwe_peak_soc_floor"
|
||||
OPTS = {"peak_soc_floor": 20, "inverters": [
|
||||
{"name": "inverter-a", "setpoint_entity": "number.sp_a",
|
||||
"soc_entity": "sensor.soc_a", "batt_entity": "sensor.batt_a",
|
||||
"max_w": 5000, "bms_soc_floor": 10},
|
||||
{"name": "inverter-b", "setpoint_entity": "number.sp_b",
|
||||
"soc_entity": "sensor.soc_b", "batt_entity": "sensor.batt_b",
|
||||
"max_w": 4600, "bms_soc_floor": 10}]}
|
||||
|
||||
|
||||
class _Errors(logging.Handler):
|
||||
def __init__(self):
|
||||
super().__init__(logging.ERROR)
|
||||
self.rec = []
|
||||
|
||||
def emit(self, r):
|
||||
self.rec.append(r.getMessage())
|
||||
|
||||
|
||||
ERR = _Errors()
|
||||
_lg = logging.getLogger("goodwe")
|
||||
_lg.addHandler(ERR)
|
||||
_lg.setLevel(logging.ERROR)
|
||||
_lg.propagate = False
|
||||
|
||||
|
||||
class Plant(P.CarPlantN):
|
||||
force = {}
|
||||
lost = {}
|
||||
|
||||
def batt_of(self, u, at):
|
||||
f = self.force.get(u)
|
||||
if f is not None:
|
||||
return float(f(at))
|
||||
return super().batt_of(u, at)
|
||||
|
||||
async def number(self, e, invert=False):
|
||||
for u, secs in self.lost.items():
|
||||
if e == "sensor.batt_" + u and int(self.t) in secs:
|
||||
return None
|
||||
return await super().number(e, invert)
|
||||
|
||||
|
||||
def shape(after, before=PRE_W, at=None):
|
||||
"""The house: `before` until `at` (E - 120), then `after` (W or fn(t))."""
|
||||
at = E - 120 if at is None else at
|
||||
return lambda t: before if t < at else (after(t) if callable(after)
|
||||
else after)
|
||||
|
||||
|
||||
def run(house, *, a=None, b=None, lost=None, car_a=6, phases=1, aim=AIM,
|
||||
mode="manual", dur=None, extra=None, sim=None, soc=None, plug=True,
|
||||
x=1, mono_x=None, explain_off=False, latch_off=False,
|
||||
cover=True):
|
||||
"""One run; returns (run, trace). `x`: fake seconds per cycle (wall and
|
||||
monotonic both; `mono_x` sets the monotonic rate apart). `explain_off`:
|
||||
the car never explains, `latch_off`: no contradiction latch (both for the
|
||||
control-identity check). `cover`: the option `ev_batt_cover`."""
|
||||
force = {}
|
||||
if a is not None:
|
||||
force["a"] = a
|
||||
if b is not None:
|
||||
force["b"] = b
|
||||
cls = type("Plant", (Plant,), {"force": force, "lost": lost or {}})
|
||||
tr = []
|
||||
n_err = [len(ERR.rec)]
|
||||
dur = E + 900 if dur is None else dur
|
||||
|
||||
def hook(plant, c):
|
||||
orig = c.car_settle
|
||||
if explain_off:
|
||||
c._car_explains_alarm = lambda *a_, **k_: False
|
||||
if latch_off:
|
||||
c._car_contradicted = lambda *a_, **k_: False
|
||||
if not cover:
|
||||
c.o["ev_batt_cover"] = False
|
||||
if mono_x is not None and mono_x != x:
|
||||
c.car_now = (lambda f=c.car_now: f() * mono_x / x)
|
||||
|
||||
async def settle():
|
||||
await orig()
|
||||
g = c.peak_guard
|
||||
red = []
|
||||
if plant.t >= E - 130:
|
||||
red = [r_["id"] for r_ in c.checks()
|
||||
if r_["ok"] is False and not r_["warn"]
|
||||
and r_["id"] == "peak_guard"]
|
||||
errs = [m for m in ERR.rec[n_err[0]:]
|
||||
if "may not draw the battery lower" in m]
|
||||
n_err[0] = len(ERR.rec)
|
||||
cl = peakguard.claim(g) if g is not None else None
|
||||
tr.append({
|
||||
"t": plant.t, "explains": c.car_explains,
|
||||
"lim": bool(g is not None and (g.floor_limited
|
||||
or g.saturated)),
|
||||
"within_aim": bool(g is not None and g.within_aim),
|
||||
"wants": bool(g is not None and g.engaged
|
||||
and (g.wanted_w or 0.0) > 0.0),
|
||||
"alarm": c._peak_floor_limited, "red": red, "err": errs,
|
||||
"w": c.car_alarm_w(), "batt": c.site_batt_w,
|
||||
"key": c._carq["key"],
|
||||
"block": (c._peak_proj_real.block_start
|
||||
if c._peak_proj_real is not None else None),
|
||||
"floor_w": g.floor_w if g is not None else None,
|
||||
"lo": getattr(cl, "lo", None),
|
||||
"sp": tuple(i.last_write for i in c.inverters)})
|
||||
c.car_settle = settle
|
||||
|
||||
ev = {0: hook}
|
||||
for t, fn in (extra or {}).items():
|
||||
if t == 0:
|
||||
ev[0] = (lambda p, c, fn=fn: (hook(p, c), fn(p, c)))
|
||||
else:
|
||||
ev[t] = fn
|
||||
socs = soc or {"a": 19.0, "b": 19.0}
|
||||
s = sim
|
||||
if s is None:
|
||||
from chargersim import SimCharger
|
||||
s = SimCharger(setpoint_a=car_a)
|
||||
if x != 1:
|
||||
tick = s.tick
|
||||
s.tick = lambda secs=1.0: tick(secs * x)
|
||||
base, step = rig.BASE, s81.TICK
|
||||
rig.BASE, s81.TICK = base - timedelta(seconds=E), float(x)
|
||||
try:
|
||||
r = P.drive(house, dur=dur, rating=5000.0, soc=socs,
|
||||
cap=aim + MARGIN, phases=phases, n=2, plant_cls=cls,
|
||||
opts=OPTS, dev_w=5000.0, setpoint=car_a, user_a=car_a,
|
||||
mode=mode, events=ev, sim=s, plug=plug)
|
||||
finally:
|
||||
rig.BASE, s81.TICK = base, step
|
||||
return r, tr
|
||||
|
||||
|
||||
def alarms(r):
|
||||
"""Seconds of each goodwe_peak_soc_floor notification."""
|
||||
return [t for t, n in r["raised"] if n == FLOOR]
|
||||
|
||||
|
||||
def window(tr, t0, t1):
|
||||
return [x for x in tr if t0 <= x["t"] <= t1]
|
||||
|
||||
|
||||
def edges(tr):
|
||||
"""Seconds at which the floor alarm goes False -> True."""
|
||||
out, was = [], False
|
||||
for x in tr:
|
||||
if x["alarm"] and not was:
|
||||
out.append(x["t"])
|
||||
was = x["alarm"]
|
||||
return out
|
||||
|
||||
|
||||
def red_secs(tr, t0=None, t1=None):
|
||||
t0 = E - 120 if t0 is None else t0
|
||||
t1 = E + 900 if t1 is None else t1
|
||||
return [x["t"] for x in window(tr, t0, t1) if x["red"]]
|
||||
|
||||
|
||||
def errors(tr):
|
||||
return [x["t"] for x in tr if x["err"]]
|
||||
|
||||
|
||||
def commands(r, tr):
|
||||
"""A digest of every command: the units' setpoints, the charger's writes,
|
||||
and the guard's floor and claim per cycle (N4)."""
|
||||
h = hashlib.sha256()
|
||||
for u in sorted(r["plant"].hists):
|
||||
h.update(repr((u, r["plant"].hists[u])).encode())
|
||||
h.update(repr(r["sim"].writes()).encode())
|
||||
h.update(repr([(x["t"], x["floor_w"], x["lo"], x["sp"])
|
||||
for x in tr]).encode())
|
||||
return h.hexdigest()[:16]
|
||||
|
||||
|
||||
def energy_gap(at, secs=1):
|
||||
"""The charger's energy entity is missing (unknown) for `secs` from `at`."""
|
||||
def on(p, c):
|
||||
p.ch.no_energy = True
|
||||
|
||||
def off(p, c):
|
||||
p.ch.no_energy = False
|
||||
return {at: on, at + secs: off}
|
||||
|
||||
|
||||
def restart(c):
|
||||
"""A restart as the car side sees it: a fresh `car_init` and an empty
|
||||
corroboration history, and no floor alarm standing."""
|
||||
mode, n, a = c.car_mode, c.car_n, c.car_a
|
||||
c.car_init(c.o, c.store)
|
||||
c.car_mode, c.car_n, c.car_a = mode, n, a
|
||||
c.car._hist.clear()
|
||||
c._peak_floor_limited = False
|
||||
@@ -1,779 +0,0 @@
|
||||
"""EV-19: the real Controller, N=2, when the batteries first reach the peak
|
||||
reserve `R` early in a Manual car session (EV-15 F-B). Used by test_ev19.py.
|
||||
|
||||
python3 tools/ev19_reserve.py # the T1 grid, one row per cell
|
||||
|
||||
The units stand at 21 % and give `bw` W (`force`) until `R`, where both read
|
||||
19 %; after `R` they follow the trajectory `traj`. The house is set so that
|
||||
house + car with the batteries at 0 W lands at aim + `over` W (F-B: +520 W,
|
||||
less than the 1 380 W car). Manual is set, then the car plugs in, `rp` s
|
||||
before `R`. The run starts `E` s before a quarter edge (rig.BASE moved back),
|
||||
so `R = E + r_rel`. One dict per cycle, taken after it.
|
||||
|
||||
Trajectories after R: t1 both 0 W; t2 a 0 W, b follows the house (the loop
|
||||
below the reserve covers house + car, up to b's rating); t3 both ramp to 0 W
|
||||
over 3 cycles; t4 as t1, but every battery reading is 10 s old (the rig reads
|
||||
battery W every 10 fake s, P1 every 5) while P1 is fresh; t4r as t1, but P1
|
||||
is 5 s late while the battery reading is fresh.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
from datetime import timedelta
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import ev04_peak as P # noqa: E402
|
||||
import ev18_peak as H # noqa: E402
|
||||
import opt11_identity as rig # noqa: E402
|
||||
import safety81_sim as s81 # noqa: E402
|
||||
from app import peakguard # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
|
||||
AIM = H.AIM
|
||||
CAR = 1380.0
|
||||
FLOOR = H.FLOOR
|
||||
RATE = {"a": 5000.0, "b": 4600.0}
|
||||
OPTS = H.OPTS
|
||||
OPTS1 = {"peak_soc_floor": 20, "inverters": [OPTS["inverters"][0]]}
|
||||
|
||||
|
||||
class Meter(SimCharger):
|
||||
"""A charger whose energy meter shows no 10 Wh step until `hold_until`
|
||||
(sim seconds; None: always live, float('inf'): never)."""
|
||||
|
||||
hold_until = None
|
||||
_held = None
|
||||
|
||||
def _build(self):
|
||||
if self.hold_until is None or self.t >= self.hold_until:
|
||||
self._held = None
|
||||
return super()._build()
|
||||
if self._held is None:
|
||||
self._held = self.kwh
|
||||
keep, self.kwh = self.kwh, self._held
|
||||
try:
|
||||
return super()._build()
|
||||
finally:
|
||||
self.kwh = keep
|
||||
|
||||
|
||||
class Draw(Meter):
|
||||
"""A charger that draws `real_w` while charging and reports `say_w`
|
||||
(as test_ev18's). `c_at_0`: it stays in mode3 C while drawing 0 W."""
|
||||
|
||||
def __init__(self, real_w, say_w, c_at_0=False, **kw):
|
||||
super().__init__(**kw)
|
||||
self.real_w, self.say_w, self.c_at_0 = real_w, say_w, c_at_0
|
||||
|
||||
def target_w(self):
|
||||
if super().target_w() <= 0.0:
|
||||
return 0.0
|
||||
return self.real_w
|
||||
|
||||
def tick(self, seconds=1.0):
|
||||
super().tick(seconds)
|
||||
if self.c_at_0 and self.state == "B" and not self.full:
|
||||
self.state = "C"
|
||||
|
||||
def _build(self):
|
||||
keep, self._frozen_w = self._frozen_w, self.say_w
|
||||
try:
|
||||
return super()._build()
|
||||
finally:
|
||||
self._frozen_w = keep
|
||||
|
||||
|
||||
class Plant(H.Plant):
|
||||
"""`batt_lag`: every battery reading is that many s old. `p1_lag` with
|
||||
`p1_from`: P1 that many s late from that second on."""
|
||||
|
||||
batt_lag = 0.0
|
||||
p1_lag = 0.0
|
||||
p1_from = 0.0
|
||||
house = None
|
||||
|
||||
def batt_of(self, u, at):
|
||||
f = self.force.get(u)
|
||||
if f is not None:
|
||||
return float(f(at, self))
|
||||
return P.CarPlantN.batt_of(self, u, at)
|
||||
|
||||
def grid(self, at):
|
||||
if self.p1_lag and at >= self.p1_from:
|
||||
at = at - self.p1_lag
|
||||
return super().grid(at)
|
||||
|
||||
async def number(self, e, invert=False):
|
||||
for u, secs in self.lost.items():
|
||||
if e == "sensor.batt_" + u and int(self.t) in secs:
|
||||
return None
|
||||
if self.batt_lag and e.startswith("sensor.batt_") \
|
||||
and e[-1] in self.socs:
|
||||
return self.batt_of(e[-1], self.t - self.batt_lag)
|
||||
return await P.CarPlantN.number(self, e, invert)
|
||||
|
||||
|
||||
def split(bw, units="ab"):
|
||||
"""`bw` over the units, each capped at its rating."""
|
||||
if len(units) == 1:
|
||||
return {units: min(bw, RATE[units])}
|
||||
a = min(RATE["a"], bw / 2.0)
|
||||
b = min(RATE["b"], bw - a)
|
||||
a = min(RATE["a"], bw - b)
|
||||
return {"a": a, "b": b}
|
||||
|
||||
|
||||
def traj_fn(u, traj, before, R, house, step=1):
|
||||
"""Unit `u`'s W at time `at`: `before` until the first cycle after R
|
||||
(R + `step`), then the trajectory. P1 is sampled 0.3 s before each cycle,
|
||||
so the battery reading shows a change one cycle before the meter does."""
|
||||
def f(at, plant):
|
||||
if at < R + step:
|
||||
return before
|
||||
if traj in ("t1", "t4", "t4r"):
|
||||
return 0.0
|
||||
if traj == "t2":
|
||||
if u == "a":
|
||||
return 0.0
|
||||
return min(RATE["b"], house(at) + plant.ch.power_w)
|
||||
if traj == "t3":
|
||||
k = int((at - R) // step)
|
||||
return before * max(0.0, (3 - k) / 3.0)
|
||||
if traj == "keep":
|
||||
return before
|
||||
raise ValueError(traj)
|
||||
return f
|
||||
|
||||
|
||||
def run(*, bw=4250.0, traj="t1", rp=180, r_rel=43, order="manual",
|
||||
energy="ok", x=1, mono_x=None, aim=AIM, over=520.0, house_w=None,
|
||||
house_fn=None, car_a=6, n=2, extra=None, rel=None, lost=None,
|
||||
after=900,
|
||||
soc_after=None, soc0=21.0, mode="manual", sim=None,
|
||||
explain_off=False, latch_off=False, force=None, plug_at=None,
|
||||
man_at=None, opts=None, pre_w=H.PRE_W):
|
||||
"""One run; returns (run, trace, meta). `over`: house + car at batteries
|
||||
0 W lands at aim + `over` W (ignored with `house_w`). `order`: 'manual'
|
||||
(Manual at plug-in - 3 s), 'plug' (plug-in at R-185, Manual at R-180),
|
||||
'off120' (plug-in and charging in Off from R-180, Manual at R-60).
|
||||
`energy`: 'ok', 'late' (first 10 Wh step at plug-in + 150 s), 'never'.
|
||||
`mode`: 'manual' or 'off' (Off throughout: the base for honest alarms).
|
||||
`house_fn`: fn(t, R) for the house after the step. `extra`: events at
|
||||
run seconds, `rel`: at seconds from R. `lost`: {unit: seconds from R}.
|
||||
`plug_at` / `man_at`: plug-in / Manual at these seconds from R (override
|
||||
`order`). `force`: {unit: fn(at, plant) or None (the unit obeys)}.
|
||||
`opts`: added to the options. `pre_w`: the house before its step."""
|
||||
units = "ab" if n == 2 else "a"
|
||||
step = int(x)
|
||||
if order == "plug":
|
||||
lead = 185
|
||||
elif order == "off120":
|
||||
lead = 180
|
||||
else:
|
||||
lead = rp + 3
|
||||
if plug_at is not None or man_at is not None:
|
||||
lead = -min(v for v in (plug_at, man_at) if v is not None)
|
||||
E = 150
|
||||
while E + r_rel - lead - 2 * step < 10:
|
||||
E += 150
|
||||
E = int(-(-E // step) * step)
|
||||
R = E + r_rel
|
||||
if x != 1:
|
||||
R = int(-(-R // step) * step)
|
||||
hw = (aim + over - CAR) if house_w is None else house_w
|
||||
t_house = min(E - 120, R - lead - step)
|
||||
if x != 1:
|
||||
t_house = int(t_house // step * step)
|
||||
|
||||
def house(t):
|
||||
if t < t_house:
|
||||
return pre_w
|
||||
if house_fn is not None:
|
||||
return house_fn(t, R)
|
||||
return hw
|
||||
|
||||
sp = split(bw, units)
|
||||
frc = {u: traj_fn(u, traj, sp[u], R, house, step) for u in units}
|
||||
frc.update(force or {})
|
||||
soc_after = soc_after or {u: 19.0 for u in units}
|
||||
lagb = 10.0 if traj == "t4" else 0.0
|
||||
cls = type("Plant", (Plant,), {
|
||||
"force": frc, "batt_lag": lagb, "R": R,
|
||||
"lost": {u: {R + k for k in v} for u, v in (lost or {}).items()},
|
||||
"p1_lag": 5.0 if traj == "t4r" else 0.0, "p1_from": float(R)})
|
||||
|
||||
s = sim or Meter(setpoint_a=car_a)
|
||||
if energy == "never":
|
||||
s.hold_until = float("inf")
|
||||
if x != 1:
|
||||
tick = s.tick
|
||||
s.tick = lambda secs=1.0: tick(secs * x)
|
||||
|
||||
if order == "plug":
|
||||
t_plug, t_man = R - 185, R - 180
|
||||
elif order == "off120":
|
||||
t_plug, t_man = R - 180, R - 60
|
||||
else:
|
||||
t_plug, t_man = R - rp, R - rp - 3
|
||||
if plug_at is not None:
|
||||
t_plug = R + plug_at
|
||||
if man_at is not None:
|
||||
t_man = R + man_at
|
||||
if x != 1:
|
||||
t_plug = int(t_plug // step * step)
|
||||
t_man = int(t_man // step * step)
|
||||
if t_man == t_plug and order != "plug":
|
||||
t_man -= step
|
||||
|
||||
tr = []
|
||||
n_err = [len(H.ERR.rec)]
|
||||
|
||||
def hook(plant, c):
|
||||
orig = c.car_settle
|
||||
if explain_off:
|
||||
c._car_explains_alarm = lambda *a_, **k_: False
|
||||
if latch_off:
|
||||
c._car_contradicted = lambda *a_, **k_: False
|
||||
if mono_x is not None and mono_x != x:
|
||||
c.car_now = (lambda f=c.car_now: f() * mono_x / x)
|
||||
|
||||
async def settle():
|
||||
await orig()
|
||||
g = c.peak_guard
|
||||
red = [r_["id"] for r_ in c.checks()
|
||||
if r_["ok"] is False and not r_["warn"]
|
||||
and r_["id"] == "peak_guard"]
|
||||
errs = [m for m in H.ERR.rec[n_err[0]:]
|
||||
if "may not draw the battery lower" in m]
|
||||
n_err[0] = len(H.ERR.rec)
|
||||
cl = peakguard.claim(g) if g is not None else None
|
||||
mono = c.car_now()
|
||||
tr.append({
|
||||
"t": plant.t, "explains": c.car_explains,
|
||||
"lim": bool(g is not None and (g.floor_limited
|
||||
or g.saturated)),
|
||||
"floor_lim": bool(g is not None and g.floor_limited),
|
||||
"within_aim": bool(g is not None and g.within_aim),
|
||||
"wants": bool(g is not None and g.engaged
|
||||
and (g.wanted_w or 0.0) > 0.0),
|
||||
"wanted": None if g is None else g.wanted_w,
|
||||
"target": None if g is None else g.target_w,
|
||||
"alarm": c._peak_floor_limited, "red": red, "err": errs,
|
||||
"w": c.car_alarm_w(), "car_raw": c.car.car_w(mono),
|
||||
"batt": c.site_batt_w,
|
||||
"true_batt": plant.batt(plant.t),
|
||||
"need_real": c._car_need_real, "need_excl": c._car_need_excl,
|
||||
"need_house": c._car_need_house, "over_now": c._car_over_now,
|
||||
"contra": c._car_contra_block is not None and (
|
||||
c._peak_proj_real is not None
|
||||
and c._car_contra_block
|
||||
== c._peak_proj_real.block_start),
|
||||
"idle": c._car_idle(mono), "peak_needed": c._peak_needed,
|
||||
"key": c._carq["key"],
|
||||
"block": (c._peak_proj_real.block_start
|
||||
if c._peak_proj_real is not None else None),
|
||||
"floor_w": g.floor_w if g is not None else None,
|
||||
"lo": getattr(cl, "lo", None),
|
||||
"sp": tuple(i.last_write for i in c.inverters)})
|
||||
c.car_settle = settle
|
||||
|
||||
def set_manual(p, c):
|
||||
c._car_action("car_mode", "manual", c.car_now())
|
||||
|
||||
def plug(p, c):
|
||||
p.ch.plug_in()
|
||||
if energy == "late":
|
||||
p.ch.hold_until = p.ch.t + 150.0
|
||||
|
||||
def reserve(p, c):
|
||||
p.socs.update(soc_after)
|
||||
|
||||
ev = {}
|
||||
|
||||
def add(t, fn):
|
||||
t = int(t)
|
||||
old = ev.get(t)
|
||||
ev[t] = fn if old is None else (
|
||||
lambda p, c, a_=old, b_=fn: (a_(p, c), b_(p, c)))
|
||||
|
||||
add(0, hook)
|
||||
add(t_plug, plug)
|
||||
if mode == "manual":
|
||||
add(t_man, set_manual)
|
||||
add(R, reserve)
|
||||
for t, fn in (extra or {}).items():
|
||||
add(t, fn)
|
||||
for t, fn in (rel or {}).items():
|
||||
add(R + t, fn)
|
||||
base, tick0 = rig.BASE, s81.TICK
|
||||
rig.BASE, s81.TICK = base - timedelta(seconds=E), float(x)
|
||||
o = dict(OPTS if n == 2 else OPTS1, **(opts or {}))
|
||||
try:
|
||||
r = P.drive(house, dur=R + after + step, rating=5000.0,
|
||||
soc={u: soc0 for u in units}, cap=aim + H.MARGIN,
|
||||
phases=1, n=n, plant_cls=cls, opts=o, dev_w=5000.0,
|
||||
setpoint=car_a, user_a=car_a, mode="off", events=ev,
|
||||
sim=s, plug=False)
|
||||
finally:
|
||||
rig.BASE, s81.TICK = base, tick0
|
||||
meta = {"E": E, "R": R, "t_plug": t_plug, "t_man": t_man,
|
||||
"t_house": t_house, "house_w": hw, "step": step}
|
||||
return r, tr, meta
|
||||
|
||||
|
||||
# ---------------------------------------------------------- event helpers
|
||||
# For `rel` (seconds from R) or `extra` (run seconds).
|
||||
def p1_gap(t0, secs):
|
||||
"""No P1 sample reaches the add-on for `secs` from `t0` (it is late)."""
|
||||
def off(p, c):
|
||||
c.p1._ev19_submit = c.p1.submit
|
||||
c.p1.submit = lambda *a, **k: None
|
||||
|
||||
def on(p, c):
|
||||
c.p1.submit = c.p1._ev19_submit
|
||||
return {t0: off, t0 + secs: on}
|
||||
|
||||
|
||||
def stale(t0, t1):
|
||||
"""The charger's readings stop reaching the car tracker from t0 to t1:
|
||||
its figure ages past `stale_s`."""
|
||||
def off(p, c):
|
||||
c.car._ev19_observe = c.car.observe
|
||||
c.car.observe = lambda *a, **k: None
|
||||
|
||||
def on(p, c):
|
||||
c.car.observe = c.car._ev19_observe
|
||||
return {t0: off, t1: on}
|
||||
|
||||
|
||||
def unavailable(t0, t1):
|
||||
return {t0: lambda p, c: p.ch.go_unavailable(True),
|
||||
t1: lambda p, c: p.ch.go_unavailable(False)}
|
||||
|
||||
|
||||
def restart(t0):
|
||||
return {t0: lambda p, c: H.restart(c)}
|
||||
|
||||
|
||||
def phases(t0, n=3):
|
||||
"""The user asks for `n` phases (the add-on's own 0 A pause follows)."""
|
||||
return {t0: lambda p, c: c._car_action("car_phases", n, c.car_now())}
|
||||
|
||||
|
||||
def socs(t0, **s):
|
||||
return {t0: lambda p, c: p.socs.update(s)}
|
||||
|
||||
|
||||
def merge(*evs):
|
||||
out = {}
|
||||
for e in evs:
|
||||
for t, fn in e.items():
|
||||
old = out.get(t)
|
||||
out[t] = fn if old is None else (
|
||||
lambda p, c, a_=old, b_=fn: (a_(p, c), b_(p, c)))
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------- grading
|
||||
def window(tr, t0, t1):
|
||||
return [x for x in tr if t0 <= x["t"] <= t1]
|
||||
|
||||
|
||||
def alarms(r):
|
||||
return H.alarms(r)
|
||||
|
||||
|
||||
def edges(tr):
|
||||
return H.edges(tr)
|
||||
|
||||
|
||||
def bad(x):
|
||||
"""An alarm, red sample or ERROR in this cycle."""
|
||||
return bool(x["alarm"] or x["red"] or x["err"])
|
||||
|
||||
|
||||
def repro(r, tr, meta, t0=-10, t1=60):
|
||||
"""T1's definition: a floor notice, ERROR or red sample in R-10..R+60 in
|
||||
a cycle where the car figure is trusted (the shape lands under the aim
|
||||
without the car, so the car explains). Returns (cycles, C5-only cycles)."""
|
||||
R = meta["R"]
|
||||
w = window(tr, R + t0, R + t1)
|
||||
notes = [t for t in alarms(r) if R + t0 <= t <= R + t1]
|
||||
hit = [x["t"] for x in w if bad(x) and x["w"] is not None
|
||||
and x["w"] > 0.0]
|
||||
c5 = [x["t"] for x in w if bad(x) and not (x["w"] is not None
|
||||
and x["w"] > 0.0)]
|
||||
return hit, c5, notes
|
||||
|
||||
|
||||
def quiet(r, tr, t0, t1):
|
||||
return (not [t for t in alarms(r) if t0 <= t <= t1]
|
||||
and not any(bad(x) for x in window(tr, t0, t1)))
|
||||
|
||||
|
||||
def commands(r, tr):
|
||||
h = hashlib.sha256()
|
||||
for u in sorted(r["plant"].hists):
|
||||
h.update(repr((u, r["plant"].hists[u])).encode())
|
||||
h.update(repr(r["sim"].writes()).encode())
|
||||
h.update(repr([(x["t"], x["floor_w"], x["lo"], x["sp"])
|
||||
for x in tr]).encode())
|
||||
return h.hexdigest()[:16]
|
||||
|
||||
|
||||
def row(name, r, tr, meta):
|
||||
hit, c5, notes = repro(r, tr, meta)
|
||||
R = meta["R"]
|
||||
first = hit[:1]
|
||||
cause = ""
|
||||
if first:
|
||||
x = next(y for y in tr if y["t"] == first[0])
|
||||
cause = (f"w={x['w']:.0f} batt={x['batt']} true={x['true_batt']:.0f}"
|
||||
f" real={x['need_real']:d} excl={x['need_excl']:d} "
|
||||
f"house={x['need_house']:d} over={x['over_now']:d} "
|
||||
f"contra={x['contra']:d} pn={x['peak_needed']:d} "
|
||||
f"wa={x['within_aim']:d} wanted={x['wanted']:.0f}")
|
||||
return (f"{name:42s} R={R:5d} notes {[t - R for t in notes]} "
|
||||
f"hit {[t - R for t in hit][:6]}{'...' if len(hit) > 6 else ''}"
|
||||
f" n={len(hit)} c5 {len(c5)} err "
|
||||
f"{len([x for x in window(tr, R - 10, R + 60) if x['err']])} "
|
||||
f"red900 {len([x for x in window(tr, R - 60, R + 900) if x['red']])}"
|
||||
f" {cause}")
|
||||
|
||||
|
||||
def t2_shape(**kw):
|
||||
"""The reproducing shape (T2): b follows the house from R, 0 W before."""
|
||||
return dict(dict(bw=0.0, traj="t2"), **kw)
|
||||
|
||||
|
||||
def t5_shape(**kw):
|
||||
"""The honest shape (T5): the house alone misses the aim by 1 680 W, more
|
||||
than the 1 380 W car; the batteries give 4 250 W until R."""
|
||||
return dict(dict(bw=4250.0, traj="t1", house_w=AIM + 1680.0), **kw)
|
||||
|
||||
|
||||
def flicker_force(bw=2000.0):
|
||||
"""T17: each unit gives bw/2 above its reserve and ramps to 0 W over 3
|
||||
cycles once at it (tau3); back above it, it gives bw/2 again at once."""
|
||||
def mk(u):
|
||||
st = {"since": None}
|
||||
|
||||
def f(at, plant):
|
||||
if plant.socs[u] >= 20.0:
|
||||
st["since"] = None
|
||||
return bw / 2.0
|
||||
if st["since"] is None:
|
||||
st["since"] = at
|
||||
k = int(at - st["since"])
|
||||
return bw / 2.0 * max(0.0, (3 - k) / 3.0)
|
||||
return f
|
||||
return {"a": mk("a"), "b": mk("b")}
|
||||
|
||||
|
||||
def _step_house(k, lo=AIM + 520.0 - CAR, hi=AIM + 1900.0):
|
||||
return lambda t, R: lo if t < R + k else hi
|
||||
|
||||
|
||||
def _burst(k, w):
|
||||
"""Inverter-b: 2 125 W until R+1, then `w` for 0.5 s before the cycle at
|
||||
R+k (P1, sampled 0.3 s before it, and the reading both show it), else
|
||||
0 W."""
|
||||
def f(at, plant):
|
||||
if at < plant.R + 1:
|
||||
return 4250.0 / 2.0
|
||||
return w if plant.R + k - 0.5 <= at <= plant.R + k else 0.0
|
||||
return f
|
||||
|
||||
|
||||
def _ignoring():
|
||||
"""The charger accepts the 6 A write and ignores it: the car stays at
|
||||
0 A."""
|
||||
s = Meter(setpoint_a=0)
|
||||
s.refuse = "ignore"
|
||||
return s
|
||||
|
||||
|
||||
def _full_at_plug(p, c):
|
||||
"""The car is full (after the plug-in at R-180): mode3 B, 0 W."""
|
||||
p.ch.car_full()
|
||||
|
||||
|
||||
def _no_energy(p, c):
|
||||
"""The charger has no energy entity."""
|
||||
p.ch.no_energy = True
|
||||
|
||||
|
||||
def _freeze_stop(p, c):
|
||||
p.ch.freeze()
|
||||
p.ch.car_full()
|
||||
|
||||
|
||||
def jobs():
|
||||
"""Every controller run test_ev19.py grades: {name: kwargs}."""
|
||||
j = {}
|
||||
for name, kw in grid():
|
||||
j["T1 " + name] = kw
|
||||
# T3: the battery W sweep
|
||||
for tj in ("t1", "t2"):
|
||||
for bw in range(0, 4601, 200):
|
||||
j[f"T3 {tj} bw={bw}"] = dict(bw=float(bw), traj=tj)
|
||||
j[f"T3 {tj} tau5"] = dict(bw=9600.0, traj=tj, aim=6000.0,
|
||||
house_w=5200.0)
|
||||
# T4: the landing without the car at aim + 9 / + 11 W
|
||||
for d in (9, 11):
|
||||
for md in ("manual", "off"):
|
||||
j[f"T4 +{d} {md}"] = t2_shape(house_w=AIM + d, mode=md)
|
||||
# T5: honest at the reserve
|
||||
for tj in ("t1", "t4"):
|
||||
for md in ("manual", "off"):
|
||||
j[f"T5 {tj} {md}"] = t5_shape(traj=tj, mode=md)
|
||||
for md in ("manual", "off"):
|
||||
j[f"T5 tau5 {md}"] = dict(bw=9600.0, traj="t1", aim=6000.0,
|
||||
house_w=7700.0, mode=md)
|
||||
# T6: the honest step in the reserve cycle
|
||||
for k in (0, 1, 5):
|
||||
for md in ("manual", "off"):
|
||||
j[f"T6 step R+{k} {md}"] = dict(bw=4250.0, traj="t1", mode=md,
|
||||
house_fn=_step_house(k))
|
||||
# T7: unknown values
|
||||
for nm, sh in (("T2", t2_shape), ("T5", t5_shape)):
|
||||
j[f"T7(a) {nm}"] = sh(lost={"a": {0, 1}})
|
||||
j[f"T7(b) {nm}"] = sh(rel=unavailable(0, 1))
|
||||
j["T7(a) T5 off"] = t5_shape(lost={"a": {0, 1}}, mode="off")
|
||||
j["T7(b) T5 off"] = t5_shape(rel=unavailable(0, 1), mode="off")
|
||||
# T8: a stale car figure
|
||||
j["T8(a) Off 120 s, Manual R-5"] = t2_shape(plug_at=-125, man_at=-5)
|
||||
j["T8(b) stale R-5..R+20"] = t2_shape(rel=stale(-5, 20))
|
||||
j["T8(c) frozen, the car stops"] = t5_shape(rel={-30: _freeze_stop})
|
||||
j["T8(c) off"] = t5_shape(rel={-30: _freeze_stop}, mode="off")
|
||||
# T9: comms
|
||||
for nm, sh in (("T2", t2_shape), ("T5", t5_shape)):
|
||||
j[f"T9(a) {nm} b lost at R"] = sh(lost={"b": {0}})
|
||||
j[f"T9(a) {nm} b lost at R-1"] = sh(lost={"b": {-1}})
|
||||
j[f"T9(b) {nm} P1 5 s late at R"] = sh(rel=p1_gap(0, 5))
|
||||
# T10: a restart
|
||||
for nm, sh in (("T2", t2_shape), ("T5", t5_shape)):
|
||||
j[f"T10 {nm} twin"] = sh()
|
||||
for k in (-2, 2):
|
||||
j[f"T10 {nm} restart R{k:+d}"] = sh(rel=restart(k))
|
||||
# T11: the quarter edge
|
||||
for rr in (-1, 0, 1, 43):
|
||||
j[f"T11 T2 R=E{rr:+d}"] = t2_shape(r_rel=rr)
|
||||
j[f"T11 T5 R=E{rr:+d}"] = t5_shape(r_rel=rr)
|
||||
j[f"T11 T5 R=E{rr:+d} off"] = t5_shape(r_rel=rr, mode="off")
|
||||
# C4: the old quarter heads over the aim (the house high all along), so the
|
||||
# guard wants power in its last 60 s and SAFETY-126's latch is carried
|
||||
j["T11 C4 T2 R=E+1"] = t2_shape(r_rel=1, house_w=13350.0, pre_w=13350.0)
|
||||
# T12: our own phase change
|
||||
for k in (-15, 5):
|
||||
j[f"T12 T2 1->3 at R{k:+d}"] = t2_shape(rel=phases(k))
|
||||
j[f"T12 T5 1->3 at R{k:+d}"] = t5_shape(rel=phases(k))
|
||||
j[f"T12 T5 1->3 at R{k:+d} off"] = t5_shape(rel=phases(k),
|
||||
mode="off")
|
||||
# T13: a wrong charger reply
|
||||
# (a): the house + the 400 W it really draws lands at aim + 520 W, so the
|
||||
# house alone misses by 120 W; (b) and T14(a): the car draws 0 W and the
|
||||
# house alone lands at aim + 520 W. An alarm is due in each.
|
||||
for md in ("manual", "off"):
|
||||
j[f"T13(a) draws 400 W {md}"] = t2_shape(
|
||||
sim=Draw(400.0, CAR, setpoint_a=6), house_w=AIM + 120.0, mode=md)
|
||||
j[f"T13(a) draws 100 W {md}"] = t2_shape(
|
||||
sim=Draw(100.0, CAR, setpoint_a=6), house_w=AIM + 420.0, mode=md)
|
||||
j[f"T13(b) the write ignored, 0 A {md}"] = t2_shape(
|
||||
sim=_ignoring(), house_w=AIM + 520.0, mode=md)
|
||||
# T14: configuration
|
||||
j[f"T14(a) 0 W in C {md}"] = t2_shape(
|
||||
sim=Draw(0.0, 0.0, c_at_0=True, setpoint_a=6),
|
||||
house_w=AIM + 520.0, mode=md)
|
||||
j[f"T14(a) idle B {md}"] = t2_shape(
|
||||
house_w=AIM + 520.0, mode=md, rel={-179: _full_at_plug})
|
||||
j["T14(b) ev_charger off"] = t2_shape(opts={"ev_charger": "off"})
|
||||
j["T14(b) off"] = t2_shape(mode="off")
|
||||
for tj in ("t1", "t4"):
|
||||
j[f"T14(c) N=1 anchor {tj}"] = dict(n=1, bw=4250.0, traj=tj)
|
||||
j["T14(c) N=1 T5"] = t5_shape(n=1)
|
||||
j["T14(c) N=1 T5 off"] = t5_shape(n=1, mode="off")
|
||||
# T15: one battery first (SAFETY-87)
|
||||
for nm, hw in (("anchor", AIM + 520.0 - CAR), ("honest", 19000.0)):
|
||||
for md in ("manual", "off"):
|
||||
j[f"T15 {nm} {md}"] = dict(
|
||||
bw=4250.0, traj="t1", house_w=hw, mode=md,
|
||||
force={"b": None}, soc_after={"a": 19.0, "b": 35.0},
|
||||
rel=socs(360, b=19.0))
|
||||
# T16: x10 (wall and mono), and mono x1 / wall x10
|
||||
for xn, xk in (("x10", dict(x=10)), ("mono1", dict(x=10, mono_x=1))):
|
||||
xk = dict(xk, r_rel=40)
|
||||
# x10: b at 1 200 W before R (at 0 W, which the forced unit holds
|
||||
# against the guard's floor, SAFETY-37's gate reads it as frozen)
|
||||
xk2 = dict(xk, bw=1200.0)
|
||||
j[f"T16 {xn} T2"] = t2_shape(**xk2)
|
||||
for tj in ("t1", "t4"):
|
||||
for bw in (0.0, 2000.0, 4250.0):
|
||||
j[f"T16 {xn} T3 {tj} bw={bw:.0f}"] = dict(bw=bw, traj=tj,
|
||||
**xk)
|
||||
for md in ("manual", "off"):
|
||||
j[f"T16 {xn} T5 {md}"] = t5_shape(mode=md, **xk)
|
||||
j[f"T16 {xn} T6 {md}"] = dict(bw=4250.0, traj="t1", mode=md,
|
||||
house_fn=_step_house(0), **xk)
|
||||
j[f"T16 {xn} T7(b) T2"] = t2_shape(rel=unavailable(0, 10), **xk2)
|
||||
for rr in (-10, 0, 10, 40):
|
||||
j[f"T16 {xn} T11 T2 R=E{rr:+d}"] = t2_shape(
|
||||
**dict(xk2, r_rel=rr))
|
||||
j[f"T16 {xn} T11 T5 R=E{rr:+d}"] = t5_shape(**dict(xk, r_rel=rr))
|
||||
# T17: no flicker
|
||||
j["T17 flicker"] = dict(
|
||||
force=flicker_force(), after=1200,
|
||||
rel=merge(socs(300, a=21.0, b=21.0), socs(600, a=19.0, b=19.0)),
|
||||
house_fn=lambda t, R: AIM + 10.0 + (40.0 if int(t // 7) % 2
|
||||
else -40.0))
|
||||
# N2: figures only `car_w_trusted` keeps out of the alarm path: no energy
|
||||
# entity (never corroborated, never contradicted) and 11 kW reported at
|
||||
# a 6 A read-back (capped at 1 518 W; the house alone misses by 1 680 W)
|
||||
for md in ("manual", "off"):
|
||||
j[f"N2 no energy entity {md}"] = t2_shape(extra={0: _no_energy},
|
||||
mode=md)
|
||||
j[f"N2 reports 11 kW at 6 A {md}"] = t5_shape(
|
||||
sim=Draw(CAR, 11000.0, setpoint_a=6), mode=md)
|
||||
# Review round 1: an honest house step answered by ONE cycle of inverter-b
|
||||
# power that P1 and the reading both show (the meter in step), after the
|
||||
# T6 shape (4 250 W until R, then 0 W).
|
||||
for k in (5, 30):
|
||||
for hi in (1900, 2500):
|
||||
for burst in (3000.0, 4600.0):
|
||||
for md in ("manual", "off"):
|
||||
j[f"RB step R+{k} aim+{hi} burst {burst:.0f} {md}"] = dict(
|
||||
bw=4250.0, traj="t1", mode=md,
|
||||
house_fn=_step_house(k - 0.5, hi=AIM + hi),
|
||||
force={"b": _burst(k, burst)})
|
||||
# T10 (mE): restarts at R-1 and R, so the rise cycle has no reading from
|
||||
# two cycles back
|
||||
for nm, sh in (("T2", t2_shape), ("T5", t5_shape)):
|
||||
for k in (-1, 0):
|
||||
j[f"T10 {nm} restart R{k:+d}"] = sh(rel=restart(k))
|
||||
# T20 / N4: the same runs with the car never explaining
|
||||
j["N4 T2 explain off"] = t2_shape(explain_off=True)
|
||||
j["N4 T5 explain off"] = t5_shape(explain_off=True)
|
||||
return j
|
||||
|
||||
|
||||
def grid():
|
||||
"""The T1 cells: (name, kwargs)."""
|
||||
cells = []
|
||||
for bw in (0.0, 400.0, 800.0, 2000.0, 4250.0, 9600.0):
|
||||
for tj in ("t1", "t2", "t3", "t4", "t4r"):
|
||||
for rp in (30, 100, 110, 180, 600):
|
||||
kw = dict(bw=bw, traj=tj, rp=rp)
|
||||
if bw == 9600.0:
|
||||
kw.update(aim=6000.0, house_w=5200.0)
|
||||
cells.append((f"core bw={bw:.0f} {tj} rp={rp}", kw))
|
||||
cells.append(("a: plug R-185, Manual R-180", dict(order="plug")))
|
||||
cells.append(("a: Off 120 s, Manual R-60", dict(order="off120")))
|
||||
cells.append(("b: energy first step late", dict(energy="late")))
|
||||
cells.append(("b: energy never steps", dict(energy="never")))
|
||||
for rr in (-60, 0, 1, 43, 450, 890):
|
||||
cells.append((f"c: R=E{rr:+d}", dict(r_rel=rr)))
|
||||
cells.append(("d: x10 wall+mono", dict(x=10, r_rel=40)))
|
||||
cells.append(("d: x10 wall, mono x1", dict(x=10, mono_x=1, r_rel=40)))
|
||||
for tj, bw in (("t4", 4250.0), ("t2", 4250.0), ("t2", 1200.0)):
|
||||
cells.append((f"d: x10 wall+mono {tj} bw={bw:.0f}",
|
||||
dict(x=10, r_rel=40, traj=tj, bw=bw)))
|
||||
cells.append((f"d: x10 wall, mono x1 {tj} bw={bw:.0f}",
|
||||
dict(x=10, mono_x=1, r_rel=40, traj=tj, bw=bw)))
|
||||
return cells
|
||||
|
||||
|
||||
class Res:
|
||||
"""What a check needs from one run, picklable: the notices (`raised`,
|
||||
seconds and ids), the trace, the command digest and the run's times."""
|
||||
|
||||
def __init__(self, r, tr, meta):
|
||||
self.raised = list(r["raised"])
|
||||
self.tr, self.meta = tr, meta
|
||||
self.cmd = commands(r, tr)
|
||||
self.R, self.E = meta["R"], meta["E"]
|
||||
|
||||
def alarms(self):
|
||||
return [t for t, n in self.raised if n == FLOOR]
|
||||
|
||||
def rel_alarms(self):
|
||||
return [int(t - self.R) for t in self.alarms()]
|
||||
|
||||
def edges(self):
|
||||
return [int(t - self.R) for t in edges(self.tr)]
|
||||
|
||||
def errors(self):
|
||||
return [int(x["t"] - self.R) for x in self.tr if x["err"]]
|
||||
|
||||
def red(self, t0=-60, t1=900):
|
||||
return [int(x["t"] - self.R) for x in
|
||||
window(self.tr, self.R + t0, self.R + t1) if x["red"]]
|
||||
|
||||
def at(self, k):
|
||||
return next((x for x in self.tr if x["t"] == self.R + k), None)
|
||||
|
||||
def win(self, t0, t1):
|
||||
return window(self.tr, self.R + t0, self.R + t1)
|
||||
|
||||
def quiet(self, t0=-60, t1=900):
|
||||
return quiet({"raised": self.raised}, self.tr,
|
||||
self.R + t0, self.R + t1)
|
||||
|
||||
def edges_per_quarter(self):
|
||||
"""False -> True edges of the floor alarm per quarter (N5)."""
|
||||
out = {}
|
||||
for t in edges(self.tr):
|
||||
q = int((t - self.E) // 900)
|
||||
out[q] = out.get(q, 0) + 1
|
||||
return out
|
||||
|
||||
def summary(self):
|
||||
return {"alarms": self.rel_alarms(), "edges": self.edges(),
|
||||
"errors": self.errors(), "red": len(self.red()),
|
||||
"cmd": self.cmd}
|
||||
|
||||
|
||||
_JOBS = {}
|
||||
|
||||
|
||||
def _job(name):
|
||||
import logging
|
||||
logging.disable(logging.WARNING)
|
||||
return name, Res(*run(**_JOBS[name]))
|
||||
|
||||
|
||||
def run_many(jobs, procs=None):
|
||||
"""{name: kwargs} -> {name: Res}, `procs` runs at a time (fork: the
|
||||
kwargs may hold functions)."""
|
||||
import multiprocessing
|
||||
_JOBS.clear()
|
||||
_JOBS.update(jobs)
|
||||
procs = procs or int(os.environ.get("EV19_JOBS", "0")) \
|
||||
or min(8, os.cpu_count() or 1)
|
||||
ctx = multiprocessing.get_context("fork")
|
||||
with ctx.Pool(procs) as pool:
|
||||
return dict(pool.imap_unordered(_job, list(jobs), chunksize=1))
|
||||
|
||||
|
||||
def _one(cell):
|
||||
import logging
|
||||
logging.disable(logging.WARNING)
|
||||
name, kw = cell
|
||||
try:
|
||||
r, tr, meta = run(**kw)
|
||||
except Exception as e: # noqa: BLE001
|
||||
import traceback
|
||||
return name, f"{name:42s} Traceback {e!r}\n{traceback.format_exc()}"
|
||||
return name, row(name, r, tr, meta)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import multiprocessing
|
||||
cells = grid()
|
||||
if len(sys.argv) > 1:
|
||||
cells = [c for c in cells if any(a in c[0] for a in sys.argv[1:])]
|
||||
with multiprocessing.Pool(int(os.environ.get("EV19_JOBS", "8"))) as pool:
|
||||
for _name, line in pool.imap(_one, cells):
|
||||
print(line, flush=True)
|
||||
@@ -1,180 +0,0 @@
|
||||
"""EV-20, T53: the acceptance sim day, shared by test_ev20_long.py (Batteries
|
||||
first) and test_ev20_long_car.py (Car first).
|
||||
|
||||
The real Controller, N=2 (A 40 % and may charge, B full), 08:00-18:00 of sun
|
||||
(9 kW at noon) with 12 clouds of 1 to 8 minutes, a house of 0.4 to 2.5 kW with
|
||||
three +3 kW steps of a little under 5 minutes. The cycle order of `step` over
|
||||
the whole day, of `step_race` over the cloudiest three hours, and a car-Off
|
||||
twin over the quarters around the house steps for the alarms.
|
||||
|
||||
What is checked, per priority and cycle order:
|
||||
- starts: at most one per stretch in which the car's target stayed under
|
||||
6 A worth longer than `ev_pause_min` (the morning counts as one), so no cloud
|
||||
or house step shorter than that starts or pauses the car;
|
||||
- no start and no pause inside a cloud of 300 s or less;
|
||||
- selects at least 600 s apart;
|
||||
- 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.
|
||||
"""
|
||||
|
||||
import math
|
||||
import random
|
||||
|
||||
import ev20_sun as S
|
||||
|
||||
DAY = 36000 # 08:00 to 18:00, 1 s cycles
|
||||
PAUSE_S = 300.0
|
||||
MARGIN = 100.0
|
||||
_rnd = random.Random(53)
|
||||
CLOUDS = []
|
||||
_t = 1800
|
||||
for _k in range(12):
|
||||
_t += _rnd.randint(1200, 2400)
|
||||
CLOUDS.append((_t, _t + _rnd.randint(60, 480)))
|
||||
STEPS = [(9000, 9290), (19000, 19290), (27000, 27290)]
|
||||
SOCS = {"a": 40.0, "b": 100.0}
|
||||
RACE = (7200, 7200 + 10800) # the cloudiest three hours
|
||||
|
||||
|
||||
def sun(t):
|
||||
base = 9000.0 * max(0.0, math.sin(math.pi * t / DAY))
|
||||
for a, b in CLOUDS:
|
||||
if a <= t < b:
|
||||
return 0.15 * base
|
||||
return base
|
||||
|
||||
|
||||
def house(t):
|
||||
w = 400.0 + 2100.0 * (0.5 + 0.5 * math.sin(t / 1700.0))
|
||||
for a, b in STEPS:
|
||||
if a <= t < b:
|
||||
w += 3000.0
|
||||
return w
|
||||
|
||||
|
||||
def cur_writes(r):
|
||||
return [(x[2], x[1], x[3]) for x in r["c"].car_solar.log
|
||||
if x[0] == "current"]
|
||||
|
||||
|
||||
def low_stretches(r, first, longer=PAUSE_S):
|
||||
"""Stretches in which the car's target was under 6 A worth on 1 phase for
|
||||
longer than `longer`: (start, end); the last may run to the day's end."""
|
||||
out, since = [], None
|
||||
for x in r["trace"]:
|
||||
sp = x["spare"]
|
||||
room = x.get("room") or 0.0
|
||||
tgt = None if sp is None else sp - (room if first == "batteries"
|
||||
else 0.0) - MARGIN
|
||||
low = tgt is None or tgt < 6.0 * 230.0
|
||||
if low and since is None:
|
||||
since = x["t"]
|
||||
if not low and since is not None:
|
||||
if x["t"] - since > longer:
|
||||
out.append((since, x["t"]))
|
||||
since = None
|
||||
if since is not None and r["trace"] \
|
||||
and r["trace"][-1]["t"] - since > longer:
|
||||
out.append((since, r["trace"][-1]["t"]))
|
||||
return out
|
||||
|
||||
|
||||
def grid_split(r):
|
||||
"""The car's grid energy outside its holds (W s): settled, and within 20 s
|
||||
of a step of the sun, the house or the car's own current."""
|
||||
tr = r["trace"]
|
||||
marks = []
|
||||
for i in range(1, len(tr)):
|
||||
a, b = tr[i - 1], tr[i]
|
||||
if abs(b["sun"] - a["sun"]) > 200.0 or abs(b["house"] - a["house"]) \
|
||||
> 200.0 or b["sp"] != a["sp"] or b["ph"] != a["ph"]:
|
||||
marks.append(b["t"])
|
||||
settled = slew = 0.0
|
||||
j = 0
|
||||
for x in tr:
|
||||
imp = max(0.0, min(x["car"], x["grid"])) \
|
||||
if x["why"] != "hold" and x["sp"] > 0 else 0.0
|
||||
if imp <= 0.0:
|
||||
continue
|
||||
while j < len(marks) and marks[j] < x["t"] - 20.0:
|
||||
j += 1
|
||||
near = j < len(marks) and marks[j] <= x["t"]
|
||||
if near:
|
||||
slew += imp
|
||||
else:
|
||||
settled += imp
|
||||
return settled, slew
|
||||
|
||||
|
||||
def run_day(first, check):
|
||||
"""Run the day for one priority and grade it through `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]}")
|
||||
runs = {"step": S.drive(house, sun, dur=DAY, first=first, socs=dict(SOCS),
|
||||
race=False),
|
||||
"race": S.drive(house, sun, dur=RACE[1] - RACE[0], t0=RACE[0],
|
||||
first=first, socs=dict(SOCS), race=True)}
|
||||
for tag, r in runs.items():
|
||||
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.
|
||||
log = r["c"].car_solar.log
|
||||
sel_t = [t for k, a, t, ok in log if k == "phases"]
|
||||
starts, pauses, paused = [], [], True
|
||||
for kind, a, t, ok in log:
|
||||
if kind != "current":
|
||||
continue
|
||||
if a == 0.0:
|
||||
if not [1 for t2 in sel_t if t <= t2 <= t + 30.0]:
|
||||
pauses.append(t)
|
||||
paused = True
|
||||
elif paused:
|
||||
starts.append(t)
|
||||
paused = False
|
||||
lows = low_stretches(r, first)
|
||||
check(f"T53 [{first} first, {tag}]: {len(starts)} starts, at most one "
|
||||
f"per stretch under 6 A worth longer than the pause "
|
||||
f"({len(lows)}: {lows[:6]})", len(starts) <= len(lows) + 1)
|
||||
# A pause or start inside a short cloud is the cloud's only when the
|
||||
# low stretch it ends began with that cloud.
|
||||
every = low_stretches(r, first, longer=-1.0)
|
||||
bad = []
|
||||
for t in pauses + starts:
|
||||
for a, b in short_c:
|
||||
if a <= t <= b + 1:
|
||||
began = [s0 for s0, e0 in every if s0 <= t <= e0 + 1]
|
||||
if not began or began[-1] >= a - 1:
|
||||
bad.append((t, a, b))
|
||||
check(f"T53 [{first} first, {tag}]: no start and no pause from a "
|
||||
f"cloud of 300 s or less ({bad[:2]}; {len(long_c)} clouds are "
|
||||
f"longer)", not bad)
|
||||
sel = [x[0] for x in r["sim"].log if x[1] == "phases"]
|
||||
check(f"T53 [{first} first, {tag}]: selects at least 600 s apart "
|
||||
f"({sel})", all(b - a >= 600.0 for a, b in zip(sel, sel[1:])))
|
||||
settled, slew = grid_split(r)
|
||||
print(f" [{first} first, {tag}] writes {len(w)}; car grid energy "
|
||||
f"outside holds: settled {settled / 3600.0:.1f} Wh, loop slew "
|
||||
f"after a step {slew / 3600.0:.1f} Wh; sun "
|
||||
f"{r['c'].car_sun_kwh()} of {r['c'].car.today_kwh} kWh")
|
||||
check(f"T53 [{first} first, {tag}]: the car's settled grid energy "
|
||||
f"outside its holds is at most 10 Wh ({settled / 3600.0:.1f} Wh)",
|
||||
settled <= 10.0 * 3600.0)
|
||||
r = runs["step"]
|
||||
for a, _b in STEPS:
|
||||
t0 = float(a - a % 900 - 900)
|
||||
off = S.drive(house, sun, dur=2700, t0=t0, first=first, mode="off",
|
||||
plug=False, socs=dict(SOCS))
|
||||
win = (t0 + 900.0, t0 + 2700.0) # the first quarter warms up
|
||||
al = [t for t, n in r["raised"] if n in S.ALARMS
|
||||
and win[0] <= t < win[1]]
|
||||
ao = [t for t, n in off["raised"] if n in S.ALARMS
|
||||
and win[0] <= t < win[1]]
|
||||
check(f"T53 [{first} first]: house-caused alarms around the +3 kW "
|
||||
f"step at {a} s at the same seconds as the car-Off twin, +2 s "
|
||||
f"({al[:3]} vs {ao[:3]})",
|
||||
len(al) == len(ao) and all(abs(x - y) <= 2
|
||||
for x, y in zip(al, ao)))
|
||||
return runs
|
||||
@@ -1,251 +0,0 @@
|
||||
"""EV-20: shared pieces of the Solar checks (test_ev20*.py): the Std run,
|
||||
the write logs, a charger model with refusals in time windows, the Never
|
||||
checks every run can carry, and the shutdown and fault shapes.
|
||||
|
||||
Each check file imports `check`, `fails` and `LOG` from here and is its own
|
||||
process, so they are its own."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
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, main as app_main # noqa: E402
|
||||
import ev20_sun as S # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(name, cond):
|
||||
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||
if not cond:
|
||||
fails.append(name)
|
||||
|
||||
|
||||
class _Log(logging.Handler):
|
||||
def __init__(self):
|
||||
super().__init__(logging.DEBUG)
|
||||
self.rec = []
|
||||
|
||||
def emit(self, r):
|
||||
self.rec.append((r.levelname, r.getMessage(), bool(r.exc_info)))
|
||||
|
||||
def mark(self):
|
||||
return len(self.rec)
|
||||
|
||||
def since(self, n, level=None):
|
||||
return [m for lv, m, _x in self.rec[n:] if level in (None, lv)]
|
||||
|
||||
def tracebacks(self, n=0):
|
||||
return [m for lv, m, x in self.rec[n:] if x]
|
||||
|
||||
|
||||
LOG = _Log()
|
||||
_g = logging.getLogger("goodwe")
|
||||
_g.addHandler(LOG)
|
||||
_g.setLevel(logging.DEBUG)
|
||||
_g.propagate = False
|
||||
|
||||
FULL = {"a": 100.0, "b": 100.0}
|
||||
SET = S.SET
|
||||
|
||||
|
||||
def const(w):
|
||||
return S.const(w)
|
||||
|
||||
|
||||
def step_fn(*pairs, base=0.0):
|
||||
"""A function of t: `base`, then each (from_t, value) in order. The meter
|
||||
is sampled 0.3 s before each cycle, so a change "at t0" is the cycle of
|
||||
t0's."""
|
||||
def f(t):
|
||||
v = base
|
||||
for t0, x in pairs:
|
||||
if t >= t0 - 0.5:
|
||||
v = x
|
||||
return float(v)
|
||||
return f
|
||||
|
||||
|
||||
def at_s(t):
|
||||
"""The cycle second a meter sample at `t` belongs to."""
|
||||
return int(round(t))
|
||||
|
||||
|
||||
def std(dur, *, sun=None, house=None, events=None, race=False, sim=None,
|
||||
first="car", socs=None, **kw):
|
||||
return S.drive(house or const(500.0), sun or const(2900.0), dur=dur,
|
||||
first=first, socs=socs or dict(FULL), events=events,
|
||||
race=race, sim=sim, **kw)
|
||||
|
||||
|
||||
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 attempts(r):
|
||||
"""(second, amps) of every current write that reached Home Assistant,
|
||||
refused ones included."""
|
||||
return [(t, v) for t, e, v in r["plant"].sets if e == SET]
|
||||
|
||||
|
||||
def selects(r):
|
||||
return [x for x in r["sim"].log if x[1] == "phases"]
|
||||
|
||||
|
||||
def act(what, value, out=None, key=None):
|
||||
async def f(p, c):
|
||||
res = await c.handle_action(what, value=value)
|
||||
if out is not None:
|
||||
out[key or what] = res
|
||||
return f
|
||||
|
||||
|
||||
def mqtt_cmd(topic, payload, retained=False):
|
||||
async def f(p, c):
|
||||
await c.mqtt_command(topic, payload, retained)
|
||||
return f
|
||||
|
||||
|
||||
def both(*fns):
|
||||
async def f(p, c):
|
||||
for fn in fns:
|
||||
x = fn(p, c)
|
||||
if asyncio.iscoroutine(x):
|
||||
await x
|
||||
return f
|
||||
|
||||
|
||||
class TSim(SimCharger):
|
||||
"""The model with refusals in time windows of its own clock: (t0, t1,
|
||||
"error" | "ignore")."""
|
||||
|
||||
def __init__(self, *a, windows=(), **kw):
|
||||
super().__init__(*a, **kw)
|
||||
self.windows = list(windows)
|
||||
|
||||
def _mode(self):
|
||||
for t0, t1, kind in self.windows:
|
||||
if t0 <= self.t <= t1:
|
||||
return kind
|
||||
return None
|
||||
|
||||
def request_current(self, a):
|
||||
keep, self.refuse = self.refuse, self._mode() or self.refuse
|
||||
try:
|
||||
return super().request_current(a)
|
||||
finally:
|
||||
self.refuse = keep
|
||||
|
||||
|
||||
def nevers(r, tag, *, clamp=16.0, gap=600.0):
|
||||
"""N1, N2, N5 and N13 over one run: no write above the clamp and no
|
||||
clamp fault; a select only at 0 A with the car under 100 W, one per 600 s;
|
||||
no two non-zero decisions under 30 s apart or under 1 A apart; no
|
||||
Traceback."""
|
||||
bad = []
|
||||
sim, c = r["sim"], r["c"]
|
||||
if c.charger.clamp_faults:
|
||||
bad.append(("N1 clamp fault", c.charger.clamp_faults))
|
||||
for t, what, v, power, sp in sim.log:
|
||||
if what == "current" and v > clamp + 1e-9:
|
||||
bad.append(("N1 over the clamp", t, v))
|
||||
last = None
|
||||
for t, what, v, power, sp in sim.log:
|
||||
if what != "phases":
|
||||
continue
|
||||
if sp > 0.0 or power >= carmode.QUIET_W:
|
||||
bad.append(("N2 select under load", t, sp, power))
|
||||
if last is not None and t - last < gap:
|
||||
bad.append(("N2 two selects", last, t))
|
||||
last = t
|
||||
prev = None
|
||||
for t, a, ok in cur_writes(r):
|
||||
if a <= 0.0:
|
||||
continue
|
||||
if prev is not None and a != prev[1]:
|
||||
if t - prev[0] < carmode.SOLAR_WRITE_S - 1e-9:
|
||||
bad.append(("N5 under 30 s", prev, (t, a)))
|
||||
if abs(a - prev[1]) < carmode.SOLAR_STEP_A:
|
||||
bad.append(("N5 under 1 A", prev, (t, a)))
|
||||
if prev is None or a != prev[1]:
|
||||
prev = (t, a)
|
||||
if LOG.tracebacks(r.get("_log", 0)):
|
||||
bad.append(("N13 Traceback", LOG.tracebacks(r.get("_log", 0))[:1]))
|
||||
check(f"{tag}: N1, N2, N5, N13 hold ({bad[:2]})", not bad)
|
||||
return bad
|
||||
|
||||
|
||||
def run(tag, fn, *a, **kw):
|
||||
n = LOG.mark()
|
||||
r = fn(*a, **kw)
|
||||
r["_log"] = n
|
||||
return r
|
||||
|
||||
|
||||
|
||||
def sets_order(r):
|
||||
return [(t, e, v) for t, e, v in r["plant"].sets]
|
||||
|
||||
|
||||
|
||||
async def _shutdown(p, c):
|
||||
await c.shutdown()
|
||||
|
||||
|
||||
|
||||
def _until(r, t0):
|
||||
"""Seconds from `t0` to the first inverter 0 W at shutdown."""
|
||||
z = [t for t, e, v in r["plant"].sets
|
||||
if e.startswith("number.sp_") and t >= t0 and v == 0.0]
|
||||
return (z[0] - t0) if z else None
|
||||
|
||||
|
||||
|
||||
def _err(p, c):
|
||||
p.ch.error = "12: Socket error"
|
||||
p.ch.fault("E")
|
||||
|
||||
|
||||
|
||||
async def _dies(p, c):
|
||||
async def boom():
|
||||
raise RuntimeError("control died")
|
||||
stop, died = asyncio.Event(), []
|
||||
task = asyncio.ensure_future(boom())
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
app_main.control_task_done(task, controller=c, stop=stop, died=died)
|
||||
p.died = (stop.is_set(), len(died))
|
||||
await c.shutdown()
|
||||
|
||||
|
||||
|
||||
def _freeze_after_write(p, c):
|
||||
p.ch.freeze()
|
||||
|
||||
|
||||
|
||||
class HangPlant(S.SunPlant):
|
||||
"""Home Assistant that never answers a charger write."""
|
||||
hang = False
|
||||
|
||||
async def set_number(self, e, v):
|
||||
if e == SET and self.hang:
|
||||
await asyncio.sleep(3600)
|
||||
return await super().set_number(e, v)
|
||||
|
||||
|
||||
|
||||
|
||||
def report():
|
||||
print(f"\n{'all passed' if not fails else f'{len(fails)} FAILED'}")
|
||||
for f in fails:
|
||||
print(" FAIL:", f)
|
||||
sys.exit(1 if fails else 0)
|
||||
@@ -1,313 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""EV-20: the real Controller on a sunny plant with N batteries and a car.
|
||||
|
||||
python3 tools/ev20_sun.py # mock-up scenario 2, both priorities
|
||||
|
||||
A 1 s cycle, a P1 meter that publishes 0.3 s before each cycle, N batteries
|
||||
each with ITS OWN rating and level (switched On, so the zero-grid loop charges
|
||||
them from the export), and `chargersim.SimCharger` behind the same Home
|
||||
Assistant. The meter sees `house + car - sun - batteries` (battery discharge
|
||||
positive), so the spare sun the add-on computes is `sun - house` whatever it
|
||||
does. A battery at 100 % takes no charge. `events` is `{second: fn(plant, c)}`,
|
||||
run before that cycle. `race=True` uses the production order (read, the writer
|
||||
task settles, then the cycle), as test_ev04.py's `World.step_race`.
|
||||
|
||||
Used by test_ev20.py and test_ev20_long.py. Adapted from EV-05's harness
|
||||
(branch EV-05, never merged), without the peak cut."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import timedelta
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
import opt11_identity as rig # noqa: E402
|
||||
import main_files # noqa: E402
|
||||
from app import packmode # noqa: E402
|
||||
from app.main import Controller # noqa: E402
|
||||
from app.p1 import make_sample, split_signed # noqa: E402
|
||||
from app.store import unit_key # noqa: E402
|
||||
from chargersim import SimCharger # noqa: E402
|
||||
from app import p1 as _p1 # noqa: E402
|
||||
|
||||
SET = "number.wallbox_power_connector_max_current_socket_1"
|
||||
PHASES = "select.wallbox_installation_max_allowed_phases"
|
||||
ALARMS = ("goodwe_peak_saturated", "goodwe_peak_soc_floor")
|
||||
RESPONSE_S = 0.5 # a battery reaches its new command this much later
|
||||
SAMPLE_LEAD_S = 0.3
|
||||
|
||||
|
||||
class SunPlant:
|
||||
"""The house, the sun, N batteries and the charger on one meter."""
|
||||
|
||||
def __init__(self, house, sun, ratings, socs, charger):
|
||||
self.house, self.sun = house, sun
|
||||
self.ratings, self.socs = dict(ratings), dict(socs)
|
||||
self.ch = charger
|
||||
self.t = 0.0
|
||||
self.hists = {u: [(-1e9, 0.0)] for u in self.ratings}
|
||||
self.notes = [] # (t, notification id) raised
|
||||
self.dismissed = []
|
||||
self.sets = [] # (t, entity, value): every number write
|
||||
# Every charger write the model took, as `SimCharger.log` has it but
|
||||
# on THIS clock (the model's own runs ahead while a write waits).
|
||||
self.wlog = []
|
||||
self.meter = 0.0
|
||||
self.meter_on = True # False: the meter stops publishing
|
||||
self.batt_nan = set() # units whose battery figure reads None
|
||||
self.utc_off = 0.0 # the wall clock jumps, the model clock not
|
||||
self.ha_down = False # Home Assistant answers nothing (SAFETY-112)
|
||||
self.response_s = RESPONSE_S # a slow battery takes longer
|
||||
|
||||
def batt_of(self, u, at):
|
||||
w = 0.0
|
||||
for when, v in self.hists[u]:
|
||||
if when <= at:
|
||||
w = v
|
||||
r = self.ratings[u]
|
||||
w = max(-r, min(r, float(round(w))))
|
||||
if self.socs[u] >= 100.0 and w < 0.0:
|
||||
w = 0.0 # a full battery takes no charge
|
||||
return w
|
||||
|
||||
def batt(self, at):
|
||||
return sum(self.batt_of(u, at) for u in self.ratings)
|
||||
|
||||
def grid(self, at):
|
||||
return self.house(at) + self.ch.power_w - self.sun(at) - self.batt(at)
|
||||
|
||||
# -- Home Assistant -----------------------------------------------------
|
||||
async def limits(self, e):
|
||||
return (-5000.0, 5000.0, 1.0)
|
||||
|
||||
async def state(self, entity_id):
|
||||
if self.ha_down:
|
||||
return None
|
||||
return self.ch.states().get(entity_id)
|
||||
|
||||
async def states(self):
|
||||
if self.ha_down:
|
||||
return []
|
||||
return list(self.ch.states().values())
|
||||
|
||||
async def call(self, domain, service, data=None):
|
||||
if self.ha_down:
|
||||
return False
|
||||
if service == "create":
|
||||
self.notes.append((self.t, (data or {}).get("notification_id")))
|
||||
if service == "dismiss":
|
||||
self.dismissed.append((self.t, (data or {}).get("notification_id")))
|
||||
if domain == "select" and service == "select_option":
|
||||
n = 3 if "3" in str((data or {}).get("option")) else 1
|
||||
return self._logged("phases", n, self.ch.request_phases)
|
||||
return True
|
||||
|
||||
def _logged(self, what, v, fn):
|
||||
n0, row = len(self.ch.log), (self.t, what, v, self.ch.power_w,
|
||||
self.ch.setpoint_a)
|
||||
ok = fn(v)
|
||||
if len(self.ch.log) > n0:
|
||||
self.wlog.append(row)
|
||||
return ok
|
||||
|
||||
async def number(self, e, invert=False):
|
||||
if self.ha_down:
|
||||
return None
|
||||
for u in self.ratings:
|
||||
if e == "sensor.soc_" + u:
|
||||
return self.socs[u]
|
||||
if e == "sensor.batt_" + u:
|
||||
return None if u in self.batt_nan else self.batt_of(u, self.t)
|
||||
if e in ("sensor.grid", "sensor.net"):
|
||||
return self.meter
|
||||
return None
|
||||
|
||||
async def set_number(self, e, v):
|
||||
if self.ha_down:
|
||||
return False
|
||||
self.sets.append((self.t, e, float(v)))
|
||||
if e == SET:
|
||||
return self._logged("current", float(v), self.ch.request_current)
|
||||
if e.startswith("number.sp_"):
|
||||
self.hists[e[-1]].append((self.t + self.response_s, float(v)))
|
||||
return True
|
||||
|
||||
|
||||
def drive(house, sun, *, dur=600.0, ratings=None, socs=None, cap=3500.0,
|
||||
margin=100, opts=None, plug=True, setpoint=0, phases=1, mode="solar",
|
||||
first="batteries", events=None, sim=None, store=None, race=False,
|
||||
on_cycle=None, car_phases=3, t0=0.0, caps=None, finale=None,
|
||||
rows=False, plant_cls=None):
|
||||
"""Run it. Returns a dict: plant, controller, charger, notifications with
|
||||
their second, and a per-second trace. `caps` ({unit: kWh}) lets each
|
||||
battery's level move with what it charges or gives; without it the
|
||||
levels stand still. `finale(plant, c)` (a coroutine) runs after the last
|
||||
cycle, on the model clock (a shutdown, for instance); `rows=True` keeps
|
||||
the ids of the amber and red rows of every cycle in the trace."""
|
||||
ratings = ratings or {"a": 5000.0, "b": 4600.0}
|
||||
socs = socs or {u: 50.0 for u in ratings}
|
||||
sim = sim or SimCharger(setpoint_a=setpoint)
|
||||
if plug:
|
||||
sim.plug_in(car_phases=car_phases)
|
||||
sim.phases_allowed = phases
|
||||
units = sorted(ratings)
|
||||
o = rig._options(len(units), dict({
|
||||
"meter_source": "ha_signed", "p1_net_entity": "sensor.net",
|
||||
"meter_phases": 1, "peak_cap_w": cap, "peak_margin_w": margin,
|
||||
"battery_modes_enabled": True,
|
||||
"ev_charger": "alfen_ha", "ev_max_a": 16, "ev_phases": "auto",
|
||||
"ev_current_entity": SET}, **(opts or {})))
|
||||
if len(units) == 1:
|
||||
o["max_w"] = ratings[units[0]]
|
||||
else:
|
||||
o["inverters"] = [dict(x, max_w=ratings[x["name"][-1]])
|
||||
for x in o["inverters"]]
|
||||
store = store or rig._Store()
|
||||
store.data["car_mode"] = mode
|
||||
store.data["car_sun_first"] = first
|
||||
for u in units:
|
||||
store.data[unit_key("inverter-" + u, packmode.USE_KEY)] = True
|
||||
db = os.path.join(tempfile.mkdtemp(prefix="ev20-"), "tariff.db")
|
||||
out = {}
|
||||
events_in = events or {}
|
||||
|
||||
async def go():
|
||||
plant = (plant_cls or SunPlant)(house, sun, ratings, socs, sim)
|
||||
c = Controller(o, plant, store, rig._Pub(), stop=asyncio.Event(),
|
||||
peak_db_path=db)
|
||||
for i in c.inverters:
|
||||
r = ratings[i.name[-1]] if len(units) > 1 else ratings[units[0]]
|
||||
i.dev_min, i.dev_max = -r, r
|
||||
c.auto = True
|
||||
clock = [t0]
|
||||
plant.clock = clock # a finale may move the model clock
|
||||
c.car_now = lambda: clock[0]
|
||||
real_time = _p1.time
|
||||
|
||||
class _Time:
|
||||
"""The meter's age on the model clock, so a silent meter goes
|
||||
stale in model seconds."""
|
||||
def __getattr__(self, k):
|
||||
return getattr(real_time, k)
|
||||
|
||||
@staticmethod
|
||||
def monotonic():
|
||||
return clock[0]
|
||||
_p1.time = _Time()
|
||||
if hasattr(c.charger, "_sleep"):
|
||||
async def sleep(s):
|
||||
sim.tick(s)
|
||||
clock[0] += s
|
||||
plant.t = clock[0]
|
||||
c.charger._sleep = sleep
|
||||
c.charger._clock = lambda: clock[0]
|
||||
real_dt = main_files.live.datetime
|
||||
|
||||
class _DT(real_dt):
|
||||
@classmethod
|
||||
def now(cls, tz=None):
|
||||
return rig.BASE + timedelta(seconds=clock[0] + plant.utc_off)
|
||||
main_files.live.datetime = _DT
|
||||
trace = []
|
||||
try:
|
||||
t = t0
|
||||
while t < t0 + dur:
|
||||
plant.t = clock[0] = t
|
||||
fn = events_in.get(int(t)) if t == int(t) else None
|
||||
if fn is not None:
|
||||
r = fn(plant, c)
|
||||
if asyncio.iscoroutine(r):
|
||||
await r
|
||||
sim.tick(1.0)
|
||||
ts = t - SAMPLE_LEAD_S
|
||||
if plant.meter_on and not plant.ha_down:
|
||||
plant.meter = plant.grid(ts)
|
||||
imp, exp = split_signed(plant.meter)
|
||||
c.p1.submit(make_sample(
|
||||
"ha_signed", imp, exp, phases=1,
|
||||
ingest_ts=rig.BASE + timedelta(seconds=ts),
|
||||
ingest_mono=ts))
|
||||
await c.read_inputs(now_mono=t)
|
||||
if race:
|
||||
await c.car_settle()
|
||||
await c.cycle()
|
||||
else:
|
||||
await c.cycle()
|
||||
await c.car_settle()
|
||||
w = c.car_solar
|
||||
g = c.peak_guard
|
||||
trace.append(dict(
|
||||
t=t, a=w.plan.a, why=w.plan.why, n=w.plan.n,
|
||||
sp=sim.setpoint_a, rb=sim.readback_a,
|
||||
ph=sim.phases_allowed, car=sim.power_w, st=sim.state,
|
||||
grid=plant.grid(t), batt=plant.batt(t),
|
||||
house=plant.house(t), sun=plant.sun(t),
|
||||
explains=c.car_explains, over=c.car_over,
|
||||
lim=bool(g is not None and (g.floor_limited
|
||||
or g.saturated)),
|
||||
floor=(None if g is None else g.floor_w),
|
||||
excess=(None if g is None else g.excess_w),
|
||||
want=(None if g is None else g.wanted_w),
|
||||
socs=dict(plant.socs),
|
||||
proj=(None if g is None else g.projected_w),
|
||||
target=(None if g is None else g.target_w),
|
||||
would=w.would, single=w.single,
|
||||
spare=c.car_spare_w(t), ok=w.plan.ok_since,
|
||||
hold=w.hold, gave_up=w.gave_up, sent=w.sent_a,
|
||||
room=(None if w.sun is None else w.sun.room_w),
|
||||
taken=w.taken,
|
||||
red=[x["id"] for x in c.checks()
|
||||
if x["ok"] is False and not x["warn"]]
|
||||
if on_cycle == "rows" or rows else [],
|
||||
amber=[x["id"] for x in c.checks()
|
||||
if x["ok"] is False and x["warn"]]
|
||||
if rows else [],
|
||||
own=c._car_own_pause(c.car_now()),
|
||||
alarm_w=c.car_alarm_w(), peak_q=dict(c.car_peak_q),
|
||||
other=w.other, mismatch=w.mismatch_since,
|
||||
fails=w.fails, fault=w.fault))
|
||||
if callable(on_cycle):
|
||||
on_cycle(plant, c, t)
|
||||
for u, kwh in (caps or {}).items():
|
||||
# 1 s of W, as a percent of kWh: W / 3600 / (kWh x 1000) x 100
|
||||
lv = plant.socs[u] - plant.batt_of(u, t) / 36000.0 / kwh
|
||||
plant.socs[u] = max(0.0, min(100.0, lv))
|
||||
t += 1.0
|
||||
await c.car_settle()
|
||||
if finale is not None:
|
||||
plant.t = clock[0]
|
||||
await finale(plant, c)
|
||||
finally:
|
||||
main_files.live.datetime = real_dt
|
||||
_p1.time = real_time
|
||||
out.update(plant=plant, c=c, sim=sim, trace=trace, store=store,
|
||||
raised=list(plant.notes), clock=clock)
|
||||
asyncio.run(go())
|
||||
return out
|
||||
|
||||
|
||||
def ids(out, *wanted):
|
||||
return [(t, n) for t, n in out["raised"] if n in wanted]
|
||||
|
||||
|
||||
def writes(out, what="current"):
|
||||
"""(t, value) of every charger write of that kind, in model seconds."""
|
||||
return [(x[0], x[2]) for x in out["sim"].writes(what)]
|
||||
|
||||
|
||||
def const(w):
|
||||
return lambda t: float(w)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.disable(logging.CRITICAL)
|
||||
for first in ("batteries", "car"):
|
||||
r = drive(const(900.0), const(7900.0), dur=600, first=first,
|
||||
socs={"a": 71.0, "b": 100.0})
|
||||
print(f"scenario 2, {first} first: writes {writes(r)} phases "
|
||||
f"{writes(r, 'phases')} batteries {r['plant'].batt(599):.0f} W "
|
||||
f"grid {r['plant'].grid(599):.0f} W")
|
||||
@@ -109,7 +109,7 @@ class Hass:
|
||||
# real `Controller._read_charger()` reads it, so the card is what the add-on
|
||||
# draws, not a picture.
|
||||
CAR_STATES = ("car", "car_none", "car_waiting", "car_full", "car_unreach",
|
||||
"car_setup", "car_manual_cover", "car_manual_over")
|
||||
"car_setup")
|
||||
CAR_ENTITY = "number.wallbox_power_connector_max_current_socket_1"
|
||||
SIM = SimCharger()
|
||||
|
||||
@@ -126,7 +126,7 @@ def car_setup(state):
|
||||
"""Put the model in the state's situation."""
|
||||
global SIM
|
||||
SIM = SimCharger(name="other" if state == "car_setup" else "wallbox")
|
||||
if state in ("car", "car_unreach", "car_manual_cover", "car_manual_over"):
|
||||
if state in ("car", "car_unreach"):
|
||||
SIM.plug_in()
|
||||
SIM.set_phases(3)
|
||||
SIM.set_current(16)
|
||||
@@ -332,27 +332,6 @@ def controller(state):
|
||||
for inv in c.inverters:
|
||||
inv.batt = 0.0
|
||||
c.car.stale_s = 15.0
|
||||
if state in ("car_manual_cover", "car_manual_over"):
|
||||
# EV-04, Manual at 16 A on 3 phases. First moment: the batteries give
|
||||
# 5 kW and the period stays on the aim. Second: they are at the peak
|
||||
# reserve, so the charge you set sets the month's peak.
|
||||
c.car_mode, c.car_a, c.car_n = "manual", 16.0, 3
|
||||
if state == "car_manual_cover":
|
||||
c.pv_w, c.grid = 4100.0, 3450.0
|
||||
for inv in c.inverters:
|
||||
inv.batt = 2500.0
|
||||
c.peak_guard = PeakDecision(
|
||||
engaged=True, floor_w=3000.0, ceiling_w=3500.0,
|
||||
ceiling_from="cap", projected_w=3450.0, excess_w=1500.0)
|
||||
else:
|
||||
c.pv_w, c.grid = 2400.0, 10200.0
|
||||
for inv in c.inverters:
|
||||
inv.soc, inv.batt = 19.0, 0.0
|
||||
c.peak_guard = PeakDecision(
|
||||
engaged=True, floor_w=0.0, ceiling_w=3500.0,
|
||||
ceiling_from="cap", projected_w=10200.0, excess_w=6750.0,
|
||||
floor_limited=True, soc=19.0, soc_floor=20.0)
|
||||
c.car_over = c.car_explains = True
|
||||
if state == "alarm":
|
||||
c.inverters[0].sign_wd.tripped = True
|
||||
if state in P3:
|
||||
|
||||
@@ -285,7 +285,7 @@ configuration:
|
||||
description: "The add-on makes every decision but keeps every inverter at 0 W. 'auto' does this while control is stopped, 'on' always, 'off' never."
|
||||
ev_charger:
|
||||
name: "Car charger · Charger"
|
||||
description: "Which car charger the add-on drives. Off leaves everything as it is. In Off mode the add-on only reads the charger and never changes it."
|
||||
description: "Which car charger the add-on reads. Off leaves everything as it is. This version only reads the charger and never changes it."
|
||||
ev_current_entity:
|
||||
name: "Car charger · Current setting entity"
|
||||
description: "The entity that sets the charger's current. The add-on finds the charger's other entities from its name."
|
||||
@@ -295,21 +295,6 @@ configuration:
|
||||
ev_phases:
|
||||
name: "Car charger · Phases"
|
||||
description: "How many phases the charger may use: 1, 3, or 1 and 3 (auto)."
|
||||
ev_batt_cover:
|
||||
name: "Car charger · Batteries help with the peak"
|
||||
description: "While the car charges. On: the batteries cover it down to the peak reserve. Off: the peak guard leaves the car out, so the car alone can set the peak."
|
||||
ev_mode_start:
|
||||
name: "Car charger · Mode after a restart"
|
||||
description: "Keep the last mode, or start in Off. A restart in Solar sets the charger to 0 A first, other modes leave its current."
|
||||
ev_margin_w:
|
||||
name: "Car charger · Sun kept back (W)"
|
||||
description: "Solar: this much spare sun is never given to the car."
|
||||
ev_start_min:
|
||||
name: "Car charger · Start after (minutes)"
|
||||
description: "Solar: the car starts after this long with enough spare sun."
|
||||
ev_pause_min:
|
||||
name: "Car charger · Pause after (minutes)"
|
||||
description: "Solar: with too little sun the car holds 6 A this long, then pauses."
|
||||
auto_start:
|
||||
name: "Advanced · Start control on boot"
|
||||
description: "Off by default. Leave it off until the site is commissioned, so someone presses Start after each restart."
|
||||
|
||||
@@ -266,7 +266,7 @@ configuration:
|
||||
description: "De add-on neemt elke beslissing maar houdt elke omvormer op 0 W. 'auto' doet dit zolang de regeling gestopt is, 'on' altijd, 'off' nooit."
|
||||
ev_charger:
|
||||
name: "Laadpaal · Laadpaal"
|
||||
description: "Welke laadpaal de add-on stuurt. Uit laat alles zoals het is. In modus Uit leest de add-on de laadpaal alleen en wijzigt niets."
|
||||
description: "Welke laadpaal de add-on leest. Uit laat alles zoals het is. Deze versie leest de laadpaal alleen en wijzigt niets."
|
||||
ev_current_entity:
|
||||
name: "Laadpaal · Entiteit van de laadstroom"
|
||||
description: "De entiteit die de stroom van de laadpaal instelt. De add-on vindt de andere entiteiten van de laadpaal via de naam."
|
||||
@@ -276,21 +276,6 @@ configuration:
|
||||
ev_phases:
|
||||
name: "Laadpaal · Fasen"
|
||||
description: "Hoeveel fasen de laadpaal mag gebruiken: 1, 3, of 1 en 3 (auto)."
|
||||
ev_batt_cover:
|
||||
name: "Laadpaal · Batterijen helpen met de piek"
|
||||
description: "Terwijl de auto laadt. Aan: de batterijen dekken ze tot de piekreserve. Uit: de piekbewaking laat de auto buiten beschouwing, dus de auto alleen kan de piek bepalen."
|
||||
ev_mode_start:
|
||||
name: "Laadpaal · Modus na een herstart"
|
||||
description: "De laatste modus houden, of starten in Uit. Een herstart in Zon zet de laadpaal eerst op 0 A, andere modi laten haar stroom."
|
||||
ev_margin_w:
|
||||
name: "Laadpaal · Zon achtergehouden (W)"
|
||||
description: "Zon: zoveel zonne-overschot krijgt de auto nooit."
|
||||
ev_start_min:
|
||||
name: "Laadpaal · Starten na (minuten)"
|
||||
description: "Zon: de auto start na zo lang genoeg zonne-overschot."
|
||||
ev_pause_min:
|
||||
name: "Laadpaal · Pauzeren na (minuten)"
|
||||
description: "Zon: met te weinig zon houdt de auto zo lang 6 A en pauzeert dan."
|
||||
auto_start:
|
||||
name: "Geavanceerd · Regeling starten bij opstarten"
|
||||
description: "Staat standaard uit. Laat het uit tot de installatie in dienst is, zodat iemand na elke herstart op Start drukt."
|
||||
|
||||
Reference in New Issue
Block a user