feat(sfm): Series-3 call-home state and audited enable/disable, live send gated until its frame is verified (phase 4)

- minimateplus.protocol: call_home_enabled(raw) reads byte 5 of the UNESCAPED
  0x2C payload (0x01 on / 0x00 off, measured 2026-04-20; anything else None --
  bench finding #1's lesson: an escaped byte before it would move the raw
  index); call_home_image(raw, enabled) is write_image's N + 2 image with byte 5
  set and everything else as read, refusing a byte 5 never measured.
- MiniMateClient.read_call_home_raw() / write_call_home_image(image) (0x7E then
  0x7F, each ack checked, never retried).
- Series3Adapter.call_home_state (wake, then 0x2C; no serial read, like status)
  and change_call_home: the shared change core with a connect() identity check,
  state 'enabled' / 'disabled' / 'unknown(0xNN)' (unknown sends nothing), the
  plan showing both exact frames, a snapshot of both unescaped images.
- S3_CALL_HOME_FRAME_VERIFIED = False: a live change is refused (501) before any
  connection until the frame is reproduced from Blastware's (next commit).

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-02 16:57:55 -05:00
1 parent eeb55effe9
commit 8612cd9df7
5 files changed
+267 -6

No files matched your search

+10
View File
@@ -1127,6 +1127,16 @@ class MiniMateClient:
raw = proto.read_call_home_config() raw = proto.read_call_home_config()
return _decode_call_home_config(raw) return _decode_call_home_config(raw)
def read_call_home_raw(self) -> bytes:
"""The `0x2C` reply payload as read (125 B, kept escapes in), for a
read-modify-write (`call_home_image`)."""
return self._require_proto().read_call_home_config()
def write_call_home_image(self, image: bytes) -> None:
"""Send a `0x7E` image (`call_home_image`) and its `0x7F` confirm, each ack
checked. No retry: what happened is the caller's to read back."""
self._require_proto().write_call_home_config(image)
def set_call_home_config( def set_call_home_config(
self, self,
*, *,
+21
View File
@@ -165,6 +165,27 @@ def write_image(sub: int, data: bytes) -> bytes:
return image return image
def call_home_enabled(raw: bytes) -> Optional[bool]:
"""The call-home switch of a `0x2C` reply payload, read UNESCAPED (an escaped
byte before it would move the raw index -- bench finding #1's lesson): byte 5,
0x01 on / 0x00 off (measured 2026-04-20, BE11529). Anything else is None."""
image = unescape_reply(bytes(raw))
if len(image) <= 5:
return None
return {0x01: True, 0x00: False}.get(image[5])
def call_home_image(raw: bytes, enabled: bool) -> bytes:
"""The `0x7E` image that turns call-home on or off: the block as read
(`write_image`, N + 2 bytes, unescaped) with byte 5 set to 0x01 / 0x00 and
every other byte as the unit sent it. Refuses a byte 5 never measured."""
image = write_image(SUB_CALL_HOME_WRITE, raw)
if image[5] not in (0x00, 0x01):
raise ValueError(f"call-home byte 5 is 0x{image[5]:02X} -- not a value ever measured "
"(0x00 off / 0x01 on); nothing built")
return image[:5] + bytes([0x01 if enabled else 0x00]) + image[6:]
# Default timeout values (seconds). # Default timeout values (seconds).
# MiniMate Plus is a slow device — keep these generous. # MiniMate Plus is a slow device — keep these generous.
DEFAULT_RECV_TIMEOUT = 10.0 DEFAULT_RECV_TIMEOUT = 10.0
+94 -5
View File
@@ -10,14 +10,19 @@ from typing import Any, Callable, Optional
from minimateplus import MiniMateClient from minimateplus import MiniMateClient
from minimateplus.blastware_file import blastware_file_bytes, blastware_filename, with_type_letter from minimateplus.blastware_file import blastware_file_bytes, blastware_filename, with_type_letter
from minimateplus.event_file_io import _GEO_INT16_FS from minimateplus.event_file_io import _GEO_INT16_FS
from minimateplus.framing import build_bw_write_frame from minimateplus.framing import build_bw_write_frame, unescape_reply
from minimateplus.protocol import SUB_START_MONITORING, SUB_STOP_MONITORING from minimateplus.protocol import (
SUB_CALL_HOME_CONFIRM, SUB_CALL_HOME_WRITE, SUB_START_MONITORING, SUB_STOP_MONITORING,
call_home_enabled, call_home_image, write_image,
)
from minimateplus.transport import TcpTransport from minimateplus.transport import TcpTransport
from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, StaleEvent, WrongUnit, translate from .errors import (DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported, StaleEvent,
from .change import monitoring_change, run_change WrongUnit, translate)
from .change import call_home_change, monitoring_change, run_change
from .events import iso_of, make_event_id, stamp_of 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)
log = logging.getLogger("sfm.device_access") log = logging.getLogger("sfm.device_access")
@@ -27,6 +32,11 @@ S3_MODES = {0x00: "Single Shot", 0x01: "Continuous", 0x03: "Histogram", 0x04: "H
S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use
# A MiniMate call-home write goes out only once SFM's 0x7E / 0x7F frames are
# reproduced from Blastware's own (tests/test_s3_call_home_bw_frames.py). Until
# then a live change is refused before any connection; a dry run still works.
S3_CALL_HOME_FRAME_VERIFIED = False
# The 0x1C flag byte (section[1]): the only values ever measured. 0x10 is # The 0x1C flag byte (section[1]): the only values ever measured. 0x10 is
# BE11529 monitoring (2026-04-08); 0x0B is BE9441 recording a histogram, # 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. # confirmed at the unit (2026-10-26). Anything else is refused for a change.
@@ -330,6 +340,85 @@ class Series3Adapter:
) )
return self._run(address, op) return self._run(address, op)
def call_home_state(self, address: UnitAddress, serial: str) -> CallHomeState:
"""The unit's call-home switch and dial string (0x2C), after a wake. Like
status, it reads no serial: the one shown is the one requested."""
def op(client: Any) -> CallHomeState:
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
raw = client.read_call_home_raw()
image = unescape_reply(raw)
dial = bytes(image[6:46]).split(b"\x00", 1)[0].decode("ascii", errors="replace") or None
return CallHomeState(serial=serial, series=3, enabled=call_home_enabled(raw),
dial_string=dial,
detail={"byte5": f"0x{image[5]:02X}" if len(image) > 5 else None,
"block": bytes(raw).hex(), "serial_verified": False})
return self._run(address, op)
def change_call_home(self, address: UnitAddress, serial: str, *, enabled: bool, dry_run: bool,
even_if_already: 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: read 0x2C, set byte 5 of the
unescaped image, send it (0x7E) and confirm (0x7F), re-read. One attempt,
never retried; refused live until the frame is verified against Blastware."""
if not dry_run and not S3_CALL_HOME_FRAME_VERIFIED:
raise NotSupported("a MiniMate call-home write waits until its frame has been "
"reproduced from a Blastware capture -- nothing sent")
what = "call-home " + ("enable" if enabled else "disable")
def op(client: Any) -> ChangeResult:
reads: list = []
images: 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)
raw = client.read_call_home_raw()
reads.append(raw)
on = call_home_enabled(raw)
if on is None:
image = unescape_reply(raw)
return f"unknown(0x{image[5]:02X})" if len(image) > 5 else "unknown(short)"
return "enabled" if on else "disabled"
def describe_plan() -> dict:
try:
image = call_home_image(reads[-1], enabled)
except ValueError as exc:
images[:] = []
return {"action": what, "steps": [], "warnings": [f"{exc}; nothing would be sent"]}
images[:] = [image]
warnings = []
if image == write_image(SUB_CALL_HOME_WRITE, reads[-1]):
warnings.append(f"the unit is already call-home {'enabled' if enabled else 'disabled'}"
" -- this write changes nothing")
return {"action": what, "warnings": warnings, "steps": [
{"sub": f"0x{SUB_CALL_HOME_WRITE:02X}", "what": "call-home config write",
"data_len": len(image), "frame": build_bw_write_frame(SUB_CALL_HOME_WRITE, image).hex()},
{"sub": f"0x{SUB_CALL_HOME_CONFIRM:02X}", "what": "call-home config confirm",
"data_len": 0, "frame": build_bw_write_frame(SUB_CALL_HOME_CONFIRM, b"").hex()}]}
def send() -> dict:
client.write_call_home_image(images[0])
return {"subs": [f"0x{0xFF - SUB_CALL_HOME_WRITE:02X}", f"0x{0xFF - SUB_CALL_HOME_CONFIRM:02X}"]}
def snapshot() -> dict:
before = write_image(SUB_CALL_HOME_WRITE, reads[0])
after = write_image(SUB_CALL_HOME_WRITE, reads[-1])
return {"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=call_home_change(enabled), serial=serial, series=3, 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=read_serial, read_state=read_state,
describe_plan=describe_plan, send=send, snapshot=snapshot)
return self._run(address, op, retry=False)
def settings(self, address: UnitAddress, serial: str) -> UnitSettings: def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
def op(client: Any) -> UnitSettings: def op(client: Any) -> UnitSettings:
info = client.connect() info = client.connect()
+19 -1
View File
@@ -20,6 +20,15 @@ THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
THOR_WRITES = Path(__file__).parent / "fixtures" / "micromate-writes" THOR_WRITES = Path(__file__).parent / "fixtures" / "micromate-writes"
def s3_call_home_raw(byte5: int = 0x01) -> bytes:
"""A MiniMate's 0x2C reply payload as S3FrameParser returns it (125 B, the
num_retries 3 kept as 10 03), laid out as the 4-20-26 captures measured
(BE11529): header 00 7C DC, [5] the enable, [6:46] the dial string."""
raw = b"\x00\x7c\xdc\x00\x00" + bytes([byte5]) + b"RADIO RING".ljust(40, b"\x00")
raw += bytes(117 - len(raw)) + b"\x10\x03"
return raw + bytes(125 - len(raw))
def um12947_call_home(enabled: bool = True) -> bytes: def um12947_call_home(enabled: bool = True) -> bytes:
"""UM12947's own 126-byte call-home content, as THOR read it (0x05 on, 0x04 off).""" """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"] ex = json.loads((THOR_WRITES / "call-home-enable-disable.json").read_text())["exchanges"]
@@ -88,13 +97,14 @@ def default_s3_events():
class FakeMiniMateClient(_Base): class FakeMiniMateClient(_Base):
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None, def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None,
monitor_states=None, write_error=None, serial_reported=None, wake_errors=None, monitor_states=None, write_error=None, serial_reported=None, wake_errors=None,
bare_requests_ignored=False, **kw): bare_requests_ignored=False, call_home_raw=None, **kw):
super().__init__(**kw) super().__init__(**kw)
self.serial = serial self.serial = serial
# As a monitoring MiniMate (measured 2026-04-08): on a fresh connection a # 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. # read before SESSION_RESET + POLL goes unanswered. Off unless a test asks.
self.bare_requests_ignored = bare_requests_ignored self.bare_requests_ignored = bare_requests_ignored
self._woken = False self._woken = False
self.call_home_raw = s3_call_home_raw() if call_home_raw is None else call_home_raw
# read_serial()'s answer (connect() keeps answering `serial`), and errors # read_serial()'s answer (connect() keeps answering `serial`), and errors
# raised by wake() once a write has gone out -- the read-back's wakes. # raised by wake() once a write has gone out -- the read-back's wakes.
self.serial_reported = serial if serial_reported is None else serial_reported self.serial_reported = serial if serial_reported is None else serial_reported
@@ -147,6 +157,14 @@ class FakeMiniMateClient(_Base):
self._bare_read("read_serial") self._bare_read("read_serial")
return self.serial_reported return self.serial_reported
def read_call_home_raw(self) -> bytes:
self._bare_read("read_call_home_raw")
return self.call_home_raw
def write_call_home_image(self, image: bytes) -> None:
self._write("call_home")
self.call_home_raw = bytes(image) # read back as the unit would store it
def get_monitor_status(self) -> MonitorStatus: def get_monitor_status(self) -> MonitorStatus:
self._bare_read("get_monitor_status") self._bare_read("get_monitor_status")
state = self.monitor_states.pop(0) if len(self.monitor_states) > 1 else self.monitor_states[0] state = self.monitor_states.pop(0) if len(self.monitor_states) > 1 else self.monitor_states[0]
+123
View File
@@ -0,0 +1,123 @@
"""Series 3 call-home: the enable byte from the unescaped 0x2C block, a write that
changes byte 5 only, and the audited change (phase 4). The live send stays
refused until its frame is reproduced from a Blastware capture (task 4)."""
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 sfm.device_access.s3 as s3mod # noqa: E402
from device_access_fakes import FakeMiniMateClient, s3_call_home_raw # noqa: E402
from minimateplus.protocol import ( # noqa: E402
SUB_CALL_HOME_WRITE, call_home_enabled, call_home_image, write_image,
)
from sfm.device_access.errors import NotSupported, UnitStateUnknown # noqa: E402
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)
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):
calls = []
def factory(address, **kw):
calls.append(kw)
return fake
a = Series3Adapter(client_factory=factory)
a.factory_calls = calls
return a
def change(a, *, enabled, dry_run=False, even_if_already=False):
return a.change_call_home(TCP, "BE18193", enabled=enabled, dry_run=dry_run,
even_if_already=even_if_already, audit=Audit(), caller="test",
sleep=lambda s: None, verify_timeout_s=3.0, verify_interval_s=1.0)
def test_s3_enable_byte_reads_from_the_unescaped_block():
raw = s3_call_home_raw()
assert call_home_enabled(raw) is True
assert call_home_enabled(s3_call_home_raw(0x00)) is False
# An escaped byte before [5] moves the raw index; the unescaped one does not.
shifted = raw[:2] + b"\x10\x03" + raw[3:]
assert shifted[5] != raw[5] and call_home_enabled(shifted) is True
assert call_home_enabled(s3_call_home_raw(0x07)) is None
def test_s3_image_changes_only_byte_5():
raw = s3_call_home_raw()
img = call_home_image(raw, False)
base = write_image(SUB_CALL_HOME_WRITE, raw)
assert len(img) == 126 == 0x7C + 2
assert [i for i in range(len(img)) if img[i] != base[i]] == [5]
assert img[5] == 0x00 and call_home_image(raw, True)[5] == 0x01
def test_s3_image_refuses_an_unknown_byte_5():
with pytest.raises(ValueError):
call_home_image(s3_call_home_raw(0x07), True)
def test_s3_call_home_state():
fake = FakeMiniMateClient()
st = adapter(fake).call_home_state(TCP, "BE18193")
assert (st.serial, st.series, st.enabled, st.dial_string) == ("BE18193", 3, True, "RADIO RING")
assert st.detail["serial_verified"] is False and st.detail["byte5"] == "0x01"
assert fake.calls.index("wake") < fake.calls.index("read_call_home_raw")
def test_s3_live_change_is_refused_until_the_frame_is_verified():
a = adapter(FakeMiniMateClient())
with pytest.raises(NotSupported) as e:
change(a, enabled=False)
assert e.value.http_status == 501 and "Blastware" in str(e.value)
assert a.factory_calls == [] # refused before any connection
def test_s3_dry_run_shows_both_frames():
fake = FakeMiniMateClient()
r = change(adapter(fake), enabled=False, dry_run=True)
assert r.outcome == "dry_run"
assert [st["sub"] for st in r.plan["steps"]] == ["0x7E", "0x7F"]
assert fake.writes == []
def test_s3_change_once_verified(monkeypatch):
monkeypatch.setattr(s3mod, "S3_CALL_HOME_FRAME_VERIFIED", True)
fake = FakeMiniMateClient()
r = change(adapter(fake), enabled=False)
assert (r.outcome, r.verified, r.state_after, r.action) == ("sent", "ok", "disabled", "disable call-home")
assert fake.writes == ["call_home"]
assert r.detail["snapshot"]["changed_offsets"] == [5]
def test_s3_unknown_byte_5_sends_nothing(monkeypatch):
monkeypatch.setattr(s3mod, "S3_CALL_HOME_FRAME_VERIFIED", True)
fake = FakeMiniMateClient(call_home_raw=s3_call_home_raw(0x07))
with pytest.raises(UnitStateUnknown):
change(adapter(fake), enabled=False)
assert fake.writes == []
def test_s3_dry_run_with_an_unknown_byte_5_shows_no_frames():
fake = FakeMiniMateClient(call_home_raw=s3_call_home_raw(0x07))
r = change(adapter(fake), enabled=False, dry_run=True)
assert r.plan["steps"] == [] and any("0x07" in w for w in r.plan["warnings"])