feat(micromate): get_setup() -- the setup block decoded, checksum-verified, and read off a real unit

MicromateClient.get_setup() reads SUB 0x1A once and returns a MicromateSetup:
record mode, sample rate, histogram interval, pre-trigger, stop mode, record
time, auto-stop, active sensors, trigger sources, the three geophone trigger
levels, mic type and (linear) mic trigger, job number, scaled distance, and
the four notes.  MEASURED FIELDS ONLY -- everything graded inferred or
unknown in the reference stays in .raw.

micromate/setup_block.py holds the decode as pure functions (no I/O), plus
crc_ok(): one checksum rule for 0x1A, 0x08 and 0x2E.  A failed checksum
raises SetupChecksumError (a ProtocolError) unless verify=False; a short
block raises either way.

Two things the decoder gets right that a naive one would not:
- the mic comes from channel block 4 (the ACTIVE mic), never blocks 5/6,
  which hold the stored settings of whichever mic is NOT fitted;
- distance and charge weight convert back with the unit's own 3.2808 and
  2.21, so 45 lb entered on the unit reads 45.0, not 44.89.

TESTS: 69 new.  15 real fixtures (2,103 B each) -- 14 UM20147 reads from the
10-17/10-19 keypad passes, chosen so every field takes at least two values,
plus UM12947's read from Thor's 9-24 capture (other firmware line).
Expected values are what the operator read off the unit's screen, never the
decoder's own output.  Fixtures force-added, per the tests/fixtures/
convention.  Full suite 541 passed; the 16 pre-existing failures
(test_bw_ascii_report.py 15, test_event_file_io.py 1) are unchanged.

VERIFIED ON HARDWARE: bridges/mm_client_check.py now prints the decoded
setup; against UM20147 every line matched the unit's screen (Brian, 10-19).

Also: the scratch harness uses the library checksum and checks all three
blocks; mm_client_check's stale labels fixed (0x06 content[4:8] is the
likely monitor-log count, not "unexplained"; 11.0BD is no longer "the first
one this code has met").

No codec, store or DB change; no backfill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-10-19 18:20:25 -04:00
1 parent a74d3c9b00
commit b3aff4ed66
22 files changed
+622 -35

No files matched your search

