Release v0.35.0 — 80 of 88 report fields from the file, and monitor logs (.MLG) #60

Merged
serversdown merged 50 commits from dev into main 2026-11-16 15:49:06 -05:00
8 changed files with 248 additions and 82 deletions
Showing only changes of commit ff705ebf87 - Show all commits

No files matched your search

+13 -7
View File
@@ -361,9 +361,12 @@ Read this first when picking the project back up.
- ⚠ **A MiniMate's open setup menu wins:** a change sent while it is open is
lost when the operator presses Cancel or Save (the menu writes its whole-block
copy back). The preview warns; nobody in the menus while the office sends.
- ⚠ An escaped checksum byte leaves a stray `0x10` in a Series-3 reply's data
(about 1 frame in 85). The settings and waveform reads take exactly what they
asked for; other reads are unaudited for it.
- ~~⚠ An escaped checksum byte leaves a stray `0x10` in a Series-3 reply's data
(about 1 frame in 85).~~ **Fixed in the parser (#58, 2026-11-06, measured):**
a checksum of 02/03/04 arrives as `10 X`, and that `10` is never data (7,747 /
7,747 recorded replies check). It had misread 1C battery/memory (419.84 V) and
the 2C call-home read; the 5A file builder's own compensation is gone with it,
and pre-fix `.a5.pkl` frames are converted on load (pickle version 2).
- ⚠ The Micromate scheduler switch is not in any block SFM reads, so a leftover
schedule blocks a change even with the scheduler Off.
**Ring path measured the same night:** with THOR's watchdog off, a call-home
@@ -496,9 +499,11 @@ Read this first when picking the project back up.
retracted 5A model: SUB 71's "offset 0x1004" reads as length 0x0400 escaped, and
Blastware escapes `03` in write data. A write whose payload holds a bare
02/03/04/10 may be malformed. One Blastware config-write capture settles it.
🔑 **Replies follow the same rule (measured, 748/748):** every 02/03/04/10 escaped,
checksum = SUM8 of the unescaped payload. The "S3 checksums frequently fail" belief
is `S3FrameParser` summing its output with the `10` of `10 02/03/04` still in it.
🔑 **Replies follow the same rule (measured, 748/748; 7,747 / 7,747 across every
recording, #58):** every 02/03/04/10 escaped, the checksum too, and checksum = SUM8
of the unescaped payload. The "S3 checksums frequently fail" belief was
`S3FrameParser` summing its output with the `10` of `10 02/03/04` still in it
(fixed 2026-11-06: `checksum_valid` holds on every recorded reply).
~~**⚠ KNOWN BUG — the 5A walk breaks once a unit's buffer crosses 64 KB.**~~
`parse_strt_end_offset()` returns only `(end_key[2] << 8) | end_key[3]`,
discarding the key's page byte. An event starting at `0x0111F2A2` and ending
@@ -2048,7 +2053,8 @@ A re-analysis in the prior session incorrectly concluded `section[1]` is always
and is device-specific. The 2026-04-09 re-analysis confirms `section[1]` was right.
**IMPORTANT — `frame.data` has checksum already stripped** by `S3FrameParser._finalise()`
(`raw_payload = body[:-1]`; `data = raw_payload[5:]`). There is NO trailing checksum byte in
(`raw_payload` = the body less its checksum, and less the `10` of an escaped one since #58;
`data = raw_payload[5:]`). There is NO trailing checksum byte in
`section`. All relative-from-end offsets must account for this.
Battery and memory fields are present in **both** states:
+1
View File
@@ -15,6 +15,7 @@
| 2026-11-09 | Appendix D.6.15 (NEW), D.6.6, D.6.11 | ✅ **Over range and the mic.** **D.6.15:** a peak past full scale (2,000 units = 32,000 counts; the mic in counts) is Blastware's `OORANGE`, per channel and per histogram interval, from the unit's own summary peaks. The vector sum is `OORANGE` exactly when a geophone is (43 / 43); never on its own (38 / 38 numeric), which retracts D.6.11's open "vector sum alone" case. The `<OORANGE>` line marks the mic over (18 / 18). **D.6.6:** the mic has its own range byte (label + 29): at 1 a count is an eighth, 7 DL2 events SFM read 8× high. The dB offset is **81.938216**: [81.9383, 81.9385] was too high, and every count Blastware printed leaves [81.9382058, 81.9382266]. Blastware's mic unit labels do not hold on every report; some mix dB and psi in one column. **80 of 88 report fields now match on every DL2 event.** |
| 2026-11-08 | Appendix D.6.14 (NEW), D.3.3, D.6.11 | ✅ **The monitor log is in the footer.** Every DL2 report prints one Monitor Log line: the footer's ts1 and ts2, then words for the footer's flag word `[18:20]` (`0x0001` Event Recorded, `0x0002` Keyboard Exit, `0x0004` Remote Exit, `0x0008` Selfcheck Passed, `0x0010` Timer Stop, `0x0020` Modem Exit, `0x0200` Battery Low Exit, `0x0800` Memory Full Exit; the higher session-end bit wins, from one file). Rebuilt, it equals Blastware's character for character on 69,983 / 69,983. **D.3.3:** footer `[20:22]` is the trigger source again, `[22:24]` is zero; `[24:26]` still unknown, and no common CRC-16 or sum fits. **72 of 88 report fields now match on every DL2 event.** |
| 2026-11-06 | Appendix D.6.13 (NEW), D.3.3, D.6.11, D.6.12 | ✅ **The record chain to the footer, and the sensor check.** Walked from the event record, the chain (event `0x05` → unit's summary `0x32`–`0x35` → sensor checks `0x3c`–`0x3f` → footer `0x0e`) ends exactly at the file's end on all 70,041 DL2 files. The footer is its last record: `00 1a` is its length, `0e` its id. **Each sensor-check record's header holds the unit's results:** channel type `[2]`, status `[4]` (0 = passed), frequency × 10 `[5:7]`, ratio × 10 `[7:9]` and amplitude mV `[9:11]`. Blastware prints them as they are: 209,943 / 209,943 geophone frequencies and ratios, 69,975 / 69,975 mic frequencies and amplitudes. The result is Passed / Check / Disabled by status and type. The status is the unit's own verdict, its bits not decoded. D.6.12's "`0x3c` / `0x3d`, before and after" retracted in place: one record per channel. **71 of 88 report fields now match on every DL2 event.** |
| 2026-11-06 (2) | §3 (replies), SUB 1C, 2C, 15, 5A file build | ✅ **An escaped checksum is the checksum, not data (#58, measured).** A reply whose checksum is 02, 03 or 04 sends it as `10 X`, and `S3FrameParser` kept that `10` as the frame's last data byte (first seen on BE9441's 1A read, 2026-11-04). **Across every recorded reply** (60 captures, March to October 2026, three units) SUM8 of the unescaped payload is the checksum on **7,747 / 7,747**, widening 2026-10-26 (4)'s 748 / 748. **272** checksums arrived escaped; every one checks as an escape pair, and no checksum ever arrived as a bare 02/03/04. **What the stray byte did:** **SUB 1C** battery and memory are counted from the end, so 12 of 760 recorded status replies read 419.84 V and 251,654,656 bytes (for 6.76 V and 983,026). A **SUB 2C** call-home read came out one byte long and was refused as "monitoring". The **SUB 15 probe reply** (`00 00 00 00 0a …`, the same on BE11529, BE18189 and BE9441) always has an escaped checksum: 230 of the 272, harmless, as nothing reads it. The **5A file builder** had compensated since 2026-04-21 (the "split pair" rule). With the parser fixed, that rule would drop a real `0x10` ending a chunk (one A5 chunk in ten ends in one; none recorded with an escaped checksum as well), so it is removed. The 1A and 09 reads' length trims (2026-11-04) stay as guards. `checksum_valid` now sums the unescaped payload, and every recorded reply checks. |
| 2026-11-05 | Appendix D.6.12 (NEW), D.6.11, §7.8.9 | ✅ **The unit's own event summary, in every event file.** The embedded event record is the first of a `[length][id][payload]` chain. It holds the vector-sum peak's sample (6,492 / 6,493). Then one 22-byte record per channel, ids `0x32` Tran … `0x35` MicL: min, max, peak sample, **half-period** and a **displacement integral**. Blastware prints them as they are. **ZC frequency** = (rate / 2) / half-period, with the interval rule's words: 25,966 / 25,966 waveform and 253,958 / 253,958 histogram channel values. **Peak displacement** = half the integral: 19,479 / 19,479. Recomputing from the samples had reached 46% and 84%: the unit works at full resolution. **Times of peak** follow the unit's peak sample. That differs from the samples only on **O117I1NK.R70W**, whose stored samples wrap at the trigger by 65,536 counts (Blastware's own table has the same values). Peak acceleration is Blastware's own computation from the stored samples (group D part 1, documented here too). The unit stores its own largest step at `[15:21]` (inferred), which Blastware does not print. §7.8.9's "constant, meaning ❓" bytes amended in place. 59 of 88 report fields now match on every DL2 event (47 before group D). |
| 2026-11-04 | SUB 1A / 09 reads, SUB 68–74 settings write, the keypad | **SFM's settings write, benched on BE9441 (Brian at the unit; ~12 writes, each with his go).** **Every write** -- trigger 0.04 ↔ 0.05, a note, several fields at once (Project, job number + its report flag, trigger), the alarm 1.0 ↔ 1.5, and a full restore -- was acknowledged on all nine steps (`97 8C 8E×5 8D 7D 7C 96 8B 8D`), read back as sent, and **confirmed on the unit's own screen**; the unit ended byte for byte as found. Moved bytes were exactly the field's: trigger f32 at each geophone channel +30 (`+31..+33` moved), **alarm f32 at channel +38** (`+39` moved; the first Series-3 alarm write), job number `[40:42]`, its report bit `[39]` `0x02`, a note's value window. **`[26:28]`** went `01 7f` → `00 00` on SFM's first write (Blastware's value) and the unit **set `01 7f` again during the next monitoring session**. The **two bytes after the block** went out as `00 00` (Blastware sends a per-unit constant) and were taken. **🔑 Escaped-checksum artifact:** when a reply's checksum byte is itself escaped (02 / 03 / 04, ~1 frame in 85), `S3FrameParser` keeps the escape's `0x10` and strips only the byte after it, so the frame's data gains one trailing `0x10`. It hit the first live 1A read (frame B 1,026 bytes after the header); the 12 recorded reads never had. SFM's settings read and waveform read now take exactly the length they asked for. **🔑 The keypad menu wins:** a write sent while the setup menu was open was acknowledged and read back, then **lost when the operator pressed Cancel or Save** -- the menu writes its own copy of the **whole** block back (both times the block returned byte for byte to its state when the menu was opened). A keypad Cancel with nothing pending leaves the block unchanged. **While monitoring**, the 1A read returns the device-info block (SFM refuses, nothing sent), and the opening poll was answered only intermittently (2 of 3 attempts timed out). Code: `minimateplus.protocol.read_compliance_content` / `read_waveform_data_raw`, `micromate.setup_fields`; notes `~/bench-logs/2026-11-04-sfm-settings/`. |
| 2026-11-03 (5) | SUB 1A / 71 / 69 (settings read and write) | **The settings block, read and written as content (measured, BE9441's 10-26 recording and BE11529's 2026-04-20 captures).** **Read:** unescape each 1A data frame and take `data[11:]`; every frame but the last starts with one `00` that is not content; dropped, the frames join into **2,090 bytes headed by N = 2090: Series IV's `0x1A` content layout** (12 / 12 reads, Blastware's 4 × 512 + 42 and SFM's 1024 + 1024 + 42). The old "stable anchor" `be 80 00 00 00 00` is content `[12:18]` (pre-trigger −0.25 + stop mode Fixed). **Round trip:** the read after each of Blastware's two 10-26 writes equals the image it had just written, all 2,090 bytes (2 / 2). While monitoring, the read returns the device-info block (`0e 'BE9441' …`, 5 / 5). **`[26:28]`:** Blastware writes `00 00` on all 11 writes; the unit reads `01 7f` after a monitoring session (BE9441 10-26, BE11529 4-20 15:19) and sets it by itself; meaning unknown. **The two bytes after the block** (`[2090:2092]` of the 0x71 image) are Blastware's own per-unit constant -- `7c ea` on all nine of BE11529's writes, `0c e9` on both of BE9441's -- not the block's CRC-16/AUG, and in no reply of BE9441's three-hour session; SFM sends `00 00`. **`0x09` `[200:202]`:** Blastware echoed the unit's `8c 76` on all nine April writes; on 10-26 it read `17 17` and wrote `78 76` (read back so); meaning unknown. **Blastware re-renders the mic trigger level:** on BE11529's first write (4-20 15:19) the unit read 0.005 and 0.01 psi in its two `MicL` channel blocks (3 and 7; Series 3 carries 8 channel blocks of 48 bytes from `[1708]`, the second four prefixed `0x32`) and Blastware wrote 0.004983 and 0.010058 -- the same levels to its 0.1 dB; every other write left them alone. **Every one of the 11 Blastware writes reproduces** from the block before it with only the fields Blastware changed (plus that re-render and, on 10-26, the mic bit of `[25]`). Code: `minimateplus.protocol.assemble_compliance_content`, `read_compliance_content`, `micromate.setup_fields`; tests `tests/test_s3_settings_read.py`, `tests/test_setup_fields.py`. |
+12 -52
View File
@@ -104,17 +104,11 @@ M529LIY6 (example event) using raw_s3_20260403_153508.bin capture):
DLE strip rule (applied AFTER slicing):
Strip any 0x10 byte that is immediately followed by 0x02, 0x03, or 0x04.
This undoes the DLE-escape that S3FrameParser preserves as literal pairs.
Applied to frame.data[skip:] + bytes([frame.chk_byte]) together, then
conditionally exclude the trailing chk_byte from the output.
chk_byte absorption:
When frame.data[-1] == 0x10 AND frame.chk_byte ∈ {0x02, 0x03, 0x04},
the last byte of frame.data is the DLE prefix of a split DLE+chk pair.
Including chk_byte in the strip buffer allows the pair to be stripped as
a unit. After stripping, the trailing chk_byte is ALWAYS removed — because
_strip_inner_frame_dles keeps the byte after the DLE (the chk_byte value),
and that value is the checksum, never payload. This applies to all three
cases (chk ∈ {0x02, 0x03, 0x04}) identically.
chk_byte absorption (retired 2026-11-06, #58):
The escape 0x10 of a checksum sent as `10 02/03/04` used to stay at the end
of frame.data, and this builder dropped it here. The parser now drops it,
so a 0x10 ending frame.data is real data (one A5 chunk in ten ends in one).
MLG CRC:
The algorithm that produces the 2-byte CRC at the start of each MLG record
@@ -297,29 +291,16 @@ def _frame_body_bytes(frame: S3Frame, skip: int) -> bytes:
Extract the waveform body contribution from one A5 S3Frame.
The contribution is frame.data[skip:] with inner-frame DLE pairs stripped
per _strip_inner_frame_dles(). The chk_byte is temporarily appended before
stripping to handle the split-pair edge case where a DLE at the end of
frame.data is paired with chk_byte.
per _strip_inner_frame_dles().
Split-pair edge case (confirmed for A5[8] of M529LIY6 (example event), 2026-04-21):
S3FrameParser appends DLE+XX pairs as two literal bytes when XX ∉ {DLE, ETX}.
When the LAST occurrence of such a pair straddles the payload/checksum boundary
(i.e., DLE is the last byte of raw_payload and XX is the checksum), the parser
splits them:
- DLE ends up as the last byte of frame.data (frame.data[-1] == 0x10)
- XX is stored as frame.chk_byte
To strip the pair correctly, we reunite the bytes before calling the strip
function. Since chk_byte is the checksum (not payload data), it is excluded
from the final output regardless of whether it was part of a pair.
Post-strip chk_byte removal (ALL cases):
_strip_inner_frame_dles strips the 0x10 and KEEPS chk_byte in all cases.
Chk_byte is always the checksum (not payload), so always strip it off.
Until #58 (2026-11-06) an escaped checksum (`10 02/03/04`) left its 0x10 as
the last byte of frame.data, and this function dropped it by pairing it with
chk_byte (first seen on A5[8] of M529LIY6, 2026-04-21). The parser drops it
now, so a 0x10 here is data and is kept.
Args:
frame: S3Frame with frame.data and frame.chk_byte populated.
frame: S3Frame from S3FrameParser (or a store pickle loaded by
WaveformStore.load_a5, which converts pre-#58 frames).
skip: Number of leading bytes in frame.data to exclude (frame header).
Returns:
@@ -327,28 +308,7 @@ def _frame_body_bytes(frame: S3Frame, skip: int) -> bytes:
"""
if skip >= len(frame.data):
return b""
relevant = frame.data[skip:]
# Detect split DLE+chk pair at the frame boundary.
has_split_pair = (
len(relevant) > 0
and relevant[-1] == 0x10
and frame.chk_byte in {0x02, 0x03, 0x04}
)
if has_split_pair:
# Reunite the split pair so the strip function sees both bytes together.
buf = relevant + bytes([frame.chk_byte])
stripped = _strip_inner_frame_dles(buf)
# _strip_inner_frame_dles strips the DLE (0x10) and KEEPS chk_byte.
# chk_byte is the received checksum — never payload — so remove it.
# This is correct for all values in {0x02, 0x03, 0x04}.
if stripped:
stripped = stripped[:-1]
return stripped
else:
return _strip_inner_frame_dles(relevant)
return _strip_inner_frame_dles(frame.data[skip:])
# ── Filename helper ───────────────────────────────────────────────────────────
+3 -2
View File
@@ -2354,8 +2354,9 @@ def _decode_monitor_status(data: bytes) -> MonitorStatus:
header, so field offsets below are relative to data[11]).
NOTE: frame.data has the checksum byte already stripped by S3FrameParser
(_finalise returns raw_payload[5:] where raw_payload = body[:-1]).
There is NO trailing checksum byte in section.
(_finalise returns raw_payload[5:], the checksum and, since #58, the 10 of
an escaped checksum removed). There is NO trailing checksum byte in section;
before #58 one status reply in 63 kept that 10 and read 419.84 V.
Monitoring flag (confirmed 4-8-26/2ndtry, byte diff of all 144 data frames):
section[1] == 0x00 → idle
+17 -12
View File
@@ -534,11 +534,13 @@ STRT_MARKER = b"STRT"
def unescape_reply(data: bytes) -> bytes:
"""A reply's data with each kept escape removed: `10 02/03/04` → `02/03/04`.
The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do
(748/748 replies, 2026-10-26). S3FrameParser collapses `10 10` but keeps the
`10` of `10 02/03/04` (inner-frame markers to it), so its `.data` carries an
extra byte before each 02/03/04 value -- harmless for fields read before the
escape, one byte off for any read after it, or counted from the end."""
The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do,
the checksum included (748/748 replies, 2026-10-26; 7,747 / 7,747 across every
recording, March to October 2026, #58). S3FrameParser collapses `10 10` but
keeps the `10` of `10 02/03/04` (inner-frame markers to it) everywhere but the
checksum, so its `.data` carries an extra byte before each 02/03/04 value --
harmless for fields read before the escape, one byte off for any read after it,
or counted from the end."""
out, i = bytearray(), 0
while i < len(data):
if data[i] == DLE and i + 1 < len(data) and data[i + 1] in (STX, ETX, 0x04):
@@ -632,11 +634,8 @@ class S3Frame:
page_lo: int # PAGE_LO from header
data: bytes # payload data section (payload[5:], checksum already stripped)
checksum_valid: bool
chk_byte: int = 0 # actual checksum byte received from wire (body[-1])
# needed for waveform file reconstruction: when the last data byte
# is 0x10 and chk_byte ∈ {0x02, 0x03, 0x04}, the DLE+chk pair
# must be included in the DLE-strip operation to correctly
# reconstruct the Blastware binary body.
chk_byte: int = 0 # actual checksum byte received from wire (body[-1]); an
# escaped one (`10 02/03/04`) leaves no 10 in `data` (#58)
@property
def page_key(self) -> int:
@@ -759,9 +758,15 @@ class S3FrameParser:
if len(body) < 6:
return None
raw_payload = body[:-1] # everything except the trailing checksum byte
# A checksum of 02, 03 or 04 arrives escaped, `10 X`, and _step keeps both
# bytes; that 10 is the escape, never data (#58: 272 of 7,747 recorded
# replies, every one an escape pair). Any other checksum is one byte.
n_chk = 2 if body[-2] == DLE and body[-1] in (STX, ETX, 0x04) else 1
raw_payload = body[:-n_chk] # everything except the checksum
chk_received = body[-1]
chk_computed = checksum(raw_payload)
# SUM8 of the payload unescaped: the kept `10` of a `10 02/03/04` is not
# summed (7,747 of 7,747 recorded replies check this way).
chk_computed = checksum(unescape_reply(raw_payload))
if len(raw_payload) < 5:
return None
+8 -6
View File
@@ -196,10 +196,11 @@ def assemble_compliance_content(frames: "list[bytes]", lengths: "Optional[tuple]
`lengths`: the content each frame was asked for (SFM's read: 1024, 1024, 42).
Each frame then gives exactly that. Measured at the bench 2026-11-04 (BE9441):
when a frame's checksum byte is itself escaped (02 / 03 / 04), the parser keeps
the escape's 0x10 and strips only the byte after it, so the frame arrives one
byte long, ending in a lone 0x10. That one byte is dropped; any other leftover
is kept, and the block then fails is_compliance_content."""
when a frame's checksum byte was itself escaped (02 / 03 / 04), the parser kept
the escape's 0x10, so the frame arrived one byte long, ending in a lone 0x10.
The parser drops it since #58; this trim stays as a guard. That one byte is
dropped; any other leftover is kept, and the block then fails
is_compliance_content."""
parts = [unescape_reply(bytes(f))[11:] for f in frames]
parts = [p[1:] for p in parts[:-1]] + parts[-1:]
if lengths is not None and len(lengths) == len(parts):
@@ -633,8 +634,9 @@ class MiniMateProtocol:
data_rsp = self._recv_one(expected_sub=rsp_sub)
raw = unescape_reply(data_rsp.data)[11:] # unescaped, as read_event_index
# An escaped checksum byte leaves its 0x10 behind (bench 2026-11-04; see
# assemble_compliance_content): one stray byte beyond what was asked is dropped.
# An escaped checksum byte left its 0x10 behind until #58 (bench 2026-11-04;
# see assemble_compliance_content): kept as a guard, one stray byte beyond
# what was asked is dropped.
if len(raw) == length + 1 and raw[-1:] == b"\x10":
raw = raw[:-1]
log.debug("read_waveform_data_raw: got %d bytes", len(raw))
+19 -3
View File
@@ -46,7 +46,19 @@ from sfm.shape_metrics import shape_from_h5, offset_from_h5
log = logging.getLogger("sfm.waveform_store")
A5_PICKLE_VERSION = 1
# 2 (2026-11-06, #58): frames as the parser gives them since an escaped checksum
# stopped leaving its 0x10 in `data`. A version-1 frame with a checksum of 02, 03
# or 04 still ends in that 0x10; load_a5 drops it (_frame_from_v1).
A5_PICKLE_VERSION = 2
def _frame_from_v1(f: S3Frame) -> S3Frame:
"""A frame pickled before #58, as the parser reads its reply now. Its 02/03/04
checksum arrived as `10 X` (every recorded one did), and the 10 ended `data`."""
if f.chk_byte in (0x02, 0x03, 0x04) and f.data[-1:] == b"\x10":
return S3Frame(sub=f.sub, page_hi=f.page_hi, page_lo=f.page_lo, data=f.data[:-1],
checksum_valid=f.checksum_valid, chk_byte=f.chk_byte)
return f
def _frame_to_dict(f: S3Frame) -> dict:
@@ -801,7 +813,8 @@ class WaveformStore:
def load_a5(self, serial: str, filename: str) -> Optional[list[S3Frame]]:
"""
Re-hydrate the pickled A5 frame stream for a stored event.
Re-hydrate the pickled A5 frame stream for a stored event, as the parser
reads it now (a version-1 pickle's frames are converted).
Returns None if the sidecar is missing.
"""
_, a5_path = self.paths_for(serial, filename)
@@ -812,7 +825,10 @@ class WaveformStore:
if not isinstance(payload, dict) or "frames" not in payload:
log.warning("WaveformStore.load_a5: malformed sidecar at %s", a5_path)
return None
return [_dict_to_frame(d) for d in payload["frames"]]
frames = [_dict_to_frame(d) for d in payload["frames"]]
if payload.get("version", 1) < 2:
frames = [_frame_from_v1(f) for f in frames]
return frames
# ── modern .sfm.json sidecar accessors ──────────────────────────────────────
+175
View File
@@ -0,0 +1,175 @@
"""#58: a reply whose checksum byte is 02, 03 or 04 arrives as `10 X`.
The unit escapes 02, 03, 04 and 10 in a reply, the checksum included. The
parser kept the `10` of an escaped checksum as the frame's last data byte, so
the data came out one byte long, ending in a lone 0x10 (measured on BE9441's
1A read at the bench, 2026-11-04).
Across every recorded reply (60 captures, March to October 2026), SUM8 of the
unescaped payload is the checksum on 7,747 of 7,747. 272 checksums arrived
escaped, and every one checks as an escape pair: the `10` is never data.
"""
from __future__ import annotations
import os
import pickle
import sys
from dataclasses import replace
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 _frame_body_bytes, write_blastware_file # noqa: E402
from minimateplus.client import _decode_monitor_status # noqa: E402
from minimateplus.framing import S3FrameParser, unescape_reply # noqa: E402
from minimateplus.models import Event # noqa: E402
from minimateplus.protocol import is_call_home_block # noqa: E402
from sfm.waveform_store import A5_PICKLE_VERSION, WaveformStore, _frame_to_dict # noqa: E402
from test_5a_blastware_walk import ByAddress # noqa: E402
FIX = Path(__file__).parent / "fixtures"
def _escape(b: bytes) -> bytes:
"""The unit's encoding: 10 before 02, 03, 04 and 10."""
return b"".join(bytes([0x10, x]) if x in (0x02, 0x03, 0x04, 0x10) else bytes([x]) for x in b)
def reply(sub: int, data: bytes, page: bytes = b"\x00\x00") -> bytes:
"""A reply as the unit sends it: header, data and SUM8 checksum, escaped."""
payload = bytes([0x00, 0x10, sub]) + page + data
return b"\x10\x02" + _escape(payload + bytes([sum(payload) & 0xFF])) + b"\x03"
def data_for(chk: int, last: int, sub: int = 0xE3) -> bytes:
"""Data ending in `last` whose reply checksum comes out as `chk`."""
base = bytes(11) + b"#58"
fill = (chk - (0x10 + sub + sum(base) + last)) & 0xFF
return base + bytes([fill, last])
def one(wire: bytes):
frames = S3FrameParser().feed(wire)
assert len(frames) == 1
return frames[0]
@pytest.mark.parametrize("chk", [0x02, 0x03, 0x04])
def test_an_escaped_checksum_leaves_nothing_in_the_data(chk):
data = data_for(chk, last=0x55)
f = one(reply(0xE3, data))
assert (unescape_reply(f.data), f.chk_byte) == (data, chk)
@pytest.mark.parametrize("chk", [0x02, 0x03, 0x04])
def test_a_last_data_byte_of_0x10_survives_an_escaped_checksum(chk):
# Wire `10 10 10 0X`: a real 0x10, then the escaped checksum. Not in any
# recording; one A5 chunk in ten ends in a real 0x10.
data = data_for(chk, last=0x10)
f = one(reply(0xE3, data))
assert (unescape_reply(f.data), f.chk_byte) == (data, chk)
REPLY_RECORDINGS = ["minimate-bench-10-25-26/BE9441_event0_01110000_rx.bin",
"minimate-bench-10-25-26/BE9441_event1_0111646a_rx.bin",
"minimate-bench-10-26-26-blastware/unit_replies.bin",
"minimate-bench-10-26-26-histogram/unit_replies.bin"]
@pytest.mark.parametrize("name", REPLY_RECORDINGS)
def test_every_recorded_reply_checks(name):
# BE9441, October 2026: 2,509 replies, 62 with an escaped checksum.
frames = S3FrameParser().feed((FIX / name).read_bytes())
assert frames
assert [i for i, f in enumerate(frames) if not f.checksum_valid] == []
@pytest.mark.parametrize("chk", [0x10, 0x00, 0x55])
def test_any_other_checksum_reads_as_before(chk):
data = data_for(chk, last=0x10)
f = one(reply(0xE3, data))
assert (unescape_reply(f.data), f.chk_byte) == (data, chk)
# Two 1C replies recorded from BE11529 on 2026-04-08, checksums 03 and 02 escaped.
# The battery and memory are counted from the end, so the stray byte read them as
# 430.08 V / 251,654,656 bytes total.
STATUS_REPLIES = [
("4-8-26/mid-monitor/raw_s3_20260408_181417",
"1002001010e300002c0000000000000000000000100408100407ea00120e2c000000000000010107cb"
"00060000010107cb0015000000001002a8000efff2000e9d80100303", 6.80, 983026, 957824),
("4-8-26/raw_s3_20260408_013431",
"1002001010e300002c0000000000000000000000100408100407ea00012312000000000000010107cb"
"00060000010107cb0015000000001002a4000efff2000e9e98100203", 6.76, 983026, 958104),
]
@pytest.mark.parametrize("capture,wire,volts,total,free", STATUS_REPLIES)
def test_a_recorded_status_reply_with_an_escaped_checksum_reads_whole(capture, wire, volts, total, free):
st = _decode_monitor_status(one(bytes.fromhex(wire)).data)
assert (st.battery_v, st.memory_total, st.memory_free) == (volts, total, free)
def test_a_call_home_read_with_an_escaped_checksum_is_a_call_home_block():
# BE11529's 2C reply (2026-04-20), its block untouched; one header pad byte is
# set so the checksum comes out 02. The stray byte made it 125 bytes, and SFM
# refused the unit as monitoring.
recorded = S3FrameParser().feed(
(FIX / "s3-call-home-bw" / "raw_s3_20260420_162148_pull_call_home_options.bin").read_bytes())
data = bytearray(unescape_reply(next(f for f in recorded if f.sub == 0xD3 and len(f.data) > 11).data))
data[10] = (0x02 - (0x10 + 0xD3 + sum(data) - data[10])) & 0xFF
f = one(reply(0xD3, bytes(data)))
assert f.chk_byte == 0x02
assert is_call_home_block(f.data[11:])
assert unescape_reply(f.data[11:]) == bytes(data[11:])
@pytest.mark.parametrize("chk", [0x02, 0x03, 0x04])
def test_the_file_builder_keeps_a_real_0x10_before_an_escaped_checksum(chk):
# An A5 chunk reply: 12 header bytes, then the body bytes it carries.
data = data_for(chk, last=0x10, sub=0xA5)
f = one(reply(0xA5, data))
assert _frame_body_bytes(f, 12) == data[12:]
# -- the waveform store's .a5.pkl frames, saved by the parser as it was ---------------
def _write_pickle(store: WaveformStore, name: str, version: int, frames: list) -> None:
_bw, a5_path = store.paths_for("BE9441", name)
a5_path.parent.mkdir(parents=True, exist_ok=True)
with a5_path.open("wb") as fp:
pickle.dump({"version": version, "frames": [_frame_to_dict(f) for f in frames]}, fp)
def test_a_pickle_saved_before_58_still_builds_blastwares_file(tmp_path, monkeypatch):
# BE9441's K441LTOG.000 (10-26 recording): two of its chunk replies have an
# escaped checksum. A pickle from before #58 holds their stray 0x10s.
fast_clock(monkeypatch)
frames = mp.MiniMateProtocol(ByAddress()).read_bulk_waveform_stream(
bytes.fromhex("0112a0b6"), stop_after_metadata=False, include_terminator=True, strict=True)
old = [replace(f, data=f.data + b"\x10") if f.chk_byte in (0x02, 0x03, 0x04) else f
for f in frames]
assert sum(o.data != f.data for o, f in zip(old, frames)) == 2
store = WaveformStore(tmp_path / "waveforms")
_write_pickle(store, "K441LTOG.000", 1, old)
loaded = store.load_a5("BE9441", "K441LTOG.000")
assert [f.data for f in loaded] == [f.data for f in frames]
ev = Event(index=0)
ev.timestamp = None
write_blastware_file(ev, loaded, tmp_path / "K441LTOG.000")
bw = FIX / "minimate-bench-10-26-26-blastware" / "blastware" / "K441LTOG.000"
assert (tmp_path / "K441LTOG.000").read_bytes() == bw.read_bytes()
def test_a_pickle_saved_now_loads_as_saved(tmp_path):
# A real 0x10 before an escaped checksum: the conversion is for old pickles only.
f = one(reply(0xA5, data_for(0x02, last=0x10, sub=0xA5)))
store = WaveformStore(tmp_path / "waveforms")
_write_pickle(store, "K441LTOG.000", A5_PICKLE_VERSION, [f])
assert store.load_a5("BE9441", "K441LTOG.000")[0].data == f.data