Files
seismo-relay/scratch/mm_config_diff.py
T
serversdownandClaude Opus 5 66171ffe36 docs(series4): the 0x1A channel blocks -- graded, because one of these is strong
and two are guesses

Six 48-byte channel blocks at content[1708], stride exactly 48: Tran, Vert,
Long, Mic, LMic, SMic.  (Mic is 3 chars, so a 4+-printable scan misses it and
the stride looks like 96 across that gap.)

RECORDED IN THREE EXPLICIT GRADES, because I wrote them in one voice first and
that is the failure mode this reference already carries retractions for -- the
0x0C float from a single sample, the cost model fitted to sub-1 KB responses,
offset detector v1.  All three were an interpretation presented with the
confidence of a measurement.

MEASURED, and the one worth having: channel+24 is a float32 BE reading
3.1030800342559814 on all three geo channels.  Divided by 10,000 that is
0.00031030800342559815 -- the documented _GEO_LSB_IPS to 1.1e-8.  It implies
10.0/3.10308 = 3.222605 V full scale, which at 10,000 counts/V gives 32226.05
counts, the documented figure exactly.

That is an INDEPENDENT confirmation of a number that until now rested purely on
statistical inference: _GEO_LSB_IPS was pinned by intersecting 991,415 rounding
constraints from Thor's own CSV exports.  The unit reports it directly.  Two
unrelated derivations agreeing to eight digits.  It is also almost exactly half
Series III's 6.206053 (ratio 1.99997, the residual being S3's rounded display
value).

Also measured: the units strings ("in."/"/s.", "psi"/"(L)", "dB"/"(A)") are
literal ASCII, and Tran/Vert/Long are byte-identical EXCEPT +47, which reads
0x01 on Tran and Vert and 0x00 on Long.

INFERRED (one setup, one unit): that +24 is the calibration constant rather than
another field holding the same number -- the arithmetic proves the number, not
the field's purpose; and that +47 is an enable or trigger-source flag.

GUESSED, explicitly flagged not to build on: +4 as a uint32 "channel type", from
six correlated observations in a single setup; and +8:24 as eight uint16 BE
values, where the split itself is an assumption.

TOOLING FIX in the same commit, from a real miss: the volatile baseline ran four
reads over eight seconds, so it never crossed a minute boundary and never saw
the minutes byte.  Five "changes" then came in a row that were just the clock.
Hours and the date would have slipped through identically.  An empirical noise
floor only catches what moves WHILE sampling, so 0x1C's known clock span
(content[2:10]) is now seeded regardless, and the report says which bytes were
observed versus seeded.  Memory-free is deliberately left unmasked -- it moves
only when the unit records, which is worth being told about.

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

347 lines
14 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"
# 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
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) -> 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 `watch-NNN`, so the
sequence can be re-diffed offline afterwards without the unit.
"""
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("timestamped below and saved as watch-NNN.\n")
prev = read_all(mm)
save(serial, "watch-000", prev)
print(f"[{time.strftime('%H:%M:%S')}] baseline captured (watch-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"watch-{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}")
print(flush=True)
prev = cur
except KeyboardInterrupt:
print("\nstopped.")
print(f"{n} change(s) recorded; snapshots watch-000..watch-{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")
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)
elif a.cmd == "diff":
cmd_diff(serial, a.a, a.b)
finally:
mm.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())