Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe5e3ee477 | ||
|
|
8a40343a84 | ||
|
|
0f3d5d75e5 | ||
|
|
9b09158ef8 | ||
|
|
7d1ed1bbcf | ||
|
|
de733f44bf | ||
|
|
7710d45393 | ||
|
|
e0e51dac12 | ||
|
|
b7c91ff746 | ||
|
|
c7b1b7dbd1 | ||
|
|
19c5d5a61e | ||
|
|
bba10f44c3 | ||
|
|
392f9c2b57 | ||
|
|
5ddabfbd93 | ||
|
|
1c387441c7 | ||
|
|
5bd2b1ec97 | ||
|
|
2e09622fe1 | ||
|
|
7628cacdb7 | ||
|
|
e522e6ffbb | ||
|
|
e83b2e315b | ||
|
|
009393a5ee | ||
|
|
1b909fb7bd |
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
### Not in a release yet
|
### Not in a release yet
|
||||||
|
|
||||||
|
- **Solar no longer writes over another writer's car current or phases.** If something else changes the car's current or its phases, also in the middle of a phase change, the add-on writes nothing over it. After 30 seconds it stops writing until you press Solar, and warns CHARGER_OTHER once. Manual does the same for a current changed during its own phase change ([[EV-22]]).
|
||||||
|
- **A car phase change whose current the charger refuses no longer sends that current five times.** After three refused tries the add-on stops at once and warns CHARGER_REFUSED; the car stays at 0 A until you change something. A value you change meanwhile gets its own three tries ([[EV-59]]).
|
||||||
- **A car current the add-on cannot send because of an error is no longer sent again every second.** It counts as a write the charger did not take: 3 tries a minute apart, then the add-on stops and warns CHARGER_REFUSED. The error is logged once per current ([[EV-56]]).
|
- **A car current the add-on cannot send because of an error is no longer sent again every second.** It counts as a write the charger did not take: 3 tries a minute apart, then the add-on stops and warns CHARGER_REFUSED. The error is logged once per current ([[EV-56]]).
|
||||||
- **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]]).
|
- **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]]).
|
- **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]]).
|
||||||
|
|||||||
@@ -3370,10 +3370,11 @@ changes at most once per 30 seconds and only by 1 A or more.
|
|||||||
be charging* follows.
|
be charging* follows.
|
||||||
- **Shadow mode** writes nothing but that one 0 A; a start in shadow mode writes
|
- **Shadow mode** writes nothing but that one 0 A; a start in shadow mode writes
|
||||||
nothing at all. The card says what Solar would set.
|
nothing at all. The card says what Solar would set.
|
||||||
- **Another writer.** If the charger shows a current Solar did not set for 30
|
- **Another writer.** If the charger shows a current or a number of phases
|
||||||
seconds, Solar writes nothing over it (also no 0 A), shows an amber row and
|
that Solar did not set, Solar writes nothing over it from the first moment,
|
||||||
logs one warning, until you press Solar again or the charger shows Solar's
|
also in the middle of a phase change. After 30 seconds it writes nothing more
|
||||||
value.
|
(also no 0 A), shows an amber row and logs one warning, until you press Solar
|
||||||
|
again or the charger shows Solar's own current and phases.
|
||||||
- **The peak limit: the car is cut first.** When the 15-minute period heads
|
- **The peak limit: the car is cut first.** When the 15-minute period heads
|
||||||
over the peak limit, Solar lowers the car first, also while the batteries
|
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.
|
could instead charge less: by the excess, to 0 A when less than 6 A would be left.
|
||||||
|
|||||||
@@ -149,18 +149,31 @@ class ManualWriter:
|
|||||||
self._r = None # the latest reading, for the phase count
|
self._r = None # the latest reading, for the phase count
|
||||||
self._late = None # (a, was, why, n) of a write not taken
|
self._late = None # (a, was, why, n) of a write not taken
|
||||||
self._rec_a = None # EV-56: the raised value already logged
|
self._rec_a = None # EV-56: the raised value already logged
|
||||||
|
self._close_k = 0 # EV-59: not-taken closes of the value owed
|
||||||
|
self._ph_diff = False # EV-22: the phases differ from our own
|
||||||
|
# (Solar only; Manual never sets it)
|
||||||
|
self._carry = [] # EV-69: the closes an ended sequence tried
|
||||||
|
|
||||||
# ------------------------------------------------------------------ user
|
# ------------------------------------------------------------------ user
|
||||||
def user_changed(self) -> None:
|
def user_changed(self) -> None:
|
||||||
"""The user changed the mode or a value: one more write is allowed,
|
"""The user changed the mode or a value: one more write is allowed,
|
||||||
and another writer's hold is lifted."""
|
and another writer's hold is lifted. EV-22 (DA1): a change that lifts
|
||||||
|
a difference inside a phase change ends the change at its 0 A; the
|
||||||
|
raise check never holds over the value the user's change took."""
|
||||||
|
if self.seq is not None:
|
||||||
|
if self._other_stands():
|
||||||
|
self.seq = None
|
||||||
|
else:
|
||||||
|
self.seq["pressed"] = True # the raise check holds off
|
||||||
self.boot = False
|
self.boot = False
|
||||||
self.rev_applied = None
|
self.rev_applied = None
|
||||||
self.hold = self.other = False
|
self.hold = self.other = False
|
||||||
self.mismatch_since = None
|
self.mismatch_since = None
|
||||||
self.fails, self.fail_at, self.gave_up = 0, None, False
|
self.fails, self.fail_at, self.gave_up = 0, None, False
|
||||||
|
self._close_k = 0 # EV-59
|
||||||
self.phase_fails, self.phases_gave_up = 0, False
|
self.phase_fails, self.phases_gave_up = 0, False
|
||||||
self.attempted_a = self.prior_a = None
|
self.attempted_a = self.prior_a = None
|
||||||
|
self._carry = [] # EV-69: a user change ends the carry
|
||||||
self._late = None # EV-52: that request is not current now
|
self._late = None # EV-52: that request is not current now
|
||||||
self._rec_a = None # EV-56 (G2): a raise is logged again
|
self._rec_a = None # EV-56 (G2): a raise is logged again
|
||||||
|
|
||||||
@@ -190,6 +203,9 @@ class ManualWriter:
|
|||||||
self._rec_a = None # EV-56 (G2): logged again
|
self._rec_a = None # EV-56 (G2): logged again
|
||||||
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
||||||
if self.seq is not None:
|
if self.seq is not None:
|
||||||
|
# EV-22 (C7): the watch runs in every step of a phase change; the
|
||||||
|
# change's own values count as own (`_own_values`).
|
||||||
|
self._watch(cur, now)
|
||||||
if self.seq["stage"] in ("zero", "select") \
|
if self.seq["stage"] in ("zero", "select") \
|
||||||
and (mode != MANUAL or not writing):
|
and (mode != MANUAL or not writing):
|
||||||
await self._undo(drv, now, tracker, clamp, shadow)
|
await self._undo(drv, now, tracker, clamp, shadow)
|
||||||
@@ -223,8 +239,10 @@ class ManualWriter:
|
|||||||
if not (phases_need or cur_need):
|
if not (phases_need or cur_need):
|
||||||
self.rev_applied, self.reapply = rev, False
|
self.rev_applied, self.reapply = rev, False
|
||||||
self.fails, self.blocked = 0, False
|
self.fails, self.blocked = 0, False
|
||||||
|
self._close_k = 0
|
||||||
if cur is not None:
|
if cur is not None:
|
||||||
self.last_a = cur # adopt what is already set
|
self.last_a = cur # adopt what is already set
|
||||||
|
self._carry = [] # EV-69: an own take ends the carry
|
||||||
# EV-52 (PM Q2): a write taken late is logged once, here.
|
# EV-52 (PM Q2): a write taken late is logged once, here.
|
||||||
late, self._late = self._late, None
|
late, self._late = self._late, None
|
||||||
if late is not None and abs(cur - float(late[0])) <= TOL_A:
|
if late is not None and abs(cur - float(late[0])) <= TOL_A:
|
||||||
@@ -249,6 +267,7 @@ class ManualWriter:
|
|||||||
self._failed(now)
|
self._failed(now)
|
||||||
return
|
return
|
||||||
self.fails, self.fail_at = 0, None
|
self.fails, self.fail_at = 0, None
|
||||||
|
self._close_k = 0
|
||||||
if not phases_need:
|
if not phases_need:
|
||||||
self.rev_applied, self.reapply = rev, False
|
self.rev_applied, self.reapply = rev, False
|
||||||
|
|
||||||
@@ -262,26 +281,86 @@ class ManualWriter:
|
|||||||
"stops asking until you change it: CHARGER_REFUSED.")
|
"stops asking until you change it: CHARGER_REFUSED.")
|
||||||
_LOG.debug("The charger refused the current %d times.", self.fails)
|
_LOG.debug("The charger refused the current %d times.", self.fails)
|
||||||
|
|
||||||
def _watch(self, cur, now) -> None:
|
def _close_end(self, now) -> None:
|
||||||
"""Is the read-back what we wrote? A difference that stands for
|
"""EV-59: the closing current was refused MAX_TRIES times in this
|
||||||
`WRITER_S` is another writer."""
|
sequence. The value owed has had `_close_k` not-taken closes since the
|
||||||
known = [x for x in (self.last_a, self.attempted_a, self.prior_a)
|
last user change: `fails` is that count, so the give-up comes only
|
||||||
|
when the value has used all its tries; else the normal path gives the
|
||||||
|
rest."""
|
||||||
|
self.fails = max(min(self._close_k, MAX_TRIES) - 1, 0)
|
||||||
|
self._failed(now)
|
||||||
|
|
||||||
|
def _other_stands(self) -> bool:
|
||||||
|
"""EV-22: another writer's value is held, or its count is running:
|
||||||
|
nothing non-zero is written over it."""
|
||||||
|
return bool(self.hold or self.mismatch_since is not None)
|
||||||
|
|
||||||
|
def _own_values(self) -> list:
|
||||||
|
"""The currents that are ours: what we wrote, tried or saw before a
|
||||||
|
try, and (EV-22, C7) every value of the phase change under way: its
|
||||||
|
0 A and each closing current it tried (also after a user change
|
||||||
|
cleared `attempted_a`)."""
|
||||||
|
vals = [x for x in (self.last_a, self.attempted_a, self.prior_a)
|
||||||
if x is not None]
|
if x is not None]
|
||||||
if not known or cur is None:
|
if self.seq is not None:
|
||||||
self.mismatch_since = None
|
vals += self.seq.get("own", ())
|
||||||
return
|
return vals + self._carry
|
||||||
if any(abs(cur - k) <= TOL_A for k in known):
|
|
||||||
self.mismatch_since = None
|
def _carry_ok(self) -> bool:
|
||||||
if self.hold:
|
"""EV-69: may an ended sequence's values be carried? Manual: yes."""
|
||||||
self.hold = self.other = False
|
return True
|
||||||
return
|
|
||||||
|
def _carry_end(self, q) -> None:
|
||||||
|
"""EV-69 (OQ1, OQ2): a sequence ended (MAX_TRIES, or Solar's EV-60 cap
|
||||||
|
end): every value it tried, its 0 A too, stays own on the lifetime of
|
||||||
|
`attempted_a`/`prior_a`, for a late take of an earlier close. Not when
|
||||||
|
the end's own value is already taken (`_carry_ok`). It ends at an own
|
||||||
|
take, any own current write, a user change, a hold, Solar's return."""
|
||||||
|
self._carry = list(q.get("own", ())) if self._carry_ok() else []
|
||||||
|
|
||||||
|
def _carried_take(self) -> None:
|
||||||
|
"""EV-69 (GUR): the charger shows a carried close. Own; the carry
|
||||||
|
stays. Manual: nothing changes."""
|
||||||
|
|
||||||
|
def _watch(self, cur, now, judge=True) -> None:
|
||||||
|
"""Is the read-back what we wrote? A difference that stands for
|
||||||
|
`WRITER_S` is another writer. EV-22: one count and one hold for the
|
||||||
|
current and (Solar) the phases; `judge=False`: the reading is from
|
||||||
|
before our own write of this step, so the current is not judged and
|
||||||
|
the count stands."""
|
||||||
|
known, diff = [], None
|
||||||
|
if cur is None:
|
||||||
|
judge = False # an unknown read: the count neither starts
|
||||||
|
# nor clears (phases are still judged)
|
||||||
|
if judge:
|
||||||
|
known = self._own_values()
|
||||||
|
if known and cur is not None:
|
||||||
|
diff = not any(abs(cur - k) <= TOL_A for k in known)
|
||||||
|
if not diff and cur > TOL_A and any(
|
||||||
|
abs(cur - k) <= TOL_A for k in self._carry):
|
||||||
|
self._carried_take()
|
||||||
|
if diff or self._ph_diff:
|
||||||
if self.mismatch_since is None:
|
if self.mismatch_since is None:
|
||||||
self.mismatch_since = now
|
self.mismatch_since = now
|
||||||
elif now - self.mismatch_since >= WRITER_S and not self.hold:
|
elif now - self.mismatch_since >= WRITER_S and not self.hold:
|
||||||
self.hold = self.other = True
|
self.hold = self.other = True
|
||||||
_LOG.info("Something else changes the charger (read-back %.0f A, "
|
self._carry = [] # EV-69: never own after a hold
|
||||||
"the add-on set %.0f A), so the add-on stops writing "
|
if diff:
|
||||||
"to it until you change it.", cur, known[0])
|
_LOG.info("Something else changes the charger (read-back "
|
||||||
|
"%.0f A, the add-on set %.0f A), so the add-on "
|
||||||
|
"stops writing to it until you change it.",
|
||||||
|
cur, known[0])
|
||||||
|
else:
|
||||||
|
_LOG.info("Something else changes the charger (the "
|
||||||
|
"phases are not the ones the add-on chose), so "
|
||||||
|
"the add-on stops writing to it until you "
|
||||||
|
"change it.")
|
||||||
|
return
|
||||||
|
if not judge:
|
||||||
|
return
|
||||||
|
self.mismatch_since = None
|
||||||
|
if diff is False and self.hold:
|
||||||
|
self.hold = self.other = False
|
||||||
|
|
||||||
# ----------------------------------------------------- EV-52: the info line
|
# ----------------------------------------------------- EV-52: the info line
|
||||||
def _why_default(self) -> str:
|
def _why_default(self) -> str:
|
||||||
@@ -326,6 +405,7 @@ class ManualWriter:
|
|||||||
# EV-56: a raise at shutdown is left to the caller (CHARGER_RESTORE).
|
# EV-56: a raise at shutdown is left to the caller (CHARGER_RESTORE).
|
||||||
strict = kw.pop("strict", False)
|
strict = kw.pop("strict", False)
|
||||||
self._late = None
|
self._late = None
|
||||||
|
self._carry = [] # EV-69: a new own write ends the carry
|
||||||
if self._rec_a is not None and abs(self._rec_a - float(a)) > TOL_A:
|
if self._rec_a is not None and abs(self._rec_a - float(a)) > TOL_A:
|
||||||
self._rec_a = None # EV-56 (G2): another value
|
self._rec_a = None # EV-56 (G2): another value
|
||||||
tracker.begin_write() # EV-12: the read-back is ours
|
tracker.begin_write() # EV-12: the read-back is ours
|
||||||
@@ -397,7 +477,8 @@ class ManualWriter:
|
|||||||
self.undone += 1
|
self.undone += 1
|
||||||
self.rev_applied, self.reapply = None, True
|
self.rev_applied, self.reapply = None, True
|
||||||
a = self._restore_a(q.get("prev"), clamp)
|
a = self._restore_a(q.get("prev"), clamp)
|
||||||
if a is not None:
|
if a is not None and not self._other_stands(): # EV-22: not over theirs
|
||||||
|
q.setdefault("own", []).append(a)
|
||||||
await self._write(drv, a, 0.0, now, tracker, why="Manual")
|
await self._write(drv, a, 0.0, now, tracker, why="Manual")
|
||||||
|
|
||||||
async def _begin(self, drv, r, cur, n, now, tracker) -> None:
|
async def _begin(self, drv, r, cur, n, now, tracker) -> None:
|
||||||
@@ -415,7 +496,7 @@ class ManualWriter:
|
|||||||
self._failed(now)
|
self._failed(now)
|
||||||
return
|
return
|
||||||
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
|
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
|
||||||
"prev": cur}
|
"prev": cur, "own": [0.0]}
|
||||||
|
|
||||||
async def abandon(self, drv, now, tracker, clamp=None) -> None:
|
async def abandon(self, drv, now, tracker, clamp=None) -> None:
|
||||||
"""The add-on is stopping in the middle of a phase change: give the car
|
"""The add-on is stopping in the middle of a phase change: give the car
|
||||||
@@ -423,13 +504,22 @@ class ManualWriter:
|
|||||||
like every write. The phases stay as the select left them."""
|
like every write. The phases stay as the select left them."""
|
||||||
q, self.seq = self.seq, None
|
q, self.seq = self.seq, None
|
||||||
a = None if q is None else self._restore_a(q.get("prev"), clamp)
|
a = None if q is None else self._restore_a(q.get("prev"), clamp)
|
||||||
if a is not None:
|
if a is not None and not self._other_stands(): # EV-22: not over theirs
|
||||||
self._clock = self._clock or (lambda: now)
|
self._clock = self._clock or (lambda: now)
|
||||||
await self._write(drv, a, 0.0, now, tracker, why="shutdown",
|
await self._write(drv, a, 0.0, now, tracker, why="shutdown",
|
||||||
strict=True)
|
strict=True)
|
||||||
|
|
||||||
|
def _select_try(self, n, ok) -> None:
|
||||||
|
"""EV-22: a phase select of ours went out and returned (Solar's
|
||||||
|
window and own phases; Manual does not judge phases)."""
|
||||||
|
|
||||||
|
def _took_as_is(self) -> None:
|
||||||
|
"""EV-22 (DA1): a user's change took the charger's value as it is
|
||||||
|
(Solar forgets what it sent)."""
|
||||||
|
|
||||||
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
|
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
|
||||||
q = self.seq
|
q = self.seq
|
||||||
|
pressed = q.pop("pressed", False) # covers the first reading only
|
||||||
if q["stage"] in ("zero", "select") and cur is not None \
|
if q["stage"] in ("zero", "select") and cur is not None \
|
||||||
and cur >= CH.MIN_A:
|
and cur >= CH.MIN_A:
|
||||||
# Something else raised the current while the car was being
|
# Something else raised the current while the car was being
|
||||||
@@ -437,11 +527,23 @@ class ManualWriter:
|
|||||||
# change, and leave the charger to whoever set it until the user
|
# change, and leave the charger to whoever set it until the user
|
||||||
# changes something.
|
# changes something.
|
||||||
self.seq = None
|
self.seq = None
|
||||||
self.hold = self.other = True
|
|
||||||
self.last_a = self.attempted_a = self.prior_a = None
|
self.last_a = self.attempted_a = self.prior_a = None
|
||||||
|
if pressed:
|
||||||
|
# EV-22 (DA1): the user's change came during this change and
|
||||||
|
# this is the first reading judged after it: the charger is
|
||||||
|
# taken as it is, never held over that value. A later raise
|
||||||
|
# is held as ever.
|
||||||
|
self._took_as_is()
|
||||||
|
return
|
||||||
|
self.hold = self.other = True
|
||||||
|
self._carry = []
|
||||||
_LOG.info("Something else raised the charger's current during a "
|
_LOG.info("Something else raised the charger's current during a "
|
||||||
"phase change, so the phases were not touched.")
|
"phase change, so the phases were not touched.")
|
||||||
return
|
return
|
||||||
|
if self._other_stands():
|
||||||
|
# EV-22 (C7): another writer's value stands (its count runs, or
|
||||||
|
# it is held): no select, no restore, no closing current over it.
|
||||||
|
return
|
||||||
if q["stage"] == "zero":
|
if q["stage"] == "zero":
|
||||||
# A power reading decides; only without one does mode3 (not C,
|
# A power reading decides; only without one does mode3 (not C,
|
||||||
# not D) say the car is quiet. Still drawing at the timeout: no
|
# not D) say the car is quiet. Still drawing at the timeout: no
|
||||||
@@ -473,6 +575,7 @@ class ManualWriter:
|
|||||||
self.last_switch = now
|
self.last_switch = now
|
||||||
self.log.append(("phases", q["n"], now, ok))
|
self.log.append(("phases", q["n"], now, ok))
|
||||||
q["stage"], q["t1"] = "settle", self.last_done # from its return
|
q["stage"], q["t1"] = "settle", self.last_done # from its return
|
||||||
|
self._select_try(q["n"], bool(ok))
|
||||||
if not ok:
|
if not ok:
|
||||||
q["failed"] = True # EV-15: no grace for the alarm
|
q["failed"] = True # EV-15: no grace for the alarm
|
||||||
# The charger did not take it: the car gets its current back
|
# The charger did not take it: the car gets its current back
|
||||||
@@ -493,6 +596,7 @@ class ManualWriter:
|
|||||||
# on whether the phases changed); Manual a number, as before.
|
# on whether the phases changed); Manual a number, as before.
|
||||||
want = want_a(q) if callable(want_a) else want_a
|
want = want_a(q) if callable(want_a) else want_a
|
||||||
a = min(max(float(want), CH.MIN_A), hi)
|
a = min(max(float(want), CH.MIN_A), hi)
|
||||||
|
q.setdefault("own", []).append(a) # EV-22: a value we tried is ours
|
||||||
if await self._write(drv, a, 0.0, now, tracker,
|
if await self._write(drv, a, 0.0, now, tracker,
|
||||||
why=self._close_why(q),
|
why=self._close_why(q),
|
||||||
n=q["n"] if q.get("sel_ok") else None):
|
n=q["n"] if q.get("sel_ok") else None):
|
||||||
@@ -500,15 +604,18 @@ class ManualWriter:
|
|||||||
# still wanted, and one that is in place is adopted.
|
# still wanted, and one that is in place is adopted.
|
||||||
self.seq, self.rev_applied, self.reapply = None, None, False
|
self.seq, self.rev_applied, self.reapply = None, None, False
|
||||||
self.fails, self.blocked = 0, False
|
self.fails, self.blocked = 0, False
|
||||||
|
self._close_k = 0
|
||||||
if not q.get("failed"):
|
if not q.get("failed"):
|
||||||
self.phase_done_at = self.last_done # EV-15
|
self.phase_done_at = self.last_done # EV-15
|
||||||
return
|
return
|
||||||
q["failed"] = True # EV-15: a refused write ends it
|
q["failed"] = True # EV-15: a refused write ends it
|
||||||
q["tries"] += 1
|
q["tries"] += 1
|
||||||
|
self._close_k += 1 # EV-59: read by Manual's end only
|
||||||
if q["tries"] >= MAX_TRIES:
|
if q["tries"] >= MAX_TRIES:
|
||||||
# Left at 0 A is the safe side; the next reading re-applies.
|
# Left at 0 A is the safe side; the next reading re-applies.
|
||||||
|
self._carry_end(q) # EV-69: the closes tried stay own
|
||||||
self.seq, self.last_a, self.reapply = None, None, True
|
self.seq, self.last_a, self.reapply = None, None, True
|
||||||
self._failed(now)
|
self._close_end(now)
|
||||||
self.rev_applied = None
|
self.rev_applied = None
|
||||||
return
|
return
|
||||||
q["t1"] = now - SETTLE_S + 5.0 # again in 5 s
|
q["t1"] = now - SETTLE_S + 5.0 # again in 5 s
|
||||||
@@ -825,6 +932,11 @@ class SolarPlan:
|
|||||||
self.a, self.set_at, self.last_dir = CH.MIN_A, now, -1
|
self.a, self.set_at, self.last_dir = CH.MIN_A, now, -1
|
||||||
|
|
||||||
|
|
||||||
|
class _CloseHeld(Exception):
|
||||||
|
"""EV-60: Solar's cut gate holds the close (raised inside `_advance`'s
|
||||||
|
want-a call, caught in `SolarWriter._advance`; never leaves it)."""
|
||||||
|
|
||||||
|
|
||||||
class SolarWriter(ManualWriter):
|
class SolarWriter(ManualWriter):
|
||||||
"""What Solar does to the charger, one `step()` per cycle. It shares
|
"""What Solar does to the charger, one `step()` per cycle. It shares
|
||||||
ManualWriter's write, phase sequence and other-writer watch.
|
ManualWriter's write, phase sequence and other-writer watch.
|
||||||
@@ -886,6 +998,15 @@ class SolarWriter(ManualWriter):
|
|||||||
self.cut_warned = False # ... and its one CHARGER_REFUSED was given
|
self.cut_warned = False # ... and its one CHARGER_REFUSED was given
|
||||||
self.sent_cut = False # `sent_a` went out as a cut try
|
self.sent_cut = False # `sent_a` went out as a cut try
|
||||||
self.refused_cut = None # a cut value the charger did not take
|
self.refused_cut = None # a cut value the charger did not take
|
||||||
|
self._cap_end = False # EV-60: a capped close ended the change
|
||||||
|
# EV-22 (D4): the phases Solar itself chose. `_own_n`: the last it
|
||||||
|
# TOOK (or the start state); `_sel_n` and `_win_t1`: its latest
|
||||||
|
# select try and when that try returned; SETTLE_S after it (and the
|
||||||
|
# one step that closes there, `_win_last`) a read-back is not judged.
|
||||||
|
self._own_n = None
|
||||||
|
self._sel_n = None
|
||||||
|
self._win_t1 = None
|
||||||
|
self._win_last = False
|
||||||
|
|
||||||
def owe_start(self) -> None:
|
def owe_start(self) -> None:
|
||||||
"""C1: the add-on starts in Off while an exit 0 A of its own was still
|
"""C1: the add-on starts in Off while an exit 0 A of its own was still
|
||||||
@@ -988,10 +1109,16 @@ class SolarWriter(ManualWriter):
|
|||||||
"""The user PRESSED SOLAR: another writer's hold is lifted and Solar
|
"""The user PRESSED SOLAR: another writer's hold is lifted and Solar
|
||||||
takes the charger as it is (its value is no longer a difference);
|
takes the charger as it is (its value is no longer a difference);
|
||||||
Solar's own value is decided and written afresh."""
|
Solar's own value is decided and written afresh."""
|
||||||
held = self.hold or self.mismatch_since is not None
|
held = self._other_stands()
|
||||||
super().user_changed()
|
had_seq = self.seq is not None
|
||||||
|
super().user_changed() # EV-22 (DA1): ends a change it lifts
|
||||||
self.gave_up, self.fails, self.fail_at = False, 0, None
|
self.gave_up, self.fails, self.fail_at = False, 0, None
|
||||||
self._stuck_end()
|
self._stuck_end()
|
||||||
|
# EV-22: the phases are taken afresh (the start state again); an own
|
||||||
|
# select's window stays.
|
||||||
|
self._own_n, self._ph_diff = None, False
|
||||||
|
if held and had_seq:
|
||||||
|
self.plan.end_switch(False)
|
||||||
if held:
|
if held:
|
||||||
self.last_a = None
|
self.last_a = None
|
||||||
self.sent_a, self.taken = None, True
|
self.sent_a, self.taken = None, True
|
||||||
@@ -1068,6 +1195,64 @@ class SolarWriter(ManualWriter):
|
|||||||
or Solar's."""
|
or Solar's."""
|
||||||
return "peak cut" if q.get("cut") else "Solar"
|
return "peak cut" if q.get("cut") else "Solar"
|
||||||
|
|
||||||
|
def _close_end(self, now) -> None:
|
||||||
|
"""EV-60: no extra `_failed`. Each refused close was counted when it
|
||||||
|
went (`_write`), a cut try in `cut_fails` too, so the sequence's end
|
||||||
|
adds nothing (Manual's `_close_end` is EV-59's, unchanged)."""
|
||||||
|
|
||||||
|
def _carry_ok(self) -> bool:
|
||||||
|
"""EV-69 (formal Dev note 2): the end's own value (`sent_a`) was
|
||||||
|
already taken (an `_adopt` earlier in the step): nothing is carried."""
|
||||||
|
return not self.taken
|
||||||
|
|
||||||
|
def _carried_take(self) -> None:
|
||||||
|
"""EV-69 GUR: a carried take resets `fails` and `gave_up` only, never
|
||||||
|
`taken` or `last_a`: `sent_a` stays owed, so the clamp value is sent
|
||||||
|
again at the next RETRY_S step."""
|
||||||
|
self.fails, self.gave_up = 0, False
|
||||||
|
|
||||||
|
def _cut_gate(self, now) -> bool:
|
||||||
|
"""EV-60 (Q1): the quarter key's cut tries are used up, or the last
|
||||||
|
refused one is less than RETRY_S old (`_put`'s two gates)."""
|
||||||
|
return self.cut_fails >= MAX_TRIES or (
|
||||||
|
self.cut_fail_at is not None and now - self.cut_fail_at < RETRY_S)
|
||||||
|
|
||||||
|
async def _advance(self, drv, r, cur, now, tracker, want_a, clamp, rev):
|
||||||
|
"""EV-60: Solar's capped close is a cut try, so it passes the cut's
|
||||||
|
gates. Tries used up: the change ends at its 0 A, nothing written
|
||||||
|
(`_cap_end`: `step` then leaves the plan as `end_switch(False)` put
|
||||||
|
it). The sequence's first cut close waits at 0 A until RETRY_S after
|
||||||
|
the last refused cut try (counts nothing, ends nothing); after a cut
|
||||||
|
close of the sequence went, the 5 s spacing of `_advance` rules."""
|
||||||
|
self._cap_end = False # set again below, read by `step` only
|
||||||
|
if callable(want_a):
|
||||||
|
# The gate runs where `_advance` asks for the close value, just
|
||||||
|
# before it writes: also on the "car kept drawing" path, which
|
||||||
|
# turns zero into settle and closes in the same call.
|
||||||
|
inner, hi = want_a, (CH.ENTITY_MAX_A if clamp is None
|
||||||
|
else float(clamp))
|
||||||
|
|
||||||
|
def want_a(q):
|
||||||
|
v = inner(q)
|
||||||
|
if self._cut_try(min(max(float(v), CH.MIN_A), hi)):
|
||||||
|
if self.cut_fails >= MAX_TRIES:
|
||||||
|
self._carry_end(q) # EV-69: the closes stay own
|
||||||
|
self.seq, self.last_a, self.reapply = None, None, True
|
||||||
|
self.rev_applied = None
|
||||||
|
self.plan.end_switch(False)
|
||||||
|
self._cap_end = True
|
||||||
|
raise _CloseHeld
|
||||||
|
if not q.get("cut_went") and self.cut_fail_at is not None \
|
||||||
|
and now - self.cut_fail_at < RETRY_S:
|
||||||
|
raise _CloseHeld
|
||||||
|
q["cut_went"] = True
|
||||||
|
return v
|
||||||
|
try:
|
||||||
|
await super()._advance(drv, r, cur, now, tracker, want_a, clamp,
|
||||||
|
rev)
|
||||||
|
except _CloseHeld:
|
||||||
|
pass
|
||||||
|
|
||||||
def _failed(self, now) -> None:
|
def _failed(self, now) -> None:
|
||||||
if self.sent_cut:
|
if self.sent_cut:
|
||||||
# EV-54 (Q1, F7): a refused cut try counts against the quarter's
|
# EV-54 (Q1, F7): a refused cut try counts against the quarter's
|
||||||
@@ -1104,6 +1289,7 @@ class SolarWriter(ManualWriter):
|
|||||||
self.startup_zero = False
|
self.startup_zero = False
|
||||||
self.last_a = cur
|
self.last_a = cur
|
||||||
self.attempted_a = self.prior_a = None
|
self.attempted_a = self.prior_a = None
|
||||||
|
self._carry = [] # EV-69: an own take ends the carry
|
||||||
self.fails, self.fail_at, self.gave_up = 0, None, False
|
self.fails, self.fail_at, self.gave_up = 0, None, False
|
||||||
self.refused_cut = None
|
self.refused_cut = None
|
||||||
if self.sent_cut:
|
if self.sent_cut:
|
||||||
@@ -1199,9 +1385,59 @@ class SolarWriter(ManualWriter):
|
|||||||
if self.live and not self.hold:
|
if self.live and not self.hold:
|
||||||
await self._put(drv, 0.0, cur, now, tracker, stuck, out=True)
|
await self._put(drv, 0.0, cur, now, tracker, stuck, out=True)
|
||||||
|
|
||||||
def _watch(self, cur, now) -> None:
|
def _took_as_is(self) -> None:
|
||||||
|
self.sent_a, self.taken = None, True
|
||||||
|
self.refused_cut = None
|
||||||
|
|
||||||
|
def _reset_phases(self, window=True) -> None:
|
||||||
|
"""EV-22: the phases Solar judges start afresh (entering Solar, the
|
||||||
|
charger's return, a press). The window of an own select goes too
|
||||||
|
unless it is kept."""
|
||||||
|
self._own_n, self._ph_diff = None, False
|
||||||
|
if window:
|
||||||
|
self._sel_n = self._win_t1 = None
|
||||||
|
self._win_last = False
|
||||||
|
|
||||||
|
def _select_try(self, n, ok) -> None:
|
||||||
|
"""EV-22 (DA3): our own select try returned. SETTLE_S from now a
|
||||||
|
read-back is not judged (A7: from its return, not from its send); a
|
||||||
|
taken select is our phases at once, one the charger did not confirm
|
||||||
|
becomes ours if a read inside the window shows it."""
|
||||||
|
self._sel_n = n
|
||||||
|
self._win_t1 = float(self.last_done)
|
||||||
|
self._win_last = False
|
||||||
|
if ok:
|
||||||
|
self._own_n, self._ph_diff = n, False
|
||||||
|
|
||||||
|
def _judge_phases(self, r, now) -> None:
|
||||||
|
"""EV-22 (D4): the read-back phases against the phases Solar itself
|
||||||
|
chose (never the plan's adopted `n`). Unknown phases and reads inside
|
||||||
|
a select's window start nothing and lift nothing. The window is the
|
||||||
|
sequence's settle time on the same clock and with the same
|
||||||
|
comparison as the close (`now - t1 < SETTLE_S`), and the one step
|
||||||
|
that closes at its end is still inside it, whatever fraction of a
|
||||||
|
second `last_done` lies after the step's `now`."""
|
||||||
|
p = getattr(r, "phases_allowed", None)
|
||||||
|
if self._win_t1 is not None:
|
||||||
|
inside = now - self._win_t1 < SETTLE_S
|
||||||
|
if not inside and not self._win_last:
|
||||||
|
self._win_last = inside = True # the closing step
|
||||||
|
if inside:
|
||||||
|
if p in (1, 3) and p == self._sel_n:
|
||||||
|
self._own_n, self._ph_diff = p, False # the take
|
||||||
|
return
|
||||||
|
self._sel_n = self._win_t1 = None
|
||||||
|
if p not in (1, 3):
|
||||||
|
return
|
||||||
|
if self._own_n is None:
|
||||||
|
self._own_n, self._ph_diff = p, False # the start state
|
||||||
|
return
|
||||||
|
self._ph_diff = p != self._own_n
|
||||||
|
|
||||||
|
def _watch(self, cur, now, judge=True) -> None:
|
||||||
was = self.hold
|
was = self.hold
|
||||||
super()._watch(cur, now)
|
self._judge_phases(self._r, now)
|
||||||
|
super()._watch(cur, now, judge)
|
||||||
if self.hold and not was:
|
if self.hold and not was:
|
||||||
_LOG.warning("Something else changes the charger, so the add-on "
|
_LOG.warning("Something else changes the charger, so the add-on "
|
||||||
"stops writing to it until you press Solar: "
|
"stops writing to it until you press Solar: "
|
||||||
@@ -1239,6 +1475,7 @@ class SolarWriter(ManualWriter):
|
|||||||
self.out, self.fault = False, None
|
self.out, self.fault = False, None
|
||||||
self.restart = True
|
self.restart = True
|
||||||
self.mismatch_since = None
|
self.mismatch_since = None
|
||||||
|
self._reset_phases()
|
||||||
self.plan.reset(self.plan.n)
|
self.plan.reset(self.plan.n)
|
||||||
|
|
||||||
def _gap_ok(self, now) -> bool:
|
def _gap_ok(self, now) -> bool:
|
||||||
@@ -1303,15 +1540,20 @@ class SolarWriter(ManualWriter):
|
|||||||
async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None:
|
async def _begin_solar(self, drv, r, cur, n, now, tracker) -> None:
|
||||||
"""Step 1 of the safe sequence: 0 A (kept when it already stands).
|
"""Step 1 of the safe sequence: 0 A (kept when it already stands).
|
||||||
A 0 A the charger does not take ends the change; tried again later
|
A 0 A the charger does not take ends the change; tried again later
|
||||||
by the plan's own dwell."""
|
by the plan's own dwell. EV-60: under a cap that 0 A is a cut try and
|
||||||
|
passes the cut's gates; stopped by them the change waits (nothing
|
||||||
|
written or counted, never a give-up) for the next quarter key."""
|
||||||
|
owed = not (cur is not None and cur <= TOL_A and self.sent_a == 0.0
|
||||||
|
and self.taken)
|
||||||
|
if owed and self._cut_try(0.0) and self._cut_gate(now):
|
||||||
|
return
|
||||||
self.phase_done_at = None
|
self.phase_done_at = None
|
||||||
if not (cur is not None and cur <= TOL_A and self.sent_a == 0.0
|
if owed:
|
||||||
and self.taken):
|
|
||||||
if not await self._write(drv, 0.0, cur, now, tracker):
|
if not await self._write(drv, 0.0, cur, now, tracker):
|
||||||
self.plan.end_switch(False)
|
self.plan.end_switch(False)
|
||||||
return
|
return
|
||||||
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
|
self.seq = {"stage": "zero", "t0": now, "n": n, "tries": 0,
|
||||||
"prev": None, "from": r.phases_allowed}
|
"prev": None, "from": r.phases_allowed, "own": [0.0]}
|
||||||
|
|
||||||
# ------------------------------------------------------------- step
|
# ------------------------------------------------------------- step
|
||||||
async def held_pause(self, drv, r, *, sun, now, tracker) -> None:
|
async def held_pause(self, drv, r, *, sun, now, tracker) -> None:
|
||||||
@@ -1360,6 +1602,7 @@ class SolarWriter(ManualWriter):
|
|||||||
# notice. The quarter's try count stays (Q5).
|
# notice. The quarter's try count stays (Q5).
|
||||||
self.refused_cut, self.sent_cut, self.cut_warned = None, False, \
|
self.refused_cut, self.sent_cut, self.cut_warned = None, False, \
|
||||||
False
|
False
|
||||||
|
self._reset_phases() # EV-22: a fresh entry starts clean
|
||||||
if not self.engaged:
|
if not self.engaged:
|
||||||
return
|
return
|
||||||
if sun is not None:
|
if sun is not None:
|
||||||
@@ -1391,7 +1634,10 @@ class SolarWriter(ManualWriter):
|
|||||||
self.startup_zero = self.boot and not self._returned
|
self.startup_zero = self.boot and not self._returned
|
||||||
self.fresh_start = self.restart = True
|
self.fresh_start = self.restart = True
|
||||||
self.mismatch_since = None
|
self.mismatch_since = None
|
||||||
|
if not self.hold:
|
||||||
|
self._reset_phases(window=False) # EV-22: start state again
|
||||||
self.last_a = self.attempted_a = self.prior_a = None
|
self.last_a = self.attempted_a = self.prior_a = None
|
||||||
|
self._carry = [] # EV-69: the return ends the carry
|
||||||
self._rec_a = None # EV-56 (G2): logged again
|
self._rec_a = None # EV-56 (G2): logged again
|
||||||
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
cur = r.allowed_a if r.allowed_a is not None else r.setpoint_a
|
||||||
stuck = bool(tracker is not None and tracker.stuck(now))
|
stuck = bool(tracker is not None and tracker.stuck(now))
|
||||||
@@ -1425,8 +1671,11 @@ class SolarWriter(ManualWriter):
|
|||||||
# owed, then nothing. The watch goes on (another writer is held
|
# owed, then nothing. The watch goes on (another writer is held
|
||||||
# for every reader) and so does the plan, for the card.
|
# for every reader) and so does the plan, for the card.
|
||||||
self.out = True
|
self.out = True
|
||||||
|
n_log = len(self.log)
|
||||||
await self._zero(drv, cur, now, tracker, stuck)
|
await self._zero(drv, cur, now, tracker, stuck)
|
||||||
self._watch(cur, now)
|
# EV-22 (DA2): `cur` is from before our own 0 A of this step:
|
||||||
|
# the current is not judged then (the phases are).
|
||||||
|
self._watch(cur, now, judge=len(self.log) == n_log)
|
||||||
self._shadow_plan(sun, now, clamp, n_now)
|
self._shadow_plan(sun, now, clamp, n_now)
|
||||||
self.restart = True
|
self.restart = True
|
||||||
return
|
return
|
||||||
@@ -1499,8 +1748,8 @@ class SolarWriter(ManualWriter):
|
|||||||
if self.drop_ready(cur, stuck):
|
if self.drop_ready(cur, stuck):
|
||||||
# EV-54 (drop rule): the refused cut value is not sent again.
|
# EV-54 (drop rule): the refused cut value is not sent again.
|
||||||
self._drop(cur, now)
|
self._drop(cur, now)
|
||||||
|
self._watch(cur, now) # EV-22 (C7): inside a change too
|
||||||
if self.seq is None:
|
if self.seq is None:
|
||||||
self._watch(cur, now)
|
|
||||||
if self.hold or self.mismatch_since is not None:
|
if self.hold or self.mismatch_since is not None:
|
||||||
# Another writer's value, held or not yet: nothing is written
|
# Another writer's value, held or not yet: nothing is written
|
||||||
# over it; the plan goes on for the card.
|
# over it; the plan goes on for the card.
|
||||||
@@ -1551,6 +1800,9 @@ class SolarWriter(ManualWriter):
|
|||||||
clamp, None)
|
clamp, None)
|
||||||
if any(x[0] == "phases" for x in self.log[n_log:]):
|
if any(x[0] == "phases" for x in self.log[n_log:]):
|
||||||
q["sel"] = True # a select went out, taken or not
|
q["sel"] = True # a select went out, taken or not
|
||||||
|
if self.seq is None and self._cap_end:
|
||||||
|
self._cap_end = False # EV-60: ended at 0 A, plan as it was
|
||||||
|
return
|
||||||
if self.seq is None:
|
if self.seq is None:
|
||||||
# Back on the old phases only when no select went out; after
|
# Back on the old phases only when no select went out; after
|
||||||
# one the plan keeps the current it wrote (the lower one) and
|
# one the plan keeps the current it wrote (the lower one) and
|
||||||
|
|||||||
@@ -799,7 +799,7 @@ for exc in (RuntimeError("the link broke"), hass.ReadOnly("read only")):
|
|||||||
errs = [m for lv, m in LOG.rec[n0:]
|
errs = [m for lv, m in LOG.rec[n0:]
|
||||||
if lv == "ERROR" and "car charger step failed" in m]
|
if lv == "ERROR" and "car charger step failed" in m]
|
||||||
check(f"T13 write_current raises {type(exc).__name__}: as on the base: "
|
check(f"T13 write_current raises {type(exc).__name__}: as on the base: "
|
||||||
"never armed, no window left, no refusal counted, the mute set, "
|
"never armed, no window left, one refusal counted, the mute set, "
|
||||||
f"the step error logged once ({len(errs)})",
|
f"the step error logged once ({len(errs)})",
|
||||||
never_stuck(tr) and pend(w.c.car) is None
|
never_stuck(tr) and pend(w.c.car) is None
|
||||||
and w.c.car_writer.fails == 1 and w.c.car.mute_until > 0
|
and w.c.car_writer.fails == 1 and w.c.car.mute_until > 0
|
||||||
@@ -1027,8 +1027,8 @@ BASE_SENDS = { # recorded on 76f4de2 (release/1.0 before EV-13)
|
|||||||
'T19-inside': ([(1011, 0.0, False), (1071, 0.0, False), (1131, 0.0, False)], [(11, 'current', 0.0), (71, 'current', 0.0), (131, 'current', 0.0)]),
|
'T19-inside': ([(1011, 0.0, False), (1071, 0.0, False), (1131, 0.0, False)], [(11, 'current', 0.0), (71, 'current', 0.0), (131, 'current', 0.0)]),
|
||||||
'T2-error-beside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []),
|
'T2-error-beside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []),
|
||||||
'T2-error-inside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []),
|
'T2-error-inside': ([(1011, 10.0, False), (1071, 10.0, False), (1131, 10.0, False)], []),
|
||||||
'T20-beside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False), (1095, 16.0, False), (1155, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
|
'T20-beside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
|
||||||
'T20-inside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False), (1095, 16.0, False), (1155, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
|
'T20-inside': ([(1011, 0.0, True), (1025, 16.0, False), (1030, 16.0, False), (1035, 16.0, False)], [(11, 'current', 0.0), (15, 'phases', 1)]),
|
||||||
'T21-beside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]),
|
'T21-beside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]),
|
||||||
'T21-inside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]),
|
'T21-inside': ([(1011, 12.0, False)], [(11, 'current', 12.0)]),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -217,23 +217,33 @@ check(f"T46: Solar starts on 1 phase (select at the start), then another "
|
|||||||
f"phase, Expected 5) ({[(x[0], x[2]) for x in s46]})",
|
f"phase, Expected 5) ({[(x[0], x[2]) for x in s46]})",
|
||||||
s46[:1] and s46[0][2] == 1
|
s46[:1] and s46[0][2] == 1
|
||||||
and not [x for x in s46 if 140 < x[0] < 700])
|
and not [x for x in s46 if 140 < x[0] < 700])
|
||||||
low = [x for x in w46 if 140 < x[0] < 700]
|
# EV-22 (PM ruling v3, D4): another writer's phase switch is a mismatch from
|
||||||
# EV-21: with both batteries at the cut-out, the other writer's 3 phases
|
# its first cycle, like a foreign current. Solar writes nothing after it (no
|
||||||
# take the period over the aim, so Solar's peak cut lowers the car first,
|
# cut, no 6 A hold, no pause: it does not cut a car it does not control) and
|
||||||
# within 1 cycle and at 690 W/A (EV-21 T34 (ii)); the 6 A hold and the pause
|
# holds after WRITER_S with one CHARGER_OTHER; the guard's alarm path is the
|
||||||
# follow. Every write in the stretch lowers; none waits for PHASE_GAP_S.
|
# one it has with the car in Off (`car_solar_can_cut` False), which is the
|
||||||
six = [x for x in low if x[1] == 6.0]
|
# alarm. Before (EV-21 T34 (ii) via EV-05): the cut, the 6 A hold and the
|
||||||
check(f"T46 (a)(b): the arithmetic uses the 3 phases the car draws on, and a "
|
# pause were written within the 30 s rule, a 4140 W x 302 s import.
|
||||||
f"lower current (EV-21's cut, the 6 A hold, the pause) is written "
|
n46 = r46["_log"]
|
||||||
f"within the 30 s rule, never blocked by PHASE_GAP_S ({w46})",
|
hold46 = next((x["t"] for x in r46["trace"] if x["hold"]), None)
|
||||||
low and six and six[0][0] <= 171 and low[0][0] <= 171
|
other46 = [m for m in LOG.since(n46, "WARNING") if "CHARGER_OTHER" in m]
|
||||||
and all(b[1] < a[1] for a, b in zip(low, low[1:]))
|
check(f"T46 (a)(b): no Solar write after another writer's 3 phases at 140 "
|
||||||
and [a for _, a, _ in low][-1:] == [0.0])
|
f"({[x for x in w46 if x[0] > 140]}), the hold at {hold46} (170), "
|
||||||
imp46 = sum(max(0.0, x["grid"]) for x in r46["trace"]
|
f"CHARGER_OTHER once ({len(other46)})",
|
||||||
if x["t"] > 140 and x["sp"] > 0)
|
not [x for x in w46 if x[0] > 140]
|
||||||
check(f"T46 (c): the car's grid import only within the hold rule "
|
and hold46 is not None and 170 <= hold46 <= 171 and len(other46) == 1)
|
||||||
f"(<= 300 s of 6 A on 3 phases) ({imp46 / 3600:.0f} Wh)",
|
off46 = run("T46 Off", S.drive, step_fn((300, 700.0), (600, 900.0), base=500.0),
|
||||||
imp46 <= 4140.0 * 302.0)
|
const(3500.0), dur=900, first="car", phases=1, mode="off",
|
||||||
|
sim=SimCharger(setpoint_a=12), socs={"a": 10.0, "b": 10.0},
|
||||||
|
rows=True, events={140: lambda p, c: p.ch.set_phases(3)})
|
||||||
|
al_s = [t for t, _n in S.ids(r46, *S.ALARMS)][:1]
|
||||||
|
al_o = [t for t, _n in S.ids(off46, *S.ALARMS)][:1]
|
||||||
|
ex_s = [(x["explains"], x["red"]) for x in r46["trace"] if x["t"] >= 142]
|
||||||
|
ex_o = [(x["explains"], x["red"]) for x in off46["trace"] if x["t"] >= 142]
|
||||||
|
check(f"T46 (c): the alarm path is the one with the car in Off: the alarm "
|
||||||
|
f"within 2 s of the Off twin's ({al_s} / {al_o}), car_explains and the "
|
||||||
|
f"red rows equal in every cycle from 142 s",
|
||||||
|
al_s and al_o and abs(al_s[0] - al_o[0]) <= 2.0 and ex_s == ex_o)
|
||||||
r46h = std(900, sun=const(3500.0), phases=3,
|
r46h = std(900, sun=const(3500.0), phases=3,
|
||||||
events={200: lambda p, c: p.ch.set_current(16),
|
events={200: lambda p, c: p.ch.set_current(16),
|
||||||
300: lambda p, c: p.ch.set_phases(3)})
|
300: lambda p, c: p.ch.set_phases(3)})
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,467 @@
|
|||||||
|
"""EV-22 T38: the Solar fuzz for the one rule of control (N1-N10 of
|
||||||
|
reports/EV-22-test-plan.md), 14 seeds of 3600 s, both cycle orders.
|
||||||
|
`python3 -B test_ev22_fuzz.py`
|
||||||
|
|
||||||
|
A model charger that knows who set its current and its phases last (the
|
||||||
|
add-on, or another writer); random foreign currents and phase switches at any
|
||||||
|
stage (zero, select, settle), unknown phases, read gaps, refused selects and
|
||||||
|
writes, late takes of a refused select inside and after the window, Stop, Off,
|
||||||
|
shadow, latch, a press (also inside a change), and a silent meter. Every cycle
|
||||||
|
checks: N1/N2 (no non-zero write, no select over a foreign value or phase that
|
||||||
|
has stood WRITER_S, unless a press took it), N3 (no mismatch, hold or
|
||||||
|
CHARGER_OTHER without a foreign event shortly before), N4 (the N3 reading, 6 A
|
||||||
|
never past the pause), N5 (the cut cap), N6 (the select rules), N7 (no select
|
||||||
|
under a mismatch or hold), N8 (can_cut False under one), N9 (one
|
||||||
|
CHARGER_OTHER per hold), N10 (Manual never judges phases; the raise check
|
||||||
|
never holds over the value a press took). The branches are counted and a
|
||||||
|
floor is asserted, so a fuzz that never reaches them fails.
|
||||||
|
|
||||||
|
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import sys
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||||
|
|
||||||
|
from app import carmode # noqa: E402
|
||||||
|
import ev20_sun as S # noqa: E402
|
||||||
|
from chargersim import SimCharger # noqa: E402
|
||||||
|
from ev20_kit import LOG, check, fails, nevers, report # noqa: E402
|
||||||
|
|
||||||
|
SITES = 14
|
||||||
|
STEPS_PER = int(os.environ.get("EV22_FUZZ_STEPS", "3600"))
|
||||||
|
ONLY = [int(x) for x in os.environ.get("EV22_FUZZ_ONLY", "").split(",") if x]
|
||||||
|
DEBUG = bool(os.environ.get("EV22_FUZZ_DEBUG"))
|
||||||
|
WRITER_S = carmode.WRITER_S
|
||||||
|
# The fuzz shortens Solar's dwells and the phase gap so that a 1 h run holds
|
||||||
|
# many phase changes (it is the changes that carry C7); nothing else moves.
|
||||||
|
if not os.environ.get("EV22_FUZZ_SLOW"):
|
||||||
|
carmode.UP_S, carmode.DOWN_S, carmode.PHASE_GAP_S = 20.0, 30.0, 60.0
|
||||||
|
|
||||||
|
|
||||||
|
class FSim(SimCharger):
|
||||||
|
"""Who set the current and the phases last, and when."""
|
||||||
|
ctl = None
|
||||||
|
|
||||||
|
def __init__(self, *a, **kw):
|
||||||
|
super().__init__(*a, **kw)
|
||||||
|
self.setter = None
|
||||||
|
self.cur_other_at = None # a foreign current stands since
|
||||||
|
self.ph_other_at = None # foreign phases stand since
|
||||||
|
self.own_ph = None # set at the first event (the start)
|
||||||
|
self.unknown = False
|
||||||
|
self.sel_log = [] # (sim t, n, taken?) of own selects
|
||||||
|
self.late = None # (n, t_sent) a refused select to take
|
||||||
|
|
||||||
|
def _apply(self, what, v):
|
||||||
|
if what == "current":
|
||||||
|
self.setter = "solar"
|
||||||
|
self.cur_other_at = None
|
||||||
|
else:
|
||||||
|
self.own_ph = 3 if v == 3 else 1
|
||||||
|
self.ph_other_at = None
|
||||||
|
super()._apply(what, v)
|
||||||
|
|
||||||
|
now_t = 0.0 # the plant's clock (not this model's)
|
||||||
|
refuse_ph = False # only the phase selects are ignored
|
||||||
|
|
||||||
|
last_sel = None # (n, plant second) of the latest select
|
||||||
|
|
||||||
|
def request_phases(self, n):
|
||||||
|
self.last_sel = (n, self.now_t)
|
||||||
|
self.sel_log.append((self.now_t, n, self.refuse_ph, self.refuse,
|
||||||
|
self.phases_allowed, self.own_ph))
|
||||||
|
keep = self.refuse
|
||||||
|
if self.refuse_ph:
|
||||||
|
self.refuse = "ignore"
|
||||||
|
try:
|
||||||
|
ok = super().request_phases(n)
|
||||||
|
finally:
|
||||||
|
self.refuse = keep
|
||||||
|
if ok and (self.refuse_ph or keep == "ignore"):
|
||||||
|
self.late = (n, self.now_t)
|
||||||
|
return ok
|
||||||
|
|
||||||
|
def set_current(self, a):
|
||||||
|
if abs(float(a) - self.setpoint_a) > 0.5:
|
||||||
|
self.setter = "other"
|
||||||
|
self.cur_other_at = self.now_t
|
||||||
|
super().set_current(a)
|
||||||
|
|
||||||
|
def set_phases(self, n):
|
||||||
|
super().set_phases(n)
|
||||||
|
if self.own_ph is None:
|
||||||
|
return # Solar has no phases of its own yet
|
||||||
|
if self.phases_allowed != self.own_ph:
|
||||||
|
self.ph_other_at = self.now_t
|
||||||
|
else:
|
||||||
|
self.ph_other_at = None
|
||||||
|
|
||||||
|
def _build(self):
|
||||||
|
out = super()._build()
|
||||||
|
if self.unknown:
|
||||||
|
for k in list(out):
|
||||||
|
if "phases" in k and ("select." in k or "max_allowed" in k):
|
||||||
|
out[k] = dict(out[k], state="unknown")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
COUNT = {}
|
||||||
|
EVLOG = []
|
||||||
|
|
||||||
|
|
||||||
|
NOW = [0.0]
|
||||||
|
|
||||||
|
|
||||||
|
def bump(k, n=1):
|
||||||
|
COUNT[k] = COUNT.get(k, 0) + n
|
||||||
|
EVLOG.append((NOW[0], k))
|
||||||
|
|
||||||
|
|
||||||
|
HIST = {}
|
||||||
|
|
||||||
|
|
||||||
|
def fuzz_site(seed):
|
||||||
|
rnd = random.Random(seed)
|
||||||
|
HIST.clear()
|
||||||
|
del EVLOG[:]
|
||||||
|
sim = FSim(setpoint_a=rnd.choice([0, 6, 10, 16]))
|
||||||
|
sim.lag_s = rnd.choice([0.0, 0.0, 3.0, 12.0])
|
||||||
|
if seed % 3 == 0:
|
||||||
|
sim.ramp_w_s, sim.stop_delay_s = 300.0, 4.0
|
||||||
|
state = {"sun": rnd.uniform(3000, 11000), "house": rnd.uniform(300, 2000)}
|
||||||
|
bad, mem = [], dict(last_foreign=-1e9, press_at=-1e9, hold=False,
|
||||||
|
rises=0, n_sel=0, n_cur=0, seq=None, zero_cnt=0,
|
||||||
|
was_ms=False)
|
||||||
|
pend = {} # name -> end second of an outage
|
||||||
|
|
||||||
|
async def ev(p, c):
|
||||||
|
sim.ctl = c
|
||||||
|
w = c.car_solar
|
||||||
|
t = p.t
|
||||||
|
NOW[0] = sim.now_t = t
|
||||||
|
|
||||||
|
def takes_charger():
|
||||||
|
"""The user's press (or Solar entered, or the charger back with
|
||||||
|
no hold) takes the charger as it is: nothing on it is foreign,
|
||||||
|
and Solar's phases are the first known read after it (OQ2), which
|
||||||
|
`on_cycle` copies from Solar's start state."""
|
||||||
|
sim.own_ph, sim.ph_other_at = None, None
|
||||||
|
sim.cur_other_at = None
|
||||||
|
if pend.get("outage") is not None and t >= pend["outage"] \
|
||||||
|
and not w.hold:
|
||||||
|
takes_charger()
|
||||||
|
for k, off in (("outage", lambda: p.ch.go_unavailable(False)),
|
||||||
|
("meter", lambda: setattr(p, "meter_on", True)),
|
||||||
|
("stop", lambda: setattr(c, "auto", True)),
|
||||||
|
("unknown", lambda: setattr(sim, "unknown", False)),
|
||||||
|
("shadow", lambda: c.o.__setitem__("shadow_mode",
|
||||||
|
"off"))):
|
||||||
|
if pend.get(k) is not None and t >= pend[k]:
|
||||||
|
off()
|
||||||
|
pend[k] = None
|
||||||
|
if pend.get("mode") is not None and t >= pend["mode"]:
|
||||||
|
pend["mode"] = None
|
||||||
|
mem["press_at"] = t
|
||||||
|
takes_charger()
|
||||||
|
await c.handle_action("car_mode", value="solar")
|
||||||
|
if sim.refuse is not None and rnd.random() < 0.03:
|
||||||
|
sim.refuse = None
|
||||||
|
# a late take of a refused select: inside (<= 12 s after it went) or
|
||||||
|
# after (>= 25 s) the window
|
||||||
|
if sim.late is not None:
|
||||||
|
n_, t_ = sim.late
|
||||||
|
age = t - t_
|
||||||
|
if 3 <= age <= 12 and rnd.random() < 0.005:
|
||||||
|
sim.set_phases(n_)
|
||||||
|
sim.own_ph = sim.phases_allowed
|
||||||
|
sim.ph_other_at = None
|
||||||
|
sim.late = None
|
||||||
|
bump("late_in")
|
||||||
|
elif age >= 25 and rnd.random() < 0.2:
|
||||||
|
sim.set_phases(n_)
|
||||||
|
mem["last_foreign"] = t
|
||||||
|
sim.late = None
|
||||||
|
bump("late_after")
|
||||||
|
elif age > 400:
|
||||||
|
sim.late = None
|
||||||
|
if pend.get("latch") is not None and t >= pend["latch"]:
|
||||||
|
c.circ_wd.tripped = False
|
||||||
|
pend["latch"] = None
|
||||||
|
seqnow = w.seq is not None
|
||||||
|
s = "_seq" if seqnow else ""
|
||||||
|
# independent draws; a change in progress draws far more events
|
||||||
|
if rnd.random() < 0.02:
|
||||||
|
state["sun"] = max(0.0, min(12000.0, state["sun"]
|
||||||
|
+ rnd.uniform(-8000, 8000)))
|
||||||
|
if rnd.random() < 0.002:
|
||||||
|
state["house"] = rnd.uniform(300, 4000)
|
||||||
|
if rnd.random() < 0.0004 and pend.get("outage") is None:
|
||||||
|
p.ch.go_unavailable(True)
|
||||||
|
pend["outage"] = t + rnd.uniform(1, 40)
|
||||||
|
bump("outage")
|
||||||
|
if rnd.random() < 0.0003:
|
||||||
|
(p.ch.unplug if p.ch.state != "A" else p.ch.plug_in)()
|
||||||
|
if rnd.random() < 0.002:
|
||||||
|
sim.refuse = rnd.choice([None, "ignore", "ignore", "error"])
|
||||||
|
bump("refuse")
|
||||||
|
if rnd.random() < (0.12 if seqnow else 0.0015):
|
||||||
|
sim.set_current(rnd.choice([0, 5, 6, 13, 16]))
|
||||||
|
mem["last_foreign"] = t
|
||||||
|
bump("f_cur" + s)
|
||||||
|
if rnd.random() < (0.12 if seqnow else 0.003):
|
||||||
|
x = rnd.choice([1, 3])
|
||||||
|
ls = sim.last_sel
|
||||||
|
if ls is not None and t - ls[1] <= 25:
|
||||||
|
# inside Solar's own select window nothing is judged (DA3,
|
||||||
|
# Finding 4): a foreign switch there can hide behind the take
|
||||||
|
# and is not drawn; T47 and T48 cover its edges
|
||||||
|
bump("f_ph_skipped_in_window")
|
||||||
|
else:
|
||||||
|
sim.set_phases(x)
|
||||||
|
if sim.ph_other_at is not None:
|
||||||
|
mem["last_foreign"] = t
|
||||||
|
bump("f_ph" + s)
|
||||||
|
ls = sim.last_sel
|
||||||
|
in_sel = ls is not None and t - ls[1] <= 40
|
||||||
|
if in_sel and sim.unknown:
|
||||||
|
# a take that nobody could read inside the window is judged when
|
||||||
|
# seen (DA3, Finding 3): no unknown phases around an own select
|
||||||
|
sim.unknown, pend["unknown"] = False, None
|
||||||
|
if rnd.random() < 0.001 and pend.get("unknown") is None \
|
||||||
|
and not in_sel:
|
||||||
|
sim.unknown = True
|
||||||
|
pend["unknown"] = t + rnd.uniform(3, 30)
|
||||||
|
bump("unknown")
|
||||||
|
if (w.hold or w.mismatch_since is not None) and rnd.random() < 0.012:
|
||||||
|
# the other writer puts its change back: the read-back is ours
|
||||||
|
if w.last_a is not None:
|
||||||
|
sim.set_current(w.last_a)
|
||||||
|
if sim.own_ph is not None:
|
||||||
|
sim.set_phases(sim.own_ph)
|
||||||
|
sim.setter = "solar"
|
||||||
|
sim.cur_other_at = sim.ph_other_at = None
|
||||||
|
bump("put_back")
|
||||||
|
if (w.hold or w.gave_up) and rnd.random() < 0.025:
|
||||||
|
mem["press_at"] = t
|
||||||
|
takes_charger()
|
||||||
|
bump("press_hold")
|
||||||
|
await c.handle_action("car_mode", value="solar")
|
||||||
|
elif seqnow and rnd.random() < (0.3 if w.mismatch_since is not None
|
||||||
|
else 0.03):
|
||||||
|
if w.hold or w.mismatch_since is not None:
|
||||||
|
bump("lift_press_seq")
|
||||||
|
mem["press_at"] = t
|
||||||
|
takes_charger()
|
||||||
|
bump("press_seq")
|
||||||
|
await c.handle_action("car_mode", value="solar")
|
||||||
|
if seqnow and not sim.refuse_ph and rnd.random() < 0.2:
|
||||||
|
sim.refuse_ph = True # a select the charger ignores
|
||||||
|
bump("refuse_seq")
|
||||||
|
elif sim.refuse_ph and rnd.random() < 0.02:
|
||||||
|
sim.refuse_ph = False
|
||||||
|
if rnd.random() < 0.0004 and pend.get("meter") is None:
|
||||||
|
p.meter_on = False
|
||||||
|
pend["meter"] = t + rnd.uniform(5, 60)
|
||||||
|
bump("meter")
|
||||||
|
counting = w.mismatch_since is not None and not w.hold
|
||||||
|
if rnd.random() < (0.05 if seqnow else 0.05 if counting else 0.0006):
|
||||||
|
k = rnd.choice(["stop", "shadow", "mode", "latch"])
|
||||||
|
bump(k + s)
|
||||||
|
back = t + rnd.uniform(5, 60)
|
||||||
|
if k == "stop" and pend.get("stop") is None:
|
||||||
|
c.auto = False
|
||||||
|
c.o["shadow_mode"] = rnd.choice(["off", "auto"])
|
||||||
|
pend["stop"] = back
|
||||||
|
elif k == "shadow" and pend.get("shadow") is None:
|
||||||
|
c.o["shadow_mode"] = "on"
|
||||||
|
pend["shadow"] = back
|
||||||
|
elif k == "latch" and pend.get("latch") is None:
|
||||||
|
c.circ_wd.tripped = True
|
||||||
|
pend["latch"] = back
|
||||||
|
elif k == "mode" and pend.get("mode") is None:
|
||||||
|
await c.handle_action("car_mode", value="off")
|
||||||
|
pend["mode"] = back
|
||||||
|
if rnd.random() < 0.0005:
|
||||||
|
await c.handle_action("car_sun_first", value=rnd.choice(
|
||||||
|
["batteries", "car"]))
|
||||||
|
|
||||||
|
def on_cycle(p, c, t):
|
||||||
|
w, m = c.car_solar, c.car_writer
|
||||||
|
t = float(t)
|
||||||
|
if sim.own_ph is None and getattr(w, "_own_n", None) is not None:
|
||||||
|
sim.own_ph = w._own_n
|
||||||
|
HIST[t] = (w.mismatch_since, w.hold, getattr(w, "_own_n", None),
|
||||||
|
getattr(w, "_win_t1", None),
|
||||||
|
None if w.seq is None else w.seq["stage"],
|
||||||
|
p.ch.phases_allowed, p.ch.own_ph, p.ch.ph_other_at,
|
||||||
|
w.sent_a, p.ch.setpoint_a)
|
||||||
|
held = w.hold
|
||||||
|
was_hold = mem["hold"]
|
||||||
|
ms = w.mismatch_since is not None
|
||||||
|
# N8
|
||||||
|
if (held or ms) and c.car_solar_can_cut():
|
||||||
|
bad.append((seed, t, "N8 can_cut under a mismatch or hold"))
|
||||||
|
# N10: Manual never judges phases
|
||||||
|
if getattr(m, "_ph_diff", False):
|
||||||
|
bad.append((seed, t, "N10 Manual judges phases"))
|
||||||
|
# N3: a mismatch or hold needs a foreign event shortly before
|
||||||
|
# (judged where it starts: a foreign value that stands unseen while
|
||||||
|
# Solar does not watch, no car or a fault, is seen when it does)
|
||||||
|
explained = (sim.ph_other_at is not None
|
||||||
|
or sim.cur_other_at is not None
|
||||||
|
or t - mem["last_foreign"] <= 400
|
||||||
|
or t - mem["press_at"] <= 400)
|
||||||
|
if ((ms and not mem["was_ms"]) or (held and not mem["hold"])) \
|
||||||
|
and not explained:
|
||||||
|
bad.append((seed, t, "N3 mismatch or hold with no foreign event",
|
||||||
|
w.mismatch_since, held))
|
||||||
|
if ms and not mem["was_ms"]:
|
||||||
|
bump("mismatch")
|
||||||
|
if mem["seq"] is not None:
|
||||||
|
bump("mismatch_seq")
|
||||||
|
mem["was_ms"] = ms
|
||||||
|
mem["seq"] = w.seq
|
||||||
|
if held and not mem["hold"]:
|
||||||
|
mem["rises"] += 1
|
||||||
|
bump("hold")
|
||||||
|
if getattr(w, "_ph_diff", False):
|
||||||
|
bump("hold_ph")
|
||||||
|
if mem["hold"] and not held:
|
||||||
|
if t - mem["press_at"] <= 2:
|
||||||
|
bump("lift_press")
|
||||||
|
else:
|
||||||
|
bump("lift_match")
|
||||||
|
mem["hold"] = held
|
||||||
|
# N10: no hold over the value a press took, in the 3 cycles after it
|
||||||
|
if held and 0 <= t - mem["press_at"] <= 3 \
|
||||||
|
and t - mem["last_foreign"] > 3:
|
||||||
|
bad.append((seed, t, "N10 hold right after a press"))
|
||||||
|
# N9: one CHARGER_OTHER per hold
|
||||||
|
others = len([1 for m_ in LOG.since(mem.get("mark", 0), "WARNING")
|
||||||
|
if "CHARGER_OTHER" in m_])
|
||||||
|
if others > mem["rises"]:
|
||||||
|
bad.append((seed, t, "N9 more CHARGER_OTHER than holds", others,
|
||||||
|
mem["rises"]))
|
||||||
|
# N5: the cut cap
|
||||||
|
if w.cut_fails > carmode.MAX_TRIES:
|
||||||
|
bad.append((seed, t, "N5 cut tries over the cap", w.cut_fails))
|
||||||
|
# N1 / N2 / N7 on the writes of this cycle
|
||||||
|
for e in p.wlog[mem["n_wlog"]:]:
|
||||||
|
# a write waits for its read-back, so its own stamp runs ahead of
|
||||||
|
# the cycle that sent it: judge by the cycle's second
|
||||||
|
tt, what, v = t, e[1], e[2]
|
||||||
|
if what == "current" and v > 0:
|
||||||
|
bump("nz_write")
|
||||||
|
for lab, since in (("N1 current", sim.cur_other_at),
|
||||||
|
("N2 phases", sim.ph_other_at)):
|
||||||
|
if since is not None and sim.setter in ("other", "solar") \
|
||||||
|
and tt - since >= WRITER_S + 2 \
|
||||||
|
and mem["press_at"] < since:
|
||||||
|
bad.append((seed, tt, lab, "write over a foreign "
|
||||||
|
"value that stood", v, since))
|
||||||
|
if what == "phases":
|
||||||
|
bump("select")
|
||||||
|
if sim.ph_other_at is not None \
|
||||||
|
and tt - sim.ph_other_at >= WRITER_S + 2 \
|
||||||
|
and mem["press_at"] < sim.ph_other_at:
|
||||||
|
bad.append((seed, tt, "N2 select over foreign phases",
|
||||||
|
sim.ph_other_at, mem["press_at"],
|
||||||
|
sim.own_ph, sim.phases_allowed))
|
||||||
|
if ms or held:
|
||||||
|
bad.append((seed, tt, "N7 select under a mismatch/hold"))
|
||||||
|
if what == "current" and v == 0.0 and ms and not held:
|
||||||
|
bump("zero_in_count")
|
||||||
|
# (the way-out 0 A of the step in which the count runs out is
|
||||||
|
# written before the watch holds: OQ1)
|
||||||
|
if what == "current" and v == 0.0 and held and was_hold:
|
||||||
|
bad.append((seed, tt, "N2 0 A written under a hold"))
|
||||||
|
mem["n_wlog"] = len(p.wlog)
|
||||||
|
if held and (c.car_mode != "solar" or not c.car_writing()):
|
||||||
|
bump("stop_under_hold")
|
||||||
|
# N4: 6 A never past the pause
|
||||||
|
pause_s = 60.0 * carmode.solar_option(c.o, "ev_pause_min")
|
||||||
|
rd = c.car.reading
|
||||||
|
avail = bool(rd is not None and rd.available)
|
||||||
|
if c.car_mode == "solar" and c.car_writing() and avail \
|
||||||
|
and (w.sent_a or 0.0) >= 6.0 and w.taken \
|
||||||
|
and sim.setter == "solar" and sim.setpoint_a >= 6.0 \
|
||||||
|
and w.plan.low_since is not None \
|
||||||
|
and t - w.plan.low_since > pause_s + 2.0 and not ms and not held:
|
||||||
|
bad.append((seed, t, "N4 6 A past the pause"))
|
||||||
|
|
||||||
|
race = seed % 2 == 1
|
||||||
|
evs = {t: ev for t in range(30, STEPS_PER)}
|
||||||
|
mark = LOG.mark()
|
||||||
|
mem["mark"] = mark
|
||||||
|
mem["n_wlog"] = 0
|
||||||
|
r = S.drive(lambda t: state["house"], lambda t: state["sun"],
|
||||||
|
dur=STEPS_PER, first=rnd.choice(["batteries", "car", "car"]),
|
||||||
|
socs={"a": rnd.uniform(40, 100), "b": rnd.uniform(70, 100)},
|
||||||
|
sim=sim, race=race, events=evs, on_cycle=on_cycle,
|
||||||
|
phases=rnd.choice([1, 3]),
|
||||||
|
opts={"ev_start_min": rnd.choice([1, 1, 2]),
|
||||||
|
"ev_pause_min": rnd.choice([1, 2, 5]),
|
||||||
|
"ev_phases": rnd.choice(["auto"] * 5 + ["1", "3"])})
|
||||||
|
r["_log"] = mark
|
||||||
|
nv = nevers(r, f"N6/N13 seed {seed}", gap=carmode.PHASE_GAP_S)
|
||||||
|
if DEBUG and bad:
|
||||||
|
t0 = float(os.environ.get("EV22_FUZZ_T0") or bad[0][1])
|
||||||
|
print(" DEBUG first bad", bad[0])
|
||||||
|
print(" writes", [(x[0], x[1], x[2]) for x in r["plant"].wlog
|
||||||
|
if t0 - 90 <= x[0] <= t0 + 5])
|
||||||
|
print(" events", sorted(x for x in EVLOG if t0 - 120 <= x[0] <= t0 + 5))
|
||||||
|
print(" lag", sim.lag_s, "seed", seed)
|
||||||
|
print(" selects (plant s, n, refuse_ph, refuse, phases, own)",
|
||||||
|
[x for x in sim.sel_log if t0 - 200 <= x[0] <= t0 + 5])
|
||||||
|
print(" hist (t, ms, hold, own_n, win_end, seq, phases, model own,"
|
||||||
|
" model foreign since)")
|
||||||
|
for tk in sorted(HIST):
|
||||||
|
if t0 - 40 <= tk <= t0 + 2:
|
||||||
|
print(" ", tk, HIST[tk])
|
||||||
|
return bad, nv
|
||||||
|
|
||||||
|
|
||||||
|
print("T38: THE FUZZ")
|
||||||
|
allbad, allnv = [], []
|
||||||
|
for seed in (ONLY or range(SITES)):
|
||||||
|
bad, nv = fuzz_site(seed)
|
||||||
|
allbad += bad
|
||||||
|
allnv += nv
|
||||||
|
if bad:
|
||||||
|
print(" seed", seed, bad[:2])
|
||||||
|
check(f"T38: N1-N5, N7-N10 hold in every cycle of {SITES} seeds x "
|
||||||
|
f"{STEPS_PER} s ({allbad[:3]})", not allbad)
|
||||||
|
WHAT = {
|
||||||
|
"N1": "no non-zero current write over a foreign current that stood "
|
||||||
|
"WRITER_S (the close, the EV-28 restore, an undo included)",
|
||||||
|
"N2": "no non-zero write and no select over foreign phases that stood "
|
||||||
|
"WRITER_S; a 0 A is never written under a hold",
|
||||||
|
"N3": "no mismatch, hold or CHARGER_OTHER without a foreign event shortly "
|
||||||
|
"before (own writes, own selects, own sequence values, a reading "
|
||||||
|
"from before the step's own 0 A, unknown, stale or failed reads)",
|
||||||
|
"N4": "the N3 reading: never 6 A past pause_s",
|
||||||
|
"N5": "at most MAX_TRIES cut tries per quarter key",
|
||||||
|
"N7": "no phase select under a mismatch or a hold",
|
||||||
|
"N8": "car_solar_can_cut is never True under a mismatch or a hold",
|
||||||
|
"N9": "at most one CHARGER_OTHER per hold",
|
||||||
|
"N10": "Manual never judges phases; no hold right after a press",
|
||||||
|
}
|
||||||
|
for k, txt in WHAT.items():
|
||||||
|
check(f"{k}: {txt} (every cycle of {SITES} seeds)",
|
||||||
|
not [b for b in allbad if b[2].split()[0] == k])
|
||||||
|
check(f"N6: no write above the clamp, a select only at 0 A under 100 W, one "
|
||||||
|
f"per 600 s, no Traceback (nevers of every seed) ({allnv[:2]})",
|
||||||
|
not allnv)
|
||||||
|
print(" counts", dict(sorted(COUNT.items())), "UP_S", carmode.UP_S,
|
||||||
|
"PHASE_GAP_S", carmode.PHASE_GAP_S)
|
||||||
|
floor = {"mismatch_seq": 20, "hold_ph": 10, "lift_match": 10, "lift_press": 10,
|
||||||
|
"lift_press_seq": 5, "zero_in_count": 5, "stop_under_hold": 5,
|
||||||
|
"late_after": 5}
|
||||||
|
if STEPS_PER >= 3600:
|
||||||
|
check(f"T38: the fuzz reaches its branches ({ {k: COUNT.get(k, 0) for k in floor} }, "
|
||||||
|
f"floor {floor})", all(COUNT.get(k, 0) >= v for k, v in floor.items()))
|
||||||
|
report()
|
||||||
@@ -704,7 +704,8 @@ async def t15():
|
|||||||
await w.step(19)
|
await w.step(19)
|
||||||
w.sim.refuse = "error"
|
w.sim.refuse = "error"
|
||||||
await w.step(40)
|
await w.step(40)
|
||||||
mid = (list(calls), w.wr.seq is None and w.wr.fails == 1,
|
mid = (list(calls), w.wr.seq is None and w.wr.fails == MAX_TRIES
|
||||||
|
and w.wr.gave_up,
|
||||||
bool(w.writes("phases")))
|
bool(w.writes("phases")))
|
||||||
w.sim.refuse = None
|
w.sim.refuse = None
|
||||||
await w.step(int(carmode.RETRY_S) + 10)
|
await w.step(int(carmode.RETRY_S) + 10)
|
||||||
@@ -715,11 +716,14 @@ w, (calls, over, anyph) = run(t15())
|
|||||||
tries = [c for c in calls if c[1] == 16.0]
|
tries = [c for c in calls if c[1] == 16.0]
|
||||||
gaps = [round(b[0] - a[0]) for a, b in zip(tries, tries[1:])]
|
gaps = [round(b[0] - a[0]) for a, b in zip(tries, tries[1:])]
|
||||||
check(f"T15: the restore is refused: tried {len(tries)} times ~5 s apart "
|
check(f"T15: the restore is refused: tried {len(tries)} times ~5 s apart "
|
||||||
f"({gaps}), no select, sequence ends, one failed write counted",
|
f"({gaps}), no select, sequence ends, the 3 closes counted: given up "
|
||||||
|
"(EV-59)",
|
||||||
len(tries) == MAX_TRIES and all(4 <= g <= 6 for g in gaps) and over
|
len(tries) == MAX_TRIES and all(4 <= g <= 6 for g in gaps) and over
|
||||||
and not anyph and not w.writes("phases"))
|
and not anyph and not w.writes("phases"))
|
||||||
check("T15: after the refusal ends the current is back at 16 A, never a "
|
check("T15: EV-59: given up after the 3 closes: no 4th try, the current stays "
|
||||||
"select", w.sim.readback_a == 16 and not w.writes("phases"))
|
"at 0 A until a user change, never a select",
|
||||||
|
w.sim.readback_a == 0 and len(tries) == MAX_TRIES
|
||||||
|
and not w.writes("phases"))
|
||||||
|
|
||||||
|
|
||||||
# --- T14: the controller level (the EV-15 harness) ------------------------- #
|
# --- T14: the controller level (the EV-15 harness) ------------------------- #
|
||||||
|
|||||||
@@ -55,10 +55,13 @@ GOLDEN = {
|
|||||||
# and the refusing (R) stub.
|
# and the refusing (R) stub.
|
||||||
"T20 T1 [A]": "905c0b8ba89bb307", "T20 T1 [R]": "343ea01aacfa1019",
|
"T20 T1 [A]": "905c0b8ba89bb307", "T20 T1 [R]": "343ea01aacfa1019",
|
||||||
"T20 T4 [A]": "ff6306ce56b35c64", "T20 T4 [R]": "f1fb141275839562",
|
"T20 T4 [A]": "ff6306ce56b35c64", "T20 T4 [R]": "f1fb141275839562",
|
||||||
"T20 T5 [A]": "369069be9187ab3c", "T20 T5 [R]": "ba32810fbb40d0f9",
|
"T20 T5 [A]": "369069be9187ab3c", "T20 T5 [R]": "78ffe9cf72c5e214", # EV-59
|
||||||
"T20 T8 [A]": "2cd78dee7ee93aaa", "T20 T8 [R]": "f0adb058a5bbefba",
|
"T20 T8 [A]": "2cd78dee7ee93aaa", "T20 T8 [R]": "f0adb058a5bbefba",
|
||||||
"T20 T11 [A]": "6d7bcb747d1dc5a3", "T20 T11 [R]": "2be1a760b699b28c",
|
"T20 T11 [A]": "6d7bcb747d1dc5a3", "T20 T11 [R]": "2be1a760b699b28c",
|
||||||
"T20 T12 [A]": "a5888e4557b4ee8f", "T20 T12 [R]": "2fd24ddbb18f14cc",
|
"T20 T12 [A]": "a5888e4557b4ee8f",
|
||||||
|
# EV-60 (Q4): re-taken; the only change from 2fd24ddbb18f14cc is Solar's
|
||||||
|
# `fails` 4 -> 3 in cycles 323-372 (after the 3rd close: no extra _failed).
|
||||||
|
"T20 T12 [R]": "25a205989dc44204",
|
||||||
"T20 T13 [A]": "1ad97e089468d71b", "T20 T13 [R]": "7baf8981ab382e05",
|
"T20 T13 [A]": "1ad97e089468d71b", "T20 T13 [R]": "7baf8981ab382e05",
|
||||||
"T20 T15 [A]": "54701b140ec6f30b", "T20 T15 [R]": "0cfd3ccd334f378d",
|
"T20 T15 [A]": "54701b140ec6f30b", "T20 T15 [R]": "0cfd3ccd334f378d",
|
||||||
"T20 T15d [A]": "1d85595302dc032a", "T20 T15d [R]": "5fc65dbdc730e539",
|
"T20 T15d [A]": "1d85595302dc032a", "T20 T15d [R]": "5fc65dbdc730e539",
|
||||||
@@ -598,28 +601,30 @@ before5 = row_at(x5, t_end - 1)
|
|||||||
check(f"T5: the close raises (_advance): writer equal to R ({eq5[:1]})",
|
check(f"T5: the close raises (_advance): writer equal to R ({eq5[:1]})",
|
||||||
not eq5)
|
not eq5)
|
||||||
check(f"T5: close tries {ts(c5)} at settle end ({t_sel} + 10), +5, +10; then "
|
check(f"T5: close tries {ts(c5)} at settle end ({t_sel} + 10), +5, +10; then "
|
||||||
f"seq None, reapply, last_a None, fails 1, the sequence failed, "
|
f"seq None, reapply, last_a None, fails MAX_TRIES, gave_up, the "
|
||||||
f"phase_done_at None ({end5 and end5[1]})",
|
f"sequence failed, phase_done_at None ({end5 and end5[1]})",
|
||||||
present(t_sel) and near_seq(ts(c5)[:3], [t_sel + 10, t_sel + 15,
|
present(t_sel) and near_seq(ts(c5)[:3], [t_sel + 10, t_sel + 15,
|
||||||
t_sel + 20])
|
t_sel + 20])
|
||||||
and end5 is not None and before5 is not None
|
and end5 is not None and before5 is not None
|
||||||
and end5[1]["seq"] is None and end5[1]["reapply"] is True
|
and end5[1]["seq"] is None and end5[1]["reapply"] is True
|
||||||
and end5[1]["last_a"] is None and end5[1]["fails"] == 1
|
and end5[1]["last_a"] is None and end5[1]["fails"] == CM.MAX_TRIES
|
||||||
|
and end5[1]["gave_up"] is True
|
||||||
and before5[1]["seq"] is not None and before5[1]["seq"][2] is True
|
and before5[1]["seq"] is not None and before5[1]["seq"][2] is True
|
||||||
and end5[1]["phase_done_at"] is None)
|
and end5[1]["phase_done_at"] is None)
|
||||||
nxt5 = calls(x5, t_end + 1 if present(t_end) else BIG)
|
nxt5 = calls(x5, t_end + 1 if present(t_end) else BIG)
|
||||||
check(f"T5: no write for 60 s after ({ts(nxt5)[:1]}); the car stays at 0 A "
|
check(f"T5: EV-59: no write after the 3rd close ({ts(nxt5)[:1]}); the car "
|
||||||
f"to 300 s ({x5['sim'].setpoint_a}); 1 record for the close value "
|
f"stays at 0 A to 300 s ({x5['sim'].setpoint_a}); 1 record for the "
|
||||||
f"({len(recs(x5))})",
|
f"close value ({len(recs(x5))})",
|
||||||
present(t_end) and nth(ts(nxt5), 0) - t_end >= 59
|
present(t_end) and not nxt5
|
||||||
and x5["sim"].setpoint_a == 0.0 and len(recs(x5)) == 1)
|
and x5["sim"].setpoint_a == 0.0 and len(recs(x5)) == 1)
|
||||||
never("T5", x5, close_ok=True)
|
never("T5", x5, close_ok=True)
|
||||||
for k in "RX":
|
for k in "RX":
|
||||||
six = calls(R5[k], 100, 300, a=6.0)
|
six = calls(R5[k], 100, 300, a=6.0)
|
||||||
gold = golden(f"T5b [{k}]", six)
|
gold = golden(f"T5b [{k}]", six)
|
||||||
check(f"T5b [{k}] (H3, not worse than base): the close value's tries "
|
check(f"T5b [{k}] (H3, not worse than base): the close value's tries "
|
||||||
f"{six} = base R's {GOLDEN['T5b']} (5, never a 6th)",
|
f"{six} = base R's first 3 {GOLDEN['T5b'][:3]} (EV-59: 3, never a "
|
||||||
near_seq(ts(six), ts(GOLDEN["T5b"])) and len(six) == 5)
|
f"4th)",
|
||||||
|
near_seq(ts(six), ts(GOLDEN["T5b"][:3])) and len(six) == CM.MAX_TRIES)
|
||||||
del gold
|
del gold
|
||||||
|
|
||||||
def shadow_on(p, c):
|
def shadow_on(p, c):
|
||||||
@@ -887,12 +892,13 @@ e12 = row_at(x12, t12)
|
|||||||
check(f"T12: the change's close raises: writer equal to R ({eq12[:1]})",
|
check(f"T12: the change's close raises: writer equal to R ({eq12[:1]})",
|
||||||
not eq12)
|
not eq12)
|
||||||
check(f"T12: 3 close tries 5 s apart ({ts(c12)[:3]}); then seq None, the "
|
check(f"T12: 3 close tries 5 s apart ({ts(c12)[:3]}); then seq None, the "
|
||||||
f"change ended ({e12 and e12[2]['plan']}), fails 4 as with R "
|
f"change ended ({e12 and e12[2]['plan']}), fails MAX_TRIES as with R "
|
||||||
|
f"(EV-60: no extra _failed at Solar's close end) "
|
||||||
f"({e12 and e12[2]['fails']}); the car at 0 A; one select only "
|
f"({e12 and e12[2]['fails']}); the car at 0 A; one select only "
|
||||||
f"({sel12})",
|
f"({sel12})",
|
||||||
len(c12) >= 3 and gaps(ts(c12)[:3]) == [5.0, 5.0]
|
len(c12) >= 3 and gaps(ts(c12)[:3]) == [5.0, 5.0]
|
||||||
and e12 is not None and e12[2]["seq"] is None
|
and e12 is not None and e12[2]["seq"] is None
|
||||||
and e12[2]["fails"] == 4 and e12[2]["plan"][2] is False
|
and e12[2]["fails"] == CM.MAX_TRIES and e12[2]["plan"][2] is False
|
||||||
and x12["sim"].setpoint_a == 0.0 and len(sel12) == 1)
|
and x12["sim"].setpoint_a == 0.0 and len(sel12) == 1)
|
||||||
never("T12", x12, close_ok=True)
|
never("T12", x12, close_ok=True)
|
||||||
|
|
||||||
@@ -1034,6 +1040,12 @@ def c4b(kind):
|
|||||||
return r
|
return r
|
||||||
drv = Drv(8.0, answer)
|
drv = Drv(8.0, answer)
|
||||||
w, trk, run = solar_writer(8.0), Trk(), Runner()
|
w, trk, run = solar_writer(8.0), Trk(), Runner()
|
||||||
|
# EV-60: the capped change ends and the plan is back at 8 A; the real
|
||||||
|
# plan lowers it to the cap again at its next step (SolarPlan.step), so
|
||||||
|
# nothing above the cap is written.
|
||||||
|
w._plan_step = lambda *a, **k: (
|
||||||
|
w.plan._cut(w.cut_a) if w.cut_a is not None and w.cut_a >= CH.MIN_A
|
||||||
|
and w.plan.a > w.cut_a else None)
|
||||||
w.cut_a, w.cut_on = 0.0, True
|
w.cut_a, w.cut_on = 0.0, True
|
||||||
w.plan.a = 0.0
|
w.plan.a = 0.0
|
||||||
t = 0
|
t = 0
|
||||||
@@ -1053,12 +1065,13 @@ def c4b(kind):
|
|||||||
return tries, w.cut_fails, run
|
return tries, w.cut_fails, run
|
||||||
|
|
||||||
|
|
||||||
for route, fn, want, cf in (("a", c4c, [0, 60, 120, 180], 4),
|
for route, fn, want, cf in (("a", c4c, [0, 60, 120], 3),
|
||||||
("b", c4b, [0, 60, 120, 192, 197, 202], 7)):
|
("b", c4b, [0, 60, 120], 3)):
|
||||||
res = {k: fn(k) for k in "RX"}
|
res = {k: fn(k) for k in "RX"}
|
||||||
check(f"T19b [{route}] (H4, not worse than base): refused cut tries per "
|
check(f"T19b [{route}] (H4, EV-60: never past the cap of MAX_TRIES): "
|
||||||
f"key R {res['R'][0]} cut_fails {res['R'][1]}, X {res['X'][0]} "
|
f"refused cut tries per key R {res['R'][0]} cut_fails "
|
||||||
f"cut_fails {res['X'][1]} = base {want} / {cf}; no record",
|
f"{res['R'][1]}, X {res['X'][0]} cut_fails {res['X'][1]} = "
|
||||||
|
f"{want} / {cf} (base had 4 / 7 tries); no record",
|
||||||
res["R"][0] == res["X"][0] == want
|
res["R"][0] == res["X"][0] == want
|
||||||
and res["R"][1] == res["X"][1] == cf
|
and res["R"][1] == res["X"][1] == cf
|
||||||
and not res["X"][2].recs() and not res["R"][2].recs())
|
and not res["X"][2].recs() and not res["R"][2].recs())
|
||||||
|
|||||||
@@ -0,0 +1,824 @@
|
|||||||
|
"""EV-59: Manual gives one value at most MAX_TRIES tries per user change, the
|
||||||
|
phase-change closes included. `python3 -B test_ev59.py`
|
||||||
|
|
||||||
|
Rows T1-T25 and N1-N14 of reports/EV-59-test-plan.md. Here: T1-T13, T14c, T15
|
||||||
|
(the answering charger, writer level), T16, T17, T18 (source checks on the
|
||||||
|
edited test files), T20-T25, T11c and N1-N14 (N8, N10, N11 as source checks).
|
||||||
|
Carried by other suites, green and unedited: T14a, T14b, T14d (test_ev56 T8,
|
||||||
|
T11, T12, T13, T19b and their T20 digests), T15's T20 digests (test_ev56
|
||||||
|
[A]), T12b/T12c's EV-28 side (test_ev28 T11-T13), T19 (the listed suites).
|
||||||
|
EDITED, not unedited: test_ev56 T5, T5b and the golden "T20 T5 [R]" (Q1, Q2),
|
||||||
|
test_ev28 T15 (Q3, T11c), test_ev13 T13 text and T26 goldens (rulings).
|
||||||
|
The `ManualWriter` / `SolarWriter` on a stub driver, a stub tracker
|
||||||
|
and a stub reading; time is the 1 s step counter, never wall time. The close
|
||||||
|
of the plan's T5 world: 0 A at t=0 and the select at t=1, both taken, so the
|
||||||
|
settle ends at s=11 and the closes are at 11, 16, 21.
|
||||||
|
|
||||||
|
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 carmode as CM # noqa: E402
|
||||||
|
|
||||||
|
fails = []
|
||||||
|
CLOCK = {"t": 0}
|
||||||
|
LOG = []
|
||||||
|
BIG = 1e12
|
||||||
|
REF = "CHARGER_REFUSED"
|
||||||
|
REC = "The car charger step failed"
|
||||||
|
|
||||||
|
|
||||||
|
class Cap(logging.Handler):
|
||||||
|
def emit(self, rec):
|
||||||
|
LOG.append((CLOCK["t"], rec.levelname, rec.getMessage()))
|
||||||
|
|
||||||
|
|
||||||
|
logging.getLogger("goodwe").addHandler(Cap())
|
||||||
|
logging.getLogger("goodwe").setLevel(logging.DEBUG)
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, cond):
|
||||||
|
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||||
|
if not cond:
|
||||||
|
fails.append(name)
|
||||||
|
|
||||||
|
|
||||||
|
class Rd:
|
||||||
|
def __init__(self, a, ph=1, power=None, state="C"):
|
||||||
|
self.available = True
|
||||||
|
self.allowed_a = self.setpoint_a = a
|
||||||
|
self.phases_allowed = ph
|
||||||
|
self.power_w = power
|
||||||
|
self.state = state
|
||||||
|
self.error = False
|
||||||
|
self.charging = True
|
||||||
|
self.current_a = ()
|
||||||
|
self.station_a = None
|
||||||
|
|
||||||
|
|
||||||
|
class Trk:
|
||||||
|
obs_at = None
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.notes = []
|
||||||
|
|
||||||
|
def begin_write(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def end_write(self, *_):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def note_write(self, now, was, a, ok, polls=()):
|
||||||
|
self.notes.append((now, a, ok))
|
||||||
|
|
||||||
|
def stuck(self, now):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class Drv:
|
||||||
|
"""answer(a, n) -> True | False | "raise"; True sets the charger. `sel`:
|
||||||
|
the answer to write_phases. `phases_log`: (t, n, the power seen then)."""
|
||||||
|
|
||||||
|
def __init__(self, cur, answer, ph=1, sel=True):
|
||||||
|
self.cur, self.ph, self.answer, self.sel = cur, ph, answer, sel
|
||||||
|
self.calls, self.now, self.polls = [], 0.0, ()
|
||||||
|
self.phases_log, self.power = [], None
|
||||||
|
|
||||||
|
async def write_current(self, a, **kw):
|
||||||
|
self.calls.append((self.now, float(a)))
|
||||||
|
r = self.answer(float(a), len(self.calls))
|
||||||
|
if r == "raise":
|
||||||
|
raise RuntimeError("HA call error")
|
||||||
|
if r:
|
||||||
|
self.cur = float(a)
|
||||||
|
return bool(r)
|
||||||
|
|
||||||
|
async def write_phases(self, n):
|
||||||
|
self.phases_log.append((self.now, n, self.power))
|
||||||
|
if self.sel:
|
||||||
|
self.ph = n
|
||||||
|
return self.sel
|
||||||
|
|
||||||
|
|
||||||
|
def refuse(a, n):
|
||||||
|
return a == 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def raises(a, n):
|
||||||
|
return True if a == 0.0 else "raise"
|
||||||
|
|
||||||
|
|
||||||
|
def snap(w):
|
||||||
|
q = w.seq
|
||||||
|
return dict(fails=w.fails, gave_up=w.gave_up, fail_at=w.fail_at,
|
||||||
|
seq=None if q is None else (q["stage"], q["tries"]),
|
||||||
|
last_a=w.last_a, reapply=w.reapply, rev_applied=w.rev_applied,
|
||||||
|
phase_done_at=w.phase_done_at, phase_fails=w.phase_fails)
|
||||||
|
|
||||||
|
|
||||||
|
class Run:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def run(answer, secs, *, cls=CM.ManualWriter, cb=None, a=6.0, n=3, cur=10.0,
|
||||||
|
sel=True, power=None, avail=None, clamp=16.0, mode=CM.MANUAL,
|
||||||
|
rd_none=False, w=None):
|
||||||
|
"""One writer run, one step per second. `cb(t, st, w, drv)` may change the
|
||||||
|
request in `st` (a, n, rev, clamp, mode) or call `w.user_changed()` (use
|
||||||
|
`uc`); it may be a coroutine. Per step: the state before and after."""
|
||||||
|
LOG.clear()
|
||||||
|
w, trk = w or cls(), Trk()
|
||||||
|
drv = Drv(cur, answer, sel=sel)
|
||||||
|
st = dict(a=a, n=n, rev=1, clamp=clamp, mode=mode)
|
||||||
|
out = Run()
|
||||||
|
out.w, out.drv, out.trk, out.st = w, drv, trk, st
|
||||||
|
out.rows, out.errs, out.ucs = {}, [], []
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
for t in range(secs):
|
||||||
|
drv.now = float(t)
|
||||||
|
CLOCK["t"] = t
|
||||||
|
if cb:
|
||||||
|
x = cb(t, st, w, drv)
|
||||||
|
if asyncio.iscoroutine(x):
|
||||||
|
await x
|
||||||
|
pw = power(t, drv) if power else (
|
||||||
|
0.0 if drv.cur == 0 else 1380.0)
|
||||||
|
drv.power = pw
|
||||||
|
r = Rd(None if rd_none else drv.cur, drv.ph, power=pw)
|
||||||
|
if avail is not None and not avail(t):
|
||||||
|
r.available = False
|
||||||
|
seq0 = w.seq is not None
|
||||||
|
try:
|
||||||
|
await w.step(drv, r, mode=st["mode"], want_a=st["a"],
|
||||||
|
want_phases=st["n"], rev=st["rev"],
|
||||||
|
clamp=st["clamp"], now=float(t), tracker=trk,
|
||||||
|
writing=True, status="charging")
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
out.errs.append((t, e))
|
||||||
|
d = snap(w)
|
||||||
|
d["seq0"], d["ncalls"] = seq0, len(drv.calls)
|
||||||
|
out.rows[t] = d
|
||||||
|
asyncio.run(main())
|
||||||
|
out.log = list(LOG)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def uc(st, w, t, out_ucs=None, **kw):
|
||||||
|
w.user_changed()
|
||||||
|
st["rev"] += 1
|
||||||
|
st.update(kw)
|
||||||
|
UCS.append(t)
|
||||||
|
|
||||||
|
|
||||||
|
UCS = []
|
||||||
|
|
||||||
|
|
||||||
|
def at(t0, **kw):
|
||||||
|
"""A callback: one user change at t0 with these request changes."""
|
||||||
|
def cb(t, st, w, drv):
|
||||||
|
if t == t0:
|
||||||
|
uc(st, w, t, **kw)
|
||||||
|
return cb
|
||||||
|
|
||||||
|
|
||||||
|
def nz(r, lo=-BIG, hi=BIG, a=None):
|
||||||
|
return [int(t) for t, x in r.drv.calls
|
||||||
|
if x > 0 and lo <= t < hi and (a is None or abs(x - a) < 0.01)]
|
||||||
|
|
||||||
|
|
||||||
|
def zeros(r):
|
||||||
|
return [int(t) for t, x in r.drv.calls if x == 0.0]
|
||||||
|
|
||||||
|
|
||||||
|
def refs(r):
|
||||||
|
return [t for t, lv, m in r.log if lv == "WARNING" and REF in m]
|
||||||
|
|
||||||
|
|
||||||
|
def recs(r):
|
||||||
|
return [t for t, lv, m in r.log if lv == "ERROR" and m == REC]
|
||||||
|
|
||||||
|
|
||||||
|
def near(got_, want, tol=1):
|
||||||
|
return len(got_) == len(want) and all(abs(g - w_) <= tol
|
||||||
|
for g, w_ in zip(got_, want))
|
||||||
|
|
||||||
|
|
||||||
|
def never(name, r, *, ucs=(), clamp=16.0):
|
||||||
|
"""N1 (no non-zero write while given up before a user change), N2 (one
|
||||||
|
REF per give-up), N5 (no select under load), N6 (nothing above the clamp
|
||||||
|
or in 0-6 A), N9 (no exception out of a step), N13 (closes at least 5 s
|
||||||
|
apart, normal tries RETRY_S apart)."""
|
||||||
|
bad1, bad3, up = [], [], 0
|
||||||
|
t_prev, gv = None, False
|
||||||
|
for t in sorted(r.rows):
|
||||||
|
row = r.rows[t]
|
||||||
|
before = r.rows.get(t - 1)
|
||||||
|
n_new = row["ncalls"] - (before["ncalls"] if before else 0)
|
||||||
|
if gv and n_new and not any(u <= t and u > (t_prev or -1) for u in ucs) \
|
||||||
|
and any(x > 0 for tt, x in r.drv.calls if tt == t):
|
||||||
|
bad1.append(t)
|
||||||
|
if row["gave_up"] and not (before or {}).get("gave_up"):
|
||||||
|
up += 1
|
||||||
|
# N3: not before MAX_TRIES tries of the value owed since the
|
||||||
|
# last user change (the last call's value, from that change on).
|
||||||
|
u0 = max([u for u in ucs if u <= t], default=-1)
|
||||||
|
last = [(tt, x) for tt, x in r.drv.calls if tt <= t and x > 0]
|
||||||
|
if last:
|
||||||
|
v = last[-1][1]
|
||||||
|
n_v = len([1 for tt, x in last if tt >= u0])
|
||||||
|
if n_v < CM.MAX_TRIES:
|
||||||
|
bad3.append((t, v, n_v))
|
||||||
|
if not row["gave_up"] and (before or {}).get("gave_up"):
|
||||||
|
gv = False
|
||||||
|
if any(u == t for u in ucs):
|
||||||
|
gv = False
|
||||||
|
elif row["gave_up"]:
|
||||||
|
gv = True
|
||||||
|
t_prev = t
|
||||||
|
nzc = [(t, x) for t, x in r.drv.calls if x > 0]
|
||||||
|
bad13 = []
|
||||||
|
for (ta, aa), (tb, ab) in zip(nzc, nzc[1:]):
|
||||||
|
inseq = r.rows[int(tb)]["seq0"]
|
||||||
|
lim = 5.0 if inseq else CM.RETRY_S
|
||||||
|
user = any(ta < u <= tb for u in ucs)
|
||||||
|
if tb - ta < lim - 1e-9 and not (user and not inseq) \
|
||||||
|
and abs(aa - ab) < 0.01:
|
||||||
|
bad13.append((ta, tb))
|
||||||
|
bad5 = [x for x in r.drv.phases_log if x[2] is not None
|
||||||
|
and x[2] >= CM.QUIET_W]
|
||||||
|
bad6 = [x for _t, x in nzc if x > clamp + 1e-9 or x < 6.0 - 1e-9]
|
||||||
|
check(f"{name}: N3 no give-up before MAX_TRIES tries of the value owed "
|
||||||
|
f"({bad3[:3]})", not bad3)
|
||||||
|
check(f"{name}: N1 no write while given up ({bad1[:3]}); N2 one REF per "
|
||||||
|
f"give-up ({len(refs(r))} for {up}); N5 no select under load "
|
||||||
|
f"({bad5[:2]}); N6 nothing above the clamp or under 6 A "
|
||||||
|
f"({bad6[:3]}); N9 no exception ({r.errs[:1]}); N13 spacing "
|
||||||
|
f"({bad13[:3]})",
|
||||||
|
not bad1 and len(refs(r)) == up and not bad5 and not bad6
|
||||||
|
and not r.errs and not bad13)
|
||||||
|
|
||||||
|
|
||||||
|
print("1. THE REPLAY, THE STATE AT THE CAP (T1, T2, T3, T23)")
|
||||||
|
UCS.clear()
|
||||||
|
R1 = run(refuse, 600)
|
||||||
|
check(f"T1: 6 A tried at {nz(R1)}: 11, 16, 21 and nothing after to 600 s; "
|
||||||
|
"the car stays at 0 A",
|
||||||
|
nz(R1) == [11, 16, 21] and R1.drv.cur == 0.0
|
||||||
|
and all(x == 6.0 for _t, x in R1.drv.calls if x > 0))
|
||||||
|
r21, r20 = R1.rows[21], R1.rows[20]
|
||||||
|
check(f"T2: at the 3rd refused close: seq None, last_a None, reapply, "
|
||||||
|
f"rev_applied None, fails MAX_TRIES, gave_up, fail_at 21, "
|
||||||
|
f"phase_done_at None ({r21}); one REF in that step ({refs(R1)})",
|
||||||
|
r21["seq"] is None and r21["last_a"] is None and r21["reapply"] is True
|
||||||
|
and r21["rev_applied"] is None and r21["fails"] == CM.MAX_TRIES
|
||||||
|
and r21["gave_up"] is True and r21["fail_at"] == 21
|
||||||
|
and r21["phase_done_at"] is None and r21["phase_fails"] == 0
|
||||||
|
and refs(R1) == [21] and r20["gave_up"] is False and r20["fails"] == 0)
|
||||||
|
check("T23: offByOne: the 2nd close (16) does not end the sequence and the "
|
||||||
|
"3rd (21) does; the states up to 16 are the base's",
|
||||||
|
R1.rows[11]["seq"] == ("settle", 1) and R1.rows[16]["seq"] ==
|
||||||
|
("settle", 2) and R1.rows[16]["fails"] == 0
|
||||||
|
and not R1.rows[16]["gave_up"] and R1.rows[21]["seq"] is None
|
||||||
|
and not any(refs(R1)[i] < 21 for i in range(len(refs(R1)))))
|
||||||
|
never("T1", R1)
|
||||||
|
|
||||||
|
RX = run(raises, 600)
|
||||||
|
strip = lambda d: {k: v for k, v in d.items() if k not in ("ncalls",)} # noqa
|
||||||
|
check("T3a: every close raises: calls, states and cycle by cycle as R; 1 "
|
||||||
|
f"ERROR record at 11 ({recs(RX)}), REF at 21 ({refs(RX)}); the "
|
||||||
|
"tracker is not told of a raise",
|
||||||
|
RX.drv.calls == R1.drv.calls
|
||||||
|
and all(strip(RX.rows[t]) == strip(R1.rows[t]) for t in range(600))
|
||||||
|
and recs(RX) == [11] and refs(RX) == [21]
|
||||||
|
and not [x for x in RX.trk.notes if x[1] > 0]
|
||||||
|
and len([x for x in R1.trk.notes if x[1] > 0]) == 3)
|
||||||
|
never("T3a", RX)
|
||||||
|
RM = run(lambda a, n: True if a == 0.0 else ("raise" if n in (2, 4)
|
||||||
|
else False), 600)
|
||||||
|
check("T3b: raise, refuse, raise: 3 tries, 1 ERROR, 1 REF at 21, fails "
|
||||||
|
f"{RM.rows[21]['fails']}",
|
||||||
|
nz(RM) == [11, 16, 21] and recs(RM) == [11] and refs(RM) == [21]
|
||||||
|
and RM.rows[21]["fails"] == CM.MAX_TRIES and RM.rows[21]["gave_up"]
|
||||||
|
and [x[1] for x in RM.trk.notes if x[1] > 0] == [6.0])
|
||||||
|
never("T3b", RM)
|
||||||
|
|
||||||
|
print("\n2. TAKEN CLOSES AND FOLLOW-UPS (T4, T5, T6, T7, T8)")
|
||||||
|
UCS.clear()
|
||||||
|
R4 = run(lambda a, n: a == 0.0 or n == 2, 400, cb=at(100, a=8.0))
|
||||||
|
r4 = R4.rows[11]
|
||||||
|
check(f"T4: the close taken on try 1: seq None, fails 0, no give-up, no REF, "
|
||||||
|
f"phase_done_at 11 ({r4['phase_done_at']}); 8 A at 100 gets 3 tries "
|
||||||
|
f"({nz(R4, 100, a=8.0)}) and one REF ({refs(R4)})",
|
||||||
|
r4["seq"] is None and r4["fails"] == 0 and not r4["gave_up"]
|
||||||
|
and r4["phase_done_at"] == 11 and near(nz(R4, 100, a=8.0),
|
||||||
|
[100, 160, 220])
|
||||||
|
and refs(R4) == [220])
|
||||||
|
never("T4", R4, ucs=[100])
|
||||||
|
for tag, tk in (("a", 3), ("b", 4)):
|
||||||
|
UCS.clear()
|
||||||
|
R5 = run(lambda a, n, tk=tk: a == 0.0 or n == tk, 400, cb=at(100, a=8.0))
|
||||||
|
r5 = R5.rows[40]
|
||||||
|
check(f"T5{tag}: close taken on try {tk - 1}: fails 0, no give-up, no "
|
||||||
|
f"REF, phase_done_at None ({r5['phase_done_at']}); 8 A at 100 gets "
|
||||||
|
f"3 full tries ({nz(R5, 100, a=8.0)})",
|
||||||
|
r5["fails"] == 0 and not r5["gave_up"] and r5["seq"] is None
|
||||||
|
and r5["phase_done_at"] is None
|
||||||
|
and near(nz(R5, 100, a=8.0), [100, 160, 220])
|
||||||
|
and refs(R5) == [220] and R5.rows[21]["fails"] == 0)
|
||||||
|
never(f"T5{tag}", R5, ucs=[100])
|
||||||
|
|
||||||
|
for tag, kw, want in (("a", dict(a=8.0), 8.0), ("b", dict(a=6.0), 6.0)):
|
||||||
|
UCS.clear()
|
||||||
|
R6 = run(refuse, 400, cb=at(100, **kw))
|
||||||
|
got6 = nz(R6, 100, a=want)
|
||||||
|
check(f"T6{tag}: after the give-up a user change to {want:.0f} A: a "
|
||||||
|
f"write at 100 and tries at +60, +120, then REF once more, never "
|
||||||
|
f"a 4th ({got6}, REF {refs(R6)})",
|
||||||
|
near(got6, [100, 160, 220]) and refs(R6) == [21, 220]
|
||||||
|
and R6.rows[100]["gave_up"] is False)
|
||||||
|
never(f"T6{tag}", R6, ucs=[100])
|
||||||
|
UCS.clear()
|
||||||
|
R6c = run(refuse, 760, cb=at(700, n=1))
|
||||||
|
check(f"T6c: after the give-up a 1 phase request (past PHASE_GAP_S): gave_up "
|
||||||
|
f"does not block it; the 0 A at 700 ({zeros(R6c)}), the select at the "
|
||||||
|
f"quiet car, then closes ({nz(R6c, 700)})",
|
||||||
|
near([z for z in zeros(R6c) if z >= 700], [700])
|
||||||
|
and R6c.rows[700]["gave_up"] is False
|
||||||
|
and [x[1] for x in R6c.drv.phases_log if x[0] >= 700] == [1]
|
||||||
|
and near(nz(R6c, 700), [711, 716, 721]) and refs(R6c) == [21, 721])
|
||||||
|
UCS.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def off_then_manual(t, st, w, drv):
|
||||||
|
if t == 100:
|
||||||
|
st["mode"] = "off"
|
||||||
|
if t == 103:
|
||||||
|
st["mode"] = CM.MANUAL
|
||||||
|
uc(st, w, t)
|
||||||
|
|
||||||
|
|
||||||
|
R6d = run(refuse, 400, cb=off_then_manual)
|
||||||
|
check(f"T6d: Off, then Manual at 103: as T6b from the pick "
|
||||||
|
f"({nz(R6d, 100, a=6.0)})",
|
||||||
|
near(nz(R6d, 100, a=6.0), [103, 163, 223]) and refs(R6d) == [21, 223])
|
||||||
|
|
||||||
|
UCS.clear()
|
||||||
|
R7a = run(refuse, 600, avail=lambda t: not 130 <= t < 161)
|
||||||
|
check(f"T7a: the charger away 130-160, back at 161: no write after the "
|
||||||
|
f"return to 600 s ({nz(R7a, 100)}); gave_up stays",
|
||||||
|
nz(R7a, 100) == [] and R7a.rows[599]["gave_up"] and refs(R7a) == [21])
|
||||||
|
never("T7a", R7a)
|
||||||
|
R7b = run(refuse, 600, avail=lambda t: not 12 <= t < 31)
|
||||||
|
check(f"T7b: away between close 1 and 2, back at 31: the count goes on: 3 "
|
||||||
|
f"tries of 6 A ({nz(R7b)}), then the give-up, REF once ({refs(R7b)})",
|
||||||
|
len(nz(R7b, a=6.0)) == 3 and R7b.rows[599]["gave_up"]
|
||||||
|
and len(refs(R7b)) == 1
|
||||||
|
and all(b - a >= 5 for a, b in zip(nz(R7b), nz(R7b)[1:])))
|
||||||
|
never("T7b", R7b)
|
||||||
|
UCS.clear()
|
||||||
|
R7c = run(raises, 600, avail=lambda t: not 130 <= t < 161,
|
||||||
|
cb=at(200, a=6.0))
|
||||||
|
check(f"T7c: X, away and back, then a user change at 200: no write before "
|
||||||
|
f"200 after the return; the record is armed again: ERROR at "
|
||||||
|
f"{recs(R7c)} (1 before 200, 1 after)",
|
||||||
|
not nz(R7c, 100, 200) and len([x for x in recs(R7c) if x < 200]) == 1
|
||||||
|
and len([x for x in recs(R7c) if x >= 200]) == 1)
|
||||||
|
|
||||||
|
UCS.clear()
|
||||||
|
R8 = run(lambda a, n: a == 0.0 or n == 4, 1200, cb=at(700, n=1))
|
||||||
|
b_calls = nz(R8, 700)
|
||||||
|
check(f"T8: sequence A (refused, refused, taken): fails "
|
||||||
|
f"{R8.rows[21]['fails']}, no give-up; then sequence B: 3 tries "
|
||||||
|
f"({b_calls}), no give-up after 1 or 2 "
|
||||||
|
f"({R8.rows[711]['gave_up']}, {R8.rows[716]['gave_up']}), then the "
|
||||||
|
f"give-up and 1 REF ({refs(R8)})",
|
||||||
|
R8.rows[21]["fails"] == 0 and not R8.rows[21]["gave_up"]
|
||||||
|
and near(b_calls, [711, 716, 721])
|
||||||
|
and not R8.rows[711]["gave_up"] and not R8.rows[716]["gave_up"]
|
||||||
|
and R8.rows[721]["gave_up"] and refs(R8) == [721])
|
||||||
|
never("T8", R8, ucs=[700])
|
||||||
|
|
||||||
|
print("\n3. A USER CHANGE DURING THE CLOSE RETRIES (T9, T24)")
|
||||||
|
for tag, t0, kw, want, exp_a, exp_6 in (
|
||||||
|
("a", 18, dict(a=8.0), 8.0, [21, 81, 141], [11, 16]),
|
||||||
|
("b", 13, dict(a=8.0), 8.0, [16, 21, 81], [11])):
|
||||||
|
for how, ans in (("R", refuse), ("X", raises)):
|
||||||
|
UCS.clear()
|
||||||
|
R9 = run(ans, 600, cb=at(t0, **kw))
|
||||||
|
g8 = nz(R9, a=8.0)
|
||||||
|
refs9 = refs(R9)
|
||||||
|
check(f"T9{tag} [{how}]: user change to 8 A at {t0}: 8 A gets "
|
||||||
|
f"exactly 3 tries ({g8}), the 6 A before it ({nz(R9, a=6.0)}); "
|
||||||
|
f"the REF once, at the 3rd try ({refs9}); fails after the "
|
||||||
|
f"close end {R9.rows[21]['fails']}",
|
||||||
|
near(g8, exp_a) and nz(R9, a=6.0) == exp_6
|
||||||
|
and refs9 == [exp_a[-1]]
|
||||||
|
and not any(R9.rows[t]["gave_up"] for t in range(exp_a[-1]))
|
||||||
|
and R9.rows[exp_a[-1]]["gave_up"])
|
||||||
|
never(f"T9{tag} [{how}]", R9, ucs=[t0])
|
||||||
|
UCS.clear()
|
||||||
|
R24 = run(refuse, 600, cb=at(18, a=8.0))
|
||||||
|
check("T24b: the user change after close 2: at the close end (21) fails 1, "
|
||||||
|
f"no give-up ({R24.rows[21]['fails']}, {R24.rows[21]['gave_up']}); the "
|
||||||
|
"normal path gives 2 more tries >= RETRY_S apart, then 1 REF",
|
||||||
|
R24.rows[21]["fails"] == 1 and not R24.rows[21]["gave_up"]
|
||||||
|
and R24.rows[81]["fails"] == 2 and R24.rows[141]["fails"] == 3
|
||||||
|
and R24.rows[141]["gave_up"] and refs(R24) == [141])
|
||||||
|
check("T24a: no user change: k = 3, fails 3, gave_up, 1 REF at the close end "
|
||||||
|
f"({R1.rows[21]['fails']}, {refs(R1)})",
|
||||||
|
R1.rows[21]["fails"] == CM.MAX_TRIES and refs(R1) == [21])
|
||||||
|
UCS.clear()
|
||||||
|
R9c = run(refuse, 600, cb=at(18, a=6.0))
|
||||||
|
after = [t for t in nz(R9c, a=6.0) if t >= 18]
|
||||||
|
check(f"T9c: the same value again at 18: 3 tries after the change ({after}), "
|
||||||
|
f"REF once at the last ({refs(R9c)})",
|
||||||
|
near(after, [21, 81, 141]) and refs(R9c) == [141]
|
||||||
|
and nz(R9c, a=6.0)[:2] == [11, 16])
|
||||||
|
never("T9c", R9c, ucs=[18])
|
||||||
|
UCS.clear()
|
||||||
|
R9d = run(refuse, 600, cb=at(2, a=8.0))
|
||||||
|
check(f"T9 (change before the 1st close): 8 A gets 3 tries "
|
||||||
|
f"({nz(R9d, a=8.0)}), REF {refs(R9d)}",
|
||||||
|
len(nz(R9d, a=8.0)) == 3 and len(refs(R9d)) == 1)
|
||||||
|
|
||||||
|
print("\n4. THE CLAMP, THE RESTORE CLOSES, THE SELECT (T10, T11, T12)")
|
||||||
|
UCS.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def clamp_falls(t, st, w, drv):
|
||||||
|
if t == 18:
|
||||||
|
st["clamp"] = 8.0
|
||||||
|
|
||||||
|
|
||||||
|
R10 = run(refuse, 400, a=10.0, clamp=10.0, cb=clamp_falls)
|
||||||
|
check(f"T10: the clamp falls to 8 A at 18: tries {nz(R10)} with values "
|
||||||
|
f"{[x for _t, x in R10.drv.calls if x > 0]}: never above the clamp then, "
|
||||||
|
f"at most 3 in all, REF once ({refs(R10)})",
|
||||||
|
len(nz(R10)) == 3 and [x for _t, x in R10.drv.calls if x > 0]
|
||||||
|
== [10.0, 10.0, 8.0] and refs(R10) == [21])
|
||||||
|
never("T10", R10, clamp=10.0)
|
||||||
|
|
||||||
|
UCS.clear()
|
||||||
|
R11a = run(refuse, 400, cur=16.0, a=16.0, power=lambda t, d: 1380.0,
|
||||||
|
cb=at(300))
|
||||||
|
check(f"T11a: the drawing timeout, the 16 A restore refused: 3 tries 5 s "
|
||||||
|
f"apart ({nz(R11a, 0, 300)}), fails {R11a.rows[30]['fails']}, "
|
||||||
|
f"gave_up, REF once ({refs(R11a)}); phase_fails "
|
||||||
|
f"{R11a.rows[30]['phase_fails']}; no select ({R11a.drv.phases_log}); "
|
||||||
|
f"a user change writes 16 A at once ({nz(R11a, 300)[:1]})",
|
||||||
|
near(nz(R11a, 0, 300), [20, 25, 30])
|
||||||
|
and R11a.rows[30]["fails"] == CM.MAX_TRIES and R11a.rows[30]["gave_up"]
|
||||||
|
and refs(R11a) == [30] and R11a.rows[30]["phase_fails"] == 1
|
||||||
|
and R11a.rows[20]["fails"] == 0 and R11a.rows[25]["fails"] == 0
|
||||||
|
and not R11a.drv.phases_log and nz(R11a, 300)[:1] == [300])
|
||||||
|
never("T11a", R11a, ucs=[300])
|
||||||
|
UCS.clear()
|
||||||
|
R11b = run(refuse, 400, cur=16.0, a=16.0, sel=False, cb=at(300))
|
||||||
|
check(f"T11b: the select refused, the restore close refused: 3 tries "
|
||||||
|
f"({nz(R11b, 0, 300)}), fails {R11b.rows[21]['fails']}, gave_up, "
|
||||||
|
f"REF once ({refs(R11b)}); phase_fails {R11b.rows[21]['phase_fails']}; "
|
||||||
|
f"1 select try ({len(R11b.drv.phases_log)}); a user change writes at "
|
||||||
|
"once",
|
||||||
|
near(nz(R11b, 0, 300), [11, 16, 21])
|
||||||
|
and R11b.rows[21]["fails"] == CM.MAX_TRIES and R11b.rows[21]["gave_up"]
|
||||||
|
and refs(R11b) == [21] and R11b.rows[21]["phase_fails"] == 1
|
||||||
|
and len(R11b.drv.phases_log) == 1 and nz(R11b, 300)[:1] == [300])
|
||||||
|
never("T11b", R11b, ucs=[300])
|
||||||
|
|
||||||
|
UCS.clear()
|
||||||
|
R12a = run(lambda a, n: a != 0.0, 400)
|
||||||
|
check(f"T12a: only the 0 A fails (_begin): tries {zeros(R12a)} >= 60 s "
|
||||||
|
f"apart, at most 3, no select, REF once ({refs(R12a)})",
|
||||||
|
0 < len(zeros(R12a)) <= 3 and not R12a.drv.phases_log
|
||||||
|
and all(b - a >= 60 for a, b in zip(zeros(R12a), zeros(R12a)[1:]))
|
||||||
|
and len(refs(R12a)) == 1 and R12a.rows[399]["gave_up"])
|
||||||
|
R12b = run(lambda a, n: True, 100, sel=False)
|
||||||
|
check(f"T12b: a refused select counts for the phases only: close taken, fails "
|
||||||
|
f"{R12b.rows[60]['fails']}, phase_fails {R12b.rows[60]['phase_fails']}, "
|
||||||
|
"no REF",
|
||||||
|
R12b.rows[60]["fails"] == 0 and R12b.rows[60]["phase_fails"] == 1
|
||||||
|
and R12b.rows[1]["fails"] == 0 and R12b.rows[1]["phase_fails"] == 1
|
||||||
|
and not refs(R12b) and not R12b.rows[60]["gave_up"])
|
||||||
|
R12c = run(lambda a, n: True, 100, cur=16.0, a=16.0,
|
||||||
|
power=lambda t, d: 1380.0)
|
||||||
|
check(f"T12c: the drawing timeout, the restore taken: fails "
|
||||||
|
f"{R12c.rows[60]['fails']}, no give-up, phase_fails "
|
||||||
|
f"{R12c.rows[60]['phase_fails']}",
|
||||||
|
R12c.rows[60]["fails"] == 0 and not R12c.rows[60]["gave_up"]
|
||||||
|
and R12c.rows[60]["phase_fails"] == 1 and not refs(R12c))
|
||||||
|
|
||||||
|
print("\n5. UNDO, SHUTDOWN, SOLAR, A CHARGER THAT ANSWERS (T13, T14, T15)")
|
||||||
|
UCS.clear()
|
||||||
|
|
||||||
|
|
||||||
|
def off_at(t0):
|
||||||
|
def cb(t, st, w, drv):
|
||||||
|
if t == t0:
|
||||||
|
st["mode"] = "off"
|
||||||
|
return cb
|
||||||
|
|
||||||
|
|
||||||
|
R13a = run(refuse, 100, power=lambda t, d: 1380.0, cb=off_at(5))
|
||||||
|
check(f"T13a: Off in stage zero: 10 A restored once ({nz(R13a)}), undone "
|
||||||
|
f"{R13a.w.undone}, fails {R13a.rows[99]['fails']}",
|
||||||
|
near(nz(R13a, a=10.0), [5]) and len(nz(R13a)) == 1
|
||||||
|
and R13a.w.undone == 1 and R13a.rows[99]["fails"] == 0)
|
||||||
|
R13b = run(refuse, 100, cb=off_at(12))
|
||||||
|
check(f"T13b: Off after close 1: the closes go on ({nz(R13b)}), give-up at "
|
||||||
|
f"21, REF once ({refs(R13b)}), no write after",
|
||||||
|
nz(R13b) == [11, 16, 21] and R13b.rows[21]["gave_up"]
|
||||||
|
and refs(R13b) == [21])
|
||||||
|
|
||||||
|
|
||||||
|
box = {}
|
||||||
|
|
||||||
|
|
||||||
|
def abandon_cb(t0, ans_kind):
|
||||||
|
def cb(t, st, w, drv):
|
||||||
|
if t == t0 + 1:
|
||||||
|
async def go():
|
||||||
|
n0 = len(drv.calls)
|
||||||
|
try:
|
||||||
|
await w.abandon(drv, float(t), Trk(), clamp=16.0)
|
||||||
|
box[ans_kind] = ("ok", len(drv.calls) - n0)
|
||||||
|
except RuntimeError:
|
||||||
|
box[ans_kind] = ("raised", len(drv.calls) - n0)
|
||||||
|
return go()
|
||||||
|
return cb
|
||||||
|
|
||||||
|
|
||||||
|
R13c = run(refuse, 40, cb=abandon_cb(11, "R"))
|
||||||
|
check(f"T13c: shutdown between close 1 and 2: the old 10 A restored once, "
|
||||||
|
f"strict, no exception ({box.get('R')}), seq None, calls {nz(R13c)}",
|
||||||
|
box.get("R") == ("ok", 1) and R13c.w.seq is None
|
||||||
|
and near(nz(R13c, a=10.0), [12]))
|
||||||
|
R13x = run(raises, 40, cb=abandon_cb(11, "X"))
|
||||||
|
check(f"T13c: X: the raise comes out of abandon, as base, for the caller's "
|
||||||
|
f"CHARGER_RESTORE ({box.get('X')}); the writer's seq is None",
|
||||||
|
box.get("X") == ("raised", 1) and R13x.w.seq is None)
|
||||||
|
R13d = run(refuse, 40, cb=abandon_cb(40, "D"))
|
||||||
|
n_d = len(R13d.drv.calls)
|
||||||
|
|
||||||
|
|
||||||
|
async def after_giveup():
|
||||||
|
n0 = len(R13d.drv.calls)
|
||||||
|
await R13d.w.abandon(R13d.drv, 41.0, Trk(), clamp=16.0)
|
||||||
|
return len(R13d.drv.calls) - n0
|
||||||
|
check("T13d: shutdown after the give-up: no write",
|
||||||
|
asyncio.run(after_giveup()) == 0 and R13d.w.gave_up)
|
||||||
|
|
||||||
|
|
||||||
|
def solar_writer(cur):
|
||||||
|
w = CM.SolarWriter()
|
||||||
|
w.engaged, w.mode_was = True, CM.SOLAR
|
||||||
|
w.fresh_start = w.restart = False
|
||||||
|
w.was_available = w._seen = True
|
||||||
|
w.sent_a, w.taken, w.last_a = cur, True, cur
|
||||||
|
w.plan.a, w.plan.n = cur, 1
|
||||||
|
w._plan_step = lambda *a, **k: None
|
||||||
|
return w
|
||||||
|
|
||||||
|
|
||||||
|
def sp3(press, cls=solar_writer):
|
||||||
|
LOG.clear()
|
||||||
|
drv = Drv(8.0, refuse)
|
||||||
|
w, trk = cls(8.0), Trk()
|
||||||
|
w.plan._set(8.0, 0.0, 3)
|
||||||
|
pressed = None
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
nonlocal pressed
|
||||||
|
for t in range(1, 200):
|
||||||
|
if press and pressed is None and \
|
||||||
|
len([x for x in drv.calls if x[1] > 0]) == 1:
|
||||||
|
w.user_changed()
|
||||||
|
pressed = t
|
||||||
|
drv.now = float(t)
|
||||||
|
CLOCK["t"] = t
|
||||||
|
w.cut_quarter(int(t // 900))
|
||||||
|
r = Rd(drv.cur, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
|
||||||
|
await w.step(drv, r, mode=CM.SOLAR,
|
||||||
|
sun=CM.SunInputs(target_w=2000.0), clamp=16.0,
|
||||||
|
now=float(t), tracker=trk, writing=True,
|
||||||
|
status="charging")
|
||||||
|
asyncio.run(main())
|
||||||
|
nzs = [int(t) for t, x in drv.calls if x > 0]
|
||||||
|
rf = [t for t, lv, m in LOG if lv == "WARNING" and REF in m]
|
||||||
|
return nzs, w.fails, w.gave_up, rf, pressed
|
||||||
|
|
||||||
|
|
||||||
|
S_NONE = sp3(False)
|
||||||
|
S_PRESS = sp3(True)
|
||||||
|
check(f"T25/T14 (N14, EV-60): Solar has no extra _failed at its close end. "
|
||||||
|
f"No press: 8 A at 12, 17, 22, fails 3, gave_up, REF at 22 "
|
||||||
|
f"({S_NONE})",
|
||||||
|
S_NONE == ([12, 17, 22], 3, True, [22], None))
|
||||||
|
check(f"T25 (resetSuper trap, EV-60): a Solar press at 13 does not reset "
|
||||||
|
f"Solar's close tries, and the value gets MAX_TRIES tries since the "
|
||||||
|
f"press: 8 A at 12, 17, 22, 82, fails 3, gave_up, REF at 82 "
|
||||||
|
f"({S_PRESS})",
|
||||||
|
S_PRESS == ([12, 17, 22, 82], 3, True, [82], 13))
|
||||||
|
|
||||||
|
def t14c():
|
||||||
|
"""T14c: Solar's close value changes between the tries (the spare falls
|
||||||
|
during the settle): `want_a(q)` is a function of the sequence. `_advance`
|
||||||
|
driven directly on a SolarWriter in stage settle, the close refused."""
|
||||||
|
LOG.clear()
|
||||||
|
w, drv, trk = solar_writer(8.0), Drv(0.0, lambda a, n: False), Trk()
|
||||||
|
w.seq = {"stage": "settle", "t0": 0.0, "n": 3, "tries": 0, "prev": 8.0,
|
||||||
|
"t1": 0.0}
|
||||||
|
vals = {10: 8.0, 15: 7.0, 20: 6.0}
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
for t in range(10, 40):
|
||||||
|
if w.seq is None:
|
||||||
|
break
|
||||||
|
drv.now = float(t)
|
||||||
|
CLOCK["t"] = t
|
||||||
|
r = Rd(drv.cur, drv.ph, power=0.0)
|
||||||
|
await w._advance(drv, r, 0.0, float(t), trk,
|
||||||
|
lambda q: vals.get(t, 5.0), 16.0, 1)
|
||||||
|
asyncio.run(main())
|
||||||
|
rf = [t for t, lv, m in LOG if lv == "WARNING" and REF in m]
|
||||||
|
return ([(int(t), x) for t, x in drv.calls], w.fails, w.gave_up, rf,
|
||||||
|
w.seq)
|
||||||
|
|
||||||
|
|
||||||
|
S14C = t14c()
|
||||||
|
check(f"T14c (N14, EV-60): Solar's close value moves between tries: 8, 7, 6 A "
|
||||||
|
f"at 10, 15, 20, then `fails` 3 (no extra _failed), gave_up, REF at "
|
||||||
|
f"20, seq None ({S14C})",
|
||||||
|
S14C == ([(10, 8.0), (15, 7.0), (20, 6.0)], 3, True, [20], None))
|
||||||
|
|
||||||
|
print("\n6. THE CAP, RESTART, UNKNOWN, NO CHARGER (T15-T22)")
|
||||||
|
UCS.clear()
|
||||||
|
RA = run(lambda a, n: True, 100)
|
||||||
|
check(f"T15: a charger that answers: 0 A at 0, 6 A at 11, nothing else "
|
||||||
|
f"({RA.drv.calls}); fails 0, no give-up, phase_done_at "
|
||||||
|
f"{RA.rows[11]['phase_done_at']}",
|
||||||
|
RA.drv.calls == [(0.0, 0.0), (11.0, 6.0)]
|
||||||
|
and RA.rows[99]["fails"] == 0 and RA.rows[11]["phase_done_at"] == 11
|
||||||
|
and not refs(RA))
|
||||||
|
for cap in (2, 4):
|
||||||
|
UCS.clear()
|
||||||
|
saved = CM.MAX_TRIES
|
||||||
|
CM.MAX_TRIES = cap
|
||||||
|
try:
|
||||||
|
R16 = run(refuse, 400)
|
||||||
|
finally:
|
||||||
|
CM.MAX_TRIES = saved
|
||||||
|
want16 = [11 + 5 * i for i in range(cap)]
|
||||||
|
check(f"T16: MAX_TRIES {cap}: tries {nz(R16)} (never {cap + 1}), give-up "
|
||||||
|
f"at {want16[-1]}, REF {refs(R16)}",
|
||||||
|
nz(R16) == want16 and refs(R16) == [want16[-1]]
|
||||||
|
and R16.rows[want16[-1]]["fails"] == cap
|
||||||
|
and R16.rows[want16[-1]]["gave_up"])
|
||||||
|
UCS.clear()
|
||||||
|
w20 = CM.ManualWriter()
|
||||||
|
check("T20: a restart: the new writer starts with 0 fails, no give-up, and "
|
||||||
|
"no count",
|
||||||
|
w20.fails == 0 and not w20.gave_up
|
||||||
|
and getattr(w20, "_close_k", 0) == 0)
|
||||||
|
R20 = run(refuse, 30, w=w20)
|
||||||
|
check(f"T20: after the restart the first write goes out once ({zeros(R20)})",
|
||||||
|
zeros(R20) == [0])
|
||||||
|
R21 = run(refuse, 400, rd_none=True)
|
||||||
|
check(f"T21: the read-back unknown (allowed and setpoint None): judged by the "
|
||||||
|
f"write's result: tries {nz(R21)}, give-up, REF once ({refs(R21)})",
|
||||||
|
len(nz(R21)) == 3 and R21.rows[399]["gave_up"] and len(refs(R21)) == 1
|
||||||
|
and not R21.errs)
|
||||||
|
R21b = run(refuse, 400, power=lambda t, d: None, cur=16.0, a=16.0)
|
||||||
|
check(f"T21: the power unknown: the drawing timeout's restore is tried 3 "
|
||||||
|
f"times (20, 25, 30), then the give-up and one REF, no exception "
|
||||||
|
f"({nz(R21b)}, {refs(R21b)}, {R21b.errs[:1]})",
|
||||||
|
nz(R21b) == [20, 25, 30] and R21b.rows[30]["gave_up"]
|
||||||
|
and refs(R21b) == [30] and not R21b.errs)
|
||||||
|
R22 = run(refuse, 600, avail=lambda t: False)
|
||||||
|
check("T22: no charger: 0 writes, no lines, no REF",
|
||||||
|
not R22.drv.calls and not R22.log and not refs(R22))
|
||||||
|
|
||||||
|
print("\n6b. A GIVE-UP NEVER BLOCKS THE UNDO, THE SHUTDOWN OR A NEW SEQUENCE (N4)")
|
||||||
|
|
||||||
|
|
||||||
|
def given_up_writer():
|
||||||
|
w = CM.ManualWriter()
|
||||||
|
w.gave_up, w.fails = True, CM.MAX_TRIES
|
||||||
|
w.seq = {"stage": "zero", "t0": 0.0, "n": 3, "tries": 0, "prev": 10.0}
|
||||||
|
return w, Drv(0.0, lambda a, n: True), Trk()
|
||||||
|
|
||||||
|
|
||||||
|
w13, d13, t13 = given_up_writer()
|
||||||
|
asyncio.run(w13._undo(d13, 1.0, t13, 16.0, False))
|
||||||
|
check(f"T13e/N4: `_undo` with gave_up set restores the 10 A ({d13.calls})",
|
||||||
|
d13.calls == [(0.0, 10.0)] and w13.seq is None)
|
||||||
|
w13, d13, t13 = given_up_writer()
|
||||||
|
asyncio.run(w13.abandon(d13, 1.0, t13, clamp=16.0))
|
||||||
|
check(f"T13e/N4: `abandon` with gave_up set gives the 10 A back "
|
||||||
|
f"({d13.calls})", d13.calls == [(0.0, 10.0)] and w13.seq is None)
|
||||||
|
w13, d13, t13 = given_up_writer()
|
||||||
|
w13.seq = None
|
||||||
|
asyncio.run(w13._begin(d13, Rd(10.0), 10.0, 3, 1.0, t13))
|
||||||
|
check(f"T13e/N4: `_begin` with gave_up set still writes the 0 A "
|
||||||
|
f"({d13.calls})", d13.calls == [(0.0, 0.0)] and w13.seq is not None)
|
||||||
|
|
||||||
|
print("\n6c. THE EDITS TO EXISTING TESTS, N7, N12 (T17, T18, T11c, N7, N11, N12)")
|
||||||
|
|
||||||
|
|
||||||
|
def tsrc(name):
|
||||||
|
return open(os.path.join(HERE, name), encoding="utf-8").read()
|
||||||
|
|
||||||
|
|
||||||
|
s56, s13, s28 = tsrc("test_ev56.py"), tsrc("test_ev13.py"), tsrc("test_ev28.py")
|
||||||
|
BASE_DIGESTS = ("905c0b8ba89bb307", "343ea01aacfa1019", "ff6306ce56b35c64",
|
||||||
|
"f1fb141275839562", "369069be9187ab3c", "2cd78dee7ee93aaa",
|
||||||
|
"f0adb058a5bbefba", "6d7bcb747d1dc5a3", "2be1a760b699b28c",
|
||||||
|
# EV-60 (Q4): "T20 T12 [R]" re-taken, was 2fd24ddbb18f14cc
|
||||||
|
"a5888e4557b4ee8f", "25a205989dc44204", "1ad97e089468d71b",
|
||||||
|
"7baf8981ab382e05", "54701b140ec6f30b", "0cfd3ccd334f378d",
|
||||||
|
"1d85595302dc032a", "5fc65dbdc730e539")
|
||||||
|
check("T17 (Q1, Q2): test_ev56 has the re-taken golden 'T20 T5 [R]' "
|
||||||
|
"(78ffe9cf72c5e214, the old ba32810fbb40d0f9 gone), T5 asserts "
|
||||||
|
"fails == MAX_TRIES and gave_up, T5b asserts len == MAX_TRIES",
|
||||||
|
'"T20 T5 [R]": "78ffe9cf72c5e214"' in s56
|
||||||
|
and "ba32810fbb40d0f9" not in s56
|
||||||
|
and 'end5[1]["fails"] == CM.MAX_TRIES' in s56
|
||||||
|
and 'end5[1]["gave_up"] is True' in s56
|
||||||
|
and "len(six) == CM.MAX_TRIES" in s56)
|
||||||
|
check("N11: every other golden digest of test_ev56 is the base's, and "
|
||||||
|
"GOLDEN['T5b'] still holds base's 5 tries",
|
||||||
|
all(f'"{d}"' in s56 for d in BASE_DIGESTS)
|
||||||
|
and '"T5b": [(111.0, 6.0), (116.0, 6.0), (121.0, 6.0), (181.0, 6.0),'
|
||||||
|
in s56)
|
||||||
|
check("T18: test_ev13 T13's check text says 'one refusal counted' and its "
|
||||||
|
"assert is still fails == 1",
|
||||||
|
"no window left, one refusal counted, the mute set" in s13
|
||||||
|
and "no refusal counted" not in s13
|
||||||
|
and "w.c.car_writer.fails == 1 and w.c.car.mute_until > 0" in s13)
|
||||||
|
check("N11: test_ev13 T26 lost only the 4th and 5th tries (1095, 1155) of "
|
||||||
|
"'T20-beside' and 'T20-inside'",
|
||||||
|
s13.count("(1035, 16.0, False)], [(11, 'current', 0.0), "
|
||||||
|
"(15, 'phases', 1)])") == 2
|
||||||
|
and "(1095, 16.0, False)" not in s13
|
||||||
|
and "(1155, 16.0, False)" not in s13)
|
||||||
|
check("T11c: test_ev28 T15 asserts fails == MAX_TRIES, gave_up, 3 tries and "
|
||||||
|
"the car at 0 A with no select (the only edit, ruled Q3)",
|
||||||
|
"w.wr.fails == MAX_TRIES" in s28 and "w.wr.gave_up" in s28
|
||||||
|
and "w.sim.readback_a == 0 and len(tries) == MAX_TRIES" in s28)
|
||||||
|
UCS.clear()
|
||||||
|
RN7 = run(lambda a, n: True, 400, cb=at(100, a=8.0))
|
||||||
|
check(f"N7: a charger that answers: the calls are 0 A at 0, 6 A at 11, 8 A at "
|
||||||
|
f"100 and nothing else ({RN7.drv.calls}); no REF, fails 0, no "
|
||||||
|
"give-up, no ERROR",
|
||||||
|
RN7.drv.calls == [(0.0, 0.0), (11.0, 6.0), (100.0, 8.0)]
|
||||||
|
and not refs(RN7) and not recs(RN7)
|
||||||
|
and RN7.rows[399]["fails"] == 0 and not RN7.rows[399]["gave_up"])
|
||||||
|
n12 = [x for x in R1.trk.notes if x[1] > 0]
|
||||||
|
check(f"N12: the tracker is told of each refused close once ({n12}) and of "
|
||||||
|
f"no raised close ({[x for x in RX.trk.notes if x[1] > 0]}, "
|
||||||
|
f"begin/end per write {RX.trk.notes[:1]})",
|
||||||
|
len(n12) == 3 and all(not ok for _t, _a, ok in n12)
|
||||||
|
and not [x for x in RX.trk.notes if x[1] > 0])
|
||||||
|
|
||||||
|
print("\n7. N4, N8, N10")
|
||||||
|
APP = os.path.join(HERE, "app")
|
||||||
|
SRC = {f: open(os.path.join(APP, f), encoding="utf-8").read()
|
||||||
|
for f in sorted(os.listdir(APP)) if f.endswith(".py")}
|
||||||
|
cm_src = SRC["carmode.py"]
|
||||||
|
check("N8 (write_phases and the peak-cut rules untouched): carmode.py still "
|
||||||
|
"has the one `write_phases(` call and no new write path; base had 1",
|
||||||
|
cm_src.count("write_phases(") == 1
|
||||||
|
and cm_src.count("drv.write_current(") == 1)
|
||||||
|
check("N10 (no new store key, setting, notification or timer): `_close_k` "
|
||||||
|
"lives in carmode.py only, never next to a store or option; the "
|
||||||
|
"asyncio.sleep, create_task and _LOG.warning counts are the base's "
|
||||||
|
"(1, 0, 10)",
|
||||||
|
[f for f, s in SRC.items() if "_close_k" in s] == ["carmode.py"]
|
||||||
|
and cm_src.count("asyncio.sleep") == 1
|
||||||
|
and cm_src.count("create_task") == 0
|
||||||
|
and cm_src.count("_LOG.warning(") == 10
|
||||||
|
and not any("_close_k" in line and ("store" in line or "opts" in line)
|
||||||
|
for line in cm_src.splitlines()))
|
||||||
|
w4 = CM.ManualWriter()
|
||||||
|
w4.gave_up, w4.fails, w4._close_k = True, 3, 3
|
||||||
|
w4.user_changed()
|
||||||
|
check("N4: user_changed clears gave_up, fails and the close count",
|
||||||
|
not w4.gave_up and w4.fails == 0 and w4._close_k == 0)
|
||||||
|
R4n = run(refuse, 400, cb=at(100, a=8.0))
|
||||||
|
check("N4: a give-up does not block the next user change or phase change "
|
||||||
|
f"({nz(R4n, 100)[:1]})", nz(R4n, 100)[:1] == [100])
|
||||||
|
|
||||||
|
print()
|
||||||
|
if fails:
|
||||||
|
print(f"FAIL: {len(fails)} check(s)")
|
||||||
|
for f in fails:
|
||||||
|
print(" -", f)
|
||||||
|
sys.exit(1)
|
||||||
|
print("ok: EV-59")
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,579 @@
|
|||||||
|
"""EV-69: a close value an ended phase change tried stays the add-on's own, so
|
||||||
|
the charger taking it late is never read as another writer (no false
|
||||||
|
CHARGER_OTHER, the peak cut never blocked). `python3 -B test_ev69.py`
|
||||||
|
|
||||||
|
Rows T1-T20, T23-T25 and the Never rules N1-N9 of reports/EV-69-test-plan.md
|
||||||
|
(T21 is test_ev69_fuzz.py, T14 and T22 are the existing suites CI runs). Every
|
||||||
|
check's label starts with its id. Writer level, `tools/ev69_kit.py`: a
|
||||||
|
`SolarWriter` / `ManualWriter` on a stub driver, a stub tracker and a stub
|
||||||
|
reading; time is a 1 s step counter on the model clock. `Base69` is de733f4's
|
||||||
|
behaviour (the carry switched off): the red side of a row, and the equal side
|
||||||
|
of T17 (i).
|
||||||
|
|
||||||
|
"S1" is the EV-22 review repro (round 2): own 3 -> 1 select taken (window from
|
||||||
|
122), clamp 16 up to 134 and 8 from 135, close tries 12 A at 132, 8 A at 137
|
||||||
|
and 142 (all refused), a press at 138, MAX_TRIES ends the change at 142, the
|
||||||
|
12 A shown at 140. "S1-np": no press. "S1-nt": no take at 140. "CE": the
|
||||||
|
EV-60 cap end (cut_fails 2, close 1 refused, cap 6 A, close 2 = 6 A refused,
|
||||||
|
then the cap end E). "MW": the Manual shape.
|
||||||
|
|
||||||
|
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 as CM # noqa: E402
|
||||||
|
from named_absence import nth, present # noqa: E402
|
||||||
|
from ev69_kit import (Base69, BaseM69, Drv, LOG, LOOP, Rd, Run, CLOCK, # noqa: E402,F401
|
||||||
|
REC, cap, check, done, evs, n_other, n_some, near,
|
||||||
|
nev, press, set_cap, show, swriter, LAST)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------ worlds
|
||||||
|
def mk_s1(cls=None, take=None):
|
||||||
|
w = swriter(0.0, ph=3, cls=cls)
|
||||||
|
w.plan.a, w.plan.n = 12.0, 1
|
||||||
|
drv = Drv(0.0, take or (lambda a, d: False), ph=1)
|
||||||
|
w.seq = {"stage": "settle", "t0": 119.0, "t1": 122.0, "n": 1, "tries": 0,
|
||||||
|
"prev": None, "from": 3, "own": [0.0], "sel": True}
|
||||||
|
w.last_done = 122.0
|
||||||
|
w._own_n = 3
|
||||||
|
w._select_try(1, True)
|
||||||
|
return w, drv
|
||||||
|
|
||||||
|
|
||||||
|
def clamp_s1(t):
|
||||||
|
return 16.0 if t < 135 else 8.0
|
||||||
|
|
||||||
|
|
||||||
|
def s1(until=400, ev=(), press_at=138, show_at=140, take=None, cls=None,
|
||||||
|
cur=None, stale=None, gone=None, writing=None):
|
||||||
|
w, drv = mk_s1(cls, take)
|
||||||
|
pairs = list(ev)
|
||||||
|
if press_at is not None:
|
||||||
|
pairs.append((press_at, press))
|
||||||
|
if show_at is not None:
|
||||||
|
pairs.append((show_at, lambda w_, d, s: setattr(
|
||||||
|
d, "cur", d.calls[0][1])))
|
||||||
|
r = Run(w, drv)
|
||||||
|
return r.go(123, until, ev=evs(*pairs), clamp=clamp_s1, cur=cur,
|
||||||
|
stale=stale, gone=gone, writing=writing)
|
||||||
|
|
||||||
|
|
||||||
|
def mk_ce(cls=None, take=None, cut_fails=2, plan_a=8.0):
|
||||||
|
w = swriter(plan_a, ph=1, cls=cls)
|
||||||
|
w.cut_key, w.cut_fails, w.cut_fail_at = 0, cut_fails, -100.0
|
||||||
|
w.plan._set(plan_a, 130.0, 3)
|
||||||
|
drv = Drv(plan_a, take or (lambda a, d: a == 0.0), ph=1)
|
||||||
|
return w, drv
|
||||||
|
|
||||||
|
|
||||||
|
def ce(until=960, cls=None, hook=None, ev=(), plan_a=8.0, take=None,
|
||||||
|
press_after_close2=False):
|
||||||
|
"""Close 1 refused, the cap comes in the step after it, close 2 (a cut
|
||||||
|
try, 6 A) refused, then the cap end E."""
|
||||||
|
w, drv = mk_ce(cls, take, plan_a=plan_a)
|
||||||
|
st = {"cap": False}
|
||||||
|
|
||||||
|
def h(t, w_, d, s):
|
||||||
|
nz = [1 for tt, a in d.calls if a > 0]
|
||||||
|
if nz and not s["cap"]:
|
||||||
|
s["cap"] = True
|
||||||
|
set_cap(w_, 6.0)
|
||||||
|
if press_after_close2 and len(nz) == 2 and not s.get("pr"):
|
||||||
|
s["pr"] = True
|
||||||
|
w_.user_changed()
|
||||||
|
if hook:
|
||||||
|
hook(t, w_, d, s)
|
||||||
|
r = Run(w, drv, st=st)
|
||||||
|
return r.go(130, until, ev=evs(*ev), hook=h)
|
||||||
|
|
||||||
|
|
||||||
|
def close_times(r):
|
||||||
|
return [int(t) for t, a in r.drv.calls if a > 0]
|
||||||
|
|
||||||
|
|
||||||
|
def mw(until, user=False, hook2=None, cls=None):
|
||||||
|
"""Manual at 12 A on 1 phase; the user picks 3 phases at 100. Every
|
||||||
|
current write but the 0 A is refused. Close 1 = 12 A, then the clamp
|
||||||
|
falls to 8 (or the user lowers the current to 8) before try 2."""
|
||||||
|
w = (cls or CM.ManualWriter)()
|
||||||
|
drv = Drv(12.0, lambda a, d: a == 0.0, ph=1)
|
||||||
|
st = {"a": 12.0, "n": 1, "rev": 1, "clamp": 16.0}
|
||||||
|
r = Run(w, drv, kind="manual", st=st)
|
||||||
|
|
||||||
|
def hook(t, w_, d, s):
|
||||||
|
if t == 100:
|
||||||
|
w_.user_changed()
|
||||||
|
s["rev"] += 1
|
||||||
|
s["n"] = 3
|
||||||
|
nzc = [1 for tt, a in d.calls if a > 0]
|
||||||
|
if len(nzc) == 1 and not s.get("low"):
|
||||||
|
s["low"] = True
|
||||||
|
if user:
|
||||||
|
w_.user_changed()
|
||||||
|
s["rev"] += 1
|
||||||
|
s["a"] = 8.0
|
||||||
|
else:
|
||||||
|
s["clamp"] = 8.0
|
||||||
|
if hook2:
|
||||||
|
hook2(t, w_, d, s)
|
||||||
|
return r.go(0, until, hook=hook)
|
||||||
|
|
||||||
|
|
||||||
|
# =========================================================================== #
|
||||||
|
print("S1 (the reviewer's clamp shape), Solar")
|
||||||
|
# =========================================================================== #
|
||||||
|
cut150 = (150, cap(6.0))
|
||||||
|
base = s1(400, ev=[cut150], cls=Base69)
|
||||||
|
check(f"T1 [red on base]: S1 on de733f4 (the carry off): mismatch "
|
||||||
|
f"{base.first_ms(140)}, hold {base.first_hold()}, no peak cut write "
|
||||||
|
f"({base.calls_from(143, 400, True)[:3]})",
|
||||||
|
near(base.first_ms(140), 143, 144) and near(base.first_hold(), 173, 174)
|
||||||
|
and 6.0 not in [a for _, a in base.calls_from(143, 200)])
|
||||||
|
r = s1(400, ev=[cut150])
|
||||||
|
cut_w = [x for x in r.calls_from(150, 152) if x[1] == 6.0]
|
||||||
|
check(f"T1: S1 (12 A shown at 140), the cut due at 150: 140-400 no mismatch, "
|
||||||
|
f"hold, CHARGER_OTHER or 'Something else' line ({r.first_ms(140)}, "
|
||||||
|
f"{n_other()}, {n_some()}), the 6 A peak cut write "
|
||||||
|
f"at 150-151 ({cut_w}), gave_up never True",
|
||||||
|
r.clean(140, 400) and n_other() == 0 and n_some() == 0 and cut_w
|
||||||
|
and not any(r.gu[t] for t in range(140, 401)))
|
||||||
|
nev("T1", r)
|
||||||
|
|
||||||
|
r = s1(400)
|
||||||
|
check("T2: S1 to 400, no cut: no mismatch, hold or CHARGER_OTHER 140-400",
|
||||||
|
r.clean(140, 400) and n_other() == 0 and n_some() == 0)
|
||||||
|
w8 = [x for x in r.calls_from(190, 215) if x[1] == 8.0]
|
||||||
|
check(f"T2: the 8 A retry goes out at about 202 and is refused ({w8}); 12 A "
|
||||||
|
f"stays own after that write: prior_a = was = 12 "
|
||||||
|
f"({r.prior[205]}, {r.att[205]})",
|
||||||
|
len(w8) == 1 and near(w8[0][0], 202, 203) and r.prior[205] == 12.0
|
||||||
|
and r.att[205] == 8.0 and r.carry[205] == [])
|
||||||
|
nev("T2", r)
|
||||||
|
|
||||||
|
# T3 (changed, GUR): H2 and the reset of fails / gave_up
|
||||||
|
rb = s1(400, press_at=None, ev=[cut150], cls=Base69)
|
||||||
|
rc = s1(400, press_at=None, ev=[cut150])
|
||||||
|
cw = [x for x in rc.calls_from(150, 152) if x[1] == 6.0]
|
||||||
|
check(f"T3: S1-np, the cut from 150: the 6 A cut write at 150-151 ({cw}), no "
|
||||||
|
f"mismatch, hold or CHARGER_OTHER 140-400 ({n_other()})",
|
||||||
|
cw and rc.clean(140, 400) and n_other() == 0)
|
||||||
|
nev("T3", rc)
|
||||||
|
rp = s1(400, press_at=None)
|
||||||
|
check(f"T3: H2, the press is not needed: S1-np on de733f4 gives mismatch "
|
||||||
|
f"{rb.first_ms(140)}, hold {rb.first_hold()}, gave_up {rb.gu[142]}, "
|
||||||
|
f"and no cut write ({rb.calls_from(143, 200, True)[:2]}) (B1)",
|
||||||
|
near(rb.first_ms(140), 143, 144) and rb.first_hold() is not None
|
||||||
|
and rb.gu[142] is True
|
||||||
|
and 6.0 not in [a for _, a in rb.calls_from(143, 200)])
|
||||||
|
check(f"T3: S1-np, no cut: no mismatch, hold or CHARGER_OTHER 140-400 "
|
||||||
|
f"({n_other()})", rp.clean(140, 400) and n_other() == 0)
|
||||||
|
check(f"T3 (GUR): the carried 12 A take resets fails/gave_up only: gave_up "
|
||||||
|
f"True at 142 ({rp.gu[142]}), False and fails 0 from 143 "
|
||||||
|
f"({rp.gu[143]}, {rp.fl[143]}); the clamp value 8 A is re-sent at the "
|
||||||
|
f"next retry ({rp.calls_from(190, 215)}). EV-69 GUR: a carried take "
|
||||||
|
f"resets fails/gave_up only",
|
||||||
|
rp.gu[142] is True and not any(rp.gu[t] for t in range(143, 202))
|
||||||
|
and all(rp.fl[t] == 0 for t in range(143, 202))
|
||||||
|
and rp.calls_from(190, 215) == [(202, 8.0)])
|
||||||
|
|
||||||
|
# T23 (GUR): a carried take is not an adopt
|
||||||
|
check(f"T23: S1-np, the carried 12 A take: taken stays False, last_a None, "
|
||||||
|
f"sent_a 8 A unchanged 143-201 "
|
||||||
|
f"({set(rp.taken[t] for t in range(143, 202))}, "
|
||||||
|
f"{set(rp.last_a[t] for t in range(143, 202))}, "
|
||||||
|
f"{set(rp.sent_a[t] for t in range(143, 202))}); the 8 A goes out at "
|
||||||
|
f"the next RETRY_S step ({rp.calls_from(143, 400)[:1]})",
|
||||||
|
all(rp.taken[t] is False for t in range(143, 202))
|
||||||
|
and all(rp.last_a[t] is None for t in range(143, 202))
|
||||||
|
and all(rp.sent_a[t] == 8.0 for t in range(143, 202))
|
||||||
|
and (142 + int(CM.RETRY_S), 8.0) in rp.calls_from(143, 400))
|
||||||
|
|
||||||
|
# T4: a late take after the end
|
||||||
|
for tk in (150, 143, 170, 199):
|
||||||
|
ev = [(tk, show(12.0))]
|
||||||
|
rb = s1(400, show_at=None, ev=ev, cls=Base69)
|
||||||
|
r = s1(400, show_at=None, ev=ev)
|
||||||
|
check(f"T4: S1-nt, 12 A from {tk}: no mismatch 142-400 (the standing 0 A "
|
||||||
|
f"is no take and does not end the carry) ({r.first_ms(142)}); "
|
||||||
|
f"base: {rb.first_ms(142)}",
|
||||||
|
r.clean(142, 400) and n_other() == 0
|
||||||
|
and rb.first_ms(142) is not None)
|
||||||
|
|
||||||
|
# T6 (c): a foreign value after the end is still counted and held
|
||||||
|
r = s1(400, ev=[(160, show(16.0))])
|
||||||
|
check(f"T6 (i): S1 then foreign 16 A at 160: mismatch at 160-161 "
|
||||||
|
f"({r.first_ms(150)}), hold at +30 ({r.first_hold()}) and not +29, "
|
||||||
|
f"exactly 1 CHARGER_OTHER ({n_other()}), nothing non-zero written 160-"
|
||||||
|
f"400 ({r.calls_from(160, 400, True)})",
|
||||||
|
near(r.first_ms(150), 160, 161) and near(r.first_hold(), 190, 191)
|
||||||
|
and r.first_hold() - r.first_ms(150) == 30 and n_other() == 1
|
||||||
|
and not r.calls_from(160, 400, True) and not r.viol)
|
||||||
|
nev("T6 (i)", r)
|
||||||
|
r = s1(400, show_at=None, ev=[(150, show(5.0))])
|
||||||
|
check(f"T6 (iii): S1-nt, foreign 5 A at 150: mismatch at 150-151 "
|
||||||
|
f"({r.first_ms(142)}), hold 30 s later ({r.first_hold()}), 1 "
|
||||||
|
f"CHARGER_OTHER ({n_other()}), nothing non-zero written after "
|
||||||
|
f"({r.calls_from(150, 400, True)})",
|
||||||
|
near(r.first_ms(142), 150, 151) and r.first_hold() - r.first_ms(142)
|
||||||
|
== 30 and n_other() == 1 and not r.calls_from(150, 400, True))
|
||||||
|
nev("T6 (iii)", r)
|
||||||
|
|
||||||
|
# T7: OQ3, the known limit and its edge
|
||||||
|
r = s1(400, show_at=None, ev=[(150, show(12.0))])
|
||||||
|
check(f"T7 (i): S1-nt, a foreign value exactly 12 A at 150: no mismatch "
|
||||||
|
f"150-200 (the accepted OQ3 limit, EV-67 class) ({r.first_ms(150)})",
|
||||||
|
r.clean(150, 200))
|
||||||
|
r = s1(400, show_at=None, ev=[(230, show(12.0))],
|
||||||
|
take=lambda a, d: a == 8.0 and d.now >= 200)
|
||||||
|
check(f"T7 (ii): the 8 A retry taken at 202 (an own take ends the bound), "
|
||||||
|
f"foreign 12 A at 230: mismatch at 230 ({r.first_ms(203)}), hold at "
|
||||||
|
f"260 ({r.first_hold()}), 1 CHARGER_OTHER ({n_other()})",
|
||||||
|
near(r.first_ms(203), 230, 231) and near(r.first_hold(), 260, 261)
|
||||||
|
and n_other() == 1)
|
||||||
|
|
||||||
|
# T10-T13: the bound
|
||||||
|
r = s1(400, show_at=None, ev=[(150, show(8.0)), (160, show(12.0))])
|
||||||
|
check(f"T10: S1-nt, the charger takes 8 A (sent_a, an adopt) at 150, then "
|
||||||
|
f"shows 12 A at 160: mismatch at 160 ({r.first_ms(150)}), hold at 190 "
|
||||||
|
f"({r.first_hold()}), 1 CHARGER_OTHER ({n_other()}), nothing non-zero "
|
||||||
|
f"written 160-400 ({r.calls_from(160, 400, True)})",
|
||||||
|
near(r.first_ms(150), 160, 161) and near(r.first_hold(), 190, 191)
|
||||||
|
and n_other() == 1 and not r.calls_from(160, 400, True)
|
||||||
|
and r.carry[151] == [])
|
||||||
|
nev("T10", r)
|
||||||
|
r = s1(400, show_at=None, ev=[(210, show(12.0))])
|
||||||
|
check(f"T11: S1-nt, the 8 A retry at about 202 refused on 0 A (prior_a 0), "
|
||||||
|
f"12 A at 210: mismatch at 210 ({r.first_ms(150)}), hold at 240 "
|
||||||
|
f"({r.first_hold()}), 1 CHARGER_OTHER ({n_other()})",
|
||||||
|
near(r.first_ms(150), 210, 211) and near(r.first_hold(), 240, 241)
|
||||||
|
and n_other() == 1 and r.prior[205] == 0.0)
|
||||||
|
r = s1(400, show_at=None, ev=[(190, cap(6.0)), (210, show(12.0))])
|
||||||
|
check(f"T11 variant: the new write is a cut try (cap 6 at 190): 12 A at 210: "
|
||||||
|
f"mismatch ({r.first_ms(150)}), hold ({r.first_hold()}), 1 "
|
||||||
|
f"CHARGER_OTHER ({n_other()}), cut written "
|
||||||
|
f"({r.calls_from(190, 195, True)})",
|
||||||
|
near(r.first_ms(150), 210, 211) and near(r.first_hold(), 240, 241)
|
||||||
|
and n_other() == 1 and (190, 6.0) in r.calls_from(190, 192, True))
|
||||||
|
r = s1(400, show_at=None, ev=[(145, press), (150, show(12.0))])
|
||||||
|
check(f"T12: S1-nt, a press at 145 (no hold: the carry ends), 12 A at 150: "
|
||||||
|
f"mismatch at 150 ({r.first_ms(146)}), hold at 180 ({r.first_hold()}), "
|
||||||
|
f"1 CHARGER_OTHER ({n_other()}), no write at or above 12 A "
|
||||||
|
f"({[x for x in r.calls_from(145) if x[1] >= 12.0]})",
|
||||||
|
near(r.first_ms(146), 150, 151) and near(r.first_hold(), 180, 181)
|
||||||
|
and n_other() == 1 and not [x for x in r.calls_from(145)
|
||||||
|
if x[1] >= 12.0])
|
||||||
|
nev("T12", r)
|
||||||
|
# The press's own retry write ends the carry too, so the row above cannot see
|
||||||
|
# the press end it. Here no step after the press is fresh (no write): the
|
||||||
|
# press alone ends the carry. Nothing is own after it (no judging, the EV-22
|
||||||
|
# start-state blind spot), so the row grades the state: the carry is gone.
|
||||||
|
r = s1(400, show_at=None, ev=[(145, press), (146, show(12.0))],
|
||||||
|
stale=lambda t: 145 <= t <= 149)
|
||||||
|
check(f"T12 (press alone): S1-nt, a press at 145, no fresh read and no write "
|
||||||
|
f"until 150: the carry ended with the press ({r.carry[144]}, "
|
||||||
|
f"{r.carry[145]}), 12 A is no own value ({r.own[149]})",
|
||||||
|
r.carry[144] != [] and all(r.carry[t] == [] for t in range(145, 150))
|
||||||
|
and 12.0 not in r.own[149] and not r.calls_from(145, 149))
|
||||||
|
r = s1(400, show_at=None, ev=[(145, show(16.0)), (200, show(12.0))])
|
||||||
|
check(f"T13: S1-nt, foreign 16 A at 145 (hold at 175), the writer then sets "
|
||||||
|
f"12 A at 200: the hold stands 175-400 (no lift by match on an old "
|
||||||
|
f"value) ({r.first_hold()}, {all(r.hold[t] for t in range(176, 401))}), "
|
||||||
|
f"1 CHARGER_OTHER ({n_other()}), nothing written 145-400 "
|
||||||
|
f"({r.calls_from(145, 400)})",
|
||||||
|
near(r.first_hold(), 175, 176) and all(r.hold[t] for t in range(177, 401))
|
||||||
|
and n_other() == 1 and not r.calls_from(145, 400, True)
|
||||||
|
and r.carry[176] == [])
|
||||||
|
nev("T13", r)
|
||||||
|
|
||||||
|
# T15: unknown read-backs
|
||||||
|
r = s1(400, show_at=None, ev=[(151, show(12.0))],
|
||||||
|
cur=lambda t, d: None if 143 <= t <= 150 else d.cur)
|
||||||
|
check(f"T15 (i): S1-nt, an unknown read-back 143-150 and 12 A at 151: no "
|
||||||
|
f"mismatch 143-400 ({r.first_ms(140)}), no hold, no CHARGER_OTHER "
|
||||||
|
f"({n_other()})", r.clean(143, 400) and n_other() == 0)
|
||||||
|
r = s1(400, show_at=None, ev=[(145, show(16.0))],
|
||||||
|
cur=lambda t, d: None if 150 <= t <= 160 else d.cur)
|
||||||
|
check(f"T15 (ii): foreign 16 A at 145, unknown 150-160, 16 A again from 161: "
|
||||||
|
f"mismatch from 145 ({r.first_ms(140)}), the count stands through "
|
||||||
|
f"None ({all(r.ms[t] is not None for t in range(146, 175))}), hold at "
|
||||||
|
f"175 ({r.first_hold()})",
|
||||||
|
near(r.first_ms(140), 145, 146)
|
||||||
|
and all(r.ms[t] is not None for t in range(146, 175))
|
||||||
|
and near(r.first_hold(), 175, 176) and n_other() == 1)
|
||||||
|
|
||||||
|
# T16: stale reads
|
||||||
|
r = s1(400, show_at=None, ev=[(143, show(12.0))],
|
||||||
|
stale=lambda t: 143 <= t <= 147)
|
||||||
|
check(f"T16 (i): S1-nt, 12 A shown from 143 but stale for 143-147: those "
|
||||||
|
f"steps decide nothing, 148-400 no mismatch ({r.first_ms(140)}), no "
|
||||||
|
f"CHARGER_OTHER ({n_other()}); the carry stands through them "
|
||||||
|
f"({r.carry[147]})",
|
||||||
|
r.clean(143, 400) and n_other() == 0 and r.carry[147] != [])
|
||||||
|
r = s1(400, show_at=None, ev=[(145, show(16.0))])
|
||||||
|
check(f"T16 (ii): a frozen foreign read is a mismatch, then a hold, as "
|
||||||
|
f"before ({r.first_ms(140)}, {r.first_hold()})",
|
||||||
|
near(r.first_ms(140), 145, 146) and near(r.first_hold(), 175, 176))
|
||||||
|
|
||||||
|
# T17: restart and return
|
||||||
|
rn = s1(400, show_at=None, cur=lambda t, d: 12.0 if t >= 156 else d.cur,
|
||||||
|
gone=lambda t: 145 <= t <= 155)
|
||||||
|
rbs = s1(400, show_at=None, cur=lambda t, d: 12.0 if t >= 156 else d.cur,
|
||||||
|
gone=lambda t: 145 <= t <= 155, cls=Base69)
|
||||||
|
same = all((rn.ms[t], rn.hold[t], rn.ncalls[t]) ==
|
||||||
|
(rbs.ms[t], rbs.hold[t], rbs.ncalls[t]) for t in range(156, 401))
|
||||||
|
check(f"T17 (i): the charger gone 145-155, back showing 12 A: from 156 every "
|
||||||
|
f"cycle's writes, mismatch and hold equal de733f4 on the same run "
|
||||||
|
f"({same}); the carry stands while it is gone ({rn.carry[155]}) and is "
|
||||||
|
f"gone with the return ({rn.carry[156]})",
|
||||||
|
same and rn.carry[156] == [] and rn.carry[155] != [])
|
||||||
|
src = open(os.path.join(HERE, "app", "carmode.py")).read()
|
||||||
|
others = [f for f in os.listdir(os.path.join(HERE, "app"))
|
||||||
|
if f.endswith(".py") and f != "carmode.py"
|
||||||
|
and "_carry" in open(os.path.join(HERE, "app", f)).read()]
|
||||||
|
w2, m2 = CM.SolarWriter(), CM.ManualWriter()
|
||||||
|
check(f"T17 (ii): a new writer (a process restart) carries nothing "
|
||||||
|
f"({w2._carry}, {m2._carry}); the carry is in no other module (no state "
|
||||||
|
f"file key) ({others})",
|
||||||
|
w2._carry == [] and m2._carry == [] and not others)
|
||||||
|
|
||||||
|
# T18: a raised try is carried
|
||||||
|
for lab, val in (("(i) try 2 (8 A) raising", 8.0),
|
||||||
|
("(ii) try 1 (12 A) raising", 12.0)):
|
||||||
|
take = (lambda v: lambda a, d: "raise" if a == v else False)(val)
|
||||||
|
rb = s1(400, show_at=None, ev=[(150, show(12.0))], take=take,
|
||||||
|
cls=Base69, press_at=None)
|
||||||
|
r = s1(400, show_at=None, ev=[(150, show(12.0))], take=take,
|
||||||
|
press_at=None)
|
||||||
|
errs = [t for t, lv, m in r.log if lv == "ERROR" and m == REC]
|
||||||
|
check(f"T18 {lab}: 12 A shown at 150: no mismatch 150-400 "
|
||||||
|
f"({r.first_ms(150)}), the raised value counted as a try, one "
|
||||||
|
f"ERROR record per value ({len(errs)}); base: {rb.first_ms(150)}",
|
||||||
|
r.clean(150, 400) and n_other() == 0 and len(errs) == 1
|
||||||
|
and rb.first_ms(150) is not None)
|
||||||
|
|
||||||
|
# T20: Stop / the 0 A rule
|
||||||
|
t0 = lambda a, d: a == 0.0 and d.now >= 158 # noqa: E731
|
||||||
|
r = s1(400, show_at=140, take=t0, writing=lambda t: t < 160)
|
||||||
|
z = [x for x in r.calls_from(160) if x[1] == 0.0]
|
||||||
|
check(f"T20 (i): S1 (12 A own), Stop at 160: the way-out 0 A at 160 ({z[:1]}), "
|
||||||
|
f"no mismatch at 160 ({r.ms[160]}), no hold, no CHARGER_OTHER "
|
||||||
|
f"({n_other()})",
|
||||||
|
z and near(z[0][0], 160, 161) and r.ms[160] is None
|
||||||
|
and not any(r.hold.values()) and n_other() == 0)
|
||||||
|
r = s1(400, take=t0, ev=[(160, show(16.0))], writing=lambda t: t < 170)
|
||||||
|
z = [x for x in r.calls_from(160) if x[1] == 0.0]
|
||||||
|
check(f"T20 (ii): T6 (i) with Stop at 170 (the count running since 160): the "
|
||||||
|
f"0 A goes out in the count ({z[:2]}), no hold after it "
|
||||||
|
f"({r.first_hold()}), no CHARGER_OTHER ({n_other()})",
|
||||||
|
z and near(z[0][0], 170, 171) and r.first_hold() is None
|
||||||
|
and n_other() == 0)
|
||||||
|
r = s1(400, take=t0, ev=[(160, show(16.0))], writing=lambda t: t < 200)
|
||||||
|
check(f"T20 (iii): T6 (i) with Stop at 200 (the hold stands): nothing "
|
||||||
|
f"written 160-400 ({r.calls_from(160, 400)}), the hold stands "
|
||||||
|
f"({r.hold[300]}), 1 CHARGER_OTHER ({n_other()})",
|
||||||
|
not r.calls_from(160, 400) and r.hold[300] and n_other() == 1)
|
||||||
|
|
||||||
|
# =========================================================================== #
|
||||||
|
print("CE (the EV-60 cap end), Solar")
|
||||||
|
# =========================================================================== #
|
||||||
|
r = ce(960)
|
||||||
|
ct = close_times(r)
|
||||||
|
E = nth(ct, 1) + 5
|
||||||
|
check(f"T5 setup: close 1 (8 A) at {nth(ct, 0)}, the cap, close 2 (6 A) at "
|
||||||
|
f"{nth(ct, 1)}, the cap end at {E} with no write ({r.ended})",
|
||||||
|
present(E) and len(ct) >= 2 and r.drv.calls[0][1] == 0.0
|
||||||
|
and [a for t, a in r.drv.calls if a > 0][:2] == [8.0, 6.0]
|
||||||
|
and r.ended == E)
|
||||||
|
for lab, at_ in (("at E+8", E + 8), ("between close 2 and E", E - 2)):
|
||||||
|
rb = ce(960, ev=[(at_, show(8.0))], cls=Base69)
|
||||||
|
r = ce(960, ev=[(at_, show(8.0))])
|
||||||
|
k1 = [x for x in r.calls_from(E + 1, 959) if x[1] > 0]
|
||||||
|
check(f"T5: CE, the charger shows 8 A (close 1) {lab}: no mismatch, hold "
|
||||||
|
f"or CHARGER_OTHER E..960 ({r.first_ms(E)}, {n_other()}), no write "
|
||||||
|
f"in key 0 after E, the 6 A cut try at the key roll 900-901 "
|
||||||
|
f"({k1[:2]}), cut_fails never above 3",
|
||||||
|
r.clean(E, 960) and n_other() == 0
|
||||||
|
and not [x for x in k1 if x[0] < 900]
|
||||||
|
and [x for x in k1 if 900 <= x[0] <= 901 and x[1] == 6.0]
|
||||||
|
and not r.viol)
|
||||||
|
check(f"T5 [red on base] {lab}: base mismatch ({rb.first_ms(E)}), hold "
|
||||||
|
f"({rb.first_hold()}), no cut try at 900 "
|
||||||
|
f"({[x for x in rb.calls_from(E + 1, 959) if x[1] > 0][:2]})",
|
||||||
|
rb.first_ms(E) is not None and rb.first_hold() is not None
|
||||||
|
and not [x for x in rb.calls_from(900, 905) if x[1] > 0])
|
||||||
|
nev("T5", r)
|
||||||
|
r = ce(960, ev=[(E + 20, show(10.0))])
|
||||||
|
check(f"T6 (ii): CE, foreign 10 A at E+20: mismatch at the change "
|
||||||
|
f"({r.first_ms(E)}), hold at +30 ({r.first_hold()}), 1 CHARGER_OTHER "
|
||||||
|
f"({n_other()}), nothing non-zero written from the change to 960 "
|
||||||
|
f"({r.calls_from(E + 20, 960, True)})",
|
||||||
|
near(r.first_ms(E), E + 20, E + 21)
|
||||||
|
and r.first_hold() - r.first_ms(E) == 30 and n_other() == 1
|
||||||
|
and not r.calls_from(E + 20, 960, True))
|
||||||
|
nev("T6 (ii)", r)
|
||||||
|
|
||||||
|
# T19: the quarter boundary
|
||||||
|
rb = ce(960, ev=[(900, show(8.0))], cls=Base69)
|
||||||
|
r = ce(960, ev=[(900, show(8.0))])
|
||||||
|
check(f"T19: CE, the cap standing to 960, the charger shows 8 A at the step "
|
||||||
|
f"of 900: no mismatch 900-960, the key-1 cut try at 900-901 "
|
||||||
|
f"({r.calls_from(899, 905)}), its refusal keeps 8 A own "
|
||||||
|
f"(prior_a {r.prior[902]})",
|
||||||
|
r.clean(900, 960) and n_other() == 0
|
||||||
|
and [x for x in r.calls_from(900, 901) if x[1] == 6.0]
|
||||||
|
and r.prior[902] == 8.0)
|
||||||
|
check(f"T19 [red on base]: mismatch at 900 ({rb.first_ms(895)})",
|
||||||
|
rb.first_ms(895) is not None)
|
||||||
|
|
||||||
|
# T24 (formal Dev note 1): the 0 A is carried
|
||||||
|
r = ce(500, press_after_close2=True)
|
||||||
|
E = close_times(r)[1] + 5
|
||||||
|
r = ce(500, press_after_close2=True, ev=[(E + 3, show(0.0))])
|
||||||
|
check(f"T24: cap end with a press inside the sequence (prior_a cleared), the "
|
||||||
|
f"charger then shows its own 0 A: no mismatch_since, no hold "
|
||||||
|
f"({r.first_ms(E)}, {r.first_hold()}); the carry holds the 0 A "
|
||||||
|
f"({r.carry[E + 4]})",
|
||||||
|
r.ended == E and r.clean(E, 500) and 0.0 in r.carry[E + 4]
|
||||||
|
and r.prior[E - 1] is None)
|
||||||
|
|
||||||
|
|
||||||
|
# T25 (formal Dev note 2): no carry when the end's own value is taken
|
||||||
|
def ce25():
|
||||||
|
w, drv = mk_ce(plan_a=12.0)
|
||||||
|
st = {"cap": False}
|
||||||
|
|
||||||
|
def hook(t, w_, d, s):
|
||||||
|
nz = [(tt, a) for tt, a in d.calls if a > 0]
|
||||||
|
if nz and not s["cap"]:
|
||||||
|
s["cap"] = True
|
||||||
|
set_cap(w_, 6.0)
|
||||||
|
if len(nz) >= 2 and t == nz[1][0] + 5:
|
||||||
|
d.cur = 6.0 # close 2 taken late, read at E
|
||||||
|
if len(nz) >= 2 and t == nz[1][0] + 5 + 10:
|
||||||
|
d.cur = 12.0 # an earlier close value
|
||||||
|
return Run(w, drv, st=st).go(130, 600, hook=hook)
|
||||||
|
|
||||||
|
|
||||||
|
r = ce25()
|
||||||
|
E = close_times(r)[1] + 5
|
||||||
|
check(f"T25: CE, the read at E adopts sent_a (6 A taken late) before the cap "
|
||||||
|
f"end: nothing is carried ({r.carry[E]}, {r.carry[E + 10]}), the 12 A "
|
||||||
|
f"(an earlier close value) is no own value when it shows at E+10 "
|
||||||
|
f"({r.own[E + 10]}), 6 A stays taken (taken {r.taken[E]}, sent_a "
|
||||||
|
f"{r.sent_a[E + 10]}); no write in key 0 after E "
|
||||||
|
f"({r.calls_from(E, 899)})",
|
||||||
|
r.ended == E and all(r.carry[t] == [] for t in range(E, 601))
|
||||||
|
and 12.0 not in r.own[E + 10] and r.taken[E] is True
|
||||||
|
and r.sent_a[E + 10] == 6.0 and not r.calls_from(E, 899))
|
||||||
|
# The test plan reads T25 as "a mismatch, a hold at +30". It cannot, by the
|
||||||
|
# code: the cap end sets last_a None (F5) and the adopt cleared attempted_a /
|
||||||
|
# prior_a, so no own value is left at all and `_watch` judges nothing (the
|
||||||
|
# EV-22 start-state blind spot, not EV-69's). The row asserts the rule itself:
|
||||||
|
# nothing carried (red under carryAfterTake, which carries 0, 12 and 6).
|
||||||
|
|
||||||
|
# =========================================================================== #
|
||||||
|
print("MW (Manual, OQ2)")
|
||||||
|
# =========================================================================== #
|
||||||
|
r = mw(300)
|
||||||
|
nzc = [int(t) for t, a in r.drv.calls if a > 0]
|
||||||
|
E = nth(nzc, -1)
|
||||||
|
check(f"T8 setup: Manual closes 12 A, the clamp falls, tries 2 and 3 are 8 A "
|
||||||
|
f"({[(int(t), a) for t, a in r.drv.calls]}), the :589 end at {r.ended}",
|
||||||
|
present(E) and [a for t, a in r.drv.calls if a > 0] == [12.0, 8.0, 8.0]
|
||||||
|
and r.ended == E and r.gu[E] is True)
|
||||||
|
for lab, kw in (("the clamp falls", dict()),
|
||||||
|
("the user lowers car_current 12 -> 8", dict(user=True))):
|
||||||
|
r0 = mw(300, **kw)
|
||||||
|
E = r0.ended
|
||||||
|
rb = mw(E + 300, cls=BaseM69, hook2=lambda t, w, d, s, E=E: setattr(
|
||||||
|
d, "cur", 12.0) if t == E + 3 else None, **kw)
|
||||||
|
r = mw(E + 300, hook2=lambda t, w, d, s, E=E: setattr(
|
||||||
|
d, "cur", 12.0) if t == E + 3 else None, **kw)
|
||||||
|
check(f"T8: Manual, {lab}, the charger shows 12 A at E+3: no mismatch, "
|
||||||
|
f"hold or 'Something else changes the charger' line E..E+300 "
|
||||||
|
f"({r.first_ms(E)}, {n_some()}); the EV-59 count is unchanged "
|
||||||
|
f"(gave_up {r.gu[E + 4]}); base: hold at {rb.first_hold(E)}",
|
||||||
|
r.clean(E, E + 300) and n_some() == 0
|
||||||
|
and r.gu[E + 4] is (not kw) # clamp: EV-59 gave up; user: the
|
||||||
|
# count restarted, it asks again
|
||||||
|
and rb.first_hold(E) is not None and near(
|
||||||
|
rb.first_hold(E), E + 33, E + 34))
|
||||||
|
nev(f"T8 ({lab})", r)
|
||||||
|
r0 = mw(300)
|
||||||
|
E = r0.ended
|
||||||
|
r = mw(E + 300, hook2=lambda t, w, d, s: setattr(d, "cur", 16.0)
|
||||||
|
if t == E + 5 else None)
|
||||||
|
check(f"T9: Manual, foreign 16 A at E+5: mismatch at E+5 ({r.first_ms(E)}), "
|
||||||
|
f"hold at E+35 ({r.first_hold(E)}), 1 INFO line ({n_some()}), no write "
|
||||||
|
f"over 16 A to E+300 ({r.calls_from(E + 1, 10 ** 9, True)})",
|
||||||
|
near(r.first_ms(E), E + 5, E + 6) and near(r.first_hold(E), E + 35,
|
||||||
|
E + 36)
|
||||||
|
and n_some() == 1 and not r.calls_from(E + 1, 10 ** 9, True))
|
||||||
|
|
||||||
|
# Manual version of T10 (formal Dev note 3: Manual's adopt ends the carry)
|
||||||
|
r0 = mw(300)
|
||||||
|
E = r0.ended
|
||||||
|
r = mw(E + 200, hook2=lambda t, w, d, s: setattr(
|
||||||
|
d, "cur", 8.0 if t == E + 3 else 12.0 if t == E + 20 else d.cur))
|
||||||
|
check(f"T10 (Manual): the charger takes the target 8 A at E+3 (Manual's adopt "
|
||||||
|
f"ends the carry: {r.carry[E + 4]}), then shows the old close 12 A at "
|
||||||
|
f"E+20: mismatch at E+20 ({r.first_ms(E)}), hold at E+50 "
|
||||||
|
f"({r.first_hold(E)}), 1 INFO line ({n_some()})",
|
||||||
|
r.carry[E + 4] == [] and near(r.first_ms(E), E + 20, E + 21)
|
||||||
|
and near(r.first_hold(E), E + 50, E + 51) and n_some() == 1)
|
||||||
|
|
||||||
|
|
||||||
|
# T17 (i) in the cap-end shape (M14): the 0 A after a return is blocked by
|
||||||
|
# the used-up cut tries, so only the return itself can end the carry.
|
||||||
|
def ce_gone(cls, lo, hi, show_at, show_a):
|
||||||
|
w, drv = mk_ce(cls)
|
||||||
|
st = {"cap": False}
|
||||||
|
|
||||||
|
def h(t, w_, d, s):
|
||||||
|
nz = [1 for tt, a in d.calls if a > 0]
|
||||||
|
if nz and not s["cap"]:
|
||||||
|
s["cap"] = True
|
||||||
|
set_cap(w_, 6.0)
|
||||||
|
if t == show_at:
|
||||||
|
d.cur = show_a
|
||||||
|
return Run(w, drv, st=st).go(130, 600, hook=h,
|
||||||
|
gone=lambda t: lo <= t <= hi)
|
||||||
|
|
||||||
|
|
||||||
|
E = ce_gone(None, -1, -1, 10 ** 6, 0.0).ended
|
||||||
|
rn = ce_gone(None, E + 3, E + 8, E + 9, 10.0)
|
||||||
|
rbs = ce_gone(Base69, E + 3, E + 8, E + 9, 10.0)
|
||||||
|
same = all((rn.ms[t], rn.hold[t], rn.ncalls[t]) ==
|
||||||
|
(rbs.ms[t], rbs.hold[t], rbs.ncalls[t]) for t in range(E + 9, 601))
|
||||||
|
check(f"T17 (i, cap end): the charger gone E+3..E+8 and back at E+9 showing "
|
||||||
|
f"10 A, the cut tries used up: the carry stands while it is gone "
|
||||||
|
f"({rn.carry[E + 8]}) and ends with the return ({rn.carry[E + 9]}); no "
|
||||||
|
f"mismatch ({rn.first_ms(E + 9)}) and every cycle equals de733f4",
|
||||||
|
E is not None and rn.carry[E + 8] != [] and rn.carry[E + 9] == []
|
||||||
|
and rn.clean(E + 9, 600) and same)
|
||||||
|
|
||||||
|
# R-MB: the standing 0 A is no take (the cur > TOL_A guard in `_watch`)
|
||||||
|
r = s1(400, press_at=None, show_at=None)
|
||||||
|
check(f"T4 (0 A guard): S1-np-nt, the charger stands at the carried 0 A: "
|
||||||
|
f"gave_up stays True 142-400 and nothing non-zero is written "
|
||||||
|
f"({r.calls_from(143, 400, True)})",
|
||||||
|
all(r.gu[t] for t in range(142, 401))
|
||||||
|
and not r.calls_from(143, 400, True))
|
||||||
|
|
||||||
|
# =========================================================================== #
|
||||||
|
print("Rules the code keeps (Dev notes)")
|
||||||
|
# =========================================================================== #
|
||||||
|
check("T1 [Dev note 1]: one helper `_carry_end` serves both ends and both "
|
||||||
|
"writers (ManualWriter defines it, SolarWriter does not redefine it)",
|
||||||
|
"_carry_end" in vars(CM.ManualWriter)
|
||||||
|
and "_carry_end" not in vars(CM.SolarWriter)
|
||||||
|
and src.count("self._carry_end(q)") == 2)
|
||||||
|
check("T1 [Dev note 6]: `_put` keeps `stopped and not cut_try` (the cut never "
|
||||||
|
"waits on gave_up)", "(stopped and not cut_try)" in src)
|
||||||
|
done()
|
||||||
@@ -0,0 +1,582 @@
|
|||||||
|
"""EV-69 T21: the fuzz for the carry (N1-N9 of reports/EV-69-test-plan.md).
|
||||||
|
`python3 -B test_ev69_fuzz.py`
|
||||||
|
|
||||||
|
Two passes, each SEEDS (10) seeds x STEPS (1200) s for Solar and for Manual,
|
||||||
|
both cycle orders. Writer level (`tools/ev69_kit.py`: `SolarWriter` /
|
||||||
|
`ManualWriter` on a stub driver). Order A applies a cycle's events before its
|
||||||
|
step, order B after it (read one cycle later).
|
||||||
|
- Mixed pass (`fuzz_mixed`): the round-1 event model of 9b09158, unchanged
|
||||||
|
(same random stream, same rates, PHASE_GAP_S as shipped). Random clamp steps,
|
||||||
|
a peak cut cap, refused and raised writes (0 A and the select are taken),
|
||||||
|
phase changes begun by the plan (Solar) or the user (Manual), late takes of
|
||||||
|
ANY value the writer tried, foreign values (some equal to a tried value),
|
||||||
|
presses, unknown and stale reads, the charger gone and back. Its floors are
|
||||||
|
a fixed list (MIXED_FLOOR), each asserted on the mixed counts alone.
|
||||||
|
- Directed pass (`fuzz_directed`, 4 x SEEDS seeds), in addition, with its
|
||||||
|
own floors (DIRECTED_FLOOR) asserted on the directed counts alone: Solar
|
||||||
|
changes run
|
||||||
|
calm (no late take, foreign value or 0 A reading inside a change, refuse
|
||||||
|
0.97 / 1.0 only, the clamp falls only after a close, a cap with `cut_fails`
|
||||||
|
2 after the first close) so that cap ends and Solar's distinct close values
|
||||||
|
are reached; presses that lift a hold or a give-up, the charger gone while a
|
||||||
|
bound stands, the plan's phases set from the read phases, PHASE_GAP_S 40 (as
|
||||||
|
test_ev22_fuzz does), and N1b's directed old-value take.
|
||||||
|
|
||||||
|
Every cycle checks, by an oracle that does not read the carry:
|
||||||
|
- N1: after a phase change ends without its value taken (MAX_TRIES, or
|
||||||
|
Solar's cap end), while nothing has ended the bound (a write, a press, a
|
||||||
|
hold or count, a return, a take of what the writer sent or wants), the
|
||||||
|
charger showing a value the change tried gives no mismatch and no hold.
|
||||||
|
- N1b (directed pass): once a bound has ended (an own take, a new own write, a
|
||||||
|
user change, a hold, Solar's return) a late take of an old value is another
|
||||||
|
writer's: the fuzz shows it for WRITER_S + 3 s with nothing else happening
|
||||||
|
and asserts the hold (skipped when no own value is left to judge against:
|
||||||
|
the EV-22 start-state blind spot).
|
||||||
|
- N2: no non-zero write while a count runs (Solar) or a hold stands.
|
||||||
|
- N4: no carry under a hold, after a press, or after a write that is not
|
||||||
|
itself followed by an end.
|
||||||
|
- N5: no write above the clamp or the cap, none in 0-6 A.
|
||||||
|
- N6: at most MAX_TRIES cut tries per quarter key.
|
||||||
|
- N7: no 0 A written under a hold.
|
||||||
|
- N8: a select only at 0 A.
|
||||||
|
- N9: at most one CHARGER_OTHER (Solar) / one INFO line (Manual) per hold.
|
||||||
|
N3 (the cut never waits on a false hold) follows from N1 and the rows T1, T5,
|
||||||
|
T19.
|
||||||
|
|
||||||
|
Mutating a module this file grades? Read MUTATION.md first (purge __pycache__).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import sys
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
sys.path.insert(0, os.path.join(HERE, "tools"))
|
||||||
|
|
||||||
|
import ev69_kit as K # noqa: E402
|
||||||
|
from app import carmode as CM # noqa: E402
|
||||||
|
|
||||||
|
SEEDS = int(os.environ.get("EV69_FUZZ_SEEDS", "10"))
|
||||||
|
STEPS = int(os.environ.get("EV69_FUZZ_STEPS", "1200"))
|
||||||
|
COUNT = {}
|
||||||
|
|
||||||
|
|
||||||
|
def bump(k, n=1):
|
||||||
|
COUNT[k] = COUNT.get(k, 0) + n
|
||||||
|
|
||||||
|
|
||||||
|
def fuzz_mixed(kind, seed):
|
||||||
|
"""9b09158's fuzz, event model unchanged. Only counters were added (no
|
||||||
|
random draw): late_nonlast_<kind>, cap_end_take, foreign_hold_after_end.
|
||||||
|
"""
|
||||||
|
rnd = random.Random(seed * 7 + (0 if kind == "solar" else 1))
|
||||||
|
order_b = seed % 2 == 1
|
||||||
|
st = {"a": rnd.choice([8.0, 10.0, 12.0]), "n": 1, "rev": 1,
|
||||||
|
"clamp": 16.0}
|
||||||
|
if kind == "solar":
|
||||||
|
w = K.swriter(8.0, ph=1)
|
||||||
|
w.cut_key = 0
|
||||||
|
else:
|
||||||
|
w = CM.ManualWriter()
|
||||||
|
mode = {"refuse": 0.97, "raise": 0.0}
|
||||||
|
|
||||||
|
def take(a, d):
|
||||||
|
if a == 0.0:
|
||||||
|
return True
|
||||||
|
if rnd.random() < mode["raise"]:
|
||||||
|
return "raise"
|
||||||
|
return rnd.random() >= mode["refuse"]
|
||||||
|
drv = K.Drv(8.0 if kind == "solar" else st["a"], take, ph=1)
|
||||||
|
run = K.Run(w, drv, kind=kind, st=st)
|
||||||
|
bad = []
|
||||||
|
s = dict(armed=False, vals=[], seq_own=[], hold_rises=0, press_t=-1,
|
||||||
|
prev_hold=False, was_gone=False, gone=False, tried=set(),
|
||||||
|
nsel=0, cap=False, cap_counted=False, fv=None, end_t=-9999)
|
||||||
|
clamp = {"v": 16.0}
|
||||||
|
|
||||||
|
def ev(t):
|
||||||
|
if rnd.random() < (0.25 if w.seq is not None else 0.01):
|
||||||
|
clamp["v"] = rnd.choice([16.0, 12.0, 10.0, 8.0, 8.0])
|
||||||
|
st["clamp"] = clamp["v"]
|
||||||
|
if kind == "solar" and rnd.random() < 0.01:
|
||||||
|
K.set_cap(w, rnd.choice([None, 6.0, 6.0, 7.0]))
|
||||||
|
if rnd.random() < 0.004:
|
||||||
|
mode["refuse"] = rnd.choice([0.0, 0.5, 0.97, 1.0, 1.0, 1.0])
|
||||||
|
mode["raise"] = rnd.choice([0.0, 0.0, 0.3])
|
||||||
|
# a phase change: Solar's plan decides it, Manual's user asks for it
|
||||||
|
if w.seq is None and rnd.random() < 0.03:
|
||||||
|
n_to = 3 if drv.ph == 1 else 1
|
||||||
|
if kind == "solar":
|
||||||
|
if not w.plan.switch:
|
||||||
|
w.plan._set(rnd.choice([8.0, 10.0, 12.0]), float(t), n_to)
|
||||||
|
else:
|
||||||
|
w.user_changed()
|
||||||
|
st["rev"] += 1
|
||||||
|
st["n"] = n_to
|
||||||
|
st["a"] = rnd.choice([8.0, 10.0, 12.0, 14.0])
|
||||||
|
s["press_t"] = t
|
||||||
|
# a late take of any value the writer tried (the ended change's
|
||||||
|
# values first)
|
||||||
|
if rnd.random() < 0.08:
|
||||||
|
pool = [v for v in s["vals"] if v > 0] if (
|
||||||
|
s["armed"] and rnd.random() < 0.6) else sorted(
|
||||||
|
v for v in s["tried"] if v > 0)
|
||||||
|
if pool:
|
||||||
|
v = rnd.choice(pool)
|
||||||
|
drv.cur = v
|
||||||
|
bump("late_take")
|
||||||
|
if s["armed"] and v in s["vals"]:
|
||||||
|
bump("late_take_ended_val")
|
||||||
|
if v != s["vals"][-1]:
|
||||||
|
bump("late_take_nonlast")
|
||||||
|
bump(f"late_nonlast_{kind}")
|
||||||
|
if rnd.random() < 0.005:
|
||||||
|
drv.cur = rnd.choice([5.0, 7.0, 9.0, 11.0, 13.0, 15.0]
|
||||||
|
+ sorted(s["tried"]))
|
||||||
|
s["fv"] = (t, drv.cur)
|
||||||
|
bump("foreign")
|
||||||
|
if rnd.random() < 0.005:
|
||||||
|
w.user_changed()
|
||||||
|
if kind == "manual":
|
||||||
|
st["rev"] += 1
|
||||||
|
s["press_t"] = t
|
||||||
|
bump("press")
|
||||||
|
if rnd.random() < 0.01:
|
||||||
|
drv.cur = 0.0
|
||||||
|
s["gone"] = rnd.random() < (0.8 if s["gone"] else 0.003)
|
||||||
|
|
||||||
|
for t in range(STEPS):
|
||||||
|
if not order_b:
|
||||||
|
ev(t)
|
||||||
|
gone, unk, stale = s["gone"], rnd.random() < 0.02, rnd.random() < 0.02
|
||||||
|
n0, sel0 = len(drv.calls), len(drv.sel)
|
||||||
|
before_seq = w.seq is not None
|
||||||
|
if before_seq:
|
||||||
|
s["seq_own"] = list(w.seq.get("own", ()))
|
||||||
|
drv.now = float(t)
|
||||||
|
K.CLOCK["t"] = t
|
||||||
|
if hasattr(w, "cut_quarter"):
|
||||||
|
w.cut_quarter(int(t // 900))
|
||||||
|
seen = None if unk else drv.cur
|
||||||
|
rd = K.Rd(seen, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
|
||||||
|
rd.available = not gone
|
||||||
|
run.trk.obs_at = (w.last_done if (stale and w.last_done is not None)
|
||||||
|
else None)
|
||||||
|
cl = clamp["v"]
|
||||||
|
if kind == "solar":
|
||||||
|
K.LOOP.run_until_complete(w.step(
|
||||||
|
drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0),
|
||||||
|
clamp=cl, now=float(t), tracker=run.trk, writing=True,
|
||||||
|
status="charging"))
|
||||||
|
else:
|
||||||
|
K.LOOP.run_until_complete(w.step(
|
||||||
|
drv, rd, mode=CM.MANUAL, want_a=st["a"],
|
||||||
|
want_phases=st["n"], rev=st["rev"], clamp=cl, now=float(t),
|
||||||
|
tracker=run.trk, writing=True, status="charging"))
|
||||||
|
new = drv.calls[n0:]
|
||||||
|
wrote = bool(new)
|
||||||
|
press_now = s["press_t"] == t
|
||||||
|
for tt, a in new:
|
||||||
|
if a > 0:
|
||||||
|
s["tried"].add(a)
|
||||||
|
if a > 0 and (w.hold or (kind == "solar"
|
||||||
|
and w.mismatch_since is not None)):
|
||||||
|
# judged after the step's own watch (a count a read cleared
|
||||||
|
# in this step is no count when the write goes out); Manual
|
||||||
|
# writes through a count and stops at the hold (EV-22)
|
||||||
|
bad.append((kind, seed, t, "N2 write while a count/hold "
|
||||||
|
"stood", a))
|
||||||
|
if a == 0.0 and w.hold:
|
||||||
|
bad.append((kind, seed, t, "N7 0 A under a hold"))
|
||||||
|
cutv = getattr(w, "cut_a", None)
|
||||||
|
if a > cl + 1e-9 and not (cutv is not None and a <= cutv + 1e-9):
|
||||||
|
bad.append((kind, seed, t, "N5 above the clamp", a, cl))
|
||||||
|
if 0 < a < CM.CH.MIN_A - 1e-9:
|
||||||
|
bad.append((kind, seed, t, "N5 in 0-6 A", a))
|
||||||
|
if getattr(w, "cut_fails", 0) > CM.MAX_TRIES:
|
||||||
|
bad.append((kind, seed, t, "N6 cut tries over the cap"))
|
||||||
|
for tt, n_, cur_ in drv.sel[sel0:]:
|
||||||
|
if cur_ > CM.TOL_A:
|
||||||
|
bad.append((kind, seed, t, "N8 select over load", cur_))
|
||||||
|
if w.hold and not s["prev_hold"]:
|
||||||
|
s["hold_rises"] += 1
|
||||||
|
bump("hold")
|
||||||
|
fv = s["fv"]
|
||||||
|
if fv is not None and 0 <= t - fv[0] <= 60 \
|
||||||
|
and drv.cur == fv[1] and 0 <= t - s["end_t"] <= 300:
|
||||||
|
bump("foreign_hold_after_end")
|
||||||
|
s["prev_hold"] = w.hold
|
||||||
|
lines = len([1 for _t, lv, m in K.LOG
|
||||||
|
if (kind == "solar" and K.OTHER in m)
|
||||||
|
or (kind == "manual" and K.SOMETHING in m)])
|
||||||
|
if lines > s["hold_rises"]:
|
||||||
|
bad.append((kind, seed, t, "N9 more lines than holds", lines,
|
||||||
|
s["hold_rises"]))
|
||||||
|
ended_now = before_seq and w.seq is None
|
||||||
|
if w.hold and w._carry:
|
||||||
|
bad.append((kind, seed, t, "N4 carry under a hold", w._carry))
|
||||||
|
if press_now and w._carry and not ended_now:
|
||||||
|
bad.append((kind, seed, t, "N4 carry after a press", w._carry))
|
||||||
|
if wrote and w._carry and not ended_now:
|
||||||
|
bad.append((kind, seed, t, "N4 carry after a write", w._carry))
|
||||||
|
# the oracle's bound: armed by an end whose last value is not taken,
|
||||||
|
# disarmed by anything that ends it (a superset of the code's ends)
|
||||||
|
took = (kind == "solar" and w.taken) or (
|
||||||
|
kind == "manual" and w.last_a is not None)
|
||||||
|
if ended_now and not took and not gone:
|
||||||
|
s["vals"] = [0.0] + [a for a in s["seq_own"] if a > 0] + [
|
||||||
|
a for tt, a in new if a > 0]
|
||||||
|
s["armed"] = True
|
||||||
|
s["end_t"] = t
|
||||||
|
s["cap"] = kind == "solar" and w.cut_fails >= CM.MAX_TRIES
|
||||||
|
s["cap_counted"] = False
|
||||||
|
bump("end")
|
||||||
|
if s["cap"]:
|
||||||
|
bump("end_cap")
|
||||||
|
elif s["armed"]:
|
||||||
|
if wrote or press_now or w.hold or gone or s["was_gone"] \
|
||||||
|
or took:
|
||||||
|
s["armed"] = False
|
||||||
|
elif w.mismatch_since is not None:
|
||||||
|
if seen is not None and seen > CM.TOL_A and seen in s["vals"]:
|
||||||
|
bad.append((kind, seed, t, "N1 a late take of a tried "
|
||||||
|
"value is held as another writer's", seen,
|
||||||
|
s["vals"]))
|
||||||
|
s["armed"] = False # a foreign value: judged as ever
|
||||||
|
bump("armed_foreign")
|
||||||
|
elif seen is not None and seen > CM.TOL_A and seen in s["vals"]:
|
||||||
|
bump("armed_take_seen")
|
||||||
|
if s["cap"] and not s["cap_counted"]:
|
||||||
|
s["cap_counted"] = True
|
||||||
|
bump("cap_end_take")
|
||||||
|
s["was_gone"] = gone
|
||||||
|
if order_b:
|
||||||
|
ev(t)
|
||||||
|
return bad
|
||||||
|
|
||||||
|
|
||||||
|
def fuzz_directed(kind, seed):
|
||||||
|
"""The directed pass (round 3's calm Solar pass), in addition."""
|
||||||
|
rnd = random.Random(seed * 7 + (0 if kind == "solar" else 1) + 1000)
|
||||||
|
order_b = seed % 2 == 1
|
||||||
|
st = {"a": rnd.choice([8.0, 10.0, 12.0]), "n": 1, "rev": 1,
|
||||||
|
"clamp": 16.0}
|
||||||
|
if kind == "solar":
|
||||||
|
w = K.swriter(8.0, ph=1)
|
||||||
|
w.cut_key = 0
|
||||||
|
else:
|
||||||
|
w = CM.ManualWriter()
|
||||||
|
mode = {"refuse": 1.0 if kind == "solar" else 0.97, "raise": 0.0}
|
||||||
|
|
||||||
|
def take(a, d):
|
||||||
|
if a == 0.0:
|
||||||
|
return True
|
||||||
|
if rnd.random() < mode["raise"]:
|
||||||
|
return "raise"
|
||||||
|
return rnd.random() >= mode["refuse"]
|
||||||
|
drv = K.Drv(8.0 if kind == "solar" else st["a"], take, ph=1)
|
||||||
|
run = K.Run(w, drv, kind=kind, st=st)
|
||||||
|
bad = []
|
||||||
|
s = dict(armed=False, vals=[], seq_own=[], hold_rises=0, press_t=-1,
|
||||||
|
prev_hold=False, was_gone=False, gone=False, tried=set(),
|
||||||
|
kind=None, cap_counted=False, seq_n0=0, fv=None, pend=None,
|
||||||
|
inj=None, end_t=-9999)
|
||||||
|
clamp = {"v": 16.0}
|
||||||
|
|
||||||
|
def ev(t):
|
||||||
|
if s["inj"] is not None: # a directed old-value take
|
||||||
|
drv.cur = s["inj"]["v"]
|
||||||
|
return
|
||||||
|
closed = w.seq is not None and (kind == "manual" or [
|
||||||
|
1 for tt, a in drv.calls[s["seq_n0"]:] if a > 0])
|
||||||
|
if rnd.random() < (0.4 if closed else 0.01): # falls after a close
|
||||||
|
clamp["v"] = rnd.choice([16.0, 14.0, 12.0, 10.0, 8.0, 7.0, 6.0])
|
||||||
|
st["clamp"] = clamp["v"]
|
||||||
|
if kind == "solar" and rnd.random() < 0.01:
|
||||||
|
K.set_cap(w, rnd.choice([None, 6.0, 6.0, 7.0]))
|
||||||
|
if kind == "solar" and w.seq is not None and w.cut_a is None \
|
||||||
|
and [1 for tt, a in drv.calls[s["seq_n0"]:] if a > 0] \
|
||||||
|
and rnd.random() < 0.4:
|
||||||
|
# the EV-60 cap end shape: a close went, then the cap comes, the
|
||||||
|
# earlier cut tries of this key being used up
|
||||||
|
K.set_cap(w, 6.0)
|
||||||
|
w.cut_fails, w.cut_fail_at = max(w.cut_fails, 2), -100.0
|
||||||
|
if w.hold and rnd.random() < 0.03:
|
||||||
|
w.user_changed() # a press lifts a hold
|
||||||
|
if kind == "manual":
|
||||||
|
st["rev"] += 1
|
||||||
|
s["press_t"] = t
|
||||||
|
bump("press")
|
||||||
|
if kind == "solar" and not s["armed"] and w.seq is None \
|
||||||
|
and (w.gave_up or w.fail_at is not None) \
|
||||||
|
and rnd.random() < 0.05:
|
||||||
|
w.user_changed() # a press lifts the give-up
|
||||||
|
s["press_t"] = t
|
||||||
|
bump("press")
|
||||||
|
if rnd.random() < 0.004:
|
||||||
|
mode["refuse"] = rnd.choice(
|
||||||
|
[0.97, 1.0, 1.0, 1.0, 1.0, 1.0] if kind == "solar" else
|
||||||
|
[0.0, 0.5, 0.97, 1.0, 1.0, 1.0])
|
||||||
|
mode["raise"] = rnd.choice([0.0, 0.0, 0.3])
|
||||||
|
# a phase change: Solar's plan decides it, Manual's user asks for it
|
||||||
|
if w.seq is None and rnd.random() < (0.1 if kind == "solar" else 0.03):
|
||||||
|
n_to = 3 if drv.ph == 1 else 1
|
||||||
|
if kind == "solar":
|
||||||
|
if not w.plan.switch:
|
||||||
|
w.plan.n = drv.ph # the plan believes the phases read
|
||||||
|
w.plan._set(rnd.choice([10.0, 12.0, 14.0]), float(t), n_to)
|
||||||
|
clamp["v"] = st["clamp"] = 16.0 # it falls later
|
||||||
|
K.set_cap(w, None) # a cap comes later
|
||||||
|
w.cut_fails = 0
|
||||||
|
else:
|
||||||
|
w.user_changed()
|
||||||
|
st["rev"] += 1
|
||||||
|
st["n"] = n_to
|
||||||
|
st["a"] = rnd.choice([8.0, 10.0, 12.0, 14.0])
|
||||||
|
s["press_t"] = t
|
||||||
|
# a late take of any value the writer tried (the ended change's
|
||||||
|
# values first)
|
||||||
|
calm = kind == "solar" and w.seq is not None
|
||||||
|
if rnd.random() < (0.0 if calm else 0.08):
|
||||||
|
pool = [v for v in s["vals"] if v > 0] if (
|
||||||
|
s["armed"] and rnd.random() < 0.6) else sorted(
|
||||||
|
v for v in s["tried"] if v > 0)
|
||||||
|
if pool:
|
||||||
|
v = rnd.choice(pool)
|
||||||
|
drv.cur = v
|
||||||
|
bump("late_take")
|
||||||
|
if s["armed"] and v in s["vals"]:
|
||||||
|
bump("late_take_ended_val")
|
||||||
|
if v != s["vals"][-1]:
|
||||||
|
bump(f"late_nonlast_{kind}")
|
||||||
|
if rnd.random() < (0.0 if calm else 0.005):
|
||||||
|
drv.cur = rnd.choice([5.0, 7.0, 9.0, 11.0, 13.0, 15.0]
|
||||||
|
+ sorted(s["tried"]))
|
||||||
|
s["fv"] = (t, drv.cur)
|
||||||
|
bump("foreign")
|
||||||
|
if rnd.random() < 0.005:
|
||||||
|
w.user_changed()
|
||||||
|
if kind == "manual":
|
||||||
|
st["rev"] += 1
|
||||||
|
s["press_t"] = t
|
||||||
|
bump("press")
|
||||||
|
if rnd.random() < (0.0 if calm else 0.01):
|
||||||
|
drv.cur = 0.0
|
||||||
|
s["gone"] = s["gone"] and rnd.random() < 0.8 or (
|
||||||
|
not s["gone"] and rnd.random() < 0.003)
|
||||||
|
if kind == "solar" and s["armed"] and rnd.random() < 0.08:
|
||||||
|
s["gone"] = True # a charger return inside the bound
|
||||||
|
|
||||||
|
for t in range(STEPS):
|
||||||
|
if not order_b:
|
||||||
|
ev(t)
|
||||||
|
inj = s["inj"]
|
||||||
|
gone = False if inj else s["gone"]
|
||||||
|
unk = False if inj else rnd.random() < 0.02
|
||||||
|
stale = False if inj else rnd.random() < 0.02
|
||||||
|
n0, sel0 = len(drv.calls), len(drv.sel)
|
||||||
|
before_seq = w.seq is not None
|
||||||
|
if before_seq:
|
||||||
|
s["seq_own"] = list(w.seq.get("own", ()))
|
||||||
|
drv.now = float(t)
|
||||||
|
K.CLOCK["t"] = t
|
||||||
|
if hasattr(w, "cut_quarter"):
|
||||||
|
w.cut_quarter(int(t // 900))
|
||||||
|
seen = None if unk else drv.cur
|
||||||
|
rd = K.Rd(seen, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
|
||||||
|
rd.available = not gone
|
||||||
|
run.trk.obs_at = (w.last_done if (stale and w.last_done is not None)
|
||||||
|
else None)
|
||||||
|
cl = clamp["v"]
|
||||||
|
if kind == "solar":
|
||||||
|
K.LOOP.run_until_complete(w.step(
|
||||||
|
drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0),
|
||||||
|
clamp=cl, now=float(t), tracker=run.trk, writing=True,
|
||||||
|
status="charging"))
|
||||||
|
else:
|
||||||
|
K.LOOP.run_until_complete(w.step(
|
||||||
|
drv, rd, mode=CM.MANUAL, want_a=st["a"],
|
||||||
|
want_phases=st["n"], rev=st["rev"], clamp=cl, now=float(t),
|
||||||
|
tracker=run.trk, writing=True, status="charging"))
|
||||||
|
new = drv.calls[n0:]
|
||||||
|
wrote = bool(new)
|
||||||
|
press_now = s["press_t"] == t
|
||||||
|
for tt, a in new:
|
||||||
|
if a > 0:
|
||||||
|
s["tried"].add(a)
|
||||||
|
if a > 0 and (w.hold or (kind == "solar"
|
||||||
|
and w.mismatch_since is not None)):
|
||||||
|
bad.append((kind, seed, t, "N2 write while a count/hold "
|
||||||
|
"stood", a))
|
||||||
|
if a == 0.0 and w.hold:
|
||||||
|
bad.append((kind, seed, t, "N7 0 A under a hold"))
|
||||||
|
cutv = getattr(w, "cut_a", None)
|
||||||
|
if a > cl + 1e-9 and not (cutv is not None and a <= cutv + 1e-9):
|
||||||
|
bad.append((kind, seed, t, "N5 above the clamp", a, cl))
|
||||||
|
if 0 < a < CM.CH.MIN_A - 1e-9:
|
||||||
|
bad.append((kind, seed, t, "N5 in 0-6 A", a))
|
||||||
|
if getattr(w, "cut_fails", 0) > CM.MAX_TRIES:
|
||||||
|
bad.append((kind, seed, t, "N6 cut tries over the cap"))
|
||||||
|
for tt, n_, cur_ in drv.sel[sel0:]:
|
||||||
|
if cur_ > CM.TOL_A:
|
||||||
|
bad.append((kind, seed, t, "N8 select over load", cur_))
|
||||||
|
if w.hold and not s["prev_hold"]:
|
||||||
|
s["hold_rises"] += 1
|
||||||
|
bump("hold")
|
||||||
|
fv = s["fv"]
|
||||||
|
if fv is not None and s["inj"] is None and 0 <= t - fv[0] <= 60 \
|
||||||
|
and drv.cur == fv[1] and 0 <= t - s["end_t"] <= 300:
|
||||||
|
# the hold rose over a value the random foreign branch set
|
||||||
|
# (never one of N1b's directed old-value takes)
|
||||||
|
bump("foreign_hold_after_end")
|
||||||
|
s["prev_hold"] = w.hold
|
||||||
|
lines = len([1 for _t, lv, m in K.LOG
|
||||||
|
if (kind == "solar" and K.OTHER in m)
|
||||||
|
or (kind == "manual" and K.SOMETHING in m)])
|
||||||
|
if lines > s["hold_rises"]:
|
||||||
|
bad.append((kind, seed, t, "N9 more lines than holds", lines,
|
||||||
|
s["hold_rises"]))
|
||||||
|
ended_now = before_seq and w.seq is None
|
||||||
|
if not before_seq and w.seq is not None:
|
||||||
|
bump(f"seq_start_{kind}")
|
||||||
|
s["seq_n0"] = len(drv.calls)
|
||||||
|
if ended_now:
|
||||||
|
tk = (kind == "solar" and w.taken) or (
|
||||||
|
kind == "manual" and w.last_a is not None)
|
||||||
|
bump(f"seq_end_{kind}_{'taken' if tk else 'refused'}")
|
||||||
|
if w.hold and w._carry:
|
||||||
|
bad.append((kind, seed, t, "N4 carry under a hold", w._carry))
|
||||||
|
if press_now and w._carry and not ended_now:
|
||||||
|
bad.append((kind, seed, t, "N4 carry after a press", w._carry))
|
||||||
|
if wrote and w._carry and not ended_now:
|
||||||
|
bad.append((kind, seed, t, "N4 carry after a write", w._carry))
|
||||||
|
# the directed old-value take (N1b)
|
||||||
|
if inj is not None:
|
||||||
|
inj["n"] += 1
|
||||||
|
if wrote or press_now or w.seq is not None \
|
||||||
|
or drv.cur != inj["v"] or inj["n"] > 60:
|
||||||
|
s["inj"] = None # something else happened: no verdict
|
||||||
|
bump("inj_aborted")
|
||||||
|
elif inj["n"] >= CM.WRITER_S + 3:
|
||||||
|
s["inj"] = None
|
||||||
|
if w.hold:
|
||||||
|
bump(f"bound_{inj['cause']}_held")
|
||||||
|
bump("bound_held")
|
||||||
|
else:
|
||||||
|
bad.append((kind, seed, t, "N1b an old value after the "
|
||||||
|
f"bound ended ({inj['cause']}) is not held",
|
||||||
|
inj["v"], w.mismatch_since))
|
||||||
|
# the oracle's bound: armed by an end whose last value is not taken,
|
||||||
|
# disarmed by anything that ends it (a superset of the code's ends)
|
||||||
|
took = (kind == "solar" and w.taken) or (
|
||||||
|
kind == "manual" and w.last_a is not None)
|
||||||
|
if ended_now and not took and not gone:
|
||||||
|
s["vals"] = [0.0] + [a for a in s["seq_own"] if a > 0] + [
|
||||||
|
a for tt, a in new if a > 0]
|
||||||
|
s["armed"] = True
|
||||||
|
s["end_t"] = t
|
||||||
|
s["cap_counted"] = False
|
||||||
|
s["pend"] = None
|
||||||
|
s["kind"] = "cap" if (kind == "solar" and not wrote
|
||||||
|
and w.cut_fails >= CM.MAX_TRIES) else "max"
|
||||||
|
bump("end")
|
||||||
|
bump(f"end_{kind}")
|
||||||
|
if len(set(a for a in s["vals"] if a > 0)) > 1:
|
||||||
|
bump(f"end_distinct_{kind}")
|
||||||
|
if s["kind"] == "cap":
|
||||||
|
bump("end_cap")
|
||||||
|
elif s["armed"]:
|
||||||
|
cause = ("hold" if w.hold else "user" if press_now
|
||||||
|
else "write" if wrote
|
||||||
|
else "return" if (gone or s["was_gone"])
|
||||||
|
else "take" if took else None)
|
||||||
|
if cause is not None:
|
||||||
|
s["armed"] = False
|
||||||
|
if not (kind == "manual" and cause == "return"):
|
||||||
|
s["pend"] = (cause, list(s["vals"]))
|
||||||
|
elif w.mismatch_since is not None:
|
||||||
|
if seen is not None and seen > CM.TOL_A and seen in s["vals"]:
|
||||||
|
bad.append((kind, seed, t, "N1 a late take of a tried "
|
||||||
|
"value is held as another writer's", seen,
|
||||||
|
s["vals"]))
|
||||||
|
s["armed"] = False # a foreign value: judged as ever
|
||||||
|
s["pend"] = ("hold", list(s["vals"]))
|
||||||
|
bump("armed_foreign")
|
||||||
|
elif seen is not None and seen > CM.TOL_A and seen in s["vals"]:
|
||||||
|
bump("armed_take_seen")
|
||||||
|
if s["kind"] == "cap" and not s["cap_counted"]:
|
||||||
|
s["cap_counted"] = True
|
||||||
|
bump("cap_end_take")
|
||||||
|
# start a directed old-value take once the bound has ended and the
|
||||||
|
# writer is calm: the value must not be own by any other route
|
||||||
|
if s["pend"] is not None and s["pend"][0] == "hold" \
|
||||||
|
and not w.hold and w.mismatch_since is None:
|
||||||
|
s["pend"] = None # the foreign value went: no hold
|
||||||
|
if s["pend"] is not None and s["inj"] is None and not gone \
|
||||||
|
and not unk and not stale and w.seq is None and not wrote \
|
||||||
|
and not press_now and rnd.random() < 0.5 \
|
||||||
|
and (s["pend"][0] != "hold" or w.hold):
|
||||||
|
cause, vals = s["pend"]
|
||||||
|
own = w._own_values()
|
||||||
|
pool = [v for v in vals if v > CM.TOL_A
|
||||||
|
and all(abs(v - o) > CM.TOL_A for o in own)]
|
||||||
|
if not pool: # any other value the writer tried
|
||||||
|
pool = [v for v in sorted(s["tried"]) if v > CM.TOL_A
|
||||||
|
and all(abs(v - o) > CM.TOL_A for o in own)]
|
||||||
|
s["pend"] = None
|
||||||
|
if not pool:
|
||||||
|
bump(f"inj_no_value_{cause}")
|
||||||
|
elif not own and not w.hold:
|
||||||
|
bump("inj_blind") # nothing own to judge against
|
||||||
|
elif cause != "hold" and w.hold:
|
||||||
|
bump("inj_other_hold")
|
||||||
|
else:
|
||||||
|
s["inj"] = dict(v=rnd.choice(pool), cause=cause, n=0)
|
||||||
|
drv.cur = s["inj"]["v"]
|
||||||
|
bump("inj_started")
|
||||||
|
s["was_gone"] = gone
|
||||||
|
if order_b:
|
||||||
|
ev(t)
|
||||||
|
return bad
|
||||||
|
|
||||||
|
|
||||||
|
# Fixed floor lists (no fallback between passes). MIXED_FLOOR is 9b09158's
|
||||||
|
# list, each floor asserted on the mixed counts alone. DIRECTED_FLOOR holds
|
||||||
|
# the plan floors the mixed pass does not reach, asserted on the directed
|
||||||
|
# counts alone.
|
||||||
|
MIXED_FLOOR = {"end": 20, "end_cap": 3, "late_take_ended_val": 10,
|
||||||
|
"late_take_nonlast": 5, "armed_take_seen": 20, "foreign": 20,
|
||||||
|
"hold": 5}
|
||||||
|
DIRECTED_FLOOR = {"late_nonlast_solar": 10, "late_nonlast_manual": 5,
|
||||||
|
"cap_end_take": 5, "bound_take_held": 5,
|
||||||
|
"bound_write_held": 5, "bound_user_held": 5,
|
||||||
|
"bound_hold_held": 5, "bound_return_held": 5,
|
||||||
|
"foreign_hold_after_end": 5}
|
||||||
|
TAGS = {"mixed": ("N1", "N2", "N4", "N5", "N6", "N7", "N8", "N9"),
|
||||||
|
"directed": ("N1", "N1b", "N2", "N4", "N5", "N6", "N7", "N8", "N9")}
|
||||||
|
MIXED, DIRECTED = {}, {}
|
||||||
|
GAP = CM.PHASE_GAP_S
|
||||||
|
# The directed pass runs 4 x SEEDS seeds (foreign_hold_after_end is rare when
|
||||||
|
# Solar changes run calm); the mixed pass keeps 9b09158's SEEDS.
|
||||||
|
for name, fn, counts, gap, nseeds, floor in (
|
||||||
|
("mixed", fuzz_mixed, MIXED, GAP, SEEDS, MIXED_FLOOR),
|
||||||
|
("directed", fuzz_directed, DIRECTED, 40.0, 4 * SEEDS,
|
||||||
|
DIRECTED_FLOOR)):
|
||||||
|
COUNT = counts
|
||||||
|
CM.PHASE_GAP_S = gap # the directed pass: many changes in 1200 s
|
||||||
|
allbad = []
|
||||||
|
for kind in ("solar", "manual"):
|
||||||
|
for seed in range(nseeds):
|
||||||
|
allbad += fn(kind, seed)
|
||||||
|
CM.PHASE_GAP_S = GAP
|
||||||
|
for tag in TAGS[name]:
|
||||||
|
hit = [b for b in allbad if b[3].startswith(tag + " ")]
|
||||||
|
K.check(f"T21 {tag}: holds in every cycle of {nseeds} seeds x {STEPS} "
|
||||||
|
f"s, Solar and Manual, both orders, {name} pass ({hit[:2]})",
|
||||||
|
not hit)
|
||||||
|
print(f" {name} counts", dict(sorted(counts.items())))
|
||||||
|
if STEPS >= 1200 and SEEDS >= 10:
|
||||||
|
for k, v in floor.items():
|
||||||
|
K.check(f"T21 floor {k} >= {v} in the {name} pass alone "
|
||||||
|
f"({counts.get(k, 0)})", counts.get(k, 0) >= v)
|
||||||
|
K.done()
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
"""EV-69: the writer-level harness of test_ev69.py and test_ev69_fuzz.py: a
|
||||||
|
`SolarWriter` / `ManualWriter` on a stub driver, a stub tracker and a stub
|
||||||
|
reading, one step per second on a model clock; `Run` records what every step
|
||||||
|
ended with. `Base69` / `BaseM69` are de733f4's writers (the carry switched
|
||||||
|
off): the red side of a row.
|
||||||
|
|
||||||
|
Each check file is its own process, so `fails` and `LOG` are its own."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
_KIT = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
sys.path.insert(0, os.path.dirname(_KIT))
|
||||||
|
|
||||||
|
from app import carmode as CM # noqa: E402
|
||||||
|
|
||||||
|
fails = []
|
||||||
|
CLOCK = {"t": 0}
|
||||||
|
LOG = []
|
||||||
|
OTHER = "CHARGER_OTHER"
|
||||||
|
SOMETHING = "Something else changes the charger"
|
||||||
|
REC = "The car charger step failed"
|
||||||
|
|
||||||
|
|
||||||
|
class Cap(logging.Handler):
|
||||||
|
def emit(self, rec):
|
||||||
|
LOG.append((CLOCK["t"], rec.levelname, rec.getMessage()))
|
||||||
|
|
||||||
|
|
||||||
|
logging.getLogger("goodwe").addHandler(Cap())
|
||||||
|
logging.getLogger("goodwe").setLevel(logging.DEBUG)
|
||||||
|
|
||||||
|
|
||||||
|
def check(name, cond):
|
||||||
|
print(f" {'ok ' if cond else 'FAIL'} {name}")
|
||||||
|
if not cond:
|
||||||
|
fails.append(name)
|
||||||
|
|
||||||
|
|
||||||
|
def done():
|
||||||
|
print("\nall passed" if not fails else f"\n{len(fails)} FAILED")
|
||||||
|
for f in fails:
|
||||||
|
print(" FAIL:", f)
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
|
|
||||||
|
|
||||||
|
class Rd:
|
||||||
|
def __init__(self, a, ph=1, power=None, state="C"):
|
||||||
|
self.available = True
|
||||||
|
self.allowed_a = self.setpoint_a = a
|
||||||
|
self.phases_allowed = ph
|
||||||
|
self.power_w = power
|
||||||
|
self.state = state
|
||||||
|
self.error = False
|
||||||
|
self.charging = True
|
||||||
|
self.current_a = ()
|
||||||
|
self.station_a = None
|
||||||
|
|
||||||
|
|
||||||
|
class Trk:
|
||||||
|
obs_at = None
|
||||||
|
|
||||||
|
def begin_write(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def end_write(self, *_):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def note_write(self, *a, **k):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def stuck(self, now):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class Drv:
|
||||||
|
"""`take(a, drv)` -> True (the charger takes it), False (refused) or
|
||||||
|
"raise" (the call raises)."""
|
||||||
|
|
||||||
|
def __init__(self, cur, take, ph=1):
|
||||||
|
self.cur, self.ph, self.take = cur, ph, take
|
||||||
|
self.calls, self.now, self.polls, self.sel = [], 0.0, (), []
|
||||||
|
|
||||||
|
async def write_current(self, a, **kw):
|
||||||
|
self.calls.append((self.now, float(a)))
|
||||||
|
r = self.take(float(a), self)
|
||||||
|
if r == "raise":
|
||||||
|
raise RuntimeError("HA call error")
|
||||||
|
if r is True:
|
||||||
|
self.cur = float(a)
|
||||||
|
return r is True
|
||||||
|
|
||||||
|
async def write_phases(self, n):
|
||||||
|
self.sel.append((self.now, n, self.cur))
|
||||||
|
self.ph = n
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _clock(self):
|
||||||
|
return self.now
|
||||||
|
|
||||||
|
async def _sleep(self, s):
|
||||||
|
self.now += s
|
||||||
|
|
||||||
|
|
||||||
|
class Base69(CM.SolarWriter):
|
||||||
|
"""de733f4's Solar: an ended sequence's values are not carried."""
|
||||||
|
|
||||||
|
def _carry_end(self, q):
|
||||||
|
self._carry = []
|
||||||
|
|
||||||
|
|
||||||
|
class BaseM69(CM.ManualWriter):
|
||||||
|
"""de733f4's Manual."""
|
||||||
|
|
||||||
|
def _carry_end(self, q):
|
||||||
|
self._carry = []
|
||||||
|
|
||||||
|
|
||||||
|
LOOP = asyncio.new_event_loop()
|
||||||
|
|
||||||
|
|
||||||
|
def swriter(cur, ph=1, cls=None):
|
||||||
|
w = (cls or CM.SolarWriter)()
|
||||||
|
w.engaged, w.mode_was = True, CM.SOLAR
|
||||||
|
w.fresh_start = w.restart = False
|
||||||
|
w.was_available = w._seen = True
|
||||||
|
w.sent_a, w.taken, w.last_a = cur, True, cur
|
||||||
|
w.plan.a, w.plan.n = cur, ph
|
||||||
|
|
||||||
|
def plan_step(sun, now, clamp, n, gap):
|
||||||
|
c = w.cut_a
|
||||||
|
if c is not None and c >= CM.CH.MIN_A and w.plan.a > c + 1e-9:
|
||||||
|
w.plan._cut(c)
|
||||||
|
w._plan_step = plan_step
|
||||||
|
return w
|
||||||
|
|
||||||
|
|
||||||
|
def set_cap(w, a):
|
||||||
|
w.cut_a, w.cut_on = a, a is not None
|
||||||
|
|
||||||
|
|
||||||
|
def show(a):
|
||||||
|
return lambda w, d, s: setattr(d, "cur", float(a))
|
||||||
|
|
||||||
|
|
||||||
|
def press(w, d, s):
|
||||||
|
w.user_changed()
|
||||||
|
s["rev"] = s.get("rev", 1) + 1
|
||||||
|
|
||||||
|
|
||||||
|
def cap(a):
|
||||||
|
return lambda w, d, s: set_cap(w, a)
|
||||||
|
|
||||||
|
|
||||||
|
def chain(*fns):
|
||||||
|
def f(w, d, s):
|
||||||
|
for fn in fns:
|
||||||
|
fn(w, d, s)
|
||||||
|
return f
|
||||||
|
|
||||||
|
|
||||||
|
def evs(*pairs):
|
||||||
|
"""{t: fn(w, drv, st)}; two at one second run both."""
|
||||||
|
out = {}
|
||||||
|
for t, fn in pairs:
|
||||||
|
out[t] = chain(out[t], fn) if t in out else fn
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
class Run:
|
||||||
|
"""One writer-level run; per second: mismatch, hold, counts."""
|
||||||
|
|
||||||
|
def __init__(self, w, drv, kind="solar", st=None):
|
||||||
|
del LOG[:]
|
||||||
|
self.w, self.drv, self.kind = w, drv, kind
|
||||||
|
self.trk, self.st = Trk(), st if st is not None else {}
|
||||||
|
self.ms, self.hold, self.gu, self.fl, self.seq = {}, {}, {}, {}, {}
|
||||||
|
self.taken, self.last_a, self.sent_a = {}, {}, {}
|
||||||
|
self.prior, self.att, self.carry, self.ncalls = {}, {}, {}, {}
|
||||||
|
self.own = {}
|
||||||
|
self.viol, self.ended, self.log = [], None, []
|
||||||
|
|
||||||
|
def go(self, t0, t1, ev=None, hook=None, clamp=16.0, writing=None,
|
||||||
|
cur=None, stale=None, gone=None):
|
||||||
|
w, drv = self.w, self.drv
|
||||||
|
for t in range(t0, t1 + 1):
|
||||||
|
drv.now = float(t)
|
||||||
|
CLOCK["t"] = t
|
||||||
|
if ev and t in ev:
|
||||||
|
ev[t](w, drv, self.st)
|
||||||
|
if hook:
|
||||||
|
hook(t, w, drv, self.st)
|
||||||
|
if hasattr(w, "cut_quarter"):
|
||||||
|
w.cut_quarter(int(t // 900))
|
||||||
|
c = drv.cur if cur is None else cur(t, drv)
|
||||||
|
rd = Rd(c, drv.ph, power=0.0 if drv.cur == 0 else 1840.0)
|
||||||
|
if gone is not None and gone(t):
|
||||||
|
rd.available = False
|
||||||
|
cl = clamp(t) if callable(clamp) else clamp
|
||||||
|
if self.kind == "manual":
|
||||||
|
cl = self.st.get("clamp", cl)
|
||||||
|
self.trk.obs_at = None
|
||||||
|
if stale is not None and stale(t):
|
||||||
|
self.trk.obs_at = w.last_done if w.last_done is not None \
|
||||||
|
else 0.0
|
||||||
|
wr = True if writing is None else writing(t)
|
||||||
|
n0, s0 = len(drv.calls), w.seq is not None
|
||||||
|
if self.kind == "solar":
|
||||||
|
LOOP.run_until_complete(w.step(
|
||||||
|
drv, rd, mode=CM.SOLAR, sun=CM.SunInputs(target_w=2000.0),
|
||||||
|
clamp=cl, now=float(t), tracker=self.trk, writing=wr,
|
||||||
|
status="charging"))
|
||||||
|
else:
|
||||||
|
LOOP.run_until_complete(w.step(
|
||||||
|
drv, rd, mode=CM.MANUAL, want_a=self.st["a"],
|
||||||
|
want_phases=self.st["n"], rev=self.st["rev"], clamp=cl,
|
||||||
|
now=float(t), tracker=self.trk, writing=wr,
|
||||||
|
status="charging"))
|
||||||
|
if s0 and w.seq is None and self.ended is None:
|
||||||
|
self.ended = t
|
||||||
|
# N2 is judged on the state after the step's own watch: a count
|
||||||
|
# a read cleared in this step (the foreign value went) is no
|
||||||
|
# count when the write goes out.
|
||||||
|
stood = bool(w.hold or (self.kind == "solar"
|
||||||
|
and w.mismatch_since is not None))
|
||||||
|
for tt, a in drv.calls[n0:]:
|
||||||
|
# N2 / N5 per write
|
||||||
|
if a > 0 and stood:
|
||||||
|
self.viol.append((t, "N2 write while a count/hold stood",
|
||||||
|
a))
|
||||||
|
if a > cl + 1e-9 or 0 < a < CM.CH.MIN_A - 1e-9:
|
||||||
|
if not (w.cut_a is not None and a <= w.cut_a + 1e-9):
|
||||||
|
self.viol.append((t, "N5 write outside clamp/6 A", a))
|
||||||
|
if getattr(w, "cut_fails", 0) > CM.MAX_TRIES:
|
||||||
|
self.viol.append((t, "N6 cut tries over the cap"))
|
||||||
|
self.ms[t], self.hold[t] = w.mismatch_since, w.hold
|
||||||
|
self.gu[t], self.fl[t] = w.gave_up, w.fails
|
||||||
|
self.seq[t], self.taken[t] = w.seq is not None, getattr(
|
||||||
|
w, "taken", None)
|
||||||
|
self.last_a[t], self.sent_a[t] = w.last_a, getattr(
|
||||||
|
w, "sent_a", None)
|
||||||
|
self.prior[t], self.att[t] = w.prior_a, w.attempted_a
|
||||||
|
self.carry[t] = list(getattr(w, "_carry", []))
|
||||||
|
self.own[t] = list(w._own_values())
|
||||||
|
self.ncalls[t] = len(drv.calls)
|
||||||
|
self.log = list(LOG)
|
||||||
|
LAST[0] = self
|
||||||
|
return self
|
||||||
|
|
||||||
|
# ---------------------------------------------------------- readings
|
||||||
|
def calls_from(self, t0, t1=10 ** 9, nz=False):
|
||||||
|
return [(int(t), a) for t, a in self.drv.calls
|
||||||
|
if t0 <= t <= t1 and (not nz or a > 0)]
|
||||||
|
|
||||||
|
def clean(self, lo, hi):
|
||||||
|
"""No mismatch, no hold, no CHARGER_OTHER line, no 'Something else
|
||||||
|
changes' line in lo..hi."""
|
||||||
|
return (all(self.ms[t] is None and not self.hold[t]
|
||||||
|
for t in range(lo, hi + 1) if t in self.ms)
|
||||||
|
and not [1 for t, lv, m in self.log if lo <= t <= hi
|
||||||
|
and (OTHER in m or SOMETHING in m)])
|
||||||
|
|
||||||
|
def first_ms(self, lo=0):
|
||||||
|
for t in sorted(self.ms):
|
||||||
|
if t >= lo and self.ms[t] is not None:
|
||||||
|
return t
|
||||||
|
return None
|
||||||
|
|
||||||
|
def first_hold(self, lo=0):
|
||||||
|
for t in sorted(self.hold):
|
||||||
|
if t >= lo and self.hold[t]:
|
||||||
|
return t
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
LAST = [None] # the run that ended last: what `n_other` / `n_some` count
|
||||||
|
|
||||||
|
|
||||||
|
def n_other():
|
||||||
|
return len([1 for t, lv, m in LAST[0].log if OTHER in m])
|
||||||
|
|
||||||
|
|
||||||
|
def n_some():
|
||||||
|
return len([1 for t, lv, m in LAST[0].log if SOMETHING in m])
|
||||||
|
|
||||||
|
|
||||||
|
def near(x, lo, hi):
|
||||||
|
return x is not None and lo <= x <= hi
|
||||||
|
|
||||||
|
|
||||||
|
def nev(tag, run):
|
||||||
|
"""N2, N5, N6 over one run (collected per step by `Run.go`), N9 (one
|
||||||
|
CHARGER_OTHER per hold rise), N8 (a select only at 0 A)."""
|
||||||
|
rises = 0
|
||||||
|
prev = False
|
||||||
|
for t in sorted(run.hold):
|
||||||
|
if run.hold[t] and not prev:
|
||||||
|
rises += 1
|
||||||
|
prev = run.hold[t]
|
||||||
|
sel_bad = [x for x in run.drv.sel if x[2] > CM.TOL_A]
|
||||||
|
check(f"N2/N5/N6 {tag}: no write over a count or hold, none above the "
|
||||||
|
f"clamp or in 0-6 A, at most 3 cut tries ({run.viol[:2]})",
|
||||||
|
not run.viol)
|
||||||
|
check(f"N8/N9 {tag}: a select only at 0 A ({sel_bad[:1]}), at most one "
|
||||||
|
f"CHARGER_OTHER per hold ({n_other()} for {rises})",
|
||||||
|
not sel_bad and n_other() <= rises)
|
||||||
Reference in New Issue
Block a user