diff --git a/minimateplus/client.py b/minimateplus/client.py index e5002bf..5f74588 100644 --- a/minimateplus/client.py +++ b/minimateplus/client.py @@ -497,6 +497,8 @@ class MiniMateClient: """ proto = self._require_proto() strict = headers_only or only_key is not None + # Passed only when on, so the legacy walk's 5A call is unchanged. + strict_5a = {"strict": True} if strict else {} log.info("get_events: requesting first event (SUB 1E)") try: @@ -653,7 +655,7 @@ class MiniMateClient: ) a5_frames = proto.read_bulk_waveform_stream( cur_key, stop_after_metadata=False, max_chunks=128, - include_terminator=True, + include_terminator=True, **strict_5a, ) if a5_frames: a5_ok = True @@ -672,7 +674,7 @@ class MiniMateClient: cur_key, stop_after_metadata=True, include_terminator=True, extra_chunks_after_metadata=extra_chunks_after_metadata, - max_chunks=128, + max_chunks=128, **strict_5a, ) if a5_frames: a5_ok = True @@ -684,6 +686,8 @@ class MiniMateClient: ev.project_info.operator if ev.project_info else None, ) except ProtocolError as exc: + if strict: + raise # a one-event download is whole or it is an error log.warning( "get_events: 5A failed for key=%s: %s — metadata unavailable", cur_key.hex(), exc, diff --git a/minimateplus/protocol.py b/minimateplus/protocol.py index 1c0bdea..509f235 100644 --- a/minimateplus/protocol.py +++ b/minimateplus/protocol.py @@ -538,11 +538,19 @@ class MiniMateProtocol: max_chunks: int = 256, # safety cap only; loop is bounded by end_offset include_terminator: bool = False, extra_chunks_after_metadata: int = 1, # DEPRECATED — no-op + strict: bool = False, ) -> list[S3Frame]: """ Download the SUB 5A (BULK_WAVEFORM_STREAM) A5 frames for one event using Blastware's exact protocol. REWRITTEN 2026-05-02 (v0.14.0). + strict: the stream must arrive whole, or this raises ProtocolError -- a + missing STRT, a metadata page or chunk with no reply, a mid-stream + terminator, the chunk cap, or no TERM reply. The one-event download uses + it: a short event must never be stored (BE9441 rebooted mid-download on + 2026-10-25 and its partial event was kept). Without strict the legacy + tolerance stands: an early end proceeds to TERM and returns what arrived. + Algorithm (matches BW captures across 2-sec / 3-sec / event-2): 1. Probe @@ -645,6 +653,10 @@ class MiniMateProtocol: # ── Step 2: parse STRT end_offset from probe response ──────────────── end_offset = parse_strt_end_offset(rsp.data) + if end_offset is None and strict: + raise ProtocolError( + f"5A probe for {key4.hex()} carried no STRT record, so the event's end " + "is unknown -- not downloaded") if end_offset is None: log.warning( "5A probe response did not contain a STRT record; " @@ -683,7 +695,11 @@ class MiniMateProtocol: meta_rsp = self._recv_one( expected_sub=rsp_sub, reset_parser=False, timeout=10.0, ) - except TimeoutError: + except TimeoutError as exc: + if strict: + raise TimeoutError( + f"5A stream ended early: metadata page 0x{meta_counter:04X} got " + "no reply -- the event was not kept") from exc log.warning( "5A metadata page 0x%04X TIMED OUT — continuing", meta_counter, @@ -728,12 +744,17 @@ class MiniMateProtocol: rsp = self._recv_one( expected_sub=rsp_sub, reset_parser=False, timeout=10.0, ) - except TimeoutError: + except TimeoutError as exc: raw = self._parser.bytes_fed log.warning( "5A TIMEOUT chunk=%d counter=0x%04X raw_bytes=%d", chunks_fetched + 1, counter, raw, ) + if strict: + raise TimeoutError( + f"5A stream ended early: no reply for the chunk at 0x{counter:04X}; the " + f"event ends at 0x{end_offset:04X} ({chunks_fetched} chunk(s) received) " + "-- the event was not kept") from exc if raw > 0 and frames_data: log.warning( "5A unexpected end-of-stream — proceeding to TERM", @@ -748,6 +769,10 @@ class MiniMateProtocol: if rsp.page_key == 0x0000: # Device terminated mid-stream unexpectedly. + if strict: + raise ProtocolError( + f"5A stream ended early: the unit sent its terminator at 0x{counter:04X}, " + f"before the event's end 0x{end_offset:04X} -- the event was not kept") log.warning( "5A unexpected page_key=0x0000 mid-stream at counter=0x%04X", counter, @@ -761,6 +786,10 @@ class MiniMateProtocol: counter += _BULK_COUNTER_STEP chunks_fetched += 1 else: + if strict: + raise ProtocolError( + f"5A reached the {max_chunks}-chunk cap at 0x{counter:04X} before the " + f"event's end 0x{end_offset:04X} -- the event was not kept") log.warning( "5A reached max_chunks=%d at counter=0x%04X (end=0x%04X)", max_chunks, counter, end_offset, @@ -796,7 +825,11 @@ class MiniMateProtocol: ) if include_terminator: frames_data.append(term_rsp) - except TimeoutError: + except TimeoutError as exc: + if strict: + raise TimeoutError( + "5A stream ended early: no reply to the TERM request, which carries the " + "event's tail and footer -- the event was not kept") from exc log.warning("5A no TERM response (timeout)") return frames_data diff --git a/tests/test_minimate_5a_strict.py b/tests/test_minimate_5a_strict.py new file mode 100644 index 0000000..7d085d1 --- /dev/null +++ b/tests/test_minimate_5a_strict.py @@ -0,0 +1,97 @@ +"""A one-event download must not keep an event whose 5A stream ended early. + +BE9441 rebooted mid-download at the bench (2026-10-25): the chunk at 0x7D06 got +no reply, the loop logged "unexpected end-of-stream -- proceeding to TERM", the +TERM got no reply either, and the short event was stored as a success. In +strict mode (the one-event download) every early end now raises; the legacy +full walk keeps its tolerance. Driven by BE9441's recorded replies for event 1. +""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import minimateplus.protocol as mp # noqa: E402 +from minimateplus.framing import S3FrameParser # noqa: E402 + +FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-25-26" / "BE9441_event1_0111646a_rx.bin" +KEY = bytes.fromhex("0111646a") + + +def a5_replies() -> list: + """The raw bytes of each A5 reply, in order (the parser fed one byte at a time).""" + raw, out, start, p = FIX.read_bytes(), [], 0, S3FrameParser() + for i in range(len(raw)): + for f in p.feed(raw[i:i + 1]): + if f.sub == 0xA5: + out.append(raw[start:i + 1]) + start = i + 1 + return out + + +class Replay: + """One recorded reply per 5A request; from request number `silent_from` on, one + stray 0x41 and then silence -- what BE9441 sent as it rebooted.""" + + def __init__(self, replies, silent_from=None): + self.replies, self.silent_from, self.sent, self._buf = list(replies), silent_from, 0, b"" + + def write(self, data): + n, self.sent = self.sent, self.sent + 1 + if self.silent_from is None or n < self.silent_from: + self._buf += self.replies[n] + elif n == self.silent_from: + self._buf += b"\x41" + + def read(self, n): + out, self._buf = self._buf[:n], self._buf[n:] + return out + + +@pytest.fixture(autouse=True) +def fast_clock(monkeypatch): + t = [0.0] + + def tick(): + t[0] += 0.5 + return t[0] + monkeypatch.setattr(mp.time, "monotonic", tick) + monkeypatch.setattr(mp.time, "sleep", lambda s: None) + + +def proto(silent_from=None): + replies = a5_replies() + p = mp.MiniMateProtocol(Replay(replies, silent_from)) + return p, len(replies) + + +def test_the_recorded_stream_replays_whole(): + p, n = proto() + frames = p.read_bulk_waveform_stream(KEY, stop_after_metadata=False, include_terminator=True, + strict=True) + assert len(frames) == n == 51 + + +def test_strict_raises_when_a_chunk_gets_no_reply(): + p, _ = proto(silent_from=40) + with pytest.raises(mp.ProtocolError, match="ended early"): + p.read_bulk_waveform_stream(KEY, stop_after_metadata=False, include_terminator=True, + strict=True) + + +def test_strict_raises_when_the_term_gets_no_reply(): + p, n = proto(silent_from=50) # every chunk answered, the TERM not + with pytest.raises(mp.ProtocolError, match="TERM"): + p.read_bulk_waveform_stream(KEY, stop_after_metadata=False, include_terminator=True, + strict=True) + + +def test_the_legacy_walk_keeps_its_tolerance(): + p, _ = proto(silent_from=40) + frames = p.read_bulk_waveform_stream(KEY, stop_after_metadata=False, include_terminator=True) + assert 0 < len(frames) < 51 # short, returned, not raised -- as before diff --git a/tests/test_minimate_download_replay.py b/tests/test_minimate_download_replay.py new file mode 100644 index 0000000..702d619 --- /dev/null +++ b/tests/test_minimate_download_replay.py @@ -0,0 +1,108 @@ +"""BE9441's recorded one-event download, replayed through the real MiniMateClient. + +The bench session (2026-10-25) is replayed reply for reply: SESSION_RESET gets +none, every other request the next recorded frame. Whole, it must give event 1 +in full (the metadata-page fix); silenced partway through the 5A stream, as the +unit was when it rebooted, it must raise (the strict-stream fix), never return +a short event. +""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import minimateplus.client as mc # noqa: E402 +import minimateplus.protocol as mp # noqa: E402 +from minimateplus.framing import S3FrameParser # noqa: E402 + +FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-25-26" / "BE9441_event1_0111646a_rx.bin" +KEY = bytes.fromhex("0111646a") +STAMP = "2026-10-25T14:10:49" +SESSION_RESET = b"\x41\x03" + + +def recorded_replies(): + """[(sub, raw_bytes)] for every frame of the session, in order.""" + raw, out, start, p = FIX.read_bytes(), [], 0, S3FrameParser() + for i in range(len(raw)): + for f in p.feed(raw[i:i + 1]): + out.append((f.sub, raw[start:i + 1])) + start = i + 1 + return out + + +class SessionReplay: + """Answers each request with the next recorded reply of its own SUB (reply = + 0xFF - request). `quiet_5a_from`: from that 5A request on, the 5A stream gets + one stray 0x41 and then nothing, while every other request is still answered + -- BE9441 dropped out of the stream as it rebooted, then answered the walk.""" + + def __init__(self, replies, quiet_5a_from=None): + self.queues = {} + for sub, raw in replies: + self.queues.setdefault(sub, []).append(raw) + self.quiet_5a_from, self.n5a, self._buf, self.open_ = quiet_5a_from, 0, b"", False + + def connect(self): + self.open_ = True + + def disconnect(self): + self.open_ = False + + def is_connected(self): + return self.open_ + + def write(self, data): + data = bytes(data) + if data == SESSION_RESET: + return + req = data[5] # 41 02 10 10 00 + if req == 0x5A: + n, self.n5a = self.n5a, self.n5a + 1 + if self.quiet_5a_from is not None and n >= self.quiet_5a_from: + if n == self.quiet_5a_from: + self._buf += b"\x41" + return + self._buf += self.queues[0xFF - req].pop(0) + + def read(self, n): + out, self._buf = self._buf[:n], self._buf[n:] + return out + + def read_until_idle(self, *a, **kw): + out, self._buf = self._buf, b"" + return out + + +@pytest.fixture(autouse=True) +def fast_clock(monkeypatch): + t = [0.0] + + def tick(): + t[0] += 0.5 + return t[0] + monkeypatch.setattr(mp.time, "monotonic", tick) + monkeypatch.setattr(mp.time, "sleep", lambda s: None) + + +def download(quiet_5a_from=None): + client = mc.MiniMateClient(transport=SessionReplay(recorded_replies(), quiet_5a_from)) + client.open() + client.connect() + return client.download_event_by_key(KEY, expected_timestamp=STAMP) + + +def test_the_whole_session_gives_event_1_in_full(): + ev = download() + assert {ch: len(ev.raw_samples[ch]) for ch in ("Tran", "Vert", "Long")} == \ + {"Tran": 21_504, "Vert": 21_504, "Long": 21_504} + + +def test_a_unit_that_goes_quiet_mid_stream_raises_instead_of_returning_a_short_event(): + with pytest.raises(mp.ProtocolError, match="ended early"): + download(quiet_5a_from=40)