prod2u_simple_protocol.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. #!/usr/bin/env python3
  2. """Reference model for the frozen Prod2U door-temperature frame contract."""
  3. from __future__ import annotations
  4. from dataclasses import dataclass
  5. from enum import IntEnum
  6. import json
  7. from pathlib import Path
  8. from typing import Iterable, Sequence
  9. _PROJECT_PATH = Path(__file__).resolve().parents[1] / "projects" / "prod2u-door-temp" / "project.json"
  10. _PROJECT = json.loads(_PROJECT_PATH.read_text(encoding="utf-8"))
  11. _OUTPUTS = _PROJECT["outputs"]
  12. _PROTOCOL = _PROJECT["protocol"]
  13. _SET_ALL = _PROTOCOL["set_all"]
  14. _CRC = _PROTOCOL["crc"]
  15. _COMMANDS = _PROTOCOL["commands"]
  16. FRAME_HEADER = bytes.fromhex(_PROTOCOL["header_hex"])
  17. PTC_COUNT = len(_OUTPUTS["ptc_channels"])
  18. FAN_COUNT = len(_OUTPUTS["fan_channels"])
  19. TEMPERATURE_COUNT = _PROJECT["temperature"]["value_count"]
  20. SET_ALL_PAYLOAD_LENGTH = _SET_ALL["payload_length"]
  21. DUTY_MIN = _SET_ALL["duty_min"]
  22. DUTY_MAX = _SET_ALL["duty_max"]
  23. MOTOR_COMMANDS = tuple(_SET_ALL["motor_values"])
  24. HEARTBEAT_MOTOR_COMMAND = _SET_ALL["heartbeat"][0]
  25. CRC_POLYNOMIAL = _CRC["polynomial"]
  26. CRC_INITIAL = _CRC["initial"]
  27. class FrameType(IntEnum):
  28. SET_ALL = _COMMANDS["set_all"]
  29. GET_TEMPERATURE = _COMMANDS["get_temperature"]
  30. TEMPERATURE_DATA = _COMMANDS["temperature_data"]
  31. class ProtocolError(ValueError):
  32. """Raised when a frame violates the frozen protocol contract."""
  33. @dataclass(frozen=True)
  34. class Frame:
  35. frame_type: FrameType
  36. payload: bytes
  37. def crc16_ccitt_false(data: bytes | bytearray | Iterable[int]) -> int:
  38. crc = CRC_INITIAL
  39. for value in data:
  40. crc ^= (int(value) & 0xFF) << 8
  41. for _ in range(8):
  42. crc = ((crc << 1) ^ CRC_POLYNOMIAL) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  43. return crc
  44. def _coerce_type(value: int | FrameType) -> FrameType:
  45. try:
  46. return FrameType(int(value))
  47. except (TypeError, ValueError) as exc:
  48. raise ProtocolError(f"unsupported frame type: {value!r}") from exc
  49. def _expected_length(frame_type: FrameType) -> int:
  50. return {
  51. FrameType.SET_ALL: SET_ALL_PAYLOAD_LENGTH,
  52. FrameType.GET_TEMPERATURE: 0,
  53. FrameType.TEMPERATURE_DATA: TEMPERATURE_COUNT,
  54. }[frame_type]
  55. def encode_frame(frame_type: int | FrameType, payload: bytes | bytearray | Sequence[int]) -> bytes:
  56. kind = _coerce_type(frame_type)
  57. body = bytes(payload)
  58. expected = _expected_length(kind)
  59. if len(body) != expected:
  60. raise ProtocolError(f"{kind.name} payload must be {expected} bytes")
  61. crc = crc16_ccitt_false(bytes((int(kind), len(body))) + body)
  62. return FRAME_HEADER + bytes((int(kind), len(body))) + body + crc.to_bytes(2, "little")
  63. def decode_frame(raw: bytes | bytearray) -> Frame:
  64. packet = bytes(raw)
  65. if len(packet) < 6 or packet[:2] != FRAME_HEADER:
  66. raise ProtocolError("invalid frame header or length")
  67. try:
  68. kind = FrameType(packet[2])
  69. except ValueError as exc:
  70. raise ProtocolError(f"unsupported frame type: 0x{packet[2]:02X}") from exc
  71. payload_length = packet[3]
  72. if len(packet) != payload_length + 6:
  73. raise ProtocolError("frame length mismatch")
  74. payload = packet[4 : 4 + payload_length]
  75. expected = _expected_length(kind)
  76. if payload_length != expected:
  77. raise ProtocolError(f"{kind.name} payload must be {expected} bytes")
  78. actual_crc = int.from_bytes(packet[-2:], "little")
  79. expected_crc = crc16_ccitt_false(packet[2:-2])
  80. if actual_crc != expected_crc:
  81. raise ProtocolError("CRC mismatch")
  82. return Frame(kind, payload)
  83. def _checked_duty_bytes(values: Iterable[int], count: int, name: str) -> bytes:
  84. items = tuple(values)
  85. if len(items) != count:
  86. raise ValueError(f"{name} must contain {count} bytes")
  87. if any(not isinstance(value, int) or not DUTY_MIN <= value <= DUTY_MAX for value in items):
  88. raise ValueError(f"{name} values must be in the range {DUTY_MIN}..{DUTY_MAX}")
  89. return bytes(items)
  90. def _checked_temperature_bytes(values: Iterable[int]) -> bytes:
  91. items = tuple(values)
  92. if len(items) != TEMPERATURE_COUNT:
  93. raise ValueError(f"temperature must contain {TEMPERATURE_COUNT} bytes")
  94. if any(not isinstance(value, int) or not 0 <= value <= 0xFF for value in items):
  95. raise ValueError("temperature values must be in the range 0..255")
  96. return bytes(items)
  97. def _checked_motor_command(value: int, name: str) -> int:
  98. if value not in MOTOR_COMMANDS:
  99. raise ValueError(f"{name} must be one of {MOTOR_COMMANDS}")
  100. return value
  101. def build_set_all(ptc: Iterable[int], fan: Iterable[int], x_command: int, y_command: int) -> bytes:
  102. x_command = _checked_motor_command(x_command, "x motor command")
  103. y_command = _checked_motor_command(y_command, "y motor command")
  104. payload = _checked_duty_bytes(ptc, PTC_COUNT, "ptc")
  105. payload += _checked_duty_bytes(fan, FAN_COUNT, "fan")
  106. return encode_frame(FrameType.SET_ALL, payload + bytes((x_command, y_command)))
  107. def build_get_temperature() -> bytes:
  108. return encode_frame(FrameType.GET_TEMPERATURE, b"")
  109. def build_temperature_data(values: Iterable[int]) -> bytes:
  110. return encode_frame(FrameType.TEMPERATURE_DATA, _checked_temperature_bytes(values))
  111. def decode_temperature_data(frame: Frame) -> tuple[int, ...]:
  112. if frame.frame_type is not FrameType.TEMPERATURE_DATA:
  113. raise ProtocolError("frame is not TEMPERATURE_DATA")
  114. return tuple(frame.payload)