From ca5c401c6faf35d52617c4f5511c153894913202 Mon Sep 17 00:00:00 2001 From: serversdown Date: Tue, 27 Oct 2026 00:02:10 -0400 Subject: [PATCH] fix(device_access): a start's read-back waits out the sensor check, then wakes the MiniMate with retries Second start through SFM, BE9441 2026-10-26 23:54:41: acked 0x69, and Brian saw 'starting, performing sensor check, recording' -- but the read-back's single SESSION_RESET + POLL went out 2.3 s after the ack, inside the ~30 s sensor check, and was never answered or re-sent (504 after 120 s, audit ca7b5b42). Brian: every unit is set to sensor-check before monitoring, ~30 s, then 'Recording...'. - MiniMateProtocol.wake(attempt_s, deadline_s): SESSION_RESET + POLL re-sent every attempt_s until the unit answers, then the POLL data step; a named timeout at the deadline. Reads only. MiniMateClient.wake() wraps it. - The Series-3 change: after a START, the first read waits S3_SENSOR_CHECK_S (30 s) before asking; every read then wakes with retries (every 5 s, up to 60 s). A stop is unchanged -- its read-back was confirmed three times tonight. Tests: a unit deaf for 4 probes is asked a 5th time and answers; a unit that never answers ends in the named timeout after ~6 probes; a start's first read waits the sensor check, a stop's does not; every read is preceded by a wake. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- minimateplus/client.py | 6 ++ minimateplus/protocol.py | 29 ++++++++++ sfm/device_access/s3.py | 30 ++++++++-- tests/device_access_fakes.py | 3 + tests/test_device_access_change.py | 18 +++++- tests/test_minimate_wake.py | 89 ++++++++++++++++++++++++++++++ 6 files changed, 166 insertions(+), 9 deletions(-) create mode 100644 tests/test_minimate_wake.py diff --git a/minimateplus/client.py b/minimateplus/client.py index 2cf70e6..509e944 100644 --- a/minimateplus/client.py +++ b/minimateplus/client.py @@ -1203,6 +1203,12 @@ class MiniMateClient: log.debug("poll: startup handshake") proto.startup() + def wake(self, attempt_s: float = 5.0, deadline_s: float = 60.0) -> None: + """SESSION_RESET + POLL, re-sent until the unit answers (see + MiniMateProtocol.wake) -- for a unit that may be busy, e.g. sensor-checking + right after a start.""" + self._require_proto().wake(attempt_s=attempt_s, deadline_s=deadline_s) + # ── Monitoring ──────────────────────────────────────────────────────────── def get_monitor_status(self) -> MonitorStatus: diff --git a/minimateplus/protocol.py b/minimateplus/protocol.py index 1339099..0d2e43d 100644 --- a/minimateplus/protocol.py +++ b/minimateplus/protocol.py @@ -289,6 +289,35 @@ class MiniMateProtocol: log.debug("read SUB=0x%02X: received %d data bytes", sub, len(data_rsp.data)) return data_rsp.data + def wake(self, attempt_s: float = 5.0, deadline_s: float = 60.0) -> S3Frame: + """SESSION_RESET + POLL, re-sent every `attempt_s` until the unit answers. + + A monitoring unit ignores everything until SESSION_RESET (2026-04-08), and + right after a start it runs its sensor check (~30 s, Brian, 2026-10-26). + BE9441 left a POLL sent 2 s after a start unanswered and never answered + it later, so one try with a long wait is not enough: ask again until the + unit answers or `deadline_s` passes. A read -- nothing but SESSION_RESET + and POLL is sent. Returns the POLL data frame. + """ + deadline = time.monotonic() + deadline_s + while True: + self._parser.reset() + self._send(SESSION_RESET) + self._send(POLL_PROBE) + try: + self._recv_one(expected_sub=_expected_rsp_sub(SUB_POLL), timeout=attempt_s) + break + except TimeoutError: + if time.monotonic() >= deadline: + raise TimeoutError( + f"the unit did not answer a POLL within {deadline_s:.0f} s " + f"(asked every {attempt_s:.0f} s)") from None + self._send(SESSION_RESET) + self._send(POLL_DATA) + rsp = self._recv_one(expected_sub=_expected_rsp_sub(SUB_POLL), timeout=attempt_s) + self._drain_boot_string(drain_ms=300) # a late answer to an earlier try, if any + return rsp + def poll(self) -> S3Frame: """ Send a single POLL (SUB 5B) probe+data cycle and return the data response. diff --git a/sfm/device_access/s3.py b/sfm/device_access/s3.py index e187b71..92d88b2 100644 --- a/sfm/device_access/s3.py +++ b/sfm/device_access/s3.py @@ -43,14 +43,23 @@ def s3_run_state(status: Any) -> str: return S3_RUN_STATES.get(flag, f"unknown(0x{flag:02X})") +# A start makes the unit run its sensor check before "Recording..." -- ~30 s +# (Brian, 2026-10-26), ~40 s on BE11529 (2026-04-08). A start's read-back waits +# this long before asking, then wakes the unit with retries (S3_WAKE_*). +S3_SENSOR_CHECK_S = 30.0 +S3_WAKE_ATTEMPT_S = 5.0 +S3_WAKE_DEADLINE_S = 60.0 + + def _woken_state(client: Any) -> str: - """The run state, read after waking the unit: SESSION_RESET + POLL first. + """The run state, read after waking the unit: SESSION_RESET + POLL first, + re-sent until it answers. A monitoring MiniMate ignores a bare request until it is woken (measured - 2026-04-08). On 2026-10-26 BE9441 acked a start, then let a bare 0x1C go - unanswered for 120 s -- the read-back had relied on the connect's wake, - which a stop's read-back (the unit idle by then) never needed.""" - client.poll() + 2026-04-08). On 2026-10-26 BE9441 acked a start, then left a bare 0x1C, and + later a single SESSION_RESET + POLL, unanswered for 120 s: both went out 2 s + after the start, inside the sensor check, and were never re-sent.""" + client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S) return s3_run_state(client.get_monitor_status()) @@ -209,17 +218,26 @@ class Series3Adapter: "data_len": 0, "expect_ack": f"0x{ack_sub:02X}", "frame": build_bw_write_frame(sub, b"").hex()}]} + settle: list = [] + def send() -> dict: # The client validates the ack SUB; it returns nothing else, so none is claimed. (client.start_monitoring if start else client.stop_monitoring)() + if start: + settle.append(S3_SENSOR_CHECK_S) # the first read waits out the check return {"subs": [f"0x{ack_sub:02X}"]} + def read_state() -> str: + if settle: + sleep(settle.pop()) + return _woken_state(client) + return run_change( serial=serial, series=3, start=start, dry_run=dry_run, even_if_already=even_if_already, audit=audit, address=address, caller=caller, sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s, read_serial=read_serial, - read_state=lambda: _woken_state(client), + read_state=read_state, describe_plan=describe_plan, send=send) return self._run(address, op, timeout=S3_EVENT_TIMEOUT, retry=False) diff --git a/tests/device_access_fakes.py b/tests/device_access_fakes.py index 08fe44c..cf656ae 100644 --- a/tests/device_access_fakes.py +++ b/tests/device_access_fakes.py @@ -105,6 +105,9 @@ class FakeMiniMateClient(_Base): def poll(self) -> None: self._step("poll") + def wake(self, **kw) -> None: + self._step("wake") + def get_monitor_status(self) -> MonitorStatus: self._step("get_monitor_status") state = self.monitor_states.pop(0) if len(self.monitor_states) > 1 else self.monitor_states[0] diff --git a/tests/test_device_access_change.py b/tests/test_device_access_change.py index 2f5c759..d4d4280 100644 --- a/tests/test_device_access_change.py +++ b/tests/test_device_access_change.py @@ -328,7 +328,7 @@ from device_access_fakes import FakeMiniMateClient # no TCP3 = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None) -def access3(fake, audit="default"): +def access3(fake, audit="default", sleep=lambda s: None): seen = [] def factory(a, **kw): @@ -336,7 +336,7 @@ def access3(fake, audit="default"): return fake da = DeviceAccess(s3_client_factory=factory, start_reaper=False, audit=Audit() if audit == "default" else audit, - sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0) + sleep=sleep, verify_timeout_s=6.0, verify_interval_s=2.0) da.factory_calls = seen return da @@ -784,4 +784,16 @@ def test_series3_wakes_the_unit_before_every_state_read(): assert r.outcome == "sent" and r.verified == "ok" after = fake.calls[fake.calls.index("start_monitoring") + 1:] reads = [i for i, c in enumerate(after) if c == "get_monitor_status"] - assert reads and all(after[i - 1] == "poll" for i in reads) + assert reads and all(after[i - 1] == "wake" for i in reads) + + +def test_series3_a_start_waits_out_the_sensor_check_before_its_first_read(): + # Brian (2026-10-26): every unit runs a ~30 s sensor check before + # "Recording..."; a stop's read-back needs no such wait. + from sfm.device_access.s3 import S3_SENSOR_CHECK_S + for start, waited in ((True, True), (False, False)): + slept = [] + fake = FakeMiniMateClient(monitor_states=[not start, start]) + da = access3(fake, sleep=slept.append) + (da.start_monitoring if start else da.stop_monitoring)(TCP3, "BE18193") + assert (S3_SENSOR_CHECK_S in slept) is waited diff --git a/tests/test_minimate_wake.py b/tests/test_minimate_wake.py new file mode 100644 index 0000000..ab30b66 --- /dev/null +++ b/tests/test_minimate_wake.py @@ -0,0 +1,89 @@ +"""Waking a MiniMate that is busy right after a start (BE9441, 2026-10-26). + +A start makes the unit run its sensor check (~30 s, Brian; ~40 s on BE11529, +2026-04-08) before 'Recording...'. Twice tonight a read-back sent 2 s after the +start's ack -- a bare 0x1C, then SESSION_RESET + POLL -- got no answer, and with +nothing re-sent the read waited out 120 s. wake() re-sends SESSION_RESET + POLL +until the unit answers or the deadline passes. +""" +from __future__ import annotations + +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import minimateplus.protocol as mp # noqa: E402 +from minimate_replay import fast_clock # noqa: E402 +from minimateplus.framing import POLL_DATA, POLL_PROBE, SESSION_RESET # noqa: E402 + +# BE9441's own POLL replies, recorded 2026-10-26 (probe ack, then the data reply) +PROBE_ACK = bytes.fromhex("1002001010a400000030000000000000000000000000d403") + + +def _poll_data_reply() -> bytes: + from pathlib import Path + from minimateplus.framing import S3FrameParser + raw = (Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram" + / "unit_replies.bin").read_bytes() + p, start = S3FrameParser(), 0 + for i in range(len(raw)): + for f in p.feed(raw[i:i + 1]): + w = raw[start:i + 1] + if f.sub == 0xA4 and len(f.data) > 20: + return w[w.index(b"\x10\x02"):] + start = i + 1 + raise AssertionError("no POLL data reply in the fixture") + + +class Busy: + """Ignores the first `deaf` POLL probes (a sensor check), then answers.""" + + def __init__(self, deaf: int): + self.deaf, self.sent, self._buf = deaf, [], b"" + self.data_reply = _poll_data_reply() + + def write(self, data): + data = bytes(data) + self.sent.append(data) + if data == POLL_PROBE: + if self.deaf: + self.deaf -= 1 + else: + self._buf += PROBE_ACK + elif data == POLL_DATA: + self._buf += self.data_reply + + def read(self, n): + out, self._buf = self._buf[:n], self._buf[n:] + return out + + +@pytest.fixture(autouse=True) +def _fast(monkeypatch): + fast_clock(monkeypatch) + + +def test_the_probe_ack_is_real(): + from minimateplus.framing import S3FrameParser + f = S3FrameParser().feed(PROBE_ACK) + assert len(f) == 1 and f[0].sub == 0xA4 + + +def test_a_busy_unit_is_asked_again_until_it_answers(): + t = Busy(deaf=4) + mp.MiniMateProtocol(t).wake(attempt_s=5.0, deadline_s=60.0) + probes = [i for i, d in enumerate(t.sent) if d == POLL_PROBE] + assert len(probes) == 5 # 4 ignored, the 5th answered + assert all(t.sent[i - 1] == SESSION_RESET for i in probes) + assert t.sent[-2:] == [SESSION_RESET, POLL_DATA] + + +def test_a_unit_that_never_answers_ends_in_a_named_timeout(): + t = Busy(deaf=10 ** 6) + with pytest.raises(mp.TimeoutError, match="did not answer a POLL"): + mp.MiniMateProtocol(t).wake(attempt_s=5.0, deadline_s=30.0) + assert 5 <= t.sent.count(POLL_PROBE) <= 7 # every ~5 s for 30 s