prod2u_simple_protocol.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. #!/usr/bin/env python3
  2. """Reference model for the Prod2U door-percent SET_ALL / status contract.
  3. Reads ``projects/prod2u-door-temp/project.json`` when present, but stays resilient
  4. if another agent is mid-edit: door fields are always percent 0..100, and frame
  5. types ``0x03`` / ``0x83`` are always accepted even when ``project.json`` still
  6. lists the legacy jog-only command table.
  7. """
  8. from __future__ import annotations
  9. from dataclasses import dataclass
  10. from enum import IntEnum, IntFlag
  11. import json
  12. from pathlib import Path
  13. from typing import Iterable, Sequence
  14. _PROJECT_PATH = Path(__file__).resolve().parents[1] / "projects" / "prod2u-door-temp" / "project.json"
  15. try:
  16. _PROJECT = json.loads(_PROJECT_PATH.read_text(encoding="utf-8"))
  17. except (OSError, json.JSONDecodeError):
  18. _PROJECT = {}
  19. _OUTPUTS = _PROJECT.get("outputs", {})
  20. _PROTOCOL = _PROJECT.get("protocol", {})
  21. _SET_ALL = _PROTOCOL.get("set_all", {})
  22. _CRC = _PROTOCOL.get("crc", {})
  23. _COMMANDS = _PROTOCOL.get("commands", {})
  24. _TEMPERATURE = _PROJECT.get("temperature", {})
  25. FRAME_HEADER = bytes.fromhex(_PROTOCOL.get("header_hex", "A55A"))
  26. CHAMBER_PTC_COUNT = int(_OUTPUTS.get("chamber_ptc_count", _SET_ALL.get("chamber_ptc_count", 4)))
  27. FAN_COUNT = len(_OUTPUTS.get("fan_channels", [0, 1, 2, 3])) or 4
  28. TEMPERATURE_COUNT = int(_TEMPERATURE.get("value_count", 27))
  29. SET_ALL_PAYLOAD_LENGTH = int(_SET_ALL.get("payload_length", 11))
  30. LEGACY_SET_ALL_PAYLOAD_LENGTH = int(_SET_ALL.get("legacy_payload_length_rejected", 14))
  31. DUTY_MIN = int(_SET_ALL.get("duty_min", 0))
  32. DUTY_MAX = int(_SET_ALL.get("duty_max", 100))
  33. DOOR_PERCENT_MIN = 0
  34. DOOR_PERCENT_MAX = 100
  35. MOTOR_STATUS_PAYLOAD_LENGTH = 31
  36. MOTOR_STATUS_FRAME_LENGTH = MOTOR_STATUS_PAYLOAD_LENGTH + 6
  37. AXIS_STATUS_BYTES = 10
  38. CRC_POLYNOMIAL = int(_CRC.get("polynomial", 4129))
  39. CRC_INITIAL = int(_CRC.get("initial", 65535))
  40. # Golden HEARTBEAT request / ack frames (empty payload)
  41. HEARTBEAT_GOLDEN = bytes.fromhex("A55A03005C48")
  42. HEARTBEAT_ACK_GOLDEN = bytes.fromhex("A55A8300C453")
  43. GET_MOTOR_STATUS_GOLDEN = HEARTBEAT_GOLDEN
  44. class FrameType(IntEnum):
  45. SET_ALL = int(_COMMANDS.get("set_all", 0x01))
  46. GET_TEMPERATURE = int(_COMMANDS.get("get_temperature", 0x02))
  47. GET_MOTOR_STATUS = int(_COMMANDS.get("get_motor_status", 0x03))
  48. HEARTBEAT = 0x03
  49. TEMPERATURE_DATA = int(_COMMANDS.get("temperature_data", 0x82))
  50. MOTOR_STATUS_DATA = int(_COMMANDS.get("motor_status_data", 0x83))
  51. HEARTBEAT_ACK = 0x83
  52. BEACON = 0x51
  53. class AxisState(IntEnum):
  54. CAL_SEEK_CLOSE = 0
  55. CAL_MEASURE_OPEN = 1
  56. IDLE = 2
  57. MOVE_OPEN = 3
  58. MOVE_CLOSE = 4
  59. WAIT_REPLAN = 5
  60. FAULT = 6
  61. class AxisFlags(IntFlag):
  62. OPEN_LIMIT = 0x01
  63. CLOSE_LIMIT = 0x02
  64. CALIBRATED = 0x04
  65. MOVING = 0x08
  66. ENDPOINT_MODE = 0x10
  67. TARGET_VALID = 0x20
  68. REPLAN_PENDING = 0x40
  69. RESERVED = 0x80
  70. class FaultCode(IntEnum):
  71. NONE = 0
  72. BOTH_LIMITS_ACTIVE = 1
  73. CAL_CLOSE_TIMEOUT = 2
  74. CAL_OPEN_TIMEOUT = 3
  75. INVALID_ZERO_OR_TINY_TRAVEL = 4
  76. ENDPOINT_TIMEOUT = 5
  77. class GlobalStatusBits(IntFlag):
  78. X_CALIBRATED = 0x01
  79. Y_CALIBRATED = 0x02
  80. Z_CALIBRATED = 0x04
  81. X_FAULT = 0x08
  82. Y_FAULT = 0x10
  83. Z_FAULT = 0x20
  84. STARTUP_COMPLETE = 0x40
  85. WATCHDOG_TRIPPED = 0x80
  86. class ProtocolError(ValueError):
  87. """Raised when a frame violates the frozen protocol contract."""
  88. @dataclass(frozen=True)
  89. class Frame:
  90. frame_type: FrameType
  91. payload: bytes
  92. @dataclass(frozen=True)
  93. class AxisMotorStatus:
  94. state: AxisState
  95. flags: AxisFlags
  96. requested_percent: int
  97. current_position: int
  98. target_position: int
  99. travel_steps: int
  100. fault_code: FaultCode
  101. @dataclass(frozen=True)
  102. class MotorStatus:
  103. global_status: GlobalStatusBits
  104. x: AxisMotorStatus
  105. y: AxisMotorStatus
  106. z: AxisMotorStatus
  107. @property
  108. def startup_complete(self) -> bool:
  109. return bool(self.global_status & GlobalStatusBits.STARTUP_COMPLETE)
  110. @property
  111. def watchdog_tripped(self) -> bool:
  112. return bool(self.global_status & GlobalStatusBits.WATCHDOG_TRIPPED)
  113. def mid_target(travel: int, percent: int) -> int:
  114. """Half-up mid-position clamp; same contract as ``door_percent_planner_ref``."""
  115. if not isinstance(travel, int) or not isinstance(percent, int):
  116. raise ValueError("travel and percent must be integers")
  117. if travel < 2:
  118. raise ValueError("travel must be >= 2 for mid targets")
  119. if not 1 <= percent <= 99:
  120. raise ValueError("mid percent must be in the range 1..99")
  121. return max(1, min(travel - 1, (travel * percent + 50) // 100))
  122. def crc16_ccitt_false(data: bytes | bytearray | Iterable[int]) -> int:
  123. crc = CRC_INITIAL
  124. for value in data:
  125. crc ^= (int(value) & 0xFF) << 8
  126. for _ in range(8):
  127. crc = ((crc << 1) ^ CRC_POLYNOMIAL) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  128. return crc
  129. def _coerce_type(value: int | FrameType) -> FrameType:
  130. try:
  131. return FrameType(int(value))
  132. except (TypeError, ValueError) as exc:
  133. raise ProtocolError(f"unsupported frame type: {value!r}") from exc
  134. def _expected_length(frame_type: FrameType) -> int:
  135. return {
  136. FrameType.SET_ALL: SET_ALL_PAYLOAD_LENGTH,
  137. FrameType.GET_TEMPERATURE: 0,
  138. FrameType.GET_MOTOR_STATUS: 0,
  139. FrameType.TEMPERATURE_DATA: TEMPERATURE_COUNT,
  140. FrameType.MOTOR_STATUS_DATA: MOTOR_STATUS_PAYLOAD_LENGTH,
  141. }[frame_type]
  142. def encode_frame(frame_type: int | FrameType, payload: bytes | bytearray | Sequence[int]) -> bytes:
  143. kind = _coerce_type(frame_type)
  144. body = bytes(payload)
  145. expected = _expected_length(kind)
  146. if len(body) != expected:
  147. raise ProtocolError(f"{kind.name} payload must be {expected} bytes")
  148. crc = crc16_ccitt_false(bytes((int(kind), len(body))) + body)
  149. return FRAME_HEADER + bytes((int(kind), len(body))) + body + crc.to_bytes(2, "little")
  150. def decode_frame(raw: bytes | bytearray) -> Frame:
  151. packet = bytes(raw)
  152. if len(packet) < 6 or packet[:2] != FRAME_HEADER:
  153. raise ProtocolError("invalid frame header or length")
  154. try:
  155. kind = FrameType(packet[2])
  156. except ValueError as exc:
  157. raise ProtocolError(f"unsupported frame type: 0x{packet[2]:02X}") from exc
  158. payload_length = packet[3]
  159. if len(packet) != payload_length + 6:
  160. raise ProtocolError("frame length mismatch")
  161. payload = packet[4 : 4 + payload_length]
  162. expected = _expected_length(kind)
  163. if payload_length != expected:
  164. raise ProtocolError(f"{kind.name} payload must be {expected} bytes")
  165. actual_crc = int.from_bytes(packet[-2:], "little")
  166. expected_crc = crc16_ccitt_false(packet[2:-2])
  167. if actual_crc != expected_crc:
  168. raise ProtocolError("CRC mismatch")
  169. return Frame(kind, payload)
  170. def _checked_duty_bytes(values: Iterable[int], count: int, name: str) -> bytes:
  171. items = tuple(values)
  172. if len(items) != count:
  173. raise ValueError(f"{name} must contain {count} bytes")
  174. if any(not isinstance(value, int) or not DUTY_MIN <= value <= DUTY_MAX for value in items):
  175. raise ValueError(f"{name} values must be in the range {DUTY_MIN}..{DUTY_MAX}")
  176. return bytes(items)
  177. def _checked_temperature_bytes(values: Iterable[int]) -> bytes:
  178. items = tuple(values)
  179. if len(items) != TEMPERATURE_COUNT:
  180. raise ValueError(f"temperature must contain {TEMPERATURE_COUNT} bytes")
  181. if any(not isinstance(value, int) or not 0 <= value <= 0xFF for value in items):
  182. raise ValueError("temperature values must be in the range 0..255")
  183. return bytes(items)
  184. def _checked_door_percent(value: int, name: str) -> int:
  185. if not isinstance(value, int) or not DOOR_PERCENT_MIN <= value <= DOOR_PERCENT_MAX:
  186. raise ValueError(f"{name} must be in the range {DOOR_PERCENT_MIN}..{DOOR_PERCENT_MAX}")
  187. return value
  188. def build_set_all(
  189. fan: Iterable[int],
  190. chamber_ptc: Iterable[int],
  191. z_percent: int,
  192. x_percent: int,
  193. y_percent: int,
  194. ) -> bytes:
  195. z_percent = _checked_door_percent(z_percent, "z_percent")
  196. x_percent = _checked_door_percent(x_percent, "x_percent")
  197. y_percent = _checked_door_percent(y_percent, "y_percent")
  198. payload = _checked_duty_bytes(fan, FAN_COUNT, "fan")
  199. payload += _checked_duty_bytes(chamber_ptc, CHAMBER_PTC_COUNT, "chamber ptc")
  200. payload += bytes((z_percent, x_percent, y_percent))
  201. return encode_frame(FrameType.SET_ALL, payload)
  202. def build_get_temperature() -> bytes:
  203. return encode_frame(FrameType.GET_TEMPERATURE, b"")
  204. def build_get_motor_status() -> bytes:
  205. frame = encode_frame(FrameType.GET_MOTOR_STATUS, b"")
  206. if frame != GET_MOTOR_STATUS_GOLDEN:
  207. raise ProtocolError(
  208. f"GET_MOTOR_STATUS golden mismatch: got {frame.hex(' ').upper()}, "
  209. f"expected {GET_MOTOR_STATUS_GOLDEN.hex(' ').upper()}"
  210. )
  211. return frame
  212. def build_temperature_data(values: Iterable[int]) -> bytes:
  213. return encode_frame(FrameType.TEMPERATURE_DATA, _checked_temperature_bytes(values))
  214. def decode_temperature_data(frame: Frame) -> tuple[int, ...]:
  215. if frame.frame_type is not FrameType.TEMPERATURE_DATA:
  216. raise ProtocolError("frame is not TEMPERATURE_DATA")
  217. return tuple(frame.payload)
  218. def _u16_le(payload: bytes, offset: int) -> int:
  219. return int.from_bytes(payload[offset : offset + 2], "little")
  220. def _parse_axis_status(raw: bytes) -> AxisMotorStatus:
  221. if len(raw) != AXIS_STATUS_BYTES:
  222. raise ProtocolError(f"axis status must be {AXIS_STATUS_BYTES} bytes")
  223. try:
  224. state = AxisState(raw[0])
  225. except ValueError as exc:
  226. raise ProtocolError(f"unsupported axis state: 0x{raw[0]:02X}") from exc
  227. flags = AxisFlags(raw[1])
  228. if flags & AxisFlags.RESERVED:
  229. raise ProtocolError("axis flags reserved bit must be 0")
  230. requested = raw[2]
  231. if not DOOR_PERCENT_MIN <= requested <= DOOR_PERCENT_MAX:
  232. raise ProtocolError(f"requested_percent out of range: {requested}")
  233. try:
  234. fault = FaultCode(raw[9])
  235. except ValueError as exc:
  236. raise ProtocolError(f"unsupported fault_code: 0x{raw[9]:02X}") from exc
  237. return AxisMotorStatus(
  238. state=state,
  239. flags=flags,
  240. requested_percent=requested,
  241. current_position=_u16_le(raw, 3),
  242. target_position=_u16_le(raw, 5),
  243. travel_steps=_u16_le(raw, 7),
  244. fault_code=fault,
  245. )
  246. def decode_motor_status_data(frame: Frame | bytes | bytearray) -> MotorStatus:
  247. if isinstance(frame, (bytes, bytearray)):
  248. frame = decode_frame(frame)
  249. if frame.frame_type is not FrameType.MOTOR_STATUS_DATA:
  250. raise ProtocolError("frame is not MOTOR_STATUS_DATA")
  251. payload = frame.payload
  252. if len(payload) != MOTOR_STATUS_PAYLOAD_LENGTH:
  253. raise ProtocolError(f"MOTOR_STATUS_DATA payload must be {MOTOR_STATUS_PAYLOAD_LENGTH} bytes")
  254. return MotorStatus(
  255. global_status=GlobalStatusBits(payload[0]),
  256. x=_parse_axis_status(payload[1:11]),
  257. y=_parse_axis_status(payload[11:21]),
  258. z=_parse_axis_status(payload[21:31]),
  259. )
  260. def build_motor_status_data(
  261. global_status: int,
  262. x: AxisMotorStatus | Sequence[int] | bytes,
  263. y: AxisMotorStatus | Sequence[int] | bytes,
  264. z: AxisMotorStatus | Sequence[int] | bytes,
  265. ) -> bytes:
  266. """Encode a 31-byte MOTOR_STATUS_DATA frame (host/sim helper)."""
  267. def _axis_bytes(axis: AxisMotorStatus | Sequence[int] | bytes) -> bytes:
  268. if isinstance(axis, AxisMotorStatus):
  269. if axis.flags & AxisFlags.RESERVED:
  270. raise ValueError("axis flags reserved bit must be 0")
  271. return bytes(
  272. (
  273. int(axis.state) & 0xFF,
  274. int(axis.flags) & 0xFF,
  275. int(axis.requested_percent) & 0xFF,
  276. )
  277. ) + int(axis.current_position).to_bytes(2, "little") + int(axis.target_position).to_bytes(
  278. 2, "little"
  279. ) + int(axis.travel_steps).to_bytes(2, "little") + bytes((int(axis.fault_code) & 0xFF,))
  280. raw = bytes(axis)
  281. if len(raw) != AXIS_STATUS_BYTES:
  282. raise ValueError(f"axis status must be {AXIS_STATUS_BYTES} bytes")
  283. return raw
  284. payload = bytes((int(global_status) & 0xFF,)) + _axis_bytes(x) + _axis_bytes(y) + _axis_bytes(z)
  285. return encode_frame(FrameType.MOTOR_STATUS_DATA, payload)
  286. SET_ALL_6400_PAYLOAD_LENGTH = 32
  287. PTC_6400_COUNT = 24
  288. FAN_6400_COUNT = 8
  289. def encode_frame_raw(frame_type: int, payload: bytes | bytearray | Sequence[int]) -> bytes:
  290. """Shared A5 5A / CRC-16/CCITT-FALSE encoder without project length tables."""
  291. body = bytes(payload)
  292. crc = crc16_ccitt_false(bytes((int(frame_type) & 0xFF, len(body))) + body)
  293. return FRAME_HEADER + bytes((int(frame_type) & 0xFF, len(body))) + body + crc.to_bytes(2, "little")
  294. def build_set_all_6400(ptc: Iterable[int], fan: Iterable[int]) -> bytes:
  295. """6400 SET_ALL: 24 PTC then 8 FAN, chamber-major intake/exhaust."""
  296. payload = _checked_duty_bytes(ptc, PTC_6400_COUNT, "ptc")
  297. payload += _checked_duty_bytes(fan, FAN_6400_COUNT, "fan")
  298. if len(payload) != SET_ALL_6400_PAYLOAD_LENGTH:
  299. raise ValueError("6400 SET_ALL payload must be 32 bytes")
  300. return encode_frame_raw(int(FrameType.SET_ALL), payload)
  301. encode_frame_untyped = encode_frame_raw