"""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 is `MicromateProtocol.execute(plan)` and nothing else: the connection holds no write permission of its own (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 _CALL_HOME_OBSERVED = (0x00, 0x01, 0x04, 0x05) # content[5] values units have held # 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 = "" def __post_init__(self) -> None: # Freeze the bytes: a caller's bytearray must not change a validated step. object.__setattr__(self, "data", bytes(self.data)) object.__setattr__(self, "params", bytes(self.params)) if len(self.params) != 10: raise ValueError(f"params must be 10 bytes, got {len(self.params)}") if not 0 <= self.offset <= 0xFFFF: raise ValueError(f"offset 0x{self.offset:X} does not fit a uint16") if not 0 <= self.sub <= 0xFF: raise ValueError(f"SUB {self.sub!r} does not fit a byte") @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, ...] warnings: Tuple[str, ...] = () def __post_init__(self) -> None: # Copy: a caller's list must not be able to add a step after validation. object.__setattr__(self, "steps", tuple(self.steps)) object.__setattr__(self, "warnings", tuple(self.warnings)) for s in self.steps: if not isinstance(s, WriteStep): raise TypeError(f"a plan holds WriteStep objects, got {type(s).__name__}") 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, "warnings": list(self.warnings), "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 is_call_home_content(block: bytes) -> bool: """Whether 126 bytes are the 0x2C call-home content: its header is its own length (00 7C, N = 124 -- 00 7C DC on every read on record, UM12947 and UM20147). A bit is flipped only in a block that carries it.""" return len(block) == _CALL_HOME_LEN and int.from_bytes(block[0:2], "big") == _CALL_HOME_LEN - 2 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. Bit 0 of `[5]` is the enable. 🔶 UM12947 (THOR's unit) read 0x05 enabled / 0x04 disabled, bit 2 set in both; UM20147 reads 0x01 (measured, phase-2 dry run). So on UM20147 "off" writes 0x00 -- measured at the bench 2026-11-03 (and again 11-04): 0x01 <-> 0x00 acknowledged, read back, and matched in the unit's own menu. A value outside those four still carries a warning. `[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)}") if not is_call_home_content(call_home): raise ValueError(f"call-home content's header is {call_home[0:2].hex()}, not its own length " f"(00 {_CALL_HOME_LEN - 2:02x}) -- not the call-home block; nothing built") 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") start = call_home[5] warnings = [] if start not in _CALL_HOME_OBSERVED or b5 not in _CALL_HOME_OBSERVED: warnings.append(f"content[5] 0x{start:02X} -> 0x{b5:02X}: no unit has been seen " "holding this value (0x04/0x05 UM12947 by THOR, 0x00/0x01 UM20147 " "by SFM); it is unobserved") if b5 == start: warnings.append(f"the unit is already call-home {'enabled' if enabled else 'disabled'}" " -- this write changes nothing") return WritePlan(what, ( WriteStep(0x7E, 0x007E, data, what="call-home config write"), WriteStep(0x7F, _CONFIRM, what="call-home config confirm"), ), tuple(warnings)) 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 int.from_bytes(block[0:2], "big") != size - 2: raise ValueError(f"{label} block's own header says " f"{int.from_bytes(block[0:2], 'big')}, expected {size - 2} -- " "not the block it claims to be") 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. ⚠ `0x1A` reads the keypad's edit buffer live. A setup read taken while someone is in the unit's menu includes their unsaved edits, and pushing this plan would commit them. The name goes out exactly as given. `MicromateClient.get_active_setup()` strips whitespace, so a setup name with leading or trailing spaces would not round-trip through it; phase 5 decides whether to take the unstripped name from the 0x41 read. """ _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"), ))