Files
seismo-relay/scratch/mm_config_diff.py
T
serversdownandClaude Opus 5 711277131a feat(micromate): a config diff harness -- and the blocks turn out to be bit-stable
The Series III config map was built by changing one setting and seeing which
bytes moved.  Whether that method transfers to Series IV depended on an
unmeasured question: how much of a config block moves ON ITS OWN.  If a block
carries a clock or a counter, every diff arrives polluted and there is no way to
tell the real answer from the noise in a single pair.

MEASURED ON UM20147 (11.0BD), FOUR READS BACK TO BACK, NOTHING TOUCHED:

  0x1A compliance    2103 B    0 bytes moved
  0x2C call home      137 B    0
  0x2E trigger         39 B    0
  0x08 event index    101 B    0
  0x01 device info    163 B    0
  0x1C monitor status  59 B    2  (and those two are explained below)

Every config block held every byte still, so the method transfers directly and
needs no noise floor subtracted.  That was the open question.

scratch/mm_config_diff.py drives it: `volatile` establishes the floor, `snap`
saves a labelled read of all five blocks, `diff` reports changed runs with each
plausible field interpretation (u8/u16be/u32be/f32be) and reports any volatile
bytes separately rather than silently hiding them.

CORRECTION TO content[6] OF 0x1C, long recorded only as "NOT the hour": it is a
sub-second tick, ~4020 counts/second in steps of exactly 4, wrapping at 256 --
about a 64 ms period, consistent with the low 6 bits of a millisecond counter.
Consequence worth knowing: a 0x1C block is never byte-identical to itself, so
any "has the status block changed?" check answers yes ~15 times a second.
Compare named fields, never whole blocks.

I nearly recorded that byte wrong, and the trap is cheap enough to document:
sampled once per second it reads as a smooth monotonic counter at ~16/s with a
16-second wrap.  Twelve consecutive samples supported it.  It is aliasing -- a
64 ms counter read once a second is noise that happens to look tidy.  Measure a
counter back to back before trusting any rate from spaced samples.

Also: the settings do not have to be changed from THOR.  The unit's own keypad
works, which needs no Windows VM and does not contend for the modem's single
TCP session.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ru8Lg9HkkYvX9VWWo65SmL
2026-10-15 12:28:40 -04:00

255 lines
9.9 KiB
Python

