"""Unified Prod2U host protocol codec (16-bit length, 2026 contract). Wire format (both 6400-front-rear and mrdimm-chamber products): A5 5A | TYPE:u8 | LENGTH:u16le | PAYLOAD | CRC:u16le CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, no reflection, xorout 0. CRC covers TYPE + LENGTH_LOW + LENGTH_HIGH + PAYLOAD; the A5 5A preamble is not covered. This module is the independent host-side reference implementation. It is deliberately written from the protocol contract text, not shared with the RTL frame parser, so the fixed contract vectors below are a cross-check between two independent implementations. Breaking change vs the historical 8-bit-length frames: old consumers must not be fed these frames and vice versa; there is no legacy autodetect. """ from __future__ import annotations from enum import IntEnum PREAMBLE = b"\xA5\x5A" HEADER_SIZE = 5 # preamble(2) + type(1) + length(2); preamble excluded from CRC MAX_REQUEST_PAYLOAD = 256 MAX_RESPONSE_PAYLOAD = 1024 class Type(IntEnum): SET_ALL = 0x01 GET_ALL = 0x02 MOTOR_QUEUE_WRITE = 0x03 MOTOR_CONTROL = 0x04 OUTPUT_KEEPALIVE = 0x05 EVENT_READ = 0x08 EVENT_CLEAR = 0x09 ACK_NACK = 0x80 ALL_STATUS_DATA = 0x81 EVENT_DATA = 0x83 REQUEST_TYPES = frozenset( { Type.SET_ALL, Type.GET_ALL, Type.MOTOR_QUEUE_WRITE, Type.MOTOR_CONTROL, Type.OUTPUT_KEEPALIVE, Type.EVENT_READ, Type.EVENT_CLEAR, } ) RESPONSE_TYPES = frozenset({Type.ACK_NACK, Type.ALL_STATUS_DATA, Type.EVENT_DATA}) class Status(IntEnum): OK = 0 UNSUPPORTED = 1 BAD_LENGTH = 2 BAD_VALUE = 3 BUSY = 4 QUEUE_FULL = 5 BAD_AXIS = 6 BAD_MODE = 7 BAD_REGISTER = 8 NOT_READY = 9 def crc16_ccitt_false(data: bytes) -> int: """CRC-16/CCITT-FALSE over ``data`` (MSB first, init 0xFFFF).""" value = 0xFFFF for byte in data: value ^= byte << 8 for _ in range(8): value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF return value def encode_frame(frame_type: int, payload: bytes = b"") -> bytes: """Encode one frame. Payload must be at most 65535 bytes.""" if not 0 <= int(frame_type) <= 0xFF: raise ValueError("frame type must fit in u8") if len(payload) > 0xFFFF: raise ValueError("payload longer than 16-bit length field") body = bytes([int(frame_type), len(payload) & 0xFF, (len(payload) >> 8) & 0xFF]) + payload return PREAMBLE + body + crc16_ccitt_false(body).to_bytes(2, "little") def encode_ack(request_type: int, status: int, detail: int = 0) -> bytes: """ACK_NACK (0x80): fixed 4-byte payload request_type/status/detail:u16le.""" return encode_frame( Type.ACK_NACK, bytes([int(request_type) & 0xFF, int(status) & 0xFF]) + int(detail).to_bytes(2, "little"), ) class Frame: __slots__ = ("frame_type", "payload", "crc_ok") def __init__(self, frame_type: int, payload: bytes, crc_ok: bool) -> None: self.frame_type = frame_type self.payload = payload self.crc_ok = crc_ok def __repr__(self) -> str: # pragma: no cover - debug aid return f"Frame(type=0x{self.frame_type:02X}, len={len(self.payload)}, crc_ok={self.crc_ok})" class FrameParser: """Streaming byte-at-a-time frame parser. Semantics required by the contract: - Syncs on the A5 5A preamble; garbage before a preamble is skipped. - Once a header is accepted the declared 16-bit length is trusted: the whole payload plus trailing CRC is consumed even if the CRC fails (an over-long declared length is consumed, not used to bound RAM). - An A5 5A inside a payload is never treated as a new frame. - Frames with bad CRC are surfaced with ``crc_ok=False`` so the caller can drop them silently; nothing else is emitted for them. """ _SYNC0, _SYNC1, _TYPE, _LEN_LO, _LEN_HI, _PAYLOAD, _CRC_LO, _CRC_HI = range(8) def __init__(self) -> None: self.discarded_bytes = 0 self.rejected_frames = 0 self._state = self._SYNC0 self._frame_type = 0 self._length = 0 self._remaining = 0 self._body = bytearray() # type + length bytes + payload (CRC input) self._payload = bytearray() self._crc = 0 def feed(self, data: bytes) -> list[Frame]: frames: list[Frame] = [] for byte in data: frame = self._step(byte) if frame is not None: frames.append(frame) return frames def _step(self, byte: int) -> Frame | None: state = self._state if state == self._SYNC0: if byte == 0xA5: self._state = self._SYNC1 else: self.discarded_bytes += 1 return None if state == self._SYNC1: if byte == 0x5A: self._state = self._TYPE elif byte == 0xA5: self._state = self._SYNC1 self.discarded_bytes += 1 else: self._state = self._SYNC0 self.discarded_bytes += 2 return None if state == self._TYPE: self._frame_type = byte self._body = bytearray([byte]) self._state = self._LEN_LO return None if state == self._LEN_LO: self._length = byte self._body.append(byte) self._state = self._LEN_HI return None if state == self._LEN_HI: self._length |= byte << 8 self._body.append(byte) self._remaining = self._length self._payload = bytearray() self._state = self._PAYLOAD if self._length else self._CRC_LO return None if state == self._PAYLOAD: self._payload.append(byte) self._body.append(byte) self._remaining -= 1 if self._remaining == 0: self._state = self._CRC_LO return None if state == self._CRC_LO: self._crc = byte self._state = self._CRC_HI return None # _CRC_HI self._crc |= byte << 8 self._state = self._SYNC0 expected = crc16_ccitt_false(bytes(self._body)) if self._crc != expected: self.rejected_frames += 1 self.discarded_bytes += len(self._payload) + 7 return Frame(self._frame_type, bytes(self._payload), self._crc == expected) def decode_frame(raw: bytes) -> Frame: """Decode one complete frame from ``raw`` (must be exactly one frame).""" if len(raw)<7 or raw[:2]!=PREAMBLE or len(raw)!=int.from_bytes(raw[3:5],'little')+7: raise ValueError('expected exactly one complete A5 5A frame') frames = FrameParser().feed(raw) if not frames: raise ValueError("no complete frame in input") return frames[0] # Fixed contract vectors (verified independently against this codec by the # test suite; they must never be regenerated by the RTL under test). VECTOR_GET_ALL = bytes.fromhex("A55A020000FCA2") VECTOR_GET_ALL_ACK = bytes.fromhex("A55A800400020000 00FEB1".replace(" ", "")) VECTOR_KEEPALIVE = bytes.fromhex("A55A0500006C27")