prod2u_simple_protocol.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #!/usr/bin/env python3
  2. """Reference model for the frozen 115200 Prod2U frame contract."""
  3. from __future__ import annotations
  4. from dataclasses import dataclass
  5. from enum import IntEnum
  6. from typing import Iterable, Sequence
  7. FRAME_HEADER = b"\xA5\x5A"
  8. PTC_COUNT = 24
  9. FAN_COUNT = 4
  10. TEMPERATURE_COUNT = 27
  11. SET_ALL_PAYLOAD_LENGTH = PTC_COUNT + FAN_COUNT + 2
  12. class FrameType(IntEnum):
  13. SET_ALL = 0x01
  14. GET_TEMPERATURE = 0x02
  15. TEMPERATURE_DATA = 0x82
  16. class ProtocolError(ValueError):
  17. """Raised when a frame violates the frozen protocol contract."""
  18. @dataclass(frozen=True)
  19. class Frame:
  20. frame_type: FrameType
  21. payload: bytes
  22. def crc16_ccitt_false(data: bytes | bytearray | Iterable[int]) -> int:
  23. crc = 0xFFFF
  24. for value in data:
  25. crc ^= (int(value) & 0xFF) << 8
  26. for _ in range(8):
  27. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  28. return crc
  29. def _coerce_type(value: int | FrameType) -> FrameType:
  30. try:
  31. return FrameType(int(value))
  32. except (TypeError, ValueError) as exc:
  33. raise ProtocolError(f"unsupported frame type: {value!r}") from exc
  34. def _expected_length(frame_type: FrameType) -> int:
  35. return {
  36. FrameType.SET_ALL: SET_ALL_PAYLOAD_LENGTH,
  37. FrameType.GET_TEMPERATURE: 0,
  38. FrameType.TEMPERATURE_DATA: TEMPERATURE_COUNT,
  39. }[frame_type]
  40. def encode_frame(frame_type: int | FrameType, payload: bytes | bytearray | Sequence[int]) -> bytes:
  41. kind = _coerce_type(frame_type)
  42. body = bytes(payload)
  43. expected = _expected_length(kind)
  44. if len(body) != expected:
  45. raise ProtocolError(f"{kind.name} payload must be {expected} bytes")
  46. crc = crc16_ccitt_false(bytes((int(kind), len(body))) + body)
  47. return FRAME_HEADER + bytes((int(kind), len(body))) + body + crc.to_bytes(2, "little")
  48. def decode_frame(raw: bytes | bytearray) -> Frame:
  49. packet = bytes(raw)
  50. if len(packet) < 6 or packet[:2] != FRAME_HEADER:
  51. raise ProtocolError("invalid frame header or length")
  52. try:
  53. kind = FrameType(packet[2])
  54. except ValueError as exc:
  55. raise ProtocolError(f"unsupported frame type: 0x{packet[2]:02X}") from exc
  56. payload_length = packet[3]
  57. if len(packet) != payload_length + 6:
  58. raise ProtocolError("frame length mismatch")
  59. payload = packet[4 : 4 + payload_length]
  60. expected = _expected_length(kind)
  61. if payload_length != expected:
  62. raise ProtocolError(f"{kind.name} payload must be {expected} bytes")
  63. actual_crc = int.from_bytes(packet[-2:], "little")
  64. expected_crc = crc16_ccitt_false(packet[2:-2])
  65. if actual_crc != expected_crc:
  66. raise ProtocolError("CRC mismatch")
  67. return Frame(kind, payload)
  68. def _checked_bytes(values: Iterable[int], count: int, name: str) -> bytes:
  69. body = bytes(values)
  70. if len(body) != count:
  71. raise ValueError(f"{name} must contain {count} bytes")
  72. return body
  73. def build_set_all(ptc: Iterable[int], fan: Iterable[int], inlet_dir: int, outlet_dir: int) -> bytes:
  74. if inlet_dir not in (0, 1) or outlet_dir not in (0, 1):
  75. raise ValueError("motor directions must be 0 or 1")
  76. payload = _checked_bytes(ptc, PTC_COUNT, "ptc")
  77. payload += _checked_bytes(fan, FAN_COUNT, "fan")
  78. return encode_frame(FrameType.SET_ALL, payload + bytes((inlet_dir, outlet_dir)))
  79. def build_get_temperature() -> bytes:
  80. return encode_frame(FrameType.GET_TEMPERATURE, b"")
  81. def build_temperature_data(values: Iterable[int]) -> bytes:
  82. return encode_frame(FrameType.TEMPERATURE_DATA, _checked_bytes(values, TEMPERATURE_COUNT, "temperature"))
  83. def decode_temperature_data(frame: Frame) -> tuple[int, ...]:
  84. if frame.frame_type is not FrameType.TEMPERATURE_DATA:
  85. raise ProtocolError("frame is not TEMPERATURE_DATA")
  86. return tuple(frame.payload)