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,210 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Chromapi health check: what is wrong, named plainly, with what to do about it.
3
+
4
+ Read-only: nothing moves. Exits with code 1 if any check fails, so scripts and the web app can use it too.
5
+
6
+ Usage::
7
+
8
+ chromapi health
9
+ """
10
+
11
+ import argparse
12
+ import getpass
13
+ import math
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Any, Dict, List, Tuple
20
+
21
+ import yaml
22
+
23
+ from chromapi.chromapi import USER_CALIBRATION_PATH, load_config
24
+ from chromapi.hardware.battery import CRITICAL, EMPTY, LOW, Battery
25
+ from chromapi.hardware.motherboard_bridge import BRIDGE_PROTOCOL_VERSION, BridgeClient
26
+
27
+ OK, WARN, FAIL = "OK", "WARN", "FAIL"
28
+ Result = Tuple[str, str, str] # (level, check, detail)
29
+
30
+ SNAPSHOTS = 5 # a servo missing one bus cycle is not a fault: it must answer in at least one snapshot
31
+ SERVO_HOT_C = 60 # [°C]
32
+ GRAVITY_TOLERANCE = 1.5 # [m.s⁻²] |acc| away from g by more than this: robot moving, or IMU wrong
33
+ SERVO_ID_RANGE = range(1, 253)
34
+ SOUND_CARD = "sndrpigooglevoi" # see deploy/asound.conf
35
+ AUDIO_KEEPALIVE = "chromapi-audio-keepalive"
36
+ FAN_SERVICE = "chromapi-fan@" # template unit, one instance per user: chromapi-fan@<user>
37
+ BOOT_CMDLINES = (Path("/boot/firmware/cmdline.txt"), Path("/boot/cmdline.txt"))
38
+
39
+
40
+ def port_users(port: str) -> List[str]:
41
+ """Return ``"<comm> (PID <pid>)"`` for every other process holding ``port`` open."""
42
+ target = os.path.realpath(port)
43
+ users = []
44
+ for proc in Path("/proc").glob("[0-9]*"):
45
+ if int(proc.name) == os.getpid():
46
+ continue
47
+ try:
48
+ if any(os.path.realpath(fd) == target for fd in (proc / "fd").iterdir()):
49
+ users.append(f"{(proc / 'comm').read_text().strip()} (PID {proc.name})")
50
+ except OSError: # process gone, or another user's
51
+ continue
52
+ return users
53
+
54
+
55
+ def check_system(port: str) -> List[Result]:
56
+ """Checks that need no bridge: serial console, port ownership, audio."""
57
+ results = []
58
+ for cmdline in BOOT_CMDLINES:
59
+ if cmdline.exists():
60
+ if any(c in cmdline.read_text() for c in ("console=serial0", "console=ttyAMA0")):
61
+ results.append((FAIL, "serial console", f"Linux console is on the bridge port ({cmdline}): "
62
+ "run 'sudo raspi-config nonint do_serial_cons 1' and reboot"))
63
+ else:
64
+ results.append((OK, "serial console", "off"))
65
+ break
66
+
67
+ users = port_users(port)
68
+ if users:
69
+ results.append((FAIL, "serial port", f"{port} already open by {', '.join(users)}: stop it first"))
70
+
71
+ if shutil.which("aplay") is None:
72
+ results.append((FAIL, "sound card", "aplay not found: sudo apt install alsa-utils"))
73
+ elif SOUND_CARD in subprocess.run(["aplay", "-l"], capture_output=True, text=True, check=False).stdout:
74
+ results.append((OK, "sound card", SOUND_CARD))
75
+ else:
76
+ results.append((FAIL, "sound card", f"{SOUND_CARD} not found by ALSA: check "
77
+ "'dtoverlay=googlevoicehat-soundcard' in config.txt and the I2S wiring"))
78
+
79
+ if shutil.which("systemctl"):
80
+ state = subprocess.run(["systemctl", "is-active", AUDIO_KEEPALIVE],
81
+ capture_output=True, text=True, check=False).stdout.strip()
82
+ if state == "active":
83
+ results.append((OK, "audio keep-alive", "active"))
84
+ else:
85
+ results.append((WARN, "audio keep-alive", f"{state or 'missing'}: the speaker will click, "
86
+ f"install deploy/{AUDIO_KEEPALIVE}.service"))
87
+ state = subprocess.run(["systemctl", "is-active", FAN_SERVICE + getpass.getuser()],
88
+ capture_output=True, text=True, check=False).stdout.strip()
89
+ if state == "active":
90
+ results.append((OK, "fan", "automatic, service active"))
91
+ else:
92
+ results.append((WARN, "fan", f"{state or 'missing'}: the fan is not driven, "
93
+ f"install deploy/{FAN_SERVICE}.service, then "
94
+ f"sudo systemctl enable --now {FAN_SERVICE}{getpass.getuser()}"))
95
+ return results
96
+
97
+
98
+ def check_calibration(path: Path) -> List[Result]:
99
+ """Is each calibration measured on this robot, rather than the package defaults?"""
100
+ try:
101
+ calibration: Dict[str, Any] = yaml.safe_load(path.read_text()) or {}
102
+ except FileNotFoundError:
103
+ calibration = {}
104
+ results = []
105
+ for section, key, label, command in (
106
+ ("servos", "zero_offset_steps", "servo centers", "chromapi calibrate servos --all"),
107
+ ("imu", "mount_offset_wxyz", "IMU mount", "chromapi calibrate imu"),
108
+ ):
109
+ if key in (calibration.get(section) or {}):
110
+ results.append((OK, label, f"calibrated ({path})"))
111
+ else:
112
+ results.append((WARN, label, f"using package defaults: run '{command}'"))
113
+ return results
114
+
115
+
116
+ def check_robot(bridge: Any, config: Dict[str, Any]) -> List[Result]:
117
+ """Checks through the bridge. ``bridge`` must be connected; nothing here moves the robot."""
118
+ id_map: Dict[str, int] = config["servos"]["id_map"]
119
+ if not bridge.ping():
120
+ return [(FAIL, "motherboard", "STM32 not answering: check the motherboard power and connection to the Pi")]
121
+ results = [(OK, "motherboard", "STM32 answering")]
122
+
123
+ version = bridge.get_version()
124
+ if version is None:
125
+ results.append((FAIL, "firmware", "older than 2.0.0 (no version command): update it"))
126
+ elif version[0] != BRIDGE_PROTOCOL_VERSION:
127
+ results.append((FAIL, "firmware", f"{'.'.join(map(str, version[1]))} speaks bridge protocol {version[0]}, "
128
+ f"this SDK speaks {BRIDGE_PROTOCOL_VERSION}: update one of them"))
129
+ else:
130
+ results.append((OK, "firmware", f"{'.'.join(map(str, version[1]))}, bridge protocol {version[0]}"))
131
+
132
+ snapshots = [s for s in (bridge.get_state(timeout=0.2) for _ in range(SNAPSHOTS)) if s is not None]
133
+ if not snapshots:
134
+ results.append((FAIL, "state", "no state snapshot: firmware and SDK out of sync?"))
135
+ return results
136
+ last = snapshots[-1]
137
+
138
+ battery = Battery(config["battery"])
139
+ for i, snap in enumerate(snapshots):
140
+ battery.update(snap["power"]["voltage_V"], snap["power"]["current_A"], 0.2 * i)
141
+ power = last["power"]
142
+ reading = f"{power['voltage_V']:.2f} V, {power['current_A']:.2f} A"
143
+ if battery.percent is None:
144
+ results.append((FAIL, "battery", "power monitor reads 0 V: INA226 / I2C problem"))
145
+ elif battery.level in (EMPTY, CRITICAL):
146
+ results.append((FAIL, "battery", f"{battery.percent:.0f} % ({reading}): too low to walk, need to charge"))
147
+ elif battery.level == LOW:
148
+ results.append((WARN, "battery", f"{battery.percent:.0f} % ({reading}): consider charging soon"))
149
+ else:
150
+ results.append((OK, "battery", f"{battery.percent:.0f} % ({reading})"))
151
+
152
+ acc = last["imu"]["acc_mps2"] # [m.s⁻²]
153
+ norm = math.sqrt(sum(a * a for a in acc)) # [m.s⁻²]
154
+ if norm == 0.0:
155
+ results.append((FAIL, "IMU", "accelerometer reads zeros: SPI link to the BMI088 dead?"))
156
+ elif abs(norm - 9.81) > GRAVITY_TOLERANCE:
157
+ results.append((WARN, "IMU", f"gravity reads {norm:.2f} m/s²: keep Chromapi still and run again"))
158
+ else:
159
+ results.append((OK, "IMU", f"gravity {norm:.2f} m/s²"))
160
+
161
+ answering = {s["id"] for snap in snapshots for s in snap["servos"] if s["fresh"]}
162
+ missing = {joint: sid for joint, sid in id_map.items() if sid not in answering}
163
+ for joint, sid in missing.items():
164
+ results.append((FAIL, f"servo {joint}", f"id {sid} not answering: check its cable"))
165
+ if missing:
166
+ # The usual cause: a new servo still on its factory id, or two servos sharing one.
167
+ expected = set(id_map.values())
168
+ strays = [i for i in SERVO_ID_RANGE if i not in expected and bridge.ping_servo(i)]
169
+ for i in strays:
170
+ results.append((FAIL, "servo bus", f"a servo answers on unexpected id {i}: "
171
+ "give it its id with 'chromapi motors setup'"))
172
+ else:
173
+ results.append((OK, "servos", f"all {len(id_map)} answering"))
174
+ for s in last["servos"]:
175
+ if s["fresh"] and s["temp_C"] > SERVO_HOT_C:
176
+ results.append((WARN, f"servo id {s['id']}", f"{s['temp_C']} °C: let it cool down"))
177
+ return results
178
+
179
+
180
+ def run_checks(port: str, calibration_path: Path) -> List[Result]:
181
+ """Run every check and return the results, in order."""
182
+ results = check_system(port) + check_calibration(calibration_path)
183
+ bridge = BridgeClient(port=port)
184
+ if not bridge.connect():
185
+ return results + [(FAIL, "serial port", f"cannot open {port}: is the UART enabled in config.txt?")]
186
+ try:
187
+ return results + check_robot(bridge, load_config(calibration_path=calibration_path))
188
+ finally:
189
+ bridge.close()
190
+
191
+
192
+ def main() -> int:
193
+ """Print the health report; return 1 if any check failed."""
194
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
195
+ parser.add_argument("--port", default="/dev/ttyAMA0", help="serial port to the STM32 bridge")
196
+ parser.add_argument("--calibration", type=Path, default=USER_CALIBRATION_PATH, help="calibration file")
197
+ args = parser.parse_args()
198
+
199
+ results = run_checks(args.port, args.calibration)
200
+ for level, check, detail in results:
201
+ print(f"[{level:^4}] {check}: {detail}")
202
+ failed = sum(level == FAIL for level, _, _ in results)
203
+ warned = sum(level == WARN for level, _, _ in results)
204
+ print(f"\n{'healthy' if not failed else f'{failed} problem(s)'}"
205
+ + (f", {warned} warning(s)" if warned else ""))
206
+ return 1 if failed else 0
207
+
208
+
209
+ if __name__ == "__main__":
210
+ sys.exit(main())
@@ -0,0 +1,75 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Support report: one text file with what helps to understand a problem, to post on forums.
3
+
4
+ Versions, health, calibration, services, recent logs. No passwords and no network configuration: the robot is
5
+ named by its serial number, LAN addresses in the logs are masked.
6
+
7
+ Usage::
8
+
9
+ chromapi report
10
+ """
11
+
12
+ import argparse
13
+ import re
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ from pathlib import Path
18
+ from typing import List
19
+
20
+ from chromapi.chromapi import USER_CALIBRATION_PATH
21
+
22
+ _LAN_IP = re.compile(r"\b(?:10(?:\.\d{1,3}){3}|172\.(?:1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}|192\.168(?:\.\d{1,3}){2})\b")
23
+
24
+ BRIDGE_COMMANDS: List[List[str]] = [ # they open the serial port: not while a robot program holds it
25
+ [sys.executable, "-m", "chromapi", "version"],
26
+ [sys.executable, "-m", "chromapi", "health"],
27
+ ]
28
+ COMMANDS: List[List[str]] = [
29
+ ["cat", "/proc/device-tree/model"],
30
+ ["cat", "/proc/device-tree/serial-number"],
31
+ ["uname", "-a"],
32
+ [sys.executable, "--version"],
33
+ ["uptime"],
34
+ ["vcgencmd", "get_throttled"], # under-voltage and throttling since boot
35
+ ["vcgencmd", "measure_temp"],
36
+ ["cat", str(USER_CALIBRATION_PATH)],
37
+ ["systemctl", "status", "--no-pager", "chromapi@*", "chromapi-audio-keepalive", "chromapi-fan@*"],
38
+ ["journalctl", "--no-pager", "-n", "300", "-u", "chromapi@*"],
39
+ [sys.executable, "-m", "pip", "list"],
40
+ ]
41
+
42
+
43
+ def run(command: List[str]) -> str:
44
+ """Output of ``command`` (stdout and stderr), or why it could not run."""
45
+ try:
46
+ done = subprocess.run(command, capture_output=True, text=True, timeout=30, check=False)
47
+ except (OSError, subprocess.TimeoutExpired) as e:
48
+ return f"[not run: {e}]\n"
49
+ output = (done.stdout + done.stderr).replace("\0", "") # /proc/device-tree files end with a NUL
50
+ return _LAN_IP.sub("<lan-ip>", output)
51
+
52
+
53
+ def write_report(path: Path, use_bridge: bool = True, extra: str = "") -> Path:
54
+ """Write the report to ``path``; ``extra`` (e.g. the live robot state) goes at the end."""
55
+ with open(path, "w") as f:
56
+ for command in (BRIDGE_COMMANDS if use_bridge else []) + COMMANDS:
57
+ f.write(f"$ {' '.join(command)}\n{run(command)}\n")
58
+ f.write(extra)
59
+ return path
60
+
61
+
62
+ def main() -> int:
63
+ """Write the report in the home folder and print its path."""
64
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
65
+ parser.add_argument("--output", type=Path, help="report file (default: ~/chromapi_report_<date>.txt)")
66
+ args = parser.parse_args()
67
+
68
+ path = args.output or Path.home() / f"chromapi_report_{time.strftime('%Y%m%d-%H%M%S')}.txt"
69
+ write_report(path)
70
+ print(f"Report written to {path}.")
71
+ return 0
72
+
73
+
74
+ if __name__ == "__main__":
75
+ sys.exit(main())
@@ -0,0 +1,189 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Motor Setup and Full Provisioning Tool.
3
+
4
+ Usage::
5
+
6
+ chromapi motors setup # new servos: give each its ID, one servo on the bus at a time
7
+ chromapi motors setup --all # assembled robot: rewrite the registers of all 12, IDs unchanged
8
+ chromapi motors setup --id N # the new servo (ID 1) becomes N, no prompt
9
+ """
10
+
11
+ import argparse
12
+ import time
13
+ from typing import Dict, List, Optional
14
+
15
+ from chromapi.chromapi import load_config
16
+ from chromapi.hardware.motherboard_bridge import BridgeClient
17
+
18
+ FACTORY_ID = 1
19
+ # Feetech STS3215 Register Map
20
+ REG_ID = 5
21
+ REG_MAX_VOLT = 14
22
+ REG_MIN_VOLT = 15
23
+ REG_UNLOAD_COND = 19
24
+ REG_P = 21
25
+ REG_D = 22
26
+ REG_I = 23
27
+ REG_MODE = 33
28
+ REG_ACCEL = 41
29
+ REG_LOCK = 55
30
+ # Undocumented: acceleration cap of the internal motion profile.
31
+ REG_MAX_ACCEL = 85
32
+ MAX_ACCEL = 254
33
+ # What configure_servo() writes, as read_servo_config() reads it back.
34
+ EXPECTED = {"P": 32, "I": 0, "D": 0, "Acceleration": 0, "Max Accel": MAX_ACCEL, "Mode": 0,
35
+ "Max Voltage": 85, "Min Voltage": 60, "Unload Cond": 44}
36
+
37
+ def read_servo_config(bridge: BridgeClient, servo_id: int) -> Dict[str, Optional[int]]:
38
+ """Read back current configuration registers directly from the hardware."""
39
+ return {
40
+ "P": bridge.read_servo_register(servo_id, REG_P, 1),
41
+ "I": bridge.read_servo_register(servo_id, REG_I, 1),
42
+ "D": bridge.read_servo_register(servo_id, REG_D, 1),
43
+ "Acceleration": bridge.read_servo_register(servo_id, REG_ACCEL, 1),
44
+ "Max Accel": bridge.read_servo_register(servo_id, REG_MAX_ACCEL, 1),
45
+ "Mode": bridge.read_servo_register(servo_id, REG_MODE, 1),
46
+ "Max Voltage": bridge.read_servo_register(servo_id, REG_MAX_VOLT, 1),
47
+ "Min Voltage": bridge.read_servo_register(servo_id, REG_MIN_VOLT, 1),
48
+ "Unload Cond": bridge.read_servo_register(servo_id, REG_UNLOAD_COND, 1),
49
+ }
50
+
51
+ def configure_servo(bridge: BridgeClient, target_id: int, new_id: int) -> Dict[str, Optional[int]]:
52
+ """Unlock, configure, assign ID, and verify parameters; return the registers that read back wrong."""
53
+ print(f"[*] Unlocking EEPROM for ID {target_id}...")
54
+ bridge.write_servo_register(target_id, REG_LOCK, 1, 0)
55
+ time.sleep(0.05)
56
+
57
+ print("[*] Setting Voltage Limits: Min = 6.0V (60), Max = 8.5V (85)")
58
+ bridge.write_servo_register(target_id, REG_MIN_VOLT, 1, 60)
59
+ bridge.write_servo_register(target_id, REG_MAX_VOLT, 1, 85)
60
+
61
+ print("[*] Setting Unload Condition = 44 (no torque cut on voltage)")
62
+ bridge.write_servo_register(target_id, REG_UNLOAD_COND, 1, 44)
63
+
64
+ print(f"[*] Setting Mode = 0 (Position), Acceleration = 0, Max Accel = {MAX_ACCEL}")
65
+ bridge.write_servo_register(target_id, REG_MODE, 1, 0)
66
+ bridge.write_servo_register(target_id, REG_ACCEL, 1, 0)
67
+ bridge.write_servo_register(target_id, REG_MAX_ACCEL, 1, MAX_ACCEL)
68
+
69
+ print("[*] Setting PID = (32, 0, 0)")
70
+ bridge.write_servo_register(target_id, REG_P, 1, 32)
71
+ bridge.write_servo_register(target_id, REG_D, 1, 0)
72
+ bridge.write_servo_register(target_id, REG_I, 1, 0)
73
+
74
+ if target_id != new_id:
75
+ print(f"[*] Changing ID to {new_id}...")
76
+ bridge.write_servo_register(target_id, REG_ID, 1, new_id)
77
+ time.sleep(0.05)
78
+
79
+ print("[*] Locking EEPROM...")
80
+ bridge.write_servo_register(new_id, REG_LOCK, 1, 1)
81
+
82
+ time.sleep(0.1)
83
+
84
+ print("\n" + "="*40)
85
+ print(f" VERIFYING MOTOR CONFIGURATION FOR ID {new_id}")
86
+ print("="*40)
87
+
88
+ cfg = read_servo_config(bridge, new_id)
89
+ wrong = {key: val for key, val in cfg.items() if key in EXPECTED and val != EXPECTED[key]}
90
+
91
+ for key, val in cfg.items():
92
+ if val is None:
93
+ print(f" {key:12} : [ERROR] Hardware read timeout")
94
+ else:
95
+ print(f" {key:12} : {val}")
96
+ print("="*40)
97
+ print(" Max Accel only applies after a servo power cycle.")
98
+ return wrong
99
+
100
+ def setup_one(bridge: BridgeClient, new_id: int, ids: List[int]) -> int:
101
+ """Assembly step: the new servo (ID 1) becomes ``new_id``; steps go from the highest ID down, one servo at a time."""
102
+ if new_id not in ids:
103
+ print(f"[!] ID {new_id} is not one of the robot's servos {ids} (config servos.id_map).")
104
+ return 1
105
+ missing = [i for i in ids if i > new_id and not bridge.ping_servo(i)]
106
+ if missing:
107
+ print(f"[!] Servos set up before not answering: {missing}. Check the chain, or set them up again.")
108
+ return 1
109
+ if new_id != FACTORY_ID and bridge.ping_servo(new_id):
110
+ print(f"[*] A servo already answers at ID {new_id}: rewriting its registers.")
111
+ target = new_id
112
+ elif bridge.ping_servo(FACTORY_ID):
113
+ target = FACTORY_ID
114
+ else:
115
+ print(f"[!] No servo answers at the factory ID {FACTORY_ID}: plug in the new servo.")
116
+ return 1
117
+ wrong = configure_servo(bridge, target, new_id)
118
+ if wrong:
119
+ print(f"[!] Read back different from what was written (lost frame?): {wrong}. Run again.")
120
+ return 1
121
+ print(f"[SUCCESS] Servo {new_id} set up" + (": power-cycle the robot so that Max Accel applies."
122
+ if new_id == min(ids) else "."))
123
+ return 0
124
+
125
+
126
+ def main() -> int:
127
+ """Run the interactive prompt for servo provisioning, or reconfigure every servo with ``--all``."""
128
+ parser = argparse.ArgumentParser(description="Set each servo's ID and registers.")
129
+ parser.add_argument("--all", action="store_true",
130
+ help="rewrite the registers of every servo of the robot, keeping their IDs")
131
+ parser.add_argument("--id", type=int, help="assembly step without a prompt: the new servo at ID 1 gets this ID")
132
+ args = parser.parse_args()
133
+
134
+ bridge = BridgeClient()
135
+ if not bridge.connect():
136
+ return 1
137
+
138
+ if args.id is not None:
139
+ try:
140
+ return setup_one(bridge, args.id, sorted(load_config()["servos"]["id_map"].values()))
141
+ finally:
142
+ bridge.close()
143
+
144
+ if args.all:
145
+ try:
146
+ missing, wrong = [], {}
147
+ for servo_id in sorted(load_config()["servos"]["id_map"].values()):
148
+ if bridge.ping_servo(servo_id):
149
+ wrong_regs = configure_servo(bridge, servo_id, servo_id)
150
+ if wrong_regs:
151
+ wrong[servo_id] = wrong_regs
152
+ else:
153
+ missing.append(servo_id)
154
+ finally:
155
+ bridge.close()
156
+ if missing:
157
+ print(f"[!] Not answering, not configured: {missing}. Check their cables and run again.")
158
+ if wrong:
159
+ print(f"[!] Read back different from what was written (lost frame?): {wrong}. Run again.")
160
+ if missing or wrong:
161
+ return 1
162
+ print("\n[*] All servos configured. Power-cycle the robot so that Max Accel applies.")
163
+ return 0
164
+
165
+ try:
166
+ while True:
167
+ print("\n--------------------------------------------------")
168
+ target_id_str = input("Enter the NEW desired ID (or 'q' to quit): ")
169
+ if target_id_str.lower() == 'q':
170
+ break
171
+
172
+ new_id = int(target_id_str)
173
+ if new_id < 1 or new_id > 253:
174
+ print("The ID must be between 1 and 253.")
175
+ continue
176
+ print(f"[*] New target ID: {new_id}")
177
+ input("-> Connect ONLY the target servo, then press ENTER...")
178
+ configure_servo(bridge, 254, new_id)
179
+ print("-> Disconnect the servo before continuing.")
180
+ time.sleep(1)
181
+
182
+ except ValueError:
183
+ print("[!] Invalid input. Program aborted.")
184
+ finally:
185
+ bridge.close()
186
+ return 0
187
+
188
+ if __name__ == "__main__":
189
+ main()
@@ -0,0 +1,126 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Run the MuJoCo simulation on its own: scripts drive it with ``Chromapi(backend="sim-server")``.
3
+
4
+ The simulation stands in for the motherboard: a script keeps the whole SDK, and can stop and start again
5
+ while the simulation (and the robot where it left it) goes on. One script at a time, as on the robot.
6
+
7
+ Usage::
8
+
9
+ chromapi sim # viewer window: close it to stop
10
+ chromapi sim --follow # the camera follows the robot
11
+ chromapi sim --headless # execution without window (Ctrl+C to stop)
12
+
13
+ then, in another terminal::
14
+
15
+ python my_script.py # with Chromapi(backend="sim-server")
16
+ """
17
+
18
+ import argparse
19
+ import logging
20
+ import threading
21
+ import time
22
+ from multiprocessing.connection import Connection, Listener
23
+ from typing import Any, Optional, Tuple
24
+
25
+ from chromapi.chromapi import SIM_ADDRESS, SIM_AUTHKEY, MuJoCoBackend
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ #: What a script may call: the RobotBackend methods, nothing else
30
+ CALLS = frozenset({"send_joint_targets", "read_state", "set_torque_enabled", "set_led_all", "set_led", "set_led_bulk"})
31
+ IDLE_STEP_S = 0.02 # [s] no script stepping it: the simulation steps itself at this period
32
+
33
+
34
+ class SimServer:
35
+ """Serves one :class:`MuJoCoBackend` to the scripts, one at a time."""
36
+
37
+ def __init__(self, backend: MuJoCoBackend, address: Tuple[str, int] = SIM_ADDRESS) -> None:
38
+ """Listen on ``address`` (OSError if taken: another simulation runs)."""
39
+ self.backend = backend
40
+ self._listener = Listener(address, authkey=SIM_AUTHKEY)
41
+ self.address: Tuple[str, int] = self._listener.address # type: ignore[assignment] # TCP: (host, port)
42
+ self._lock = threading.Lock() # the backend: the script's calls and the idle steps
43
+ self._last_step = 0.0 # [s] monotonic
44
+ self._driver: Optional[Connection] = None # the script driving the simulation
45
+
46
+ def call(self, name: str, args: Tuple[Any, ...]) -> Any:
47
+ """The result of ``backend.name(*args)``, or the exception to raise in the script."""
48
+ if name not in CALLS:
49
+ return ValueError(f"not a simulation call: {name!r}")
50
+ with self._lock:
51
+ try:
52
+ result = getattr(self.backend, name)(*args)
53
+ except Exception as exc: # raised in the script, the simulation goes on
54
+ return exc
55
+ if name == "send_joint_targets":
56
+ self._last_step = time.monotonic()
57
+ return result
58
+
59
+ def step_when_idle(self) -> None:
60
+ """Keep the physics going (targets held) while no script steps it."""
61
+ with self._lock:
62
+ if time.monotonic() - self._last_step > IDLE_STEP_S:
63
+ self.backend.send_joint_targets({})
64
+ self._last_step = time.monotonic()
65
+
66
+ def serve_forever(self) -> None:
67
+ """Accept the scripts, each in its own thread."""
68
+ while True:
69
+ try:
70
+ conn = self._listener.accept()
71
+ except Exception as exc: # wrong key, or a connection dropped during the handshake
72
+ logger.warning("Connection refused: %s", exc)
73
+ continue
74
+ threading.Thread(target=self._serve, args=(conn,), name="chromapi-sim-client", daemon=True).start()
75
+
76
+ def _serve(self, conn: Connection) -> None:
77
+ with conn:
78
+ if self._driver is not None:
79
+ conn.recv()
80
+ conn.send(RuntimeError("A script is already driving the simulation: stop it first"))
81
+ return
82
+ self._driver = conn
83
+ logger.info("Script connected")
84
+ try:
85
+ while True:
86
+ name, args = conn.recv()
87
+ conn.send(self.call(name, args))
88
+ except (EOFError, OSError):
89
+ pass
90
+ except Exception:
91
+ logger.exception("Script dropped: bad request")
92
+ finally:
93
+ self._driver = None
94
+ logger.info("Script left: the simulation goes on")
95
+
96
+
97
+ def main() -> int:
98
+ """Run the simulation until its window is closed (or Ctrl+C)."""
99
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
100
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
101
+ parser.add_argument("--headless", action="store_true", help="no viewer window")
102
+ parser.add_argument("--follow", action="store_true", help="the camera follows the robot")
103
+ args = parser.parse_args()
104
+
105
+ backend = MuJoCoBackend(launch_viewer=not args.headless, follow_robot=args.follow)
106
+ try:
107
+ server = SimServer(backend)
108
+ except OSError as exc:
109
+ print(f"[!] Cannot listen on {SIM_ADDRESS[0]}:{SIM_ADDRESS[1]} ({exc}): is a simulation already running?")
110
+ return 1
111
+ backend.connect()
112
+ threading.Thread(target=server.serve_forever, name="chromapi-sim-server", daemon=True).start()
113
+ print(f'Simulation running on {server.address[0]}:{server.address[1]}: drive it with Chromapi(backend="sim-server")')
114
+ try:
115
+ while backend.is_alive():
116
+ server.step_when_idle()
117
+ time.sleep(IDLE_STEP_S / 2)
118
+ except KeyboardInterrupt:
119
+ pass
120
+ finally:
121
+ backend.close()
122
+ return 0
123
+
124
+
125
+ if __name__ == "__main__":
126
+ raise SystemExit(main())
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Web app served by ``chromapi run``: drive, state and maintenance from a browser."""