From 0c92239a63b9116f1ea00191407e9303c1e0b692 Mon Sep 17 00:00:00 2001 From: glenn schrooyen Date: Mon, 16 Nov 2026 05:24:36 +0100 Subject: [PATCH 1/4] EV-04: car Manual mode, never throttled for the peak, no false guard alarms Off and Manual (runtime state, Home and Home Assistant): the current (6 A to the clamp) and the phases (1 or 3) are written once per user change through the safe phase sequence, read back within 10 s, clamped to min(ev_max_a, station limit, entity range). Shadow mode gates the writes. The car's fresh power goes to the peak guard's alarm path: no false "Load too high" or "Battery stopped limiting the peak", one grey notice per session. ev_batt_cover and ev_mode_start options, peak line "set by the car", HA entities, sim writes, DOCS, CHANGELOG, test_ev04.py. Co-Authored-By: Claude --- goodwe_controller/CHANGELOG.md | 4 + .../DECISIONS/EV-04-manual-mode.md | 95 ++ goodwe_controller/DOCS.md | 103 +- goodwe_controller/app/carmode.py | 304 ++++ goodwe_controller/app/chargers.py | 181 +- goodwe_controller/app/ctl_alarms.py | 6 +- goodwe_controller/app/ctl_car.py | 310 ++++ goodwe_controller/app/ctl_cycle.py | 18 + goodwe_controller/app/ctl_status.py | 63 +- goodwe_controller/app/homeview.py | 83 +- goodwe_controller/app/main.py | 32 +- goodwe_controller/app/messages.py | 78 + goodwe_controller/app/mqtt.py | 112 +- goodwe_controller/app/static/app.js | 42 + goodwe_controller/app/static/index.html | 12 +- goodwe_controller/app/ui_text/en.json | 25 +- goodwe_controller/app/ui_text/nl.json | 25 +- goodwe_controller/app/uilayout.py | 6 +- goodwe_controller/app/web.py | 10 + goodwe_controller/config.yaml | 14 +- goodwe_controller/test_ev03.py | 16 +- goodwe_controller/test_ev04.py | 1488 +++++++++++++++++ goodwe_controller/tools/chargersim.py | 103 +- goodwe_controller/tools/ev04_peak.py | 153 ++ goodwe_controller/tools/ux13_demo.py | 25 +- goodwe_controller/translations/en.yaml | 8 +- goodwe_controller/translations/nl.yaml | 8 +- 27 files changed, 3242 insertions(+), 82 deletions(-) create mode 100644 goodwe_controller/DECISIONS/EV-04-manual-mode.md create mode 100644 goodwe_controller/app/carmode.py create mode 100644 goodwe_controller/app/ctl_car.py create mode 100644 goodwe_controller/test_ev04.py create mode 100644 goodwe_controller/tools/ev04_peak.py diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index b84a686..45fac1e 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +### Not in a release yet + +- The *Car* card can now charge: choose **Manual** and set the current (6 A up to the charger limit) and 1 or 3 phases, on Home or from Home Assistant. The car is never slowed for the peak limit, the add-on says so instead of raising false peak alarms, and the batteries help cover it unless you switch that off. Off still writes nothing ([[EV-04]]). + ## 0.23.0 **A minor bump: the add-on can now read a car charger (Alfen, through Home Assistant), and with two inverters a maintenance charge stays paused during a real peak. Four new options were added, all with defaults, and none needs setting.** diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md new file mode 100644 index 0000000..bc02e85 --- /dev/null +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -0,0 +1,95 @@ +# EV-04 — Manual mode: the first write to a car charger + +The design is `reports/EV-01-design-report.md` (sections 2 to 5), accepted on +2026-11-15 with all eight decisions as recommended. This record keeps what the +code had to decide that the design left open. + +## What writes, and who may + +`app/carmode.py` `ManualWriter` is the only caller of `write_current` and +`write_phases` (test_ev03.py greps for any other). It runs in a background task +(`ctl_car.CarMixin.car_kick`), never in the control cycle: a write waits up to +10 s for the charger's read-back, and the cycle must never wait for a charger. + +- **Off writes nothing.** The mode is runtime state in the store (`car_mode`, + `car_current`, `car_phases`), changed on Home or from Home Assistant with no + restart. Solar and Night are not accepted (EV-05, EV-02). +- **Once per user change.** A user change sets a flag the writer clears when the + charger has what was asked. A difference nobody asked for is the other-writer + detector's business, not a reason to write. +- **No car or a full car: nothing is written**, and the setting waits for a car. +- **Shadow mode and a stopped control write nothing**; the card says what the add-on + would set. +- **The clamp is the driver's too.** The writer asks for at most the clamp, and + `AlfenHaDriver.write_current` refuses anything above + `min(ev_max_a, station limit read now, entity range max)`: it sends nothing, + logs `CHARGER_CLAMP` at ERROR (the OUTPUT_CLAMP shape) and answers False. +- **"Taken"** means the read-back followed within 10 s. A write that was not + taken is tried again after a minute, three times, then it waits for the user + (an amber row). A late read-back is adopted, never called another writer. + +## The phase sequence + +0 A, wait until the charger reports under 100 W 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`). + +## Another writer + +A read-back that differs from what the add-on last wrote (or tried to write, or +saw before a refused write) for 30 s is another writer: a grey row, and no write +until the user changes the mode or a value. EV-03's detector still serves Off; +the tracker mutes its own detector for 15 s after each of our writes, so Manual +back to Off does not show the add-on as a second writer. + +## The peak guard's alarm path + +`Controller` passes the car's power to the guard's alarm path (`car_cycle`). +**The car explains the excess when the house alone would land the period under +the aim**: the car's average over the whole period (what it drew so far, and its +power now for the rest, `car_avg_w`) is at least how far the projected period is +over the aim. With decision 1 on it also needs the guard to be unable to hold +it (saturated or at the peak reserve). Then "Load too high" and "Battery stopped +limiting the peak" are not raised, the rows are not red, and one grey notice per +charging session says so. The claim, the floor and the commands are unchanged. + +The brief's wording is `car_w >= projected excess over the aim`. The +instantaneous form (`car_w >= excess_w`, the watts to come off the meter now) +stops holding late in a period that the car already pushed over, because +`excess_w` grows as the seconds run out; the average form does not, and it is the +same test for a steady car. + +**A stale or stuck 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 (power and read-back unchanged 60 s +after a write that moved the setpoint by 1 A or more, SAFETY-37's shape), and never +above what the read-back allows the car to draw. A figure that is stuck from the +start with no write is not caught by the stuck rule; it is bounded by the +read-back and is the one hole this card leaves (the design's own rule). + +## Decision 1 (`ev_batt_cover`) + +On (the default): the guard works as it does and the batteries cover the car down +to the peak reserve. Off: the projection the guard sees leaves the car out +(`house - car_w`, with the car's average so far), so it does not force the +batteries to discharge for it, and the period goes over by the car alone. The +car is never throttled either way. The projection the guard sees is also the +one `charge_room_w` reads, so with the switch off a grid charge of the batteries +sees the room the car leaves; that is the owner's trade and DOCS says so. + +## Deviations from the design text + +- **Titles and setting names** follow STYLE.md (at most 5 and 6 words): + "Car over the peak limit" (the design: "Car charge over the peak limit"), + setting "Batteries help with the peak" (the design: "... while the car + charges", which is in its description). +- **No "or choose Solar"** in the Why or the notice: Solar is not in this card. +- **The Why lines** are two sentences of at most 12 words, as test_messages.py + asks; `peak.car` says "The car takes {car} and the batteries cover {cov}." + without "of it". +- **`peak.set_by_car`** keeps its first sentence only ("The batteries were at the + peak reserve" is not true with decision 1 off). A quarter counts as set by the + car when the car drew half the peak or more over it. diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index d59db33..8aa787a 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -251,10 +251,12 @@ The label and description each setting shows on the Configuration tab, in tab or | Safety | Opposing inverters time (s) | `circulation_hold_s` | For two or more inverters: how long they may push against each other before a safety stop. Derived value, leave it unchanged. | | Safety | Not delivering alarm after (s) | `delivery_hold_s` | For two or more inverters: how long one may fall short of its share before an alarm, which changes nothing. Derived value, leave it unchanged. | | Safety | Shadow mode | `shadow_mode` | The add-on makes every decision but keeps every inverter at 0 W. 'auto' does this while control is stopped, 'on' always, 'off' never. | -| Car charger | Charger | `ev_charger` | Which car charger the add-on reads. Off leaves everything as it is. This version only reads the charger and never changes it. | +| Car charger | Charger | `ev_charger` | Which car charger the add-on drives. Off leaves everything as it is. In Off mode the add-on only reads the charger and never changes it. | | Car charger | Current setting entity | `ev_current_entity` | The entity that sets the charger's current. The add-on finds the charger's other entities from its name. | | Car charger | Charger limit (A) | `ev_max_a` | The most current the charger may ever be asked for. Never above what the charger reports. Lower it for a weaker fuse or cable. | | Car charger | Phases | `ev_phases` | How many phases the charger may use: 1, 3, or 1 and 3 (auto). | +| Car charger | Batteries help with the peak | `ev_batt_cover` | While the car charges. On: the batteries cover it down to the peak reserve. Off: the peak guard leaves the car out, so the car alone can set the peak. | +| Car charger | Mode after a restart | `ev_mode_start` | Keep the last mode, or start in Off. A restart never changes the charger's current. | | 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. | @@ -3275,9 +3277,10 @@ it. ### Car charger -The add-on can read your car charger and show it on **Home**, on a *Car* card. In -this version it only reads. It never changes the charger, so it is safe to run -beside your own automation. Later versions will add charging modes. +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. | option | meaning | |---|---| @@ -3285,44 +3288,91 @@ beside your own automation. Later versions will add charging modes. | `ev_current_entity` | The charger's current setting, for example `number.wallbox_power_connector_max_current_socket_1`. The add-on finds the charger's other entities from this name. | | `ev_max_a` | The most current the charger may ever be asked for. It cannot be higher than the station limit the charger reports. | | `ev_phases` | `1`, `3` or `auto` (1 and 3). | +| `ev_batt_cover` | On (the default): the batteries help cover the car down to the peak reserve. Off: the car is left out of what the peak guard protects. | +| `ev_mode_start` | `keep` (the default) or `off`: the mode after a restart. | **What the Car card shows.** The state (Charging, Connected waiting, No car connected, Car is full, Charger not reachable), the power and current, and the energy charged today. The car's power is taken out of the **House** tile and out of the house profile that plans the batteries' night charge, so the batteries -no longer buy energy for a car that charged last night. The peak limit works as -before: the car is still part of what the grid meter sees. +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` +and `select.goodwe_car_phases`. The mode, the current and the phases apply at +once, with no restart. The add-on writes each one once, when you change it, and +checks within 10 seconds that the charger took it. + +- The current is never higher than the smallest of the charger limit, the station + limit the charger reports and the charger's own range. A value above that is a + software fault: it is logged and never sent. +- With no car connected, or a full car, nothing is written. The setting waits + until a car is connected. +- A phase change always goes through the same steps: 0 A, wait until the + charger draws under 100 W (at most 20 seconds), select the phases, wait 10 + seconds, set the current again. At most one phase change per 10 minutes. +- Shadow mode keeps the charger alone, as it keeps the inverters alone: the card + says what the add-on *would* set. Nothing is written either while control is + stopped. +- A restart, stopping control and a safety stop leave the charger at its + current. When the charger answers again after being away, the add-on sets your + current again only if the charger shows a different one. +- Off writes nothing, ever. + +**The car is never slowed for the peak limit.** A Manual charge goes on whatever +the 15-minute peak does. With the default `ev_batt_cover` on, the batteries help +cover it down to the peak reserve; a 3-phase 16 A charge (11 kW) can empty two +batteries to the reserve in about 1.5 hours, and the month's peak then rises by +what the car drew. When the car alone is why the batteries cannot hold the +period, the add-on does **not** raise *Battery stopped limiting the peak* or +*Load too high for battery*. It shows a grey note *Car over the peak +limit* once per charging session, a grey row, and says so in the car's *Why*. +This holds only while the car's reading is fresh: a stale or stuck reading +never hides a real overload of the house. With `ev_batt_cover` off, the peak +guard protects the house without the car, so it does not force the batteries to +discharge for it, and the period goes over by the car alone. When the month's peak was set by a car +charge, Home's peak line says so. **When the charger does not answer.** After 30 seconds the card says *Charger not reachable* and one amber row appears. After 5 minutes one notification follows. While the car reading is older than 15 seconds the House tile shows no reading, and that moment is left out of the house profile, rather than guessing -how much the car took. +how much the car took. A reading that does not move for a minute after the +add-on changed the current shows the amber row *Charger reading may be stuck*; +the add-on goes on writing. -**Another controller.** If the charger's current changes while the add-on writes -nothing, something else sets it, usually your own automation. The page then shows -the grey row *Another controller changes the charger*. That is expected while -you migrate. +**Another writer.** In Manual, if the charger shows a different current than the +add-on set, for 30 seconds, something else is setting it, usually your own +automation. The page shows a grey row, and the add-on writes nothing over it until +you change the mode or a value. In Off the grey row *Something else changes the +charger* shows for an hour after a change. That is expected while you migrate. **Moving your own automation to the add-on.** Each step can be undone. -1. Install this version and set `ev_charger` to `alfen_ha`. The add-on reads the - charger and writes nothing. Compare the card with your automation for a few - days. -2. When a later version adds charging modes, switch your automation **off** - (do not delete it) in the evening with the car unplugged, then choose the - add-on's Manual mode with the current your helper held. Plug in and check the - current on the card and on the charger's display. +1. Install this version and set `ev_charger` to `alfen_ha`. The mode starts in + **Off**: the add-on reads the charger and writes nothing. Compare the card + with your automation for a few days. +2. Cut-over, in the evening with the car unplugged: in Home Assistant switch your + automation **off** (do not delete it). On the card choose **Manual** with the + current your helper held (`input_number.ev_manual_current`). Plug in and check + the current on the card and on the charger's display. 3. On the next sunny day, choose Solar, with *spare sun goes first to* set as - your priority switch was. + your priority switch was. (Solar comes in a later version; until then keep + Manual or Off.) 4. Keep your Home Assistant helpers for a week. To go back, set the add-on mode to Off and switch the automation on. After that you can delete the helpers and the automation. -Never let the automation and the add-on both write the charger. +**Never let the automation and the add-on both write the charger.** Two writers +fight over the one setting and neither can tell which won. Turn the automation +off before you choose Manual, and the add-on off (mode Off) before you turn the +automation on. -**Home Assistant entities.** With MQTT the add-on adds three sensors: -`goodwe_car_power`, `goodwe_car_state` and `goodwe_car_today_kwh`. +**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 +restart of Home Assistant cannot change the charger. ### Site @@ -3451,6 +3501,14 @@ last setting. The add-on changes nothing on the charger in any case. Check the charger's integration in Home Assistant. The notification goes by itself when the charger answers again. +### Car over the peak limit + +The car charge you set (Manual) takes the 15-minute period over the peak limit, +and the batteries cannot hold it because they are at the peak reserve or at +their full power. The add-on never slows the car, so this is information, not an +alarm. It is raised once per charging session. To stay under the limit, lower the +current. + ### For installers: notifications A fixed tariff beside the price service raises no notification: it is the @@ -3478,6 +3536,7 @@ default `info` hides it. | Battery cycle did not finish | warning | `goodwe_maint_failed_` | MAINT-13 | | No prices | warning | `goodwe_no_prices` | PRICE-01 | | Charger not reachable | warning | `goodwe_charger_unreachable` | EV-03 | +| Car over the peak limit | info | `goodwe_car_over` | EV-04 | **The Details link.** Home Assistant 2026.2 and newer show add-on pages at `/config/app//documentation`; 2026.5 removed the old diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py new file mode 100644 index 0000000..c2fe84e --- /dev/null +++ b/goodwe_controller/app/carmode.py @@ -0,0 +1,304 @@ +"""EV-04: the car charger's Manual mode, the one place the add-on WRITES to it. + +Pure but for the driver it is handed: no clock of its own (`now` is monotonic +seconds from the caller), no Home Assistant, no store. DECISIONS/EV-04-manual- +mode.md has the record; the design is reports/EV-01-design-report.md sections +2, 3 and 4. + +THE RULES, each tested in test_ev04.py: + +* Off writes NOTHING. Manual writes the current (6 A to the clamp) and the + phases (1 or 3), each ONCE PER USER CHANGE, and only with a car connected + and not full: with no car, or a full one, the current stands and the write + waits for the car. +* Every current is clamped to `min(ev_max_a, the station limit the charger + 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. +* 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. +""" + +from __future__ import annotations + +import logging + +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) +#: Home Assistant's select labels, English and pinned. +MODE_LABELS = {OFF: "Off", MANUAL: "Manual"} +START_KEEP, START_OFF = "keep", "off" + +KEY_MODE, KEY_A, KEY_PHASES = "car_mode", "car_current", "car_phases" +DEFAULT_A = 6.0 +DEFAULT_PHASES = 1 + +QUIET_W = 100.0 # "paused": under this, or mode3 has left C +ZERO_WAIT_S = 20.0 # at most this long for the car to stop drawing +SETTLE_S = 10.0 # after the phases select, before the current +PHASE_GAP_S = 600.0 # at most one phase switch per this +WRITER_S = 30.0 # a differing read-back this long is another writer +RETRY_S = 60.0 # a write the charger did not take, tried again after +MAX_TRIES = 3 # ... this many times, then it waits for the user +TOL_A = CH.TOOK_TOL_A + + +def allowed_phases(opts: dict) -> tuple: + """The phase counts the user may pick: the `ev_phases` setting says what + the installation allows (`auto` is 1 and 3).""" + v = str((opts or {}).get("ev_phases", CH.EV_OPTION_DEFAULTS["ev_phases"])) + return (1,) if v == "1" else (3,) if v == "3" else (1, 3) + + +def start_mode(opts: dict, stored) -> str: + """The mode after a restart: the stored one (`keep`), or Off.""" + if str((opts or {}).get("ev_mode_start") + or CH.EV_OPTION_DEFAULTS["ev_mode_start"]) == START_OFF: + return OFF + return stored if stored in MODES else OFF + + +def clamp_for(opts: dict, reading) -> float | None: + """The most a write may ask for, from the options and the last reading: + `min(ev_max_a, the station limit, 40 A)`. None when the limit setting is + not a number. (The driver reads the entity's own range as well.)""" + amps = CH.max_a(opts) + if amps is None: + return None + lim = [amps, CH.ENTITY_MAX_A] + st = getattr(reading, "station_a", None) + if st is not None: + lim.append(float(st)) + return min(lim) + + +def value_a(raw, clamp: float | None): + """A current the user asked for, as a whole number of amps inside + `[6, clamp]`, or None when it is not a number. Above the clamp is the + clamp: the user's value never reaches the driver bigger than it.""" + try: + v = float(raw) + except (TypeError, ValueError): + return None + if v != v: + return None + v = round(v) + hi = CH.ENTITY_MAX_A if clamp is None else max(CH.MIN_A, float(clamp)) + return float(min(max(v, CH.MIN_A), hi)) + + +class ManualWriter: + """What Manual does to the charger, one `step()` per cycle.""" + + def __init__(self): + self.rev_applied = None # the user's last change we have acted on + self.last_a = None # the last current the charger took from us + self.attempted_a = None # a write it did not take ... + self.prior_a = None # ... and what the charger showed before it + self.mismatch_since = None + self.hold = False # another writer: no write until the user + self.other = False # ... and the info row says so + self.reapply = True # first reading, or the charger came back + self.was_available = False + self.fails = 0 + self.fail_at = None + self.gave_up = False + self.seq = None # a phase change under way + self.last_switch = None + self.blocked = False # a phase change waits for PHASE_GAP_S + self.would = None # (amps, phases): what it would set + self.log = [] # (kind, value, now, ok), for the checks + + # ------------------------------------------------------------------ user + def user_changed(self) -> None: + """The user changed the mode or a value: one more write is allowed, + and another writer's hold is lifted.""" + self.rev_applied = None + self.hold = self.other = False + self.mismatch_since = None + self.fails, self.fail_at, self.gave_up = 0, None, False + self.attempted_a = self.prior_a = None + + # ------------------------------------------------------------------ step + async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp, + now, tracker, writing, status): + """One cycle. `r` is the latest `ChargerReading`; `writing` is False in + shadow mode and while control is stopped (the step then only works out + what it WOULD set, in `self.would`).""" + if r is None or not r.available: + self.was_available = False + return + if not self.was_available: + self.was_available = True + self.reapply = True # on return: only if it differs + cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a + if self.seq is not None: + await self._advance(drv, r, cur, now, tracker, want_a, clamp, rev) + return + self.would = None + if mode != MANUAL: + return + if clamp is None or clamp < CH.MIN_A: + return + n_eff = want_phases if want_phases in (1, 3) else DEFAULT_PHASES + target = min(max(float(want_a), CH.MIN_A), float(clamp)) + self.would = (target, n_eff) + # No car, or a full one: the current stands, nothing is written. The + # setting waits (rev stays unapplied) until a car is there. + if r.state == "A" or status in (CH.NONE_, CH.FULL): + self.mismatch_since = None + return + if not writing: + return + self._watch(cur, now) + if self.hold: + return + phases_need = (r.phases_allowed is not None + and r.phases_allowed != n_eff) + cur_need = cur is None or abs(cur - target) > TOL_A + need_user = rev != self.rev_applied + if not (phases_need or cur_need): + self.rev_applied, self.reapply = rev, False + self.fails, self.blocked = 0, False + if cur is not None: + self.last_a = cur # adopt what is already set + return + if not (need_user or self.reapply): + return # a difference nobody asked for: `_watch()` judges + if self.gave_up or (self.fail_at is not None + and now - self.fail_at < RETRY_S): + return + if phases_need: + if self.last_switch is not None \ + and now - self.last_switch < PHASE_GAP_S: + self.blocked = True + else: + self.blocked = False + await self._begin(drv, r, cur, n_eff, now, tracker) + return + if cur_need: + ok = await self._write(drv, target, cur, now, tracker) + if not ok: + self._failed(now) + return + self.fails, self.fail_at = 0, None + if not phases_need: + self.rev_applied, self.reapply = rev, False + + # ------------------------------------------------------------- internals + def _failed(self, now) -> None: + self.fails += 1 + self.fail_at = now + if self.fails >= MAX_TRIES: + self.gave_up = True + _LOG.warning("The charger did not take the current, so the add-on " + "stops asking until you change it: CHARGER_REFUSED.") + _LOG.debug("The charger refused the current %d times.", self.fails) + + def _watch(self, cur, now) -> None: + """Is the read-back what we wrote? A difference that stands for + `WRITER_S` is another writer.""" + known = [x for x in (self.last_a, self.attempted_a, self.prior_a) + if x is not None] + if not known or cur is None: + self.mismatch_since = None + return + if any(abs(cur - k) <= TOL_A for k in known): + self.mismatch_since = None + if self.hold: + self.hold = self.other = False + return + if self.mismatch_since is None: + self.mismatch_since = now + elif now - self.mismatch_since >= WRITER_S and not self.hold: + self.hold = self.other = True + _LOG.info("Something else changes the charger (read-back %.0f A, " + "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: + ok = await drv.write_current(a) + tracker.note_write(now, was, a) + self.log.append(("current", a, now, ok)) + if ok: + self.last_a = a + self.attempted_a = self.prior_a = None + else: + self.attempted_a, self.prior_a = a, was + return ok + + async def _begin(self, drv, r, cur, n, now, tracker) -> None: + """Step 1 of the safe sequence: 0 A. A charger that does not take it + stops the sequence before the phases are touched.""" + ok = await self._write(drv, 0.0, cur, now, tracker) + if not ok: + self._failed(now) + return + self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, + "prev": cur} + + async def abandon(self, drv, now, tracker) -> None: + """The add-on is stopping in the middle of a phase change: give the car + its current back (a stopped add-on must not leave it at 0 A). The + phases stay as the select left them.""" + q, self.seq = self.seq, None + if q is not None and q.get("prev") is not None \ + and q["prev"] >= CH.MIN_A: + await self._write(drv, float(q["prev"]), 0.0, now, tracker) + + async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev): + q = self.seq + if q["stage"] in ("zero", "select") and cur is not None \ + and cur >= CH.MIN_A: + # Something else raised the current while the car was being + # paused. The phases are never selected under that: give up the + # change, and leave the charger to whoever set it until the user + # changes something. + self.seq = None + self.hold = self.other = True + self.last_a = self.attempted_a = self.prior_a = None + _LOG.info("Something else raised the charger's current during a " + "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" + if q["stage"] == "select": + ok = await drv.write_phases(q["n"]) + self.last_switch = now + self.log.append(("phases", q["n"], now, ok)) + q["stage"], q["t1"] = "settle", now + return + 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) + 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. + self.seq, self.rev_applied, self.reapply = None, None, False + self.fails, self.blocked = 0, False + return + q["tries"] += 1 + if q["tries"] >= MAX_TRIES: + # Left at 0 A is the safe side; the next reading re-applies. + self.seq, self.last_a, self.reapply = None, None, True + self._failed(now) + self.rev_applied = None + return + q["t1"] = now - SETTLE_S + 5.0 # again in 5 s diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index 0973283..b69914a 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -5,10 +5,12 @@ 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. -THIS CARD NEVER WRITES TO THE CHARGER. `write_current`, `write_phases` and -`release` are defined so the seam is whole, and NOTHING in the controller calls -them: Off is the only mode. test_ev03.py greps the controller for a call and -proves a full cycle makes no service call that names a charger entity. +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 +`min(ev_max_a, the station limit the charger reports, the entity's own range)` +and a value above that is NEVER SENT: it is a software fault, logged in the +OUTPUT_CLAMP shape. It says True only when the charger's read-back followed +within `TOOK_S`. Off writes nothing (EV-03's no-write test still holds for it). VALUES ARE BELIEVED ONLY IN THEIR OWN UNIT (as TEL-11 does for power): power in a power unit, energy in a kWh unit, current in A. A reading in another unit is @@ -20,12 +22,17 @@ as an argument, so the checks need no sleep. from __future__ import annotations +import asyncio +import logging import re +import time from dataclasses import dataclass from .hass import BAD_STATES from .solarfc import KWH_PER +_LOG = logging.getLogger("goodwe") + OFF = "off" ALFEN_HA = "alfen_ha" #: the `ev_charger` values the options accept @@ -34,7 +41,8 @@ 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_max_a": 16, "ev_phases": "auto", + "ev_batt_cover": True, "ev_mode_start": "keep"} def max_a(opts: dict): @@ -58,6 +66,14 @@ FULL_C_S = 600.0 # mode3 C under FULL_C_W this long: car full FULL_C_W = 200.0 WRITER_HOLD_S = 3600.0 # "another controller" stays shown this long IDLE_A = 1.0 # a phase under this draws nothing +TOOK_S = 10.0 # a write is "taken" when the read-back follows by then +TOOK_TOL_A = 0.5 # ... to within this +STUCK_S = 60.0 # EV-04: power and read-back unchanged after a write +STUCK_MIN_A = 1.0 # ... that moved the setpoint by at least this +OWN_WRITE_MUTE_S = 15.0 # the tracker's two-writer detector ignores our own +# Volts used to bound a car figure by what the read-back allows (a physical +# ceiling for the alarm path, never a setpoint). +CEILING_V = 253.0 # role -> (entity domain, suffix after `_`). `current` is the setpoint, the # one the installer names; the rest are derived by swapping its suffix. @@ -350,7 +366,12 @@ class ChargerDriver: async def read(self) -> ChargerReading: raise NotImplementedError - # --- the write side. DEFINED, UNUSED BY THE CONTROLLER IN THIS CARD. ---- + # --- the write side (EV-04). `app/carmode.py` is the one caller. --------- + async def clamp_a(self) -> float: + """The most a write may ask for: `min(ev_max_a, the station limit read + from the charger, the entity's own range max)`.""" + raise NotImplementedError + async def write_current(self, a: float) -> bool: raise NotImplementedError @@ -376,6 +397,12 @@ class AlfenHaDriver(ChargerDriver): self._ents = entities_for(self.current_entity) self._hass = None self._getter = None + # Seams for the checks: how a write waits for the read-back, and the + # clock it counts on. + self._sleep = asyncio.sleep + self._clock = time.monotonic + self.clamp_faults = [] # (asked, clamp), newest last, for the log + self.sent = [] # every number value actually sent @classmethod def from_options(cls, opts: dict) -> "AlfenHaDriver": @@ -414,7 +441,6 @@ class AlfenHaDriver(ChargerDriver): return dict(self._ents) async def _states(self, roles=_ROLE_ORDER) -> dict: - import asyncio hass = self._h() got = await asyncio.gather(*(hass.state(self._ents[r]) for r in roles)) return dict(zip(roles, got)) @@ -434,20 +460,84 @@ class AlfenHaDriver(ChargerDriver): by_ent = {self._ents[r]: o for r, o in st.items()} return probe_from(self.current_entity, by_ent.get) - # --- the write side, UNUSED in EV-03 -------------------------------------- + # --- the write side ------------------------------------------------------- + async def clamp_a(self) -> float: + """`min(ev_max_a, station limit, entity range max)`. A limit the charger + did not answer is not a limit (the other two still bound the write).""" + st = await self._states(("current", "station", "station_active")) + station = _first(_amps(st["station_active"]), _amps(st["station"])) + rng = ENTITY_MAX_A + attrs = (st["current"] or {}).get("attributes") \ + if isinstance(st.get("current"), dict) else None + if isinstance(attrs, dict): + try: + rng = min(rng, float(attrs["max"])) + except (KeyError, TypeError, ValueError): + pass + return min(x for x in (self.max_a, station, rng) if x is not None) + async def write_current(self, a: float) -> bool: - a = max(0.0, min(float(a), self.max_a, ENTITY_MAX_A)) - return await self._h().set_number(self.current_entity, a) + """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 + SOFTWARE FAULT: nothing is sent, it is logged (the clamp watchdog's + shape) and the answer is False.""" + try: + a = float(a) + except (TypeError, ValueError): + a = float("nan") + clamp = await self.clamp_a() + if a != a or a < 0.0 or a > clamp + 1e-9: + self.clamp_faults.append((a, clamp)) + del self.clamp_faults[:-20] + _LOG.error("Software fault: the add-on was about to ask the charger " + "for more than its limit, so nothing was sent: " + "CHARGER_CLAMP.") + _LOG.debug("Asked for %.1f A against a limit of %.1f A.", a, clamp) + return False + hass = self._h() + self.sent.append(a) + del self.sent[:-50] + if not await hass.set_number(self.current_entity, a): + return False + return await self._took(a) + + async def _took(self, a: float) -> bool: + """Did the read-back follow the write, within `TOOK_S`?""" + t0 = self._clock() + while True: + st = await self._states(("readback", "current")) + seen = _first(_amps(st["readback"]), _amps(st["current"])) + if seen is not None and abs(seen - a) <= TOOK_TOL_A: + return True + if self._clock() - t0 >= TOOK_S: + return False + await self._sleep(1.0) async def write_phases(self, n: int) -> bool: + """Select 1 or 3 phases. ONLY THROUGH `carmode`'s safe sequence: the + setting moves the contactors, so it is touched with the car paused.""" if n not in (1, 3): return False - return await self._h().call("select", "select_option", { - "entity_id": self._ents["phases_set"], - "option": "1 Phase" if n == 1 else "3 Phases"}) + want = "1 Phase" if n == 1 else "3 Phases" + if not await self._h().call("select", "select_option", { + "entity_id": self._ents["phases_set"], "option": want}): + return False + t0 = self._clock() + while True: + st = await self._states(("phases_read", "phases_set")) + seen = _phases(st["phases_read"]) + if seen is None: + seen = _phases(st["phases_set"]) + if seen == n: + return True + if self._clock() - t0 >= TOOK_S: + return False + await self._sleep(1.0) async def release(self, mode: str) -> bool: - return await self.write_current(0.0) if mode == "solar" else True + """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).""" + return True class UnavailableCharger(ChargerDriver): @@ -473,6 +563,9 @@ class UnavailableCharger(ChargerDriver): async def limits(self) -> tuple: return None, None, None + async def clamp_a(self) -> float: + return 0.0 + async def read(self) -> ChargerReading: return ChargerReading(why=self.why) @@ -546,6 +639,12 @@ class CarTracker: c_low_since: float | None = None writer_at_utc: object = None _prev: tuple | None = None + # EV-04: our own writes, and the stuck-reading rule (SAFETY-37's shape) + mute_until: float = 0.0 + armed_at: float | None = None + armed_sig: tuple | None = None + sig: tuple | None = None + stuck_now: bool = False # today's energy day: str | None = None today_kwh: float | None = None @@ -564,7 +663,8 @@ class CarTracker: self.last_ok = now self.last_good, self.last_good_utc = r, now_utc if r.available: - self._writer(r, now_utc) + self._sig(r, now) + self._writer(r, now_utc, now) self._energy(r, day) self._timers(r, now) self._status_edge(now, now_utc) @@ -594,11 +694,58 @@ class CarTracker: except (TypeError, ValueError): return None + # -- EV-04: the stuck-reading rule ------------------------------------------- + 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.""" + 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: + self.armed_at, self.armed_sig = now, self.sig + + def _sig(self, r, now: float) -> None: + sig = (r.power_w, r.allowed_a) + if self.armed_at is not None and self.armed_sig is not None \ + and sig != self.armed_sig: + self.armed_at = self.armed_sig = None # it moved: alive + self.stuck_now = False + elif self.armed_at is not None and self.armed_sig is None: + self.armed_sig = sig + self.sig = sig + if self.armed_at is not None and now - self.armed_at >= STUCK_S: + self.stuck_now = True + + def stuck(self, now: float) -> bool: + """Power and read-back unchanged `STUCK_S` after a write that moved the + setpoint. Cleared the moment either moves.""" + return self.stuck_now + + def car_w_trusted(self, now: float): + """The car's power for the peak guard's ALARM PATH, or None. Fresh (the + EV-03 rules), not stuck, and never above what the read-back allows the + car to draw: an old or stuck figure must not hide a house overload.""" + w = self.car_w(now) + if w is None or self.stuck(now): + return None + r = self.reading + a = r.allowed_a if r.allowed_a is not None else r.setpoint_a + if a is not None: + n = r.phases_allowed if r.phases_allowed in (1, 3) else 3 + w = min(w, max(0.0, float(a)) * CEILING_V * n) + return w + # -- the two-writer detector ---------------------------------------------- - def _writer(self, r, now_utc): + def _writer(self, r, now_utc, now=None): cur = (r.setpoint_a, r.allowed_a) prev = self._prev - if prev is not None: + muted = now is not None and now < self.mute_until + if prev is not None and not muted: for a, b in zip(prev, cur): if a is not None and b is not None and a != b: self.writer_at_utc = now_utc diff --git a/goodwe_controller/app/ctl_alarms.py b/goodwe_controller/app/ctl_alarms.py index fe8f342..e982849 100644 --- a/goodwe_controller/app/ctl_alarms.py +++ b/goodwe_controller/app/ctl_alarms.py @@ -233,6 +233,9 @@ class AlarmsMixin: # persistent overload is still notified once per quarter. high = bool( g is not None and g.saturated and p is not None + # EV-04: not when the car you set explains the excess (a fresh, + # trusted car reading only; `ctl_car.car_cycle`). + and not getattr(self, "car_explains", False) and p.block_start is not None and not self._peak_rolled and peakguard.load_too_high( p, batt_w=batt, ceiling_w=g.ceiling_w, @@ -276,7 +279,8 @@ class AlarmsMixin: the floor binds this guard only; the loop has no SoC floor and goes on discharging. Edge-triggered. (DECISIONS/MAIN-orchestration-archive.md)""" g = self.peak_guard - limited = bool(g is not None and g.floor_limited) + limited = bool(g is not None and g.floor_limited + and not getattr(self, "car_explains", False)) if limited and (g.floor_w or 0.0) > 0.0: limited = self._reserve_short(g) else: diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py new file mode 100644 index 0000000..483553c --- /dev/null +++ b/goodwe_controller/app/ctl_car.py @@ -0,0 +1,310 @@ +"""EV-04: the Controller's side of the car's Manual mode. + +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. +""" + +import asyncio +import dataclasses +import logging +from datetime import timezone + +from . import carmode, chargers, messages, peakguard +from .tariff import QUARTER_S + +_LOG = logging.getLogger("goodwe") + +CAR_PEAK_KEY = "car_peak_q" # {quarter start iso: the car's average W} +CAR_PEAK_MIN_W = 50.0 # a quarter the car hardly touched is not kept +CAR_PEAK_KEEP = 3200 # about a month of quarters +OVER_HOLD_S = peakguard.ALARM_HOLD_S + + +class CarMixin: + # ------------------------------------------------------------------ state + def car_init(self, opts, store) -> None: + """Mode, current and phases from the store; `ev_mode_start` says what a + restart does with the mode. A site with no charger keeps defaults and + writes nothing.""" + data = getattr(store, "data", None) or {} + self.car_mode = carmode.start_mode(opts, data.get(carmode.KEY_MODE)) + if carmode.start_mode(opts, carmode.MANUAL) == carmode.OFF \ + and data.get(carmode.KEY_MODE) not in (None, carmode.OFF): + store.set(carmode.KEY_MODE, carmode.OFF) + clamp = carmode.clamp_for(opts, None) + a = carmode.value_a(data.get(carmode.KEY_A, carmode.DEFAULT_A), clamp) + self.car_a = carmode.DEFAULT_A if a is None else a + n = data.get(carmode.KEY_PHASES, carmode.DEFAULT_PHASES) + ok = carmode.allowed_phases(opts) + self.car_n = n if n in ok else ok[0] + self.car_rev = 0 + self.car_writer = carmode.ManualWriter() + self._car_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_notified = None # the session a notice was raised for + self._car_session = 0 + self._car_prev_state = None + self._carq = {"key": None, "ws": 0.0, "mono": None} + self._peak_proj_real = None + saved = data.get(CAR_PEAK_KEY) + self.car_peak_q = dict(saved) if isinstance(saved, dict) else {} + + @property + def car_cover(self) -> bool: + """Decision 1: do the batteries help cover the car down to the peak + reserve? Default yes.""" + v = self.o.get("ev_batt_cover") + return bool(chargers.EV_OPTION_DEFAULTS["ev_batt_cover"] + if v is None else v) + + def car_manual(self) -> bool: + return (self.charger.configured() + and self.car_mode == carmode.MANUAL) + + def car_clamp(self): + return carmode.clamp_for(self.o, self.car.reading) + + def car_writing(self) -> bool: + """May the add-on write to the charger now? Control runs, shadow mode is + off, and the add-on is not shutting down. Shadow mode gates charger + writes exactly as it gates inverter writes.""" + return bool(self.auto and not self.shadow + and not getattr(self, "stopping", False)) + + # ---------------------------------------------------------------- actions + def _car_action(self, what, value, now) -> dict: + """The mode, the current or the phases, from the page or from Home + Assistant. Store state, applied by the next step with no restart.""" + if not self.charger.configured(): + return {"error": messages.car_refused("off")} + if what == "car_mode": + if value not in carmode.MODES: + return {"error": messages.car_refused("value")} + self.car_mode = value + self.store.set(carmode.KEY_MODE, value) + elif what == "car_current": + clamp = self.car_clamp() + if isinstance(value, bool): + return {"error": messages.car_refused("value")} + a = carmode.value_a(value, clamp) + try: + inside = a is not None and abs(float(value) - a) < 0.5 + except (TypeError, ValueError): + inside = False + if not inside: + return {"error": messages.car_refused("value")} + self.car_a = a + self.store.set(carmode.KEY_A, a) + else: + if value not in (1, 3) or isinstance(value, bool): + return {"error": messages.car_refused("value")} + if value not in carmode.allowed_phases(self.o): + return {"error": messages.car_refused("phases")} + self.car_n = value + self.store.set(carmode.KEY_PHASES, value) + self.car_rev += 1 + self.car_writer.user_changed() + self.log_event(f"car {what[4:]} set to {value} by operator", + hint=messages.hint(what)) + return {"mode": self.car_mode, "current": self.car_a, + "phases": self.car_n} + + def car_command_values(self) -> dict: + """The MQTT state of the three car entities.""" + return {"car_mode": carmode.MODE_LABELS[self.car_mode], + "car_current": round(self.car_a), + "car_phases": str(self.car_n)} + + # ------------------------------------------------------------- the writer + def car_kick(self) -> None: + """Start one writer step in the background, unless one is running. A + write waits up to 10 s for the charger's read-back, and a control cycle + never waits for the charger.""" + if not self.charger.configured(): + return + t = self._car_task + if t is not None and not t.done(): + return + self._car_task = asyncio.ensure_future(self._car_run()) + + async def car_settle(self) -> None: + """Wait for the writer step in flight (the checks use it).""" + t = self._car_task + if t is not None: + await asyncio.gather(t, return_exceptions=True) + + async def _car_run(self) -> None: + try: + await self.car_step() + except asyncio.CancelledError: + raise + except Exception: # noqa: BLE001 + # Once at WARNING-and-above, then quietly: a step that fails + # fails every second. + if not self._car_step_failed: + self._car_step_failed = True + _LOG.exception("The car charger step failed") + else: + _LOG.debug("The car charger step failed again", exc_info=True) + else: + self._car_step_failed = False + + async def car_shutdown(self) -> None: + """The add-on stops: no new write, and a phase change in the middle is + undone by giving the car its current back. The current stands + otherwise (Manual's fail state).""" + 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 not self.charger.configured() \ + or getattr(self, "car_writer", None) is None \ + or self.car_writer.seq is None: + return + try: + await asyncio.wait_for(self.car_writer.abandon( + self.charger, self.car_now(), self.car), 15.0) + except Exception: # noqa: BLE001 + _LOG.warning("The car could not be given its current back " + "before the add-on stopped: CHARGER_RESTORE.") + + async def car_step(self) -> None: + """One step of Manual. Reads nothing from the world (the cycle's read + did) and writes only through `carmode.ManualWriter`.""" + 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(), + status=self.car.status(now, True)) + + # ------------------------------------------- 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(): + return None + return self.car.car_w_trusted(self.car_now()) + + def _car_quarter(self, proj, w, mono) -> None: + """The car's energy in the open quarter, for the average the guard's + house leaves out and for the peak line.""" + q = self._carq + key = None if proj is None else proj.block_start + last = q["mono"] + if key != q["key"]: + self._car_bank(q) + q["key"], q["ws"] = key, 0.0 + if key is not None and w is not None and last is not None: + q["ws"] += float(w) * min(max(mono - last, 0.0), 5.0) + q["mono"] = mono + + def _car_bank(self, q) -> None: + """A closed quarter in which the car drew its share goes on the list.""" + key = q["key"] + if key is None: + return + avg = q["ws"] / QUARTER_S + if avg < CAR_PEAK_MIN_W: + return + self.car_peak_q[key.astimezone(timezone.utc).isoformat()] = round(avg) + if len(self.car_peak_q) > CAR_PEAK_KEEP: + for k in sorted(self.car_peak_q)[:-CAR_PEAK_KEEP]: + del self.car_peak_q[k] + self.store.set(CAR_PEAK_KEY, dict(self.car_peak_q)) + + def car_avg_w(self, proj, w) -> float: + """The car's average over the whole open quarter: what it drew so far + and `w` for the rest.""" + if proj is None or w is None: + return 0.0 + left = max(0.0, QUARTER_S - float(proj.elapsed_s)) + so_far = self._carq["ws"] if self._carq["key"] == proj.block_start \ + else 0.0 + return (so_far + float(w) * left) / QUARTER_S + + def car_exclude(self, proj, w): + """Decision 1 off: the projection the guard sees without the car + (`house - car_w`). Unchanged without a fresh car reading.""" + if proj is None or w is None or proj.block_start is None: + return proj + avg = self.car_avg_w(proj, w) + return dataclasses.replace( + proj, projected_w=max(0.0, float(proj.projected_w) - avg), + held_w=max(0.0, float(proj.held_w) - float(w))) + + def car_cycle(self, real_proj, guard, target_w, now_utc) -> None: + """After the guard has decided: does the car alone explain the excess? + `real_proj` is the projection WITH the car, whatever the guard saw.""" + mono = self.car_now() + w = self.car_alarm_w() + self._car_quarter(real_proj, w, mono) + self._car_session_tick(mono) + explains = over = False + if w is not None and real_proj is not None and target_w is not None \ + and real_proj.block_start is not None: + # The car explains the excess when the house alone would land the + # period under the aim: what the car takes over the whole period + # (`car_avg_w`) is at least how far the projection is over it. + ex = float(real_proj.projected_w) - float(target_w) + beyond = ex > 0.0 and self.car_avg_w(real_proj, w) >= ex + if self.car_cover: + explains = bool( + beyond and guard is not None + and (guard.saturated or guard.floor_limited)) + over = explains + else: + over = beyond + self.car_explains = explains + if over: + if self._car_over_since is None: + self._car_over_since = mono + held = mono - self._car_over_since >= OVER_HOLD_S + else: + self._car_over_since, held = None, False + self.car_over = held + + def _car_session_tick(self, mono) -> None: + """A charging session is a plug-in: the state goes from no car to a + car. The notice is raised once per session.""" + s = self.car.status(mono, True) + if s in (chargers.NONE_,) and self._car_prev_state not in ( + None, chargers.NONE_): + self._car_over_notified = None + if s not in (chargers.NONE_, None) and self._car_prev_state in ( + chargers.NONE_, None): + self._car_session += 1 + self._car_prev_state = s + + async def check_car_over(self) -> None: + """One grey notice per charging session: the charge you set takes the + 15-minute period over the peak limit. Raised nowhere else.""" + if not self.car_over or self._car_over_notified == self._car_session: + return + self._car_over_notified = self._car_session + _LOG.info("The car charge you set takes this 15-minute period over " + "the peak limit: CAR_OVER_PEAK.") + await self.hass.call("persistent_notification", "create", + messages.car_over(f"{self.car_a:.0f}").data()) + + def car_peak_by_car(self, reading, now): + """`(True, local time)` when the month's peak quarter was one the car + mostly made (it drew half the peak or more), else `(False, None)`.""" + if reading is None or not getattr(reading, "is_observed", False) \ + or reading.quarter_start is None or not self.car_peak_q: + return False, None + avg = self.car_peak_q.get( + reading.quarter_start.astimezone(timezone.utc).isoformat()) + if avg is None or reading.peak_w is None \ + or 2.0 * float(avg) < float(reading.peak_w): + return False, None + return True, reading.quarter_start diff --git a/goodwe_controller/app/ctl_cycle.py b/goodwe_controller/app/ctl_cycle.py index 3a03b07..82c0bab 100644 --- a/goodwe_controller/app/ctl_cycle.py +++ b/goodwe_controller/app/ctl_cycle.py @@ -391,6 +391,15 @@ class CycleMixin: if self._peak_proj is not None and len(self.inverters) > 1: self._peak_proj = next_quarter(self._peak_proj, self.p1.averager.max_hold_s) + # EV-04, decision 1: with "Batteries help with the peak while the car + # charges" OFF, the guard's house leaves the car out (`house - car_w`). + # `_peak_proj_real` keeps the quarter as the meter will bill it, for + # the car's own words. Only a fresh, trusted car reading is left out. + self._peak_proj_real = self._peak_proj + if (self._peak_proj is not None and not self.car_cover + and self.car_manual()): + self._peak_proj = self.car_exclude(self._peak_proj, + self.car_alarm_w()) self.peak_guard = None if not self.p1_enabled else peakguard.decide( self._peak_proj, # ⚠️ THE SITE SUM. The guard sizes a floor from what the battery is @@ -440,6 +449,13 @@ class CycleMixin: self.peak_guard = self._peak_landing(self.peak_guard) self.peak_guard = peakguard.cap_floor( # SAFETY-128 self.peak_guard, self.answer.peak_cap(site_standing)) + # EV-04: does the car alone explain what the guard cannot hold? Fresh + # car readings only; the claim, the floor and the commands above are + # not touched by it. + self.car_cycle(self._peak_proj_real, self.peak_guard, + peakguard.quarter_target_w( + float(self.o.get("peak_cap_w", 3500)), + self.peak_margin_w, _reading), now) # SITE, and peakguard.claim() says so on the object it builds: the # quantity is the 15-minute average OFFTAKE AT THE GRID CONNECTION, # which the capacity tariff bills (one quarter-hour peak per site, not @@ -1048,6 +1064,8 @@ class CycleMixin: # and, on a change only, one Home Assistant call. await self.check_price_gap() await self.check_charger() + await self.check_car_over() + self.car_kick() # EV-04: Manual, in the background await self.check_fixed_note() # SAFETY-31's alarm, and its boundary is the LATCH, not a number: it diff --git a/goodwe_controller/app/ctl_status.py b/goodwe_controller/app/ctl_status.py index f83f4c2..20eed53 100644 --- a/goodwe_controller/app/ctl_status.py +++ b/goodwe_controller/app/ctl_status.py @@ -15,8 +15,8 @@ from .freeze import rail_unreachable, rail_w from .hass import OUTAGE from .maintenance import IDLE from .mqtt import ( - PAYLOAD_NONE, announced_units, optional_keys, parse_command, unit_slugs, - unit_state_key, + BASE, PAYLOAD_NONE, announced_units, optional_keys, parse_car_command, + parse_command, unit_slugs, unit_state_key, ) from . import peakguard from . import pv as pv_read @@ -35,6 +35,9 @@ class StatusMixin: already holds the last choice). Never raises: MQTT must not reach control. (DECISIONS/MAIN-orchestration-archive.md)""" try: + if isinstance(topic, str) and topic.startswith(f"{BASE}/car/"): + await self._car_mqtt_command(topic, payload, retained) + return slug, action, value, why = parse_command( topic, payload, retained, packmode.MODES) if why is None: @@ -68,6 +71,29 @@ class StatusMixin: except Exception: # noqa: BLE001 _LOG.exception("Home Assistant command could not be handled") + async def _car_mqtt_command(self, topic, payload, retained) -> None: + """EV-04: one command from the car's HA entities, through + handle_action(). A retained command is never applied. Never raises.""" + action, value, why = parse_car_command(topic, payload, retained) + result = None + if why is None: + result = await self.handle_action(action, value=value) + if isinstance(result, dict) and "error" not in result: + self.mqtt.publish(self.car_command_values()) + return + why = result["error"] if isinstance(result, dict) else "refused" + else: + why = messages.car_refused("topic") if why == "topic" else \ + messages.pack_refused(why) + topic_s = "".join(c if c.isprintable() else "?" for c in str(topic)[:128]) + _LOG.debug("Home Assistant command %s %s refused: %s", topic_s, + repr(payload)[:48], why) + if (topic_s, why) not in self._mqtt_refused \ + and len(self._mqtt_refused) < 32: + self._mqtt_refused.add((topic_s, why)) + _LOG.warning("Home Assistant command on %s ignored: %s", topic_s, + why) + @property def why_words(self) -> str: """The page's "Why" line. While control waits for a missing reading @@ -178,9 +204,30 @@ class StatusMixin: out.append({"ok": False, "warn": True, "id": "charger", "text": messages.row_charger_unreach( f"{brussels(self.car.bad_since_utc):%H:%M}")}) - if self.car.other_writer(datetime.now(timezone.utc)): + w = self.car_writer + if self.car_mode == "manual": + # EV-04: in Manual the add-on's own writes are not "another + # writer"; its own detector (a read-back that differs from the + # last write for 30 s) says so, in grey. + if w.other: + out.append({"ok": True, "warn": True, "id": "charger_other", + "text": messages.row_charger_other()}) + if w.gave_up: + out.append({"ok": False, "warn": True, "id": "charger_refused", + "text": messages.row_charger_refused()}) + elif self.car.other_writer(datetime.now(timezone.utc)): out.append({"ok": True, "warn": True, "id": "charger_writer", "text": messages.row_charger_writer()}) + if self.car.stuck(self.car_now()): + out.append({"ok": False, "warn": True, "id": "charger_stuck", + "text": messages.row_charger_stuck()}) + r = self.car.reading + if r is not None and r.available and r.error: + out.append({"ok": True, "warn": True, "id": "charger_error", + "text": messages.row_charger_error(r.error)}) + if self.car_over: + out.append({"ok": True, "warn": True, "id": "car_over", + "text": messages.row_car_over()}) return out def car_values(self) -> dict: @@ -192,6 +239,7 @@ class StatusMixin: with homeview.in_lang("en"): word = homeview.car_state_word(state) return { + **self.car_command_values(), "car_state": word, # `ABSENT_AS_UNKNOWN` stays the one PV key (test_pv.py): an absent # car figure is HA's own "no value" payload, sent by name. @@ -335,6 +383,13 @@ class StatusMixin: if _pg is None: out.append({"ok": True, "warn": True, "id": "peak_guard", "text": messages.row_peak_guard_waiting()}) + elif self.car_explains and (_pg.saturated or _pg.floor_limited): + # EV-04: the car you set is what the batteries cannot hold, so + # no red row. The grey row `car_over` says what is going on. + out.append({"ok": True, "warn": False, "id": "peak_guard", + "text": messages.row_peak_guard_on( + _pg.floor_w or 0.0, _pg.ceiling_w, + shadow=self.shadow)}) elif _pg.saturated and not _pg.within_aim: out.append({"ok": False, "warn": False, "id": "peak_guard", "runs": True, @@ -864,6 +919,8 @@ 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"): + return self._car_action(what, value, now) if what == "auto_toggle": self.auto = not self.auto self.store.set("auto", self.auto) diff --git a/goodwe_controller/app/homeview.py b/goodwe_controller/app/homeview.py index 4e93ca0..941e941 100644 --- a/goodwe_controller/app/homeview.py +++ b/goodwe_controller/app/homeview.py @@ -19,7 +19,8 @@ section at the bottom and is held to STYLE.md by test_messages.py. import contextlib from datetime import datetime, timedelta, timezone -from . import arbitrage, cheaproll, handback, messages, peakguard, priceruns, uitext +from . import (arbitrage, carmode, cheaproll, handback, messages, peakguard, + priceruns, uitext) from .dayplan import EFF from .maintenance import CHARGE as M_CHARGE, DRAIN as M_DRAIN, HOLD as M_HOLD from .maintenance import IDLE as M_IDLE, next_slot_start @@ -871,8 +872,10 @@ def peak_engaged(c) -> bool: only), so no battery gives power for it. Nor when the quarter ends on the aim anyway (SAFETY-126, `within_aim`).""" pg = getattr(c, "peak_guard", None) + # EV-04: not for a cause the car's own Why explains. return bool(pg is not None and pg.engaged and (pg.floor_w or 0.0) > 0.0 - and not pg.within_aim) + and not pg.within_aim + and not getattr(c, "car_explains", False)) def battery_rows(c, shadow, running, held=False): @@ -1129,10 +1132,30 @@ def month_peak(c, now): if pg is not None: out["period_w"] = pg.projected_w ceiling = pg.ceiling_w or limit_w + real = getattr(c, "_peak_proj_real", None) + if getattr(c, "car_enabled", False) and c.charger.configured() \ + and not c.car_cover and c.car_manual() and real is not None \ + and getattr(real, "block_start", None) is not None: + # EV-04, decision 1 off: the guard's own projection leaves the car + # out; the period as the meter will bill it does not. + out["period_w"] = real.projected_w out["line"] = line_period(out["period_w"], ceiling, c.shadow, unmeasured=getattr(c, "peak_unmeasured_s", 0.0) > 0.0, cut=getattr(c, "room_charge", False)) + # EV-04: when a car charge you asked for is in this period, and when one + # set the month's peak. Both empty without a charger in Manual. + out["car_line"] = out["set_by"] = "" + if getattr(c, "car_enabled", False) and c.charger.configured(): + w = c.car_alarm_w() + if pg is not None and w is not None and w >= 500.0 \ + and out["period_w"] is not None and (pg.engaged or c.car_over): + out["car_line"] = _t("peak.car", kw=_kw(out["period_w"]), + car=_kw(w), + cov=_kw(max(0.0, float(c.site_batt_w or 0)))) + by_car, at = c.car_peak_by_car(reading, now) + if by_car: + out["set_by"] = _t("peak.set_by_car", t=f"{brussels(at):%H:%M}") return out @@ -1278,6 +1301,35 @@ def _car_why(key, c, good): return _t("car.why." + (key if key else "wait")) +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.""" + 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: + 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 + else "car.why.manual_full", a=a, pct=pct) + if c.shadow: + t, n = w.would if w.would is not None else (c.car_a, c.car_n) + return _t("car.why.manual_would", a=f"{float(t):.0f}", + phases=car_phases_word(n)) + if not c.auto: + return _t("car.why.manual_stopped") + if key in ("none", "full"): + return _t("car.why.manual_wait", a=a) + if w.blocked: + return _t("car.why.manual_blocked") + if c.car_cover and peak_engaged(c): + giving = max(0.0, float(c.site_batt_w or 0.0)) + return _t("car.why.manual_cover", a=a, kw=_kw(giving), pct=pct) + return _t("car.why.manual_set", a=a, phases=car_phases_word(c.car_n)) + + 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).""" @@ -1292,17 +1344,32 @@ def car_block(c, now): today = None if configured and c.car.today_kwh is not None: today = _t("car.today", kwh=_kwh(c.car.today_kwh)) - return { + mode = getattr(c, "car_mode", "off") if configured else "off" + why = _car_why(key, c, good) + if mode == "manual" and key in ("charging", "waiting", "none", "full"): + why = _car_manual_why(c, key) + out = { "state": key or "wait", "chip": car_state_word(key), "kind": _CAR_KIND.get(key, "muted"), "big": _car_big(key, c, r if fresh else None, good), "today": today, - "why": _car_why(key, c, good), - "mode": "off", + "why": why, + "mode": mode, "power_w": (None if not fresh or r is None or r.power_w is None else round(float(r.power_w), 1)), } + if configured: + # EV-04: what the page can set. Off and Manual only (Solar and Night + # are later cards, so they are not offered). + clamp = c.car_clamp() + hi = int(clamp) if clamp is not None and clamp >= 6 else 6 + out["modes"] = ["off", "manual"] + out["current"] = {"value": round(float(c.car_a)), "min": 6, + "max": hi} + out["phases"] = {"value": c.car_n, + "choices": list(carmode.allowed_phases(c.o))} + return out # =========================================================================== # @@ -1815,8 +1882,12 @@ def _samples() -> list: out += [("title", _t("car.state." + k)) for k in words["car"]["state"]] out += [("plan", _t("car.big." + k, t="09:12")) for k in words["car"]["big"]] - out += [("plan", _t("car.why." + k, a="10", brand="Alfen")) + out += [("plan", _t("car.why." + k, a="10", brand="Alfen", kw="8.6 kW", + pct="20 %", phases=car_phases_word(3))) 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", "11.0 kW · 16 A · " + _t("car.phase_many", n=3))] out += [("plan", line_no_trade(k)) for k in diff --git a/goodwe_controller/app/main.py b/goodwe_controller/app/main.py index b8b8325..8b622c9 100644 --- a/goodwe_controller/app/main.py +++ b/goodwe_controller/app/main.py @@ -42,6 +42,7 @@ from .arbiter import ( P_SAFETY, SET, Claim, Resolution, actuator_for, pre_resolve, resolve, ) from . import allocator +from . import carmode from . import chargers from . import dayplan from . import modetrade @@ -83,8 +84,9 @@ from .maintenance import ( CHARGE, DRAIN, HOLD, IDLE, POWER_MOVING, MaintConfig, Maintenance, FAIL_BACKOFF_DAYS, MaintResult, arbitrate as maint_arbitrate, site_zone, ) -from .mqtt import (MODE_CONFIGS_KEY, MODE_LABELS, USE_OFF, USE_ON, - MqttPublisher, announced_units, mode_configs, +from .mqtt import (CAR_CONFIGS_KEY, MODE_CONFIGS_KEY, MODE_LABELS, USE_OFF, + USE_ON, MqttPublisher, announced_units, car_configs, + mode_configs, optional_keys, parse_command, unit_slugs, unit_state_key) from . import peakguard from . import packshare @@ -113,6 +115,7 @@ from . import web # stays importable from `app.main`. DECISIONS/MAIN-orchestration.md. from .ctl_tasks import TasksMixin from .ctl_status import StatusMixin +from .ctl_car import CarMixin from .ctl_alarms import ( AlarmsMixin, HANDBACK_CYCLES, REANNOUNCE_S, ROLLING_BOUND_CYCLES, ROLLING_S, SHORT_CYCLES, SHORT_SPAN_S, @@ -183,7 +186,7 @@ def _load_latch(data, now=None): class Controller(InputsMixin, WritesMixin, TradeMixin, CycleMixin, AlarmsMixin, - StatusMixin, TasksMixin): + StatusMixin, TasksMixin, CarMixin): def __init__(self, opts: dict, hass: HomeAssistant, store, mqtt_pub, *, stop, peak_db_path: str = "/data/tariff.db", price_history_path: str = "/data/price_history.json", @@ -576,6 +579,8 @@ class Controller(InputsMixin, WritesMixin, TradeMixin, CycleMixin, AlarmsMixin, self._charger_probed = False self._car_down_logged = False self._car_announced = False + # EV-04: Manual mode's state (runtime, in the store) and its writer. + self.car_init(opts, store) self.house_profile = None if self.fc_entity is not None: self.house_profile = dayplan.HouseProfile( @@ -1036,6 +1041,7 @@ class Controller(InputsMixin, WritesMixin, TradeMixin, CycleMixin, AlarmsMixin, _LOG.info(handback.log_shutdown(handback.current()) or "shutting down - commanding 0 W on every inverter") await self.command_site_release() + await self.car_shutdown() # EV-04: undo a phase change half way self.mqtt.close() @@ -1062,6 +1068,23 @@ def mode_announcement(opts, store) -> tuple: return modes, retract +def car_announcement(opts, store) -> tuple: + """EV-04: `(car, retract)` for the MQTT publisher at start-up: the three car + entities while a charger is switched on, and the config topics to remove + when it is not (`mqtt.car_configs()`). A site that never had a charger gets + nothing and its store is not written.""" + car = None + if chargers.census_entity(opts): + amps = chargers.max_a(opts) + car = (chargers.EV_OPTION_DEFAULTS["ev_max_a"] if amps is None + else amps, carmode.allowed_phases(opts)) + stored = store.data.get(CAR_CONFIGS_KEY) + keep, retract = car_configs(car, stored) + if keep and keep != stored: + store.set(CAR_CONFIGS_KEY, keep) + return car, retract + + def control_task_done(task: asyncio.Task, *, controller, stop: asyncio.Event, died: list) -> None: """Done-callback on the control task: log its death now and wake amain() @@ -1231,6 +1254,7 @@ async def amain() -> None: # OPT-11 P2: each battery's switch and mode list, only while # battery modes are on (`mode_announcement()`). _modes, _retract = mode_announcement(opts, store) + _car, _car_retract = car_announcement(opts, store) broker = await hass.mqtt_service() pub = MqttPublisher( broker.get("host") if broker else None, @@ -1250,6 +1274,8 @@ async def amain() -> None: units=roster_names(opts), modes=_modes, retract=_retract, + car=_car, + car_retract=_car_retract, ) except Exception as err: # noqa: BLE001 _LOG.warning("MQTT unavailable (%s) - continuing without status entities", err) diff --git a/goodwe_controller/app/messages.py b/goodwe_controller/app/messages.py index 9014bc8..e04b400 100644 --- a/goodwe_controller/app/messages.py +++ b/goodwe_controller/app/messages.py @@ -188,6 +188,8 @@ T_METER_FROZEN_NL = "Meter staat mogelijk vast" TITLE_NL = {T_LOOP_BOUND: T_LOOP_BOUND_NL, T_OUTPUT_CLAMP: T_OUTPUT_CLAMP_NL} T_CHARGER_UNREACH = "Charger not reachable" T_CHARGER_UNREACH_NL = "Laadpaal onbereikbaar" +T_CAR_OVER = "Car over the peak limit" +T_CAR_OVER_NL = "Auto boven de piekgrens" T_NO_PRICES = "No prices" T_NO_PRICES_NL = "Prijzen ontbreken" @@ -201,6 +203,7 @@ ID_METER_FROZEN = "goodwe_meter_frozen" ID_MAINT_FAILED = "goodwe_maint_failed_{slug}" ID_NO_PRICES = "goodwe_no_prices" ID_CHARGER_UNREACH = "goodwe_charger_unreachable" +ID_CAR_OVER = "goodwe_car_over" # 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" @@ -496,6 +499,54 @@ def row_charger_writer() -> str: "Iets anders wijzigt de laadpaal en deze add-on leest alleen.") +def car_over(a_text) -> Notice: + """EV-04: a charge the user set takes the 15-minute period over the peak + limit, and the batteries cannot hold it. Grey, once per charging session. + Not an alarm: the car is never throttled, the user asked for it.""" + en = (f"You set {a_text} A, which takes this 15-minute period over the " + "peak limit.") + nl = f"U stelde {a_text} A in, wat dit kwartier boven de piekgrens brengt." + return Notice(ID_CAR_OVER, INFO, T_CAR_OVER, en, + body_nl=f"{T_CAR_OVER_NL}. {nl}") + + +def row_car_over() -> str: + """EV-04: the grey row while the car charge you set is over the peak limit.""" + return Bi("The car charge you set takes this 15-minute period over the " + "peak limit.", + "De autolading die u instelde brengt dit kwartier boven de " + "piekgrens.") + + +def row_charger_other() -> str: + """EV-04: the grey row, in Manual, while something else sets the current.""" + return Bi("Something else changed the charger, so the add-on writes " + "nothing until you change it.", + "Iets anders wijzigde de laadpaal, dus de add-on schrijft niets " + "tot u iets wijzigt.") + + +def row_charger_stuck() -> str: + """EV-04: the amber row when the charger's reading does not move.""" + return Bi("The charger reading may be stuck, so check the charger.", + "De meting van de laadpaal staat mogelijk vast, dus controleer " + "de laadpaal.") + + +def row_charger_refused() -> str: + """EV-04: the amber row when the charger does not take the setting.""" + return Bi("The charger did not take the setting, so check the charger.", + "De laadpaal nam de instelling niet over, dus controleer de " + "laadpaal.") + + +def row_charger_error(text) -> str: + """EV-04: the grey row while the charger reports an error. Writes go on.""" + t = " ".join(str(text or "").split())[:60] + return Bi(f"The charger reports an error: {t}.", + f"De laadpaal meldt een fout: {t}.") + + def row_charger_setup() -> str: """EV-03: the amber row when the charger's entities are not found.""" return Bi("The add-on cannot find the charger, so check its entity in " @@ -1423,6 +1474,9 @@ def why_waiting(missing_s) -> str: HINTS = { "control_started": "Control started", "control_stopped": "Control stopped", + "car_mode": "Car mode set", + "car_current": "Car current set", + "car_phases": "Car phases set", "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", @@ -1511,6 +1565,20 @@ def pack_refused(why: str) -> str: return PACK_REFUSED[why] +# EV-04: why a car mode, current or phases change was refused (the page and +# Home Assistant show it). +CAR_REFUSED = { + "off": "The car charger is not set up.", + "value": "That choice is not possible for the car charger.", + "phases": "The charger limit allows only one number of phases.", + "topic": "That is not a car command.", +} + + +def car_refused(why: str) -> str: + return CAR_REFUSED[why] + + # MAINT-11: why a start or stop of ONE battery's cycle was refused. `{unit}` is # the battery the sentence is about (for "busy", the one that is cycling). The # page shows the same sentences in Dutch from app/ui_text, keyed by the code. @@ -1703,6 +1771,11 @@ def status_samples() -> list: ("row_no_prices", AMBER, row_no_prices()), ("row_charger_unreach", AMBER, row_charger_unreach("09:12")), ("row_charger_writer", GREEN, row_charger_writer()), + ("row_car_over", GREEN, row_car_over()), + ("row_charger_other", GREEN, row_charger_other()), + ("row_charger_error", GREEN, row_charger_error("Socket error")), + ("row_charger_stuck", AMBER, row_charger_stuck()), + ("row_charger_refused", AMBER, row_charger_refused()), ("row_charger_setup", AMBER, row_charger_setup()), ] @@ -1740,6 +1813,7 @@ def samples() -> list: no_prices(*_SINCE_OLDER), no_prices(), charger_unreachable("09:12"), + car_over("16"), ] @@ -1806,6 +1880,8 @@ LABELS = { "ev_charger": "Charger", "ev_current_entity": "Current setting entity", "ev_max_a": "Charger limit", + "ev_batt_cover": "Batteries help with the peak", + "ev_mode_start": "Mode after a restart", "ev_phases": "Phases", } @@ -1890,6 +1966,8 @@ LABELS_NL = { "ev_charger": "Laadpaal", "ev_current_entity": "Entiteit van de laadstroom", "ev_max_a": "Laadpaalgrens", + "ev_batt_cover": "Batterijen helpen met de piek", + "ev_mode_start": "Modus na een herstart", "ev_phases": "Fasen", } # The inverter list shows two of them under a shorter name. diff --git a/goodwe_controller/app/mqtt.py b/goodwe_controller/app/mqtt.py index 85f422c..be471be 100644 --- a/goodwe_controller/app/mqtt.py +++ b/goodwe_controller/app/mqtt.py @@ -405,7 +405,7 @@ def _unit_places(names): yield slug, device, prefix -def discovery_payloads(units=(), omit=(), include=(), modes=()) -> list: +def discovery_payloads(units=(), omit=(), include=(), modes=(), car=None) -> list: """Every `(topic, payload)` this add-on announces, in announcement order. Split out of `_announce()` so that the acceptance criterion can be graded as @@ -421,6 +421,8 @@ def discovery_payloads(units=(), omit=(), include=(), modes=()) -> list: re-announces every entity on a live install). `modes` (OPT-11 P2) is the battery modes offered, empty when they are off. + `car` (EV-04) is None, or `(max_a, phases)`: the car's three command + entities, announced after everything else so no existing row moves. """ omit = set(omit) include = [k for k in include if k not in omit] @@ -452,6 +454,7 @@ def discovery_payloads(units=(), omit=(), include=(), modes=()) -> list: DEVICE, unit, dev_class, state_class, icon))) # OPT-11 P2: last, and only when battery modes are on. out.extend(mode_payloads(units, modes)) + out.extend(car_payloads(car)) return out @@ -518,6 +521,101 @@ def mode_payloads(units, modes) -> list: return out +# --- EV-04: the car's mode, current and phases, as HA entities ---------------- +# Announced only with a charger switched on, after every other row. A command +# goes through Controller.handle_action(); a retained one is dropped. +CAR_MODE_LABELS = {"off": "Off", "manual": "Manual"} # English, pinned +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_CONFIG_RE = re.compile( + rf"homeassistant/(select|number)/{BASE}_car_(mode|current|phases)/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"), +] + + +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.""" + if not car: + return [] + max_a, phases = car + out = [] + for key, component, name, icon in CAR_ENTITIES: + unique_id = f"{BASE}_car_{key}" + cfg = { + "name": name, + "object_id": f"goodwe_car_{key}", + "unique_id": unique_id, + "state_topic": f"{BASE}/car_{key}", + "command_topic": f"{BASE}/car/{key}/set", + } + if key == "mode": + cfg["options"] = list(CAR_MODE_LABELS.values()) + elif key == "phases": + cfg["options"] = [str(n) for n in phases] + else: + cfg.update({"min": CAR_MIN_A, "max": int(max_a), "step": 1, + "unit_of_measurement": "A", "device_class": "current", + "mode": "box"}) + cfg.update({"retain": False, "availability_topic": AVAILABILITY, + "device": DEVICE, "icon": icon}) + out.append((f"homeassistant/{component}/{unique_id}/config", cfg)) + return out + + +def car_configs(car, stored) -> tuple: + """`(keep, retract)` at start-up, as `mode_configs()` does for the battery + modes: turning the charger off removes exactly the entities announced + before, and a site that never had one publishes nothing.""" + current = [t for t, _ in car_payloads(car)] + old = [t for t in (stored if isinstance(stored, list) else []) + if isinstance(t, str) and _CAR_CONFIG_RE.fullmatch(t) + and t not in current] + old = list(dict.fromkeys(old)) + return current + old, old + + +def parse_car_command(topic, payload, retained): + """`(action, value, reject)` for one message on a car command topic. + `action` is `car_mode`, `car_current` or `car_phases`. A value that is + none of the entity's own is None (the action then refuses it).""" + m = _CAR_CMD_RE.fullmatch(topic) if isinstance(topic, str) else None + if m is None: + return None, None, "topic" + key = m.group(1) + action = f"car_{key}" + if bool(retained): + return action, None, "retained" + if not isinstance(payload, (bytes, bytearray)): + return action, None, "size" + if MAX_COMMAND_BYTES < len(payload): + return action, None, "size" + try: + text = bytes(payload).decode(encoding="utf-8").strip() + except ValueError: # UnicodeDecodeError is one + return action, None, "encoding" + value = None + if key == "mode": + value = next((k for k, v in CAR_MODE_LABELS.items() if v == text), + None) + elif key == "phases": + value = {"1": 1, "3": 3}.get(text) + else: + try: + f = float(text) + value = f if f == f and abs(f) < 1000 else None + except ValueError: + value = None + return action, value, None + + def mode_retractions(stored, current) -> list: """Config topics announced before and not now: each gets an empty retained config, which removes the entity from HA. Anything in the store @@ -574,11 +672,13 @@ class MqttPublisher: # test fixture that builds one with __new__) behaves as before. modes = () retract = () + car = None # EV-04: `(max_a, phases)` when the charger is on _loop = None _handler = None def __init__(self, host, port, username=None, password=None, omit=(), - units=(), include=(), modes=(), retract=()): + units=(), include=(), modes=(), retract=(), car=None, + car_retract=()): # `omit` drops sensor keys from discovery entirely. ⚠️ Announcing a # sensor that nothing will ever publish to is not harmless here: # p1_sample_age_s is a watchdog input, and an entity that exists but is @@ -597,7 +697,8 @@ class MqttPublisher: # OPT-11 P2: the modes offered (empty when battery modes are off), and # the mode config topics to remove (`mode_retractions()`). self.modes = tuple(modes) - self.retract = [str(t) for t in retract] + self.retract = [str(t) for t in retract] + [str(t) for t in car_retract] + self.car = tuple(car) if car else None self.enabled = mqtt is not None and bool(host) self.client = None if not self.enabled: @@ -636,7 +737,8 @@ class MqttPublisher: # diffing what actually goes on the wire - and a payload built here # instead would be one this add-on publishes and no check has ever seen. for topic, cfg in discovery_payloads(self.units, self.omit, - self.include, self.modes): + self.include, self.modes, + self.car): self.client.publish(topic, json.dumps(cfg), retain=True) for topic in self.retract: self.client.publish(topic, "", retain=True) @@ -647,6 +749,8 @@ class MqttPublisher: if self.modes: for key in ("mode", "use"): self.client.subscribe(f"{BASE}/unit/+/{key}/set") + if self.car: + self.client.subscribe(f"{BASE}/car/+/set") def bind(self, loop, handler) -> None: """OPT-11 P2: hand each command to `handler(topic, payload, retained)`, diff --git a/goodwe_controller/app/static/app.js b/goodwe_controller/app/static/app.js index 5fbbcb3..82bae51 100644 --- a/goodwe_controller/app/static/app.js +++ b/goodwe_controller/app/static/app.js @@ -158,6 +158,46 @@ $("#car-today").textContent = c.today || ""; $("#car-today").hidden = !c.today; $("#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. + let carTouch = 0, carTimer = null, carBusy = false; + async function carAct(what, value) { + if (carBusy) return; + carBusy = true; + try { + const r = await fetch("action", { method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ action: what, value: value }) }); + const j = await r.json().catch(() => ({})); + if (!r.ok) toast(j.error || t("toast.failed")); + } catch (e) { toast(t("toast.failed")); } + finally { carBusy = false; } + await refresh(true); + } + function renderCarControls(c) { + const modes = c.modes || []; + $("#car-mode").hidden = !modes.length; + $("#car-mode").replaceChildren(...modes.map((m) => h("button", { + type: "button", role: "radio", "aria-checked": String(c.mode === m), + onclick: () => carAct("car_mode", m) }, t("car.mode_" + m)))); + $("#car-help").textContent = t("car.help_" + c.mode + ".description") || ""; + const on = c.mode === "manual" && !!c.current; + $("#car-manual").hidden = !on; + if (!on) return; + const a = $("#car-a"); + if (Date.now() - carTouch > 3000) { + a.min = c.current.min; a.max = c.current.max; a.value = c.current.value; + } + $("#car-a-out").textContent = a.value + " A"; + a.oninput = () => { + carTouch = Date.now(); $("#car-a-out").textContent = a.value + " A"; + clearTimeout(carTimer); + carTimer = setTimeout(() => carAct("car_current", Number(a.value)), 2000); + }; + $("#car-phases").replaceChildren(...c.phases.choices.map((n) => h("button", { + type: "button", role: "radio", "aria-checked": String(c.phases.value === n), + onclick: () => carAct("car_phases", n) }, t("car.phases_" + n)))); } /* ---------------- Home: today's plan ---------------- */ @@ -288,6 +328,8 @@ bar.className = pct >= 100 ? "bad" : pct >= 80 ? "warn" : ""; $("#peak-meter").setAttribute("aria-label", t("peak.this_month") + " " + (m.pct == null ? "–" : Math.round(m.pct) + " %")); $("#peak-line").textContent = m.line; + $("#peak-car").textContent = m.car_line || ""; $("#peak-car").hidden = !m.car_line; + $("#peak-setby").textContent = m.set_by || ""; $("#peak-setby").hidden = !m.set_by; } function renderAttention() { const list = S.attention; diff --git a/goodwe_controller/app/static/index.html b/goodwe_controller/app/static/index.html index 9d370b8..fa2a6fa 100644 --- a/goodwe_controller/app/static/index.html +++ b/goodwe_controller/app/static/index.html @@ -44,8 +44,14 @@
-
-

