""" minimateplus/mlg_file.py — Blastware's monitor log (.MLG): reader and writer. Blastware writes one .MLG per call-in, named .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(" bool: return crc16_aug_ccitt(record[:288]) == struct.unpack_from(" 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(" 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(" 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())