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/web/app.py ADDED
@@ -0,0 +1,1136 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Chromapi web app: drive Chromapi from a phone or a PC browser, watch its state, look after it.
3
+
4
+ Chromapi only moves on "Wake up"; the page sends intentions, never joint angles, and its sticks centre after
5
+ :data:`INPUT_TIMEOUT_S` of silence.
6
+
7
+ Usage::
8
+
9
+ chromapi run # on the robot
10
+ chromapi run --sim # on a PC, in simulation (MuJoCo)
11
+ """
12
+
13
+ import argparse
14
+ import functools
15
+ import getpass
16
+ import io
17
+ import json
18
+ import logging
19
+ import math
20
+ import os
21
+ import queue
22
+ import signal
23
+ import socket
24
+ import subprocess
25
+ import sys
26
+ import tempfile
27
+ import threading
28
+ import time
29
+ from pathlib import Path
30
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
31
+
32
+ import numpy as np
33
+ from flask import Flask, Response, request, send_file, send_from_directory, session
34
+ from flask_socketio import SocketIO
35
+
36
+ from chromapi.chromapi import (
37
+ AUDIO_DIR,
38
+ IDLE_LED_RGB,
39
+ Chromapi,
40
+ HardwareBackend,
41
+ load_config,
42
+ sdk_version,
43
+ )
44
+ from chromapi.estimation.attitude import tilt
45
+ from chromapi.hardware import fan as fan_service
46
+ from chromapi.hardware.battery import CRITICAL, EMPTY, LOW, OK
47
+ from chromapi.input.gamepad import GamepadInput
48
+ from chromapi.locomotion.balance import BalanceMove
49
+ from chromapi.locomotion.gait import WALK_POSTURE
50
+ from chromapi.locomotion.recorded_move import (
51
+ EMOTE_MAX_TILT_DEG,
52
+ RecordedLegMove,
53
+ RecordedMove,
54
+ RecordedMoves,
55
+ )
56
+ from chromapi.media import led
57
+ from chromapi.utils.flash import shipped_version, update_available
58
+ from chromapi.utils.report import write_report
59
+ from chromapi.web.access import MIN_CODE_LENGTH, Access, tls_certificate
60
+
61
+ logger = logging.getLogger(__name__)
62
+
63
+ STATIC_DIR = Path(__file__).resolve().parent / "static"
64
+ INPUT_TIMEOUT_S = 0.4 # [s]
65
+ JOYSTICK_DEADZONE = 0.12
66
+ NOMINAL_LINEAR_MPS = 0.12 # [m.s⁻¹] at 100 %
67
+ MAX_SPEED_SCALE = 2.0
68
+ LOW_BATTERY_SPEED_SCALE = 1.0 # speed cap when the battery is low
69
+ MIN_SPEED_SCALE = 0.25
70
+ BATTERY_MOODS: Dict[Optional[str], str] = {LOW: "tired", CRITICAL: "alert"}
71
+ _LEVEL_RANK: Dict[Optional[str], int] = {None: 0, OK: 0, LOW: 1, CRITICAL: 2, EMPTY: 3}
72
+ MAX_ANGULAR_RAD_S = math.radians(40.0) # [rad.s⁻¹]
73
+ MAX_LEAN_RAD = math.radians(6.0) # [rad] at full stick
74
+ MAX_LEAN_SHIFT_M = 0.03 # [m] at full stick
75
+ HEIGHT_RANGE_M = (-0.04, 0.02) # [m]
76
+ TICK_S = 0.02 # [s] teleop loop
77
+ # Gamepad: DualShock-like raw joystick numbers (``jstest /dev/input/js0``)
78
+ PAD_DEVICE = "/dev/input/js0"
79
+ PAD_CROSS, PAD_CIRCLE, PAD_TRIANGLE, PAD_SQUARE = "0", "1", "2", "3"
80
+ PAD_L1, PAD_L2, PAD_R2, PAD_SHARE, PAD_START, PAD_L3, PAD_R3 = "4", "6", "7", "8", "9", "11", "12"
81
+ PAD_IDLE_S = 1.0 # [s] at rest this long, the gamepad hands the sticks back to the page
82
+ PAD_RETRY_S = 2.0 # [s] how often to look for a gamepad
83
+ PAD_SHUTDOWN_HOLD_S = 3.0 # [s] START held
84
+ PAD_HEIGHT_RATE_MPS = 0.02 # [m.s⁻¹] D-pad up/down held
85
+ PAD_SPEED_STEP = 0.25 # per D-pad press
86
+ PAD_TILT_FULL_RAD = math.radians(30.0) # [rad] controller tilt for a full lean
87
+ PAD_TILT_SIGNS = (1.0, -1.0) # (forward, right)
88
+ PAD_FLASH_S = led.BATTERY_FLASH_S # [s] battery or mood shown on the light bar
89
+ PAD_BATTERY_LOW_PERCENT = 20
90
+ PAD_BATTERY_CHECK_S = 10.0 # [s]
91
+ TELEMETRY_PERIOD_S = 0.2 # [s]
92
+ STATE_STALE_S = 1.0 # [s]
93
+ RECONNECT_S = 5.0 # [s]
94
+ HELD_LOAD = 30.0 # [0.1 % rated torque] above it at start-up, the firmware still holds the robot up
95
+ EMPTY_SHUTDOWN_S = 10.0 # [s] at 0 %, time to lie down before powering the Pi off
96
+ MAINTENANCE = {
97
+ "calibrate_imu": (["calibrate", "imu"], "Calibrating the IMU: keep Chromapi still on a level floor"),
98
+ "calibrate_servos": (["calibrate", "servos", "--all", "--yes"], "Calibrating the servos: keep the legs clear"),
99
+ "update_firmware": (["flash", "--yes"], "Updating the firmware: do not switch the robot off"),
100
+ "pair_gamepad": (["gamepad", "pair"], "Pairing: hold the controller's pair button until its light flashes fast"),
101
+ }
102
+ # New servos come with ID 1: set them up from the highest ID down
103
+ SERVO_SETUP = sorted(load_config()["servos"]["id_map"].items(), key=lambda joint_id: -joint_id[1])
104
+ MAINTENANCE.update({f"setup_servo_{i}": (["motors", "setup", "--id", str(i)], f"Setting up servo {i} ({joint})")
105
+ for joint, i in SERVO_SETUP})
106
+ MAINTENANCE_TIMEOUT_S = 15 * 60 # [s]
107
+ MAINTENANCE_CANCEL_S = 5.0 # [s] then killed
108
+ UNCANCELLABLE = {"update_firmware"} # stopped mid-flash, the board stays in reset
109
+ POWER_COMMANDS = {"shutdown": "poweroff", "reboot": "reboot", "quit": None} # page action -> systemctl command
110
+ # Talkie-walkie
111
+ TALK_RATE = 16000 # [Hz]
112
+ TALK_IDLE_S = 0.5 # [s]
113
+ TALK_MAX_CHUNK = 2 * TALK_RATE
114
+
115
+ RECORDING_SUFFIXES = ("_photo.jpg", "_camera.avi")
116
+ OPEN_ENDPOINTS = {"index", "favicon", "static", "auth_state", "auth_setup", "auth_login"}
117
+ SESSION_LIFETIME_S = 365 * 24 * 3600 # [s]
118
+ CODE_CHECK_S = 1.0 # [s] a new access code closes the open connections within this
119
+ GREETING_SOUND = AUDIO_DIR / "greeting.wav"
120
+ DATASET_MOOD = "happy" # ring and sound of a dataset move that names no (known) mood
121
+ FAVICON = AUDIO_DIR.parent / "favicon.ico"
122
+
123
+
124
+ def _in_circle(x: float, y: float) -> Tuple[float, float]:
125
+ """Clamp a stick to the unit circle."""
126
+ norm = math.hypot(x, y)
127
+ return (x / norm, y / norm) if norm > 1.0 else (x, y)
128
+
129
+
130
+ class WebInput:
131
+ """Latest sticks from the page, centred when the page goes silent."""
132
+
133
+ def __init__(self) -> None:
134
+ """Sticks centred, no message yet."""
135
+ self._lock = threading.Lock()
136
+ self._axes: Dict[str, float] = {}
137
+ self._last_s = float("-inf") # [s]
138
+
139
+ def set_axes(self, axes: Dict[str, Any]) -> None:
140
+ """Store ``lx``, ``ly``, ``rx``, ``ry`` in [-1, 1] (y up-positive), with a deadzone."""
141
+ clean = {}
142
+ for key in ("lx", "ly", "rx", "ry"):
143
+ value = min(max(float(axes.get(key, 0.0)), -1.0), 1.0)
144
+ clean[key] = 0.0 if abs(value) < JOYSTICK_DEADZONE else value
145
+ with self._lock:
146
+ self._axes, self._last_s = clean, time.monotonic()
147
+
148
+ def release(self) -> None:
149
+ """Centre the sticks now (last page disconnected)."""
150
+ with self._lock:
151
+ self._axes = {}
152
+
153
+ def read(self) -> Dict[str, float]:
154
+ """The sticks, all zero if the page has been silent for :data:`INPUT_TIMEOUT_S`."""
155
+ with self._lock:
156
+ if time.monotonic() - self._last_s >= INPUT_TIMEOUT_S:
157
+ self._axes = {}
158
+ return {key: self._axes.get(key, 0.0) for key in ("lx", "ly", "rx", "ry")}
159
+
160
+
161
+ class GamepadControl:
162
+ """The gamepad, driving the same :class:`Teleop` as the page; it takes over while moved."""
163
+
164
+ def __init__(self, device: str = PAD_DEVICE, open_pad: Callable[[str], Any] = GamepadInput) -> None:
165
+ """Nothing opened yet: :meth:`poll` looks for the device every :data:`PAD_RETRY_S`."""
166
+ self.device, self._open = device, open_pad
167
+ self._pad: Any = None
168
+ self._next_try = float("-inf") # [s]
169
+ self._failures = 0 # opening attempts failed in a row
170
+ self._held_before: Optional[Set[str]] = None
171
+ self._polled = float("-inf") # [s] last poll
172
+ self._shutdown_since: Optional[float] = None # [s] START held since; -inf once the shutdown is asked
173
+ self._last_active = float("-inf") # [s]
174
+ self.sticks = dict.fromkeys(("lx", "ly", "rx", "ry"), 0.0)
175
+ self.mood = 0 # index in led.MOODS, chosen with L2/R2
176
+ self.tilt_lean = False # Settings: in Lean mode, the controller's tilt leans the robot too
177
+ self._tilt_zero: Optional[Tuple[float, float]] = None # [rad] the controller's pose when tilting started
178
+ self._color: Optional[Tuple[int, int, int]] = None # last light bar colour sent
179
+ self._flash: Tuple[Tuple[int, int, int], float] = (IDLE_LED_RGB, float("-inf")) # (colour, until [s])
180
+ self.battery: Optional[Tuple[int, bool]] = None # (percent, charging) of the controller
181
+ self._battery_next = float("-inf") # [s]
182
+ self._battery_warned = False
183
+
184
+ @property
185
+ def connected(self) -> bool:
186
+ """A gamepad is open and still there."""
187
+ return self._pad is not None and self._pad.connected
188
+
189
+ def active(self, now: float) -> bool:
190
+ """The gamepad moved within :data:`PAD_IDLE_S`: it drives, the page's sticks wait."""
191
+ return self.connected and now - self._last_active < PAD_IDLE_S
192
+
193
+ def rumble(self, pulses: int) -> None:
194
+ """Buzz the controller, if there is one."""
195
+ if self.connected:
196
+ self._pad.rumble(pulses)
197
+
198
+ def close(self) -> None:
199
+ """The app stops: the light bar gets its own colour back."""
200
+ if self._pad is not None:
201
+ self._pad.stop()
202
+ self._pad = None
203
+
204
+ def _reconnect(self, now: float) -> bool:
205
+ if self.connected:
206
+ return True
207
+ self.close()
208
+ self.sticks = dict.fromkeys(self.sticks, 0.0)
209
+ self._held_before, self._shutdown_since, self._tilt_zero, self._color = None, None, None, None
210
+ self.battery, self._battery_next, self._battery_warned = None, float("-inf"), False
211
+ if now < self._next_try or not os.path.exists(self.device):
212
+ return False
213
+ self._next_try = now + PAD_RETRY_S
214
+ pad = self._open(self.device)
215
+ try:
216
+ pad.start()
217
+ except OSError as exc:
218
+ self._failures += 1 # a just-paired pad fails once, before udev sets js0's group
219
+ if self._failures == 2:
220
+ logger.warning("Gamepad: %s", exc)
221
+ return False
222
+ logger.info("Gamepad connected on %s", self.device)
223
+ self._pad, self._failures = pad, 0
224
+ return True
225
+
226
+ def poll(self, teleop: "Teleop", now: float) -> None:
227
+ """Read the gamepad: sticks for :meth:`Teleop._drive`, buttons as the page's actions."""
228
+ if not self._reconnect(now):
229
+ return
230
+ user = self._pad.read()
231
+ self.sticks = {"lx": user.lateral, "ly": user.forward, "rx": -user.turn, "ry": user.vertical}
232
+ self._pad.motion = self.tilt_lean and teleop.mode == "lean"
233
+ if self._pad.motion:
234
+ self._tilt_sticks()
235
+ else:
236
+ self._tilt_zero = None
237
+ held = set(user.held)
238
+ if held or any(self.sticks.values()):
239
+ self._last_active = now
240
+ # The D-pad only reports held directions: a press is a new one
241
+ before = held if self._held_before is None else self._held_before
242
+ self._held_before = held
243
+ for button in sorted(set(user.pressed) | (held - before)):
244
+ self._press(button, teleop, now)
245
+ self._hold_to_shutdown(held, teleop, now)
246
+ dt, self._polled = min(now - self._polled, 2 * TICK_S), now # [s]
247
+ rise = ("dpad_up" in held) - ("dpad_down" in held)
248
+ if rise:
249
+ teleop.height = min(max(teleop.height + rise * PAD_HEIGHT_RATE_MPS * dt, HEIGHT_RANGE_M[0]),
250
+ HEIGHT_RANGE_M[1])
251
+ color = self._flash[0] if now < self._flash[1] else led.dimmed(led.idle_color())
252
+ if color != self._color:
253
+ self._pad.set_color(color)
254
+ self._color = color
255
+ self._check_battery(teleop, now)
256
+
257
+ def _tilt_sticks(self) -> None:
258
+ """The controller's tilt since Lean started, as the right stick."""
259
+ gravity = self._pad.tilt()
260
+ if gravity is None:
261
+ return # no motion sensors: the right stick still leans
262
+ x, y, z = gravity
263
+ norm = math.sqrt(x * x + y * y + z * z) or 1.0
264
+ forward, right = math.atan2(z, y), math.asin(min(max(x / norm, -1.0), 1.0)) # [rad]
265
+ if self._tilt_zero is None:
266
+ self._tilt_zero = (forward, right)
267
+ if self.sticks["rx"] or self.sticks["ry"]:
268
+ return
269
+ tilt = ((forward - self._tilt_zero[0] + math.pi) % (2 * math.pi) - math.pi, right - self._tilt_zero[1])
270
+ for key, angle, sign in zip(("ry", "rx"), tilt, PAD_TILT_SIGNS):
271
+ value = min(max(sign * angle / PAD_TILT_FULL_RAD, -1.0), 1.0)
272
+ self.sticks[key] = 0.0 if abs(value) < JOYSTICK_DEADZONE else value
273
+
274
+ def _press(self, button: str, teleop: "Teleop", now: float) -> None:
275
+ names = [mood.name for mood in led.MOODS]
276
+ if button == PAD_CROSS:
277
+ teleop.request("rest" if teleop.awake else "wake")
278
+ elif button == PAD_SQUARE:
279
+ teleop.request("greet")
280
+ elif button == PAD_TRIANGLE:
281
+ teleop.request("kick")
282
+ elif button == PAD_CIRCLE:
283
+ teleop.request(f"mood:{names[self.mood]}")
284
+ elif button in (PAD_L2, PAD_R2):
285
+ self.mood = (self.mood + (1 if button == PAD_R2 else -1)) % len(names)
286
+ teleop.status = f"Mood: {names[self.mood]} (Circle plays it)"
287
+ self._flash = (led.PAD_MOOD_COLORS[names[self.mood]], now + PAD_FLASH_S)
288
+ elif button == PAD_L1:
289
+ teleop.ring.torch = not teleop.ring.torch
290
+ elif button == PAD_L3:
291
+ teleop.request("crawl" if teleop.gait == "trot" else "trot")
292
+ elif button == PAD_R3:
293
+ teleop.request("lean" if teleop.mode == "turn" else "turn")
294
+ elif button == PAD_SHARE:
295
+ teleop.request("show_battery")
296
+ percent = teleop.robot.battery.percent
297
+ if percent is not None:
298
+ self._flash = (led.battery_color(percent), now + PAD_FLASH_S)
299
+ elif button in ("dpad_left", "dpad_right"):
300
+ step = PAD_SPEED_STEP if button == "dpad_right" else -PAD_SPEED_STEP
301
+ teleop.speed_scale = min(max(teleop.speed_scale + step, MIN_SPEED_SCALE), teleop.max_speed_scale)
302
+
303
+ def _hold_to_shutdown(self, held: Set[str], teleop: "Teleop", now: float) -> None:
304
+ """START held :data:`PAD_SHUTDOWN_HOLD_S` powers off."""
305
+ if PAD_START not in held:
306
+ self._shutdown_since = None
307
+ return
308
+ if self._shutdown_since is None:
309
+ self._shutdown_since = now
310
+ left = PAD_SHUTDOWN_HOLD_S - (now - self._shutdown_since) # [s]; -inf once asked
311
+ if left <= 0.0 and self._shutdown_since != float("-inf"):
312
+ self._shutdown_since = float("-inf") # once per hold
313
+ teleop.request("shutdown")
314
+ elif left > 0.0:
315
+ teleop.status = f"Keep holding START to power off ({math.ceil(left):.0f} s)"
316
+
317
+ def _check_battery(self, teleop: "Teleop", now: float) -> None:
318
+ if now < self._battery_next:
319
+ return
320
+ self._battery_next = now + PAD_BATTERY_CHECK_S
321
+ self.battery = self._pad.battery()
322
+ if self.battery is None:
323
+ return
324
+ percent, charging = self.battery
325
+ if charging or percent > PAD_BATTERY_LOW_PERCENT:
326
+ self._battery_warned = False
327
+ elif not self._battery_warned:
328
+ self._battery_warned = True
329
+ self._pad.rumble(2)
330
+ teleop.status = f"Controller battery low: {percent} %"
331
+
332
+
333
+ class Teleop:
334
+ """What Chromapi is doing; every robot call happens in :meth:`tick`'s thread."""
335
+
336
+ def __init__(self, robot: Chromapi, web_input: WebInput, hardware: bool,
337
+ pad: Optional[GamepadControl] = None) -> None:
338
+ """Start lying down, trot, turn mode, full speed."""
339
+ self.robot = robot
340
+ self.web_input = web_input
341
+ self.pad = pad
342
+ self.hardware = hardware
343
+ self.ring = led.LedRing(robot)
344
+ self.awake = False
345
+ self.gait = "trot"
346
+ self.mode = "turn" # right stick turns; "lean": it tilts the chassis
347
+ self._lean_target: Optional[Tuple[float, ...]] = None # last (x, y, roll, pitch) sticks sent
348
+ self._leaning = False
349
+ self._lean_height0 = 0.0 # [m] height offset when Lean started
350
+ self.height = 0.0 # [m] chassis height offset, both modes
351
+ self.speed_scale = 1.0
352
+ self.status = "Ready: press Wake up"
353
+ self.shutting_down = False
354
+ self.on_shutdown: Callable[[str], None] = lambda power: None # "shutdown", "reboot" or "quit", to the pages
355
+ self._actions: "queue.Queue[str]" = queue.Queue()
356
+ self._emote: Optional[Union[RecordedLegMove, RecordedMove]] = None
357
+ self._next_greeting_leg = "tl"
358
+ self._next_kick_leg = "tr"
359
+ self._body = BalanceMove(dt=1.0 / robot.loop_hz) # Lean and the emotes' weight shift
360
+ self._moves = RecordedMoves() # mood gestures, greeting and kick: assets/moves
361
+ dataset = (getattr(robot, "config", None) or {}).get("moves", {}).get("dataset")
362
+ if dataset: # downloaded (or the cache) without holding the start-up
363
+ threading.Thread(target=self._load_dataset, args=(dataset,), daemon=True).start()
364
+ self._empty_since: Optional[float] = None # [s]
365
+ self._battery_rank = 0 # lowest level seen (_LEVEL_RANK)
366
+ self._battery_mood: Optional[str] = None # played once the emote ends
367
+ self._greeted = False
368
+ self.maintenance: Dict[str, Any] = {} # job, running, ok, cancelled, log
369
+ self._tool: Optional["subprocess.Popen[str]"] = None
370
+ self._talk_out: Any = None # PersistentAudioOutput
371
+ self._talk_last = 0.0 # [s]
372
+ self._talk_lock = threading.Lock()
373
+ self._mic: Any = None # MicStream
374
+ self._listen_next: Optional[Callable[[bytes], None]] = None # opens once the talk ends
375
+
376
+ def request(self, action: str) -> None:
377
+ """Queue an action (see :meth:`_do`); ``maintenance_cancel`` acts at once."""
378
+ if action == "maintenance_cancel":
379
+ self.cancel_maintenance()
380
+ else:
381
+ self._actions.put(action)
382
+
383
+ def talk(self, pcm: bytes) -> None:
384
+ """Play a chunk of the page's microphone (``TALK_RATE`` mono int16) on Chromapi's speaker."""
385
+ if not pcm or len(pcm) > TALK_MAX_CHUNK or len(pcm) % 2:
386
+ return
387
+ self.listen_stop() # one way at a time
388
+ samples = np.frombuffer(pcm, dtype="<i2").astype(np.float32) * (self.robot.sound_volume / 32768.0)
389
+ with self._talk_lock:
390
+ if self._talk_out is None:
391
+ self._talk_out = self._open_speaker()
392
+ if self._talk_out is None:
393
+ return
394
+ self._talk_out.write(samples, TALK_RATE)
395
+ self._talk_last = time.monotonic()
396
+
397
+ def _open_speaker(self) -> Any:
398
+ """A live output on Chromapi's speaker, at TALK_RATE if the device takes it."""
399
+ from chromapi.media.audio import PersistentAudioOutput, find_output_device
400
+
401
+ hint = self.robot._speaker_hint
402
+ device = find_output_device(hint) if hint else None
403
+ for rate in (TALK_RATE, None): # None: the device's rate
404
+ out = PersistentAudioOutput(samplerate=rate, device=device)
405
+ if out.start():
406
+ return out
407
+ self.status = "Talkie-walkie: no speaker"
408
+ return None
409
+
410
+ @property
411
+ def talking(self) -> bool:
412
+ """The page's voice is playing on the robot."""
413
+ return self._talk_out is not None
414
+
415
+ def listen_start(self, send: Callable[[bytes], None]) -> bool:
416
+ """Stream Chromapi's microphone (``TALK_RATE`` mono int16 chunks) to ``send``, after any talk."""
417
+ if self._mic is not None:
418
+ return False
419
+ with self._talk_lock:
420
+ if self.talking:
421
+ self._listen_next = send
422
+ return True
423
+ from chromapi.media.audio import MicStream
424
+
425
+ cfg = self.robot.config.get("audio", {}) if self.hardware else {}
426
+ mic = MicStream(send, samplerate=TALK_RATE, gain=float(cfg.get("mic_gain", 1.0)),
427
+ denoise=bool(cfg.get("mic_denoise", True)))
428
+ if not mic.start():
429
+ self.status = "Listening: no microphone"
430
+ return False
431
+ self._mic = mic
432
+ self.ring.listening = True
433
+ return True
434
+
435
+ def listen_stop(self) -> None:
436
+ """Close Chromapi's microphone."""
437
+ self._listen_next = None
438
+ mic, self._mic = self._mic, None
439
+ if mic is not None:
440
+ mic.stop()
441
+ self.ring.listening = False
442
+
443
+ def _close_idle_talk(self) -> None:
444
+ with self._talk_lock:
445
+ if self._talk_out is not None and time.monotonic() - self._talk_last > TALK_IDLE_S:
446
+ self._talk_out.stop()
447
+ self._talk_out = None
448
+ resume, self._listen_next = self._listen_next, None
449
+ if resume is not None:
450
+ self.listen_start(resume)
451
+
452
+ def cancel_maintenance(self) -> None:
453
+ """Ctrl-C the running maintenance tool (not a flash)."""
454
+ tool = self._tool
455
+ if self.maintenance.get("job") in UNCANCELLABLE or tool is None or tool.poll() is not None:
456
+ return
457
+ self.maintenance["cancelled"] = True
458
+ self.status = "Cancelling..."
459
+ tool.send_signal(signal.SIGINT)
460
+ threading.Timer(MAINTENANCE_CANCEL_S, tool.kill).start()
461
+
462
+ @property
463
+ def walking(self) -> bool:
464
+ """A walk is under way (not settled on the neutral stance)."""
465
+ return self.robot.is_walking
466
+
467
+ @property
468
+ def max_speed_scale(self) -> float:
469
+ """Speed slider limit, lower when the battery is low."""
470
+ return LOW_BATTERY_SPEED_SCALE if self.robot.battery.level in (LOW, CRITICAL, EMPTY) else MAX_SPEED_SCALE
471
+
472
+ def _cap_speed(self) -> None:
473
+ if self.speed_scale > self.max_speed_scale:
474
+ self.speed_scale = self.max_speed_scale
475
+ self.status = f"Battery low: speed capped at {self.max_speed_scale:.0%}"
476
+
477
+ @property
478
+ def emote_running(self) -> bool:
479
+ """An emote is playing."""
480
+ return self._emote is not None
481
+
482
+ def tick(self) -> None:
483
+ """One loop step: actions, emote, battery, sticks."""
484
+ self._close_idle_talk()
485
+ if self.maintenance.get("running"):
486
+ return
487
+ if self.pad is not None:
488
+ self.pad.poll(self, time.monotonic())
489
+ while not self._actions.empty():
490
+ self._do(self._actions.get())
491
+ if self._emote is not None and (self._emote.done or self.robot.active_move is not self._emote):
492
+ if self.robot.active_move is self._emote:
493
+ self.robot.stop_move()
494
+ self._emote = None
495
+ self._check_battery()
496
+ self._cap_speed()
497
+ if self.awake and self._emote is None:
498
+ self._drive()
499
+
500
+ def _do(self, action: str) -> None:
501
+ if action == "wake" and not self.awake:
502
+ self.status = "Waking up"
503
+ self.robot.wake_up(wait=True)
504
+ self.ring.set_persistent(led.render_idle)
505
+ self.awake = True
506
+ self._lean_target, self._leaning = None, False
507
+ self.status = "Standing"
508
+ elif action == "rest" and self.awake:
509
+ self._lie_down()
510
+ self.status = "Lying down"
511
+ elif action in ("trot", "crawl"):
512
+ if self.walking:
513
+ self.status = "Stop walking before changing the gait"
514
+ else:
515
+ self.gait = action
516
+ self.status = f"Gait: {action}"
517
+ elif action in ("turn", "lean"):
518
+ if self.walking or self._emote is not None:
519
+ self.status = "Stop moving before changing the mode"
520
+ else:
521
+ if action == "turn" and self._leaning:
522
+ self._body.set_body_pose() # back to the start pose; walking takes over from there
523
+ self.mode, self._lean_target, self._leaning = action, None, False
524
+ self.status = f"Mode: {action}"
525
+ elif action in ("greet", "kick", "kick_left", "kick_right"):
526
+ self._start_emote(action)
527
+ elif action == "identify":
528
+ self.ring.play_mood("scream")
529
+ elif action == "show_battery":
530
+ percent = self.robot.battery.percent
531
+ if percent is None:
532
+ self.status = "Battery not read yet"
533
+ else:
534
+ self.ring.flash(led.render_battery(percent), led.BATTERY_FLASH_S)
535
+ elif action.startswith("mood:") and (action[5:] in led.MOODS_BY_NAME or action[5:] in self.extra_moves()):
536
+ self._play_mood(action[5:])
537
+ elif action in MAINTENANCE:
538
+ self._start_maintenance(action)
539
+ elif action in POWER_COMMANDS:
540
+ self._shutdown(POWER_COMMANDS[action])
541
+
542
+ def resume_if_held(self) -> None:
543
+ """At start-up, take over a robot the firmware still holds standing."""
544
+ state = self.robot.get_state()
545
+ load = max((abs(v) for v in state.joint_loads.values()), default=0.0) if state else 0.0
546
+ logger.info("Start-up servo load: %.0f (held above %.0f)", load, HELD_LOAD)
547
+ if self.hardware and load > HELD_LOAD:
548
+ self._do("wake")
549
+ self.status = "Still standing: resumed"
550
+
551
+ def _lie_down(self) -> None:
552
+ self.robot.stop_walk(wait=True)
553
+ self.ring.set_persistent(led.render_off)
554
+ self.robot.rest()
555
+ self.awake = False
556
+ self._emote, self._leaning = None, False
557
+
558
+ def _start_maintenance(self, job: str) -> None:
559
+ if not isinstance(self.robot.backend, HardwareBackend):
560
+ self.status = "Maintenance works on the real robot only"
561
+ elif self.awake:
562
+ self.status = "Maintenance: lay Chromapi down first"
563
+ else:
564
+ self.maintenance = {"job": job, "running": True, "ok": None, "cancelled": False, "log": ""}
565
+ self.status = MAINTENANCE[job][1]
566
+ threading.Thread(target=self._maintain, args=(job,), name="chromapi-maintenance", daemon=True).start()
567
+
568
+ def _maintain(self, job: str) -> None:
569
+ """Hand the serial port to the ``chromapi`` tool, then take it back with the new calibration."""
570
+ self.ring.stop()
571
+ self.robot.disconnect()
572
+ try:
573
+ with subprocess.Popen([sys.executable, "-m", "chromapi", *MAINTENANCE[job][0]], stdout=subprocess.PIPE,
574
+ stderr=subprocess.STDOUT, text=True) as tool:
575
+ self._tool = tool
576
+ try:
577
+ log = tool.communicate(timeout=MAINTENANCE_TIMEOUT_S)[0]
578
+ except subprocess.TimeoutExpired:
579
+ tool.kill()
580
+ log = tool.communicate()[0] + f"\ntimed out after {MAINTENANCE_TIMEOUT_S:.0f} s"
581
+ ok, log = tool.returncode == 0, log.strip()
582
+ except OSError as exc:
583
+ ok, log = False, str(exc)
584
+ self._tool = None
585
+ cancelled = bool(self.maintenance.get("cancelled"))
586
+ logger.info("Maintenance %s %s:\n%s", job, "cancelled" if cancelled else "done" if ok else "failed", log)
587
+ if ok and isinstance(self.robot.backend, HardwareBackend):
588
+ self.robot.config = load_config()
589
+ self.robot.backend.apply_calibration(self.robot.config)
590
+ if self.robot.connect():
591
+ self.robot.disable_motors() # the servo sweep leaves torque on
592
+ self.ring.start()
593
+ last = log.splitlines()[-1] if log else ""
594
+ outcome = "Cancelled" if cancelled else "Done" if ok else "Failed"
595
+ self.status = f"{outcome}: {last}" if last else outcome
596
+ self.maintenance = {"job": job, "running": False, "ok": ok, "cancelled": cancelled,
597
+ "log": "\n".join(log.splitlines()[-40:])}
598
+
599
+ def _load_dataset(self, dataset: str) -> None:
600
+ """Add the moves of the Hugging Face dataset ``config["moves"]["dataset"]`` to the bundled ones."""
601
+ try:
602
+ self._moves.update(RecordedMoves(dataset))
603
+ except Exception as exc: # no huggingface_hub, never downloaded and offline, unknown dataset
604
+ logger.warning("Moves of %s not available: %s", dataset, exc)
605
+
606
+ def extra_moves(self) -> List[str]:
607
+ """Body moves without a mood of their own (from a dataset): listed after the moods."""
608
+ return [n for n in self._moves.list_moves() if n not in led.MOODS_BY_NAME and not self._moves.is_leg_move(n)]
609
+
610
+ def _play_mood(self, name: str) -> None:
611
+ """Sound and ring, plus the recorded move of the same name when Chromapi can move."""
612
+ duration_s = 0.0 # [s]
613
+ if name in self._moves.list_moves() and self._emote_refusal() is None:
614
+ gesture = self._moves.get(name, self._body)
615
+ self._emote, self._leaning = gesture, False
616
+ self.robot.play_move(gesture)
617
+ duration_s = gesture.duration
618
+ mood = name if name in led.MOODS_BY_NAME else self._moves.mood(name)
619
+ self.ring.play_mood(mood if mood in led.MOODS_BY_NAME else DATASET_MOOD, duration_s)
620
+
621
+ def _emote_refusal(self) -> Optional[str]:
622
+ """Why Chromapi cannot play an emote now; None if it can."""
623
+ refusal = None
624
+ if not self.awake:
625
+ refusal = "wake Chromapi up first"
626
+ elif self.mode != "turn":
627
+ refusal = "switch back to Turn mode"
628
+ elif self._emote is not None:
629
+ refusal = "an emote is already playing"
630
+ elif self.robot.is_walking:
631
+ refusal = "wait for Chromapi to stand still"
632
+ else:
633
+ tilt_deg = math.degrees(tilt(self.robot.get_imu_orientation()))
634
+ if tilt_deg > EMOTE_MAX_TILT_DEG:
635
+ refusal = f"Chromapi is not level ({tilt_deg:.0f}°)"
636
+ return refusal
637
+
638
+ def _start_emote(self, name: str) -> None:
639
+ refusal = self._emote_refusal()
640
+ if refusal:
641
+ self.status = f"{name.capitalize()}: {refusal}"
642
+ return
643
+ if name == "greet":
644
+ leg, self._next_greeting_leg = self._next_greeting_leg, "tr" if self._next_greeting_leg == "tl" else "tl"
645
+ self._emote = self._moves.get("greeting", self._body, leg)
646
+ self.robot.play_sound(GREETING_SOUND)
647
+ else:
648
+ leg = {"kick_left": "tl", "kick_right": "tr"}.get(name, self._next_kick_leg)
649
+ self._next_kick_leg = "tl" if leg == "tr" else "tr"
650
+ self._emote = self._moves.get("kick", self._body, leg)
651
+ self._leaning = False
652
+ self.robot.play_move(self._emote)
653
+ self.status = name.replace("_", " ").capitalize()
654
+
655
+ def _lean(self, x_in: float, y_in: float, roll_in: float, pitch_in: float, height: float) -> None:
656
+ """Pose the chassis, feet planted, from sticks in [-1, 1]."""
657
+ self._lean_target = (x_in, y_in, roll_in, pitch_in, height)
658
+ if not self._leaning or self.robot.active_move is not self._body:
659
+ self.robot.play_move(self._body)
660
+ self._leaning, self._lean_height0 = True, height
661
+ k = min(self.speed_scale, 1.0)
662
+ self._body.set_body_pose(
663
+ (x_in * MAX_LEAN_SHIFT_M * k, y_in * MAX_LEAN_SHIFT_M * k, height - self._lean_height0),
664
+ (roll_in * MAX_LEAN_RAD * k, pitch_in * MAX_LEAN_RAD * k),
665
+ )
666
+
667
+ def _drive(self) -> None:
668
+ pad = self.pad
669
+ sticks = pad.sticks if pad is not None and pad.active(time.monotonic()) else self.web_input.read()
670
+ if self.mode == "lean":
671
+ # Chassis frame: +X forward, +Y left; roll > 0 right, pitch > 0 nose down
672
+ shift, tilt = _in_circle(sticks["ly"], -sticks["lx"]), _in_circle(sticks["rx"], sticks["ry"])
673
+ target = (*shift, *tilt, self.height)
674
+ # No ramp: the stick goes straight through, BalanceMove's joint speed limit smooths it (stick circles,
675
+ # MuJoCo: feet slide ~1 mm; 12 mm with shift and tilt circling together at 2 s a turn).
676
+ if target != self._lean_target and (self._lean_target is not None or any(target)):
677
+ self._lean(*target)
678
+ return
679
+ vx = sticks["ly"] * NOMINAL_LINEAR_MPS * self.speed_scale
680
+ vy = -sticks["lx"] * NOMINAL_LINEAR_MPS * self.speed_scale # stick right, walk() positive left
681
+ wz = -sticks["rx"] * MAX_ANGULAR_RAD_S * self.speed_scale
682
+ height = WALK_POSTURE[2] + self.height # [m]
683
+ move = self.robot.walk_move
684
+ if vx == vy == wz == 0.0 and self.robot.active_move is not move:
685
+ if (move.height_target if move is not None else WALK_POSTURE[2]) == height:
686
+ return
687
+ try:
688
+ self.robot.walk(vx=vx, vy=vy, wz=wz, pattern=self.gait).set_body_height(height)
689
+ except RuntimeError as exc: # battery too low
690
+ self.status = str(exc)
691
+
692
+ def startup_mood(self) -> str:
693
+ """The startup mood: scream, or the battery's mood if already low."""
694
+ level = self.robot.battery.level
695
+ self._battery_rank = _LEVEL_RANK[level]
696
+ self._greeted = True
697
+ return BATTERY_MOODS.get(level, "alert" if level == EMPTY else "scream")
698
+
699
+ def _check_battery(self) -> None:
700
+ level = self.robot.battery.level
701
+ if self._greeted and _LEVEL_RANK[level] > self._battery_rank:
702
+ self._battery_rank = _LEVEL_RANK[level]
703
+ self._battery_mood = BATTERY_MOODS.get(level, self._battery_mood)
704
+ if self.pad is not None and level in (LOW, CRITICAL):
705
+ self.pad.rumble(2 if level == LOW else 3)
706
+ if self._battery_mood is not None and self._emote is None:
707
+ self.ring.play_mood(self._battery_mood)
708
+ self._battery_mood = None
709
+ if level != EMPTY:
710
+ self._empty_since = None
711
+ return
712
+ self.awake = False # the SDK lies Chromapi down
713
+ self.status = "Battery empty: lying down" + (", then powering off" if self.hardware else "")
714
+ if self._empty_since is None:
715
+ self._empty_since = time.monotonic()
716
+ elif self.hardware and time.monotonic() - self._empty_since > EMPTY_SHUTDOWN_S:
717
+ self._shutdown()
718
+
719
+ def _shutdown(self, command: Optional[str] = "poweroff") -> None:
720
+ """Lie down, release the servos, stop the app, then ``systemctl <command>`` (None: stop only)."""
721
+ self.shutting_down = True
722
+ self.on_shutdown({v: k for k, v in POWER_COMMANDS.items()}[command])
723
+ self.status = {"reboot": "Restarting", "poweroff": "Powering off"}.get(command or "", "Developer mode: app stopped")
724
+ if self.awake:
725
+ self._lie_down()
726
+ self.ring.stop()
727
+ self.robot.disconnect(disable_torque=True)
728
+ if command is None:
729
+ logger.info("Developer mode: app stopped, serial port free. Back with 'sudo systemctl start chromapi@%s' "
730
+ "or by switching Chromapi off and on.", getpass.getuser())
731
+ return
732
+ if self.hardware and subprocess.run(["systemctl", "--no-ask-password", command], check=False).returncode:
733
+ logger.error("Not allowed to %s the Pi: the robot is lying down and limp, use its switch. "
734
+ "'chromapi run' started as the system service can do it.", command)
735
+
736
+
737
+ def telemetry(robot: Chromapi, teleop: Teleop, camera: Any, connected: bool) -> Dict[str, Any]:
738
+ """State sent to the page."""
739
+ state = robot.get_state()
740
+ stale = state is None or time.monotonic() - state.timestamp > STATE_STALE_S
741
+ fan = fan_service.status() if teleop.hardware else None
742
+ firmware, shipped = getattr(robot.backend, "firmware_version", None), shipped_version()
743
+ data: Dict[str, Any] = {
744
+ "link": "no serial port" if not connected else "STM32 not answering" if stale else "ok",
745
+ "simulation": not teleop.hardware,
746
+ "awake": teleop.awake,
747
+ "gait": teleop.gait,
748
+ "mode": teleop.mode,
749
+ "torch": teleop.ring.torch,
750
+ "ring": "rainbow" if led.idle_rainbow() else "#%02x%02x%02x" % led.idle_color(),
751
+ "fan": fan[0] if fan is not None else None,
752
+ "fan_auto": fan is not None and fan[1],
753
+ "speed_scale": teleop.speed_scale,
754
+ "speed_max": teleop.max_speed_scale,
755
+ "height_mm": round(teleop.height * 1000),
756
+ "walking": teleop.walking,
757
+ "emote": teleop.emote_running,
758
+ "maintenance": teleop.maintenance,
759
+ "status": teleop.status,
760
+ "cpu_temp": fan_service.cpu_temp_c(),
761
+ "host": socket.gethostname(),
762
+ "versions": {"sdk": sdk_version(), "firmware": firmware, "firmware_shipped": shipped,
763
+ "firmware_update": teleop.hardware and connected and not stale and update_available(firmware, shipped)},
764
+ "battery": {"percent": robot.battery.percent, "level": robot.battery.level},
765
+ "cam_rec": camera.recording_status() if camera is not None else None,
766
+ "viewers": camera.viewers if camera is not None else 0,
767
+ "gamepad": {"battery": teleop.pad.battery and teleop.pad.battery[0], "tilt_lean": teleop.pad.tilt_lean}
768
+ if teleop.pad is not None and teleop.pad.connected else None,
769
+ }
770
+ if state is not None and not stale:
771
+ data.update(
772
+ voltage=state.voltage_v or None,
773
+ current=state.current_a,
774
+ power=state.power_w,
775
+ tilt_deg=math.degrees(tilt(state.imu_quat_wxyz)),
776
+ contacts={leg: bool(on) for leg, on in state.foot_contacts.items()},
777
+ servos={
778
+ "missing": state.missing_servos,
779
+ "max_temp": max(state.joint_temperatures.values(), default=None),
780
+ },
781
+ )
782
+ return data
783
+
784
+
785
+ def build_server(teleop: Teleop, web_input: WebInput, camera: Any, record_dir: Path,
786
+ snapshot: Any, access: Access, https: bool = False) -> "tuple[Flask, SocketIO]":
787
+ """Flask app (page, camera, recordings, report) and its Socket.IO events, behind the access code."""
788
+ app = Flask(__name__, static_folder=str(STATIC_DIR))
789
+ app.secret_key = access.secret_key
790
+ app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Strict", SESSION_COOKIE_SECURE=https,
791
+ PERMANENT_SESSION_LIFETIME=SESSION_LIFETIME_S)
792
+ socketio = SocketIO(app, async_mode="threading")
793
+ # sid -> access generation, in arrival order: the first page drives, the others watch
794
+ clients: Dict[str, str] = {}
795
+ clients_lock = threading.Lock()
796
+
797
+ def pilot_only(handler: Callable[[Any], None]) -> Callable[[Any], None]:
798
+ """Drop the commands of watching pages."""
799
+ @functools.wraps(handler)
800
+ def checked(data: Any = None) -> None:
801
+ with clients_lock:
802
+ pilot = next(iter(clients), None)
803
+ if request.sid == pilot: # type: ignore[attr-defined]
804
+ handler(data)
805
+ return checked
806
+
807
+ def announce_roles() -> None:
808
+ with clients_lock:
809
+ sids = list(clients)
810
+ for i, sid in enumerate(sids):
811
+ socketio.emit("role", {"pilot": i == 0, "watchers": len(sids) - 1}, to=sid)
812
+
813
+ def signed_in() -> bool:
814
+ return access.configured and session.get("access") == access.generation
815
+
816
+ def sign_in() -> None:
817
+ session.permanent = True
818
+ session["access"] = access.generation
819
+
820
+ def posted(key: str = "code") -> str:
821
+ return str((request.get_json(silent=True) or {}).get(key, ""))
822
+
823
+ def refused(error: str, wait_s: float) -> Any:
824
+ return {"error": error + (f": wait {wait_s:.0f} s" if wait_s else ""), "wait_s": wait_s}, 403
825
+
826
+ def sign_out_on_new_code() -> None:
827
+ """Close the connections opened with an older access code."""
828
+ while True:
829
+ socketio.sleep(CODE_CHECK_S)
830
+ current = access.generation
831
+ with clients_lock:
832
+ stale = [sid for sid, generation in clients.items() if generation != current]
833
+ for sid in stale:
834
+ socketio.server.disconnect(sid, namespace="/")
835
+
836
+ socketio.start_background_task(sign_out_on_new_code)
837
+
838
+ @app.before_request
839
+ def require_access() -> Any:
840
+ """Everything but the page and its sign-in screen needs a session."""
841
+ if request.endpoint not in OPEN_ENDPOINTS and not signed_in():
842
+ return Response("sign in first", status=401)
843
+ return None
844
+
845
+ @app.route("/auth/state")
846
+ def auth_state() -> Any:
847
+ return {"configured": access.configured, "signed_in": signed_in(), "min_length": MIN_CODE_LENGTH}
848
+
849
+ @app.route("/auth/setup", methods=["POST"])
850
+ def auth_setup() -> Any:
851
+ """The first visitor chooses the access code."""
852
+ try:
853
+ if not access.choose(posted()):
854
+ return {"error": "an access code is already set: enter it"}, 409
855
+ except ValueError as exc:
856
+ return {"error": str(exc)}, 400
857
+ sign_in()
858
+ return {"ok": True}
859
+
860
+ @app.route("/auth/login", methods=["POST"])
861
+ def auth_login() -> Any:
862
+ ok, wait_s = access.check(posted())
863
+ if not ok:
864
+ return refused("wrong code", wait_s)
865
+ sign_in()
866
+ return {"ok": True}
867
+
868
+ @app.route("/auth/change", methods=["POST"])
869
+ def auth_change() -> Any:
870
+ """A new code, given the current one: every other browser must enter it."""
871
+ ok, wait_s = access.check(posted("current"))
872
+ if not ok:
873
+ return refused("wrong current code", wait_s)
874
+ try:
875
+ access.set_code(posted())
876
+ except ValueError as exc:
877
+ return {"error": str(exc)}, 400
878
+ sign_in()
879
+ return {"ok": True}
880
+
881
+ @app.route("/")
882
+ def index() -> Any:
883
+ return send_from_directory(STATIC_DIR, "index.html")
884
+
885
+ @app.route("/favicon.ico")
886
+ def favicon() -> Any:
887
+ return send_file(FAVICON)
888
+
889
+ @app.route("/photo")
890
+ def photo() -> Any:
891
+ path = None if camera is None else camera.photo(record_dir / f"{time.strftime('%Y%m%d-%H%M%S')}_photo.jpg")
892
+ if path is None:
893
+ return Response("no camera image", status=404)
894
+ return send_file(path, as_attachment=True)
895
+
896
+ @app.route("/video_feed")
897
+ def video_feed() -> Any:
898
+ if camera is None:
899
+ return Response("camera disabled", status=404)
900
+ return Response(camera.mjpeg(), mimetype="multipart/x-mixed-replace; boundary=frame")
901
+
902
+ @app.route("/recordings/<path:name>")
903
+ def recording(name: str) -> Any:
904
+ return send_from_directory(record_dir.resolve(), name)
905
+
906
+ @app.route("/recordings/<name>", methods=["DELETE"])
907
+ def delete_recording(name: str) -> Any:
908
+ """A photo or video of the gallery, nothing else."""
909
+ path = record_dir / name
910
+ if path.parent != record_dir or not name.endswith(RECORDING_SUFFIXES) or not path.is_file():
911
+ return Response("no such recording", status=404)
912
+ path.unlink()
913
+ return {"ok": True}
914
+
915
+ @app.route("/gallery")
916
+ def gallery() -> Any:
917
+ """Photos and videos taken from the page, newest first."""
918
+ files = [f for suffix in RECORDING_SUFFIXES
919
+ for f in sorted(record_dir.glob("*" + suffix), key=lambda f: f.name, reverse=True)]
920
+ return {"files": [{"name": f.name, "kind": "photo" if f.suffix == ".jpg" else "video",
921
+ "size_mb": round(f.stat().st_size / 1e6, 1)} for f in files]}
922
+
923
+ @app.route("/moods")
924
+ def moods() -> Any:
925
+ return {"moods": [{"name": m.name, "emoji": m.emoji} for m in led.MOODS]
926
+ + [{"name": name, "emoji": "✨"} for name in teleop.extra_moves()]}
927
+
928
+ @app.route("/servos")
929
+ def servos() -> Any:
930
+ return {"servos": [{"id": i, "joint": joint} for joint, i in SERVO_SETUP]}
931
+
932
+ @app.route("/report")
933
+ def report() -> Any:
934
+ """No copy is kept on the robot."""
935
+ name = f"chromapi_report_{time.strftime('%Y%m%d-%H%M%S')}.txt"
936
+ live = "$ live state (web app)\n" + json.dumps(snapshot(), indent=2, default=str) + "\n"
937
+ with tempfile.TemporaryDirectory() as directory:
938
+ data = write_report(Path(directory) / name, use_bridge=False, extra=live).read_bytes()
939
+ return send_file(io.BytesIO(data), mimetype="text/plain", as_attachment=True, download_name=name)
940
+
941
+ @socketio.on("connect")
942
+ def on_connect(auth: Any = None) -> Any:
943
+ if not signed_in():
944
+ return False
945
+ with clients_lock:
946
+ clients[request.sid] = session["access"] # type: ignore[attr-defined]
947
+ announce_roles()
948
+ return None
949
+
950
+ @socketio.on("disconnect")
951
+ def on_disconnect(*_args: Any) -> None:
952
+ with clients_lock:
953
+ was_pilot = next(iter(clients), None) == request.sid # type: ignore[attr-defined]
954
+ clients.pop(request.sid, None) # type: ignore[attr-defined]
955
+ if was_pilot:
956
+ web_input.release()
957
+ teleop.listen_stop()
958
+ announce_roles()
959
+ elif clients:
960
+ announce_roles()
961
+
962
+ @socketio.on("axes")
963
+ @pilot_only
964
+ def on_axes(data: Any) -> None:
965
+ web_input.set_axes(data or {})
966
+
967
+ @socketio.on("action")
968
+ @pilot_only
969
+ def on_action(data: Any) -> None:
970
+ teleop.request(str((data or {}).get("name", "")))
971
+
972
+ @socketio.on("set_speed")
973
+ @pilot_only
974
+ def on_speed(data: Any) -> None:
975
+ teleop.speed_scale = min(max(float((data or {}).get("value", 1.0)), MIN_SPEED_SCALE), teleop.max_speed_scale)
976
+
977
+ @socketio.on("set_height")
978
+ @pilot_only
979
+ def on_height(data: Any) -> None:
980
+ teleop.height = min(max(float((data or {}).get("mm", 0.0)) / 1000.0, HEIGHT_RANGE_M[0]), HEIGHT_RANGE_M[1])
981
+
982
+ @socketio.on("talk")
983
+ @pilot_only
984
+ def on_talk(data: Any) -> None:
985
+ if isinstance(data, (bytes, bytearray)):
986
+ teleop.talk(bytes(data))
987
+
988
+ @socketio.on("listen_start")
989
+ @pilot_only
990
+ def on_listen_start(data: Any = None) -> None:
991
+ sid = request.sid # type: ignore[attr-defined]
992
+ teleop.listen_start(lambda pcm: socketio.emit("listen", pcm, to=sid))
993
+
994
+ @socketio.on("listen_stop")
995
+ @pilot_only
996
+ def on_listen_stop(data: Any = None) -> None:
997
+ teleop.listen_stop()
998
+
999
+ @socketio.on("set_pad_tilt")
1000
+ @pilot_only
1001
+ def on_pad_tilt(data: Any) -> None:
1002
+ if teleop.pad is not None:
1003
+ teleop.pad.tilt_lean = bool((data or {}).get("on"))
1004
+
1005
+ @socketio.on("set_torch")
1006
+ @pilot_only
1007
+ def on_torch(data: Any) -> None:
1008
+ teleop.ring.torch = bool((data or {}).get("on"))
1009
+
1010
+ @socketio.on("set_ring_color")
1011
+ @pilot_only
1012
+ def on_ring_color(data: Any) -> None:
1013
+ """``{"rgb": [r, g, b]}`` (0-255), ``{"rainbow": true}``, or ``{}`` for the default."""
1014
+ data = data or {}
1015
+ rgb = data.get("rgb")
1016
+ if data.get("rainbow"):
1017
+ led.set_idle_rainbow()
1018
+ else:
1019
+ led.set_idle_color((int(rgb[0]), int(rgb[1]), int(rgb[2])) if isinstance(rgb, list) and len(rgb) == 3 else None)
1020
+
1021
+ @socketio.on("set_fan")
1022
+ @pilot_only
1023
+ def on_fan(data: Any) -> None:
1024
+ if teleop.hardware:
1025
+ data = data or {}
1026
+ fan_service.request(None if data.get("auto") else float(data.get("percent", 100.0)))
1027
+
1028
+ @socketio.on("camera_record")
1029
+ @pilot_only
1030
+ def on_camera_record(data: Any) -> None:
1031
+ if camera is None:
1032
+ return
1033
+ if (data or {}).get("on"):
1034
+ camera.start_recording(record_dir / f"{time.strftime('%Y%m%d-%H%M%S')}_camera.avi")
1035
+ else:
1036
+ camera.stop_recording()
1037
+
1038
+ return app, socketio
1039
+
1040
+
1041
+ def _lan_ip() -> str:
1042
+ """This machine's LAN address (no packet is sent)."""
1043
+ try:
1044
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
1045
+ s.connect(("10.255.255.255", 1))
1046
+ return str(s.getsockname()[0])
1047
+ except OSError:
1048
+ return "127.0.0.1"
1049
+
1050
+
1051
+ def main() -> int:
1052
+ """Serve the web app until Ctrl-C (or the page's power-off button)."""
1053
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
1054
+ parser.add_argument("--sim", action="store_true", help="run in MuJoCo instead of on the robot")
1055
+ parser.add_argument("--host", default="0.0.0.0")
1056
+ parser.add_argument("--port", type=int, default=5000)
1057
+ parser.add_argument("--no-camera", action="store_true")
1058
+ parser.add_argument("--camera-index", type=int, default=0)
1059
+ parser.add_argument("--record-dir", type=Path, default=Path.home() / "chromapi_recordings",
1060
+ help="where the camera Record button saves its videos")
1061
+ parser.add_argument("--http", action="store_true",
1062
+ help="plain HTTP instead of HTTPS (no phone microphone, traffic readable on the network)")
1063
+ args = parser.parse_args()
1064
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
1065
+ logging.getLogger("werkzeug").setLevel(logging.WARNING)
1066
+ hardware = not args.sim
1067
+
1068
+ # Heavy setup before connect(): it would starve the control loop
1069
+ robot = Chromapi(backend="hardware" if hardware else "mujoco", launch_viewer=not hardware)
1070
+ web_input = WebInput()
1071
+ teleop = Teleop(robot, web_input, hardware, GamepadControl())
1072
+ teleop.on_shutdown = lambda power: socketio.emit("goodbye", power)
1073
+ camera = None
1074
+ if hardware and not args.no_camera:
1075
+ from chromapi.web.camera import CameraStreamer
1076
+
1077
+ camera = CameraStreamer(load_config().get("camera", {}), device=args.camera_index)
1078
+ camera.start()
1079
+
1080
+ connected = robot.connect()
1081
+ if not connected:
1082
+ logger.error("Cannot open the serial port: retrying every %.0f s", RECONNECT_S)
1083
+ teleop.ring.start()
1084
+ certificate = None if args.http else tls_certificate()
1085
+ app, socketio = build_server(teleop, web_input, camera, args.record_dir,
1086
+ lambda: telemetry(robot, teleop, camera, connected), Access(),
1087
+ https=certificate is not None)
1088
+ threading.Thread(
1089
+ target=lambda: socketio.run(app, host=args.host, port=args.port, use_reloader=False,
1090
+ allow_unsafe_werkzeug=True, log_output=False, ssl_context=certificate),
1091
+ name="chromapi-web", daemon=True,
1092
+ ).start()
1093
+ scheme = "https" if certificate else "http"
1094
+ if args.host == "0.0.0.0":
1095
+ logger.info("Web app on %s://%s.local:%d (or %s://%s:%d)", scheme, socket.gethostname(), args.port,
1096
+ scheme, _lan_ip(), args.port)
1097
+ else:
1098
+ logger.info("Web app on %s://%s:%d", scheme, args.host, args.port)
1099
+
1100
+ next_telemetry = next_connect = time.monotonic()
1101
+ greeted = False
1102
+ try:
1103
+ while not teleop.shutting_down and robot.backend.is_alive():
1104
+ now = time.monotonic()
1105
+ if not connected and now >= next_connect:
1106
+ connected, next_connect = robot.connect(), now + RECONNECT_S
1107
+ if connected:
1108
+ if not greeted and robot.get_state() is not None:
1109
+ teleop.resume_if_held()
1110
+ # Threaded: the first sound loads PortAudio
1111
+ threading.Thread(target=teleop.ring.play_mood, args=(teleop.startup_mood(),), name="chromapi-greeting",
1112
+ daemon=True).start()
1113
+ greeted = True
1114
+ teleop.tick()
1115
+ if now >= next_telemetry:
1116
+ socketio.emit("telemetry", telemetry(robot, teleop, camera, connected))
1117
+ next_telemetry = now + TELEMETRY_PERIOD_S
1118
+ time.sleep(TICK_S)
1119
+ except KeyboardInterrupt:
1120
+ pass
1121
+ finally:
1122
+ if teleop.pad is not None:
1123
+ teleop.pad.close()
1124
+ if camera is not None:
1125
+ camera.stop()
1126
+ teleop.cancel_maintenance()
1127
+ if not teleop.shutting_down and robot.is_connected: # during maintenance, the port is the tool's
1128
+ if teleop.awake:
1129
+ teleop._lie_down()
1130
+ teleop.ring.stop()
1131
+ robot.disconnect(disable_torque=True)
1132
+ return 0
1133
+
1134
+
1135
+ if __name__ == "__main__":
1136
+ raise SystemExit(main())