+
+

+
@@ -71,6 +77,8 @@
:
+ +
diff --git a/goodwe_controller/app/ui_text/en.json b/goodwe_controller/app/ui_text/en.json index 1b245b1..62d710d 100644 --- a/goodwe_controller/app/ui_text/en.json +++ b/goodwe_controller/app/ui_text/en.json @@ -4,7 +4,7 @@ "inverters": {"name": "Inverters and batteries", "description": "The inverters the add-on controls, and your solar."}, "tariff": {"name": "Tariff and prices", "description": "What you pay and are paid per kWh."}, "safety": {"name": "Safety limits", "description": "The peak limit, starting and stopping, and the safety stops."}, - "car": {"name": "Car charger", "description": "Which charger the add-on reads, and its limits."}, + "car": {"name": "Car charger", "description": "Which charger the add-on drives, its limits and the mode defaults."}, "maintenance": {"name": "Maintenance", "description": "The monthly battery cycle and the log."}, "tuning": {"name": "Control tuning", "description": "For support only, because these were measured on real hardware."} }, @@ -36,6 +36,7 @@ "meter_source": {"off": "One grid power entity", "ha_dsmr": "Import and export entities", "mqtt_p1": "Meter over MQTT", "ha_signed": "One net power entity", "homewizard_local": "HomeWizard meter on the network"}, "ev_charger": {"off": "None", "alfen_ha": "Alfen (Home Assistant integration)"}, "ev_phases": {"1": "1 phase", "3": "3 phases", "auto": "1 and 3"}, + "ev_mode_start": {"keep": "Keep the last mode", "off": "Off"}, "meter_phases": {"1": "1 phase", "3": "3 phases"}, "shadow_mode": {"auto": "Automatic", "on": "Always on", "off": "Off"}, "price_provider": {"generic_dayahead": "Day-ahead market price", "custom_formula": "Your own price formula", "manual_csv": "A price file", "price_service": "Your own price service"}, @@ -90,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", "help_off": {"description": "The add-on leaves the charger alone."}, "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"}, "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"}, @@ -319,9 +320,22 @@ "limit": "The charger limit is above what the charger allows. Lower it in Settings.", "name": "The current setting entity does not fit the charger. Check it in Settings.", "fault": "The charger reports a fault. Check it at the charger itself.", - "wait": "Waiting for the first reading." + "wait": "Waiting for the first reading.", + "manual_set": "You set {a} A, {phases}. The charger keeps it, whatever the peak limit does.", + "manual_cover": "You set {a} A. The batteries give {kw} and help down to {pct}.", + "manual_over": "You set {a} A. The batteries are at {pct}, so this charge sets the peak.", + "manual_full": "You set {a} A. The batteries give all they can, so this charge sets the peak.", + "manual_nocover": "You set {a} A. The batteries keep their charge, so this charge sets 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." } }, + "peak": { + "car": "This 15-minute period is heading for {kw}. The car takes {car} and the batteries cover {cov}.", + "set_by_car": "Set by the car charge you asked for, at {t}." + }, "tile": { "not_set_up": "Not set up", "no_reading": "No reading", @@ -527,6 +541,11 @@ "solar_forecast": "Solar forecast", "charger": "Charger not reachable", "charger_writer": "Something else changes the charger", + "charger_other": "Something else changed the charger", + "charger_stuck": "Charger reading may be stuck", + "charger_refused": "Charger did not take it", + "charger_error": "The charger reports an error", + "car_over": "Car over the peak limit", "charger_setup": "Charger not set up", "none": "Inverter connection" }, diff --git a/goodwe_controller/app/ui_text/nl.json b/goodwe_controller/app/ui_text/nl.json index 188b135..d590bd0 100644 --- a/goodwe_controller/app/ui_text/nl.json +++ b/goodwe_controller/app/ui_text/nl.json @@ -4,7 +4,7 @@ "inverters": {"name": "Omvormers en batterijen", "description": "De omvormers die de add-on regelt, en uw zonnepanelen."}, "tariff": {"name": "Tarief en prijzen", "description": "Wat u per kWh betaalt en terugkrijgt."}, "safety": {"name": "Veiligheidsgrenzen", "description": "De piekgrens, starten en stoppen, en de veiligheidsstops."}, - "car": {"name": "Laadpaal", "description": "Welke laadpaal de add-on leest, en haar grenzen."}, + "car": {"name": "Laadpaal", "description": "Welke laadpaal de add-on stuurt, haar grenzen en de standaardmodus."}, "maintenance": {"name": "Onderhoud", "description": "De maandelijkse batterijcyclus en het logboek."}, "tuning": {"name": "Afstelling van de regeling", "description": "Alleen voor support, want deze zijn gemeten op echte hardware."} }, @@ -36,6 +36,7 @@ "meter_source": {"off": "Eén entiteit voor netvermogen", "ha_dsmr": "Entiteiten voor afname en injectie", "mqtt_p1": "Meter via MQTT", "ha_signed": "Eén entiteit voor nettovermogen", "homewizard_local": "HomeWizard-meter op het netwerk"}, "ev_charger": {"off": "Geen", "alfen_ha": "Alfen (Home Assistant-integratie)"}, "ev_phases": {"1": "1 fase", "3": "3 fasen", "auto": "1 en 3"}, + "ev_mode_start": {"keep": "Laatste modus houden", "off": "Uit"}, "meter_phases": {"1": "1 fase", "3": "3 fasen"}, "shadow_mode": {"auto": "Automatisch", "on": "Altijd aan", "off": "Uit"}, "price_provider": {"generic_dayahead": "Day-aheadprijs van de markt", "custom_formula": "Uw eigen prijsformule", "manual_csv": "Een prijsbestand", "price_service": "Uw eigen prijsdienst"}, @@ -87,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", "help_off": {"description": "De add-on laat de laadpaal met rust."}, "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"}, "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"}, @@ -273,9 +274,22 @@ "limit": "De laadpaalgrens is hoger dan de laadpaal toestaat. Verlaag ze bij Instellingen.", "name": "De entiteit van de laadstroom past niet bij de laadpaal. Controleer ze bij Instellingen.", "fault": "De laadpaal meldt een storing. Controleer ze aan de laadpaal zelf.", - "wait": "Wacht op de eerste meting." + "wait": "Wacht op de eerste meting.", + "manual_set": "U stelde {a} A in, {phases}. De laadpaal houdt dit aan, wat de piekgrens ook doet.", + "manual_cover": "U stelde {a} A in. De batterijen leveren {kw} en helpen tot {pct}.", + "manual_over": "U stelde {a} A in. De batterijen staan op {pct}, dus deze lading bepaalt de piek.", + "manual_full": "U stelde {a} A in. De batterijen geven alles, dus deze lading bepaalt de piek.", + "manual_nocover": "U stelde {a} A in. De batterijen houden hun lading, dus deze lading bepaalt de piek.", + "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." } }, + "peak": { + "car": "Dit kwartier gaat richting {kw}. De auto neemt {car} en de batterijen dekken {cov}.", + "set_by_car": "Bepaald door de autolading die u vroeg, om {t}." + }, "tile": {"not_set_up": "Niet ingesteld", "no_reading": "Geen meting", "producing": "Produceert", "not_producing": "Produceert niet", "needs_solar": "Zonnemeting nodig", "not_adding_up": "Metingen kloppen niet", "using": "Verbruikt", "taking": "Neemt af van het net", "feeding": "Injecteert", "balanced": "In evenwicht", "giving": "Levert stroom", "charging": "Laadt", "resting": "Rust"}, "now": { "no_reading": "Geen meting van deze batterij.", @@ -448,6 +462,11 @@ "solar_forecast": "Zonneprognose", "charger": "Laadpaal onbereikbaar", "charger_writer": "Iets anders wijzigt de laadpaal", + "charger_other": "Iets anders wijzigde de laadpaal", + "charger_stuck": "Laadpaalmeting staat mogelijk vast", + "charger_refused": "Laadpaal nam het niet over", + "charger_error": "De laadpaal meldt een fout", + "car_over": "Auto boven de piekgrens", "charger_setup": "Laadpaal niet ingesteld", "none": "Verbinding met de omvormer" }, diff --git a/goodwe_controller/app/uilayout.py b/goodwe_controller/app/uilayout.py index 54dead0..0bb138a 100644 --- a/goodwe_controller/app/uilayout.py +++ b/goodwe_controller/app/uilayout.py @@ -223,8 +223,8 @@ GROUPS = ( Field("delivery_hold_s", LOCKED, "s", step=5, show=_SEVERAL), ), collapsed=True), )), - # EV-03: the car charger, read only. Everything after the choice shows - # only while a charger is switched on. + # EV-03: the car charger. Everything after the choice shows only while a + # charger is switched on. EV-04 adds the battery switch and the restart mode. Group("car", ( Part("", ( Field("ev_charger", CHOICE, simple=True), @@ -232,6 +232,8 @@ GROUPS = ( show=_CAR), Field("ev_max_a", SLIDER, "A", simple=True, show=_CAR), Field("ev_phases", SEGMENTED, simple=True, show=_CAR), + Field("ev_batt_cover", TOGGLE, simple=True, show=_CAR), + Field("ev_mode_start", SEGMENTED, simple=True, show=_CAR), )), )), Group("maintenance", ( diff --git a/goodwe_controller/app/web.py b/goodwe_controller/app/web.py index b7edb00..3a17a94 100644 --- a/goodwe_controller/app/web.py +++ b/goodwe_controller/app/web.py @@ -62,6 +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") # MAINT-11: start or stop one battery's maintenance cycle (the unit is optional). MAINT_ACTIONS = ("maint_start", "maint_abort") @@ -176,6 +177,15 @@ def build_app(controller, selfcfg=None) -> web.Application: return web.json_response({"ok": False, "error": result["error"]}, status=400) + elif what in CAR_ACTIONS: + # EV-04: the car's mode, current or phases. Store state, applied by + # the writer's next step; nothing is written to the charger here. + result = await controller.handle_action( + what, value=body.get("value")) + if isinstance(result, dict) and "error" in result: + return web.json_response({"ok": False, + "error": result["error"]}, + status=400) elif what in MAINT_ACTIONS and body.get("unit") is not None: # MAINT-11: one battery's cycle. No unit = the old bare call below. result = await controller.handle_action(what, unit=body["unit"]) diff --git a/goodwe_controller/config.yaml b/goodwe_controller/config.yaml index 738db25..8f0b857 100644 --- a/goodwe_controller/config.yaml +++ b/goodwe_controller/config.yaml @@ -873,16 +873,20 @@ options: shadow_mode: "auto" # ========================================================================== - # CAR CHARGER - read only (EV-03) + # CAR CHARGER (EV-03 reads it, EV-04 adds Manual) # ========================================================================== # `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` reads the charger through its Home Assistant integration. THIS - # VERSION NEVER WRITES TO THE CHARGER; later cards add the modes. + # `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. ev_charger: "off" ev_current_entity: "" ev_max_a: 16 ev_phases: "auto" + ev_batt_cover: true + ev_mode_start: "keep" # ========================================================================== # ADVANCED - the control law and diagnostics @@ -1262,7 +1266,7 @@ schema: shadow_mode: list(auto|on|off) # ========================================================================== - # CAR CHARGER - read only (EV-03) + # CAR CHARGER (EV-03 reads it, EV-04 adds Manual) # ========================================================================== # `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 @@ -1271,6 +1275,8 @@ schema: ev_current_entity: str? ev_max_a: int(6,40) ev_phases: list(1|3|auto) + ev_batt_cover: bool + ev_mode_start: list(keep|off) # ========================================================================== # ADVANCED - the control law and diagnostics diff --git a/goodwe_controller/test_ev03.py b/goodwe_controller/test_ev03.py index da6cfa7..905ece4 100644 --- a/goodwe_controller/test_ev03.py +++ b/goodwe_controller/test_ev03.py @@ -185,7 +185,9 @@ def callers_of_writes(): out = [] for root, _d, files in os.walk(os.path.join(HERE, "app")): for f in files: - if not f.endswith(".py") or f == "chargers.py": + # EV-04: carmode.py is the one place that writes, and only in + # Manual (test_ev04.py grades it); chargers.py is the seam. + if not f.endswith(".py") or f in ("chargers.py", "carmode.py"): continue tree = ast.parse(io.open(os.path.join(root, f), encoding="utf-8").read()) @@ -199,15 +201,17 @@ def callers_of_writes(): return out -check(f"nothing in the add-on calls write_current, write_phases or the " - f"charger's release ({callers_of_writes()})", not callers_of_writes()) +check(f"nothing in the add-on but carmode.py calls write_current, " + f"write_phases or the charger's release ({callers_of_writes()})", + not callers_of_writes()) check("the seam does define them (the next cards use them)", all(hasattr(CH.ChargerDriver, m) for m in ("write_current", "write_phases", "release"))) _ha = FakeHa(SimCharger()) -asyncio.run(CH.AlfenHaDriver(SET, 16).bind(_ha).write_current(99)) -check("the Alfen driver's write (a later card's) is clamped to the charger " - "limit, 16 A and not 99", _ha.sets == [(SET, 16.0)]) +_took99 = asyncio.run(CH.AlfenHaDriver(SET, 16).bind(_ha).write_current(99)) +check("the Alfen driver never sends 99 A against a 16 A limit (EV-04: a value " + "above the clamp is a software fault, not sent)", + _ha.sets == [] and _took99 is False) # --------------------------------------------------------------------------- # print("\n2. THE SEAM") diff --git a/goodwe_controller/test_ev04.py b/goodwe_controller/test_ev04.py new file mode 100644 index 0000000..49b593d --- /dev/null +++ b/goodwe_controller/test_ev04.py @@ -0,0 +1,1488 @@ +"""EV-04: the car charger's Manual mode, the first card that WRITES to a charger. +`python3 -B test_ev04.py` + +1. Off writes nothing (EV-03's no-write test keeps passing for Off), whatever + the user sets while Off. +2. Mode, current and phases are runtime state: actions, refusals, the store, the + mode after a restart. +3. Manual writes the current once per user change, read back within 10 s. +4. The clamp: nothing above min(ev_max_a, station limit, entity range) is ever + sent (property-style), and a value above it is a software fault. +5. Phase changes: the safe sequence in order, one switch per 10 minutes. +6. Shadow mode and a stopped control write nothing; the card says what it would. +7. Fail states, the Manual column. +8. Another writer. +9. The peak guard's alarm path: the car you set is not a false alarm, and a + stale or stuck reading never hides a real overload (real Controller, 1 s + cycle, the SAFETY-81 plant plus a charger). +10. Decision 1: batteries help on and off. +11. The peak line: set by the car, and the Peak card's car line. +12. Home Assistant entities, strings, the page's /action route. +13. The simulator. +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import io +import json +import logging +import os +import random +import sys +from datetime import datetime, timedelta, timezone + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode, chargers as CH, homeview, messages, mqtt # noqa: E402 +from app.main import Controller # noqa: E402 +from app import freshness # noqa: E402 +from chargersim import FakeHa, SimCharger # noqa: E402 + +fails = [] + + +def check(name, cond): + print(f" {'ok ' if cond else 'FAIL'} {name}") + if not cond: + fails.append(name) + + +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 __init__(self): + self.values = [] + + def publish(self, v): + self.values.append(dict(v)) + + def close(self): + pass + + +class _Log(logging.Handler): + def __init__(self): + super().__init__(logging.DEBUG) + self.rec = [] + + def emit(self, r): + self.rec.append((r.levelname, r.getMessage())) + + def text(self, level=None): + return "\n".join(m for lv, m in self.rec if level in (None, lv)) + + +LOG = _Log() +logging.getLogger("goodwe").addHandler(LOG) +logging.getLogger("goodwe").setLevel(logging.DEBUG) + + +class Site(FakeHa): + """The charger model plus a grid, a battery and a solar entity.""" + + 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)) + + +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"]} +SET = "number.wallbox_power_connector_max_current_socket_1" +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] # one clock for the whole file + + +class World: + """A real Controller on the charger model, one clock for all of it.""" + + def __init__(self, opts=CAR, sim=None, store=None, plug=True, setpoint=10, + grid=800.0, phases=1, **simkw): + self.sim = sim or SimCharger(setpoint_a=setpoint, **simkw) + if plug: + 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 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()} + + +def run(coro): + return asyncio.run(coro) + + +# =========================================================================== # +print("1. OFF WRITES NOTHING") +# =========================================================================== # + + +async def part1(): + w = World() + await w.step(5) + await w.act("car_current", 14) # the user sets values while Off + await w.act("car_phases", 3) + await w.step(60) + return w + + +w1 = run(part1()) +check("PRECONDITION: the charger was read and the car is charging", + w1.c.car.status(CLOCK[0]) == "charging" and w1.c.car.reading.power_w > 1000) +check("PRECONDITION: the mode is Off (the default)", w1.c.car_mode == "off") +check("Off: no number write and no service call names a charger entity, " + "although the user set 14 A and 3 phases while Off", + w1.site.charger_writes() == [] and w1.sim.log == []) +check("Off: the driver was never asked to send anything", w1.drv.sent == []) +check("Off: the model's own setpoint is where it was (10 A, 1 phase)", + w1.sim.setpoint_a == 10 and w1.sim.phases_allowed == 1) +check("the user's values were kept for when Manual is chosen", + w1.c.car_a == 14 and w1.c.car_n == 3) + +# =========================================================================== # +print("\n2. MODE, CURRENT, PHASES: RUNTIME STATE") +# =========================================================================== # + + +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["night"] = await w.act("car_mode", "night") + out["a12"] = await w.act("car_current", 12) + out["a5"] = await w.act("car_current", 5) + out["a17"] = await w.act("car_current", 17) # above ev_max_a + out["a_text"] = await w.act("car_current", "x") + out["a_bool"] = await w.act("car_current", True) + out["a_nan"] = await w.act("car_current", float("nan")) + out["a_half"] = await w.act("car_current", 12.5) + out["n2"] = await w.act("car_phases", 2) + out["n3"] = await w.act("car_phases", 3) + return w, out + + +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)", + "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", + "error" not in o2["a12"] and w2.store.data.get("car_current") == 12.0) +check("5 A, 17 A (above ev_max_a 16), text, a bool, NaN and 12.5 are refused", + all("error" in o2[k] for k in ("a5", "a17", "a_text", "a_bool", + "a_nan", "a_half"))) +check("the refused values did not change the stored current", + w2.c.car_a == 12.0 and w2.store.data["car_current"] == 12.0) +check("phases: 2 refused, 3 accepted and stored", + "error" in o2["n2"] and w2.store.data.get("car_phases") == 3) +check("the three live in the store (like OPT-11's modes)", + w2.store.data.get("car_mode") == "manual") +check("every refusal is a plain sentence", + all(isinstance(o2[k].get("error"), str) for k in ("bad_mode", "a5"))) + + +async def part2b(): + out = {} + # no charger at all: refused, nothing stored + w = World(BASE) + out["nocharger"] = await w.act("car_mode", "manual") + out["stored"] = dict(w.store.data) + # one-phase-only installation + w = World(dict(CAR, ev_phases="1")) + out["n3"] = await w.act("car_phases", 3) + out["n1"] = await w.act("car_phases", 1) + return out + + +o2b = run(part2b()) +check("with no charger the actions are refused and nothing is stored", + "error" in o2b["nocharger"] and "car_mode" not in o2b["stored"]) +check("ev_phases 1: 3 phases cannot be chosen, 1 can", + "error" in o2b["n3"] and "error" not in o2b["n1"]) + + +async def part2c(): + out = {} + for start, stored in (("keep", "manual"), ("off", "manual"), + ("keep", None), ("keep", "solar")): + st = _Store() + if stored: + st.data["car_mode"] = stored + w = World(dict(CAR, ev_mode_start=start), store=st) + out[(start, stored)] = (w.c.car_mode, st.data.get("car_mode")) + return out + + +o2c = run(part2c()) +check("ev_mode_start keep: a restart keeps Manual", + o2c[("keep", "manual")][0] == "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") + +# =========================================================================== # +print("\n3. MANUAL WRITES THE CURRENT ONCE PER USER CHANGE") +# =========================================================================== # + + +async def part3(): + w = World(setpoint=10) + await w.step(3) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(30) + n1 = len(w.writes("current")) + sent1 = list(w.drv.sent) + await w.step(60) # nothing asked: nothing written + n2 = len(w.writes("current")) + await w.act("car_current", 8) + await w.step(10) + n3 = len(w.writes("current")) + await w.act("car_current", 8) # the same value again + await w.step(10) + n4 = len(w.writes("current")) + return w, n1, sent1, n2, n3, n4 + + +w3, n1, sent1, n2, n3, n4 = run(part3()) +check("choosing Manual at 12 A writes 12 A once", n1 == 1 and sent1 == [12.0]) +check("the charger took it: setpoint and read-back are 12 A (then 8 A)", + w3.sim.setpoint_a == 8 and w3.sim.readback_a == 8) +check("60 s with nothing asked: no further write", n2 == 1) +check("a new value (8 A) is one more write", n3 == 2) +check("the same value again is not written (the charger already has it)", + n4 == 2) +check("the add-on's own write is not 'another writer' in the page", + "charger_writer" not in w3.rows() and "charger_other" not in w3.rows()) + + +def spy_on(drv): + """Every `write_current` of this driver and what it said.""" + res, real = [], drv.write_current + + async def spy(a): + r = await real(a) + res.append((a, r)) + return r + drv.write_current = spy + return res + + +async def part3b(): + out = {} + # the charger takes 4 s to show it: the write is still taken (< 10 s) + w = World(setpoint=10) + w.sim.lag_s = 4.0 + await w.step(2) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(20) + out["lag4"] = (w.writes("current"), w.sim.readback_a, + w.c.car_writer.last_a, w.c.car_writer.gave_up) + # the charger takes 14 s: the write is NOT taken in 10 s, and is not + # retried at once + w = World(setpoint=10) + w.sim.lag_s = 14.0 + await w.step(2) + res = spy_on(w.drv) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(40) + out["lag14"] = (list(res), w.sim.readback_a, w.c.car_writer.gave_up, + w.c.car_writer.fails, "charger_other" in w.rows()) + # the charger ignores it: tried 3 times, a minute apart, then it waits + w = World(setpoint=10) + await w.step(2) + w.sim.refuse = "ignore" + res = spy_on(w.drv) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(5) + out["ignore5"] = (list(res), w.c.car_writer.fails) + await w.step(200) + out["ignore"] = (list(res), w.c.car_writer.gave_up, w.rows()) + await w.step(600) + out["ignore_later"] = len(res) + w.sim.refuse = None + await w.act("car_current", 13) + await w.step(20) + out["after_user"] = (w.sim.readback_a, w.c.car_writer.gave_up) + # Home Assistant refuses the call outright + w = World(setpoint=10) + await w.step(2) + w.sim.refuse = "error" + res = spy_on(w.drv) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(10) + out["error"] = list(res) + return out + + +o3b = run(part3b()) +check("a charger that shows the change 4 s late still took it (read back " + "within 10 s)", len(o3b["lag4"][0]) == 1 and o3b["lag4"][1] == 12 + and o3b["lag4"][2] == 12 and not o3b["lag4"][3]) +check("a charger that shows it 14 s late did NOT take it: write_current " + "says False, and the add-on does not write again at once", + o3b["lag14"][0] == [(12.0, False)] and o3b["lag14"][2] is False) +check("...and when the late read-back arrives it is adopted, with no 'another " + "writer'", o3b["lag14"][1] == 12 and not o3b["lag14"][4]) +check("a charger that ignores it: 3 tries a minute apart, then it stops", + [r for _a, r in o3b["ignore"][0]] == [False, False, False] + and o3b["ignore"][1] is True and o3b["ignore_later"] == 3 + and o3b["ignore5"][0] == [(12.0, False)]) +check("...and says so: one amber row 'Charger did not take it'", + o3b["ignore"][2].get("charger_refused", {}).get("warn") is True + and o3b["ignore"][2]["charger_refused"]["ok"] is False) +check("...and a new value from the user is tried again (and taken)", + o3b["after_user"] == (13.0, False)) +check("Home Assistant refusing the call is a False, not an exception", + o3b["error"] and all(r is False for _a, r in o3b["error"])) + +# =========================================================================== # +print("\n4. THE CLAMP: NOTHING ABOVE min(ev_max_a, station, entity range) IS SENT") +# =========================================================================== # + + +def fast(drv, sim): + """A driver whose 10 s wait for a read-back costs no real time.""" + clock = [0.0] + + async def sl(s): + clock[0] += s + sim.tick(s) + drv._sleep, drv._clock = sl, (lambda: clock[0]) + return drv + + +async def clamp_prop(): + rnd = random.Random(4) + bad, faults_ok, n = [], 0, 0 + for _ in range(80): + station = rnd.choice([6, 10, 13, 16, 20, 25, 32, 40]) + max_a = rnd.choice([6, 8, 10, 16, 20, 32, 40]) + sim = SimCharger(station_a=station, setpoint_a=min(6, station)) + sim.plug_in() + ha = FakeHa(sim) + drv = fast(CH.AlfenHaDriver(SET, max_a).bind(ha), sim) + clamp = min(max_a, station, 40) + for a in (0, 6, clamp - 1, clamp, clamp + 0.1, clamp + 1, 40, 41, 99, + -1, float("nan"), rnd.uniform(0, 80)): + before = len(ha.sets) + ok = await drv.write_current(a) + n += 1 + sent = [v for _e, v in ha.sets[before:]] + if any(v > clamp + 1e-9 for v in sent): + bad.append((station, max_a, a, sent)) + over = a != a or a < 0 or a > clamp + if over: + if sent or ok: + bad.append(("over was sent or said True", station, max_a, + a, sent, ok)) + else: + faults_ok += 1 + return bad, faults_ok, n + + +bad4, faults4, n4c = run(clamp_prop()) +check(f"property: over {n4c} writes with random station limits, ev_max_a and " + f"values, nothing above the clamp is ever sent ({bad4[:2]})", not bad4) +check(f"...and every value above the clamp (or negative, or NaN) is a False " + f"and a fault ({faults4} of them)", faults4 > 400) + + +async def clamp_log(): + sim = SimCharger(station_a=16) + sim.plug_in() + ha = FakeHa(sim) + drv = fast(CH.AlfenHaDriver(SET, 16).bind(ha), sim) + LOG.rec.clear() + r = await drv.write_current(17) + return r, ha.sets, LOG.text("ERROR"), drv.clamp_faults + + +r4, sets4, log4, faults = run(clamp_log()) +check("17 A against 16 A: not sent, False, and logged as a software fault with " + "its code, at ERROR", r4 is False and sets4 == [] + and "CHARGER_CLAMP" in log4 and "Software fault" in log4) +check("...and the fault is on the driver for the page and the checks", + faults == [(17.0, 16.0)]) + + +async def clamp_world(): + # the station limit falls to 10 A after the user set 16 A: the writer never + # asks for more than the charger reports + w = World(setpoint=6) + await w.step(3) + await w.act("car_mode", "manual") + await w.act("car_current", 16) + await w.step(10) + first = w.sim.readback_a + w.sim.station_a = 10.0 + await w.act("car_current", 16) + await w.step(10) + return w, first + + +w4, first4 = run(clamp_world()) +check("the user's 16 A is written at 16 A while the station limit is 16 A", + first4 == 16) +check("the station limit falling to 10 A: the next write is 10 A, never 16 A", + w4.sim.readback_a == 10 and w4.drv.sent[-1] == 10.0 + and max(v for _e, v in w4.site.sets if "wallbox" in _e) <= 16) +_s40 = SimCharger(station_a=40) +check("the entity's own range (0-40 A) bounds a write too", + run(fast(CH.AlfenHaDriver(SET, 40).bind(FakeHa(_s40)), _s40 + ).write_current(41)) is False) + +# =========================================================================== # +print("\n5. PHASE CHANGES: THE SAFE SEQUENCE") +# =========================================================================== # + + +async def phase_story(**simkw): + w = World(setpoint=10, phases=1, **simkw) + await w.step(8) + await w.act("car_mode", "manual") + await w.act("car_current", 10) + await w.step(5) + n0 = len(w.writes()) + t0 = w.sim.t + await w.act("car_phases", 3) + await w.step(45) + return w, n0, t0 + + +w5, n05, t05 = run(phase_story()) +seq5 = w5.writes()[n05:] +check("the sequence is exactly 0 A, phases 3, then the current again " + f"({[(x[1], x[2]) for x in seq5]})", + [(x[1], x[2]) for x in seq5] == [("current", 0.0), ("phases", 3), + ("current", 10.0)]) +check("the phases were selected only with the car paused: under 100 W " + f"({seq5[1][3]:.0f} W) and the setpoint at 0 A ({seq5[1][4]})", + seq5[1][3] < 100 and seq5[1][4] == 0.0) +check("the current was written again 10 s or more after the phases " + f"({seq5[2][0] - seq5[1][0]:.0f} s)", seq5[2][0] - seq5[1][0] >= 10.0) +check("afterwards the charger is at 10 A on 3 phases and the car draws 3 phases", + w5.sim.readback_a == 10 and w5.sim.phases_allowed == 3 + and w5.sim.power_w > 6000) +check("the phases were written exactly once", len(w5.writes("phases")) == 1) + + +async def phase_gap(): + w, n0, _t = await phase_story() + await w.act("car_phases", 1) # one minute later: too soon + await w.step(120) + soon = len(w.writes("phases")) + why = homeview.car_block(w.c, datetime.now(timezone.utc))["why"] + blocked = w.c.car_writer.blocked + await w.step(500) # now more than 10 minutes after + later = len(w.writes("phases")) + return soon, why, blocked, later, w + + +soon5, why5, blocked5, later5, w5g = run(phase_gap()) +check("a second phase change a minute later waits (one per 10 minutes)", + soon5 == 1 and blocked5) +check("...and the card says it waits", "10 minutes" in why5) +check("...and it goes through once 10 minutes have passed, by the same " + "sequence", later5 == 2 and w5g.sim.phases_allowed == 1 + and [x[1] for x in w5g.writes()][-3:] == ["current", "phases", "current"]) + + +async def slow_stop(): + # the car takes 40 s to stop drawing: the add-on waits at most 20 s + w = World(setpoint=10, phases=1) + w.sim.ramp_w_s = 50.0 + w.sim.stop_delay_s = 40.0 + await w.step(60) + await w.act("car_mode", "manual") + await w.act("car_current", 10) + await w.step(3) + n0 = len(w.writes()) + await w.act("car_phases", 3) + await w.step(60) + return w, n0 + + +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) + + +async def zero_refused(): + # the charger does not take 0 A: the phases are NOT touched + 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 + + +w5z = run(zero_refused()) +check("a charger that does not take 0 A never gets the phases select", + w5z.writes("phases") == [] and w5z.sim.phases_allowed == 1) + + +async def shutdown_mid_sequence(): + w = World(setpoint=10, phases=1) + w.sim.ramp_w_s = 50.0 + w.sim.stop_delay_s = 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(4) # 0 A is written, phases not yet + mid = (w.sim.readback_a, w.c.car_writer.seq is not None) + await w.c.car_shutdown() + return mid, w + + +mid5, w5x = run(shutdown_mid_sequence()) +check("the add-on stops in the middle of a phase change: the car gets its " + "10 A back, and nothing is left at 0 A", + mid5 == (0.0, True) and w5x.sim.readback_a == 10 + and w5x.c.car_writer.seq is None) + + +async def other_writer_in_sequence(): + w = World(setpoint=10, phases=1) + w.sim.ramp_w_s = 50.0 + w.sim.stop_delay_s = 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) # 0 A written, the car winding down + w.sim.set_current(9) # the automation + await w.step(60) + return w + + +w5o = run(other_writer_in_sequence()) +check("something else raises the current while the car is being paused: the " + "phases are never selected (the car was drawing), the change is given " + "up and the grey row says so", + w5o.writes("phases") == [] and w5o.sim.phases_allowed == 1 + and w5o.sim.readback_a == 9 and w5o.c.car_writer.seq is None + and "charger_other" in w5o.rows()) + + +async def phases_in_off(): + w = World(setpoint=10, phases=1) + await w.step(5) + await w.act("car_phases", 3) + await w.step(60) + return w + + +check("in Off a phase change writes nothing either", + run(phases_in_off()).writes() == []) + +# --- every write path: who calls the seam, and a fuzz over the lot --------- # +def seam_callers(): + """(file, name) of every call of the charger's write methods in app/.""" + import ast + 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("the write paths are exactly these (all in carmode.py): the current " + "(one call), the phases (one call), nothing else " + f"({seam_callers()})", + seam_callers() == [("carmode.py", "write_current"), + ("carmode.py", "write_phases")]) + + +async def fuzz(seed): + rnd = random.Random(seed) + w = World(setpoint=rnd.choice([6, 10, 16]), phases=rnd.choice([1, 3])) + w.sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0]) + bad = [] + seen = 0 + last_switch = None + if rnd.random() < 0.8: + await w.act("car_mode", "manual") + for step in range(400): + c, sim = w.c, w.sim + seq = c.car_writer.seq is not None + r = rnd.random() + if r < 0.02: + await w.act("car_mode", rnd.choice(["off", "manual", "manual"])) + elif r < 0.07: + await w.act("car_current", rnd.randint(6, 16)) + elif r < 0.09: + await w.act("car_phases", rnd.choice([1, 3])) + elif r < 0.095 and not seq: + sim.go_unavailable(rnd.random() < 0.5) + elif r < 0.10 and not seq: + sim.station_a = float(rnd.choice([10, 13, 16])) + elif r < 0.105 and not seq: + (sim.unplug if sim.state != "A" else sim.plug_in)() + elif r < 0.103 and rnd.random() < 0.5: + sim.set_current(rnd.randint(0, 16)) # another writer + elif r < 0.115: + sim.refuse = rnd.choice([None, None, "ignore", "error"]) + elif r < 0.12: + c.auto = rnd.random() < 0.8 + mode_now, auto_now = c.car_mode, c.auto + n0 = len(sim.log) + await w.step(1) + for t, what, v, power, sp in sim.log[n0:]: + clamp = min(16.0, sim.station_a) + if what == "current" and not 0.0 <= v <= clamp + 1e-9: + bad.append((seed, step, "over the clamp", v, clamp)) + if what == "current" and (mode_now != "manual" and not seq): + bad.append((seed, step, "written outside Manual", mode_now)) + if what in ("current", "phases") and not auto_now and not seq: + bad.append((seed, step, "written with control stopped")) + if what == "current" and sim.state == "A" and not seq: + bad.append((seed, step, "written with no car")) + if what == "phases": + if sp != 0.0: + bad.append((seed, step, "phases with the setpoint up", sp)) + if last_switch is not None and t - last_switch < 600.0: + bad.append((seed, step, "two switches inside 10 min", + t - last_switch)) + last_switch = t + seen += len(sim.log) - n0 + return bad, seen + + +fz_bad, fz_n = [], 0 +for _seed in range(14): + _b, _n = run(fuzz(_seed)) + fz_bad += _b + fz_n += _n +check(f"fuzz: {fz_n} charger writes over 14 random sites and 5600 steps of " + f"random user changes, outages, unplugs, refusals and other writers: " + f"none over the clamp, none outside Manual, none with control stopped " + f"or no car, the phases never moved with the car drawing, one switch " + f"per 10 minutes ({fz_bad[:3]})", not fz_bad and fz_n > 100) + +# =========================================================================== # +print("\n6. SHADOW MODE AND A STOPPED CONTROL WRITE NOTHING") +# =========================================================================== # + + +async def shadow_story(shadow, auto): + w = World(dict(CAR, shadow_mode=shadow), setpoint=10, phases=1) + w.c.auto = auto + await w.step(5) + await w.act("car_mode", "manual") + await w.act("car_current", 14) + await w.act("car_phases", 3) + await w.step(80) + card = homeview.car_block(w.c, datetime.now(timezone.utc)) + return w, card + + +w6, card6 = run(shadow_story("on", True)) +check("shadow mode: no write to the charger at all, although Manual, 14 A and " + "3 phases are set", w6.sim.log == [] and w6.site.charger_writes() == [] + and w6.drv.sent == []) +check("shadow mode: the Car card says what it would set", + "would set 14 A" in card6["why"] and "3 phases" in card6["why"]) +check("shadow mode: the card is in Manual all the same", + card6["mode"] == "manual") +w6b, card6b = run(shadow_story("off", False)) +check("control stopped (shadow off): nothing is written, the card says so", + w6b.sim.log == [] and "stopped" in card6b["why"]) + + +async def shadow_off_then_on(): + w, _c = await shadow_story("off", False) + w.c.auto = True + await w.step(60) + return w + + +w6c = run(shadow_off_then_on()) +check("...and when control starts the waiting setting is written (once, by " + "the safe sequence for the phases)", + w6c.sim.readback_a == 14 and w6c.sim.phases_allowed == 3) + +# =========================================================================== # +print("\n7. FAIL STATES, THE MANUAL COLUMN") +# =========================================================================== # + + +async def restart_story(start): + st = _Store() + w = World(dict(CAR, ev_mode_start=start), store=st, setpoint=10, phases=1) + await w.step(3) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(20) + before = list(w.sim.log) + # a restart: a new Controller on the same store and the same charger + w.make(dict(CAR, ev_mode_start=start)) + await w.step(40) + return w, before + + +w7, before7 = run(restart_story("keep")) +check("a restart (keep): the charger stays at 12 A and nothing is written, " + "not even 0 A", w7.sim.log == before7 and w7.sim.readback_a == 12 + and w7.c.car_mode == "manual") +w7o, before7o = run(restart_story("off")) +check("a restart with 'Mode after a restart: Off': the mode is Off, nothing " + "is written, the current stands (Manual's own column)", + w7o.sim.log == before7o and w7o.sim.readback_a == 12 + and w7o.c.car_mode == "off") + + +async def stop_story(): + w = World(setpoint=10, phases=1) + await w.step(3) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(10) + n = len(w.sim.log) + await w.c.handle_action("auto_toggle") # the Stop button + await w.step(30) + stopped = (len(w.sim.log) == n, w.sim.readback_a) + # a safety stop: a failsafe latch is up + w.c.auto = True + w.c.inverters[0].sign_wd.tripped = True + await w.step(30) + safety = (len(w.sim.log) == n, w.sim.readback_a) + return stopped, safety + + +stopped7, safety7 = run(stop_story()) +check("control stopped by the button: the current stands, nothing is written", + stopped7 == (True, 12)) +check("a safety stop (a failsafe latch): the current stands, nothing is " + "written", safety7 == (True, 12)) + + +async def return_story(other): + w = World(setpoint=10, phases=1) + await w.step(3) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(10) + n = len(w.sim.log) + w.sim.go_unavailable() + await w.step(60) + if other: + w.sim.go_unavailable(False) + w.sim.set_current(7) # it came back with another value + else: + w.sim.go_unavailable(False) + await w.step(30) + return w, n + + +w7a, n7a = run(return_story(False)) +check("the charger comes back with the same read-back: nothing is written", + len(w7a.sim.log) == n7a) +w7b, n7b = run(return_story(True)) +check("it comes back with a different read-back: the setting is written again, " + "once", len(w7b.sim.log) == n7b + 1 and w7b.sim.readback_a == 12) + + +async def outage_write(): + w = World(setpoint=10, phases=1) + await w.step(3) + await w.act("car_mode", "manual") + await w.step(5) + n0 = len(w.sim.log) + w.sim.go_unavailable() + await w.step(5) + await w.act("car_current", 13) # changed while it is away + await w.step(40) + during = len(w.sim.log) - n0 + w.sim.go_unavailable(False) + await w.step(10) + return during, w.sim.readback_a, w.drv.sent + + +during7, rb7, sent7 = run(outage_write()) +check("a value set while the charger is away is written when it answers", + during7 == 0 and rb7 == 13 and sent7[-1] == 13.0) + + +async def error_story(): + w = World(setpoint=10, phases=1) + await w.step(3) + await w.act("car_mode", "manual") + w.sim.error = "17: Overcurrent" + await w.step(5) + await w.act("car_current", 12) + await w.step(10) + return w + + +w7e = run(error_story()) +check("a charger error is shown (a grey row) and the writes go on", + w7e.rows().get("charger_error", {}).get("ok") is True + and "Overcurrent" in w7e.rows()["charger_error"]["text"] + and w7e.sim.readback_a == 12) + + +async def nocar_story(): + w = World(plug=False, setpoint=10, phases=1) + await w.step(5) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.act("car_phases", 3) + await w.step(60) + none_writes = len(w.sim.log) + none_why = homeview.car_block(w.c, datetime.now(timezone.utc))["why"] + w.sim.plug_in() + await w.step(80) + return w, none_writes, none_why + + +w7n, none7, why7n = run(nocar_story()) +check("no car: the current stands and nothing is written (not even for the " + "user's change)", none7 == 0) +check("...and the card says it is set when a car is connected", + "when a car is connected" in why7n) +check("...when the car is plugged in the waiting setting is written", + w7n.sim.readback_a == 12 and w7n.sim.phases_allowed == 3) + + +async def full_story(): + w = World(setpoint=10, phases=1) + await w.step(3) + await w.act("car_mode", "manual") + await w.step(5) + w.sim.car_full() + await w.step(120) + state = w.c.car.status(CLOCK[0]) + n = len(w.sim.log) + await w.act("car_current", 14) + await w.step(60) + return state, n, len(w.sim.log) + + +state7f, n7f, m7f = run(full_story()) +check("a full car: the current stands, nothing is written", state7f == "full" + and n7f == m7f) + +# =========================================================================== # +print("\n8. ANOTHER WRITER") +# =========================================================================== # + + +async def writer_story(): + w = World(setpoint=10, phases=1) + await w.step(3) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(10) + n = len(w.sim.log) + w.sim.set_current(9) # the HA automation + await w.step(20) + early = ("charger_other" in w.rows(), w.c.car_writer.hold, len(w.sim.log)) + await w.step(20) + held = ("charger_other" in w.rows(), w.c.car_writer.hold) + row = w.rows().get("charger_other") + await w.step(200) + stays = (len(w.sim.log) == n, w.sim.readback_a) + await w.act("car_current", 14) + await w.step(10) + after = ("charger_other" in w.rows(), w.sim.readback_a, w.c.car_writer.hold) + return early, held, row, stays, after, n, w + + +early8, held8, row8, stays8, after8, n8, w8 = run(writer_story()) +check("a different read-back for under 30 s is not yet 'another writer'", + early8 == (False, False, n8)) +check("after 30 s it is: an info row (grey, not amber)", + held8 == (True, True) and row8["ok"] is True and row8["warn"] is True) +check("...and the add-on does not write over it, for minutes", stays8 == (True, 9)) +check("...until the user changes a value: then it writes it, and the row goes", + after8 == (False, 14, False)) + + +async def writer_off(): + w = World(setpoint=10, phases=1) + await w.step(3) + await w.act("car_mode", "manual") + await w.act("car_current", 12) + await w.step(10) + await w.act("car_mode", "off") # back to Off after the add-on wrote + await w.step(30) + own = "charger_writer" in w.rows() + w.sim.set_current(7) # now somebody else + await w.step(3) + return own, "charger_writer" in w.rows(), len(w.writes()) + + +own8, off8, nw8 = run(writer_off()) +check("Manual back to Off: the add-on's own writes do not show as another " + "writer", own8 is False) +check("Off keeps EV-03's grey row for a real other writer", off8 is True + and nw8 == 1) + +# =========================================================================== # +print("\n9. THE PEAK GUARD'S ALARM PATH: THE CAR YOU SET IS NOT A FALSE ALARM") +# =========================================================================== # +import ev04_peak as P # noqa: E402 +import safety81_sim as s81 # noqa: E402 +import opt11_identity as rig # noqa: E402 + +LOG.rec.clear() +logging.disable(logging.NOTSET) +HOUSE = s81.constant(1100.0) + + +def alarms(r): + return P.ids(r, *P.ALARMS) + + +def cardwhy(r): + return homeview.car_block(r["c"], rig.BASE + timedelta(seconds=299))["why"] + + +r_off = P.drive(HOUSE, dur=240, mode="off") +r_man = P.drive(HOUSE, dur=240) +check("PRECONDITION: Off, an 11 kW car on a 1.1 kW house and a 2 kW battery " + "raises 'Load too high for battery' (the false alarm today)", + len(alarms(r_off)) == 1 and alarms(r_off)[0][1] == "goodwe_peak_saturated") +check("Manual: the same car raises neither 'Load too high' nor 'Battery " + "stopped limiting the peak'", alarms(r_man) == []) +check("Manual: one grey notice 'Car over the peak limit', once", + len(P.ids(r_man, P.OVER)) == 1) +check("...the claim, the floor and the commands are those of Off (the " + "battery gives its 2000 W in both)", + [s[4] for s in r_man["snaps"]] == [s[4] for s in r_off["snaps"]] + and max(s[4] for s in r_man["snaps"]) == 2000.0) +check("the car is never throttled: the add-on wrote nothing to the charger " + "after choosing Manual", r_man["sim"].setpoint_a == 16 + and r_man["sim"].writes() == []) +rows_m = {x["id"]: x for x in r_man["c"].checks()} +check("no red row for that cause; the peak row is not an alarm", + rows_m["peak_guard"]["ok"] is True + and not any(x["ok"] is False and not x["warn"] for x in r_man["c"].checks() + if x["id"] in ("peak_guard",))) +check("one grey row says the car charge you set is over the limit", + rows_m.get("car_over", {}).get("ok") is True + and rows_m["car_over"]["warn"] is True) +check("the Car card's Why says it (the batteries give all they can)", + "batteries give all they can" in cardwhy(r_man)) +att = homeview.attention(r_man["c"].checks()) +check("Needs attention holds the grey note and nothing red", + any(a["id"] == "car_over" and a["severity"] == "info" for a in att) + and not [a for a in att if a["severity"] == "alarm"]) + +# the batteries at the peak reserve: 'Battery stopped limiting the peak' +r_off_r = P.drive(HOUSE, dur=240, mode="off", soc=15.0) +r_man_r = P.drive(HOUSE, dur=240, soc=15.0) +check("PRECONDITION: Off, batteries at the reserve: 'Battery stopped limiting " + "the peak' fires", [n for _t, n in alarms(r_off_r)] == + ["goodwe_peak_soc_floor"]) +check("Manual, batteries at the reserve: no alarm, one grey notice", + alarms(r_man_r) == [] and len(P.ids(r_man_r, P.OVER)) == 1) +check("...and the Why says the batteries are at the reserve", + "at 20 %" in cardwhy(r_man_r)) + +# once per charging session +def replug(plant, c): + plant.ch.unplug() + + +def plugin(plant, c): + plant.ch.plug_in() + + +r_ses = P.drive(HOUSE, dur=400, events={150: replug, 200: plugin}) +check("the notice is once per charging session: a second plug-in raises it " + "again, a long charge does not", + len(P.ids(r_ses, P.OVER)) == 2 and alarms(r_ses) == []) + +# a car that is not the cause: a house overload on top of a small car +def house_overload(plant, c): + plant.house = lambda at: 9000.0 + plant.ch.power_w + + +r_both = P.drive(s81.constant(1100.0), dur=240, user_a=6, setpoint=6, phases=1, + events={60: lambda p, c: setattr( + p, "load", lambda at: 9000.0 + p.ch.power_w)}) +check("a 1.4 kW car and a house that steps to 9 kW: the car does not explain " + "the excess, so the normal alarm fires", + [n for _t, n in alarms(r_both)] == ["goodwe_peak_saturated"]) + +# --- a stale or stuck car reading must NOT hide a real house overload ------- # +def stale_then_overload(plant, c): + plant.ch.unplug() # the car goes + plant.ch.go_unavailable() # and the charger stops answering + plant.load = lambda at: 9000.0 + plant.ch.power_w + + +r_stale = P.drive(HOUSE, dur=300, events={60: stale_then_overload}) +check("the charger stops answering and the house steps to 9 kW: the car " + "figure is not used (not fresh), so the normal alarm fires", + [n for _t, n in alarms(r_stale)] == ["goodwe_peak_saturated"] + and 60 < alarms(r_stale)[0][0] < 60 + 15 + 25) + + +def stuck_then_overload(plant, c): + plant.ch.freeze() # the reading stops moving + plant.ch.unplug() # the car really goes + plant.load = lambda at: 9000.0 + plant.ch.power_w + run_user_change(c) + + +def run_user_change(c): + asyncio.get_event_loop().create_task(c.handle_action("car_current", + value=10)) + + +r_stuck = P.drive(HOUSE, dur=400, events={60: stuck_then_overload}) +at_stuck = alarms(r_stuck) +check("a stuck car figure (11 kW, frozen) and a real house overload: the " + "stuck rule (60 s after the write) lets the normal alarm fire", + [n for _t, n in at_stuck] == ["goodwe_peak_saturated"] + and at_stuck[0][0] < 60 + 60 + 25) +check("...and the amber row 'Charger reading may be stuck' says so", + "charger_stuck" in {x["id"]: x for x in r_stuck["c"].checks()} + and {x["id"]: x for x in r_stuck["c"].checks()}["charger_stuck"]["warn"]) +w_ = r_stuck["c"] +check("...while stuck, the car figure is not used by the alarm path", + w_.car.stuck(w_.car_now()) and w_.car_alarm_w() is None) + +# a plausible figure is bounded by what the read-back allows +tr = CH.CarTracker() +tr.observe(CH.ChargerReading(available=True, state="C", power_w=11000.0, + allowed_a=6.0, setpoint_a=6.0, + phases_allowed=1), 100.0, + datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") +check("a car figure of 11 kW on a 6 A, 1 phase read-back counts for no more " + "than that allows (1.5 kW), so an old figure cannot cover a house " + "overload", abs(tr.car_w_trusted(100.0) - 6 * 253) < 1) +check("...and None when it is not fresh", tr.car_w_trusted(100.0 + 16) is None) + +# =========================================================================== # +print("\n10. DECISION 1: BATTERIES HELP WITH THE PEAK, ON AND OFF") +# =========================================================================== # +r_on = P.drive(HOUSE, dur=240, opts={"ev_batt_cover": True}) +r_no = P.drive(HOUSE, dur=240, opts={"ev_batt_cover": False}) +check("on (the default): the guard asks the batteries for the car's share " + "(the battery gives 2000 W) and the guard is engaged", + max(s[4] for s in r_on["snaps"]) == 2000.0 + and r_on["snaps"][-1][3] is True) +check("off: the guard sees the house without the car, is not engaged, and the " + "batteries keep their charge (0 W)", + max(s[4] for s in r_no["snaps"]) == 0.0 + and r_no["snaps"][-1][3] is False) +check("off: the quarter goes over by the car alone, and the add-on says so " + "(one grey notice), with no alarm", + alarms(r_no) == [] and len(P.ids(r_no, P.OVER)) == 1) +check("off: the Why says the batteries keep their charge", + "keep their charge" in cardwhy(r_no)) +check("either way the car is never throttled", + r_on["sim"].writes() == [] and r_no["sim"].writes() == [] + and r_no["sim"].setpoint_a == 16 and r_no["sim"].power_w > 10000) +r_no_h = P.drive(HOUSE, dur=300, opts={"ev_batt_cover": False}, user_a=6, + setpoint=6, phases=1, + events={60: lambda p, c: setattr( + p, "load", lambda at: 9000.0 + p.ch.power_w)}) +check("off: a real house overload is still an alarm (the car is only left out " + "of the guard's house)", [n for _t, n in alarms(r_no_h)] + == ["goodwe_peak_saturated"]) +r_no_s = P.drive(HOUSE, dur=300, opts={"ev_batt_cover": False}, + events={60: stale_then_overload}) +check("off: a house overload with a car that is no longer read still alarms", + [n for _t, n in alarms(r_no_s)] == ["goodwe_peak_saturated"]) + +# =========================================================================== # +print("\n11. THE PEAK LINE: SET BY THE CAR, AND THE PEAK CARD'S CAR LINE") +# =========================================================================== # + + +def unplug_at(plant, c): + plant.ch.unplug() + + +r_pk = P.drive(HOUSE, dur=1900, events={950: unplug_at}) +c_pk = r_pk["c"] +now_pk = rig.BASE + timedelta(seconds=1899) +mp = homeview.month_peak(c_pk, now_pk) +check("PRECONDITION: a quarter was banked as this month's peak, with the car " + "in it", mp["peak_w"] and mp["peak_w"] > 4000 and c_pk.car_peak_q) +check("the Home peak line names the car and the time of that quarter", + mp["set_by"].startswith("Set by the car charge you asked for, at ") + and mp["set_by"].endswith(".") and ":" in mp["set_by"]) +with homeview.in_lang("nl"): + mp_nl = homeview.month_peak(c_pk, now_pk) +check("...in Dutch too", mp_nl["set_by"].startswith("Bepaald door de " + "autolading die u vroeg")) +r_pk_off = P.drive(HOUSE, dur=1900, mode="off", events={950: unplug_at}) +check("Off: the month's peak is not 'set by the car you asked for'", + homeview.month_peak(r_pk_off["c"], now_pk)["set_by"] == "" + and r_pk_off["c"].car_peak_q == {}) +mp_now = homeview.month_peak(r_man["c"], rig.BASE + timedelta(seconds=239)) +check("while the car charges and the guard works, the Peak card says what the " + "car takes and the batteries cover", + "The car takes 11.0 kW and the batteries cover 2.0 kW" in mp_now["car_line"]) +check("a site with no charger has neither line", + homeview.month_peak(s81.run(HOUSE, dur=60.0)[2], + rig.BASE)["set_by"] == "") + +# =========================================================================== # +print("\n12. HOME ASSISTANT ENTITIES, THE PAGE'S ROUTE, STRINGS") +# =========================================================================== # +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 + 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 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") +check("the phases are 1 and 3 (or the one the installation allows)", + ph["options"] == ["1", "3"] + and dict(mqtt.car_payloads((16, (3,))))[ + "homeassistant/select/goodwe_ctl_car_phases/config"][ + "options"] == ["3"]) +check("commands go to goodwe_ctl/car//set, HA sends them unretained", + all(x["command_topic"].startswith("goodwe_ctl/car/") and + x["command_topic"].endswith("/set") and x["retain"] is False + for x in (sel, num, ph))) +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.car_payloads((16, (1, 3)))]) +cmd = mqtt.parse_car_command +check("a command parses: mode, current, phases", + cmd("goodwe_ctl/car/mode/set", b"Manual", False) + == ("car_mode", "manual", None) + and cmd("goodwe_ctl/car/current/set", b"12", False) + == ("car_current", 12.0, None) + and cmd("goodwe_ctl/car/phases/set", b"3", False) + == ("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 + 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 + and cmd("goodwe_ctl/car/mode/set", b"x" * 100, False)[2] == "size" + and cmd("goodwe_ctl/car/mode/set", b"\xff\xfe", False)[2] == "encoding" + and cmd("goodwe_ctl/battery/mode/set", b"Manual", False)[2] == "topic") + + +async def ha_story(): + w = World(setpoint=10) + await w.step(3) + await w.c.mqtt_command("goodwe_ctl/car/mode/set", b"Manual", False) + await w.c.mqtt_command("goodwe_ctl/car/current/set", b"13", False) + await w.step(10) + 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/current/set", b"99", False) + await w.c.mqtt_command("goodwe_ctl/car/phases/set", b"2", False) + await w.step(5) + out["after"] = (w.c.car_mode, w.c.car_a, w.c.car_n) + await w.step(2) + await w.c.publish_values() if hasattr(w.c, "publish_values") else None + w.c.publish() + out["state"] = {k: v for k, v in w.c.mqtt.values[-1].items() + if k.startswith("car_")} + return out + + +ha = run(ha_story()) +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", + ha["after"] == ("manual", 13.0, 1)) +check("the three states are in the published values", + ha["state"].get("car_mode") == "Manual" + and ha["state"].get("car_current") == 13 + and ha["state"].get("car_phases") == "1") + + +class _S: + def __init__(self, d=None): + self.data = dict(d or {}) + + def set(self, k, v): + self.data[k] = v + + +from app import main as _main # noqa: E402 +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) +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) +st2 = _S() +check("a site that never had a charger publishes nothing and its store is " + "not written", + _main.car_announcement(BASE, st2) == (None, []) and st2.data == {}) + + +async def web_story(): + import socket + import aiohttp + from aiohttp import web as aioweb + from app import web as app_web + w = World(setpoint=10) + await w.step(3) + app = app_web.build_app(w.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() + out = {} + try: + async with aiohttp.ClientSession() as s: + root = f"http://127.0.0.1:{port}/" + for key, body in ( + ("manual", {"action": "car_mode", "value": "manual"}), + ("a", {"action": "car_current", "value": 12}), + ("n", {"action": "car_phases", "value": 3}), + ("solar", {"action": "car_mode", "value": "solar"}), + ("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)) + for lang in ("en", "nl"): + async with s.get(root + "status?lang=" + lang) as r: + out["status_" + lang] = (await r.json(content_type=None)) + async with s.get(root) as r: + out["page"] = await r.text() + finally: + await runner.cleanup() + return out, w + + +web, ww = run(web_story()) +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", + 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"] + 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", + '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"]) +check("the page names the Manual strings in both languages", + "Handmatig" in web["page"] and "Manual" in web["page"]) + +en = json.load(io.open(os.path.join(HERE, "app", "ui_text", "en.json"), + encoding="utf-8")) +nl = json.load(io.open(os.path.join(HERE, "app", "ui_text", "nl.json"), + encoding="utf-8")) + + +def keys(d, pre=""): + out = set() + for k, v in d.items(): + out |= keys(v, pre + k + ".") if isinstance(v, dict) else {pre + k} + return out + + +new_keys = {"home.car.mode_manual", "home.car.help_manual.description", + "home.car.current", "home.car.phases", "home.car.phases_1", + "home.car.phases_3", "home_words.peak.car", + "home_words.peak.set_by_car", "home_words.car.why.manual_set", + "home_words.car.why.manual_cover", "home_words.car.why.manual_over", + "home_words.car.why.manual_full", + "home_words.car.why.manual_nocover", + "home_words.car.why.manual_wait", "home_words.car.why.manual_would", + "home_words.car.why.manual_stopped", + "home_words.car.why.manual_blocked", + "home_words.attn.charger_other", "home_words.attn.charger_stuck", + "home_words.attn.charger_refused", "home_words.attn.charger_error", + "home_words.attn.car_over", "choices.ev_mode_start.keep", + "choices.ev_mode_start.off"} +ke, kn = keys(en), keys(nl) +check("every new Home string exists in English and in Dutch", + new_keys <= ke and new_keys <= kn) +check("the Dutch is not the English for the sentences", + all(en["home_words"]["car"]["why"][k] != nl["home_words"]["car"]["why"][k] + for k in ("manual_set", "manual_cover", "manual_over", "manual_full", + "manual_nocover", "manual_wait", "manual_would", + "manual_stopped", "manual_blocked"))) +check("every new row, notice and refusal is bilingual", + all(getattr(f, "nl", None) for f in ( + messages.row_car_over(), messages.row_charger_other(), + messages.row_charger_stuck(), messages.row_charger_refused(), + messages.row_charger_error("x"))) + and messages.car_over("16").body_nl) +check("the page shows the option names and choices in Settings, both languages", + messages.LABELS["ev_batt_cover"] and messages.LABELS_NL["ev_mode_start"]) + +# =========================================================================== # +print("\n13. THE SIMULATOR") +# =========================================================================== # +s = SimCharger(setpoint_a=10) +s.plug_in() +s.lag_s = 3.0 +s.request_current(12) +s.tick(2) +check("the model shows a write after its read-back lag, not before", + s.readback_a == 10) +s.tick(1) +check("...and after it", s.readback_a == 12) +s.refuse = "ignore" +check("a refusing charger says yes and does not change", + s.request_current(6) and s.readback_a == 12) +s.refuse = "error" +check("a refusing Home Assistant says no", not s.request_current(6)) +s.refuse = None +s.freeze() +s.set_current(7) +check("a frozen model serves the readings of the moment it froze", + s.states()[f"sensor.wallbox_main_active_max_current_socket_1"]["state"] + == "12") +s.freeze(False) + +print() +if fails: + print(f"{len(fails)} FAILED") + for f in fails: + print(" -", f) + sys.exit(1) +print("all passed") diff --git a/goodwe_controller/tools/chargersim.py b/goodwe_controller/tools/chargersim.py index 2b53394..8eef795 100644 --- a/goodwe_controller/tools/chargersim.py +++ b/goodwe_controller/tools/chargersim.py @@ -2,6 +2,14 @@ """EV-03: a model of an Alfen car charger behind Home Assistant, for the unit tests and, later, for TEST-23. +EV-04 ADDS THE WRITE SIDE: `request_current()` and `request_phases()` are what +the add-on's writes reach. The new state is taken after `lag_s` seconds of +model time (the read-back lag), the power RAMPS to it, and `refuse` makes the +charger ignore a write ("ignore": Home Assistant says yes, the charger does not +change) or Home Assistant refuse it ("error"). `log` records every write with +the model's clock and the power and setpoint at that moment, so a test can +prove the safe phase sequence (0 A first, under 100 W before the phases move). + WHERE IT LIVES, AND WHY. The rig's hardware sims (`hwsim.py`, `plantsim.py`) are in the infra repo admin/goodwe under `sim/`, pinned by `.gitea/infra-pin`; there is no `sim/` in this repository. This card may write only to this repository, so @@ -51,6 +59,16 @@ class SimCharger: self.unavailable = False self.login_on = True self.error = "0: No Error" + # EV-04: the write side + self.t = 0.0 # model seconds + self.lag_s = 0.0 # a write shows in the read-back this late + self.refuse = None # None | "ignore" | "error" + self._snap = None # `freeze()`: the readings stop moving + self.ramp_w_s = RAMP_W_S # how fast the power follows its target + self.stop_delay_s = 0.0 # mode3 stays C this long after 0 A + self._c_hold = 0.0 + self.log = [] # (t, what, value, power_w, setpoint_a) + self._pending = [] # -- the world acts on it ------------------------------------------------- def plug_in(self, car_phases=3): @@ -76,6 +94,44 @@ class SimCharger: """mode3 E or F: the charger's own error states.""" self.state, self.power_w = letter, 0.0 + # -- what the add-on's writes reach (EV-04) ---------------------------------- + def request_current(self, a): + """`number.set_value` on the current. False: Home Assistant refused it + (out of the entity's 0-40 A range, or `refuse == "error"`).""" + a = float(a) + if a != a or a < 0.0 or a > 40.0 or self.refuse == "error": + return False + self.log.append((self.t, "current", a, self.power_w, self.setpoint_a)) + if self.refuse == "ignore": + return True + self._later("current", a) + return True + + def request_phases(self, n): + """`select.select_option` on the installation's allowed phases.""" + if self.refuse == "error" or n not in (1, 3): + return False + self.log.append((self.t, "phases", n, self.power_w, self.setpoint_a)) + if self.refuse == "ignore": + return True + self._later("phases", n) + return True + + def _later(self, what, v): + if self.lag_s <= 0: + self._apply(what, v) + else: + self._pending.append((self.t + self.lag_s, what, v)) + + def _apply(self, what, v): + if what == "current": + self.setpoint_a = self.readback_a = max(0.0, min(v, self.station_a)) + else: + self.phases_allowed = 3 if v == 3 else 1 + + def writes(self, what=None): + return [x for x in self.log if what in (None, x[1])] + def go_unavailable(self, on=True): self.unavailable = bool(on) @@ -94,13 +150,22 @@ class SimCharger: def tick(self, seconds=1.0): for _ in range(int(max(1, round(seconds)))): + self.t += 1.0 + for p in [x for x in self._pending if x[0] <= self.t]: + self._pending.remove(p) + self._apply(p[1], p[2]) if self.state in ("E", "F"): # a fault: nothing flows, it stays self.power_w = 0.0 continue if self.state != "A": - self.state = "C" if self.target_w() > 0 else "B" + if self.target_w() > 0: + self.state, self._c_hold = "C", 0.0 + elif self.state == "C" and self._c_hold < self.stop_delay_s: + self._c_hold += 1.0 # the car has not let go yet + else: + self.state = "B" tgt = self.target_w() - step = RAMP_W_S + step = self.ramp_w_s if self.power_w < tgt: self.power_w = min(tgt, self.power_w + step) else: @@ -113,7 +178,15 @@ class SimCharger: if self.phases_used and self.power_w else 0.0) return [per if i < self.phases_used else 0.0 for i in range(3)] + def freeze(self, on=True): + """A stuck sensor: Home Assistant goes on serving the readings of this + moment, whatever the charger does after it.""" + self._snap = self._build() if on else None + def states(self) -> dict: + return self._snap if self._snap is not None else self._build() + + def _build(self) -> dict: x = self.x bad = "unavailable" if self.unavailable else None @@ -195,10 +268,20 @@ class FakeHa: async def set_number(self, entity_id, value): self.sets.append((entity_id, value)) + c = self.charger + if c is not None and entity_id == \ + f"number.{c.x}_power_connector_max_current_socket_1": + return c.request_current(value) return True async def call(self, domain, service, data=None): self.calls.append((domain, service, data)) + c = self.charger + if c is not None and domain == "select" and service == "select_option" \ + and (data or {}).get("entity_id") == \ + f"select.{c.x}_installation_max_allowed_phases": + return c.request_phases( + 3 if "3" in str((data or {}).get("option")) else 1) return True def charger_writes(self): @@ -251,6 +334,22 @@ def _selftest(): assert c.state == "B" and c.power_w == 0 # under 6 A: paused c.set_current(10); c.car_full(); c.tick(5) assert c.state == "B" and c.power_w == 0 and c.readback_a == 10 + # EV-04: writes, the read-back lag, a refusal + w = SimCharger(); w.plug_in(); w.tick(1) + assert w.request_current(12) and w.setpoint_a == 12 + assert not w.request_current(41) and not w.request_current(-1) + w.lag_s = 3.0 + assert w.request_current(8) and w.readback_a == 12 + w.tick(2); assert w.readback_a == 12 + w.tick(1); assert w.readback_a == 8 + w.refuse = "ignore" + assert w.request_current(6) and w.readback_a == 8 + w.refuse = "error" + assert not w.request_current(6) and not w.request_phases(3) + w.refuse = None; w.lag_s = 0.0 + assert w.request_phases(3) and w.phases_allowed == 3 + assert [x[1] for x in w.writes()] == ["current", "current", "current", + "phases"], w.writes() c.go_unavailable() assert c.states()[f"sensor.wallbox_active_power_total_socket_1"]["state"] \ == "unavailable" diff --git a/goodwe_controller/tools/ev04_peak.py b/goodwe_controller/tools/ev04_peak.py new file mode 100644 index 0000000..cd5f9c4 --- /dev/null +++ b/goodwe_controller/tools/ev04_peak.py @@ -0,0 +1,153 @@ +#!/usr/bin/env python3 +"""EV-04: the real Controller on the SAFETY-81 plant, plus a car charger. + + python3 tools/ev04_peak.py # a few runs and what they raised + +A 1 s cycle, a 3500 W cap, one battery switched Off (so only the peak guard +makes it give, at most `rating` W), a P1 meter that publishes 0.3 s before each +cycle, and `chargersim.SimCharger` behind the same Home Assistant: its power +is part of the load the meter sees, and the add-on reads and writes it through +the real driver. `events` is `{second: fn(plant, controller)}`, run before that +cycle: unplug, freeze the reading, step the house, change the user's current. + +Used by test_ev04.py (sections 9 to 11) and, later, by the rig test.""" + +import asyncio +import logging +import os +import sys +import tempfile +import time +from datetime import timedelta + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import opt11_identity as rig # noqa: E402 +import main_files # noqa: E402 +import safety81_sim as s81 # noqa: E402 +from app import packmode # noqa: E402 +from app.main import Controller # noqa: E402 +from app.p1 import make_sample, split_signed # noqa: E402 +from app.store import unit_key # noqa: E402 +from chargersim import SimCharger # noqa: E402 + +SET = "number.wallbox_power_connector_max_current_socket_1" +PHASES = "select.wallbox_installation_max_allowed_phases" +ALARMS = ("goodwe_peak_saturated", "goodwe_peak_soc_floor") +OVER = "goodwe_car_over" + + +class CarPlant(s81._Plant): + """The SAFETY-81 plant with a charger on the same meter: the grid sees the + house, the car and what the battery does.""" + + def __init__(self, house, rating, soc, charger): + super().__init__(lambda at: house(at) + charger.power_w, rating, soc) + self.ch = charger + + async def state(self, entity_id): + return self.ch.states().get(entity_id) + + async def set_number(self, e, v): + if e == SET: + return self.ch.request_current(float(v)) + return await super().set_number(e, v) + + async def call(self, domain, service, data=None): + if domain == "select" and service == "select_option": + n = 3 if "3" in str((data or {}).get("option")) else 1 + return self.ch.request_phases(n) + return await super().call(domain, service, data) + + +def drive(house, *, dur=300.0, rating=2000.0, soc=60.0, cap=3500.0, margin=50, + opts=None, plug=True, setpoint=16, phases=3, mode="manual", + user_a=16, events=None, sim=None, store=None): + """Run it. Returns a namespace-like dict: plant, controller, charger, the + notification ids raised with their second, and the controller's rows.""" + sim = sim or SimCharger(setpoint_a=setpoint) + if plug: + sim.plug_in() + sim.phases_allowed = phases + o = rig._options(1, dict({ + "meter_source": "ha_signed", "p1_net_entity": "sensor.net", + "meter_phases": 1, "peak_cap_w": cap, "peak_margin_w": margin, + "battery_modes_enabled": True, "max_w": rating, + "ev_charger": "alfen_ha", "ev_max_a": 16, "ev_phases": "auto", + "ev_current_entity": SET}, **(opts or {}))) + store = store or rig._Store() + store.data[unit_key("inverter-a", packmode.USE_KEY)] = False + store.data[packmode.USE_KEY] = False + db = os.path.join(tempfile.mkdtemp(prefix="ev4-"), "tariff.db") + out = {} + + async def go(): + plant = CarPlant(house, rating, soc, sim) + c = Controller(o, plant, store, rig._Pub(), stop=asyncio.Event(), + peak_db_path=db) + for i in c.inverters: + i.dev_min, i.dev_max = -5000.0, 5000.0 + c.auto = True + clock = [0.0] + c.car_now = lambda: clock[0] + if hasattr(c.charger, "_sleep"): + async def sleep(s): + sim.tick(s) + clock[0] += s + c.charger._sleep = sleep + c.charger._clock = lambda: clock[0] + real_dt = main_files.live.datetime + + class _DT(real_dt): + @classmethod + def now(cls, tz=None): + return rig.BASE + timedelta(seconds=clock[0]) + main_files.live.datetime = _DT + c.car_mode, c.car_n, c.car_a = mode, phases, float(user_a) + snaps = [] + try: + t = 0.0 + while t < dur: + plant.t = clock[0] = t + fn = events_in.get(int(t)) if t == int(t) else None + if fn is not None: + fn(plant, c) + sim.tick(1.0) + ts = t - s81.SAMPLE_LEAD_S + plant.meter = plant.grid(ts) + imp, exp = split_signed(plant.meter) + c.p1.submit(make_sample( + "ha_signed", imp, exp, phases=1, + ingest_ts=rig.BASE + timedelta(seconds=ts), + ingest_mono=time.monotonic())) + await c.read_inputs(now_mono=t) + await c.cycle() + await c.car_settle() + snaps.append((t, c.car_explains, c.car_over, + (c.peak_guard.engaged if c.peak_guard else None), + plant.batt(t), sim.power_w)) + t += s81.TICK + finally: + main_files.live.datetime = real_dt + raised = [(at, nid) for at, nid in plant.notes] + out.update(plant=plant, c=c, sim=sim, raised=raised, snaps=snaps, + store=store) + events_in = events or {} + asyncio.run(go()) + return out + + +def ids(out, *wanted): + return [(t, n) for t, n in out["raised"] if n in wanted] + + +if __name__ == "__main__": + logging.disable(logging.CRITICAL) + for name, kw in ( + ("car 11 kW, house 1.1 kW, Manual", + dict(house=s81.constant(1100.0))), + ("same, Off", dict(house=s81.constant(1100.0), mode="off"))): + r = drive(**kw) + print(f"{name:34s} alarms {ids(r, *ALARMS)} " + f"car notice {ids(r, OVER)}") diff --git a/goodwe_controller/tools/ux13_demo.py b/goodwe_controller/tools/ux13_demo.py index 25dfb1a..271bb83 100644 --- a/goodwe_controller/tools/ux13_demo.py +++ b/goodwe_controller/tools/ux13_demo.py @@ -109,7 +109,7 @@ class Hass: # real `Controller._read_charger()` reads it, so the card is what the add-on # draws, not a picture. CAR_STATES = ("car", "car_none", "car_waiting", "car_full", "car_unreach", - "car_setup") + "car_setup", "car_manual_cover", "car_manual_over") CAR_ENTITY = "number.wallbox_power_connector_max_current_socket_1" SIM = SimCharger() @@ -126,7 +126,7 @@ def car_setup(state): """Put the model in the state's situation.""" global SIM SIM = SimCharger(name="other" if state == "car_setup" else "wallbox") - if state in ("car", "car_unreach"): + if state in ("car", "car_unreach", "car_manual_cover", "car_manual_over"): SIM.plug_in() SIM.set_phases(3) SIM.set_current(16) @@ -332,6 +332,27 @@ def controller(state): for inv in c.inverters: inv.batt = 0.0 c.car.stale_s = 15.0 + if state in ("car_manual_cover", "car_manual_over"): + # EV-04, Manual at 16 A on 3 phases. First moment: the batteries give + # 5 kW and the period stays on the aim. Second: they are at the peak + # reserve, so the charge you set sets the month's peak. + c.car_mode, c.car_a, c.car_n = "manual", 16.0, 3 + if state == "car_manual_cover": + c.pv_w, c.grid = 4100.0, 3450.0 + for inv in c.inverters: + inv.batt = 2500.0 + c.peak_guard = PeakDecision( + engaged=True, floor_w=3000.0, ceiling_w=3500.0, + ceiling_from="cap", projected_w=3450.0, excess_w=1500.0) + else: + c.pv_w, c.grid = 2400.0, 10200.0 + for inv in c.inverters: + inv.soc, inv.batt = 19.0, 0.0 + c.peak_guard = PeakDecision( + engaged=True, floor_w=0.0, ceiling_w=3500.0, + ceiling_from="cap", projected_w=10200.0, excess_w=6750.0, + floor_limited=True, soc=19.0, soc_floor=20.0) + c.car_over = c.car_explains = True if state == "alarm": c.inverters[0].sign_wd.tripped = True if state in P3: diff --git a/goodwe_controller/translations/en.yaml b/goodwe_controller/translations/en.yaml index b4eec31..6ba1f20 100644 --- a/goodwe_controller/translations/en.yaml +++ b/goodwe_controller/translations/en.yaml @@ -285,7 +285,7 @@ configuration: description: "The add-on makes every decision but keeps every inverter at 0 W. 'auto' does this while control is stopped, 'on' always, 'off' never." ev_charger: name: "Car charger · Charger" - description: "Which car charger the add-on reads. Off leaves everything as it is. This version only reads the charger and never changes it." + description: "Which car charger the add-on drives. Off leaves everything as it is. In Off mode the add-on only reads the charger and never changes it." ev_current_entity: name: "Car charger · Current setting entity" description: "The entity that sets the charger's current. The add-on finds the charger's other entities from its name." @@ -295,6 +295,12 @@ configuration: ev_phases: name: "Car charger · Phases" description: "How many phases the charger may use: 1, 3, or 1 and 3 (auto)." + ev_batt_cover: + name: "Car charger · Batteries help with the peak" + description: "While the car charges. On: the batteries cover it down to the peak reserve. Off: the peak guard leaves the car out, so the car alone can set the peak." + ev_mode_start: + name: "Car charger · Mode after a restart" + description: "Keep the last mode, or start in Off. A restart never changes the charger's current." 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." diff --git a/goodwe_controller/translations/nl.yaml b/goodwe_controller/translations/nl.yaml index 019ad81..064fd31 100644 --- a/goodwe_controller/translations/nl.yaml +++ b/goodwe_controller/translations/nl.yaml @@ -266,7 +266,7 @@ configuration: description: "De add-on neemt elke beslissing maar houdt elke omvormer op 0 W. 'auto' doet dit zolang de regeling gestopt is, 'on' altijd, 'off' nooit." ev_charger: name: "Laadpaal · Laadpaal" - description: "Welke laadpaal de add-on leest. Uit laat alles zoals het is. Deze versie leest de laadpaal alleen en wijzigt niets." + description: "Welke laadpaal de add-on stuurt. Uit laat alles zoals het is. In modus Uit leest de add-on de laadpaal alleen en wijzigt niets." ev_current_entity: name: "Laadpaal · Entiteit van de laadstroom" description: "De entiteit die de stroom van de laadpaal instelt. De add-on vindt de andere entiteiten van de laadpaal via de naam." @@ -276,6 +276,12 @@ configuration: ev_phases: name: "Laadpaal · Fasen" description: "Hoeveel fasen de laadpaal mag gebruiken: 1, 3, of 1 en 3 (auto)." + ev_batt_cover: + name: "Laadpaal · Batterijen helpen met de piek" + description: "Terwijl de auto laadt. Aan: de batterijen dekken ze tot de piekreserve. Uit: de piekbewaking laat de auto buiten beschouwing, dus de auto alleen kan de piek bepalen." + ev_mode_start: + name: "Laadpaal · Modus na een herstart" + description: "De laatste modus houden, of starten in Uit. Een herstart verandert de stroom van de laadpaal nooit." 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." -- 2.54.0 From 661a3b009a22eeabc419ef2441f3df400b80bfff Mon Sep 17 00:00:00 2001 From: glenn schrooyen Date: Mon, 16 Nov 2026 06:51:15 +0100 Subject: [PATCH 2/4] EV-04 round 2: race-free another-writer check, refused phase select, undo before the select, clamped restore, energy-corroborated car figure M1 the writer ignores a reading taken before its latest confirmed write. M2 a refused phase select gives the current back and stops after 3 tries (amber row). M3 Off, shadow mode or a control/safety stop before the select undoes the change. M4 the restore on shutdown (and the undo) is clamped. M5 the car's power reaches the alarm path only while the charger's energy meter agrees with it. L1 fuzz other-writer branch reachable and shown to run. L2 one wording. L3 Batteries-help-off text. Co-Authored-By: Claude --- .../DECISIONS/EV-04-manual-mode.md | 22 +- goodwe_controller/DOCS.md | 17 +- goodwe_controller/app/carmode.py | 72 +++- goodwe_controller/app/chargers.py | 59 ++- goodwe_controller/app/ctl_car.py | 13 +- goodwe_controller/app/ctl_status.py | 3 + goodwe_controller/app/messages.py | 12 +- goodwe_controller/app/ui_text/en.json | 5 +- goodwe_controller/app/ui_text/nl.json | 5 +- goodwe_controller/test_ev04.py | 338 ++++++++++++++++-- goodwe_controller/tools/chargersim.py | 15 +- 11 files changed, 493 insertions(+), 68 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index bc02e85..ddffd38 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -62,13 +62,23 @@ 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 stale or stuck car figure must never hide a real overload.** Only +**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 (power and read-back unchanged 60 s -after a write that moved the setpoint by 1 A or more, SAFETY-37's shape), and never -above what the read-back allows the car to draw. A figure that is stuck from the -start with no write is not caught by the stuck rule; it is bounded by the -read-back and is the one hole this card leaves (the design's own rule). +unavailable reading None at once), not stuck after a write (SAFETY-37's shape), +never above what the read-back allows, and CORROBORATED by the charger's energy +meter (round 2). The rule (`CarTracker.corroborated`, constants `CORR_*` in +`chargers.py`): the charger reports charging (mode3 C) and has an energy entity, +and over the last 60 s of unbroken charging readings the meter has gained at +least 50 % of what the reported power adds up to, less 15 Wh (the meter shows +10 Wh steps). A gap, a state other than C or a meter that goes back starts the +window again. With less than a window of readings (a session just began, or +the add-on just started) the figure is believed, so a charge does not raise the +false alarms for its first minute; a frozen figure is believed for that minute +only. No energy entity: never corroborated, so the normal alarms stand. The +tolerance is loose on purpose (ramps, 10 Wh steps, the sampling) and tight +enough that a frozen power figure on a car that has stopped, or everything +frozen together, fails inside a window. Below about 0.5 kW the rule passes by +itself; such a figure cannot hide an overload that matters. ## Decision 1 (`ev_batt_cover`) diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index 8aa787a..1d358f7 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -3328,10 +3328,15 @@ what the car drew. When the car alone is why the batteries cannot hold the period, the add-on does **not** raise *Battery stopped limiting the peak* or *Load too high for battery*. It shows a grey note *Car over the peak limit* once per charging session, a grey row, and says so in the car's *Why*. -This holds only while the car's reading is fresh: a stale or stuck reading -never hides a real overload of the house. With `ev_batt_cover` off, the peak -guard protects the house without the car, so it does not force the batteries to -discharge for it, and the period goes over by the car alone. When the month's peak was set by a car +This holds only while the car's reading is fresh and the charger's energy +meter confirms it (the meter must have gained at least half of what the power +adds up to over the last minute). A stale, stuck or frozen reading, or a +charger with no energy entity, never hides a real overload of the house: the +normal alarms stand. With `ev_batt_cover` off, the peak +guard protects the house without the car, so it does not spend the batteries on +it. Normal zero-grid control can still discharge them for the car, and a grid +charge of the batteries can bring the period to the peak limit plus the car. +The period can go over by the car alone. When the month's peak was set by a car charge, Home's peak line says so. **When the charger does not answer.** After 30 seconds the card says *Charger @@ -3340,7 +3345,9 @@ follows. While the car reading is older than 15 seconds the House tile shows no reading, and that moment is left out of the house profile, rather than guessing how much the car took. A reading that does not move for a minute after the add-on changed the current shows the amber row *Charger reading may be stuck*; -the add-on goes on writing. +the add-on goes on writing. If the charger does not take a phase change three +times, an amber row says so and the add-on stops trying until you change +something; the car gets its current back each time. **Another writer.** In Manual, if the charger shows a different current than the add-on set, for 30 seconds, something else is setting it, usually your own diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index c2fe84e..e5c280a 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -120,6 +120,11 @@ class ManualWriter: self.blocked = False # a phase change waits for PHASE_GAP_S self.would = None # (amps, phases): what it would set self.log = [] # (kind, value, now, ok), for the checks + self.last_done = None # when our latest write was confirmed + self._clock = None + self.phase_fails = 0 # phase selects the charger did not take + self.phases_gave_up = False + self.undone = 0 # sequences undone before the select # ------------------------------------------------------------------ user def user_changed(self) -> None: @@ -129,22 +134,35 @@ class ManualWriter: self.hold = self.other = False self.mismatch_since = None self.fails, self.fail_at, self.gave_up = 0, None, False + self.phase_fails, self.phases_gave_up = 0, False self.attempted_a = self.prior_a = None # ------------------------------------------------------------------ step async def step(self, drv, r, *, mode, want_a, want_phases, rev, clamp, - now, tracker, writing, status): + now, tracker, writing, status, shadow=False, clock=None): """One cycle. `r` is the latest `ChargerReading`; `writing` is False in shadow mode and while control is stopped (the step then only works out what it WOULD set, in `self.would`).""" + self._clock = clock or (lambda: now) if r is None or not r.available: self.was_available = False return + # A reading taken before our latest write was confirmed says nothing + # about it (the writer runs beside the cycle and can finish between a + # read and the step that follows): wait for one taken after. + 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: + return if not self.was_available: self.was_available = True self.reapply = True # on return: only if it differs cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a if self.seq is not None: + if self.seq["stage"] in ("zero", "select") \ + and (mode != MANUAL or not writing): + await self._undo(drv, now, tracker, clamp, shadow) + return await self._advance(drv, r, cur, now, tracker, want_a, clamp, rev) return self.would = None @@ -166,7 +184,8 @@ class ManualWriter: if self.hold: return phases_need = (r.phases_allowed is not None - and r.phases_allowed != n_eff) + and r.phases_allowed != n_eff + and not self.phases_gave_up) cur_need = cur is None or abs(cur - target) > TOL_A need_user = rev != self.rev_applied if not (phases_need or cur_need): @@ -230,6 +249,7 @@ class ManualWriter: async def _write(self, drv, a, was, now, tracker) -> bool: ok = await drv.write_current(a) + self._stamp(now) tracker.note_write(now, was, a) self.log.append(("current", a, now, ok)) if ok: @@ -239,6 +259,29 @@ class ManualWriter: self.attempted_a, self.prior_a = a, was return ok + def _stamp(self, now) -> None: + self.last_done = (self._clock or (lambda: now))() + + @staticmethod + def _restore_a(prev, clamp): + """The current to give back: what it was, never above the clamp.""" + if prev is None: + return None + hi = CH.ENTITY_MAX_A if clamp is None else float(clamp) + a = min(float(prev), hi) + return a if a >= CH.MIN_A else None + + async def _undo(self, drv, now, tracker, clamp, shadow) -> None: + """Off, shadow mode or a stopped control while the car is paused and the + phases have NOT been selected: no switch. The old current comes back + (clamped), except in shadow mode, which writes nothing further.""" + q, self.seq = self.seq, None + self.undone += 1 + self.rev_applied, self.reapply = None, True + a = None if shadow else self._restore_a(q.get("prev"), clamp) + if a is not None: + await self._write(drv, a, 0.0, now, tracker) + async def _begin(self, drv, r, cur, n, now, tracker) -> None: """Step 1 of the safe sequence: 0 A. A charger that does not take it stops the sequence before the phases are touched.""" @@ -249,14 +292,15 @@ class ManualWriter: self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0, "prev": cur} - async def abandon(self, drv, now, tracker) -> None: + async def abandon(self, drv, now, tracker, clamp=None) -> None: """The add-on is stopping in the middle of a phase change: give the car - its current back (a stopped add-on must not leave it at 0 A). The - phases stay as the select left them.""" + its current back (a stopped add-on must not leave it at 0 A), clamped + like every write. The phases stay as the select left them.""" q, self.seq = self.seq, None - if q is not None and q.get("prev") is not None \ - and q["prev"] >= CH.MIN_A: - await self._write(drv, float(q["prev"]), 0.0, now, tracker) + a = None if q is None else self._restore_a(q.get("prev"), clamp) + if a is not None: + self._clock = self._clock or (lambda: now) + await self._write(drv, a, 0.0, now, tracker) async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev): q = self.seq @@ -280,9 +324,21 @@ class ManualWriter: q["stage"] = "select" if q["stage"] == "select": ok = await drv.write_phases(q["n"]) + self._stamp(now) self.last_switch = now self.log.append(("phases", q["n"], now, ok)) q["stage"], q["t1"] = "settle", now + if not ok: + # The charger did not take it: the car gets its current back + # on the old phases at once, and the change is tried again + # after PHASE_GAP_S, MAX_TRIES times in all. + self.phase_fails += 1 + q["t1"] = now - SETTLE_S + 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.") return if now - q["t1"] < SETTLE_S: return diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index b69914a..b4a9dfd 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -26,7 +26,7 @@ import asyncio import logging import re import time -from dataclasses import dataclass +from dataclasses import dataclass, field from .hass import BAD_STATES from .solarfc import KWH_PER @@ -74,6 +74,15 @@ OWN_WRITE_MUTE_S = 15.0 # the tracker's two-writer detector ignores our own # Volts used to bound a car figure by what the read-back allows (a physical # ceiling for the alarm path, never a setpoint). CEILING_V = 253.0 +# EV-04 round 2: the car's power may be used by the peak guard's alarm path only +# while the charger's energy meter CORROBORATES it. Over the last CORR_WINDOW_S +# seconds of readings (all in mode3 C, no gap) the meter must have advanced by at +# least CORR_RATIO of what the reported power adds up to, less CORR_SLACK_WH (the +# meter shows 10 Wh steps). Until a window of CORR_WINDOW_S exists (a session just +# began, or the add-on just started) the figure is believed, as it was before. +CORR_WINDOW_S = 60.0 +CORR_RATIO = 0.5 +CORR_SLACK_WH = 15.0 # role -> (entity domain, suffix after `_`). `current` is the setpoint, the # one the installer names; the rest are derived by swapping its suffix. @@ -645,6 +654,8 @@ class CarTracker: armed_sig: tuple | None = None sig: tuple | None = None stuck_now: bool = False + obs_at: float | None = None # monotonic second of the latest reading + _hist: list = field(default_factory=list) # (t, power W, energy Wh) # today's energy day: str | None = None today_kwh: float | None = None @@ -653,6 +664,8 @@ class CarTracker: def observe(self, r: ChargerReading, now: float, now_utc, day: str): self.reading = r + self.obs_at = now + self._corr_note(r, now) usable = r.available and r.power_w is not None if r.available: self.bad_since = None @@ -721,6 +734,43 @@ class CarTracker: if self.armed_at is not None and now - self.armed_at >= STUCK_S: self.stuck_now = True + def _corr_note(self, r, now: float) -> None: + """Keep the last `CORR_WINDOW_S` of (power, energy) while the charger is + charging. Any gap, a car that is not in mode3 C, a reading without + power or energy, or a meter that goes back starts the window again.""" + h = self._hist + ok = (r.available and r.charging is True and r.power_w is not None + and r.energy_kwh is not None) + if not ok or (h and r.energy_kwh * 1000.0 < h[-1][2] - 0.5): + h.clear() + if not ok: + return + h.append((now, float(r.power_w), r.energy_kwh * 1000.0)) + while len(h) > 2 and now - h[1][0] >= CORR_WINDOW_S: + h.pop(0) + + def corroborated(self, now: float) -> bool: + """Does the charger's energy meter agree with the power it reports? No + energy entity, or not charging: no. Less than a window of readings: yes + (the first minute of a session is believed). Otherwise the energy the + meter gained over the window must be at least `CORR_RATIO` of what the + power adds up to, less `CORR_SLACK_WH`. A frozen power figure on a car + that has stopped fails this within a window, and so does everything + frozen together.""" + r = self.reading + h = self._hist + if r is None or not r.available or r.charging is not True \ + or r.energy_kwh is None or not h: + return False + span = h[-1][0] - h[0][0] + if span < CORR_WINDOW_S - 5.0: + return True + exp_wh = 0.0 + for (t0, p0, _e0), (t1, _p1, _e1) in zip(h, h[1:]): + exp_wh += p0 * (t1 - t0) / 3600.0 + got_wh = h[-1][2] - h[0][2] + return got_wh >= CORR_RATIO * exp_wh - CORR_SLACK_WH + def stuck(self, now: float) -> bool: """Power and read-back unchanged `STUCK_S` after a write that moved the setpoint. Cleared the moment either moves.""" @@ -728,10 +778,11 @@ class CarTracker: def car_w_trusted(self, now: float): """The car's power for the peak guard's ALARM PATH, or None. Fresh (the - EV-03 rules), not stuck, and never above what the read-back allows the - car to draw: an old or stuck figure must not hide a house overload.""" + EV-03 rules), not stuck after a write, corroborated by the energy meter + (`corroborated`), and never above what the read-back allows the car to + draw: an old or frozen figure must not hide a house overload.""" w = self.car_w(now) - if w is None or self.stuck(now): + if w is None or self.stuck(now) or not self.corroborated(now): return None r = self.reading a = r.allowed_a if r.allowed_a is not None else r.setpoint_a diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index 483553c..52587a6 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -71,9 +71,11 @@ class CarMixin: def car_writing(self) -> bool: """May the add-on write to the charger now? Control runs, shadow mode is - off, and the add-on is not shutting down. Shadow mode gates charger + off, no safety stop is latched and the add-on is not shutting down. Shadow mode gates charger writes exactly as it gates inverter writes.""" - return bool(self.auto and not self.shadow + latched = (any(i.sign_wd.tripped for i in self.inverters) + or self.site_sign_wd.tripped or self.circ_wd.tripped) + return bool(self.auto and not self.shadow and not latched and not getattr(self, "stopping", False)) # ---------------------------------------------------------------- actions @@ -168,7 +170,8 @@ class CarMixin: return try: await asyncio.wait_for(self.car_writer.abandon( - self.charger, self.car_now(), self.car), 15.0) + self.charger, self.car_now(), self.car, self.car_clamp()), + 15.0) except Exception: # noqa: BLE001 _LOG.warning("The car could not be given its current back " "before the add-on stopped: CHARGER_RESTORE.") @@ -183,8 +186,8 @@ class CarMixin: 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(), - status=self.car.status(now, True)) + writing=self.car_writing(), shadow=bool(self.shadow), + status=self.car.status(now, True), clock=self.car_now) # ------------------------------------------- the car and the peak guard def car_alarm_w(self): diff --git a/goodwe_controller/app/ctl_status.py b/goodwe_controller/app/ctl_status.py index 20eed53..4dda3ec 100644 --- a/goodwe_controller/app/ctl_status.py +++ b/goodwe_controller/app/ctl_status.py @@ -215,6 +215,9 @@ class StatusMixin: if w.gave_up: out.append({"ok": False, "warn": True, "id": "charger_refused", "text": messages.row_charger_refused()}) + if w.phases_gave_up: + out.append({"ok": False, "warn": True, "id": "charger_phases", + "text": messages.row_charger_phases()}) elif self.car.other_writer(datetime.now(timezone.utc)): out.append({"ok": True, "warn": True, "id": "charger_writer", "text": messages.row_charger_writer()}) diff --git a/goodwe_controller/app/messages.py b/goodwe_controller/app/messages.py index e04b400..33ae65e 100644 --- a/goodwe_controller/app/messages.py +++ b/goodwe_controller/app/messages.py @@ -520,9 +520,9 @@ def row_car_over() -> str: def row_charger_other() -> str: """EV-04: the grey row, in Manual, while something else sets the current.""" - return Bi("Something else changed the charger, so the add-on writes " + return Bi("Something else changes the charger, so the add-on writes " "nothing until you change it.", - "Iets anders wijzigde de laadpaal, dus de add-on schrijft niets " + "Iets anders wijzigt de laadpaal, dus de add-on schrijft niets " "tot u iets wijzigt.") @@ -540,6 +540,13 @@ def row_charger_refused() -> str: "laadpaal.") +def row_charger_phases() -> str: + """EV-04: the amber row when the charger does not take the phases.""" + return Bi("The charger did not take the phases, so check the charger.", + "De laadpaal nam de fasen niet over, dus controleer de " + "laadpaal.") + + def row_charger_error(text) -> str: """EV-04: the grey row while the charger reports an error. Writes go on.""" t = " ".join(str(text or "").split())[:60] @@ -1776,6 +1783,7 @@ def status_samples() -> list: ("row_charger_error", GREEN, row_charger_error("Socket error")), ("row_charger_stuck", AMBER, row_charger_stuck()), ("row_charger_refused", AMBER, row_charger_refused()), + ("row_charger_phases", AMBER, row_charger_phases()), ("row_charger_setup", AMBER, row_charger_setup()), ] diff --git a/goodwe_controller/app/ui_text/en.json b/goodwe_controller/app/ui_text/en.json index 62d710d..0cf0be9 100644 --- a/goodwe_controller/app/ui_text/en.json +++ b/goodwe_controller/app/ui_text/en.json @@ -325,7 +325,7 @@ "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 batteries keep their charge, 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.", @@ -541,7 +541,8 @@ "solar_forecast": "Solar forecast", "charger": "Charger not reachable", "charger_writer": "Something else changes the charger", - "charger_other": "Something else changed the charger", + "charger_other": "Something else changes the charger", + "charger_phases": "Charger did not take phases", "charger_stuck": "Charger reading may be stuck", "charger_refused": "Charger did not take it", "charger_error": "The charger reports an error", diff --git a/goodwe_controller/app/ui_text/nl.json b/goodwe_controller/app/ui_text/nl.json index d590bd0..975e3dd 100644 --- a/goodwe_controller/app/ui_text/nl.json +++ b/goodwe_controller/app/ui_text/nl.json @@ -279,7 +279,7 @@ "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 batterijen houden hun lading, 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.", @@ -462,7 +462,8 @@ "solar_forecast": "Zonneprognose", "charger": "Laadpaal onbereikbaar", "charger_writer": "Iets anders wijzigt de laadpaal", - "charger_other": "Iets anders wijzigde de laadpaal", + "charger_other": "Iets anders wijzigt de laadpaal", + "charger_phases": "Laadpaal nam fasen niet over", "charger_stuck": "Laadpaalmeting staat mogelijk vast", "charger_refused": "Laadpaal nam het niet over", "charger_error": "De laadpaal meldt een fout", diff --git a/goodwe_controller/test_ev04.py b/goodwe_controller/test_ev04.py index 49b593d..e263d76 100644 --- a/goodwe_controller/test_ev04.py +++ b/goodwe_controller/test_ev04.py @@ -186,6 +186,18 @@ class World: await self.c.cycle() await self.c.car_settle() + async def step_race(self, n=1, dt=1.0): + """The production order: the writer task can finish AFTER the cycle's + read and BEFORE that cycle's kick (read -> task settles -> cycle), so + the step that follows sees a reading older than the write.""" + 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) @@ -682,6 +694,134 @@ async def phases_in_off(): check("in Off a phase change writes nothing either", run(phases_in_off()).writes() == []) + +print("\n5b. ROUND 2: THE SEQUENCE UNDER A RACING WRITER, A REFUSED SELECT, " + "A MODE CHANGE, THE CLAMP") + + +async def m1_race(lag): + # the writer task finishes between a cycle's read and that cycle's kick + 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(10) + n0 = len(w.writes()) + await w.act("car_phases", 3) + await w.step_race(60) + seq = [(x[1], x[2]) for x in w.writes()[n0:]] + await w.step_race(300) + return w, seq + + +for _lag in (0.0, 3.0): + w_m1, seq_m1 = run(m1_race(_lag)) + check(f"M1 (read -> writer settles -> cycle, read-back lag {_lag:.0f} s): " + "the phases are selected and the car gets its 10 A back, with no " + f"false 'something else changed the charger' ({seq_m1})", + seq_m1 == [("current", 0.0), ("phases", 3), ("current", 10.0)] + and w_m1.sim.readback_a == 10 and w_m1.sim.phases_allowed == 3 + and not w_m1.c.car_writer.hold and "charger_other" not in w_m1.rows() + and w_m1.sim.power_w > 6000) + + +async def m2_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(5) + sim = w.sim + + def deaf(n): # Home Assistant says yes, nothing moves + sim.log.append((sim.t, "phases", n, sim.power_w, sim.setpoint_a)) + return True + sim.request_phases = deaf + n0 = len(w.writes()) + await w.act("car_phases", 3) + await w.step(3700) + mid = [x for x in w.writes()[n0:]] + ph = [x for x in mid if x[1] == "phases"] + zeros = [x for x in mid if x[1] == "current" and x[2] == 0.0] + out = dict(ph=len(ph), zeros=len(zeros), rb=sim.readback_a, + gave=getattr(w.c.car_writer, "phases_gave_up", None), row=w.rows().get( + "charger_phases"), power=sim.power_w) + await w.act("car_phases", 3) # the user asks again: tried again + await w.step(60) + out["after_user"] = len([x for x in w.writes() if x[1] == "phases"]) - len(ph) + return out + + +m2 = run(m2_refused()) +check("M2: a phase select the charger never takes is tried 3 times (10 minutes " + "apart), not for ever", m2["ph"] == 3 and m2["zeros"] == 3) +check("...each time the car gets its current back on the old phases (10 A, " + "drawing), and at the end it is not left paused", m2["rb"] == 10 + and m2["power"] > 2000) +check("...then an amber row says the charger did not take the phases, and " + "the add-on stops trying", m2["gave"] is True + and m2["row"]["ok"] is False and m2["row"]["warn"] is True) +check("...until the user changes something: then it tries again", + m2["after_user"] == 1) + + +async def m3(trigger): + w = World(setpoint=10, phases=1) + w.sim.ramp_w_s = 50.0 + w.sim.stop_delay_s = 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) # 0 A written, the select not yet + n0 = len(w.writes()) + mid = (w.sim.readback_a, w.c.car_writer.seq["stage"]) + if trigger == "off": + await w.act("car_mode", "off") + elif trigger == "shadow": + w.c.o["shadow_mode"] = "on" + elif trigger == "stop": + await w.c.handle_action("auto_toggle") + w.c.o["shadow_mode"] = "off" + elif trigger == "safety": + w.c.inverters[0].sign_wd.tripped = True + await w.step(80) + return w, mid, [(x[1], x[2]) for x in w.writes()[n0:]] + + +for _trig, _want in (("off", [("current", 10.0)]), ("shadow", []), + ("stop", [("current", 10.0)]), + ("safety", [("current", 10.0)])): + w_m3, mid_m3, wr_m3 = run(m3(_trig)) + check(f"M3 ({_trig} mid-sequence, before the select): no phase switch, " + + ("nothing is written further" if not _want else + "the old 10 A comes back") + f" ({wr_m3})", + mid_m3[0] == 0.0 and wr_m3 == _want and w_m3.writes("phases") == [] + and w_m3.sim.phases_allowed == 1 and w_m3.c.car_writer.seq is None) + + +async def m4(): + w = World(dict(CAR, ev_max_a=10), setpoint=16, phases=1) + w.sim.ramp_w_s = 50.0 + w.sim.stop_delay_s = 40.0 + await w.step(60) + await w.act("car_mode", "manual") + await w.act("car_phases", 3) + await w.step(4) + prev = w.c.car_writer.seq["prev"] + await w.c.car_shutdown() + return w, prev + + +w_m4, prev_m4 = run(m4()) +check("M4: the old read-back was 16 A (another writer's) against ev_max_a 10; " + "the restore on shutdown is clamped: the car gets 10 A back, no " + "software fault is logged", + prev_m4 == 16.0 and w_m4.sim.readback_a == 10.0 + and w_m4.drv.clamp_faults == [] and w_m4.drv.sent[-1] == 10.0) + # --- every write path: who calls the seam, and a fuzz over the lot --------- # def seam_callers(): """(file, name) of every call of the charger's write methods in app/.""" @@ -712,47 +852,71 @@ async def fuzz(seed): rnd = random.Random(seed) w = World(setpoint=rnd.choice([6, 10, 16]), phases=rnd.choice([1, 3])) w.sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0]) - bad = [] - seen = 0 + race = seed % 2 == 1 # half the sites run read -> settle -> cycle + bad, seen, others, holds, undos = [], 0, 0, 0, 0 last_switch = None if rnd.random() < 0.8: await w.act("car_mode", "manual") for step in range(400): c, sim = w.c, w.sim - seq = c.car_writer.seq is not None + wr = c.car_writer + stage = wr.seq["stage"] if wr.seq is not None else None + seq = stage is not None r = rnd.random() - if r < 0.02: + if stage in ("zero", "select") and rnd.random() < 0.15: + # the user, a stop or shadow mode arrives mid-sequence + pick = rnd.choice(["off", "stop", "shadow"]) + if pick == "off": + await w.act("car_mode", "off") + elif pick == "stop": + c.auto = False + else: + c.o["shadow_mode"] = "on" + elif r < 0.02: await w.act("car_mode", rnd.choice(["off", "manual", "manual"])) elif r < 0.07: await w.act("car_current", rnd.randint(6, 16)) elif r < 0.09: await w.act("car_phases", rnd.choice([1, 3])) - elif r < 0.095 and not seq: + elif r < 0.093 and not seq: sim.go_unavailable(rnd.random() < 0.5) - elif r < 0.10 and not seq: + elif r < 0.096 and not seq: sim.station_a = float(rnd.choice([10, 13, 16])) - elif r < 0.105 and not seq: + elif r < 0.099 and not seq: (sim.unplug if sim.state != "A" else sim.plug_in)() - elif r < 0.103 and rnd.random() < 0.5: + elif r < 0.108: sim.set_current(rnd.randint(0, 16)) # another writer - elif r < 0.115: + others += 1 + elif r < 0.112: sim.refuse = rnd.choice([None, None, "ignore", "error"]) - elif r < 0.12: + elif r < 0.116: c.auto = rnd.random() < 0.8 - mode_now, auto_now = c.car_mode, c.auto - n0 = len(sim.log) - await w.step(1) + elif r < 0.12: + c.o["shadow_mode"] = rnd.choice(["on", "off", "off"]) + mode_now, auto_now, shadow_now = c.car_mode, c.auto, c.shadow + n0, u0 = len(sim.log), getattr(wr, "undone", 0) + await (w.step_race(1) if race else w.step(1)) + undone = getattr(wr, "undone", 0) > u0 + undos += undone + holds += bool(wr.hold) for t, what, v, power, sp in sim.log[n0:]: clamp = min(16.0, sim.station_a) + # a sequence whose select has gone out is finished whatever the + # mode says; one undone before it gives the old current back + exempt = stage == "settle" or undone if what == "current" and not 0.0 <= v <= clamp + 1e-9: bad.append((seed, step, "over the clamp", v, clamp)) - if what == "current" and (mode_now != "manual" and not seq): + if what == "current" and mode_now != "manual" and not exempt: bad.append((seed, step, "written outside Manual", mode_now)) - if what in ("current", "phases") and not auto_now and not seq: + if what in ("current", "phases") and not auto_now and not exempt: bad.append((seed, step, "written with control stopped")) + if what in ("current", "phases") and shadow_now and not exempt: + bad.append((seed, step, "written in shadow mode")) if what == "current" and sim.state == "A" and not seq: bad.append((seed, step, "written with no car")) if what == "phases": + if mode_now != "manual" or not auto_now or shadow_now: + bad.append((seed, step, "phases selected outside Manual")) if sp != 0.0: bad.append((seed, step, "phases with the setpoint up", sp)) if last_switch is not None and t - last_switch < 600.0: @@ -760,19 +924,26 @@ async def fuzz(seed): t - last_switch)) last_switch = t seen += len(sim.log) - n0 - return bad, seen + return bad, seen, others, holds, undos -fz_bad, fz_n = [], 0 +fz_bad, fz_n, fz_o, fz_h, fz_u = [], 0, 0, 0, 0 for _seed in range(14): - _b, _n = run(fuzz(_seed)) + _b, _n, _o, _h, _u = run(fuzz(_seed)) fz_bad += _b fz_n += _n + fz_o += _o + fz_h += _h + fz_u += _u check(f"fuzz: {fz_n} charger writes over 14 random sites and 5600 steps of " - f"random user changes, outages, unplugs, refusals and other writers: " - f"none over the clamp, none outside Manual, none with control stopped " - f"or no car, the phases never moved with the car drawing, one switch " - f"per 10 minutes ({fz_bad[:3]})", not fz_bad and fz_n > 100) + 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 " + f"phases never selected outside Manual or with the car drawing, one " + f"switch per 10 minutes ({fz_bad[:3]})", not fz_bad and fz_n > 100) +check(f"fuzz: the other-writer branch runs ({fz_o} other writers made, " + f"{fz_h} steps with the add-on holding off one, {fz_u} sequences undone)", + fz_o > 30 and fz_h > 5 and fz_u > 0) # =========================================================================== # print("\n6. SHADOW MODE AND A STOPPED CONTROL WRITE NOTHING") @@ -1160,16 +1331,101 @@ w_ = r_stuck["c"] check("...while stuck, the car figure is not used by the alarm path", w_.car.stuck(w_.car_now()) and w_.car_alarm_w() is None) -# a plausible figure is bounded by what the read-back allows +# a plausible figure is bounded by what the read-back allows (and needs an +# energy meter that agrees with it) +def corr(tr, t): + f = getattr(tr, "corroborated", None) + return f(t) if f else True # an old tree has no such rule + + +def charging_reading(e_kwh, w=11000.0, a=6.0): + return CH.ChargerReading(available=True, state="C", charging=True, + power_w=w, allowed_a=a, setpoint_a=a, + phases_allowed=1, energy_kwh=e_kwh) + + +def feed(tr, secs, e_of, w=11000.0, t0=100.0): + for i in range(secs): + tr.observe(charging_reading(e_of(i), w), t0 + i, + datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") + return t0 + secs - 1 + + tr = CH.CarTracker() -tr.observe(CH.ChargerReading(available=True, state="C", power_w=11000.0, - allowed_a=6.0, setpoint_a=6.0, - phases_allowed=1), 100.0, - datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") -check("a car figure of 11 kW on a 6 A, 1 phase read-back counts for no more " +t_end = feed(tr, 80, lambda i: 1000.0 + i * 11000.0 / 3.6e6) +check("an honest 11 kW figure on a 6 A, 1 phase read-back counts for no more " "than that allows (1.5 kW), so an old figure cannot cover a house " - "overload", abs(tr.car_w_trusted(100.0) - 6 * 253) < 1) -check("...and None when it is not fresh", tr.car_w_trusted(100.0 + 16) is None) + "overload", abs(tr.car_w_trusted(t_end) - 6 * 253) < 1 + and corr(tr, t_end)) +check("...and None when it is not fresh", tr.car_w_trusted(t_end + 16) is None) +tr = CH.CarTracker() +t_end = feed(tr, 20, lambda i: 1000.0) +check("the first minute of readings is believed (a session just began): no " + "false alarm while the meter has had no time to show it", + corr(tr, t_end) and tr.car_w_trusted(t_end) is not None) +t_end = feed(tr, 80, lambda i: 1000.0, t0=t_end + 1) +check("M5: a power figure of 11 kW with an energy meter that does not move " + "is not corroborated after a window: no car figure for the alarms", + not corr(tr, t_end) and tr.car_w_trusted(t_end) is None) +tr = CH.CarTracker() +t_end = feed(tr, 80, lambda i: 1000.0 + i * 1500.0 / 3.6e6) +check("M5: a meter that gains 1.5 kW while the power says 11 kW is not " + "corroborated either", not corr(tr, t_end)) +tr = CH.CarTracker() +t_end = feed(tr, 80, lambda i: None) +check("M5: no energy entity: never corroborated, so never used", + not corr(tr, t_end) and tr.car_w_trusted(t_end) is None) +tr = CH.CarTracker() +t_end = feed(tr, 80, lambda i: 1000.0 + i * 5000.0 / 3.6e6, w=5000.0) +t_end = feed(tr, 80, lambda i: 1000.0 + i * 11000.0 / 3.6e6, t0=t_end + 1) +check("a car that really ramps up (5 kW to 11 kW) stays corroborated", + corr(tr, t_end)) + +# --- M5 end to end: the meter, the plant and the real controller ------------- # +def freeze_all(plant, c): + plant.ch.freeze() # every reading sticks + plant.ch.set_current(0) # the car really stops + plant.load = lambda at: 9000.0 + plant.ch.power_w + + +def freeze_power_only(plant, c): + plant.ch.freeze_power() # only the power sensor sticks + plant.ch.set_current(6) # the car really draws 1.4 kW + plant.ch.set_phases(1) + plant.load = lambda at: 9000.0 + plant.ch.power_w + + +r_fz_mid = P.drive(HOUSE, dur=400, events={120: freeze_all}) +r_fz_pw = P.drive(HOUSE, dur=400, events={120: freeze_power_only}) +r_fz_0 = P.drive(HOUSE, dur=400, events={5: freeze_all}) +r_noe = P.drive(HOUSE, dur=240, sim=SimCharger(setpoint_a=16)) +for _name, _r, _t0 in (("a freeze in the middle of a session (everything " + "stuck, the car stops)", r_fz_mid, 120), + ("only the power sensor sticks while the car draws " + "1.4 kW", r_fz_pw, 120), + ("a freeze from the start", r_fz_0, 5)): + _al = alarms(_r) + check(f"M5: {_name} and the house steps to 9 kW: after a window the " + f"normal alarm fires ({_al})", + [n for _t, n in _al] == ["goodwe_peak_saturated"] + and _t0 < _al[0][0] < _t0 + 60 + 25) +r_honest = P.drive(HOUSE, dur=400) +check("M5: an honest charging car still suppresses the alarms for the whole " + "run, meter and all", alarms(r_honest) == [] + and len(P.ids(r_honest, P.OVER)) == 1) + + +class _NoE(SimCharger): + pass + + +_sim_noe = SimCharger(setpoint_a=16) +_sim_noe.no_energy = True +r_noe = P.drive(HOUSE, dur=240, sim=_sim_noe) +check("M5: a charger with no energy entity does not suppress: the normal " + "alarm fires and there is no car notice", + [n for _t, n in alarms(r_noe)] == ["goodwe_peak_saturated"] + and P.ids(r_noe, P.OVER) == []) # =========================================================================== # print("\n10. DECISION 1: BATTERIES HELP WITH THE PEAK, ON AND OFF") @@ -1187,8 +1443,9 @@ check("off: the guard sees the house without the car, is not engaged, and the " check("off: the quarter goes over by the car alone, and the add-on says so " "(one grey notice), with no alarm", alarms(r_no) == [] and len(P.ids(r_no, P.OVER)) == 1) -check("off: the Why says the batteries keep their charge", - "keep their charge" in cardwhy(r_no)) +check("off: the Why says the guard ignores the car (and promises nothing " + "about the batteries)", "guard ignores the car" in cardwhy(r_no) + and "keep their charge" not in cardwhy(r_no)) check("either way the car is never throttled", r_on["sim"].writes() == [] and r_no["sim"].writes() == [] and r_no["sim"].setpoint_a == 16 and r_no["sim"].power_w > 10000) @@ -1445,6 +1702,23 @@ check("the Dutch is not the English for the sentences", for k in ("manual_set", "manual_cover", "manual_over", "manual_full", "manual_nocover", "manual_wait", "manual_would", "manual_stopped", "manual_blocked"))) +check("L2: one wording for 'something else changes the charger', in Off and " + "Manual, English and Dutch", + en["home_words"]["attn"]["charger_other"] + == en["home_words"]["attn"]["charger_writer"] + and nl["home_words"]["attn"]["charger_other"] + == nl["home_words"]["attn"]["charger_writer"] + and "changes the charger" in str(messages.row_charger_other()) + and "wijzigt de laadpaal" in messages.row_charger_other().nl + and "changed" not in str(messages.row_charger_other())) +check("L3: with Batteries help off the Why promises nothing about the " + "batteries, and DOCS says what it does", + "keep their charge" not in json.dumps(en) + json.dumps(nl) + .replace("houden hun lading", "keep their charge") + and "zero-grid control can still discharge them for the car" + in io.open(os.path.join(HERE, "DOCS.md"), encoding="utf-8").read() + .replace("\n", " ").replace("Normal zero-grid control can still", + "zero-grid control can still")) check("every new row, notice and refusal is bilingual", all(getattr(f, "nl", None) for f in ( messages.row_car_over(), messages.row_charger_other(), diff --git a/goodwe_controller/tools/chargersim.py b/goodwe_controller/tools/chargersim.py index 8eef795..476e3f4 100644 --- a/goodwe_controller/tools/chargersim.py +++ b/goodwe_controller/tools/chargersim.py @@ -64,6 +64,8 @@ class SimCharger: self.lag_s = 0.0 # a write shows in the read-back this late self.refuse = None # None | "ignore" | "error" self._snap = None # `freeze()`: the readings stop moving + self._frozen_w = None # `freeze_power()`: only the power does + self.no_energy = False # a charger with no energy entity self.ramp_w_s = RAMP_W_S # how fast the power follows its target self.stop_delay_s = 0.0 # mode3 stays C this long after 0 A self._c_hold = 0.0 @@ -183,6 +185,11 @@ class SimCharger: moment, whatever the charger does after it.""" self._snap = self._build() if on else None + def freeze_power(self, on=True): + """Only the power sensor sticks, at what it reads now; the energy meter + and the rest go on telling the truth.""" + self._frozen_w = self.power_w if on else None + def states(self) -> dict: return self._snap if self._snap is not None else self._build() @@ -207,7 +214,8 @@ class SimCharger: {"A": "Available", "B": "EV Connected", "C": "Charging Normal"}.get(self.state, "Error")), st(f"sensor.{x}_active_power_total_socket_1", - f"{self.power_w:.0f}", "W"), + f"{self.power_w if self._frozen_w is None else self._frozen_w:.0f}", + "W"), st(f"sensor.{x}_meter_reading_socket_1", f"{self.kwh:.2f}", "kWh"), st(f"sensor.{x}_current_l1_socket_1", f"{amps[0]:.1f}", "A"), @@ -226,7 +234,10 @@ class SimCharger: "state": bad or ("on" if self.login_on else "off"), "attributes": {"device_class": "connectivity"}}), ] - return dict(rows) + out = dict(rows) + if self.no_energy: + out.pop(f"sensor.{x}_meter_reading_socket_1", None) + return out class FakeHa: -- 2.54.0 From f31dcb62b6bc3023adf0a188d4099843287feaf0 Mon Sep 17 00:00:00 2001 From: glenn schrooyen Date: Mon, 16 Nov 2026 07:59:15 +0100 Subject: [PATCH 3/4] EV-04 round 3: undo restores the current in shadow mode too, energy rule catches a frozen 6 A figure, settle after a refused select N1 the undo gives the old current back (clamped) in shadow mode; DECISIONS records it as the one write shadow mode allows. N2 the corroboration looks back to a stretch with at least 40 Wh expected (60 s at 2.4 kW and up, 104 s at 1.38 kW). L4 the current comes back 10 s after the phase select returned, also when it was refused. Co-Authored-By: Claude --- .../DECISIONS/EV-04-manual-mode.md | 38 ++++-- goodwe_controller/app/carmode.py | 14 ++- goodwe_controller/app/chargers.py | 32 +++-- goodwe_controller/test_ev04.py | 113 +++++++++++++++++- 4 files changed, 162 insertions(+), 35 deletions(-) diff --git a/goodwe_controller/DECISIONS/EV-04-manual-mode.md b/goodwe_controller/DECISIONS/EV-04-manual-mode.md index ddffd38..c9585bc 100644 --- a/goodwe_controller/DECISIONS/EV-04-manual-mode.md +++ b/goodwe_controller/DECISIONS/EV-04-manual-mode.md @@ -68,17 +68,33 @@ unavailable reading None at once), not stuck after a write (SAFETY-37's shape), never above what the read-back allows, and CORROBORATED by the charger's energy meter (round 2). The rule (`CarTracker.corroborated`, constants `CORR_*` in `chargers.py`): the charger reports charging (mode3 C) and has an energy entity, -and over the last 60 s of unbroken charging readings the meter has gained at -least 50 % of what the reported power adds up to, less 15 Wh (the meter shows -10 Wh steps). A gap, a state other than C or a meter that goes back starts the -window again. With less than a window of readings (a session just began, or -the add-on just started) the figure is believed, so a charge does not raise the -false alarms for its first minute; a frozen figure is believed for that minute -only. No energy entity: never corroborated, so the normal alarms stand. The -tolerance is loose on purpose (ramps, 10 Wh steps, the sampling) and tight -enough that a frozen power figure on a car that has stopped, or everything -frozen together, fails inside a window. Below about 0.5 kW the rule passes by -itself; such a figure cannot hide an overload that matters. +and, looking back over unbroken charging readings to the shortest stretch that +is at least 55 s long and over which the reported power adds up to at least +40 Wh, the meter has gained at least 50 % of that, less 15 Wh (the meter shows +10 Wh steps, so at 40 Wh it must show one step; an honest car can fall one step +short and still passes). Readings are kept 180 s. A gap, a state other than C or +a meter that goes back starts the history again. With no such stretch yet (a +session just began, or the add-on just started) the figure is believed, so a +charge does not raise false alarms for its first minute; a frozen figure is +believed for that long only. No energy entity: never corroborated, so the normal +alarms stand. **Bound:** a frozen figure of P watts on a car that has really +stopped is caught within max(60 s, 40 Wh / P): 60 s from 2.4 kW up, 104 s at +1.38 kW (6 A, 1 phase, the lowest charge), plus the alarms' own 10 s hold. Below +about 0.8 kW (40 Wh over the 180 s kept) the figure is believed; it cannot hide +an overload that matters. (Round 2 had a 15 Wh slack that cancelled the 50 % rule +up to 1.8 kW; the 40 Wh floor fixes that.) + +## The one write shadow mode allows + +When the add-on has paused the car (0 A) for a phase change and has not yet +selected the phases, Off, a stop of control, a safety latch or shadow mode ends +the change. The old current is given back (clamped, `_restore_a`) in every one of +those cases, shadow mode included. With the shipped `shadow_mode: auto`, stopping +control turns shadow on, so without this the car would stay at 0 A for as long +as control is stopped, while the design's Manual column says the current +stands. Undoing our own half-done change is not a new command; it is the same +write the shutdown restore makes. Nothing else is written in shadow mode: no +phase switch, and no write afterwards. ## Decision 1 (`ev_batt_cover`) diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index e5c280a..347988f 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -274,11 +274,13 @@ class ManualWriter: async def _undo(self, drv, now, tracker, clamp, shadow) -> None: """Off, shadow mode or a stopped control while the car is paused and the phases have NOT been selected: no switch. The old current comes back - (clamped), except in shadow mode, which writes nothing further.""" + (clamped), in shadow mode too: it undoes the add-on's own half-done + change (as the shutdown restore does) and is the one write shadow mode + allows. Nothing else is written afterwards.""" q, self.seq = self.seq, None self.undone += 1 self.rev_applied, self.reapply = None, True - a = None if shadow else self._restore_a(q.get("prev"), clamp) + a = self._restore_a(q.get("prev"), clamp) if a is not None: await self._write(drv, a, 0.0, now, tracker) @@ -327,13 +329,13 @@ class ManualWriter: self._stamp(now) self.last_switch = now self.log.append(("phases", q["n"], now, ok)) - q["stage"], q["t1"] = "settle", now + q["stage"], q["t1"] = "settle", self.last_done # from its return if not ok: # The charger did not take it: the car gets its current back - # on the old phases at once, and the change is tried again - # after PHASE_GAP_S, MAX_TRIES times in all. + # on the old phases after the same SETTLE_S as a taken select + # (HA may have taken it and only the read-back be late), and + # the change is tried again after PHASE_GAP_S, MAX_TRIES times. self.phase_fails += 1 - q["t1"] = now - SETTLE_S if self.phase_fails >= MAX_TRIES: self.phases_gave_up = True _LOG.warning("The charger did not take the phases, so the " diff --git a/goodwe_controller/app/chargers.py b/goodwe_controller/app/chargers.py index b4a9dfd..f02a573 100644 --- a/goodwe_controller/app/chargers.py +++ b/goodwe_controller/app/chargers.py @@ -75,14 +75,22 @@ OWN_WRITE_MUTE_S = 15.0 # the tracker's two-writer detector ignores our own # ceiling for the alarm path, never a setpoint). CEILING_V = 253.0 # EV-04 round 2: the car's power may be used by the peak guard's alarm path only -# while the charger's energy meter CORROBORATES it. Over the last CORR_WINDOW_S -# seconds of readings (all in mode3 C, no gap) the meter must have advanced by at -# least CORR_RATIO of what the reported power adds up to, less CORR_SLACK_WH (the -# meter shows 10 Wh steps). Until a window of CORR_WINDOW_S exists (a session just -# began, or the add-on just started) the figure is believed, as it was before. +# while the charger's energy meter CORROBORATES it. Looking back over readings +# (all in mode3 C, no gap) to the shortest stretch that is at least CORR_WINDOW_S +# long AND over which the reported power adds up to at least CORR_MIN_WH, the +# meter must have advanced by at least CORR_RATIO of that, less CORR_SLACK_WH (the +# meter shows 10 Wh steps, so at 40 Wh expected it must show one step). Readings +# are kept for CORR_KEEP_S. Until such a stretch exists (a session just began, or +# the add-on just started) the figure is believed, as it was before. A frozen +# figure of P watts on a car that has really stopped is caught within +# max(CORR_WINDOW_S, CORR_MIN_WH / P) seconds: 60 s at 2.4 kW and up, 104 s at +# 1.38 kW (6 A, 1 phase). Below CORR_MIN_WH over CORR_KEEP_S (about 0.8 kW) the +# figure is believed; it cannot hide an overload that matters. CORR_WINDOW_S = 60.0 CORR_RATIO = 0.5 CORR_SLACK_WH = 15.0 +CORR_MIN_WH = 40.0 +CORR_KEEP_S = 180.0 # role -> (entity domain, suffix after `_`). `current` is the setpoint, the # one the installer names; the rest are derived by swapping its suffix. @@ -746,7 +754,7 @@ class CarTracker: if not ok: return h.append((now, float(r.power_w), r.energy_kwh * 1000.0)) - while len(h) > 2 and now - h[1][0] >= CORR_WINDOW_S: + while len(h) > 2 and now - h[1][0] >= CORR_KEEP_S: h.pop(0) def corroborated(self, now: float) -> bool: @@ -762,14 +770,14 @@ class CarTracker: if r is None or not r.available or r.charging is not True \ or r.energy_kwh is None or not h: return False - span = h[-1][0] - h[0][0] - if span < CORR_WINDOW_S - 5.0: - return True exp_wh = 0.0 - for (t0, p0, _e0), (t1, _p1, _e1) in zip(h, h[1:]): + for k in range(len(h) - 1, 0, -1): + (t0, p0, e0), (t1, _p1, _e1) = h[k - 1], h[k] exp_wh += p0 * (t1 - t0) / 3600.0 - got_wh = h[-1][2] - h[0][2] - return got_wh >= CORR_RATIO * exp_wh - CORR_SLACK_WH + if h[-1][0] - t0 >= CORR_WINDOW_S - 5.0 and exp_wh >= CORR_MIN_WH: + got_wh = h[-1][2] - e0 + return got_wh >= CORR_RATIO * exp_wh - CORR_SLACK_WH + return True def stuck(self, now: float) -> bool: """Power and read-back unchanged `STUCK_S` after a write that moved the diff --git a/goodwe_controller/test_ev04.py b/goodwe_controller/test_ev04.py index e263d76..d07e136 100644 --- a/goodwe_controller/test_ev04.py +++ b/goodwe_controller/test_ev04.py @@ -766,8 +766,46 @@ check("...until the user changes something: then it tries again", m2["after_user"] == 1) -async def m3(trigger): +async def l4_late(): + # Home Assistant takes the select but the read-back is late: the current + # must not come back before SETTLE_S has passed 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 + ret = [] + real = w.drv.write_phases + + async def spy(n): + r = await real(n) + ret.append((sim.t, r)) # model time the select call returned + return r + w.drv.write_phases = spy + n0 = len(w.writes()) + await w.act("car_phases", 3) + await w.step(60) + ws = w.writes()[n0:] + t_back = next(x[0] for x in ws if x[1] == "current" and x[0] > ret[0][0] - 1) + return ret[0][1], t_back - ret[0][0] + + +took_l4, gap_l4 = run(l4_late()) +check(f"L4: after a phase select the charger did not take in time (read-back " + f"12 s late), the current comes back only 10 s after the select call " + f"returned ({gap_l4:.0f} s)", took_l4 is False and gap_l4 >= 10.0) + + +async def m3(trigger): + # the shipped shadow_mode: auto (shadow is on whenever control is stopped) + w = World(dict(CAR, shadow_mode="auto"), setpoint=10, phases=1) w.sim.ramp_w_s = 50.0 w.sim.stop_delay_s = 40.0 await w.step(60) @@ -784,22 +822,23 @@ async def m3(trigger): w.c.o["shadow_mode"] = "on" elif trigger == "stop": await w.c.handle_action("auto_toggle") - w.c.o["shadow_mode"] = "off" elif trigger == "safety": w.c.inverters[0].sign_wd.tripped = True await w.step(80) return w, mid, [(x[1], x[2]) for x in w.writes()[n0:]] -for _trig, _want in (("off", [("current", 10.0)]), ("shadow", []), +for _trig, _want in (("off", [("current", 10.0)]), + ("shadow", [("current", 10.0)]), ("stop", [("current", 10.0)]), ("safety", [("current", 10.0)])): w_m3, mid_m3, wr_m3 = run(m3(_trig)) check(f"M3 ({_trig} mid-sequence, before the select): no phase switch, " - + ("nothing is written further" if not _want else - "the old 10 A comes back") + f" ({wr_m3})", + + "the old 10 A comes back, and nothing is written after it " + + f"(N1, shipped shadow_mode auto; {wr_m3})", mid_m3[0] == 0.0 and wr_m3 == _want and w_m3.writes("phases") == [] - and w_m3.sim.phases_allowed == 1 and w_m3.c.car_writer.seq is None) + and w_m3.sim.readback_a == 10.0 and w_m3.sim.phases_allowed == 1 + and w_m3.c.car_writer.seq is None) async def m4(): @@ -1381,6 +1420,46 @@ t_end = feed(tr, 80, lambda i: 1000.0 + i * 11000.0 / 3.6e6, t0=t_end + 1) check("a car that really ramps up (5 kW to 11 kW) stays corroborated", corr(tr, t_end)) +# N2: the lowest charge, 6 A on 1 phase (1380 W), honest and frozen +def honest_1380(tr, secs, t0=100.0, e0=1000.0, step_wh=10.0): + """An honest 1380 W car whose meter shows `step_wh` steps.""" + for i in range(secs): + wh = 1380.0 * i / 3600.0 + tr.observe(charging_reading((e0 + (wh // step_wh) * step_wh) / 1000.0, + 1380.0), t0 + i, + datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") + return t0 + secs - 1 + + +tr = CH.CarTracker() +t_end = honest_1380(tr, 400) +check("N2: an honest 6 A, 1 phase car (1380 W) with a meter that shows 10 Wh " + "steps is believed, minute after minute", + corr(tr, t_end) and tr.car_w_trusted(t_end) is not None + and all(corr(tr, t) for t in (t_end - 3, t_end - 17))) +ok_all = True +tr = CH.CarTracker() +for i in range(500): # step sizes and phases of the meter vary + wh = 1380.0 * i / 3600.0 + step_wh = (10.0, 5.0, 20.0)[i // 170] + tr.observe(charging_reading((1000.0 + (wh // step_wh) * step_wh) / 1000.0, + 1380.0), 100.0 + i, + datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") + ok_all &= corr(tr, 100.0 + i) +check("...at every second of a 500 s charge with 5, 10 and 20 Wh meter steps", + ok_all) +tr = CH.CarTracker() +t_end = honest_1380(tr, 200) +frozen_at, caught = t_end, None +for i in range(1, 200): # now the figure and the meter freeze + tr.observe(charging_reading(tr.reading.energy_kwh, 1380.0), t_end + i, + datetime(2026, 11, 16, tzinfo=timezone.utc), "2026-11-16") + if caught is None and not corr(tr, t_end + i): + caught = i +check(f"N2: a frozen 1380 W figure is caught {caught} s after the freeze " + "(bound: 40 Wh / 1.38 kW = 104 s, and not sooner than the honest run " + "allows)", caught is not None and 60 <= caught <= 110) + # --- M5 end to end: the meter, the plant and the real controller ------------- # def freeze_all(plant, c): plant.ch.freeze() # every reading sticks @@ -1409,6 +1488,28 @@ for _name, _r, _t0 in (("a freeze in the middle of a session (everything " f"normal alarm fires ({_al})", [n for _t, n in _al] == ["goodwe_peak_saturated"] and _t0 < _al[0][0] < _t0 + 60 + 25) +def freeze_1380(plant, c): + plant.ch.freeze() + plant.ch.set_current(0) # the car really stops + plant.load = lambda at: 9000.0 + plant.ch.power_w + + +_s6 = SimCharger(setpoint_a=6) +_s6.phases_allowed = 1 +r_fz_6a = P.drive(HOUSE, dur=500, sim=_s6, user_a=6, setpoint=6, phases=1, + events={150: freeze_1380}) +_al6 = alarms(r_fz_6a) +check("N2 (probe G): a frozen 6 A, 1 phase figure (1380 W) after the car " + "really stops, and the house steps to 9 kW: the normal alarm fires " + f"within the stated bound ({_al6})", + [n for _t, n in _al6] == ["goodwe_peak_saturated"] + and 150 < _al6[0][0] < 150 + 104 + 10 + 25) +_s6h = SimCharger(setpoint_a=6) +r_6_honest = P.drive(HOUSE, dur=500, sim=_s6h, user_a=6, setpoint=6, phases=1, + opts={"peak_cap_w": 1500}) +check("an honest 6 A, 1 phase car on the real controller: the corroboration " + "never turns the figure off (the car stays trusted to the end)", + r_6_honest["c"].car_alarm_w() is not None) r_honest = P.drive(HOUSE, dur=400) check("M5: an honest charging car still suppresses the alarms for the whole " "run, meter and all", alarms(r_honest) == [] -- 2.54.0 From 6e6344eb028a13f9fee5817706431d52a51e61a2 Mon Sep 17 00:00:00 2001 From: glenn schrooyen Date: Mon, 16 Nov 2026 08:22:16 +0100 Subject: [PATCH 4/4] EV-04 round 3: guard the L4 test's reads for test_named_absence Co-Authored-By: Claude --- goodwe_controller/test_ev04.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/goodwe_controller/test_ev04.py b/goodwe_controller/test_ev04.py index d07e136..1b28031 100644 --- a/goodwe_controller/test_ev04.py +++ b/goodwe_controller/test_ev04.py @@ -792,9 +792,12 @@ async def l4_late(): n0 = len(w.writes()) await w.act("car_phases", 3) await w.step(60) - ws = w.writes()[n0:] - t_back = next(x[0] for x in ws if x[1] == "current" and x[0] > ret[0][0] - 1) - return ret[0][1], t_back - ret[0][0] + if not ret: + return None, 0.0 + t_ret, took = ret[0] + t_back = next((x[0] for x in w.writes()[n0:] + if x[1] == "current" and x[0] > t_ret - 1), None) + return took, (0.0 if t_back is None else t_back - t_ret) took_l4, gap_l4 = run(l4_late()) -- 2.54.0