From c082f72d624905a4c38df3e1c01ff84fde38a226 Mon Sep 17 00:00:00 2001 From: serversdown Date: Tue, 3 Nov 2026 21:43:03 -0500 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- micromate/opcodes.py | 5 +- micromate/setup_fields.py | 15 +++ sfm/device_access/change.py | 6 + sfm/device_access/errors.py | 12 ++ sfm/device_access/s4.py | 138 ++++++++++++++++++- tests/device_access_fakes.py | 58 +++++++- tests/test_device_access_s4_settings.py | 171 ++++++++++++++++++++++++ tests/test_micromate_execute.py | 16 ++- tests/test_micromate_opcodes.py | 2 +- 9 files changed, 407 insertions(+), 16 deletions(-) create mode 100644 tests/test_device_access_s4_settings.py diff --git a/micromate/opcodes.py b/micromate/opcodes.py index 2f3d7ce..3e88e5c 100644 --- a/micromate/opcodes.py +++ b/micromate/opcodes.py @@ -86,7 +86,10 @@ READ_SUBS: Mapping[int, str] = MappingProxyType(_READ_SUBS) # (0xA8/0xAA), raw file writes (0x8D/0x8E -- they could reach the modem # settings) and 0xA2 never belong here without one. Phase 4 (2026-11-02) added # the call-home write and its confirm (spec row 9: enable/disable only). -ENABLEABLE_WRITES = frozenset({0x96, 0x97, 0x7E, 0x7F}) +# Phase 5 (2026-11-03) added the setup push -- name, preferences, trigger and setup +# blocks with their confirms -- for changing a unit's settings by serial (spec row 10). +ENABLEABLE_WRITES = frozenset({0x96, 0x97, 0x7E, 0x7F, + 0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72}) # + the setup push (phase 5) class OpcodeRefused(RuntimeError): diff --git a/micromate/setup_fields.py b/micromate/setup_fields.py index d2b6f38..ceca0c6 100644 --- a/micromate/setup_fields.py +++ b/micromate/setup_fields.py @@ -233,6 +233,21 @@ def field_values(content: bytes, series: int) -> Dict[str, Any]: return {d["field"]: d["value"] for d in editable_fields(content, series)} +def field_rows(before: bytes, written: bytes, series: int, fields, now: Optional[bytes] = None) -> Dict[str, Dict[str, Any]]: + """For each changed field: its label, the value the unit had (old), the value + sent (new) and, given a read-back, what the unit now holds (now).""" + a, w = field_values(before, series), field_values(written, series) + n = field_values(now, series) if now is not None else None + labels = {d["field"]: d["label"] for d in editable_fields(written, series)} + out: Dict[str, Dict[str, Any]] = {} + for f in fields: + row: Dict[str, Any] = {"label": labels[f], "old": a[f], "new": w[f]} + if n is not None: + row["now"] = n[f] + out[f] = row + return out + + # ── Checking ──────────────────────────────────────────────────────────────── def _number(field: str, v: Any) -> float: diff --git a/sfm/device_access/change.py b/sfm/device_access/change.py index 17b2660..dca1e70 100644 --- a/sfm/device_access/change.py +++ b/sfm/device_access/change.py @@ -63,6 +63,12 @@ def call_home_change(enabled: bool) -> ChangeKind: else ChangeKind("disable call-home", "disabled", "disabled")) +def settings_change() -> ChangeKind: + """A settings change (phase 5): its "state" is a read-back verdict -- + "as asked" (the unit holds what was written), "unchanged", or "differs".""" + return ChangeKind("change settings", "as asked", "applied") + + def _take_snapshot(snapshot: Optional[Callable[[], Dict[str, Any]]]) -> Optional[Dict[str, Any]]: """The caller's record of what the unit holds after the change -- for the result and the audit row only. It never decides the outcome.""" diff --git a/sfm/device_access/errors.py b/sfm/device_access/errors.py index 6f65e31..b405904 100644 --- a/sfm/device_access/errors.py +++ b/sfm/device_access/errors.py @@ -88,6 +88,18 @@ class EventNotFound(DeviceError): http_status = 404 +class SettingsChanged(DeviceError): + """The unit's settings changed since the preview the request names (a keypad + edit, another program, or a preview of another unit). Nothing was sent.""" + http_status = 409 + + +class ChangeRefused(DeviceError): + """A change SFM will not send to this unit, and why -- its factory setup, a + schedule that would undo it, a block SFM has not seen. Nothing was sent.""" + http_status = 409 + + class StaleEvent(DeviceError): """The event at that key is not the one listed -- the unit was erased, or its memory wrapped, since the list was read.""" diff --git a/sfm/device_access/s4.py b/sfm/device_access/s4.py index 57b8f95..4dd3ce3 100644 --- a/sfm/device_access/s4.py +++ b/sfm/device_access/s4.py @@ -19,16 +19,27 @@ from typing import Any, Callable, Optional, TypeVar from micromate.client import MicromateClient from micromate.opcodes import OpcodeRefused from micromate.protocol import THOR_CHUNK_SIZE +from micromate.protocol import ProtocolError as _MMProtocolError +from micromate.schedule import parse_schedule, schedule_conflicts +from micromate.setup_block import decode_setup +from micromate.setup_fields import ( + SettingsValueError, check_changes, editable_fields, encode_setup, field_rows, settings_state, +) +from micromate.setup_fields import revision as settings_revision from micromate.writes import ( - is_call_home_content, plan_call_home_enabled, plan_start_monitoring, plan_stop_monitoring, + is_call_home_content, plan_call_home_enabled, plan_setup_push, plan_start_monitoring, + plan_stop_monitoring, ) from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport from .errors import ( - AuditIncomplete, CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound, - MalformedReply, StaleEvent, UnitStateUnknown, WrongUnit, translate, + AuditIncomplete, BadRequest, CallHomeInProgress, ChangeRefused, ChangeUnconfirmed, DeviceError, + EventNotFound, MalformedReply, SettingsChanged, StaleEvent, UnitStateUnknown, WrongUnit, + translate, +) +from .change import ( + CALL_HOME_MESSAGE, call_home_change, monitoring_change, run_change, settings_change, ) -from .change import CALL_HOME_MESSAGE, call_home_change, monitoring_change, run_change from .events import iso_of, make_event_id, stamp_of from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus) @@ -268,7 +279,8 @@ def s4_status(client: Any, serial: str, run_state: bool = False) -> UnitStatus: def s4_settings(client: Any, serial: str) -> UnitSettings: - s = client.get_setup() + content = client.get_setup_content() + s = decode_setup(content) return UnitSettings( serial=serial, series=4, setup_name=s.name, record_mode=s.record_mode_name, sample_rate=s.sample_rate, record_time_s=s.record_time_s, @@ -293,6 +305,7 @@ def s4_settings(client: Any, serial: str) -> UnitSettings: "distance_ft": s.distance_ft, "charge_weight_lb": s.charge_weight_lb, "scaled_distance": s.scaled_distance, + "editable": editable_fields(content, 4), }, ) @@ -452,3 +465,118 @@ def s4_change_call_home(client: Any, serial: str, *, enabled: bool, dry_run: boo is_ring=lambda e: isinstance(e, RingDetected), pre_send=lambda: client.read_unsolicited(), snapshot=snapshot) + + +# ── Changing settings (phase 5) ────────────────────────────────────────────── + +S4_SETTINGS_WHILE_MONITORING = ("is monitoring -- stop it first (a stop makes it call in if " + "call-home is on)") +_EDIT_BUFFER_WARNING = ("this reads the unit's keypad edit buffer: if someone is in its menu, " + "their unsaved edits are sent too") +_FACTORY = "factory.mmb" + + +def s4_change_settings(client: Any, serial: str, *, changes: dict, revision: Optional[str], + dry_run: bool, audit: Any, address: UnitAddress, caller: str, + sleep: Callable[[float], None], verify_timeout_s: float, + verify_interval_s: float) -> ChangeResult: + """Series-4 pieces for the shared core: read the name, preferences, trigger + and setup blocks and the schedule; patch the setup's fields + (micromate.setup_fields); send THOR's setup push under the active setup's own + name; read the setup back. The plan is built from the read run_change made + just before it, and that same plan is the one sent. + + Refused before anything is sent: a monitoring unit; values the unit does not + allow (BadRequest); a live call whose `revision` is not this read's + (SettingsChanged); the factory setup, a schedule that would load another + setup, an unreadable schedule, or a block SFM has not seen (ChangeRefused, + shown as `blocked` in a preview).""" + st: dict = {} + reads: list = [] + + def first_read() -> str: + name = client.get_active_setup_raw() + prefs = client.get_prefs_content() + trigger = client.get_trigger_content() + setup = client.get_setup_content() + try: + normal = check_changes(setup, 4, changes) + except SettingsValueError as exc: + raise BadRequest(f"{exc} -- nothing sent") from exc + rev = settings_revision([name.encode("ascii", "replace"), prefs, trigger, setup]) + 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, 4, normal) + blocked: list = [] + warnings = [_EDIT_BUFFER_WARNING] + if name.strip().casefold() == _FACTORY: + blocked.append("this unit is running its factory setup; load any other setup on " + "its keypad, then try again") + try: + entries = parse_schedule(client.read_schedule()) + except (_MMProtocolError, ValueError) as exc: + blocked.append(f"could not read this unit's schedule ({exc}) -- SFM will not change " + "a unit whose schedule it cannot check") + else: + conflicts = schedule_conflicts(entries, name) + for e in conflicts: + blocked.append(f"this unit's schedule loads {e.setup} at {e.time}, which would " + "replace this change") + for e in entries: + if "start_with_setup" in e.actions and e not in conflicts: + warnings.append(f"the unit's schedule loads this setup at {e.time}; the " + "change survives it") + plan = None + try: + plan = plan_setup_push(prefs, trigger, image, name) + except ValueError as exc: + blocked.append(f"this unit's {exc} -- SFM has not seen a block like it") + st.update(name=name, prefs=prefs, trigger=trigger, setup=setup, image=image, + changes=normal, revision=rev, blocked=blocked, warnings=warnings, plan=plan) + reads.append(setup) + return settings_state(setup, image, setup, series=4) + + def read_state() -> str: + run = client.read_run_state().name + if run == "calling_home" or run.startswith("unknown"): + return run # the core refuses both; a write waits for a known state + if not st: + if run == "monitoring": + raise UnitStateUnknown(f"{serial} {S4_SETTINGS_WHILE_MONITORING} -- nothing sent") + return first_read() + now = client.get_setup_content() + reads.append(now) + return settings_state(st["setup"], st["image"], now, series=4) + + def describe_plan() -> dict: + ok = st["plan"] is not None and not st["blocked"] + d = st["plan"].describe() if ok else {"action": "setup push", "steps": [], "warnings": []} + d["warnings"] = list(st["warnings"]) + list(d.get("warnings", [])) + d.update(fields=field_rows(st["setup"], st["image"], 4, st["changes"]), + revision=st["revision"], blocked=list(st["blocked"])) + if st["blocked"] and not dry_run: + raise ChangeRefused("; ".join(st["blocked"]) + " -- nothing sent") + return d + + def send() -> dict: + acks = client.protocol.execute(st["plan"]) + return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]} + + def snapshot() -> dict: + before, after = st["setup"], reads[-1] + return {"fields": field_rows(before, st["image"], 4, st["changes"], now=after), + "before": before.hex(), "after": after.hex(), + "changed_offsets": _changed_offsets(before, after), + "prefs": st["prefs"].hex(), "trigger": st["trigger"].hex()} + + return run_change( + kind=settings_change(), serial=serial, series=4, 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=lambda: client.serial(refresh=True), + read_state=read_state, describe_plan=describe_plan, send=send, + is_refusal=lambda e: isinstance(e, OpcodeRefused), + is_ring=lambda e: isinstance(e, RingDetected), + pre_send=lambda: client.read_unsolicited(), + snapshot=snapshot) diff --git a/tests/device_access_fakes.py b/tests/device_access_fakes.py index 54d94d0..63fcd1d 100644 --- a/tests/device_access_fakes.py +++ b/tests/device_access_fakes.py @@ -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") diff --git a/tests/test_device_access_s4_settings.py b/tests/test_device_access_s4_settings.py new file mode 100644 index 0000000..f91a4c7 --- /dev/null +++ b/tests/test_device_access_s4_settings.py @@ -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 == [] diff --git a/tests/test_micromate_execute.py b/tests/test_micromate_execute.py index ac11dcc..bfaa68b 100644 --- a/tests/test_micromate_execute.py +++ b/tests/test_micromate_execute.py @@ -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) diff --git a/tests/test_micromate_opcodes.py b/tests/test_micromate_opcodes.py index b70184b..b181e19 100644 --- a/tests/test_micromate_opcodes.py +++ b/tests/test_micromate_opcodes.py @@ -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):