chromapi 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. chromapi/__init__.py +2 -0
  2. chromapi/__main__.py +6 -0
  3. chromapi/assets/audio/alert.wav +0 -0
  4. chromapi/assets/audio/chromapi_scream.wav +0 -0
  5. chromapi/assets/audio/confused.wav +0 -0
  6. chromapi/assets/audio/dizzy.wav +0 -0
  7. chromapi/assets/audio/excited.wav +0 -0
  8. chromapi/assets/audio/greeting.wav +0 -0
  9. chromapi/assets/audio/happy.wav +0 -0
  10. chromapi/assets/audio/no.wav +0 -0
  11. chromapi/assets/audio/purring.wav +0 -0
  12. chromapi/assets/audio/sad.wav +0 -0
  13. chromapi/assets/audio/scared.wav +0 -0
  14. chromapi/assets/audio/sleepy.wav +0 -0
  15. chromapi/assets/audio/squeak.wav +0 -0
  16. chromapi/assets/audio/surprised.wav +0 -0
  17. chromapi/assets/audio/thinking.wav +0 -0
  18. chromapi/assets/audio/upset.wav +0 -0
  19. chromapi/assets/audio/yes.wav +0 -0
  20. chromapi/assets/favicon.ico +0 -0
  21. chromapi/assets/firmware/chromapi_stm32_core_v2.0.0.hex +2222 -0
  22. chromapi/assets/firmware/flash.sh +88 -0
  23. chromapi/assets/moves/README.md +48 -0
  24. chromapi/assets/moves/angry.json +1 -0
  25. chromapi/assets/moves/confused.json +1 -0
  26. chromapi/assets/moves/dizzy.json +1 -0
  27. chromapi/assets/moves/excited.json +1 -0
  28. chromapi/assets/moves/greeting.json +1 -0
  29. chromapi/assets/moves/happy.json +1 -0
  30. chromapi/assets/moves/joy.json +1 -0
  31. chromapi/assets/moves/kick.json +1 -0
  32. chromapi/assets/moves/metadata.jsonl +15 -0
  33. chromapi/assets/moves/no.json +1 -0
  34. chromapi/assets/moves/purring.json +1 -0
  35. chromapi/assets/moves/sad.json +1 -0
  36. chromapi/assets/moves/scared.json +1 -0
  37. chromapi/assets/moves/surprised.json +1 -0
  38. chromapi/assets/moves/tired.json +1 -0
  39. chromapi/assets/moves/yes.json +1 -0
  40. chromapi/chromapi.py +1460 -0
  41. chromapi/cli.py +106 -0
  42. chromapi/config/config.yaml +118 -0
  43. chromapi/estimation/__init__.py +6 -0
  44. chromapi/estimation/attitude.py +107 -0
  45. chromapi/hardware/__init__.py +2 -0
  46. chromapi/hardware/battery.py +54 -0
  47. chromapi/hardware/fan.py +165 -0
  48. chromapi/hardware/motherboard_bridge.py +345 -0
  49. chromapi/input/__init__.py +2 -0
  50. chromapi/input/gamepad.py +379 -0
  51. chromapi/input/pairing.py +98 -0
  52. chromapi/kinematics/__init__.py +10 -0
  53. chromapi/kinematics/kromatics.py +324 -0
  54. chromapi/kinematics/poses.py +29 -0
  55. chromapi/kinematics/topology.py +26 -0
  56. chromapi/kinematics/types.py +21 -0
  57. chromapi/locomotion/__init__.py +7 -0
  58. chromapi/locomotion/balance.py +284 -0
  59. chromapi/locomotion/gait.py +595 -0
  60. chromapi/locomotion/recorded_move.py +290 -0
  61. chromapi/media/__init__.py +2 -0
  62. chromapi/media/audio.py +424 -0
  63. chromapi/media/led.py +461 -0
  64. chromapi/model/LICENSE +438 -0
  65. chromapi/model/mjcf/additional.xml +21 -0
  66. chromapi/model/mjcf/assets/18650_li_ion_battery.msh +0 -0
  67. chromapi/model/mjcf/assets/18650_li_ion_battery.part +13 -0
  68. chromapi/model/mjcf/assets/battery_holder.msh +0 -0
  69. chromapi/model/mjcf/assets/battery_holder.part +13 -0
  70. chromapi/model/mjcf/assets/camera_imx219_d160.msh +0 -0
  71. chromapi/model/mjcf/assets/camera_imx219_d160.part +13 -0
  72. chromapi/model/mjcf/assets/chromapi_logo.msh +0 -0
  73. chromapi/model/mjcf/assets/chromapi_logo.part +13 -0
  74. chromapi/model/mjcf/assets/chromapi_logo_circle.msh +0 -0
  75. chromapi/model/mjcf/assets/chromapi_logo_inner.msh +0 -0
  76. chromapi/model/mjcf/assets/chromapi_logo_outer.msh +0 -0
  77. chromapi/model/mjcf/assets/chromapi_motherboard.msh +0 -0
  78. chromapi/model/mjcf/assets/chromapi_motherboard.part +13 -0
  79. chromapi/model/mjcf/assets/composant2_1__corps1.msh +0 -0
  80. chromapi/model/mjcf/assets/composant2_1__corps1.part +13 -0
  81. chromapi/model/mjcf/assets/composant3_1__corps1.msh +0 -0
  82. chromapi/model/mjcf/assets/composant3_1__corps1.part +13 -0
  83. chromapi/model/mjcf/assets/composant4_1__corps1.msh +0 -0
  84. chromapi/model/mjcf/assets/composant4_1__corps1.part +13 -0
  85. chromapi/model/mjcf/assets/connector_f_1__corps1.msh +0 -0
  86. chromapi/model/mjcf/assets/connector_f_1__corps1.part +13 -0
  87. chromapi/model/mjcf/assets/connector_f_1__corps1_1.msh +0 -0
  88. chromapi/model/mjcf/assets/connector_f_1__corps1_1.part +13 -0
  89. chromapi/model/mjcf/assets/corps14.msh +0 -0
  90. chromapi/model/mjcf/assets/corps14.part +13 -0
  91. chromapi/model/mjcf/assets/fan_nf_a4x10.msh +0 -0
  92. chromapi/model/mjcf/assets/fan_nf_a4x10.part +13 -0
  93. chromapi/model/mjcf/assets/foot.msh +0 -0
  94. chromapi/model/mjcf/assets/foot.part +13 -0
  95. chromapi/model/mjcf/assets/left_coxa.msh +0 -0
  96. chromapi/model/mjcf/assets/left_coxa.part +13 -0
  97. chromapi/model/mjcf/assets/left_femur.msh +0 -0
  98. chromapi/model/mjcf/assets/left_femur.part +13 -0
  99. chromapi/model/mjcf/assets/left_tibia.msh +0 -0
  100. chromapi/model/mjcf/assets/left_tibia.part +13 -0
  101. chromapi/model/mjcf/assets/microswitch.msh +0 -0
  102. chromapi/model/mjcf/assets/microswitch.part +13 -0
  103. chromapi/model/mjcf/assets/power_switch.msh +0 -0
  104. chromapi/model/mjcf/assets/power_switch.part +13 -0
  105. chromapi/model/mjcf/assets/raspberry_pi_4_model_b.msh +0 -0
  106. chromapi/model/mjcf/assets/raspberry_pi_4_model_b.part +13 -0
  107. chromapi/model/mjcf/assets/right_coxa.msh +0 -0
  108. chromapi/model/mjcf/assets/right_coxa.part +13 -0
  109. chromapi/model/mjcf/assets/right_femur.msh +0 -0
  110. chromapi/model/mjcf/assets/right_femur.part +13 -0
  111. chromapi/model/mjcf/assets/right_tibia.msh +0 -0
  112. chromapi/model/mjcf/assets/right_tibia.part +13 -0
  113. chromapi/model/mjcf/assets/robot_case_bottom.msh +0 -0
  114. chromapi/model/mjcf/assets/robot_case_bottom.part +13 -0
  115. chromapi/model/mjcf/assets/robot_case_top.msh +0 -0
  116. chromapi/model/mjcf/assets/robot_case_top.part +13 -0
  117. chromapi/model/mjcf/assets/rpi_battery_bracket.msh +0 -0
  118. chromapi/model/mjcf/assets/rpi_battery_bracket.part +13 -0
  119. chromapi/model/mjcf/assets/speaker.msh +0 -0
  120. chromapi/model/mjcf/assets/speaker.part +13 -0
  121. chromapi/model/mjcf/assets/vis_1__corps1.msh +0 -0
  122. chromapi/model/mjcf/assets/vis_1__corps1.part +13 -0
  123. chromapi/model/mjcf/assets/vis_1__corps1_1.msh +0 -0
  124. chromapi/model/mjcf/assets/vis_1__corps1_1.part +13 -0
  125. chromapi/model/mjcf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.msh +0 -0
  126. chromapi/model/mjcf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.part +13 -0
  127. chromapi/model/mjcf/assets/ws2812b_cob_pixel_ring_27mm.msh +0 -0
  128. chromapi/model/mjcf/assets/ws2812b_cob_pixel_ring_27mm.part +13 -0
  129. chromapi/model/mjcf/config.json +14 -0
  130. chromapi/model/mjcf/robot.xml +639 -0
  131. chromapi/model/mjcf/scene.xml +24 -0
  132. chromapi/model/urdf/assets/18650_li_ion_battery.part +13 -0
  133. chromapi/model/urdf/assets/18650_li_ion_battery.stl +0 -0
  134. chromapi/model/urdf/assets/battery_holder.part +13 -0
  135. chromapi/model/urdf/assets/battery_holder.stl +0 -0
  136. chromapi/model/urdf/assets/camera_imx219_d160.part +13 -0
  137. chromapi/model/urdf/assets/camera_imx219_d160.stl +0 -0
  138. chromapi/model/urdf/assets/chromapi_logo.part +13 -0
  139. chromapi/model/urdf/assets/chromapi_logo.stl +0 -0
  140. chromapi/model/urdf/assets/chromapi_logo_circle.stl +0 -0
  141. chromapi/model/urdf/assets/chromapi_logo_inner.stl +0 -0
  142. chromapi/model/urdf/assets/chromapi_logo_outer.stl +0 -0
  143. chromapi/model/urdf/assets/chromapi_motherboard.part +13 -0
  144. chromapi/model/urdf/assets/chromapi_motherboard.stl +0 -0
  145. chromapi/model/urdf/assets/composant2_1__corps1.part +13 -0
  146. chromapi/model/urdf/assets/composant2_1__corps1.stl +0 -0
  147. chromapi/model/urdf/assets/composant3_1__corps1.part +13 -0
  148. chromapi/model/urdf/assets/composant3_1__corps1.stl +0 -0
  149. chromapi/model/urdf/assets/composant4_1__corps1.part +13 -0
  150. chromapi/model/urdf/assets/composant4_1__corps1.stl +0 -0
  151. chromapi/model/urdf/assets/connector_f_1__corps1.part +13 -0
  152. chromapi/model/urdf/assets/connector_f_1__corps1.stl +0 -0
  153. chromapi/model/urdf/assets/connector_f_1__corps1_1.part +13 -0
  154. chromapi/model/urdf/assets/connector_f_1__corps1_1.stl +0 -0
  155. chromapi/model/urdf/assets/corps14.part +13 -0
  156. chromapi/model/urdf/assets/corps14.stl +0 -0
  157. chromapi/model/urdf/assets/fan_nf_a4x10.part +13 -0
  158. chromapi/model/urdf/assets/fan_nf_a4x10.stl +0 -0
  159. chromapi/model/urdf/assets/foot.part +13 -0
  160. chromapi/model/urdf/assets/foot.stl +0 -0
  161. chromapi/model/urdf/assets/left_coxa.part +13 -0
  162. chromapi/model/urdf/assets/left_coxa.stl +0 -0
  163. chromapi/model/urdf/assets/left_femur.part +13 -0
  164. chromapi/model/urdf/assets/left_femur.stl +0 -0
  165. chromapi/model/urdf/assets/left_tibia.part +13 -0
  166. chromapi/model/urdf/assets/left_tibia.stl +0 -0
  167. chromapi/model/urdf/assets/microswitch.part +13 -0
  168. chromapi/model/urdf/assets/microswitch.stl +0 -0
  169. chromapi/model/urdf/assets/power_switch.part +13 -0
  170. chromapi/model/urdf/assets/power_switch.stl +0 -0
  171. chromapi/model/urdf/assets/raspberry_pi_4_model_b.part +13 -0
  172. chromapi/model/urdf/assets/raspberry_pi_4_model_b.stl +0 -0
  173. chromapi/model/urdf/assets/right_coxa.part +13 -0
  174. chromapi/model/urdf/assets/right_coxa.stl +0 -0
  175. chromapi/model/urdf/assets/right_femur.part +13 -0
  176. chromapi/model/urdf/assets/right_femur.stl +0 -0
  177. chromapi/model/urdf/assets/right_tibia.part +13 -0
  178. chromapi/model/urdf/assets/right_tibia.stl +0 -0
  179. chromapi/model/urdf/assets/robot_case_bottom.part +13 -0
  180. chromapi/model/urdf/assets/robot_case_bottom.stl +0 -0
  181. chromapi/model/urdf/assets/robot_case_top.part +13 -0
  182. chromapi/model/urdf/assets/robot_case_top.stl +0 -0
  183. chromapi/model/urdf/assets/rpi_battery_bracket.part +13 -0
  184. chromapi/model/urdf/assets/rpi_battery_bracket.stl +0 -0
  185. chromapi/model/urdf/assets/speaker.part +13 -0
  186. chromapi/model/urdf/assets/speaker.stl +0 -0
  187. chromapi/model/urdf/assets/vis_1__corps1.part +13 -0
  188. chromapi/model/urdf/assets/vis_1__corps1.stl +0 -0
  189. chromapi/model/urdf/assets/vis_1__corps1_1.part +13 -0
  190. chromapi/model/urdf/assets/vis_1__corps1_1.stl +0 -0
  191. chromapi/model/urdf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.part +13 -0
  192. chromapi/model/urdf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.stl +0 -0
  193. chromapi/model/urdf/assets/ws2812b_cob_pixel_ring_27mm.part +13 -0
  194. chromapi/model/urdf/assets/ws2812b_cob_pixel_ring_27mm.stl +0 -0
  195. chromapi/model/urdf/config.json +8 -0
  196. chromapi/model/urdf/robot.urdf +2587 -0
  197. chromapi/utils/calibrate_imu_mount.py +80 -0
  198. chromapi/utils/calibrate_servo_centers.py +432 -0
  199. chromapi/utils/flash.py +141 -0
  200. chromapi/utils/health.py +210 -0
  201. chromapi/utils/report.py +75 -0
  202. chromapi/utils/setup_motors.py +189 -0
  203. chromapi/utils/sim_server.py +126 -0
  204. chromapi/web/__init__.py +2 -0
  205. chromapi/web/access.py +167 -0
  206. chromapi/web/app.py +1136 -0
  207. chromapi/web/camera.py +202 -0
  208. chromapi/web/static/fonts/varela-round.woff2 +0 -0
  209. chromapi/web/static/index.html +1079 -0
  210. chromapi/web/static/logo.png +0 -0
  211. chromapi/web/static/motherboard_front.png +0 -0
  212. chromapi/web/static/socket.io.min.js +7 -0
  213. chromapi-1.0.0.dist-info/METADATA +222 -0
  214. chromapi-1.0.0.dist-info/RECORD +219 -0
  215. chromapi-1.0.0.dist-info/WHEEL +5 -0
  216. chromapi-1.0.0.dist-info/entry_points.txt +2 -0
  217. chromapi-1.0.0.dist-info/licenses/LICENSE +201 -0
  218. chromapi-1.0.0.dist-info/licenses/src/chromapi/model/LICENSE +438 -0
  219. chromapi-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,345 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Motherboard Bridge Module for Chromapi.
