diff --git a/docs/instantel_protocol_reference.md b/docs/instantel_protocol_reference.md index a608b2f..60b5c69 100644 --- a/docs/instantel_protocol_reference.md +++ b/docs/instantel_protocol_reference.md @@ -11,7 +11,7 @@ | Date | Section | Change | |---|---|---| -| 2026-11-03 | 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. Code: `minimateplus.protocol.assemble_compliance_content`, `read_compliance_content`; tests `tests/test_s3_settings_read.py`. | +| 2026-11-03 | 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`. | | 2026-11-03 | Appendix D.3.3, D.6.1, D.6.3, D.6.5, D.6.7, §8 | ✅ **File-only decode, second pass (on `dev`).** **D.3.3:** the footer is the file's last 26 bytes (70,041 / 70,041); an earlier stop-time record fooled the first-match search on 14 files, making histograms a day late. Its `[18:24]` is **not** fixed (retracted). **D.6.1:** STRT[18] now picks the codec; the waveform codec had claimed 2018 5 s histograms. **D.6.3:** the job number (flags `k − 9` bit `0x02`, uint16 at `k − 8`; 2,997 / 2,997). **D.6.5:** the PVS² high word is non-zero above 1.28 in/s (retracted "reads 0000"), so the layout check now uses peak ≤ PVS ≤ √3·peak (34,502,955 / 34,502,955); Blastware's "Number of Intervals" is the monitoring time ÷ the interval. **§8:** where the 1995 default-clock events come from. 18 of 88 report fields now match on every DL2 event. | | 2026-11-03 | call home (SUB 2C / 7E / 7F) | **SFM's call-home write, measured both ways.** SFM's 0x7E image (`write_image` of the 0x2C read with byte 5 set, framed ONCE) and its 0x7F confirm reproduce Blastware's 2026-04-20 enable and disable writes byte for byte (BE11529; `tests/test_s3_call_home_bw_frames.py`). Live on BE9441, idle: a no-op, on and off were all acked (0x81 / 0x80) and read back, and the unit's menu agreed. Only byte 5 changes: no unit-maintained field, unlike Series 4's `[118:120]`. Byte 5 is read from the UNESCAPED block. ⚠ Unescaping is not idempotent, so a built image must never pass through `write_image` again: a call-in time of 16:02-16:04 is `10 02`-`10 04` in the image. ⚠ **While monitoring, the unit answers the 0x2C read with its DEVICE-INFO block** ('Instantel', 'MiniMate Plus', its serial), as it answers 1A. Idle again, minutes later, it returns the call-home block. So a monitoring unit's call-home cannot be read-modify-written; SFM refuses with 'stop monitoring first'. A blind write while monitoring stays untested on purpose. | | 2026-11-02 | Appendix D.3.1, D.6 (NEW), §15 | ✅ **Event fields SFM reads from the file alone (v0.33.0, plus the range on `dev`).** New D.6 records the bytes and the DL2 verification for each field: the record type `STRT[18]`, the recording-setup block (sample rate, pre-trigger, record time, the four notes), the geophone range (label + 29 in the setup's channel blocks), each histogram interval's PVS², and the mic scale (one count = 0.25 Pa). **Retracted in place:** D.3.1's `STRT[20]` = record time (it is `00` on every DL2 file; the "70 s" SFM used to report was `STRT[18]`, the record-type byte), and the 2026-08-26 reading of sub-minute histogram records as little-endian (big-endian from byte 5 since v0.32.0, #47/#49). **For #48:** the file's copy of the block puts the pre-trigger where the 1A "stable anchor" `be 80 00 00 00 00` sits. In the file, though, it is each event's own pre-trigger, which varies on the same unit on the same day (253–256 samples at 1024 sps), and Blastware reports it per event. So the file says little about whether the live 1A loses its anchor, and #48 stays open. | diff --git a/micromate/setup_block.py b/micromate/setup_block.py index 80b3364..daeaf43 100644 --- a/micromate/setup_block.py +++ b/micromate/setup_block.py @@ -88,6 +88,20 @@ def crc_ok(content: bytes) -> bool: 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] diff --git a/micromate/setup_fields.py b/micromate/setup_fields.py new file mode 100644 index 0000000..d2b6f38 --- /dev/null +++ b/micromate/setup_fields.py @@ -0,0 +1,407 @@ +"""setup_fields.py -- the settings an operator can change, for both series (phase 5). + +Pure byte interpretation: no I/O, no device, no `sfm` and no `minimateplus` +imports. Every offset is into the settings block's CONTENT: + + * Series 4: the `0x1A` content, 2,092 bytes (N = 2090, then its CRC). + * Series 3: the 1A read assembled by `minimateplus.protocol. + assemble_compliance_content`, 2,090 bytes (N = 2090, no CRC in the read). + +**One layout.** Measured 2026-11-03: Blastware's MiniMate compliance image IS +Series IV's `0x1A` content layout (`decode_setup` reads it), and each of +BE11529's nine 2026-04-20 Blastware writes moved exactly the bytes of the field +it changed. Series 4's offsets are from the 47-snapshot keypad pass on UM20147 +(2026-10-17/19). Fields measured on one series only are offered on that series +only. + +**Limits are the units' own, from Instantel's manuals** (Brian, 2026-11-03: "I +want to use the actual unit limits, not just what we have done in the past"): + * geophone trigger 0.005-10 in/s in steps of 0.001 -- MiniMate Plus manual + 716U0101 Rev 15, Appendix *Series III Specifications*; Micromate manual + 721U0201 Rev 06, *Geophone Trigger Level* -- and at most the range's full + scale; + * record time: Micromate 1-90 s (*Record Time*); MiniMate up to §4.4's + *Maximum Record Times* for a 1 MB unit, channels 1-4, at the sample rate, + and 13 s in Histogram Combo (§3.8.9); + * job number 1-9999 (both manuals). +What a unit does not take, the read-back shows (`settings_state`). + +tests/test_setup_fields.py holds this to Blastware's writes and the keypad +fixtures byte for byte. +""" +from __future__ import annotations + +import hashlib +import math +import struct +from typing import Any, Dict, List, Optional, Set + +from .setup_block import crc_ok, with_crc + + +class SettingsValueError(ValueError): + """A requested change SFM will not make, said plainly. Nothing is sent.""" + + +# ── Layout ────────────────────────────────────────────────────────────────── + +_MODE = 5 +_SAMPLE_RATE = slice(6, 8) # u16 BE +_HIST_INTERVAL = slice(8, 10) # u16 BE seconds +_RECORD_TIME = 18 # f32 BE seconds +_REPORT_FLAGS = 39 # bit 0x02 = job number on the report (measured both series) +_JOB_SHOWN = 0x02 +_JOB_NUMBER = slice(40, 42) # u16 BE + +_NOTE_LABEL, _NOTE_VALUE, _NOTE_STRIDE, _NOTES = 122, 144, 64, 4 +_NOTE_LABEL_WIDTH, _NOTE_WIDTH = 22, 42 +NOTE_MAX = _NOTE_WIDTH - 1 # a NUL always ends the value + +_CHANNELS, _CHANNEL_SIZE, _GEOPHONES = 1708, 48, (0, 1, 2) +_CH_RANGE = 29 # u8: 0 Normal (10 in/s), 1 Sensitive (1.25 in/s) -- Series 3, measured +_CH_TRIGGER = 30 # f32 BE, in/s for a geophone +_CH_UNIT = slice(34, 38) # "in." / "in" (the keypad re-renders it); NOT an identifier +_CH_ALARM = 38 # f32 BE -- Series 3, read; a write waits for the bench +_FULL_SCALE = {0: 10.0, 1: 1.25} +_RANGES = {"normal": 0, "sensitive": 1} + +# Blastware writes these bytes as a fixed value on every write on record (11 of 11, +# both units); the unit reads `01 7f` there after a monitoring session. Meaning +# unknown -- SFM writes what Blastware writes. Series 3 only. +S3_BLASTWARE_FIXED = {26: b"\x00\x00"} + +# A Series-3 alarm-level write has never been seen; the bench measures one, with +# Brian's go, before this turns on. +S3_ALARM_WRITE_MEASURED = False + +MODES = { + 3: {"single_shot": 0x00, "continuous": 0x01, "histogram": 0x03, "histogram_continuous": 0x04}, + 4: {"waveform": 0x01, "manual": 0x02, "histogram": 0x03, "combo": 0x04}, +} +_MODE_LABELS = { + "single_shot": "Single Shot", "continuous": "Continuous", "histogram": "Histogram", + "histogram_continuous": "Histogram + Continuous", "waveform": "Waveform", "manual": "Manual", + "combo": "Combo", +} +SAMPLE_RATES = (1024, 2048, 4096) +INTERVALS = (2, 5, 15, 60, 300, 900) +TRIGGER_MIN, TRIGGER_MAX, TRIGGER_STEP = 0.005, 10.0, 0.001 +RECORD_MIN_S = 1.0 +S4_MAX_RECORD_S = 90.0 +S3_MAX_RECORD_S = {1024: 104.0, 2048: 52.0, 4096: 26.0} +S3_COMBO_MAX_RECORD_S = 13.0 +JOB_MIN, JOB_MAX = 1, 9999 + +_SERIES_FIELDS = { + 3: ("record_mode", "sample_rate", "histogram_interval_s", "record_time_s", "geo_trigger_ips", + "geo_range", "geo_alarm_ips", "job_number", "job_number_shown", + "note_1", "note_2", "note_3", "note_4"), + 4: ("record_mode", "sample_rate", "histogram_interval_s", "record_time_s", "geo_trigger_ips", + "job_number", "job_number_shown", "note_1", "note_2", "note_3", "note_4"), +} +_LEVELS = ("geo_trigger_ips", "geo_alarm_ips") + + +def _ch(k: int) -> int: + return _CHANNELS + _CHANNEL_SIZE * k + + +def _f32(c: bytes, offset: int) -> float: + return struct.unpack_from(">f", c, offset)[0] + + +def _shown(v: float) -> float: + """An f32 as an operator typed it: 0.30000001192 is 0.3.""" + return round(v, 6) + + +def _note_offsets(n: int) -> tuple: + label = _NOTE_LABEL + n * _NOTE_STRIDE + value = _NOTE_VALUE + n * _NOTE_STRIDE + return label, value + + +def _note_label(c: bytes, n: int) -> str: + start, _ = _note_offsets(n) + raw = c[start:start + _NOTE_LABEL_WIDTH].split(b"\x00")[0] + text = raw.decode("ascii", "replace").strip().rstrip(":").strip() + return text or f"Note {n + 1}" + + +def _note_value(c: bytes, n: int) -> str: + _, start = _note_offsets(n) + return c[start:start + _NOTE_WIDTH].split(b"\x00")[0].decode("ascii", "replace") + + +def field_bytes(series: int) -> Dict[str, Set[int]]: + """Every byte each field may move, by content offset.""" + def chans(rel: int, width: int) -> Set[int]: + return {_ch(k) + rel + i for k in _GEOPHONES for i in range(width)} + out = { + "record_mode": {_MODE}, + "sample_rate": set(range(6, 8)), + "histogram_interval_s": set(range(8, 10)), + "record_time_s": set(range(_RECORD_TIME, _RECORD_TIME + 4)), + "geo_trigger_ips": chans(_CH_TRIGGER, 4), + "geo_range": chans(_CH_RANGE, 1), + "geo_alarm_ips": chans(_CH_ALARM, 4), + "job_number": set(range(40, 42)), + "job_number_shown": {_REPORT_FLAGS}, + } + for n in range(_NOTES): + _, v = _note_offsets(n) + out[f"note_{n + 1}"] = set(range(v, v + _NOTE_WIDTH)) + return {f: out[f] for f in _SERIES_FIELDS[series]} + + +# ── Reading ───────────────────────────────────────────────────────────────── + +def _mode_name(c: bytes, series: int) -> str: + code = c[_MODE] + for name, value in MODES[series].items(): + if value == code: + return name + return f"unknown(0x{code:02x})" + + +def _range_code(c: bytes) -> int: + return c[_ch(0) + _CH_RANGE] + + +def _full_scale(c: bytes, series: int, range_name: Optional[str] = None) -> Optional[float]: + if series == 4: + return _FULL_SCALE[0] # Series 4's range byte is not mapped; 10 in/s is the hardware's + code = _RANGES[range_name] if range_name is not None else _range_code(c) + return _FULL_SCALE.get(code) + + +def _s3_max_record(rate: int, mode: str) -> Optional[float]: + top = S3_MAX_RECORD_S.get(rate) + if top is None: + return None + return min(top, S3_COMBO_MAX_RECORD_S) if mode == "histogram_continuous" else top + + +def _unit_string(c: bytes) -> List[str]: + return [c[_ch(k) + _CH_UNIT.start:_ch(k) + _CH_UNIT.stop].replace(b"\x00", b"") + .replace(b".", b"").decode("ascii", "replace") for k in _GEOPHONES] + + +def editable_fields(content: bytes, series: int) -> List[Dict[str, Any]]: + """The fields an operator can change, described for a form: field, label, + kind ("number" / "choice" / "text" / "bool"), value, and as relevant unit, + min, max, step, choices [{value, label}], maxlength, readonly.""" + c = content + rate = int.from_bytes(c[_SAMPLE_RATE], "big") + mode = _mode_name(c, series) + out: List[Dict[str, Any]] = [ + {"field": "record_mode", "label": "Record mode", "kind": "choice", "value": mode, + "choices": [{"value": n, "label": _MODE_LABELS[n]} for n in MODES[series]]}, + {"field": "sample_rate", "label": "Sample rate", "kind": "choice", "value": rate, "unit": "sps", + "choices": [{"value": r, "label": f"{r} sps"} for r in SAMPLE_RATES]}, + {"field": "histogram_interval_s", "label": "Histogram interval", "kind": "choice", + "value": int.from_bytes(c[_HIST_INTERVAL], "big"), + "choices": [{"value": s, "label": f"{s} s" if s < 60 else f"{s // 60} min"} for s in INTERVALS]}, + {"field": "record_time_s", "label": "Record time", "kind": "number", "unit": "s", + "value": _shown(_f32(c, _RECORD_TIME)), "min": RECORD_MIN_S, + "max": S4_MAX_RECORD_S if series == 4 else _s3_max_record(rate, mode)}, + {"field": "geo_trigger_ips", "label": "Geophone trigger", "kind": "number", "unit": "in/s", + "value": _shown(_f32(c, _ch(0) + _CH_TRIGGER)), "min": TRIGGER_MIN, + "max": min(TRIGGER_MAX, _full_scale(c, series) or TRIGGER_MAX), "step": TRIGGER_STEP}, + ] + if series == 3: + code = _range_code(c) + name = next((n for n, v in _RANGES.items() if v == code), f"unknown(0x{code:02x})") + out.append({"field": "geo_range", "label": "Geophone range", "kind": "choice", "value": name, + "choices": [{"value": "normal", "label": "Normal (10 in/s)"}, + {"value": "sensitive", "label": "Sensitive (1.25 in/s)"}]}) + out.append({"field": "geo_alarm_ips", "label": "Geophone alarm", "kind": "number", + "unit": "in/s", "value": _shown(_f32(c, _ch(0) + _CH_ALARM)), + "min": TRIGGER_MIN, "max": _full_scale(c, 3) or TRIGGER_MAX, + "step": TRIGGER_STEP, "readonly": not S3_ALARM_WRITE_MEASURED}) + out.append({"field": "job_number", "label": "Job number", "kind": "number", + "value": int.from_bytes(c[_JOB_NUMBER], "big"), "min": JOB_MIN, "max": JOB_MAX, "step": 1}) + out.append({"field": "job_number_shown", "label": "Job number on report", "kind": "bool", + "value": bool(c[_REPORT_FLAGS] & _JOB_SHOWN)}) + for n in range(_NOTES): + out.append({"field": f"note_{n + 1}", "label": _note_label(c, n), "kind": "text", + "value": _note_value(c, n), "maxlength": NOTE_MAX}) + return out + + +def field_values(content: bytes, series: int) -> Dict[str, Any]: + return {d["field"]: d["value"] for d in editable_fields(content, series)} + + +# ── Checking ──────────────────────────────────────────────────────────────── + +def _number(field: str, v: Any) -> float: + if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v): + raise SettingsValueError(f"{field} must be a number, not {v!r}") + return float(v) + + +def _integer(field: str, v: Any) -> int: + if isinstance(v, bool) or not isinstance(v, int): + raise SettingsValueError(f"{field} must be a whole number, not {v!r}") + return v + + +def check_changes(content: bytes, series: int, changes: Dict[str, Any]) -> Dict[str, Any]: + """The changes, normalised -- or SettingsValueError naming the first one SFM + will not make, and why. Checks names, types and the units' own limits, then + what depends on this unit's block: its unit strings and its range.""" + if series not in _SERIES_FIELDS: + raise SettingsValueError(f"Series {series} has no settings SFM can change") + if not isinstance(changes, dict) or not changes: + raise SettingsValueError("no settings to change") + allowed = _SERIES_FIELDS[series] + out: Dict[str, Any] = {} + for field, v in changes.items(): + if field not in allowed: + raise SettingsValueError(f"{field} is not a setting SFM can change on a Series {series} unit") + if field == "record_mode": + if v not in MODES[series]: + raise SettingsValueError(f"record_mode must be one of {', '.join(MODES[series])}, not {v!r}") + out[field] = v + elif field == "sample_rate": + if _integer(field, v) not in SAMPLE_RATES: + raise SettingsValueError(f"sample_rate must be one of {SAMPLE_RATES}, not {v}") + out[field] = v + elif field == "histogram_interval_s": + if _integer(field, v) not in INTERVALS: + raise SettingsValueError(f"histogram_interval_s must be one of {INTERVALS} s, not {v}") + out[field] = v + elif field == "geo_range": + if v not in _RANGES: + raise SettingsValueError(f"geo_range must be normal or sensitive, not {v!r}") + out[field] = v + elif field in ("geo_trigger_ips", "geo_alarm_ips"): + if field == "geo_alarm_ips" and not S3_ALARM_WRITE_MEASURED: + raise SettingsValueError("the alarm level is shown but not changed yet: a MiniMate " + "alarm write has never been measured (the bench measures it)") + x = _number(field, v) + if not TRIGGER_MIN <= x <= TRIGGER_MAX: + raise SettingsValueError(f"{field} must be {TRIGGER_MIN}-{TRIGGER_MAX} in/s, not {x}") + if abs(x - round(x, 3)) > 1e-9: + raise SettingsValueError(f"{field} must be in steps of {TRIGGER_STEP} in/s, not {x}") + out[field] = round(x, 3) + elif field == "record_time_s": + out[field] = _number(field, v) + elif field == "job_number": + if not JOB_MIN <= _integer(field, v) <= JOB_MAX: + raise SettingsValueError(f"job_number must be {JOB_MIN}-{JOB_MAX}, not {v}") + out[field] = v + elif field == "job_number_shown": + if not isinstance(v, bool): + raise SettingsValueError(f"job_number_shown must be true or false, not {v!r}") + out[field] = v + else: # note_1 .. note_4 + if not isinstance(v, str): + raise SettingsValueError(f"{field} must be text, not {v!r}") + if any(not 0x20 <= ord(ch) <= 0x7E for ch in v): + raise SettingsValueError(f"{field} must be plain printable ASCII (no accents, tabs or " + "line breaks)") + if len(v) > NOTE_MAX: + raise SettingsValueError(f"{field} is {len(v)} characters; the unit holds {NOTE_MAX}") + out[field] = v + + # What depends on this unit's block, with the NEW mode / rate / range if they change too. + c = content + if "record_time_s" in out: + t = out["record_time_s"] + if series == 4: + top: Optional[float] = S4_MAX_RECORD_S + else: + rate = out.get("sample_rate", int.from_bytes(c[_SAMPLE_RATE], "big")) + top = _s3_max_record(rate, out.get("record_mode", _mode_name(c, series))) + if top is None: + raise SettingsValueError(f"this unit's sample rate ({rate}) has no record-time limit " + "in the manual -- set the sample rate too") + if not RECORD_MIN_S <= t <= top: + raise SettingsValueError(f"record_time_s must be {RECORD_MIN_S}-{top:g} s here, not {t}") + if any(f in out for f in _LEVELS): + units = _unit_string(c) + if any(u != "in" for u in units): + raise SettingsValueError(f"this unit's geophone channels read {units}, not in/s -- only " + "in/s is measured, so SFM will not change a level") + full = _full_scale(c, series, out.get("geo_range")) + if full is None: + raise SettingsValueError("this unit's geophone range byte is not a value ever measured") + for f in _LEVELS: + if f in out and out[f] > full: + raise SettingsValueError(f"{f} {out[f]} in/s is above the range's full scale ({full} in/s)") + return out + + +# ── Writing ───────────────────────────────────────────────────────────────── + +def encode_setup(content: bytes, series: int, changes: Dict[str, Any]) -> bytes: + """`content` with only the changed fields' bytes moved. `changes` should + come from check_changes; this patches, it does not judge. Bit fields are + patched bit by bit. Series 3 also writes Blastware's fixed bytes; Series 4 + gets its checksum recomputed.""" + out = bytearray(content) + for field, v in changes.items(): + if field == "record_mode": + out[_MODE] = MODES[series][v] + elif field == "sample_rate": + out[_SAMPLE_RATE] = int(v).to_bytes(2, "big") + elif field == "histogram_interval_s": + out[_HIST_INTERVAL] = int(v).to_bytes(2, "big") + elif field == "record_time_s": + struct.pack_into(">f", out, _RECORD_TIME, float(v)) + elif field == "geo_trigger_ips": + for k in _GEOPHONES: + struct.pack_into(">f", out, _ch(k) + _CH_TRIGGER, float(v)) + elif field == "geo_alarm_ips": + for k in _GEOPHONES: + struct.pack_into(">f", out, _ch(k) + _CH_ALARM, float(v)) + elif field == "geo_range": + for k in _GEOPHONES: + out[_ch(k) + _CH_RANGE] = _RANGES[v] + elif field == "job_number": + out[_JOB_NUMBER] = int(v).to_bytes(2, "big") + elif field == "job_number_shown": + out[_REPORT_FLAGS] = (out[_REPORT_FLAGS] | _JOB_SHOWN) if v else (out[_REPORT_FLAGS] & ~_JOB_SHOWN) + elif field.startswith("note_") and field[5:].isdigit() and 1 <= int(field[5:]) <= _NOTES: + _, start = _note_offsets(int(field[5:]) - 1) + out[start:start + _NOTE_WIDTH] = v.encode("ascii").ljust(_NOTE_WIDTH, b"\x00") + else: + raise SettingsValueError(f"{field} is not a setting SFM can change") + if series == 3: + for offset, value in S3_BLASTWARE_FIXED.items(): + out[offset:offset + len(value)] = value + return bytes(out) + return with_crc(bytes(out)) + + +# ── Reading back ──────────────────────────────────────────────────────────── + +_COMPARED = 2090 + + +def settings_state(before: bytes, written: bytes, now: bytes, *, series: int) -> str: + """What a read of the unit says about a change, from the bytes alone: + "as asked" (it holds what was written), "unchanged" (it holds what it had), + or "differs". Floats are never compared -- 0.3 is the same f32 both ways. + Series 4 also needs the unit's own checksum to hold. Series 3 bytes that + differ only in Blastware's fixed bytes count as as asked: nothing the operator + asked for is different.""" + a, w, n = before[:_COMPARED], written[:_COMPARED], now[:_COMPARED] + if series == 4 and not crc_ok(now): + return "differs" + if n == w: + return "as asked" + if series == 3: + fixed = {o + i for o, v in S3_BLASTWARE_FIXED.items() for i in range(len(v))} + if len(n) == len(w) and all(n[i] == w[i] for i in range(len(n)) if i not in fixed): + return "as asked" + if n == a: + return "unchanged" + return "differs" + + +def revision(blocks: List[bytes]) -> str: + """A short fingerprint of the blocks a preview read; a live change must match it.""" + return hashlib.sha256(b"".join(bytes(b) for b in blocks)).hexdigest()[:16] diff --git a/tests/test_setup_fields.py b/tests/test_setup_fields.py new file mode 100644 index 0000000..a58d0ee --- /dev/null +++ b/tests/test_setup_fields.py @@ -0,0 +1,290 @@ +"""One settings codec for both series (phase 5): the field registry, the limits, +the byte patching, and the read-back verdict. + +Ground truth: + * Series 3: Blastware's own compliance writes -- BE11529's nine on 2026-04-20 + (bridges/captures/4-20-26) and BE9441's two on 2026-10-26 -- each reproduced + from the block before it with the fields Blastware changed. + * Series 4: the 15 UM20147 / UM12947 keypad fixtures, pairwise. +Limits are the units' own, from Instantel's manuals (Brian, 2026-11-03). +""" +from __future__ import annotations + +import glob +import itertools +import os +import re +import struct +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from micromate import setup_fields as sf # noqa: E402 +from micromate.setup_block import crc_ok # noqa: E402 +from micromate.setup_fields import ( # noqa: E402 + SettingsValueError, check_changes, editable_fields, encode_setup, field_bytes, field_values, + revision, settings_state, +) +from minimateplus.framing import S3FrameParser # noqa: E402 +from minimateplus.protocol import assemble_compliance_content, is_compliance_content # noqa: E402 +from test_minimate_write_frames import WRITES, _frames, _payload # noqa: E402 + +ROOT = Path(__file__).resolve().parent.parent +APRIL = ROOT / "bridges" / "captures" / "4-20-26" +S4_FIX = sorted(glob.glob(str(ROOT / "tests" / "fixtures" / "micromate-setup" / "*.bin"))) +TEN26 = ROOT / "tests" / "fixtures" / "minimate-bench-10-26-26-histogram" + + +def _s4(path) -> bytes: + b = Path(path).read_bytes() + return b[-2092:] if len(b) > 2092 else b + + +def _image(frames) -> bytes: + return b"".join(_payload(f)[16:] for f in frames if _payload(f)[2] == 0x71) + + +def _reads(replies: bytes) -> list: + """Each 1A read in a reply stream, assembled (a probe reply starts each).""" + reads, cur = [], None + for f in S3FrameParser().feed(replies): + if f.sub != 0xE5: + continue + if len(f.data) == 11: + cur = [] + reads.append(cur) + elif cur is not None: + cur.append(bytes(f.data)) + return [assemble_compliance_content(r) for r in reads if r] + + +def _april_pairs() -> list: + """(name, before, after) for BE11529's April writes, in time order.""" + if not APRIL.is_dir(): + return [] + files = sorted(glob.glob(str(APRIL / "**" / "raw_bw_*.bin"), recursive=True), + key=lambda p: re.search(r"_(\d{6})_", os.path.basename(p)).group(1)) + imgs = [(os.path.basename(p), _image(_frames(Path(p).read_bytes()))) for p in files] + imgs = [(n, i) for n, i in imgs if len(i) >= 2092] + pairs = [] + first_name, first_img = imgs[0] + s3 = Path(str(Path(files[0]).parent / first_name.replace("raw_bw_", "raw_s3_"))) + whole = [r for r in _reads(s3.read_bytes())] if s3.exists() else [] + whole = [r for r in whole if is_compliance_content(r)] + if whole: # the read Blastware took before its first write + pairs.append((first_name, whole[0], first_img)) + for (_, a), (n, b) in zip(imgs, imgs[1:]): + pairs.append((n, a, b)) + return pairs + + +def _ten26_pairs() -> list: + reads = _reads((TEN26 / "unit_replies.bin").read_bytes()) + i0, i1 = _image(WRITES[0:13]), _image(WRITES[13:26]) + return [("10-26 send1", reads[0], i0), ("10-26 send2", i0, i1)] + + +def _changes(before: bytes, after: bytes, series: int) -> dict: + a, b = field_values(before, series), field_values(after, series) + return {f: b[f] for f in b if b[f] != a[f]} + + +def _with_mic(encoded: bytes, after: bytes) -> bytes: + """Test-only: BE9441's 16:26 write also turned the mic on ([25] bit 0x08), a + byte v1 does not offer. Copy that one bit from Blastware's image.""" + out = bytearray(encoded) + out[25] = (out[25] & ~0x08) | (after[25] & 0x08) + return bytes(out) + + +def _blastware_mic_rerender(before: bytes, after: bytes) -> bytes: + """Blastware's write with the unit's own mic trigger levels put back where + Blastware re-rendered them through its dB value. Measured on BE11529's first + write of 2026-04-20 (15:19): the unit read 0.005 and 0.01 psi (channel blocks + 3 and 7, `MicL`), Blastware wrote 0.004983 and 0.010058 -- the same levels to + its 0.1 dB. SFM echoes the unit's bytes instead; every other byte must match.""" + out = bytearray(after) + for k in range(8): + o = 1708 + 48 * k + if before[o:o + 4] != b"MicL": + continue + a = struct.unpack_from(">f", before, o + 30)[0] + b = struct.unpack_from(">f", after, o + 30)[0] + if a != b and abs(a - b) <= 0.01 * abs(a): # 0.1 dB is 1.2 % in pressure + out[o + 30:o + 34] = before[o + 30:o + 34] + return bytes(out) + + +S3_PAIRS = _april_pairs() + _ten26_pairs() + + +@pytest.mark.parametrize("name,before,after", S3_PAIRS, ids=[p[0] for p in S3_PAIRS]) +def test_s3_reproduces_every_blastware_write(name, before, after): + out = _with_mic(encode_setup(before[:2090], 3, _changes(before, after, 3)), after) + assert out[:2090] == _blastware_mic_rerender(before, after)[:2090] + + +def test_the_blastware_writes_are_all_here(): + if not APRIL.is_dir(): + pytest.skip("bridges/captures is not on this machine") + assert len(S3_PAIRS) >= 10 # 8 April pairs (+1 if its first read is whole) and 2 on 10-26 + + +def _diffs(a: bytes, b: bytes) -> set: + return {i for i in range(2090) if a[i] != b[i]} + + +def test_s4_fixture_pairs_reproduce(): + fb = field_bytes(4) + covered = 0 + for pa, pb in itertools.permutations(S4_FIX, 2): + a, b = _s4(pa), _s4(pb) + d = _diffs(a, b) + if not d: + continue + touched = {f for f, bs in fb.items() if bs & d} + if d - set().union(*(fb[f] for f in touched)): + continue # a byte outside the registry moved: not a field-only pair + out = encode_setup(a, 4, {f: field_values(b, 4)[f] for f in touched}) + assert out == b, (os.path.basename(pa), os.path.basename(pb)) + covered += 1 + assert covered >= 10 + + +# ── limits (the units' own) ────────────────────────────────────────────────── + +S3_BLOCK = _ten26_pairs()[1][2][:2090] # BE9441, 4096 sps, histogram, Normal range +S4_BLOCK = _s4(ROOT / "tests" / "fixtures" / "micromate-setup" / "um20147_baseline.bin") + + +def _refused(block, series, changes): + with pytest.raises(SettingsValueError): + check_changes(block, series, changes) + + +def test_trigger_checked_against_the_new_range(): + _refused(S3_BLOCK, 3, {"geo_range": "sensitive", "geo_trigger_ips": 2.0}) + assert check_changes(S3_BLOCK, 3, {"geo_range": "sensitive", "geo_trigger_ips": 1.25}) + assert check_changes(S3_BLOCK, 3, {"geo_trigger_ips": 2.0}) + + +def test_limits_refuse_outside_values(): + for v in (0.004, 10.001, 0.3005): + _refused(S4_BLOCK, 4, {"geo_trigger_ips": v}) + for v in (0, 10000): + _refused(S4_BLOCK, 4, {"job_number": v}) + for v in (0.9, 90.1): + _refused(S4_BLOCK, 4, {"record_time_s": v}) + assert check_changes(S4_BLOCK, 4, {"record_time_s": 90.0}) + assert check_changes(S3_BLOCK, 3, {"record_time_s": 26.0}) # 4096 sps + _refused(S3_BLOCK, 3, {"record_time_s": 26.1}) + assert check_changes(S3_BLOCK, 3, {"record_mode": "histogram_continuous", "record_time_s": 13.0}) + _refused(S3_BLOCK, 3, {"record_mode": "histogram_continuous", "record_time_s": 13.1}) + assert check_changes(S3_BLOCK, 3, {"sample_rate": 1024, "record_time_s": 100.0}) # the new rate counts + _refused(S3_BLOCK, 3, {"sample_rate": 8192}) + _refused(S3_BLOCK, 3, {"histogram_interval_s": 30}) + _refused(S3_BLOCK, 3, {"geo_trigger_ips": "0.3"}) # a number, not a string + _refused(S3_BLOCK, 3, {"job_number": True}) + + +def test_field_not_offered_for_the_series(): + with pytest.raises(SettingsValueError, match="Series 4"): + check_changes(S4_BLOCK, 4, {"geo_range": "sensitive"}) + _refused(S4_BLOCK, 4, {"no_such_field": 1}) + + +def test_alarm_is_read_only_until_measured(): + assert sf.S3_ALARM_WRITE_MEASURED is False + _refused(S3_BLOCK, 3, {"geo_alarm_ips": 1.0}) + alarm = next(d for d in editable_fields(S3_BLOCK, 3) if d["field"] == "geo_alarm_ips") + assert alarm["readonly"] is True + + +def _with_unit(block: bytes, unit: bytes) -> bytes: + out = bytearray(block) + for k in range(3): + out[1708 + 48 * k + 34: 1708 + 48 * k + 38] = unit + return bytes(out) + + +def test_metric_unit_string_refuses_level_writes(): + _refused(_with_unit(S4_BLOCK, b"mm\x00\x00"), 4, {"geo_trigger_ips": 0.3}) + assert check_changes(_with_unit(S4_BLOCK, b"in.\x00"), 4, {"geo_trigger_ips": 0.3}) + assert check_changes(_with_unit(S4_BLOCK, b"in\x00\x00"), 4, {"geo_trigger_ips": 0.3}) + assert check_changes(_with_unit(S4_BLOCK, b"mm\x00\x00"), 4, {"job_number": 5}) # not a level + + +def test_note_edges(): + assert check_changes(S4_BLOCK, 4, {"note_1": ""}) + assert check_changes(S4_BLOCK, 4, {"note_1": "x" * 41}) + _refused(S4_BLOCK, 4, {"note_1": "x" * 42}) + _refused(S4_BLOCK, 4, {"note_1": "café"}) + _refused(S4_BLOCK, 4, {"note_1": "tab\there"}) + out = encode_setup(S4_BLOCK, 4, {"note_1": ""}) + assert out[144:186] == bytes(42) + + +def test_note_labels_are_never_written(): + out = encode_setup(S4_BLOCK, 4, {"note_2": "Loc 9 - North wall"}) + assert _diffs(S4_BLOCK, out) <= set(range(208, 250)) + assert out[186:208] == S4_BLOCK[186:208] + + +def test_bit_fields_keep_unknown_bits(): + b = bytearray(S4_BLOCK) + b[39] = 0x81 + assert encode_setup(bytes(b), 4, {"job_number_shown": True})[39] == 0x83 + b[39] = 0x83 + assert encode_setup(bytes(b), 4, {"job_number_shown": False})[39] == 0x81 + + +def test_s3_fixed_bytes(): + b = bytearray(S3_BLOCK) + b[26:28] = b"\x01\x7f" + assert encode_setup(bytes(b), 3, {"job_number": 7})[26:28] == b"\x00\x00" + + +def test_s4_encode_recomputes_the_crc(): + out = encode_setup(S4_BLOCK, 4, {"job_number": 7}) + assert crc_ok(out) and out[40:42] == (7).to_bytes(2, "big") + + +def test_f32_values_read_back_as_asked(): + written = encode_setup(S4_BLOCK, 4, {"geo_trigger_ips": 0.3}) + assert struct.unpack_from(">f", written, 1708 + 30)[0] != 0.3 # f32: 0.30000001192 + assert field_values(written, 4)["geo_trigger_ips"] == 0.3 + assert settings_state(S4_BLOCK, written, written, series=4) == "as asked" + + +def test_settings_state(): + written = encode_setup(S4_BLOCK, 4, {"job_number": 7}) + assert settings_state(S4_BLOCK, written, S4_BLOCK, series=4) == "unchanged" + other = encode_setup(S4_BLOCK, 4, {"job_number": 8}) + assert settings_state(S4_BLOCK, written, other, series=4) == "differs" + bad = bytearray(written) + bad[2091] ^= 0xFF + assert settings_state(S4_BLOCK, written, bytes(bad), series=4) == "differs" + # Series 3: a block that differs from its image only in Blastware's fixed bytes is as asked + before = bytearray(S3_BLOCK) + before[26:28] = b"\x01\x7f" + before = bytes(before) + assert settings_state(before, encode_setup(before, 3, {}), before, series=3) == "as asked" + + +def test_revision_is_stable_and_content_sensitive(): + r = revision([S4_BLOCK, b"name"]) + assert r == revision([S4_BLOCK, b"name"]) and len(r) == 16 + assert r != revision([S4_BLOCK, b"nams"]) + + +def test_editable_fields_describe_both_series(): + s3 = {d["field"]: d for d in editable_fields(S3_BLOCK, 3)} + s4 = {d["field"]: d for d in editable_fields(S4_BLOCK, 4)} + assert {"geo_range", "geo_alarm_ips"} <= set(s3) and not {"geo_range", "geo_alarm_ips"} & set(s4) + assert s3["record_mode"]["value"] == "histogram" and s3["sample_rate"]["value"] == 4096 + assert s3["note_1"]["label"] == "Project" and s3["note_1"]["maxlength"] == 41 + assert s4["note_1"]["label"] == "Location" + assert s4["record_time_s"]["max"] == 90.0 and s3["record_time_s"]["max"] == 26.0