Files
seismo-relay/scratch/mm_config_diff.py
T
serversdownandClaude Opus 5.5 b3aff4ed66 feat(micromate): get_setup() -- the setup block decoded, checksum-verified, and read off a real unit
MicromateClient.get_setup() reads SUB 0x1A once and returns a MicromateSetup:
record mode, sample rate, histogram interval, pre-trigger, stop mode, record
time, auto-stop, active sensors, trigger sources, the three geophone trigger
levels, mic type and (linear) mic trigger, job number, scaled distance, and
the four notes.  MEASURED FIELDS ONLY -- everything graded inferred or
unknown in the reference stays in .raw.

micromate/setup_block.py holds the decode as pure functions (no I/O), plus
crc_ok(): one checksum rule for 0x1A, 0x08 and 0x2E.  A failed checksum
raises SetupChecksumError (a ProtocolError) unless verify=False; a short
block raises either way.

Two things the decoder gets right that a naive one would not:
- the mic comes from channel block 4 (the ACTIVE mic), never blocks 5/6,
  which hold the stored settings of whichever mic is NOT fitted;
- distance and charge weight convert back with the unit's own 3.2808 and
  2.21, so 45 lb entered on the unit reads 45.0, not 44.89.

TESTS: 69 new.  15 real fixtures (2,103 B each) -- 14 UM20147 reads from the
10-17/10-19 keypad passes, chosen so every field takes at least two values,
plus UM12947's read from Thor's 9-24 capture (other firmware line).
Expected values are what the operator read off the unit's screen, never the
decoder's own output.  Fixtures force-added, per the tests/fixtures/
convention.  Full suite 541 passed; the 16 pre-existing failures
(test_bw_ascii_report.py 15, test_event_file_io.py 1) are unchanged.

VERIFIED ON HARDWARE: bridges/mm_client_check.py now prints the decoded
setup; against UM20147 every line matched the unit's screen (Brian, 10-19).

Also: the scratch harness uses the library checksum and checks all three
blocks; mm_client_check's stale labels fixed (0x06 content[4:8] is the
likely monitor-log count, not "unexplained"; 11.0BD is no longer "the first
one this code has met").

No codec, store or DB change; no backfill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-19 18:20:25 -04:00

369 lines
15 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 micromate.setup_block import crc_ok # noqa: E402
from minimateplus.transport import TcpTransport # noqa: E402
SNAP_ROOT = Path(__file__).resolve().parent / "mm_config_snaps"
# Content starts at data[11]; the reference documents fields as content[N], so
# every changed offset is reported both ways to save a subtraction per finding.
CONTENT = 11
# 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.
# Bytes that are KNOWN volatile from the field layout, seeded regardless of
# whether they happened to move during the sample window. An empirical noise
# floor only catches what moves WHILE sampling: a four-read pass over eight
# seconds sees the sub-second tick and the seconds byte and silently misses
# minutes, hours and the date, which then surface later as fake "findings".
# 0x1C content[2:10] is day/month/year/tick/hour/min/sec; content starts at 11.
# Memory-free (content[40:44]) is deliberately NOT masked -- it moves only when
# the unit actually records, which is a thing worth being told about.
KNOWN_VOLATILE = {
"1C_monitor_status": list(range(11 + 2, 11 + 10)),
}
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
# Blocks that carry the config checksum (micromate.setup_block.crc_ok): N =
# content[0:2], CRC-16/AUG-CCITT over [0:N-2] stored at [N:N+2]. 0x2C has none.
CRC_BLOCKS = {"1A_compliance", "08_event_index", "2E_trigger"}
def crc_status(raw: bytes) -> str:
"""A mismatch means a short or corrupt read -- or a block this rule misses."""
c = raw[CONTENT:]
stored = c[int.from_bytes(c[0:2], "big"):][:2].hex() if len(c) >= 2 else "--"
return f"CRC ok ({stored})" if crc_ok(c) else f"CRC MISMATCH (stored {stored})"
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 | set(KNOWN_VOLATILE.get(name, [])))
print()
for name, offs in volatile.items():
size = len(snaps[0][name])
seeded = set(KNOWN_VOLATILE.get(name, []))
observed = set(offs) - seeded
if not offs:
print(f" {name:20s} {size:5d} B STABLE -- every byte held still")
else:
note = f"{len(observed)} observed"
if seeded:
note += f" + {len(seeded)} seeded from the known clock layout"
print(f" {name:20s} {size:5d} B {len(offs):4d} volatile ({note})")
print(f" {'':20s} {offs[:20]}" + (" ..." if len(offs) > 20 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}) content[{off - CONTENT:d}] {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 cmd_watch(mm: MicromateClient, serial: str, interval: float,
duration: float, prefix: str | None = None) -> None:
"""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
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 pass. Each distinct state is also saved as `<prefix>-NNN`, so the
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"
vol = json.loads(vpath.read_text()) if vpath.is_file() else {}
if not vol:
print("⚠ no volatile.json -- run `volatile` first.\n")
print(f"watching every {interval:g}s"
+ (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(f"timestamped below and saved as {prefix}-NNN.\n")
prev = read_all(mm)
save(serial, f"{prefix}-000", prev)
print(f"[{time.strftime('%H:%M:%S')}] baseline captured ({prefix}-000)")
for k, v in sorted(prev.items()):
print(f" {k:20s} {len(v):5d} B")
print()
n, t0 = 0, time.monotonic()
try:
while not duration or time.monotonic() - t0 < duration:
time.sleep(interval)
cur = read_all(mm)
hits = []
for name in sorted(set(prev) & set(cur)):
a, b = prev[name], cur[name]
ignore = set(vol.get(name, []))
if len(a) != len(b):
hits.append((name, None, len(a), len(b)))
continue
runs = _runs(a, b, ignore)
if runs:
hits.append((name, runs, None, None))
if not hits:
continue
n += 1
label = f"{prefix}-{n:03d}"
save(serial, label, cur)
print(f"[{time.strftime('%H:%M:%S')}] CHANGE #{n} ({label})")
for name, runs, la, lb in hits:
if runs is None:
print(f" {name}: LENGTH {la} -> {lb} (a length change is a finding)")
continue
print(f" {name} — {len(runs)} run(s)")
for off, run in runs:
a, b = prev[name], cur[name]
print(f" @{off:5d} (0x{off:04x}) content[{off - CONTENT:d}] {run} B "
f"{a[off:off + run].hex()} -> {b[off:off + run].hex()}")
for line in _interps(a, b, off, run):
print(f" {line}")
if name in CRC_BLOCKS:
print(f" {crc_status(cur[name])}")
print(flush=True)
prev = cur
except KeyboardInterrupt:
print("\nstopped.")
print(f"{n} change(s) recorded; snapshots {prefix}-000..{prefix}-{n:03d} under")
print(f" {SNAP_ROOT / serial}")
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)
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("--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.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 == "watch":
cmd_watch(mm, serial, a.interval, a.duration, a.prefix)
elif a.cmd == "diff":
cmd_diff(serial, a.a, a.b)
finally:
mm.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())