fix(micromate): config watcher no longer overwrites the previous session -- and checks the 0x1A CRC

`watch` saved every session as `watch-000..NNN`, so each run silently
overwrote the last.  Harmless while those snapshots were clock ticks; data
loss once they were findings.  Labels now default to `watch-MMDD-HHMM-NNN`
(`--prefix` overrides).

Each 0x1A change also prints its trailer check: CRC-16/AUG-CCITT over
content[0:2088], stored BE at content[2090:2092].  Measured on 47/47
snapshots of UM20147 plus UM12947's 9-24 capture; a mismatch means a short
or corrupt read, or a layout this does not assume.

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-10-17 02:22:00 -04:00
1 parent ba021df6b2
commit 75cbe23214
1 file changed
+41 -8
+41 -8
View File
@@ -138,6 +138,30 @@ def _interps(a: bytes, b: bytes, off: int, run: int) -> list[str]:
return out return out
def crc16_aug_ccitt(data: bytes) -> int:
"""CRC-16/AUG-CCITT: poly 0x1021, init 0x1D0F, no reflection, xorout 0."""
c = 0x1D0F
for x in data:
c ^= x << 8
for _ in range(8):
c = ((c << 1) ^ 0x1021) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
def crc_status_1a(raw: bytes) -> str:
"""Check 0x1A's trailer: CRC over content[0:2088], stored BE at [2090:2092].
Found 2026-10-17 from one keypad diff and confirmed on 23 snapshots plus
UM12947's 9-24 capture. A mismatch means a short or corrupt read -- or
that the layout is not what this assumes, which is worth knowing too.
"""
c = raw[CONTENT:]
if len(c) < 2092:
return f"CRC n/a (content {len(c)} B < 2092)"
want, got = crc16_aug_ccitt(c[:2088]), int.from_bytes(c[2090:2092], "big")
return f"CRC ok ({got:04x})" if want == got else f"CRC MISMATCH computed {want:04x}, stored {got:04x}"
def _runs(a: bytes, b: bytes, ignore: set[int]) -> list[tuple[int, int]]: def _runs(a: bytes, b: bytes, ignore: set[int]) -> list[tuple[int, int]]:
"""Contiguous runs of differing offsets, skipping known-volatile ones.""" """Contiguous runs of differing offsets, skipping known-volatile ones."""
diff = [i for i in range(min(len(a), len(b))) diff = [i for i in range(min(len(a), len(b)))
@@ -226,15 +250,21 @@ def cmd_diff(serial: str, a_label: str, b_label: str) -> None:
def cmd_watch(mm: MicromateClient, serial: str, interval: float, def cmd_watch(mm: MicromateClient, serial: str, interval: float,
duration: float) -> None: duration: float, prefix: str | None = None) -> None:
"""Poll the config blocks and report each change as it lands. """Poll the config blocks and report each change as it lands.
A round trip per setting means walking to the unit and back for every A round trip per setting means walking to the unit and back for every
field. This instead lets one person stand at the keypad changing settings field. This instead lets one person stand at the keypad changing settings
one at a time while every change is timestamped here, so a whole session is one at a time while every change is timestamped here, so a whole session is
one pass. Each distinct state is also saved as `watch-NNN`, so the one pass. Each distinct state is also saved as `<prefix>-NNN`, so the
sequence can be re-diffed offline afterwards without the unit. sequence can be re-diffed offline afterwards without the unit.
The prefix defaults to `watch-MMDD-HHMM`, i.e. one per session. It used to
be a fixed `watch-`, so every run silently overwrote the previous run's
snapshots -- harmless while they were clock ticks, data loss once they
were findings.
""" """
prefix = prefix or time.strftime("watch-%m%d-%H%M")
vpath = SNAP_ROOT / serial / "volatile.json" vpath = SNAP_ROOT / serial / "volatile.json"
vol = json.loads(vpath.read_text()) if vpath.is_file() else {} vol = json.loads(vpath.read_text()) if vpath.is_file() else {}
if not vol: if not vol:
@@ -243,11 +273,11 @@ def cmd_watch(mm: MicromateClient, serial: str, interval: float,
print(f"watching every {interval:g}s" print(f"watching every {interval:g}s"
+ (f" for {duration:g}s" if duration else " until Ctrl-C")) + (f" for {duration:g}s" if duration else " until Ctrl-C"))
print("change ONE setting at a time on the unit's keypad; each change is") print("change ONE setting at a time on the unit's keypad; each change is")
print("timestamped below and saved as watch-NNN.\n") print(f"timestamped below and saved as {prefix}-NNN.\n")
prev = read_all(mm) prev = read_all(mm)
save(serial, "watch-000", prev) save(serial, f"{prefix}-000", prev)
print(f"[{time.strftime('%H:%M:%S')}] baseline captured (watch-000)") print(f"[{time.strftime('%H:%M:%S')}] baseline captured ({prefix}-000)")
for k, v in sorted(prev.items()): for k, v in sorted(prev.items()):
print(f" {k:20s} {len(v):5d} B") print(f" {k:20s} {len(v):5d} B")
print() print()
@@ -270,7 +300,7 @@ def cmd_watch(mm: MicromateClient, serial: str, interval: float,
if not hits: if not hits:
continue continue
n += 1 n += 1
label = f"watch-{n:03d}" label = f"{prefix}-{n:03d}"
save(serial, label, cur) save(serial, label, cur)
print(f"[{time.strftime('%H:%M:%S')}] CHANGE #{n} ({label})") print(f"[{time.strftime('%H:%M:%S')}] CHANGE #{n} ({label})")
for name, runs, la, lb in hits: for name, runs, la, lb in hits:
@@ -284,11 +314,13 @@ def cmd_watch(mm: MicromateClient, serial: str, interval: float,
f"{a[off:off + run].hex()} -> {b[off:off + run].hex()}") f"{a[off:off + run].hex()} -> {b[off:off + run].hex()}")
for line in _interps(a, b, off, run): for line in _interps(a, b, off, run):
print(f" {line}") print(f" {line}")
if name == "1A_compliance":
print(f" {crc_status_1a(cur[name])}")
print(flush=True) print(flush=True)
prev = cur prev = cur
except KeyboardInterrupt: except KeyboardInterrupt:
print("\nstopped.") print("\nstopped.")
print(f"{n} change(s) recorded; snapshots watch-000..watch-{n:03d} under") print(f"{n} change(s) recorded; snapshots {prefix}-000..{prefix}-{n:03d} under")
print(f" {SNAP_ROOT / serial}") print(f" {SNAP_ROOT / serial}")
@@ -305,6 +337,7 @@ def main() -> int:
w = sub.add_parser("watch", help="poll and report each change as it lands") w = sub.add_parser("watch", help="poll and report each change as it lands")
w.add_argument("--interval", type=float, default=2.0) w.add_argument("--interval", type=float, default=2.0)
w.add_argument("--duration", type=float, default=0.0, help="0 = until Ctrl-C") w.add_argument("--duration", type=float, default=0.0, help="0 = until Ctrl-C")
w.add_argument("--prefix", help="snapshot label prefix (default: watch-MMDD-HHMM)")
d = sub.add_parser("diff", help="diff two saved snapshots") d = sub.add_parser("diff", help="diff two saved snapshots")
d.add_argument("a") d.add_argument("a")
d.add_argument("b") d.add_argument("b")
@@ -334,7 +367,7 @@ def main() -> int:
elif a.cmd == "volatile": elif a.cmd == "volatile":
cmd_volatile(mm, serial, a.n) cmd_volatile(mm, serial, a.n)
elif a.cmd == "watch": elif a.cmd == "watch":
cmd_watch(mm, serial, a.interval, a.duration) cmd_watch(mm, serial, a.interval, a.duration, a.prefix)
elif a.cmd == "diff": elif a.cmd == "diff":
cmd_diff(serial, a.a, a.b) cmd_diff(serial, a.a, a.b)
finally: finally: