From e8eabee4a246de669e6aa675e3fd705102d6a4e5 Mon Sep 17 00:00:00 2001 From: serversdown Date: Tue, 3 Nov 2026 21:51:20 -0500 Subject: [PATCH] feat(sfm): POST /device/settings/change; retire the legacy config write DeviceAccess.change_settings refuses before any I/O a request with no changes, a live change without its preview's revision, or no audit log, then dispatches the series' change (never retried). The route returns the preview (fields old -> new, warnings, blocked, revision) or the result (fields old/new/now), statuses as the other changes, and marks the cached by-host config dirty after a live change. /device/config and /device/config/project now answer 410 with a pointer. Deleted with them: MiniMateClient.apply_config / set_project_info and the raw-offset _encode_compliance_config (#46 found it wrong), the lab script poc_set_project.py and experiments.py's EXP6, both of which wrote a live unit through it. Git keeps them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- experiments.py | 107 ------- minimateplus/client.py | 372 +--------------------- poc_set_project.py | 68 ---- sfm/device_access/access.py | 34 +- sfm/server.py | 183 +++-------- tests/test_device_access_settings.py | 70 ++++ tests/test_minimate_write_frames.py | 36 +-- tests/test_s3_compliance_anchor_fields.py | 29 +- tests/test_server_series3_guard.py | 13 +- tests/test_server_settings_change.py | 153 +++++++++ 10 files changed, 316 insertions(+), 749 deletions(-) delete mode 100644 poc_set_project.py create mode 100644 tests/test_device_access_settings.py create mode 100644 tests/test_server_settings_change.py diff --git a/experiments.py b/experiments.py index 7c5bff3..58ce8ad 100644 --- a/experiments.py +++ b/experiments.py @@ -60,7 +60,6 @@ from minimateplus.framing import build_bw_frame, SESSION_RESET from minimateplus.client import ( MiniMateClient, _decode_compliance_config_into, - _encode_compliance_config, ) from minimateplus.models import DeviceInfo @@ -462,111 +461,6 @@ def exp_fewer_polls(host: str, port: int) -> tuple[str, str, dict]: t.disconnect() -# ══════════════════════════════════════════════════════════════════════════════ -# EXP6 — Compliance-only write (71×3→72), skip event index + trigger + waveform -# ══════════════════════════════════════════════════════════════════════════════ -# -# Blastware's full write sequence: 68→73 | 71×3→72 | 82→83 | 69→74→72 -# We want to know: can we write ONLY the compliance block (71×3→72)? -# -# Test procedure: -# 1. Read current compliance config (SUB 1A) -# 2. Patch the "notes" field to a test marker -# 3. Write ONLY 71×3→72 (skip 68, 73, 82, 83, 69, 74, final 72) -# 4. Read back (SUB 1A) and verify the change was written -# 5. Restore original value -# -# If PASS: we can push individual config fields without touching event index, -# trigger config, or waveform data — huge simplification. -# If FAIL: the device needs the full write sequence (may reject partial write). -# -# SAFETY: We restore original data in a finally block. If the restore write -# fails, the device will have the test marker in "notes" — harmless but visible. - -_EXP6_MARKER = "[exp6-test]" - -def exp_compliance_only(host: str, port: int) -> tuple[str, str, dict]: - """Write compliance block alone (71×3→72), verify, and restore.""" - client, info = connect_client(host, port) - original_raw: Optional[bytes] = None - try: - proto = client._proto - if proto is None: - return "FAIL", "Could not get protocol handle from client", {} - - # 1. Read current compliance - print(" Reading current compliance config (SUB 1A)…") - original_raw = proto.read_compliance_config() - print(f" Got {len(original_raw)} bytes of compliance config") - - # Find current notes value for display - info_obj = DeviceInfo() - _decode_compliance_config_into(original_raw, info_obj) - cc = info_obj.compliance_config - orig_notes = cc.notes if cc else "(unknown)" - print(f" Current notes field: {orig_notes!r}") - - # 2. Build modified payload with test marker in notes - test_notes = _EXP6_MARKER - modified_raw = _encode_compliance_config( - original_raw, - notes=test_notes, - ) - print(f" Encoded modified compliance payload ({len(modified_raw)} bytes)") - print(f" Patching notes: {orig_notes!r} → {test_notes!r}") - - # 3. Write ONLY the compliance block: 71×3 → 72 - print(" Writing compliance ONLY (71×3→72) — skipping 68/73/82/83/69/74…") - proto.write_compliance_config_raw(modified_raw) - print(" Write complete — device acked 71×3→72") - - # 4. Read back and verify - print(" Reading back compliance config to verify…") - readback_raw = proto.read_compliance_config() - readback_info = DeviceInfo() - _decode_compliance_config_into(readback_raw, readback_info) - rb_cc = readback_info.compliance_config - readback_notes = rb_cc.notes if rb_cc else "(decode failed)" - print(f" Read-back notes: {readback_notes!r}") - - write_worked = (readback_notes == test_notes) - print(f" Write verified: {write_worked}") - - details = { - "original_notes": orig_notes, - "written_notes": test_notes, - "readback_notes": readback_notes, - "write_verified": write_worked, - } - - if write_worked: - return "PASS", "Compliance-only write works! No event index or trigger writes needed.", details - else: - return "FAIL", f"Write was not reflected in read-back (got {readback_notes!r})", details - - except ProtocolError as exc: - return "FAIL", f"Protocol error: {exc}", {} - - finally: - # Restore original compliance data regardless of outcome - if original_raw is not None: - print(" Restoring original compliance config…") - try: - proto2 = client._proto - if proto2: - proto2.write_compliance_config_raw( - _encode_compliance_config(original_raw) # no-op patch = verbatim - ) - print(" Restore complete") - else: - print(" WARNING: protocol handle gone — could not restore") - except Exception as exc_r: - print(f" WARNING: restore failed: {exc_r}") - client.close() - - -# ══════════════════════════════════════════════════════════════════════════════ -# Registry + main # ══════════════════════════════════════════════════════════════════════════════ EXPERIMENTS = { @@ -575,7 +469,6 @@ EXPERIMENTS = { "no_5a": ("EXP3", exp_no_5a, "Event record (0C) without bulk waveform (5A)"), "skip_1e": ("EXP4", exp_skip_1e, "0A/0C with cached key — skip initial 1E"), "fewer_polls": ("EXP5", exp_fewer_polls, "1 POLL before 5A instead of Blastware's 3"), - "compliance_only": ("EXP6", exp_compliance_only, "Compliance-only write (71×3→72), no other blocks"), } diff --git a/minimateplus/client.py b/minimateplus/client.py index 527a1a7..01868de 100644 --- a/minimateplus/client.py +++ b/minimateplus/client.py @@ -70,15 +70,8 @@ S3_MONITORING_FLAGS = frozenset({0x10, 0x0B}) # ⚠ RETRACTED 2026-10-27 (#46): a trigger block "hardcoded from 3-11-26 -- no # read exists, Blastware writes this fixed blob". Blastware reads it first (SUB # 0x2E), and its byte 5 differs by unit and session (01 / 03 / 04 on record), so -# the copy changed that setting on any unit that differed. apply_config reads -# the unit's own block (MiniMateProtocol.read_trigger_config). - -# Compliance ASCII slot format (confirmed from 3-11-26 capture + label search): -# Each label occupies a 64-byte slot. -# Value starts at slot_start + 22, max 42 bytes, null-padded. -_COMPLIANCE_SLOT_SIZE = 64 -_COMPLIANCE_VALUE_OFFSET = 22 -_COMPLIANCE_VALUE_MAX = _COMPLIANCE_SLOT_SIZE - _COMPLIANCE_VALUE_OFFSET # 42 +# the copy changed that setting on any unit that differed. A settings write sends +# the unit's own block back (sfm.device_access.s3 change_settings, phase 5). # ── MiniMateClient ──────────────────────────────────────────────────────────── @@ -997,120 +990,6 @@ class MiniMateClient: log.info("push_config_raw: complete") - def apply_config( - self, - *, - # Recording parameters - recording_mode: Optional[int] = None, - sample_rate: Optional[int] = None, - record_time: Optional[float] = None, - histogram_interval_sec: Optional[int] = None, - # Threshold parameters (geo channels, in/s) - trigger_level_geo: Optional[float] = None, - alarm_level_geo: Optional[float] = None, - geo_range: Optional[int] = None, # 0x00=Normal 10in/s, 0x01=Sensitive 1.25in/s - # Project / operator strings - project: Optional[str] = None, - client_name: Optional[str] = None, - operator: Optional[str] = None, - seis_loc: Optional[str] = None, - notes: Optional[str] = None, - ) -> None: - """ - Read the current device config, apply any supplied changes to the - compliance block, and write the full config back to the device. - - Only non-None arguments are modified; all other bytes are round-tripped - verbatim from the device. - - Configurable fields - ------------------- - Recording parameters: - recording_mode : int — 0x00=Single Shot, 0x01=Continuous, 0x03=Histogram, 0x04=Histogram+Continuous - sample_rate : int — samples/sec; valid values: 1024, 2048, 4096 - record_time : float — record duration in seconds (e.g. 2.0, 3.0) - - Trigger/alarm thresholds and range (geo channels): - trigger_level_geo : float — trigger threshold in/s (e.g. 0.5) - alarm_level_geo : float — alarm threshold in/s (e.g. 1.0) - geo_range : int — 0x00=Normal 10.000 in/s, 0x01=Sensitive 1.250 in/s - (written to Tran/Vert/Long channel blocks) - - Project / operator strings (max 41 ASCII characters each): - project : str - client_name : str - operator : str - seis_loc : str — sensor location - notes : str — extended notes - - Write sequence (confirmed from 3-11-26 BW TX capture): - 68→73 | 71×3→72 | 82→83 | 69→74→72 - - Write payloads: - event_index_data : 88 bytes — read live via SUB 08 - compliance_data : ~2128 bytes — read live via SUB 1A (~2126 bytes, varies ±1-2) + \\x00\\x00 footer - trigger_data : 26 bytes — read live via SUB 2E (was hard-coded; #46) - waveform_data : 204 bytes — read live via SUB 09 - - Raises: - RuntimeError: if not connected. - ProtocolError: if any read or write step fails. - ValueError: if compliance buffer is shorter than the 2082-byte write minimum. - """ - proto = self._require_proto() - - # 1. Read current payloads from the device - log.info("apply_config: reading event index (SUB 08)") - event_index_data = proto.read_event_index() - - log.info("apply_config: reading compliance config (SUB 1A)") - compliance_raw = proto.read_compliance_config() # ~2126 bytes (varies ±1-2 by DLE jitter) - - log.info("apply_config: reading waveform data (SUB 09)") - waveform_data = proto.read_waveform_data_raw() # 204 bytes - - log.info("apply_config: reading trigger config (SUB 2E)") - trigger_data = proto.read_trigger_config() # 26 bytes, this unit's own - - # 2. Patch the compliance buffer and build the 2128-byte write payload - compliance_data = _encode_compliance_config( - compliance_raw, - recording_mode=recording_mode, - sample_rate=sample_rate, - record_time=record_time, - histogram_interval_sec=histogram_interval_sec, - trigger_level_geo=trigger_level_geo, - alarm_level_geo=alarm_level_geo, - geo_range=geo_range, - project=project, - client_name=client_name, - operator=operator, - seis_loc=seis_loc, - notes=notes, - ) - log.info("apply_config: compliance payload ready (%d bytes)", len(compliance_data)) - - # 3. Push the full write sequence to the device - self.push_config_raw(event_index_data, compliance_data, trigger_data, waveform_data) - log.info("apply_config: complete") - - def set_project_info( - self, - project: Optional[str] = None, - client_name: Optional[str] = None, - operator: Optional[str] = None, - seis_loc: Optional[str] = None, - notes: Optional[str] = None, - ) -> None: - """Backwards-compat shim — delegates to apply_config().""" - self.apply_config( - project=project, - client_name=client_name, - operator=operator, - seis_loc=seis_loc, - notes=notes, - ) - # ── Call home config ────────────────────────────────────────────────────── def get_call_home_config(self) -> CallHomeConfig: @@ -2127,253 +2006,6 @@ def _extract_project_strings(data: bytes) -> Optional[ProjectInfo]: ) -def _encode_compliance_config( - raw: bytes, - *, - recording_mode: Optional[int] = None, - sample_rate: Optional[int] = None, - record_time: Optional[float] = None, - trigger_level_geo: Optional[float] = None, - alarm_level_geo: Optional[float] = None, - geo_range: Optional[int] = None, # 0x00=Normal 10in/s, 0x01=Sensitive 1.25in/s - histogram_interval_sec: Optional[int] = None, - project: Optional[str] = None, - client_name: Optional[str] = None, - operator: Optional[str] = None, - seis_loc: Optional[str] = None, - notes: Optional[str] = None, -) -> bytes: - """ - Patch a live 2126-byte compliance buffer (read from the device) with any - supplied field values and return the 2128-byte write payload. - - Only non-None arguments are modified; everything else is round-tripped verbatim. - - Numeric field locations (all anchor-relative or label-relative — immune to - DLE-jitter shifts): - - Anchor: b'\\xbe\\x80\\x00\\x00\\x00\\x00' (confirmed stable, both BE11529 and BE18189) - ⚠ 2026-10-29: these RAW offsets were measured at 1024 sps, where the escape - before `04` sits between the mode and the anchor. The decoder now reads - the four fields after unescaping (mode -7, rate -6, interval -4, record - time +6), so at any other layout these patch the wrong bytes. Until the - encoder is rewritten on unescaped bytes (#46), a payload whose four fields - do not read back as asked raises ValueError -- see the end of this function. - recording_mode → uint8 at anchor_pos - 8 (raw; right at 1024 sps only) - Values: 0x00=Single Shot, 0x01=Continuous, 0x03=Histogram, 0x04=Histogram+Continuous - NOTE: The byte at anchor_pos - 7 is always 0x10 (a DLE marker regenerated by - device firmware in every E5 response). It must NOT be overwritten during - write — doing so causes anchor drift (+1 per write cycle). - CORRECTION 2026-04-21: previous doc stated anchor-7 for write; empirically - confirmed wrong — writing to anchor-7 shifts the anchor by 1 on every cycle. - sample_rate → uint16 BE at anchor_pos - 6 - histogram_interval_sec → uint16 BE at anchor_pos - 4 (seconds; mode-gated to Histogram/Histogram+Continuous) - Valid values: 2, 5, 15, 60, 300, 900 (= 2s, 5s, 15s, 1m, 5m, 15m) - record_time → float32 BE at anchor_pos + 6 - - Channel block (anchored on b"Tran" with unit-string guard): - geo_range → uint8 at tran_pos + 33 (confirmed 2026-04-20) - 0x00 = Normal 10.000 in/s, 0x01 = Sensitive 1.250 in/s - Written to Tran, Vert, Long channel blocks (all three). - adc_scale_factor → float32 BE at tran_pos + 28 (= 6.206053; do NOT write) - trigger_level_geo → float32 BE at tran_pos + 34 - "in.\\x00" → unit string at tran_pos + 38 (layout guard) - alarm_level_geo → float32 BE at tran_pos + 42 - "/s\\x00\\x00" → unit string at tran_pos + 46 (layout guard) - NOTE: tran_pos+28 (float32 = 6.206053) is the ADC-to-velocity scale factor - (= 1/sensitivity, (in/s)/V — Interface Handbook §4.5: 1.61133 V × 6.206053 = 10.000 in/s). - This is a hardware/firmware constant common to all MiniMate Plus S3 units. - It must NOT be written — do not add it back as a parameter. - - String field locations (64-byte slots, label+22 format): - b"Project:" → value at label_pos + 22, max 41 chars + null - b"Client:" → value at label_pos + 22, max 41 chars + null - b"User Name:" → value at label_pos + 22, max 41 chars + null - b"Seis Loc:" → value at label_pos + 22, max 41 chars + null - b"Extended Notes"→ value at label_pos + 22, max 41 chars + null - - Returns: - 2128-byte write payload: patched 2126-byte buffer + 2-byte footer \\x00\\x00. - (Checksum formula for the footer is unknown; \\x00\\x00 confirmed accepted - by the device in POC test 2026-04-07.) - - Raises: - ValueError: if raw is shorter than the minimum needed for the 3-chunk write. - """ - # Total size is nominally ~2126 bytes but varies by ±1-2 bytes depending on - # DLE jitter in the E5 read response (0x10 bytes in the config data cause - # 1-byte expansions per occurrence during DLE stuffing/unstuffing). The - # anchor-based field access and the chunk splitter (fixed chunk1=1027, - # chunk2=1055, chunk3=remainder) both handle variable length correctly. - # Only enforce a minimum — must have at least chunk1+chunk2 bytes of content. - _MIN_COMPLIANCE_LEN = 1027 + 1055 # = 2082 - if len(raw) < _MIN_COMPLIANCE_LEN: - raise ValueError( - f"_encode_compliance_config: compliance buffer too short " - f"({len(raw)} bytes, need at least {_MIN_COMPLIANCE_LEN})" - ) - if len(raw) not in range(2124, 2132): - log.warning( - "_encode_compliance_config: unusual compliance buffer length %d " - "(expected ~2126); proceeding with anchor-based access", - len(raw), - ) - - buf = bytearray(raw) - - # ── Numeric: recording_mode + sample_rate + record_time (anchor-relative) ── - _ANC = b'\xbe\x80\x00\x00\x00\x00' - _anc = buf.find(_ANC, 0, 150) - - # Log anchor position every time so we can detect unexpected shifts due to - # DLE jitter or firmware differences. Expected position is ~15. - if _anc < 0: - log.warning( - "_encode_compliance_config: anchor NOT FOUND in cfg[0:150] " - "(buf len=%d) — all anchor-relative writes will be skipped", - len(buf), - ) - else: - log.info( - "_encode_compliance_config: anchor at cfg[%d] buf_len=%d " - "(recording_mode@%d DLE_marker@%d sample_rate@%d:%d " - "histogram_interval@%d:%d record_time@%d:%d)", - _anc, len(buf), - _anc - 8, - _anc - 7, - _anc - 6, _anc - 4, - _anc - 4, _anc - 2, - _anc + 6, _anc + 10, - ) - - if recording_mode is not None: - if _anc < 8: - log.warning("_encode_compliance_config: anchor not found — cannot write recording_mode") - else: - # Write to anchor-8, same physical position as the E5 read format. - # The byte at anchor-7 is a DLE marker (0x10) that the device firmware - # regenerates in every E5 response — it must NOT be overwritten. - # Writing to anchor-7 causes the device to add an extra byte on the - # next read-back, drifting the anchor by +1 on every write cycle. - # (CLAUDE.md "anchor-7 write" was incorrect — confirmed 2026-04-21) - buf[_anc - 8] = recording_mode & 0xFF - log.debug("_encode_compliance_config: recording_mode=0x%02X -> offset %d", - recording_mode, _anc - 8) - - if sample_rate is not None: - if _anc < 6: - log.warning("_encode_compliance_config: anchor not found — cannot write sample_rate") - else: - struct.pack_into(">H", buf, _anc - 6, sample_rate) - log.debug("_encode_compliance_config: sample_rate=%d -> offset %d", sample_rate, _anc - 6) - - if histogram_interval_sec is not None: - if _anc < 4: - log.warning("_encode_compliance_config: anchor not found — cannot write histogram_interval") - else: - struct.pack_into(">H", buf, _anc - 4, histogram_interval_sec) - log.debug("_encode_compliance_config: histogram_interval=%ds -> offset %d", - histogram_interval_sec, _anc - 4) - - if record_time is not None: - if _anc < 0 or _anc + 10 > len(buf): - log.warning("_encode_compliance_config: anchor not found — cannot write record_time") - else: - struct.pack_into(">f", buf, _anc + 6, record_time) - log.debug("_encode_compliance_config: record_time=%.3f -> offset %d", record_time, _anc + 6) - - # ── Numeric: channel block (Tran label + unit-string guard) ─────────────── - # NOTE: tran_pos+24 (write format) or tran_pos+28 (E5 read format) is the - # ADC-to-velocity scale factor (6.206053, hardware constant — never written). - # geo_range is written to ALL THREE geo channel blocks (Tran, Vert, Long), - # confirmed from 4-20-26 captures showing the byte at label+29 in each block. - _needs_channel = any(v is not None for v in (trigger_level_geo, alarm_level_geo, geo_range)) - if _needs_channel: - _tran = buf.find(b"Tran", 44) - _valid = ( - _tran >= 0 - and buf[_tran + 4 : _tran + 5] != b"2" - and _tran + 50 <= len(buf) - and buf[_tran + 38 : _tran + 42] == b"in.\x00" - and buf[_tran + 46 : _tran + 50] == b"/s\x00\x00" - ) - if not _valid: - log.warning( - "_encode_compliance_config: 'Tran' channel block not found or unit " - "guard failed — trigger/alarm/geo_range will not be written" - ) - else: - if trigger_level_geo is not None: - struct.pack_into(">f", buf, _tran + 34, trigger_level_geo) - log.debug("_encode_compliance_config: trigger_level_geo=%.4f -> offset %d", trigger_level_geo, _tran + 34) - if alarm_level_geo is not None: - struct.pack_into(">f", buf, _tran + 42, alarm_level_geo) - log.debug("_encode_compliance_config: alarm_level_geo=%.4f -> offset %d", alarm_level_geo, _tran + 42) - if geo_range is not None: - # Write geo_range to all three geo channel blocks (Tran, Vert, Long). - # Field at label+33 in the E5-format compliance bytes (same in read and write - # since the 2126-byte payload is round-tripped verbatim). - # 0x00 = Normal 10.000 in/s, 0x01 = Sensitive 1.250 in/s. - for _ch_label in (b"Tran", b"Vert", b"Long"): - _ch = buf.find(_ch_label, 44) - if _ch >= 0 and buf[_ch + 4 : _ch + 5] != b"2" and _ch + 34 <= len(buf): - buf[_ch + 33] = geo_range & 0xFF - log.debug( - "_encode_compliance_config: geo_range=0x%02X -> %s+33 offset %d", - geo_range, _ch_label.decode(), _ch + 33, - ) - - # ── ASCII strings (64-byte slot, value at label_pos+22) ─────────────────── - def _set_string(label: bytes, value: Optional[str]) -> None: - if value is None: - return - idx = buf.find(label) - if idx < 0: - log.warning("_encode_compliance_config: label %r not found", label) - return - val_bytes = value.encode("ascii", errors="replace")[:_COMPLIANCE_VALUE_MAX - 1] - padded = val_bytes + b"\x00" * (_COMPLIANCE_VALUE_MAX - len(val_bytes)) - buf[idx + _COMPLIANCE_VALUE_OFFSET : idx + _COMPLIANCE_SLOT_SIZE] = padded - log.debug("_encode_compliance_config: %r -> %r", label, value) - - _set_string(b"Project:", project) - _set_string(b"Client:", client_name) - _set_string(b"User Name:", operator) - _set_string(b"Seis Loc:", seis_loc) - _set_string(b"Extended Notes", notes) - - # ── Read-back check: the payload must decode to what was asked ──────────── - # The decoder is the measured layout (every recorded reply); these offsets are - # 1024-sps raw ones. A mode change on BE9441's 10-25 Continuous / 4096 block - # rewrote the byte in front of the mode and read back unchanged. Refuse it - # here, before push_config_raw sends anything. - asked = {"recording_mode": recording_mode, "sample_rate": sample_rate, - "histogram_interval_sec": histogram_interval_sec, "record_time": record_time} - if any(v is not None for v in asked.values()): - before, after = _settings_read_back(raw), _settings_read_back(bytes(buf)) - if record_time is not None: - asked["record_time"] = struct.unpack(">f", struct.pack(">f", record_time))[0] - want = {k: (v if v is not None else before[k]) for k, v in asked.items()} - wrong = {k: (after[k], want[k]) for k in asked if after[k] != want[k]} - if wrong: - raise ValueError( - "_encode_compliance_config: the patched block would not read back as asked (" - + ", ".join(f"{k} reads {got!r}, not {exp!r}" for k, (got, exp) in wrong.items()) - + ") -- refused, nothing built or sent. The encoder's offsets were measured at " - "1024 sps and need rewriting on unescaped bytes (#46)." - ) - - # 2-byte footer — checksum formula unknown; \x00\x00 confirmed accepted by device - return bytes(buf) + b"\x00\x00" - - -def _settings_read_back(data: bytes) -> dict: - """Mode, sample rate, interval and record time as the decoder reads `data`.""" - info = DeviceInfo(serial="", firmware_minor=0) - _decode_compliance_config_into(data, info) - cc = info.compliance_config - return {k: getattr(cc, k, None) if cc is not None else None - for k in ("recording_mode", "sample_rate", "histogram_interval_sec", "record_time")} def _decode_compliance_config_into(data: bytes, info: DeviceInfo) -> None: diff --git a/poc_set_project.py b/poc_set_project.py deleted file mode 100644 index b5ecc51..0000000 --- a/poc_set_project.py +++ /dev/null @@ -1,68 +0,0 @@ -""" -poc_set_project.py — POC test for set_project_info() against a live MiniMate Plus. - -Usage: - python poc_set_project.py [--host IP] [--port PORT] - -Default target: BE11529 at 63.43.212.232:9034 -""" - -import argparse -import logging -import sys - -logging.basicConfig( - level=logging.DEBUG, - format="%(asctime)s %(levelname)-7s %(name)s %(message)s", - datefmt="%H:%M:%S", -) -log = logging.getLogger("poc_set_project") - -from minimateplus import MiniMateClient -from minimateplus.transport import TcpTransport - - -DEFAULT_HOST = "63.43.212.232" -DEFAULT_PORT = 9034 - - -def main() -> None: - ap = argparse.ArgumentParser(description="POC: write project info to MiniMate Plus") - ap.add_argument("--host", default=DEFAULT_HOST, help="Modem IP address") - ap.add_argument("--port", type=int, default=DEFAULT_PORT, help="TCP port") - ap.add_argument("--project", default="POC Write Test") - ap.add_argument("--client-name", default="Terra-Mechanics Inc.") - ap.add_argument("--operator", default="B. Harrison") - ap.add_argument("--seis-loc", default="Lab Bench - POC") - ap.add_argument("--notes", default="set_project_info POC 2026-04-07") - args = ap.parse_args() - - log.info("Connecting to %s:%d", args.host, args.port) - transport = TcpTransport(args.host, port=args.port) - - with MiniMateClient(transport=transport, timeout=60.0) as client: - log.info("Performing POLL handshake + identity read …") - info = client.connect() - log.info("Connected: serial=%s firmware=%s", info.serial, info.firmware_version) - - log.info("Calling set_project_info() …") - client.set_project_info( - project=args.project, - client_name=args.client_name, - operator=args.operator, - seis_loc=args.seis_loc, - notes=args.notes, - ) - log.info("set_project_info() returned — write sequence complete") - - log.info("Done. Reconnect Blastware to verify the fields were written.") - - -if __name__ == "__main__": - try: - main() - except KeyboardInterrupt: - sys.exit(0) - except Exception as exc: - log.exception("Fatal: %s", exc) - sys.exit(1) diff --git a/sfm/device_access/access.py b/sfm/device_access/access.py index 77bacb2..d9599aa 100644 --- a/sfm/device_access/access.py +++ b/sfm/device_access/access.py @@ -9,7 +9,7 @@ import threading import time from typing import Any, Callable, Dict, Optional -from .errors import ConnectFailed, DeviceError, NoAnswer, NotSupported, WrongUnit +from .errors import BadRequest, ConnectFailed, DeviceError, NoAnswer, NotSupported, WrongUnit from .events import parse_event_id from .locks import UnitLocks from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo, @@ -17,6 +17,7 @@ from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, Un from .s3 import Series3Adapter, default_s3_client_factory from .s4 import ( Series4Session, default_s4_client_factory, s4_call_home_state, s4_change_call_home, s4_change_monitoring, + s4_change_settings, s4_download_event, s4_identify, s4_list_events, s4_settings, s4_status, ) from .series import normalise_serial, series_for_serial @@ -27,6 +28,9 @@ log = logging.getLogger("sfm.device_access") # reads, a second apart -- not the start/stop window. _CALL_HOME_VERIFY_TIMEOUT_S = 3.0 _CALL_HOME_VERIFY_INTERVAL_S = 1.0 +# A settings read-back is one block read (seconds over cellular): two tries, a second apart. +_SETTINGS_VERIFY_TIMEOUT_S = 2.0 +_SETTINGS_VERIFY_INTERVAL_S = 1.0 class DeviceAccess: @@ -140,6 +144,34 @@ class DeviceAccess: lambda c, s: s4_change_call_home(c, s, address=address, **kw), change=True) + def change_settings(self, address: UnitAddress, serial: str, *, changes: dict, + revision: Optional[str], dry_run: bool = False, + caller: str = "api") -> ChangeResult: + """Change the unit's settings (spec row 10, phase 5). A dry run is the + preview: old -> new per field and a `revision`. A live change needs that + revision; it is audited, identity-checked, sent once, never retried, and + read back. Refused before any I/O: no changes, a live call without a + revision, no audit log.""" + serial = normalise_serial(serial) + series_for_serial(serial) # BadRequest (422) before anything else + if not isinstance(changes, dict) or not changes: + raise BadRequest("no settings to change -- nothing sent") + if not dry_run and not revision: + raise BadRequest("preview first: a live change needs the revision from its preview " + "-- nothing sent") + if not dry_run and self._audit is None: + raise NotSupported("no audit log is configured -- SFM refuses to change a unit " + "without one (nothing sent)") + kw = dict(changes=changes, revision=revision, dry_run=dry_run, audit=self._audit, + caller=caller, sleep=self._sleep, + verify_timeout_s=_SETTINGS_VERIFY_TIMEOUT_S, + verify_interval_s=_SETTINGS_VERIFY_INTERVAL_S) + return self._dispatch( + address, serial, + lambda a, s: self._s3.change_settings(a, s, **kw), + lambda c, s: s4_change_settings(c, s, address=address, **kw), + change=True) + def held_serial(self, address: UnitAddress) -> Optional[str]: """Serial of the OPEN held Series-4 line at this address, else None. No I/O.""" with self._sessions_guard: diff --git a/sfm/server.py b/sfm/server.py index ab3b0c6..8701472 100644 --- a/sfm/server.py +++ b/sfm/server.py @@ -50,7 +50,7 @@ import tempfile import threading import time from pathlib import Path -from typing import Mapping, Optional +from typing import Any, Dict, Mapping, Optional # FastAPI / Pydantic try: @@ -426,6 +426,7 @@ _SERIAL_AWARE_PATHS = frozenset({ "/device/events", "/device/events/download", "/device/monitor/start", "/device/monitor/stop", "/device/call_home/state", "/device/call_home/enable", "/device/call_home/disable", + "/device/settings/change", }) @@ -1112,145 +1113,61 @@ def device_event_blastware_file( # ── Write endpoints ─────────────────────────────────────────────────────────── -class DeviceConfigBody(BaseModel): - """ - Request body for POST /device/config. - - All fields are optional — only supplied (non-null) fields are written to - the device. All other config bytes are round-tripped verbatim. - - Recording parameters - -------------------- - recording_mode : Recording mode enum. Values: 0=Single Shot, 1=Continuous, 3=Histogram, 4=Histogram+Continuous. - sample_rate : Samples per second. Valid values: 1024, 2048, 4096. - record_time : Record duration in seconds (e.g. 1.0, 2.0, 3.0). - - Trigger / alarm thresholds and range (geo channels) - ---------------------------------------------------- - trigger_level_geo : Trigger threshold in in/s (e.g. 0.5). - alarm_level_geo : Alarm threshold in in/s (e.g. 1.0). - geo_range : Geophone range/sensitivity. 0=Normal 10.000 in/s, 1=Sensitive 1.250 in/s. - Project / operator strings (max 41 ASCII characters each) - ---------------------------- - project : Project description. - client_name : Client / company name. - operator : Operator / technician name. - seis_loc : Sensor location description. - notes : Extended notes. - """ - # Recording parameters - recording_mode: Optional[int] = None - sample_rate: Optional[int] = None - record_time: Optional[float] = None - histogram_interval_sec: Optional[int] = None # seconds: 2, 5, 15, 60, 300, 900 (mode-gated) - # Threshold parameters / geo range - trigger_level_geo: Optional[float] = None - alarm_level_geo: Optional[float] = None - geo_range: Optional[int] = None # 0=Normal 10.000 in/s, 1=Sensitive 1.250 in/s - # Project / operator strings - project: Optional[str] = None - client_name: Optional[str] = None - operator: Optional[str] = None - seis_loc: Optional[str] = None - notes: Optional[str] = None +_CONFIG_RETIRED = ("retired: change a unit's settings by serial with POST /device/settings/change " + "(audited, previewed, read back)") @app.post("/device/config") -def device_config( - body: DeviceConfigBody, - port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"), - baud: int = Query(38400, description="Serial baud rate"), - host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"), - tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"), - serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC), -) -> dict: - """ - Read the current device config, apply any supplied changes to the compliance - block, and write the full config back. - - Only non-null fields in the JSON body are modified. All other config bytes - are round-tripped verbatim from the device. - - Supply either *port* (serial) or *host* (TCP/modem). - - Example body (all fields optional — include only what you want to change): - { - "recording_mode": 1, - "sample_rate": 1024, - "record_time": 3.0, - "trigger_level_geo": 0.5, - "alarm_level_geo": 1.0, - "project": "Bridge Inspection 2026", - "client_name": "City of Portland", - "operator": "Brian Harrison", - "seis_loc": "South Abutment", - "notes": "Pre-blast baseline" - } - - Returns: - {"status": "ok", "updated_fields": {...}} on success. - - Raises: - 502 on protocol errors (timeout, bad ack, etc.). - 422 if neither port nor host is provided. - """ - changed = body.model_dump(exclude_none=True) - conn_key = _live_cache.make_conn_key(host, tcp_port, port, baud) - log.info("POST /device/config port=%s host=%s fields=%s", port, host, list(changed.keys())) - - try: - def _do(): - with _build_client(port, baud, host, tcp_port) as client: - info = client.connect() - _require_series3(info.serial, serial) - client.apply_config( - recording_mode=body.recording_mode, - sample_rate=body.sample_rate, - record_time=body.record_time, - histogram_interval_sec=body.histogram_interval_sec, - trigger_level_geo=body.trigger_level_geo, - alarm_level_geo=body.alarm_level_geo, - geo_range=body.geo_range, - project=body.project, - client_name=body.client_name, - operator=body.operator, - seis_loc=body.seis_loc, - notes=body.notes, - ) - _run_with_retry(_do, is_tcp=_is_tcp(host)) - except HTTPException: - raise - except ProtocolError as exc: - raise HTTPException(status_code=502, detail=f"Protocol error: {exc}") from exc - except OSError as exc: - raise HTTPException(status_code=502, detail=f"Connection error: {exc}") from exc - except ValueError as exc: - raise HTTPException(status_code=422, detail=str(exc)) from exc - except Exception as exc: - raise HTTPException(status_code=500, detail=f"Device error: {exc}") from exc - - # Config was written to the device — the cached compliance config is now stale. - conn_key = SFMCache.make_conn_key(host, tcp_port, port, baud) - get_cache().mark_config_dirty(conn_key) - - return { - "status": "ok", - "updated_fields": changed, - } +def device_config() -> JSONResponse: + """Retired (phase 5, 2026-11-03). It wrote a MiniMate's settings through an + encoder #46 found wrong, unaudited, with no read-back, retrying the whole + write on a TCP error. Use POST /device/settings/change.""" + return JSONResponse(status_code=410, content={"detail": _CONFIG_RETIRED}) -# Keep the old endpoint alive under its old URL for anything already calling it @app.post("/device/config/project") -def device_config_project( - body: DeviceConfigBody, - port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"), - baud: int = Query(38400, description="Serial baud rate"), - host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"), +def device_config_project() -> JSONResponse: + """Retired with POST /device/config -- use POST /device/settings/change.""" + return JSONResponse(status_code=410, content={"detail": _CONFIG_RETIRED}) + + +class SettingsChangeBody(BaseModel): + """POST /device/settings/change. `changes` maps field -> new value, using + the field names in GET /device/settings' `detail.editable`. `revision` is the + one a dry run (the preview) returned; a live change without it is refused.""" + changes: Dict[str, Any] + revision: Optional[str] = None + + +@app.post("/device/settings/change") +def device_settings_change( + body: SettingsChangeBody, + serial: str = Query(..., description=_SERIAL_DOC), + host: Optional[str] = Query(None, description="TCP host — modem IP"), tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"), - serial: Optional[str] = Query(None, description=_SERIAL_CHECK_DOC), -) -> dict: - """Deprecated alias for POST /device/config — use that instead.""" - return device_config(body=body, port=port, baud=baud, host=host, tcp_port=tcp_port, serial=serial) + port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"), + baud: Optional[int] = Query(None, description="Serial baud rate"), + dry_run: bool = Query(False, description="Preview: old -> new and a revision; send nothing"), + caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"), +): + """Change a unit's settings by serial, both series (spec row 10, phase 5). + + Preview first (`dry_run=true`): it reads the unit and returns, per field, the + value it holds and the value it would get, any warnings, anything that blocks + the change, and a `revision`. Then send the same body live with that + revision: identity read first, refused if the unit is monitoring or its + settings changed since the preview (409), sent once, never retried, read back. + Statuses as /device/monitor/start; a change that went out but was not + confirmed carries `sent` and `audit_id`.""" + resp = _change_response(lambda: _device_access().change_settings( + _unit_address(port, baud, host, tcp_port), serial, changes=body.changes, + revision=body.revision, dry_run=dry_run, caller=caller or "api")) + if not dry_run: + try: # a by-host read must not serve stale settings + get_cache().mark_config_dirty(_live_cache.make_conn_key(host, tcp_port, port, baud)) + except Exception as exc: # noqa: BLE001 -- the change's answer stands + log.warning("could not mark the cached config dirty: %s", exc) + return resp # ── Monitoring endpoints ─────────────────────────────────────────────────────── diff --git a/tests/test_device_access_settings.py b/tests/test_device_access_settings.py new file mode 100644 index 0000000..9569152 --- /dev/null +++ b/tests/test_device_access_settings.py @@ -0,0 +1,70 @@ +"""DeviceAccess.change_settings (phase 5): the series-independent entry point -- +what it refuses before any I/O, and that it dispatches a change (never retried).""" +from __future__ import annotations + +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from device_access_fakes import FakeMiniMateClient, FakeMicromateClient # noqa: E402 +from sfm.device_access.access import DeviceAccess # noqa: E402 +from sfm.device_access.errors import BadRequest, NotSupported # noqa: E402 +from sfm.device_access.models import UnitAddress # noqa: E402 + +ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None) + + +class Audit: + def __init__(self): + self.rows = {} + + def begin(self, **f): + cid = f"c{len(self.rows) + 1}" + self.rows[cid] = dict(f, outcome="pending") + return cid + + def finish(self, cid, **f): + self.rows[cid].update(f) + + +def _never(*a, **kw): + raise AssertionError("no connection may be opened") + + +def _access(s3=_never, s4=_never, audit="default"): + return DeviceAccess(s3_client_factory=s3, s4_client_factory=s4, start_reaper=False, + audit=Audit() if audit == "default" else audit, sleep=lambda s: None) + + +def test_live_change_without_revision_is_refused_before_io(): + with pytest.raises(BadRequest, match="preview first"): + _access().change_settings(ADDR, "UM20147", changes={"job_number": 7}, revision=None) + + +@pytest.mark.parametrize("changes", [{}, None, "job_number=7"]) +def test_empty_changes_is_a_bad_request(changes): + with pytest.raises(BadRequest): + _access().change_settings(ADDR, "BE18193", changes=changes, revision="r", dry_run=True) + + +def test_a_live_change_without_an_audit_log_is_refused(): + with pytest.raises(NotSupported, match="audit"): + _access(audit=None).change_settings(ADDR, "BE18193", changes={"job_number": 7}, revision="r") + + +def test_change_settings_dispatches_by_series_with_change_true(monkeypatch): + access = _access(s3=lambda a, **kw: FakeMiniMateClient(), s4=lambda a, **kw: FakeMicromateClient()) + seen = [] + real = access._dispatch + + def spy(address, serial, s3_op, s4_op, *, change=False): + seen.append((serial, change)) + return real(address, serial, s3_op, s4_op, change=change) + monkeypatch.setattr(access, "_dispatch", spy) + r3 = access.change_settings(ADDR, "be18193", changes={"job_number": 7}, revision=None, dry_run=True) + r4 = access.change_settings(ADDR, "UM20147", changes={"job_number": 7}, revision=None, dry_run=True) + assert (r3.series, r4.series) == (3, 4) and r3.outcome == r4.outcome == "dry_run" + assert seen == [("BE18193", True), ("UM20147", True)] diff --git a/tests/test_minimate_write_frames.py b/tests/test_minimate_write_frames.py index 94683b5..05e87dc 100644 --- a/tests/test_minimate_write_frames.py +++ b/tests/test_minimate_write_frames.py @@ -213,40 +213,8 @@ def test_each_read_returns_the_block_blastware_then_wrote(read, sub, size): assert block[:-2] == want[:-2] if sub == 0x69 else block == want[:-2] -# -- apply_config writes this unit's own trigger block --------------------------- - -class StubProto: - """Serves BE9441's blocks as read on 2026-10-26; records every write.""" - - def __init__(self): - self.writes = [] - - def read_event_index(self): - return _image(0x68)[:-2] - - def read_compliance_config(self): - return _image(0x71)[:-2] - - def read_waveform_data_raw(self): - return _image(0x69) - - def read_trigger_config(self): - return _image(0x82)[:-2] - - def __getattr__(self, name): - if name.startswith("write_"): - return lambda *a, **k: self.writes.append((name, a)) - raise AttributeError(name) - - -def test_apply_config_writes_the_units_own_trigger_block(): - from minimateplus.client import MiniMateClient - c = MiniMateClient(transport=object()) - c._proto = StubProto() - c.apply_config() # nothing changed: a round trip - trig = [a[0] for n, a in c._proto.writes if n == "write_trigger_config"] - assert trig == [_image(0x82)[:-2]] - assert trig[0][5] == 0x01 # BE9441's; the March copy had 0x03 +# -- the unit's own trigger block is sent back: tests/test_device_access_s3_settings.py +# (test_s3_trigger_change_sends_the_units_own_blocks), phase 5. def test_a_bad_block_is_refused_before_the_first_write_goes_out(): diff --git a/tests/test_s3_compliance_anchor_fields.py b/tests/test_s3_compliance_anchor_fields.py index 52f2d4d..a7b0389 100644 --- a/tests/test_s3_compliance_anchor_fields.py +++ b/tests/test_s3_compliance_anchor_fields.py @@ -96,30 +96,5 @@ def test_a_reply_without_the_settings_block_reads_as_unknown(): (None, None, None, None) -# The write side (review finding, 2026-10-29). _encode_compliance_config patches -# the RAW bytes at offsets measured at 1024 sps (April 2026), where an escape sits -# between the mode and the anchor. At other rates the mode is one byte later, so -# a mode change rewrote the byte in front of it. A payload that would not read -# back as asked is refused before anything is sent. - -from minimateplus.client import _encode_compliance_config # noqa: E402 - - -def _block(i): - return _settings_replies()[i].ljust(2126, b"\x00") # a whole block's length - - -@pytest.mark.parametrize("i, change", [ - (0, {"recording_mode": 0}), # 10-25 Continuous / 4096: mode sits at -7, not -8 - (1, {"sample_rate": 4096}), # 10-26 Histogram+Continuous / 2048: escaped mode shifts the rate -]) -def test_a_change_that_would_not_read_back_is_refused(i, change): - with pytest.raises(ValueError, match="read back"): - _encode_compliance_config(_block(i), **change) - - -def test_a_change_that_reads_back_as_asked_is_built(): - out = _encode_compliance_config(_block(0), record_time=7.0) - cc = _decode(out) - assert (cc.recording_mode, cc.sample_rate, cc.histogram_interval_sec, cc.record_time) == \ - (1, 4096, 5, 7.0) +# The write side moved to the shared settings codec in phase 5 (2026-11-03): +# tests/test_setup_fields.py reproduces every Blastware write byte for byte. diff --git a/tests/test_server_series3_guard.py b/tests/test_server_series3_guard.py index a52ef91..7f601c9 100644 --- a/tests/test_server_series3_guard.py +++ b/tests/test_server_series3_guard.py @@ -23,7 +23,7 @@ from fastapi import HTTPException # noqa: E402 import sfm.server as srv # noqa: E402 -WRITES = {"delete_all_events", "apply_config", "set_call_home_config", "stop_monitoring"} +WRITES = {"delete_all_events", "set_call_home_config", "stop_monitoring"} ADDR = dict(port=None, baud=38400, host="10.0.0.9", tcp_port=9034) @@ -56,9 +56,6 @@ class Unit: def delete_all_events(self): self._rec("delete_all_events") - def apply_config(self, **kw): - self._rec("apply_config") - def set_call_home_config(self, **kw): self._rec("set_call_home_config") @@ -72,8 +69,6 @@ class Cache: def _call(route, serial): - if route == "config": - return srv.device_config(body=srv.DeviceConfigBody(), serial=serial, **ADDR) if route == "erase": return srv.device_events_erase(serial=serial, **ADDR) if route == "rescue": @@ -98,7 +93,7 @@ def unit(monkeypatch): return make -ROUTES = ["config", "erase", "rescue", "call_home"] +ROUTES = ["erase", "rescue", "call_home"] # /device/config is retired (410) @pytest.mark.parametrize("route", ROUTES) @@ -131,8 +126,8 @@ def test_guarded_route_proceeds_for_the_named_series3_unit(unit, route): def test_the_identity_check_reuses_connects_serial_where_there_is_one(unit): - # speed: config and erase already read the serial in connect(); no extra read - for route in ("config", "erase"): + # speed: erase already reads the serial in connect(); no extra read + for route in ("erase",): u = unit("BE9441") _call(route, None) assert "read_serial" not in u.calls diff --git a/tests/test_server_settings_change.py b/tests/test_server_settings_change.py new file mode 100644 index 0000000..0ebe96a --- /dev/null +++ b/tests/test_server_settings_change.py @@ -0,0 +1,153 @@ +"""POST /device/settings/change (phase 5), and the legacy config write retired. +Handlers are called directly, every parameter passed, as in +test_server_device_access.py.""" +from __future__ import annotations + +import json +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import micromate.protocol as mm_proto # noqa: E402 +import sfm.server as srv # noqa: E402 +from device_access_fakes import FakeMicromateClient, schedule_record # noqa: E402 +from fastapi import HTTPException # noqa: E402 +from sfm.device_access.access import DeviceAccess # noqa: E402 + +TCP = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034) + + +class Audit: + def __init__(self): + self.rows = {} + + def begin(self, **f): + cid = f"c{len(self.rows) + 1}" + self.rows[cid] = dict(f, outcome="pending") + return cid + + def finish(self, cid, **f): + self.rows[cid].update(f) + + +class Cache: + def __init__(self): + self.dirty = [] + + def mark_config_dirty(self, key): + self.dirty.append(key) + + +@pytest.fixture +def unit(monkeypatch): + def make(fake): + access = DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False, + audit=Audit(), sleep=lambda s: None) + monkeypatch.setattr(srv, "_device_access_instance", access) + cache = Cache() + monkeypatch.setattr(srv, "get_cache", lambda: cache) + return cache + return make + + +def _post(changes, *, revision=None, dry_run=False, serial="UM20147"): + return srv.device_settings_change(body=srv.SettingsChangeBody(changes=changes, revision=revision), + serial=serial, dry_run=dry_run, caller="test", **TCP) + + +def _body(resp): + return json.loads(resp.body) + + +def test_route_dry_run_returns_fields_and_revision(unit): + cache = unit(FakeMicromateClient()) + resp = _post({"geo_trigger_ips": 0.3}, dry_run=True) + body = _body(resp) + assert resp.status_code == 200 and body["outcome"] == "dry_run" + assert body["plan"]["fields"]["geo_trigger_ips"] == {"label": "Geophone trigger", "old": 0.5, "new": 0.3} + assert len(body["plan"]["revision"]) == 16 and cache.dirty == [] + + +def test_route_verified_change_is_200_and_mismatch_409(unit, monkeypatch): + fake = FakeMicromateClient() + cache = unit(fake) + rev = _body(_post({"geo_trigger_ips": 0.3}, dry_run=True))["plan"]["revision"] + resp = _post({"geo_trigger_ips": 0.3}, revision=rev) + assert resp.status_code == 200 and _body(resp)["state_after"] == "as asked" + assert len(cache.dirty) == 1 # a by-host read must not serve stale settings + # a unit that acks but stores something else reads back "differs": 409 + fake2 = FakeMicromateClient() + unit(fake2) + rev = _body(_post({"job_number": 7}, dry_run=True))["plan"]["revision"] + real = fake2.protocol.execute + + def wrong(plan): + acks = real(plan) + fake2.setup = fake2.setup[:40] + b"\x00\x08" + fake2.setup[42:] + from micromate.setup_block import with_crc + fake2.setup = with_crc(fake2.setup) + return acks + monkeypatch.setattr(fake2.protocol, "execute", wrong) + resp = _post({"job_number": 7}, revision=rev) + assert resp.status_code == 409 and _body(resp)["verified"] == "mismatch" + + +def test_route_unconfirmed_carries_sent_and_audit_id(unit, monkeypatch): + fake = FakeMicromateClient() + unit(fake) + rev = _body(_post({"geo_trigger_ips": 0.3}, dry_run=True))["plan"]["revision"] + real = fake.protocol.execute + + def then_drop(plan): + acks = real(plan) + fake.run_states = [0x03] # it began calling home before the read-back + return acks + monkeypatch.setattr(fake.protocol, "execute", then_drop) + resp = _post({"geo_trigger_ips": 0.3}, revision=rev) + body = _body(resp) + assert body["sent"] == "acknowledged" and body["audit_id"] + + +@pytest.mark.parametrize("fake_kw, match", [ + (dict(schedule_body=schedule_record(14, 0x02, "other.mmb") + bytes(264)), "other.mmb"), + (dict(active_name="factory.MMB"), "factory setup"), + (dict(run_states=[0x02]), "stop it first"), +]) +def test_route_refusal_is_409_with_reason(unit, fake_kw, match): + fake = FakeMicromateClient(**fake_kw) + unit(fake) + rev = "0000000000000000" + if 0x02 not in fake.run_states: # a monitoring unit refuses the preview too + rev = _body(_post({"geo_trigger_ips": 0.3}, dry_run=True))["plan"]["revision"] + with pytest.raises(HTTPException) as e: + _post({"geo_trigger_ips": 0.3}, revision=rev) + assert e.value.status_code == 409 and match in str(e.value.detail) + + +def test_route_stale_preview_is_409(unit): + unit(FakeMicromateClient()) + with pytest.raises(HTTPException) as e: + _post({"geo_trigger_ips": 0.3}, revision="0000000000000000") + assert e.value.status_code == 409 and "preview again" in str(e.value.detail) + + +def test_route_live_without_revision_is_422(unit): + unit(FakeMicromateClient()) + with pytest.raises(HTTPException) as e: + _post({"geo_trigger_ips": 0.3}) + assert e.value.status_code == 422 and "preview first" in str(e.value.detail) + + +@pytest.mark.parametrize("route", ["device_config", "device_config_project"]) +def test_legacy_config_routes_are_gone(route, monkeypatch): + monkeypatch.setattr(srv, "_build_client", lambda *a, **kw: pytest.fail("no client may be built")) + resp = getattr(srv, route)() + assert resp.status_code == 410 and "/device/settings/change" in _body(resp)["detail"] + + +def test_settings_change_is_serial_aware(): + assert "/device/settings/change" in srv._SERIAL_AWARE_PATHS + assert srv._device_guard("/device/settings/change", {"serial": "UM20147", "host": "h"}) is None