3
+
4
+ Provides the UART communication interface between the Raspberry Pi and the STM32 motherboard
5
+ using a custom protocol.
6
+ """
7
+
8
+ import binascii
9
+ import logging
10
+ import struct
11
+ import threading
12
+ import time
13
+ from enum import IntEnum
14
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
15
+
16
+ import serial
17
+
18
+ BRIDGE_SYNC = b'\x55\xaa'
19
+ DEFAULT_BAUDRATE = 2_000_000
20
+
21
+ # Reply timeout for get_state(): a snapshot arrives every 5 ms, 50 ms = 10 missed cycles
22
+ _HOT_PATH_TIMEOUT_S = 0.05 # [s]
23
+ # Blocking granularity of a single serial read, set once on the port
24
+ _READ_POLL_S = 0.002 # [s]
25
+ # The STM32 releases the servos without a valid frame (60 s); one ping per second stays far within it
26
+ _LINK_KEEPALIVE_S = 1.0 # [s]
27
+
28
+ # seq, t_us, cycle_us, power, 12 x servo (pos, speed, load, temp, volt, current),
29
+ # imu acc/gyro/gyro_corr/quat, switches, servo fresh mask
30
+ _SNAPSHOT_FORMAT = '<BIH' + 'iii' + ('HhhBBh' * 12) + 'hhh' * 3 + 'hhhh' + 'BH'
31
+ _SNAPSHOT_LEN = struct.calcsize(_SNAPSHOT_FORMAT) # 168 bytes
32
+ _SERVO_CURRENT_A_PER_UNIT = 0.0065 # STS3215 Present_Current resolution [A]
33
+
34
+
35
+ def _crc16(data: bytes) -> int:
36
+ """Compute the CRC-16-CCITT checksum of the given data."""
37
+ return binascii.crc_hqx(data, 0xFFFF)
38
+
39
+
40
+ #: Bridge protocol this SDK speaks - must match the firmware's BRIDGE_PROTOCOL_VERSION (bridge.h).
41
+ BRIDGE_PROTOCOL_VERSION = 2
42
+
43
+
44
+ class Command(IntEnum):
45
+ """Available bridge commands."""
46
+
47
+ PING_BRIDGE = 0x01
48
+ SET_POSITIONS = 0x02
49
+ SET_TORQUE = 0x03
50
+ PING_SERVO = 0x04
51
+ SET_SERVO_ID = 0x06
52
+ SET_LED_COLOR = 0x07
53
+ SET_LED_RING_BULK = 0x08
54
+ WRITE_SERVO_REGISTER = 0x0A
55
+ READ_SERVO_REGISTER = 0x0B
56
+ GET_VERSION = 0x0C
57
+
58
+ class Response(IntEnum):
59
+ """Possible bridge responses."""
60
+
61
+ OK = 0x80
62
+ ERROR = 0x81
63
+ STATE_SNAPSHOT = 0x83
64
+ SERVO_REG_VALUE = 0x84
65
+ VERSION = 0x85
66
+
67
+ class LedTarget(IntEnum):
68
+ """LED target types for the SET_LED_COLOR command."""
69
+
70
+ LED_RING_ALL = 0x01
71
+ LED_RING_SINGLE = 0x02
72
+
73
+ LED_RING_COUNT = 18
74
+
75
+ class BridgeClient:
76
+ """Client class to interact with the STM32 Chromapi Motherboard."""
77
+
78
+ def __init__(self, port: str = '/dev/ttyAMA0', baudrate: int = DEFAULT_BAUDRATE, timeout: float = 1.0) -> None:
79
+ """Initialize the BridgeClient with serial port parameters.
80
+
81
+ Args:
82
+ port: Serial device of the RPi4 <-> STM32 UART bridge.
83
+ baudrate: UART baud rate (must match the firmware).
84
+ timeout: Default timeout for requests [s].
85
+
86
+ """
87
+ self.port: str = port
88
+ self.baudrate: int = baudrate
89
+ self.timeout: float = timeout # [s]
90
+ self.serial: Optional[serial.Serial] = None
91
+ self.logger: logging.Logger = logging.getLogger("BridgeClient")
92
+ self._rx = bytearray()
93
+ self._latest: Optional[bytes] = None # newest snapshot payload not yet returned
94
+ # One frame exchange at a time: Chromapi's control loop and the caller's thread (wake_up,
95
+ # rest, LEDs) share this port, and interleaved writes or RX parsing corrupt frames.
96
+ self._io_lock = threading.Lock()
97
+
98
+ def connect(self) -> bool:
99
+ """Attempt to open the serial port connection."""
100
+ try:
101
+ self.serial = serial.Serial(self.port, self.baudrate, timeout=_READ_POLL_S)
102
+ self.serial.reset_input_buffer()
103
+ self.logger.info(f"Connected to bridge on {self.port} at {self.baudrate} baud.")
104
+ return True
105
+ except serial.SerialException as e:
106
+ self.logger.error(f"Failed to open serial port: {e}")
107
+ return False
108
+
109
+ def close(self) -> None:
110
+ """Close the serial port connection safely."""
111
+ if self.serial and self.serial.is_open:
112
+ self.serial.close()
113
+
114
+ def _send_frame(self, cmd: int, payload: bytes = b'') -> None:
115
+ """Wrap and send a command frame over UART."""
116
+ if self.serial is None or not self.serial.is_open:
117
+ raise ConnectionError("Serial port is not open.")
118
+ body = bytes([len(payload) + 1, cmd]) + payload
119
+ self.serial.write(BRIDGE_SYNC + body + struct.pack('<H', _crc16(body)))
120
+
121
+ def _pop_frame(self) -> Optional[Tuple[int, bytes]]:
122
+ """Extract the next valid frame from the RX buffer, or None if none is complete yet."""
123
+ rx = self._rx
124
+ while True:
125
+ start = rx.find(BRIDGE_SYNC)
126
+ if start < 0:
127
+ del rx[:-1] # keep a trailing 0x55, it may be the start of the next sync
128
+ return None
129
+ del rx[:start]
130
+ if len(rx) < 3:
131
+ return None
132
+ n = rx[2]
133
+ if len(rx) < n + 5:
134
+ return None
135
+ body = bytes(rx[2:3 + n])
136
+ if n == 0 or rx[3 + n] | rx[4 + n] << 8 != _crc16(body):
137
+ del rx[:1] # bad frame: resync on the next sync pattern
138
+ continue
139
+ del rx[:n + 5]
140
+ return body[1], body[2:]
141
+
142
+ def _drain(self) -> None:
143
+ """Parse everything already received without blocking, keeping the newest snapshot."""
144
+ assert self.serial is not None
145
+ self._rx += self.serial.read(self.serial.in_waiting)
146
+ while (frame := self._pop_frame()) is not None:
147
+ if frame[0] == Response.STATE_SNAPSHOT:
148
+ self._latest = frame[1]
149
+
150
+ def _wait_for(self, want: Tuple[int, ...], timeout: float) -> Tuple[int, bytes]:
151
+ """Block until a frame whose cmd is in ``want`` arrives; snapshots seen meanwhile are kept."""
152
+ assert self.serial is not None
153
+ deadline = time.monotonic() + timeout # [s]
154
+ while True:
155
+ frame = self._pop_frame()
156
+ if frame is None:
157
+ if time.monotonic() > deadline:
158
+ raise TimeoutError("Timeout waiting for a bridge frame.")
159
+ self._rx += self.serial.read(max(1, self.serial.in_waiting))
160
+ elif frame[0] in want:
161
+ return frame
162
+ elif frame[0] == Response.STATE_SNAPSHOT:
163
+ self._latest = frame[1]
164
+
165
+ def _transact(self, cmd: Command, payload: bytes = b'', want: Tuple[int, ...] = (Response.OK,)) -> Optional[Tuple[int, bytes]]:
166
+ """Send a request/reply command; None on timeout/IO error. ERROR replies are returned too."""
167
+ if self.serial is None or not self.serial.is_open:
168
+ return None
169
+ try:
170
+ with self._io_lock:
171
+ self._drain() # drop stale replies so a late ACK can't answer this request
172
+ self._send_frame(cmd, payload)
173
+ return self._wait_for(want + (Response.ERROR,), self.timeout)
174
+ except (TimeoutError, serial.SerialException) as e:
175
+ self.logger.warning(f"{cmd.name} failed: {e}")
176
+ return None
177
+
178
+ def _ack(self, cmd: Command, payload: bytes = b'') -> bool:
179
+ reply = self._transact(cmd, payload)
180
+ return reply is not None and reply[0] == Response.OK
181
+
182
+ def ping(self) -> bool:
183
+ """Send a ping command to verify STM32 connectivity."""
184
+ return self._ack(Command.PING_BRIDGE)
185
+
186
+ def _led(self, cmd: Command, payload: bytes, wait: bool) -> bool:
187
+ """``wait=False``: no ACK wait, so a lost ACK cannot hold the bus (and the control loop) for a timeout."""
188
+ return self._ack(cmd, payload) if wait else self._send_nowait(cmd, payload)
189
+
190
+ def set_led_color(self, index: int, r: int, g: int, b: int, wait: bool = True) -> bool:
191
+ """Set a single ring LED (0-17)."""
192
+ if not (0 <= index < LED_RING_COUNT):
193
+ raise ValueError(f"index must be in [0, {LED_RING_COUNT - 1}]")
194
+ payload = bytes([LedTarget.LED_RING_SINGLE, index & 0xFF, r & 0xFF, g & 0xFF, b & 0xFF])
195
+ return self._led(Command.SET_LED_COLOR, payload, wait)
196
+
197
+ def set_led_color_all(self, r: int, g: int, b: int, wait: bool = True) -> bool:
198
+ """Set all 18 ring LEDs to a single color."""
199
+ return self._led(Command.SET_LED_COLOR, bytes([LedTarget.LED_RING_ALL, r & 0xFF, g & 0xFF, b & 0xFF]), wait)
200
+
201
+ def set_led_color_bulk(self, colors: List[Tuple[int, int, int]], wait: bool = True) -> bool:
202
+ """Set all 18 ring LEDs individually in a single UART frame."""
203
+ if len(colors) != LED_RING_COUNT:
204
+ raise ValueError(f"Expected exactly {LED_RING_COUNT} (r,g,b) tuples.")
205
+ payload = b''.join(bytes([r & 0xFF, g & 0xFF, b & 0xFF]) for r, g, b in colors)
206
+ return self._led(Command.SET_LED_RING_BULK, payload, wait)
207
+
208
+ @staticmethod
209
+ def _decode_state_snapshot(payload: bytes) -> Dict[str, Any]:
210
+ """Decode a STATE_SNAPSHOT payload.
211
+
212
+ Units of the returned fields: ``t_us`` MCU time of the servo read [µs] (uint32, wraps),
213
+ ``cycle_us`` bus cycle duration [µs]; ``voltage_V`` [V], ``current_A`` [A], ``power_W`` [W];
214
+ per servo ``pos`` [step], ``speed`` [step.s⁻¹], ``load`` [0.1 %] of rated torque,
215
+ ``temp_C`` [°C], ``volt_V`` [V], ``current_A`` [A] (magnitude), ``fresh`` (answered this
216
+ cycle, else the values are from an earlier one); ``acc_mps2`` [m.s⁻²], ``gyro_rps`` (raw)
217
+ and ``gyro_corr_rps`` (Mahony bias removed) [rad.s⁻¹], ``quat`` unit quaternion (w, x, y, z).
218
+ """
219
+ d = struct.unpack(_SNAPSHOT_FORMAT, payload)
220
+ seq, t_us, cycle_us, bus_uV, curr_uA, power_uW = d[:6]
221
+ servos, imu = d[6:78], d[78:91]
222
+ switches, fresh = d[91], d[92]
223
+
224
+ return {
225
+ "seq": seq,
226
+ "t_us": t_us,
227
+ "cycle_us": cycle_us,
228
+ "power": {
229
+ "voltage_V": bus_uV / 1_000_000.0,
230
+ "current_A": curr_uA / 1_000_000.0,
231
+ "power_W": power_uW / 1_000_000.0,
232
+ },
233
+ "servos": [
234
+ {
235
+ "id": i + 1,
236
+ "pos": servos[i * 6],
237
+ "speed": servos[i * 6 + 1],
238
+ "load": servos[i * 6 + 2],
239
+ "temp_C": servos[i * 6 + 3],
240
+ "volt_V": servos[i * 6 + 4] / 10.0,
241
+ "current_A": servos[i * 6 + 5] * _SERVO_CURRENT_A_PER_UNIT,
242
+ "fresh": bool(fresh >> i & 1),
243
+ }
244
+ for i in range(12)
245
+ ],
246
+ "imu": {
247
+ "acc_mps2": [v / 100.0 for v in imu[0:3]],
248
+ "gyro_rps": [v / 1000.0 for v in imu[3:6]],
249
+ "gyro_corr_rps": [v / 1000.0 for v in imu[6:9]],
250
+ "quat": [v / 32767.0 for v in imu[9:13]],
251
+ },
252
+ "switches": {
253
+ "TL": bool(switches & 0x01),
254
+ "TR": bool(switches & 0x02),
255
+ "BL": bool(switches & 0x04),
256
+ "BR": bool(switches & 0x08),
257
+ },
258
+ }
259
+
260
+ def _send_nowait(self, cmd: Command, payload: bytes) -> bool:
261
+ """Send a command that gets no reply; False if the port is closed/broken."""
262
+ try:
263
+ with self._io_lock:
264
+ self._send_frame(cmd, payload)
265
+ return True
266
+ except (ConnectionError, serial.SerialException) as e:
267
+ self.logger.warning(f"{cmd.name} error: {e}")
268
+ return False
269
+
270
+ def sleep(self, duration: float) -> None:
271
+ """``time.sleep()`` that keeps the STM32 link watchdog fed while torque is held.
272
+
273
+ The firmware releases every servo after 60 s without a valid frame. A script that holds
274
+ torque while idle for longer must wait with this instead of ``time.sleep()``. The pings expect no
275
+ reply here: their ACKs are dropped by the next command's ``_drain()``.
276
+ """
277
+ end = time.monotonic() + duration # [s]
278
+ while (left := end - time.monotonic()) > 0:
279
+ self._send_nowait(Command.PING_BRIDGE, b'')
280
+ time.sleep(min(_LINK_KEEPALIVE_S, left))
281
+
282
+ def set_positions(self, raw_steps: List[int]) -> bool:
283
+ """Send target positions to all 12 servomotors."""
284
+ if len(raw_steps) != 12:
285
+ raise ValueError("Expected exactly 12 raw positions (pad with 0 if unused).")
286
+ return self._send_nowait(Command.SET_POSITIONS, struct.pack('<12H', *raw_steps))
287
+
288
+ def set_torque(self, enabled: bool, servo_ids: Optional[Iterable[int]] = None) -> bool:
289
+ """Switch torque on/off for servo_ids (default: all 12) in one frame."""
290
+ mask = 0
291
+ for servo_id in (servo_ids if servo_ids is not None else range(1, 13)):
292
+ if not 1 <= servo_id <= 12:
293
+ raise ValueError(f"servo_id must be in [1, 12], got {servo_id}")
294
+ mask |= 1 << (servo_id - 1)
295
+ return self._send_nowait(Command.SET_TORQUE, struct.pack('<HH', mask, mask if enabled else 0))
296
+
297
+ def get_state(self, timeout: float = _HOT_PATH_TIMEOUT_S) -> Optional[Dict[str, Any]]:
298
+ """Retrieve the global hardware state snapshot."""
299
+ if self.serial is None or not self.serial.is_open:
300
+ return None
301
+ try:
302
+ with self._io_lock:
303
+ self._drain()
304
+ payload, self._latest = self._latest, None
305
+ if payload is None:
306
+ _, payload = self._wait_for((Response.STATE_SNAPSHOT,), timeout)
307
+ except (TimeoutError, serial.SerialException) as e:
308
+ self.logger.error(f"get_state error: {e}")
309
+ return None
310
+ if len(payload) != _SNAPSHOT_LEN:
311
+ self.logger.warning(f"Unexpected state snapshot size: {len(payload)} bytes (firmware/SDK protocol mismatch?)")
312
+ return None
313
+ return self._decode_state_snapshot(payload)
314
+
315
+ def ping_servo(self, servo_id: int) -> bool:
316
+ """Ping a specific servomotor on the bus."""
317
+ return self._ack(Command.PING_SERVO, bytes([servo_id & 0xFF]))
318
+
319
+ def set_servo_id(self, old_id: int, new_id: int) -> bool:
320
+ """Change the ID of a Feetech servomotor."""
321
+ return self._ack(Command.SET_SERVO_ID, bytes([old_id & 0xFF, new_id & 0xFF]))
322
+
323
+ def write_servo_register(self, servo_id: int, reg: int, size: int, value: int) -> bool:
324
+ """Write 1 or 2 bytes to a specific Feetech register via the STM32 bridge."""
325
+ payload = bytes([servo_id & 0xFF, reg & 0xFF, size & 0xFF, value & 0xFF, (value >> 8) & 0xFF])
326
+ return self._ack(Command.WRITE_SERVO_REGISTER, payload)
327
+
328
+ def get_version(self) -> Optional[Tuple[int, Tuple[int, int, int]]]:
329
+ """Return ``(protocol, (major, minor, patch))`` of the firmware, or None.
330
+
331
+ None also means a firmware older than 2.0.0, which does not know this command.
332
+ """
333
+ reply = self._transact(Command.GET_VERSION, want=(Response.VERSION,))
334
+ if reply is None or reply[0] != Response.VERSION or len(reply[1]) != 4:
335
+ return None
336
+ protocol, major, minor, patch = reply[1]
337
+ return protocol, (major, minor, patch)
338
+
339
+ def read_servo_register(self, servo_id: int, reg: int, size: int) -> Optional[int]:
340
+ """Read 1 or 2 bytes from a specific Feetech register."""
341
+ reply = self._transact(Command.READ_SERVO_REGISTER, bytes([servo_id & 0xFF, reg & 0xFF, size & 0xFF]),
342
+ want=(Response.SERVO_REG_VALUE,))
343
+ if reply is None or reply[0] != Response.SERVO_REG_VALUE or len(reply[1]) != size or size not in (1, 2):
344
+ return None
345
+ return int.from_bytes(reply[1], 'little')
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Human input sources for Chromapi."""