prod2u_simple_protocol.py 13 KB

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