Files
seismo-relay/minimateplus/mlg_file.py
T
serversdownandClaude Opus 5.5 3cd95db405 feat(mlg): read Blastware .MLG files, every record's checksum verified
minimateplus/mlg_file.py parses the measured format: an 18-byte prefix,
then length-led 292-byte records, each with a CRC-16/AUG-CCITT over
[0:288] stored little-endian.  A record that fails its checksum is
returned flagged, never silently dropped.  One shared CRC function
(minimateplus/crc.py) replaces micromate/setup_block's copy.

Fixtures: 12 real .MLG files (DL2's ACH folder + 3 bench files) in
tests/fixtures/mlg-11-9-26/, force-added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:39:44 -05:00

142 lines
5.3 KiB
Python

"""
minimateplus/mlg_file.py — Blastware's monitor log (.MLG): reader and writer.
Blastware writes one .MLG per call-in, named <serial><counter>.MLG, holding what
the unit logged since the previous call-in: each time monitoring started, each
event, and each time it stopped and why. Measured on 1,273 DL2 files and 9
bench files (2026-11-09; reference D.4, spec
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md):
[18-byte prefix 10 00 01 80 00 00 "Instantel\\0" 07 2c]
[292-byte records ...] size is always 18 + 292*n
Every record:
[0:2] length, uint16 LE = 290
[2:4] id: 0e a0 the header record (first, carries the serial), 0e 80 a log record
[4:12] start: day, month, year LE, 0, hour, minute, second
[12:20] stop, same format; all zeros = no stop
[20:22] monitor-log flag word, uint16 LE (the event footer's, D.6.14); 0xFFFF = started
[22:24] trigger source, uint16 LE: 0x0001-0x0008 a channel, 0x0400 a histogram
[24:34] serial, NUL-padded ASCII
[34:288] text, NUL-padded; an event's starts 0x08 + its 8-byte time
[288:290] 00 00
[290:292] CRC-16/AUG-CCITT over [0:288], little-endian
An empty file is the prefix alone: no header record, no serial. Pure: no I/O
beyond reading the path it is given.
"""
from __future__ import annotations
import datetime
import struct
from pathlib import Path
from typing import Optional, Union
from .crc import crc16_aug_ccitt
from .event_file_io import monitor_log_description
from .models import MlgFile, MlgRecord
MLG_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c"
RECORD_SIZE = 292
_RECORD_LENGTH = 290
_HEADER_ID = b"\x0e\xa0"
_LOG_ID = b"\x0e\x80"
_EVENT_TIME_MARK = 0x08
_TRIGGER_LEVEL_PREFIXES = ("Trigger Level :", "Trigger Level:")
class MlgFormatError(ValueError):
"""The bytes are not a whole .MLG file."""
def _ts(raw: bytes) -> Optional[datetime.datetime]:
"""8-byte MLG time (year little-endian); all zeros = None. Raises ValueError."""
if raw == bytes(8):
return None
year = struct.unpack_from("<H", raw, 2)[0]
return datetime.datetime(year, raw[1], raw[0], raw[5], raw[6], raw[7])
def _crc_ok(record: bytes) -> bool:
return crc16_aug_ccitt(record[:288]) == struct.unpack_from("<H", record, 290)[0]
def _trigger_level(text: str) -> Optional[str]:
line = text.split("\r", 1)[0]
for prefix in _TRIGGER_LEVEL_PREFIXES:
if line.startswith(prefix):
line = line[len(prefix):]
break
line = line.strip()
return line or None
def _log_record(index: int, rec: bytes) -> MlgRecord:
try:
start = _ts(rec[4:12])
stop = _ts(rec[12:20])
except ValueError as exc:
raise MlgFormatError(f"record {index}: a time cannot be decoded ({exc})") from None
if start is None:
raise MlgFormatError(f"record {index}: no start time")
flags, source = struct.unpack_from("<HH", rec, 20)
text_raw = rec[34:288]
body, event_time = text_raw, None
if text_raw[0] == _EVENT_TIME_MARK:
try:
event_time = _ts(text_raw[1:9])
except ValueError as exc:
raise MlgFormatError(f"record {index}: the event time cannot be decoded ({exc})") from None
body = text_raw[9:]
text = body.split(b"\x00", 1)[0].decode("latin-1")
is_start = flags == 0xFFFF
return MlgRecord(
index=index,
start=start,
stop=stop,
flags=flags,
trigger_source=source,
serial=rec[24:34].split(b"\x00", 1)[0].decode("ascii", errors="replace"),
text_raw=text_raw,
event_time=event_time,
text=text,
trigger_level=_trigger_level(text),
description="Monitoring started" if is_start else monitor_log_description(flags).strip(),
crc_ok=_crc_ok(rec),
)
def parse_mlg(data: bytes) -> MlgFile:
"""Parse the bytes of a .MLG file.
Raises MlgFormatError when the bytes are not a whole .MLG. A record whose
checksum fails is returned with crc_ok=False (MlgFile.crc_failures lists
them); the caller decides what to do with it."""
if len(data) < len(MLG_PREFIX) or not data.startswith(MLG_PREFIX):
raise MlgFormatError("not an MLG: the 18-byte Instantel prefix is missing")
body = data[len(MLG_PREFIX):]
if len(body) % RECORD_SIZE:
raise MlgFormatError(f"not an MLG: size {len(data)} is not 18 + 292*n")
records = [body[i:i + RECORD_SIZE] for i in range(0, len(body), RECORD_SIZE)]
if not records:
return MlgFile(serial=None)
for index, rec in enumerate(records):
length = struct.unpack_from("<H", rec, 0)[0]
if length != _RECORD_LENGTH:
raise MlgFormatError(f"record {index}: length field {length}, expected 290")
expected = _HEADER_ID if index == 0 else _LOG_ID
if rec[2:4] != expected:
raise MlgFormatError(f"record {index}: id {rec[2:4].hex()}, expected {expected.hex()}")
header = records[0]
return MlgFile(
serial=header[24:34].split(b"\x00", 1)[0].decode("ascii", errors="replace"),
records=[_log_record(i, rec) for i, rec in enumerate(records) if i > 0],
header_crc_ok=_crc_ok(header),
)
def read_mlg(path: Union[str, Path]) -> MlgFile:
"""Read and parse a .MLG file."""
return parse_mlg(Path(path).read_bytes())