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,379 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Raw Linux joystick gamepad input - :class:`GamepadInput`.
3
+
4
+ No external dependency: reads ``/dev/input/js*`` directly
5
+ via the kernel joystick API, instead of a gamepad library. This also means Bluetooth "just
6
+ works" with no gamepad-specific Bluetooth code here at all: once a controller is paired at the
7
+ OS level (steps below), it shows up as an ordinary ``/dev/input/js0``, indistinguishable from
8
+ a wired one.
9
+
10
+ Pairing a controller over Bluetooth (Raspberry Pi or any Linux host)
11
+ ----------------------------------------------------------------------
12
+ ``chromapi gamepad pair`` does steps 1-2. By hand:
13
+
14
+ 1. Put the controller in pairing mode (hold its pair button until its LED flashes rapidly).
15
+ 2. ``bluetoothctl``, then: ``power on``, ``agent on``, ``scan on`` (note the MAC address once
16
+ the controller shows up), ``scan off``, ``pair <MAC>``, ``trust <MAC>``, ``connect <MAC>``.
17
+ 3. Once paired *and trusted*, it reconnects automatically on power-on - no repeat pairing.
18
+ 4. With the ``joystick`` package installed (``sudo apt install joystick``), you can use
19
+ ``jstest /dev/input/js0``: this shows live axis/button numbers - may be useful if your
20
+ controller doesn't match :class:`GamepadAxisMap`'s defaults below.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import fcntl
26
+ import logging
27
+ import os
28
+ import select
29
+ import struct
30
+ import threading
31
+ import time
32
+ from dataclasses import dataclass, field
33
+ from pathlib import Path
34
+ from typing import Dict, List, Optional, Set, Tuple
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+ _JS_EVENT = struct.Struct("=IhBB")
39
+ _JS_EVENT_BUTTON = 0x01
40
+ _JS_EVENT_AXIS = 0x02
41
+ _JS_EVENT_INIT = 0x80
42
+
43
+ #: Signed 16-bit axis full scale (raw joystick axis values are int16, +-32767).
44
+ _AXIS_FULL_SCALE = 32767.0
45
+
46
+ # evdev: motion sensors and rumble, which the joystick API does not carry
47
+ _INPUT_EVENT = struct.Struct("@llHHi") # struct input_event: timeval, type, code, value
48
+ _EV_ABS, _EV_FF, _FF_RUMBLE = 0x03, 0x15, 0x50
49
+ # struct ff_effect (64-bit) with its rumble member (strong, weak)
50
+ _FF_EFFECT = struct.Struct("=HhHHHHH2xHH28x")
51
+ _EVIOCSFF = 0x40304580 # _IOW('E', 0x80, struct ff_effect)
52
+ RUMBLE_MS = 150 # [ms] one pulse
53
+ RUMBLE_GAP_MS = 120 # [ms] before each pulse
54
+ RUMBLE_LED_REFRESH_S = 0.3 # [s] some pads turn the light bar off to rumble
55
+ ACCEL_SMOOTHING = 0.05 # accelerometer low-pass
56
+ READ_PERIOD_S = 0.01 # [s] batched reads: one wake-up per report starves the control loop
57
+
58
+
59
+ @dataclass
60
+ class UserInput:
61
+ """One tick of decoded input, as human intents; the caller maps them onto ``Chromapi.walk()``."""
62
+
63
+ forward: float = 0.0 # [-1, 1] positive forward
64
+ lateral: float = 0.0 # [-1, 1] positive right
65
+ turn: float = 0.0 # [-1, 1] positive left
66
+ vertical: float = 0.0 # [-1, 1] positive up
67
+ pressed: Set[str] = field(default_factory=set) # one-shot actions
68
+ held: Set[str] = field(default_factory=set) # hold-to-repeat actions
69
+
70
+
71
+ @dataclass
72
+ class GamepadAxisMap:
73
+ """Which raw joystick axis/button numbers feed :class:`UserInput`, and the deadzone.
74
+
75
+ Verify your own controller's numbering with ``jstest`` (see the module docstring) if
76
+ movement doesn't respond, or responds on the wrong stick/axis.
77
+ """
78
+
79
+ left_x: int = 0
80
+ left_y: int = 1
81
+ right_x: int = 3
82
+ right_y: int = 4
83
+ dpad_x: int = 6
84
+ dpad_y: int = 7
85
+ deadzone: float = 0.12
86
+
87
+ class GamepadInput:
88
+ """Reads a gamepad via the raw Linux joystick API.
89
+
90
+ Runs its own background thread (started by :meth:`start`) parsing events as they arrive;
91
+ :meth:`read` just returns the latest call every tick from a teleop loop.
92
+ """
93
+
94
+ def __init__(
95
+ self, device: str = "/dev/input/js0", axis_map: Optional[GamepadAxisMap] = None
96
+ ) -> None:
97
+ """Build the input source - does not open the device until :meth:`start`.
98
+
99
+ Args:
100
+ device: Path to the joystick device node.
101
+ axis_map: See :class:`GamepadAxisMap`.
102
+
103
+ """
104
+ self.device = device
105
+ self.axis_map = axis_map or GamepadAxisMap()
106
+ self._fd: Optional[int] = None
107
+ self._axis_state: Dict[int, float] = {}
108
+ self._pressed: Set[str] = set()
109
+ self._held: Set[str] = set()
110
+ self._hat_state: Dict[int, Optional[str]] = {}
111
+ self._lock = threading.Lock()
112
+ self._stop_event = threading.Event()
113
+ self._thread: Optional[threading.Thread] = None
114
+ self._motion_fd: Optional[int] = None
115
+ self._motion_path: Optional[str] = None
116
+ self.motion = False # read the motion sensors
117
+ self._accel: List[Optional[float]] = [None, None, None] # low-passed, raw units
118
+ self._ff_fd: Optional[int] = None
119
+ self._ff_id = -1
120
+ self._led_files: List[Path] = []
121
+ self._led_max = 255
122
+ self._led_default: Optional[List[str]] = None
123
+ self._rgb: Optional[Tuple[int, int, int]] = None
124
+ self._led_refresh_at = float("inf") # [s]
125
+ self._battery: Optional[Path] = None
126
+
127
+ def start(self) -> None:
128
+ """Open the device and start the background reader thread."""
129
+ try:
130
+ self._fd = os.open(self.device, os.O_RDONLY | os.O_NONBLOCK)
131
+ except FileNotFoundError as exc:
132
+ raise FileNotFoundError(
133
+ f"No gamepad found at {self.device!r}. Is one connected/paired? Check with "
134
+ f"'ls /dev/input/js*' - see chromapi.input.gamepad's module docstring for "
135
+ f"Bluetooth pairing steps if nothing shows up there at all."
136
+ ) from exc
137
+ except PermissionError as exc:
138
+ raise PermissionError(
139
+ f"Found {self.device!r} but can't open it (permission denied) - check that "
140
+ f"your user is in the 'input' group ('groups' to check, then 'sudo usermod "
141
+ f"-aG input $USER' and re-login if not)."
142
+ ) from exc
143
+ self._find_extras()
144
+ self._stop_event.clear()
145
+ self._thread = threading.Thread(
146
+ target=self._loop, name="chromapi-gamepad", daemon=True
147
+ )
148
+ self._thread.start()
149
+
150
+ def _find_extras(self) -> None:
151
+ """Motion sensors, rumble, light bar and battery, when the pad has them."""
152
+ try:
153
+ pad = Path("/sys/class/input", Path(self.device).name, "device").resolve()
154
+ hid = pad.parent.parent
155
+ event = next(pad.glob("event*"), None)
156
+ motion = next((next(d.glob("event*"), None) for d in hid.glob("input/input*")
157
+ if "Motion Sensors" in (d / "name").read_text()), None)
158
+ except OSError:
159
+ return
160
+ if motion is not None:
161
+ self._motion_path = f"/dev/input/{motion.name}"
162
+ if event is not None:
163
+ try:
164
+ self._ff_fd = os.open(f"/dev/input/{event.name}", os.O_RDWR | os.O_NONBLOCK)
165
+ effect = bytearray(_FF_EFFECT.pack(_FF_RUMBLE, -1, 0, 0, 0, RUMBLE_MS, RUMBLE_GAP_MS, 0xC000, 0x8000))
166
+ fcntl.ioctl(self._ff_fd, _EVIOCSFF, effect, True)
167
+ self._ff_id = _FF_EFFECT.unpack(effect)[1]
168
+ except OSError: # no rumble
169
+ self._close_ff()
170
+ rgb = next(hid.glob("leds/*:rgb:indicator"), None)
171
+ triplet = [next(hid.glob(f"leds/*:{color}"), None) for color in ("red", "green", "blue")]
172
+ leds: List[Path] = [rgb] if rgb is not None else [led for led in triplet if led is not None]
173
+ if rgb is None and len(leds) != 3:
174
+ leds = []
175
+ try:
176
+ self._led_max = int((leds[0] / "max_brightness").read_text()) if leds else 255
177
+ except (OSError, ValueError):
178
+ leds = []
179
+ self._led_files = [rgb / "brightness", rgb / "multi_intensity"] if rgb is not None else [
180
+ led / "brightness" for led in leds]
181
+ self._battery = next(hid.glob("power_supply/*"), None)
182
+
183
+ def _close_ff(self) -> None:
184
+ if self._ff_fd is not None:
185
+ os.close(self._ff_fd)
186
+ self._ff_fd = None
187
+
188
+ def tilt(self) -> Optional[Tuple[float, float, float]]:
189
+ """Gravity in the pad's frame (raw units), None without motion sensors."""
190
+ with self._lock:
191
+ x, y, z = self._accel
192
+ return None if x is None or y is None or z is None else (x, y, z)
193
+
194
+ def rumble(self, pulses: int = 1) -> None:
195
+ """Buzz ``pulses`` short pulses."""
196
+ if self._ff_fd is None:
197
+ return
198
+ try:
199
+ os.write(self._ff_fd, _INPUT_EVENT.pack(0, 0, _EV_FF, self._ff_id, pulses))
200
+ except OSError:
201
+ self._close_ff()
202
+ return
203
+ self._led_refresh_at = (time.monotonic() + pulses * (RUMBLE_MS + RUMBLE_GAP_MS) / 1000.0
204
+ + RUMBLE_LED_REFRESH_S)
205
+
206
+ def set_color(self, rgb: Tuple[int, int, int]) -> None:
207
+ """Light bar colour (needs ``deploy/99-chromapi-gamepad.rules``); :meth:`stop` restores the driver's."""
208
+ self._rgb = rgb
209
+ self._write_color(rgb)
210
+
211
+ def _write_color(self, rgb: Tuple[int, int, int]) -> None:
212
+ if not self._led_files:
213
+ return
214
+ levels = [str(round(min(max(c, 0), 255) * self._led_max / 255)) for c in rgb]
215
+ values = [str(self._led_max), " ".join(levels)] if len(self._led_files) == 2 else levels
216
+ try:
217
+ if self._led_default is None:
218
+ self._led_default = [path.read_text().strip() for path in self._led_files]
219
+ for path, value in zip(self._led_files, values):
220
+ path.write_text(value)
221
+ except OSError as exc:
222
+ logger.warning("Gamepad light bar: %s (install deploy/99-chromapi-gamepad.rules)", exc)
223
+ self._led_files = []
224
+
225
+ def battery(self) -> Optional[Tuple[int, bool]]:
226
+ """(percent, charging) of the pad's battery, None if unknown."""
227
+ if self._battery is None:
228
+ return None
229
+ try:
230
+ percent = int((self._battery / "capacity").read_text())
231
+ status = (self._battery / "status").read_text().strip()
232
+ except (OSError, ValueError):
233
+ return None
234
+ return percent, status in ("Charging", "Full")
235
+
236
+ def stop(self) -> None:
237
+ """Stop the reader thread, restore the light bar, close the devices."""
238
+ self._stop_event.set()
239
+ if self._thread is not None:
240
+ self._thread.join(timeout=1.0)
241
+ self._thread = None
242
+ if self._led_default is not None:
243
+ try:
244
+ for path, value in zip(self._led_files, self._led_default):
245
+ path.write_text(value)
246
+ except OSError:
247
+ pass
248
+ self._led_default = None
249
+ self._close_ff()
250
+ if self._motion_fd is not None:
251
+ os.close(self._motion_fd)
252
+ self._motion_fd = None
253
+ if self._fd is not None:
254
+ try:
255
+ os.close(self._fd)
256
+ except OSError:
257
+ logger.warning("GamepadInput.stop(): closing %s failed (already disconnected?)", self.device)
258
+ self._fd = None
259
+
260
+ @property
261
+ def connected(self) -> bool:
262
+ """The reader thread runs (it ends when the device goes away)."""
263
+ return self._thread is not None and self._thread.is_alive()
264
+
265
+ def _loop(self) -> None:
266
+ """Background thread loop: read events from the device and update internal state."""
267
+ while not self._stop_event.wait(READ_PERIOD_S):
268
+ assert self._fd is not None
269
+ self._open_motion(self.motion)
270
+ fds = [self._fd] if self._motion_fd is None else [self._fd, self._motion_fd]
271
+ readable, _, _ = select.select(fds, [], [], 0.1)
272
+ if time.monotonic() >= self._led_refresh_at:
273
+ self._refresh_color()
274
+ if self._motion_fd in readable:
275
+ self._read_motion()
276
+ if self._fd not in readable:
277
+ continue
278
+ try:
279
+ data = os.read(self._fd, _JS_EVENT.size * 256)
280
+ except OSError:
281
+ logger.warning("Gamepad %s disconnected", self.device)
282
+ return
283
+ n_complete = len(data) - (len(data) % _JS_EVENT.size)
284
+ for offset in range(0, n_complete, _JS_EVENT.size):
285
+ _, value, ev_type, number = _JS_EVENT.unpack_from(data, offset)
286
+ self._handle_event(ev_type, number, value)
287
+
288
+ def _open_motion(self, wanted: bool) -> None:
289
+ """Open or close the motion sensors, from the reader thread."""
290
+ if wanted == (self._motion_fd is not None) or self._motion_path is None:
291
+ return
292
+ if wanted:
293
+ try:
294
+ self._motion_fd = os.open(self._motion_path, os.O_RDONLY | os.O_NONBLOCK)
295
+ except OSError as exc:
296
+ logger.warning("Gamepad motion sensors: %s", exc)
297
+ self._motion_path = None
298
+ return
299
+ os.close(self._motion_fd) # type: ignore[arg-type]
300
+ self._motion_fd = None
301
+ with self._lock:
302
+ self._accel = [None, None, None]
303
+
304
+ def _refresh_color(self) -> None:
305
+ """Send the colour again (the driver skips unchanged values)."""
306
+ self._led_refresh_at = float("inf")
307
+ if self._rgb is not None:
308
+ r, g, b = self._rgb
309
+ self._write_color((r + 1 if r < 255 else r - 1, g, b))
310
+ self._write_color(self._rgb)
311
+
312
+ def _read_motion(self) -> None:
313
+ assert self._motion_fd is not None
314
+ try:
315
+ data = os.read(self._motion_fd, _INPUT_EVENT.size * 1024)
316
+ except OSError:
317
+ return
318
+ for offset in range(0, len(data) - _INPUT_EVENT.size + 1, _INPUT_EVENT.size):
319
+ _, _, ev_type, code, value = _INPUT_EVENT.unpack_from(data, offset)
320
+ if ev_type == _EV_ABS and code < 3: # accelerometer
321
+ with self._lock:
322
+ last = self._accel[code]
323
+ self._accel[code] = float(value) if last is None else last + ACCEL_SMOOTHING * (value - last)
324
+
325
+ def _handle_event(self, ev_type: int, number: int, value: int) -> None:
326
+ """Update internal state from one decoded event."""
327
+ kind = ev_type & ~_JS_EVENT_INIT
328
+ is_init = bool(ev_type & _JS_EVENT_INIT)
329
+ if kind == _JS_EVENT_AXIS and number == self.axis_map.dpad_x:
330
+ self._update_hat(number, value, negative="dpad_left", positive="dpad_right")
331
+ elif kind == _JS_EVENT_AXIS and number == self.axis_map.dpad_y:
332
+ self._update_hat(number, value, negative="dpad_up", positive="dpad_down")
333
+ elif kind == _JS_EVENT_AXIS:
334
+ normalized = value / _AXIS_FULL_SCALE
335
+ if abs(normalized) < self.axis_map.deadzone:
336
+ normalized = 0.0
337
+ with self._lock:
338
+ self._axis_state[number] = normalized
339
+ elif kind == _JS_EVENT_BUTTON:
340
+ name = str(number)
341
+ with self._lock:
342
+ if value == 1:
343
+ self._held.add(name)
344
+ if not is_init:
345
+ self._pressed.add(name)
346
+ else:
347
+ self._held.discard(name)
348
+
349
+ def _update_hat(self, axis_number: int, value: int, negative: str, positive: str) -> None:
350
+ """Decode one D-pad hat axis reading into a held name (or none)."""
351
+ if value < -_AXIS_FULL_SCALE / 2:
352
+ current: Optional[str] = negative
353
+ elif value > _AXIS_FULL_SCALE / 2:
354
+ current = positive
355
+ else:
356
+ current = None
357
+ with self._lock:
358
+ previous = self._hat_state.get(axis_number)
359
+ if previous is not None:
360
+ self._held.discard(previous)
361
+ if current is not None:
362
+ self._held.add(current)
363
+ self._hat_state[axis_number] = current
364
+
365
+ def read(self) -> UserInput:
366
+ """Return the latest decoded input - non-blocking."""
367
+ with self._lock:
368
+ axes = dict(self._axis_state)
369
+ pressed = set(self._pressed)
370
+ held = set(self._held)
371
+ self._pressed.clear()
372
+ return UserInput(
373
+ forward=-axes.get(self.axis_map.left_y, 0.0),
374
+ lateral=axes.get(self.axis_map.left_x, 0.0),
375
+ turn=-axes.get(self.axis_map.right_x, 0.0),
376
+ vertical=-axes.get(self.axis_map.right_y, 0.0),
377
+ pressed=pressed,
378
+ held=held,
379
+ )
@@ -0,0 +1,98 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Pair a Bluetooth gamepad with ``bluetoothctl``: the first unpaired one found in pairing mode.
3
+
4
+ Usage::
5
+
6
+ chromapi gamepad pair
7
+ """
8
+
9
+ import argparse
10
+ import re
11
+ import subprocess
12
+ import time
13
+ from typing import List, Tuple
14
+
15
+ SCAN_S = 20 # [s]
16
+ STEP_TIMEOUT_S = 30 # [s]
17
+ # (command, fields `info` must show, --timeout [s]); trusted first, or a controller pad is refused right after pairing
18
+ STEPS = (("trust", ("Trusted",), 0.0), ("pair", ("Paired", "Bonded"), 15.0), ("connect", ("Connected",), 10.0))
19
+ CHECK_S = 5.0 # [s] for a step's state to show in `info`
20
+ _DEVICE = re.compile(r"^Device ([0-9A-F:]{17}) (.*)$")
21
+ _COLOUR = re.compile(r"\x1b\[[0-9;]*m|\x01|\x02") # bluetoothctl colours even into a pipe
22
+
23
+
24
+ def _ctl(*args: str, timeout_s: float = STEP_TIMEOUT_S) -> Tuple[bool, str]:
25
+ """Run one ``bluetoothctl`` command: (succeeded, output)."""
26
+ try:
27
+ done = subprocess.run(["bluetoothctl", *args], capture_output=True, text=True, timeout=timeout_s, check=False)
28
+ except FileNotFoundError:
29
+ return False, "bluetoothctl not found: sudo apt install bluez"
30
+ except subprocess.TimeoutExpired:
31
+ return False, f"bluetoothctl {' '.join(args)}: no answer after {timeout_s:.0f} s"
32
+ output = _COLOUR.sub("", done.stdout + done.stderr).strip()
33
+ return done.returncode == 0 and "Failed" not in output and "not available" not in output, output
34
+
35
+
36
+ def _reached(mac: str, fields: Tuple[str, ...]) -> bool:
37
+ """``info`` shows ``<field>: yes`` for each field it lists, within :data:`CHECK_S`."""
38
+ deadline = time.monotonic() + CHECK_S
39
+ while True:
40
+ info = _ctl("info", mac)[1]
41
+ if all(f"{field}: yes" in info or f"{field}:" not in info for field in fields):
42
+ return True
43
+ if time.monotonic() >= deadline:
44
+ return False
45
+ time.sleep(0.5)
46
+
47
+
48
+ def unpaired_gamepads() -> List[Tuple[str, str]]:
49
+ """(MAC, name) of the gamepads BlueZ knows of and has not paired yet."""
50
+ found = []
51
+ for line in _ctl("devices")[1].splitlines():
52
+ match = _DEVICE.match(line.strip())
53
+ if match:
54
+ info = _ctl("info", match[1])[1]
55
+ if "Icon: input-gaming" in info and "Paired: no" in info:
56
+ found.append((match[1], match[2]))
57
+ return found
58
+
59
+
60
+ def main() -> int:
61
+ """Pair the first gamepad found; the adapter is pairable only meanwhile."""
62
+ try:
63
+ return _pair()
64
+ finally:
65
+ _ctl("pairable", "off")
66
+
67
+
68
+ def _pair() -> int:
69
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
70
+ parser.add_argument("--scan", type=float, default=SCAN_S, help="[s] how long to look for the controller")
71
+ args = parser.parse_args()
72
+ ok, output = _ctl("power", "on")
73
+ if ok: # not pairable: paired without a bond, then refused
74
+ ok, output = _ctl("pairable", "on")
75
+ if not ok:
76
+ print(f"Bluetooth does not start: {output.splitlines()[-1] if output else 'no adapter'}")
77
+ return 1
78
+ print(f"Looking for a controller in pairing mode for {args.scan:.0f} s...", flush=True)
79
+ _ctl("--timeout", f"{args.scan:.0f}", "scan", "on", timeout_s=args.scan + STEP_TIMEOUT_S)
80
+ gamepads = unpaired_gamepads()
81
+ if not gamepads:
82
+ print("No controller found: hold its pair button until its light flashes fast, then try again")
83
+ return 1
84
+ mac, name = gamepads[0]
85
+ for step, fields, open_s in STEPS:
86
+ print(f"{step} {name} ({mac})", flush=True)
87
+ keep_open = ("--agent", "NoInputNoOutput", "--timeout", f"{open_s:.0f}") if open_s else ()
88
+ ok, output = _ctl(*keep_open, step, mac, timeout_s=open_s + STEP_TIMEOUT_S)
89
+ if not ok or not _reached(mac, fields):
90
+ failed = [line for line in output.splitlines() if "Failed" in line]
91
+ print(f"Could not {step} {name}: {failed[-1] if failed else f'not {fields[0]} afterwards'}")
92
+ return 1
93
+ print(f"Paired {name}: it reconnects on its own when switched on")
94
+ return 0
95
+
96
+
97
+ if __name__ == "__main__":
98
+ raise SystemExit(main())
@@ -0,0 +1,10 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Kinematics layer for Chromapi.
3
+
4
+ - :mod:`chromapi.kinematics.types` - shared array/dict type aliases.
5
+ - :mod:`chromapi.kinematics.topology` - leg/joint naming (no numbers).
6
+ - :mod:`chromapi.kinematics.poses` - named joint configurations (rest/approach/wake-up/zero).
7
+ - :mod:`chromapi.kinematics.kromatics` - :class:`~chromapi.kinematics.kromatics.Kromatics`, the
8
+ whole-body kinematic solver (a single QP over all 12 joints, via Rhoban's ``placo``/
9
+ Pinocchio) used by :class:`chromapi.chromapi.Chromapi` and :mod:`chromapi.locomotion.gait`.
10
+ """