feat(mlg): write .MLG files as Blastware does; retire the old writer

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
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-13 13:41:38 -05:00
1 parent 3cd95db405
commit a8adb03d23
3 files changed
+70 -220

No files matched your search

+5 -219
View File
@@ -3,7 +3,8 @@ blastware_file.py — Blastware binary file codec for bidirectional interoperabi
Reads and writes the proprietary Instantel/Blastware file formats:
Waveform events (.CE0W, .VM0H, .440, .7M0, etc.) (extension encoding UNKNOWN — see below)
.MLG — Monitor log (monitoring session history)
Monitor logs (.MLG) live in minimateplus/mlg_file.py (reader and writer, 2026-11-13).
All waveform formats share a common 22-byte file header prefix and identical
internal binary structure (same type tag 00 12 03 00, same STRT record layout).
@@ -61,27 +62,6 @@ Waveform file structure (confirmed from example-events/4-3-26-multi/M529LIY6 (ex
Timestamp format (big-endian, 8 bytes):
[day] [month] [year_HI] [year_LO] [0x00] [hour] [min] [sec]
MLG (monitor log, confirmed from example-events/4-3-26-multi/BE11529.MLG):
[308B header] [N × 292B records]
Header (308 bytes):
Offset 0x00: 10 00 01 80 00 00 Instantel\x00 07 2c 22 01 0e a0 — fixed (16B)
Offset 0x10: ... (unknown structure, written as zeros + serial)
Offset 0x2A: serial number (8 bytes, null-padded ASCII, e.g. "BE11529")
... zero-padded to 308 bytes total
Record (292 bytes each):
[2B CRC] — unknown algorithm; written as 0x00 0x00
22 01 0e 80 — record marker
[ts1: 8B big-endian timestamp] — start time
[ts2: 8B big-endian timestamp] — stop time (zeros if no stop)
[4B flags] — see MLG_FLAGS_* constants below
[10B serial] — null-padded serial number ASCII
[text] — for trigger records: [0x08][8B ts1_copy] then ASCII "Geo: X.XXX in/s"
for monitoring records: b'' (or minimal separator)
[zero-padded to 292 bytes]
─── Critical implementation notes ──────────────────────────────────────────────
Waveform body reconstruction algorithm (confirmed 2026-04-21 from verification against
@@ -110,14 +90,6 @@ M529LIY6 (example event) using raw_s3_20260403_153508.bin capture):
of frame.data, and this builder dropped it here. The parser now drops it,
so a 0x10 ending frame.data is real data (one A5 chunk in ten ends in one).
MLG CRC:
The algorithm that produces the 2-byte CRC at the start of each MLG record
is unknown. All examined records use non-zero values that do not match
CRC-16/CCITT, CRC-16/IBM, CRC-32 (truncated), word sums, XOR variants, or
any of the 40+ polynomial/init combinations tested. The writer emits 0x0000.
This produces files that Blastware may reject or display without the CRC check —
the exact impact on BW import is unknown (TODO: test).
─── Public API ──────────────────────────────────────────────────────────────────
blastware_filename(event, serial)
@@ -133,13 +105,6 @@ MLG CRC:
read_blastware_file(path) → Event
Parse a Blastware waveform file into an Event object with waveform data populated.
(Not yet implemented — placeholder raises NotImplementedError.)
write_mlg(entries, serial, path)
Create a .MLG file from a list of MonitorLogEntry objects.
read_mlg(path) → list[MonitorLogEntry]
Parse a .MLG file into MonitorLogEntry objects.
(Not yet implemented — placeholder raises NotImplementedError.)
"""
from __future__ import annotations
@@ -152,7 +117,7 @@ from pathlib import Path
from typing import Optional, Union
from .framing import S3Frame
from .models import Event, MonitorLogEntry, Timestamp
from .models import Event, Timestamp
log = logging.getLogger(__name__)
@@ -169,9 +134,6 @@ _FILE_HEADER_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c" # 17 byt
# Waveform file type tag (4 bytes after common prefix) — shared by ALL waveform extensions
_WAVEFORM_TYPE_TAG = b"\x00\x12\x03\x00" # confirmed from M529LIY6 (example event) — same tag for .CE0W, .VM0H, etc.
# MLG type tag (4 bytes after common prefix)
_MLG_TYPE_TAG = b"\x22\x01\x0e\xa0" # confirmed from BE11529.MLG offset 0x11..0x14
# Total header sizes
_WAVEFORM_HEADER_SIZE = 22 # 17 + 4 = 21... wait. Let me recalculate.
# From binary: first 22 bytes = header, then STRT at byte 22.
@@ -180,17 +142,6 @@ _WAVEFORM_HEADER_SIZE = 22 # 17 + 4 = 21... wait. Let me recalculate.
# Re-count: b"\x10\x00\x01\x80\x00\x00" = 6B + b"Instantel\x00" = 10B + b"\x07\x2c" = 2B = 18B prefix.
_FILE_HEADER_PREFIX = b"\x10\x00\x01\x80\x00\x00Instantel\x00\x07\x2c" # 18 bytes
_WAVEFORM_HEADER_SIZE = 22 # 18 + 4 = 22 bytes ✅
_MLG_HEADER_SIZE = 308 # confirmed from BE11529.MLG
# MLG record marker (4 bytes after 2-byte CRC at start of each record)
_MLG_RECORD_MARKER = b"\x22\x01\x0e\x80"
_MLG_RECORD_SIZE = 292 # bytes per record (confirmed from BE11529.MLG)
# MLG record flags (4 bytes at record[22:26])
# Confirmed from BE11529.MLG binary inspection:
MLG_FLAGS_START_ONLY = b"\xff\xff\x00\x00" # monitoring start with no stop
MLG_FLAGS_TRIGGER = b"\x01\x00\x02\x00" # triggered event (has ts1 + ts2)
MLG_FLAGS_INTERVAL = b"\x02\x00\x00\x00" # monitoring interval (has ts1 + ts2)
# ── Timestamp helpers ─────────────────────────────────────────────────────────
@@ -199,7 +150,8 @@ def _encode_ts_be(ts: Optional[datetime.datetime]) -> bytes:
"""
Encode a datetime as an 8-byte big-endian Blastware timestamp.
Format (waveform file and MLG record timestamps):
Format (event file timestamps; an .MLG stores the year little-endian,
see minimateplus/mlg_file.py):
[day][month][year_HI][year_LO][0x00][hour][min][sec]
Big-endian year confirmed from M529LIY6 (example event) footer:
@@ -936,169 +888,3 @@ def read_blastware_file(path: Union[str, Path]) -> Event:
NotImplementedError: always (pending implementation).
"""
raise NotImplementedError("read_blastware_file() is not yet implemented")
# ── MLG file writer ───────────────────────────────────────────────────────────
def _build_mlg_header(serial: str) -> bytes:
"""
Build the 308-byte MLG file header.
Header structure (confirmed from BE11529.MLG binary inspection):
Offset 0x00: 10 00 01 80 00 00 Instantel\x00 07 2c 22 01 0e a0 (22B)
Offset 0x16: ... (16B unknown — observed as zeros in BE11529.MLG)
Offset 0x2A: serial number (8 bytes, null-padded ASCII)
... rest zero-padded to 308 bytes
The serial string "BE11529" appears at offset 0x2A (42 decimal).
"""
buf = bytearray(_MLG_HEADER_SIZE)
# Common prefix + MLG type tag
prefix = _FILE_HEADER_PREFIX + _MLG_TYPE_TAG # 22 bytes
buf[0:len(prefix)] = prefix
# Serial number at offset 0x2A
serial_bytes = serial.encode("ascii", errors="replace")[:8]
serial_padded = serial_bytes.ljust(8, b"\x00")
buf[0x2A : 0x2A + 8] = serial_padded
return bytes(buf)
def _build_mlg_record(
entry: MonitorLogEntry,
serial: str,
) -> bytes:
"""
Build one 292-byte MLG record from a MonitorLogEntry.
Record layout (confirmed from BE11529.MLG binary inspection):
[0:2] CRC — 2-byte CRC (algorithm unknown; written as 0x0000)
[2:6] marker — 22 01 0e 80
[6:14] ts1 — 8B big-endian start timestamp
[14:22] ts2 — 8B big-endian stop timestamp
[22:26] flags — 4B record flags (see MLG_FLAGS_* constants)
[26:36] serial — 10B null-padded serial number
[36:] text — for triggered events: [0x08][8B ts1_copy]["Geo: X.XXX in/s"]
for monitoring intervals: b"" or minimal separator
[... zero-padded to 292 bytes]
Flags based on entry type:
- MonitorLogEntry with start_time only (no stop_time): MLG_FLAGS_START_ONLY
- MonitorLogEntry with both times and geo_threshold_ips set: MLG_FLAGS_TRIGGER
- MonitorLogEntry with both times (monitoring interval): MLG_FLAGS_INTERVAL
The triggered-event text block (flags = MLG_FLAGS_TRIGGER):
[0x08] [ts1: 8B] [ASCII "Geo: X.XXX in/s\x00"]
Confirmed from BE11529.MLG records at offset 0x0134 and 0x0258.
"""
buf = bytearray(_MLG_RECORD_SIZE)
start_dt = (
datetime.datetime(
entry.start_time.year, entry.start_time.month, entry.start_time.day,
entry.start_time.hour, entry.start_time.minute, entry.start_time.second,
)
if entry.start_time else None
)
stop_dt = (
datetime.datetime(
entry.stop_time.year, entry.stop_time.month, entry.stop_time.day,
entry.stop_time.hour, entry.stop_time.minute, entry.stop_time.second,
)
if entry.stop_time else None
)
# [0:2] CRC placeholder
buf[0:2] = b"\x00\x00"
# [2:6] Record marker
buf[2:6] = _MLG_RECORD_MARKER
# [6:14] ts1
buf[6:14] = _encode_ts_be(start_dt)
# [14:22] ts2
buf[14:22] = _encode_ts_be(stop_dt)
# [22:26] flags
if stop_dt is None:
flags = MLG_FLAGS_START_ONLY
elif entry.geo_threshold_ips is not None:
flags = MLG_FLAGS_TRIGGER
else:
flags = MLG_FLAGS_INTERVAL
buf[22:26] = flags
# [26:36] serial (10B null-padded)
serial_bytes = serial.encode("ascii", errors="replace")[:10]
buf[26 : 26 + len(serial_bytes)] = serial_bytes
# [36:] text content
pos = 36
if flags == MLG_FLAGS_TRIGGER:
# Extra ts1 copy: [0x08][ts1: 8B]
buf[pos] = 0x08
pos += 1
buf[pos : pos + 8] = _encode_ts_be(start_dt)
pos += 8
if entry.geo_threshold_ips is not None:
geo_text = f"Geo: {entry.geo_threshold_ips:.3f} in/s\x00".encode("ascii")
buf[pos : pos + len(geo_text)] = geo_text
pos += len(geo_text)
return bytes(buf)
def write_mlg(
entries: list[MonitorLogEntry],
serial: str,
path: Union[str, Path],
) -> None:
"""
Write a Blastware .MLG monitor log file.
Args:
entries: List of MonitorLogEntry objects (from get_monitor_log_entries()).
Each entry produces one 292-byte record in the file.
serial: Device serial number string (e.g. "BE11529").
Written to the file header and each record.
path: Destination file path. Extension is not enforced — use ".MLG".
File layout:
[308B header] [N × 292B records]
Note: The 2-byte CRC at the start of each record is written as 0x0000.
The CRC algorithm is unknown (see module docstring).
Raises:
OSError: if the file cannot be written.
"""
path = Path(path)
header = _build_mlg_header(serial)
with open(path, "wb") as f:
f.write(header)
for entry in entries:
record = _build_mlg_record(entry, serial)
f.write(record)
def read_mlg(path: Union[str, Path]) -> list[MonitorLogEntry]:
"""
Parse a Blastware .MLG file into a list of MonitorLogEntry objects.
NOT YET IMPLEMENTED.
Args:
path: Path to the .MLG file.
Returns:
List of MonitorLogEntry objects.
Raises:
NotImplementedError: always (pending implementation).
"""
raise NotImplementedError("read_mlg() is not yet implemented")
+44
View File
@@ -139,3 +139,47 @@ def parse_mlg(data: bytes) -> MlgFile:
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))
+21 -1
View File
@@ -22,7 +22,7 @@ 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
from minimateplus.mlg_file import MlgFormatError, mlg_bytes, parse_mlg, read_mlg, write_mlg
FIX = Path(__file__).parent / "fixtures" / "mlg-11-9-26"
dt = datetime.datetime
@@ -108,3 +108,23 @@ def test_a_flipped_byte_in_the_header_record_is_reported():
def test_structure_errors_raise(mangle):
with pytest.raises(MlgFormatError):
parse_mlg(mangle((FIX / "BE128443065.MLG").read_bytes()))
# ── Writer ────────────────────────────────────────────────────────────────────
@pytest.mark.parametrize("name", sorted(p.name for p in FIX.glob("*.MLG")))
def test_rebuilds_every_fixture_byte_for_byte(name):
raw = (FIX / name).read_bytes()
assert mlg_bytes(parse_mlg(raw)) == raw
def test_write_mlg_writes_the_same_bytes(tmp_path):
raw = (FIX / "BE8081321.MLG").read_bytes()
out = tmp_path / "BE8081321.MLG"
write_mlg(parse_mlg(raw), out)
assert out.read_bytes() == raw
def test_old_mlg_code_is_gone():
import minimateplus.blastware_file as bw
assert not hasattr(bw, "read_mlg") and not hasattr(bw, "MLG_FLAGS_TRIGGER")