prod2u_p4_protocol.py 20 KB

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