fix(minimateplus): MiniMate requests escape 02/03/04/10, and the 5A walk is 32-bit linear -- the 64 KB page bug
A recording of Blastware downloading all 8 of BE9441's events (three crossing a 64 KB page; tests/fixtures/minimate-bench-10-26-26-blastware/) settles it: every one of its 748 requests is the standard 16-byte payload with a SUM8 checksum and every 02 / 03 / 04 / 10 byte DLE-escaped -- 748/748 re-encode byte-identically. A 5A request is not a special frame: it is that payload with a 2-byte LENGTH (0x0200 per chunk, the remainder for TERM) and a 4-byte linear ADDRESS. The walk is the event's start, +0x200 at a time carrying into the page byte, then TERM at the next boundary for exactly the remainder. What the old model misread: the fixed 'offset 0x1002' is length 0x0200 escaped (10 02 00); the first event's 'metadata pages at 0x1002/0x1004' are its chunks at 0x0200 and 0x0400; the 16-bit counter could not leave the key's page. - build_bw_frame escapes the four values (was 0x10 only); new s3_stuff(). - build_5a_request(address, length); parse_strt_end_key() -> the full 32 bits. - read_bulk_waveform_stream: one linear walk, no event-1 special case; strict mode keeps every refusal; an end at or before the start is refused as a corrupt STRT (a page crossing is no longer refused -- it downloads). Tests: all 540 Blastware 5A requests and all 208 others rebuilt byte for byte; SFM's walks for events 0, 1, 3 and 7 send exactly Blastware's requests and, fed Blastware's recorded replies, build whole events. In-page requests are byte-identical to before. No codec, store or DB change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
465bc704dd
commit
887e75d1ba
7 files changed
+339
-196
No files matched your search
+67
-2
@@ -28,6 +28,10 @@ De-stuffed payload layout:
|
||||
|
||||
DLE stuffing rule: any 0x10 byte in the payload is doubled on the wire (0x10 → 0x10 0x10).
|
||||
This applies to the checksum byte too.
|
||||
⚠ AMENDED 2026-10-26 (measured): a request escapes FOUR values, not one -- every 02, 03,
|
||||
04 and 10 in payload and checksum gets a DLE in front. Blastware's 748 recorded requests
|
||||
re-encode byte-identically under that rule (tests/test_5a_blastware_walk.py); a bare 02 or
|
||||
03 left a request unanswered. See `s3_stuff()`.
|
||||
|
||||
Confirmed from live captures (s3_parser.py validation + raw_bw.bin / raw_s3.bin).
|
||||
"""
|
||||
@@ -83,6 +87,24 @@ def dle_unstuff(data: bytes) -> bytes:
|
||||
|
||||
# ── Checksum ─────────────────────────────────────────────────────────────────
|
||||
|
||||
# Every byte value a request DLE-escapes (2026-10-26, measured): Blastware's 748
|
||||
# requests from a whole download session re-encode byte-identically with this set,
|
||||
# payload and checksum alike. A bare 0x02 checksum or a 0x03 inside the params left
|
||||
# BE9441 silent (and the 0x02 made it reset ~11 s later). It is a Micromate's set
|
||||
# too (micromate.framing._ESCAPED).
|
||||
_ESCAPED = frozenset({STX, ETX, 0x04, DLE})
|
||||
|
||||
|
||||
def s3_stuff(data: bytes) -> bytes:
|
||||
"""Escape every byte a request escapes: `XX` → `10 XX` for 02, 03, 04 and 10."""
|
||||
out = bytearray()
|
||||
for b in data:
|
||||
if b in _ESCAPED:
|
||||
out.append(DLE)
|
||||
out.append(b)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def checksum(payload: bytes) -> int:
|
||||
"""SUM8: sum of all de-stuffed payload bytes, mod 256."""
|
||||
return sum(payload) & 0xFF
|
||||
@@ -95,6 +117,30 @@ def checksum(payload: bytes) -> int:
|
||||
SUB_5A = 0x5A
|
||||
|
||||
|
||||
_BULK_CHUNK = 0x0200 # bytes per 5A read; a TERM reads the remainder
|
||||
|
||||
|
||||
def build_5a_request(address: int, length: int) -> bytes:
|
||||
"""A SUB 5A read of `length` bytes at the unit's 32-bit `address`.
|
||||
|
||||
Measured 2026-10-26 from Blastware downloading all 8 of BE9441's events (three
|
||||
crossing a 64 KB page): a 5A request is an ORDINARY 16-byte request --
|
||||
`[10 00 5A 00][length BE][address BE 4][zeros 6]`, SUM8 checksum, every
|
||||
02/03/04/10 escaped -- and this rebuilds all 540 of Blastware's 5A requests
|
||||
byte for byte. The older model below (`build_5a_frame`: a raw "offset_hi
|
||||
0x10", an "11-byte params", "metadata pages at 0x1002 / 0x1004") was the
|
||||
same bytes misread: `10 02 00` is the length 0x0200 escaped, and the
|
||||
"metadata pages" are the first event's chunks at 0x0200 and 0x0400.
|
||||
"""
|
||||
if not 0 <= address <= 0xFFFFFFFF:
|
||||
raise ValueError(f"address must fit in 32 bits, got {address:#x}")
|
||||
if not 0 <= length <= 0xFFFF:
|
||||
raise ValueError(f"length must fit in 16 bits, got {length:#x}")
|
||||
payload = (bytes([BW_CMD, 0x00, SUB_5A, 0x00, (length >> 8) & 0xFF, length & 0xFF])
|
||||
+ address.to_bytes(4, "big") + bytes(6))
|
||||
return bytes([ACK, STX]) + s3_stuff(payload + bytes([checksum(payload)])) + bytes([ETX])
|
||||
|
||||
|
||||
def build_5a_frame(offset_word: int, raw_params: bytes) -> bytes:
|
||||
"""
|
||||
Build a BW→S3 frame for SUB 5A (BULK_WAVEFORM_STREAM) that exactly
|
||||
@@ -210,7 +256,7 @@ def build_bw_frame(sub: int, offset: int = 0, params: bytes = bytes(10)) -> byte
|
||||
byte lives at params[6] (= payload[12]). Use waveform_key_params() and
|
||||
token_params() helpers to build these safely.
|
||||
|
||||
Wire output: [ACK] [STX] dle_stuff(payload + checksum) [ETX]
|
||||
Wire output: [ACK] [STX] s3_stuff(payload + checksum) [ETX]
|
||||
|
||||
Args:
|
||||
sub: SUB command byte (e.g. 0x01 = FULL_CONFIG_READ)
|
||||
@@ -233,7 +279,7 @@ def build_bw_frame(sub: int, offset: int = 0, params: bytes = bytes(10)) -> byte
|
||||
offset_lo = offset & 0xFF
|
||||
payload = bytes([BW_CMD, 0x00, sub, 0x00, offset_hi, offset_lo]) + params
|
||||
chk = checksum(payload)
|
||||
wire = bytes([ACK, STX]) + dle_stuff(payload + bytes([chk])) + bytes([ETX])
|
||||
wire = bytes([ACK, STX]) + s3_stuff(payload + bytes([chk])) + bytes([ETX])
|
||||
return wire
|
||||
|
||||
|
||||
@@ -548,6 +594,25 @@ def bulk_waveform_term_v2(
|
||||
STRT_MARKER = b"STRT"
|
||||
|
||||
|
||||
def parse_strt_end_key(a5_data: bytes) -> Optional[int]:
|
||||
"""The event's FULL 32-bit end key from the STRT record in an A5 reply's
|
||||
data, or None. The page byte is part of it: an event that ends in the next
|
||||
64 KB page reads e.g. 0x011216C4 here, where `parse_strt_end_offset` gave
|
||||
0x16C4. Read after removing the reply's inner DLE pairs (10 02 / 10 03 /
|
||||
10 04 → 02 / 03 / 04), which the parser keeps as two bytes."""
|
||||
out, i = bytearray(), 0
|
||||
while i < len(a5_data):
|
||||
if a5_data[i] == DLE and i + 1 < len(a5_data) and a5_data[i + 1] in (STX, ETX, 0x04):
|
||||
i += 1
|
||||
continue
|
||||
out.append(a5_data[i])
|
||||
i += 1
|
||||
pos = bytes(out).find(STRT_MARKER)
|
||||
if pos < 0 or pos + 10 > len(out):
|
||||
return None
|
||||
return int.from_bytes(out[pos + 6:pos + 10], "big")
|
||||
|
||||
|
||||
def parse_strt_end_offset(a5_data: bytes) -> Optional[int]:
|
||||
"""
|
||||
Extract the event-end offset from the STRT record in an A5 response payload.
|
||||
|
||||
+78
-185
@@ -37,6 +37,8 @@ from .framing import (
|
||||
bulk_waveform_term_params,
|
||||
bulk_waveform_term_v2,
|
||||
parse_strt_end_offset,
|
||||
parse_strt_end_key,
|
||||
build_5a_request,
|
||||
POLL_PROBE,
|
||||
POLL_DATA,
|
||||
SESSION_RESET,
|
||||
@@ -558,48 +560,34 @@ class MiniMateProtocol:
|
||||
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):
|
||||
The walk (measured 2026-10-26: Blastware downloading all 8 of BE9441's
|
||||
events, three crossing a 64 KB page -- tests/test_5a_blastware_walk.py
|
||||
rebuilds its requests byte for byte):
|
||||
|
||||
1. Probe
|
||||
- For events at start_key[2:4] = 0x0000 (first event after erase
|
||||
/ wrap): probe at counter=0x0000 with full key in params.
|
||||
- For continuation events (start_key[2:4] != 0): first chunk at
|
||||
counter = start_key[2:4] + 0x0046; acts as both probe and
|
||||
first sample chunk; response carries STRT.
|
||||
1. Read 0x200 bytes at the event's own 32-bit address (the key). The
|
||||
reply carries STRT, whose end key is the full 32-bit address where
|
||||
the event ends.
|
||||
2. Read 0x200 bytes at each next address, +0x200 at a time, as plain
|
||||
32-bit numbers -- crossing into the next 64 KB page needs nothing
|
||||
special -- while the whole chunk fits before the end.
|
||||
3. TERM: read the remainder (end - next boundary) at the next boundary.
|
||||
Its reply carries the event's tail and the file footer.
|
||||
|
||||
2. Parse end_offset from STRT record at data[23:27] of the probe response.
|
||||
|
||||
3. Read two fixed metadata pages at counter=0x1002 and counter=0x1004
|
||||
— global session metadata (Project / Client / User Name / Seis Loc
|
||||
/ Extended Notes ASCII strings). Event 1 only; continuation
|
||||
events skip these (BW caches them across the session).
|
||||
|
||||
4. Walk sample chunks at 0x0200 increments, starting from 0x0600 for
|
||||
event 1 or `start + 0x0046 + 0x0200` for continuation events.
|
||||
Stop when `next_chunk + 0x0200 > end_offset`.
|
||||
|
||||
5. Send TERM frame with offset_word and params computed by
|
||||
`bulk_waveform_term_v2(key4, end_offset, last_chunk_counter)`.
|
||||
The TERM response contains the partial last chunk (residual =
|
||||
end_offset - next_boundary) including the 26-byte 0e 08 file
|
||||
footer.
|
||||
The first event on a unit reads 0x0000, 0x0200, 0x0400, 0x0600, ...: the
|
||||
"metadata pages at 0x1002 / 0x1004" of the earlier model were its chunks
|
||||
at 0x0200 and 0x0400, escaped (`10 02 00`, `10 04 00`). That model's
|
||||
16-bit counter could not leave the key's page -- the 64 KB page bug.
|
||||
|
||||
Returns:
|
||||
List of S3Frame objects from each A5 response (probe, metadata
|
||||
pages, sample chunks, optional TERM response). Caller passes
|
||||
`include_terminator=True` (e.g. write_blastware_file) to keep the
|
||||
TERM response in the list — it's required to reconstruct the
|
||||
file footer.
|
||||
The A5 frames in order (first chunk, chunks, and with
|
||||
`include_terminator=True` the TERM reply, which write_blastware_file
|
||||
needs for the footer).
|
||||
|
||||
Deprecated kwargs:
|
||||
stop_after_metadata: legacy "Project:"-string-based stop condition.
|
||||
No-op under the BW-exact walk; the loop is
|
||||
deterministically bounded by end_offset from
|
||||
STRT. Accepted for backward compat.
|
||||
extra_chunks_after_metadata: same.
|
||||
Deprecated kwargs (no-ops): stop_after_metadata, extra_chunks_after_metadata.
|
||||
|
||||
Raises:
|
||||
ProtocolError: on timeout / bad checksum / unexpected SUB.
|
||||
ProtocolError: on timeout / bad checksum / unexpected SUB, and in
|
||||
strict mode on any early end.
|
||||
"""
|
||||
if len(key4) != 4:
|
||||
raise ValueError(f"waveform key must be 4 bytes, got {len(key4)}")
|
||||
@@ -613,38 +601,15 @@ class MiniMateProtocol:
|
||||
|
||||
rsp_sub = _expected_rsp_sub(SUB_BULK_WAVEFORM) # 0xA5
|
||||
frames_data: list[S3Frame] = []
|
||||
start = int.from_bytes(key4, "big")
|
||||
|
||||
start_offset = (key4[2] << 8) | key4[3]
|
||||
is_event_1 = (start_offset == 0)
|
||||
def request(address: int, length: int) -> None:
|
||||
self._send(build_5a_request(address, length))
|
||||
self._parser.reset()
|
||||
|
||||
# ── Step 1: probe / first chunk ──────────────────────────────────────
|
||||
if is_event_1:
|
||||
probe_counter = 0
|
||||
probe_params = bulk_waveform_params(key4, 0, is_probe=True)
|
||||
log.debug("5A probe (event-1) key=%s counter=0x0000", key4.hex())
|
||||
else:
|
||||
# Continuation events: first 5A request lands at counter = key[2:4]
|
||||
# (i.e. the address of the off=0x46 WAVEHDR record returned by 1F).
|
||||
# The probe response carries STRT at byte 17 with end_offset.
|
||||
#
|
||||
# Confirmed 2026-05-04 from 5-1-26 "copy 2nd address" capture
|
||||
# (BW probes counter=0x2238 with key=01112238, STRT@17 end=0x417E)
|
||||
# and 5-4-26 BW captures (2-sec event probes counter=0x2238).
|
||||
#
|
||||
# The earlier "+0x46" formula in the doc came from calling
|
||||
# start_key the BOUNDARY (off=0x2C) key, but the iteration walk
|
||||
# uses 1F's off=0x46 key as cur_key, which already incorporates
|
||||
# the +0x46 offset relative to the boundary. Adding it again
|
||||
# caused the probe to overshoot, miss STRT, and run uncapped.
|
||||
probe_counter = start_offset
|
||||
probe_params = bulk_waveform_params(key4, probe_counter)
|
||||
log.debug(
|
||||
"5A probe (event-N) key=%s counter=0x%04X",
|
||||
key4.hex(), probe_counter,
|
||||
)
|
||||
|
||||
self._send(build_5a_frame(_BULK_CHUNK_OFFSET, probe_params))
|
||||
self._parser.reset()
|
||||
# ── Step 1: the event's first chunk; its reply carries STRT ──────────
|
||||
log.debug("5A first chunk key=%s", key4.hex())
|
||||
request(start, _BULK_COUNTER_STEP)
|
||||
try:
|
||||
rsp = self._recv_one(expected_sub=rsp_sub, reset_parser=False)
|
||||
except TimeoutError:
|
||||
@@ -653,110 +618,49 @@ class MiniMateProtocol:
|
||||
key4.hex(), self._parser.bytes_fed,
|
||||
)
|
||||
raise
|
||||
|
||||
frames_data.append(rsp)
|
||||
log.debug("5A A5[0] (probe) page_key=0x%04X %d bytes",
|
||||
rsp.page_key, len(rsp.data))
|
||||
log.debug("5A A5[0] (probe) page_key=0x%04X %d bytes", rsp.page_key, len(rsp.data))
|
||||
|
||||
# ── Step 2: parse STRT end_offset from probe response ────────────────
|
||||
end_offset = parse_strt_end_offset(rsp.data)
|
||||
if end_offset is None and strict:
|
||||
# ── Step 2: where the event ends -- STRT's full 32-bit end key ───────
|
||||
end = parse_strt_end_key(rsp.data)
|
||||
if end 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 strict and end_offset is not None and end_offset < start_offset:
|
||||
# The known 5A page bug: parse_strt_end_offset keeps only the low 16
|
||||
# bits, so an event that ends in the next 64 KB page reads as ending
|
||||
# before it starts, and the walk cannot follow it yet. BE9441's
|
||||
# events 2 and 19 (bench 2026-10-26) -- named here, before any chunk.
|
||||
raise ProtocolError(
|
||||
f"event {key4.hex()} crosses the unit's 64 KB page boundary (starts at "
|
||||
f"0x{start_offset:04X} in page 0x{key4[1]:02X}, ends at 0x{end_offset:04X} in "
|
||||
"the next) -- SFM cannot download such an event yet (the known 5A page bug); "
|
||||
"not saved")
|
||||
if end_offset is None:
|
||||
if end is not None and end <= start:
|
||||
if strict:
|
||||
raise ProtocolError(
|
||||
f"5A STRT for {key4.hex()} says the event ends at 0x{end:08X}, at or "
|
||||
"before its start -- not downloaded")
|
||||
log.warning("5A STRT end 0x%08X is not after the start 0x%08X -- ignored", end, start)
|
||||
end = None
|
||||
have_end = end is not None
|
||||
if not have_end:
|
||||
log.warning(
|
||||
"5A probe response did not contain a STRT record; "
|
||||
"5A probe response did not contain a usable STRT record; "
|
||||
"cannot bound chunk loop — falling back to max_chunks=%d cap",
|
||||
max_chunks,
|
||||
)
|
||||
end_offset = 0xFFFF # impossible value → loop runs to max_chunks
|
||||
end = start + (max_chunks + 2) * _BULK_COUNTER_STEP # the cap bounds the loop
|
||||
else:
|
||||
log.info(
|
||||
"5A STRT start_offset=0x%04X end_offset=0x%04X size=0x%04X",
|
||||
start_offset, end_offset, end_offset - start_offset,
|
||||
)
|
||||
log.info("5A STRT start=0x%08X end=0x%08X size=0x%X", start, end, end - start)
|
||||
|
||||
# ── Step 3: metadata pages 0x1002 + 0x1004 (event 1 only) ────────────
|
||||
# Confirmed from BW captures: BW reads these two fixed device-buffer
|
||||
# pages immediately after the probe for events at start_key[2:4]=0.
|
||||
# Continuation events skip them (BW caches across the session).
|
||||
# Their content is global compliance-setup metadata: Project, Client,
|
||||
# User Name, Seis Loc, Extended Notes.
|
||||
if is_event_1:
|
||||
for meta_counter in (0x1002, 0x1004):
|
||||
# Metadata page params have an extra trailing 0x00 byte
|
||||
# (12-byte params instead of 11) — empirical from BW captures.
|
||||
# Checksum-neutral but matches BW byte-for-byte.
|
||||
meta_params = bytes([
|
||||
0x00,
|
||||
key4[0], key4[1],
|
||||
(meta_counter >> 8) & 0xFF,
|
||||
meta_counter & 0xFF,
|
||||
0, 0, 0, 0, 0, 0, 0,
|
||||
])
|
||||
log.debug("5A metadata page counter=0x%04X", meta_counter)
|
||||
self._send(build_5a_frame(_BULK_CHUNK_OFFSET, meta_params))
|
||||
self._parser.reset()
|
||||
try:
|
||||
meta_rsp = self._recv_one(
|
||||
expected_sub=rsp_sub, reset_parser=False, timeout=10.0,
|
||||
)
|
||||
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,
|
||||
)
|
||||
continue
|
||||
frames_data.append(meta_rsp)
|
||||
log.debug(
|
||||
"5A meta@0x%04X page_key=0x%04X %d bytes",
|
||||
meta_counter, meta_rsp.page_key, len(meta_rsp.data),
|
||||
)
|
||||
|
||||
# ── Step 4: sample chunk loop, bounded by end_offset ─────────────────
|
||||
# Sample chunks start at:
|
||||
# event 1: counter = 0x0600
|
||||
# event N (>0): counter = probe_counter + 0x0200
|
||||
# (probe was the first sample chunk)
|
||||
if is_event_1:
|
||||
counter = 0x0600
|
||||
else:
|
||||
counter = probe_counter + _BULK_COUNTER_STEP
|
||||
|
||||
last_chunk_counter: Optional[int] = (
|
||||
probe_counter if not is_event_1 else None
|
||||
)
|
||||
# ── Step 3: chunks at +0x200, plain 32-bit addresses ─────────────────
|
||||
address = start + _BULK_COUNTER_STEP
|
||||
last = start
|
||||
chunks_fetched = 0
|
||||
|
||||
while chunks_fetched < max_chunks:
|
||||
# Stop when next chunk would straddle the event end.
|
||||
if counter + _BULK_COUNTER_STEP > end_offset:
|
||||
# Stop when the next chunk would straddle the event end.
|
||||
if address + _BULK_COUNTER_STEP > end:
|
||||
log.debug(
|
||||
"5A chunk loop done at counter=0x%04X (end=0x%04X); "
|
||||
"%d chunks fetched",
|
||||
counter, end_offset, chunks_fetched,
|
||||
"5A chunk loop done at 0x%08X (end=0x%08X); %d chunks fetched",
|
||||
address, end, chunks_fetched,
|
||||
)
|
||||
break
|
||||
|
||||
params = bulk_waveform_params(key4, counter)
|
||||
log.debug("5A chunk #%d counter=0x%04X", chunks_fetched + 1, counter)
|
||||
self._send(build_5a_frame(_BULK_CHUNK_OFFSET, params))
|
||||
self._parser.reset()
|
||||
log.debug("5A chunk #%d address=0x%08X", chunks_fetched + 1, address)
|
||||
request(address, _BULK_COUNTER_STEP)
|
||||
try:
|
||||
rsp = self._recv_one(
|
||||
expected_sub=rsp_sub, reset_parser=False, timeout=10.0,
|
||||
@@ -764,13 +668,13 @@ class MiniMateProtocol:
|
||||
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,
|
||||
"5A TIMEOUT chunk=%d address=0x%08X raw_bytes=%d",
|
||||
chunks_fetched + 1, address, 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) "
|
||||
f"5A stream ended early: no reply for the chunk at 0x{address:08X}; the "
|
||||
f"event ends at 0x{end:08X} ({chunks_fetched} chunk(s) received) "
|
||||
"-- the event was not kept") from exc
|
||||
if raw > 0 and frames_data:
|
||||
log.warning(
|
||||
@@ -788,52 +692,41 @@ class MiniMateProtocol:
|
||||
# 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")
|
||||
f"5A stream ended early: the unit sent its terminator at 0x{address:08X}, "
|
||||
f"before the event's end 0x{end:08X} -- the event was not kept")
|
||||
log.warning(
|
||||
"5A unexpected page_key=0x0000 mid-stream at counter=0x%04X",
|
||||
counter,
|
||||
"5A unexpected page_key=0x0000 mid-stream at address=0x%08X",
|
||||
address,
|
||||
)
|
||||
if include_terminator:
|
||||
frames_data.append(rsp)
|
||||
return frames_data
|
||||
|
||||
frames_data.append(rsp)
|
||||
last_chunk_counter = counter
|
||||
counter += _BULK_COUNTER_STEP
|
||||
last = address
|
||||
address += _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")
|
||||
f"5A reached the {max_chunks}-chunk cap at 0x{address:08X} before the "
|
||||
f"event's end 0x{end:08X} -- the event was not kept")
|
||||
log.warning(
|
||||
"5A reached max_chunks=%d at counter=0x%04X (end=0x%04X)",
|
||||
max_chunks, counter, end_offset,
|
||||
"5A reached max_chunks=%d at address=0x%08X (end=0x%08X)",
|
||||
max_chunks, address, end,
|
||||
)
|
||||
|
||||
# ── Step 5: TERM with proper end_offset-derived formula ──────────────
|
||||
if last_chunk_counter is None or end_offset == 0xFFFF:
|
||||
# No STRT or no chunks fetched — fall back to legacy TERM.
|
||||
log.warning(
|
||||
"5A using legacy TERM (offset_word=0x005A); "
|
||||
"end_offset unavailable or no chunks fetched",
|
||||
)
|
||||
legacy_counter = (last_chunk_counter or probe_counter) + _BULK_COUNTER_STEP
|
||||
term_offset_word = _BULK_TERM_OFFSET # 0x005A
|
||||
term_params = bulk_waveform_term_params(key4, legacy_counter)
|
||||
# ── Step 4: TERM -- the remainder, from the next boundary ───────────
|
||||
boundary = last + _BULK_COUNTER_STEP
|
||||
if have_end:
|
||||
term_length = end - boundary
|
||||
log.debug("5A TERM address=0x%08X length=0x%04X end=0x%08X",
|
||||
boundary, term_length, end)
|
||||
else:
|
||||
term_offset_word, term_params = bulk_waveform_term_v2(
|
||||
key4, end_offset, last_chunk_counter,
|
||||
)
|
||||
log.debug(
|
||||
"5A TERM offset_word=0x%04X params[2:4]=%s end=0x%04X "
|
||||
"last_chunk=0x%04X",
|
||||
term_offset_word, term_params[2:4].hex(),
|
||||
end_offset, last_chunk_counter,
|
||||
)
|
||||
term_length = _BULK_TERM_OFFSET # legacy: no STRT, so no remainder known
|
||||
log.warning("5A using legacy TERM (length 0x%04X); end unknown", term_length)
|
||||
|
||||
self._send(build_5a_frame(term_offset_word, term_params))
|
||||
self._send(build_5a_request(boundary, term_length))
|
||||
try:
|
||||
term_rsp = self._recv_one(expected_sub=rsp_sub, timeout=10.0)
|
||||
log.info(
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Blastware downloading all 8 events from BE9441, recorded (2026-10-26)
|
||||
|
||||
BE9441 (S338.17, single shot, 4096 sps) on the dev box's serial port, shared on TCP by
|
||||
`bridges/mm_link.py`; Blastware connected over TCP, listed the events and copied all 8
|
||||
to disk. Both directions, raw:
|
||||
|
||||
| file | direction | size |
|
||||
|---|---|---|
|
||||
| `blastware_requests.bin` | Blastware → unit (748 requests, each after a `41 03` SESSION_RESET) | 17,757 B |
|
||||
| `unit_replies.bin` | unit → Blastware | 364,972 B |
|
||||
|
||||
Events (key → end), from Blastware's 5A walks. Three cross a 64 KB page:
|
||||
|
||||
| event | start key | end (STRT) | 5A requests |
|
||||
|---|---|---|---|
|
||||
| 0 | 01110000 | 01118a2c | 70 |
|
||||
| 1 | 01118a2c | 011216c4 | 71 (crosses into page 0x12) |
|
||||
| 2 | 011216c4 | 0112a0b6 | 69 |
|
||||
| 3 | 0112a0b6 | 011329d2 | 69 (crosses into 0x13) |
|
||||
| 4 | 011329d2 | 0113b072 | 68 |
|
||||
| 5 | 0113b072 | 01143046 | 64 (crosses into 0x14) |
|
||||
| 6 | 01143046 | 0114b0b2 | 65 |
|
||||
| 7 | 0114b0b2 | 01152f0e | 64 (crosses into 0x15) |
|
||||
|
||||
What it settled (measured): every request is the standard 16-byte payload, SUM8 checksum,
|
||||
and every 02 / 03 / 04 / 10 byte DLE-escaped (748/748 re-encode byte-identically). The 5A
|
||||
"offset" is a length (0x0200 per chunk, the remainder for TERM), followed by a 4-byte linear
|
||||
address; a walk is start, start+0x200, ... carrying into the page byte, then TERM at the next
|
||||
boundary for exactly the remainder. The first event's "metadata pages at 0x1002/0x1004" are
|
||||
its chunks at 0x0200 and 0x0400, escaped (`10 02 00`, `10 04 00`).
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,154 @@
|
||||
"""SFM's MiniMate requests and 5A walk, against Blastware's own (recorded 2026-10-26).
|
||||
|
||||
Blastware downloaded all 8 of BE9441's events -- three of which cross a 64 KB page
|
||||
-- while a bridge recorded both directions (fixture README). Every one of its 748
|
||||
requests is the standard 16-byte payload with a SUM8 checksum and every 02 / 03 /
|
||||
04 / 10 byte DLE-escaped; a 5A request carries a length (0x0200, or the remainder
|
||||
for TERM) and a 4-byte linear address. The walk is the event's start, then
|
||||
+0x200 at a time carrying into the page byte, then TERM at the next boundary for
|
||||
exactly the remainder. SFM must send exactly those requests.
|
||||
"""
|
||||
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__))))
|
||||
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.blastware_file import extract_body_bytes # noqa: E402
|
||||
from minimateplus.framing import S3FrameParser, build_5a_request, build_bw_frame, waveform_key_params # noqa: E402
|
||||
from minimateplus.waveform_codec import STREAM_END_ID, decode_waveform_v2, walk_records # noqa: E402
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-blastware"
|
||||
|
||||
|
||||
def _unstuff(b: bytes) -> bytes:
|
||||
out, k = bytearray(), 0
|
||||
while k < len(b):
|
||||
if b[k] == 0x10 and k + 1 < len(b):
|
||||
out.append(b[k + 1]); k += 2
|
||||
else:
|
||||
out.append(b[k]); k += 1
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def bw_requests() -> list:
|
||||
"""Blastware's requests, each as wire bytes; the SESSION_RESETs dropped."""
|
||||
raw, out, i = (FIX / "blastware_requests.bin").read_bytes(), [], 0
|
||||
while i < len(raw):
|
||||
if raw[i:i + 2] == b"\x41\x03":
|
||||
i += 2
|
||||
continue
|
||||
j = i + 2
|
||||
while raw[j] != 0x03: # the first ETX not escaped by a DLE
|
||||
j += 2 if raw[j] == 0x10 else 1
|
||||
out.append(raw[i:j + 1])
|
||||
i = j + 1
|
||||
return out
|
||||
|
||||
|
||||
def logical(frame: bytes) -> bytes:
|
||||
return _unstuff(frame[2:-1])[:-1] # the 16-byte payload, checksum dropped
|
||||
|
||||
|
||||
def unit_a5_replies() -> list:
|
||||
raw, out, start, p = (FIX / "unit_replies.bin").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
|
||||
|
||||
|
||||
REQS = bw_requests()
|
||||
FIVE_A = [f for f in REQS if logical(f)[2] == 0x5A]
|
||||
|
||||
|
||||
def addr_len(frame: bytes) -> tuple:
|
||||
p = logical(frame)
|
||||
return int.from_bytes(p[6:10], "big"), int.from_bytes(p[4:6], "big")
|
||||
|
||||
|
||||
def test_the_recording_is_what_the_readme_says():
|
||||
assert (len(REQS), len(FIVE_A)) == (748, 540)
|
||||
|
||||
|
||||
def test_every_blastware_5a_request_is_rebuilt_byte_for_byte():
|
||||
assert [build_5a_request(*addr_len(f)) for f in FIVE_A] == FIVE_A
|
||||
|
||||
|
||||
def test_every_other_blastware_request_is_rebuilt_byte_for_byte():
|
||||
others = [f for f in REQS if logical(f)[2] != 0x5A]
|
||||
assert len(others) == 208
|
||||
for f in others:
|
||||
p = logical(f)
|
||||
assert build_bw_frame(p[2], p[5], p[6:16]) == f
|
||||
|
||||
|
||||
def test_a_standard_request_escapes_02_03_04_in_its_params_and_checksum():
|
||||
frame = build_bw_frame(0x0A, 0x46, waveform_key_params(bytes.fromhex("01120203")))
|
||||
assert b"\x10\x02\x10\x03" in frame # the key's 02 and 03
|
||||
for low in range(256): # a checksum of 0x03
|
||||
f = build_bw_frame(0x0A, 0x46, waveform_key_params(bytes([0x01, 0x11, 0x50, low])))
|
||||
if sum(_unstuff(f[2:-1])[:-1]) & 0xFF == 0x03:
|
||||
assert f.endswith(b"\x10\x03\x03")
|
||||
break
|
||||
else:
|
||||
pytest.fail("no key gave a checksum of 0x03")
|
||||
|
||||
|
||||
# -- the walk ------------------------------------------------------------------
|
||||
|
||||
class ByAddress:
|
||||
"""Answers each 5A request with Blastware's recorded reply for the same
|
||||
(address, length); records what SFM sent."""
|
||||
|
||||
def __init__(self):
|
||||
self.replies = {addr_len(q): r for q, r in zip(FIVE_A, unit_a5_replies())}
|
||||
self.sent, self._buf = [], b""
|
||||
|
||||
def write(self, data):
|
||||
data = bytes(data)
|
||||
self.sent.append(data)
|
||||
self._buf += self.replies.get(addr_len(data), b"")
|
||||
|
||||
def read(self, n):
|
||||
out, self._buf = self._buf[:n], self._buf[n:]
|
||||
return out
|
||||
|
||||
|
||||
def blastware_walk(start: int) -> list:
|
||||
"""Blastware's requests for the event that starts at `start`."""
|
||||
i = next(k for k, f in enumerate(FIVE_A) if addr_len(f) == (start, 0x200))
|
||||
walk = [FIVE_A[i]]
|
||||
while addr_len(walk[-1])[1] == 0x200: # until TERM (a short read)
|
||||
i += 1
|
||||
walk.append(FIVE_A[i])
|
||||
return walk
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fast(monkeypatch):
|
||||
fast_clock(monkeypatch)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["01110000", "01118a2c", "0112a0b6", "0114b0b2"])
|
||||
def test_the_walk_sends_exactly_blastwares_requests_and_the_event_is_whole(key):
|
||||
t = ByAddress()
|
||||
frames = mp.MiniMateProtocol(t).read_bulk_waveform_stream(
|
||||
bytes.fromhex(key), stop_after_metadata=False, include_terminator=True, strict=True)
|
||||
want = blastware_walk(int(key, 16))
|
||||
assert t.sent == want
|
||||
assert len(frames) == len(want)
|
||||
_s, body, _f = extract_body_bytes(frames)
|
||||
recs = walk_records(body)
|
||||
assert body[recs[-1]["end"] + 4] == STREAM_END_ID
|
||||
dec = decode_waveform_v2(body)
|
||||
assert len({len(dec[c]) for c in ("Tran", "Vert", "Long")}) == 1
|
||||
@@ -71,8 +71,9 @@ def test_strict_raises_when_the_term_gets_no_reply():
|
||||
stream(a5_replies(), silent_from=50, strict=True) # every chunk answered, the TERM not
|
||||
|
||||
|
||||
def test_strict_raises_when_a_metadata_page_gets_no_reply():
|
||||
with pytest.raises(mp.ProtocolError, match="metadata page 0x1002 got no reply"):
|
||||
def test_strict_raises_when_the_first_events_second_chunk_gets_no_reply():
|
||||
# once called the "metadata page at 0x1002": it is event 0's chunk at 0x0200
|
||||
with pytest.raises(mp.ProtocolError, match="no reply for the chunk at 0x01110200"):
|
||||
stream(a5_replies(FIX_EVENT0), key=KEY0, silent_from=1, strict=True)
|
||||
|
||||
|
||||
@@ -101,15 +102,15 @@ def test_the_legacy_walk_keeps_its_tolerance():
|
||||
assert 0 < len(frames) < 51 # short, returned, not raised -- as before
|
||||
|
||||
|
||||
def test_strict_names_an_event_that_crosses_the_64kb_page_boundary():
|
||||
"""BE9441 events 2 and 19 end in the next page (end offset < start offset);
|
||||
the walk cannot follow them yet. Refused by name, before any chunk is sent."""
|
||||
def test_strict_refuses_a_strt_whose_end_is_not_after_its_start():
|
||||
"""An event that crosses a 64 KB page now downloads (tests/test_5a_blastware_walk.py);
|
||||
an end at or before the start can only be a corrupt STRT."""
|
||||
r = a5_replies()
|
||||
i = r[0].find(b"STRT")
|
||||
assert r[0][i + 6:i + 10] == bytes.fromhex("0111c92c") # the end key: same page
|
||||
r[0] = r[0][:i + 6] + bytes.fromhex("01122f06") + r[0][i + 10:] # ... now the next page
|
||||
assert r[0][i + 6:i + 10] == bytes.fromhex("0111c92c") # the end key
|
||||
r[0] = r[0][:i + 6] + bytes.fromhex("01110000") + r[0][i + 10:] # ... before the start
|
||||
p = mp.MiniMateProtocol(Replay(r))
|
||||
with pytest.raises(mp.ProtocolError, match="crosses the unit's 64 KB page boundary"):
|
||||
with pytest.raises(mp.ProtocolError, match="at or before its start"):
|
||||
p.read_bulk_waveform_stream(KEY, stop_after_metadata=False, include_terminator=True,
|
||||
strict=True)
|
||||
assert p._transport.sent == 1 # the probe, and nothing after
|
||||
assert p._transport.sent == 1 # the first chunk, and nothing after
|
||||
Reference in new issue
Block a user