"""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)]