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

+6 -2
View File
@@ -960,12 +960,16 @@ class MiniMateClient:
# 2026-10-27): a block refused after 68 + 73 had been sent left a partial
# write behind. write_image is the same check each write makes.
from .protocol import (SUB_COMPLIANCE_WRITE, SUB_EVENT_INDEX_WRITE,
SUB_TRIGGER_CONFIG_WRITE, SUB_WAVEFORM_DATA_WRITE, write_image)
SUB_TRIGGER_CONFIG_WRITE, SUB_WAVEFORM_DATA_WRITE, ImageRefused,
write_image)
for sub, data in ((SUB_EVENT_INDEX_WRITE, event_index_data),
(SUB_COMPLIANCE_WRITE, compliance_data),
(SUB_TRIGGER_CONFIG_WRITE, trigger_data),
(SUB_WAVEFORM_DATA_WRITE, waveform_data)):
write_image(sub, data)
try:
write_image(sub, data)
except ValueError as exc: # refused before any frame: the caller audits "nothing sent"
raise ImageRefused(str(exc)) from exc
# 68 → 73
log.info("push_config_raw: write event index (SUB 68)")
+116 -21
View File
@@ -11,15 +11,22 @@ from minimateplus import MiniMateClient
from minimateplus.blastware_file import blastware_file_bytes, blastware_filename, with_type_letter
from minimateplus.event_file_io import _GEO_INT16_FS
from minimateplus.framing import build_bw_write_frame, unescape_reply
from micromate.setup_block import decode_setup
from micromate.setup_fields import (
SettingsValueError, check_changes, editable_fields, encode_setup, field_rows, field_values,
settings_state,
)
from micromate.setup_fields import revision as settings_revision
from minimateplus.protocol import (
SUB_CALL_HOME_CONFIRM, SUB_CALL_HOME_WRITE, SUB_START_MONITORING, SUB_STOP_MONITORING,
ImageRefused, call_home_enabled, call_home_image, is_call_home_block, write_image,
ImageRefused, call_home_enabled, call_home_image, is_call_home_block, is_compliance_content,
write_image,
)
from minimateplus.transport import TcpTransport
from .errors import (DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported, StaleEvent,
UnitStateUnknown, WrongUnit, translate)
from .change import call_home_change, monitoring_change, run_change
from .errors import (BadRequest, DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported,
SettingsChanged, StaleEvent, UnitStateUnknown, WrongUnit, translate)
from .change import call_home_change, monitoring_change, run_change, settings_change
from .events import iso_of, make_event_id, stamp_of
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress,
UnitInfo, UnitSettings, UnitStatus)
@@ -49,6 +56,19 @@ S3_CALL_HOME_WHILE_MONITORING = ("did not return its call-home settings -- a Min
# The 0x1C flag byte (section[1]): the only values ever measured. 0x10 is
# BE11529 monitoring (2026-04-08); 0x0B is BE9441 recording a histogram,
# confirmed at the unit (2026-10-26). Anything else is refused for a change.
# Measured 2026-11-03 (BE9441's 10-26 recording, 5 / 5 reads): while monitoring, a
# MiniMate answers the 1A settings read with its device-info block.
S3_SETTINGS_WHILE_MONITORING = ("did not return its settings -- a MiniMate answers this way "
"while monitoring; stop monitoring first")
# Blastware's settings write, in its order (push_config_raw): event index, the
# settings block in addressed chunks, trigger, waveform data, with their confirms.
_S3_SETTINGS_STEPS = ((0x68, "event index (as read)"), (0x73, "confirm B"),
(0x71, "settings block"), (0x72, "confirm A"),
(0x82, "trigger block (as read)"), (0x83, "trigger confirm"),
(0x69, "waveform data (as read)"), (0x74, "confirm C"), (0x72, "confirm A"))
_S3_TAIL_WARNING = ("the two bytes after the settings block go out as 00 00 (Blastware sends "
"its own constant; effect unmeasured)")
S3_RUN_STATES = {0x00: "idle", 0x10: "monitoring", 0x0B: "monitoring"}
@@ -435,29 +455,104 @@ class Series3Adapter:
is_refusal=lambda e: isinstance(e, ImageRefused))
return self._run(address, op, retry=False)
def change_settings(self, address: UnitAddress, serial: str, *, changes: dict,
revision: Optional[str], dry_run: bool, audit: Any, caller: str,
sleep: Callable[[float], None], verify_timeout_s: float,
verify_interval_s: float) -> ChangeResult:
"""Series-3 pieces for the shared core (phase 5): read the four settings
blocks, patch the settings block's fields (micromate.setup_fields), send
Blastware's sequence through push_config_raw with the other three blocks
as read, re-read the settings. One attempt, never retried.
Refused before anything is sent: a monitoring unit (it answers 1A with its
device-info block); a value the unit does not allow (BadRequest); a live
call whose `revision` is not this read's (SettingsChanged)."""
def op(client: Any) -> ChangeResult:
st: dict = {}
reads: list = []
def read_serial() -> str:
return client.connect().serial or "" # a fresh connection: the 0x15 read
def read_state() -> str:
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
if st:
now = client.read_compliance_content()
if not is_compliance_content(now):
raise MalformedReply("the read-back did not return the settings block")
reads.append(now)
return settings_state(st["setup"], st["image"], now, series=3)
blocks = client.read_settings_blocks()
setup = blocks["compliance"]
if not is_compliance_content(setup):
raise UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING} -- nothing sent")
try:
normal = check_changes(setup, 3, changes)
except SettingsValueError as exc:
raise BadRequest(f"{exc} -- nothing sent") from exc
rev = settings_revision([blocks["event_index"], setup, blocks["trigger"], blocks["waveform"]])
if not dry_run and revision != rev:
raise SettingsChanged(f"{serial}'s settings changed since the preview -- "
"preview again; nothing sent")
image = encode_setup(setup, 3, normal)
st.update(blocks=blocks, setup=setup, image=image, changes=normal, revision=rev)
reads.append(setup)
return settings_state(setup, image, setup, series=3)
def describe_plan() -> dict:
b = st["blocks"]
lens = {0x68: len(b["event_index"]), 0x71: len(st["image"]) + 2,
0x82: len(b["trigger"]), 0x69: len(b["waveform"])}
return {"action": "settings write", "blocked": [],
"steps": [{"sub": f"0x{sub:02X}", "what": what, "data_len": lens.get(sub, 0)}
for sub, what in _S3_SETTINGS_STEPS],
"fields": field_rows(st["setup"], st["image"], 3, st["changes"]),
"revision": st["revision"], "warnings": [_S3_TAIL_WARNING]}
def send() -> dict:
b = st["blocks"]
client.push_config_raw(b["event_index"], st["image"], b["trigger"], b["waveform"])
return {"subs": [f"0x{0xFF - sub:02X}" for sub, _ in _S3_SETTINGS_STEPS]}
def snapshot() -> dict:
before, after = st["setup"], reads[-1]
return {"fields": field_rows(before, st["image"], 3, st["changes"], now=after),
"before": before.hex(), "after": after.hex(),
"changed_offsets": [i for i in range(min(len(before), len(after)))
if before[i] != after[i]]}
return run_change(
kind=settings_change(), serial=serial, series=3, dry_run=dry_run,
even_if_already=False, audit=audit, address=address, caller=caller, sleep=sleep,
verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
read_serial=read_serial, read_state=read_state, describe_plan=describe_plan,
send=send, snapshot=snapshot,
# raised before the first frame goes out: audited as nothing sent
is_refusal=lambda e: isinstance(e, ImageRefused))
return self._run(address, op, retry=False)
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
"""The 1A read assembled into the logical block and decoded by the shared
settings codec (phase 5)."""
def op(client: Any) -> UnitSettings:
info = client.connect()
self._check(info.serial, serial, address)
cc = info.compliance_config
if cc is None:
raise MalformedReply("could not read the unit's settings (SUB 0x1A)")
mode = None
if cc.recording_mode is not None:
mode = S3_MODES.get(cc.recording_mode, f"unknown (0x{cc.recording_mode:02x})")
notes = {
label: value for label, value in (
("Project", cc.project), ("Client", cc.client), ("User Name", cc.operator),
("Seis Loc", cc.sensor_location), ("Extended Notes", cc.notes),
) if value is not None
}
content = client.read_compliance_content()
if not is_compliance_content(content):
raise UnitStateUnknown(f"{serial} {S3_SETTINGS_WHILE_MONITORING}")
v = field_values(content, 3)
name = decode_setup(content + bytes(2), verify=False).name # Series 3 reads no CRC
labels = {d["field"]: d["label"] for d in editable_fields(content, 3)}
notes = {labels[f]: v[f] for f in ("note_1", "note_2", "note_3", "note_4")}
code = content[5]
return UnitSettings(
serial=info.serial, series=3, setup_name=cc.setup_name, record_mode=mode,
sample_rate=cc.sample_rate, record_time_s=cc.record_time,
histogram_interval_s=cc.histogram_interval_sec, geo_trigger_ips=cc.trigger_level_geo,
serial=info.serial, series=3, setup_name=name or None,
record_mode=S3_MODES.get(code, f"unknown (0x{code:02x})"),
sample_rate=v["sample_rate"], record_time_s=v["record_time_s"],
histogram_interval_s=v["histogram_interval_s"], geo_trigger_ips=v["geo_trigger_ips"],
notes=notes,
detail={"record_mode_code": cc.recording_mode, "alarm_level_geo": cc.alarm_level_geo,
"geo_range": cc.geo_range},
detail={"record_mode_code": code, "alarm_level_geo": v["geo_alarm_ips"],
"geo_range": v["geo_range"], "editable": editable_fields(content, 3)},
)
return self._run(address, op)
+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 == []