"""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; write measured at the bench 2026-11-04 _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"} # Measured at the bench 2026-11-04 (BE9441, Brian's go): 1.0 -> 1.5 -> 1.0 in/s, # each acknowledged, read back, and shown in the unit's own setup menu; the write # moved exactly channel +39 of the three geophones (the f32 at +38). S3_ALARM_WRITE_MEASURED = True 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)} def field_rows(before: bytes, written: bytes, series: int, fields, now: Optional[bytes] = None) -> Dict[str, Dict[str, Any]]: """For each changed field: its label, the value the unit had (old), the value sent (new) and, given a read-back, what the unit now holds (now).""" a, w = field_values(before, series), field_values(written, series) n = field_values(now, series) if now is not None else None labels = {d["field"]: d["label"] for d in editable_fields(written, series)} out: Dict[str, Dict[str, Any]] = {} for f in fields: row: Dict[str, Any] = {"label": labels[f], "old": a[f], "new": w[f]} if n is not None: row["now"] = n[f] out[f] = row return out # ── 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 -- checked on the block that would RESULT, so a one-field change (the range, # the rate, the mode) cannot leave a value the unit already holds over its limit # (final review, 2026-11-03). c = content if any(f in out for f in ("record_time_s", "sample_rate", "record_mode")): t = out.get("record_time_s", _shown(_f32(c, _RECORD_TIME))) held = "" if "record_time_s" in out else f" (the unit holds {t:g} s; change the record time too)" 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}{held}") if any(f in out for f in (*_LEVELS, "geo_range")): 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 or the range") 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") held_levels = {"geo_trigger_ips": _CH_TRIGGER, "geo_alarm_ips": _CH_ALARM} for f in _LEVELS: if f not in _SERIES_FIELDS[series]: continue v = out.get(f, _shown(_f32(c, _ch(0) + held_levels[f]))) if v > full: held = "" if f in out else " (the unit holds it)" raise SettingsValueError(f"{f} {v} in/s is above the range's full scale ({full} in/s){held}") 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] def changes_bytes(changes: Dict[str, Any]) -> bytes: """The normalised changes, canonically: part of a preview's revision, so a live change must ask for exactly what was previewed (final review, 2026-11-03).""" import json return json.dumps(changes, sort_keys=True, separators=(",", ":")).encode("ascii")