""" framing.py — DLE frame codec for the Instantel MiniMate Plus RS-232 protocol. Wire format: BW→S3 (our requests): [ACK=0x41] [STX=0x02] [stuffed payload+chk] [ETX=0x03] S3→BW (device replies): [DLE=0x10] [STX=0x02] [stuffed payload+chk] [DLE=0x10] [ETX=0x03] The ACK 0x41 byte often precedes S3 frames too — it is silently discarded by the streaming parser. De-stuffed payload layout: BW→S3 request frame: [0] CMD 0x10 (BW request marker) [1] flags 0x00 [2] SUB command sub-byte [3] 0x00 always zero in captured frames [4] 0x00 always zero in captured frames [5] OFFSET two-step offset: 0x00 = length-probe, DATA_LEN = data-request [6-15] zero padding (total de-stuffed payload = 16 bytes) S3→BW response frame: [0] CMD 0x00 (S3 response marker) [1] flags 0x10 [2] SUB response sub-byte (= 0xFF - request SUB) [3] PAGE_HI high byte of page address (always 0x00 in observed frames) [4] PAGE_LO low byte (always 0x00 in observed frames) [5+] data payload data section (composite inner frames for large responses) DLE stuffing rule: any 0x10 byte in the payload is doubled on the wire (0x10 → 0x10 0x10). This applies to the checksum byte too. ⚠ AMENDED 2026-10-26 (measured): a request escapes FOUR values, not one -- every 02, 03, 04 and 10 in payload and checksum gets a DLE in front. Blastware's 748 recorded requests re-encode byte-identically under that rule (tests/test_5a_blastware_walk.py); a bare 02 or 03 left a request unanswered. See `s3_stuff()`. Confirmed from live captures (s3_parser.py validation + raw_bw.bin / raw_s3.bin). """ from __future__ import annotations from dataclasses import dataclass from typing import Optional # ── Protocol byte constants ─────────────────────────────────────────────────── DLE = 0x10 # Data Link Escape STX = 0x02 # Start of text ETX = 0x03 # End of text ACK = 0x41 # Acknowledgement / frame-start marker (BW side) BW_CMD = 0x10 # CMD byte value in BW→S3 frames S3_CMD = 0x00 # CMD byte value in S3→BW frames S3_FLAGS = 0x10 # flags byte value in S3→BW frames # BW read-command payload size: 5 header bytes + 11 padding bytes = 16 total. # Confirmed from captured raw_bw.bin: all read-command frames carry exactly 16 # de-stuffed bytes (excluding the appended checksum). _BW_PAYLOAD_SIZE = 16 # ── DLE stuffing / de-stuffing ──────────────────────────────────────────────── def dle_stuff(data: bytes) -> bytes: """Escape literal 0x10 bytes: 0x10 → 0x10 0x10.""" out = bytearray() for b in data: if b == DLE: out.append(DLE) out.append(b) return bytes(out) def dle_unstuff(data: bytes) -> bytes: """Remove DLE stuffing: 0x10 0x10 → 0x10.""" out = bytearray() i = 0 while i < len(data): b = data[i] if b == DLE and i + 1 < len(data) and data[i + 1] == DLE: out.append(DLE) i += 2 else: out.append(b) i += 1 return bytes(out) # ── Checksum ───────────────────────────────────────────────────────────────── # Every byte value a request DLE-escapes (2026-10-26, measured): Blastware's 748 # requests from a whole download session re-encode byte-identically with this set, # payload and checksum alike. A bare 0x02 checksum or a 0x03 inside the params left # BE9441 silent (and the 0x02 made it reset ~11 s later). It is a Micromate's set # too (micromate.framing._ESCAPED). _ESCAPED = frozenset({STX, ETX, 0x04, DLE}) def s3_stuff(data: bytes) -> bytes: """Escape every byte a request escapes: `XX` → `10 XX` for 02, 03, 04 and 10.""" out = bytearray() for b in data: if b in _ESCAPED: out.append(DLE) out.append(b) return bytes(out) def checksum(payload: bytes) -> int: """SUM8: sum of all de-stuffed payload bytes, mod 256.""" return sum(payload) & 0xFF # ── BW→S3 frame builder ─────────────────────────────────────────────────────── # SUB byte for 5A (protocol.py has the full constant set; defined here to # avoid a circular import). SUB_5A = 0x5A def build_5a_request(address: int, length: int) -> bytes: """A SUB 5A read of `length` bytes at the unit's 32-bit `address`. Measured 2026-10-26 from Blastware downloading all 8 of BE9441's events (four crossing a 64 KB page): a 5A request is an ORDINARY 16-byte request -- `[10 00 5A 00][length BE][address BE 4][zeros 6]`, SUM8 checksum, every 02/03/04/10 escaped -- and this rebuilds all 540 of Blastware's 5A requests byte for byte. The older model (`build_5a_frame` and the `bulk_waveform_*` helpers, removed 2026-11-20: a raw "offset_hi 0x10", an "11-byte params", "metadata pages at 0x1002 / 0x1004") was the same bytes misread: `10 02 00` is the length 0x0200 escaped, and the "metadata pages" are the first event's chunks at 0x0200 and 0x0400. """ if not 0 <= address <= 0xFFFFFFFF: raise ValueError(f"address must fit in 32 bits, got {address:#x}") return build_bw_frame(SUB_5A, length, address.to_bytes(4, "big") + bytes(6)) def build_bw_frame(sub: int, offset: int = 0, params: bytes = bytes(10)) -> bytes: """ Build a BW→S3 read-command frame. The payload is always 16 de-stuffed bytes: [BW_CMD, 0x00, sub, 0x00, 0x00, offset] + params(10 bytes) Confirmed from BW capture analysis: payload[3] and payload[4] are always 0x00 across all observed read commands. The two-step offset lives at payload[5]: 0x00 for the length-probe step, DATA_LEN for the data-fetch step. The 10 params bytes (payload[6..15]) are zero for standard reads. For keyed reads (SUBs 0A, 0C) the 4-byte waveform key lives at params[4..7] (= payload[10..13]). For token-based reads (SUBs 1E, 1F) a single token byte lives at params[6] (= payload[12]). Use waveform_key_params() and token_params() helpers to build these safely. Wire output: [ACK] [STX] s3_stuff(payload + checksum) [ETX] Args: sub: SUB command byte (e.g. 0x01 = FULL_CONFIG_READ) offset: Value placed at payload[5]. Pass 0 for the probe step; pass DATA_LENGTHS[sub] for the data step. params: 10 bytes placed at payload[6..15]. Default: all zeros. Returns: Complete frame bytes ready to write to the serial port / socket. """ if len(params) != 10: raise ValueError(f"params must be exactly 10 bytes, got {len(params)}") if offset > 0xFFFF: raise ValueError(f"offset must fit in uint16, got {offset:#06x}") # offset is a uint16 split across bytes [4] (high) and [5] (low). # For all standard reads (offset ≤ 0xFF), byte[4] = 0x00 — consistent with # every captured BW frame. For large payloads (e.g. SUB 1A / E5 at 0x082A), # byte[4] carries the high byte. 🔶 INFERRED — confirm once E5 is captured. offset_hi = (offset >> 8) & 0xFF offset_lo = offset & 0xFF payload = bytes([BW_CMD, 0x00, sub, 0x00, offset_hi, offset_lo]) + params chk = checksum(payload) wire = bytes([ACK, STX]) + s3_stuff(payload + bytes([chk])) + bytes([ETX]) return wire def build_bw_write_frame( sub: int, data: bytes, *, offset: Optional[int] = None, params: bytes = bytes(10), ) -> bytes: """A write request: the standard 16-byte request followed by `data`, escaped and checksummed like every other request (s3_stuff, SUM8). `offset` is the payload's [4:6] field -- the data's LENGTH; it defaults to len(data), which is what Blastware sends on every write on record. Measured 2026-10-26/27 (issue #46): all of Blastware's requests from February to October 2026 -- 3,869 frames in the uploaded captures plus BE9441's 26 write frames tonight -- rebuild byte for byte this way, the 77 write frames that carry data included (event index 68, compliance 71, trigger 82, waveform data 69). ⚠ RETRACTED: "only BW_CMD is doubled, everything else raw" and the "DLE-aware checksum" `(sum of payload[2:] skipping 0x10) + 0x10`. That model rebuilt the March frames only because it was fitted to data that still held its escape bytes; the "data length 91, offset 90" it explained was 90 bytes plus one escape. It got 7 of every 13 frames in a config write wrong. """ if len(params) != 10: raise ValueError(f"params must be exactly 10 bytes, got {len(params)}") length = len(data) if offset is None else offset if not 0 <= length <= 0xFFFF: raise ValueError(f"length must fit in 16 bits, got {length:#x}") payload = bytes([BW_CMD, 0x00, sub, 0x00, (length >> 8) & 0xFF, length & 0xFF]) + params + data return bytes([ACK, STX]) + s3_stuff(payload + bytes([checksum(payload)])) + bytes([ETX]) def waveform_key_params(key4: bytes) -> bytes: """ Build the 10-byte params block that carries a 4-byte waveform key. Used for SUBs 0A (WAVEFORM_HEADER) and 0C (WAVEFORM_RECORD). The key goes at params[4..7], which maps to payload[10..13]. Confirmed from 3-31-26 capture: 0A and 0C request frames carry the 4-byte record address at payload[10..13]. Probe and data-fetch steps carry the same key in both frames. Args: key4: exactly 4 bytes — the opaque waveform record address returned by the EVENT_HEADER (1E) or EVENT_ADVANCE (1F) response. Returns: 10-byte params block with key embedded at positions [4..7]. """ if len(key4) != 4: raise ValueError(f"waveform key must be 4 bytes, got {len(key4)}") p = bytearray(10) p[4:8] = key4 return bytes(p) def token_params(token: int = 0) -> bytes: """ Build the 10-byte params block that carries a single token byte. Used for SUBs 1E (EVENT_HEADER) and 1F (EVENT_ADVANCE). The token goes at params[7], which maps to payload[13]. Confirmed from BOTH 3-31-26 and 4-3-26 BW TX captures: raw params bytes: 00 00 00 00 00 00 00 fe 00 00 token is at index 7 (not 6 — that was wrong). - token=0x00: first-event read / browse mode (no download marking) - token=0xfe: download mode (causes 1F to skip partial bins and advance to the next full record) The device echoes the token at data[8] of the S3 response (payload[13]), distinct from the next-event key at data[11:15] (payload[16:20]). Args: token: single byte to place at params[7] / payload[13]. Returns: 10-byte params block with token at position [7]. """ p = bytearray(10) p[7] = token return bytes(p) # ── End-offset extraction from STRT record ──────────────────────────────────── STRT_MARKER = b"STRT" def unescape_reply(data: bytes) -> bytes: """A reply's data with each kept escape removed: `10 02/03/04` → `02/03/04`. The unit escapes 02, 03, 04 and 10 in its replies exactly as requests do, the checksum included (748/748 replies, 2026-10-26; 7,747 / 7,747 across every recording, March to October 2026, #58). S3FrameParser collapses `10 10` but keeps the `10` of `10 02/03/04` (inner-frame markers to it) everywhere but the checksum, so its `.data` carries an extra byte before each 02/03/04 value -- harmless for fields read before the escape, one byte off for any read after it, or counted from the end.""" out, i = bytearray(), 0 while i < len(data): if data[i] == DLE and i + 1 < len(data) and data[i + 1] in (STX, ETX, 0x04): i += 1 continue out.append(data[i]) i += 1 return bytes(out) def parse_strt_end_key(a5_data: bytes) -> Optional[int]: """The event's FULL 32-bit end key from the STRT record in an A5 reply's data, or None. The page byte is part of it: an event that ends in the next 64 KB page reads e.g. 0x011216C4 here, where `parse_strt_end_offset` gave 0x16C4. Read after `unescape_reply`.""" out = unescape_reply(a5_data) pos = out.find(STRT_MARKER) if pos < 0 or pos + 10 > len(out): return None return int.from_bytes(out[pos + 6:pos + 10], "big") def parse_strt_end_offset(a5_data: bytes) -> Optional[int]: """ ⛔ SUPERSEDED 2026-10-26 by `parse_strt_end_key`: this keeps only the low 16 bits (the 64 KB page bug) and misreads an end whose low bytes hold an escaped 02/03/04. No production caller; tests/test_5a_blastware_walk.py keeps it to show that misread. Extract the event-end offset from the STRT record in an A5 response payload. The first A5 response (the probe response, or the first chunk for events with non-zero start_key[2:4]) contains a STRT record at byte offset 17 of `data`. Layout: data[17:21] "STRT" data[21:23] ff fe sentinel data[23:27] end_key ← 4-byte key of where this event ENDS data[27:31] start_key ... Returns `(end_key[2] << 8) | end_key[3]` — the absolute device-buffer address where the event ends. Use this to bound the chunk loop and to compute the TERM frame. Verified end_offset values: | event start_key | end_key | end_offset | | 01110000 | 01111ABE | 0x1ABE | | 01110000 | 011121F2 | 0x21F2 | | 011121F2 | 0111417E | 0x417E | Args: a5_data: The `data` field of an A5 response frame (frame.data). Returns: The end_offset (uint16) if STRT is found, else None. """ pos = a5_data.find(STRT_MARKER) if pos < 0 or pos + 10 > len(a5_data): return None # data[pos+4:pos+6] is "ff fe"; data[pos+6:pos+10] is end_key. end_key = a5_data[pos + 6 : pos + 10] if len(end_key) < 4: return None return (end_key[2] << 8) | end_key[3] # ── Pre-built POLL frames ───────────────────────────────────────────────────── # # POLL (SUB 0x5B) uses the same two-step pattern as all other reads — the # hardcoded length 0x30 lives at payload[5], exactly as in build_bw_frame(). POLL_PROBE = build_bw_frame(0x5B, 0x00) # length-probe POLL (offset = 0) POLL_DATA = build_bw_frame(0x5B, 0x30) # data-request POLL (offset = 0x30) # Session-reset signal (ACK + ETX, no STX/payload). # Confirmed from 4-8-26 BW TX captures: Blastware sends this 2-byte sequence # immediately before the first POLL probe, and again between the POLL probe # and the POLL data request. Required to wake a unit that is actively # monitoring — without it the unit does not respond to POLL over TCP. # Harmless for idle units (they respond to POLL regardless). SESSION_RESET = bytes([0x41, 0x03]) # ── S3 response dataclass ───────────────────────────────────────────────────── @dataclass class S3Frame: """A fully parsed and de-stuffed S3→BW response frame.""" sub: int # response SUB byte (e.g. 0xA4 = POLL_RESPONSE) page_hi: int # PAGE_HI from header (= data length on step-2 length response) page_lo: int # PAGE_LO from header data: bytes # payload data section (payload[5:], checksum already stripped) checksum_valid: bool chk_byte: int = 0 # actual checksum byte received from wire (body[-1]); an # escaped one (`10 02/03/04`) leaves no 10 in `data` (#58) @property def page_key(self) -> int: """Combined 16-bit page address / length: (page_hi << 8) | page_lo.""" return (self.page_hi << 8) | self.page_lo # ── Streaming S3 frame parser ───────────────────────────────────────────────── class S3FrameParser: """ Incremental byte-stream parser for S3→BW response frames. Feed incoming bytes with feed(). Complete, valid frames are returned immediately and also accumulated in self.frames. State machine: IDLE — scanning for DLE (0x10) SEEN_DLE — saw DLE, waiting for STX (0x02) to start a frame IN_FRAME — collecting de-stuffed payload bytes; bare ETX ends frame IN_FRAME_DLE — inside frame, saw DLE; DLE continues stuffing; DLE+ETX is treated as literal data (NOT a frame end), which lets inner-frame terminators pass through intact Wire format confirmed from captures: [DLE=0x10] [STX=0x02] [stuffed payload+chk] [bare ETX=0x03] The ETX is NOT preceded by a DLE on the wire. DLE+ETX sequences that appear inside the payload are inner-frame terminators and must be treated as literal data. ACK (0x41) bytes and arbitrary non-DLE bytes in IDLE state are silently discarded (covers device boot string "Operating System" and keepalive ACKs). """ _IDLE = 0 _SEEN_DLE = 1 _IN_FRAME = 2 _IN_FRAME_DLE = 3 def __init__(self) -> None: self._state = self._IDLE self._body = bytearray() # accumulates de-stuffed frame bytes self.frames: list[S3Frame] = [] self.bytes_fed: int = 0 # cumulative raw bytes fed since last reset def reset(self) -> None: self._state = self._IDLE self._body.clear() self.bytes_fed = 0 def feed(self, data: bytes) -> list[S3Frame]: """ Process a chunk of incoming bytes. Returns a list of S3Frame objects completed during this call. All completed frames are also appended to self.frames. """ self.bytes_fed += len(data) completed: list[S3Frame] = [] for b in data: frame = self._step(b) if frame is not None: completed.append(frame) self.frames.append(frame) return completed def _step(self, b: int) -> Optional[S3Frame]: """Process one byte. Returns a completed S3Frame or None.""" if self._state == self._IDLE: if b == DLE: self._state = self._SEEN_DLE # ACK, boot strings, garbage — silently ignored elif self._state == self._SEEN_DLE: if b == STX: self._body.clear() self._state = self._IN_FRAME else: # Stray DLE not followed by STX — back to idle self._state = self._IDLE elif self._state == self._IN_FRAME: if b == DLE: self._state = self._IN_FRAME_DLE elif b == ETX: # Bare ETX = real frame terminator (confirmed from captures) frame = self._finalise() self._state = self._IDLE return frame else: self._body.append(b) elif self._state == self._IN_FRAME_DLE: if b == DLE: # DLE DLE → literal 0x10 in payload self._body.append(DLE) self._state = self._IN_FRAME elif b == ETX: # DLE+ETX inside a frame is an inner-frame terminator, NOT # the outer frame end. Treat as literal data and continue. self._body.append(DLE) self._body.append(ETX) self._state = self._IN_FRAME else: # Unexpected DLE + byte — treat both as literal data and continue self._body.append(DLE) self._body.append(b) self._state = self._IN_FRAME return None def _finalise(self) -> Optional[S3Frame]: """ Called when DLE+ETX is seen. Validates checksum and builds S3Frame. Returns None if the frame is too short or structurally invalid. """ body = bytes(self._body) # Minimum valid frame: 5-byte header + at least 1 checksum byte = 6 if len(body) < 6: return None # A checksum of 02, 03 or 04 arrives escaped, `10 X`, and _step keeps both # bytes; that 10 is the escape, never data (#58: 272 of 7,747 recorded # replies, every one an escape pair). Any other checksum is one byte. n_chk = 2 if body[-2] == DLE and body[-1] in (STX, ETX, 0x04) else 1 raw_payload = body[:-n_chk] # everything except the checksum chk_received = body[-1] # SUM8 of the payload unescaped: the kept `10` of a `10 02/03/04` is not # summed (7,747 of 7,747 recorded replies check this way). chk_computed = checksum(unescape_reply(raw_payload)) if len(raw_payload) < 5: return None # Validate CMD byte — we only accept S3→BW response frames here if raw_payload[0] != S3_CMD: return None return S3Frame( sub = raw_payload[2], page_hi = raw_payload[3], page_lo = raw_payload[4], data = raw_payload[5:], checksum_valid = (chk_received == chk_computed), chk_byte = chk_received, )