hth_protocol.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. """Unified Prod2U host protocol codec (single 8-bit length frame protocol).
  2. Wire format (both 6400-front-rear and mrdimm-chamber products):
  3. A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC:u16le
  4. CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, no reflection, xorout 0.
  5. CRC covers TYPE + LENGTH + PAYLOAD; the A5 5A preamble is not covered.
  6. Total bytes = LENGTH + 6.
  7. """
  8. from __future__ import annotations
  9. from dataclasses import dataclass
  10. from enum import IntEnum
  11. PREAMBLE = b"\xA5\x5A"
  12. PREAMBLE_BYTES = (0xA5, 0x5A)
  13. HEADER_SIZE = 4 # preamble(2) + type(1) + length(1)
  14. FRAME_OVERHEAD = 6 # preamble(2) + type(1) + length(1) + crc(2)
  15. MAX_PAYLOAD = 0xFF
  16. def crc16_ccitt_false(data: bytes | bytearray | memoryview, initial: int = 0xFFFF) -> int:
  17. crc = initial & 0xFFFF
  18. for byte in data:
  19. crc ^= (byte & 0xFF) << 8
  20. for _ in range(8):
  21. if crc & 0x8000:
  22. crc = ((crc << 1) ^ 0x1021) & 0xFFFF
  23. else:
  24. crc = (crc << 1) & 0xFFFF
  25. return crc
  26. class FrameType(IntEnum):
  27. SET_ALL = 0x01
  28. GET_ALL = 0x02
  29. HEARTBEAT = 0x03
  30. GET_DATA = 0x42
  31. MOTOR_DONE = 0x50
  32. BEACON = 0x51
  33. DIAGNOSTIC = 0x52
  34. SET_ACK = 0x81
  35. GET_ACK = 0x82
  36. HEARTBEAT_ACK = 0x83
  37. NACK = 0xC0
  38. Type = FrameType
  39. class NackReason(IntEnum):
  40. UNSUPPORTED = 0x01
  41. BAD_LENGTH = 0x02
  42. BAD_VALUE = 0x03
  43. QUEUE_FULL = 0x04
  44. BUSY = 0x05
  45. Status = NackReason
  46. class MotorAction(IntEnum):
  47. NOTHING = 0x00
  48. PUSH_DOWN = 0x01
  49. PUSH_UP = 0x02
  50. STOP_CLEAR = 0xFF
  51. class DoneReason(IntEnum):
  52. COMPLETE = 0x00
  53. LOWER_LIMIT = 0x01
  54. UPPER_LIMIT = 0x02
  55. BOTH_LIMITS = 0x03
  56. @dataclass(frozen=True, slots=True)
  57. class Frame:
  58. frame_type: int
  59. payload: bytes
  60. crc_ok: bool = True
  61. @property
  62. def type_name(self) -> str:
  63. try:
  64. return FrameType(self.frame_type).name
  65. except ValueError:
  66. return f"UNKNOWN(0x{int(self.frame_type) & 0xFF:02X})"
  67. def to_bytes(self) -> bytes:
  68. return encode_frame(self.frame_type, self.payload)
  69. def encode_frame(frame_type: int | FrameType, payload: bytes | bytearray = b"") -> bytes:
  70. p = bytes(payload)
  71. if len(p) > MAX_PAYLOAD:
  72. raise ValueError(f"payload length {len(p)} exceeds maximum {MAX_PAYLOAD}")
  73. t = int(frame_type) & 0xFF
  74. length = len(p)
  75. crc = crc16_ccitt_false(bytes([t, length]) + p)
  76. return PREAMBLE + bytes([t, length]) + p + crc.to_bytes(2, "little")
  77. def decode_frame(data: bytes | bytearray | memoryview) -> Frame:
  78. buf = bytes(data)
  79. if len(buf) < FRAME_OVERHEAD:
  80. raise ValueError("frame shorter than minimum header + CRC")
  81. if buf[:2] != PREAMBLE:
  82. raise ValueError(f"bad preamble: {buf[:2].hex()}")
  83. frame_type = buf[2]
  84. declared_length = buf[3]
  85. expected_total = declared_length + FRAME_OVERHEAD
  86. if len(buf) != expected_total:
  87. raise ValueError(f"frame length mismatch: expected {expected_total}, got {len(buf)}")
  88. payload = buf[4 : 4 + declared_length]
  89. wire_crc = int.from_bytes(buf[-2:], "little")
  90. computed_crc = crc16_ccitt_false(buf[2:-2])
  91. crc_ok = (wire_crc == computed_crc)
  92. return Frame(frame_type=frame_type, payload=payload, crc_ok=crc_ok)