hth_protocol.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. GET_DATA = 0x42
  30. MOTOR_DONE = 0x50
  31. SET_ACK = 0x81
  32. GET_ACK = 0x82
  33. NACK = 0xC0
  34. Type = FrameType
  35. class NackReason(IntEnum):
  36. UNSUPPORTED = 0x01
  37. BAD_LENGTH = 0x02
  38. BAD_VALUE = 0x03
  39. QUEUE_FULL = 0x04
  40. BUSY = 0x05
  41. Status = NackReason
  42. class MotorAction(IntEnum):
  43. NOTHING = 0x00
  44. PUSH_DOWN = 0x01
  45. PUSH_UP = 0x02
  46. STOP_CLEAR = 0xFF
  47. class DoneReason(IntEnum):
  48. COMPLETE = 0x00
  49. LOWER_LIMIT = 0x01
  50. UPPER_LIMIT = 0x02
  51. BOTH_LIMITS = 0x03
  52. @dataclass(frozen=True, slots=True)
  53. class Frame:
  54. frame_type: int
  55. payload: bytes
  56. crc_ok: bool = True
  57. @property
  58. def type_name(self) -> str:
  59. try:
  60. return FrameType(self.frame_type).name
  61. except ValueError:
  62. return f"UNKNOWN(0x{int(self.frame_type) & 0xFF:02X})"
  63. def to_bytes(self) -> bytes:
  64. return encode_frame(self.frame_type, self.payload)
  65. def encode_frame(frame_type: int | FrameType, payload: bytes | bytearray = b"") -> bytes:
  66. p = bytes(payload)
  67. if len(p) > MAX_PAYLOAD:
  68. raise ValueError(f"payload length {len(p)} exceeds maximum {MAX_PAYLOAD}")
  69. t = int(frame_type) & 0xFF
  70. length = len(p)
  71. crc = crc16_ccitt_false(bytes([t, length]) + p)
  72. return PREAMBLE + bytes([t, length]) + p + crc.to_bytes(2, "little")
  73. def decode_frame(data: bytes | bytearray | memoryview) -> Frame:
  74. buf = bytes(data)
  75. if len(buf) < FRAME_OVERHEAD:
  76. raise ValueError("frame shorter than minimum header + CRC")
  77. if buf[:2] != PREAMBLE:
  78. raise ValueError(f"bad preamble: {buf[:2].hex()}")
  79. frame_type = buf[2]
  80. declared_length = buf[3]
  81. expected_total = declared_length + FRAME_OVERHEAD
  82. if len(buf) != expected_total:
  83. raise ValueError(f"frame length mismatch: expected {expected_total}, got {len(buf)}")
  84. payload = buf[4 : 4 + declared_length]
  85. wire_crc = int.from_bytes(buf[-2:], "little")
  86. computed_crc = crc16_ccitt_false(buf[2:-2])
  87. crc_ok = (wire_crc == computed_crc)
  88. return Frame(frame_type=frame_type, payload=payload, crc_ok=crc_ok)