#!/usr/bin/env python3 """Cross-check .MLG records against Blastware event files, in both directions. check_mlg_vs_events.py Every .MLG record with the Event Recorded bit (not a "monitoring started" one) should have an event file whose footer has the same stop time, flag word and trigger source; and every event file inside a unit's .MLG period (its first record's start to its last record's stop) should have such a record. The footer is read straight from each event file's last 28 bytes, independently of the event decoder, and its CRC-16/AUG-CCITT is checked on the way. Spec docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md ยง7. Read-only. """ from __future__ import annotations import collections import datetime import os import struct import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from minimateplus.crc import crc16_aug_ccitt from minimateplus.mlg_file import MlgFormatError, read_mlg from sfm.waveform_store import _serial_number_from_bw_filename _FOOTER_HEAD = b"\x00\x1a\x0e\x08" def _ts_be(raw: bytes): try: return datetime.datetime(struct.unpack(">H", raw[2:4])[0], raw[1], raw[0], raw[5], raw[6], raw[7]) except ValueError: return None def _serial_number(serial: str): digits = "".join(ch for ch in serial if ch.isdigit()) return int(digits) if digits else None def mlg_side(mlg_dir: Path): """{unit number: (serial, [(stop, flags, source)], first start, last stop)}""" units = {} for path in sorted(p for p in mlg_dir.rglob("*") if p.is_file() and p.suffix.upper() == ".MLG"): try: mlg = read_mlg(path) except MlgFormatError as exc: print(f" skipped {path}: {exc}") continue if not mlg.serial or not mlg.records: continue n = _serial_number(mlg.serial) serial, keys, lo, hi = units.get(n, (mlg.serial, [], None, None)) for r in mlg.records: lo = min(lo, r.start) if lo else r.start if r.stop: hi = max(hi, r.stop) if hi else r.stop if not r.is_start and r.flags & 0x0001: keys.append((r.stop, r.flags, r.trigger_source)) units[n] = (serial, keys, lo, hi) return units def event_side(event_dir: Path, wanted: set): """{unit number: [(stop, flags, source, file name)]}, plus footer CRC failures.""" files = collections.defaultdict(list) crc_bad = 0 for entry in os.scandir(event_dir): if not entry.is_file(): continue n = _serial_number_from_bw_filename(entry.name) if n not in wanted: continue with open(entry.path, "rb") as f: f.seek(0, 2) if f.tell() < 28: continue f.seek(-28, 2) tail = f.read(28) if not tail.startswith(_FOOTER_HEAD): continue if crc16_aug_ccitt(tail[0:24]) != struct.unpack(">H", tail[26:28])[0]: crc_bad += 1 flags, source = struct.unpack(">HH", tail[20:24]) files[n].append((_ts_be(tail[12:20]), flags, source, entry.name)) return files, crc_bad def main(argv=None) -> int: argv = argv if argv is not None else sys.argv[1:] if len(argv) != 2: print(__doc__) return 2 units = mlg_side(Path(argv[0])) files, crc_bad = event_side(Path(argv[1]), set(units)) checked = sum(len(v) for v in files.values()) print(f"event-file footers checked (units with .MLGs only): {checked}, failing their CRC: {crc_bad}") for n, (serial, keys, lo, hi) in sorted(units.items(), key=lambda kv: kv[1][0]): in_period = [f for f in files.get(n, []) if f[0] and lo <= f[0] <= hi] file_keys = {f[:3] for f in in_period} rec_keys = set(keys) matched = [k for k in keys if k in file_keys] record_only = [k for k in keys if k not in file_keys] file_only = [f for f in in_period if f[:3] not in rec_keys] print(f"\n{serial}: .MLG period {lo} -> {hi}") print(f" matched {len(matched)}, record-only {len(record_only)}, file-only {len(file_only)}") for k in record_only[:5]: print(f" record-only: stop {k[0]} flags {k[1]:#06x} source {k[2]:#06x}") if record_only: print(f" record-only stops run {min(k[0] for k in record_only)} -> {max(k[0] for k in record_only)}") for f in file_only[:5]: print(f" file-only: {f[3]} stop {f[0]} flags {f[1]:#06x} source {f[2]:#06x}") return 0 if __name__ == "__main__": raise SystemExit(main())