"""EV-18: the real Controller across one quarter edge `E`, N=2, both units at the peak reserve and the car charging (`ev04_peak.drive`). Used by test_ev18.py. The run starts `E` s before an edge (rig.BASE is moved back for the run), with a light house so the first quarter does not raise the month's peak (the aim stays `AIM`). At `E - 120` the house steps to the shape, so the guard first wants power at the edge, as on the rig (EV-15 F-A). `force` makes a unit give what the loop gives below the reserve whatever it is told; `lost` drops its reading for some seconds (the grid still sees it). The trace is one dict per cycle, taken after it. """ import hashlib import logging import os import sys from datetime import timedelta HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import ev04_peak as P # noqa: E402 import opt11_identity as rig # noqa: E402 import safety81_sim as s81 # noqa: E402 from app import peakguard # noqa: E402 E = 150 # the edge, in run seconds AIM = 13600.0 MARGIN = 50.0 PRE_W = 5000.0 # the first quarter's house: under the cap FLOOR = "goodwe_peak_soc_floor" OPTS = {"peak_soc_floor": 20, "inverters": [ {"name": "inverter-a", "setpoint_entity": "number.sp_a", "soc_entity": "sensor.soc_a", "batt_entity": "sensor.batt_a", "max_w": 5000, "bms_soc_floor": 10}, {"name": "inverter-b", "setpoint_entity": "number.sp_b", "soc_entity": "sensor.soc_b", "batt_entity": "sensor.batt_b", "max_w": 4600, "bms_soc_floor": 10}]} class _Errors(logging.Handler): def __init__(self): super().__init__(logging.ERROR) self.rec = [] def emit(self, r): self.rec.append(r.getMessage()) ERR = _Errors() _lg = logging.getLogger("goodwe") _lg.addHandler(ERR) _lg.setLevel(logging.ERROR) _lg.propagate = False class Plant(P.CarPlantN): force = {} lost = {} def batt_of(self, u, at): f = self.force.get(u) if f is not None: return float(f(at)) return super().batt_of(u, at) async def number(self, e, invert=False): for u, secs in self.lost.items(): if e == "sensor.batt_" + u and int(self.t) in secs: return None return await super().number(e, invert) def shape(after, before=PRE_W, at=None): """The house: `before` until `at` (E - 120), then `after` (W or fn(t)).""" at = E - 120 if at is None else at return lambda t: before if t < at else (after(t) if callable(after) else after) def run(house, *, a=None, b=None, lost=None, car_a=6, phases=1, aim=AIM, mode="manual", dur=None, extra=None, sim=None, soc=None, plug=True, x=1, mono_x=None, explain_off=False, latch_off=False, cover=True): """One run; returns (run, trace). `x`: fake seconds per cycle (wall and monotonic both; `mono_x` sets the monotonic rate apart). `explain_off`: the car never explains, `latch_off`: no contradiction latch (both for the control-identity check). `cover`: the option `ev_batt_cover`.""" force = {} if a is not None: force["a"] = a if b is not None: force["b"] = b cls = type("Plant", (Plant,), {"force": force, "lost": lost or {}}) tr = [] n_err = [len(ERR.rec)] dur = E + 900 if dur is None else dur def hook(plant, c): orig = c.car_settle if explain_off: c._car_explains_alarm = lambda *a_, **k_: False if latch_off: c._car_contradicted = lambda *a_, **k_: False if not cover: c.o["ev_batt_cover"] = False if mono_x is not None and mono_x != x: c.car_now = (lambda f=c.car_now: f() * mono_x / x) async def settle(): await orig() g = c.peak_guard red = [] if plant.t >= E - 130: red = [r_["id"] for r_ in c.checks() if r_["ok"] is False and not r_["warn"] and r_["id"] == "peak_guard"] errs = [m for m in ERR.rec[n_err[0]:] if "may not draw the battery lower" in m] n_err[0] = len(ERR.rec) cl = peakguard.claim(g) if g is not None else None tr.append({ "t": plant.t, "explains": c.car_explains, "lim": bool(g is not None and (g.floor_limited or g.saturated)), "within_aim": bool(g is not None and g.within_aim), "wants": bool(g is not None and g.engaged and (g.wanted_w or 0.0) > 0.0), "alarm": c._peak_floor_limited, "red": red, "err": errs, "w": c.car_alarm_w(), "batt": c.site_batt_w, "key": c._carq["key"], "block": (c._peak_proj_real.block_start if c._peak_proj_real is not None else None), "floor_w": g.floor_w if g is not None else None, "lo": getattr(cl, "lo", None), "sp": tuple(i.last_write for i in c.inverters)}) c.car_settle = settle ev = {0: hook} for t, fn in (extra or {}).items(): if t == 0: ev[0] = (lambda p, c, fn=fn: (hook(p, c), fn(p, c))) else: ev[t] = fn socs = soc or {"a": 19.0, "b": 19.0} s = sim if s is None: from chargersim import SimCharger s = SimCharger(setpoint_a=car_a) if x != 1: tick = s.tick s.tick = lambda secs=1.0: tick(secs * x) base, step = rig.BASE, s81.TICK rig.BASE, s81.TICK = base - timedelta(seconds=E), float(x) try: r = P.drive(house, dur=dur, rating=5000.0, soc=socs, cap=aim + MARGIN, phases=phases, n=2, plant_cls=cls, opts=OPTS, dev_w=5000.0, setpoint=car_a, user_a=car_a, mode=mode, events=ev, sim=s, plug=plug) finally: rig.BASE, s81.TICK = base, step return r, tr def alarms(r): """Seconds of each goodwe_peak_soc_floor notification.""" return [t for t, n in r["raised"] if n == FLOOR] def window(tr, t0, t1): return [x for x in tr if t0 <= x["t"] <= t1] def edges(tr): """Seconds at which the floor alarm goes False -> True.""" out, was = [], False for x in tr: if x["alarm"] and not was: out.append(x["t"]) was = x["alarm"] return out def red_secs(tr, t0=None, t1=None): t0 = E - 120 if t0 is None else t0 t1 = E + 900 if t1 is None else t1 return [x["t"] for x in window(tr, t0, t1) if x["red"]] def errors(tr): return [x["t"] for x in tr if x["err"]] def commands(r, tr): """A digest of every command: the units' setpoints, the charger's writes, and the guard's floor and claim per cycle (N4).""" h = hashlib.sha256() for u in sorted(r["plant"].hists): h.update(repr((u, r["plant"].hists[u])).encode()) h.update(repr(r["sim"].writes()).encode()) h.update(repr([(x["t"], x["floor_w"], x["lo"], x["sp"]) for x in tr]).encode()) return h.hexdigest()[:16] def energy_gap(at, secs=1): """The charger's energy entity is missing (unknown) for `secs` from `at`.""" def on(p, c): p.ch.no_energy = True def off(p, c): p.ch.no_energy = False return {at: on, at + secs: off} def restart(c): """A restart as the car side sees it: a fresh `car_init` and an empty corroboration history, and no floor alarm standing.""" mode, n, a = c.car_mode, c.car_n, c.car_a c.car_init(c.o, c.store) c.car_mode, c.car_n, c.car_a = mode, n, a c.car._hist.clear() c._peak_floor_limited = False