Compare commits

..
25 Commits
Author SHA1 Message Date
Claude d18ed56fad EV-20: T4 through the Controller, T21 (a) on car_cycle itself
checks / unit (pull_request) Waiting to run
infra-pin / fresh (pull_request) Waiting to run
T4: battery A's power missing, NaN or unavailable, for one cycle (no
write) and for 400 s (no spare, the current held, 0 A at 300 s).
T21 (a): car_cycle on the same projection, guard and reading gives the
same car figure, explains and over in Solar and Manual.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-22 20:47:58 +01:00
Claude 226e5a1e8b EV-20: Car Solar mode, spare sun to the car (charging only)
infra-pin / fresh (pull_request) Waiting to run
checks / unit (pull_request) In progress
Solar as a second writer next to Manual (carmode.SolarPlan, SolarWriter on
ManualWriter's one write site, safe phase sequence and other-writer watch):
signed spare, Batteries first on the batteries' ratings, the margin, whole
amps rounded down, the 30 s / 1 A rule, start and pause dwells, auto phases,
a one-phase car. Every way out ends at 0 A, retried by EV-04's rule; at
shutdown before the inverters, three tries inside 15 s (D3); start-up and a
returning charger or HA write 0 A first (D2); never over another writer's
hold. The peak guard treats a Solar car as a Manual car (D1 wording). Solar
kWh sensor and card line; select.goodwe_car_sun_first; ev_margin_w,
ev_start_min, ev_pause_min with config, validator, translations, DOCS,
DECISIONS and CHANGELOG.

Checks: test_ev20.py, test_ev20_exits.py, test_ev20_writers.py,
test_ev20_guard.py, test_ev20_long.py, test_ev20_long_car.py,
test_ev20_fuzz.py (harness tools/ev20_sun.py, ev20_kit.py, ev20_day.py);
test_ev03/test_ev04 no longer use Solar as the refused example.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-22 20:31:26 +01:00
ems-agent 885528ab48 Merge pull request 'EV-14: Car Why says what happens in shadow mode and after an abandoned phase change' (#270) from EV-14 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-22 15:52:30 +01:00
Claude 9987a32424 EV-14 review: T1 phases check (shadow-over phases come from would)
checks / unit (pull_request) Successful in 26m36s
infra-pin / fresh (pull_request) Successful in 1s
Kills the surviving mutant 'shadow-over phases from car_n'.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-22 15:25:32 +01:00
Claude b66ce68d4d EV-14: T33 reads the raw nl words; T29 carries a would
checks / unit (pull_request) Successful in 34m43s
infra-pin / fresh (pull_request) Successful in 1s
2026-11-22 13:50:40 +01:00
Claude d0285470cb EV-14: Car Why says what happens in shadow mode and after a phase change that did not happen
Display only: shadow mode over-limit Why speaks in would-terms; read phases that
differ from the setting say the charger stays; a writer hold says something
else set the charger. EN and NL texts, test_ev14.py.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-22 13:45:30 +01:00
ems-agent c8f529273f Merge pull request 'EV-13: a refused current write shows one amber row' (#269) from EV-13 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-22 12:09:19 +01:00
Claude 6cd775788d EV-13 review round 2: tie the driver's polls to the cycle reading per phase (D1, D2)
checks / unit (pull_request) Successful in 30m36s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-22 10:45:14 +01:00
Claude 57a9f56a64 EV-13: guard the P4 live check's last sample (test_named_absence)
infra-pin / fresh (pull_request) Successful in 2s
checks / unit (pull_request) Successful in 27m17s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-22 07:58:56 +01:00
Claude 0774d1efd5 EV-13 router round 3: N2 names P1/P2; P4 live window dated the send; kills R1
checks / unit (pull_request) Failing after 58m19s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-22 06:54:30 +01:00
Claude 5ebd830966 EV-13 review: compare phase currents per phase; test a late read-back
checks / unit (pull_request) Successful in 26m23s
infra-pin / fresh (pull_request) Successful in 1s
A phase that drops out or comes back shifted the compressed current_a tuple and
read as life, so a frozen charger never armed. ChargerReading.phase_a keeps
L1/L2/L3 with None for a missing phase and the life test uses it.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-22 05:44:31 +01:00
Claude 1b39f1698a EV-13 router round 1: lapse a refusal's window on unavailable readings; T27, T28 and the N-ids
checks / unit (pull_request) Successful in 31m40s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-22 03:56:53 +01:00
Claude c3903b796b EV-13: CHANGELOG line and DECISIONS note
checks / unit (pull_request) Successful in 33m25s
infra-pin / fresh (pull_request) Successful in 1s
Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-22 02:23:56 +01:00
Claude c25877fea4 EV-13: a refused current write arms the stuck check only when the charger shows no life
A refused write on a live charger no longer reads as a stuck reading 60 s
later, so a refused write shows one amber row (charger_refused). A frozen
charger still arms and is still caught.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VSY9UpTaUYnjJF5oVtbM1w
2026-11-22 01:50:44 +01:00
ems-agent 76f4de23c7 Merge pull request 'EV-28: no phase select while the car still draws' (#268) from EV-28 into release/1.0
infra-pin / fresh (push) Successful in 1s
2026-11-21 23:28:03 +01:00
Claude (review agent) 4b4a4c1053 EV-28 review: pin the restore step in T17a and the counted failure in T15
checks / unit (pull_request) Successful in 28m34s
infra-pin / fresh (pull_request) Successful in 1s
Review fixes, no logic change:
- T17a now asserts the restore is the first write once the charger is back
  (it was only checked to happen at some point); mutant M3 (restore after
  SETTLE_S) now turns T17a red.
- T15 now asserts the refused restore is counted once (`fails == 1`);
  a mutant without `_failed` there now turns T15 red.
- DECISIONS "The phase sequence" and the carmode docstring reflowed to 79
  columns; DECISIONS says D counts as drawing too, as the code does.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 22:58:56 +01:00
Claude (dev agent) 83f114fe08 EV-28: never select the phases while the car still draws
checks / unit (pull_request) Successful in 32m4s
infra-pin / fresh (pull_request) Successful in 1s
Stage zero counted mode3 B as quiet whatever the power and selected at the
20 s timeout under load. A power reading now decides (under 100 W); mode3
(not C, not D) only without one. Still drawing at 20 s: no select, the
current comes back at once, one failed try, next try PHASE_GAP_S later.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 21:04:13 +01:00
ems-agent 4eba2d9acf Merge pull request 'CI-20: bump infra-pin to f884612' (#267) from CI-20 into release/1.0
infra-pin / fresh (push) Successful in 2s
2026-11-21 19:37:59 +01:00
Claude af374026b1 CI-20: bump infra-pin to admin/goodwe release/1.0 f884612
checks / unit (pull_request) Successful in 26m51s
infra-pin / fresh (pull_request) Successful in 2s
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 18:33:08 +01:00
admin 00b116e5b2 Merge pull request 'EV-16: hold the Car Why text while the guard floor flag toggles' (#266) from EV-16 into release/1.0
infra-pin / fresh (push) Failing after 1s
2026-11-21 16:08:07 +01:00
EV-16 reviewerandClaude 91cbdf2f43 EV-16 review round 2: pin the unread-SoC rule on the Why's live fallback
checks / unit (pull_request) Successful in 24m26s
infra-pin / fresh (pull_request) Failing after 2s
The fallback (no record yet, or a record of an ended episode) had no check;
reading floor_limited alone there survived test_ev16. Test only.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 12:37:06 +01:00
Claude (dev) c707eb4776 EV-16: time the Car Why hold on the control cycle, not on page reads
checks / unit (pull_request) Successful in 24m55s
infra-pin / fresh (pull_request) Failing after 1s
car_cycle ends with _car_why_tick (display only: control writes, never reads);
the Why reads the record. Adds read-gap tests (A, B, cover off/on), a long
guard-None test and a lower bound for the hold.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 11:23:13 +01:00
Claude (dev) b662d7171b EV-16: key the held Car Why to the car_over episode; add T16, T18 and N-id checks
checks / unit (pull_request) Successful in 25m43s
infra-pin / fresh (pull_request) Failing after 2s
Control bumps _car_over_ep at each start and end of car_over; the display
ignores a hold of another episode, so a read overlapping the end cannot bring
a stale text back.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 10:04:00 +01:00
Claude (dev) 3b1189cdbf EV-16: hold the Car Why text while car_over holds and the guard floor flag toggles
checks / unit (pull_request) Successful in 27m49s
infra-pin / fresh (pull_request) Failing after 2s
Display only: the 'are at' / 'give all they can' text changes only when the
other state has stood for 180 s (the car_over off hold); SoC unread is never
'are at'. Cleared when car_over drops, on unplug and with cover off.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-21 08:54:04 +01:00
admin 8150608317 Merge pull request 'EV-19: no floor alarm when the batteries first reach the reserve early in a Manual car session' (#265) from EV-19 into release/1.0
infra-pin / fresh (push) Failing after 1s
Reviewed-on: #265
2026-11-20 23:42:30 +01:00
41 changed files with 8575 additions and 155 deletions
+3 -1
View File
@@ -49,10 +49,12 @@ 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_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"
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"
#
JOBS=${CI_JOBS:-10}
cd "${TESTS_DIR:-/w/goodwe-addon/goodwe_controller}"
+1 -1
View File
@@ -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").
3b4ff84757f9c2c5b63a4b4a53e593ccaeafb847
f88461234f3a7d53c025a68beda4cb6e4384cebf
+3
View File
@@ -2,6 +2,9 @@
### 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
@@ -30,12 +30,14 @@ code had to decide that the design left open.
## The phase sequence
0 A, wait until the charger reports under 100 W or mode3 leaves C (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 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`).
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
@@ -62,6 +64,16 @@ 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),
@@ -0,0 +1,90 @@
# 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.
+73 -10
View File
@@ -256,7 +256,10 @@ The label and description each setting shows on the Configuration tab, in tab or
| 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 never changes the charger's current. |
| 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. |
@@ -3278,9 +3281,10 @@ it.
### Car charger
The add-on can drive your car charger and shows it on **Home**, on a *Car* card.
The card has two modes in this version: **Off** (the add-on only reads the
charger and writes nothing) and **Manual** (the add-on sets the current and the
phases you choose). Solar and Night modes come in later versions.
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.
| option | meaning |
|---|---|
@@ -3290,6 +3294,9 @@ phases you choose). Solar and Night modes come in later versions.
| `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
@@ -3299,7 +3306,7 @@ 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), `number.goodwe_car_current`
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.
@@ -3320,6 +3327,56 @@ checks within 10 seconds that the charger took it.
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
@@ -3365,8 +3422,7 @@ charger* shows for an hour after a change. That is expected while you migrate.
current your helper held (`input_number.ev_manual_current`). 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. (Solar comes in a later version; until then keep
Manual or Off.)
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.
@@ -3377,8 +3433,8 @@ off before you choose Manual, and the add-on off (mode Off) before you turn the
automation on.
**Home Assistant entities.** With MQTT the add-on adds the sensors
`goodwe_car_power`, `goodwe_car_state` and `goodwe_car_today_kwh`, and the three
controls named above. A saved ("retained") command is never applied, so a
`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.
### Site
@@ -3514,7 +3570,14 @@ 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.
current. In Solar it says "Solar charges the car at {a} A, which sets the
peak.": the same case, with the current the charger has.
### Car 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
+721 -17
View File
@@ -15,31 +15,43 @@ THE RULES, each tested in test_ev04.py:
reports, the entity's own range)`. The driver refuses anything above it; this
module never asks for more.
* Phases change only through the SAFE SEQUENCE: 0 A, wait until the charger
reports under `QUIET_W` or mode3 leaves C (at most `ZERO_WAIT_S`), select the
phases, wait `SETTLE_S`, write the current again. At most one switch per
`PHASE_GAP_S`. A sequence that has begun is always finished, because it
leaves the car at 0 A otherwise.
reports under `QUIET_W` (mode3 leaving C only without a power reading; at
most `ZERO_WAIT_S`, then the current comes back and it counts as a failed
try), select the phases, wait `SETTLE_S`, write the current again. At most
one switch per `PHASE_GAP_S`. A sequence that has begun is always finished,
because it leaves the car at 0 A otherwise.
* A read-back that differs from the add-on's own last write for `WRITER_S` is
ANOTHER WRITER: an info row, and no write over it until the user changes the
mode or a value again.
* A charger that comes back after being unavailable gets the setting again only
if its read-back differs.
EV-20 adds Solar (`SolarPlan`, `SolarWriter`, below): spare sun to the car,
charging only. DECISIONS/EV-20-solar-mode.md.
"""
from __future__ import annotations
import asyncio
import logging
import math
from . import chargers as CH
_LOG = logging.getLogger("goodwe")
OFF, MANUAL = "off", "manual"
#: the modes this card offers. Solar and Night are later cards (EV-05, EV-02).
MODES = (OFF, MANUAL)
OFF, MANUAL, SOLAR = "off", "manual", "solar"
#: the modes offered. Night is a later card (EV-02).
MODES = (OFF, MANUAL, SOLAR)
#: Home Assistant's select labels, English and pinned.
MODE_LABELS = {OFF: "Off", MANUAL: "Manual"}
MODE_LABELS = {OFF: "Off", MANUAL: "Manual", SOLAR: "Solar"}
START_KEEP, START_OFF = "keep", "off"
#: EV-20: where Solar's spare sun goes first, runtime state in the store.
FIRST_BATT, FIRST_CAR = "batteries", "car"
FIRSTS = (FIRST_BATT, FIRST_CAR)
FIRST_LABELS = {FIRST_BATT: "Batteries", FIRST_CAR: "Car"}
DEFAULT_FIRST = FIRST_BATT
KEY_FIRST = "car_sun_first"
KEY_MODE, KEY_A, KEY_PHASES = "car_mode", "car_current", "car_phases"
DEFAULT_A = 6.0
@@ -249,14 +261,15 @@ class ManualWriter:
"the add-on set %.0f A), so the add-on stops writing "
"to it until you change it.", cur, known[0])
async def _write(self, drv, a, was, now, tracker) -> bool:
async def _write(self, drv, a, was, now, tracker, **kw) -> bool:
tracker.begin_write() # EV-12: the read-back is ours
try:
ok = await drv.write_current(a)
# EV-20: `kw` is only Solar's shorter read-back wait at shutdown.
ok = await drv.write_current(a, **kw)
finally:
self._stamp(now)
tracker.end_write(self.last_done)
tracker.note_write(now, was, a)
tracker.note_write(now, was, a, ok, getattr(drv, "polls", ()))
tracker.end_write(self.last_done)
self.log.append(("current", a, now, ok))
if ok:
@@ -333,11 +346,29 @@ class ManualWriter:
"phase change, so the phases were not touched.")
return
if q["stage"] == "zero":
quiet = ((r.power_w is not None and r.power_w < QUIET_W)
or (r.state is not None and r.state != "C"))
if not quiet and now - q["t0"] < ZERO_WAIT_S:
return
q["stage"] = "select"
# A power reading decides; only without one does mode3 (not C,
# not D) say the car is quiet. Still drawing at the timeout: no
# select, the current comes back (EV-28).
if r.power_w is not None:
quiet = r.power_w < QUIET_W
else:
quiet = r.state is not None and r.state not in ("C", "D")
if not quiet:
if now - q["t0"] < ZERO_WAIT_S:
return
self.last_switch = now
self.phase_fails += 1
q["failed"] = True # EV-15: no grace for the alarm
q["stage"], q["t1"] = "settle", now - SETTLE_S # restore now
_LOG.warning("The car kept drawing, so the phases were not "
"changed.")
if self.phase_fails >= MAX_TRIES:
self.phases_gave_up = True
_LOG.warning("The charger did not take the phases, so the "
"add-on stops trying until you change "
"something: CHARGER_PHASES.")
else:
q["stage"] = "select"
if q["stage"] == "select":
ok = await drv.write_phases(q["n"])
self._stamp(now)
@@ -360,7 +391,10 @@ class ManualWriter:
if now - q["t1"] < SETTLE_S:
return
hi = CH.ENTITY_MAX_A if clamp is None else float(clamp)
a = min(max(float(want_a), CH.MIN_A), hi)
# EV-20: Solar hands a function of the sequence (its current depends
# on whether the phases changed); Manual a number, as before.
want = want_a(q) if callable(want_a) else want_a
a = min(max(float(want), CH.MIN_A), hi)
if await self._write(drv, a, 0.0, now, tracker):
# Judged afresh next cycle: a value the user changed meanwhile is
# still wanted, and one that is in place is adopted.
@@ -378,3 +412,673 @@ class ManualWriter:
self.rev_applied = None
return
q["t1"] = now - SETTLE_S + 5.0 # again in 5 s
# =========================================================================== #
# EV-20: Solar. `SolarPlan` decides what the car should get from the spare sun;
# `SolarWriter` makes the charger match it through ManualWriter's write, phase
# sequence and other-writer watch. DECISIONS/EV-20-solar-mode.md.
# =========================================================================== #
VOLTS = 230.0 # per phase: what an amp is worth in watts
SOLAR_WRITE_S = 30.0 # at most one current change per this ...
SOLAR_STEP_A = 1.0 # ... and only on a change of this or more
UP_W, UP_S = 4500.0, 180.0 # auto phases: to 3 at this for this long
DOWN_W, DOWN_S = 4000.0, 300.0 # ... back to 1 under this for this long
ONE_PHASE_S = 10.0 # one phase drawing while 3 are allowed this long
ONE_PHASE_MIN_W = 500.0 # ... with the car drawing at least this
# D3: at shutdown the 0 A is tried this many times, this far apart, each
# waiting this long for its read-back: inside `ctl_car.RELEASE_WAIT_S`.
RELEASE_TRIES = 3
RELEASE_GAP_S = 5.0
RELEASE_TOOK_S = 4.0
def _num(v):
try:
f = float(v)
except (TypeError, ValueError):
return None
return f if math.isfinite(f) else None
def spare_w(car_w, batt_w, grid_w):
"""The spare sun, SIGNED and not clipped: `car + battery charge - grid
import`, which is the solar production less the house. `batt_w` is the
add-on's site battery figure (discharge positive), so it is subtracted.
A grid charge of the batteries, or batteries giving more than the house
uses, is never spare sun. None when a figure is missing or not a number."""
c, b, g = _num(car_w), _num(batt_w), _num(grid_w)
if c is None or b is None or g is None:
return None
return c - b - g
def car_target_w(spare, room_w, margin_w, first):
"""What the car may take: Batteries first `spare - room - margin`, Car
first `spare - margin`. None while the spare is unknown."""
s = _num(spare)
if s is None:
return None
room = float(_num(room_w) or 0.0) if first == FIRST_BATT else 0.0
return s - room - float(_num(margin_w) or 0.0)
def amps_for(car_w, n, clamp=None):
"""Whole amps for `car_w` on `n` phases, ROUNDED DOWN, never above the
clamp, never below 0. None for a figure that is not a number."""
w = _num(car_w)
if w is None or n not in (1, 3):
return None
a = math.floor(w / (VOLTS * n) + 1e-9)
hi = CH.ENTITY_MAX_A if _num(clamp) is None else float(clamp)
return float(max(0, min(a, math.floor(hi))))
def solar_option(opts: dict, key: str) -> float:
"""`ev_margin_w`, `ev_pause_min` or `ev_start_min` as a number; the shipped
default when it is not one (the validator refuses it anyway)."""
v = _num((opts or {}).get(key))
return float(CH.EV_OPTION_DEFAULTS[key]) if v is None else v
class SunInputs:
"""One cycle's inputs for Solar, built by the Controller."""
def __init__(self, target_w=None, hold=False, auto=True, start_s=120.0,
pause_s=300.0, spare_w=None, room_w=0.0, margin_w=100.0,
first=DEFAULT_FIRST):
self.target_w, self.hold, self.auto = target_w, hold, auto
self.start_s, self.pause_s = start_s, pause_s
self.spare_w, self.room_w, self.margin_w = spare_w, room_w, margin_w
self.first = first
class SolarPlan:
"""What Solar wants set, one `step()` per cycle. Pure: monotonic `now`
from the caller and no driver, so shadow mode runs it the same and the
card says what it would set. `a` is the current wanted (0: paused), `n`
the phases it is meant for; `switch` is a phase change it decided that
the writer has not finished."""
def __init__(self, n=1):
self.reset(n)
def reset(self, n=1, why="paused"):
self.a = 0.0
self.n = n if n in (1, 3) else 1
self.switch = False
self.set_at = None # the latest non-zero change (30 s rule)
self.ok_since = None # enough sun to start, since
self.low_since = None # under 6 A worth, holding 6 A, since
self.unknown_since = None # the spare cannot be measured, since
self.up_since = self.down_since = None
self.why = why
self.target_w = None
self._before = None # the state before a phase change
def pause(self, why="paused"):
self.a = 0.0
self.switch, self._before = False, None
self.ok_since = self.low_since = self.unknown_since = None
self.up_since = self.down_since = None
self.why = why
def _gate(self, now) -> bool:
return self.set_at is None or now - self.set_at >= SOLAR_WRITE_S
def _set(self, a, now, n=None):
if n is not None and n != self.n:
self._before = (self.a, self.n, self.set_at, self.low_since,
self.why)
self.n, self.switch = n, True
self.a, self.set_at, self.why = float(a), now, "running"
self.ok_since = self.low_since = None
self.up_since = self.down_since = None
def end_switch(self, done: bool) -> None:
"""The writer finished (`done`) or gave up the phase change. Given up,
the plan is back where it was before it: its current for the old
phases, its hold count (N3), so nothing meant for the new phases is
written on the old ones."""
if self.switch and not done and self._before is not None:
self.a, self.n, self.set_at, self.low_since, self.why = \
self._before
self.switch, self._before = False, None
def step(self, now, *, target_w, n_now, auto, clamp, start_s, pause_s,
hold=False, gap_ok=True):
"""`n_now`: the phases the car draws on now (1 for a one-phase car);
`auto`: Solar may choose the phases; `gap_ok`: a phase change is
allowed now (EV-04's one per `PHASE_GAP_S`); `hold`: readings late
under the stale bound, everything stands."""
if hold:
# Readings late under the stale bound: nothing changes, but a
# hold or an unknown spare that has run its time still pauses
# (N3: never 6 A past `pause_s`, however often the verdict
# comes back).
if self.a > 0.0 and any(
since is not None and now - since >= pause_s
for since in (self.low_since, self.unknown_since)):
self.pause("unknown")
return
self.target_w = target_w
if not self.switch and n_now in (1, 3):
self.n = n_now # the phases are what the charger has
if target_w is None: # the sun cannot be measured: hold, then 0
self.ok_since = None
if self.a > 0.0:
if self.unknown_since is None:
self.unknown_since = now
# A hold that began on a known low spare still ends on time.
if now - self.unknown_since >= pause_s or (
self.low_since is not None
and now - self.low_since >= pause_s):
self.pause("unknown")
else:
self.why = "unknown"
return
self.unknown_since = None
if self.a <= 0.0: # paused: the start rule
n0 = 1 if auto else self.n
if target_w >= (CH.MIN_A + 1.0) * VOLTS * n0:
if self.ok_since is None:
self.ok_since = now
self.why = "start"
if now - self.ok_since >= start_s \
and (n0 == self.n or gap_ok):
a = amps_for(target_w, n0, clamp)
if a is not None and a >= CH.MIN_A:
self._set(a, now, n0)
else:
self.ok_since = None
self.why = "paused"
return
hi = None if _num(clamp) is None else math.floor(float(clamp))
if hi is not None and self.a > hi: # the clamp came down
if hi < CH.MIN_A:
self.pause()
return
self.a, self.set_at = float(hi), now
if auto and not self.switch: # auto phases, by dwells
if self.n == 1:
self.down_since = None
if target_w >= UP_W:
if self.up_since is None:
self.up_since = now
else:
self.up_since = None
if self.up_since is not None and now - self.up_since >= UP_S \
and gap_ok and self._gate(now):
a = amps_for(target_w, 3, clamp)
if a is not None and a >= CH.MIN_A:
self._set(a, now, 3)
return
else:
self.up_since = None
if target_w < DOWN_W:
if self.down_since is None:
self.down_since = now
else:
self.down_since = None
if self.down_since is not None \
and now - self.down_since >= DOWN_S \
and gap_ok and self._gate(now):
a = amps_for(target_w, 1, clamp)
if a is not None and a >= CH.MIN_A:
self._set(a, now, 1)
return
want = amps_for(target_w, self.n, clamp)
if want is not None and want >= CH.MIN_A:
self.low_since = None
self.why = "running"
if abs(want - self.a) >= SOLAR_STEP_A and self._gate(now):
self.a, self.set_at = want, now
return
if auto and self.n == 3 and target_w >= DOWN_W and not self.switch:
# Inside the phase hysteresis (4.0 kW up to 6 A on 3 phases): 6 A
# on 3 phases stands until the down dwell, with no pause count.
self.low_since = None
self.why = "running"
if self.a != CH.MIN_A and self._gate(now):
self.a, self.set_at = CH.MIN_A, now
return
if self.low_since is None:
self.low_since = now
self.why = "hold"
if now - self.low_since >= pause_s:
self.pause()
return
if self.a != CH.MIN_A and self._gate(now):
self.a, self.set_at = CH.MIN_A, now
class SolarWriter(ManualWriter):
"""What Solar does to the charger, one `step()` per cycle. It shares
ManualWriter's write, phase sequence and other-writer watch.
ONE RULE FOR EVERY WRITE (EV-05 review rounds 2-9): Solar writes a value
when it DECIDES a new one (`sent_a` differs), and tries a value the
charger did not take again after `RETRY_S`, `MAX_TRIES` times, then the
gave-up row and warning. A read-back that shows the value Solar sent
confirms it, however late (`_adopt`). A read-back that differs from what
Solar sent is never written over: `_watch` judges it (EV-04's 30 s
other-writer rule), and while its hold stands nothing at all is written.
WAYS OUT (Off, Stop, shadow, a safety stop, a charger error or stuck
reading, no car, shutdown) write 0 A only while Solar's own current may
stand on the charger (`live`): a non-zero value it sent, or a 0 A not yet
confirmed. Once that 0 A is confirmed nothing more is written, and a
start in shadow or with control stopped writes nothing. THE START-UP and
a charger (or Home Assistant) that comes back write 0 A first whatever the
charger shows, then the start rule (D2). An interrupted phase change ends
at the 0 A it began with; nothing is restored."""
def __init__(self):
super().__init__()
self.plan = SolarPlan()
self.engaged = False # Solar ran since it was chosen
self.sent_a = None # the current Solar last decided to write
self.taken = True # ... and the charger confirmed it
self.fresh_start = True # start-up or back: 0 A first (D2)
self.restart = True # writing again: the plan starts paused
self.out = False # not writing now (shadow, Stop, latch)
self.fault = None # "error" | "stuck" while it stands
self.single = False # a one-phase car on a 3-phase allowance
self._one_since = None
self.zero_at = None # EV-15: our own latest 0 A was sent then
self.sun = None # the last `SunInputs`, for the card
self._would_n = None # shadow: the phases the plan believes
self._would_switch = None # ... and when it last changed them
self.released = None # D3: True / False once shutdown tried
self.mode_was = None # the mode of the previous step
# ------------------------------------------------------------- state
@property
def live(self) -> bool:
"""May a current of Solar's own stand on the charger? A non-zero value
it sent (taken or not), or a 0 A not yet confirmed. Only then does a
way out write its 0 A."""
return self.sent_a is not None and (self.sent_a > TOL_A
or not self.taken)
@property
def zero_owed(self) -> bool:
"""A way-out 0 A the charger has not confirmed yet (for the card)."""
return bool(self.engaged and self.sent_a is not None
and self.sent_a <= TOL_A and not self.taken
and not self.hold)
def amps_out(self, clamp) -> float:
"""The plan's current, never above the clamp; 0 when under 6 A."""
a = float(self.plan.a)
if _num(clamp) is not None:
a = min(a, float(math.floor(float(clamp))))
return a if a >= CH.MIN_A else 0.0
def user_changed(self) -> None:
"""The user PRESSED SOLAR: another writer's hold is lifted and Solar
takes the charger as it is (its value is no longer a difference);
Solar's own value is decided and written afresh."""
held = self.hold or self.mismatch_since is not None
super().user_changed()
self.gave_up, self.fails, self.fail_at = False, 0, None
if held:
self.last_a = None
self.sent_a, self.taken = None, True
# ------------------------------------------------------------- writes
async def _write(self, drv, a, was, now, tracker, **kw) -> bool:
"""ManualWriter's one write site. What Solar SENT is recorded before
the write goes out, so a write cancelled while it waits for its
read-back is never trusted (`live`)."""
self.sent_a, self.taken = float(a), False
zero = float(a) <= TOL_A
if zero:
self.zero_at = self.zero_sent_at = now
try:
ok = await super()._write(drv, a, was, now, tracker, **kw)
finally:
if zero:
self.zero_sent_at = None
if ok:
self.taken = True
self.fails, self.fail_at, self.gave_up = 0, None, False
else:
self._failed(now)
return ok
def _failed(self, now) -> None:
self.fails += 1
self.fail_at = now
if self.fails >= MAX_TRIES and not self.gave_up:
self.gave_up = True
_LOG.warning("The charger did not take the current, so the add-on "
"stops asking until you press Solar: "
"CHARGER_REFUSED.")
def _adopt(self, cur) -> None:
"""The read-back shows what Solar sent: taken, however late."""
self.taken = True
self.last_a = cur
self.attempted_a = self.prior_a = None
self.fails, self.fail_at, self.gave_up = 0, None, False
async def _put(self, drv, want, cur, now, tracker, stuck=False) -> None:
"""Make the charger match `want`: write a new decision, try one the
charger did not take again after `RETRY_S`. A new 0 A gets its own
`MAX_TRIES` and never waits (0 A is the safe side)."""
if self.hold:
return
if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A:
if self.taken or self.gave_up or (
self.fail_at is not None
and now - self.fail_at < RETRY_S):
return
await self._write(drv, want, cur, now, tracker)
return
if not stuck and cur is not None and abs(cur - want) <= TOL_A:
self.sent_a = want # it already stands
self._adopt(cur)
return
if want <= TOL_A:
self.fails, self.fail_at, self.gave_up = 0, None, False
elif self.gave_up or (self.fail_at is not None
and now - self.fail_at < RETRY_S):
return
await self._write(drv, want, cur, now, tracker)
async def _zero(self, drv, cur, now, tracker, stuck=False) -> None:
"""A way out: 0 A while Solar's own current may stand, never over
another writer's hold."""
self.seq = None
self.plan.end_switch(False)
if self.live and not self.hold:
await self._put(drv, 0.0, cur, now, tracker, stuck)
def _watch(self, cur, now) -> None:
was = self.hold
super()._watch(cur, now)
if self.hold and not was:
_LOG.warning("Something else changes the charger, so the add-on "
"stops writing to it until you press Solar: "
"CHARGER_OTHER.")
def _mark(self, r, now) -> None:
"""A car that draws one phase while 3 are allowed is a one-phase car
for the session: the sun arithmetic then uses 1 phase."""
if r.state == "A":
if self.single:
_LOG.info("The car was unplugged, so the add-on counts the "
"phases the charger allows again.")
self.single, self._one_since = False, None
return
amps = [x for x in (r.current_a or ()) if x is not None]
drawing = [x for x in amps if x >= CH.IDLE_A]
one = (r.phases_allowed == 3 and r.charging is True
and r.power_w is not None and r.power_w >= ONE_PHASE_MIN_W
and len(amps) >= 3 and len(drawing) == 1)
if not one:
self._one_since = None
return
if self._one_since is None:
self._one_since = now
if now - self._one_since >= ONE_PHASE_S and not self.single:
self.single = True
_LOG.info("The car draws one phase while three are allowed, so "
"the add-on counts one phase for this charge.")
def _leave(self) -> None:
"""Solar is no longer the mode and owes nothing."""
self.engaged, self.seq, self.would = False, None, None
self.out, self.fault = False, None
self.restart = True
self.mismatch_since = None
self.plan.reset(self.plan.n)
def _gap_ok(self, now) -> bool:
return self.last_switch is None or now - self.last_switch \
>= PHASE_GAP_S
def _plan_step(self, sun, now, clamp, n_now, gap_ok) -> None:
self.plan.step(
now, target_w=sun.target_w, hold=sun.hold, n_now=n_now,
auto=sun.auto and not self.single and not self.phases_gave_up,
clamp=clamp, start_s=sun.start_s, pause_s=sun.pause_s,
gap_ok=gap_ok)
@staticmethod
def _drawing(r) -> bool:
"""EV-04's test of a car that has not stopped (`_advance`)."""
if r.power_w is not None:
return r.power_w >= QUIET_W
return r.state in ("C", "D")
def _hold_over(self, now, sun) -> bool:
"""Has the hold the plan was in before its phase change run out?"""
before = self.plan._before
return bool(before is not None and before[3] is not None
and sun is not None
and now - before[3] >= sun.pause_s)
def _seq_want(self, clamp):
"""The current that ends a phase change: for the new phases, or for
the old ones when the select did not happen."""
def want(q):
before = self.plan._before
if q.get("failed") and before is not None:
return before[0] if before[0] >= CH.MIN_A else CH.MIN_A
return self.amps_out(clamp) or CH.MIN_A
return want
async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None:
"""Step 1 of the safe sequence: 0 A (kept when it already stands).
A 0 A the charger does not take ends the change; tried again later
by the plan's own dwell."""
self.phase_done_at = None
if not (cur is not None and cur <= TOL_A and self.sent_a == 0.0
and self.taken):
if not await self._write(drv, 0.0, cur, now, tracker):
self.plan.end_switch(False)
return
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
"prev": None, "from": r.phases_allowed}
# ------------------------------------------------------------- step
async def step(self, drv, r, *, mode, sun, clamp, now, tracker, writing,
status, clock=None):
"""One cycle. `sun` is `SunInputs` (None outside Solar); `writing` is
False in shadow mode, while control is stopped, under a safety stop
and while stopping."""
self._clock = clock or (lambda: now)
entering = mode == SOLAR and self.mode_was != SOLAR
self.mode_was = mode
if entering:
# Chosen (or the start-up): the plan starts paused, 0 A first.
self.engaged, self.restart = True, True
self.sent_a, self.taken = None, True
self.fails, self.fail_at, self.gave_up = 0, None, False
if not self.engaged:
return
if sun is not None:
self.sun = sun
if r is None or not r.available:
self.was_available = False # nothing is tried while it is down
return
if self.last_done is not None and tracker is not None \
and tracker.obs_at is not None \
and tracker.obs_at <= self.last_done:
# A reading older than our latest write says nothing about it:
# no write and no watch, but the plan's dwells go on counting.
if mode == SOLAR and sun is not None and writing \
and self.seq is None and not self.plan.switch \
and not self.restart and self.fault is None \
and not self.hold and self.mismatch_since is None:
self._plan_step(sun, now, clamp, self.plan.n,
self._gap_ok(now))
return
if not self.was_available:
# Start-up, or back after the charger or Home Assistant was gone:
# the charger's current is its own, not another writer's, and the
# first write is 0 A whatever it shows (D2, round 9).
self.was_available = True
self.fresh_start = self.restart = True
self.mismatch_since = None
self.last_a = self.attempted_a = self.prior_a = None
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
stuck = bool(tracker is not None and tracker.stuck(now))
if not self.taken and self.sent_a is not None and not stuck \
and cur is not None and abs(cur - self.sent_a) <= TOL_A:
self._adopt(cur) # round 9: a late read-back
self._mark(r, now)
if mode != SOLAR:
self.would = None
if mode == OFF: # 0 A while owed, then nothing
await self._zero(drv, cur, now, tracker, stuck)
if self.live and not self.hold:
return # tried again (or gave up)
self._leave() # Manual writes its own current
return
n_real = r.phases_allowed if r.phases_allowed in (1, 3) \
else self.plan.n
n_now = 1 if self.single else n_real
if not writing:
# Shadow, Stop, a safety stop, stopping: the way-out 0 A while
# owed, then nothing. The watch goes on (another writer is held
# for every reader) and so does the plan, for the card.
self.out = True
await self._zero(drv, cur, now, tracker, stuck)
self._watch(cur, now)
self._shadow_plan(sun, now, clamp, n_now)
self.restart = True
return
self.out = False
self._would_n = self._would_switch = None
self.would = None
fault = ("error" if (r.error or r.state in ("E", "F")) else
"stuck" if stuck else None)
if fault is not None:
# 0 A while owed, then no write until it clears; then the start
# rule. A stuck reading cannot confirm the 0 A.
if self.fault != fault:
self.fault = fault
if fault == "error":
_LOG.warning("The charger reports an error, so the add-on "
"sets the car to 0 A: CHARGER_ERROR.")
await self._zero(drv, cur, now, tracker, stuck)
self.plan.reset(n_now, why=fault)
self.restart = True
return
if self.fault is not None:
self.fault = None
if r.state == "A" or status == CH.NONE_:
# No car: 0 A while owed, then nothing until a car is plugged in
# and the start rule passes.
await self._zero(drv, cur, now, tracker)
self.plan.reset(n_now, why="none")
self.restart = True
return
if self.restart:
self.restart = False
self.seq = None
self.plan.reset(n_now)
if self.fresh_start:
self.fresh_start = False
self.sent_a, self.taken = None, True # 0 A first (D2)
if self.seq is None:
self._watch(cur, now)
if self.hold or self.mismatch_since is not None:
# Another writer's value, held or not yet: nothing is written
# over it; the plan goes on for the card.
self._plan_step(sun, now, clamp, n_now, False)
return
gap = self._gap_ok(now)
if self.sent_a == 0.0 and not self.taken:
self.plan.ok_since = None # 0 A first, then the start rule
if self.seq is not None:
self._plan_step(sun, now, clamp, self.plan.n, gap)
if self.plan.a < CH.MIN_A:
self.seq = None # paused: it stays at 0 A
self.plan.end_switch(True)
return
q = self.seq
if q["stage"] == "zero" and now - q["t0"] >= ZERO_WAIT_S \
and self._drawing(r) and self._hold_over(now, sun):
# The car still draws at the cap and the hold the plan came
# from has run its time: no select and no current back (N3);
# the 0 A stands as the pause. EV-04 counts the try.
self.seq = None
self.last_switch = now
self.phase_fails += 1
if self.phase_fails >= MAX_TRIES:
self.phases_gave_up = True
_LOG.warning("The car kept drawing, so the phases were not "
"changed.")
self.plan.end_switch(False)
self.plan.pause()
return
await self._advance(drv, r, cur, now, tracker,
self._seq_want(clamp), clamp, None)
if self.seq is None:
# Done when the phases were selected and the current is back;
# otherwise the plan returns to its old phases.
self.plan.end_switch(not q.get("failed"))
return
self._plan_step(sun, now, clamp, n_now, gap)
want = self.amps_out(clamp)
if want >= CH.MIN_A and self.plan.switch \
and self.plan.n != n_now and not self.single:
if self.gave_up or (self.fail_at is not None
and now - self.fail_at < RETRY_S):
return
await self._begin_solar(drv, r, cur, self.plan.n, now, tracker)
return
if self.plan.switch:
self.plan.end_switch(self.plan.n == n_now)
await self._put(drv, want, cur, now, tracker)
def _shadow_plan(self, sun, now, clamp, n_now) -> None:
"""Not writing: the plan runs on the phases it believes, a phase
change it decides counting as done, so the card says what Solar would
set (`would`)."""
n = self._would_n if self._would_n in (1, 3) else n_now
gap = self._would_switch is None or now - self._would_switch \
>= PHASE_GAP_S
if sun is not None:
self._plan_step(sun, now, clamp, n, gap)
if self.plan.switch:
self.plan.end_switch(True)
self._would_n, self._would_switch = self.plan.n, now
elif self._would_n is None:
self._would_n = self.plan.n
self.would = (self.amps_out(clamp), self.plan.n)
async def release(self, drv, r, now, tracker) -> bool | None:
"""The add-on stops in Solar (D3): 0 A while Solar's own current may
stand (a write cancelled while it waited counts), never over another
writer's hold. Up to `RELEASE_TRIES` tries `RELEASE_GAP_S` apart, each
waiting `RELEASE_TOOK_S` for its read-back. True: taken; False: not
taken (the caller warns); None: nothing was owed. Nothing is restored
of an interrupted phase change."""
self.seq = None
self.plan.end_switch(False)
self._clock = self._clock or (lambda: now)
if not self.engaged or not self.live or self.hold:
return None
if r is not None and r.available:
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
else:
cur = None
clock = getattr(drv, "_clock", None) or (lambda: now)
sleep = getattr(drv, "_sleep", None) or asyncio.sleep
t0 = clock()
for k in range(RELEASE_TRIES):
if k:
wait = t0 + k * RELEASE_GAP_S - clock()
if wait > 0:
await sleep(wait)
if await self._write(drv, 0.0, cur, clock(), tracker,
took_s=RELEASE_TOOK_S):
self.released = True
return True
self.released = False
return False
+140 -18
View File
@@ -5,8 +5,8 @@ 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, and only in Manual
(`app/carmode.py` is the one caller). `write_current` is clamped to
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
@@ -42,7 +42,13 @@ 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_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)}
def max_a(opts: dict):
@@ -70,6 +76,7 @@ TOOK_S = 10.0 # a write is "taken" when the read-back follows by t
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).
@@ -120,6 +127,7 @@ 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)
@@ -161,6 +169,10 @@ 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):
@@ -280,6 +292,7 @@ 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")),
@@ -389,7 +402,7 @@ class ChargerDriver:
from the charger, the entity's own range max)`."""
raise NotImplementedError
async def write_current(self, a: float) -> bool:
async def write_current(self, a: float, took_s: float = TOOK_S) -> bool:
raise NotImplementedError
async def write_phases(self, n: int) -> bool:
@@ -420,6 +433,9 @@ class AlfenHaDriver(ChargerDriver):
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":
@@ -493,11 +509,13 @@ class AlfenHaDriver(ChargerDriver):
pass
return min(x for x in (self.max_a, station, rng) if x is not None)
async def write_current(self, a: float) -> bool:
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`. A value above `clamp_a()` is a
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):
@@ -516,20 +534,32 @@ class AlfenHaDriver(ChargerDriver):
del self.sent[:-50]
if not await hass.set_number(self.current_entity, a):
return False
return await self._took(a)
return await self._took(a, took_s)
async def _took(self, a: float) -> bool:
"""Did the read-back follow the write, within `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"))
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:
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
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."""
@@ -553,7 +583,9 @@ class AlfenHaDriver(ChargerDriver):
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)."""
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
@@ -631,6 +663,31 @@ 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
@@ -663,6 +720,9 @@ class CarTracker:
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
@@ -683,7 +743,10 @@ 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._energy(r, day)
@@ -727,19 +790,78 @@ class CarTracker:
`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) -> None:
"""The add-on wrote the current. 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."""
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 moved and self.armed_at is None:
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)
+327 -28
View File
@@ -1,9 +1,12 @@
"""EV-04: the Controller's side of the car's Manual mode.
"""EV-04 and EV-20: the Controller's side of the car's Manual and Solar modes.
The writes themselves are `carmode.ManualWriter`'s; this mixin owns the state
(mode, current, phases: 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.
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
@@ -11,7 +14,7 @@ import dataclasses
import logging
from datetime import timezone
from . import carmode, chargers, messages, peakguard
from . import carmode, chargers, messages, packshare, peakguard
from .tariff import QUARTER_S
_LOG = logging.getLogger("goodwe")
@@ -34,6 +37,13 @@ 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"
# 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:
@@ -55,12 +65,31 @@ class CarMixin:
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
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
@@ -87,6 +116,23 @@ class CarMixin:
return (self.charger.configured()
and self.car_mode == carmode.MANUAL)
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)
@@ -108,8 +154,23 @@ class CarMixin:
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):
@@ -132,6 +193,11 @@ class CarMixin:
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,
@@ -141,7 +207,8 @@ class CarMixin:
"""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_phases": str(self.car_n),
"car_sun_first": carmode.FIRST_LABELS[self.car_first]}
# ------------------------------------------------------------- the writer
def car_kick(self) -> None:
@@ -153,8 +220,20 @@ class CarMixin:
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
@@ -178,13 +257,29 @@ class CarMixin:
self._car_step_failed = False
async def car_shutdown(self) -> None:
"""The add-on stops: no new write, and a phase change in the middle is
undone by giving the car its current back. The current stands
otherwise (Manual's fail state)."""
"""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:
@@ -197,25 +292,171 @@ class CarMixin:
_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. Reads nothing from the world (the cycle's read
did) and writes only through `carmode.ManualWriter`."""
"""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()
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)
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:
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 only, 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_manual():
"""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())
@@ -224,13 +465,21 @@ class CarMixin:
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."""
wr = getattr(self, "car_writer", None)
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) or wr.hold:
and wr.zero_sent_at is None and not own_zero) \
or wr.hold:
return False
r = self.car.reading
if not (self.car_manual() and self.car_writing()
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
@@ -239,7 +488,21 @@ class CarMixin:
if q is not None:
return not q.get("failed") and 0.0 <= mono - q["t0"] \
<= OWN_PAUSE_MAX_S
return 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_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
@@ -249,7 +512,7 @@ class CarMixin:
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_manual():
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))
@@ -346,6 +609,7 @@ class CarMixin:
"""After the guard has decided: does the car alone explain the excess?
`real_proj` is the projection WITH the car, whatever the guard saw."""
mono = self.car_now()
self._car_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
@@ -398,7 +662,34 @@ class CarMixin:
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
@@ -497,6 +788,7 @@ class CarMixin:
# 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
@@ -508,6 +800,13 @@ class CarMixin:
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",
+7 -2
View File
@@ -253,6 +253,7 @@ class CycleMixin:
stale_after = float(self.o.get("stale_input_s", 15))
late_s = self._readings_late(site_standing) # SAFETY-128
self._car_late_s = late_s # EV-20: Solar holds, then the stale rule
self._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
@@ -272,6 +273,7 @@ class CycleMixin:
# this cycle's. (DECISIONS/MAIN-orchestration-archive.md)
self.why_words = messages.why_waiting(bad_for)
self._why_waiting_since = now - timedelta(seconds=bad_for)
self._car_hold_kick() # EV-20: Solar counts from now
return
if late_s is not None and late_s < stale_after and self.inputs_ok \
and (self.auto or self.shadow) \
@@ -279,6 +281,7 @@ class CycleMixin:
and not (n_units > 1 and self.site_sign_wd.tripped):
self.reason = f"readings late {late_s:.0f}s" # SAFETY-128: hold
self.why_words = messages.why_late()
self._car_hold_kick() # EV-20: Solar holds its current
return
claims = []
@@ -396,8 +399,9 @@ class CycleMixin:
# `_peak_proj_real` keeps the quarter as the meter will bill it, for
# the car's own words. Only a fresh, trusted car reading is left out.
self._peak_proj_real = self._peak_proj
# EV-20: a Solar car exactly as a Manual car.
if (self._peak_proj is not None and not self.car_cover
and self.car_manual()):
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(
@@ -1065,7 +1069,8 @@ class CycleMixin:
await self.check_price_gap()
await self.check_charger()
await self.check_car_over()
self.car_kick() # EV-04: Manual, in the background
await self.check_car_release() # EV-20 (D3)
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
+21 -3
View File
@@ -205,7 +205,19 @@ class StatusMixin:
"text": messages.row_charger_unreach(
f"{brussels(self.car.bad_since_utc):%H:%M}")})
w = self.car_writer
if self.car_mode == "manual":
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.
@@ -230,7 +242,10 @@ class StatusMixin:
"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()})
"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:
@@ -250,6 +265,9 @@ 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 ------------------------------------------------------------------
@@ -922,7 +940,7 @@ 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"):
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
+115 -9
View File
@@ -1134,7 +1134,7 @@ def month_peak(c, now):
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_manual() and real is not None \
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.
@@ -1301,18 +1301,55 @@ 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."""
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 pg is not None and pg.floor_limited
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)
@@ -1320,6 +1357,8 @@ def _car_manual_why(c, key):
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:
@@ -1327,9 +1366,62 @@ def _car_manual_why(c, key):
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)."""
@@ -1342,12 +1434,21 @@ def car_block(c, now):
good = c.car.last_good
fresh = configured and c.car.fresh(mono)
today = None
if configured and c.car.today_kwh is not None:
today = _t("car.today", kwh=_kwh(c.car.today_kwh))
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 = {
"state": key or "wait",
"chip": car_state_word(key),
@@ -1360,11 +1461,14 @@ def car_block(c, now):
else round(float(r.power_w), 1)),
}
if configured:
# EV-04: what the page can set. Off and Manual only (Solar and Night
# are later cards, so they are not offered).
# 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"] = ["off", "manual"]
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,
@@ -1883,12 +1987,14 @@ def _samples() -> list:
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)))
pct="20 %", phases=car_phases_word(3),
real=car_phases_word(1), s="5"))
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",
+10 -1
View File
@@ -1040,8 +1040,17 @@ 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()
await self.car_shutdown() # EV-04: undo a phase change half way
if solar:
await self.car_release_notice()
else:
await self.car_shutdown() # EV-04: undo a phase change half way
self.mqtt.close()
+61
View File
@@ -190,6 +190,8 @@ T_CHARGER_UNREACH = "Charger not reachable"
T_CHARGER_UNREACH_NL = "Laadpaal onbereikbaar"
T_CAR_OVER = "Car over the peak limit"
T_CAR_OVER_NL = "Auto boven de piekgrens"
T_CAR_RELEASE = "Car may still be charging"
T_CAR_RELEASE_NL = "Auto laadt mogelijk nog"
T_NO_PRICES = "No prices"
T_NO_PRICES_NL = "Prijzen ontbreken"
@@ -204,6 +206,7 @@ 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"
# 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"
@@ -518,6 +521,44 @@ def row_car_over() -> str:
"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_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 "
@@ -526,6 +567,15 @@ def row_charger_other() -> str:
"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.",
@@ -1484,6 +1534,7 @@ HINTS = {
"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",
@@ -1780,6 +1831,8 @@ def status_samples() -> list:
("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()),
@@ -1822,6 +1875,8 @@ def samples() -> list:
no_prices(),
charger_unreachable("09:12"),
car_over("16"),
car_over_solar("8"),
car_release_failed(),
]
@@ -1890,6 +1945,9 @@ LABELS = {
"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",
}
@@ -1976,6 +2034,9 @@ LABELS_NL = {
"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.
+23 -7
View File
@@ -144,6 +144,8 @@ 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
@@ -200,7 +202,8 @@ 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")
out += ("car_power", "car_state", "car_today_kwh",
"car_today_solar_kwh")
return out
@@ -524,25 +527,32 @@ def mode_payloads(units, modes) -> list:
# --- 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
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)/set")
_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)/config")
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` and `select.goodwe_car_phases`. `car` is
`(max_a, phases)`; empty when it is None."""
`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
@@ -560,6 +570,8 @@ def car_payloads(car) -> list:
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",
@@ -584,7 +596,8 @@ def car_configs(car, stored) -> tuple:
def parse_car_command(topic, payload, retained):
"""`(action, value, reject)` for one message on a car command topic.
`action` is `car_mode`, `car_current` or `car_phases`. A value that is
`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:
@@ -607,6 +620,9 @@ def parse_car_command(topic, payload, retained):
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)
+10 -2
View File
@@ -160,8 +160,9 @@
$("#car-why").textContent = c.why;
renderCarControls(c);
}
// EV-04: Off and Manual. The mode and the phases send at once; the current
// sends after two seconds of rest. A slider being dragged is left alone.
// 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;
@@ -182,6 +183,13 @@
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;
+5
View File
@@ -52,6 +52,11 @@
<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="car-why small"><span class="muted" data-t="car.why"></span><span id="car-why"></span></div>
</div>
+23 -4
View File
@@ -91,7 +91,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"},
"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."}},
"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,11 +302,12 @@
"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"},
"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."},
"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."},
"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.",
@@ -329,7 +330,25 @@
"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."
"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."
}
},
"peak": {
+23 -4
View File
@@ -88,7 +88,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"},
"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."}},
"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,11 +256,12 @@
"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"},
"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."},
"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."},
"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.",
@@ -283,7 +284,25 @@
"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."
"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."
}
},
"peak": {
+3
View File
@@ -234,6 +234,9 @@ GROUPS = (
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", (
+13
View File
@@ -677,6 +677,19 @@ 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"])
+1 -1
View File
@@ -62,7 +62,7 @@ _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_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")
+13 -5
View File
@@ -873,20 +873,25 @@ options:
shadow_mode: "auto"
# ==========================================================================
# CAR CHARGER (EV-03 reads it, EV-04 adds Manual)
# CAR CHARGER (EV-03 reads it, EV-04 adds Manual, EV-20 Solar)
# ==========================================================================
# `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 or Manual), the current and the phases 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.
# 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`.
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
@@ -1266,7 +1271,7 @@ schema:
shadow_mode: list(auto|on|off)
# ==========================================================================
# CAR CHARGER (EV-03 reads it, EV-04 adds Manual)
# CAR CHARGER (EV-03 reads it, EV-04 adds Manual, EV-20 Solar)
# ==========================================================================
# `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
@@ -1277,6 +1282,9 @@ schema:
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
+7 -5
View File
@@ -905,16 +905,18 @@ check("it stays for an hour and then goes",
# --------------------------------------------------------------------------- #
print("\n9. THE MQTT SENSORS")
# --------------------------------------------------------------------------- #
check("the three car sensors are announced only with a charger on",
check("the car sensors (EV-20: four, with today's solar kWh) are announced "
"only with a charger on",
mqtt.optional_keys(CAR) == ("pv", "car_power", "car_state",
"car_today_kwh")
"car_today_kwh", "car_today_solar_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 three sensors, goodwe_car_power, "
f"goodwe_car_state and goodwe_car_today_kwh ({names})",
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})",
[pl[k]["object_id"] for k in names] == [
"goodwe_car_power", "goodwe_car_state", "goodwe_car_today_kwh"]
"goodwe_car_power", "goodwe_car_state", "goodwe_car_today_kwh",
"goodwe_car_today_solar_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(
+49 -29
View File
@@ -248,7 +248,7 @@ async def part2():
w = World()
out = {}
out["manual"] = await w.act("car_mode", "manual")
out["bad_mode"] = await w.act("car_mode", "solar") # not in this card
out["bad_mode"] = await w.act("car_mode", "bogus") # EV-20 accepts Solar
out["night"] = await w.act("car_mode", "night")
out["a12"] = await w.act("car_current", 12)
out["a5"] = await w.act("car_current", 5)
@@ -266,7 +266,7 @@ w2, o2 = run(part2())
check("Manual is chosen at once, no restart", o2["manual"] == {
"mode": "manual", "current": 6.0, "phases": 1} and w2.c.car_mode == "manual"
or w2.c.car_mode == "manual")
check("Solar and Night are not accepted (EV-05, EV-02)",
check("Night (EV-02) and an unknown mode are not accepted",
"error" in o2["bad_mode"] and "error" in o2["night"]
and w2.c.car_mode == "manual")
check("a current between 6 A and the clamp is accepted and stored",
@@ -307,7 +307,7 @@ check("ev_phases 1: 3 phases cannot be chosen, 1 can",
async def part2c():
out = {}
for start, stored in (("keep", "manual"), ("off", "manual"),
("keep", None), ("keep", "solar")):
("keep", None), ("keep", "night")):
st = _Store()
if stored:
st.data["car_mode"] = stored
@@ -322,7 +322,7 @@ check("ev_mode_start keep: a restart keeps Manual",
check("ev_mode_start off: a restart starts in Off and the store says so",
o2c[("off", "manual")] == ("off", "off"))
check("no stored mode, or one this build does not know, is Off",
o2c[("keep", None)][0] == "off" and o2c[("keep", "solar")][0] == "off")
o2c[("keep", None)][0] == "off" and o2c[("keep", "night")][0] == "off")
# =========================================================================== #
print("\n3. MANUAL WRITES THE CURRENT ONCE PER USER CHANGE")
@@ -613,10 +613,15 @@ async def slow_stop():
w5s, n05s = run(slow_stop())
seq5s = w5s.writes()[n05s:]
check("a car that is slow to stop: the phases are selected after 20 s at most "
f"({seq5s[1][0] - seq5s[0][0]:.0f} s after the 0 A)",
[x[1] for x in seq5s][:2] == ["current", "phases"]
and 19.0 <= seq5s[1][0] - seq5s[0][0] <= 22.0)
# EV-28: a car still drawing at 20 s gets no select; the current comes back
rest5s = [x for x in seq5s if x[1] == "current" and x[2] == 10.0]
check("a car that is slow to stop (about 1300 W after 20 s): the phases are "
"NOT selected, the add-on gives up at 20 s, the 10 A come back at once "
f"({[(x[1], x[2]) for x in seq5s]}), one failed try",
[x[1] for x in seq5s].count("phases") == 0
and [x[2] for x in seq5s if x[1] == "current"][:2] == [0.0, 10.0]
and rest5s and 20.0 <= rest5s[0][0] - seq5s[0][0] <= 21.0
and w5s.sim.phases_allowed == 1 and w5s.c.car_writer.phase_fails == 1)
async def zero_refused():
@@ -890,9 +895,11 @@ check("the write paths are exactly these (all in carmode.py): the current "
("carmode.py", "write_phases")])
async def fuzz(seed):
async def fuzz(seed, slow=False):
rnd = random.Random(seed)
w = World(setpoint=rnd.choice([6, 10, 16]), phases=rnd.choice([1, 3]))
if slow: # EV-28: the car's power ramps down slowly
w.sim.ramp_w_s, w.sim.stop_delay_s = 200.0, float(seed % 2)
w.sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0])
race = seed % 2 == 1 # half the sites run read -> settle -> cycle
bad, seen, others, holds, undos = [], 0, 0, 0, 0
@@ -961,6 +968,9 @@ async def fuzz(seed):
bad.append((seed, step, "phases selected outside Manual"))
if sp != 0.0:
bad.append((seed, step, "phases with the setpoint up", sp))
if power >= carmode.QUIET_W: # EV-28 (N1)
bad.append((seed, step, "phases selected under load",
power))
if last_switch is not None and t - last_switch < 600.0:
bad.append((seed, step, "two switches inside 10 min",
t - last_switch))
@@ -977,7 +987,15 @@ for _seed in range(14):
fz_o += _o
fz_h += _h
fz_u += _u
check(f"fuzz: {fz_n} charger writes over 14 random sites and 5600 steps of "
for _seed in range(100, 104): # EV-28: ramp 200 W/s, B after 0 or 1 s
_b, _n, _o, _h, _u = run(fuzz(_seed, slow=True))
fz_bad += _b
fz_n += _n
fz_o += _o
fz_h += _h
fz_u += _u
check(f"fuzz: {fz_n} charger writes over 18 random sites (4 of them with a "
f"car that stops at 200 W/s) and 7200 steps of "
f"random user changes, outages, unplugs, refusals, shadow and control "
f"stops, in both cycle orders: none over the clamp, none outside "
f"Manual, none with control stopped, in shadow mode or with no car, the "
@@ -1606,13 +1624,14 @@ pl = dict(mqtt.car_payloads((16, (1, 3))))
sel = pl["homeassistant/select/goodwe_ctl_car_mode/config"]
num = pl["homeassistant/number/goodwe_ctl_car_current/config"]
ph = pl["homeassistant/select/goodwe_ctl_car_phases/config"]
check("three entities: select.goodwe_car_mode, number.goodwe_car_current, "
"select.goodwe_car_phases", len(pl) == 3
check("four entities: select.goodwe_car_mode, number.goodwe_car_current, "
"select.goodwe_car_phases and (EV-20) select.goodwe_car_sun_first",
len(pl) == 4
and sel["object_id"] == "goodwe_car_mode"
and num["object_id"] == "goodwe_car_current"
and ph["object_id"] == "goodwe_car_phases")
check("the mode's labels are English and pinned: Off, Manual (Solar and Night "
"are not offered)", sel["options"] == ["Off", "Manual"])
check("the mode's labels are English and pinned: Off, Manual, Solar (EV-20; "
"Night is not offered)", sel["options"] == ["Off", "Manual", "Solar"])
check("the current is 6 A to the clamp, whole amps", num["min"] == 6
and num["max"] == 16 and num["step"] == 1
and num["unit_of_measurement"] == "A")
@@ -1629,7 +1648,7 @@ check("nothing is announced without a charger (and the default announcement "
"is as it was)", mqtt.car_payloads(None) == []
and mqtt.discovery_payloads() == mqtt.discovery_payloads(car=None))
check("the car entities come after every other row",
[t for t, _ in mqtt.discovery_payloads(car=(16, (1, 3)))][-3:]
[t for t, _ in mqtt.discovery_payloads(car=(16, (1, 3)))][-4:]
== [t for t, _ in mqtt.car_payloads((16, (1, 3)))])
cmd = mqtt.parse_car_command
check("a command parses: mode, current, phases",
@@ -1641,8 +1660,8 @@ check("a command parses: mode, current, phases",
== ("car_phases", 3, None))
check("a retained command is dropped",
cmd("goodwe_ctl/car/mode/set", b"Manual", True)[2] == "retained")
check("Solar, Night, junk and a long payload are refused",
cmd("goodwe_ctl/car/mode/set", b"Solar", False)[1] is None
check("Night, an unknown mode, junk and a long payload are refused",
cmd("goodwe_ctl/car/mode/set", b"Bogus", False)[1] is None
and cmd("goodwe_ctl/car/mode/set", b"Night", False)[1] is None
and cmd("goodwe_ctl/car/current/set", b"abc", False)[1] is None
and cmd("goodwe_ctl/car/phases/set", b"2", False)[1] is None
@@ -1660,7 +1679,7 @@ async def ha_story():
out = {"mode": w.c.car_mode, "a": w.c.car_a, "rb": w.sim.readback_a,
"pub": list(w.c.mqtt.values)[-1]}
await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Off", True) # retained
await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Solar", False)
await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Night", False)
await w.c.mqtt_command("goodwe_ctl/car/current/set", b"99", False)
await w.c.mqtt_command("goodwe_ctl/car/phases/set", b"2", False)
await w.step(5)
@@ -1678,8 +1697,8 @@ check("HA commands go through handle_action(): Manual and 13 A are applied "
"and written, and the new state is published",
ha["mode"] == "manual" and ha["a"] == 13.0 and ha["rb"] == 13
and ha["pub"] == {"car_mode": "Manual", "car_current": 13,
"car_phases": "1"})
check("a retained command, Solar, 99 A and 2 phases change nothing",
"car_phases": "1", "car_sun_first": "Batteries"})
check("a retained command, Night, 99 A and 2 phases change nothing",
ha["after"] == ("manual", 13.0, 1))
check("the three states are in the published values",
ha["state"].get("car_mode") == "Manual"
@@ -1700,11 +1719,11 @@ st_ = _S()
car_, retract_ = _main.car_announcement(CAR, st_)
check("with a charger the entities are announced and their topics kept",
car_ == (16.0, (1, 3)) and not retract_ and len(
st_.data["mqtt_car_configs"]) == 3)
st_.data["mqtt_car_configs"]) == 4)
car2, retract2 = _main.car_announcement(BASE, st_)
check("turning the charger off removes exactly those entities",
car2 is None and sorted(retract2) == sorted(st_.data["mqtt_car_configs"])
and len(retract2) == 3)
and len(retract2) == 4)
st2 = _S()
check("a site that never had a charger publishes nothing and its store is "
"not written",
@@ -1734,7 +1753,7 @@ async def web_story():
("manual", {"action": "car_mode", "value": "manual"}),
("a", {"action": "car_current", "value": 12}),
("n", {"action": "car_phases", "value": 3}),
("solar", {"action": "car_mode", "value": "solar"}),
("solar", {"action": "car_mode", "value": "night"}),
("big", {"action": "car_current", "value": 40})):
async with s.post(root + "action", json=body) as r:
out[key] = (r.status, await r.json(content_type=None))
@@ -1753,21 +1772,22 @@ check("POST /action car_mode, car_current and car_phases store and answer",
web["manual"] == (200, {"ok": True, "result": {
"mode": "manual", "current": 6.0, "phases": 1}})
and web["a"][0] == 200 and web["n"][0] == 200)
check("...Solar and 40 A (above the clamp) are a 400 with a plain reason",
check("...Night and 40 A (above the clamp) are a 400 with a plain reason",
web["solar"][0] == 400 and web["solar"][1]["ok"] is False
and web["solar"][1]["error"] == messages.car_refused("value")
and web["big"][0] == 400)
car_s = web["status_en"]["car"]
check("/status gives the page what it needs: the mode, the modes offered (Off "
"and Manual only), the current's range, the phases",
car_s["mode"] == "manual" and car_s["modes"] == ["off", "manual"]
check("/status gives the page what it needs: the mode, the modes offered (Off, "
"Manual and, EV-20, Solar), the current's range, the phases",
car_s["mode"] == "manual"
and car_s["modes"] == ["off", "manual", "solar"]
and car_s["current"] == {"value": 12, "min": 6, "max": 16}
and car_s["phases"] == {"value": 3, "choices": [1, 3]})
check("/status in Dutch has the Dutch Why",
web["status_nl"]["car"]["why"].startswith("U stelde 12 A in"))
check("the page has the controls and no Solar or Night button",
check("the page has the controls and no Night button (EV-20 adds Solar)",
'id="car-manual"' in web["page"] and 'id="car-a"' in web["page"]
and "mode_solar" not in web["page"] and "mode_night" not in web["page"])
and "mode_night" not in web["page"])
check("the page names the Manual strings in both languages",
"Handmatig" in web["page"] and "Manual" in web["page"])
File diff suppressed because it is too large Load Diff
+832
View File
@@ -0,0 +1,832 @@
"""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")
+538
View File
@@ -0,0 +1,538 @@
"""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)
+701
View File
@@ -0,0 +1,701 @@
"""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 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])
# 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()
+619
View File
@@ -0,0 +1,619 @@
"""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 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)
# 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()
+312
View File
@@ -0,0 +1,312 @@
"""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)
+493
View File
@@ -0,0 +1,493 @@
"""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()
+52
View File
@@ -0,0 +1,52 @@
"""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)
+52
View File
@@ -0,0 +1,52 @@
"""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)
+227
View File
@@ -0,0 +1,227 @@
"""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()
+939
View File
@@ -0,0 +1,939 @@
"""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")
+180
View File
@@ -0,0 +1,180 @@
"""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
+251
View File
@@ -0,0 +1,251 @@
"""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)
+313
View File
@@ -0,0 +1,313 @@
#!/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")
+10 -1
View File
@@ -300,7 +300,16 @@ configuration:
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 never changes the charger's current."
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."
+10 -1
View File
@@ -281,7 +281,16 @@ configuration:
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 verandert de stroom van de laadpaal nooit."
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."