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
This commit is contained in:
1 parent
74ce7abcc6
commit
3cd95db405
17 files changed
+322
-10
No files matched your search
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
minimateplus/crc.py — Instantel's record checksum, shared by every reader that checks one.
|
||||
|
||||
CRC-16/AUG-CCITT: poly 0x1021, init 0x1D0F, no reflection, no final XOR. The
|
||||
same rule covers a Micromate's setup blocks (0x1A, 0x08, 0x2E; stored big-endian),
|
||||
a Blastware event file's footer (big-endian) and every .MLG record (little-endian).
|
||||
Each block says where its checksum sits; this module only computes it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
_POLY = 0x1021
|
||||
_INIT = 0x1D0F
|
||||
|
||||
|
||||
def crc16_aug_ccitt(data: bytes) -> int:
|
||||
"""CRC-16/AUG-CCITT of `data` (check value: b"123456789" -> 0xE5CC)."""
|
||||
c = _INIT
|
||||
for b in data:
|
||||
c ^= b << 8
|
||||
for _ in range(8):
|
||||
c = ((c << 1) ^ _POLY) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
|
||||
return c
|
||||
@@ -0,0 +1,141 @@
|
||||
"""
|
||||
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())
|
||||
@@ -729,6 +729,52 @@ class MonitorLogEntry:
|
||||
return f"MonitorLog#{self.index} key={self.key} {start}→{stop}{dur}"
|
||||
|
||||
|
||||
# ── Blastware monitor log (.MLG) ──────────────────────────────────────────────
|
||||
|
||||
@dataclass
|
||||
class MlgRecord:
|
||||
"""One log record of a Blastware .MLG file (minimateplus/mlg_file.py).
|
||||
|
||||
Times are the unit's own local clock. `flags` is the monitor-log flag word
|
||||
(the event footer's, reference D.6.14); 0xFFFF means monitoring started
|
||||
and has no stop yet."""
|
||||
index: int # position in the file; 0 is the header record
|
||||
start: datetime.datetime
|
||||
stop: Optional[datetime.datetime]
|
||||
flags: int
|
||||
trigger_source: int # 0x0001-0x0008 a channel, 0x0400 a histogram, 0 none
|
||||
serial: str
|
||||
text_raw: bytes = field(repr=False) # record[34:288] exactly, for write_mlg
|
||||
event_time: Optional[datetime.datetime] = None
|
||||
text: str = "" # Blastware's text, after any event time
|
||||
trigger_level: Optional[str] = None # e.g. "Geo: 0.0500 in/s Mic: 125.0 dB(L)", "Histogram"
|
||||
description: str = "" # "Monitoring started", or Blastware's words
|
||||
crc_ok: bool = True
|
||||
|
||||
@property
|
||||
def is_start(self) -> bool:
|
||||
return self.flags == 0xFFFF
|
||||
|
||||
|
||||
@dataclass
|
||||
class MlgFile:
|
||||
"""A whole .MLG file: the serial from its header record and its log records,
|
||||
in file order. An empty file (the 18-byte prefix alone) has neither."""
|
||||
serial: Optional[str]
|
||||
records: list[MlgRecord] = field(default_factory=list)
|
||||
header_crc_ok: bool = True
|
||||
|
||||
@property
|
||||
def empty(self) -> bool:
|
||||
return self.serial is None and not self.records
|
||||
|
||||
@property
|
||||
def crc_failures(self) -> list[int]:
|
||||
"""Indexes of the records whose checksum fails (0 is the header record)."""
|
||||
head = [] if self.header_crc_ok else [0]
|
||||
return head + [r.index for r in self.records if not r.crc_ok]
|
||||
|
||||
|
||||
# ── MonitorStatus ─────────────────────────────────────────────────────────────
|
||||
|
||||
@dataclass
|
||||
|
||||
Reference in new issue
Block a user