Files
seismo-relay/tests/test_s3_escaped_checksum.py
serversdownandClaude Opus 5.5 47da0ddef0 fix(framing): checksum_valid sums the reply's payload unescaped
S3FrameParser summed its payload with the kept `10` of each `10 02/03/04`
still in, so checksum_valid was False on about a third of good replies (the
old "S3 checksums frequently fail" belief).  SUM8 of the unescaped payload
is the unit's checksum on 7,747 of 7,747 recorded replies; the test pins it
on the 2,509 in the committed October fixtures (62 with an escaped checksum),
which also proves #58's split of data from checksum on real replies.

Nothing decides on checksum_valid; seismo_lab's display stops crying wolf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-06 14:54:45 -05:00

176 lines
7.9 KiB
Python

"""#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