mlg_bytes()/write_mlg() rebuild all 12 fixture files byte for byte: little-endian times, length-led records, each record's checksum. The old blastware_file writer (big-endian times, a zero CRC at the wrong end, 308- byte header) and the read_mlg stub are removed; nothing called them. No re-export: event_file_io imports blastware_file, and mlg_file imports event_file_io. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
186 lines
7.1 KiB
Python
186 lines
7.1 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())
|
|
|
|
|
|
# ── Writer ────────────────────────────────────────────────────────────────────
|
|
|
|
def _ts_bytes(ts: Optional[datetime.datetime]) -> bytes:
|
|
if ts is None:
|
|
return bytes(8)
|
|
return bytes([ts.day, ts.month]) + struct.pack("<H", ts.year) + bytes([0, ts.hour, ts.minute, ts.second])
|
|
|
|
|
|
def _serial_field(serial: str) -> bytes:
|
|
return serial.encode("ascii", errors="replace")[:10].ljust(10, b"\x00")
|
|
|
|
|
|
def _sealed(body: bytes) -> bytes:
|
|
"""`body` is record[0:288]; append the two zero bytes and the LE checksum."""
|
|
return body + b"\x00\x00" + struct.pack("<H", crc16_aug_ccitt(body))
|
|
|
|
|
|
def _header_record(serial: str) -> bytes:
|
|
# Every byte but the serial is zero on all 1,273 DL2 files (measured 2026-11-13).
|
|
body = struct.pack("<H", _RECORD_LENGTH) + _HEADER_ID + bytes(20) + _serial_field(serial)
|
|
return _sealed(body.ljust(288, b"\x00"))
|
|
|
|
|
|
def _log_record_bytes(r: MlgRecord) -> bytes:
|
|
body = (struct.pack("<H", _RECORD_LENGTH) + _LOG_ID + _ts_bytes(r.start) + _ts_bytes(r.stop)
|
|
+ struct.pack("<HH", r.flags, r.trigger_source) + _serial_field(r.serial)
|
|
+ r.text_raw.ljust(254, b"\x00")[:254])
|
|
return _sealed(body)
|
|
|
|
|
|
def mlg_bytes(mlg: MlgFile) -> bytes:
|
|
"""The bytes of a .MLG file, as Blastware writes them: little-endian times,
|
|
length-led records, each record's checksum computed. An empty MlgFile is
|
|
the prefix alone."""
|
|
if mlg.empty:
|
|
return MLG_PREFIX
|
|
return MLG_PREFIX + _header_record(mlg.serial or "") + b"".join(_log_record_bytes(r) for r in mlg.records)
|
|
|
|
|
|
def write_mlg(mlg: MlgFile, path: Union[str, Path]) -> None:
|
|
"""Write `mlg` to `path` (see mlg_bytes)."""
|
|
Path(path).write_bytes(mlg_bytes(mlg))
|