hth_protocol.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. """Unified Prod2U host protocol codec (16-bit length, 2026 contract).
  2. Wire format (both 6400-front-rear and mrdimm-chamber products):
  3. A5 5A | TYPE:u8 | LENGTH:u16le | PAYLOAD | CRC:u16le
  4. CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, no reflection, xorout 0.
  5. CRC covers TYPE + LENGTH_LOW + LENGTH_HIGH + PAYLOAD; the A5 5A preamble
  6. is not covered.
  7. This module is the independent host-side reference implementation. It is
  8. deliberately written from the protocol contract text, not shared with the
  9. RTL frame parser, so the fixed contract vectors below are a cross-check
  10. between two independent implementations.
  11. Breaking change vs the historical 8-bit-length frames: old consumers must
  12. not be fed these frames and vice versa; there is no legacy autodetect.
  13. """
  14. from __future__ import annotations
  15. from enum import IntEnum
  16. PREAMBLE = b"\xA5\x5A"
  17. HEADER_SIZE = 4 # preamble(2) + type(1) + length(2)... preamble excluded from CRC
  18. MAX_REQUEST_PAYLOAD = 256
  19. MAX_RESPONSE_PAYLOAD = 1024
  20. class Type(IntEnum):
  21. SET_ALL = 0x01
  22. GET_ALL = 0x02
  23. MOTOR_QUEUE_WRITE = 0x03
  24. MOTOR_CONTROL = 0x04
  25. OUTPUT_KEEPALIVE = 0x05
  26. EVENT_READ = 0x08
  27. EVENT_CLEAR = 0x09
  28. ACK_NACK = 0x80
  29. ALL_STATUS_DATA = 0x81
  30. EVENT_DATA = 0x83
  31. REQUEST_TYPES = frozenset(
  32. {
  33. Type.SET_ALL,
  34. Type.GET_ALL,
  35. Type.MOTOR_QUEUE_WRITE,
  36. Type.MOTOR_CONTROL,
  37. Type.OUTPUT_KEEPALIVE,
  38. Type.EVENT_READ,
  39. Type.EVENT_CLEAR,
  40. }
  41. )
  42. RESPONSE_TYPES = frozenset({Type.ACK_NACK, Type.ALL_STATUS_DATA, Type.EVENT_DATA})
  43. class Status(IntEnum):
  44. OK = 0
  45. UNSUPPORTED = 1
  46. BAD_LENGTH = 2
  47. BAD_VALUE = 3
  48. BUSY = 4
  49. QUEUE_FULL = 5
  50. BAD_AXIS = 6
  51. BAD_MODE = 7
  52. BAD_REGISTER = 8
  53. NOT_READY = 9
  54. def crc16_ccitt_false(data: bytes) -> int:
  55. """CRC-16/CCITT-FALSE over ``data`` (MSB first, init 0xFFFF)."""
  56. value = 0xFFFF
  57. for byte in data:
  58. value ^= byte << 8
  59. for _ in range(8):
  60. value = ((value << 1) ^ 0x1021) & 0xFFFF if value & 0x8000 else (value << 1) & 0xFFFF
  61. return value
  62. def encode_frame(frame_type: int, payload: bytes = b"") -> bytes:
  63. """Encode one frame. Payload must be at most 65535 bytes."""
  64. if not 0 <= int(frame_type) <= 0xFF:
  65. raise ValueError("frame type must fit in u8")
  66. if len(payload) > 0xFFFF:
  67. raise ValueError("payload longer than 16-bit length field")
  68. body = bytes([int(frame_type), len(payload) & 0xFF, (len(payload) >> 8) & 0xFF]) + payload
  69. return PREAMBLE + body + crc16_ccitt_false(body).to_bytes(2, "little")
  70. def encode_ack(request_type: int, status: int, detail: int = 0) -> bytes:
  71. """ACK_NACK (0x80): fixed 4-byte payload request_type/status/detail:u16le."""
  72. return encode_frame(
  73. Type.ACK_NACK,
  74. bytes([int(request_type) & 0xFF, int(status) & 0xFF]) + int(detail).to_bytes(2, "little"),
  75. )
  76. class Frame:
  77. __slots__ = ("frame_type", "payload", "crc_ok")
  78. def __init__(self, frame_type: int, payload: bytes, crc_ok: bool) -> None:
  79. self.frame_type = frame_type
  80. self.payload = payload
  81. self.crc_ok = crc_ok
  82. def __repr__(self) -> str: # pragma: no cover - debug aid
  83. return f"Frame(type=0x{self.frame_type:02X}, len={len(self.payload)}, crc_ok={self.crc_ok})"
  84. class FrameParser:
  85. """Streaming byte-at-a-time frame parser.
  86. Semantics required by the contract:
  87. - Syncs on the A5 5A preamble; garbage before a preamble is skipped.
  88. - Once a header is accepted the declared 16-bit length is trusted: the
  89. whole payload plus trailing CRC is consumed even if the CRC fails
  90. (an over-long declared length is consumed, not used to bound RAM).
  91. - An A5 5A inside a payload is never treated as a new frame.
  92. - Frames with bad CRC are surfaced with ``crc_ok=False`` so the caller
  93. can drop them silently; nothing else is emitted for them.
  94. """
  95. _SYNC0, _SYNC1, _TYPE, _LEN_LO, _LEN_HI, _PAYLOAD, _CRC_LO, _CRC_HI = range(8)
  96. def __init__(self) -> None:
  97. self._state = self._SYNC0
  98. self._frame_type = 0
  99. self._length = 0
  100. self._remaining = 0
  101. self._body = bytearray() # type + length bytes + payload (CRC input)
  102. self._payload = bytearray()
  103. self._crc = 0
  104. def feed(self, data: bytes) -> list[Frame]:
  105. frames: list[Frame] = []
  106. for byte in data:
  107. frame = self._step(byte)
  108. if frame is not None:
  109. frames.append(frame)
  110. return frames
  111. def _step(self, byte: int) -> Frame | None:
  112. state = self._state
  113. if state == self._SYNC0:
  114. if byte == 0xA5:
  115. self._state = self._SYNC1
  116. return None
  117. if state == self._SYNC1:
  118. if byte == 0x5A:
  119. self._state = self._TYPE
  120. elif byte == 0xA5:
  121. self._state = self._SYNC1
  122. else:
  123. self._state = self._SYNC0
  124. return None
  125. if state == self._TYPE:
  126. self._frame_type = byte
  127. self._body = bytearray([byte])
  128. self._state = self._LEN_LO
  129. return None
  130. if state == self._LEN_LO:
  131. self._length = byte
  132. self._body.append(byte)
  133. self._state = self._LEN_HI
  134. return None
  135. if state == self._LEN_HI:
  136. self._length |= byte << 8
  137. self._body.append(byte)
  138. self._remaining = self._length
  139. self._payload = bytearray()
  140. self._state = self._PAYLOAD if self._length else self._CRC_LO
  141. return None
  142. if state == self._PAYLOAD:
  143. self._payload.append(byte)
  144. self._body.append(byte)
  145. self._remaining -= 1
  146. if self._remaining == 0:
  147. self._state = self._CRC_LO
  148. return None
  149. if state == self._CRC_LO:
  150. self._crc = byte
  151. self._state = self._CRC_HI
  152. return None
  153. # _CRC_HI
  154. self._crc |= byte << 8
  155. self._state = self._SYNC0
  156. expected = crc16_ccitt_false(bytes(self._body))
  157. return Frame(self._frame_type, bytes(self._payload), self._crc == expected)
  158. def decode_frame(raw: bytes) -> Frame:
  159. """Decode one complete frame from ``raw`` (must be exactly one frame)."""
  160. frames = FrameParser().feed(raw)
  161. if not frames:
  162. raise ValueError("no complete frame in input")
  163. return frames[0]
  164. # Fixed contract vectors (verified independently against this codec by the
  165. # test suite; they must never be regenerated by the RTL under test).
  166. VECTOR_GET_ALL = bytes.fromhex("A55A020000FCA2")
  167. VECTOR_GET_ALL_ACK = bytes.fromhex("A55A800400020000 00FEB1".replace(" ", ""))
  168. VECTOR_KEEPALIVE = bytes.fromhex("A55A0500006C27")