prod2u_p4_protocol.py 20 KB

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