feat(s4): change a Micromate's settings by serial, audited, schedule-checked

s4_change_settings runs the shared change core with a read-back verdict
for its state (as asked / unchanged / differs).  It reads the active
setup's name (unstripped), the preferences, trigger and setup blocks and
the schedule; patches the setup through micromate.setup_fields; sends
THOR's setup push (0xDA 68 73 82 83 71 72, now enableable) once; reads
the setup back.  Refused before sending: a monitoring unit, a value the
unit does not allow (422), a stale preview (SettingsChanged, 409), and --
shown as 'blocked' in the preview -- the factory setup, a schedule that
loads another setup, an unreadable schedule, or a block SFM has not seen
(ChangeRefused, 409).  s4_settings carries the editable fields.

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:43:03 -05:00
1 parent d0335dbbbd
commit c082f72d62
9 files changed
+407 -16

No files matched your search

+56 -2
View File
@@ -17,6 +17,24 @@ from minimateplus.models import ComplianceConfig, DeviceInfo, Event, MonitorStat
SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um20147_baseline.bin"
THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
PUSH_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-writes" / "setup-push-overwrite-test1.json"
def s4_push_reads() -> dict:
"""UM12947's reads (content, by SUB) just before THOR's setup push: 0x08 prefs,
0x2E trigger, 0x1A setup, 0x41 active name."""
import json
ex = json.loads(PUSH_FIXTURE.read_text())["exchanges"]
start = next(i for i, e in enumerate(ex) if e["sub"] == 0xDA)
return {e["sub"]: bytes.fromhex(e["response_data"])[11:] for e in ex[:start]}
def schedule_record(time_slot: int, action: int, setup: str = "") -> bytes:
"""One 260-byte schedule.dat record (micromate.schedule's layout)."""
rec = bytearray(260)
rec[4], rec[5], rec[6], rec[7] = time_slot, 3, action, len(setup)
rec[8:8 + len(setup)] = setup.encode("ascii")
return bytes(rec)
THOR_WRITES = Path(__file__).parent / "fixtures" / "micromate-writes"
@@ -269,6 +287,10 @@ class _FakeProtocol:
old = self._owner.call_home
self._owner.call_home = bytes(st.data[:118]) + bytes(~b & 0xFF for b in old[118:120]) \
+ bytes(st.data[120:])
if st.sub == 0x71: # the unit stores the setup and computes its own CRC
from micromate.setup_block import with_crc
old = self._owner.setup
self._owner.setup = with_crc(old[:3] + bytes(st.data[3:2090]) + old[2090:2092])
return [type("Ack", (), {"sub": s.ack_sub, "data": bytes(11)})() for s in plan.steps]
def read_call_home_config(self):
@@ -279,10 +301,20 @@ class _FakeProtocol:
class FakeMicromateClient(_Base):
def __init__(self, serial="UM20147", *, monitoring=False, events=5,
unsolicited=b"", event_refs=None, run_states=None,
serial_reported=None, execute_error=None, call_home=None, **kw):
serial_reported=None, execute_error=None, call_home=None, setup=None,
prefs=None, trigger=None, active_name=None, schedule_body=None,
schedule_error=None, **kw):
super().__init__(**kw)
self.unit_serial = serial # not `serial`: that is the client's method
self.call_home = um12947_call_home() if call_home is None else call_home
push = s4_push_reads()
self.setup = SETUP_FIXTURE.read_bytes()[11:] if setup is None else setup
self.prefs = push[0x08] if prefs is None else prefs
self.trigger = push[0x2E] if trigger is None else trigger
self.active_name = (push[0x41].split(b"\x00")[0].decode("ascii")
if active_name is None else active_name)
self.schedule_body = bytes(524) if schedule_body is None else schedule_body
self.schedule_error = schedule_error
self.run_states = list(run_states) if run_states else [0x00]
self.serial_reported = serial if serial_reported is None else serial_reported
self.execute_error = execute_error
@@ -334,7 +366,29 @@ class FakeMicromateClient(_Base):
def get_setup(self):
self._step("get_setup")
return decode_setup(SETUP_FIXTURE.read_bytes()[11:])
return decode_setup(self.setup)
def get_setup_content(self) -> bytes:
self._step("get_setup_content")
return self.setup
def get_prefs_content(self) -> bytes:
self._step("get_prefs_content")
return self.prefs
def get_trigger_content(self) -> bytes:
self._step("get_trigger_content")
return self.trigger
def get_active_setup_raw(self) -> str:
self._step("get_active_setup_raw")
return self.active_name
def read_schedule(self) -> bytes:
self._step("read_schedule")
if self.schedule_error is not None:
raise self.schedule_error
return self.schedule_body
def read_unsolicited(self) -> bytes:
self._step("read_unsolicited")
+171
View File
@@ -0,0 +1,171 @@
"""Changing a Micromate's settings by serial (phase 5): preview, one audited send,
read back. The push is micromate.writes.plan_setup_push (THOR's frames) under
the active setup's own name; the unit's schedule is read first, because a
scheduled start loads the setup it names and would undo a change to another."""
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 micromate.protocol as mm_proto # noqa: E402
from device_access_fakes import FakeMicromateClient, schedule_record # noqa: E402
from micromate.opcodes import ENABLEABLE_WRITES # noqa: E402
from micromate.setup_fields import field_values # noqa: E402
from sfm.device_access.errors import ( # noqa: E402
BadRequest, ChangeRefused, SettingsChanged, UnitStateUnknown,
)
from sfm.device_access.models import UnitAddress # noqa: E402
from sfm.device_access.s4 import s4_change_settings, s4_settings # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
PUSH_SUBS = [0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 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 change(fake, changes, *, revision=None, dry_run=False, audit=None):
return s4_change_settings(fake, "UM20147", changes=changes, revision=revision, dry_run=dry_run,
audit=audit if audit is not None else Audit(), address=ADDR,
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_setup_push_subs_are_now_enableable():
assert set(PUSH_SUBS) <= ENABLEABLE_WRITES
def test_s4_settings_read_describes_the_editable_fields():
st = s4_settings(FakeMicromateClient(), "UM20147")
fields = {d["field"]: d for d in st.detail["editable"]}
assert fields["geo_trigger_ips"]["value"] == 0.5 and "geo_range" not in fields
def test_s4_dry_run_previews_old_to_new_and_sends_nothing():
fake = FakeMicromateClient()
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
assert r.outcome == "dry_run"
assert r.plan["fields"] == {"geo_trigger_ips": {"label": "Geophone trigger", "old": 0.5, "new": 0.3}}
assert len(r.plan["revision"]) == 16 and r.plan["blocked"] == []
assert [s["sub"] for s in r.plan["steps"]] == [f"0x{s:02X}" for s in PUSH_SUBS]
assert any("edit buffer" in w for w in r.plan["warnings"])
assert fake.executed == []
def test_s4_trigger_change_sends_the_push_and_verifies():
fake = FakeMicromateClient()
r = live(fake, {"geo_trigger_ips": 0.3})
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "as asked")
assert [st.sub for st in fake.executed[0].steps] == PUSH_SUBS
assert field_values(fake.setup, 4)["geo_trigger_ips"] == 0.3
assert r.detail["snapshot"]["fields"]["geo_trigger_ips"] == {
"label": "Geophone trigger", "old": 0.5, "new": 0.3, "now": 0.3}
name_step = fake.executed[0].steps[0]
assert name_step.data.rstrip(b"\x00") == b"TEST1.mmb" # the active setup's own name
def test_s4_stale_revision_sends_nothing():
fake = FakeMicromateClient()
rev = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True).plan["revision"]
fake.setup = FakeMicromateClient(setup=None).setup[:40] + b"\x00\x07" + fake.setup[42:] # job number moved
audit = Audit()
with pytest.raises(SettingsChanged):
change(fake, {"geo_trigger_ips": 0.3}, revision=rev, audit=audit)
assert fake.executed == [] and audit.rows == {}
def test_s4_already_as_asked_is_skipped():
fake = FakeMicromateClient()
r = live(fake, {"geo_trigger_ips": 0.5})
assert r.outcome == "skipped" and fake.executed == []
@pytest.mark.parametrize("dry_run", [True, False])
def test_s4_monitoring_is_refused(dry_run):
fake = FakeMicromateClient(run_states=[0x02])
with pytest.raises(UnitStateUnknown) as e:
change(fake, {"geo_trigger_ips": 0.3}, revision="x", dry_run=dry_run)
assert "stop it first" in str(e.value) and "nothing sent" in str(e.value)
assert fake.executed == []
def test_s4_a_value_the_unit_does_not_allow_is_a_bad_request():
with pytest.raises(BadRequest):
change(FakeMicromateClient(), {"geo_trigger_ips": 12.0}, dry_run=True)
def test_s4_factory_setup_is_refused_live_and_shown_in_preview():
fake = FakeMicromateClient(active_name="factory.MMB")
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
assert any("factory setup" in b for b in r.plan["blocked"]) and r.plan["steps"] == []
with pytest.raises(ChangeRefused):
change(fake, {"geo_trigger_ips": 0.3}, revision=r.plan["revision"])
assert fake.executed == []
def test_s4_schedule_conflict_blocks():
fake = FakeMicromateClient(schedule_body=schedule_record(14, 0x02, "other.mmb") + bytes(264))
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
assert any("other.mmb" in b and "07:00" in b for b in r.plan["blocked"])
with pytest.raises(ChangeRefused) as e:
change(fake, {"geo_trigger_ips": 0.3}, revision=r.plan["revision"])
assert "nothing sent" in str(e.value) and fake.executed == []
def test_s4_schedule_on_the_active_setup_warns_only():
fake = FakeMicromateClient(schedule_body=schedule_record(14, 0x02, "test1.MMB")
+ schedule_record(37, 0x04) + bytes(4))
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
assert r.plan["blocked"] == [] and any("survives" in w and "07:00" in w for w in r.plan["warnings"])
assert live(fake, {"geo_trigger_ips": 0.3}).verified == "ok"
def test_an_unreadable_schedule_refuses():
fake = FakeMicromateClient(schedule_error=mm_proto.ProtocolError("no reply to 0x94"))
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
assert any("could not read this unit's schedule" in b for b in r.plan["blocked"])
with pytest.raises(ChangeRefused):
change(fake, {"geo_trigger_ips": 0.3}, revision=r.plan["revision"])
assert fake.executed == []
def test_no_schedule_records_is_no_conflict():
r = live(FakeMicromateClient(), {"geo_trigger_ips": 0.3})
assert r.verified == "ok"
def test_s4_a_lost_ack_records_what_the_unit_holds():
fake = FakeMicromateClient(execute_error=mm_proto.TimeoutError("lost"))
r = live(fake, {"geo_trigger_ips": 0.3})
assert (r.outcome, r.sent) == ("failed", True)
snap = r.detail["snapshot"]
assert snap["fields"]["geo_trigger_ips"]["now"] == 0.5 and snap["changed_offsets"] == []
def test_s4_unseen_block_size_is_blocked():
fake = FakeMicromateClient()
fake.prefs = fake.prefs + b"\x00"
r = change(fake, {"geo_trigger_ips": 0.3}, dry_run=True)
assert any("has not seen a block like it" in b for b in r.plan["blocked"])
with pytest.raises(ChangeRefused):
change(fake, {"geo_trigger_ips": 0.3}, revision=r.plan["revision"])
assert fake.executed == []
+9 -7
View File
@@ -33,9 +33,11 @@ def _ready(responses):
return p, t
def test_the_ceiling_is_start_stop_and_call_home():
# Phase 4 (2026-11-02) added the call-home write and its confirm.
assert ENABLEABLE_WRITES == frozenset({0x96, 0x97, 0x7E, 0x7F})
def test_the_ceiling_is_start_stop_call_home_and_the_setup_push():
# Phase 4 (2026-11-02) added the call-home write and its confirm; phase 5
# (2026-11-03) the setup push: name, preferences, trigger, setup, confirms.
assert ENABLEABLE_WRITES == frozenset({0x96, 0x97, 0x7E, 0x7F,
0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72})
def test_execute_sends_exactly_the_plans_frame_and_returns_the_ack():
@@ -54,10 +56,10 @@ def test_permission_ends_with_the_call():
def test_a_plan_beyond_the_ceiling_is_refused_and_nothing_is_sent():
# 0x71 (the setup-block write) stays above the ceiling until phase 5.
# 0xA8 (delete one event) stays above the ceiling (0x71 joined it in phase 5).
p, t = _ready([])
with pytest.raises(OpcodeRefused, match="ceiling"):
p.execute(WritePlan("setup push", (WriteStep(0x71, 0x0000, bytes(4)),)))
p.execute(WritePlan("delete", (WriteStep(0xA8, 0x0000, bytes(4)),)))
assert t.written == []
@@ -111,7 +113,7 @@ def test_a_duck_typed_plan_is_refused():
def test_a_forged_step_in_a_real_plan_is_refused_at_the_step():
p, t = _ready([])
plan = plan_start_monitoring()
object.__setattr__(plan, "steps", (WriteStep(0x71, 0),)) # subs now reads 0x71 too
object.__setattr__(plan, "steps", (WriteStep(0xA8, 0),)) # subs now reads 0xA8 too
with pytest.raises(OpcodeRefused):
p.execute(plan)
assert t.written == []
@@ -122,7 +124,7 @@ def test_a_forged_step_hidden_behind_a_good_plan_is_refused():
@property
def subs(self):
return frozenset({0x96})
plan = Lying("x", (WriteStep(0x96, 0xFFFF), WriteStep(0x71, 0)))
plan = Lying("x", (WriteStep(0x96, 0xFFFF), WriteStep(0xA8, 0)))
p, t = _ready([ACK_START])
with pytest.raises(OpcodeRefused):
p.execute(plan)
+1 -1
View File
@@ -98,7 +98,7 @@ def test_an_unknown_opcode_is_refused_and_nothing_is_written(sub):
assert t.written == []
@pytest.mark.parametrize("sub", [0xEE, 0x71, 0xA8]) # 0x71 (setup write) stays above the ceiling until phase 5
@pytest.mark.parametrize("sub", [0xEE, 0xA8, 0xAA]) # delete and its confirm stay above the ceiling
def test_a_permit_beyond_the_ceiling_is_refused_at_the_wire(sub):
p, t = proto([])
with pytest.raises(OpcodeRefused):