#!/usr/bin/env python3
"""mm_config_diff.py — snapshot a Micromate's config blocks and diff them.
**Read-only.** Sends only the five config reads plus POLL/SERIAL. It never
writes, never erases, never starts or stops monitoring.
Why it exists
-------------
`docs/micromate_protocol_reference.md` has about a dozen fields read out of
`SUB 0x1A` (2,103 bytes) and *nothing* out of `0x2C`, `0x2E`, `0x08` or `0x01`.
They are fetched and undecoded. The method that mapped the Series III config
was a diff loop: change exactly one setting, re-read, see which bytes moved.
This is that loop for Series IV.
The one thing that loop needs first
-----------------------------------
**Which bytes move on their own.** A config block read twice, thirty seconds
apart, with nothing touched, is not byte-identical — it carries a clock, a free
-memory figure and at least one counter. Diff two snapshots taken either side
of a setting change and those bytes show up alongside the real answer, and
there is no way to tell which is which from a single pair.
So `volatile` runs first: N reads back to back, nothing changed, and every byte
that differs is recorded as noise. `diff` then reports the two sets
separately. Without that baseline a diff is suggestive; with it, it is
evidence.
Usage
-----
# establish the noise floor FIRST -- nothing touched between reads
python3 scratch/mm_config_diff.py /dev/ttyACM0 volatile -n 4
# baseline, then change ONE setting on the unit's keypad, then:
python3 scratch/mm_config_diff.py /dev/ttyACM0 snap before
python3 scratch/mm_config_diff.py /dev/ttyACM0 snap after-rectime-4s
python3 scratch/mm_config_diff.py /dev/ttyACM0 diff before after-rectime-4s
Snapshots live in `scratch/mm_config_snaps/<serial>/<label>/`, which is
gitignored like the other capture artefacts.
"""
from __future__ import annotations
import argparse
import json
import struct
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from bridges.mm_client_check import StdlibSerial # noqa: E402
from micromate.client import MicromateClient # noqa: E402
from minimateplus.transport import TcpTransport # noqa: E402
SNAP_ROOT = Path(__file__).resolve().parent / "mm_config_snaps"
# Block name -> the protocol method that reads it. 0x1C is included on purpose:
# it is the one block whose volatility is already known (it carries the clock),
# so it doubles as a positive control that the volatile pass is working.
BLOCKS = {
"1A_compliance": "read_compliance_config",
"2C_call_home": "read_call_home_config",
"2E_trigger": "read_trigger_config",
"08_event_index": "read_event_index",
"01_device_info": "read_device_info",
"1C_monitor_status": "read_monitor_status",
}
def _open(target: str, timeout: float):
if ":" in target and not target.startswith("/"):
host, _, port = target.rpartition(":")
return TcpTransport(host, int(port))
return StdlibSerial(target, baud=115200)
def read_all(mm: MicromateClient) -> dict[str, bytes]:
out = {}
for name, meth in BLOCKS.items():
try:
out[name] = bytes(getattr(mm._proto, meth)())
except Exception as e: # noqa: BLE001
print(f" {name}: FAILED {type(e).__name__}: {e}")
return out
def save(serial: str, label: str, blocks: dict[str, bytes]) -> Path:
d = SNAP_ROOT / serial / label
d.mkdir(parents=True, exist_ok=True)
for name, raw in blocks.items():
(d / f"{name}.bin").write_bytes(raw)
(d / "meta.json").write_text(json.dumps({
"serial": serial,
"label": label,
"taken": time.strftime("%Y-%m-%dT%H:%M:%S"),
"sizes": {k: len(v) for k, v in blocks.items()},
}, indent=2))
return d
def load(serial: str, label: str) -> dict[str, bytes]:
d = SNAP_ROOT / serial / label
if not d.is_dir():
sys.exit(f"no snapshot '{label}' for {serial} (looked in {d})")
return {p.stem: p.read_bytes() for p in sorted(d.glob("*.bin"))}
def _interps(a: bytes, b: bytes, off: int, run: int) -> list[str]:
"""How a changed run reads under each plausible field type."""
out = [f"u8 {a[off]:3d} -> {b[off]:3d}"]
if run <= 2 and off + 2 <= len(a):
x, y = struct.unpack_from(">H", a, off)[0], struct.unpack_from(">H", b, off)[0]
out.append(f"u16be {x} -> {y}")
if run <= 4 and off + 4 <= len(a):
x, y = struct.unpack_from(">I", a, off)[0], struct.unpack_from(">I", b, off)[0]
out.append(f"u32be {x} -> {y}")
fx, fy = struct.unpack_from(">f", a, off)[0], struct.unpack_from(">f", b, off)[0]
if all(abs(v) < 1e9 and (v == 0 or abs(v) > 1e-6) for v in (fx, fy)):
out.append(f"f32be {fx:g} -> {fy:g}")
return out
def _runs(a: bytes, b: bytes, ignore: set[int]) -> list[tuple[int, int]]:
"""Contiguous runs of differing offsets, skipping known-volatile ones."""
diff = [i for i in range(min(len(a), len(b)))
if a[i] != b[i] and i not in ignore]
runs, start = [], None
for i, off in enumerate(diff):
if start is None:
start = off
if i + 1 == len(diff) or diff[i + 1] != off + 1:
runs.append((start, off - start + 1))
start = None
return runs
def cmd_volatile(mm: MicromateClient, serial: str, n: int) -> None:
print(f"\n{n} reads back to back, nothing touched between them.")
print("Every byte that moves here is noise and must be excluded from a diff.\n")
snaps = []
for i in range(n):
print(f" read {i + 1}/{n} ...", end="", flush=True)
snaps.append(read_all(mm))
print(" ok")
if i + 1 < n:
time.sleep(2.0)
volatile: dict[str, list[int]] = {}
for name in snaps[0]:
moved = set()
for later in snaps[1:]:
if name not in later:
continue
a, b = snaps[0][name], later[name]
if len(a) != len(b):
print(f" {name}: LENGTH CHANGED {len(a)} -> {len(b)} -- that is itself a finding")
moved |= {i for i in range(min(len(a), len(b))) if a[i] != b[i]}
volatile[name] = sorted(moved)
print()
for name, offs in volatile.items():
size = len(snaps[0][name])
if not offs:
print(f" {name:20s} {size:5d} B STABLE -- every byte held still")
else:
pct = 100.0 * len(offs) / size
print(f" {name:20s} {size:5d} B {len(offs):4d} volatile ({pct:.1f}%) {offs[:16]}"
+ (" ..." if len(offs) > 16 else ""))
out = SNAP_ROOT / serial / "volatile.json"
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(volatile, indent=2))
print(f"\nwrote {out}")
print("`diff` reads this automatically and reports noise separately.")
def cmd_diff(serial: str, a_label: str, b_label: str) -> None:
A, B = load(serial, a_label), load(serial, b_label)
vpath = SNAP_ROOT / serial / "volatile.json"
vol = json.loads(vpath.read_text()) if vpath.is_file() else {}
if not vol:
print("⚠ no volatile.json -- run `volatile` first, or every clock tick")
print(" below will look like a config field.\n")
for name in sorted(set(A) & set(B)):
a, b = A[name], B[name]
ignore = set(vol.get(name, []))
if len(a) != len(b):
print(f"\n{name}: LENGTH {len(a)} -> {len(b)} (a length change is a finding)")
runs = _runs(a, b, ignore)
noise = sum(1 for i in range(min(len(a), len(b)))
if a[i] != b[i] and i in ignore)
if not runs:
tail = f" ({noise} volatile bytes ignored)" if noise else ""
print(f"\n{name:20s} no non-volatile change{tail}")
continue
print(f"\n{name} — {len(runs)} changed run(s)"
+ (f", {noise} volatile bytes ignored" if noise else ""))
for off, run in runs:
print(f" @{off:5d} (0x{off:04x}) {run} B "
f"{a[off:off + run].hex()} -> {b[off:off + run].hex()}")
for line in _interps(a, b, off, run):
print(f" {line}")
def main() -> int:
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("target", help="/dev/ttyACM0 or host:port")
p.add_argument("--timeout", type=float, default=10.0)
sub = p.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("snap", help="read all blocks and save under a label")
s.add_argument("label")
v = sub.add_parser("volatile", help="find bytes that move with nothing changed")
v.add_argument("-n", type=int, default=4)
d = sub.add_parser("diff", help="diff two saved snapshots")
d.add_argument("a")
d.add_argument("b")
d.add_argument("--serial", help="override (default: read from the unit)")
a = p.parse_args()
# `diff` is pure offline work on saved files -- do not touch the unit for it.
if a.cmd == "diff" and a.serial:
cmd_diff(a.serial, a.a, a.b)
return 0
transport = _open(a.target, a.timeout)
mm = MicromateClient(transport, recv_timeout=a.timeout)
mm.open() # opens the port; connect() only handshakes
info = mm.connect()
serial = info.serial or "unknown"
print(f"{serial} {info.model} fw={info.firmware_line} "
f"setup={info.active_setup} monitoring={info.monitoring}")
try:
if a.cmd == "snap":
blocks = read_all(mm)
d = save(serial, a.label, blocks)
print(f"\nsaved {len(blocks)} blocks -> {d}")
for k, v2 in sorted(blocks.items()):
print(f" {k:20s} {len(v2):5d} B")
elif a.cmd == "volatile":
cmd_volatile(mm, serial, a.n)
elif a.cmd == "diff":
cmd_diff(serial, a.a, a.b)
finally:
mm.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())