feat(s3): change a MiniMate's settings by serial on the shared codec

Series3Adapter.settings reads the 1A block assembled into its 2,090
logical bytes and decodes it with micromate.setup_fields (a monitoring
unit's device-info answer is refused with 'stop monitoring first').
change_settings runs the shared change core: read the four settings
blocks, patch the settings block's fields, send Blastware's sequence
through push_config_raw with the event index, trigger and waveform blocks
as read, re-read.  Refused before sending: monitoring, a value the unit
does not allow, a stale preview.  push_config_raw's pre-check now raises
ImageRefused, so a refused image is audited as nothing sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-03 21:46:50 -05:00
1 parent c082f72d62
commit 66bb29b9d4
5 files changed
+346 -36

No files matched your search

+56 -1
View File
@@ -29,6 +29,41 @@ def s4_push_reads() -> dict:
return {e["sub"]: bytes.fromhex(e["response_data"])[11:] for e in ex[:start]}
_S3_BLOCKS = None
def s3_settings_blocks() -> dict:
"""BE9441's four settings blocks on 2026-10-26, as SFM's reads return them:
the 1A read Blastware took right after its second write (assembled, 2,090 B),
and the event index / trigger / waveform blocks that write sent back (each a
write is the read plus two bytes)."""
global _S3_BLOCKS
if _S3_BLOCKS is None:
from minimateplus.framing import S3FrameParser
from minimateplus.protocol import assemble_compliance_content
from test_minimate_write_frames import WRITES, _payload
fix = Path(__file__).parent / "fixtures" / "minimate-bench-10-26-26-histogram"
reads, cur = [], None
for f in S3FrameParser().feed((fix / "unit_replies.bin").read_bytes()):
if f.sub != 0xE5:
continue
if len(f.data) == 11:
cur = []
reads.append(cur)
else:
cur.append(bytes(f.data))
sent = {_payload(f)[2]: _payload(f)[16:] for f in WRITES[13:26]}
_S3_BLOCKS = {"event_index": sent[0x68][:-2], "compliance": assemble_compliance_content(reads[2]),
"trigger": sent[0x82][:-2], "waveform": sent[0x69][:-2]}
return dict(_S3_BLOCKS)
def s3_device_info_answer(serial: bytes = b"BE9441") -> bytes:
"""What a MONITORING MiniMate returns for a 1A read, assembled: its device-info
block (BE9441 10-26: reads 3-7 start 0e 'BE9441'), 2,090 bytes."""
return (b"\x0e" + serial).ljust(2090, b"\x00")
def schedule_record(time_slot: int, action: int, setup: str = "") -> bytes:
"""One 260-byte schedule.dat record (micromate.schedule's layout)."""
rec = bytearray(260)
@@ -115,9 +150,13 @@ def default_s3_events():
class FakeMiniMateClient(_Base):
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None,
monitor_states=None, write_error=None, serial_reported=None, wake_errors=None,
bare_requests_ignored=False, call_home_raw=None, **kw):
bare_requests_ignored=False, call_home_raw=None, settings_blocks=None,
monitoring_settings=False, **kw):
super().__init__(**kw)
self.serial = serial
self.settings_blocks = s3_settings_blocks() if settings_blocks is None else dict(settings_blocks)
self.monitoring_settings = monitoring_settings
self.pushed = None
# As a monitoring MiniMate (measured 2026-04-08): on a fresh connection a
# read before SESSION_RESET + POLL goes unanswered. Off unless a test asks.
self.bare_requests_ignored = bare_requests_ignored
@@ -183,6 +222,22 @@ class FakeMiniMateClient(_Base):
self._write("call_home")
self.call_home_raw = bytes(image) # read back as the unit would store it
def read_compliance_content(self) -> bytes:
self._bare_read("read_compliance_content")
return s3_device_info_answer() if self.monitoring_settings else self.settings_blocks["compliance"]
def read_settings_blocks(self) -> dict:
self._bare_read("read_settings_blocks")
blocks = dict(self.settings_blocks)
if self.monitoring_settings:
blocks["compliance"] = s3_device_info_answer()
return blocks
def push_config_raw(self, event_index, compliance, trigger, waveform) -> None:
self.pushed = (bytes(event_index), bytes(compliance), bytes(trigger), bytes(waveform))
self._write("push_config_raw")
self.settings_blocks["compliance"] = bytes(compliance)[:2090] # read back as the unit stores it
def get_monitor_status(self) -> MonitorStatus:
self._bare_read("get_monitor_status")
state = self.monitor_states.pop(0) if len(self.monitor_states) > 1 else self.monitor_states[0]
+12 -12
View File
@@ -11,7 +11,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import minimateplus.protocol as mmp_proto # noqa: E402
from device_access_fakes import FakeMiniMateClient # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
ConnectFailed, MalformedReply, NoAnswer, WrongUnit,
ConnectFailed, MalformedReply, NoAnswer, UnitStateUnknown, WrongUnit,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s3 import Series3Adapter # noqa: E402
@@ -51,20 +51,20 @@ def test_status_maps_monitor_status():
assert fake.calls == ["poll", "get_monitor_status"]
def test_settings_maps_the_compliance_config():
s = adapter(FakeMiniMateClient()).settings(TCP, "BE18193")
assert s.record_mode == "Continuous"
assert (s.sample_rate, s.record_time_s, s.histogram_interval_s) == (1024, 3.0, 300)
assert s.geo_trigger_ips == 0.5
assert s.setup_name == "BRIDGE-A"
assert s.notes == {"Project": "Bridge job", "Client": "Acme", "User Name": "BH", "Seis Loc": "Loc 1"}
assert s.detail["record_mode_code"] == 0x01
def test_settings_reads_the_logical_block():
# Phase 5: the settings come from the 1A read assembled into its 2,090 bytes and
# decoded by micromate.setup_fields (tests/test_device_access_s3_settings.py has
# the rest); the fake's block is BE9441's of 2026-10-26.
fake = FakeMiniMateClient()
s = adapter(fake).settings(TCP, "BE18193")
assert (s.record_mode, s.sample_rate, s.setup_name) == ("Histogram", 4096, "Standard Recording Setup.set")
assert fake.calls.index("connect") < fake.calls.index("read_compliance_content")
def test_settings_without_a_compliance_read_is_a_malformed_reply_and_not_retried():
def test_settings_of_a_monitoring_unit_is_refused_and_not_retried():
# One fake only: a retry would ask the factory for a second and fail.
with pytest.raises(MalformedReply, match="settings"):
adapter(FakeMiniMateClient(compliance=None)).settings(TCP, "BE18193")
with pytest.raises(UnitStateUnknown, match="settings"):
adapter(FakeMiniMateClient(monitoring_settings=True)).settings(TCP, "BE18193")
def test_a_cold_unit_over_tcp_gets_one_retry():
+156
View File
@@ -0,0 +1,156 @@
"""Changing a MiniMate's settings by serial (phase 5): preview, one audited send,
read back. The settings block is the 1A read assembled into its 2,090 logical
bytes; the write is push_config_raw's Blastware sequence (68 73 | 71 x n 72 |
82 83 | 69 74 72) with the event index, trigger and waveform blocks sent back as
read. Fixture blocks: BE9441, 2026-10-26."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import minimateplus.protocol as mp # noqa: E402
from device_access_fakes import FakeMiniMateClient, s3_settings_blocks # noqa: E402
from micromate.setup_fields import encode_setup, field_values # noqa: E402
from minimateplus.client import MiniMateClient # noqa: E402
from minimateplus.protocol import ImageRefused # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
BadRequest, DeviceError, SettingsChanged, UnitStateUnknown,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s3 import Series3Adapter # noqa: E402
TCP = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None)
BW_ORDER = ["0x68", "0x73", "0x71", "0x72", "0x82", "0x83", "0x69", "0x74", "0x72"]
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 adapter(fake):
return Series3Adapter(client_factory=lambda address, **kw: fake)
def change(fake, changes, *, revision=None, dry_run=False, audit=None):
return adapter(fake).change_settings(
TCP, "BE18193", changes=changes, revision=revision, dry_run=dry_run,
audit=audit if audit is not None else Audit(), caller="test", sleep=lambda s: None,
verify_timeout_s=2.0, verify_interval_s=1.0)
def live(fake, changes, audit=None):
rev = change(fake, changes, dry_run=True).plan["revision"]
return change(fake, changes, revision=rev, audit=audit)
def test_s3_settings_read_uses_the_codec():
s = adapter(FakeMiniMateClient()).settings(TCP, "BE18193")
assert (s.record_mode, s.sample_rate, s.histogram_interval_s) == ("Histogram", 4096, 2)
assert (s.record_time_s, s.geo_trigger_ips) == (20.0, 0.04)
assert s.notes["Project"] == "TestUnit-Minimate" and s.notes["Client"] == "Terra-Mechanics"
assert s.detail["record_mode_code"] == 0x03 and s.detail["geo_range"] == "normal"
fields = {d["field"]: d for d in s.detail["editable"]}
assert fields["geo_range"]["value"] == "normal" and fields["note_1"]["label"] == "Project"
def test_s3_settings_read_of_a_monitoring_unit_says_why():
with pytest.raises(UnitStateUnknown, match="stop monitoring first"):
adapter(FakeMiniMateClient(monitoring_settings=True)).settings(TCP, "BE18193")
def test_s3_dry_run_previews_and_sends_nothing():
fake = FakeMiniMateClient()
r = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True)
assert r.outcome == "dry_run" and fake.writes == []
assert r.plan["fields"] == {"geo_trigger_ips": {"label": "Geophone trigger", "old": 0.04, "new": 0.05}}
assert [s["sub"] for s in r.plan["steps"]] == BW_ORDER
assert any("00 00" in w for w in r.plan["warnings"]) and r.plan["blocked"] == []
assert len(r.plan["revision"]) == 16
def test_s3_trigger_change_sends_the_units_own_blocks():
fake = FakeMiniMateClient()
blocks = s3_settings_blocks()
live(fake, {"geo_trigger_ips": 0.05})
event_index, compliance, trigger, waveform = fake.pushed
assert (event_index, trigger, waveform) == (blocks["event_index"], blocks["trigger"], blocks["waveform"])
assert compliance == encode_setup(blocks["compliance"], 3, {"geo_trigger_ips": 0.05})
def test_s3_change_verifies_by_read_back():
fake = FakeMiniMateClient()
r = live(fake, {"geo_trigger_ips": 0.05, "note_4": "Loc 2 - north wall"})
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "as asked")
rows = r.detail["snapshot"]["fields"]
assert rows["geo_trigger_ips"] == {"label": "Geophone trigger", "old": 0.04, "new": 0.05, "now": 0.05}
assert rows["note_4"]["now"] == "Loc 2 - north wall"
assert field_values(fake.settings_blocks["compliance"], 3)["geo_trigger_ips"] == 0.05
def test_s3_stale_revision_sends_nothing():
fake = FakeMiniMateClient()
rev = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True).plan["revision"]
fake.settings_blocks["compliance"] = encode_setup(fake.settings_blocks["compliance"], 3, {"job_number": 9})
audit = Audit()
with pytest.raises(SettingsChanged):
change(fake, {"geo_trigger_ips": 0.05}, revision=rev, audit=audit)
assert fake.writes == [] and audit.rows == {}
@pytest.mark.parametrize("dry_run", [True, False])
def test_s3_monitoring_is_refused(dry_run):
fake = FakeMiniMateClient(monitoring_settings=True)
with pytest.raises(UnitStateUnknown) as e:
change(fake, {"geo_trigger_ips": 0.05}, revision="x", dry_run=dry_run)
assert "stop monitoring first" in str(e.value) and "nothing sent" in str(e.value)
assert fake.writes == []
def test_s3_a_value_the_unit_does_not_allow_is_a_bad_request():
with pytest.raises(BadRequest):
change(FakeMiniMateClient(), {"record_time_s": 30.0}, dry_run=True) # 4096 sps: 26 s at most
def test_s3_a_refused_image_is_audited_as_nothing_sent():
audit = Audit()
fake = FakeMiniMateClient(write_error=ImageRefused("write SUB 0x71: not a whole block"))
rev = change(fake, {"geo_trigger_ips": 0.05}, dry_run=True).plan["revision"]
with pytest.raises(DeviceError):
change(fake, {"geo_trigger_ips": 0.05}, revision=rev, audit=audit)
((_, row),) = audit.rows.items()
assert (row["outcome"], row["sent"]) == ("failed", 0)
assert row["error"].startswith("refused before sending")
class _Recorder:
def __init__(self):
self.sent = []
def write(self, data):
self.sent.append(bytes(data))
def read(self, n):
return b""
def test_push_config_raw_precheck_raises_image_refused():
t = _Recorder()
c = MiniMateClient("unused")
c._proto = mp.MiniMateProtocol(t, recv_timeout=0.2)
b = s3_settings_blocks()
with pytest.raises(ImageRefused):
c.push_config_raw(b["event_index"], b["compliance"][:2089], b["trigger"], b["waveform"])
assert t.sent == []