Files
seismo-relay/tests/test_minimate_write_frames.py
T
serversdownandClaude Opus 5.5 b5037b0b1e 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
2026-10-27 02:54:26 -04:00

250 lines
8.5 KiB
Python

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