""" 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 with_crc(content: bytes) -> bytes: """`content` with its trailing checksum recomputed: CRC-16/AUG-CCITT over ``[0:N-2]``, stored big-endian at ``[N:N+2]`` (the rule `crc_ok` checks). THOR's write omits the checksum and the unit computes its own; this keeps a patched block self-consistent so a plan's integrity check still means something.""" n = int.from_bytes(content[0:2], "big") if n < 2 or len(content) < n + 2: raise ValueError(f"block header says {n} but the block is {len(content)} B") out = bytearray(content) out[n : n + 2] = _crc16_aug_ccitt(content[: n - 2]).to_bytes(2, "big") return bytes(out) 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, )