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
chromapi/cli.py ADDED
@@ -0,0 +1,106 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Chromapi command line: one ``chromapi`` command for every robot tool.
3
+
4
+ Usage::
5
+
6
+ chromapi run
7
+ chromapi version
8
+ chromapi calibrate servos --all
9
+ chromapi calibrate imu --dry-run
10
+ chromapi motors setup
11
+ chromapi health
12
+ chromapi flash
13
+ chromapi report
14
+ chromapi <command> --help
15
+ """
16
+
17
+ import argparse
18
+ import importlib
19
+ import sys
20
+ from typing import Any, Dict, List, Optional
21
+
22
+ from chromapi.chromapi import sdk_version
23
+ from chromapi.hardware.motherboard_bridge import BRIDGE_PROTOCOL_VERSION, BridgeClient
24
+
25
+ #: ``chromapi <group> <tool>`` -> (``module:function`` of a tool that parses its own arguments, help).
26
+ TOOLS: Dict[str, Any] = {
27
+ "calibrate": {
28
+ "servos": ("chromapi.utils.calibrate_servo_centers:main", "find each servo's center from its mechanical stops"),
29
+ "imu": ("chromapi.utils.calibrate_imu_mount:main", "measure the IMU board tilt on a level floor"),
30
+ },
31
+ "access": {
32
+ "reset": ("chromapi.web.access:reset_main", "forget the web app's access code: the next visitor chooses one"),
33
+ },
34
+ "gamepad": {
35
+ "pair": ("chromapi.input.pairing:main", "pair a Bluetooth controller (put it in pairing mode first)"),
36
+ },
37
+ "led": {
38
+ "error": ("chromapi.media.led:error_main", "light the ring red (the service does it when the app crashed)"),
39
+ },
40
+ "motors": {
41
+ "setup": ("chromapi.utils.setup_motors:main", "set each servo's ID and registers (--all: the 12 already assembled)"),
42
+ },
43
+ "run": ("chromapi.web.app:main", "start Chromapi and its web app (https://<robot-ip>:5000)"),
44
+ "sim": ("chromapi.utils.sim_server:main", "run the MuJoCo simulation on its own: scripts use Chromapi(backend=\"sim-server\")"),
45
+ "health": ("chromapi.utils.health:main", "what is wrong with Chromapi, and what to do about it"),
46
+ "flash": ("chromapi.utils.flash:main", "update the motherboard firmware (STM32)"),
47
+ "report": ("chromapi.utils.report:main", "write a support report to post on Discord"),
48
+ }
49
+
50
+
51
+ def version(port: str) -> int:
52
+ """Print the SDK, firmware and bridge protocol versions; return 1 if they can't work together."""
53
+ print(f"chromapi SDK {sdk_version()} · bridge protocol {BRIDGE_PROTOCOL_VERSION}")
54
+ bridge = BridgeClient(port=port)
55
+ if not bridge.connect():
56
+ print(f"firmware unknown (cannot open {port})")
57
+ return 1
58
+ try:
59
+ fw = bridge.get_version()
60
+ finally:
61
+ bridge.close()
62
+ if fw is None:
63
+ print("firmware older than 2.0.0, or not answering - update it")
64
+ return 1
65
+ protocol, (major, minor, patch) = fw
66
+ print(f"firmware {major}.{minor}.{patch} · bridge protocol {protocol}")
67
+ if protocol != BRIDGE_PROTOCOL_VERSION:
68
+ print(f"[!] protocol mismatch: firmware {protocol}, SDK {BRIDGE_PROTOCOL_VERSION} - update one of them")
69
+ return 1
70
+ return 0
71
+
72
+
73
+ def _run_tool(name: str, target: str, args: List[str]) -> None:
74
+ """Run a tool's own CLI on ``args``, under its ``chromapi ...`` name."""
75
+ module, function = target.split(":")
76
+ sys.argv = [name, *args] # the tool parses sys.argv itself
77
+ sys.exit(getattr(importlib.import_module(module), function)())
78
+
79
+
80
+ def main(argv: Optional[List[str]] = None) -> None:
81
+ """Dispatch ``chromapi <command>``."""
82
+ parser = argparse.ArgumentParser(prog="chromapi", description=__doc__.splitlines()[0])
83
+ commands = parser.add_subparsers(dest="command", required=True, metavar="<command>")
84
+ version_parser = commands.add_parser("version", help="SDK, firmware and bridge protocol versions")
85
+ version_parser.add_argument("--port", default="/dev/ttyAMA0", help="serial port to the STM32 bridge")
86
+ for name, entry in TOOLS.items():
87
+ if isinstance(entry, tuple):
88
+ tool = commands.add_parser(name, help=entry[1], add_help=False)
89
+ tool.set_defaults(target=entry[0], name=f"chromapi {name}")
90
+ continue
91
+ group = commands.add_parser(name, help=", ".join(entry)).add_subparsers(required=True, metavar="<tool>")
92
+ for tool_name, (target, help_text) in entry.items():
93
+ tool = group.add_parser(tool_name, help=help_text, add_help=False)
94
+ tool.set_defaults(target=target, name=f"chromapi {name} {tool_name}")
95
+
96
+ # Unknown arguments belong to the tool (argparse.REMAINDER would reject a leading --help).
97
+ args, tool_args = parser.parse_known_args(argv)
98
+ if args.command == "version":
99
+ if tool_args:
100
+ parser.error(f"unrecognized arguments: {' '.join(tool_args)}")
101
+ sys.exit(version(args.port))
102
+ _run_tool(args.name, args.target, tool_args)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
@@ -0,0 +1,118 @@
1
+ camera:
2
+ camera_matrix:
3
+ - - 307.9005275582122
4
+ - 0.0
5
+ - 326.08287547037986
6
+ - - 0.0
7
+ - 307.9432072951142
8
+ - 235.95634050668792
9
+ - - 0.0
10
+ - 0.0
11
+ - 1.0
12
+ dist_coeffs:
13
+ - - -0.022444170194783026
14
+ - - -0.028276126105961166
15
+ - - 0.03268006024045968
16
+ - - -0.01659105741326503
17
+ model: fisheye
18
+ per_frame_errors:
19
+ - 0.09989427030086517
20
+ - 0.19589051604270935
21
+ - 0.1691097468137741
22
+ - 0.07466690242290497
23
+ - 0.20179392397403717
24
+ - 0.22518488764762878
25
+ - 0.30351585149765015
26
+ - 0.22308585047721863
27
+ - 0.13207602500915527
28
+ - 0.26898372173309326
29
+ - 0.22857339680194855
30
+ - 0.23996774852275848
31
+ - 0.19337213039398193
32
+ - 0.15066125988960266
33
+ - 0.17457318305969238
34
+ resolution:
35
+ - 640
36
+ - 480
37
+ rms_error: 0.2437574021099268
38
+
39
+ servos:
40
+ id_map:
41
+ tl_1: 1
42
+ tl_2: 2
43
+ tl_3: 3
44
+ bl_1: 4
45
+ bl_2: 5
46
+ bl_3: 6
47
+ br_1: 7
48
+ br_2: 8
49
+ br_3: 9
50
+ tr_1: 10
51
+ tr_2: 11
52
+ tr_3: 12
53
+ # Direction multiplier (+1/-1) applied when converting radians -> raw steps, to
54
+ # absorb any servo mounted as a mirror image of the URDF's assumed orientation.
55
+ sign:
56
+ tl_1: -1
57
+ tl_2: -1
58
+ tl_3: -1
59
+ tr_1: 1
60
+ tr_2: 1
61
+ tr_3: 1
62
+ bl_1: -1
63
+ bl_2: -1
64
+ bl_3: -1
65
+ br_1: 1
66
+ br_2: 1
67
+ br_3: 1
68
+ # Raw-step offset added after scaling, to align the servo's own internal zero with the kinematic q=0.
69
+ zero_offset_steps:
70
+ tl_1: 0
71
+ tl_2: 0
72
+ tl_3: 0
73
+ tr_1: 0
74
+ tr_2: 0
75
+ tr_3: 0
76
+ bl_1: 0
77
+ bl_2: 0
78
+ bl_3: 0
79
+ br_1: 0
80
+ br_2: 0
81
+ br_3: 0
82
+
83
+ imu:
84
+ mount_offset_wxyz: [1.0, 0.0, 0.0, 0.0]
85
+
86
+ battery:
87
+ # 2S Li-ion. Measured on a full discharge trotting at 0.08 m/s (1.3 A, 1 h 49, 2370 mAh, 17 Wh):
88
+ resistance_ohm: 0.245 # [Ω]
89
+ smoothing_s: 10.0 # [s]
90
+ ocv_table: # [V + I·R [V], charge [%]]; 0 % = 6.4 V under 1.3 A, the endurance test cutoff
91
+ - [6.777, 0]
92
+ - [6.958, 10]
93
+ - [7.125, 20]
94
+ - [7.253, 30]
95
+ - [7.392, 40]
96
+ - [7.549, 50]
97
+ - [7.668, 60]
98
+ - [7.822, 70]
99
+ - [7.964, 80]
100
+ - [8.083, 90]
101
+ - [8.257, 100]
102
+ low_percent: 30.0 # [%]
103
+ critical_percent: 10.0 # [%]
104
+
105
+ audio:
106
+ speaker: ""
107
+ volume: 0.25
108
+ mic_gain: 30.0
109
+ mic_denoise: true
110
+
111
+ moves:
112
+ dataset: "" # a Hugging Face dataset (e.g. "Mowibox/chromaposes") added to the bundled moves; empty: none
113
+
114
+ control:
115
+ loop_hz: 100.0
116
+ wake_up_duration_s: 2.5
117
+ rest_duration_s: 2.0
118
+ approach_duration_s: 2.0
@@ -0,0 +1,6 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """State estimation layer for Chromapi.
3
+
4
+ - :mod:`chromapi.estimation.attitude` - projected gravity, roll/pitch, tilt and
5
+ :class:`~chromapi.estimation.attitude.ImuMount`, from the firmware's Mahony quaternion.
6
+ """
@@ -0,0 +1,107 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Attitude helpers for Chromapi - tilt from the IMU quaternion.
3
+
4
+ The STM32 runs the Mahony filter and sends a unit quaternion
5
+ (w, x, y, z), world Z up.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ from dataclasses import dataclass
12
+ from typing import Iterable, Sequence, Tuple
13
+
14
+ import numpy as np
15
+ import numpy.typing as npt
16
+
17
+ #: Unit quaternion (w, x, y, z).
18
+ Quaternion = Tuple[float, float, float, float]
19
+
20
+ IDENTITY_QUAT: Quaternion = (1.0, 0.0, 0.0, 0.0)
21
+
22
+
23
+ def quat_multiply(a: Sequence[float], b: Sequence[float]) -> Quaternion:
24
+ """Hamilton product between two quaternions (w, x, y, z)."""
25
+ aw, ax, ay, az = a
26
+ bw, bx, by, bz = b
27
+ return (
28
+ aw * bw - ax * bx - ay * by - az * bz,
29
+ aw * bx + ax * bw + ay * bz - az * by,
30
+ aw * by - ax * bz + ay * bw + az * bx,
31
+ aw * bz + ax * by - ay * bx + az * bw,
32
+ )
33
+
34
+
35
+ def quat_conjugate(q: Sequence[float]) -> Quaternion:
36
+ """Inverse of a unit quaternion."""
37
+ w, x, y, z = q
38
+ return (w, -x, -y, -z)
39
+
40
+
41
+ def projected_gravity(q: Sequence[float]) -> npt.NDArray[np.float64]:
42
+ """Unit gravity vector in the body frame, (0, 0, -1) when level."""
43
+ w, x, y, z = q
44
+ return -np.array(
45
+ [
46
+ 2.0 * (x * z - w * y),
47
+ 2.0 * (w * x + y * z),
48
+ w * w - x * x - y * y + z * z,
49
+ ]
50
+ )
51
+
52
+
53
+
54
+ def roll_pitch_from_gravity(g_body: npt.NDArray[np.float64]) -> Tuple[float, float]:
55
+ """(roll, pitch) [rad] of the ZYX (yaw-pitch-roll) convention, from projected gravity."""
56
+ gx, gy, gz = g_body
57
+ roll = math.atan2(-gy, -gz)
58
+ pitch = math.atan2(gx, math.hypot(gy, gz))
59
+ return roll, pitch
60
+
61
+
62
+ def roll_pitch(q: Sequence[float]) -> Tuple[float, float]:
63
+ """(roll, pitch) [rad] of ``q`` - same as ZYX Euler angles, without the yaw."""
64
+ return roll_pitch_from_gravity(projected_gravity(q))
65
+
66
+
67
+ def tilt(q: Sequence[float]) -> float:
68
+ """Angle [rad] between the body Z axis and the vertical."""
69
+ return math.acos(float(np.clip(-projected_gravity(q)[2], -1.0, 1.0)))
70
+
71
+
72
+ def quat_from_roll_pitch(roll: float, pitch: float) -> Quaternion:
73
+ """Quaternion of ``Ry(pitch).Rx(roll)``."""
74
+ cr, sr = math.cos(roll / 2.0), math.sin(roll / 2.0)
75
+ cp, sp = math.cos(pitch / 2.0), math.sin(pitch / 2.0)
76
+ return (cp * cr, cp * sr, sp * cr, -sp * sr)
77
+
78
+
79
+ def remove_yaw(q: Sequence[float]) -> Quaternion:
80
+ """Removing the yaw component: same tilt, safe to feed a controller or a policy."""
81
+ return quat_from_roll_pitch(*roll_pitch(q))
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class ImuMount:
86
+ """Fixed sensor-to-chassis tilt offset (board not perfectly level on the chassis)."""
87
+
88
+ offset: Quaternion = IDENTITY_QUAT
89
+
90
+ @classmethod
91
+ def from_level_samples(cls, quats: Iterable[Sequence[float]]) -> "ImuMount":
92
+ """Calibrate from quaternions recorded with the chassis level and still."""
93
+ gravities = [projected_gravity(q) for q in quats]
94
+ if not gravities:
95
+ raise ValueError("ImuMount.from_level_samples: no samples")
96
+ g_mean = np.mean(gravities, axis=0) # averaged as vectors: no quaternion sign ambiguity
97
+ return cls(quat_from_roll_pitch(*roll_pitch_from_gravity(g_mean / np.linalg.norm(g_mean))))
98
+
99
+ def apply(self, q: Sequence[float]) -> Quaternion:
100
+ """Chassis orientation from the sensor one: ``q ⊗ offset⁻¹``."""
101
+ return quat_multiply(q, quat_conjugate(self.offset))
102
+
103
+ def apply_vector(self, v: Sequence[float]) -> Tuple[float, float, float]:
104
+ """Sensor-frame vector (gyro, accel) expressed in the chassis frame: ``R(offset) v``."""
105
+ w, x, y, z = self.offset
106
+ rotated = quat_multiply(quat_multiply(self.offset, (0.0, *v)), (w, -x, -y, -z))
107
+ return (rotated[1], rotated[2], rotated[3])
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Hardware Module for Chromapi."""
@@ -0,0 +1,54 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Battery charge estimate from the INA226 reading: ``V + I·R`` smoothed, voltage -> % table conversion."""
3
+
4
+ from typing import Any, Dict, Optional
5
+
6
+ import numpy as np
7
+
8
+ OK, LOW, CRITICAL, EMPTY = "ok", "low", "critical", "empty"
9
+
10
+
11
+ class Battery:
12
+ """Charge estimate, updated with every power reading."""
13
+
14
+ def __init__(self, config: Dict[str, Any]) -> None:
15
+ """Build from the battery section of ``config.yaml``."""
16
+ table = np.array(sorted(config["ocv_table"]), dtype=float) # rows (V_ocv [V], charge [%])
17
+ self._ocv_v, self._ocv_percent = table[:, 0], table[:, 1]
18
+ self.resistance_ohm: float = float(config["resistance_ohm"]) # [Ω]
19
+ self.smoothing_s: float = float(config["smoothing_s"]) # [s]
20
+ self.low_percent: float = float(config["low_percent"]) # [%]
21
+ self.critical_percent: float = float(config["critical_percent"]) # [%]
22
+ self.ocv_v: Optional[float] = None # [V] smoothed V + I·R; None until the first reading
23
+ self._last_t: Optional[float] = None # [s]
24
+
25
+ def update(self, voltage_v: float, current_a: float, t: float) -> None:
26
+ """Add a reading taken at time ``t`` [s]."""
27
+ if voltage_v <= 0.0:
28
+ return
29
+ ocv = voltage_v + current_a * self.resistance_ohm # [V]
30
+ if self.ocv_v is None or self._last_t is None:
31
+ self.ocv_v = ocv
32
+ else:
33
+ k = min(1.0, max(0.0, t - self._last_t) / self.smoothing_s) # low-pass filter
34
+ self.ocv_v += k * (ocv - self.ocv_v)
35
+ self._last_t = t
36
+
37
+ @property
38
+ def percent(self) -> Optional[float]:
39
+ """Charge left in %."""
40
+ if self.ocv_v is None:
41
+ return None
42
+ return float(np.interp(self.ocv_v, self._ocv_v, self._ocv_percent))
43
+
44
+ @property
45
+ def level(self) -> Optional[str]:
46
+ """``"ok"``, ``"low"`` (yellow), ``"critical"`` (red: no walking), ``"empty"`` (sit down); None if unread."""
47
+ percent = self.percent
48
+ if percent is None:
49
+ return None
50
+ if percent <= 0.0:
51
+ return EMPTY
52
+ if percent < self.critical_percent:
53
+ return CRITICAL
54
+ return LOW if percent < self.low_percent else OK
@@ -0,0 +1,165 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Cooling fan on the Raspberry Pi's hardware PWM, through ``/sys/class/pwm``.
3
+
4
+ ``deploy/chromapi-fan@.service`` runs :func:`main` for as long as the Pi is on, whatever else runs: it holds the
5
+ CPU near :data:`TARGET_TEMP_C`. Any process imposes a speed with
6
+ :func:`request`, and gives it back to the automatic mode with ``request(None)``.
7
+
8
+ Usage::
9
+
10
+ python3 -m chromapi.hardware.fan # what the service runs
11
+ """
12
+
13
+ import logging
14
+ import time
15
+ from pathlib import Path
16
+ from typing import Optional, Tuple
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ MODEL_PATH = Path("/proc/device-tree/model")
21
+
22
+
23
+ def _board_pwm_chip() -> int:
24
+ """GPIO 13's PWM chip: the SoC's on a Pi 4 / Zero 2W, the RP1's on a Pi 5."""
25
+ try:
26
+ model = MODEL_PATH.read_text()
27
+ except OSError:
28
+ return 0
29
+ return 2 if model.startswith("Raspberry Pi 5") else 0
30
+
31
+
32
+ PWM_CHIP = _board_pwm_chip()
33
+ PWM_CHANNEL = 1 # GPIO 13 is channel 1 on all three boards
34
+ PWM_FREQUENCY_HZ = 25_000 # [Hz]
35
+ TEMP_PATH = Path("/sys/class/thermal/thermal_zone0/temp")
36
+ OVERRIDE_PATH = Path("/run/chromapi/fan") # the service's RuntimeDirectory
37
+ TARGET_TEMP_C = 60.0 # [°C] the Pi 4 throttles from 80 °C
38
+ FULL_SPEED_TEMP_C = 75.0 # [°C] full speed whatever was requested
39
+ KP = 5.0 # [%.°C⁻¹]
40
+ KI = 0.1 # [%.°C⁻¹.s⁻¹]
41
+ MIN_RUN_PERCENT = 30.0 # [%] below, the fan may stall
42
+ PERIOD_S = 1.0 # [s] also the delay before a request applies
43
+ EXPORT_TIMEOUT_S = 2.0 # [s] for udev to set the exported channel's group
44
+
45
+
46
+ def _pwm_dir(chip: int = PWM_CHIP, channel: int = PWM_CHANNEL) -> Path:
47
+ return Path(f"/sys/class/pwm/pwmchip{chip}/pwm{channel}")
48
+
49
+
50
+ def cpu_temp_c() -> Optional[float]:
51
+ """CPU temperature [°C], None off a Pi."""
52
+ try:
53
+ return int(TEMP_PATH.read_text()) / 1000.0
54
+ except (OSError, ValueError):
55
+ return None
56
+
57
+
58
+ def request(percent: Optional[float]) -> bool:
59
+ """Impose a fan speed [%] on the fan service, or None for the automatic mode. False if the service is off."""
60
+ try:
61
+ OVERRIDE_PATH.write_text("auto" if percent is None else f"{min(max(float(percent), 0.0), 100.0):g}")
62
+ except OSError:
63
+ logger.warning("Fan service not running (no %s): request ignored", OVERRIDE_PATH.parent)
64
+ return False
65
+ return True
66
+
67
+
68
+ def requested() -> Optional[float]:
69
+ """The speed [%] imposed through :func:`request`, None in the automatic mode."""
70
+ try:
71
+ return float(OVERRIDE_PATH.read_text())
72
+ except (OSError, ValueError): # no file, or "auto"
73
+ return None
74
+
75
+
76
+ def status() -> Optional[Tuple[float, bool]]:
77
+ """(speed [%], automatic) as the service runs the fan, None if it is not running."""
78
+ if not OVERRIDE_PATH.parent.is_dir():
79
+ return None
80
+ try:
81
+ duty, period = (int((_pwm_dir() / name).read_text()) for name in ("duty_cycle", "period"))
82
+ except (OSError, ValueError):
83
+ return None
84
+ return 100.0 * duty / period, requested() is None
85
+
86
+
87
+ class Fan:
88
+ """One PWM channel driving the fan, and the automatic mode's state."""
89
+
90
+ def __init__(self, chip: int = PWM_CHIP, channel: int = PWM_CHANNEL, frequency_hz: int = PWM_FREQUENCY_HZ,
91
+ target_c: float = TARGET_TEMP_C) -> None:
92
+ """Export and configure the channel; :attr:`available` tells whether it worked."""
93
+ self._pwm = _pwm_dir(chip, channel)
94
+ self._period_ns = int(1e9 / frequency_hz) # [ns]
95
+ self.available = False
96
+ self.percent = 0.0 # [%]
97
+ self.target_c = target_c # [°C]
98
+ self._integral = 0.0 # [%]
99
+ deadline = time.monotonic() + EXPORT_TIMEOUT_S
100
+ while True:
101
+ try:
102
+ if not self._pwm.exists():
103
+ (self._pwm.parent / "export").write_text(str(channel))
104
+ (self._pwm / "period").write_text(str(self._period_ns))
105
+ (self._pwm / "duty_cycle").write_text("0")
106
+ (self._pwm / "enable").write_text("1")
107
+ break
108
+ except OSError as exc:
109
+ # Right after the export, udev has not yet handed the new channel's files to the gpio group.
110
+ if not isinstance(exc, PermissionError) or time.monotonic() > deadline:
111
+ logger.warning("Fan PWM unavailable (%s): no fan control", exc)
112
+ return
113
+ time.sleep(0.1)
114
+ self.available = True
115
+
116
+ def set_percent(self, percent: float) -> None:
117
+ """Fan speed [%], 0 to 100."""
118
+ if not self.available:
119
+ return
120
+ self.percent = max(0.0, min(100.0, float(percent)))
121
+ try:
122
+ (self._pwm / "duty_cycle").write_text(str(int(self._period_ns * self.percent / 100.0)))
123
+ except OSError:
124
+ logger.exception("Fan PWM write failed: no fan control from now on")
125
+ self.available = False
126
+
127
+ def resume_auto(self) -> None:
128
+ """Start the automatic mode again from the current speed (no jump)."""
129
+ self._integral = self.percent
130
+
131
+ def auto_percent(self, temp_c: float, dt: float) -> float:
132
+ """PI step on the CPU temperature: the speed [%] for ``temp_c`` [°C], ``dt`` [s] after the previous step."""
133
+ error = temp_c - self.target_c # [°C]
134
+ self._integral = min(max(self._integral + KI * error * dt, 0.0), 100.0) # clamped: no windup
135
+ percent = min(max(KP * error + self._integral, 0.0), 100.0)
136
+ if percent < MIN_RUN_PERCENT: # running: hold the minimum down to half of it, then stop
137
+ percent = MIN_RUN_PERCENT if self.percent > 0.0 and percent > MIN_RUN_PERCENT / 2 else 0.0
138
+ return percent
139
+
140
+
141
+ def main() -> int:
142
+ """Run the fan until the service stops; 1 if the PWM cannot be driven (systemd retries)."""
143
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
144
+ fan = Fan()
145
+ manual: Optional[float] = None
146
+ while fan.available:
147
+ temp = cpu_temp_c()
148
+ wanted = requested()
149
+ if wanted != manual:
150
+ logger.info("Fan %s", "automatic" if wanted is None else f"at {wanted:g} % (requested)")
151
+ if wanted is None:
152
+ fan.resume_auto()
153
+ manual = wanted
154
+ if temp is None or temp >= FULL_SPEED_TEMP_C:
155
+ fan.set_percent(100.0)
156
+ elif manual is not None:
157
+ fan.set_percent(manual)
158
+ else:
159
+ fan.set_percent(fan.auto_percent(temp, PERIOD_S))
160
+ time.sleep(PERIOD_S)
161
+ return 1
162
+
163
+
164
+ if __name__ == "__main__":
165
+ raise SystemExit(main())