feat(sfm): Series-4 call-home state and audited enable/disable (phase 4)
- micromate: ENABLEABLE_WRITES gains 0x7E/0x7F (the call-home write and its confirm; spec row 9, enable/disable only); MicromateClient.get_call_home_content() returns the 126-byte 0x2C content. - sfm/device_access: CallHomeState (serial, series, enabled, dial_string, detail with byte5 and the whole block); s4_call_home_state reads bit 0 of [5] and the dial string at [6:46]; s4_change_call_home runs the shared change core with micromate.writes.plan_call_home_enabled -- built from the read run_change made just before, and that same plan is the one sent. A unit calling home (run state 0x03) is refused, nothing sent. The read-back judges the edited bit only; the snapshot records both blocks and every changed offset -- [118:120] is unit-maintained and always moves. - The write-ceiling tests take 0x71 (the setup write, phase 5) as their over-the-ceiling example now that 0x7E is enableable. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
1dd5bfa464
commit
eeb55effe9
7 files changed
+213
-13
No files matched your search
@@ -388,6 +388,11 @@ class MicromateClient:
|
||||
# Anything else reads unknown(0x..): the safe default, which the change path refuses.
|
||||
_RUN_STATES = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
|
||||
|
||||
def get_call_home_content(self) -> bytes:
|
||||
"""The `0x2C` call-home block's 126-byte content (bit 0 of [5] is the
|
||||
enable, [6:46] the dial string; [118:120] is unit-maintained)."""
|
||||
return _content(self.protocol.read_call_home_config())
|
||||
|
||||
def read_run_state(self) -> MicromateRunState:
|
||||
"""`SUB 0x49` -> the unit's run state, with the in-call-home value kept
|
||||
(connect()'s `monitoring` bool flattens 0x03 into True)."""
|
||||
|
||||
@@ -84,8 +84,9 @@ READ_SUBS: Mapping[int, str] = MappingProxyType(_READ_SUBS)
|
||||
# The write SUBs any code may transmit at all -- through MicromateProtocol.execute,
|
||||
# one call at a time. Raising this is a spec change, reviewed like one: delete
|
||||
# (0xA8/0xAA), raw file writes (0x8D/0x8E -- they could reach the modem
|
||||
# settings) and 0xA2 never belong here without one.
|
||||
ENABLEABLE_WRITES = frozenset({0x96, 0x97})
|
||||
# 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})
|
||||
|
||||
|
||||
class OpcodeRefused(RuntimeError):
|
||||
|
||||
@@ -69,6 +69,18 @@ class UnitSettings:
|
||||
detail: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CallHomeState:
|
||||
"""A unit's call-home switch, read by serial (phase 4). `enabled` is None when
|
||||
the enable byte is not a value ever measured; `detail` keeps `byte5` and the
|
||||
whole `block` (hex) as read."""
|
||||
serial: str
|
||||
series: int
|
||||
enabled: Optional[bool]
|
||||
dial_string: Optional[str]
|
||||
detail: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class EventRef:
|
||||
"""One stored event, as listed. `event_id` is opaque: pass it back to
|
||||
|
||||
+65
-3
@@ -19,16 +19,17 @@ 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.writes import plan_start_monitoring, plan_stop_monitoring
|
||||
from micromate.writes import plan_call_home_enabled, plan_start_monitoring, plan_stop_monitoring
|
||||
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
|
||||
|
||||
from .errors import (
|
||||
AuditIncomplete, CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound,
|
||||
MalformedReply, StaleEvent, WrongUnit, translate,
|
||||
)
|
||||
from .change import CALL_HOME_MESSAGE, monitoring_change, run_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 ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||||
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress,
|
||||
UnitInfo, UnitSettings, UnitStatus)
|
||||
from .series import normalise_serial
|
||||
|
||||
log = logging.getLogger("sfm.device_access")
|
||||
@@ -370,3 +371,64 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
|
||||
# out. One transport read: RingWatchTransport over Tcp/SerialTransport,
|
||||
# each with a 10 ms read timeout, so it returns at once on a quiet line.
|
||||
pre_send=lambda: client.read_unsolicited())
|
||||
|
||||
|
||||
def _dial_string(block: bytes) -> Optional[str]:
|
||||
raw = bytes(block[6:46]).split(b"\x00", 1)[0]
|
||||
return raw.decode("ascii", errors="replace") or None
|
||||
|
||||
|
||||
def _changed_offsets(before: bytes, after: bytes) -> list:
|
||||
return [i for i in range(max(len(before), len(after)))
|
||||
if (before[i] if i < len(before) else None) != (after[i] if i < len(after) else None)]
|
||||
|
||||
|
||||
def s4_call_home_state(client: Any, serial: str) -> CallHomeState:
|
||||
"""Bit 0 of content[5] is the enable (UM12947 reads 0x05 / 0x04, UM20147 0x01)."""
|
||||
block = client.get_call_home_content()
|
||||
return CallHomeState(serial=serial, series=4, enabled=bool(block[5] & 0x01),
|
||||
dial_string=_dial_string(block),
|
||||
detail={"byte5": f"0x{block[5]:02X}", "block": block.hex()})
|
||||
|
||||
|
||||
def s4_change_call_home(client: Any, serial: str, *, enabled: bool, dry_run: bool,
|
||||
even_if_already: 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 0x2C, flip bit 0 of [5], send the
|
||||
rest back byte for byte, re-read. The plan is built from the read run_change
|
||||
made just before it (spec: build the plan on the same line, right before
|
||||
sending), and that same plan is the one sent."""
|
||||
reads: list = []
|
||||
planned: list = []
|
||||
|
||||
def read_state() -> str:
|
||||
if client.read_run_state().name == "calling_home":
|
||||
return "calling_home"
|
||||
block = client.get_call_home_content()
|
||||
reads.append(block)
|
||||
return "enabled" if block[5] & 0x01 else "disabled"
|
||||
|
||||
def describe_plan() -> dict:
|
||||
planned[:] = [plan_call_home_enabled(reads[-1], enabled)]
|
||||
return planned[0].describe()
|
||||
|
||||
def send() -> dict:
|
||||
acks = client.protocol.execute(planned[0])
|
||||
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 = reads[0], reads[-1]
|
||||
return {"before": before.hex(), "after": after.hex(),
|
||||
"changed_offsets": _changed_offsets(before, after)}
|
||||
|
||||
return run_change(
|
||||
kind=call_home_change(enabled), serial=serial, series=4, dry_run=dry_run,
|
||||
even_if_already=even_if_already, 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)
|
||||
@@ -8,6 +8,7 @@ from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import datetime
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from micromate.models import MicromateDeviceInfo, MicromateEventRef, MicromateState
|
||||
@@ -16,6 +17,14 @@ 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"
|
||||
THOR_WRITES = Path(__file__).parent / "fixtures" / "micromate-writes"
|
||||
|
||||
|
||||
def um12947_call_home(enabled: bool = True) -> bytes:
|
||||
"""UM12947's own 126-byte call-home content, as THOR read it (0x05 on, 0x04 off)."""
|
||||
ex = json.loads((THOR_WRITES / "call-home-enable-disable.json").read_text())["exchanges"]
|
||||
reads = [bytes.fromhex(e["response_data"])[11:] for e in ex if e["sub"] == 0x2C]
|
||||
return next(r for r in reads if r[5] == (0x05 if enabled else 0x04))
|
||||
|
||||
|
||||
from minimateplus.protocol import TimeoutError as mmp_TimeoutError # noqa: E402
|
||||
@@ -237,15 +246,25 @@ class _FakeProtocol:
|
||||
self._owner.executed.append(plan)
|
||||
if self._owner.execute_error is not None:
|
||||
raise self._owner.execute_error
|
||||
for st in plan.steps:
|
||||
if st.sub == 0x7E: # the unit stores the block and moves [118:120] itself
|
||||
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:])
|
||||
return [type("Ack", (), {"sub": s.ack_sub, "data": bytes(11)})() for s in plan.steps]
|
||||
|
||||
def read_call_home_config(self):
|
||||
self._owner._step("read_call_home_config")
|
||||
return bytes(11) + self._owner.call_home
|
||||
|
||||
|
||||
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, **kw):
|
||||
serial_reported=None, execute_error=None, call_home=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
|
||||
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
|
||||
@@ -272,6 +291,10 @@ class FakeMicromateClient(_Base):
|
||||
self._step("serial")
|
||||
return self.serial_reported if refresh else self.unit_serial
|
||||
|
||||
def get_call_home_content(self) -> bytes:
|
||||
self._step("get_call_home_content")
|
||||
return self.call_home
|
||||
|
||||
def read_run_state(self):
|
||||
from micromate.models import MicromateRunState
|
||||
self._step("read_run_state")
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Series 4 call-home: read the enable bit and dial string, and change it through
|
||||
the audited path (phase 4). The frames are micromate.writes' (equal to THOR's
|
||||
for UM12947); [118:120] is unit-maintained and moves after any config write."""
|
||||
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 FakeMicromateClient, um12947_call_home # noqa: E402
|
||||
from micromate.opcodes import ENABLEABLE_WRITES # noqa: E402
|
||||
from micromate.writes import plan_call_home_enabled # noqa: E402
|
||||
from sfm.device_access.errors import CallHomeInProgress # noqa: E402
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
from sfm.device_access.s4 import s4_call_home_state, s4_change_call_home # 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 change(fake, *, enabled, dry_run=False, even_if_already=False):
|
||||
return s4_change_call_home(fake, "UM20147", enabled=enabled, dry_run=dry_run,
|
||||
even_if_already=even_if_already, audit=Audit(), address=ADDR,
|
||||
caller="test", sleep=lambda s: None,
|
||||
verify_timeout_s=3.0, verify_interval_s=1.0)
|
||||
|
||||
|
||||
def test_call_home_writes_are_now_enableable():
|
||||
assert {0x7E, 0x7F} <= ENABLEABLE_WRITES
|
||||
|
||||
|
||||
def test_s4_call_home_state_reads_the_enable_bit_and_dial_string():
|
||||
st = s4_call_home_state(FakeMicromateClient(), "UM20147")
|
||||
assert (st.serial, st.series, st.enabled, st.dial_string) == ("UM20147", 4, True, "RADIO RING")
|
||||
assert st.detail["byte5"] == "0x05"
|
||||
assert st.detail["block"] == um12947_call_home().hex()
|
||||
assert s4_call_home_state(FakeMicromateClient(call_home=um12947_call_home(False)), "UM20147").enabled is False
|
||||
|
||||
|
||||
def test_s4_dry_run_shows_thors_frames():
|
||||
fake = FakeMicromateClient()
|
||||
r = change(fake, enabled=False, dry_run=True)
|
||||
assert r.outcome == "dry_run"
|
||||
assert r.plan["steps"] == plan_call_home_enabled(um12947_call_home(), False).describe()["steps"]
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_s4_disable_sends_7e_7f_and_verifies():
|
||||
fake = FakeMicromateClient()
|
||||
r = change(fake, enabled=False)
|
||||
assert (r.outcome, r.verified, r.state_after, r.action) == ("sent", "ok", "disabled", "disable call-home")
|
||||
assert [st.sub for st in fake.executed[0].steps] == [0x7E, 0x7F]
|
||||
assert fake.call_home[5] == 0x04
|
||||
|
||||
|
||||
def test_s4_unit_maintained_bytes_do_not_make_a_mismatch():
|
||||
r = change(FakeMicromateClient(), enabled=False)
|
||||
assert r.verified == "ok"
|
||||
snap = r.detail["snapshot"]
|
||||
assert snap["changed_offsets"] == [5, 118, 119]
|
||||
assert snap["before"] == um12947_call_home().hex() and snap["after"] != snap["before"]
|
||||
|
||||
|
||||
def test_s4_no_change_while_calling_home():
|
||||
fake = FakeMicromateClient(run_states=[0x03])
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
change(fake, enabled=False)
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_s4_already_enabled_is_skipped():
|
||||
fake = FakeMicromateClient()
|
||||
r = change(fake, enabled=True)
|
||||
assert r.outcome == "skipped" and fake.executed == []
|
||||
|
||||
|
||||
def test_s4_even_if_already_sends_the_no_op_write():
|
||||
fake = FakeMicromateClient()
|
||||
r = change(fake, enabled=True, even_if_already=True)
|
||||
assert len(fake.executed) == 1
|
||||
assert any("changes nothing" in w for w in r.plan["warnings"])
|
||||
@@ -16,7 +16,7 @@ from micromate.framing import FLAGS_THOR, build_request # noqa:
|
||||
from micromate.opcodes import ENABLEABLE_WRITES, OpcodeRefused # noqa: E402
|
||||
from micromate.protocol import ACK_DATA_LEN, TimeoutError as MmTimeout, UnexpectedResponse # noqa: E402
|
||||
from micromate.writes import ( # noqa: E402
|
||||
WritePlan, WriteStep, plan_call_home_enabled, plan_start_monitoring,
|
||||
WritePlan, WriteStep, plan_start_monitoring,
|
||||
plan_stop_monitoring,
|
||||
)
|
||||
from test_micromate_protocol import frame, proto # noqa: E402
|
||||
@@ -33,8 +33,9 @@ def _ready(responses):
|
||||
return p, t
|
||||
|
||||
|
||||
def test_the_ceiling_is_start_and_stop_only():
|
||||
assert ENABLEABLE_WRITES == frozenset({0x96, 0x97})
|
||||
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_execute_sends_exactly_the_plans_frame_and_returns_the_ack():
|
||||
@@ -53,10 +54,10 @@ def test_permission_ends_with_the_call():
|
||||
|
||||
|
||||
def test_a_plan_beyond_the_ceiling_is_refused_and_nothing_is_sent():
|
||||
content = bytes(5) + b"\x05" + bytes(120)
|
||||
# 0x71 (the setup-block write) stays above the ceiling until phase 5.
|
||||
p, t = _ready([])
|
||||
with pytest.raises(OpcodeRefused, match="ceiling"):
|
||||
p.execute(plan_call_home_enabled(content, False))
|
||||
p.execute(WritePlan("setup push", (WriteStep(0x71, 0x0000, bytes(4)),)))
|
||||
assert t.written == []
|
||||
|
||||
|
||||
@@ -110,7 +111,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(0x7E, 0),)) # subs now reads 0x7E too
|
||||
object.__setattr__(plan, "steps", (WriteStep(0x71, 0),)) # subs now reads 0x71 too
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p.execute(plan)
|
||||
assert t.written == []
|
||||
@@ -121,7 +122,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(0x7E, 0)))
|
||||
plan = Lying("x", (WriteStep(0x96, 0xFFFF), WriteStep(0x71, 0)))
|
||||
p, t = _ready([ACK_START])
|
||||
with pytest.raises(OpcodeRefused):
|
||||
p.execute(plan)
|
||||
|
||||
Reference in new issue
Block a user