prod2u_p4_protocol.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. #!/usr/bin/env python3
  2. """Prod2U Profile 4 Normal binary921-v3 wire protocol helpers.
  3. Host request frame types and payload layouts are intentionally frozen. The
  4. temperature command is the sole exception on the response side: it returns a
  5. compact 35-byte frame instead of a normal 14-byte-header Binary921 frame.
  6. """
  7. from __future__ import annotations
  8. from dataclasses import dataclass
  9. from enum import IntEnum
  10. from typing import Iterable
  11. PROTOCOL_ID = "binary921-v3"
  12. MAGIC = b"\xA5\x5A"
  13. VERSION = 2
  14. PROFILE_ID = 4
  15. HEADER_LEN = 14
  16. CRC_LEN = 2
  17. MAX_PAYLOAD_LEN = 255
  18. HOST_CMD_PAYLOAD_LEN = 4
  19. HOST_ACK_PAYLOAD_LEN = 8
  20. OUTPUT_SNAPSHOT_PAYLOAD_LEN = 34
  21. MOTION_COMMAND_PAYLOAD_LEN = 8
  22. MOTION_STATUS_PAYLOAD_LEN = 10
  23. PTC_CHANNEL_COUNT = 24
  24. FAN_CHANNEL_COUNT = 4
  25. TEMPERATURE_VALUE_COUNT = 27
  26. TEMPERATURE_RESPONSE_TYPE = 0x10
  27. TEMPERATURE_RESPONSE_LEN = 6 + TEMPERATURE_VALUE_COUNT + CRC_LEN
  28. class P4FrameError(ValueError):
  29. """Raised when a Profile 4 frame cannot be decoded safely."""
  30. class FrameType(IntEnum):
  31. HOST_CMD = 0x05
  32. HOST_ACK = 0x06
  33. HOST_BATCH_CMD = 0x07
  34. MOTION_CMD = 0x11
  35. MOTION_STATUS = 0x12
  36. class CommandId(IntEnum):
  37. GET_STATUS = 0x24
  38. DISABLE = 0x26
  39. GET_TEMPERATURES = 0x28
  40. SET_OUTPUT_SNAPSHOT = 0x2A
  41. class MotionOpcode(IntEnum):
  42. JOG = 0x35
  43. MARK_CLOSED = 0x36
  44. GET_MOTOR_STATUS = 0x37
  45. class StatusCode(IntEnum):
  46. OK = 0x00
  47. UNSUPPORTED_IN_PROFILE = 0x01
  48. BAD_FLAGS = 0x02
  49. BAD_LENGTH = 0x03
  50. BAD_VALUE = 0x05
  51. BUSY = 0x09
  52. TEMPERATURE_BUS_ERROR = 0x0A
  53. PARTIAL = 0x16
  54. @dataclass(frozen=True)
  55. class P4Frame:
  56. version: int
  57. profile_id: int
  58. frame_type: FrameType
  59. seq: int
  60. timestamp_tick: int
  61. payload: bytes
  62. crc16: int
  63. raw: bytes
  64. @dataclass(frozen=True)
  65. class HostCommand:
  66. command: CommandId
  67. channel: int
  68. value: int
  69. flags: int
  70. @dataclass(frozen=True)
  71. class HostAck:
  72. ok: bool
  73. command: CommandId | MotionOpcode | int
  74. status: StatusCode
  75. detail: int
  76. state_hash16: int
  77. response_type: FrameType | int
  78. result_flags: int
  79. request_seq: int | None
  80. @dataclass(frozen=True)
  81. class OutputSnapshot:
  82. ptc_percent: tuple[int, ...]
  83. fan_percent: tuple[int, ...]
  84. solenoid: int
  85. xyz: tuple[int, int, int]
  86. state_hash16: int
  87. @dataclass(frozen=True)
  88. class MotionCommand:
  89. opcode: MotionOpcode
  90. axis: int
  91. raw_dir: int
  92. speed_code: int
  93. steps: int
  94. @dataclass(frozen=True)
  95. class MotionStatus:
  96. flags: int
  97. position_valid_mask: int
  98. busy_mask: int
  99. current_xyz: tuple[int, int, int]
  100. target_xyz: tuple[int, int, int]
  101. fault_mask: int
  102. def crc16_ccitt(data: bytes | bytearray | Iterable[int], *, initial: int = 0xFFFF) -> int:
  103. """Return CRC-16/CCITT-FALSE for *data*."""
  104. crc = initial & 0xFFFF
  105. for byte in bytes(data):
  106. crc ^= byte << 8
  107. for _ in range(8):
  108. crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
  109. return crc
  110. def _u8(value: int, name: str) -> int:
  111. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFF:
  112. raise ValueError(f"{name} must fit in one byte")
  113. return value
  114. def _u16(value: int, name: str) -> int:
  115. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFF:
  116. raise ValueError(f"{name} must fit in 16 bits")
  117. return value
  118. def _u32(value: int, name: str) -> int:
  119. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFFFFFF:
  120. raise ValueError(f"{name} must fit in 32 bits")
  121. return value
  122. def encode_frame(
  123. *,
  124. frame_type: FrameType | int,
  125. seq: int,
  126. timestamp_tick: int,
  127. payload: bytes | bytearray | Iterable[int],
  128. ) -> bytes:
  129. payload_bytes = bytes(payload)
  130. if len(payload_bytes) > MAX_PAYLOAD_LEN:
  131. raise ValueError("payload too long for binary921-v3")
  132. try:
  133. typed_frame = FrameType(int(frame_type))
  134. except (TypeError, ValueError) as exc:
  135. raise ValueError(f"unknown Profile 4 frame type: {frame_type}") from exc
  136. seq = _u32(seq, "seq")
  137. timestamp_tick = _u32(timestamp_tick, "timestamp_tick")
  138. if seq != 0:
  139. raise ValueError("binary921-v3 seq must be zero")
  140. if timestamp_tick != 0:
  141. raise ValueError("binary921-v3 timestamp must be zero")
  142. body = bytes([VERSION, PROFILE_ID, int(typed_frame)])
  143. body += seq.to_bytes(4, "little")
  144. body += timestamp_tick.to_bytes(4, "little")
  145. body += bytes([len(payload_bytes)]) + payload_bytes
  146. return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little")
  147. def decode_frame(frame: bytes | bytearray) -> P4Frame:
  148. raw = bytes(frame)
  149. if len(raw) < HEADER_LEN + CRC_LEN:
  150. raise P4FrameError("short Profile 4 frame")
  151. if raw[:2] != MAGIC:
  152. raise P4FrameError("bad Profile 4 magic")
  153. if raw[2] != VERSION:
  154. raise P4FrameError(f"unsupported binary921 version {raw[2]}")
  155. if raw[3] != PROFILE_ID:
  156. raise P4FrameError(f"unexpected binary921 profile {raw[3]}")
  157. payload_len = raw[13]
  158. expected_len = HEADER_LEN + payload_len + CRC_LEN
  159. if len(raw) != expected_len:
  160. raise P4FrameError(f"length mismatch: expected {expected_len}, got {len(raw)}")
  161. expected_crc = crc16_ccitt(raw[2:-2])
  162. actual_crc = int.from_bytes(raw[-2:], "little")
  163. if actual_crc != expected_crc:
  164. raise P4FrameError(f"crc mismatch: expected 0x{expected_crc:04x}, got 0x{actual_crc:04x}")
  165. if raw[5:9] != b"\x00\x00\x00\x00":
  166. raise P4FrameError("binary921-v3 seq must be zero")
  167. if raw[9:13] != b"\x00\x00\x00\x00":
  168. raise P4FrameError("binary921-v3 timestamp must be zero")
  169. try:
  170. frame_type = FrameType(raw[4])
  171. except ValueError as exc:
  172. raise P4FrameError(f"unknown Profile 4 frame type 0x{raw[4]:02x}") from exc
  173. return P4Frame(
  174. version=raw[2],
  175. profile_id=raw[3],
  176. frame_type=frame_type,
  177. seq=0,
  178. timestamp_tick=0,
  179. payload=raw[14:-2],
  180. crc16=actual_crc,
  181. raw=raw,
  182. )
  183. def decode_stream(data: bytes | bytearray) -> tuple[list[P4Frame], bytes]:
  184. """Decode complete valid frames while preserving a possible partial tail."""
  185. buf = bytes(data)
  186. frames: list[P4Frame] = []
  187. offset = 0
  188. while True:
  189. magic_at = buf.find(MAGIC, offset)
  190. if magic_at < 0:
  191. remaining = buf[offset:]
  192. return frames, remaining[-1:] if remaining.endswith(MAGIC[:1]) else b""
  193. if len(buf) - magic_at < HEADER_LEN + CRC_LEN:
  194. return frames, buf[magic_at:]
  195. end = magic_at + HEADER_LEN + buf[magic_at + 13] + CRC_LEN
  196. if end > len(buf):
  197. next_magic = buf.find(MAGIC, magic_at + 1)
  198. if next_magic < 0:
  199. return frames, buf[magic_at:]
  200. offset = next_magic
  201. continue
  202. try:
  203. frames.append(decode_frame(buf[magic_at:end]))
  204. offset = end
  205. except P4FrameError:
  206. offset = magic_at + 1
  207. def _payload(value: P4Frame | bytes | bytearray, frame_type: FrameType, length: int, words: str) -> bytes:
  208. if isinstance(value, P4Frame):
  209. if value.frame_type != frame_type:
  210. raise ValueError(f"expected {frame_type.name} frame")
  211. payload = value.payload
  212. else:
  213. payload = bytes(value)
  214. if len(payload) != length:
  215. raise ValueError(f"{frame_type.name} payload must be exactly {words}")
  216. return payload
  217. def _percent_tuple(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
  218. result = tuple(values)
  219. if len(result) != count:
  220. raise ValueError(f"snapshot requires exactly {count} {label} values")
  221. for index, value in enumerate(result):
  222. if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100:
  223. raise ValueError(f"{label}[{index}] must be an integer from 0 to 100")
  224. return result
  225. def _binary_output(value: int, label: str) -> int:
  226. if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 100):
  227. raise ValueError(f"{label} must be 0 or 100")
  228. return value
  229. def state_hash16(
  230. *,
  231. ptc_percent: Iterable[int],
  232. fan_percent: Iterable[int],
  233. solenoid: int,
  234. ) -> int:
  235. """Hash the currently applied PTC, fan, and solenoid values."""
  236. ptc = _percent_tuple(ptc_percent, count=PTC_CHANNEL_COUNT, label="PTC")
  237. fan = _percent_tuple(fan_percent, count=FAN_CHANNEL_COUNT, label="FAN")
  238. checked_solenoid = _binary_output(solenoid, "solenoid")
  239. return crc16_ccitt(bytes(ptc + fan + (checked_solenoid,)))
  240. def build_output_snapshot(
  241. *,
  242. ptc_percent: Iterable[int],
  243. fan_percent: Iterable[int],
  244. solenoid: int,
  245. xyz: Iterable[int],
  246. ) -> bytes:
  247. ptc = _percent_tuple(ptc_percent, count=PTC_CHANNEL_COUNT, label="PTC")
  248. fan = _percent_tuple(fan_percent, count=FAN_CHANNEL_COUNT, label="FAN")
  249. checked_solenoid = _binary_output(solenoid, "solenoid")
  250. xyz_values = tuple(xyz)
  251. if len(xyz_values) != 3:
  252. raise ValueError("snapshot requires exactly 3 XYZ values")
  253. checked_xyz = tuple(_u8(value, "XYZ") for value in xyz_values)
  254. payload = bytes((CommandId.SET_OUTPUT_SNAPSHOT, 0))
  255. payload += bytes(ptc + fan + (checked_solenoid,) + checked_xyz)
  256. return encode_frame(
  257. frame_type=FrameType.HOST_BATCH_CMD,
  258. seq=0,
  259. timestamp_tick=0,
  260. payload=payload,
  261. )
  262. def decode_output_snapshot(value: P4Frame | bytes | bytearray) -> OutputSnapshot:
  263. payload = _payload(value, FrameType.HOST_BATCH_CMD, OUTPUT_SNAPSHOT_PAYLOAD_LEN, "thirty-four bytes")
  264. if payload[0] != CommandId.SET_OUTPUT_SNAPSHOT:
  265. raise ValueError("HOST_BATCH_CMD command must be SET_OUTPUT_SNAPSHOT")
  266. if payload[1] != 0:
  267. raise ValueError("SET_OUTPUT_SNAPSHOT flags must be zero")
  268. ptc = _percent_tuple(payload[2:26], count=PTC_CHANNEL_COUNT, label="PTC")
  269. fan = _percent_tuple(payload[26:30], count=FAN_CHANNEL_COUNT, label="FAN")
  270. solenoid = _binary_output(payload[30], "solenoid")
  271. xyz_values = tuple(payload[31:34])
  272. return OutputSnapshot(
  273. ptc_percent=ptc,
  274. fan_percent=fan,
  275. solenoid=solenoid,
  276. xyz=(xyz_values[0], xyz_values[1], xyz_values[2]),
  277. state_hash16=state_hash16(ptc_percent=ptc, fan_percent=fan, solenoid=solenoid),
  278. )
  279. def build_host_command(
  280. *,
  281. seq: int = 0,
  282. command: CommandId | int,
  283. channel: int = 0,
  284. value: int = 0,
  285. flags: int = 0,
  286. timestamp_tick: int = 0,
  287. ) -> bytes:
  288. try:
  289. command = CommandId(int(command))
  290. except (TypeError, ValueError) as exc:
  291. raise ValueError(f"unknown Profile4 command: {command}") from exc
  292. payload = bytes([int(command), _u8(channel, "channel"), _u8(value, "value"), _u8(flags, "flags")])
  293. return encode_frame(
  294. frame_type=FrameType.HOST_CMD,
  295. seq=seq,
  296. timestamp_tick=timestamp_tick,
  297. payload=payload,
  298. )
  299. def build_get_temperatures() -> bytes:
  300. """Build the exact HOST_CMD request for one on-demand temperature read."""
  301. return build_host_command(command=CommandId.GET_TEMPERATURES)
  302. def build_temperature_response(values: bytes | bytearray | Iterable[int]) -> bytes:
  303. """Build the compact 35-byte temperature response used by command 0x28."""
  304. try:
  305. payload = bytes(values)
  306. except (TypeError, ValueError) as exc:
  307. raise ValueError("temperature response values must be bytes") from exc
  308. if len(payload) != TEMPERATURE_VALUE_COUNT:
  309. raise ValueError("temperature response requires exactly 27 values")
  310. body = bytes(
  311. [VERSION, PROFILE_ID, TEMPERATURE_RESPONSE_TYPE, TEMPERATURE_VALUE_COUNT]
  312. ) + payload
  313. return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little")
  314. def decode_temperature_response(frame: bytes | bytearray) -> bytes:
  315. """Decode the compact 35-byte temperature response used by command 0x28."""
  316. raw = bytes(frame)
  317. if len(raw) != TEMPERATURE_RESPONSE_LEN:
  318. raise P4FrameError(
  319. f"temperature response length mismatch: expected "
  320. f"{TEMPERATURE_RESPONSE_LEN}, got {len(raw)}"
  321. )
  322. expected_prefix = bytes(
  323. [*MAGIC, VERSION, PROFILE_ID, TEMPERATURE_RESPONSE_TYPE, TEMPERATURE_VALUE_COUNT]
  324. )
  325. if raw[:6] != expected_prefix:
  326. raise P4FrameError("bad compact temperature response header")
  327. expected_crc = crc16_ccitt(raw[2:-2])
  328. actual_crc = int.from_bytes(raw[-2:], "little")
  329. if actual_crc != expected_crc:
  330. raise P4FrameError(
  331. f"temperature response crc mismatch: expected 0x{expected_crc:04x}, "
  332. f"got 0x{actual_crc:04x}"
  333. )
  334. return raw[6:-2]
  335. def decode_host_command(value: P4Frame | bytes | bytearray) -> HostCommand:
  336. payload = _payload(value, FrameType.HOST_CMD, HOST_CMD_PAYLOAD_LEN, "four bytes")
  337. try:
  338. command = CommandId(payload[0])
  339. except ValueError as exc:
  340. raise ValueError(f"unknown Profile4 command: 0x{payload[0]:02x}") from exc
  341. return HostCommand(command=command, channel=payload[1], value=payload[2], flags=payload[3])
  342. def build_host_ack(
  343. *,
  344. ok: bool,
  345. command: CommandId | MotionOpcode | int,
  346. status: StatusCode | int,
  347. seq: int = 0,
  348. detail: int = 0,
  349. state_hash16: int = 0,
  350. response_type: FrameType | int = 0,
  351. result_flags: int = 0,
  352. timestamp_tick: int = 0,
  353. ) -> bytes:
  354. command_value = _u8(int(command), "command")
  355. status_value = StatusCode(int(status))
  356. if not isinstance(ok, bool):
  357. raise ValueError("ok must be a bool")
  358. payload = bytes([int(ok), command_value, int(status_value), _u8(detail, "detail")])
  359. payload += _u16(state_hash16, "state_hash16").to_bytes(2, "little")
  360. payload += bytes([_u8(int(response_type), "response_type"), _u8(result_flags, "result_flags")])
  361. return encode_frame(
  362. frame_type=FrameType.HOST_ACK,
  363. seq=seq,
  364. timestamp_tick=timestamp_tick,
  365. payload=payload,
  366. )
  367. def decode_host_ack(value: P4Frame | bytes | bytearray) -> HostAck:
  368. request_seq = value.seq if isinstance(value, P4Frame) else None
  369. payload = _payload(value, FrameType.HOST_ACK, HOST_ACK_PAYLOAD_LEN, "eight bytes")
  370. if payload[0] not in (0, 1):
  371. raise ValueError("HOST_ACK ok must be 0 or 1")
  372. try:
  373. command: CommandId | MotionOpcode | int = CommandId(payload[1])
  374. except ValueError:
  375. try:
  376. command = MotionOpcode(payload[1])
  377. except ValueError:
  378. command = payload[1]
  379. try:
  380. status = StatusCode(payload[2])
  381. except ValueError as exc:
  382. raise ValueError("HOST_ACK contains an unknown status") from exc
  383. try:
  384. response_type: FrameType | int = FrameType(payload[6])
  385. except ValueError:
  386. response_type = payload[6]
  387. return HostAck(
  388. ok=payload[0] == 1,
  389. command=command,
  390. status=status,
  391. detail=payload[3],
  392. state_hash16=int.from_bytes(payload[4:6], "little"),
  393. response_type=response_type,
  394. result_flags=payload[7],
  395. request_seq=request_seq,
  396. )
  397. def _axis(value: int) -> int:
  398. if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 1, 2):
  399. raise ValueError("axis must be 0, 1, or 2")
  400. return value
  401. def _bit(value: int, label: str) -> int:
  402. if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 1):
  403. raise ValueError(f"{label} must be 0 or 1")
  404. return value
  405. def build_motor_jog(*, axis: int, raw_dir: int, speed_code: int, steps: int) -> bytes:
  406. checked_axis = _axis(axis)
  407. checked_dir = _bit(raw_dir, "raw_dir")
  408. if isinstance(speed_code, bool) or not isinstance(speed_code, int) or speed_code not in range(4):
  409. raise ValueError("speed_code must be from 0 to 3")
  410. if isinstance(steps, bool) or not isinstance(steps, int) or not 1 <= steps <= 0xFFFF:
  411. raise ValueError("steps must be from 1 to 65535")
  412. payload = bytes((MotionOpcode.JOG, checked_axis, checked_dir, speed_code))
  413. payload += steps.to_bytes(2, "little") + b"\x00\x00"
  414. return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload)
  415. def build_mark_closed(*, axis: int, close_dir: int) -> bytes:
  416. """Build the frozen legacy request; compliant firmware rejects it."""
  417. checked_axis = _axis(axis)
  418. if checked_axis == 2:
  419. raise ValueError("MARK_CLOSED axis must be X or Y")
  420. payload = bytes((MotionOpcode.MARK_CLOSED, checked_axis, _bit(close_dir, "close_dir"))) + b"\x00" * 5
  421. return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload)
  422. def build_get_motor_status() -> bytes:
  423. payload = bytes((MotionOpcode.GET_MOTOR_STATUS,)) + b"\x00" * 7
  424. return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload)
  425. def decode_motion_command(value: P4Frame | bytes | bytearray) -> MotionCommand:
  426. payload = _payload(value, FrameType.MOTION_CMD, MOTION_COMMAND_PAYLOAD_LEN, "eight bytes")
  427. try:
  428. opcode = MotionOpcode(payload[0])
  429. except ValueError as exc:
  430. raise ValueError(f"unknown motion opcode 0x{payload[0]:02x}") from exc
  431. if opcode == MotionOpcode.JOG:
  432. if payload[6:8] != b"\x00\x00":
  433. raise ValueError("JOG reserved bytes must be zero")
  434. axis = _axis(payload[1])
  435. raw_dir = _bit(payload[2], "raw_dir")
  436. speed_code = payload[3]
  437. steps = int.from_bytes(payload[4:6], "little")
  438. if speed_code not in range(4):
  439. raise ValueError("speed_code must be from 0 to 3")
  440. if not 1 <= steps <= 0xFFFF:
  441. raise ValueError("steps must be from 1 to 65535")
  442. return MotionCommand(opcode, axis, raw_dir, speed_code, steps)
  443. if opcode == MotionOpcode.MARK_CLOSED:
  444. if payload[1] not in (0, 1):
  445. raise ValueError("MARK_CLOSED axis must be X or Y")
  446. if payload[3:8] != b"\x00" * 5:
  447. raise ValueError("MARK_CLOSED reserved bytes must be zero")
  448. return MotionCommand(opcode, payload[1], _bit(payload[2], "close_dir"), 0, 0)
  449. if payload[1:8] != b"\x00" * 7:
  450. raise ValueError("GET_MOTOR_STATUS reserved bytes must be zero")
  451. return MotionCommand(opcode, 0, 0, 0, 0)
  452. def _position_triplet(values: Iterable[int], label: str) -> tuple[int, int, int]:
  453. result = tuple(values)
  454. if len(result) != 3:
  455. raise ValueError(f"{label} must contain exactly three values")
  456. for value in result:
  457. if value not in (0, 100, 0xFE, 0xFF):
  458. raise ValueError(f"{label} values must be 0, 100, 254, or 255")
  459. return result[0], result[1], result[2]
  460. def _validate_motion_status_contract(
  461. *,
  462. flags: int,
  463. position_valid_mask: int,
  464. busy_mask: int,
  465. current_xyz: tuple[int, int, int],
  466. target_xyz: tuple[int, int, int],
  467. fault_mask: int,
  468. ) -> None:
  469. if position_valid_mask != 0 or busy_mask != 0 or fault_mask != 0:
  470. raise ValueError("MOTION_STATUS valid, busy, and fault fields must be zero")
  471. if current_xyz != (0xFF, 0xFF, 0xFF) or target_xyz != (0xFF, 0xFF, 0xFF):
  472. raise ValueError("MOTION_STATUS current and target must remain unknown")
  473. if flags & 0x01:
  474. raise ValueError("MOTION_STATUS any_busy must be zero")
  475. if not flags & 0x02:
  476. raise ValueError("MOTION_STATUS en_active must be one")
  477. if flags & 0x08 and not flags & 0x04:
  478. raise ValueError("MOTION_STATUS watchdog_timeout requires disabled")
  479. def build_motion_status(
  480. *,
  481. flags: int,
  482. position_valid_mask: int,
  483. busy_mask: int,
  484. current_xyz: Iterable[int],
  485. target_xyz: Iterable[int],
  486. fault_mask: int,
  487. ) -> bytes:
  488. current = _position_triplet(current_xyz, "current_xyz")
  489. target = _position_triplet(target_xyz, "target_xyz")
  490. for name, value in (
  491. ("position_valid_mask", position_valid_mask),
  492. ("busy_mask", busy_mask),
  493. ("fault_mask", fault_mask),
  494. ):
  495. if isinstance(value, bool) or not isinstance(value, int) or value & ~0x07:
  496. raise ValueError(f"{name} must use only XYZ bits")
  497. checked_flags = _u8(flags, "flags")
  498. if checked_flags & 0xF0:
  499. raise ValueError("motion status flags contain reserved bits")
  500. _validate_motion_status_contract(
  501. flags=checked_flags,
  502. position_valid_mask=position_valid_mask,
  503. busy_mask=busy_mask,
  504. current_xyz=current,
  505. target_xyz=target,
  506. fault_mask=fault_mask,
  507. )
  508. payload = bytes((checked_flags, position_valid_mask, busy_mask, *current, *target, fault_mask))
  509. return encode_frame(frame_type=FrameType.MOTION_STATUS, seq=0, timestamp_tick=0, payload=payload)
  510. def decode_motion_status(value: P4Frame | bytes | bytearray) -> MotionStatus:
  511. payload = _payload(value, FrameType.MOTION_STATUS, MOTION_STATUS_PAYLOAD_LEN, "ten bytes")
  512. flags = payload[0]
  513. if flags & 0xF0:
  514. raise ValueError("motion status flags contain reserved bits")
  515. position_valid_mask = payload[1]
  516. busy_mask = payload[2]
  517. fault_mask = payload[9]
  518. for name, field in (
  519. ("position_valid_mask", position_valid_mask),
  520. ("busy_mask", busy_mask),
  521. ("fault_mask", fault_mask),
  522. ):
  523. if field & ~0x07:
  524. raise ValueError(f"{name} must use only XYZ bits")
  525. current = _position_triplet(payload[3:6], "current_xyz")
  526. target = _position_triplet(payload[6:9], "target_xyz")
  527. _validate_motion_status_contract(
  528. flags=flags,
  529. position_valid_mask=position_valid_mask,
  530. busy_mask=busy_mask,
  531. current_xyz=current,
  532. target_xyz=target,
  533. fault_mask=fault_mask,
  534. )
  535. return MotionStatus(
  536. flags=flags,
  537. position_valid_mask=position_valid_mask,
  538. busy_mask=busy_mask,
  539. current_xyz=current,
  540. target_xyz=target,
  541. fault_mask=fault_mask,
  542. )