"""Unified Prod2U host protocol codec (single 8-bit length frame protocol). Wire format (both 6400-front-rear and mrdimm-chamber products): A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC:u16le CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, no reflection, xorout 0. CRC covers TYPE + LENGTH + PAYLOAD; the A5 5A preamble is not covered. Total bytes = LENGTH + 6. """ from __future__ import annotations from dataclasses import dataclass from enum import IntEnum PREAMBLE = b"\xA5\x5A" PREAMBLE_BYTES = (0xA5, 0x5A) HEADER_SIZE = 4 # preamble(2) + type(1) + length(1) FRAME_OVERHEAD = 6 # preamble(2) + type(1) + length(1) + crc(2) MAX_PAYLOAD = 0xFF def crc16_ccitt_false(data: bytes | bytearray | memoryview, initial: int = 0xFFFF) -> int: crc = initial & 0xFFFF for byte in data: crc ^= (byte & 0xFF) << 8 for _ in range(8): if crc & 0x8000: crc = ((crc << 1) ^ 0x1021) & 0xFFFF else: crc = (crc << 1) & 0xFFFF return crc class FrameType(IntEnum): SET_ALL = 0x01 GET_ALL = 0x02 HEARTBEAT = 0x03 GET_DATA = 0x42 MOTOR_DONE = 0x50 BEACON = 0x51 DIAGNOSTIC = 0x52 SET_ACK = 0x81 GET_ACK = 0x82 HEARTBEAT_ACK = 0x83 NACK = 0xC0 Type = FrameType class NackReason(IntEnum): UNSUPPORTED = 0x01 BAD_LENGTH = 0x02 BAD_VALUE = 0x03 QUEUE_FULL = 0x04 BUSY = 0x05 Status = NackReason class MotorAction(IntEnum): NOTHING = 0x00 PUSH_DOWN = 0x01 PUSH_UP = 0x02 STOP_CLEAR = 0xFF class DoneReason(IntEnum): COMPLETE = 0x00 LOWER_LIMIT = 0x01 UPPER_LIMIT = 0x02 BOTH_LIMITS = 0x03 @dataclass(frozen=True, slots=True) class Frame: frame_type: int payload: bytes crc_ok: bool = True @property def type_name(self) -> str: try: return FrameType(self.frame_type).name except ValueError: return f"UNKNOWN(0x{int(self.frame_type) & 0xFF:02X})" def to_bytes(self) -> bytes: return encode_frame(self.frame_type, self.payload) def encode_frame(frame_type: int | FrameType, payload: bytes | bytearray = b"") -> bytes: p = bytes(payload) if len(p) > MAX_PAYLOAD: raise ValueError(f"payload length {len(p)} exceeds maximum {MAX_PAYLOAD}") t = int(frame_type) & 0xFF length = len(p) crc = crc16_ccitt_false(bytes([t, length]) + p) return PREAMBLE + bytes([t, length]) + p + crc.to_bytes(2, "little") def decode_frame(data: bytes | bytearray | memoryview) -> Frame: buf = bytes(data) if len(buf) < FRAME_OVERHEAD: raise ValueError("frame shorter than minimum header + CRC") if buf[:2] != PREAMBLE: raise ValueError(f"bad preamble: {buf[:2].hex()}") frame_type = buf[2] declared_length = buf[3] expected_total = declared_length + FRAME_OVERHEAD if len(buf) != expected_total: raise ValueError(f"frame length mismatch: expected {expected_total}, got {len(buf)}") payload = buf[4 : 4 + declared_length] wire_crc = int.from_bytes(buf[-2:], "little") computed_crc = crc16_ccitt_false(buf[2:-2]) crc_ok = (wire_crc == computed_crc) return Frame(frame_type=frame_type, payload=payload, crc_ok=crc_ok)