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.
- chromapi/__init__.py +2 -0
- chromapi/__main__.py +6 -0
- chromapi/assets/audio/alert.wav +0 -0
- chromapi/assets/audio/chromapi_scream.wav +0 -0
- chromapi/assets/audio/confused.wav +0 -0
- chromapi/assets/audio/dizzy.wav +0 -0
- chromapi/assets/audio/excited.wav +0 -0
- chromapi/assets/audio/greeting.wav +0 -0
- chromapi/assets/audio/happy.wav +0 -0
- chromapi/assets/audio/no.wav +0 -0
- chromapi/assets/audio/purring.wav +0 -0
- chromapi/assets/audio/sad.wav +0 -0
- chromapi/assets/audio/scared.wav +0 -0
- chromapi/assets/audio/sleepy.wav +0 -0
- chromapi/assets/audio/squeak.wav +0 -0
- chromapi/assets/audio/surprised.wav +0 -0
- chromapi/assets/audio/thinking.wav +0 -0
- chromapi/assets/audio/upset.wav +0 -0
- chromapi/assets/audio/yes.wav +0 -0
- chromapi/assets/favicon.ico +0 -0
- chromapi/assets/firmware/chromapi_stm32_core_v2.0.0.hex +2222 -0
- chromapi/assets/firmware/flash.sh +88 -0
- chromapi/assets/moves/README.md +48 -0
- chromapi/assets/moves/angry.json +1 -0
- chromapi/assets/moves/confused.json +1 -0
- chromapi/assets/moves/dizzy.json +1 -0
- chromapi/assets/moves/excited.json +1 -0
- chromapi/assets/moves/greeting.json +1 -0
- chromapi/assets/moves/happy.json +1 -0
- chromapi/assets/moves/joy.json +1 -0
- chromapi/assets/moves/kick.json +1 -0
- chromapi/assets/moves/metadata.jsonl +15 -0
- chromapi/assets/moves/no.json +1 -0
- chromapi/assets/moves/purring.json +1 -0
- chromapi/assets/moves/sad.json +1 -0
- chromapi/assets/moves/scared.json +1 -0
- chromapi/assets/moves/surprised.json +1 -0
- chromapi/assets/moves/tired.json +1 -0
- chromapi/assets/moves/yes.json +1 -0
- chromapi/chromapi.py +1460 -0
- chromapi/cli.py +106 -0
- chromapi/config/config.yaml +118 -0
- chromapi/estimation/__init__.py +6 -0
- chromapi/estimation/attitude.py +107 -0
- chromapi/hardware/__init__.py +2 -0
- chromapi/hardware/battery.py +54 -0
- chromapi/hardware/fan.py +165 -0
- chromapi/hardware/motherboard_bridge.py +345 -0
- chromapi/input/__init__.py +2 -0
- chromapi/input/gamepad.py +379 -0
- chromapi/input/pairing.py +98 -0
- chromapi/kinematics/__init__.py +10 -0
- chromapi/kinematics/kromatics.py +324 -0
- chromapi/kinematics/poses.py +29 -0
- chromapi/kinematics/topology.py +26 -0
- chromapi/kinematics/types.py +21 -0
- chromapi/locomotion/__init__.py +7 -0
- chromapi/locomotion/balance.py +284 -0
- chromapi/locomotion/gait.py +595 -0
- chromapi/locomotion/recorded_move.py +290 -0
- chromapi/media/__init__.py +2 -0
- chromapi/media/audio.py +424 -0
- chromapi/media/led.py +461 -0
- chromapi/model/LICENSE +438 -0
- chromapi/model/mjcf/additional.xml +21 -0
- chromapi/model/mjcf/assets/18650_li_ion_battery.msh +0 -0
- chromapi/model/mjcf/assets/18650_li_ion_battery.part +13 -0
- chromapi/model/mjcf/assets/battery_holder.msh +0 -0
- chromapi/model/mjcf/assets/battery_holder.part +13 -0
- chromapi/model/mjcf/assets/camera_imx219_d160.msh +0 -0
- chromapi/model/mjcf/assets/camera_imx219_d160.part +13 -0
- chromapi/model/mjcf/assets/chromapi_logo.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_logo.part +13 -0
- chromapi/model/mjcf/assets/chromapi_logo_circle.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_logo_inner.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_logo_outer.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_motherboard.msh +0 -0
- chromapi/model/mjcf/assets/chromapi_motherboard.part +13 -0
- chromapi/model/mjcf/assets/composant2_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/composant2_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/composant3_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/composant3_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/composant4_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/composant4_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/connector_f_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/connector_f_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/connector_f_1__corps1_1.msh +0 -0
- chromapi/model/mjcf/assets/connector_f_1__corps1_1.part +13 -0
- chromapi/model/mjcf/assets/corps14.msh +0 -0
- chromapi/model/mjcf/assets/corps14.part +13 -0
- chromapi/model/mjcf/assets/fan_nf_a4x10.msh +0 -0
- chromapi/model/mjcf/assets/fan_nf_a4x10.part +13 -0
- chromapi/model/mjcf/assets/foot.msh +0 -0
- chromapi/model/mjcf/assets/foot.part +13 -0
- chromapi/model/mjcf/assets/left_coxa.msh +0 -0
- chromapi/model/mjcf/assets/left_coxa.part +13 -0
- chromapi/model/mjcf/assets/left_femur.msh +0 -0
- chromapi/model/mjcf/assets/left_femur.part +13 -0
- chromapi/model/mjcf/assets/left_tibia.msh +0 -0
- chromapi/model/mjcf/assets/left_tibia.part +13 -0
- chromapi/model/mjcf/assets/microswitch.msh +0 -0
- chromapi/model/mjcf/assets/microswitch.part +13 -0
- chromapi/model/mjcf/assets/power_switch.msh +0 -0
- chromapi/model/mjcf/assets/power_switch.part +13 -0
- chromapi/model/mjcf/assets/raspberry_pi_4_model_b.msh +0 -0
- chromapi/model/mjcf/assets/raspberry_pi_4_model_b.part +13 -0
- chromapi/model/mjcf/assets/right_coxa.msh +0 -0
- chromapi/model/mjcf/assets/right_coxa.part +13 -0
- chromapi/model/mjcf/assets/right_femur.msh +0 -0
- chromapi/model/mjcf/assets/right_femur.part +13 -0
- chromapi/model/mjcf/assets/right_tibia.msh +0 -0
- chromapi/model/mjcf/assets/right_tibia.part +13 -0
- chromapi/model/mjcf/assets/robot_case_bottom.msh +0 -0
- chromapi/model/mjcf/assets/robot_case_bottom.part +13 -0
- chromapi/model/mjcf/assets/robot_case_top.msh +0 -0
- chromapi/model/mjcf/assets/robot_case_top.part +13 -0
- chromapi/model/mjcf/assets/rpi_battery_bracket.msh +0 -0
- chromapi/model/mjcf/assets/rpi_battery_bracket.part +13 -0
- chromapi/model/mjcf/assets/speaker.msh +0 -0
- chromapi/model/mjcf/assets/speaker.part +13 -0
- chromapi/model/mjcf/assets/vis_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/vis_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/vis_1__corps1_1.msh +0 -0
- chromapi/model/mjcf/assets/vis_1__corps1_1.part +13 -0
- chromapi/model/mjcf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.msh +0 -0
- chromapi/model/mjcf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.part +13 -0
- chromapi/model/mjcf/assets/ws2812b_cob_pixel_ring_27mm.msh +0 -0
- chromapi/model/mjcf/assets/ws2812b_cob_pixel_ring_27mm.part +13 -0
- chromapi/model/mjcf/config.json +14 -0
- chromapi/model/mjcf/robot.xml +639 -0
- chromapi/model/mjcf/scene.xml +24 -0
- chromapi/model/urdf/assets/18650_li_ion_battery.part +13 -0
- chromapi/model/urdf/assets/18650_li_ion_battery.stl +0 -0
- chromapi/model/urdf/assets/battery_holder.part +13 -0
- chromapi/model/urdf/assets/battery_holder.stl +0 -0
- chromapi/model/urdf/assets/camera_imx219_d160.part +13 -0
- chromapi/model/urdf/assets/camera_imx219_d160.stl +0 -0
- chromapi/model/urdf/assets/chromapi_logo.part +13 -0
- chromapi/model/urdf/assets/chromapi_logo.stl +0 -0
- chromapi/model/urdf/assets/chromapi_logo_circle.stl +0 -0
- chromapi/model/urdf/assets/chromapi_logo_inner.stl +0 -0
- chromapi/model/urdf/assets/chromapi_logo_outer.stl +0 -0
- chromapi/model/urdf/assets/chromapi_motherboard.part +13 -0
- chromapi/model/urdf/assets/chromapi_motherboard.stl +0 -0
- chromapi/model/urdf/assets/composant2_1__corps1.part +13 -0
- chromapi/model/urdf/assets/composant2_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/composant3_1__corps1.part +13 -0
- chromapi/model/urdf/assets/composant3_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/composant4_1__corps1.part +13 -0
- chromapi/model/urdf/assets/composant4_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/connector_f_1__corps1.part +13 -0
- chromapi/model/urdf/assets/connector_f_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/connector_f_1__corps1_1.part +13 -0
- chromapi/model/urdf/assets/connector_f_1__corps1_1.stl +0 -0
- chromapi/model/urdf/assets/corps14.part +13 -0
- chromapi/model/urdf/assets/corps14.stl +0 -0
- chromapi/model/urdf/assets/fan_nf_a4x10.part +13 -0
- chromapi/model/urdf/assets/fan_nf_a4x10.stl +0 -0
- chromapi/model/urdf/assets/foot.part +13 -0
- chromapi/model/urdf/assets/foot.stl +0 -0
- chromapi/model/urdf/assets/left_coxa.part +13 -0
- chromapi/model/urdf/assets/left_coxa.stl +0 -0
- chromapi/model/urdf/assets/left_femur.part +13 -0
- chromapi/model/urdf/assets/left_femur.stl +0 -0
- chromapi/model/urdf/assets/left_tibia.part +13 -0
- chromapi/model/urdf/assets/left_tibia.stl +0 -0
- chromapi/model/urdf/assets/microswitch.part +13 -0
- chromapi/model/urdf/assets/microswitch.stl +0 -0
- chromapi/model/urdf/assets/power_switch.part +13 -0
- chromapi/model/urdf/assets/power_switch.stl +0 -0
- chromapi/model/urdf/assets/raspberry_pi_4_model_b.part +13 -0
- chromapi/model/urdf/assets/raspberry_pi_4_model_b.stl +0 -0
- chromapi/model/urdf/assets/right_coxa.part +13 -0
- chromapi/model/urdf/assets/right_coxa.stl +0 -0
- chromapi/model/urdf/assets/right_femur.part +13 -0
- chromapi/model/urdf/assets/right_femur.stl +0 -0
- chromapi/model/urdf/assets/right_tibia.part +13 -0
- chromapi/model/urdf/assets/right_tibia.stl +0 -0
- chromapi/model/urdf/assets/robot_case_bottom.part +13 -0
- chromapi/model/urdf/assets/robot_case_bottom.stl +0 -0
- chromapi/model/urdf/assets/robot_case_top.part +13 -0
- chromapi/model/urdf/assets/robot_case_top.stl +0 -0
- chromapi/model/urdf/assets/rpi_battery_bracket.part +13 -0
- chromapi/model/urdf/assets/rpi_battery_bracket.stl +0 -0
- chromapi/model/urdf/assets/speaker.part +13 -0
- chromapi/model/urdf/assets/speaker.stl +0 -0
- chromapi/model/urdf/assets/vis_1__corps1.part +13 -0
- chromapi/model/urdf/assets/vis_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/vis_1__corps1_1.part +13 -0
- chromapi/model/urdf/assets/vis_1__corps1_1.stl +0 -0
- chromapi/model/urdf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.part +13 -0
- chromapi/model/urdf/assets/vis_a_tete_tronconique_jis_b_1111_m3x4_h_acier_inoxydable_a2_standard_v1_1__corps1.stl +0 -0
- chromapi/model/urdf/assets/ws2812b_cob_pixel_ring_27mm.part +13 -0
- chromapi/model/urdf/assets/ws2812b_cob_pixel_ring_27mm.stl +0 -0
- chromapi/model/urdf/config.json +8 -0
- chromapi/model/urdf/robot.urdf +2587 -0
- chromapi/utils/calibrate_imu_mount.py +80 -0
- chromapi/utils/calibrate_servo_centers.py +432 -0
- chromapi/utils/flash.py +141 -0
- chromapi/utils/health.py +210 -0
- chromapi/utils/report.py +75 -0
- chromapi/utils/setup_motors.py +189 -0
- chromapi/utils/sim_server.py +126 -0
- chromapi/web/__init__.py +2 -0
- chromapi/web/access.py +167 -0
- chromapi/web/app.py +1136 -0
- chromapi/web/camera.py +202 -0
- chromapi/web/static/fonts/varela-round.woff2 +0 -0
- chromapi/web/static/index.html +1079 -0
- chromapi/web/static/logo.png +0 -0
- chromapi/web/static/motherboard_front.png +0 -0
- chromapi/web/static/socket.io.min.js +7 -0
- chromapi-1.0.0.dist-info/METADATA +222 -0
- chromapi-1.0.0.dist-info/RECORD +219 -0
- chromapi-1.0.0.dist-info/WHEEL +5 -0
- chromapi-1.0.0.dist-info/entry_points.txt +2 -0
- chromapi-1.0.0.dist-info/licenses/LICENSE +201 -0
- chromapi-1.0.0.dist-info/licenses/src/chromapi/model/LICENSE +438 -0
- chromapi-1.0.0.dist-info/top_level.txt +1 -0
chromapi/chromapi.py
ADDED
|
@@ -0,0 +1,1460 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Chromapi class for controlling a Chromapi robot.
|
|
3
|
+
|
|
4
|
+
High-level SDK entry point: one :class:`Chromapi` object drives either the real robot (over
|
|
5
|
+
the STM32 UART bridge, see :mod:`chromapi.hardware.motherboard_bridge`) or a MuJoCo
|
|
6
|
+
simulation of it (``model/mjcf/scene.xml``).
|
|
7
|
+
|
|
8
|
+
Standing is not the zero configuration
|
|
9
|
+
---------------------------------------
|
|
10
|
+
Note that for Chromapi q = 0 on every joint means the legs are splayed out flat, roughly level (see
|
|
11
|
+
Onshape assembly). It is a valid, structurally stable configuration (the motors are strong), but it is
|
|
12
|
+
not what you want to power on into for locomotion. Because of this:
|
|
13
|
+
|
|
14
|
+
- :meth:`Chromapi.connect` never commands ``ZERO_POSE`` on its own; it only reads back
|
|
15
|
+
whatever configuration the robot/sim is already in.
|
|
16
|
+
- :meth:`Chromapi.wake_up` is the only way to reach :meth:`Chromapi.stand_pose` - always
|
|
17
|
+
through a smooth interpolation, never a jump, regardless of the starting configuration.
|
|
18
|
+
- :meth:`Chromapi.rest` returns to a compact, *load-bearing* crouch
|
|
19
|
+
(:data:`chromapi.kinematics.kromatics.REST_POSE`), not to
|
|
20
|
+
:data:`~chromapi.kinematics.kromatics.ZERO_POSE`.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import importlib.metadata
|
|
26
|
+
import logging
|
|
27
|
+
import os
|
|
28
|
+
import signal
|
|
29
|
+
import sys
|
|
30
|
+
import threading
|
|
31
|
+
import time
|
|
32
|
+
from abc import ABC, abstractmethod
|
|
33
|
+
from dataclasses import dataclass, field, replace
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import (
|
|
36
|
+
TYPE_CHECKING,
|
|
37
|
+
Any,
|
|
38
|
+
Callable,
|
|
39
|
+
Dict,
|
|
40
|
+
List,
|
|
41
|
+
Optional,
|
|
42
|
+
Sequence,
|
|
43
|
+
Tuple,
|
|
44
|
+
Union,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
import numpy as np
|
|
48
|
+
import numpy.typing as npt
|
|
49
|
+
import yaml
|
|
50
|
+
|
|
51
|
+
from chromapi.estimation.attitude import IDENTITY_QUAT, ImuMount
|
|
52
|
+
from chromapi.hardware.battery import CRITICAL, EMPTY, LOW, OK, Battery
|
|
53
|
+
from chromapi.hardware.motherboard_bridge import (
|
|
54
|
+
BRIDGE_PROTOCOL_VERSION,
|
|
55
|
+
DEFAULT_BAUDRATE,
|
|
56
|
+
BridgeClient,
|
|
57
|
+
)
|
|
58
|
+
from chromapi.kinematics import kromatics as K
|
|
59
|
+
|
|
60
|
+
if TYPE_CHECKING:
|
|
61
|
+
from chromapi.locomotion.gait import GaitParams, WalkMove
|
|
62
|
+
|
|
63
|
+
logger = logging.getLogger(__name__)
|
|
64
|
+
|
|
65
|
+
_PACKAGE_DIR = Path(__file__).resolve().parent
|
|
66
|
+
DEFAULT_CONFIG_PATH = _PACKAGE_DIR / "config" / "config.yaml"
|
|
67
|
+
USER_CALIBRATION_PATH = (
|
|
68
|
+
Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "chromapi" / "calibration.yaml"
|
|
69
|
+
)
|
|
70
|
+
DEFAULT_URDF_PATH = _PACKAGE_DIR / "model" / "urdf" / "robot.urdf"
|
|
71
|
+
DEFAULT_MJCF_PATH = _PACKAGE_DIR / "model" / "mjcf" / "scene.xml"
|
|
72
|
+
AUDIO_DIR = _PACKAGE_DIR / "assets" / "audio"
|
|
73
|
+
DEFAULT_CHROMAPI_SCREAM_PATH = AUDIO_DIR / "chromapi_scream.wav"
|
|
74
|
+
IDLE_LED_RGB = (63, 1, 88)
|
|
75
|
+
IK_QUERY_ITERATIONS = 100 # QP iterations of inverse_kinematics(): far targets need more than the walk's
|
|
76
|
+
IK_TOLERANCE_M = 0.001 # [m]
|
|
77
|
+
WAIT_MARGIN_S = 1.0 # [s] a wait=True call gives up this long after the move should have ended
|
|
78
|
+
STOP_WAIT_S = 3.0 # [s]
|
|
79
|
+
GIL_SWITCH_INTERVAL_S = 0.001 # [s]
|
|
80
|
+
CONTROL_LOOP_RT_PRIORITY = 10
|
|
81
|
+
|
|
82
|
+
#: STS3215 magnetic-encoder resolution (steps per revolution) and center step, standard
|
|
83
|
+
#: Feetech convention (see stm32-sts3215-lib's ``sts3215_regs.h``/memory table).
|
|
84
|
+
STS3215_STEPS_PER_REV = 4096 # [step.rev⁻¹]
|
|
85
|
+
STS3215_CENTER_STEP = 2048 # [step]
|
|
86
|
+
#: While walking, servo replies get lost now and then (~0.1 s): report a servo only after this many control
|
|
87
|
+
#: ticks in a row without an answer, which means it is really disconnected.
|
|
88
|
+
SERVO_MISSING_CYCLES = 50
|
|
89
|
+
#: After a reset (power-on, a flash) the firmware calibrates its IMU, so we wait a little before it answers anything [s].
|
|
90
|
+
STM32_BOOT_WAIT_S = 10.0
|
|
91
|
+
_STEPS_PER_RAD = STS3215_STEPS_PER_REV / (2.0 * np.pi) # [step.rad⁻¹]
|
|
92
|
+
|
|
93
|
+
def sdk_version() -> str:
|
|
94
|
+
"""Installed version of this SDK."""
|
|
95
|
+
try:
|
|
96
|
+
return importlib.metadata.version("chromapi")
|
|
97
|
+
except importlib.metadata.PackageNotFoundError:
|
|
98
|
+
return "unknown (not installed)"
|
|
99
|
+
|
|
100
|
+
# ========================================================================================
|
|
101
|
+
# Chromapi state
|
|
102
|
+
# ========================================================================================
|
|
103
|
+
@dataclass
|
|
104
|
+
class RobotState:
|
|
105
|
+
"""A timestamped snapshot of the robot's proprioceptive state."""
|
|
106
|
+
|
|
107
|
+
joint_positions: Dict[str, float] = field(default_factory=dict) # [rad]
|
|
108
|
+
joint_velocities: Dict[str, float] = field(default_factory=dict) # [rad.s⁻¹]
|
|
109
|
+
joint_loads: Dict[str, float] = field(default_factory=dict) # [0.1 %] of rated torque (raw STS3215 load)
|
|
110
|
+
joint_currents: Dict[str, float] = field(default_factory=dict) # [A] motor current magnitude (≥ 0)
|
|
111
|
+
joint_temperatures: Dict[str, float] = field(default_factory=dict) # [°C]
|
|
112
|
+
missing_servos: List[str] = field(default_factory=list) # joints whose servo stopped answering
|
|
113
|
+
imu_quat_wxyz: Tuple[float, float, float, float] = (1.0, 0.0, 0.0, 0.0) # unit quaternion
|
|
114
|
+
imu_gyro: Tuple[float, float, float] = (0.0, 0.0, 0.0) # [rad.s⁻¹] bias-corrected
|
|
115
|
+
imu_gyro_raw: Tuple[float, float, float] = (0.0, 0.0, 0.0) # [rad.s⁻¹] as read by the sensor
|
|
116
|
+
imu_accel: Tuple[float, float, float] = (0.0, 0.0, 0.0) # [m.s⁻²] specific force: (0, 0, +g) when level
|
|
117
|
+
foot_contacts: Dict[str, bool] = field(default_factory=dict)
|
|
118
|
+
voltage_v: float = 0.0 # [V]
|
|
119
|
+
current_a: float = 0.0 # [A]
|
|
120
|
+
power_w: float = 0.0 # [W]
|
|
121
|
+
battery_percent: Optional[float] = None # [%] smoothed charge estimate; None until read, and in simulation
|
|
122
|
+
timestamp: float = 0.0 # [s]
|
|
123
|
+
mcu_time_us: int = 0 # [µs] STM32 time of the servo read; 0 in simulation
|
|
124
|
+
|
|
125
|
+
# ========================================================================================
|
|
126
|
+
# Backend abstraction - real hardware vs MuJoCo, behind one interface
|
|
127
|
+
# ========================================================================================
|
|
128
|
+
class RobotBackend(ABC):
|
|
129
|
+
"""What Chromapi needs from a hardware or simulated backend.
|
|
130
|
+
|
|
131
|
+
Interface implemented by both a real-servo controller
|
|
132
|
+
and a MuJoCo/MeshCat one - keeping :class:`Chromapi` itself
|
|
133
|
+
entirely backend-agnostic.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
@abstractmethod
|
|
137
|
+
def connect(self) -> bool:
|
|
138
|
+
"""Open the connection (serial port, or instantiate the sim). Returns success."""
|
|
139
|
+
|
|
140
|
+
@abstractmethod
|
|
141
|
+
def close(self) -> None:
|
|
142
|
+
"""Release the connection/simulation resources."""
|
|
143
|
+
|
|
144
|
+
@abstractmethod
|
|
145
|
+
def send_joint_targets(self, q: Dict[str, float]) -> bool:
|
|
146
|
+
"""Send target joint angles [rad], keyed by joint name. Returns success."""
|
|
147
|
+
|
|
148
|
+
@abstractmethod
|
|
149
|
+
def read_state(self) -> Optional[RobotState]:
|
|
150
|
+
"""Read back the current proprioceptive state, or None on failure/timeout."""
|
|
151
|
+
|
|
152
|
+
def set_torque_enabled(
|
|
153
|
+
self, enabled: bool, joints: Optional[Sequence[str]] = None
|
|
154
|
+
) -> None:
|
|
155
|
+
"""Enable/disable actuator torque on the given joints (default: all). No-op if unsupported."""
|
|
156
|
+
|
|
157
|
+
def set_led_all(self, r: int, g: int, b: int) -> None:
|
|
158
|
+
"""Set every ring LED to one color. No-op if unsupported."""
|
|
159
|
+
|
|
160
|
+
def set_led(self, index: int, r: int, g: int, b: int) -> None:
|
|
161
|
+
"""Set a single ring LED (0-17). No-op if unsupported."""
|
|
162
|
+
|
|
163
|
+
def set_led_bulk(self, colors: Sequence[Tuple[int, int, int]]) -> None:
|
|
164
|
+
"""Set all 18 ring LEDs at once from a list of (r, g, b) tuples. No-op if unsupported."""
|
|
165
|
+
|
|
166
|
+
def is_alive(self) -> bool:
|
|
167
|
+
"""Whether the backend is still usable - False once it can no longer be driven.
|
|
168
|
+
|
|
169
|
+
Checked once per :meth:`Chromapi._control_loop` tick; returning False ends the
|
|
170
|
+
control loop (see :class:`MuJoCoBackend`'s override, for the interactive viewer
|
|
171
|
+
window being closed). Always True by default (real hardware has no equivalent
|
|
172
|
+
"closed" state short of :meth:`close`).
|
|
173
|
+
"""
|
|
174
|
+
return True
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class HardwareBackend(RobotBackend):
|
|
178
|
+
"""Real Chromapi hardware, over the STM32 UART bridge (:class:`BridgeClient`)."""
|
|
179
|
+
|
|
180
|
+
def __init__(
|
|
181
|
+
self,
|
|
182
|
+
servo_config: Dict[str, Dict[str, Any]],
|
|
183
|
+
port: str = "/dev/ttyAMA0",
|
|
184
|
+
baudrate: int = DEFAULT_BAUDRATE,
|
|
185
|
+
imu_mount: Optional[ImuMount] = None,
|
|
186
|
+
) -> None:
|
|
187
|
+
"""Build the backend from the ``servos:`` section of ``config.yaml``.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
servo_config: The ``config["servos"]`` mapping (``id_map``, ``sign``,
|
|
191
|
+
``zero_offset_steps`` - see ``config/config.yaml``).
|
|
192
|
+
port: Serial device for the RPi4 <-> STM32 UART bridge.
|
|
193
|
+
baudrate: Must match the bridge firmware (2 Mbps).
|
|
194
|
+
imu_mount: IMU board offset, applied to every IMU reading (``config["imu"]``).
|
|
195
|
+
|
|
196
|
+
"""
|
|
197
|
+
self._imu_mount: ImuMount = imu_mount if imu_mount is not None else ImuMount()
|
|
198
|
+
self._bridge = BridgeClient(port=port, baudrate=baudrate)
|
|
199
|
+
self.firmware_version: Optional[str] = None # "major.minor.patch", read by connect()
|
|
200
|
+
self._misses: Dict[str, int] = {} # consecutive bus cycles without an answer, per joint
|
|
201
|
+
self._missing_since: Dict[str, float] = {} # [s] joints reported missing, since when
|
|
202
|
+
self._id_map: Dict[str, int] = dict(servo_config["id_map"])
|
|
203
|
+
self._sign: Dict[str, int] = dict(servo_config["sign"])
|
|
204
|
+
self._zero_offset: Dict[str, int] = dict(servo_config["zero_offset_steps"]) # [step]
|
|
205
|
+
self._id_to_joint: Dict[int, str] = {v: k for k, v in self._id_map.items()}
|
|
206
|
+
missing = set(K.JOINT_NAMES) - set(self._id_map)
|
|
207
|
+
if missing:
|
|
208
|
+
raise ValueError(f"servo config is missing joints: {sorted(missing)}")
|
|
209
|
+
|
|
210
|
+
def connect(self) -> bool:
|
|
211
|
+
"""Open the UART serial port to the STM32 bridge, and log the firmware version."""
|
|
212
|
+
if not self._bridge.connect():
|
|
213
|
+
return False
|
|
214
|
+
self._wait_until_answering()
|
|
215
|
+
version = self._bridge.get_version()
|
|
216
|
+
if version is not None:
|
|
217
|
+
self.firmware_version = ".".join(map(str, version[1]))
|
|
218
|
+
if version is None:
|
|
219
|
+
logger.warning("chromapi SDK %s, motherboard firmware older than 2.0.0 (no version command) - "
|
|
220
|
+
"please update it", sdk_version())
|
|
221
|
+
elif version[0] != BRIDGE_PROTOCOL_VERSION:
|
|
222
|
+
logger.warning(
|
|
223
|
+
"Motherboard firmware %d.%d.%d speaks bridge protocol %d, chromapi SDK %s speaks %d - "
|
|
224
|
+
"update one of them", *version[1], version[0], sdk_version(), BRIDGE_PROTOCOL_VERSION,
|
|
225
|
+
)
|
|
226
|
+
else:
|
|
227
|
+
logger.info("chromapi SDK %s, motherboard firmware %d.%d.%d, bridge protocol %d",
|
|
228
|
+
sdk_version(), *version[1], version[0])
|
|
229
|
+
return True
|
|
230
|
+
|
|
231
|
+
def close(self) -> None:
|
|
232
|
+
"""Close the UART serial port."""
|
|
233
|
+
self._bridge.close()
|
|
234
|
+
|
|
235
|
+
def _wait_until_answering(self) -> bool:
|
|
236
|
+
"""Wait (at most STM32_BOOT_WAIT_S) for the STM32's state stream."""
|
|
237
|
+
bridge_log = logging.getLogger("BridgeClient")
|
|
238
|
+
level = bridge_log.level
|
|
239
|
+
bridge_log.setLevel(logging.CRITICAL) # its timeouts are expected while the board boots
|
|
240
|
+
try:
|
|
241
|
+
deadline = time.monotonic() + STM32_BOOT_WAIT_S # [s]
|
|
242
|
+
waiting = False
|
|
243
|
+
while time.monotonic() < deadline:
|
|
244
|
+
if self._bridge.get_state() is not None:
|
|
245
|
+
return True
|
|
246
|
+
if not waiting:
|
|
247
|
+
logger.info("Waiting for the motherboard to answer (it calibrates its IMU after a reset)...")
|
|
248
|
+
waiting = True
|
|
249
|
+
logger.warning("The motherboard does not answer after %.0f s", STM32_BOOT_WAIT_S)
|
|
250
|
+
return False
|
|
251
|
+
finally:
|
|
252
|
+
bridge_log.setLevel(level)
|
|
253
|
+
|
|
254
|
+
def apply_calibration(self, config: Dict[str, Any]) -> None:
|
|
255
|
+
"""Take the servo zero offsets and the IMU mount of ``config`` (after ``chromapi calibrate``)."""
|
|
256
|
+
self._zero_offset = dict(config["servos"]["zero_offset_steps"]) # [step]
|
|
257
|
+
self._imu_mount = ImuMount(tuple(config.get("imu", {}).get("mount_offset_wxyz", IDENTITY_QUAT)))
|
|
258
|
+
|
|
259
|
+
def _rad_to_steps(self, joint: str, angle_rad: float) -> int:
|
|
260
|
+
raw = ( # [step]
|
|
261
|
+
STS3215_CENTER_STEP
|
|
262
|
+
+ self._sign[joint] * angle_rad * _STEPS_PER_RAD
|
|
263
|
+
+ self._zero_offset[joint]
|
|
264
|
+
)
|
|
265
|
+
return min(max(round(raw), 0), STS3215_STEPS_PER_REV - 1)
|
|
266
|
+
|
|
267
|
+
def _steps_to_rad(self, joint: str, raw_steps: int) -> float:
|
|
268
|
+
raw = raw_steps - STS3215_CENTER_STEP - self._zero_offset[joint] # [step]
|
|
269
|
+
return self._sign[joint] * raw / _STEPS_PER_RAD
|
|
270
|
+
|
|
271
|
+
def send_joint_targets(self, q: Dict[str, float]) -> bool:
|
|
272
|
+
"""Pack joint angles into the 12-servo raw-step frame and send SET_POSITIONS."""
|
|
273
|
+
raw_steps = [STS3215_CENTER_STEP] * 12 # [step]
|
|
274
|
+
for joint, angle in q.items():
|
|
275
|
+
servo_id = self._id_map.get(joint)
|
|
276
|
+
if servo_id is None:
|
|
277
|
+
continue
|
|
278
|
+
raw_steps[servo_id - 1] = self._rad_to_steps(joint, angle)
|
|
279
|
+
return self._bridge.set_positions(raw_steps)
|
|
280
|
+
|
|
281
|
+
def read_state(self) -> Optional[RobotState]:
|
|
282
|
+
"""Return a :class:`RobotState`."""
|
|
283
|
+
snapshot = self._bridge.get_state()
|
|
284
|
+
if snapshot is None:
|
|
285
|
+
return None
|
|
286
|
+
|
|
287
|
+
state = RobotState(timestamp=time.monotonic(), mcu_time_us=snapshot["t_us"])
|
|
288
|
+
for servo in snapshot["servos"]:
|
|
289
|
+
joint = self._id_to_joint.get(servo["id"])
|
|
290
|
+
if joint is None:
|
|
291
|
+
continue
|
|
292
|
+
state.joint_positions[joint] = self._steps_to_rad(joint, servo["pos"])
|
|
293
|
+
# STS3215 "Present Speed" shares the position register's step resolution
|
|
294
|
+
# (Feetech convention: raw units are steps/second).
|
|
295
|
+
state.joint_velocities[joint] = (
|
|
296
|
+
self._sign[joint] * servo["speed"] / _STEPS_PER_RAD
|
|
297
|
+
)
|
|
298
|
+
state.joint_loads[joint] = float(servo["load"])
|
|
299
|
+
state.joint_currents[joint] = servo["current_A"] # magnitude, no direction
|
|
300
|
+
state.joint_temperatures[joint] = float(servo["temp_C"])
|
|
301
|
+
self._misses[joint] = 0 if servo["fresh"] else self._misses.get(joint, 0) + 1
|
|
302
|
+
if self._misses[joint] >= SERVO_MISSING_CYCLES:
|
|
303
|
+
state.missing_servos.append(joint)
|
|
304
|
+
if joint not in self._missing_since:
|
|
305
|
+
self._missing_since[joint] = state.timestamp
|
|
306
|
+
logger.warning("Servo %s (id %d) not answering (battery %.2f V, %.2f A)", joint, servo["id"],
|
|
307
|
+
snapshot["power"]["voltage_V"], snapshot["power"]["current_A"])
|
|
308
|
+
elif joint in self._missing_since and servo["fresh"]:
|
|
309
|
+
logger.warning("Servo %s (id %d) back after %.2f s", joint, servo["id"],
|
|
310
|
+
state.timestamp - self._missing_since.pop(joint))
|
|
311
|
+
|
|
312
|
+
# The firmware sends the IMU in the URDF/MJCF "imu" frame (x forward, y left, z up), as MuJoCo does
|
|
313
|
+
state.imu_quat_wxyz = self._imu_mount.apply(snapshot["imu"]["quat"])
|
|
314
|
+
state.imu_gyro_raw = self._imu_mount.apply_vector(snapshot["imu"]["gyro_rps"]) # [rad.s⁻¹]
|
|
315
|
+
state.imu_gyro = self._imu_mount.apply_vector(snapshot["imu"]["gyro_corr_rps"]) # [rad.s⁻¹]
|
|
316
|
+
state.imu_accel = self._imu_mount.apply_vector(snapshot["imu"]["acc_mps2"]) # [m.s⁻²]
|
|
317
|
+
state.foot_contacts = {
|
|
318
|
+
"tl": snapshot["switches"]["TL"],
|
|
319
|
+
"tr": snapshot["switches"]["TR"],
|
|
320
|
+
"bl": snapshot["switches"]["BL"],
|
|
321
|
+
"br": snapshot["switches"]["BR"],
|
|
322
|
+
}
|
|
323
|
+
state.voltage_v = snapshot["power"]["voltage_V"]
|
|
324
|
+
state.current_a = snapshot["power"]["current_A"]
|
|
325
|
+
state.power_w = snapshot["power"]["power_W"]
|
|
326
|
+
return state
|
|
327
|
+
|
|
328
|
+
def set_torque_enabled(
|
|
329
|
+
self, enabled: bool, joints: Optional[Sequence[str]] = None
|
|
330
|
+
) -> None:
|
|
331
|
+
"""Switch STS3215 torque on the given joints."""
|
|
332
|
+
target_joints = joints if joints is not None else K.JOINT_NAMES
|
|
333
|
+
servo_ids = [self._id_map[j] for j in target_joints if j in self._id_map]
|
|
334
|
+
if servo_ids:
|
|
335
|
+
self._bridge.set_torque(enabled, servo_ids)
|
|
336
|
+
|
|
337
|
+
def set_led_all(self, r: int, g: int, b: int) -> None:
|
|
338
|
+
"""Set every ring LED via a single bridge frame."""
|
|
339
|
+
self._bridge.set_led_color_all(r, g, b, wait=False)
|
|
340
|
+
|
|
341
|
+
def set_led(self, index: int, r: int, g: int, b: int) -> None:
|
|
342
|
+
"""Set a single ring LED via the bridge."""
|
|
343
|
+
self._bridge.set_led_color(index, r, g, b, wait=False)
|
|
344
|
+
|
|
345
|
+
def set_led_bulk(self, colors: Sequence[Tuple[int, int, int]]) -> None:
|
|
346
|
+
"""Set all 18 ring LEDs via a single bridge frame."""
|
|
347
|
+
self._bridge.set_led_color_bulk(list(colors), wait=False)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
#: Chassis height [m] at which Chromapi rests on the floor in ZERO_POSE (settles at 0.0774 m): start_in_pose lowers from above it.
|
|
351
|
+
_SPAWN_HEIGHT_M = 0.08
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class MuJoCoBackend(RobotBackend):
|
|
355
|
+
"""MuJoCo simulation backend, driving ``model/mjcf/scene.xml``."""
|
|
356
|
+
|
|
357
|
+
def __init__(
|
|
358
|
+
self,
|
|
359
|
+
mjcf_path: Union[str, Path] = DEFAULT_MJCF_PATH,
|
|
360
|
+
realtime: bool = True,
|
|
361
|
+
launch_viewer: bool = False,
|
|
362
|
+
key_callback: Optional[Callable[[int], None]] = None,
|
|
363
|
+
follow_robot: bool = False,
|
|
364
|
+
) -> None:
|
|
365
|
+
"""Load the MJCF model.
|
|
366
|
+
|
|
367
|
+
Args:
|
|
368
|
+
mjcf_path: Path to ``model/mjcf/scene.xml``
|
|
369
|
+
realtime: If True, steps the simulation in real-time. If False, steps as fast as possible.
|
|
370
|
+
launch_viewer: If True, opens an interactive ``mujoco.viewer`` window.
|
|
371
|
+
key_callback: Receives a raw GLFW keycode on every keypress in
|
|
372
|
+
the viewer window for teleop use.
|
|
373
|
+
follow_robot: If True, the viewer camera tracks the chassis (Esc frees it).
|
|
374
|
+
|
|
375
|
+
"""
|
|
376
|
+
if os.environ.get("XDG_SESSION_TYPE") == "wayland" and os.environ.get("DISPLAY"):
|
|
377
|
+
# GLFW's Wayland build draws no title bar (no close button): the X11 one, through XWayland, does.
|
|
378
|
+
os.environ.setdefault("PYGLFW_LIBRARY_VARIANT", "x11")
|
|
379
|
+
import mujoco # local import: mujoco is an optional ("sim") dependency
|
|
380
|
+
|
|
381
|
+
self._mujoco = mujoco
|
|
382
|
+
self._model = mujoco.MjModel.from_xml_path(str(mjcf_path))
|
|
383
|
+
self._data = mujoco.MjData(self._model)
|
|
384
|
+
self._realtime = realtime
|
|
385
|
+
self._last_step_time: Optional[float] = None # [s]
|
|
386
|
+
self._viewer: Any = None # mujoco.viewer.Handle once connect() opened it
|
|
387
|
+
self._viewer_thread: Optional[threading.Thread] = None
|
|
388
|
+
self._launch_viewer = launch_viewer
|
|
389
|
+
self._key_callback = key_callback
|
|
390
|
+
self._follow_robot = follow_robot
|
|
391
|
+
|
|
392
|
+
self._chassis_body_id = mujoco.mj_name2id(
|
|
393
|
+
self._model, mujoco.mjtObj.mjOBJ_BODY, "chassis_assembly"
|
|
394
|
+
)
|
|
395
|
+
self._foot_body_ids = {
|
|
396
|
+
leg: mujoco.mj_name2id(
|
|
397
|
+
self._model, mujoco.mjtObj.mjOBJ_BODY, f"{leg}_foot"
|
|
398
|
+
)
|
|
399
|
+
for leg in K.LEG_NAMES
|
|
400
|
+
}
|
|
401
|
+
self._floor_geom_id = mujoco.mj_name2id(
|
|
402
|
+
self._model, mujoco.mjtObj.mjOBJ_GEOM, "floor"
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
self._led_ring_material_id = mujoco.mj_name2id(
|
|
406
|
+
self._model, mujoco.mjtObj.mjOBJ_MATERIAL, "ws2812b_cob_pixel_ring_27mm_material"
|
|
407
|
+
)
|
|
408
|
+
self._led_ring_default_rgb: Optional[npt.NDArray[np.float64]] = (
|
|
409
|
+
self._model.mat_rgba[self._led_ring_material_id][:3].copy()
|
|
410
|
+
if self._led_ring_material_id >= 0
|
|
411
|
+
else None
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
# A foot is "in contact" if any geom belonging to its tibia body touches the floor.
|
|
415
|
+
self._foot_geom_ids: Dict[str, List[int]] = {leg: [] for leg in K.LEG_NAMES}
|
|
416
|
+
tibia_body_of_leg = {
|
|
417
|
+
"tl": "left_tibia_assembly",
|
|
418
|
+
"bl": "left_tibia_assembly_2",
|
|
419
|
+
"br": "right_tibia_assembly",
|
|
420
|
+
"tr": "right_tibia_assembly_2",
|
|
421
|
+
}
|
|
422
|
+
for leg, body_name in tibia_body_of_leg.items():
|
|
423
|
+
body_id = mujoco.mj_name2id(self._model, mujoco.mjtObj.mjOBJ_BODY, body_name)
|
|
424
|
+
self._foot_geom_ids[leg] = [
|
|
425
|
+
g for g in range(self._model.ngeom) if self._model.geom_bodyid[g] == body_id
|
|
426
|
+
]
|
|
427
|
+
|
|
428
|
+
# The MJCF puts the chassis at z = 0, inside the floor: start lying in REST_POSE, as the real robot.
|
|
429
|
+
self.start_in_pose(K.REST_POSE)
|
|
430
|
+
|
|
431
|
+
def connect(self) -> bool:
|
|
432
|
+
"""No-op (the model is already loaded); optionally opens the interactive viewer."""
|
|
433
|
+
if self._launch_viewer and self._viewer is None:
|
|
434
|
+
import mujoco.viewer
|
|
435
|
+
|
|
436
|
+
threads_before = set(threading.enumerate())
|
|
437
|
+
self._viewer = mujoco.viewer.launch_passive(
|
|
438
|
+
self._model,
|
|
439
|
+
self._data,
|
|
440
|
+
key_callback=self._key_callback,
|
|
441
|
+
show_left_ui=False, # Tab / Shift+Tab bring the panels back
|
|
442
|
+
show_right_ui=False,
|
|
443
|
+
)
|
|
444
|
+
self._viewer_thread = next(iter(set(threading.enumerate()) - threads_before), None)
|
|
445
|
+
with self._viewer.lock(): # three-quarter front view, close on the robot
|
|
446
|
+
cam = self._viewer.cam
|
|
447
|
+
cam.lookat[:] = self._data.xpos[self._chassis_body_id] - (0.0, 0.0, 0.025)
|
|
448
|
+
cam.distance = 0.85 # [m]
|
|
449
|
+
cam.elevation = -18.0 # [deg]
|
|
450
|
+
cam.azimuth = 195.0 # [deg]
|
|
451
|
+
if self._follow_robot:
|
|
452
|
+
cam.type = self._mujoco.mjtCamera.mjCAMERA_TRACKING
|
|
453
|
+
cam.trackbodyid = self._chassis_body_id
|
|
454
|
+
return True
|
|
455
|
+
|
|
456
|
+
def close(self) -> None:
|
|
457
|
+
"""Close the interactive viewer, if one was opened."""
|
|
458
|
+
if self._viewer is not None:
|
|
459
|
+
try:
|
|
460
|
+
self._viewer.close()
|
|
461
|
+
except Exception:
|
|
462
|
+
logger.debug("MuJoCo viewer close() raised (already closed?) - ignoring", exc_info=True)
|
|
463
|
+
if self._viewer_thread is not None:
|
|
464
|
+
self._viewer_thread.join(timeout=5.0)
|
|
465
|
+
self._viewer = None
|
|
466
|
+
self._viewer_thread = None
|
|
467
|
+
|
|
468
|
+
def is_alive(self) -> bool:
|
|
469
|
+
"""Check if the interactive viewer window is still open."""
|
|
470
|
+
return self._viewer is None or self._viewer.is_running()
|
|
471
|
+
|
|
472
|
+
@property
|
|
473
|
+
def viewer(self) -> Any:
|
|
474
|
+
"""The ``mujoco.viewer`` handle opened by :meth:`connect`, or None if not launched."""
|
|
475
|
+
return self._viewer
|
|
476
|
+
|
|
477
|
+
_MAX_CATCHUP_S = 0.1 # [s]
|
|
478
|
+
|
|
479
|
+
def send_joint_targets(self, q: Dict[str, float]) -> bool:
|
|
480
|
+
"""Write joint targets to the position actuators and step the simulation forward."""
|
|
481
|
+
for joint, angle in q.items():
|
|
482
|
+
try:
|
|
483
|
+
self._data.actuator(joint).ctrl[0] = angle
|
|
484
|
+
except KeyError:
|
|
485
|
+
continue
|
|
486
|
+
|
|
487
|
+
now = time.monotonic() # [s]
|
|
488
|
+
if self._realtime and self._last_step_time is not None:
|
|
489
|
+
elapsed_sim_needed = min( # [s]
|
|
490
|
+
self._MAX_CATCHUP_S, max(0.0, now - self._last_step_time)
|
|
491
|
+
)
|
|
492
|
+
else:
|
|
493
|
+
elapsed_sim_needed = self._model.opt.timestep
|
|
494
|
+
self._last_step_time = now
|
|
495
|
+
|
|
496
|
+
n_substeps = max(1, round(elapsed_sim_needed / self._model.opt.timestep))
|
|
497
|
+
for _ in range(n_substeps):
|
|
498
|
+
self._mujoco.mj_step(self._model, self._data)
|
|
499
|
+
|
|
500
|
+
if self._viewer is not None and self._viewer.is_running():
|
|
501
|
+
self._viewer.sync()
|
|
502
|
+
return True
|
|
503
|
+
|
|
504
|
+
def read_state(self) -> Optional[RobotState]:
|
|
505
|
+
"""Read joint/IMU/contact state directly from MjData."""
|
|
506
|
+
state = RobotState(timestamp=time.monotonic())
|
|
507
|
+
for joint in K.JOINT_NAMES:
|
|
508
|
+
try:
|
|
509
|
+
state.joint_positions[joint] = float(self._data.joint(joint).qpos[0])
|
|
510
|
+
state.joint_velocities[joint] = float(self._data.joint(joint).qvel[0])
|
|
511
|
+
except KeyError:
|
|
512
|
+
continue
|
|
513
|
+
|
|
514
|
+
try:
|
|
515
|
+
quat = self._data.sensor("orientation").data
|
|
516
|
+
state.imu_quat_wxyz = (
|
|
517
|
+
float(quat[0]),
|
|
518
|
+
float(quat[1]),
|
|
519
|
+
float(quat[2]),
|
|
520
|
+
float(quat[3]),
|
|
521
|
+
)
|
|
522
|
+
gyro = self._data.sensor("imu_ang_vel").data # [rad.s⁻¹]
|
|
523
|
+
state.imu_gyro = (float(gyro[0]), float(gyro[1]), float(gyro[2]))
|
|
524
|
+
state.imu_gyro_raw = state.imu_gyro
|
|
525
|
+
accel = self._data.sensor("imu_accel").data # [m.s⁻²]
|
|
526
|
+
state.imu_accel = (float(accel[0]), float(accel[1]), float(accel[2]))
|
|
527
|
+
except KeyError:
|
|
528
|
+
logger.warning("MJCF model has no 'imu' sensors - IMU state left at defaults")
|
|
529
|
+
|
|
530
|
+
for leg, geom_ids in self._foot_geom_ids.items():
|
|
531
|
+
state.foot_contacts[leg] = self._is_contact(geom_ids)
|
|
532
|
+
|
|
533
|
+
return state
|
|
534
|
+
|
|
535
|
+
def _is_contact(self, geom_ids: List[int]) -> bool:
|
|
536
|
+
geom_id_set = set(geom_ids)
|
|
537
|
+
for i in range(self._data.ncon):
|
|
538
|
+
contact = self._data.contact[i]
|
|
539
|
+
pair = {contact.geom1, contact.geom2}
|
|
540
|
+
if self._floor_geom_id in pair and pair & geom_id_set:
|
|
541
|
+
return True
|
|
542
|
+
return False
|
|
543
|
+
|
|
544
|
+
def _set_led_ring_rgb(self, rgb: npt.NDArray[np.float64]) -> None:
|
|
545
|
+
"""Apply an (r, g, b) triplet (0-255 scale) to the ring material."""
|
|
546
|
+
if self._led_ring_material_id < 0:
|
|
547
|
+
return
|
|
548
|
+
peak = float(np.max(rgb))
|
|
549
|
+
if peak <= 0.0:
|
|
550
|
+
normalized = (
|
|
551
|
+
self._led_ring_default_rgb
|
|
552
|
+
if self._led_ring_default_rgb is not None
|
|
553
|
+
else np.zeros(3)
|
|
554
|
+
)
|
|
555
|
+
else:
|
|
556
|
+
normalized = rgb / peak
|
|
557
|
+
self._model.mat_rgba[self._led_ring_material_id][:3] = normalized
|
|
558
|
+
|
|
559
|
+
def set_led_all(self, r: int, g: int, b: int) -> None:
|
|
560
|
+
"""Recolor the LED ring material according to the given RGB triplet (0-255 scale) - see :meth:`_set_led_ring_rgb`."""
|
|
561
|
+
self._set_led_ring_rgb(np.array([r, g, b], dtype=np.float64))
|
|
562
|
+
|
|
563
|
+
def set_led_bulk(self, colors: Sequence[Tuple[int, int, int]]) -> None:
|
|
564
|
+
"""Recolor the LED ring material to the *average* of ``colors`` - see :meth:`_set_led_ring_rgb`."""
|
|
565
|
+
if not colors:
|
|
566
|
+
return
|
|
567
|
+
mean_rgb = np.mean(np.asarray(colors, dtype=np.float64), axis=0)
|
|
568
|
+
self._set_led_ring_rgb(mean_rgb)
|
|
569
|
+
|
|
570
|
+
def start_in_pose(self, q: Dict[str, float], settle_s: float = 0.5) -> None:
|
|
571
|
+
"""Put Chromapi in the joint configuration ``q`` [rad], lying on the floor - simulation-only.
|
|
572
|
+
|
|
573
|
+
Call before :meth:`connect`: the chassis is lowered until something touches the floor, then the
|
|
574
|
+
physics runs ``settle_s`` [s] with the actuators holding ``q``.
|
|
575
|
+
"""
|
|
576
|
+
for joint, angle in q.items():
|
|
577
|
+
self._data.joint(joint).qpos[0] = angle
|
|
578
|
+
self._data.actuator(joint).ctrl[0] = angle
|
|
579
|
+
self._data.qvel[:] = 0.0
|
|
580
|
+
z = _SPAWN_HEIGHT_M + 0.1 # [m] above any crouch
|
|
581
|
+
while z > 0.0:
|
|
582
|
+
self._data.qpos[2] = z
|
|
583
|
+
self._mujoco.mj_forward(self._model, self._data)
|
|
584
|
+
contacts = (self._data.contact[i] for i in range(self._data.ncon))
|
|
585
|
+
if any(self._floor_geom_id in (c.geom1, c.geom2) for c in contacts):
|
|
586
|
+
break
|
|
587
|
+
z -= 0.001
|
|
588
|
+
for _ in range(round(settle_s / self._model.opt.timestep)):
|
|
589
|
+
self._mujoco.mj_step(self._model, self._data)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
#: Where ``chromapi sim`` listens: this computer only. The key keeps other local programs out (pickled calls).
|
|
593
|
+
SIM_ADDRESS = ("localhost", 7447)
|
|
594
|
+
SIM_AUTHKEY = b"chromapi-sim"
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
class SimClientBackend(RobotBackend):
|
|
598
|
+
"""The simulation of another process (``chromapi sim``), standing in for the motherboard.
|
|
599
|
+
|
|
600
|
+
The script keeps the whole SDK (control loop, moves, walk); the simulation only runs the physics and
|
|
601
|
+
the viewer, and goes on when the script stops or restarts.
|
|
602
|
+
"""
|
|
603
|
+
|
|
604
|
+
def __init__(self, address: Tuple[str, int] = SIM_ADDRESS) -> None:
|
|
605
|
+
"""Where ``chromapi sim`` listens; nothing is opened before :meth:`connect`."""
|
|
606
|
+
self._address = address
|
|
607
|
+
self._conn: Any = None # multiprocessing.connection.Connection once connected
|
|
608
|
+
self._lock = threading.Lock() # one call at a time: the control loop and the script's thread share it
|
|
609
|
+
|
|
610
|
+
def connect(self) -> bool:
|
|
611
|
+
"""Reach the simulation; False (logged) if ``chromapi sim`` is not running."""
|
|
612
|
+
from multiprocessing.connection import Client
|
|
613
|
+
|
|
614
|
+
try:
|
|
615
|
+
self._conn = Client(self._address, authkey=SIM_AUTHKEY)
|
|
616
|
+
except OSError:
|
|
617
|
+
logger.error("No simulation on %s:%d: start it first with 'chromapi sim'", *self._address)
|
|
618
|
+
return False
|
|
619
|
+
return True
|
|
620
|
+
|
|
621
|
+
def close(self) -> None:
|
|
622
|
+
"""Leave the simulation running."""
|
|
623
|
+
if self._conn is not None:
|
|
624
|
+
self._conn.close()
|
|
625
|
+
self._conn = None
|
|
626
|
+
|
|
627
|
+
def _call(self, name: str, *args: Any) -> Any:
|
|
628
|
+
"""Run ``name(*args)`` in the simulation; None once it is closed."""
|
|
629
|
+
with self._lock:
|
|
630
|
+
if self._conn is None:
|
|
631
|
+
return None
|
|
632
|
+
try:
|
|
633
|
+
self._conn.send((name, args))
|
|
634
|
+
result = self._conn.recv()
|
|
635
|
+
except (EOFError, OSError):
|
|
636
|
+
logger.warning("The simulation was closed")
|
|
637
|
+
self._conn = None
|
|
638
|
+
return None
|
|
639
|
+
if isinstance(result, Exception):
|
|
640
|
+
raise result
|
|
641
|
+
return result
|
|
642
|
+
|
|
643
|
+
def send_joint_targets(self, q: Dict[str, float]) -> bool:
|
|
644
|
+
"""Write the targets and step the simulation up to now."""
|
|
645
|
+
return bool(self._call("send_joint_targets", dict(q)))
|
|
646
|
+
|
|
647
|
+
def read_state(self) -> Optional[RobotState]:
|
|
648
|
+
"""The simulated joint/IMU/contact state."""
|
|
649
|
+
result: Optional[RobotState] = self._call("read_state")
|
|
650
|
+
return result
|
|
651
|
+
|
|
652
|
+
def set_torque_enabled(self, enabled: bool, joints: Optional[Sequence[str]] = None) -> None:
|
|
653
|
+
"""Forwarded (no-op in MuJoCo for now)."""
|
|
654
|
+
self._call("set_torque_enabled", enabled, None if joints is None else list(joints))
|
|
655
|
+
|
|
656
|
+
def set_led_all(self, r: int, g: int, b: int) -> None:
|
|
657
|
+
"""Recolor the simulated ring."""
|
|
658
|
+
self._call("set_led_all", r, g, b)
|
|
659
|
+
|
|
660
|
+
def set_led(self, index: int, r: int, g: int, b: int) -> None:
|
|
661
|
+
"""Forwarded (no-op in MuJoCo)."""
|
|
662
|
+
self._call("set_led", index, r, g, b)
|
|
663
|
+
|
|
664
|
+
def set_led_bulk(self, colors: Sequence[Tuple[int, int, int]]) -> None:
|
|
665
|
+
"""Recolor the simulated ring (its mean color)."""
|
|
666
|
+
self._call("set_led_bulk", [tuple(c) for c in colors])
|
|
667
|
+
|
|
668
|
+
def is_alive(self) -> bool:
|
|
669
|
+
"""False once the simulation was closed: the control loop then stops."""
|
|
670
|
+
return self._conn is not None
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
# ========================================================================================
|
|
674
|
+
# Move / behavior abstraction - the RL residual & scripted-motion extension point
|
|
675
|
+
# ========================================================================================
|
|
676
|
+
|
|
677
|
+
@dataclass
|
|
678
|
+
class MotorCommand:
|
|
679
|
+
"""The joint-target output of a :class:`Move`, built on top of a kinematic reference."""
|
|
680
|
+
|
|
681
|
+
target_angles: Dict[str, float] # [rad]
|
|
682
|
+
|
|
683
|
+
class Move(ABC):
|
|
684
|
+
"""A stateful behavior driving joint targets on every control-loop tick."""
|
|
685
|
+
|
|
686
|
+
@abstractmethod
|
|
687
|
+
def step(self, state: RobotState, command: MotorCommand, dt: float) -> None:
|
|
688
|
+
"""Update ``command.target_angles`` in place for this tick.
|
|
689
|
+
|
|
690
|
+
Args:
|
|
691
|
+
state: Latest proprioceptive snapshot.
|
|
692
|
+
command: Target joints to update - starts each tick pre-filled with the previous
|
|
693
|
+
tick's targets.
|
|
694
|
+
dt: Time since the previous tick [s].
|
|
695
|
+
|
|
696
|
+
"""
|
|
697
|
+
|
|
698
|
+
def on_start(self) -> None:
|
|
699
|
+
"""Run once when the move becomes active (:meth:`Chromapi.play_move`)."""
|
|
700
|
+
|
|
701
|
+
def on_stop(self) -> None:
|
|
702
|
+
"""Run once when the move is deactivated (:meth:`Chromapi.stop_move`)."""
|
|
703
|
+
|
|
704
|
+
# ========================================================================================
|
|
705
|
+
# Chromapi
|
|
706
|
+
# ========================================================================================
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def _deep_merge(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
|
|
710
|
+
"""Recursively merge two dicts, returning a new dict."""
|
|
711
|
+
merged = dict(base)
|
|
712
|
+
for key, value in override.items():
|
|
713
|
+
if isinstance(value, dict) and isinstance(merged.get(key), dict):
|
|
714
|
+
merged[key] = _deep_merge(merged[key], value)
|
|
715
|
+
else:
|
|
716
|
+
merged[key] = value
|
|
717
|
+
return merged
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
def _read_yaml(path: Path) -> Dict[str, Any]:
|
|
721
|
+
"""Read a YAML file and return its contents as a dict."""
|
|
722
|
+
return dict(yaml.safe_load(path.read_text()) or {}) if path.exists() else {}
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def load_config(
|
|
726
|
+
config_path: Union[str, Path] = DEFAULT_CONFIG_PATH,
|
|
727
|
+
calibration_path: Union[str, Path] = USER_CALIBRATION_PATH,
|
|
728
|
+
) -> Dict[str, Any]:
|
|
729
|
+
"""Return the package defaults (``config_path``) with this robot's calibration merged over them."""
|
|
730
|
+
with open(config_path) as f:
|
|
731
|
+
defaults = dict(yaml.safe_load(f))
|
|
732
|
+
return _deep_merge(defaults, _read_yaml(Path(calibration_path)))
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def save_calibration(
|
|
736
|
+
updates: Dict[str, Any], calibration_path: Union[str, Path] = USER_CALIBRATION_PATH
|
|
737
|
+
) -> Path:
|
|
738
|
+
"""Merge the given updates into the calibration file, creating it if necessary, and return the path."""
|
|
739
|
+
path = Path(calibration_path)
|
|
740
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
741
|
+
data = _deep_merge(_read_yaml(path), updates)
|
|
742
|
+
tmp = path.with_suffix(".tmp")
|
|
743
|
+
tmp.write_text(yaml.safe_dump(data, sort_keys=False))
|
|
744
|
+
os.replace(tmp, path)
|
|
745
|
+
return path
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _minimum_jerk(t01: float) -> float:
|
|
749
|
+
"""Minimum-jerk time-scaling s(t) in [0, 1] for a normalized time t01 in [0, 1] (zero vel/accel at ends)."""
|
|
750
|
+
t01 = float(np.clip(t01, 0.0, 1.0))
|
|
751
|
+
return 10.0 * t01**3 - 15.0 * t01**4 + 6.0 * t01**5
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
_YAW_PRESTAGE_THRESHOLD_RAD = 0.2 # [rad]
|
|
755
|
+
_SETTLE_MAX_S = 0.4 # [s] at most, for the servos to stop after a transition
|
|
756
|
+
_SETTLE_WINDOW_S = 0.05 # [s]
|
|
757
|
+
_SETTLE_MOTION_RAD = 0.005 # [rad] the joints moved less than this over the window: settled
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
class Chromapi:
|
|
761
|
+
"""High-level SDK for the Chromapi 12-DOF quadruped, real or simulated.
|
|
762
|
+
|
|
763
|
+
::
|
|
764
|
+
|
|
765
|
+
with Chromapi(backend="mujoco") as robot:
|
|
766
|
+
robot.wake_up()
|
|
767
|
+
robot.go_to_pose(body_rpy=(0.0, 0.1, 0.0)) # look down
|
|
768
|
+
state = robot.get_state()
|
|
769
|
+
robot.rest()
|
|
770
|
+
|
|
771
|
+
A background thread runs the control loop at ``config["control"]["loop_hz"]``: on every
|
|
772
|
+
tick it lets the active :class:`Move` (if any) update the joint targets, sends them to
|
|
773
|
+
the backend, and refreshes the latest :class:`RobotState`.
|
|
774
|
+
"""
|
|
775
|
+
|
|
776
|
+
def __init__(
|
|
777
|
+
self,
|
|
778
|
+
backend: str = "hardware",
|
|
779
|
+
config_path: Union[str, Path] = DEFAULT_CONFIG_PATH,
|
|
780
|
+
mjcf_path: Union[str, Path] = DEFAULT_MJCF_PATH,
|
|
781
|
+
port: str = "/dev/ttyAMA0",
|
|
782
|
+
baudrate: int = DEFAULT_BAUDRATE,
|
|
783
|
+
launch_viewer: bool = False,
|
|
784
|
+
key_callback: Optional[Callable[[int], None]] = None,
|
|
785
|
+
follow_robot: bool = False,
|
|
786
|
+
) -> None:
|
|
787
|
+
"""Build a Chromapi instance without connecting yet (see :meth:`connect`).
|
|
788
|
+
|
|
789
|
+
Args:
|
|
790
|
+
backend: ``"hardware"`` (real robot over UART), ``"mujoco"`` (simulation in this process) or
|
|
791
|
+
``"sim-server"`` (the simulation of ``chromapi sim``, running in another terminal).
|
|
792
|
+
config_path: Path to ``config.yaml`` (servo ID map, control-loop frequency, ...),
|
|
793
|
+
with :data:`USER_CALIBRATION_PATH` merged over it.
|
|
794
|
+
mjcf_path: MJCF scene to load for the ``"mujoco"`` backend.
|
|
795
|
+
port: Serial port for the ``"hardware"`` backend.
|
|
796
|
+
baudrate: Baud rate for the ``"hardware"`` backend (must match the firmware).
|
|
797
|
+
launch_viewer: For the ``"mujoco"`` backend, open an interactive viewer window.
|
|
798
|
+
key_callback: For the ``"mujoco"`` backend with ``launch_viewer=True``, a
|
|
799
|
+
keyboard callback forwarded to the viewer.
|
|
800
|
+
follow_robot: For the ``"mujoco"`` backend with ``launch_viewer=True``, the camera
|
|
801
|
+
tracks the robot.
|
|
802
|
+
|
|
803
|
+
"""
|
|
804
|
+
self.config = load_config(config_path)
|
|
805
|
+
control_cfg = self.config.get("control", {})
|
|
806
|
+
self.loop_hz: float = float(control_cfg.get("loop_hz", 100.0)) # [Hz]
|
|
807
|
+
self.wake_up_duration_s: float = float(control_cfg.get("wake_up_duration_s", 3.5)) # [s]
|
|
808
|
+
self.rest_duration_s: float = float(control_cfg.get("rest_duration_s", 2.0)) # [s]
|
|
809
|
+
self.approach_duration_s: float = float(control_cfg.get("approach_duration_s", 2.0)) # [s]
|
|
810
|
+
audio_cfg = self.config.get("audio", {})
|
|
811
|
+
self.sound_volume: float = float(audio_cfg.get("volume", 0.25))
|
|
812
|
+
self._speaker_hint: str = str(audio_cfg.get("speaker", "")) if backend == "hardware" else ""
|
|
813
|
+
self.kinematics = K.Kromatics(
|
|
814
|
+
DEFAULT_URDF_PATH, dt=1.0 / self.loop_hz, initial_pose=dict(K.ZERO_POSE)
|
|
815
|
+
)
|
|
816
|
+
self._query_kinematics: Optional[K.Kromatics] = None # its own solver: the walk uses self.kinematics
|
|
817
|
+
self._query_lock = threading.Lock()
|
|
818
|
+
|
|
819
|
+
if backend == "hardware":
|
|
820
|
+
imu_cfg = self.config.get("imu", {})
|
|
821
|
+
self.backend: RobotBackend = HardwareBackend(
|
|
822
|
+
self.config["servos"],
|
|
823
|
+
port=port,
|
|
824
|
+
baudrate=baudrate,
|
|
825
|
+
imu_mount=ImuMount(tuple(imu_cfg.get("mount_offset_wxyz", IDENTITY_QUAT))),
|
|
826
|
+
)
|
|
827
|
+
elif backend == "mujoco":
|
|
828
|
+
self.backend = MuJoCoBackend(
|
|
829
|
+
mjcf_path,
|
|
830
|
+
launch_viewer=launch_viewer,
|
|
831
|
+
key_callback=key_callback,
|
|
832
|
+
follow_robot=follow_robot,
|
|
833
|
+
)
|
|
834
|
+
elif backend == "sim-server":
|
|
835
|
+
self.backend = SimClientBackend()
|
|
836
|
+
else:
|
|
837
|
+
raise ValueError(f"Unknown backend {backend!r}, expected 'hardware', 'mujoco' or 'sim-server'")
|
|
838
|
+
|
|
839
|
+
self.battery = Battery(self.config["battery"])
|
|
840
|
+
self._battery_level: Optional[str] = None
|
|
841
|
+
self._connected = False
|
|
842
|
+
self._state_lock = threading.Lock()
|
|
843
|
+
self._latest_state: Optional[RobotState] = None
|
|
844
|
+
self._targets_lock = threading.Lock()
|
|
845
|
+
self._current_targets: Dict[str, float] = dict(K.ZERO_POSE) # [rad]
|
|
846
|
+
self._active_move: Optional[Move] = None
|
|
847
|
+
self._walk_move: Optional["WalkMove"] = None
|
|
848
|
+
self._stop_event = threading.Event()
|
|
849
|
+
self._loop_thread: Optional[threading.Thread] = None
|
|
850
|
+
|
|
851
|
+
def connect(self) -> bool:
|
|
852
|
+
"""Open the backend connection and start the background control loop."""
|
|
853
|
+
if self._connected:
|
|
854
|
+
return True
|
|
855
|
+
if not self.backend.connect():
|
|
856
|
+
return False
|
|
857
|
+
|
|
858
|
+
state = self.backend.read_state()
|
|
859
|
+
with self._targets_lock:
|
|
860
|
+
if state is not None and state.joint_positions:
|
|
861
|
+
self._current_targets.update(state.joint_positions)
|
|
862
|
+
else:
|
|
863
|
+
logger.warning(
|
|
864
|
+
"Could not read initial joint state - holding the built-in ZERO_POSE "
|
|
865
|
+
"(legs splayed) until the first command; call wake_up() promptly."
|
|
866
|
+
)
|
|
867
|
+
|
|
868
|
+
for module in ("sounddevice", "chromapi.media.audio", "chromapi.locomotion.gait"):
|
|
869
|
+
try:
|
|
870
|
+
__import__(module)
|
|
871
|
+
except (ImportError, OSError):
|
|
872
|
+
pass
|
|
873
|
+
|
|
874
|
+
self._connected = True
|
|
875
|
+
self._stop_event.clear()
|
|
876
|
+
sys.setswitchinterval(GIL_SWITCH_INTERVAL_S)
|
|
877
|
+
self._loop_thread = threading.Thread(
|
|
878
|
+
target=self._control_loop, name="chromapi-control-loop", daemon=True
|
|
879
|
+
)
|
|
880
|
+
self._loop_thread.start()
|
|
881
|
+
return True
|
|
882
|
+
|
|
883
|
+
def disconnect(self, disable_torque: bool = False) -> None:
|
|
884
|
+
"""Stop the control loop and close the backend connection.
|
|
885
|
+
|
|
886
|
+
Args:
|
|
887
|
+
disable_torque: If True, disable motor torque after the control loop thread has actually stopped.
|
|
888
|
+
|
|
889
|
+
"""
|
|
890
|
+
if not self._connected:
|
|
891
|
+
return
|
|
892
|
+
self._stop_event.set()
|
|
893
|
+
if self._loop_thread is not None:
|
|
894
|
+
self._loop_thread.join(timeout=2.0)
|
|
895
|
+
if self._loop_thread.is_alive():
|
|
896
|
+
logger.warning(
|
|
897
|
+
"Control loop did not stop within 2s - leaving the backend connection "
|
|
898
|
+
"open rather than risk closing it out from under the still-running loop thread."
|
|
899
|
+
)
|
|
900
|
+
return
|
|
901
|
+
if disable_torque:
|
|
902
|
+
self.backend.set_torque_enabled(False)
|
|
903
|
+
self.backend.close()
|
|
904
|
+
self._connected = False
|
|
905
|
+
|
|
906
|
+
def __enter__(self) -> "Chromapi":
|
|
907
|
+
"""Connect on entering a ``with`` block."""
|
|
908
|
+
self.connect()
|
|
909
|
+
return self
|
|
910
|
+
|
|
911
|
+
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
|
912
|
+
"""Disconnect on exiting a ``with`` block - lying down first if it ends on Ctrl-C or an error."""
|
|
913
|
+
if exc_type is not None and self._connected and self.backend.is_alive():
|
|
914
|
+
try:
|
|
915
|
+
self.stop_walk()
|
|
916
|
+
self._wait_until_stopped(timeout_s=1.0)
|
|
917
|
+
self.set_led_all(0, 0, 0)
|
|
918
|
+
self.rest()
|
|
919
|
+
except BaseException: # a second Ctrl-C: give up lying down, still disconnect
|
|
920
|
+
logger.warning("Interrupted while lying down - disconnecting where it stands")
|
|
921
|
+
self.disconnect()
|
|
922
|
+
|
|
923
|
+
def __del__(self) -> None:
|
|
924
|
+
"""Best-effort cleanup if :meth:`disconnect` was not called explicitly."""
|
|
925
|
+
try:
|
|
926
|
+
self.disconnect()
|
|
927
|
+
except Exception:
|
|
928
|
+
pass
|
|
929
|
+
|
|
930
|
+
def _control_loop(self) -> None:
|
|
931
|
+
if isinstance(self.backend, HardwareBackend):
|
|
932
|
+
# Real-time priority, allowed for the service only
|
|
933
|
+
try:
|
|
934
|
+
os.sched_setscheduler(0, os.SCHED_FIFO, os.sched_param(CONTROL_LOOP_RT_PRIORITY))
|
|
935
|
+
logger.info("Control loop: real-time priority %d", CONTROL_LOOP_RT_PRIORITY)
|
|
936
|
+
except (OSError, AttributeError):
|
|
937
|
+
pass
|
|
938
|
+
period = 1.0 / self.loop_hz # [s]
|
|
939
|
+
last_tick = time.monotonic() # [s]
|
|
940
|
+
next_deadline = last_tick + period # [s]
|
|
941
|
+
while not self._stop_event.is_set():
|
|
942
|
+
if not self.backend.is_alive():
|
|
943
|
+
logger.info("Viewer window closed - stopping, as with Ctrl-C")
|
|
944
|
+
os.kill(os.getpid(), signal.SIGINT) # unlike interrupt_main(), also ends a sleep()
|
|
945
|
+
return
|
|
946
|
+
tick_start = time.monotonic()
|
|
947
|
+
dt = tick_start - last_tick # [s]
|
|
948
|
+
last_tick = tick_start
|
|
949
|
+
|
|
950
|
+
state = self.backend.read_state()
|
|
951
|
+
if state is not None:
|
|
952
|
+
self.battery.update(state.voltage_v, state.current_a, state.timestamp)
|
|
953
|
+
state.battery_percent = self.battery.percent
|
|
954
|
+
with self._state_lock:
|
|
955
|
+
self._latest_state = state
|
|
956
|
+
self._check_battery()
|
|
957
|
+
|
|
958
|
+
with self._targets_lock:
|
|
959
|
+
if self._active_move is not None and state is not None:
|
|
960
|
+
command = MotorCommand(target_angles=dict(self._current_targets))
|
|
961
|
+
try:
|
|
962
|
+
self._active_move.step(state, command, dt)
|
|
963
|
+
except Exception:
|
|
964
|
+
logger.exception("Move.step() raised - holding last targets")
|
|
965
|
+
else:
|
|
966
|
+
self._current_targets = command.target_angles
|
|
967
|
+
targets = dict(self._current_targets)
|
|
968
|
+
|
|
969
|
+
self.backend.send_joint_targets(targets)
|
|
970
|
+
|
|
971
|
+
elapsed = time.monotonic() - tick_start # [s]
|
|
972
|
+
# In simulation the viewer's sync() alone often takes 20 ms; the physics catches up.
|
|
973
|
+
if elapsed > 2 * period and isinstance(self.backend, HardwareBackend):
|
|
974
|
+
logger.warning(
|
|
975
|
+
"Control loop overrun: tick took %.1f ms (target period %.1f ms)",
|
|
976
|
+
elapsed * 1000,
|
|
977
|
+
period * 1000,
|
|
978
|
+
)
|
|
979
|
+
|
|
980
|
+
now = time.monotonic() # [s]
|
|
981
|
+
sleep_for = next_deadline - now # [s]
|
|
982
|
+
if sleep_for > 0:
|
|
983
|
+
time.sleep(sleep_for)
|
|
984
|
+
elif sleep_for < -period:
|
|
985
|
+
next_deadline = now
|
|
986
|
+
next_deadline += period
|
|
987
|
+
|
|
988
|
+
def _check_battery(self) -> None:
|
|
989
|
+
"""Log each drop to a lower battery level; at 0 %, lie down (control loop thread, so no waiting here)."""
|
|
990
|
+
order = (None, OK, LOW, CRITICAL, EMPTY)
|
|
991
|
+
level = self.battery.level
|
|
992
|
+
if order.index(level) <= order.index(self._battery_level): # never back up: no flicker at a threshold
|
|
993
|
+
return
|
|
994
|
+
self._battery_level = level
|
|
995
|
+
if level == EMPTY:
|
|
996
|
+
logger.error("Battery empty (%.2f V without load) - lying down; need to charge", self.battery.ocv_v)
|
|
997
|
+
with self._targets_lock:
|
|
998
|
+
start = dict(self._current_targets)
|
|
999
|
+
self.play_move(_InterpolationMove(start, self.rest_pose(), self.rest_duration_s))
|
|
1000
|
+
elif level is not None:
|
|
1001
|
+
logger.info("Battery %s: %.0f %%", level, self.battery.percent)
|
|
1002
|
+
|
|
1003
|
+
# -- state --------------------------------------------------------------------------
|
|
1004
|
+
|
|
1005
|
+
def get_state(self) -> Optional[RobotState]:
|
|
1006
|
+
"""Return the latest :class:`RobotState` snapshot (updated at ``loop_hz``)."""
|
|
1007
|
+
with self._state_lock:
|
|
1008
|
+
return self._latest_state
|
|
1009
|
+
|
|
1010
|
+
def get_current_joint_positions(self) -> Dict[str, float]:
|
|
1011
|
+
"""Return the last commanded joint targets (not the measured state)."""
|
|
1012
|
+
with self._targets_lock:
|
|
1013
|
+
return dict(self._current_targets)
|
|
1014
|
+
|
|
1015
|
+
def get_joint_positions(self) -> Dict[str, float]:
|
|
1016
|
+
"""Return the measured joint angles [rad]; the commanded ones until the first reading."""
|
|
1017
|
+
state = self.get_state()
|
|
1018
|
+
if state is not None and state.joint_positions:
|
|
1019
|
+
return dict(state.joint_positions)
|
|
1020
|
+
return self.get_current_joint_positions()
|
|
1021
|
+
|
|
1022
|
+
@property
|
|
1023
|
+
def is_connected(self) -> bool:
|
|
1024
|
+
"""The control loop runs."""
|
|
1025
|
+
return self._connected
|
|
1026
|
+
|
|
1027
|
+
@property
|
|
1028
|
+
def active_move(self) -> Optional[Move]:
|
|
1029
|
+
"""The :class:`Move` driving the joints, None if they hold."""
|
|
1030
|
+
return self._active_move
|
|
1031
|
+
|
|
1032
|
+
@property
|
|
1033
|
+
def walk_move(self) -> Optional["WalkMove"]:
|
|
1034
|
+
"""The last :class:`~chromapi.locomotion.gait.WalkMove` from :meth:`walk`, active or not."""
|
|
1035
|
+
return self._walk_move
|
|
1036
|
+
|
|
1037
|
+
@property
|
|
1038
|
+
def is_walking(self) -> bool:
|
|
1039
|
+
"""A walk is under way (not yet settled on the neutral stance)."""
|
|
1040
|
+
move = self._walk_move
|
|
1041
|
+
return move is not None and self._active_move is move and not move.settled
|
|
1042
|
+
|
|
1043
|
+
@property
|
|
1044
|
+
def is_moving(self) -> bool:
|
|
1045
|
+
"""A transition, a walk or another move with a ``done`` flag is under way."""
|
|
1046
|
+
return self.is_walking or getattr(self._active_move, "done", True) is False
|
|
1047
|
+
|
|
1048
|
+
def _wait_while_moving(self, timeout_s: float) -> None:
|
|
1049
|
+
deadline = time.monotonic() + timeout_s # [s]
|
|
1050
|
+
while self.is_moving and time.monotonic() < deadline:
|
|
1051
|
+
time.sleep(0.01)
|
|
1052
|
+
|
|
1053
|
+
def _wait_until_settled(self) -> None:
|
|
1054
|
+
"""Wait (up to :data:`_SETTLE_MAX_S`) for the measured joints to stop moving."""
|
|
1055
|
+
deadline = time.monotonic() + _SETTLE_MAX_S # [s]
|
|
1056
|
+
before = self.get_joint_positions()
|
|
1057
|
+
while time.monotonic() < deadline:
|
|
1058
|
+
time.sleep(_SETTLE_WINDOW_S)
|
|
1059
|
+
now = self.get_joint_positions()
|
|
1060
|
+
if max(abs(now[j] - before[j]) for j in now) < _SETTLE_MOTION_RAD:
|
|
1061
|
+
return
|
|
1062
|
+
before = now
|
|
1063
|
+
|
|
1064
|
+
def get_imu_orientation(self) -> Tuple[float, float, float, float]:
|
|
1065
|
+
"""Return the trunk orientation quaternion (w, x, y, z), or identity if no state yet."""
|
|
1066
|
+
state = self.get_state()
|
|
1067
|
+
return state.imu_quat_wxyz if state is not None else (1.0, 0.0, 0.0, 0.0)
|
|
1068
|
+
|
|
1069
|
+
# -- kinematics -----------------------------------------------------------------------
|
|
1070
|
+
|
|
1071
|
+
def _query_solver(self) -> K.Kromatics:
|
|
1072
|
+
if self._query_kinematics is None:
|
|
1073
|
+
self._query_kinematics = K.Kromatics(DEFAULT_URDF_PATH, dt=1.0 / self.loop_hz)
|
|
1074
|
+
return self._query_kinematics
|
|
1075
|
+
|
|
1076
|
+
def forward_kinematics(self, q: Optional[Dict[str, float]] = None) -> Dict[str, npt.NDArray[np.float64]]:
|
|
1077
|
+
"""Foot positions (x, y, z) [m] in the chassis frame, for ``q`` [rad] or the measured joints by default."""
|
|
1078
|
+
if q is None:
|
|
1079
|
+
q = self.get_joint_positions()
|
|
1080
|
+
with self._query_lock:
|
|
1081
|
+
return self._query_solver().forward_kinematics(q)
|
|
1082
|
+
|
|
1083
|
+
def inverse_kinematics(self, feet: Dict[str, Sequence[float]]) -> Dict[str, float]:
|
|
1084
|
+
"""Joint angles [rad] placing each foot of ``feet`` (leg -> (x, y, z) [m], chassis frame); the others stay.
|
|
1085
|
+
|
|
1086
|
+
Moves nothing: pass the result to :meth:`set_joint_targets`. Raises ValueError if a foot is out of reach.
|
|
1087
|
+
"""
|
|
1088
|
+
q0 = self.get_current_joint_positions()
|
|
1089
|
+
targets = {leg: np.asarray(xyz, dtype=float) for leg, xyz in feet.items()}
|
|
1090
|
+
with self._query_lock:
|
|
1091
|
+
solver = self._query_solver()
|
|
1092
|
+
q, _ = solver.inverse_kinematics({**solver.forward_kinematics(q0), **targets}, q_init=q0,
|
|
1093
|
+
iterations=IK_QUERY_ITERATIONS)
|
|
1094
|
+
q = {joint: q[joint] if joint[:2] in targets else angle for joint, angle in q0.items()}
|
|
1095
|
+
reached = solver.forward_kinematics(q)
|
|
1096
|
+
error_m = max(float(np.linalg.norm(reached[leg] - target)) for leg, target in targets.items())
|
|
1097
|
+
if error_m > IK_TOLERANCE_M:
|
|
1098
|
+
raise ValueError(f"foot target out of reach ({error_m * 1000:.1f} mm off)")
|
|
1099
|
+
return q
|
|
1100
|
+
|
|
1101
|
+
# -- direct joint control ------------------------------------------------------------
|
|
1102
|
+
|
|
1103
|
+
def set_joint_targets(
|
|
1104
|
+
self, q: Union[Dict[str, float], Sequence[float]], duration: float = 0.0, wait: bool = False
|
|
1105
|
+
) -> None:
|
|
1106
|
+
"""Command joint targets directly, optionally with a minimum-jerk transition.
|
|
1107
|
+
|
|
1108
|
+
Args:
|
|
1109
|
+
q: Target joint angles [rad], as a joint dict or a length-12 array in
|
|
1110
|
+
``kromatics.JOINT_NAMES`` order. Joints not present in a dict keep their
|
|
1111
|
+
current target.
|
|
1112
|
+
duration: If > 0, interpolate from the current targets over this duration [s]. If 0,
|
|
1113
|
+
jump immediately (only safe for small corrections).
|
|
1114
|
+
wait: Return once the transition is over.
|
|
1115
|
+
|
|
1116
|
+
"""
|
|
1117
|
+
target_dict = K.Kromatics.to_dict(q) if not isinstance(q, dict) else dict(q)
|
|
1118
|
+
if duration <= 0.0:
|
|
1119
|
+
with self._targets_lock:
|
|
1120
|
+
self._current_targets.update(target_dict)
|
|
1121
|
+
self._active_move = None
|
|
1122
|
+
return
|
|
1123
|
+
|
|
1124
|
+
with self._targets_lock:
|
|
1125
|
+
start = dict(self._current_targets)
|
|
1126
|
+
self.play_move(_InterpolationMove(start, target_dict, duration))
|
|
1127
|
+
if wait:
|
|
1128
|
+
self._wait_while_moving(duration + WAIT_MARGIN_S)
|
|
1129
|
+
|
|
1130
|
+
# -- high-level poses -----------------------------------------------------------------
|
|
1131
|
+
|
|
1132
|
+
def stand_pose(self) -> Dict[str, float]:
|
|
1133
|
+
"""Return the nominal standing joint configuration (``kromatics.WAKE_UP_POSE``)."""
|
|
1134
|
+
return dict(K.WAKE_UP_POSE)
|
|
1135
|
+
|
|
1136
|
+
def approach_pose(self) -> Dict[str, float]:
|
|
1137
|
+
"""Return the compact "legs pulled in" pose (``kromatics.APPROACH_POSE``)."""
|
|
1138
|
+
return dict(K.APPROACH_POSE)
|
|
1139
|
+
|
|
1140
|
+
def rest_pose(self) -> Dict[str, float]:
|
|
1141
|
+
"""Return the compact resting joint configuration (``kromatics.REST_POSE``)."""
|
|
1142
|
+
return dict(K.REST_POSE)
|
|
1143
|
+
|
|
1144
|
+
def approach(self, duration: Optional[float] = None, wait: bool = False) -> None:
|
|
1145
|
+
"""Smoothly pull the legs in to :meth:`approach_pose`, from whatever configuration."""
|
|
1146
|
+
self.set_joint_targets(self.approach_pose(), duration=duration or self.approach_duration_s, wait=wait)
|
|
1147
|
+
|
|
1148
|
+
def wake_up(self, duration: Optional[float] = None, wait: bool = False) -> None:
|
|
1149
|
+
"""Smoothly stand up from whatever configuration the robot is currently in.
|
|
1150
|
+
|
|
1151
|
+
Args:
|
|
1152
|
+
duration: Transition time [s] (default: ``config["control"]["wake_up_duration_s"]``).
|
|
1153
|
+
wait: Return once standing.
|
|
1154
|
+
|
|
1155
|
+
"""
|
|
1156
|
+
self.enable_motors()
|
|
1157
|
+
total_duration = duration or self.wake_up_duration_s # [s]
|
|
1158
|
+
target = self.stand_pose()
|
|
1159
|
+
current = self.get_current_joint_positions()
|
|
1160
|
+
|
|
1161
|
+
yaw_joints = [K.joint_name(leg, 1) for leg in K.LEG_NAMES]
|
|
1162
|
+
max_yaw_delta = max( # [rad]
|
|
1163
|
+
abs(target[joint] - current.get(joint, 0.0)) for joint in yaw_joints
|
|
1164
|
+
)
|
|
1165
|
+
if max_yaw_delta <= _YAW_PRESTAGE_THRESHOLD_RAD:
|
|
1166
|
+
self.set_joint_targets(target, duration=total_duration, wait=wait)
|
|
1167
|
+
return
|
|
1168
|
+
|
|
1169
|
+
yaw_prestage = dict(current)
|
|
1170
|
+
for joint in yaw_joints:
|
|
1171
|
+
yaw_prestage[joint] = target[joint]
|
|
1172
|
+
prestage_duration = total_duration * 0.6 # [s]
|
|
1173
|
+
rise_duration = total_duration * 0.4 # [s]
|
|
1174
|
+
self.set_joint_targets(yaw_prestage, duration=prestage_duration, wait=True)
|
|
1175
|
+
self._wait_until_settled()
|
|
1176
|
+
self.set_joint_targets(target, duration=rise_duration, wait=wait)
|
|
1177
|
+
|
|
1178
|
+
def rest(self, duration: Optional[float] = None, disable_torque: bool = True, wait: bool = False) -> None:
|
|
1179
|
+
"""Smoothly crouch down to :meth:`rest_pose` and optionally release motor torque.
|
|
1180
|
+
|
|
1181
|
+
Args:
|
|
1182
|
+
duration: Transition time [s] (default: ``config["control"]["rest_duration_s"]``).
|
|
1183
|
+
disable_torque: If True (default), disable torque once crouch is reached (this waits too).
|
|
1184
|
+
wait: Return once lying down.
|
|
1185
|
+
|
|
1186
|
+
"""
|
|
1187
|
+
self.set_joint_targets(self.rest_pose(), duration=duration or self.rest_duration_s,
|
|
1188
|
+
wait=wait or disable_torque)
|
|
1189
|
+
if disable_torque:
|
|
1190
|
+
self._wait_until_settled()
|
|
1191
|
+
self.disable_motors()
|
|
1192
|
+
|
|
1193
|
+
def go_to_pose(
|
|
1194
|
+
self,
|
|
1195
|
+
body_xyz: Sequence[float] = (0.0, 0.0, 0.0),
|
|
1196
|
+
body_rpy: Sequence[float] = (0.0, 0.0, 0.0),
|
|
1197
|
+
duration: float = 1.0,
|
|
1198
|
+
reference_height: Optional[float] = None,
|
|
1199
|
+
x_reach: Optional[float] = None,
|
|
1200
|
+
y_reach: Optional[float] = None,
|
|
1201
|
+
wait: bool = False,
|
|
1202
|
+
) -> bool:
|
|
1203
|
+
"""Tilt the trunk while standing, feet planted (quasi-static body posing).
|
|
1204
|
+
|
|
1205
|
+
Args:
|
|
1206
|
+
body_xyz: Translation of the chassis relative to the nominal stand pose
|
|
1207
|
+
(world/ground frame) [m].
|
|
1208
|
+
body_rpy: Orientation of the chassis relative to level [rad].
|
|
1209
|
+
duration: Transition time [s].
|
|
1210
|
+
reference_height: Stance height for the default footprint [m].
|
|
1211
|
+
x_reach: Footprint half-width along chassis X for the same default footprint [m].
|
|
1212
|
+
y_reach: Footprint half-width along chassis Y for the same default footprint [m].
|
|
1213
|
+
wait: Return once the pose is reached.
|
|
1214
|
+
|
|
1215
|
+
Returns:
|
|
1216
|
+
True if the target pose was reachable by all 4 legs (the transition is still
|
|
1217
|
+
started either way, converging to the closest reachable configuration).
|
|
1218
|
+
|
|
1219
|
+
"""
|
|
1220
|
+
height = ( # [m]
|
|
1221
|
+
reference_height
|
|
1222
|
+
if reference_height is not None
|
|
1223
|
+
else K.Kromatics._STAND_REACH[2]
|
|
1224
|
+
)
|
|
1225
|
+
x_reach_m = x_reach if x_reach is not None else K.Kromatics._STAND_REACH[0] # [m]
|
|
1226
|
+
y_reach_m = y_reach if y_reach is not None else K.Kromatics._STAND_REACH[1] # [m]
|
|
1227
|
+
footprint = self.kinematics.stance_targets(height, x_reach_m, y_reach_m)
|
|
1228
|
+
q_target, converged = self.kinematics.body_ik(
|
|
1229
|
+
np.asarray(body_xyz),
|
|
1230
|
+
np.asarray(body_rpy),
|
|
1231
|
+
foot_targets_world=footprint,
|
|
1232
|
+
reference_height=height,
|
|
1233
|
+
)
|
|
1234
|
+
if not converged:
|
|
1235
|
+
logger.warning("go_to_pose target is outside the reachable envelope for some leg")
|
|
1236
|
+
self.set_joint_targets(q_target, duration=duration, wait=wait)
|
|
1237
|
+
return converged
|
|
1238
|
+
|
|
1239
|
+
# -- walking --------------------------------------------------------------------------
|
|
1240
|
+
|
|
1241
|
+
def walk(
|
|
1242
|
+
self,
|
|
1243
|
+
vx: float = 0.0,
|
|
1244
|
+
vy: float = 0.0,
|
|
1245
|
+
wz: float = 0.0,
|
|
1246
|
+
pattern: str = "trot",
|
|
1247
|
+
params: Optional["GaitParams"] = None,
|
|
1248
|
+
) -> "WalkMove":
|
|
1249
|
+
"""Start (or update) open-loop walking at the given body-frame velocity.
|
|
1250
|
+
|
|
1251
|
+
Args:
|
|
1252
|
+
vx: Commanded forward velocity (positive = forward) [m.s⁻¹].
|
|
1253
|
+
vy: Commanded lateral velocity (positive = left) [m.s⁻¹].
|
|
1254
|
+
wz: Commanded yaw rate (positive = turn left) [rad.s⁻¹].
|
|
1255
|
+
pattern: ``"trot"`` (default, faster, dynamic) or ``"crawl"`` (statically stable).
|
|
1256
|
+
params: Explicit :class:`~chromapi.locomotion.gait.GaitParams`, overriding
|
|
1257
|
+
``pattern``.
|
|
1258
|
+
|
|
1259
|
+
Returns:
|
|
1260
|
+
The active :class:`~chromapi.locomotion.gait.WalkMove`
|
|
1261
|
+
|
|
1262
|
+
Raises:
|
|
1263
|
+
RuntimeError: Starting to walk with the battery under ``critical_percent``. An ongoing walk
|
|
1264
|
+
still takes new velocities, until the battery is empty and Chromapi lies down.
|
|
1265
|
+
|
|
1266
|
+
"""
|
|
1267
|
+
percent = self.battery.percent
|
|
1268
|
+
starting = self._walk_move is None or self._active_move is not self._walk_move
|
|
1269
|
+
if starting and percent is not None and percent < self.battery.critical_percent:
|
|
1270
|
+
raise RuntimeError(f"Battery at {percent:.0f} %: too low to walk, need to charge")
|
|
1271
|
+
|
|
1272
|
+
from chromapi.locomotion.gait import GaitParams as _GaitParams
|
|
1273
|
+
from chromapi.locomotion.gait import WalkMove as _WalkMove
|
|
1274
|
+
|
|
1275
|
+
if params is not None:
|
|
1276
|
+
resolved_params = params
|
|
1277
|
+
elif pattern == "trot":
|
|
1278
|
+
resolved_params = _GaitParams.trot()
|
|
1279
|
+
elif pattern == "crawl":
|
|
1280
|
+
resolved_params = _GaitParams.crawl()
|
|
1281
|
+
else:
|
|
1282
|
+
resolved_params = _GaitParams(pattern=pattern)
|
|
1283
|
+
|
|
1284
|
+
current = self._walk_move
|
|
1285
|
+
if current is None or replace(resolved_params, body_height=current.gait.params.body_height) != current.gait.params:
|
|
1286
|
+
current = _WalkMove(self.kinematics, resolved_params)
|
|
1287
|
+
self._walk_move = current
|
|
1288
|
+
current.set_velocity(vx, vy, wz) # chassis frame: +X forward, +Y left
|
|
1289
|
+
if self._active_move is not current:
|
|
1290
|
+
self.play_move(current)
|
|
1291
|
+
return current
|
|
1292
|
+
|
|
1293
|
+
def stop_walk(self, wait: bool = False) -> None:
|
|
1294
|
+
"""Ramp the walking velocity to zero, settling the feet at the neutral stance footprint.
|
|
1295
|
+
|
|
1296
|
+
Args:
|
|
1297
|
+
wait: Return once the feet are settled (up to :data:`STOP_WAIT_S`).
|
|
1298
|
+
|
|
1299
|
+
"""
|
|
1300
|
+
if self._walk_move is not None:
|
|
1301
|
+
self._walk_move.set_velocity(0.0, 0.0, 0.0)
|
|
1302
|
+
if wait:
|
|
1303
|
+
self._wait_while_moving(STOP_WAIT_S)
|
|
1304
|
+
|
|
1305
|
+
def _wait_until_stopped(self, timeout_s: float = 3.0) -> None:
|
|
1306
|
+
"""Block until the walking velocity has ramped down to zero (after :meth:`stop_walk`)."""
|
|
1307
|
+
deadline = time.monotonic() + timeout_s # [s]
|
|
1308
|
+
while self._walk_move is not None and self._walk_move.gait.twist.any() and time.monotonic() < deadline:
|
|
1309
|
+
time.sleep(0.01)
|
|
1310
|
+
|
|
1311
|
+
def walk_distance(
|
|
1312
|
+
self,
|
|
1313
|
+
distance_m: float,
|
|
1314
|
+
speed: float = 0.08,
|
|
1315
|
+
lateral: bool = False,
|
|
1316
|
+
**walk_kwargs: Any,
|
|
1317
|
+
) -> None:
|
|
1318
|
+
"""Walk forward (or sideways) approximately ``distance_m``, then stop (returns once stopped).
|
|
1319
|
+
|
|
1320
|
+
Args:
|
|
1321
|
+
distance_m: Signed distance to walk [m]. Positive = forward (or left, with
|
|
1322
|
+
``lateral=True``).
|
|
1323
|
+
speed: Commanded walking speed (magnitude only) [m.s⁻¹].
|
|
1324
|
+
lateral: If True, move sideways (left/right) instead of forward/backward.
|
|
1325
|
+
**walk_kwargs: Forwarded to :meth:`walk` (``pattern``, ``params``).
|
|
1326
|
+
|
|
1327
|
+
"""
|
|
1328
|
+
if speed <= 0.0:
|
|
1329
|
+
raise ValueError(f"speed must be positive, got {speed}")
|
|
1330
|
+
direction = 1.0 if distance_m >= 0.0 else -1.0
|
|
1331
|
+
if lateral:
|
|
1332
|
+
self.walk(vx=0.0, vy=direction * speed, wz=0.0, **walk_kwargs)
|
|
1333
|
+
else:
|
|
1334
|
+
self.walk(vx=direction * speed, vy=0.0, wz=0.0, **walk_kwargs)
|
|
1335
|
+
time.sleep(abs(distance_m) / speed)
|
|
1336
|
+
self.stop_walk()
|
|
1337
|
+
self._wait_until_stopped()
|
|
1338
|
+
|
|
1339
|
+
def turn(
|
|
1340
|
+
self,
|
|
1341
|
+
degrees: float,
|
|
1342
|
+
angular_speed_deg_s: float = 30.0,
|
|
1343
|
+
**walk_kwargs: Any,
|
|
1344
|
+
) -> None:
|
|
1345
|
+
"""Turn in place by ``degrees``, measured on the IMU yaw, then stop (returns once stopped).
|
|
1346
|
+
|
|
1347
|
+
The open-loop gait slips, so the turn is stopped on the measured yaw rather than after
|
|
1348
|
+
the theoretical time - early enough for the yaw-rate ramp-down to finish the angle. Falls
|
|
1349
|
+
back to three times that theoretical time (plus the speed ramp) if the IMU yaw never gets there.
|
|
1350
|
+
|
|
1351
|
+
Args:
|
|
1352
|
+
degrees: Signed angle to turn [deg]. Positive = left.
|
|
1353
|
+
angular_speed_deg_s: Commanded turning speed (magnitude only) [deg.s⁻¹].
|
|
1354
|
+
**walk_kwargs: Forwarded to :meth:`walk` (``pattern``, ``params``).
|
|
1355
|
+
|
|
1356
|
+
"""
|
|
1357
|
+
if angular_speed_deg_s <= 0.0:
|
|
1358
|
+
raise ValueError(f"angular_speed_deg_s must be positive, got {angular_speed_deg_s}")
|
|
1359
|
+
direction = 1.0 if degrees >= 0.0 else -1.0
|
|
1360
|
+
target_rad = abs(np.radians(degrees)) # [rad]
|
|
1361
|
+
angular_speed_rad_s = np.radians(angular_speed_deg_s) # [rad.s⁻¹]
|
|
1362
|
+
move = self.walk(vx=0.0, vy=0.0, wz=direction * angular_speed_rad_s, **walk_kwargs)
|
|
1363
|
+
max_yaw_accel = move.gait.params.max_angular_acceleration_rad_s2 # [rad.s⁻²]
|
|
1364
|
+
ramp_s = angular_speed_rad_s / max_yaw_accel # [s] to reach the speed - longer than a small turn itself
|
|
1365
|
+
deadline = time.monotonic() + 3.0 * (target_rad / angular_speed_rad_s + ramp_s) # [s]
|
|
1366
|
+
previous_yaw = self.get_imu_yaw() # [rad]
|
|
1367
|
+
turned = 0.0 # [rad]
|
|
1368
|
+
while abs(turned) < target_rad - move.gait.twist[2] ** 2 / (2.0 * max_yaw_accel):
|
|
1369
|
+
if time.monotonic() > deadline:
|
|
1370
|
+
logger.warning("turn: IMU yaw at %.0f of %.0f deg - stopping on time", np.degrees(abs(turned)), abs(degrees))
|
|
1371
|
+
break
|
|
1372
|
+
time.sleep(0.01)
|
|
1373
|
+
yaw = self.get_imu_yaw()
|
|
1374
|
+
turned += (yaw - previous_yaw + np.pi) % (2.0 * np.pi) - np.pi
|
|
1375
|
+
previous_yaw = yaw
|
|
1376
|
+
self.stop_walk()
|
|
1377
|
+
self._wait_until_stopped()
|
|
1378
|
+
|
|
1379
|
+
def get_imu_yaw(self) -> float:
|
|
1380
|
+
"""Return the trunk heading from the IMU [rad], positive = left (drifts slowly over minutes)."""
|
|
1381
|
+
w, x, y, z = self.get_imu_orientation()
|
|
1382
|
+
return float(np.arctan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z)))
|
|
1383
|
+
|
|
1384
|
+
# -- motors / LEDs ----------------------------------------------------------------
|
|
1385
|
+
|
|
1386
|
+
def enable_motors(self, joints: Optional[Sequence[str]] = None) -> None:
|
|
1387
|
+
"""Enable actuator torque (STS3215 ``TORQUE_SWITCH``) on the given joints (default: all)."""
|
|
1388
|
+
self.backend.set_torque_enabled(True, joints)
|
|
1389
|
+
|
|
1390
|
+
def disable_motors(self, joints: Optional[Sequence[str]] = None) -> None:
|
|
1391
|
+
"""Disable actuator torque on the given joints (default: all) - motors go limp."""
|
|
1392
|
+
self.backend.set_torque_enabled(False, joints)
|
|
1393
|
+
|
|
1394
|
+
def set_led_all(self, r: int, g: int, b: int) -> None:
|
|
1395
|
+
"""Set every ring LED to one RGB color."""
|
|
1396
|
+
self.backend.set_led_all(r, g, b)
|
|
1397
|
+
|
|
1398
|
+
def set_led(self, index: int, r: int, g: int, b: int) -> None:
|
|
1399
|
+
"""Set a single ring LED (0-17)."""
|
|
1400
|
+
self.backend.set_led(index, r, g, b)
|
|
1401
|
+
|
|
1402
|
+
def set_led_bulk(self, colors: Sequence[Tuple[int, int, int]]) -> None:
|
|
1403
|
+
"""Set all 18 ring LEDs at once from a list of (r, g, b) tuples."""
|
|
1404
|
+
self.backend.set_led_bulk(colors)
|
|
1405
|
+
|
|
1406
|
+
def play_sound(self, path: Union[str, Path], volume: Optional[float] = None, wait: bool = False,
|
|
1407
|
+
gain: float = 1.0) -> bool:
|
|
1408
|
+
"""Play a .wav on Chromapi's speaker (``config["audio"]``), or the PC's default output in simulation.
|
|
1409
|
+
|
|
1410
|
+
``gain`` multiplies the volume (``config["audio"]["volume"]`` by default), for a sound recorded quieter.
|
|
1411
|
+
|
|
1412
|
+
Returns False, with a warning in the log, if it could not be played (no ``audio`` extra,
|
|
1413
|
+
no output device).
|
|
1414
|
+
"""
|
|
1415
|
+
from chromapi.media.audio import find_output_device, play_wav
|
|
1416
|
+
|
|
1417
|
+
device = find_output_device(self._speaker_hint) if self._speaker_hint else None
|
|
1418
|
+
return play_wav(path, wait=wait, volume=(self.sound_volume if volume is None else volume) * gain, device=device)
|
|
1419
|
+
|
|
1420
|
+
# -- moves / behaviors --------------------------------------------------------------
|
|
1421
|
+
|
|
1422
|
+
def play_move(self, move: Move) -> None:
|
|
1423
|
+
"""Activate ``move``, stopping (``on_stop``) the active one first."""
|
|
1424
|
+
with self._targets_lock:
|
|
1425
|
+
previous = self._active_move
|
|
1426
|
+
self._active_move = None
|
|
1427
|
+
if previous is not None:
|
|
1428
|
+
previous.on_stop()
|
|
1429
|
+
move.on_start()
|
|
1430
|
+
with self._targets_lock:
|
|
1431
|
+
self._active_move = move
|
|
1432
|
+
|
|
1433
|
+
def stop_move(self) -> None:
|
|
1434
|
+
"""Deactivate the current move, freezing the joint targets at their last value."""
|
|
1435
|
+
with self._targets_lock:
|
|
1436
|
+
move = self._active_move
|
|
1437
|
+
self._active_move = None
|
|
1438
|
+
if move is not None:
|
|
1439
|
+
move.on_stop()
|
|
1440
|
+
|
|
1441
|
+
|
|
1442
|
+
class _InterpolationMove(Move):
|
|
1443
|
+
"""Internal one-shot minimum-jerk transition between two joint configurations."""
|
|
1444
|
+
|
|
1445
|
+
def __init__(self, start: Dict[str, float], target: Dict[str, float], duration: float) -> None:
|
|
1446
|
+
"""Store the endpoints; ``duration`` <= 0 completes on the first tick."""
|
|
1447
|
+
self._start = start
|
|
1448
|
+
self._target = target
|
|
1449
|
+
self._duration = max(duration, 1e-6) # [s]
|
|
1450
|
+
self._elapsed = 0.0 # [s]
|
|
1451
|
+
self.done = False
|
|
1452
|
+
|
|
1453
|
+
def step(self, state: RobotState, command: MotorCommand, dt: float) -> None:
|
|
1454
|
+
"""Advance the interpolation by ``dt`` and write the blended targets."""
|
|
1455
|
+
self._elapsed += dt
|
|
1456
|
+
self.done = self._elapsed >= self._duration
|
|
1457
|
+
s = _minimum_jerk(self._elapsed / self._duration)
|
|
1458
|
+
for joint, target in self._target.items():
|
|
1459
|
+
start = self._start.get(joint, target)
|
|
1460
|
+
command.target_angles[joint] = (1.0 - s) * start + s * target
|