diff --git a/goodwe_controller/DECISIONS/EV-21-car-cut-first.md b/goodwe_controller/DECISIONS/EV-21-car-cut-first.md index ea9997d..e1b39cd 100644 --- a/goodwe_controller/DECISIONS/EV-21-car-cut-first.md +++ b/goodwe_controller/DECISIONS/EV-21-car-cut-first.md @@ -10,8 +10,9 @@ the failure catalogue it answers. ## The rule, in plain words - **Solar only.** When the 15-minute period heads over the aim (cap less - margin) and the batteries would have to give more than now for it, the car is - lowered first. A charge the batteries only have to slow down is not a cut. + margin), the car is lowered first. Slowing a battery charge counts as the + batteries taking more (PM Q2), so a charge they could slow down only counts + as headroom for the 15 s wait. - **How far.** `floor((car W - excess W) / (230 x phases))` A, with the phases the car draws on (1 for a one-phase car). Under 6 A it is 0 A, never between. Never above the current Solar has set. An untrusted car figure cuts to 0 A. @@ -64,11 +65,9 @@ the failure catalogue it answers. ## Choices the rulings left open -- **"The batteries would have to give more than now"** is `battery W + excess - > 0` on the projection with the car: the guard's `wanted_w` with the cover on, - the same test on the real period with it off. Without it, Solar's own start - on slow batteries cut the car for the seconds the batteries took to stop - charging. +- **A lowering on its way** (`CUT_SENT_S`, 2 s) counts as Solar's own for + grading, once per value (PM Q1): a re-send of the same value, a retry + included, gets no new grace; after it, not read back is not cut. - **While the 15 s wait runs** the cap is the current Solar has then (C4: no raise while due). - **Under a cut the plan may lower** (formal C10), by its own 30 s rule. diff --git a/goodwe_controller/DOCS.md b/goodwe_controller/DOCS.md index bdb038b..b996073 100644 --- a/goodwe_controller/DOCS.md +++ b/goodwe_controller/DOCS.md @@ -3375,8 +3375,8 @@ changes at most once per 30 seconds and only by 1 A or more. logs one warning, until you press Solar again or the charger shows Solar's value. - **The peak limit: the car is cut first.** When the 15-minute period heads - over the peak limit and the batteries would have to give more for it, Solar - lowers the car first: by the excess, to 0 A when less than 6 A would be left. + over the peak limit, Solar lowers the car first, also while the batteries + could instead charge less: by the excess, to 0 A when less than 6 A would be left. It waits at most 15 seconds, and only while the batteries can still give more; it does not wait when they are at full power or at the peak reserve, when a battery reading is missing, with `ev_batt_cover` off, or in the last 2 diff --git a/goodwe_controller/app/carmode.py b/goodwe_controller/app/carmode.py index 37eb722..9cc661a 100644 --- a/goodwe_controller/app/carmode.py +++ b/goodwe_controller/app/carmode.py @@ -842,8 +842,13 @@ class SolarWriter(ManualWriter): """ManualWriter's one write site. What Solar SENT is recorded before the write goes out, so a write cancelled while it waits for its read-back is never trusted (`live`).""" + prev = self.sent_a self.sent_a, self.taken = float(a), False - self.sent_at = now # EV-21: a lowering on its way + 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 + # way is once per value; a re-send of the same value (a retry) + # gets none. + self.sent_at = now zero = float(a) <= TOL_A if not zero and tracker is not None and tracker.stuck(now): self.stuck_starts += 1 # C12: a start under a stuck verdict diff --git a/goodwe_controller/app/ctl_car.py b/goodwe_controller/app/ctl_car.py index a9995a6..e7efbf8 100644 --- a/goodwe_controller/app/ctl_car.py +++ b/goodwe_controller/app/ctl_car.py @@ -314,13 +314,10 @@ class CarMixin: # C12: Solar's own phase change holds the car at 0 A on its way to a # current: a cut due then ends it at that 0 A (no closing current). seq_on = w.seq is not None and w.plan.a > 0.0 - # The batteries would have to give more than now (the guard's - # `wanted_w`, on the projection WITH the car): a charge that only - # has to slow down is the loop's, not a cut. Unknown: they add - # nothing (Q4). - batt = self.site_batt_w - wants = batt is None or float(batt) + ex > 0.0 - due = ex > 0.0 and wants and running and (drawing or seq_on) + # PM Q2 (formal C14): slowing a battery charge counts as the + # batteries taking more, so a cut is due whatever they do now; their + # charge only counts as headroom for the 15 s wait. + due = ex > 0.0 and running and (drawing or seq_on) n = self._car_cut_n() if st["cap"] is not None: # A cut stands: deeper only if the excess grows (OQ7); the diff --git a/goodwe_controller/test_ev21.py b/goodwe_controller/test_ev21.py index a8165ad..3294848 100644 --- a/goodwe_controller/test_ev21.py +++ b/goodwe_controller/test_ev21.py @@ -243,8 +243,10 @@ def refuse_a(p, c): c.inverters[0].refused = 1 -ev14 = {t: refuse_a for t in range(1, 1100)} -ev14[0] = lambda p, c: (refuse_a(p, c), set_resp(5.0)(p, c)) +# A's refusal and B's 5 s response from 900 (after Solar's own start, which +# PM Q2 / formal C14 would otherwise cut on its start blip). +ev14 = {t: refuse_a for t in range(900, 1100)} +ev14[901] = lambda p, c: (refuse_a(p, c), set_resp(5.0)(p, c)) r = shape("W", events=ev14, plant_cls=RefusesA, dur=1100, rows=False) z = zero_at(r, 960) check(f"T14: N=2, A refuses to give, B has 4600 W: the excess is beyond " diff --git a/goodwe_controller/test_ev21_fix1.py b/goodwe_controller/test_ev21_fix1.py new file mode 100644 index 0000000..8d29a27 --- /dev/null +++ b/goodwe_controller/test_ev21_fix1.py @@ -0,0 +1,182 @@ +"""EV-21 fix round 1 (formal round 4): C14 and C15, and pins of the code's +current answer to three questions the owner has not ruled (C16, C18, Q1's +other writer). `python3 -B test_ev21_fix1.py` + +- C14 (PM Q2): slowing a battery charge counts as the batteries taking more, + so a cut is due while the batteries charge at least the excess: after + CUT_WAIT_S with real headroom, at once with the cover off. +- C15 (PM Q1): the 2 s grace of a lowering on its way is once per value; a + retry of a refused cut gets none. +- C16, C18, Q1-other-writer: what the code does today, pinned so a ruling + that changes it shows here. These are not rulings. + +The real Controller on `tools/ev20_sun.py` through `tools/ev21_kit.py`. +Mutating a module this file grades? Read MUTATION.md first (purge __pycache__). +""" + +import dataclasses +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.join(HERE, "tools")) + +from app import ctl_car # noqa: E402 +import ev20_sun as S # noqa: E402 +from ev20_kit import LOG, check, fails, const, step_fn # noqa: E402 +from ev21_kit import (AIM, after, drive, shape, _mode, set_resp, # noqa: E402 + merge, never) + +n_log0 = LOG.mark() +CUT_WAIT_S = getattr(ctl_car, "CUT_WAIT_S", 15.0) + + +def tick_case(cover, elapsed): + """`_car_cut_tick` itself, on a real Controller: Shape W just before its + step (Solar runs the car at 10 A on 3 phases, both batteries at 60 %), + then the batteries set to CHARGE 3 kW and a projection with the car + whose excess is 1 kW at `elapsed` s; the guard does not engage + (battery + excess = -2 kW). Returns (cap, wait) after the first tick + and the cap after a second tick CUT_WAIT_S later.""" + # The run itself with the cover on: with it off, Solar's own start at + # 120 s already meets C14's rule (see the dev report's Findings). + r = shape("W", dur=959) + c = r["c"] + c.o["ev_batt_cover"] = cover + t = c.car_now() + for inv in c.inverters: + inv.batt = -1500.0 # 3 kW of charge, site sum + c._car_cut_meter_fresh = lambda: True # the meter is fresh (N9 aside) + left = 900.0 - elapsed + proj = dataclasses.replace( + c._peak_proj_real, elapsed_s=elapsed, + projected_w=AIM + 1000.0 * left / 900.0) + guard = dataclasses.replace( + c.peak_guard, engaged=False, floor_w=None, saturated=False, + floor_limited=False, blind=None, wanted_w=-2000.0, able_w=None, + held=()) + c._cut = c._cut_fresh(None) + c.car_now = lambda: t + c._car_cut_tick(proj, guard, AIM, t) + first = (c._cut["cap"], c._cut["wait"], c._cut["since"]) + c.car_now = lambda: t + CUT_WAIT_S + c._car_cut_tick(proj, guard, AIM, t + CUT_WAIT_S) + return first, c._cut["cap"], c.site_batt_w + + +# =========================================================================== # +print("\n1. C14: A CUT IS DUE WHILE THE BATTERIES CHARGE (PM Q2)") +# =========================================================================== # +for name, cover, el, at_once in ( + ("cover on, real headroom", True, 300.0, False), + ("cover off (OQ3)", False, 300.0, True), + ("the last 120 s", True, 800.0, True)): + first, later, batt = tick_case(cover, el) + cap0, wait0, since0 = first + if at_once: + ok = cap0 is not None + how = "at once" + else: + ok = cap0 is None and since0 is not None and later is not None + how = f"after the {CUT_WAIT_S:.0f} s wait" + check(f"C14 [{name}]: the batteries charge {-(batt or 0):.0f} W against " + f"an excess of 1000 W; the cut is due all the same, {how} (first " + f"tick cap {cap0}, wait {wait0}, episode since {since0}; " + f"{CUT_WAIT_S:.0f} s later cap {later})", ok) + +# =========================================================================== # +print("\n2. C15: THE 2 s GRACE IS ONCE PER VALUE (PM Q1)") +# =========================================================================== # + + +def ignore(p, c): + p.ch.refuse = "ignore" + + +r = shape("C", dur=1120, beside=True, events={959: ignore}) +sends = [(t, v) for t, e, v in r["plant"].sets if e == S.SET and t >= 959] +rec = r["rec"].rows +t_first = sends[0][0] if sends else None +late = [x["t"] for x in rec if t_first is not None + and x["t"] > t_first + 2.0 and x["can"] and x["rb"] > 0.0] +check(f"C15: the cut 0 A is ignored and tried again ({sends}); while the " + f"read-back still shows the old current, Solar counts as able to cut " + f"for the first 2 s of the first send only, never on a retry " + f"({late[:4]})", len(sends) >= 2 and not late) + +# =========================================================================== # +print("\n3. OPEN QUESTIONS, PINNED AS THE CODE HAS THEM (C16, C18, Q1)") +# =========================================================================== # +# C16: after a partial cut, the restart adds only max(0, start power - the +# car's power now) to the projection. A car still at 6 A adds nothing, so +# the car may come back while the period with a FULL 6 A on top would not +# be under the aim. +sun16 = step_fn((1200, 0.0), (1260, 5000.0), base=7900.0) +r = drive(step_fn((1200, 800.0), base=900.0), sun16, dur=1700, first="car", + phases=3, socs={"a": 10.0, "b": 10.0}, opts={"ev_phases": "3"}, + events={1198: lambda p, c: setattr(c.car_solar, "nonzero_at", + p.t)}) +rows = r["rec"].rows +part = [x for x in rows if x["t"] >= 1200 and x["cap"] is not None] +und = [x for x in rows if x["t"] > 1200 and x["under"] is not None] +u = und[0] if und else {} +left = 900.0 - (u.get("t", 0) - 900.0) +full = (u.get("proj") or 0) + 4140.0 * left / 900.0 +check(f"C16 (pinned, not a ruling): a partial cut to " + f"{part[0]['cap'] if part else None} A; the restart clock starts at " + f"{u.get('t')} with the projection {u.get('proj') or 0:.0f} W under " + f"the aim while the car still draws {u.get('car')} W; with a full 6 A " + f"on top it would be {full:.0f} W", + bool(part) and 0 < part[0]["cap"] < 10 and bool(und) + and (u.get("car") or 0) >= 4000.0 and (u.get("proj") or 0) < AIM + and full >= AIM) + +# C18: Solar's own 1 -> 3 change under way when a cut becomes due WITH +# headroom (the 15 s wait). Pinned: the change may close during the wait, at +# no more than the current the wait holds, on the phases it selected. +kw = dict(dur=700, first="car", phases=1, socs={"a": 60.0, "b": 60.0}, + opts={"ev_phases": "auto"}) +r0 = drive(const(900.0), const(9280.0), **kw) +log0 = r0["c"].car_solar.log +sel_t = [t for k, a, t, ok in log0 if k == "phases"] +zero_b = [t for k, a, t, ok in log0 if k == "current" and a == 0.0 + and sel_t and t <= sel_t[0]] +tb = int(zero_b[-1]) if zero_b else 400 +kw["dur"] = tb + 60 +r = drive(step_fn((tb + 1, 9280.0 + 3400.0 + 1500.0), base=900.0), + const(9280.0), **dict(kw, events={0: set_resp(20.0)})) +rows = r["rec"].rows +wait = [x for x in rows if x["t"] >= tb + 1 and x["wait"] is not None] +close = [(t, a) for t, a, _ in after(r, tb + 1) if a > 0.0] +sel = [(x[0], x[2]) for x in r["sim"].log if x[1] == "phases" + and x[0] >= tb] +caps = [x["t"] for x in rows if x["t"] >= tb + 1 and x["cap"] is not None] +check(f"C18 (pinned, not a ruling): Solar's change began at {tb}; the cut " + f"due at {wait[0]['t'] if wait else None} waits (cap " + f"{wait[0]['wait'] if wait else None} A); during the wait the change " + f"selects {sel} and closes at {close[:1]}; the cut at {caps[:1]}", + bool(wait) and bool(close) and close[0][1] <= wait[0]["wait"] + and (not caps or close[0][0] <= caps[0])) + +# Q1 (other writer): another writer raises the current inside the 2 s grace +# of Solar's lowering. Pinned: until the next writer step marks the +# difference (`mismatch_since`), car_solar_can_cut() stays True. +r = shape("C", dur=950) +c = r["c"] +w = c.car_solar +rd = c.car.reading +w.sent_a, w.sent_at, w.fail_at, w.mismatch_since = 0.0, c.car_now(), None, \ + None +c.car.reading = dataclasses.replace(rd, allowed_a=16.0, setpoint_a=16.0) +in_grace = c.car_solar_can_cut() +w.mismatch_since = c.car_now() +marked = c.car_solar_can_cut() +check(f"Q1 other writer (pinned, not a ruling): Solar sent 0 A, another " + f"writer shows 16 A inside the 2 s grace: can-cut {in_grace} until the " + f"difference is marked, then {marked}", in_grace is True + and marked is False) + +tb_ = LOG.tracebacks(n_log0) +check(f"N11: no traceback in this file's runs ({tb_[:1]})", not tb_) +print(f"\n{'FAILED: ' + str(len(fails)) if fails else 'ALL PASSED'}") +sys.exit(1 if fails else 0) diff --git a/goodwe_controller/test_ev21_paths.py b/goodwe_controller/test_ev21_paths.py index 065f600..9905347 100644 --- a/goodwe_controller/test_ev21_paths.py +++ b/goodwe_controller/test_ev21_paths.py @@ -384,11 +384,13 @@ for kind in ("M", "C"): for n in (2, 1): # The old period heads over at 1700 (100 s left: at once); the house is # back to 900 W at 1790, so the new period starts under the aim. - r = near_end(1700, n=n, house_after=9000.0, sun_back=1810, dur=2100, + r = near_end(1700, n=n, house_after=12000.0, sun_back=1810, dur=2100, house_more=((1790, 900.0),)) w = [(t, a) for t, a, _ in after(r, 1695)] cut = [t for t, a in w if a == 0.0] - nz = [t for t, a in w if a > 0.0] + # Non-zero writes after the cut only (Solar's own steps before the step + # at 1700 are not a restart). + nz = [t for t, a in w if a > 0.0 and cut and t > cut[0]] new_q = [x["t"] for x in r["rec"].rows if 1800 <= x["t"] < 1930 and x["cap"] is not None] check(f"T39 [N={n}]: the old period's cut at {cut[:1]}; none at or " @@ -495,17 +497,21 @@ lim = None bad = [] if rb: car_a = (rec.at(rb[0] + 5) or {}).get("car", 0.0) - lim = max(0.0, (dec.get("want") or 0.0) - (car_b - car_a)) + 150.0 - # A cycle whose battery reading moved since the last one reads the - # battery a cycle before the meter (want = battery + excess): a skew of - # the measurement, not a floor raised for the car; those are skipped. - tb = {x["t"]: x["batt"] for x in r["trace"]} - bad = [(x["t"], round(x["want"] or 0)) for x in rec.rows - if rb[0] + 5 <= x["t"] <= rb[0] + 60 and (x["want"] or 0) > lim - and abs(tb.get(x["t"], 0.0) - tb.get(x["t"] - 1, 0.0)) < 50.0] -check(f"T46: from 5 s after the cut's read-back the guard wants no more than " - f"its want at the cut less what the car gave back, +150 W ({lim}; " - f"{bad[:3]})", bool(rb) and not bad) + # Fix round 1: the bound is on the guard's EXCESS (what the site must + # still shed: wanted_w less the batteries' own output). In Shape W the + # batteries answer 20 s late, so the commands sent before the cut reach + # them after it and `wanted_w` (battery + excess) rises with that late + # output while the excess is negative: not a floor raised for the car. + tr_ = {x["t"]: x for x in r["trace"]} + ex_dec = (tr_.get(z) or {}).get("excess") or 0.0 + lim = max(0.0, ex_dec - (car_b - car_a)) + 150.0 + bad = [(x["t"], round(x["excess"] or 0), round(x["want"] or 0)) + for x in r["trace"] + if rb[0] + 5 <= x["t"] <= rb[0] + 60 and (x["excess"] or 0) > lim] +check(f"T46: from 5 s after the cut's read-back the excess the guard asks the " + f"batteries for is no more than at the cut less what the car gave " + f"back, +150 W ({lim}; (t, excess, wanted_w) over it: {bad[:3]})", + bool(rb) and not bad) # =========================================================================== # print("\n9. THE WALL CLOCK JUMPS (T48)") diff --git a/goodwe_controller/test_ev21_same.py b/goodwe_controller/test_ev21_same.py index ca11ee4..921a21a 100644 --- a/goodwe_controller/test_ev21_same.py +++ b/goodwe_controller/test_ev21_same.py @@ -162,10 +162,18 @@ def house_trace(t): return 600.0 + (k * 7919 % 900) +def cover_off(p, c): + c.o["ev_batt_cover"] = False + + for cover in (True, False): + # Cover off from 300 s, once Solar's own start is past: with it off from + # the start, PM Q2 / formal C14 with OQ3 cut Solar's own start blip at + # once (dev report, Findings). On c79eb37 both hours hash the same. r = drive(house_trace, lambda t: house_trace(t) + 7000.0, dur=3600, first="car", phases=3, socs={"a": 60.0, "b": 60.0}, - opts={"ev_phases": "3", "ev_batt_cover": cover}) + opts={"ev_phases": "3"}, + events={} if cover else {300: cover_off}) caps = [x["t"] for x in r["rec"].rows if x["cap"] is not None] check(f"T38 [cover {'on' if cover else 'off'}]: no cut in an hour with no " f"excess ({caps[:2]})", not caps) diff --git a/goodwe_controller/tools/ev21_kit.py b/goodwe_controller/tools/ev21_kit.py index e519b0d..08ea069 100644 --- a/goodwe_controller/tools/ev21_kit.py +++ b/goodwe_controller/tools/ev21_kit.py @@ -126,7 +126,10 @@ def shape(kind, *, step=960, mode="solar", first="car", n=2, cover=True, o = dict({"ev_phases": "3", "ev_batt_cover": cover}, **(opts or {})) ev = dict(events or {}) if kind in ("W", "S"): - ev = merge(ev, 0, set_resp(20.0)) + # Slow batteries from 60 s before the step: Solar's own start at + # 120 s runs on quick ones (with slow ones its own start blip lasts + # past the 15 s wait and is cut, PM Q2 / formal C14). + ev = merge(ev, max(0, int(step) - 60), set_resp(20.0)) sp = setpoint if setpoint is not None else (car_a if mode != "solar" else 0) if kind == "F" and sun_w is None: @@ -168,6 +171,13 @@ def _mode(units, on): return f +class NoGive(S.SunPlant): + """Every battery refuses to give: the plant gives min(command, 0).""" + + def batt_of(self, u, at): + return min(super().batt_of(u, at), 0.0) + + def refuse_n1(p, c): """N=1: the sole battery refuses to give (SAFETY-73's latch, held).""" c.batt_refused, c.batt_refused_at = 1, p.t @@ -180,9 +190,11 @@ def near_end(step, *, n=2, house_after=3000.0, sun_back=None, dur=1800, modes until 1500; N=1: the battery refuses to give throughout), then the sun is back and Solar starts the car at 10 A on 3 phases; at `step` the sun goes and the house is `house_after`. The batteries (N=2: 60 %) take - 20 s to respond. `sun_back`: the sun returns then.""" + 20 s to respond from 30 s before the step (Solar's own start runs on + quick ones: PM Q2 / formal C14 would cut its own start blip otherwise). + `sun_back`: the sun returns then.""" ev = dict(kw.pop("events", None) or {}) - ev = merge(ev, 0, set_resp(20.0)) + ev = merge(ev, max(0, int(step) - 30), set_resp(20.0)) if n == 2: ev = merge(merge(ev, 899, _mode("ab", False)), 1500, _mode("ab", True)) @@ -192,6 +204,9 @@ def near_end(step, *, n=2, house_after=3000.0, sun_back=None, dur=1800, ev = merge(ev, t, refuse_n1) ratings = {"a": 5000.0} kw.setdefault("rows", False) + # The harness plant gives what it is asked; a refusing battery + # gives nothing (it still takes a charge). + kw.setdefault("plant_cls", NoGive) house = step_fn((900, 3350.0), (1500, 900.0), (step, house_after), *house_more, base=900.0) pairs = [(900, 0.0), (1500, 7900.0), (step, 0.0)]