From d0335dbbbd0bcf9d62878f48492ab52943413694 Mon Sep 17 00:00:00 2001 From: serversdown Date: Tue, 3 Nov 2026 21:37:30 -0500 Subject: [PATCH] feat(micromate): read the schedule file (read-only) MicromateProtocol.read_file: 0x94 + path, then 0x48 pages to an all-zero reply -- THOR's frames byte for byte (UM12947, 2026-09-24), including params[3] = 1 on 0x94 and params[7] = 1 on the first 0x48. micromate.schedule parses the 260-byte records (two- and five-entry schedules from THOR's captures) and names the scheduled starts that would load a setup other than the active one, ignoring case. The client gains the raw (unstripped) active-setup name and the prefs / trigger / setup content reads a setup push sends back. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- docs/micromate_protocol_reference.md | 9 ++ micromate/client.py | 23 +++++ micromate/protocol.py | 31 ++++++ micromate/schedule.py | 75 ++++++++++++++ tests/test_micromate_opcodes.py | 2 +- tests/test_micromate_schedule.py | 142 +++++++++++++++++++++++++++ 6 files changed, 281 insertions(+), 1 deletion(-) create mode 100644 micromate/schedule.py create mode 100644 tests/test_micromate_schedule.py diff --git a/docs/micromate_protocol_reference.md b/docs/micromate_protocol_reference.md index 9c54cab..05e4fc4 100644 --- a/docs/micromate_protocol_reference.md +++ b/docs/micromate_protocol_reference.md @@ -1925,6 +1925,15 @@ at `payload[3:5]`: | 2nd | `0x0002` | 535 B | the file body | | 3rd | `0x0000` | 11 B | all zeros = **end of file** | +✅ **SFM reads the schedule this way, read-only (2026-11-03, phase 5)** -- +`MicromateProtocol.read_file` / `MicromateClient.read_schedule`, frames equal to +THOR's byte for byte (`tests/test_micromate_schedule.py`). Two details the table +above leaves out: the `0x94` request carries **`params[3] = 1`**, and the **first** +`0x48` carries **`params[7] = 1`** (the later ones all-zero params); both `0x48` +offsets are `0xFFFF`. A long file is **written** in 1,024-byte `0x8E` pieces +(the five-entry *actioncheck* schedule went as 1,024 + 280). ⚠ Unmeasured: what +`0x94` / `0x48` return for a unit with no schedule file. + ⚠ This is the single most consequential find of the session, because it is not specific to the scheduler. **`callhome.MMB` is a file too**, and the call-home config is the last unsolved piece of the project. Reading it should be a diff --git a/micromate/client.py b/micromate/client.py index 37247f6..2f3651e 100644 --- a/micromate/client.py +++ b/micromate/client.py @@ -48,6 +48,7 @@ from .models import ( MicromateState, ) from .protocol import MicromateProtocol, ProtocolError +from .schedule import SCHEDULE_PATH from .setup_block import decode_setup log = logging.getLogger(__name__) @@ -333,6 +334,28 @@ class MicromateClient: """`SUB 0x41` — the loaded `.MMB` file name, e.g. `TEST1.mmb`.""" return _cstring(_content(self._proto.read_active_setup_name())) + def get_active_setup_raw(self) -> str: + """The `0x41` name exactly as stored, up to its NUL -- NOT stripped, so a + setup push writes back the very name the unit holds.""" + return _content(self._proto.read_active_setup_name()).split(b"\x00")[0].decode("ascii", "replace") + + def get_prefs_content(self) -> bytes: + """`SUB 0x08` -- the preferences block's content (a setup push sends it back).""" + return _content(self._proto.read_event_index()) + + def get_trigger_content(self) -> bytes: + """`SUB 0x2E` -- the trigger block's content (a setup push sends it back).""" + return _content(self._proto.read_trigger_config()) + + def get_setup_content(self) -> bytes: + """`SUB 0x1A` -- the setup block's content, undecoded (2,092 B, CRC last). + ⚠ The keypad's edit buffer: unsaved menu edits come back too.""" + return _content(self._proto.read_compliance_config()) + + def read_schedule(self) -> bytes: + """`schedule.dat`, read-only (`micromate.schedule.parse_schedule` reads it).""" + return self._proto.read_file(SCHEDULE_PATH) + def get_setup(self, *, verify: bool = True) -> MicromateSetup: """`SUB 0x1A` — what the unit is set to, decoded. One read. diff --git a/micromate/protocol.py b/micromate/protocol.py index 6e4c4f4..43295e2 100644 --- a/micromate/protocol.py +++ b/micromate/protocol.py @@ -93,6 +93,8 @@ SUB_STATE = 0x49 SUB_BULK_DOWNLOAD = 0x5A SUB_POLL = 0x5B SUB_ARM_EVENT = 0x93 +SUB_FILE_READ_NEXT = 0x48 # file transfer: next page of the file opened by 0x94 +SUB_FILE_OPEN_READ = 0x94 # file transfer: open a file by path, for reading # ⚠ Reads are SINGLE-STEP. Series III probes at offset 0 to learn the length, # then reads again at that length; a Micromate returns the whole block when @@ -102,6 +104,10 @@ READ_ALL = 0xFFFF # The two commands that do NOT use READ_ALL, and the data length each returned # on UM12947 (firmware 11.0CB). +_FILE_OPEN_PARAMS = bytes([0, 0, 0, 1, 0, 0, 0, 0, 0, 0]) +_FILE_FIRST_PAGE_PARAMS = bytes([0, 0, 0, 0, 0, 0, 0, 1, 0, 0]) +_MAX_FILE_PAGES = 64 + _OFFSETS = { SUB_POLL: 0x0030, # 59 B — the one offset THOR treats as a constant SUB_SERIAL: 0x000A, # 21 B @@ -376,6 +382,31 @@ class MicromateProtocol: """ return self._read(SUB_SETUP_NEXT) + # ── Files, by path (read-only) ──────────────────────────────────────────── + + def read_file(self, path: str) -> bytes: + """A file off the unit, by full path: `0x94` + the path opens it, then + `0x48` pages follow until an all-zero reply. The first `0x48` reply is a + descriptor, not file content. Frames are THOR's exactly (UM12947 reading + `schedule.dat`, 2026-09-24): `0x94` carries `params[3] = 1` and the path, + unpadded, as data with offset = its length; the first `0x48` carries + `params[7] = 1`, the rest none. Returns the content (each page's data + after its 11-byte prefix), joined. + """ + raw = path.encode("ascii") + self._request(build_request(SUB_FILE_OPEN_READ, len(raw), _FILE_OPEN_PARAMS, raw), + 0xFF - SUB_FILE_OPEN_READ) + body = bytearray() + for page in range(_MAX_FILE_PAGES): + f = self._exchange(SUB_FILE_READ_NEXT, + params=_FILE_FIRST_PAGE_PARAMS if page == 0 else bytes(10)) + if page == 0: + continue # the descriptor + if not any(f.data): + return bytes(body) + body += f.data[11:] + raise ProtocolError(f"{path}: no end of file after {_MAX_FILE_PAGES} pages") + # ── Event chain ─────────────────────────────────────────────────────────── def arm_event(self) -> MicromateFrame: diff --git a/micromate/schedule.py b/micromate/schedule.py new file mode 100644 index 0000000..c26e870 --- /dev/null +++ b/micromate/schedule.py @@ -0,0 +1,75 @@ +"""schedule.py -- a Micromate's schedule file, parsed. Pure; read-only by design. + +THOR's scheduler lives in a file on the unit, `\\system\\schedule\\schedule.dat`, +read by path (`MicromateProtocol.read_file`). The format is decoded in +docs/micromate_protocol_reference.md, *The schedule record format* (measured on +UM12947, 2026-09-24/25): 260-byte records, + + [0] record 0 only: 3 = repeat on, 2 = repeat off + [4] half-hour slot, 0-47 + [5] day (3 in every record seen -- undetermined) + [6] action bitmask: 2 start monitoring with setup, 4 stop, 8 self-check, + 16 auto call home + [7] setup-name length + [8:260] setup name (empty for actions that take none) + +Why SFM reads it (phase 5): each scheduled start LOADS the setup it names. A +settings change to any other setup would be replaced at the next start, so SFM +refuses that change -- `schedule_conflicts`. SFM never writes the schedule. +""" +from __future__ import annotations + +from dataclasses import dataclass +from typing import List, Tuple + +SCHEDULE_PATH = "\\system\\schedule\\schedule.dat" + +_RECORD = 260 +_NAME_MAX = _RECORD - 8 +_ACTIONS = ((0x02, "start_with_setup"), (0x04, "stop"), (0x08, "self_check"), (0x10, "call_home")) +_KNOWN_BITS = sum(bit for bit, _ in _ACTIONS) + + +@dataclass(frozen=True) +class ScheduleEntry: + index: int + time: str # "HH:MM", from the half-hour slot + day: int # the raw byte; undetermined + action_bits: int + actions: Tuple[str, ...] # named bits; any other set bit as "unknown(0xNN)" + setup: str # "" when the action takes no setup + + +def _actions(bits: int) -> Tuple[str, ...]: + named = tuple(name for bit, name in _ACTIONS if bits & bit) + unknown = tuple(f"unknown(0x{1 << i:02x})" for i in range(8) + if bits & (1 << i) and not (1 << i) & _KNOWN_BITS) + return named + unknown + + +def parse_schedule(body: bytes) -> List[ScheduleEntry]: + """The entries in a schedule file body. A record with nothing in [4:8] and + no name ends the list (the file is padded with zeros).""" + out: List[ScheduleEntry] = [] + for i in range(len(body) // _RECORD): + r = body[i * _RECORD:(i + 1) * _RECORD] + n = min(r[7], _NAME_MAX) + name = r[8:8 + n].decode("ascii", "replace") if n else "" + if not any(r[4:8]) and not name: + break + slot = r[4] + out.append(ScheduleEntry(index=i, time=f"{slot // 2:02d}:{(slot % 2) * 30:02d}", day=r[5], + action_bits=r[6], actions=_actions(r[6]), setup=name)) + return out + + +def _same_setup(a: str, b: str) -> bool: + return a.strip().casefold() == b.strip().casefold() + + +def schedule_conflicts(entries: List[ScheduleEntry], active_setup: str) -> List[ScheduleEntry]: + """The scheduled starts that would load a setup other than `active_setup` + (compared ignoring case and surrounding spaces: THOR and the keypad disagree + on case, e.g. `factory.MMB` / `test2.mmb`).""" + return [e for e in entries + if "start_with_setup" in e.actions and e.setup and not _same_setup(e.setup, active_setup)] diff --git a/tests/test_micromate_opcodes.py b/tests/test_micromate_opcodes.py index d5b3f4e..b70184b 100644 --- a/tests/test_micromate_opcodes.py +++ b/tests/test_micromate_opcodes.py @@ -81,7 +81,7 @@ def test_a_frame_that_is_not_a_request_is_refused_not_sent(): def test_every_protocol_read_sub_is_in_the_read_table(): consts = {k: v for k, v in vars(mm_proto).items() if k.startswith("SUB_")} - assert len(consts) == 19 + assert len(consts) == 21 # + 0x48 and 0x94, the file read (phase 5) assert set(consts.values()) <= set(READ_SUBS) assert {0x94, 0x48} <= set(READ_SUBS) diff --git a/tests/test_micromate_schedule.py b/tests/test_micromate_schedule.py new file mode 100644 index 0000000..d216b66 --- /dev/null +++ b/tests/test_micromate_schedule.py @@ -0,0 +1,142 @@ +"""Reading a Micromate's schedule file, read-only (phase 5). + +A Micromate's scheduled start loads the setup it names, so a settings change to +another setup would be undone at the next start: SFM reads the schedule to refuse +that case. Ground truth is THOR's 2026-09-24/25 captures of UM12947 +(bridges/captures/9-24-26 - micromate2): its read of `schedule.dat` (0x94, then +0x48 pages) and its writes of a two- and a five-entry schedule (0x8E bodies). +""" +from __future__ import annotations + +import os +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from micromate.client import MicromateClient # noqa: E402 +from micromate.framing import MicromateFrameParser, unstuff # noqa: E402 +from micromate.protocol import MicromateProtocol # noqa: E402 +from micromate.schedule import ( # noqa: E402 + SCHEDULE_PATH, ScheduleEntry, parse_schedule, schedule_conflicts, +) +from test_micromate_protocol import ScriptedTransport, frame # noqa: E402 +from test_minimate_write_frames import _frames # noqa: E402 + +D = Path(__file__).resolve().parent.parent / "bridges" / "captures" / "9-24-26 - micromate2" +READ_S3 = D / "raw_s3_20260924_191835_read_scheduler.bin" +READ_BW = D / "raw_bw_20260924_191835_read_scheduler.bin" +ACTIONCHECK_BW = D / "raw_bw_20260925_005122_actioncheck.bin" +pytestmark = pytest.mark.skipif(not D.is_dir(), reason="bridges/captures is not on this machine") + + +def _payloads(path: Path) -> list: + return [unstuff(f[2:-1])[:-1] for f in _frames(path.read_bytes())] + + +def _written_schedule(path: Path) -> bytes: + """The schedule body THOR wrote: the 0x8E chunks after the 0x8D that opens + schedule.dat, joined (a long body goes in 1,024-byte pieces).""" + body, current = b"", None + for p in _payloads(path): + if p[2] == 0x8D: + current = p[16:] == SCHEDULE_PATH.encode("ascii") + elif p[2] == 0x8E and current: + body += p[16:] + return body + + +def _read_replies() -> list: + """The unit's replies to THOR's schedule read: 0x6B, then three 0xB7 pages.""" + fr = MicromateFrameParser().feed(READ_S3.read_bytes()) + i = next(k for k, f in enumerate(fr) if f.sub == 0x6B) + return fr[i:i + 4] + + +def test_the_read_capture_parses(): + body = bytes(_read_replies()[2].data)[11:] + assert len(body) == 524 + e = parse_schedule(body) + assert [(x.time, x.actions) for x in e] == [("07:30", ("start_with_setup",)), ("19:30", ("call_home",))] + assert len(e[0].setup) == 40 and e[1].setup == "" + assert e[0].day == 3 and e[0].action_bits == 2 + + +def test_the_five_entry_schedule_parses(): + e = parse_schedule(_written_schedule(ACTIONCHECK_BW)) + assert [(x.time, x.actions, x.setup) for x in e] == [ + ("07:30", ("start_with_setup",), "TEST1.mmb"), + ("08:00", ("stop",), ""), + ("08:30", ("self_check",), ""), + ("09:00", ("start_with_setup",), "test2.mmb"), + ("19:30", ("call_home",), ""), + ] + + +def test_conflicts_are_case_insensitive(): + e = parse_schedule(_written_schedule(ACTIONCHECK_BW)) + assert [x.setup for x in schedule_conflicts(e, "test1.MMB")] == ["test2.mmb"] + assert [x.setup for x in schedule_conflicts(e, " TEST2.mmb ")] == ["TEST1.mmb"] + + +def test_no_schedule_records_is_no_conflict(): + assert parse_schedule(bytes(524)) == [] + assert schedule_conflicts(parse_schedule(bytes(524)), "x.mmb") == [] + + +def test_an_unknown_action_bit_is_named_not_dropped(): + rec = bytearray(260) + rec[4], rec[5], rec[6] = 14, 3, 0x01 # 07:00, the setup-less start THOR never sends? + (e,) = parse_schedule(bytes(rec)) + assert e.actions == ("unknown(0x01)",) and e.setup == "" + assert schedule_conflicts([e], "a.mmb") == [] # no setup named: nothing to undo the change + + +def test_read_file_sends_thors_frames_and_stops_at_zeros(): + replies = [frame(f.sub, bytes(f.data), flags=f.flags, page=f.page_key) for f in _read_replies()] + t = ScriptedTransport(replies) + body = MicromateProtocol(t, recv_timeout=0.5).read_file(SCHEDULE_PATH) + thor = [f for f in _frames(READ_BW.read_bytes()) if unstuff(f[2:-1])[2] in (0x94, 0x48)] + assert t.written == thor[:4] # 0x94 + path, 0x48 (first page), 0x48, 0x48 + assert body == bytes(_read_replies()[2].data)[11:] + + +class _Proto: + def __init__(self, data: bytes): + self.data = data + + def read_active_setup_name(self): + return self.data + + def read_event_index(self): + return self.data + + def read_trigger_config(self): + return self.data + + def read_compliance_config(self): + return self.data + + +def _client(data: bytes) -> MicromateClient: + c = MicromateClient.__new__(MicromateClient) + c._proto = _Proto(data) + return c + + +def test_get_active_setup_raw_keeps_spaces(): + c = _client(bytes(11) + b" LOC 4 .mmb \x00junk") + assert c.get_active_setup_raw() == " LOC 4 .mmb " + assert c.get_active_setup() == "LOC 4 .mmb" + + +def test_block_content_getters_strip_the_prefix(): + c = _client(bytes(range(11)) + b"content") + assert c.get_prefs_content() == c.get_trigger_content() == c.get_setup_content() == b"content" + + +def test_schedule_entry_is_a_value(): + assert ScheduleEntry(0, "07:00", 3, 2, ("start_with_setup",), "a") == \ + ScheduleEntry(0, "07:00", 3, 2, ("start_with_setup",), "a")