hth_protocol.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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 = 5 # 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.discarded_bytes = 0
  98. self.rejected_frames = 0
  99. self._state = self._SYNC0
  100. self._frame_type = 0
  101. self._length = 0
  102. self._remaining = 0
  103. self._body = bytearray() # type + length bytes + payload (CRC input)
  104. self._payload = bytearray()
  105. self._crc = 0
  106. def feed(self, data: bytes) -> list[Frame]:
  107. frames: list[Frame] = []
  108. for byte in data:
  109. frame = self._step(byte)
  110. if frame is not None:
  111. frames.append(frame)
  112. return frames
  113. def _step(self, byte: int) -> Frame | None:
  114. state = self._state
  115. if state == self._SYNC0:
  116. if byte == 0xA5:
  117. self._state = self._SYNC1
  118. else:
  119. self.discarded_bytes += 1
  120. return None
  121. if state == self._SYNC1:
  122. if byte == 0x5A:
  123. self._state = self._TYPE
  124. elif byte == 0xA5:
  125. self._state = self._SYNC1
  126. self.discarded_bytes += 1
  127. else:
  128. self._state = self._SYNC0
  129. self.discarded_bytes += 2
  130. return None
  131. if state == self._TYPE:
  132. self._frame_type = byte
  133. self._body = bytearray([byte])
  134. self._state = self._LEN_LO
  135. return None
  136. if state == self._LEN_LO:
  137. self._length = byte
  138. self._body.append(byte)
  139. self._state = self._LEN_HI
  140. return None
  141. if state == self._LEN_HI:
  142. self._length |= byte << 8
  143. self._body.append(byte)
  144. self._remaining = self._length
  145. self._payload = bytearray()
  146. self._state = self._PAYLOAD if self._length else self._CRC_LO
  147. return None
  148. if state == self._PAYLOAD:
  149. self._payload.append(byte)
  150. self._body.append(byte)
  151. self._remaining -= 1
  152. if self._remaining == 0:
  153. self._state = self._CRC_LO
  154. return None
  155. if state == self._CRC_LO:
  156. self._crc = byte
  157. self._state = self._CRC_HI
  158. return None
  159. # _CRC_HI
  160. self._crc |= byte << 8
  161. self._state = self._SYNC0
  162. expected = crc16_ccitt_false(bytes(self._body))
  163. if self._crc != expected:
  164. self.rejected_frames += 1
  165. self.discarded_bytes += len(self._payload) + 7
  166. return Frame(self._frame_type, bytes(self._payload), self._crc == expected)
  167. def decode_frame(raw: bytes) -> Frame:
  168. """Decode one complete frame from ``raw`` (must be exactly one frame)."""
  169. if len(raw)<7 or raw[:2]!=PREAMBLE or len(raw)!=int.from_bytes(raw[3:5],'little')+7:
  170. raise ValueError('expected exactly one complete A5 5A frame')
  171. frames = FrameParser().feed(raw)
  172. if not frames:
  173. raise ValueError("no complete frame in input")
  174. return frames[0]
  175. # Fixed contract vectors (verified independently against this codec by the
  176. # test suite; they must never be regenerated by the RTL under test).
  177. VECTOR_GET_ALL = bytes.fromhex("A55A020000FCA2")
  178. VECTOR_GET_ALL_ACK = bytes.fromhex("A55A800400020000 00FEB1".replace(" ", ""))
  179. VECTOR_KEEPALIVE = bytes.fromhex("A55A0500006C27")