fix(minimateplus): MiniMate config writes are ordinary escaped requests carrying whole blocks; apply_config reads the unit's own trigger block (#46)
Measured against every Blastware request on record: the uploaded Feb-Apr 2026
captures (3,869 frames, 3,869 re-encode exactly) and BE9441's two sends on
2026-10-26 (26 write frames). A write is the standard 16-byte request plus its
data, every 02/03/04/10 escaped, SUM8 checksum; the length field is the data's
length. A config block starts with its own length N and is written as N + 2
bytes: event index (68) and trigger (82) as read plus 02 00 / 00 00 (constant on
15 sends), waveform data (69) and the 2,092-byte compliance image (71) whole.
The compliance image goes in addressed chunks (params[2:4] = address): 512 bytes
tonight (Blastware 10.74), 1,024 in March.
- framing.build_bw_write_frame: uniform escaping, SUM8, length = len(data).
RETRACTED: 'only BW_CMD doubled', the 'DLE-aware checksum', 'offset = data[1]
+ 2' -- fitted to frames still holding their escape bytes ('data 91, offset 90'
was 90 bytes and one escape). It got 7 of every 13 frames in a write wrong.
- protocol.write_image(): unescapes (callers may pass the parser's form), adds
the trailing two bytes to an N-byte block, and REFUSES anything else before a
byte is sent -- an edit beside a kept escape byte (the old encoder's anc-9
hazard) leaves an image one byte long.
- write_compliance_config_raw: 512-byte addressed chunks, then confirm 72.
- read_event_index / read_waveform_data_raw unescape before slicing (a block
holding 02/03/04/10 came out short); new read_trigger_config (SUB 0x2E).
- apply_config reads the unit's trigger block. RETRACTED: the block
'hardcoded from 3-11-26 -- no read exists'. Blastware reads it; byte 5 has
been 01 / 03 / 04 by unit and session, and the March copy (03) would have
changed BE9441's (01).
- The call-home write (7E) goes through write_image: its 127-byte 'read + 00 00'
is the 126-byte image (N = 0x7C). No Blastware 7E is on record here -- that
one is inferred from the other 77 write frames.
Tests: tonight's 26 and every Feb-Apr write frame rebuilt byte for byte; each
block as read written exactly as Blastware wrote it; the parser's form; the
stray-byte refusal; the reads against the unit's recorded replies; apply_config
writes BE9441's own trigger block. Six mutants, each caught. The old
test_write_frames.py (25 tests that had been skipping) runs now that the
captures are here, rewritten to the measured model.
Not yet sent to a unit: a config push changes settings, so its first live use
is a bench session with Brian. 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
a7f581f66a
commit
b5037b0b1e
5 files changed
+436
-702
No files matched your search
+8
-10
@@ -67,14 +67,11 @@ S3_MONITORING_FLAGS = frozenset({0x10, 0x0B})
|
||||
|
||||
# ── Module-level constants ────────────────────────────────────────────────────
|
||||
|
||||
# Trigger config payload hardcoded from 3-11-26 BW TX capture (BW frame 108).
|
||||
# No SUB 0x22 read exists in the capture — Blastware writes this fixed blob.
|
||||
# 29 bytes: [00][1A][D5][00][00][10][03][08][0A] + 18×FF + [00][00]
|
||||
_TRIGGER_DATA_HARDCODED: bytes = bytes.fromhex(
|
||||
"001ad500001003080a"
|
||||
"ffffffffffffffffffffffffffffffffffffff"
|
||||
"0000"
|
||||
)
|
||||
# ⚠ RETRACTED 2026-10-27 (#46): a trigger block "hardcoded from 3-11-26 -- no
|
||||
# read exists, Blastware writes this fixed blob". Blastware reads it first (SUB
|
||||
# 0x2E), and its byte 5 differs by unit and session (01 / 03 / 04 on record), so
|
||||
# the copy changed that setting on any unit that differed. apply_config reads
|
||||
# the unit's own block (MiniMateProtocol.read_trigger_config).
|
||||
|
||||
# Compliance ASCII slot format (confirmed from 3-11-26 capture + label search):
|
||||
# Each label occupies a 64-byte slot.
|
||||
@@ -1037,7 +1034,7 @@ class MiniMateClient:
|
||||
Write payloads:
|
||||
event_index_data : 88 bytes — read live via SUB 08
|
||||
compliance_data : ~2128 bytes — read live via SUB 1A (~2126 bytes, varies ±1-2) + \\x00\\x00 footer
|
||||
trigger_data : 29 bytes — hardcoded from 3-11-26 capture
|
||||
trigger_data : 26 bytes — read live via SUB 2E (was hard-coded; #46)
|
||||
waveform_data : 204 bytes — read live via SUB 09
|
||||
|
||||
Raises:
|
||||
@@ -1057,7 +1054,8 @@ class MiniMateClient:
|
||||
log.info("apply_config: reading waveform data (SUB 09)")
|
||||
waveform_data = proto.read_waveform_data_raw() # 204 bytes
|
||||
|
||||
trigger_data = _TRIGGER_DATA_HARDCODED # 29 bytes
|
||||
log.info("apply_config: reading trigger config (SUB 2E)")
|
||||
trigger_data = proto.read_trigger_config() # 26 bytes, this unit's own
|
||||
|
||||
# 2. Patch the compliance buffer and build the 2128-byte write payload
|
||||
compliance_data = _encode_compliance_config(
|
||||
|
||||
+20
-89
@@ -284,103 +284,34 @@ def build_bw_write_frame(
|
||||
sub: int,
|
||||
data: bytes,
|
||||
*,
|
||||
offset: int = 0,
|
||||
offset: Optional[int] = None,
|
||||
params: bytes = bytes(10),
|
||||
) -> bytes:
|
||||
"""
|
||||
Build a BW→S3 write-command frame.
|
||||
"""A write request: the standard 16-byte request followed by `data`, escaped
|
||||
and checksummed like every other request (s3_stuff, SUM8).
|
||||
|
||||
Write frames extend the standard 16-byte read header with a variable-length
|
||||
data payload. They use a different checksum formula from read frames.
|
||||
`offset` is the payload's [4:6] field -- the data's LENGTH; it defaults to
|
||||
len(data), which is what Blastware sends on every write on record.
|
||||
|
||||
**CRITICAL: Write frames use minimal DLE stuffing.**
|
||||
Measured 2026-10-26/27 (issue #46): all of Blastware's requests from February
|
||||
to October 2026 -- 3,869 frames in the uploaded captures plus BE9441's 26
|
||||
write frames tonight -- rebuild byte for byte this way, the 77 write frames
|
||||
that carry data included (event index 68, compliance 71, trigger 82, waveform
|
||||
data 69).
|
||||
|
||||
Unlike read frames (build_bw_frame), write frames do NOT apply full DLE
|
||||
stuffing to the payload. Only the BW_CMD byte (0x10) at position [0] is
|
||||
doubled to 0x10 0x10 on the wire. All other bytes — flags, sub, offset,
|
||||
params, data, and checksum — are written RAW with no stuffing, even if they
|
||||
contain 0x10 bytes (e.g. offset_hi=0x10 for compliance chunks, or 0x10
|
||||
bytes in the write data payload).
|
||||
|
||||
Confirmed from 3-11-26 BW TX capture (frames 102–112): all 11 write frames
|
||||
match the rule "double BW_CMD only; everything else raw." ✅ 2026-04-07.
|
||||
|
||||
Wire layout:
|
||||
[41] ACK
|
||||
[02] STX
|
||||
[10 10] BW_CMD doubled (the ONLY DLE stuffing applied)
|
||||
[00] flags
|
||||
[sub] write command byte (0x68–0x83)
|
||||
[00] always zero
|
||||
[hi][lo] offset as uint16 BE (raw; NOT stuffed even if hi=0x10)
|
||||
[params] 10 bytes (raw)
|
||||
[data] variable-length write payload (raw; NOT stuffed)
|
||||
[chk] checksum byte (raw; NOT stuffed even if 0x10)
|
||||
[03] ETX
|
||||
|
||||
De-stuffed payload (for checksum computation):
|
||||
[0] BW_CMD 0x10
|
||||
[1] flags 0x00
|
||||
[2] SUB write command byte
|
||||
[3] 0x00 always zero
|
||||
[4] offset_hi
|
||||
[5] offset_lo
|
||||
[6:16] params 10 bytes
|
||||
[16:] data write payload
|
||||
[-1] chk
|
||||
|
||||
**Checksum formula (confirmed 2026-03-12 from 3-11-26 BW TX capture):**
|
||||
chk = (sum(b for b in payload[2:] if b != 0x10) + 0x10) % 256
|
||||
where payload = destuffed content BEFORE appending chk.
|
||||
This skips all 0x10 bytes in payload[2:] (sub onwards), including any
|
||||
0x10 bytes in the offset, params, data, and the checksum byte itself.
|
||||
|
||||
The offset field [4:6] meaning per write SUB:
|
||||
- SUBs 68, 69, 82 (single-chunk writes): offset = data[1] + 2, where
|
||||
data[1] is an embedded length field in the write payload.
|
||||
Confirmed from capture: 68→0x5A (data[1]=0x58+2), 82→0x1C
|
||||
(data[1]=0x1A+2), 69→0xCA (data[1]=0xC8+2).
|
||||
- SUB 71 (multi-chunk compliance): 0x1004 for full chunks, 0x002C
|
||||
for the final partial chunk.
|
||||
- Confirm frames (72, 73, 74, 83): offset=0, no data.
|
||||
|
||||
Args:
|
||||
sub: Write command SUB byte.
|
||||
data: Write payload (variable length; empty for confirm frames).
|
||||
offset: 16-bit value placed at [4:6]. See per-SUB notes above.
|
||||
params: 10 bytes placed at [6:16]. All-zero for most writes; compliance
|
||||
chunk writes use chunk-specific values.
|
||||
|
||||
Returns:
|
||||
Complete frame bytes ready to write to the transport.
|
||||
⚠ RETRACTED: "only BW_CMD is doubled, everything else raw" and the "DLE-aware
|
||||
checksum" `(sum of payload[2:] skipping 0x10) + 0x10`. That model rebuilt the
|
||||
March frames only because it was fitted to data that still held its escape
|
||||
bytes; the "data length 91, offset 90" it explained was 90 bytes plus one
|
||||
escape. It got 7 of every 13 frames in a config write wrong.
|
||||
"""
|
||||
if len(params) != 10:
|
||||
raise ValueError(f"params must be exactly 10 bytes, got {len(params)}")
|
||||
if offset > 0xFFFF:
|
||||
raise ValueError(f"offset must fit in uint16, got {offset:#06x}")
|
||||
|
||||
offset_hi = (offset >> 8) & 0xFF
|
||||
offset_lo = offset & 0xFF
|
||||
|
||||
# Destuffed payload (used only for checksum; not sent directly)
|
||||
payload_no_chk = bytes([BW_CMD, 0x00, sub, 0x00, offset_hi, offset_lo]) + params + data
|
||||
|
||||
# Large-frame checksum: sum payload[2:] skipping all 0x10 bytes, add 0x10.
|
||||
# Applied to the destuffed representation — confirms correctly against
|
||||
# all 11 write frames in the 3-11-26/170151 BW TX capture. ✅
|
||||
chk = (sum(b for b in payload_no_chk[2:] if b != 0x10) + 0x10) & 0xFF
|
||||
|
||||
# Wire construction: only BW_CMD is doubled; everything else is raw.
|
||||
# Do NOT use dle_stuff() here — that would incorrectly double 0x10 bytes
|
||||
# in the offset, params, and data sections.
|
||||
wire = (
|
||||
bytes([ACK, STX]) # Frame prefix (not part of payload)
|
||||
+ bytes([BW_CMD, BW_CMD]) # BW_CMD doubled (only DLE stuffing applied)
|
||||
+ payload_no_chk[1:] # flags, sub, offset, params, data — RAW
|
||||
+ bytes([chk]) # checksum — RAW
|
||||
+ bytes([ETX]) # Frame terminator
|
||||
)
|
||||
return wire
|
||||
length = len(data) if offset is None else offset
|
||||
if not 0 <= length <= 0xFFFF:
|
||||
raise ValueError(f"length must fit in 16 bits, got {length:#x}")
|
||||
payload = bytes([BW_CMD, 0x00, sub, 0x00, (length >> 8) & 0xFF, length & 0xFF]) + params + data
|
||||
return bytes([ACK, STX]) + s3_stuff(payload + bytes([checksum(payload)])) + bytes([ETX])
|
||||
|
||||
|
||||
def waveform_key_params(key4: bytes) -> bytes:
|
||||
|
||||
+93
-205
@@ -33,6 +33,7 @@ from .framing import (
|
||||
waveform_key_params,
|
||||
token_params,
|
||||
parse_strt_end_key,
|
||||
unescape_reply,
|
||||
build_5a_request,
|
||||
POLL_PROBE,
|
||||
POLL_DATA,
|
||||
@@ -130,6 +131,40 @@ _BULK_COUNTER_STEP = 0x0200 # bytes per chunk read, and the step between addre
|
||||
# claim past this is a misread STRT, refused before walking megabytes of garbage.
|
||||
_BULK_MAX_EVENT_BYTES = 0x400000 # 4 MiB
|
||||
|
||||
# Config writes (issue #46, measured on every Blastware write since February 2026).
|
||||
_COMPLIANCE_CHUNK = 0x0200
|
||||
# The two bytes after a block's N header bytes, when the read returned only N:
|
||||
# Blastware's own, constant on record -- event index 02 00, trigger 00 00. The
|
||||
# unit evidently does not check them (they are no CRC, and the compliance
|
||||
# image's went out stale, unchanged across two different sends).
|
||||
_WRITE_TAIL = {SUB_EVENT_INDEX_WRITE: b"\x02\x00", SUB_TRIGGER_CONFIG_WRITE: b"\x00\x00",
|
||||
SUB_WAVEFORM_DATA_WRITE: b"\x00\x00", SUB_COMPLIANCE_WRITE: b"\x00\x00",
|
||||
SUB_CALL_HOME_WRITE: b"\x00\x00"}
|
||||
|
||||
|
||||
def write_image(sub: int, data: bytes) -> bytes:
|
||||
"""The whole block a write sends: `data` unescaped, N + 2 bytes.
|
||||
|
||||
A config block starts with its own length N (uint16 BE) and is written as N
|
||||
bytes plus two -- on every Blastware write on record. `data` may be the
|
||||
block as a read returned it (N bytes, or N + 2) and may still hold the
|
||||
parser's kept escape bytes (10 02 / 10 03 / 10 04), which come out here.
|
||||
Anything else is refused before a byte is sent: a block one byte longer than
|
||||
its header says is what an edit beside a kept escape byte leaves behind.
|
||||
"""
|
||||
image = unescape_reply(bytes(data))
|
||||
if len(image) < 2:
|
||||
raise ValueError(f"write SUB 0x{sub:02X}: {len(image)} bytes is not a whole block")
|
||||
n = int.from_bytes(image[:2], "big")
|
||||
if len(image) == n:
|
||||
image += _WRITE_TAIL[sub]
|
||||
elif len(image) != n + 2:
|
||||
raise ValueError(
|
||||
f"write SUB 0x{sub:02X}: {len(image)} bytes, but its header says {n} (+ 2) -- "
|
||||
"not a whole block (a stray byte?); nothing sent")
|
||||
return image
|
||||
|
||||
|
||||
# Default timeout values (seconds).
|
||||
# MiniMate Plus is a slow device — keep these generous.
|
||||
DEFAULT_RECV_TIMEOUT = 10.0
|
||||
@@ -383,7 +418,9 @@ class MiniMateProtocol:
|
||||
self._send(build_bw_frame(SUB_EVENT_INDEX, length))
|
||||
data_rsp = self._recv_one(expected_sub=rsp_sub)
|
||||
|
||||
raw = data_rsp.data[11 : 11 + length]
|
||||
# Unescaped first (2026-10-27): a 02/03/04 inside the block arrives as
|
||||
# 10 0X and the parser keeps both, so a slice by length came up short.
|
||||
raw = unescape_reply(data_rsp.data)[11 : 11 + length]
|
||||
log.debug("read_event_index: got %d bytes", len(raw))
|
||||
return raw
|
||||
|
||||
@@ -515,7 +552,7 @@ class MiniMateProtocol:
|
||||
self._send(build_bw_frame(SUB_WAVEFORM_DATA, length))
|
||||
data_rsp = self._recv_one(expected_sub=rsp_sub)
|
||||
|
||||
raw = data_rsp.data[11:]
|
||||
raw = unescape_reply(data_rsp.data)[11:] # unescaped, as read_event_index
|
||||
log.debug("read_waveform_data_raw: got %d bytes", len(raw))
|
||||
return raw
|
||||
|
||||
@@ -1013,208 +1050,66 @@ class MiniMateProtocol:
|
||||
self._send(frame)
|
||||
return self.recv_write_ack(expected_sub=rsp_sub)
|
||||
|
||||
def write_event_index(self, data: bytes) -> S3Frame:
|
||||
"""
|
||||
Send a SUB 68 (EVENT_INDEX_WRITE) frame and await the confirm ack (SUB 97).
|
||||
|
||||
Offset formula: data[1] + 2 — confirmed from 3-11-26 BW TX capture frame 102.
|
||||
The write payload has a 2-byte header [0x00][length] where data[1] encodes
|
||||
the length of the meaningful payload; offset = data[1] + 2.
|
||||
|
||||
Example from capture:
|
||||
data[0:4] = 00 58 09 00 (data[1]=0x58=88 → offset=0x5A=90)
|
||||
data length = 91, offset = 90
|
||||
|
||||
Write sequence fragment:
|
||||
68 (data) → device acks with SUB 0x97
|
||||
73 (confirm) → device acks with SUB 0x8C
|
||||
|
||||
Callers should call write_confirm(SUB_WRITE_CONFIRM_B) after this.
|
||||
|
||||
Args:
|
||||
data: Raw event-index payload bytes to write to the device.
|
||||
Must be at least 2 bytes. data[1] must contain the length field.
|
||||
|
||||
Returns:
|
||||
The SUB 0x97 ack frame.
|
||||
|
||||
Raises:
|
||||
ProtocolError: on timeout or wrong response SUB.
|
||||
ValueError: if data is shorter than 2 bytes.
|
||||
"""
|
||||
if len(data) < 2:
|
||||
raise ValueError(f"event index write data must be at least 2 bytes, got {len(data)}")
|
||||
rsp_sub = _expected_rsp_sub(SUB_EVENT_INDEX_WRITE) # 0xFF - 0x68 = 0x97
|
||||
offset = data[1] + 2
|
||||
frame = build_bw_write_frame(SUB_EVENT_INDEX_WRITE, data, offset=offset)
|
||||
log.debug(
|
||||
"write_event_index: %d bytes data[1]=0x%02X offset=0x%04X rsp_sub=0x%02X",
|
||||
len(data), data[1], offset, rsp_sub,
|
||||
)
|
||||
def _write_block(self, sub: int, data: bytes, params: bytes = bytes(10)) -> S3Frame:
|
||||
"""Send one config block as a write and return its ack (0xFF - sub)."""
|
||||
image = write_image(sub, data)
|
||||
frame = build_bw_write_frame(sub, image, params=params)
|
||||
log.debug("write SUB=0x%02X: %d-byte image", sub, len(image))
|
||||
self._send(frame)
|
||||
return self.recv_write_ack(expected_sub=rsp_sub)
|
||||
return self.recv_write_ack(expected_sub=_expected_rsp_sub(sub))
|
||||
|
||||
def write_event_index(self, data: bytes) -> S3Frame:
|
||||
"""SUB 68: write the event-index block (as SUB 08 read it). Ack 0x97;
|
||||
callers follow with write_confirm(SUB_WRITE_CONFIRM_B). See write_image."""
|
||||
return self._write_block(SUB_EVENT_INDEX_WRITE, data)
|
||||
|
||||
def write_waveform_data(self, data: bytes) -> S3Frame:
|
||||
"""
|
||||
Send a SUB 69 (WAVEFORM_DATA_WRITE) frame and await the confirm ack (SUB 96).
|
||||
|
||||
Offset formula: data[1] + 2 — same pattern as write_event_index().
|
||||
Confirmed from 3-11-26 BW TX capture frame 110:
|
||||
data[0:4] = 00 c8 08 00 (data[1]=0xC8=200 → offset=0xCA=202)
|
||||
data length = 204, offset = 202
|
||||
|
||||
Write sequence fragment:
|
||||
69 (data) → device acks with SUB 0x96
|
||||
74 (confirm) → device acks with SUB 0x8B
|
||||
72 (confirm) → device acks with SUB 0x8D
|
||||
|
||||
Callers should call write_confirm(SUB_WRITE_CONFIRM_C) then
|
||||
write_confirm(SUB_WRITE_CONFIRM_A) after this.
|
||||
|
||||
Args:
|
||||
data: Raw waveform-data payload bytes to write.
|
||||
Must be at least 2 bytes. data[1] must contain the length field.
|
||||
|
||||
Returns:
|
||||
The SUB 0x96 ack frame.
|
||||
|
||||
Raises:
|
||||
ProtocolError: on timeout or wrong response SUB.
|
||||
ValueError: if data is shorter than 2 bytes.
|
||||
"""
|
||||
if len(data) < 2:
|
||||
raise ValueError(f"waveform data write payload must be at least 2 bytes, got {len(data)}")
|
||||
rsp_sub = _expected_rsp_sub(SUB_WAVEFORM_DATA_WRITE) # 0xFF - 0x69 = 0x96
|
||||
offset = data[1] + 2
|
||||
frame = build_bw_write_frame(SUB_WAVEFORM_DATA_WRITE, data, offset=offset)
|
||||
log.debug(
|
||||
"write_waveform_data: %d bytes data[1]=0x%02X offset=0x%04X rsp_sub=0x%02X",
|
||||
len(data), data[1], offset, rsp_sub,
|
||||
)
|
||||
self._send(frame)
|
||||
return self.recv_write_ack(expected_sub=rsp_sub)
|
||||
"""SUB 69: write the waveform-data block (as SUB 09 read it). Ack 0x96;
|
||||
callers follow with write_confirm C then A. See write_image."""
|
||||
return self._write_block(SUB_WAVEFORM_DATA_WRITE, data)
|
||||
|
||||
def write_compliance_config_raw(self, data: bytes) -> None:
|
||||
"""SUB 71: write the compliance image in addressed chunks, then confirm (72).
|
||||
|
||||
Measured: the image is 2,092 bytes (its header N = 2,090, plus 2), sent as
|
||||
512-byte chunks with the chunk's address at params[2:4] -- 0x0000, 0x0200,
|
||||
0x0400, 0x0600, then the 44-byte rest at 0x0800 -- each acked 0x8E, then
|
||||
SUB 72 (ack 0x8D). Blastware 10.74 on BE9441 (2026-10-26), byte for byte.
|
||||
March 2026's Blastware sent 1,024-byte chunks the same way; the units took
|
||||
both. (Retracted: "exactly 3 chunks, offset 0x1004, params 00 00 00 10 04"
|
||||
-- the length 0x0400 and address 0x0400, read with their escape bytes.)
|
||||
"""
|
||||
Send the SUB 71 (COMPLIANCE_WRITE) 3-chunk sequence and final confirm.
|
||||
|
||||
The full compliance config payload (~2128 bytes) is split into exactly 3
|
||||
chunks with hardcoded boundaries and params confirmed from the 3-11-26 BW
|
||||
TX capture (frames 104–108):
|
||||
|
||||
Chunk 1 — first 1027 bytes:
|
||||
offset=0x1004 params=bytes(10)
|
||||
device acks SUB 0x8E
|
||||
|
||||
Chunk 2 — next 1055 bytes:
|
||||
offset=0x1004 params=b'\\x00\\x00\\x00\\x00\\x10\\x04' + b'\\x00'*4
|
||||
device acks SUB 0x8E
|
||||
|
||||
Chunk 3 — remaining bytes:
|
||||
offset=0x002C params=b'\\x00\\x00\\x08' + b'\\x00'*7
|
||||
device acks SUB 0x8E
|
||||
|
||||
Confirm — SUB 72 (zero data):
|
||||
device acks SUB 0x8D
|
||||
|
||||
The total write payload should be at least 1027+1055=2082 bytes; chunk 3
|
||||
carries everything after offset 2082 (typically ~46 bytes for a 2128-byte
|
||||
config).
|
||||
|
||||
Args:
|
||||
data: Raw compliance config bytes to write. Must be at least 2082 bytes.
|
||||
|
||||
Raises:
|
||||
ValueError: if data is too short to fill chunks 1 and 2.
|
||||
ProtocolError: on timeout or wrong response SUB from any chunk.
|
||||
"""
|
||||
_CHUNK1_SIZE = 1027
|
||||
_CHUNK2_SIZE = 1055
|
||||
_CHUNK1_OFFSET = 0x1004
|
||||
_CHUNK2_OFFSET = 0x1004
|
||||
_CHUNK3_OFFSET = 0x002C
|
||||
|
||||
_CHUNK1_PARAMS = bytes(10)
|
||||
_CHUNK2_PARAMS = bytes([0x00, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00])
|
||||
_CHUNK3_PARAMS = bytes([0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
|
||||
|
||||
min_size = _CHUNK1_SIZE + _CHUNK2_SIZE
|
||||
if len(data) < min_size:
|
||||
raise ValueError(
|
||||
f"Compliance write data too short: {len(data)} bytes, "
|
||||
f"need at least {min_size} (chunk1={_CHUNK1_SIZE} + chunk2={_CHUNK2_SIZE})"
|
||||
)
|
||||
|
||||
rsp_sub = _expected_rsp_sub(SUB_COMPLIANCE_WRITE) # 0xFF - 0x71 = 0x8E
|
||||
|
||||
chunk1 = data[:_CHUNK1_SIZE]
|
||||
chunk2 = data[_CHUNK1_SIZE : _CHUNK1_SIZE + _CHUNK2_SIZE]
|
||||
chunk3 = data[_CHUNK1_SIZE + _CHUNK2_SIZE :]
|
||||
|
||||
chunks = [
|
||||
(1, chunk1, _CHUNK1_OFFSET, _CHUNK1_PARAMS),
|
||||
(2, chunk2, _CHUNK2_OFFSET, _CHUNK2_PARAMS),
|
||||
(3, chunk3, _CHUNK3_OFFSET, _CHUNK3_PARAMS),
|
||||
]
|
||||
|
||||
for chunk_num, chunk_data, chunk_offset, chunk_params in chunks:
|
||||
frame = build_bw_write_frame(
|
||||
SUB_COMPLIANCE_WRITE,
|
||||
chunk_data,
|
||||
offset=chunk_offset,
|
||||
params=chunk_params,
|
||||
)
|
||||
log.debug(
|
||||
"write_compliance_config_raw: chunk %d %d bytes "
|
||||
"offset=0x%04X params=%s",
|
||||
chunk_num, len(chunk_data), chunk_offset, chunk_params.hex(),
|
||||
)
|
||||
image = write_image(SUB_COMPLIANCE_WRITE, data)
|
||||
rsp_sub = _expected_rsp_sub(SUB_COMPLIANCE_WRITE)
|
||||
for addr in range(0, len(image), _COMPLIANCE_CHUNK):
|
||||
params = bytes([0x00, 0x00, (addr >> 8) & 0xFF, addr & 0xFF]) + bytes(6)
|
||||
frame = build_bw_write_frame(SUB_COMPLIANCE_WRITE,
|
||||
image[addr:addr + _COMPLIANCE_CHUNK], params=params)
|
||||
log.debug("write_compliance_config_raw: chunk at 0x%04X", addr)
|
||||
self._send(frame)
|
||||
self.recv_write_ack(expected_sub=rsp_sub)
|
||||
log.debug("write_compliance_config_raw: chunk %d acked", chunk_num)
|
||||
|
||||
# Final confirm (SUB 72)
|
||||
log.debug("write_compliance_config_raw: sending confirm (SUB 0x72)")
|
||||
self.write_confirm(SUB_WRITE_CONFIRM_A)
|
||||
log.debug("write_compliance_config_raw: done")
|
||||
|
||||
def write_trigger_config(self, data: bytes) -> S3Frame:
|
||||
"""SUB 82: write the trigger block (as SUB 0x2E read it). Ack 0x7D;
|
||||
callers follow with write_confirm(SUB_TRIGGER_CONFIRM). See write_image."""
|
||||
return self._write_block(SUB_TRIGGER_CONFIG_WRITE, data)
|
||||
|
||||
def read_trigger_config(self) -> bytes:
|
||||
"""SUB 0x2E two-step read: the 26-byte trigger block that SUB 82 writes.
|
||||
|
||||
Blastware reads it before writing it (BE9441, 2026-10-26). Its byte 5
|
||||
differs by unit and session (01 / 03 / 04 on record) -- so a block copied
|
||||
from another unit, as apply_config once wrote, changes a setting.
|
||||
Returns the block unescaped (data[11:] after unescape_reply).
|
||||
"""
|
||||
Send a SUB 82 (TRIGGER_CONFIG_WRITE) frame and await the confirm ack (SUB 7D).
|
||||
|
||||
Offset formula: data[1] + 2 — same pattern as write_event_index().
|
||||
Confirmed from 3-11-26 BW TX capture frame 108:
|
||||
data[0:4] = 00 1a d5 00 (data[1]=0x1A=26 → offset=0x1C=28)
|
||||
data length = 29, offset = 28
|
||||
|
||||
Write sequence fragment:
|
||||
82 (data) → device acks with SUB 0x7D
|
||||
83 (confirm) → device acks with SUB 0x7C
|
||||
|
||||
Callers should call write_confirm(SUB_TRIGGER_CONFIRM) after this.
|
||||
|
||||
Args:
|
||||
data: Raw trigger-config payload bytes to write.
|
||||
Must be at least 2 bytes. data[1] must contain the length field.
|
||||
|
||||
Returns:
|
||||
The SUB 0x7D ack frame.
|
||||
|
||||
Raises:
|
||||
ProtocolError: on timeout or wrong response SUB.
|
||||
ValueError: if data is shorter than 2 bytes.
|
||||
"""
|
||||
if len(data) < 2:
|
||||
raise ValueError(f"trigger config write payload must be at least 2 bytes, got {len(data)}")
|
||||
rsp_sub = _expected_rsp_sub(SUB_TRIGGER_CONFIG_WRITE) # 0xFF - 0x82 = 0x7D
|
||||
offset = data[1] + 2
|
||||
frame = build_bw_write_frame(SUB_TRIGGER_CONFIG_WRITE, data, offset=offset)
|
||||
log.debug(
|
||||
"write_trigger_config: %d bytes data[1]=0x%02X offset=0x%04X rsp_sub=0x%02X",
|
||||
len(data), data[1], offset, rsp_sub,
|
||||
)
|
||||
self._send(frame)
|
||||
return self.recv_write_ack(expected_sub=rsp_sub)
|
||||
rsp_sub = _expected_rsp_sub(SUB_UNKNOWN_2E)
|
||||
length = DATA_LENGTHS[SUB_UNKNOWN_2E]
|
||||
self._send(build_bw_frame(SUB_UNKNOWN_2E, 0))
|
||||
self._recv_one(expected_sub=rsp_sub)
|
||||
self._send(build_bw_frame(SUB_UNKNOWN_2E, length))
|
||||
data_rsp = self._recv_one(expected_sub=rsp_sub)
|
||||
return unescape_reply(data_rsp.data)[11:11 + length]
|
||||
|
||||
# ── Call home config (SUBs 0x2C / 0x7E / 0x7F) ──────────────────────────
|
||||
|
||||
@@ -1278,20 +1173,13 @@ class MiniMateProtocol:
|
||||
ValueError: if data is not exactly 127 bytes or lacks expected header.
|
||||
ProtocolError: on timeout or wrong response SUB.
|
||||
"""
|
||||
if len(data) < 2:
|
||||
raise ValueError(f"call home write payload must be at least 2 bytes, got {len(data)}")
|
||||
rsp_sub_write = _expected_rsp_sub(SUB_CALL_HOME_WRITE) # 0xFF - 0x7E = 0x81
|
||||
rsp_sub_confirm = _expected_rsp_sub(SUB_CALL_HOME_CONFIRM) # 0xFF - 0x7F = 0x80
|
||||
|
||||
# Offset formula: data[1] + 2 (same pattern as other single-chunk writes)
|
||||
offset = data[1] + 2 # 0x7C + 2 = 0x7E = 126
|
||||
frame = build_bw_write_frame(SUB_CALL_HOME_WRITE, data, offset=offset)
|
||||
log.debug(
|
||||
"write_call_home_config: %d bytes data[1]=0x%02X offset=0x%04X",
|
||||
len(data), data[1], offset,
|
||||
)
|
||||
self._send(frame)
|
||||
self.recv_write_ack(expected_sub=rsp_sub_write)
|
||||
# 2026-10-27 (#46): the read payload holds the parser's kept escape bytes
|
||||
# (num_retries 3 arrives as 10 03); write_image removes them, so the
|
||||
# 127-byte "read + 00 00" goes out as its 126-byte image (N = 0x7C, + 2),
|
||||
# escaped like every request. No Blastware call-home write is on record
|
||||
# here to compare against -- inferred from the 77 other write frames.
|
||||
self._write_block(SUB_CALL_HOME_WRITE, data)
|
||||
log.debug("write_call_home_config: write acked; sending confirm 0x7F")
|
||||
|
||||
confirm_frame = build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"")
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
"""MiniMate config writes, against Blastware's own (issue #46).
|
||||
|
||||
Measured 2026-10-26/27: every Blastware request on record -- 3,869 frames from
|
||||
February to April 2026 plus tonight's -- is the standard 16-byte payload with a
|
||||
SUM8 checksum and every 02/03/04/10 escaped, write frames included (77 carrying
|
||||
data). A write's length field is its data's length, and each block is written as
|
||||
read plus two trailing bytes: event index (68) `02 00`, trigger (82) `00 00`, the
|
||||
2,092-byte compliance image (71) in addressed chunks. The old builder ("raw
|
||||
except BW_CMD", "DLE-aware checksum") got 7 of every 13 frames wrong, and
|
||||
apply_config wrote a trigger block hard-coded from March whose byte 5 differs by
|
||||
unit and session (01 / 03 / 04).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import glob
|
||||
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, build_bw_write_frame, unescape_reply # noqa: E402
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram"
|
||||
CAPTURES = Path(__file__).parent.parent / "bridges" / "captures"
|
||||
|
||||
|
||||
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 _frames(raw: bytes) -> list:
|
||||
out, i = [], 0
|
||||
while i < len(raw):
|
||||
if raw[i:i + 2] == b"\x41\x03":
|
||||
i += 2
|
||||
continue
|
||||
if raw[i:i + 2] != b"\x41\x02":
|
||||
i += 1
|
||||
continue
|
||||
j = i + 2
|
||||
while j < len(raw) and raw[j] != 0x03:
|
||||
j += 2 if raw[j] == 0x10 else 1
|
||||
out.append(raw[i:j + 1])
|
||||
i = j + 1
|
||||
return out
|
||||
|
||||
|
||||
def _payload(frame: bytes) -> bytes:
|
||||
return _unstuff(frame[2:-1])[:-1]
|
||||
|
||||
|
||||
REQS = _frames((FIX / "requests.bin").read_bytes())
|
||||
WRITES = [f for f in REQS if 0x68 <= _payload(f)[2] <= 0x83]
|
||||
SEND2 = WRITES[13:26] # 16:27:21, the interval back to 2 s
|
||||
|
||||
|
||||
def _image(sub: int) -> bytes:
|
||||
return b"".join(_payload(f)[16:] for f in SEND2 if _payload(f)[2] == sub)
|
||||
|
||||
|
||||
def test_the_fixture_holds_two_whole_sends():
|
||||
assert [f"{_payload(f)[2]:02X}" for f in SEND2] == \
|
||||
["68", "73", "71", "71", "71", "71", "71", "72", "82", "83", "69", "74", "72"]
|
||||
|
||||
|
||||
def _rebuilds(frames: list) -> bool:
|
||||
for f in frames:
|
||||
p = _payload(f)
|
||||
if build_bw_write_frame(p[2], p[16:], params=p[6:16]) != f:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def test_every_write_frame_tonight_is_rebuilt_byte_for_byte():
|
||||
assert len(WRITES) == 26 and _rebuilds(WRITES)
|
||||
|
||||
|
||||
_OLD = sorted(glob.glob(str(CAPTURES / "[234]-*" / "**" / "raw_bw*.bin"), recursive=True))
|
||||
|
||||
|
||||
@pytest.mark.skipif(not _OLD, reason="the Feb-Apr 2026 Blastware captures are not on this box")
|
||||
def test_every_write_frame_since_february_is_rebuilt_byte_for_byte():
|
||||
frames = [f for path in _OLD for f in _frames(Path(path).read_bytes())
|
||||
if 0x68 <= _payload(f)[2] <= 0x83]
|
||||
assert len([f for f in frames if len(_payload(f)) > 16]) >= 48
|
||||
assert _rebuilds(frames)
|
||||
|
||||
|
||||
# -- the protocol: images in, Blastware's frames out ---------------------------
|
||||
|
||||
def _ack(write_sub: int) -> bytes:
|
||||
raw, 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]):
|
||||
w = raw[start:i + 1]
|
||||
if f.sub == (0xFF - write_sub) & 0xFF:
|
||||
return w[w.index(b"\x10\x02"):]
|
||||
start = i + 1
|
||||
raise AssertionError(f"no ack for 0x{write_sub:02X}")
|
||||
|
||||
|
||||
class Acks:
|
||||
"""Answers every write request with the unit's recorded ack for its SUB."""
|
||||
|
||||
def __init__(self):
|
||||
self.sent, self._buf = [], b""
|
||||
|
||||
def write(self, data):
|
||||
data = bytes(data)
|
||||
self.sent.append(data)
|
||||
self._buf += _ack(_payload(data)[2])
|
||||
|
||||
def read(self, n):
|
||||
out, self._buf = self._buf[:n], self._buf[n:]
|
||||
return out
|
||||
|
||||
|
||||
def _proto():
|
||||
t = Acks()
|
||||
return mp.MiniMateProtocol(t), t
|
||||
|
||||
|
||||
def test_the_event_index_block_as_read_is_written_as_blastware_wrote_it():
|
||||
p, t = _proto()
|
||||
block = _image(0x68)[:-2] # the 88 bytes 0x08 returns
|
||||
p.write_event_index(block)
|
||||
assert t.sent == [f for f in SEND2 if _payload(f)[2] == 0x68]
|
||||
|
||||
|
||||
def test_the_trigger_block_as_read_is_written_as_blastware_wrote_it():
|
||||
p, t = _proto()
|
||||
p.write_trigger_config(_image(0x82)[:-2]) # the 26 bytes 0x2E returns
|
||||
assert t.sent == [f for f in SEND2 if _payload(f)[2] == 0x82]
|
||||
|
||||
|
||||
def test_the_compliance_image_goes_in_blastwares_chunks_then_the_confirm():
|
||||
p, t = _proto()
|
||||
p.write_compliance_config_raw(_image(0x71))
|
||||
want = [f for f in SEND2 if _payload(f)[2] == 0x71]
|
||||
assert t.sent[:-1] == want
|
||||
assert _payload(t.sent[-1])[2] == 0x72
|
||||
|
||||
|
||||
def test_the_waveform_data_block_is_written_as_given():
|
||||
p, t = _proto()
|
||||
p.write_waveform_data(_image(0x69))
|
||||
assert t.sent == [f for f in SEND2 if _payload(f)[2] == 0x69]
|
||||
|
||||
|
||||
def test_an_image_in_the_parsers_form_is_unescaped_first():
|
||||
# what a read hands over: the parser keeps the 10 of 10 02/03/04
|
||||
p, t = _proto()
|
||||
img = _image(0x71)
|
||||
parser_form = img.replace(b"\x03", b"\x10\x03").replace(b"\x04", b"\x10\x04")
|
||||
assert unescape_reply(parser_form) == img and parser_form != img
|
||||
p.write_compliance_config_raw(parser_form)
|
||||
assert t.sent[:-1] == [f for f in SEND2 if _payload(f)[2] == 0x71]
|
||||
|
||||
|
||||
def test_a_stray_byte_is_refused_before_anything_is_sent():
|
||||
# the encoder's old hazard: a value changed beside a kept escape byte leaves a
|
||||
# lone 10 behind -- the image is then one byte longer than its header says
|
||||
p, t = _proto()
|
||||
img = _image(0x71)
|
||||
with pytest.raises(ValueError, match="not a whole block"):
|
||||
p.write_compliance_config_raw(img[:6] + b"\x10" + img[6:])
|
||||
assert t.sent == []
|
||||
|
||||
|
||||
class Replies:
|
||||
"""Answers each request with the unit's next recorded reply of the right SUB."""
|
||||
|
||||
def __init__(self):
|
||||
raw, start, p = (FIX / "unit_replies.bin").read_bytes(), 0, S3FrameParser()
|
||||
self.by_sub, self.sent, self._buf = {}, [], b""
|
||||
for i in range(len(raw)):
|
||||
for f in p.feed(raw[i:i + 1]):
|
||||
w = raw[start:i + 1]
|
||||
self.by_sub.setdefault(f.sub, []).append(w[w.index(b"\x10\x02"):])
|
||||
start = i + 1
|
||||
|
||||
def write(self, data):
|
||||
data = bytes(data)
|
||||
self.sent.append(data)
|
||||
self._buf += self.by_sub[(0xFF - _payload(data)[2]) & 0xFF].pop(0)
|
||||
|
||||
def read(self, n):
|
||||
out, self._buf = self._buf[:n], self._buf[n:]
|
||||
return out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("read,sub,size", [("read_event_index", 0x68, 88),
|
||||
("read_trigger_config", 0x82, 26),
|
||||
("read_waveform_data_raw", 0x69, 202)])
|
||||
def test_each_read_returns_the_block_blastware_then_wrote(read, sub, size):
|
||||
"""A 02/03/04/10 inside a block arrives escaped; a slice of the parser's output
|
||||
by length came up short. The reads return the unescaped block -- the bytes
|
||||
Blastware wrote back (the waveform-data read includes its 2 trailing bytes,
|
||||
which Blastware replaced)."""
|
||||
block = getattr(mp.MiniMateProtocol(Replies()), read)()
|
||||
assert len(block) == size
|
||||
want = _image(sub)
|
||||
assert block[:-2] == want[:-2] if sub == 0x69 else block == want[:-2]
|
||||
|
||||
|
||||
# -- apply_config writes this unit's own trigger block ---------------------------
|
||||
|
||||
class StubProto:
|
||||
"""Serves BE9441's blocks as read on 2026-10-26; records every write."""
|
||||
|
||||
def __init__(self):
|
||||
self.writes = []
|
||||
|
||||
def read_event_index(self):
|
||||
return _image(0x68)[:-2]
|
||||
|
||||
def read_compliance_config(self):
|
||||
return _image(0x71)[:-2]
|
||||
|
||||
def read_waveform_data_raw(self):
|
||||
return _image(0x69)
|
||||
|
||||
def read_trigger_config(self):
|
||||
return _image(0x82)[:-2]
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name.startswith("write_"):
|
||||
return lambda *a, **k: self.writes.append((name, a))
|
||||
raise AttributeError(name)
|
||||
|
||||
|
||||
def test_apply_config_writes_the_units_own_trigger_block():
|
||||
from minimateplus.client import MiniMateClient
|
||||
c = MiniMateClient(transport=object())
|
||||
c._proto = StubProto()
|
||||
c.apply_config() # nothing changed: a round trip
|
||||
trig = [a[0] for n, a in c._proto.writes if n == "write_trigger_config"]
|
||||
assert trig == [_image(0x82)[:-2]]
|
||||
assert trig[0][5] == 0x01 # BE9441's; the March copy had 0x03
|
||||
+66
-398
@@ -1,26 +1,19 @@
|
||||
"""
|
||||
test_write_frames.py — Verify write frame construction against BW capture.
|
||||
test_write_frames.py — the 3-11-26/170151 Blastware config write, read correctly.
|
||||
|
||||
Validates that build_bw_write_frame() reproduces the exact wire bytes that
|
||||
Blastware sent during the 3-11-26/170151 compliance-config write session.
|
||||
Frames 102–112 of raw_bw_20260311_170151.bin: 68, 73, 71×3, 72, 82, 83, 69, 74, 72.
|
||||
|
||||
Frames tested (BW TX frame indices 102–112):
|
||||
102 — SUB 0x68 event index write
|
||||
103 — SUB 0x73 confirm B
|
||||
104 — SUB 0x71 compliance write chunk 1
|
||||
105 — SUB 0x71 compliance write chunk 2
|
||||
106 — SUB 0x71 compliance write chunk 3
|
||||
107 — SUB 0x72 confirm A
|
||||
108 — SUB 0x82 trigger config write
|
||||
109 — SUB 0x83 trigger confirm
|
||||
110 — SUB 0x69 waveform data write
|
||||
111 — SUB 0x74 confirm C
|
||||
112 — SUB 0x72 confirm A (end of sequence)
|
||||
⚠ REWRITTEN 2026-10-27 (#46). This file pinned a model of these frames that was
|
||||
wrong: "only BW_CMD is doubled", a "DLE-aware checksum", compliance chunks of
|
||||
1,027 / 1,055 bytes at "offset 0x1004", single-block "offset = data[1] + 2".
|
||||
Every one of those read the frames with their escape bytes still in. Decoded
|
||||
as every Blastware request decodes (each 02/03/04/10 escaped, SUM8 of the
|
||||
payload), these frames are ordinary requests: a LENGTH at [4:6] equal to the
|
||||
data's length, the compliance image in 1,024-byte chunks addressed by
|
||||
params[2:4], and blocks of N + 2 bytes. tests/test_minimate_write_frames.py
|
||||
covers every write on record, tonight's 26 frames included.
|
||||
|
||||
Run:
|
||||
python -m pytest tests/test_write_frames.py -v
|
||||
or:
|
||||
python tests/test_write_frames.py
|
||||
Skips when the capture is absent.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,407 +23,82 @@ import sys
|
||||
|
||||
import pytest
|
||||
|
||||
# Allow running from the project root without installation
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from minimateplus.framing import build_bw_write_frame
|
||||
|
||||
|
||||
# ── Capture loading ────────────────────────────────────────────────────────────
|
||||
from minimateplus.framing import build_bw_write_frame, checksum
|
||||
|
||||
CAPTURE_PATH = os.path.join(
|
||||
os.path.dirname(__file__),
|
||||
"..",
|
||||
"bridges",
|
||||
"captures",
|
||||
"3-11-26",
|
||||
"raw_bw_20260311_170151.bin",
|
||||
os.path.dirname(__file__), "..", "bridges", "captures", "3-11-26", "raw_bw_20260311_170151.bin",
|
||||
)
|
||||
|
||||
|
||||
def _load_bw_frames(path: str) -> list[bytes]:
|
||||
"""
|
||||
Parse a raw BW capture file into a list of BW frames.
|
||||
|
||||
BW frames start with ACK=0x41 followed by STX=0x02. The frame boundary is
|
||||
the position of the NEXT 0x41 0x02 sequence (the ETX=0x03 terminator is the
|
||||
last byte before the next frame start).
|
||||
|
||||
NOTE: A naive scan for ETX=0x03 fails because 0x03 can appear inside the
|
||||
DLE-stuffed payload. This parser uses consecutive 0x41 0x02 starts as
|
||||
boundaries, which is safe because the ACK byte (0x41) is never DLE-stuffed.
|
||||
"""
|
||||
with open(path, "rb") as f:
|
||||
raw = f.read()
|
||||
|
||||
boundaries: list[int] = []
|
||||
i = 0
|
||||
while i < len(raw) - 1:
|
||||
if raw[i] == 0x41 and raw[i + 1] == 0x02:
|
||||
boundaries.append(i)
|
||||
i += 1
|
||||
boundaries.append(len(raw))
|
||||
|
||||
frames = []
|
||||
for k in range(len(boundaries) - 1):
|
||||
frames.append(raw[boundaries[k] : boundaries[k + 1]])
|
||||
return frames
|
||||
|
||||
|
||||
def _destuff(data: bytes) -> bytes:
|
||||
"""Undo DLE stuffing: replace every 0x10 0x10 pair with a single 0x10."""
|
||||
result = bytearray()
|
||||
k = 0
|
||||
while k < len(data):
|
||||
if data[k] == 0x10 and k + 1 < len(data) and data[k + 1] == 0x10:
|
||||
result.append(0x10)
|
||||
k += 2
|
||||
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:
|
||||
result.append(data[k])
|
||||
k += 1
|
||||
return bytes(result)
|
||||
out.append(b[k]); k += 1
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _decode_bw_frame(wire: bytes) -> tuple[int, int, bytes, bytes, int]:
|
||||
"""
|
||||
Decode a BW wire frame into its components.
|
||||
def _frames(raw: bytes) -> list:
|
||||
out, i = [], 0
|
||||
while i < len(raw):
|
||||
if raw[i:i + 2] == b"\x41\x03":
|
||||
i += 2
|
||||
continue
|
||||
if raw[i:i + 2] != b"\x41\x02":
|
||||
i += 1
|
||||
continue
|
||||
j = i + 2
|
||||
while j < len(raw) and raw[j] != 0x03:
|
||||
j += 2 if raw[j] == 0x10 else 1
|
||||
out.append(raw[i:j + 1])
|
||||
i = j + 1
|
||||
return out
|
||||
|
||||
Returns:
|
||||
(sub, offset, params, data, chk)
|
||||
sub — SUB byte (payload[2])
|
||||
offset — uint16 from payload[4:6]
|
||||
params — 10-byte params field (payload[6:16])
|
||||
data — write payload bytes (payload[16:-1])
|
||||
chk — checksum byte (payload[-1])
|
||||
"""
|
||||
inner = wire[2:-1] # strip ACK+STX and trailing ETX
|
||||
payload = _destuff(inner)
|
||||
sub = payload[2]
|
||||
offset = (payload[4] << 8) | payload[5]
|
||||
params = payload[6:16]
|
||||
data = payload[16:-1]
|
||||
chk = payload[-1]
|
||||
return sub, offset, params, data, chk
|
||||
|
||||
|
||||
# ── Test fixtures ──────────────────────────────────────────────────────────────
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def bw_frames() -> list[bytes]:
|
||||
def writes() -> list:
|
||||
if not os.path.exists(CAPTURE_PATH):
|
||||
pytest.skip(f"Capture file not found: {CAPTURE_PATH}")
|
||||
return _load_bw_frames(CAPTURE_PATH)
|
||||
frames = _frames(open(CAPTURE_PATH, "rb").read())
|
||||
w = [f for f in frames if 0x68 <= _unstuff(f[2:-1])[2] <= 0x83]
|
||||
assert [f"{_unstuff(f[2:-1])[2]:02X}" for f in w] == \
|
||||
["68", "73", "71", "71", "71", "72", "82", "83", "69", "74", "72"]
|
||||
return w
|
||||
|
||||
|
||||
# ── Individual frame tests ─────────────────────────────────────────────────────
|
||||
def _fields(frame: bytes):
|
||||
p = _unstuff(frame[2:-1])
|
||||
payload, chk = p[:-1], p[-1]
|
||||
return payload[2], int.from_bytes(payload[4:6], "big"), payload[6:16], payload[16:], chk, payload
|
||||
|
||||
class TestWriteFrameReconstruction:
|
||||
"""Verify build_bw_write_frame() reproduces the exact wire bytes from the capture."""
|
||||
|
||||
def test_frame_102_event_index_write_sub68(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x68 — event index write (frame 102)."""
|
||||
cap_wire = bw_frames[102]
|
||||
sub_cap, offset_cap, params_cap, data_cap, chk_cap = _decode_bw_frame(cap_wire)
|
||||
def test_every_frame_is_an_ordinary_request_with_a_sum8_checksum(writes):
|
||||
for f in writes:
|
||||
sub, length, params, data, chk, payload = _fields(f)
|
||||
assert chk == checksum(payload)
|
||||
assert build_bw_write_frame(sub, data, params=params) == f
|
||||
|
||||
assert sub_cap == 0x68
|
||||
assert params_cap == bytes(10)
|
||||
|
||||
# Reconstruct using build_bw_write_frame with the same data and offset
|
||||
built = build_bw_write_frame(0x68, data_cap, offset=offset_cap, params=params_cap)
|
||||
assert built == cap_wire, (
|
||||
f"SUB 0x68 wire mismatch\n"
|
||||
f" built: {built.hex()}\n"
|
||||
f" capt: {cap_wire.hex()}"
|
||||
)
|
||||
def test_the_length_field_is_the_datas_length(writes):
|
||||
for f in writes:
|
||||
sub, length, params, data, chk, _ = _fields(f)
|
||||
assert length == len(data)
|
||||
|
||||
def test_frame_103_confirm_b_sub73(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x73 — confirm B (zero-data confirm frame 103)."""
|
||||
cap_wire = bw_frames[103]
|
||||
sub_cap, offset_cap, params_cap, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
assert sub_cap == 0x73
|
||||
assert data_cap == b""
|
||||
assert offset_cap == 0x0000
|
||||
def test_single_blocks_are_their_header_plus_two(writes):
|
||||
for f in writes:
|
||||
sub, length, params, data, chk, _ = _fields(f)
|
||||
if sub in (0x68, 0x82, 0x69):
|
||||
assert len(data) == int.from_bytes(data[:2], "big") + 2
|
||||
|
||||
built = build_bw_write_frame(0x73, b"")
|
||||
assert built == cap_wire
|
||||
|
||||
def test_frame_104_compliance_chunk1_sub71(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x71 chunk 1 — 1027-byte compliance write (frame 104)."""
|
||||
cap_wire = bw_frames[104]
|
||||
sub_cap, offset_cap, params_cap, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
assert sub_cap == 0x71
|
||||
assert offset_cap == 0x1004
|
||||
assert params_cap == bytes(10)
|
||||
assert len(data_cap) == 1027
|
||||
|
||||
built = build_bw_write_frame(
|
||||
0x71, data_cap,
|
||||
offset=0x1004,
|
||||
params=bytes(10),
|
||||
)
|
||||
assert built == cap_wire
|
||||
|
||||
def test_frame_105_compliance_chunk2_sub71(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x71 chunk 2 — 1055-byte compliance write (frame 105)."""
|
||||
cap_wire = bw_frames[105]
|
||||
sub_cap, offset_cap, params_cap, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
_CHUNK2_PARAMS = bytes([0x00, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00])
|
||||
|
||||
assert sub_cap == 0x71
|
||||
assert offset_cap == 0x1004
|
||||
assert params_cap == _CHUNK2_PARAMS
|
||||
assert len(data_cap) == 1055
|
||||
|
||||
built = build_bw_write_frame(
|
||||
0x71, data_cap,
|
||||
offset=0x1004,
|
||||
params=_CHUNK2_PARAMS,
|
||||
)
|
||||
assert built == cap_wire
|
||||
|
||||
def test_frame_106_compliance_chunk3_sub71(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x71 chunk 3 — 46-byte compliance write (frame 106)."""
|
||||
cap_wire = bw_frames[106]
|
||||
sub_cap, offset_cap, params_cap, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
_CHUNK3_PARAMS = bytes([0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
|
||||
|
||||
assert sub_cap == 0x71
|
||||
assert offset_cap == 0x002C
|
||||
assert params_cap == _CHUNK3_PARAMS
|
||||
assert len(data_cap) == 46
|
||||
|
||||
built = build_bw_write_frame(
|
||||
0x71, data_cap,
|
||||
offset=0x002C,
|
||||
params=_CHUNK3_PARAMS,
|
||||
)
|
||||
assert built == cap_wire
|
||||
|
||||
def test_frame_107_confirm_a_sub72(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x72 — confirm A after compliance write (frame 107)."""
|
||||
cap_wire = bw_frames[107]
|
||||
sub_cap, offset_cap, params_cap, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
assert sub_cap == 0x72
|
||||
assert data_cap == b""
|
||||
assert offset_cap == 0x0000
|
||||
|
||||
built = build_bw_write_frame(0x72, b"")
|
||||
assert built == cap_wire
|
||||
|
||||
def test_frame_108_trigger_config_write_sub82(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x82 — trigger config write (frame 108)."""
|
||||
cap_wire = bw_frames[108]
|
||||
sub_cap, offset_cap, params_cap, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
assert sub_cap == 0x82
|
||||
assert params_cap == bytes(10)
|
||||
assert len(data_cap) == 29
|
||||
|
||||
# Verify offset formula: data[1] + 2
|
||||
assert offset_cap == data_cap[1] + 2, (
|
||||
f"Trigger write offset formula mismatch: "
|
||||
f"data[1]={data_cap[1]} → expected {data_cap[1]+2}, got {offset_cap}"
|
||||
)
|
||||
|
||||
built = build_bw_write_frame(
|
||||
0x82, data_cap,
|
||||
offset=offset_cap,
|
||||
params=params_cap,
|
||||
)
|
||||
assert built == cap_wire
|
||||
|
||||
def test_frame_109_trigger_confirm_sub83(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x83 — trigger confirm (frame 109)."""
|
||||
cap_wire = bw_frames[109]
|
||||
sub_cap, _, _, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
assert sub_cap == 0x83
|
||||
assert data_cap == b""
|
||||
|
||||
built = build_bw_write_frame(0x83, b"")
|
||||
assert built == cap_wire
|
||||
|
||||
def test_frame_110_waveform_data_write_sub69(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x69 — waveform data write (frame 110)."""
|
||||
cap_wire = bw_frames[110]
|
||||
sub_cap, offset_cap, params_cap, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
assert sub_cap == 0x69
|
||||
assert params_cap == bytes(10)
|
||||
assert len(data_cap) == 204
|
||||
|
||||
# Verify offset formula: data[1] + 2
|
||||
assert offset_cap == data_cap[1] + 2, (
|
||||
f"Waveform write offset formula mismatch: "
|
||||
f"data[1]={data_cap[1]} → expected {data_cap[1]+2}, got {offset_cap}"
|
||||
)
|
||||
|
||||
built = build_bw_write_frame(
|
||||
0x69, data_cap,
|
||||
offset=offset_cap,
|
||||
params=params_cap,
|
||||
)
|
||||
assert built == cap_wire
|
||||
|
||||
def test_frame_111_confirm_c_sub74(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x74 — confirm C after waveform data write (frame 111)."""
|
||||
cap_wire = bw_frames[111]
|
||||
sub_cap, _, _, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
assert sub_cap == 0x74
|
||||
assert data_cap == b""
|
||||
|
||||
built = build_bw_write_frame(0x74, b"")
|
||||
assert built == cap_wire
|
||||
|
||||
def test_frame_112_confirm_a_sub72_end(self, bw_frames: list[bytes]) -> None:
|
||||
"""SUB 0x72 — final confirm A at end of write sequence (frame 112)."""
|
||||
cap_wire = bw_frames[112]
|
||||
sub_cap, _, _, data_cap, _ = _decode_bw_frame(cap_wire)
|
||||
|
||||
assert sub_cap == 0x72
|
||||
assert data_cap == b""
|
||||
|
||||
built = build_bw_write_frame(0x72, b"")
|
||||
assert built == cap_wire
|
||||
|
||||
|
||||
class TestOffsetFormula:
|
||||
"""Verify the offset = data[1] + 2 formula for single-chunk write commands."""
|
||||
|
||||
def test_event_index_offset_formula(self, bw_frames: list[bytes]) -> None:
|
||||
"""Frame 102 (SUB 0x68): offset = data[1] + 2."""
|
||||
_, offset_cap, _, data_cap, _ = _decode_bw_frame(bw_frames[102])
|
||||
assert offset_cap == data_cap[1] + 2
|
||||
|
||||
def test_trigger_config_offset_formula(self, bw_frames: list[bytes]) -> None:
|
||||
"""Frame 108 (SUB 0x82): offset = data[1] + 2."""
|
||||
_, offset_cap, _, data_cap, _ = _decode_bw_frame(bw_frames[108])
|
||||
assert offset_cap == data_cap[1] + 2
|
||||
|
||||
def test_waveform_data_offset_formula(self, bw_frames: list[bytes]) -> None:
|
||||
"""Frame 110 (SUB 0x69): offset = data[1] + 2."""
|
||||
_, offset_cap, _, data_cap, _ = _decode_bw_frame(bw_frames[110])
|
||||
assert offset_cap == data_cap[1] + 2
|
||||
|
||||
|
||||
class TestChecksumVerification:
|
||||
"""Verify large-frame DLE-aware checksum for all write frames."""
|
||||
|
||||
def _verify_checksum(self, wire: bytes, label: str) -> None:
|
||||
inner = wire[2:-1]
|
||||
payload = _destuff(inner)
|
||||
chk = payload[-1]
|
||||
computed = (sum(b for b in payload[2:-1] if b != 0x10) + 0x10) & 0xFF
|
||||
assert computed == chk, (
|
||||
f"{label}: checksum mismatch — computed=0x{computed:02X}, got=0x{chk:02X}"
|
||||
)
|
||||
|
||||
def test_all_write_frame_checksums(self, bw_frames: list[bytes]) -> None:
|
||||
write_frames = {
|
||||
102: "SUB 0x68 event index write",
|
||||
103: "SUB 0x73 confirm B",
|
||||
104: "SUB 0x71 compliance chunk 1",
|
||||
105: "SUB 0x71 compliance chunk 2",
|
||||
106: "SUB 0x71 compliance chunk 3",
|
||||
107: "SUB 0x72 confirm A",
|
||||
108: "SUB 0x82 trigger config write",
|
||||
109: "SUB 0x83 trigger confirm",
|
||||
110: "SUB 0x69 waveform data write",
|
||||
111: "SUB 0x74 confirm C",
|
||||
112: "SUB 0x72 confirm A (end)",
|
||||
}
|
||||
for idx, label in write_frames.items():
|
||||
self._verify_checksum(bw_frames[idx], f"Frame {idx} ({label})")
|
||||
|
||||
|
||||
class TestComplianceChunkSizes:
|
||||
"""Verify compliance write chunk sizes and sequence."""
|
||||
|
||||
def test_chunk1_size(self, bw_frames: list[bytes]) -> None:
|
||||
_, _, _, data, _ = _decode_bw_frame(bw_frames[104])
|
||||
assert len(data) == 1027, f"Chunk 1 should be 1027 bytes, got {len(data)}"
|
||||
|
||||
def test_chunk2_size(self, bw_frames: list[bytes]) -> None:
|
||||
_, _, _, data, _ = _decode_bw_frame(bw_frames[105])
|
||||
assert len(data) == 1055, f"Chunk 2 should be 1055 bytes, got {len(data)}"
|
||||
|
||||
def test_chunk3_size(self, bw_frames: list[bytes]) -> None:
|
||||
_, _, _, data, _ = _decode_bw_frame(bw_frames[106])
|
||||
assert len(data) == 46, f"Chunk 3 should be 46 bytes, got {len(data)}"
|
||||
|
||||
def test_total_compliance_data(self, bw_frames: list[bytes]) -> None:
|
||||
total = sum(
|
||||
len(_decode_bw_frame(bw_frames[i])[3]) for i in [104, 105, 106]
|
||||
)
|
||||
assert total == 2128, f"Total compliance write data should be 2128 bytes, got {total}"
|
||||
|
||||
def test_chunk1_params(self, bw_frames: list[bytes]) -> None:
|
||||
_, _, params, _, _ = _decode_bw_frame(bw_frames[104])
|
||||
assert params == bytes(10)
|
||||
|
||||
def test_chunk2_params(self, bw_frames: list[bytes]) -> None:
|
||||
_, _, params, _, _ = _decode_bw_frame(bw_frames[105])
|
||||
assert params == bytes([0x00, 0x00, 0x00, 0x10, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00])
|
||||
|
||||
def test_chunk3_params(self, bw_frames: list[bytes]) -> None:
|
||||
_, _, params, _, _ = _decode_bw_frame(bw_frames[106])
|
||||
assert params == bytes([0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00])
|
||||
|
||||
def test_chunk1_offset(self, bw_frames: list[bytes]) -> None:
|
||||
_, offset, _, _, _ = _decode_bw_frame(bw_frames[104])
|
||||
assert offset == 0x1004
|
||||
|
||||
def test_chunk2_offset(self, bw_frames: list[bytes]) -> None:
|
||||
_, offset, _, _, _ = _decode_bw_frame(bw_frames[105])
|
||||
assert offset == 0x1004
|
||||
|
||||
def test_chunk3_offset(self, bw_frames: list[bytes]) -> None:
|
||||
_, offset, _, _, _ = _decode_bw_frame(bw_frames[106])
|
||||
assert offset == 0x002C
|
||||
|
||||
|
||||
# ── Standalone runner ──────────────────────────────────────────────────────────
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not os.path.exists(CAPTURE_PATH):
|
||||
print(f"ERROR: Capture file not found: {CAPTURE_PATH}")
|
||||
sys.exit(1)
|
||||
|
||||
frames = _load_bw_frames(CAPTURE_PATH)
|
||||
print(f"Loaded {len(frames)} BW frames from capture")
|
||||
|
||||
write_frame_indices = list(range(102, 113))
|
||||
all_pass = True
|
||||
print()
|
||||
print(f"{'Frame':>6} {'SUB':>5} {'Offset':>8} {'DataLen':>8} {'Chk OK':>7} {'Rebuilt':>8}")
|
||||
print("-" * 60)
|
||||
for idx in write_frame_indices:
|
||||
wire = frames[idx]
|
||||
sub, offset, params, data, chk = _decode_bw_frame(wire)
|
||||
payload = _destuff(wire[2:-1])
|
||||
computed = (sum(b for b in payload[2:-1] if b != 0x10) + 0x10) & 0xFF
|
||||
chk_ok = computed == chk
|
||||
|
||||
built = build_bw_write_frame(sub, data, offset=offset, params=params)
|
||||
rebuilt_ok = built == wire
|
||||
|
||||
status = "✅" if (chk_ok and rebuilt_ok) else "❌"
|
||||
print(
|
||||
f" {idx:4d} 0x{sub:02X} 0x{offset:04X} {len(data):8d} "
|
||||
f"{'✅' if chk_ok else '❌':>7} {'✅' if rebuilt_ok else '❌':>8} {status}"
|
||||
)
|
||||
if not (chk_ok and rebuilt_ok):
|
||||
all_pass = False
|
||||
|
||||
print()
|
||||
if all_pass:
|
||||
print("All 11 write frames verified ✅")
|
||||
else:
|
||||
print("FAILURES DETECTED ❌")
|
||||
sys.exit(1)
|
||||
def test_the_compliance_image_goes_in_1024_byte_chunks_addressed_by_params(writes):
|
||||
chunks = [_fields(f) for f in writes if _fields(f)[0] == 0x71]
|
||||
assert [(length, params[2:4].hex()) for _, length, params, *_ in chunks] == \
|
||||
[(0x400, "0000"), (0x400, "0400"), (0x2C, "0800")]
|
||||
image = b"".join(c[3] for c in chunks)
|
||||
assert len(image) == 2092 and int.from_bytes(image[:2], "big") == 2090
|
||||
Reference in new issue
Block a user