diff --git a/goodwe_controller/CHANGELOG.md b/goodwe_controller/CHANGELOG.md index 9bc8f5f..ee84ce5 100644 --- a/goodwe_controller/CHANGELOG.md +++ b/goodwe_controller/CHANGELOG.md @@ -2,6 +2,7 @@ ### Not in a release yet +- **A peak cut the charger does not take no longer stops Solar.** After three refused tries in a 15-minute period, Solar goes on controlling the car and tries the cut again at the start of the next period while it is still needed. The warning now says "The charger did not take the peak cut, so the add-on tries again next quarter: CHARGER_REFUSED." ([[EV-54]]). - **The add-on log now says when the add-on sets a new car current or the car mode changes.** One line each, for example "Car: set from 10 A to 6 A on 1 phase (Manual)." and "Car mode is now Manual." It names the reason: Manual, Solar, peak cut, start-up or shutdown. A refused write adds no such line, and nothing is written or timed differently ([[EV-52]]). - **Solar now lowers the car first for the peak limit.** When the 15-minute period heads over the limit, Solar lowers the car before the batteries give more, and brings it back when the period allows. One grey note says "Solar lowered the car for the peak." A Solar car the add-on cannot lower (another writer, shadow mode, a stop) no longer hides a peak alarm. Manual and Off do not change. See "Car charger" in DOCS ([[EV-21]]). diff --git a/goodwe_controller/DECISIONS/EV-54-refused-cut-retry.md b/goodwe_controller/DECISIONS/EV-54-refused-cut-retry.md new file mode 100644 index 0000000..4878637 --- /dev/null +++ b/goodwe_controller/DECISIONS/EV-54-refused-cut-retry.md @@ -0,0 +1,64 @@ +# EV-54 — Solar: a refused peak cut is tried again next quarter + +EV-21 sent its cut tries through Solar's normal retry, whose third refusal set +the session-wide `gave_up`. A cut is held at 0 A (or a partial value) under a +standing cap, so neither way out of `gave_up` could come: after three refused +tries Solar never wrote again, also once the charger took writes again (EV-21 +rig, finding 1). The rules below are the PM rulings Q1-Q9, G1-G6, QA, QB and +QC (brief v6); the formal check is reports/EV-54-formal-report.md. + +## The rule, in plain words + +- **A cut try** is a Solar write while a cut is due or stands, at or under its + cap (the cut, its retry, a 0 A of a phase change or a way out): `_cut_try`. +- **At most 3 refused cut tries per quarter key** (the projection's + `block_start`), across cut values and episodes. A deeper cut does not give + new tries; a press of Solar, or Off then Solar, does not either. The count + is in memory only: a restart starts afresh (`cut_quarter`, `cut_fails`). +- **A refused cut try never sets `gave_up`.** Solar's normal writes go on. The + third refusal of a quarter logs one warning per episode: "The charger did not + take the peak cut, so the add-on tries again next quarter: CHARGER_REFUSED." + (DEBUG after; a taken cut or a mode change re-arms it). The amber row and + the card's Why show it while the tries are used up and the charger shows + more than the cut (`cut_refused`). The hold path's text is unchanged. +- **The next quarter tries again** while a cut is still needed, as EV-21's cut: + at once without headroom, else after the 15 s wait; a same-value retry no + sooner than 60 s after the last refusal. +- **The drop.** Once no cut stands (the cap lifted, or a new quarter's cut + waits) a refused cut value is never sent again. Solar takes the read-back + as its own: `sent_a` = read-back, taken, `gave_up` cleared, and the plan's + current = read-back, timed as a new decision (`_drop`). The retry clock + stays, so nothing non-zero reaches the charger within 60 s of its refusal. + The drop waits while the reading is stuck (QA) or the read-back is unknown + (QB); meanwhile Solar sends nothing but a way out's 0 A. +- **A stuck reading after the lift** keeps base's fault path: its 0 A goes + out three times 60 s apart with reason Solar, then `gave_up` with the hold + path's text; the first good reading drops it and clears `gave_up` (QC). +- **A cut write that raises** counts as a refused cut try (no Traceback, no + try per cycle). The same gap outside the cut is EV-56. + +## Choices the rulings left open + +- Refused cut tries still count in `fails` (without `gave_up`), and outside the + cut `fails >= MAX_TRIES` stops a write as `gave_up` did, but only while the + refused value is still owed. So Off's way-out 0 A after refused cut tries is + written exactly as before (N10). Once that value is gone (the charger came + back, another value was written), nothing blocks Solar's normal writes + (review round 1: a gate on `fails` alone froze Solar after the charger came + back under a capped quarter). The gate is scoped rather than `fails` reset, + so one rule covers every way the value goes, and the quarter's cut count + (`cut_fails`) is never touched by it. When the cut + stops standing in Solar and the value cannot be dropped yet (stuck), that + value becomes Solar's own: reason Solar, a fresh `fails` count (QC). +- `fails` counts only refusals of the value now owed (PM, review round 2). + Where a refused cut value stops being owed without a drop (the charger's + return, another value written in its place), `fails` goes to 0 + (`_forget_refused`); `cut_fails` stays. Elsewhere `fails` is already + right: a drop, a taken write or an adopt clear it; a Solar press or a + change into Solar clear it; Off and the quarter roll keep the owed value, + so its count stays (Off's way-out as before). +- At a new quarter's wait the cut tick holds the read-back the writer is about + to take, not the refused value, so the wait never re-sends it (G1). +- No drop over another writer's value (a hold or a difference being watched). +- A new cut value under the read-back is logged "peak cut", also when it lies + above a refused value. diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index b996073..ec0ddb2 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -3389,6 +3389,10 @@ changes at most once per 30 seconds and only by 1 A or more. fault, or a lower current the charger has not shown yet), the peak alarms treat the car as in Off. A Solar charge is never counted as setting the month's peak. +- **A cut the charger does not take** is tried again after a minute, at most + three times per 15-minute period; then one warning and an amber row say so. + Solar's normal control goes on, and the cut is tried again at the start of + the next period while it is still needed. - **Energy.** The card says "{kWh} charged today, {kWh} from the sun", and the sensor `goodwe_car_today_solar_kwh` has the sun's part. Only Solar's own share of spare sun counts, not the hold's battery or grid power. diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index f4cbcb5..23bc92a 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -845,6 +845,16 @@ class SolarWriter(ManualWriter): self.sent_at = None # EV-21: when `sent_a` went out self.startup_zero = False # EV-52: the 0 A the start itself caused self.sent_why = None # EV-52: the reason of `sent_a`'s write + # EV-54: the peak cut's refused tries, per quarter key, in memory only + # (DECISIONS/EV-54-refused-cut-retry.md). + self.cut_on = False # a cut stands (its cap), set per cycle + self.cut_blind = False # ... sized on a stale or blind meter now + self.cut_key = None # the quarter key the count is for + self.cut_fails = 0 # cut tries the charger did not take in it + self.cut_fail_at = None # ... the latest of them + self.cut_warned = False # ... and its one CHARGER_REFUSED was given + self.sent_cut = False # `sent_a` went out as a cut try + self.refused_cut = None # a cut value the charger did not take def owe_start(self) -> None: """C1: the add-on starts in Off while an exit 0 A of its own was still @@ -882,6 +892,60 @@ class SolarWriter(ManualWriter): and self.sent_a <= TOL_A and not self.taken and not self.hold) + @property + def cut_refused(self) -> bool: + """EV-54: the quarter's cut tries are used up and the charger still + shows more than the cut (the amber row and the card's Why).""" + return bool(self.cut_fails >= MAX_TRIES + and self.refused_cut is not None and not self.taken) + + def cut_quarter(self, key) -> None: + """EV-54 (Q1, Q8): a new quarter key gives the cut MAX_TRIES tries + again. Only a known key counts: a cycle without a projection keeps + the count.""" + if key is not None and key != self.cut_key: + self.cut_key, self.cut_fails = key, 0 + + def _cut_try(self, a) -> bool: + """EV-54 (Q6): a write while a cut is due or stands, at or under its + cap, is a cut try (the cut, a retry, a 0 A of a way out or of a phase + change).""" + return self.cut_a is not None and float(a) <= self.cut_a + TOL_A + + def _forget_refused(self) -> None: + """EV-54 (PM, review r2): a refused cut value is no longer owed and + is not dropped (the charger's return, another value written): its + refusals leave `fails` with it. `cut_fails`, the quarter's cap, stays.""" + if self.refused_cut is not None: + self.refused_cut = None + self.fails = 0 + + def drop_ready(self, cur, stuck) -> bool: + """EV-54 (drop rule): a cut value the charger did not take, no cut + stands any more (lifted, or a new quarter's cut waits), and a known + read-back that is not stuck and not another writer's: Solar takes + the charger as it is instead of sending that value again.""" + return bool(self.refused_cut is not None and not self.taken + and not self.cut_on and not stuck and cur is not None + and not self.hold and self.mismatch_since is None + and not self.fresh_start) + + def _drop(self, cur, now) -> None: + """EV-54: `sent_a` = the read-back, taken (an adopt: `gave_up` and the + try count cleared), and the plan's current = the read-back, timed as + a new decision. Nothing is written. The retry clock stays: no + non-zero write reaches the charger within RETRY_S of its refusal.""" + if self.sent_a is not None and self.sent_a <= TOL_A: + self._owed(False) # that 0 A is no longer owed + at = self.fail_at + self.sent_a, self.sent_cut = float(cur), False + self._adopt(cur) + self.fail_at = at + if float(cur) >= CH.MIN_A: + self.plan._set(float(cur), now) + else: + self.plan.pause() + def amps_out(self, clamp) -> float: """The plan's current, never above the clamp; 0 when under 6 A.""" a = float(self.plan.a) @@ -900,6 +964,7 @@ class SolarWriter(ManualWriter): if held: self.last_a = None self.sent_a, self.taken = None, True + self.refused_cut = None # ------------------------------------------------------------- writes async def _write(self, drv, a, was, now, tracker, **kw) -> bool: @@ -914,6 +979,10 @@ class SolarWriter(ManualWriter): and self.boot else "Solar" kw["why"] = why self.sent_why = why + cut_try = self.sent_cut = self._cut_try(a) + if self.refused_cut is not None \ + and abs(self.refused_cut - float(a)) > TOL_A: + self._forget_refused() # EV-54: another value, not that one self.sent_a, self.taken = float(a), False if prev is None or abs(prev - float(a)) > TOL_A: # EV-21 (PM Q1, formal C15): the 2 s grace of a lowering on its @@ -930,6 +999,15 @@ class SolarWriter(ManualWriter): self._owed(True) # C1: kept with the mode until back try: ok = await super()._write(drv, a, was, now, tracker, **kw) + except Exception as e: # noqa: BLE001 + if not cut_try: + raise + # EV-54 (T15): a cut write that raises is a refused cut try, so it + # is spaced and capped like one, not tried once per cycle. + _LOG.debug("The peak cut write failed: %s", e) + self.log.append(("current", a, now, False)) + self.attempted_a, self.prior_a = a, was + ok = False finally: if zero: self.zero_sent_at = None @@ -937,6 +1015,9 @@ class SolarWriter(ManualWriter): self.taken = True self.startup_zero = False self.fails, self.fail_at, self.gave_up = 0, None, False + self.refused_cut = None + if cut_try: + self.cut_warned = False # EV-54: a taken cut re-arms it if zero: self._owed(False) else: @@ -949,6 +1030,25 @@ class SolarWriter(ManualWriter): return "peak cut" if q.get("cut") else "Solar" def _failed(self, now) -> None: + if self.sent_cut: + # EV-54 (Q1, F7): a refused cut try counts against the quarter's + # MAX_TRIES and never stops Solar; the next quarter tries again. + # `fails` counts it as before, so a way out of Off that follows + # is tried as often as before (N10). + self.fails += 1 + self.fail_at = self.cut_fail_at = now + self.cut_fails += 1 + self.refused_cut = self.sent_a + if self.cut_fails >= MAX_TRIES: + if not self.cut_warned: + self.cut_warned = True + _LOG.warning("The charger did not take the peak cut, so " + "the add-on tries again next quarter: " + "CHARGER_REFUSED.") + else: + _LOG.debug("The charger did not take the peak cut, %d " + "tries this quarter.", self.cut_fails) + return self.fails += 1 self.fail_at = now if self.fails >= MAX_TRIES and not self.gave_up: @@ -966,24 +1066,49 @@ class SolarWriter(ManualWriter): self.last_a = cur self.attempted_a = self.prior_a = None self.fails, self.fail_at, self.gave_up = 0, None, False + self.refused_cut = None + if self.sent_cut: + self.cut_warned = False # EV-54: a cut taken late re-arms it # EV-52 (PM Q2): a write the charger took late is logged once, here. late, self._late = self._late, None if late is not None and cur is not None \ and abs(float(cur) - float(late[0])) <= TOL_A: self._log_set(*late) - async def _put(self, drv, want, cur, now, tracker, stuck=False) -> None: + async def _put(self, drv, want, cur, now, tracker, stuck=False, + out=False) -> None: """Make the charger match `want`: write a new decision, try one the charger did not take again after `RETRY_S`. A new 0 A gets its own - `MAX_TRIES` and never waits (0 A is the safe side).""" + `MAX_TRIES` and never waits (0 A is the safe side). EV-54: a cut try + is capped per quarter, never stopped by `gave_up`; a refused cut + value no cut needs is dropped (`_drop`), never sent again, except as + a way out's 0 A (`out`).""" if self.hold: return if want > TOL_A and self.nz_block: return # C17/C18: 0 A only, no retry or raise + # EV-54: refused cut tries count in `fails` without `gave_up`; outside + # the cut they stop a write as `gave_up` did before, but only while + # that refused value is still owed. Once it is gone (the charger's + # return, another write) no stale count blocks Solar (review r1). + # The quarter's cut count (`cut_fails`) is not touched. + stopped = self.gave_up or (self.fails >= MAX_TRIES + and self.refused_cut is not None + and not self.taken) + cut_try = self._cut_try(want) + if cut_try and self.cut_fails >= MAX_TRIES: + return # EV-54 (Q1): this quarter's tries used + if cut_try and self.cut_blind and self.refused_cut is not None \ + and abs(want - self.refused_cut) <= TOL_A: + return # EV-54 (N7): no retry on a stale meter + if not out and self.refused_cut is not None and not self.taken \ + and not self.cut_on and ( + want > TOL_A or abs(want - self.refused_cut) <= TOL_A): + return # EV-54: the drop waits for a reading if self.sent_a is not None and abs(self.sent_a - want) <= TOL_A: if self.held_step: return # C18: no retry to a charger not answering - if self.taken or self.gave_up or ( + if self.taken or (stopped and not cut_try) or ( self.fail_at is not None and now - self.fail_at < RETRY_S): return @@ -997,14 +1122,23 @@ class SolarWriter(ManualWriter): return cut = (self.cut_a is not None and want <= self.cut_a + TOL_A and self.sent_a is not None and want < self.sent_a - TOL_A) + if cut_try and self.refused_cut is None \ + and self.cut_fail_at is not None \ + and now - self.cut_fail_at < RETRY_S: + return # EV-54 (F6): a new episode's try if want <= TOL_A or cut: # A new 0 A, or EV-21's new lower cut value: its own tries, at once. self.fails, self.fail_at, self.gave_up = 0, None, False - elif self.gave_up or (self.fail_at is not None - and now - self.fail_at < RETRY_S): + elif (stopped and not cut_try) or ( + self.fail_at is not None and now - self.fail_at < RETRY_S): return + # EV-54 (review r1): a new cut value under the read-back is a peak cut, + # also when it lies above the refused one (`cut` compares with + # `sent_a`, which is that refused value). + peak = cut or (cut_try and self.refused_cut is not None + and cur is not None and want < cur - TOL_A) await self._write(drv, want, cur, now, tracker, - why="peak cut" if cut else None) + why="peak cut" if peak else None) def _own_readback(self, cur) -> bool: """C9: does the read-back show a current of Solar's own (sent, @@ -1024,7 +1158,7 @@ class SolarWriter(ManualWriter): if not self.live and self._own_readback(cur) and not stuck: self.taken = False # C9: a 0 A is owed if self.live and not self.hold: - await self._put(drv, 0.0, cur, now, tracker, stuck) + await self._put(drv, 0.0, cur, now, tracker, stuck, out=True) def _watch(self, cur, now) -> None: was = self.hold @@ -1183,6 +1317,10 @@ class SolarWriter(ManualWriter): self.engaged, self.restart = True, True self.sent_a, self.taken = None, True self.fails, self.fail_at, self.gave_up = 0, None, False + # EV-54: nothing refused is pending; a mode change re-arms the + # notice. The quarter's try count stays (Q5). + self.refused_cut, self.sent_cut, self.cut_warned = None, False, \ + False if not self.engaged: return if sun is not None: @@ -1255,6 +1393,12 @@ class SolarWriter(ManualWriter): self.out = False self._would_n = self._would_switch = None self.would = None + if self.refused_cut is not None and not self.taken \ + and not self.cut_on and self.sent_cut: + # EV-54 (QC): no cut stands, so a value still owed is Solar's own + # (a stuck reading's way out), not a peak cut: its reason is + # Solar's and it gets Solar's own tries. + self.sent_why, self.sent_cut, self.fails = "Solar", False, 0 fault = ("error" if (r.error or r.state in ("E", "F")) else "stuck" if stuck else None) if not stuck: @@ -1311,6 +1455,10 @@ class SolarWriter(ManualWriter): if self.fresh_start: self.fresh_start = False self.sent_a, self.taken = None, True # 0 A first (D2) + self._forget_refused() + if self.drop_ready(cur, stuck): + # EV-54 (drop rule): the refused cut value is not sent again. + self._drop(cur, now) if self.seq is None: self._watch(cur, now) if self.hold or self.mismatch_since is not None: diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index caa9ba2..39f733f 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -294,7 +294,7 @@ class CarMixin: w = self.car_solar if not self.car_solar_mode(): self._cut = self._cut_fresh(None) - w.cut_a = None + w.cut_a, w.cut_on, w.cut_blind = None, False, False return key = None if real_proj is None else real_proj.block_start st = self._cut @@ -306,7 +306,10 @@ class CarMixin: # N9: nothing sized from a stale projection; what stands stays. w.cut_a = st["cap"] if st["cap"] is not None \ else self._car_wait_a(st) + w.cut_on, w.cut_blind = st["cap"] is not None, True return + w.cut_blind = False + w.cut_quarter(key) # EV-54: the quarter's refused cut tries ex = peakguard.excess_w(real_proj, target_w) left = QUARTER_S - float(real_proj.elapsed_s) r = self.car.reading @@ -355,10 +358,11 @@ class CarMixin: st = self._cut = self._cut_fresh(key) st["cuts"] = cuts w.cut_a = st["cap"] + w.cut_on = st["cap"] is not None return if not due: st["since"], st["wait"] = None, None # the batteries caught it - w.cut_a = None + w.cut_a, w.cut_on = None, False return if st["since"] is None: st["since"], st["car0"], st["ex"] = mono, car_w, ex @@ -373,13 +377,18 @@ class CarMixin: st["cap"] = 0.0 if a is None else a st["cuts"] += 1 st["wait"], st["at"] = None, mono - w.cut_a = st["cap"] + w.cut_a, w.cut_on = st["cap"], True return # C4: due and waiting: no raise meanwhile. PM R1: held in watts (the # plan's current on its phases), turned into amps with the phases at - # the write. + # the write. EV-54 (G1): a refused cut value is dropped in the wait, + # so the hold is the read-back the writer takes, not that value. + w.cut_on = False p = w.plan - now_w = float(p.a) * carmode.VOLTS * (p.n if p.n in (1, 3) else n) + a_now = float(p.a) + if w.drop_ready(cur, self.car.stuck(mono)): + a_now = float(cur) + now_w = a_now * carmode.VOLTS * (p.n if p.n in (1, 3) else n) st["wait"] = now_w if st["wait"] is None else min(st["wait"], now_w) w.cut_a = self._car_wait_a(st) diff --git a/goodwe_controller/app/ctl_status.py b/goodwe_controller/app/ctl_status.py index f8a7986..2c071ee 100644 --- a/goodwe_controller/app/ctl_status.py +++ b/goodwe_controller/app/ctl_status.py @@ -211,7 +211,7 @@ class StatusMixin: if sw.other and self.car_mode == "solar": out.append({"ok": False, "warn": True, "id": "charger_other", "text": messages.row_charger_other_solar()}) - if sw.gave_up: + if sw.gave_up or getattr(sw, "cut_refused", False): # EV-54 out.append({"ok": False, "warn": True, "id": "charger_refused", "text": messages.row_charger_refused()}) if sw.phases_gave_up and self.car_mode == "solar": diff --git a/goodwe_controller/app/homeview.py b/goodwe_controller/app/homeview.py index 642ca6d..617e359 100644 --- a/goodwe_controller/app/homeview.py +++ b/goodwe_controller/app/homeview.py @@ -1386,11 +1386,12 @@ def _car_solar_why(c, key): return _t("car.why.solar_peak") if w.hold: return _t("car.why.solar_other") + refused = w.gave_up or getattr(w, "cut_refused", False) # EV-54 if w.zero_owed: # The way-out 0 A is not taken yet: never "paused". - return _t("car.why.solar_zero_failed" if w.gave_up + return _t("car.why.solar_zero_failed" if refused else "car.why.solar_zeroing") - if w.gave_up: + if refused: return _t("car.why.solar_refused") if c.shadow: a, n = w.would if w.would is not None else (0.0, p.n) diff --git a/goodwe_controller/test_ev52.py b/goodwe_controller/test_ev52.py index f023cae..3f4669e 100644 --- a/goodwe_controller/test_ev52.py +++ b/goodwe_controller/test_ev52.py @@ -823,11 +823,14 @@ check(f"N5: no mode line without a change: {len(modes(r4))} in r4 (start + " and len(modes(r30)) == 2) # N8: the existing warning and info texts are the base's, word for word. +# EV-54 (Q3) adds the refused peak cut's own text; the others are unchanged. EXACT = { "The charger did not take the current, so the add-on stops asking until " "you change it: CHARGER_REFUSED.", "The charger did not take the current, so the add-on stops asking until " "you press Solar: CHARGER_REFUSED.", + "The charger did not take the peak cut, so the add-on tries again next " + "quarter: CHARGER_REFUSED.", "The charger did not take the current, so the add-on tries again in 15 " "min, then every 30 min: CHARGER_REFUSED.", "The charger did not take 0 A before the add-on stopped, so the car may " @@ -839,7 +842,7 @@ EXACT = { seen8 = {m for r in ALL for _t, lv, m in r["lines"] if lv != "DEBUG" and ("CHARGER_" in m or "CAR_CUT" in m or "kept drawing" in m)} check(f"N8: every CHARGER_* / CAR_CUT / kept-drawing line seen in any run is " - f"one of base's texts, and each of the seven was seen " + f"one of base's texts or EV-54's, and each of the eight was seen " f"({sorted(seen8 - EXACT)[:2]}, missing {sorted(EXACT - seen8)[:2]})", seen8 == EXACT) diff --git a/goodwe_controller/test_ev54.py b/goodwe_controller/test_ev54.py new file mode 100644 index 0000000..ef72563 --- /dev/null +++ b/goodwe_controller/test_ev54.py @@ -0,0 +1,577 @@ +"""EV-54: after the quarter's refused cut tries, Solar's normal control goes +on, and the cut is tried again at the next quarter start while one is needed. +`python3 -B test_ev54.py` + +Rows T1-T13 and T15-T23 of reports/EV-54-test-plan.md (T14 and T25-T35, the +drop rule, are in test_ev54_drop.py; T24 is the run of the existing files). +The real Controller on `tools/ev20_sun.py` through `tools/ev54_kit.py`; +Shape C is N=2, both batteries at 10 %, the car at 10 A on 3 phases, the +house 3000 W and the sun 0 from 960; the second period runs 900-1800. +"Refusal" is the charger ignoring a write ("ignore") or Home Assistant +refusing it ("error"). Golden values marked bdfd3e6 were taken on that tree +with `EV54_GOLDEN=1 python3 -B test_ev54.py`. + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import carmode, messages # noqa: E402 +from ev20_kit import LOG, check, fails, act, step_fn, const # noqa: E402 +from ev21_kit import (ALARMS, digest, merge, shape, view_guard, # noqa: E402 + view_writes, refuse_n1, set_resp) +from ev54_kit import (HOLD_TEXT, Q3_TEXT, W54, as_off, cut_writes, # noqa: E402 + house_c, key_change, never54, refused_by_key, row, + rows, run, sun_c, t_lift, twin, window, writes, + dropped, first, nth, present) + +n_log0 = LOG.mark() +TAKE = os.environ.get("EV54_GOLDEN") == "1" +CUT = messages.ID_CAR_CUT +GOLDEN = { + 'T10 [C]': ('938225cc1dd6d8f8', 'ba8e36dfa3011013'), + 'T10 [W]': ('dfb6d075dd1f2330', 'eec4c29653ce1e3e'), + 'T10 [M]': ('385ae1fbf07b25d6', 'a52b1c929747cd07'), + 'T11 [Manual]': ([(1601.0, 8.0), (1671.0, 8.0), (1741.0, 8.0)], + ['WARNING']), + 'T11 [Off]': [(1080.0, 0.0, False)], +} +got = {} + + +def golden(name, value): + got[name] = value + if TAKE: + print(f"GOLDEN {name!r}: {value!r},") + return GOLDEN.get(name) + + +def refused(r, t0=0, t1=1e9): + """(t, a) of the refused cut tries in [t0, t1).""" + return [(t, a) for t, a, ok, _why, _k in cut_writes(r, t0, t1) if not ok] + + +def gaps(ts): + return [b - a for a, b in zip(ts, ts[1:])] + + +def near(t, want, lo, hi): + return t is not None and want - lo <= t <= want + hi + + +def amber(r, t0, t1, rid="charger_refused"): + return [x["t"] for x in r["trace"] if t0 <= x["t"] < t1 + and rid in (x.get("amber") or [])] + + +def gave_up_at(r, t0=0, t1=1e9): + return [x["t"] for x in rows(r, t0, t1) if x["gave_up"]] + + +def roll_try(name, r, kc, n, *, value=0.0, taken_by=None, hold_s=0.0, + graded=True): + """T4's bound: the new key's first try in its first cycle (at N=2 up to + max_hold_s before :00), then (if `taken_by`) the next try 60 s or more + later is taken, read back within 2 s, and (`graded`, T4's own row) + graded can-cut from that cycle (+1 s) with the CAR_CUT note once.""" + w2 = [(t, a, ok) for t, a, ok, _w, _k in cut_writes(r, 1800 - hold_s - 1)] + t1 = nth(w2, 0) + lo = 1800 - (hold_s if n == 2 else 0) - 1 + ok1 = present(t1) and lo <= t1[0] <= 1801 and abs(t1[1] - value) < 0.01 \ + and present(kc) and abs(t1[0] - kc) <= 1 + if taken_by is None: + check(f"{name}: the new key ({kc}) is tried in its first cycle " + f"({t1}, bound [{lo}, 1801]), as {value} A", ok1) + return + t2 = nth(w2, 1) + ok2 = present(t1, t2) and t2[2] and not t1[2] \ + and t2[0] - t1[0] >= carmode.RETRY_S and t2[0] <= taken_by + 61 + rb = [x["t"] for x in rows(r, t2[0] if present(t2) else 1e9) + if abs(x["rb"] - value) < 0.01] + can = [x["t"] for x in rows(r, t2[0] if present(t2) else 1e9) + if x["can"]] + cuts = [t for t, n_ in r["raised"] if n_ == CUT and t >= 1790] + check(f"{name}: the new key ({kc}) tried in its first cycle ({t1}, bound " + f"[{lo}, 1801]) and refused; the next try {t2} 60 s or more later " + f"is taken, read back by {first(rb)}, can-cut from {first(can)}; " + f"CAR_CUT once ({cuts})", + ok1 and ok2 and bool(rb) and rb[0] <= t2[0] + 2 + and (not graded or (bool(can) and can[0] <= rb[0] + 1 + and len(cuts) == 1))) + + +# =========================================================================== # +print("\n1. SOLAR GOES ON AFTER THE QUARTER'S TRIES (T1, T2, T3)") +# =========================================================================== # +T1R = {} +for kind in ("ignore", "error"): + r = run(house_c((1250, 900.0)), sun_c((1250, 9000.0)), dur=1800, + events=window({}, 959, 1100, kind)) + T1R[kind] = r + tr = refused(r, 900, 1800) + ts = [t for t, _a in tr] + tl = t_lift(r, 1100, 1800) + nz = [(t, a, why) for t, a, ok, why in writes(r, (tl or 1e9) + 1, + (tl or 1e9) + 131) + if a > 0.0 and ok] + check(f"T1 [{kind}]: tries {tr}: 0 A at 960+-1, 1020+-2, 1080+-2, no " + f"4th in 900-1800", + len(tr) == 3 and all(a == 0.0 for _t, a in tr) + and near(nth(ts, 0), 960, 1, 1) and near(nth(ts, 1), 1020, 2, 2) + and near(nth(ts, 2), 1080, 2, 2)) + check(f"T1 [{kind}]: the cap lifts at {tl} (1370+-2); the drop then: " + f"sent_a 10, taken, plan 10 ({dropped(r, tl or 0, 10.0)}); a " + f"non-zero Solar write within 130 s ({nz[:2]}); gave_up never " + f"({gave_up_at(r, 900, 1800)[:2]})", + near(tl, 1370, 2, 2) and dropped(r, tl or 0, 10.0) is not None + and bool(nz) and 6.0 <= nz[0][1] <= 16.0 and nz[0][2] == "Solar" + and not gave_up_at(r, 900, 1800)) + never54(f"T1 [{kind}]", r) + +ev2 = window({}, 959, None) +T2 = run(house_c(), sun_c(), dur=1800, events=ev2) +tr = refused(T2, 900, 1800) +ts = [t for t, _a in tr] +nz2 = [(t, a) for t, a, _ok, _why in writes(T2, 900, 1800) if a > 0.0] +caps = sorted({x["cap"] for x in rows(T2, 961, 1800)}, key=str) +check(f"T2: a cut needed all quarter: exactly 3 tries ({tr}), all 0 A, gaps " + f"{gaps(ts)} >= 60; no non-zero Solar write ({nz2[:2]}); the cap stays " + f"0 ({caps})", + len(tr) == 3 and all(a == 0.0 for _t, a in tr) + and all(g >= 60 for g in gaps(ts)) and not nz2 and caps == [0.0]) +never54("T2", T2) + +# T1 continued, in the next period: in 900-1800 the import of 960-1250 keeps +# the projection near the aim, so a sun drop there makes a new cut due, and +# with the quarter's tries used up none goes out (Q1). From 1800 the period +# is fresh: the sun falls to 7 A worth at 1900, under 6 A worth at 2000. +r = run(house_c((1250, 900.0)), + sun_c((1250, 9000.0), (1900, 5900.0), (2000, 4400.0)), dur=2350, + events=window({}, 959, 1100)) +w3 = [(t, a, ok, why) for t, a, ok, why in writes(r, 1081, 2350)] +down = [x for x in w3 if 1900 <= x[0] <= 1932] +hold6 = [x for x in w3 if 2000 <= x[0] <= 2032 and x[1] == 6.0] +pause = [x for x in w3 if 2298 <= x[0] <= 2302 and x[1] == 0.0] +prev = [x for x in w3 if x[0] < 1900] +caps3 = [x["t"] for x in rows(r, 1800, 2350) if x["cap"] is not None] +check(f"T3: after the drop Solar follows the spare: a step-down by 1932 " + f"({down}), the 6 A hold by 2032 ({hold6}), the pause 0 A 'Solar' at " + f"2300+-2 ({pause}); all taken ({[x for x in w3 if not x[2]]}); no cut " + f"in that period ({caps3[:2]})", + bool(down) and bool(prev) and down[0][1] < prev[-1][1] and bool(hold6) + and bool(pause) and pause[0][3] == "Solar" + and all(x[2] for x in w3) and not caps3) +never54("T3", r) + +# =========================================================================== # +print("\n2. THE NEXT QUARTER TRIES AGAIN (T4, T5, T6)") +# =========================================================================== # +T4R = {} +for n in (2, 1): + for kind in ("ignore", "error"): + r = run(house_c(), sun_c(), dur=1950, n=n, + events=window({}, 959, 1830, kind)) + T4R[(n, kind)] = r + hold_s = r["c"].p1.averager.max_hold_s + rbk = refused_by_key(r) + kc = key_change(r, 1700, 1900) + k900 = [v for k, v in rbk.items() if k == row(r, 1000)["key"]] \ + if present(row(r, 1000)) else [] + check(f"T4 [N={n}, {kind}]: 3 refused tries in 900-1800 ({k900})", + bool(k900) and len(k900[0]) == 3) + roll_try(f"T4 [N={n}, {kind}]", r, kc, n, taken_by=1830, + hold_s=hold_s) + never54(f"T4 [N={n}, {kind}]", r) + +T5R = {} +for tag, socs in (("both at 10 %", None), ("a 10 %, b 60 %", + {"a": 10.0, "b": 60.0})): + r = run(house_c(), sun_c(), dur=3600, socs=socs, + events=window({}, 959, None)) + T5R[tag] = r + rbk = refused_by_key(r, 900, 3600) + per = sorted(len(v) for v in rbk.values()) + allt = sorted(t for v in rbk.values() for t in v) + other = [(t, a) for t, a, ok, _why in writes(r, 900, 3600) + if t not in allt] + vals = sorted({a for t, a, ok, _w in writes(r, 900, 3600)}) + check(f"T5 [{tag}]: refusal never lifted: exactly 3 tries in each of 3 " + f"quarter keys ({ {k: v for k, v in rbk.items()} }), all 0 A " + f"({vals}), gaps {gaps(allt)} >= 60 within and across; no other " + f"write ({other[:3]})", + per == [3, 3, 3] and vals == [0.0] + and all(g >= 60 for g in gaps(allt)) and not other) + never54(f"T5 [{tag}]", r) + +r = run(house_c((1790, 900.0)), sun_c((1790, 9000.0)), dur=2700, + events=window({}, 959, 1900)) +kc = key_change(r, 1700, 1900) +bad = [(t, a, why) for t, a, ok, why in writes(r, 1795, 2700) + if a == 0.0 or why == "peak cut"] +nxt = first(x for x in writes(r, (kc or 1e9) + 1, 2700)) +check(f"T6: the new quarter starts under the aim: no 0 A and no 'peak cut' " + f"write from 1795 ({bad[:3]}); the drop at the key change {kc} " + f"(1800+-2): {dropped(r, kc or 0, 10.0)}; the next write a normal one " + f"({nxt})", + not bad and near(kc, 1800, 2 + r["c"].p1.averager.max_hold_s, 2) + and dropped(r, kc or 0, 10.0) is not None + and (nxt is None or not present(nxt) or nxt[3] == "Solar")) +never54("T6", r) + +# =========================================================================== # +print("\n3. AS OFF WHILE THE CUT IS REFUSED (T7)") +# =========================================================================== # +for name, r, win in ( + ("T1 [ignore]", T1R["ignore"], (961, 1360)), + ("T2", T2, (961, 1800)), + ("T4 [N=2, ignore]", T4R[(2, "ignore")], (961, 1855)), + ("T5 [both at 10 %]", T5R["both at 10 %"], (961, 3600))): + as_off(f"T7 {name}", r, twin(r), ALARMS, refused=win) +evw = merge(window({}, 959, 1830), 900, set_resp(20.0)) +r = run(house_c(), sun_c(), dur=1900, socs={"a": 60.0, "b": 60.0}, + events=evw) +as_off("T7 [Shape W, refusal 959-1830]", r, twin(r, {900: set_resp(20.0)}), + ALARMS, refused=(961, 1800)) +never54("T7 [Shape W]", r) + +# =========================================================================== # +print("\n4. THE NOTICE (T8) AND SOLAR'S OWN REFUSED WRITE (T9)") +# =========================================================================== # +for name, r, t1 in (("T2", T2, 1800), ("T5", T5R["both at 10 %"], 3600)): + ts = [t for t, _a in refused(r, 900, 1800)] + q3 = r["w"].lines(Q3_TEXT) + q3w = [(t, lv) for t, lv, _m in q3 if lv == "WARNING"] + old = [t for t, _lv, _m in r["w"].lines("until you press Solar")] + amb = amber(r, (nth(ts, 2) if present(nth(ts, 2)) else 1e9) + 1, 1800) + want_amb = list(range(int(nth(ts, 2)) + 1, 1800)) \ + if present(nth(ts, 2)) else [None] + check(f"T8 [{name} run]: at the 3rd refused try ({nth(ts, 2)}) one WARNING " + f"'{Q3_TEXT}' ({q3w}) over the run (DEBUG after: " + f"{[(t, lv) for t, lv, _m in q3 if lv != 'WARNING'][:3]}); no " + f"'until you press Solar' ({old[:2]}); the amber row from the 3rd " + f"try to 1800 ({len(amb)} of {len(want_amb)} s); gave_up never " + f"({gave_up_at(r)[:2]})", + len(q3w) == 1 and present(nth(ts, 2)) + and abs(q3w[0][0] - nth(ts, 2)) <= 1 and not old + and [float(t) for t in want_amb] == amb and not gave_up_at(r)) + +r = run(const(900.0), step_fn((1000, 6700.0), base=7900.0), dur=1900, + events=window({}, 999, None)) +w9 = writes(r, 999, 1900) +hold = [(t, lv) for t, lv, _m in r["w"].lines(HOLD_TEXT)] +third = nth(w9, 2) +amb = amber(r, (third[0] if present(third) else 1e9) + 1, 1900) +check(f"T9: Solar's own step-down refused 3 times ({w9[:5]}): the existing " + f"'{HOLD_TEXT}' once ({hold}), the amber row after it ({len(amb)} s), " + f"no write after the 3rd, also across 1800 ({w9[3:5]})", + len(w9) == 3 and all(not ok for _t, _a, ok, _w in w9) + and len({a for _t, a, _o, _w in w9}) == 1 and len(hold) == 1 + and hold[0][1] == "WARNING" and len(amb) >= 1800 - third[0] - 2) +never54("T9", r) + +# =========================================================================== # +print("\n5. A CHARGER THAT TAKES THE CUT; MANUAL AND OFF (T10, T11)") +# =========================================================================== # +for kind in ("C", "W", "S", "F", "M"): + rec = W54() + r = shape(kind, dur=1300, on_cycle=rec) + r["w"] = rec + cw = cut_writes(r, 950) + vals = [a for _t, a, _ok, _w, _k in cw] + check(f"T10 [{kind}]: the charger takes the cut: one write per value, " + f"each taken, no retry ({[(t, a, ok) for t, a, ok, _w, _k in cw]})", + all(ok for _t, _a, ok, _w, _k in cw) + and len(vals) == len(set(vals))) + if kind in ("C", "W", "M"): + d = (digest(view_writes(r)), digest(view_guard(r))) + want = golden(f"T10 [{kind}]", d) + check(f"T10 [{kind}]: view_writes and view_guard as bdfd3e6 " + f"({d} vs {want})", d == want) + +import opt11_identity as rig # noqa: E402 +st = rig._Store() +st.data["car_current"], st.data["car_phases"] = 10.0, 3 +evm = window({1600: act("car_current", 8)}, 1599, None) +r = run(house_c(), sun_c(), dur=1900, mode="manual", store=st, events=evm) +wm = [(x[0], x[2]) for x in r["sim"].log if x[1] == "current" + and x[0] >= 1590] +mt = [lv for _t, lv, _m in r["w"].lines( + "stops asking until you change it: CHARGER_REFUSED.")] +d = (wm, mt) +want = golden("T11 [Manual]", d) +check(f"T11 [Manual]: a change refused 3 times ({wm}), then the roll at " + f"1800: no 4th; the Manual text once ({mt}); as bdfd3e6 ({want})", + len(wm) == 3 and mt == ["WARNING"] and d == want) + +evo = window({1030: act("car_mode", "off")}, 959, None) +r = run(house_c(), sun_c(), dur=1300, events=evo) +wo = [(t, a, ok) for t, a, ok, _w in writes(r, 1025)] +want = golden("T11 [Off]", wo) +check(f"T11 [Off]: Solar left to Off during a refused cut: Off's way-out " + f"0 A writes {wo} as bdfd3e6's ({want})", wo == want and bool(wo)) + +# =========================================================================== # +print("\n6. AN UNTRUSTED CAR (T12), A SILENT METER (T13)") +# =========================================================================== # + + +def no_energy(p, c): + p.ch.no_energy = True + + +ev12 = window({950: no_energy}, 959, 1830) +r = run(house_c(h=9000.0), sun_c(), dur=1950, events=ev12) +tr = refused(r, 900, 1795) +check(f"T12: an untrusted car figure: the cut is 0 A, 3 tries in 900-1800 " + f"({tr})", len(tr) == 3 and all(a == 0.0 for _t, a in tr)) +roll_try("T12", r, key_change(r, 1700, 1900), 2, taken_by=1830, + hold_s=r["c"].p1.averager.max_hold_s, graded=False) +o = twin(r, {950: no_energy}) +a_r = first(t for t, n in r["raised"] if n in ALARMS and t >= 900) +a_o = first(t for t, n in o["raised"] if n in ALARMS and t >= 900) +check(f"T12: the alarm at the Off twin's second +2 ({a_r} vs {a_o})", + present(a_r, a_o) and a_r is not None and a_o is not None + and abs(a_r - a_o) <= 2) +never54("T12", r) + + +def silent(on): + def f(p, c): + p.meter_on = not on + return f + + +seen13 = [] + + +def fresh13(p, c): + """Before the cycle (a refused write's read-back wait moves the model + clock inside it): is the meter fresh for the cut (N9)?""" + seen13.append((p.t, c._car_cut_meter_fresh())) + + +ev13 = window({1780: silent(True), 1900: silent(False)}, 959, None) +for t in range(1781, 1900): + ev13 = merge(ev13, t, fresh13) +r = run(house_c(), sun_c(), dur=2000, events=ev13) +# The bound is EV-21's N9 (`_car_cut_meter_fresh`): stale_input_s, or +# meter_max_age_s on `ha_signed` (the harness's meter source). +stale_t = first(t for t, ok in seen13 if not ok) +dark = [(t, a) for t, a, _ok, _w in writes(r, stale_t or 1e9, 1900)] +nxt = first((t, a) for t, a, _ok, _w in writes(r, 1900)) +k2 = [len(v) for k, v in refused_by_key(r, 1795).items()] +check(f"T13: the meter silent 1780-1900, stale for the cut (N9) from " + f"{stale_t}: no try while stale ({dark}); the first try at {nxt} " + f"(within [1900, 1902]); at most 3 in the new key ({k2})", + present(stale_t) and stale_t is not None and stale_t < 1860 + and not dark and present(nxt) and nxt is not None + and 1900 <= nxt[0] <= 1902 and all(k <= 3 for k in k2)) +never54("T13", r) + +# =========================================================================== # +print("\n7. A RAISING WRITE (T15), A RESTART (T16), THE KEY (T17)") +# =========================================================================== # +calls15 = [] + + +def boom(p, c): + drv = c.charger + drv._ev54_wc = drv.write_current + + async def wc(a, **kw): + calls15.append((p.t, a)) + raise RuntimeError("EV-54 T15: the write raised") + drv.write_current = wc + + +def unboom(p, c): + c.charger.write_current = c.charger._ev54_wc + + +m15 = LOG.mark() +r = run(house_c(), sun_c(), dur=1950, events={959: boom, 1830: unboom}) +c1 = [t for t, _a in calls15 if t < 1795] +c2 = [t for t, _a in calls15 if t >= 1795] +step_w = [m for m in LOG.since(m15, "ERROR") + LOG.since(m15, "WARNING") + if "charger step failed" in m] +tb15 = LOG.tracebacks(m15) +kc = key_change(r, 1700, 1900) +taken2 = [(t, a) for t, a, ok, _w in writes(r, 1830) if ok and a == 0.0] +check(f"T15: a write that raises counts as a refused try: {c1} in 900-1800 " + f"(3, >= 60 s apart), never once per cycle; the new key's try at " + f"{c2[:1]} (key {kc}), the next taken {taken2[:1]}; step-failed " + f"warnings {len(step_w)} (<= 1), Tracebacks {len(tb15)}", + len(c1) == 3 and all(g >= 60 for g in gaps(c1)) and bool(c2) + and present(kc) and kc is not None and abs(c2[0] - kc) <= 1 + and bool(taken2) and taken2[0][0] - c2[0] >= 60 + and len(step_w) <= 1 and not tb15) + +r1 = run(house_c(), sun_c(), dur=1050, events=window({}, 959, None)) +r2 = run(house_c(), sun_c(), t0=1050.0, dur=850, sim=r1["sim"], + store=r1["store"], plug=False, events={1830: lambda p, c: + setattr(p.ch, "refuse", + None)}) +w16 = [(t, a, ok, why) for t, a, ok, why in writes(r2, 1050, 1795)] +ts = [t for t, _a, _ok, _w in w16] +keys = [k for k in r1["store"].data if "cut" in str(k).lower() + or "tries" in str(k).lower()] +check(f"T16: 2 refused tries, then a restart at 1050: D2's 0 A at 1050+-1 " + f"'start-up' ({w16[:1]}); its retries >= 60 s apart ({gaps(ts)}), at " + f"most 3 in 1050-1800 ({len(w16)}); no store key holds a count " + f"({keys})", + bool(w16) and near(w16[0][0], 1050, 1, 1) and w16[0][1] == 0.0 + and w16[0][3] == "start-up" and all(g >= 60 for g in gaps(ts)) + and len(w16) <= 3 and all(a == 0.0 for _t, a, _o, _w in w16) + and not keys) +roll_try("T16", r2, key_change(r2, 1700, 1900), 2, taken_by=1830, + hold_s=r2["c"].p1.averager.max_hold_s) +never54("T16", r2) + + +def none_proj(p, c): + orig = c._car_cut_tick + + def tick(proj, guard, target, mono): + if 1801 <= p.t <= 1803: + proj = None + return orig(proj, guard, target, mono) + c._car_cut_tick = tick + + +r = run(house_c(), sun_c(), dur=2700, events=window({1795: none_proj}, + 959, None)) +rbk = refused_by_key(r, 1700, 2700) +keyed = {k: v for k, v in rbk.items() if k is not None} +check(f"T17 (a): the early roll, then no projection 1801-1803, then fresh: " + f"the count reset once ({keyed}: exactly 3 in the new key, the first " + f"at the roll)", + len(keyed) == 1 and [len(v) for v in keyed.values()] == [3]) +never54("T17 (a)", r) + + +def jump(dt): + def f(p, c): + p.utc_off = dt + return f + + +r = run(house_c(), sun_c(), dur=2000, events=window({1790: jump(-3600.0)}, + 959, None)) +allt = sorted(t for t, _a, ok, _w in writes(r, 900) if not ok) +check(f"T17 (b): the wall clock jumps -3600 s at 1790: tries {allt} stay " + f">= 60 s apart on the monotonic clock", + bool(allt) and all(g >= 60 for g in gaps(allt))) +never54("T17 (b)", r) + +# =========================================================================== # +print("\n8. A PHASE CHANGE (T18), A LATE TAKE (T19), COVER OFF (T20)") +# =========================================================================== # +kw18 = dict(n=2, opts={"ev_phases": "auto"}, phases=1) +r0 = run(const(900.0), const(9280.0), dur=700, **kw18) +log0 = r0["c"].car_solar.log +sel = [t for k, _a, t, _ok in log0 if k == "phases"] +zb = [t for k, a, t, _ok in log0 if k == "current" and a == 0.0 + and sel and t <= sel[0]] +tb = int(nth(zb, -1)) if present(nth(zb, -1)) else 400 +q1 = (tb // 900 + 1) * 900 +ev18 = window({}, tb - 1, None) +r = run(step_fn((tb + 1, 9280.0 + 3400.0 + 2000.0), base=900.0), + const(9280.0), dur=q1 + 100, events=ev18, **kw18) +ph = [(t, n, ok) for k, n, t, ok in r["c"].car_solar.log + if k == "phases" and t >= tb - 1] +nz = [(t, a) for t, a, _ok, _w in writes(r, tb - 1) if a > 0.0] +cw = [(t, a, ok) for t, a, ok, _w, k in cut_writes(r, tb - 1, q1)] +sw = [x["t"] for x in rows(r, tb + 5, q1) if x["switch"]] +nq = first((t, a) for t, a, _ok, _w, _k in cut_writes(r, q1 - 15)) +check(f"T18: Solar's own change sent its 0 A at {tb}, the cut due from " + f"{tb + 1}, the charger refusing: no select ({ph}), no closing current " + f"({nz[:2]}); at most 3 cut tries in the quarter ({cw}); the plan's " + f"switch ended ({sw[:2]}); the next quarter's try {nq} is 0 A", + bool(zb) and not ph and not nz and 1 <= len(cw) <= 3 and not sw + and present(nq) and nq is not None and nq[1] == 0.0) +never54("T18", r) + + +def late_take(p, c): + p.ch.refuse = None + p.ch.set_current(0) + + +r = run(house_c(), sun_c(), dur=1300, events=window({1110: late_take}, + 959, None)) +set_l = [(t, m) for t, _lv, m in r["w"].lines("Car: set") if t >= 900] +after3 = [(t, a) for t, a, _ok, _w in writes(r, 1081)] +can = [x["t"] for x in rows(r, 1110) if x["can"]] +cuts = [t for t, n in r["raised"] if n == CUT] +new_ref = [t for t, _lv, _m in r["w"].lines("CHARGER_REFUSED") if t >= 1100] +check(f"T19: the charger shows 0 A at 1110 after the 3rd try: one 'Car: set " + f"from 10 A to 0 A (peak cut).' at 1110+-1 ({set_l}); no further try " + f"({after3}); can-cut from {can[:1]}; CAR_CUT once ({cuts}); no new " + f"CHARGER_REFUSED ({new_ref})", + len(set_l) == 1 and near(set_l[0][0], 1110, 1, 1) + and set_l[0][1] == "Car: set from 10 A to 0 A on 3 phases (peak cut)." + and not after3 and bool(can) and can[0] <= 1111 and len(cuts) == 1 + and not new_ref) + +r = run(house_c(), sun_c(), dur=1950, opts={"ev_batt_cover": False}, + events=window({}, 959, 1830)) +tr = refused(r, 900, 1795) +check(f"T20: the cover off: the cut at once at 960+-1 and 3 tries in " + f"900-1800 ({tr})", len(tr) == 3 and near(tr[0][0], 960, 1, 1)) +roll_try("T20", r, key_change(r, 1700, 1900), 2, taken_by=1830, + hold_s=r["c"].p1.averager.max_hold_s, graded=False) +never54("T20", r) + +# =========================================================================== # +print("\n9. TWO EPISODES (T21), A 50 W CAR (T22), A PRESS (T23)") +# =========================================================================== # +r = run(house_c(), sun_c((961, 9000.0), (1400, 0.0)), dur=1700, + opts={"ev_start_min": 1}, events=window({}, 959, 1800)) +tr = refused(r, 900, 1800) +ts = [t for t, _a in tr] +tl = t_lift(r, 961, 1300) +check(f"T21: episode 1 (lifted at {tl}) and episode 2 from 1400 share the " + f"quarter's 3 refused tries ({tr}): 960, 1020, then 1400+-1; none " + f"after", len(tr) == 3 and near(nth(ts, 2), 1400, 0, 1) + and present(tl) and tl is not None and nth(ts, 1) < tl) +never54("T21", r) + + +def car50(p, c): + p.ch.target_w = lambda: 50.0 + + +ev22 = window({900: car50}, 959, None) +r = run(house_c(h=9000.0), sun_c(), dur=1800, events=ev22) +o = twin(r, {900: car50}) +a_r = first(t for t, n in r["raised"] if n in ALARMS and t >= 900) +a_o = first(t for t, n in o["raised"] if n in ALARMS and t >= 900) +tr = refused(r, 900, 1800) +check(f"T22: a 50 W car on 10 A: the house alarm at the Off twin's second " + f"({a_r} vs {a_o}); tries {tr} (<= 3)", + present(a_r, a_o) and a_r is not None and a_o is not None + and abs(a_r - a_o) <= 2 and len(tr) <= 3) +never54("T22", r) + +for tag, ev in (("Solar pressed at 1100", {1100: act("car_mode", "solar")}), + ("Off at 1100, Solar at 1200", + {1100: act("car_mode", "off"), + 1200: act("car_mode", "solar")})): + r = run(house_c(), sun_c(), dur=1950, events=window(ev, 959, 1830)) + tr = refused(r, 900, 1795) + check(f"T23 [{tag}]: no 4th cut try in 900-1800 ({tr})", len(tr) == 3) + roll_try(f"T23 [{tag}]", r, key_change(r, 1700, 1900), 2, + taken_by=1830, hold_s=r["c"].p1.averager.max_hold_s) + never54(f"T23 [{tag}]", r) + +tb_all = LOG.tracebacks(n_log0) +check(f"N13: no traceback in this file's runs ({tb_all[:1]})", not tb_all) +if TAKE: + print("(golden taken; no checks graded)") + sys.exit(0) +print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}") +sys.exit(1 if fails else 0) diff --git a/goodwe_controller/test_ev54_drop.py b/goodwe_controller/test_ev54_drop.py new file mode 100644 index 0000000..888e293 --- /dev/null +++ b/goodwe_controller/test_ev54_drop.py @@ -0,0 +1,702 @@ +"""EV-54: the drop rule. A cut value the charger did not take is never sent +again once no cut stands: Solar takes the read-back as its own (sent, taken, +the plan's current), and the next cut try is a new episode's. +`python3 -B test_ev54_drop.py` + +Rows T14 and T25-T35 of reports/EV-54-test-plan.md (G1-G6, QA, QB, QC) and +the writer-level replay of the formal check's C4. The real Controller on +`tools/ev20_sun.py` through `tools/ev54_kit.py`; Shape C as in test_ev54.py. +Golden values marked bdfd3e6 were taken on that tree with +`EV54_GOLDEN=1 python3 -B test_ev54_drop.py`. + +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import asyncio +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +import ev20_sun as S # noqa: E402 +from app import carmode, messages # noqa: E402 +from ev20_kit import LOG, check, fails, act, step_fn # noqa: E402 +from ev21_kit import ALARMS, NoGive, refuse_n1, merge, set_resp # noqa: E402 +from ev54_kit import (HOLD_TEXT, as_off, cut_writes, dropped, first, # noqa: E402 + house_c, key_change, never54, nth, present, + refused_by_key, row, rows, run, sun_c, t_lift, twin, + window, writes) + +n_log0 = LOG.mark() +TAKE = os.environ.get("EV54_GOLDEN") == "1" +CUT = messages.ID_CAR_CUT +GOLDEN = { + 'T35 (b)': [], + 'T35 (c)': ([(1020.0, 0.0, True)], + ['Car: set from 10 A to 0 A on 3 phases (peak cut).']), + 'T38': [], +} + + +def golden(name, value): + if TAKE: + print(f"GOLDEN {name!r}: {value!r},") + return GOLDEN.get(name) + + +def refused(r, t0=0, t1=1e9): + return [(t, a) for t, a, ok, _why, _k in cut_writes(r, t0, t1) if not ok] + + +def near(t, want, lo, hi): + return t is not None and present(t) and want - lo <= t <= want + hi + + +def gave_up_at(r, t0=0, t1=1e9): + return [x["t"] for x in rows(r, t0, t1) if x["gave_up"]] + + +def stick(p, c): + """The charger's reading freezes and the tracker's stuck check is armed + now: a stuck verdict STUCK_S later (chargers.py), as after a write.""" + p.ch.freeze() + c.car.armed_at = float(p.t) + c.car.armed_sig = c.car.sig + + +def unstick(a): + """The reading moves again and shows `a` A; the charger takes writes.""" + def f(p, c): + p.ch.freeze(False) + p.ch.refuse = None + p.ch.set_current(a) + return f + + +def held(t0, t1): + """The charger's read fails t0-t1 (under stale_input_s: held reads).""" + return {t0: lambda p, c: p.ch.go_unavailable(), + t1: lambda p, c: p.ch.go_unavailable(False)} + + +# =========================================================================== # +print("\n1. QA + QC: A STUCK READING AND THE LIFT (T14, T34, T35 (a))") +# =========================================================================== # +# The car's high import is short (960-1010) so the start rule's projection, +# with the start power counted while the car figure is untrusted, lifts the +# cap inside the stuck spell (from 1100). +ev14 = dict(held(1015, 1025)) +ev14.update({1040: stick, 1600: unstick(9)}) +ev14 = window(ev14, 959, None) +r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0), (1600, 4900.0)), + dur=1950, events=ev14) +w14 = writes(r, 900, 1950) +tr = refused(r, 900, 1300) +ts = [t for t, _a in tr] +heldw = [(t, a) for t, a, _ok, _w in writes(r, 1015, 1025)] +tl = t_lift(r, 1100, 1600) +stuck_from = first(x["t"] for x in rows(r, 1040) if x["stuck"]) +check(f"T14: tries {tr}: 0 A at 960, at the first real read after the held " + f"reads 1015-1025, then 60 s on; none while held ({heldw})", + len(tr) == 3 and near(nth(ts, 0), 960, 1, 1) + and near(nth(ts, 1), 1025, 0, 2) and not heldw + and nth(ts, 2) - nth(ts, 1) >= 60 if len(tr) == 3 else False) +pre = [(t, a) for t, a, _ok, _w in writes(r, 1090, tl or 1e9)] +check(f"T14: stuck from {stuck_from}, the cap standing to {tl}: no 0 A from " + f"the stuck path while the tries are used up ({pre})", + present(stuck_from) and tl is not None and stuck_from < tl and not pre) +sw = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, 1600)] +hold = [(t, lv) for t, lv, _m in r["w"].lines(HOLD_TEXT)] +nodrop = [x["t"] for x in rows(r, (tl or 1e9), 1600) + if x["sent"] != 0.0 or x["taken"]] +cf = sorted({x["cut_fails"] for x in rows(r, (tl or 1e9), 1600)}, key=str) +check(f"T14 (QA b, QC 1): after the lift at {tl}, while stuck: the fault " + f"path's 0 A 3 times, 60 s apart, reason Solar, refused ({sw}); not " + f"cut tries (count {cf}); at the 3rd gave_up and the hold path's text " + f"once ({hold}); no drop while stuck ({nodrop[:3]})", + len(sw) == 3 and all(a == 0.0 and not ok and why == "Solar" + for _t, a, ok, why in sw) + and near(sw[0][0], tl or 0, 0, 2) and near(sw[1][0], sw[0][0], -58, 62) + and near(sw[2][0], sw[1][0], -58, 62) and cf == [3] + and len(hold) == 1 and near(hold[0][0], sw[2][0], 1, 1) + and hold[0][1] == "WARNING" and bool(gave_up_at(r, sw[2][0], 1600)) + and not nodrop if len(sw) == 3 else False) +d14 = dropped(r, 1600, 9.0) +gu = [x["t"] for x in rows(r, d14 or 1e9, 1950) if x["gave_up"]] +pause = [(t, a, ok, why) for t, a, ok, why in writes(r, 1890, 1910) + if a == 0.0] +check(f"T14 (QA a): the first good reading 1600 shows 9 A: the drop at " + f"{d14} with sent_a 9 (not the frozen 10), taken, plan 9, gave_up " + f"cleared ({gu[:2]}); Solar resumes: the pause 0 A, Solar, taken, at " + f"1900+-2 ({pause})", + near(d14, 1600, 0, 2) and not gu and len(pause) == 1 + and near(pause[0][0], 1900, 2, 2) and pause[0][2] + and pause[0][3] == "Solar") +never54("T14", r) + +ev34 = window({1040: stick, 2400: unstick(9)}, 959, None) +r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0)), dur=2500, n=2, + events=ev34) +tl = t_lift(r, 1100, 2400) +sw = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, 2400)] +hold = [(t, lv) for t, lv, _m in r["w"].lines(HOLD_TEXT)] +gu = [x["t"] for x in rows(r, (nth(sw, 2)[0] if present(nth(sw, 2)) + else 1e9) + 1, 2400) if not x["gave_up"]] +d34 = dropped(r, 2400, 9.0) +up = [(t, a, why) for t, a, ok, why in writes(r, 2401, 2500) + if a > 10.0 and ok] +check(f"T34 (QC 1): stuck 1040-2400, across the roll: after the lift at " + f"{tl} the stuck 0 A 3 times ({sw}), then gave_up and one hold-path " + f"WARNING ({hold}); nothing to 2400, also at the roll; gave_up stands " + f"({gu[:2]}); the drop at {d34} (2400+-2, the good reading 9 A); a " + f"step-up > 10 A, Solar, in [2430, 2460] ({up[:1]})", + len(sw) == 3 and len(hold) == 1 and not gu and near(d34, 2400, 0, 2) + and bool(up) and 2430 <= up[0][0] <= 2460 and up[0][1] <= 16.0 + and up[0][2] == "Solar" + and not [x for x in rows(r, d34 or 0, 2500) if x["gave_up"]]) +never54("T34", r) + +st35 = {"lift": None, "prev": None} + + +def lift_watch(p, c, t): + """T35 (a): 30 s after the lift the charger takes writes and its reading + follows again (the stuck verdict stands until it moves).""" + cap = (getattr(c, "_cut", None) or {}).get("cap") + if st35["lift"] is None and st35["prev"] is not None and cap is None \ + and t > 1100: + st35["lift"] = t + st35["prev"] = cap + if st35["lift"] is not None and t == st35["lift"] + 29: + p.ch.refuse = None + p.ch.freeze(False) + + +r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0)), dur=1600, + events=window({1040: stick}, 959, None), on_cycle=lift_watch) +tl = st35["lift"] +sw = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, 1600) + if a == 0.0] +lines = [(t, m) for t, _lv, m in r["w"].lines("Car: set") if t >= 900 + and " to 0 A" in m] +pk = [(t, m) for t, _lv, m in r["w"].lines("peak cut") if t >= (tl or 0)] +check(f"T35 (a) (QC 2): the stuck 0 A after the lift at {tl}: refused, then " + f"taken at the 2nd try ({sw}), reason Solar; one 'Car: set from 10 A " + f"to 0 A ... (Solar).' ({lines}); no 'peak cut' line after the lift " + f"({pk})", + len(sw) == 2 and not sw[0][2] and sw[1][2] + and all(why == "Solar" for _t, _a, _o, why in sw) + and [m for _t, m in lines] + == ["Car: set from 10 A to 0 A on 3 phases (Solar)."] and not pk + if len(sw) == 2 else False) +never54("T35 (a)", r) + +# =========================================================================== # +print("\n2. G1: A NEW QUARTER'S CUT WAIT (T25)") +# =========================================================================== # + + +class GiveFrom(S.SunPlant): + """The battery gives nothing until 1800, then what it is asked, slowly + (its 20 s response from 1790): headroom at the new quarter, not used + within its first seconds.""" + + def batt_of(self, u, at): + v = super().batt_of(u, at) + return min(v, 0.0) if at < 1800 else v + + +def free(p, c): + c.batt_refused = 0 + + +for tag, car_sun, s in (("0 A", 5830.0, 0.0), ("6 A", 7900.0, 1900.0)): + a0 = 7.0 if tag == "0 A" else 10.0 + ev = {t: refuse_n1 for t in range(0, 1795)} + for t in range(1795, 1830): + ev = merge(ev, t, free) + ev = window(merge(ev, 1790, set_resp(20.0)), 959, 1810) + r = run(house_c(h=900.0), step_fn((960, s), base=car_sun), dur=1900, + n=1, socs={"a": 60.0}, events=ev, plant_cls=GiveFrom, + rows=False) + tr = refused(r, 900, 1800) + d = dropped(r, 1800, a0) + wait = [x["t"] for x in rows(r, 1800, 1830) if x["wait"] is not None] + inwait = [(t, a) for t, a, _ok, _w in writes(r, 1800, 1830) + if t <= (wait[-1] if wait else 1e9)] + cw = [(t, a, ok, why) for t, a, ok, why, _k in cut_writes(r, 1800, 1830)] + c1 = nth(cw, 0) + rb = [x["t"] for x in rows(r, c1[0] if present(c1) else 1e9) + if present(c1) and abs(x["rb"] - c1[1]) < 0.01] + cuts = [t for t, n in r["raised"] if n == CUT and t >= 1800] + want = 0.0 if tag == "0 A" else 6.0 + check(f"T25 [{tag}] (G1): 3 refused tries in 900-1800 ({tr}); the drop " + f"at {d} (1800+-2: sent_a {a0}, taken, plan {a0}); the wait " + f"{wait[:1]}..{wait[-1:]} with no write in it ({inwait}); then the " + f"cut try {c1} ({want} A, peak cut, taken) after the wait, read " + f"back by {rb[:1]}, CAR_CUT once ({cuts})", + len(tr) == 3 and near(d, 1800, 0, 2) and bool(wait) + and not inwait and present(c1) and c1[0] > wait[-1] + and c1[0] <= 1817 and c1[1] == want and c1[2] + and c1[3] == "peak cut" and bool(rb) and rb[0] <= c1[0] + 2 + and len(cuts) == 1 if wait else False) + never54(f"T25 [{tag}]", r) + +# =========================================================================== # +print("\n3. G2, G3: THE LIFT (T26, T27, T28) AND THE C4 REPLAY") +# =========================================================================== # +r = run(house_c((1250, 900.0)), sun_c((1250, 9000.0)), dur=2700, + events=window({}, 959, 1300)) +tl = t_lift(r, 1100, 1800) +d = dropped(r, tl or 0, 10.0) +paused = [x["t"] for x in rows(r, tl or 1e9, (tl or 1e9) + 30) + if x["plan"] < 6.0 or x["plan_why"] == "paused"] +z = [(t, ok) for t, a, ok, _w in writes(r, 1081, 2700) if a == 0.0] +up = [(t, a, why) for t, a, ok, why in writes(r, (tl or 1e9) + 30, + (tl or 1e9) + 61) if a > 10.0] +nxt = first((t, a, why) for t, a, _ok, why in writes(r, 1081, 2700)) +check(f"T26 (G2): the lift at {tl} (1370+-2): the drop {d} (plan 10, not " + f"paused {paused[:2]}, so '0 A first' does not clear its start count); " + f"no 0 A after the 3rd try ({z[:2]}); then the first write {nxt} is a " + f"step-up > 10 A, Solar, in [t_lift+30, t_lift+60] ({up[:1]})", + near(tl, 1370, 2, 2) and d is not None and not paused and not z + and bool(up) and up[0][1] <= 16.0 and up[0][2] == "Solar" + and present(nxt) and nxt == up[0]) +never54("T26", r) + +for tag, H in (("6 A", 12500.0), ("0 A", 16000.0)): + ev = {t: refuse_n1 for t in range(0, 2701)} + ev = window(ev, 1699, 1900) + # The period sits near the aim (EV-21's near_end): the house steps at + # 1700 for 5 s (100 s left, so the cut is at once), the cut stands; + # it lifts only at the period's end, with tries left. + house = step_fn((900, 3350.0), (1500, 900.0), (1700, H), (1705, 900.0), + base=900.0) + sun = step_fn((900, 0.0), (1500, 7900.0), (1700, 7000.0), base=7900.0) + r = run(house, sun, dur=2700, n=1, socs={"a": 60.0}, events=ev, + plant_cls=NoGive, rows=False) + want = 6.0 if tag == "6 A" else 0.0 + tr = refused(r, 1690, 1800) + d = dropped(r, 1800, 10.0) + bad = [(t, a, why) for t, a, ok, why in writes(r, 1800, 2700) + if abs(a - want) < 0.01 or why == "peak cut"] + nxt = first(x for x in writes(r, 1800, 2700)) + check(f"T27 [{tag}] (G3, tries left): {tr} refused ({want} A) before the " + f"period's end; the drop at {d} (1800+-2); no re-send of {want} A " + f"and no 'peak cut' write in [1800, 2700) ({bad[:3]}); the next " + f"write the plan's ({nxt})", + 1 <= len(tr) <= 2 and all(a == want for _t, a in tr) + and near(d, 1800, 0, 2) and not bad + and (not present(nxt) or nxt[3] == "Solar")) + never54(f"T27 [{tag}]", r) + + +class Drv: + def __init__(self): + self.calls = [] + + async def write_current(self, a, **kw): + self.calls.append(a) + return False + + +class Trk: + obs_at = None + + def begin_write(self): + pass + + def end_write(self, *a): + pass + + def note_write(self, *a, **k): + pass + + def stuck(self, now): + return False + + +async def c4_replay(): + w = carmode.SolarWriter() + w.engaged, w.sent_a, w.taken, w.last_a = True, 10.0, True, 10.0 + drv, trk = Drv(), Trk() + w.cut_a, w.cut_on = 6.0, True + await w._put(drv, 6.0, 10.0, 1000.0, trk) + first_try = list(drv.calls) + w.cut_a, w.cut_on = None, False + await w._put(drv, 6.0, 10.0, 1070.0, trk) + return first_try, drv.calls[len(first_try):], w.sent_why + + +try: + c4 = asyncio.run(c4_replay()) +except Exception as e: # noqa: BLE001 + c4 = (None, ["raised " + repr(e)], None) +check(f"T27 (formal C4 replay): a 6 A cut refused once {c4[0]}; with no " + f"cut 70 s later `_put(6)` sends nothing ({c4[1]})", + c4[0] == [6.0] and c4[1] == []) + +r = run(house_c((1250, 900.0)), sun_c((1250, 7950.0)), dur=2700, + events=window({}, 959, 1900)) +tl = t_lift(r, 1100, 1800) +d = dropped(r, tl or 0, 10.0) +w28 = [(t, a) for t, a, _ok, _w in writes(r, 1081, 2700)] +check(f"T28 (G3, tries used up): the lift at {tl}: the drop {d}; no write " + f"at all in (1080, 2700) ({w28[:3]}), also not at the roll; gave_up " + f"never ({gave_up_at(r, 900)[:2]})", + near(tl, 1370, 2, 2) and d is not None and not w28 + and not gave_up_at(r, 900)) +never54("T28", r) + +# =========================================================================== # +print("\n4. G4, G5, G6: A PARTIAL CUT (T29, T30, T32), A DEEPER CUT (T31)") +# =========================================================================== # +r = run(house_c((1250, 900.0), h=900.0), sun_c((1250, 9000.0), s=1900.0), + dur=1800, events=window({}, 959, 1100)) +tr = refused(r, 900, 1800) +tl = t_lift(r, 1100, 1800) +d = dropped(r, tl or 0, 10.0) +six = [(t, a) for t, a, _ok, _w in writes(r, 1081, 1800) if a == 6.0] +up = [(t, a, why) for t, a, ok, why in writes(r, (tl or 1e9), + (tl or 1e9) + 61) if a > 10.0] +check(f"T29 (G4): 6 A refused 3 times ({tr}), no 4th; the lift at {tl}: the " + f"drop {d} (sent 10, plan 10); no 6 A after 1080 ({six}); a step-up " + f"> 10 A, Solar, within t_lift+60 ({up[:1]})", + [a for _t, a in tr] == [6.0, 6.0, 6.0] and near(tl, 1370, 2, 2) + and d is not None and not six and bool(up) and up[0][1] <= 16.0 + and up[0][2] == "Solar") +never54("T29", r) +as_off("T29", r, twin(r), ALARMS, refused=(961, (tl or 1371) - 1)) +pre = [(t, a) for t, a, _ok, _w in writes(r, 1081, (tl or 1e9) - 2)] +hi = [(x["t"], x["plan"]) for x in rows(r, 1081, tl or 1e9) + if x["plan"] > 6.0] +check(f"T32 (G6): the tries used up, the spare about 16 A from 1250, the cap " + f"to {tl}: no write in (1080, t_lift-2) ({pre}); the plan at most 6 A " + f"until the lift ({hi[:3]})", tl is not None and not pre and not hi) + +for n in (1, 2): + for tag, s2 in (("6 A", 1900.0), ("under 6 A", 1200.0)): + r = run(house_c(h=900.0), sun_c((1800, s2), s=1900.0), dur=1900, + n=n, events=window({}, 959, 1790)) + tr = refused(r, 900, 1795) + hold_s = r["c"].p1.averager.max_hold_s + kc = key_change(r, 1700, 1900) + c2 = first((t, a, ok) for t, a, ok, _w, _k in + cut_writes(r, 1800 - hold_s - 1)) + lo = 1800 - (hold_s if n == 2 else 0) - 1 + x2 = row(r, c2[0]) if present(c2) else None + cap2 = x2["cap"] if present(x2) and x2 is not None else None + rb = [x["t"] for x in rows(r, c2[0] if present(c2) else 1e9) + if present(c2) and abs(x["rb"] - c2[1]) < 0.01] + cuts = [t for t, nn in r["raised"] if nn == CUT and t >= 1790] + # The value is the new quarter's cut, or lower when Solar's own plan + # is lower (here its pause: the spare stayed under 6 A worth). + check(f"T30 [N={n}, {tag}] (G4): 3 refused tries of 6 A ({tr}); the " + f"new key ({kc}) tried in its first cycle ({c2}, bound " + f"[{lo}, 1801]) at or under the new quarter's sized cut " + f"({cap2} A), 0 A or 6 A and more, never 1-5 A, taken, read " + f"back by {rb[:1]}; CAR_CUT once ({cuts})", + [a for _t, a in tr] == [6.0, 6.0, 6.0] and present(c2) + and c2 is not None and lo <= c2[0] <= 1801 + and cap2 is not None and c2[1] <= cap2 + 0.01 + and (c2[1] == 0.0 or c2[1] >= 6.0) and c2[2] and bool(rb) + and rb[0] <= c2[0] + 2 and len(cuts) == 1) + never54(f"T30 [N={n}, {tag}]", r) + if n == 2 and tag == "6 A": + as_off("T30 [N=2, 6 A]", r, twin(r), ALARMS, + refused=(961, 1790)) + +r = run(house_c((1030, 3000.0), h=900.0), sun_c((1030, 0.0), s=1900.0), + dur=1950, events=window({}, 959, 1830)) +tr = refused(r, 900, 1795) +check(f"T31 (G5): 6 A refused at 960 and 1020, the cut deepens at 1030: 0 A " + f"at once, refused, try 3 ({tr}); no 4th refused try in 900-1800; " + f"gave_up never ({gave_up_at(r, 900, 1800)[:2]})", + [a for _t, a in tr] == [6.0, 6.0, 0.0] and near(nth(tr, 2)[0] + if present(nth(tr, 2)) + else None, 1030, 0, 2) + and not gave_up_at(r, 900, 1800)) +hold_s = r["c"].p1.averager.max_hold_s +kc = key_change(r, 1700, 1900) +w2 = [(t, a, ok) for t, a, ok, _w, _k in cut_writes(r, 1800 - hold_s - 1)] +check(f"T31: the new key ({kc}) tried in its first cycle and refused, the " + f"next 60 s or more later taken ({w2[:2]})", + len(w2) >= 2 and not w2[0][2] and w2[1][2] + and w2[1][0] - w2[0][0] >= 60 and present(kc) and kc is not None + and abs(w2[0][0] - kc) <= 1) +never54("T31", r) + +# =========================================================================== # +print("\n5. QB: NO READ-BACK AT THE LIFT (T33)") +# =========================================================================== # + + +def rb_none(on): + """The charger answers, but neither its setpoint nor its read-back is a + number: `allowed_a` and `setpoint_a` are both None.""" + def f(p, c): + ch = p.ch + if on: + orig = ch.states + + def st(): + d = dict(orig()) + for k in list(d): + if k.endswith("_power_connector_max_current_socket_1") \ + or k.endswith("_main_active_max_current_socket_1"): + d[k] = dict(d[k], state="-") + return d + ch._ev54_states = orig + ch.states = st + else: + ch.states = ch._ev54_states + return f + + +seen33 = [] + + +def rd33(p, c, t): + rd = c.car.reading + if rd is not None and 1340 <= t < 1400: + seen33.append((rd.available, rd.allowed_a, rd.setpoint_a)) + + +r = run(house_c((1250, 900.0)), sun_c((1250, 7950.0)), dur=2700, + events=window({1340: rb_none(True), 1400: rb_none(False)}, 959, 1900), + on_cycle=rd33) +tl = t_lift(r, 1100, 1800) +w33 = [(t, a) for t, a, _ok, _w in writes(r, 1081, 2700)] +nod = [x["t"] for x in rows(r, 1340, 1400) if x["sent"] != 0.0 or x["taken"]] +d = dropped(r, 1400, 10.0) +check(f"T33 (QB): the read-back unknown 1340-1400 ({sorted(set(seen33))}), " + f"the lift at {tl} inside it: no write ({w33[:3]}), no drop and " + f"sent_a 0 untaken, not None ({nod[:3]}); the drop at {d} (1400+-2) " + f"with 10 A; then no write to 2700", + sorted(set(seen33)) == [(True, None, None)] and present(tl) + and tl is not None and 1340 < tl < 1400 and not w33 and not nod + and near(d, 1400, 0, 2)) +never54("T33", r) + +# The variant: the charger away 1100-1400, the cap lifted while it is away +# (T14's short import spell, so the start rule's projection lifts it without +# a car figure). +ev = window({1100: lambda p, c: p.ch.go_unavailable(), + 1400: lambda p, c: p.ch.go_unavailable(False)}, 959, 1900) +r = run(house_c((1010, 900.0)), sun_c((1010, 16000.0)), dur=1500, + events=ev) +tl = t_lift(r, 1100, 1400) +away = [(t, a) for t, a, _ok, _w in writes(r, 1100, 1400)] +back = [(t, a, why) for t, a, _ok, why in writes(r, 1400, 1500)] +keys = [k for k in r["store"].data if "cut" in str(k).lower()] +check(f"T33 [charger away 1100-1400, the lift at {tl}]: nothing while away " + f"({away}); on return D2's 0 A as bdfd3e6 ({back[:1]}), not a re-send " + f"of the cut; no store key ({keys})", + present(tl) and tl is not None and 1100 < tl < 1400 and not away + and bool(back) and near(back[0][0], 1400, 0, 1) and back[0][1] == 0.0 + and back[0][2] != "peak cut" and not keys) +never54("T33 [away]", r) + +# =========================================================================== # +print("\n6. QC 2: THE WAY-OUT REASON WITH OFF (T35 (b), (c))") +# =========================================================================== # +r = run(house_c((1250, 900.0)), sun_c((1250, 9000.0)), dur=1500, + events=window({1400: act("car_mode", "off")}, 959, 1380)) +wb = [(t, a, ok) for t, a, ok, _w in writes(r, 1395)] +lb = [m for t, _lv, m in r["w"].lines("Car: set") if t >= 1395] +whyb = [why for t, _a, _ok, why in writes(r, 1395)] +# bdfd3e6 writes nothing here: it is frozen with `gave_up` after the lift (C3) +# and Off does not clear it. After the drop the car's 10 A is Solar's, so Off +# writes EV-20's way-out 0 A once, at the press, as Solar's. +want = golden("T35 (b)", wb) +check(f"T35 (b): Off at 1400 after the lift: its way-out 0 A {wb} once at " + f"the press (bdfd3e6: {want}, frozen), reason Solar ({whyb}); one line " + f"({lb})", + wb == [(1400.0, 0.0, True)] and whyb == ["Solar"] + and lb == ["Car: set from 10 A to 0 A on 3 phases (Solar)."]) + +r = run(house_c(), sun_c(), dur=1200, + events=window({1000: act("car_mode", "off")}, 959, 999)) +wc = [(t, a, ok) for t, a, ok, _w in writes(r, 995)] +lc = [m for t, _lv, m in r["w"].lines("Car: set") if t >= 995] +want = golden("T35 (c)", (wc, lc)) +check(f"T35 (c): Off at 1000 while the cut stands: writes {wc} and lines " + f"{lc} as bdfd3e6's ({want})", (wc, lc) == want and bool(wc)) + +# =========================================================================== # +print("\n7. REVIEW ROUND 1: AWAY WHILE CAPPED (T36), F6 (T37), OFF (T38), " + "THE REASON (T39)") +# =========================================================================== # +# T36 (review r1, Major): the charger is away 1100-1200 and comes back while +# the cap stands with the quarter's 3 tries used up; then the lift. D2's 0 A +# is a cut try and stays held (ruling 3); the return does not give the +# quarter new tries; after the lift Solar's control resumes. +for tag, h, s in (("0 A", 3000.0, 0.0), ("6 A", 900.0, 1900.0)): + ev = window({1100: lambda p, c: p.ch.go_unavailable(), + 1200: lambda p, c: p.ch.go_unavailable(False)}, 959, 1300) + r = run(house_c((1250, 900.0), h=h), sun_c((1250, 9000.0), s=s), + dur=2700, events=ev) + tr = refused(r, 900, 1100) + tl = t_lift(r, 1200, 1800) + held_w = [(t, a) for t, a, _ok, _w in writes(r, 1081, tl or 1e9)] + cf = sorted({x["cut_fails"] for x in rows(r, 1081, tl or 1e9)}, key=str) + nz = [(t, a, ok, why) for t, a, ok, why in writes(r, tl or 1e9, + (tl or 1e9) + 61) + if a > 0.0] + check(f"T36 [{tag}] (review r1): 3 refused tries ({tr}); the charger away " + f"1100-1200 and back while capped: no D2 0 A or other write until " + f"the lift at {tl} ({held_w}); the quarter's cut count stays 3 " + f"across the return ({cf}); after the lift a Solar write within " + f"60 s ({nz[:1]})", + len(tr) == 3 and present(tl) and tl is not None and not held_w + and cf == [3] and bool(nz) and nz[0][2] and nz[0][3] == "Solar") + never54(f"T36 [{tag}]", r) + +# T37 (review r1, F6): episode 1 is lifted by the start rule (60 s) after +# 2 refused tries (960, 1020); episode 2 is due at 1040, within 60 s of the +# last refusal, with one try left: that try waits to 1080. +r = run(house_c(), sun_c((961, 9000.0), (1040, 0.0)), dur=1300, + opts={"ev_start_min": 1}, events=window({}, 959, 1800)) +tl = t_lift(r, 961, 1040) +due2 = first(x["t"] for x in rows(r, (tl or 1e9) + 1, 1100) + if x["cap"] is not None or x["wait"] is not None) +tr = [t for t, _a in refused(r, 900, 1300)] +early = [t for t, _a, _ok, _w in writes(r, due2 or 1e9, 1080)] +check(f"T37 (review r1, F6): episode 1 lifted at {tl} after tries {tr[:2]}; " + f"episode 2 due at {due2}: no try before 60 s after the last refusal " + f"({early}), then try 3 at {nth(tr, 2)} (>= 1080); none after", + present(tl) and tl is not None and present(due2) and due2 is not None + and due2 < 1080 and tr[:2] == [960.0, 1020.0] and not early + and len(tr) == 3 and tr[2] >= 1080 if len(tr) >= 2 else False) +never54("T37", r) + +# T38 (review r1, the fails gate): Off after the quarter's 3 refused tries, +# the refused 0 A still owed: no way-out try, as bdfd3e6 (gave_up there). +r = run(house_c(), sun_c(), dur=1300, + events=window({1100: act("car_mode", "off")}, 959, None)) +w38 = [(t, a, ok) for t, a, ok, _w in writes(r, 1081)] +want = golden("T38", w38) +check(f"T38 (review r1): Off at 1100 after 3 refused cut tries: Off's " + f"way-out writes {w38} as bdfd3e6's ({want})", w38 == want) + + +async def reason_replay(): + """T39: a refused 6 A cut, then the next quarter sizes 7 A (above the + refused value, under the 10 A read-back).""" + w = carmode.SolarWriter() + w.engaged, w.sent_a, w.taken, w.last_a = True, 10.0, True, 10.0 + drv, trk = Drv(), Trk() + w.cut_quarter("q1") + w.cut_a, w.cut_on = 6.0, True + await w._put(drv, 6.0, 10.0, 1000.0, trk) + w.cut_quarter("q2") + w.cut_a = 7.0 + await w._put(drv, 7.0, 10.0, 1070.0, trk) + return list(drv.calls), w.sent_why + + +try: + t39 = asyncio.run(reason_replay()) +except Exception as e: # noqa: BLE001 + t39 = (["raised " + repr(e)], None) +check(f"T39 (review r1): a new cut value above the refused one, under the " + f"read-back, goes out as 'peak cut' ({t39})", + t39[0] == [6.0, 7.0] and t39[1] == "peak cut") + +# =========================================================================== # +print("\n8. REVIEW ROUND 2: `fails` COUNTS ONLY THE OWED VALUE (T40-T42)") +# =========================================================================== # + + +def away_run(h, s, refuse_end, away=True): + ev = {} + if away: + ev = {1100: lambda p, c: p.ch.go_unavailable(), + 1200: lambda p, c: p.ch.go_unavailable(False)} + return run(house_c((1250, 900.0), h=h), sun_c((1250, 9000.0), s=s), + dur=1800, events=window(ev, 959, refuse_end)) + + +def after_lift(r): + tl = t_lift(r, 1200, 1800) + w = [(t, a, ok) for t, a, ok, _w in writes(r, tl or 1e9, 1800)] + hold = [t for t, _lv, _m in r["w"].lines(HOLD_TEXT)] + gu = [x["t"] for x in rows(r, tl or 1e9, 1800) if x["gave_up"]] + cf = sorted({x["cut_fails"] for x in rows(r, 1081, tl or 1e9)}, key=str) + return tl, w, hold, gu, cf + + +# T40 (PM row a): the charger refuses to 1430: after the return Solar's own +# write gets its own tries; the 2nd, 60 s later, is taken. +for tag, h, s in (("0 A", 3000.0, 0.0), ("6 A", 900.0, 1900.0)): + r = away_run(h, s, 1430) + tl, w, hold, gu, cf = after_lift(r) + pre = [t for t, _a, _ok, _w in writes(r, 1081, tl or 1e9)] + tk = [t for t, _a, ok in w if ok] + check(f"T40 [{tag}] (review r2): away 1100-1200 while capped, refused to " + f"1430: nothing until the lift at {tl} ({pre}); then Solar tries " + f"{w[:3]}: the 1st refused, the 2nd 60 s later, a taken write by " + f"1462 ({tk[:1]}); no gave_up ({gu[:2]}) or hold text ({hold}); " + f"the quarter's cut count unchanged across the return ({cf})", + present(tl) and tl is not None and not pre and len(w) >= 2 + and not w[0][2] and w[1][0] - w[0][0] >= 60 and bool(tk) + and tk[0] <= 1462 and not gu and not hold and cf == [3]) + never54(f"T40 [{tag}]", r) + + +def ok41(res): + tl, w, hold, gu, cf = res + if not (len(w) == 3 and len(hold) == 1 and present(tl) and tl is not None + and bool(gu)): + return False + return (not any(ok for _t, _a, ok in w) and w[0][0] <= tl + 60 + and all(b[0] - a[0] >= 60 for a, b in zip(w, w[1:])) + and abs(hold[0] - w[2][0]) <= 1 and gu[0] >= w[2][0] - 1 + and cf == [3]) + + +# T41 (PM row b): refused to 1600: Solar's own 3 tries 60 s apart, then +# gave_up and the hold text, as in the same run without the away. +for tag, h, s in (("0 A", 3000.0, 0.0), ("6 A", 900.0, 1900.0)): + ra = after_lift(away_run(h, s, 1600, away=True)) + rn = after_lift(away_run(h, s, 1600, away=False)) + check(f"T41 [{tag}] (review r2): refused to 1600: with the away {ra[1]}, " + f"gave_up from {ra[3][:1]}, hold text {ra[2]}; without it {rn[1]}, " + f"gave_up from {rn[3][:1]}, hold text {rn[2]}: 3 tries 60 s apart, " + f"then gave_up, in both", ok41(ra) and ok41(rn)) + + +async def replaced_value(): + """T42 (PM row c): a refused 6 A cut, then the next quarter's 7 A (the + reachable path of T39) replaces it and is refused too: `fails` counts + only the owed 7 A.""" + w = carmode.SolarWriter() + w.engaged, w.sent_a, w.taken, w.last_a = True, 10.0, True, 10.0 + drv, trk = Drv(), Trk() + w.cut_quarter("q1") + w.cut_a, w.cut_on = 6.0, True + await w._put(drv, 6.0, 10.0, 1000.0, trk) + w.cut_quarter("q2") + w.cut_a = 7.0 + await w._put(drv, 7.0, 10.0, 1070.0, trk) + return list(drv.calls), w.fails, w.cut_fails, w.refused_cut + + +try: + t42 = asyncio.run(replaced_value()) +except Exception as e: # noqa: BLE001 + t42 = (["raised " + repr(e)], None, None, None) +check(f"T42 (review r2): 6 A refused, then 7 A written in its place and " + f"refused (calls {t42[0]}): fails {t42[1]} counts only the owed 7 A " + f"(1), the new quarter's cut count {t42[2]} (1), owed {t42[3]}", + t42[0] == [6.0, 7.0] and t42[1] == 1 and t42[2] == 1 + and t42[3] == 7.0) + +tb_all = LOG.tracebacks(n_log0) +check(f"N13: no traceback in this file's runs ({tb_all[:1]})", not tb_all) +if TAKE: + print("(golden taken; no checks graded)") + sys.exit(0) +print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}") +sys.exit(1 if fails else 0) diff --git a/goodwe_controller/tools/ev54_kit.py b/goodwe_controller/tools/ev54_kit.py new file mode 100644 index 0000000..fe5449c --- /dev/null +++ b/goodwe_controller/tools/ev54_kit.py @@ -0,0 +1,335 @@ +"""EV-54: shared pieces of the refused-cut checks (test_ev54*.py): the run +with a per-cycle writer recorder, refusal windows, the cut tries per quarter +key, the Off twin with Solar's charger replayed, and the Never checks of +reports/EV-54-test-plan.md every run carries. + +The plant is EV-21's (`ev21_kit.drive` on `ev20_sun`): Shape C is N=2, both +batteries at 10 %, the car 10 A on 3 phases, the house 3000 W and the sun 0 +from 960. Aim 3400 W; the second period runs 900-1800. Every value is read +through getattr or `named_absence`, so a tree without EV-54 grades FAIL, +never a crash.""" + +import os +import sys + +_KIT = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, _KIT) +sys.path.insert(0, os.path.dirname(_KIT)) + +from app import carmode # noqa: E402 +from ev20_kit import LOG, check, step_fn # noqa: E402,F401 +from ev21_kit import drive, merge, Q, NoGive, refuse_n1 # noqa: E402,F401 +from named_absence import first, nth, given, present # noqa: E402,F401 + +Q3_TEXT = ("The charger did not take the peak cut, so the add-on tries again " + "next quarter: CHARGER_REFUSED.") +HOLD_TEXT = ("The charger did not take the current, so the add-on stops " + "asking until you press Solar: CHARGER_REFUSED.") +RETRY_S = carmode.RETRY_S +TOL = 0.01 + + +class W54: + """Per cycle, after the cycle and its writer step: the cut state, the + writer's own state, the read-back and the log mark; and every current + write Solar made, with the reason it was sent with.""" + + def __init__(self): + self.rows = [] + self.writes = [] # (t, a, ok, why) + self.n = 0 + self.marks = [] # (t, log index after the cycle) + self.mark0 = LOG.mark() + + def __call__(self, p, c, t): + w = c.car_solar + st = getattr(c, "_cut", None) or {} + for x in w.log[self.n:]: + if x[0] == "current": + self.writes.append((x[2], x[1], x[3], + getattr(w, "sent_why", None))) + self.n = len(w.log) + cc = getattr(c, "car_solar_can_cut", None) + g = c.peak_guard + self.rows.append(dict( + t=t, key=st.get("key"), cap=st.get("cap"), wait=st.get("wait"), + cuts=st.get("cuts"), under=st.get("under"), + cut_a=w.cut_a, sent=w.sent_a, taken=w.taken, gave_up=w.gave_up, + why=getattr(w, "sent_why", None), fails=w.fails, + cut_fails=getattr(w, "cut_fails", None), plan=w.plan.a, + plan_why=w.plan.why, ok_since=w.plan.ok_since, + set_at=w.plan.set_at, switch=w.plan.switch, seq=w.seq, + rb=p.ch.readback_a, sp=p.ch.setpoint_a, car=p.ch.power_w, + can=getattr(c, "_car_can", None), + can_now=bool(cc()) if cc else None, explains=c.car_explains, + floor=None if g is None else g.floor_w, mode=c.car_mode, + hold=w.hold, fault=w.fault, stuck=bool(c.car.stuck(t)))) + self.marks.append((t, LOG.mark())) + + def at(self, t): + return first(x for x in self.rows if x["t"] == t) + + def lines(self, text=None, level=None): + """(cycle second, level, message) of the log lines of this run.""" + out, lo = [], self.mark0 + for t, hi in self.marks: + for lv, m, _x in LOG.rec[lo:hi]: + if (text is None or text in m) and level in (None, lv): + out.append((t, lv, m)) + lo = hi + return out + + +def refuse(kind="ignore"): + def f(p, c): + p.ch.refuse = kind + return f + + +def accept(p, c): + p.ch.refuse = None + + +def window(ev, t0, t1, kind="ignore"): + """The charger refuses `kind` from t0 to t1 (None: to the end).""" + ev = merge(ev, int(t0), refuse(kind)) + if t1 is not None: + ev = merge(ev, int(t1), accept) + return ev + + +def house_c(*more, h=3000.0): + """Shape C's house: 900 W, `h` from 960, then the (t, W) pairs.""" + return step_fn((960, h), *more, base=900.0) + + +def sun_c(*more, s=0.0): + """Shape C's sun: 7900 W (the car's 10 A, the house and 100 W), `s` + from 960, then the (t, W) pairs.""" + return step_fn((960, s), *more, base=7900.0) + + +def run(house=None, sun=None, *, dur, n=2, socs=None, events=None, + opts=None, mode="solar", setpoint=0, phases=3, **kw): + """Shape C (N=2 both at 10 %, or N=1 `a` at 10 %) with `house` and `sun`, + Car first, the car on 3 phases. `out["w"]` is the W54 recorder. At N=1 + without a `plant_cls`, the sole battery refuses to give (EV-21's N=1 + rows: `refuse_n1` with the `NoGive` plant), so the cut stays needed.""" + if n == 1 and "plant_cls" not in kw: + kw["plant_cls"] = NoGive + kw.setdefault("rows", False) + ev = dict(events or {}) + for t in range(int(kw.get("t0", 0.0)), int(kw.get("t0", 0.0) + dur)): + ev = merge(ev, t, refuse_n1) + events = ev + ratings = {"a": 5000.0, "b": 4600.0} if n == 2 else {"a": 5000.0} + socs = dict(socs or {u: 10.0 for u in ratings}) + rec = W54() + oc = kw.pop("on_cycle", None) + + def on_cycle(p, c, t): + rec(p, c, t) + if callable(oc): + oc(p, c, t) + o = dict({"ev_phases": "3"}, **(opts or {})) + out = drive(house or house_c(), sun or sun_c(), dur=dur, first="car", + phases=phases, mode=mode, socs=socs, ratings=ratings, opts=o, + events=events, setpoint=setpoint, on_cycle=on_cycle, **kw) + out["w"] = rec + out["spec"] = dict(house=house or house_c(), sun=sun or sun_c(), + dur=dur, n=n, socs=socs, opts=opts, phases=phases, + kw=kw) + return out + + +# ------------------------------------------------------------- reading runs +def writes(r, t0=0, t1=1e9): + """(t, a, ok, why) of every current write Solar made in [t0, t1).""" + return [x for x in r["w"].writes if t0 <= x[0] < t1] + + +def row(r, t): + return r["w"].at(t) + + +def rows(r, t0=0, t1=1e9): + return [x for x in r["w"].rows if t0 <= x["t"] < t1] + + +def cut_writes(r, t0=0, t1=1e9): + """The writes made while a cut was due or stood (the cycle's cap or its + wait): the cut tries, (t, a, ok, why, key).""" + out = [] + for t, a, ok, why in writes(r, t0, t1): + x = row(r, t) + if present(x) and (x["cap"] is not None or x["wait"] is not None): + out.append((t, a, ok, why, x["key"])) + return out + + +def refused_by_key(r, t0=0, t1=1e9): + """{quarter key: [t, ...]} of the refused cut tries.""" + out = {} + for t, _a, ok, _why, key in cut_writes(r, t0, t1): + if not ok: + out.setdefault(key, []).append(t) + return out + + +def key_change(r, t0, t1): + """The first cycle in [t0, t1) whose quarter key differs from the one + before it.""" + prev = None + for x in r["w"].rows: + if x["t"] >= t0 and x["t"] < t1 and prev is not None \ + and x["key"] is not None and x["key"] != prev: + return x["t"] + if x["key"] is not None: + prev = x["key"] + return None + + +def t_lift(r, t0, t1): + """The cycle the cap was lifted in [t0, t1): a cap, then none.""" + prev = None + for x in r["w"].rows: + if t0 <= x["t"] < t1 and prev is not None and x["cap"] is None: + return x["t"] + prev = x["cap"] if t0 <= x["t"] else None + return None + + +def dropped(r, t, a, slack=2): + """The drop by `t` (+-slack): `sent_a` = `a` (the read-back), taken, the + plan's current `a`. Returns the first cycle that shows it, or None.""" + for x in rows(r, t - slack, t + slack + 1): + if x["sent"] is not None and abs(x["sent"] - a) <= TOL and x["taken"] \ + and abs(x["plan"] - a) <= TOL: + return x["t"] + return None + + +def same_gaps(r, t0=0, t1=1e9): + """N2: two tries of the same value less than RETRY_S apart (the list of + offending pairs), refused tries and their retries.""" + w = [(t, a) for t, a, ok, _why in writes(r, t0, t1)] + bad = [] + for i, (ta, aa) in enumerate(w): + for tb, ab in w[i + 1:]: + if abs(aa - ab) <= TOL and tb - ta < RETRY_S - 1e-9: + prev_ok = [ok for t, a, ok, _w in writes(r, ta, ta + 1) + if abs(a - aa) <= TOL] + if prev_ok and not prev_ok[0]: + bad.append((ta, tb, aa)) + break + return bad + + +def never54(name, r, *, clamp=16.0, max_q=3, peak_free=True): + """N1 (at most 3 refused cut tries per quarter key), N2 (the same value + not twice within RETRY_S after a refusal), N3 (no write between 0 and + 6 A), N4 (none above the clamp), N6 (no non-zero write above a standing + cap), N12 (`gave_up` never set by a cut try; no "until you press Solar" + while a cut is due or stands), N13 (no Traceback), N16 (no "peak cut" + write while no cut is due or stands).""" + rbk = refused_by_key(r) + bad1 = {k: v for k, v in rbk.items() if len(v) > max_q} + check(f"{name}: N1 at most {max_q} refused cut tries per quarter key " + f"({bad1})", not bad1) + bad2 = same_gaps(r) + check(f"{name}: N2 no retry of a refused value within {RETRY_S:.0f} s " + f"({bad2[:3]})", not bad2) + w = writes(r) + bad3 = [(t, a) for t, a, _ok, _why in w if 0.0 + TOL < a < 6.0 - TOL] + bad4 = [(t, a) for t, a, _ok, _why in w if a > clamp + TOL] + check(f"{name}: N3 no write between 0 and 6 A ({bad3[:3]}); N4 none above " + f"the clamp ({bad4[:3]})", not bad3 and not bad4) + bad6 = [] + for t, a, _ok, _why in w: + x = row(r, t) + if a > TOL and present(x) and x["cap"] is not None \ + and a > x["cap"] + TOL: + bad6.append((t, a, x["cap"])) + check(f"{name}: N6 no non-zero write above a standing cut ({bad6[:3]})", + not bad6) + hi = r["w"].marks[-1][1] if r["w"].marks else r["w"].mark0 + tb = [m for _lv, m, x in LOG.rec[r["w"].mark0:hi] if x] + check(f"{name}: N13 no Traceback ({tb[:1]})", not tb) + if peak_free: + bad16 = [] + for t, a, _ok, why in w: + x = row(r, t) + if why == "peak cut" and present(x) and x["cap"] is None \ + and x["wait"] is None: + bad16.append((t, a)) + for t, _lv, m in r["w"].lines("(peak cut)"): + x = row(r, t) + if present(x) and x["cap"] is None and x["wait"] is None: + bad16.append((t, m)) + check(f"{name}: N16 no 'peak cut' write or line while no cut is due " + f"or stands ({bad16[:3]})", not bad16) + + +# ------------------------------------------------------------- the Off twin +def twin(r, extra_events=None): + """The run of `r` in Off: the same house, sun and batteries, and the + charger moved at the same seconds as Solar's taken writes moved it, so + the car is the same and only the mode differs.""" + sp = r["spec"] + ev = dict(extra_events or {}) + prev = None + for x in r["trace"]: + if prev is not None and abs(x["sp"] - prev) > TOL: + def put(p, c, v=x["sp"]): + p.ch.set_current(v) + ev = merge(ev, int(x["t"]) + 1, put) + prev = x["sp"] + kw = dict(sp["kw"]) + return run(sp["house"], sp["sun"], dur=sp["dur"], n=sp["n"], + socs=sp["socs"], opts=sp["opts"], mode="off", setpoint=0, + phases=sp["phases"], events=ev, **kw) + + +def alarms_by_q(r, ids): + out = {} + for t, n in r["raised"]: + if n in ids: + q0 = int(t) // Q * Q + out.setdefault(q0, t) + return out + + +def as_off(name, r, o, ids, *, t0=900, refused=None): + """T7 / N5: the run `r` against its Off twin `o`. Before the read-back + shows the cut, `car_explains` is never True; the first alarm of every + quarter at the twin's second +2; `car_peak_q` as the twin's; the guard's + floor within 50 W of the twin's while the cut is refused (`refused`: + the (t0, t1) of that); `car_solar_can_cut()` False while the read-back + is above `sent_a`.""" + # Graded out only in the cut's own cycle (nothing written yet: EV-21 + # T30); from the cycle after its write, as Off until the read-back. + t_ex = refused[0] if refused is not None else t0 + bad_ex = [x["t"] for x in rows(r, t_ex) if x["explains"] and x["sent"] + is not None and x["rb"] > x["sent"] + TOL] + a_r, a_o = alarms_by_q(r, ids), alarms_by_q(o, ids) + qs = sorted(set(a_r) | set(a_o)) + bad_a = [(q, a_r.get(q), a_o.get(q)) for q in qs if q >= t0 and ( + a_r.get(q) is None or a_o.get(q) is None + or abs(a_r[q] - a_o[q]) > 2)] + bad_f = [] + if refused is not None: + fo = {x["t"]: x["floor"] for x in o["w"].rows} + for x in rows(r, refused[0], refused[1]): + y = fo.get(x["t"]) + if abs((x["floor"] or 0.0) - (y or 0.0)) > 50.0: + bad_f.append((x["t"], x["floor"], y)) + bad_c = [x["t"] for x in rows(r, t0) if x["can_now"] and x["sent"] + is not None and x["rb"] > x["sent"] + TOL] + check(f"{name}: T7 as Off: car_explains never True before the read-back " + f"shows the cut ({bad_ex[:3]}); each quarter's first alarm at the " + f"twin's second +2 ({bad_a[:3]}); car_peak_q as the twin's " + f"({r['c'].car_peak_q} vs {o['c'].car_peak_q}); floor within 50 W " + f"while refused ({bad_f[:3]}); can-cut False while the read-back is " + f"above sent_a ({bad_c[:3]})", + not bad_ex and not bad_a and not bad_f and not bad_c + and r["c"].car_peak_q == o["c"].car_peak_q)