+51 -13
View File
@@ -18,9 +18,9 @@ verified that way:
than using idle-gap detection, which should be strictly more robust — but
"should be" is the point of this script.
* **the other firmware line.** `11.0BD` reports `flags = 0x03`, a shorter
model string, and a `SUB 0x1C` block 4 bytes longer. Everything about that
is currently inference from one 2026-09-23 sweep whose captures never
landed in the repo.
model string, and a `SUB 0x1C` block 4 bytes longer. Inferred from a
2026-09-23 sweep; **confirmed on UM20147 2026-09-30** (forward offsets read
a correct battery and clock).
Run it over both paths and diff the two reports. Anything that differs beyond
timings is a finding.
@@ -244,7 +244,36 @@ def _select(refs, which: str):
return [r for r in refs if r.key_hex.lower() == which]
def step(label: str, fn):
def _setup_lines(s) -> list[str]:
"""A decoded setup, laid out the way the unit's own menus group it."""
def sensors(geo: bool, mic: bool) -> str:
return " + ".join(n for n, on in (("geophones", geo), ("mic", mic)) if on) or "none"
stop = f"Auto, after {s.auto_stop_after_s} s quiet" if s.auto_record_stop else "Fixed"
if s.mic_type == "linear":
mic = f"linear, trigger {s.mic_trigger_db:.1f} dB ({s.mic_trigger_psi:.5f} psi)"
else:
mic = s.mic_type
sd = (f"on: {s.distance_ft:.1f} ft, {s.charge_weight_lb:.1f} lb"
+ (f" -> {s.scaled_distance:.2f}" if s.scaled_distance else "")
if s.scaled_distance_enabled else "off")
return [
f"record mode {s.record_mode_name}",
f"sample rate {s.sample_rate} sps",
f"histogram interval {s.histogram_interval_s} s",
f"record time {s.record_time_s:g} s stop: {stop}",
f"pre-trigger {s.pretrigger_s:g} s",
f"sensors on {sensors(s.geophones_active, s.mic_active)}",
f"trigger on {sensors(s.trigger_on_geophones, s.trigger_on_mic)}",
"geophone trigger " + " / ".join(f"{v:.3f}" for v in s.geo_trigger_ips) + " in/s",
f"microphone {mic}",
f"job number {s.job_number} ({'on' if s.job_number_enabled else 'off'})",
f"scaled distance {sd}",
*(f"note {k:<15}{v!r}" for k, v in s.notes.items()),
]
def step(label: str, fn, show=None):
"""Run one read, report how long it took and what it returned."""
t0 = time.monotonic()
try:
@@ -256,6 +285,8 @@ def step(label: str, fn):
shown = value if isinstance(value, str) else repr(value)
if isinstance(value, list):
shown = f"{len(value)} entries"
if show:
shown = show(value)
print(f" {label:.<26} {ms:7.0f} ms {shown}")
return value
@@ -319,9 +350,8 @@ def main() -> int:
f"fw={info.firmware_line} monitoring={info.monitoring}")
print(f" active setup={info.active_setup!r}")
if info.firmware_line == "thor":
print(" *** 11.0BD unit — the FIRST one this code has met. ***")
print(" *** Check the battery and clock below carefully: ***")
print(" *** its 0x1C block is 4 bytes longer. ***")
print(" (11.0BD / Thor line: 0x1C is 4 B longer -- read forward, "
"confirmed 2026-09-30)")
state = step("get_state()", mm.get_state)
if state:
@@ -333,22 +363,30 @@ def main() -> int:
print(" *** device clock did not decode — dump raw below. ***")
print(f" raw 0x1C content: {_content(state.raw).hex(' ')}")
setup = step("get_setup()", mm.get_setup, show=lambda s: f"{s.name} (checksum ok)")
if setup:
print(" check each line against the unit's screen:")
for line in _setup_lines(setup):
print(f" {line}")
setups = step("list_setups()", mm.list_setups)
if setups:
print(f" first={setups[0]!r} last={setups[-1]!r}")
# ── SUB 0x06: is content[0:4] really the event count? ─────────────
# Two samples on one unit said yes, and THOR reads it BEFORE the chain
# walk then stops without ever reading the sentinel. A third value
# either confirms it or kills it.
# ── SUB 0x06: event count, and (likely) the monitor-log count ─────
# content[0:4] is the event count: 3/3 against the chain walk, and THOR's
# own ReadEventRecordCount agrees. content[4:8] was once recorded as "a
# constant 9" -- it read 47 during the 10-14 ACH session against THOR's
# "Monitor Log count: 45", so it is very likely the monitor-log count.
# Still graded a strong candidate, not settled (reference, 10-14).
claimed = None
raw06 = step("0x06 storage range", mm.protocol.read_storage_range)
if raw06:
c = _content(raw06)
claimed = int.from_bytes(c[0:4], "big")
print(f" content[0:4] = {claimed} <- CANDIDATE: event count")
print(f" content[0:4] = {claimed} <- event count")
print(f" content[4:8] = {int.from_bytes(c[4:8],'big')} "
f"<- unexplained (read 9 alongside a 6 on UM12947)")
f"<- likely the monitor-log count (strong candidate)")
if a.download:
print("\n event chain (read-only), via MicromateClient:")
+14 -1
View File
@@ -39,8 +39,9 @@ from typing import Optional
from minimateplus.transport import BaseTransport
from .models import MicromateDeviceInfo, MicromateEventRef, MicromateState
from .models import MicromateDeviceInfo, MicromateEventRef, MicromateSetup, MicromateState
from .protocol import MicromateProtocol, ProtocolError
from .setup_block import decode_setup
log = logging.getLogger(__name__)
@@ -300,6 +301,18 @@ class MicromateClient:
"""`SUB 0x41` — the loaded `.MMB` file name, e.g. `TEST1.mmb`."""
return _cstring(_content(self._proto.read_active_setup_name()))
def get_setup(self, *, verify: bool = True) -> MicromateSetup:
"""`SUB 0x1A` — what the unit is set to, decoded. One read.
Raises ``SetupChecksumError`` if the block's CRC fails, unless
``verify=False``. Offsets and what is deliberately not decoded are in
``micromate/setup_block.py``.
⚠ This reads the keypad's EDIT BUFFER: if someone is in the unit's setup
menu, unsaved values come back.
"""
return decode_setup(_content(self._proto.read_compliance_config()), verify=verify)
def list_setups(self) -> list[str]:
"""`0x3F` then `0x40`… — every setup file stored on the unit.
+76
View File
@@ -22,6 +22,7 @@ shrink or disappear.
from __future__ import annotations
import datetime
import math
from dataclasses import dataclass, field
from typing import Any, Dict, Optional, Tuple
@@ -480,6 +481,81 @@ class MicromateState:
return " ".join(bits)
_RECORD_MODES = {0x01: "Waveform", 0x02: "Waveform Manual", 0x03: "Histogram", 0x04: "Histogram Combo"}
# The unit's OWN conversion constants, identified bit-exactly from what it
# stored for keypad entries (2026-10-19). Not the textbook 3.28084 / 2.20462:
# convert back with these, or 45 lb entered on the unit reads as 44.89 lb.
_FT_PER_M = 3.2808
_LB_PER_KG = 2.21
_PA_PER_PSI = 6894.757
_P_REF_PA = 20e-6 # dB re 20 µPa
@dataclass
class MicromateSetup:
"""A unit's active setup, from ``SUB 0x1A`` — see ``micromate/setup_block.py``.
**Measured fields only.** Each was located by changing that one setting on a
unit's keypad and watching the bytes; anything graded inferred or unknown in
the protocol reference is left in ``raw`` rather than guessed at here.
⚠ This is what the unit is set to *right now* — including unsaved edits if
someone is in its setup menu, because ``0x1A`` reads the keypad's edit
buffer. Values are in the units the unit stores, whatever it displays:
in/s, psi, metres, kilograms.
"""
name: str # ⚠ ".MMB" after a keypad save, ".mmb" after a load
record_mode: int # see record_mode_name
sample_rate: int # samples per second
histogram_interval_s: int
pretrigger_s: float # positive; the unit stores it negative
auto_record_stop: bool # False = Fixed record time
record_time_s: float
auto_stop_after_s: int # quiet time before an Auto stop
geophones_active: bool
mic_active: bool
trigger_on_geophones: bool
trigger_on_mic: bool
geo_trigger_ips: Tuple[float, float, float] # Tran, Vert, Long
mic_type: str # "linear" | "sound_level" | "unknown (<code>)"
mic_trigger_psi: Optional[float] # linear mic only; SLM units not measured
job_number_enabled: bool
job_number: int # kept while switched off
scaled_distance_enabled: bool
distance_m: float
charge_weight_kg: float
notes: Dict[str, str] # label -> value, in the unit's order
raw: bytes = field(default=b"", repr=False) # the 2,092-byte content
@property
def record_mode_name(self) -> str:
return _RECORD_MODES.get(self.record_mode, f"unknown (0x{self.record_mode:02x})")
@property
def mic_trigger_db(self) -> Optional[float]:
"""dB re 20 µPa. Matches the unit's screen to ±0.001 dB on 131 and 140."""
if not self.mic_trigger_psi:
return None
return 20.0 * math.log10(self.mic_trigger_psi * _PA_PER_PSI / _P_REF_PA)
@property
def distance_ft(self) -> float:
return self.distance_m * _FT_PER_M
@property
def charge_weight_lb(self) -> float:
return self.charge_weight_kg * _LB_PER_KG
@property
def scaled_distance(self) -> Optional[float]:
"""ft / √lb, as the unit computes it for display. It is not stored."""
if self.charge_weight_kg <= 0:
return None
return self.distance_ft / math.sqrt(self.charge_weight_lb)
@dataclass
class MicromateEventRef:
"""One entry in a unit's event chain, from `1E`/`1F` and optionally `0x0C`.
+154
View File
@@ -0,0 +1,154 @@
"""
setup_block.py — the Micromate setup block (`SUB 0x1A`), decoded.
Pure byte interpretation: no I/O, no device. `MicromateClient.get_setup()`
does the read and hands the content here.
Every offset below is into **content** (response data minus its 11-byte prefix)
and was measured on UM20147 (`11.0BD`) by changing one setting on the unit's own
keypad and watching which bytes moved, 2026-10-17/19. Method, grades and the
fields deliberately left out are in docs/micromate_protocol_reference.md, under
*The `0x1A` field map from a keypad pass* and the 2026-10-19 section after it.
"""
from __future__ import annotations
import struct
from .models import MicromateSetup
from .protocol import ProtocolError
class SetupChecksumError(ProtocolError):
"""A config block's trailing CRC does not match its contents."""
_CRC_POLY = 0x1021
_CRC_INIT = 0x1D0F # CRC-16/AUG-CCITT
_CONTENT_SIZE = 2092 # = content[0:2] (2090) + the 2-byte CRC
# ── Head of the block ─────────────────────────────────────────────────────────
_MODE = 5 # 01 Waveform · 02 Manual · 03 Histogram · 04 Combo
_SAMPLE_RATE = slice(6, 8) # uint16 BE ⚠ 4096 puts a literal 0x10 here
_HIST_INTERVAL = slice(8, 10) # uint16 BE seconds
_PRETRIGGER = 12 # f32 BE, NEGATIVE seconds
_STOP_MODE = 17 # 00 Fixed · 01 Auto (u8 or u16 BE [16:18] — unresolved)
_RECORD_TIME = 18 # f32 BE seconds
_AUTO_STOP = 23 # seconds (u8 or u16 BE [22:24] — unresolved)
_SENSORS = 25 # bitmask: 0x07 geophones, 0x08 mic
_TRIGGERS = 29 # same bits: which sensors may trigger
_DISTANCE = 30 # f32 BE metres (keypad: ft / 3.2808)
_CHARGE = 34 # f32 BE kg (keypad: lb / 2.21)
_REPORT_FLAGS = 39 # 0x02 job number on · 0x08 scaled distance on · 0x01 ?
_JOB_NUMBER = slice(40, 42) # uint16 BE
_NAME = slice(42, 86) # setup file name, null-padded
_GEO_BITS, _MIC_BIT = 0x07, 0x08
_JOB_ON, _SCALED_ON = 0x02, 0x08
# ── Notes: four [label 22][value 42] pairs on a 64-byte stride ────────────────
_NOTE_LABEL, _NOTE_VALUE, _NOTE_STRIDE, _NOTES = 122, 144, 64, 4
# ── Channel blocks, 48 bytes each from content[1708] ──────────────────────────
# 1-3 are the geophones. Block 4 is the ACTIVE mic: a byte copy of block 5
# (stored linear settings) or block 6 (stored sound-level settings). Read the
# mic from block 4 only — 5 and 6 describe whichever mic is NOT selected.
_CHANNELS, _CHANNEL_SIZE = 1708, 48
_CH_SENSOR_CODE = slice(4, 8) # uint32 BE: 1 geophone, 2 linear mic, 9 SLM, 0 off
_CH_TRIGGER = 30 # f32 BE: geophone in/s, linear mic psi
_ACTIVE_MIC = 3 # block index (0-based)
_MIC_TYPES = {2: "linear", 9: "sound_level"}
def _crc16_aug_ccitt(data: bytes) -> int:
c = _CRC_INIT
for b in data:
c ^= b << 8
for _ in range(8):
c = ((c << 1) ^ _CRC_POLY) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
def crc_ok(content: bytes) -> bool:
"""True if a config block's trailing checksum matches its contents.
One rule covers the setup (`0x1A`), preferences (`0x08`) and `0x2E` blocks:
``content[0:2]`` is a uint16 BE length N, and a CRC-16/AUG-CCITT over
``content[0:N-2]`` is stored big-endian at ``content[N:N+2]``. The two bytes
at ``[N-2:N]`` are zero and not covered. `0x2C` (call-home) has no checksum.
A block too short to hold its own declared length reads as bad, not as an
error: a truncated read is exactly what this exists to catch.
"""
if len(content) < 2:
return False
n = int.from_bytes(content[0:2], "big")
if n < 2 or len(content) < n + 2:
return False
return _crc16_aug_ccitt(content[: n - 2]) == int.from_bytes(content[n : n + 2], "big")
def _f32(c: bytes, offset: int) -> float:
return struct.unpack_from(">f", c, offset)[0]
def _ascii(buf: bytes) -> str:
return buf.split(b"\x00")[0].decode("ascii", "replace").strip()
def _channel(c: bytes, index: int) -> bytes:
start = _CHANNELS + index * _CHANNEL_SIZE
return c[start : start + _CHANNEL_SIZE]
def decode_setup(content: bytes, *, verify: bool = True) -> MicromateSetup:
"""Decode a setup block's content (``0x1A`` data minus its 11-byte prefix).
Raises ``SetupChecksumError`` if the trailing CRC does not match — unless
``verify=False``, which decodes anyway, for looking at what a bad read held.
A block shorter than 2,092 bytes raises ``ProtocolError`` either way: the
checksum is optional, the bounds are not.
"""
if len(content) < _CONTENT_SIZE:
raise ProtocolError(f"setup block content is {len(content)} B, need {_CONTENT_SIZE}")
if verify and not crc_ok(content):
raise SetupChecksumError(
"setup block checksum mismatch — a short or corrupt read "
"(decode_setup(..., verify=False) to inspect it anyway)"
)
c = content
mic = _channel(c, _ACTIVE_MIC)
mic_code = int.from_bytes(mic[_CH_SENSOR_CODE], "big")
mic_type = _MIC_TYPES.get(mic_code, f"unknown ({mic_code})")
flags = c[_REPORT_FLAGS]
notes = {}
for n in range(_NOTES):
label = _ascii(c[_NOTE_LABEL + n * _NOTE_STRIDE : _NOTE_VALUE + n * _NOTE_STRIDE])
value = _ascii(c[_NOTE_VALUE + n * _NOTE_STRIDE : _NOTE_LABEL + (n + 1) * _NOTE_STRIDE])
notes[label] = value
return MicromateSetup(
name=_ascii(c[_NAME]),
record_mode=c[_MODE],
sample_rate=int.from_bytes(c[_SAMPLE_RATE], "big"),
histogram_interval_s=int.from_bytes(c[_HIST_INTERVAL], "big"),
pretrigger_s=-_f32(c, _PRETRIGGER),
auto_record_stop=bool(c[_STOP_MODE]),
record_time_s=_f32(c, _RECORD_TIME),
auto_stop_after_s=c[_AUTO_STOP],
geophones_active=bool(c[_SENSORS] & _GEO_BITS),
mic_active=bool(c[_SENSORS] & _MIC_BIT),
trigger_on_geophones=bool(c[_TRIGGERS] & _GEO_BITS),
trigger_on_mic=bool(c[_TRIGGERS] & _MIC_BIT),
geo_trigger_ips=tuple(_f32(_channel(c, i), _CH_TRIGGER) for i in range(3)),
mic_type=mic_type,
mic_trigger_psi=_f32(mic, _CH_TRIGGER) if mic_type == "linear" else None,
job_number_enabled=bool(flags & _JOB_ON),
job_number=int.from_bytes(c[_JOB_NUMBER], "big"),
scaled_distance_enabled=bool(flags & _SCALED_ON),
distance_m=_f32(c, _DISTANCE),
charge_weight_kg=_f32(c, _CHARGE),
notes=notes,
raw=c,
)
+10 -21
View File
@@ -52,6 +52,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from bridges.mm_client_check import StdlibSerial # noqa: E402
from micromate.client import MicromateClient # noqa: E402
from micromate.setup_block import crc_ok # noqa: E402
from minimateplus.transport import TcpTransport # noqa: E402
SNAP_ROOT = Path(__file__).resolve().parent / "mm_config_snaps"
@@ -138,28 +139,16 @@ def _interps(a: bytes, b: bytes, off: int, run: int) -> list[str]:
return out
def crc16_aug_ccitt(data: bytes) -> int:
"""CRC-16/AUG-CCITT: poly 0x1021, init 0x1D0F, no reflection, xorout 0."""
c = 0x1D0F
for x in data:
c ^= x << 8
for _ in range(8):
c = ((c << 1) ^ 0x1021) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
# Blocks that carry the config checksum (micromate.setup_block.crc_ok): N =
# content[0:2], CRC-16/AUG-CCITT over [0:N-2] stored at [N:N+2]. 0x2C has none.
CRC_BLOCKS = {"1A_compliance", "08_event_index", "2E_trigger"}
def crc_status_1a(raw: bytes) -> str:
"""Check 0x1A's trailer: CRC over content[0:2088], stored BE at [2090:2092].
Found 2026-10-17 from one keypad diff and confirmed on 23 snapshots plus
UM12947's 9-24 capture. A mismatch means a short or corrupt read -- or
that the layout is not what this assumes, which is worth knowing too.
"""
def crc_status(raw: bytes) -> str:
"""A mismatch means a short or corrupt read -- or a block this rule misses."""
c = raw[CONTENT:]
if len(c) < 2092:
return f"CRC n/a (content {len(c)} B < 2092)"
want, got = crc16_aug_ccitt(c[:2088]), int.from_bytes(c[2090:2092], "big")
return f"CRC ok ({got:04x})" if want == got else f"CRC MISMATCH computed {want:04x}, stored {got:04x}"
stored = c[int.from_bytes(c[0:2], "big"):][:2].hex() if len(c) >= 2 else "--"
return f"CRC ok ({stored})" if crc_ok(c) else f"CRC MISMATCH (stored {stored})"
def _runs(a: bytes, b: bytes, ignore: set[int]) -> list[tuple[int, int]]:
@@ -314,8 +303,8 @@ def cmd_watch(mm: MicromateClient, serial: str, interval: float,
f"{a[off:off + run].hex()} -> {b[off:off + run].hex()}")
for line in _interps(a, b, off, run):
print(f" {line}")
if name == "1A_compliance":
print(f" {crc_status_1a(cur[name])}")
if name in CRC_BLOCKS:
print(f" {crc_status(cur[name])}")
print(flush=True)
prev = cur
except KeyboardInterrupt:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+45
View File
@@ -22,6 +22,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from micromate.client import CONTENT, MicromateClient, _content, _cstring
from micromate.framing import ETX, STX, checksum, stuff
from micromate.protocol import ProtocolError
from micromate.setup_block import SetupChecksumError
FLAGS_CB, FLAGS_THOR = 0xC5, 0x03
@@ -491,3 +492,47 @@ def test_the_four_extra_bd_bytes_are_not_all_zero():
"""
assert _content(MS_BD_MONITORING)[44:] == bytes.fromhex("0fa00004")
assert _content(MS_IDLE)[44:] == b"", "the CB block has no such tail"
# ── get_setup() ───────────────────────────────────────────────────────────────
# Decoding itself is covered field by field in test_micromate_setup.py; these
# check the client's read, its framing round trip and the verify switch.
SETUP_FIXTURES = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fixtures", "micromate-setup")
def _setup_read(name: str) -> bytes:
with open(os.path.join(SETUP_FIXTURES, f"{name}.bin"), "rb") as f:
return f.read()
def test_get_setup_is_one_read_of_0x1a():
"""One frame -- not Series III's four-frame compliance sequence."""
mm, t = client([frame(0xE5, _setup_read("um20147_baseline"))])
mm.get_setup()
assert [w[5] for w in t.written] == [0x1A]
def test_get_setup_survives_a_literal_dle_through_the_framing():
"""4096 sps puts 0x10 in the payload, which the unit must escape on the wire
and the parser must unescape. Wrong either way and the rate reads wrong or
the CRC fails."""
mm, _ = client([frame(0xE5, _setup_read("um20147_4096sps"))])
s = mm.get_setup()
assert s.sample_rate == 4096
assert s.raw == _setup_read("um20147_4096sps")[CONTENT:]
def test_get_setup_raises_on_a_corrupt_read_by_default():
data = bytearray(_setup_read("um20147_baseline"))
data[CONTENT + 5] = 0x05
mm, _ = client([frame(0xE5, bytes(data))])
with pytest.raises(SetupChecksumError):
mm.get_setup()
def test_get_setup_verify_false_returns_the_corrupt_read():
data = bytearray(_setup_read("um20147_baseline"))
data[CONTENT + 5] = 0x05
mm, _ = client([frame(0xE5, bytes(data))])
assert mm.get_setup(verify=False).record_mode == 0x05
+272
View File
@@ -0,0 +1,272 @@
"""
Tests for micromate/setup_block.py — the Micromate setup block (SUB 0x1A) decoder.
Every fixture is a real read off a unit, taken with scratch/mm_config_diff.py
while an operator changed settings on the unit's own keypad, 2026-10-17/19.
**Expected values are what the operator read off the unit's screen**, recorded in
docs/micromate_protocol_reference.md — never values computed by this decoder.
A test whose expectation came from the code under test passes whatever the code
does.
Fixtures are 2,103-byte `0x1A` response data: an 11-byte prefix, then the
2,092-byte content the decoder reads. `um12947_2026-09-24.bin` is a second unit
on the other firmware line, cut from Thor's 9-24 "send TEST1" capture.
"""
from __future__ import annotations
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from micromate.protocol import ProtocolError # noqa: E402
from micromate.setup_block import SetupChecksumError, crc_ok, decode_setup # noqa: E402
FIXTURES = Path(__file__).parent / "fixtures" / "micromate-setup"
ALL_FIXTURES = sorted(FIXTURES.glob("*.bin"))
# Small real blocks for the generic checksum rule (content only, prefix stripped).
# 0x08 preferences, Imperial and Metric -- UM20147, 2026-10-19 17:07 / 17:14.
PREFS_IMPERIAL = bytes.fromhex(
"00580900000000000000000000000000000000000000000000000000000000000000000000"
"000000000100010001000100000000000000010001000000000000000000000000000000"
"000002000000000000000200000000b42f"
)
PREFS_METRIC = bytes.fromhex(
"00580900000000000000000000000000000000000000000000000000000000010000000000"
"000000000100010001000100000000000000010001000000000000000000000000000000"
"000002000000000000000200000000911a"
)
# 0x2E, same session.
BLOCK_2E = bytes.fromhex("001ad50000010000000000000000000000000000000000000000141a")
def content_of(name: str) -> bytes:
return (FIXTURES / f"{name}.bin").read_bytes()[11:]
# ── The checksum rule ─────────────────────────────────────────────────────────
def test_fixtures_are_present():
"""15 fixtures; a missing directory would otherwise make the parametrised
tests below collect nothing and pass vacuously."""
assert len(ALL_FIXTURES) == 15
@pytest.mark.parametrize("path", ALL_FIXTURES, ids=lambda p: p.stem)
def test_every_real_setup_read_passes_its_checksum(path):
assert crc_ok(path.read_bytes()[11:])
@pytest.mark.parametrize(
"block", [PREFS_IMPERIAL, PREFS_METRIC, BLOCK_2E], ids=["0x08-imperial", "0x08-metric", "0x2E"]
)
def test_the_rule_is_the_blocks_own_length_not_the_setup_size(block):
"""One rule covers three blocks: N = content[0:2], CRC over [0:N-2] stored at
[N:N+2]. An implementation hard-wired to the setup block's 2088 fails here."""
assert crc_ok(block)
@pytest.mark.parametrize("offset", [5, 144, 1738, 2087], ids=["mode", "note", "trigger", "last-covered"])
def test_one_changed_byte_fails_the_checksum(offset):
c = bytearray(content_of("um20147_baseline"))
c[offset] ^= 0x01
assert not crc_ok(bytes(c))
def test_a_changed_trailer_fails_the_checksum():
c = bytearray(content_of("um20147_baseline"))
c[2091] ^= 0x01
assert not crc_ok(bytes(c))
@pytest.mark.parametrize("n", [0, 1, 2, 100, 2091], ids=lambda n: f"{n}B")
def test_a_block_too_short_for_its_own_length_fails(n):
"""A truncated read must read as bad, never raise IndexError and never pass."""
assert not crc_ok(content_of("um20147_baseline")[:n])
# ── Fields: every value below is what the operator read off the screen ────────
@pytest.mark.parametrize(
"name, mode_code, mode_name",
[
("um20147_waveform", 0x01, "Waveform"),
("um20147_waveform_manual", 0x02, "Waveform Manual"),
("um20147_histogram_300s", 0x03, "Histogram"),
("um20147_baseline", 0x04, "Histogram Combo"),
],
)
def test_record_mode(name, mode_code, mode_name):
"""Same codes as Series III, one byte later than the S3 analogy put them.
The keypad menu order is 03 04 01 02, so an off-by-one enum reads wrong here."""
s = decode_setup(content_of(name))
assert s.record_mode == mode_code
assert s.record_mode_name == mode_name
@pytest.mark.parametrize(
"name, rate",
[("um20147_baseline", 1024), ("um20147_waveform_manual", 2048), ("um20147_4096sps", 4096)],
)
def test_sample_rate(name, rate):
"""4096 puts a literal 0x10 (DLE) at content[6] -- the case that shifted
every later field by one byte on Series III."""
assert decode_setup(content_of(name)).sample_rate == rate
@pytest.mark.parametrize("name, seconds", [("um20147_baseline", 2), ("um20147_histogram_300s", 300)])
def test_histogram_interval(name, seconds):
"""300 = 01 2c: the high byte is what proves the field is two bytes wide."""
assert decode_setup(content_of(name)).histogram_interval_s == seconds
@pytest.mark.parametrize("name, seconds", [("um20147_baseline", 1.0), ("um20147_pretrig025_auto", 0.25)])
def test_pretrigger_is_reported_positive(name, seconds):
"""Stored as NEGATIVE seconds (-1.0 / -0.25); the screen shows 1.0 / 0.25."""
assert decode_setup(content_of(name)).pretrigger_s == seconds
@pytest.mark.parametrize(
"name, auto, record_time, auto_stop",
[("um20147_baseline", False, 10.0, 3), ("um20147_pretrig025_auto", True, 11.0, 1)],
)
def test_record_time_window(name, auto, record_time, auto_stop):
s = decode_setup(content_of(name))
assert s.auto_record_stop is auto
assert s.record_time_s == record_time
assert s.auto_stop_after_s == auto_stop
@pytest.mark.parametrize(
"name, geo_on, mic_on, trig_geo, trig_mic",
[
("um20147_baseline", True, True, True, True),
("um20147_geo_only", True, False, True, False),
("um20147_mic_only", False, True, False, True),
("um20147_geo_trigger_off", True, True, False, True),
],
)
def test_active_sensors_and_trigger_sources_are_separate_masks(name, geo_on, mic_on, trig_geo, trig_mic):
"""content[25] is which sensors are on, content[29] which may trigger.
geo_trigger_off has both sensors on but only the mic triggering -- a decoder
reading both from one byte gets that fixture wrong."""
s = decode_setup(content_of(name))
assert (s.geophones_active, s.mic_active) == (geo_on, mic_on)
assert (s.trigger_on_geophones, s.trigger_on_mic) == (trig_geo, trig_mic)
@pytest.mark.parametrize(
"name, level",
[("um20147_baseline", 0.5), ("um20147_waveform_manual", 0.6), ("um12947_2026-09-24", 0.3)],
)
def test_geophone_trigger_level_per_channel(name, level):
s = decode_setup(content_of(name))
assert s.geo_trigger_ips == pytest.approx((level, level, level), abs=1e-6)
@pytest.mark.parametrize("name, db", [("um20147_baseline", 131.0), ("um20147_mic_140db", 140.0)])
def test_linear_mic_trigger_is_psi_and_reads_back_as_the_screens_db(name, db):
s = decode_setup(content_of(name))
assert s.mic_type == "linear"
assert s.mic_trigger_psi is not None
assert s.mic_trigger_db == pytest.approx(db, abs=0.01)
def test_the_mic_comes_from_block_4_not_from_the_stored_setups():
"""Block 4 is the ACTIVE mic; blocks 5/6 are stored linear/SLM settings.
With a sound-level mic selected, block 5 still holds a linear mic -- read it
and the decoder reports a mic that is not plugged in."""
s = decode_setup(content_of("um20147_sound_level_mic"))
assert s.mic_type == "sound_level"
assert s.mic_trigger_psi is None # its unit is not measured; not exposed
assert s.mic_trigger_db is None
@pytest.mark.parametrize(
"name, enabled, number",
[
("um20147_baseline", False, 0),
("um20147_job_1234", True, 1234),
("um20147_scaled_distance", False, 1234), # switched off, number kept
],
)
def test_job_number(name, enabled, number):
s = decode_setup(content_of(name))
assert s.job_number_enabled is enabled
assert s.job_number == number
def test_scaled_distance_uses_the_units_own_conversion_constants():
"""Entered as 123 ft and 45 lb; the screen then showed scaled distance 18.34.
Stored as metres and kg via ft / 3.2808 and lb / 2.21 -- converting back with
the textbook 2.20462 shows 44.89 lb, not what the operator typed."""
s = decode_setup(content_of("um20147_scaled_distance"))
assert s.scaled_distance_enabled is True
assert s.distance_ft == pytest.approx(123.0, abs=1e-3)
assert s.charge_weight_lb == pytest.approx(45.0, abs=1e-3)
assert s.scaled_distance == pytest.approx(18.34, abs=0.005)
def test_scaled_distance_off_with_no_charge_weight():
s = decode_setup(content_of("um20147_baseline"))
assert s.scaled_distance_enabled is False
assert s.scaled_distance is None # no charge weight: nothing to divide by
def test_notes_are_label_value_pairs():
s = decode_setup(content_of("um20147_location_bench01"))
assert list(s.notes) == ["Location", "Client", "Company", "General Notes"]
assert s.notes["Location"] == "BENCH01"
def test_a_second_unit_on_the_other_firmware_line():
"""UM12947 (11.0CB), cut from Thor's 9-24 capture: a different unit, firmware
and setup. Strings are this job's notes as the read returned them."""
s = decode_setup(content_of("um12947_2026-09-24"))
assert s.name == "Univ of Pitt-1st Yr. Housing-Loc1 Ruskin.mmb"
assert s.notes == {
"Location": "Univ of Pitt-1st Yr Housing-Loc1 Ruskin",
"Client": "PJ Dick Inc.",
"Company": "Terra-Mechanics, Inc. - Harrison",
"General Notes": "Loc#1-Univ of Pitt. - Ruskin Hall",
}
def test_raw_is_the_content():
c = content_of("um20147_baseline")
assert decode_setup(c).raw == c
# ── Errors ────────────────────────────────────────────────────────────────────
def test_a_corrupt_block_raises_rather_than_decoding_garbage():
c = bytearray(content_of("um20147_baseline"))
c[5] = 0x05 # a mode byte no keypad produces
with pytest.raises(SetupChecksumError):
decode_setup(bytes(c))
def test_a_checksum_error_is_a_protocol_error():
"""Callers already catching ProtocolError around a read keep working."""
assert issubclass(SetupChecksumError, ProtocolError)
def test_verify_false_decodes_a_corrupt_block_anyway():
"""For diagnosis: see what a bad read contained instead of only that it was bad."""
c = bytearray(content_of("um20147_baseline"))
c[5] = 0x05
s = decode_setup(bytes(c), verify=False)
assert s.record_mode_name == "unknown (0x05)"
@pytest.mark.parametrize("verify", [True, False])
def test_a_short_block_raises_even_without_verify(verify):
"""verify=False skips the checksum, never the bounds -- a short read would
otherwise decode as zeros, or raise an IndexError from deep in a slice."""
with pytest.raises(ProtocolError, match="2092"):
decode_setup(content_of("um20147_baseline")[:1900], verify=verify)