From 49f8f49ac1cccf886d4eb942650fbb6a48a9a3f3 Mon Sep 17 00:00:00 2001 From: serversdown Date: Thu, 22 Oct 2026 17:24:16 -0400 Subject: [PATCH] feat(micromate): write plans for start/stop, call-home and setup push -- THOR's frames byte for byte Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- micromate/writes.py | 139 ++++++++++++++++++++++++++++ tests/test_micromate_writes.py | 162 +++++++++++++++++++++++++++++++++ 2 files changed, 301 insertions(+) create mode 100644 micromate/writes.py create mode 100644 tests/test_micromate_writes.py diff --git a/micromate/writes.py b/micromate/writes.py new file mode 100644 index 0000000..28d7149 --- /dev/null +++ b/micromate/writes.py @@ -0,0 +1,139 @@ +"""Write plans for a Micromate: the exact frames a write would send, in order. + +A plan is what a dry run returns. Building one sends nothing; transmitting it +also needs a protocol constructed with those SUBs in `allowed_writes`, which no +code does yet (see `micromate.opcodes`). + +Every input is the unit's OWN read of the block being written (content, i.e. +response data[11:]), and every plan sends back exactly what was read except +the one thing the operation changes. THOR works the same way, and the +reproduction tests hold the plans to THOR's frames byte for byte. + +Offsets are THOR's observed constants. 🔶 Each was seen at one block size +only, so a plan refuses a block of any other size rather than guess. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import FrozenSet, List, Tuple + +from .framing import build_request +from .opcodes import CROSS_SERIES_COLLISIONS, WRITE_SUBS, OpcodeRefused +from .setup_block import crc_ok + +_CONFIRM = 0xFFFF + +# block content sizes THOR's offsets were observed at (all on UM12947 / 11.0CB) +_PREFS_LEN, _TRIGGER_LEN, _SETUP_LEN, _CALL_HOME_LEN = 90, 28, 2092, 126 +_NAME_FIELD = 256 + + +@dataclass(frozen=True) +class WriteStep: + sub: int + offset: int + data: bytes = b"" + params: bytes = field(default=bytes(10)) + what: str = "" + + @property + def ack_sub(self) -> int: + return 0xFF - self.sub + + @property + def frame(self) -> bytes: + return build_request(self.sub, self.offset, self.params, self.data) + + def describe(self) -> dict: + return {"sub": f"0x{self.sub:02X}", "what": self.what, + "offset": f"0x{self.offset:04X}", "data_len": len(self.data), + "expect_ack": f"0x{self.ack_sub:02X}", "frame": self.frame.hex()} + + +@dataclass(frozen=True) +class WritePlan: + action: str + steps: Tuple[WriteStep, ...] + + def __post_init__(self) -> None: + for s in self.steps: + if s.sub in CROSS_SERIES_COLLISIONS: + raise OpcodeRefused( + f"a plan cannot hold SUB 0x{s.sub:02X}: {CROSS_SERIES_COLLISIONS[s.sub]}") + if s.sub not in WRITE_SUBS: + raise ValueError(f"SUB 0x{s.sub:02X} is not a write opcode") + + @property + def subs(self) -> FrozenSet[int]: + return frozenset(s.sub for s in self.steps) + + def frames(self) -> List[bytes]: + return [s.frame for s in self.steps] + + def describe(self) -> dict: + return {"action": self.action, "sends_nothing": True, + "steps": [s.describe() for s in self.steps]} + + +def plan_start_monitoring() -> WritePlan: + return WritePlan("start monitoring", (WriteStep(0x96, _CONFIRM, what="start monitoring"),)) + + +def plan_stop_monitoring() -> WritePlan: + return WritePlan("stop monitoring", (WriteStep(0x97, _CONFIRM, what="stop monitoring"),)) + + +def plan_call_home_enabled(call_home: bytes, enabled: bool) -> WritePlan: + """Read `0x2C`, flip bit 0 of content[5], send the rest back byte for byte. + + `[5]` reads 0x05 enabled / 0x04 disabled; bit 2 is set in both, so only + bit 0 is the enable. `[118:120]` is unit-maintained and THOR echoes it. + """ + if len(call_home) != _CALL_HOME_LEN: + raise ValueError(f"call-home content must be {_CALL_HOME_LEN} B " + f"(the size THOR's offset was seen at), got {len(call_home)}") + b5 = (call_home[5] | 0x01) if enabled else (call_home[5] & 0xFE) + data = call_home[:5] + bytes([b5]) + call_home[6:] + what = "call-home " + ("enable" if enabled else "disable") + return WritePlan(what, ( + WriteStep(0x7E, 0x007E, data, what="call-home config write"), + WriteStep(0x7F, _CONFIRM, what="call-home config confirm"), + )) + + +def _checked(block: bytes, size: int, label: str) -> bytes: + if len(block) != size: + raise ValueError(f"{label} block size {len(block)} B is not the {size} B " + "THOR's offset was observed at -- refusing to guess") + if not crc_ok(block): + raise ValueError(f"{label} block failed its checksum -- refusing to write a " + "corrupt read back to the unit") + return block + + +def plan_setup_push(prefs: bytes, trigger: bytes, setup: bytes, name: str) -> WritePlan: + """Rewrite a setup as THOR does: read 0x08, 0x2E, 0x1A, send each back. + + No field editing here (phase 5). Each block goes back with its length echo + [0:3] zeroed; the unit recomputes the CRCs, so 0x68 and 0x71 drop the CRC + slot and 0x82 sends it zeroed -- exactly THOR's frames. + """ + _checked(prefs, _PREFS_LEN, "preferences (0x08)") + _checked(trigger, _TRIGGER_LEN, "trigger (0x2E)") + _checked(setup, _SETUP_LEN, "setup (0x1A)") + try: + raw = name.encode("ascii") + except UnicodeEncodeError: + raise ValueError(f"setup name must be ASCII: {name!r}") from None + if not raw or b"\x00" in raw or len(raw) >= _NAME_FIELD: + raise ValueError(f"setup name must be 1-{_NAME_FIELD - 1} ASCII bytes " + f"with no NUL: {name!r}") + return WritePlan(f"setup push: {name}", ( + WriteStep(0xDA, 0x0100, raw.ljust(_NAME_FIELD, b"\x00"), what="setup file name"), + WriteStep(0x68, 0x005A, bytes(3) + prefs[3:88], what="preferences block"), + WriteStep(0x73, _CONFIRM, what="preferences confirm"), + WriteStep(0x82, 0x001C, bytes(3) + trigger[3:26] + bytes(2), what="trigger block"), + WriteStep(0x83, _CONFIRM, what="trigger confirm"), + WriteStep(0x71, 0x082C, bytes(3) + setup[3:2090], what="setup block"), + WriteStep(0x72, _CONFIRM, what="setup confirm"), + )) diff --git a/tests/test_micromate_writes.py b/tests/test_micromate_writes.py new file mode 100644 index 0000000..3e3fad7 --- /dev/null +++ b/tests/test_micromate_writes.py @@ -0,0 +1,162 @@ +"""Write plans: built from the unit's own reads, equal to THOR's frames byte for byte.""" +from __future__ import annotations + +import json +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.opcodes import OpcodeRefused # noqa: E402 +from micromate.writes import ( # noqa: E402 + WritePlan, WriteStep, plan_call_home_enabled, plan_setup_push, + plan_start_monitoring, plan_stop_monitoring, +) + +FIX = Path(__file__).parent / "fixtures" / "micromate-writes" +PUSHES = ["setup-push-new-test1", "setup-push-overwrite-test1", "setup-push-read-scheduler", + "setup-push-pull-schedule", "setup-push-multiday"] +NO_EDIT_PUSHES = ["setup-push-read-scheduler", "setup-push-pull-schedule", "setup-push-multiday"] + + +def _session(slug): + return json.loads((FIX / f"{slug}.json").read_text())["exchanges"] + + +def _content(ex): + return bytes.fromhex(ex["response_data"])[11:] + + +def _first_push(slug): + """The reads (by SUB) and THOR's writes (by SUB) of the session's first push.""" + ex = _session(slug) + start = next(i for i, e in enumerate(ex) if e["sub"] == 0xDA) + reads = {} + for e in ex[:start]: + reads[e["sub"]] = _content(e) # the LAST read of each SUB before the push + writes = {} + for e in ex[start:]: + if e["sub"] in writes: + break + writes[e["sub"]] = bytes.fromhex(e["request"]) + if e["sub"] == 0x72: + break + return reads, writes + + +def _name_from_active(content): + # Mirrors micromate.client._cstring(content): name at content[0], NUL-terminated, stripped. + return content.split(b"\x00")[0].decode("ascii", "replace").strip() + + +# ── start / stop ────────────────────────────────────────────────────────────── + +def test_start_and_stop_equal_thors_frames(): + thor = {e["sub"]: bytes.fromhex(e["request"]) for e in _session("monitor-start-stop") + if e["sub"] in (0x96, 0x97)} + assert plan_start_monitoring().frames() == [thor[0x96]] + assert plan_stop_monitoring().frames() == [thor[0x97]] + assert thor[0x96].hex() == "41021010009600ffff00000000000000000000a403" + + +# ── call-home ───────────────────────────────────────────────────────────────── + +def test_call_home_enable_then_disable_equal_thors_frames(): + ex = _session("call-home-enable-disable") + pairs, last_read = [], None + for e in ex: + if e["sub"] == 0x2C: + last_read = _content(e) + elif e["sub"] == 0x7E: + pairs.append((last_read, bytes.fromhex(e["request"]))) + confirms = [bytes.fromhex(e["request"]) for e in ex if e["sub"] == 0x7F] + assert len(pairs) == 2 and len(confirms) == 2 + (r1, w1), (r2, w2) = pairs + on, off = plan_call_home_enabled(r1, True), plan_call_home_enabled(r2, False) + assert on.frames() == [w1, confirms[0]] + assert off.frames() == [w2, confirms[1]] + + +def test_call_home_flips_exactly_one_bit_and_echoes_everything_else(): + r1 = next(_content(e) for e in _session("call-home-enable-disable") if e["sub"] == 0x2C) + for enabled in (True, False): + data = plan_call_home_enabled(r1, enabled).steps[0].data + diff = [i for i in range(len(r1)) if data[i] != r1[i]] + assert set(diff) <= {5} + assert data[5] & 0x01 == (1 if enabled else 0) + assert data[5] & 0xFE == r1[5] & 0xFE + assert data[118:120] == r1[118:120] + + +def test_call_home_refuses_an_unobserved_size(): + with pytest.raises(ValueError, match="126"): + plan_call_home_enabled(bytes(125), True) + + +# ── setup push ──────────────────────────────────────────────────────────────── + +@pytest.mark.parametrize("slug", PUSHES) +def test_setup_push_name_prefs_trigger_and_confirms_equal_thors_frames(slug): + reads, thor = _first_push(slug) + name = ("TEST1.mmb" if slug == "setup-push-new-test1" + else _name_from_active(reads[0x41])) + plan = plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], name) + ours = {s.sub: s.frame for s in plan.steps} + for sub in (0xDA, 0x68, 0x73, 0x82, 0x83, 0x72): + assert ours[sub] == thor[sub], f"{slug}: SUB 0x{sub:02X}" + assert [s.sub for s in plan.steps] == [0xDA, 0x68, 0x73, 0x82, 0x83, 0x71, 0x72] + + +@pytest.mark.parametrize("slug", NO_EDIT_PUSHES) +def test_a_no_edit_push_reproduces_thors_setup_block_frame(slug): + reads, thor = _first_push(slug) + plan = plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], _name_from_active(reads[0x41])) + assert next(s.frame for s in plan.steps if s.sub == 0x71) == thor[0x71] + + +def test_setup_push_refuses_a_read_that_fails_its_checksum(): + reads, _ = _first_push("setup-push-multiday") + bad = bytearray(reads[0x1A]) + bad[100] ^= 0xFF + with pytest.raises(ValueError, match="checksum"): + plan_setup_push(reads[0x08], reads[0x2E], bytes(bad), "x.mmb") + + +@pytest.mark.parametrize("which", ["prefs", "trigger", "setup"]) +def test_setup_push_refuses_an_unobserved_block_size(which): + reads, _ = _first_push("setup-push-multiday") + args = {"prefs": reads[0x08], "trigger": reads[0x2E], "setup": reads[0x1A]} + args[which] = args[which] + b"\x00\x00" + with pytest.raises(ValueError, match="size"): + plan_setup_push(args["prefs"], args["trigger"], args["setup"], "x.mmb") + + +@pytest.mark.parametrize("name", ["", "a\x00b", "é.mmb", "x" * 256]) +def test_setup_push_refuses_a_bad_name(name): + reads, _ = _first_push("setup-push-multiday") + with pytest.raises(ValueError): + plan_setup_push(reads[0x08], reads[0x2E], reads[0x1A], name) + + +# ── the plan object ─────────────────────────────────────────────────────────── + +def test_a_plan_cannot_hold_a_collision_opcode(): + with pytest.raises(OpcodeRefused): + WritePlan("end call-home", (WriteStep(0xA2, 0xFFFF),)) + + +def test_a_plan_cannot_hold_a_read(): + with pytest.raises(ValueError): + WritePlan("poll", (WriteStep(0x5B, 0x0030),)) + + +def test_describe_is_the_dry_run_shape(): + d = plan_stop_monitoring().describe() + assert d["action"] == "stop monitoring" and d["sends_nothing"] is True + step = d["steps"][0] + assert step == {"sub": "0x97", "what": "stop monitoring", "offset": "0xFFFF", + "data_len": 0, "expect_ack": "0x68", + "frame": "41021010009700ffff00000000000000000000a503"}