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:
serversdownandClaude Opus 5.5 committed 2026-11-13 13:39:44 -05:00
1 parent 74ce7abcc6
commit 3cd95db405
17 files changed
+322 -10

No files matched your search

+2 -10
View File
@@ -15,6 +15,8 @@ from __future__ import annotations
import struct
from minimateplus.crc import crc16_aug_ccitt as _crc16_aug_ccitt
from .models import MicromateSetup
from .protocol import ProtocolError
@@ -23,8 +25,6 @@ class SetupChecksumError(ProtocolError):
"""A config block's trailing CRC does not match its contents."""
_CRC_POLY = 0x1021
_CRC_INIT = 0x1D0F # CRC-16/AUG-CCITT
_CONTENT_SIZE = 2092 # = content[0:2] (2090) + the 2-byte CRC
# ── Head of the block ─────────────────────────────────────────────────────────
@@ -60,14 +60,6 @@ _ACTIVE_MIC = 3 # block index (0-based)
_MIC_TYPES = {2: "linear", 9: "sound_level"}
def _crc16_aug_ccitt(data: bytes) -> int:
c = _CRC_INIT
for b in data:
c ^= b << 8
for _ in range(8):
c = ((c << 1) ^ _CRC_POLY) & 0xFFFF if c & 0x8000 else (c << 1) & 0xFFFF
return c
def crc_ok(content: bytes) -> bool:
"""True if a config block's trailing checksum matches its contents.
+23
View File
@@ -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
+141
View File
@@ -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())
+46
View File
@@ -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
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+110
View File
@@ -0,0 +1,110 @@
"""
Tests for minimateplus/mlg_file.py — Blastware's monitor log (.MLG) reader and writer.
Fixtures (tests/fixtures/mlg-11-9-26/) are real files: DL2's ACH folder
(BE12844, BE6907 from 2026; BE8081 from 2018-19) and three bench files.
Expected values come from an independent scratch parser that was checked
against DL2's event-file footers (785 / 785 BE8081 records matched by stop,
flag word and trigger source), never from the code under test. Format:
docs/instantel_protocol_reference.md D.4, spec
docs/superpowers/specs/2026-11-09-mlg-unit-timeline-design.md.
"""
from __future__ import annotations
import datetime
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.crc import crc16_aug_ccitt
from minimateplus.mlg_file import MlgFormatError, parse_mlg, read_mlg
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
dt = datetime.datetime
def test_crc_matches_the_micromate_rule():
from micromate.setup_block import _crc16_aug_ccitt
assert crc16_aug_ccitt(b"123456789") == _crc16_aug_ccitt(b"123456789") == 0xE5CC
def test_every_fixture_record_passes_its_checksum():
files = sorted(FIX.glob("*.MLG"))
assert len(files) == 12
for p in files:
assert parse_mlg(p.read_bytes()).crc_failures == [], p.name
def test_closed_records():
m = read_mlg(FIX / "BE128443065.MLG")
assert m.serial == "BE12844" and len(m.records) == 2
r1, r2 = m.records
assert (r1.index, r1.start, r1.stop, r1.flags, r1.trigger_source) == (
1, dt(2026, 9, 5, 18, 47, 26), dt(2026, 9, 5, 20, 0, 0), 0x0010, 0)
assert r1.description == "Timer Stop"
assert r1.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert r1.serial == "BE12844"
assert (r2.start, r2.stop, r2.description) == (
dt(2026, 9, 6, 6, 0, 13), dt(2026, 9, 6, 18, 45, 0), "Modem Exit")
def test_monitoring_started_and_an_event():
m = read_mlg(FIX / "BE128443067.MLG")
start, ev = m.records[1], m.records[2]
assert start.is_start and start.stop is None
assert start.description == "Monitoring started"
assert start.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
assert (ev.flags, ev.trigger_source, ev.description) == (0x0001, 0x0001, "Event Recorded")
assert ev.event_time == dt(2026, 9, 8, 13, 38, 22)
assert ev.text == "Geo: 0.0500 in/s Mic: 125.0 dB(L)\rTran: 0.0500 in/s"
assert ev.trigger_level == "Geo: 0.0500 in/s Mic: 125.0 dB(L)"
def test_histogram_with_a_waveform_event():
r = read_mlg(FIX / "BE8081.MLG").records
assert (r[1].flags, r[1].trigger_source, r[1].description) == (
0x0021, 0x0400, "Event Recorded Modem Exit")
assert r[1].trigger_level == "Histogram"
assert (r[2].trigger_source, r[2].trigger_level) == (0x0002, "Geo: 0.300 in/s")
def test_trigger_level_with_or_without_a_space_before_the_colon():
a = read_mlg(FIX / "BE11529.MLG").records[0]
b = read_mlg(FIX / "BE115292.MLG").records[0]
assert a.text == "Trigger Level: Histogram" and b.text == "Trigger Level : Histogram"
assert a.trigger_level == b.trigger_level == "Histogram"
def test_empty_file():
m = read_mlg(FIX / "BE6907751.MLG")
assert m.serial is None and m.records == [] and m.empty
def test_a_flipped_byte_fails_only_its_record():
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 292 + 40] ^= 0xFF # inside record 1's text
m = parse_mlg(bytes(data))
assert m.crc_failures == [1]
assert m.records[0].crc_ok is False and m.records[1].crc_ok is True
def test_a_flipped_byte_in_the_header_record_is_reported():
data = bytearray((FIX / "BE128443065.MLG").read_bytes())
data[18 + 100] ^= 0xFF # inside the header record's zero area
assert parse_mlg(bytes(data)).crc_failures == [0]
@pytest.mark.parametrize("mangle", [
lambda d: d[:-1], # not 18 + 292·n
lambda d: b"\x00" + d[1:], # wrong prefix
lambda d: d[:18] + b"\x23" + d[19:], # header length field not 290
lambda d: d[:6], # shorter than the prefix
], ids=["not-whole", "prefix", "length-field", "short"])
def test_structure_errors_raise(mangle):
with pytest.raises(MlgFormatError):
parse_mlg(mangle((FIX / "BE128443065.MLG").read_bytes()))