Compare commits

..
4 Commits
6 changed files with 12 additions and 355 deletions
-4
View File
@@ -1,9 +1,5 @@
# Changelog
### Not in a release yet
- When the add-on changes the car's phases while the batteries are at the peak reserve, there is no longer a false "Battery stopped limiting the peak" for a moment ([[EV-15]]).
## 0.24.0
**A minor bump: the add-on can now charge the car (Manual mode), and a car that alone takes the batteries to the peak reserve no longer raises a false peak alarm. Two new options were added, both with defaults, and none needs setting.**
@@ -120,21 +120,6 @@ up to 1.8 kW; the 40 Wh floor fixes that.)
the gaps seen on the rig, 150 to 250 s at 50 s sampling, and shorter than a
quarter) and a gap does not restart the 10 s
on-count. `car_explains`, which the alarms read, has no hold.
- **Our own phase change is not a reason to alarm** (EV-15). Rig, twice: at the
reserve, with the car covering, the add-on's 3 -> 1 switch set the car to 0 A.
A car that is not charging has no corroboration (`CarTracker._corr_note` clears
the window, `corroborated` is False), so `car_alarm_w()` was None, the car
explained nothing and `_car_need_excl` latched for the quarter: one
PEAK_GUARD_FLOOR_LIMITED and one `goodwe_peak_soc_floor`. Now, only for grading
(`car_cycle`), `ctl_car._car_own_pause` lets the car's fresh, not stuck figure
(`CarTracker.car_w_paused`, 0 W while paused) stand in without corroboration:
from our 0 A write (`seq` exists) until the current is set again, at most
`OWN_PAUSE_MAX_S` (85 s, the sequence's own waits), then at most one
corroboration window (60 s). It ends at once on Off, Stop, shadow, unplug,
another writer, or a refused select or write (`seq["failed"]`). The energy it
drew in the pause is kept apart (`ws_p`), so `car_exclude`, the guard's
input, the claim, floor and writes are unchanged. A house overload still fails
the test without the car, so it alarms as on Off.
- **Our own write is ours until its mute ends** (EV-12). The mute of the tracker's
own detector opens before the write and runs 15 s from when it returns, because
the read-back reaches the cycle while the write still waits for it.
-6
View File
@@ -125,7 +125,6 @@ class ManualWriter:
self.phase_fails = 0 # phase selects the charger did not take
self.phases_gave_up = False
self.undone = 0 # sequences undone before the select
self.phase_done_at = None # EV-15: our phase change ended well then
# ------------------------------------------------------------------ user
def user_changed(self) -> None:
@@ -297,7 +296,6 @@ class ManualWriter:
if not ok:
self._failed(now)
return
self.phase_done_at = None
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
"prev": cur}
@@ -338,7 +336,6 @@ class ManualWriter:
self.log.append(("phases", q["n"], now, ok))
q["stage"], q["t1"] = "settle", self.last_done # from its return
if not ok:
q["failed"] = True # EV-15: no grace for the alarm
# The charger did not take it: the car gets its current back
# on the old phases after the same SETTLE_S as a taken select
# (HA may have taken it and only the read-back be late), and
@@ -359,10 +356,7 @@ class ManualWriter:
# still wanted, and one that is in place is adopted.
self.seq, self.rev_applied, self.reapply = None, None, False
self.fails, self.blocked = 0, False
if not q.get("failed"):
self.phase_done_at = self.last_done # EV-15
return
q["failed"] = True # EV-15: a refused write ends it
q["tries"] += 1
if q["tries"] >= MAX_TRIES:
# Left at 0 A is the safe side; the next reading re-applies.
+1 -13
View File
@@ -800,20 +800,8 @@ class CarTracker:
EV-03 rules), not stuck after a write, corroborated by the energy meter
(`corroborated`), and never above what the read-back allows the car to
draw: an old or frozen figure must not hide a house overload."""
return self._capped_w(now, True)
def car_w_paused(self, now: float):
"""EV-15: the same figure as `car_w_trusted` without the energy-meter
corroboration, which a car held at 0 A by the add-on's own phase change
cannot give (the meter's window restarts when it stops charging). Fresh,
not stuck, and capped by the read-back. Only for grading the alarm
during that sequence (`ctl_car._car_own_pause`)."""
return self._capped_w(now, False)
def _capped_w(self, now: float, corroborate: bool):
w = self.car_w(now)
if w is None or self.stuck(now) \
or (corroborate and not self.corroborated(now)):
if w is None or self.stuck(now) or not self.corroborated(now):
return None
r = self.reading
a = r.allowed_a if r.allowed_a is not None else r.setpoint_a
+11 -52
View File
@@ -24,13 +24,6 @@ OVER_HOLD_S = peakguard.ALARM_HOLD_S
# the cause: longer than the gaps seen on the rig (150 to 250 s at 50 s
# sampling) and shorter than a quarter, or until the session really ends.
OVER_OFF_HOLD_S = 180.0
# EV-15: the longest our own phase change can take (0 A wait, settle, three
# tries of a write at 5 s apart and up to 10 s each, the select's own wait);
# the grace for the alarm never outlasts it, and after the current is set
# again it lasts at most one corroboration window.
OWN_PAUSE_MAX_S = (carmode.ZERO_WAIT_S + carmode.SETTLE_S
+ carmode.MAX_TRIES * 15.0 + 10.0)
OWN_PAUSE_TAIL_S = chargers.CORR_WINDOW_S
class CarMixin:
@@ -64,7 +57,7 @@ class CarMixin:
self._car_over_notified = None # the session a notice was raised for
self._car_session = 0
self._car_prev_state = None
self._carq = {"key": None, "ws": 0.0, "ws_p": 0.0, "mono": None}
self._carq = {"key": None, "ws": 0.0, "mono": None}
self._peak_proj_real = None
saved = data.get(CAR_PEAK_KEY)
self.car_peak_q = dict(saved) if isinstance(saved, dict) else {}
@@ -213,42 +206,17 @@ class CarMixin:
return None
return self.car.car_w_trusted(self.car_now())
def _car_own_pause(self, mono) -> bool:
"""EV-15: is the car held at 0 A by the add-on's OWN phase change (its
0 A write until the current is set again, then at most one
corroboration window)? No when it was aborted (Off, Stop, shadow,
unplug, another writer), a write was refused, or it ran past its own
maximum."""
wr = getattr(self, "car_writer", None)
if wr is None or (wr.seq is None and wr.phase_done_at is None):
return False
r = self.car.reading
if not (self.car_manual() and self.car_writing()
and r is not None and r.available and r.state != "A"):
return False
q = wr.seq
if q is not None:
return not q.get("failed") and 0.0 <= mono - q["t0"] \
<= OWN_PAUSE_MAX_S
return 0.0 <= mono - wr.phase_done_at <= OWN_PAUSE_TAIL_S
def _car_quarter(self, proj, w, mono, wg=None) -> None:
def _car_quarter(self, proj, w, mono) -> None:
"""The car's energy in the open quarter, for the average the guard's
house leaves out and for the peak line. `wg` (EV-15) is the figure for
grading during our own pause; its energy is kept apart (`ws_p`) so the
guard's input is unchanged."""
house leaves out and for the peak line."""
q = self._carq
key = None if proj is None else proj.block_start
last = q["mono"]
if key != q["key"]:
self._car_bank(q)
q["key"], q["ws"], q["ws_p"] = key, 0.0, 0.0
if key is not None and last is not None:
dt = min(max(mono - last, 0.0), 5.0)
if w is not None:
q["ws"] += float(w) * dt
elif wg is not None:
q["ws_p"] = q.get("ws_p", 0.0) + float(wg) * dt
q["key"], q["ws"] = key, 0.0
if key is not None and w is not None and last is not None:
q["ws"] += float(w) * min(max(mono - last, 0.0), 5.0)
q["mono"] = mono
def _car_bank(self, q) -> None:
@@ -265,17 +233,14 @@ class CarMixin:
del self.car_peak_q[k]
self.store.set(CAR_PEAK_KEY, dict(self.car_peak_q))
def car_avg_w(self, proj, w, graded=False) -> float:
def car_avg_w(self, proj, w) -> float:
"""The car's average over the whole open quarter: what it drew so far
and `w` for the rest. `graded` (EV-15) adds what it drew during our
own pause."""
and `w` for the rest."""
if proj is None or w is None:
return 0.0
left = max(0.0, QUARTER_S - float(proj.elapsed_s))
so_far = self._carq["ws"] if self._carq["key"] == proj.block_start \
else 0.0
if graded and self._carq["key"] == proj.block_start:
so_far += self._carq.get("ws_p", 0.0)
return (so_far + float(w) * left) / QUARTER_S
def car_exclude(self, proj, w):
@@ -299,7 +264,7 @@ class CarMixin:
the car asked for. Unchanged without a fresh car reading."""
if proj is None or w is None or proj.block_start is None:
return proj
avg = self.car_avg_w(proj, w, graded=True)
avg = self.car_avg_w(proj, w)
left = max(0.0, QUARTER_S - float(proj.elapsed_s))
held = float(proj.held_w)
done_ws = QUARTER_S * float(proj.projected_w) - max(held, 0.0) * left
@@ -315,19 +280,13 @@ class CarMixin:
`real_proj` is the projection WITH the car, whatever the guard saw."""
mono = self.car_now()
w = self.car_alarm_w()
# EV-15: the figure for grading only. Our own phase change holds the
# car at 0 A and the energy meter cannot corroborate it then, so for
# that bounded time its fresh, not stuck figure stands in.
wg = w
if w is None and self._car_own_pause(mono):
wg = self.car.car_w_paused(mono)
self._car_quarter(real_proj, w, mono, wg)
self._car_quarter(real_proj, w, mono)
self._car_session_tick(mono)
explains = over = False
if real_proj is not None and target_w is not None \
and real_proj.block_start is not None:
# EV-10: every cycle, so the latches do not depend on the option.
graded = self._car_explains_alarm(real_proj, guard, target_w, wg)
graded = self._car_explains_alarm(real_proj, guard, target_w, w)
if self.car_cover:
explains = over = graded
elif w is not None:
-265
View File
@@ -1,265 +0,0 @@
"""EV-15: the add-on's own phase change at the peak reserve raises no alarm.
`python3 -B test_ev15.py`
The rig (EV-10 and EV-10b, F-2): cover on, the batteries at the reserve, the car
charging and explaining the excess. The add-on's own 3 -> 1 phase switch sets
the car to 0 A; with the car not charging its figure is no longer corroborated
(`CarTracker.corroborated`), so `car_alarm_w()` is None, nothing is explained,
and PEAK_GUARD_FLOOR_LIMITED plus `goodwe_peak_soc_floor` fire. The rule: for
the add-on's own sequence only (`ctl_car._car_own_pause`, bounded) the car's
fresh, not stuck figure stands in for grading.
1. The rig shapes end to end through the car cycle: 3 -> 1 and 1 -> 3.
2. A house overload that starts during the sequence still alarms, as on Off.
3. Aborted (Off, Stop, unplug), refused, an outside writer: no grace.
4. The bounds, and the figure that stands in (stale, stuck: nothing).
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
"""
import asyncio
import logging
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, carmode, chargers as CH # noqa: E402
import ev04_peak as P # noqa: E402
import safety81_sim as s81 # noqa: E402
logging.disable(logging.CRITICAL)
fails = []
def check(name, cond):
print(f" {'ok ' if cond else 'FAIL'} {name}")
if not cond:
fails.append(name)
def at(t, fn):
return {"t": t, "fn": fn}
def run(house, cap, t_res, t_sw, new, *, extra=None, mode="manual",
sim_fn=None, dur=895, plug=True):
"""Reserve at `t_res`, our phase change to `new` at `t_sw`. Returns the
run, a per-second trace (second, own-pause, explains, red rows) and the
alarms."""
tr = []
def note(plant, c):
red = [x["id"] for x in c.checks()
if x["ok"] is False and not x["warn"]] \
if t_sw - 5 <= plant.t <= t_sw + 90 else []
g = c.peak_guard
lim = bool(g is not None and (g.floor_limited or g.saturated))
tr.append((plant.t, getattr(c, "_car_own_pause", lambda _t: False)(c.car_now()), c.car_explains,
red, plant.ch.power_w, plant.ch.state, lim))
def reserve(plant, c):
plant.soc = 19.0
plant.load = lambda t: house + plant.ch.power_w
def switch(plant, c):
asyncio.get_event_loop().create_task(
c.handle_action("car_phases", value=new))
ev = {t: note for t in range(0, dur)}
ev[t_res] = lambda p, c: (reserve(p, c), note(p, c))
ev[t_sw] = lambda p, c: (switch(p, c), note(p, c))
for t, fn in (extra or {}).items():
prev = ev.get(t, note)
ev[t] = (lambda p, c, prev=prev, fn=fn: (fn(p, c), prev(p, c)))
sim = None
if sim_fn is not None:
from chargersim import SimCharger
sim = SimCharger(setpoint_a=16)
sim_fn(sim)
r = P.drive(s81.constant(house), dur=dur, rating=12000.0, soc=60.0,
cap=cap, phases=(3 if new == 1 else 1), user_a=16, setpoint=16,
mode=mode, events=ev, sim=sim, plug=plug)
return r, tr, P.ids(r, *P.ALARMS)
def reds(tr):
return [x for x in tr if x[3]]
# =========================================================================== #
print("1. THE RIG SHAPES THROUGH THE CAR CYCLE")
# =========================================================================== #
SHAPES = (
("EV-10 shape: house 3 kW, car 11 kW, aim 6 kW, 3 -> 1",
3000.0, 6050.0, 300, 600, 1),
("EV-10b shape: a 9411 W limit, 3 -> 1", 2000.0, 9461.0, 300, 600, 1),
("1 -> 3 (the car 3.7 kW, then 11 kW), aim 5 kW", 2500.0, 5050.0,
100, 600, 3),
)
for name, house, cap, t_res, t_sw, new in SHAPES:
r, tr, al = run(house, cap, t_res, t_sw, new)
c, sim = r["c"], r["sim"]
sw = [x for x in sim.writes() if x[1] == "phases"]
check(f"{name}: the car at the reserve covers, and the add-on's own "
f"sequence ran (0 A, select, the current back)",
len(sw) == 1 and [x[2] for x in sim.writes("current")][-2:]
== [0.0, 16.0] and sim.phases_allowed == new)
pause = [x for x in tr if x[1]]
check(f"{name}: the own-pause grace was on during it, and ended",
len(pause) >= 10 and not any(x[1] for x in tr[-1:])
and (pause[-1][0] - pause[0][0])
<= getattr(ctl_car, "OWN_PAUSE_MAX_S", 0)
+ getattr(ctl_car, "OWN_PAUSE_TAIL_S", 0))
check(f"{name}: no PEAK_GUARD_FLOOR_LIMITED / saturated, no "
f"goodwe_peak_soc_floor notification", al == [])
check(f"{name}: no red row in any sample around the switch",
reds(tr) == [])
limited = [x for x in tr if x[1] and x[6]]
check(f"{name}: in every cycle of the sequence in which the guard is "
f"limited (the cycle of the rig's alarm among them) the car "
f"explains it", len(limited) >= 1 and all(x[2] for x in limited)
and any(x[2] for x in tr if x[0] == t_sw + 1))
check(f"{name}: and in every limited cycle after it, to the quarter's end",
all(x[2] for x in tr if x[0] >= t_sw and x[6]))
# =========================================================================== #
print("\n2. A HOUSE OVERLOAD DURING THE SEQUENCE STILL ALARMS")
# =========================================================================== #
def overload(plant, c):
plant.load = lambda t: 25000.0 + plant.ch.power_w
r, tr, al = run(3000.0, 6050.0, 300, 600, 1, extra={606: overload})
ro, tro, alo = run(3000.0, 6050.0, 300, 600, 1, extra={606: overload},
mode="off", plug=False)
rn, trn, aln = run(3000.0, 6050.0, 300, 900, 1, extra={606: overload})
check("PRECONDITION: on Off (no car) the same load alarms, and in Manual "
"with no phase change", alo != [] and aln != [])
check("a 25 kW house overload that starts 6 s into the sequence (the car "
"paused): the alarm fires", al != [])
print(f" alarm seconds: in the sequence {[t for t, _ in al]}, Off without "
f"the car {[t for t, _ in alo]}, Manual with no phase change "
f"{[t for t, _ in aln]}")
check("...at the same second as on Off and as in Manual with no phase change",
bool(al) and bool(alo) and bool(aln)
and al[0][0] == alo[0][0] == aln[0][0])
check("...and the car does not explain it (during the sequence too)",
not any(x[2] for x in tr if 640 <= x[0] <= 660))
# =========================================================================== #
print("\n3. ABORTED, REFUSED, OUTSIDE: NO GRACE AFTER IT")
# =========================================================================== #
def hit(res, t0, secs):
return [x for x in res if t0 <= x[0] <= t0 + secs and x[1]]
def off_now(plant, c):
asyncio.get_event_loop().create_task(c.handle_action("car_mode",
value="off"))
def stop_now(plant, c):
c.auto = False
def unplug(plant, c):
plant.ch.unplug()
slow = lambda s: setattr(s, "stop_delay_s", 8.0) # noqa: E731
for what, fn in (("Off", off_now), ("Stop", stop_now), ("unplug", unplug)):
r, tr, al = run(3000.0, 6050.0, 300, 600, 1, extra={602: fn},
sim_fn=slow)
check(f"{what} 2 s into the sequence: the grace is off from the next "
f"cycle on", not hit(tr, 604, 200)
and any(x[1] for x in tr if 600 <= x[0] <= 602))
def refuse_phases(sim):
sim.request_phases = lambda n: False
r, tr, al = run(3000.0, 6050.0, 300, 600, 1, sim_fn=refuse_phases)
check("the select is refused: the grace ends at once (no cycle of it after "
"the refusal), the current comes back",
len([x for x in r["sim"].writes("current")]) >= 2
and not hit(tr, 606, 200))
def outside_zero(plant, c):
plant.ch.set_current(0.0)
r2, tr2, al2 = run(3000.0, 6050.0, 300, 900, 1, extra={602: outside_zero})
check("an outside writer's 0 A: no grace, and the normal grading (no car "
"power: nothing explained) raises the alarm as before",
not any(x[1] for x in tr2) and not any(x[2] for x in tr2
if 610 <= x[0] <= 700)
and al2 != [])
# =========================================================================== #
print("\n4. THE BOUNDS AND THE FIGURE THAT STANDS IN")
# =========================================================================== #
class _C(ctl_car.CarMixin):
"""The mixin with just what `_car_own_pause` reads."""
def __init__(self):
self.o = {}
self.car_init({}, type("S", (), {"data": {}, "set": lambda s, k, v: 0})())
self.car_mode = carmode.MANUAL
self.auto, self.shadow = True, False
self.inverters, self.site_sign_wd = [], type("W", (), {"tripped": False})()
self.circ_wd = type("W", (), {"tripped": False})()
self.charger = type("H", (), {"configured": lambda s: True})()
self.car = CH.CarTracker()
self.car.reading = CH.ChargerReading(available=True, state="B")
c = _C()
c.car_writer.seq = {"stage": "settle", "t0": 100.0, "n": 1, "tries": 0,
"prev": 16.0}
M = ctl_car.OWN_PAUSE_MAX_S
check("bound: the sequence's own maximum is its waits (0 A wait, settle, "
"three tries at 15 s, the select) and no more",
M == carmode.ZERO_WAIT_S + carmode.SETTLE_S + carmode.MAX_TRIES * 15.0
+ 10.0 and ctl_car.OWN_PAUSE_TAIL_S == CH.CORR_WINDOW_S)
check("bound: on at the 0 A write and up to the maximum",
c._car_own_pause(100.0) and c._car_own_pause(100.0 + M))
check("bound: off one second past it", not c._car_own_pause(101.0 + M))
c.car_writer.seq = None
c.car_writer.phase_done_at = 200.0
T = ctl_car.OWN_PAUSE_TAIL_S
check("bound: after the current is set again it lasts one corroboration "
"window", c._car_own_pause(200.0 + T) and not c._car_own_pause(201.0 + T))
c.car_writer.phase_done_at = None
check("no sequence and none just done: no grace", not c._car_own_pause(100.0))
c.car_writer.seq = {"stage": "settle", "t0": 100.0, "failed": True}
check("a refused write marks the sequence: no grace", not c._car_own_pause(110.0))
c.car_writer.seq = {"stage": "settle", "t0": 100.0}
c.car_mode = carmode.OFF
check("Off: no grace", not c._car_own_pause(110.0))
c.car_mode, c.shadow = carmode.MANUAL, True
check("shadow mode: no grace", not c._car_own_pause(110.0))
c.shadow, c.auto = False, False
check("control stopped: no grace", not c._car_own_pause(110.0))
c.auto = True
c.car.reading = CH.ChargerReading(available=True, state="A")
check("unplugged: no grace", not c._car_own_pause(110.0))
c.car.reading = CH.ChargerReading(available=True, state="B")
check("PRECONDITION: the same state is on", c._car_own_pause(110.0))
tk = CH.CarTracker()
tk.reading = CH.ChargerReading(available=True, state="B", power_w=500.0,
allowed_a=16.0, phases_allowed=1)
tk.last_ok = 0.0
check("the stand-in figure is the fresh reading, capped by the read-back",
tk.car_w_paused(5.0) == 500.0 and tk.car_w_trusted(5.0) is None)
check("a stale reading stands in for nothing", tk.car_w_paused(100.0) is None)
tk.stuck_now = True
check("a stuck reading stands in for nothing", tk.car_w_paused(5.0) is None)
print()
if fails:
print(f"FAIL: {len(fails)} check(s)")
for f in fails:
print(" -", f)
sys.exit(1)
print("ok: EV-15")