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
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""IMU Mount Calibration Tool.
|
|
3
|
+
|
|
4
|
+
Put Chromapi on a flat floor (rest pose or standing, chassis level) and don't touch it.
|
|
5
|
+
|
|
6
|
+
Usage::
|
|
7
|
+
|
|
8
|
+
chromapi calibrate imu
|
|
9
|
+
chromapi calibrate imu --duration 10 --dry-run
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import math
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import List, Sequence
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
|
|
21
|
+
from chromapi.chromapi import USER_CALIBRATION_PATH, save_calibration
|
|
22
|
+
from chromapi.estimation.attitude import ImuMount, roll_pitch
|
|
23
|
+
from chromapi.hardware.motherboard_bridge import BridgeClient
|
|
24
|
+
|
|
25
|
+
STILL_GYRO_RPS = 0.05 # [rad.s⁻¹] samples above this are dropped (robot moving)
|
|
26
|
+
MIN_STILL_FRACTION = 0.9
|
|
27
|
+
SAMPLE_PERIOD_S = 0.01 # [s]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _record(bridge: BridgeClient, duration_s: float) -> List[Sequence[float]]:
|
|
31
|
+
"""Quaternions read while the gyro says the robot is still."""
|
|
32
|
+
quats: List[Sequence[float]] = []
|
|
33
|
+
n_total = 0
|
|
34
|
+
t_end = time.monotonic() + duration_s
|
|
35
|
+
while time.monotonic() < t_end:
|
|
36
|
+
state = bridge.get_state()
|
|
37
|
+
if state is not None:
|
|
38
|
+
n_total += 1
|
|
39
|
+
if np.linalg.norm(state["imu"]["gyro_rps"]) < STILL_GYRO_RPS:
|
|
40
|
+
quats.append(state["imu"]["quat"])
|
|
41
|
+
time.sleep(SAMPLE_PERIOD_S)
|
|
42
|
+
if n_total == 0 or len(quats) < MIN_STILL_FRACTION * n_total:
|
|
43
|
+
raise RuntimeError(f"robot not still enough ({len(quats)}/{n_total} still samples)")
|
|
44
|
+
return quats
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def main() -> None:
|
|
48
|
+
"""Record, compute and write the IMU mount offset."""
|
|
49
|
+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
50
|
+
parser.add_argument("--port", default="/dev/ttyAMA0", help="UART bridge serial device")
|
|
51
|
+
parser.add_argument("--calibration", type=Path, default=USER_CALIBRATION_PATH, help="calibration file to update")
|
|
52
|
+
parser.add_argument("--duration", type=float, default=5.0, help="recording time [s]")
|
|
53
|
+
parser.add_argument("--dry-run", action="store_true", help="measure and print, but never write the calibration")
|
|
54
|
+
args = parser.parse_args()
|
|
55
|
+
|
|
56
|
+
bridge = BridgeClient(port=args.port)
|
|
57
|
+
if not bridge.connect():
|
|
58
|
+
sys.exit("[!] Cannot open the UART bridge.")
|
|
59
|
+
try:
|
|
60
|
+
print(f"[*] Recording {args.duration:.0f} s - keep Chromapi still on a level floor...")
|
|
61
|
+
quats = _record(bridge, args.duration)
|
|
62
|
+
except RuntimeError as exc:
|
|
63
|
+
sys.exit(f"[!] {exc}")
|
|
64
|
+
finally:
|
|
65
|
+
bridge.close()
|
|
66
|
+
|
|
67
|
+
mount = ImuMount.from_level_samples(quats)
|
|
68
|
+
roll, pitch = roll_pitch(mount.offset)
|
|
69
|
+
print(f"[*] {len(quats)} samples - board offset: roll {math.degrees(roll):+.2f} deg, "
|
|
70
|
+
f"pitch {math.degrees(pitch):+.2f} deg")
|
|
71
|
+
print(f" mount_offset_wxyz: [{', '.join(f'{v:.6f}' for v in mount.offset)}]")
|
|
72
|
+
if args.dry_run:
|
|
73
|
+
print("(--dry-run: calibration left untouched)")
|
|
74
|
+
return
|
|
75
|
+
path = save_calibration({"imu": {"mount_offset_wxyz": [float(v) for v in mount.offset]}}, args.calibration)
|
|
76
|
+
print(f"[SUCCESS] Written to {path}")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
if __name__ == "__main__":
|
|
80
|
+
main()
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
"""Servo Center Calibration Tool.
|
|
2
|
+
|
|
3
|
+
Usage::
|
|
4
|
+
|
|
5
|
+
chromapi calibrate servos --joint tl_2
|
|
6
|
+
chromapi calibrate servos --all
|
|
7
|
+
chromapi calibrate servos --joint tl_2 --verbose --dry-run
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import math
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Callable, Dict, List, Optional
|
|
17
|
+
|
|
18
|
+
from chromapi.chromapi import (
|
|
19
|
+
DEFAULT_CONFIG_PATH,
|
|
20
|
+
STS3215_CENTER_STEP,
|
|
21
|
+
STS3215_STEPS_PER_REV,
|
|
22
|
+
USER_CALIBRATION_PATH,
|
|
23
|
+
load_config,
|
|
24
|
+
save_calibration,
|
|
25
|
+
)
|
|
26
|
+
from chromapi.hardware.motherboard_bridge import DEFAULT_BAUDRATE, BridgeClient
|
|
27
|
+
from chromapi.kinematics import kromatics as K
|
|
28
|
+
|
|
29
|
+
# --- Feetech STS3215 register map (SRAM half - see utils/setup_motors.py for the EEPROM half) ---
|
|
30
|
+
REG_TORQUE_SWITCH = 40 # 1 byte : 0 = free, 1 = position-controlled (torque enabled)
|
|
31
|
+
REG_GOAL_POSITION = 42 # 2 bytes: 0-4095
|
|
32
|
+
REG_PRESENT_POSITION = 56 # 2 bytes: 0-4095
|
|
33
|
+
REG_PRESENT_LOAD = 60 # 2 bytes: bits 0-9 = duty magnitude (0-1023, 0.1% units), bit 10 = sign (0=CCW, 1=CW)
|
|
34
|
+
|
|
35
|
+
# --- Sweep tuning (override via CLI flags if a joint false-triggers or never stalls) ---
|
|
36
|
+
DEFAULT_STEP = 12 # raw steps per sweep increment (~1 deg)
|
|
37
|
+
DEFAULT_MARGIN = 200 # load units above the idle baseline counted as "hit a stop"
|
|
38
|
+
SETTLE_S = 0.08 # wait after each step before sampling load
|
|
39
|
+
SAMPLES_PER_STEP = 3
|
|
40
|
+
STALL_HITS_REQUIRED = 3 # consecutive spikes required before declaring a stop
|
|
41
|
+
MIN_PLAUSIBLE_RANGE_STEPS = 100 # ~9 deg; below this, something is probably wrong
|
|
42
|
+
MAX_SWEEP_STEPS = 400 # hard cap on increments per direction, as a last-resort guard
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
#: Each hip sweeps into its same-side neighbour: that neighbour's hip swings this far away [rad].
|
|
46
|
+
NEIGHBOUR_HIP_AWAY_RAD = math.radians(65.0)
|
|
47
|
+
_NEIGHBOUR = {"tl": "bl", "bl": "tl", "tr": "br", "br": "tr"}
|
|
48
|
+
_AWAY_SIGN = {"tl": +1, "bl": -1, "tr": +1, "br": -1} # sign of a hip angle pointing away from its neighbour
|
|
49
|
+
#: Tibia angle while its femur sweeps toward negative (DOWN) / positive (UP) angles, set on the robot.
|
|
50
|
+
TIBIA_FEMUR_DOWN_RAD = math.radians(90.0)
|
|
51
|
+
TIBIA_FEMUR_UP_RAD = math.radians(-90.0)
|
|
52
|
+
#: While a hip sweeps, every tibia opens this much from the rest pose: the feet rise ~45 mm and the
|
|
53
|
+
#: swept leg's tibia passes over the neighbouring hip instead of brushing it.
|
|
54
|
+
HIP_SWEEP_TIBIA_LIFT_RAD = math.radians(30.0)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def clearance_pose(joint: str) -> Dict[str, float]:
|
|
58
|
+
"""Joint angles [rad] to hold while ``joint`` is swept, so both stops it finds are its own."""
|
|
59
|
+
leg, index = joint.split("_")
|
|
60
|
+
pose = dict(K.REST_POSE)
|
|
61
|
+
if index == "1":
|
|
62
|
+
pose[joint] = 0.0
|
|
63
|
+
neighbour = _NEIGHBOUR[leg]
|
|
64
|
+
pose[f"{neighbour}_1"] = _AWAY_SIGN[neighbour] * NEIGHBOUR_HIP_AWAY_RAD
|
|
65
|
+
for any_leg in K.LEG_NAMES:
|
|
66
|
+
pose[f"{any_leg}_3"] += HIP_SWEEP_TIBIA_LIFT_RAD
|
|
67
|
+
else:
|
|
68
|
+
for i in ("1", "2", "3"):
|
|
69
|
+
pose[f"{leg}_{i}"] = 0.0
|
|
70
|
+
if index == "2":
|
|
71
|
+
pose[f"{leg}_3"] = TIBIA_FEMUR_DOWN_RAD
|
|
72
|
+
return pose
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _rad_to_step(servos: Dict[str, Dict[str, int]], joint: str, angle: float) -> int:
|
|
76
|
+
"""Same conversion as ``HardwareBackend``, with the offsets calibrated so far."""
|
|
77
|
+
raw = (
|
|
78
|
+
STS3215_CENTER_STEP
|
|
79
|
+
+ servos["sign"][joint] * angle * STS3215_STEPS_PER_REV / (2.0 * math.pi)
|
|
80
|
+
+ servos["zero_offset_steps"].get(joint, 0)
|
|
81
|
+
)
|
|
82
|
+
return _clamp_step(round(raw))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _tibia_follows_femur(bridge: BridgeClient, servos: Dict[str, Dict[str, int]], femur: str) -> Callable[[int], None]:
|
|
86
|
+
"""Before each half-sweep of ``femur`` (raw direction -1/+1), fold its tibia for that direction."""
|
|
87
|
+
tibia = femur[:-1] + "3"
|
|
88
|
+
|
|
89
|
+
def before_sweep(raw_direction: int) -> None:
|
|
90
|
+
lowering = raw_direction * servos["sign"][femur] < 0
|
|
91
|
+
_move_to_pose(bridge, servos, {tibia: TIBIA_FEMUR_DOWN_RAD if lowering else TIBIA_FEMUR_UP_RAD})
|
|
92
|
+
|
|
93
|
+
return before_sweep
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _move_to_pose(bridge: BridgeClient, servos: Dict[str, Dict[str, int]], pose: Dict[str, float]) -> None:
|
|
97
|
+
"""Move every servo of ``pose`` [rad], one at a time, and hold it there."""
|
|
98
|
+
for other, angle in pose.items():
|
|
99
|
+
servo_id = servos["id_map"][other]
|
|
100
|
+
present = _read_present_position(bridge, servo_id)
|
|
101
|
+
if present is None:
|
|
102
|
+
raise RuntimeError(f"servo {servo_id} ({other}): not responding, cannot move it out of the way.")
|
|
103
|
+
_set_torque(bridge, servo_id, True)
|
|
104
|
+
_move_smoothly(bridge, servo_id, present, _rad_to_step(servos, other, angle))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass
|
|
108
|
+
class SweepResult:
|
|
109
|
+
"""The two mechanical stops found for a servo, and the midpoint between them."""
|
|
110
|
+
|
|
111
|
+
min_step: int
|
|
112
|
+
max_step: int
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def center_step(self) -> int:
|
|
116
|
+
"""Midpoint between the two mechanical stops, taken as the true servo center."""
|
|
117
|
+
return (self.min_step + self.max_step) // 2
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def range_steps(self) -> int:
|
|
121
|
+
"""Total measured travel, in raw steps."""
|
|
122
|
+
return self.max_step - self.min_step
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _clamp_step(raw_step: int) -> int:
|
|
126
|
+
return max(0, min(STS3215_STEPS_PER_REV - 1, raw_step))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _decode_load(raw: int) -> int:
|
|
130
|
+
"""Decode a raw `Present Load` register value into a signed duty (-1023..1023)."""
|
|
131
|
+
magnitude = raw & 0x3FF
|
|
132
|
+
return -magnitude if raw & 0x400 else magnitude
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _read_present_position(bridge: BridgeClient, servo_id: int) -> Optional[int]:
|
|
136
|
+
"""Read the Present Position register, returning None on timeout."""
|
|
137
|
+
return bridge.read_servo_register(servo_id, REG_PRESENT_POSITION, 2)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _read_load_magnitude(bridge: BridgeClient, servo_id: int) -> Optional[int]:
|
|
141
|
+
"""Read the Present Load register, returning None on timeout."""
|
|
142
|
+
raw = bridge.read_servo_register(servo_id, REG_PRESENT_LOAD, 2)
|
|
143
|
+
if raw is None:
|
|
144
|
+
return None
|
|
145
|
+
return abs(_decode_load(raw))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _set_torque(bridge: BridgeClient, servo_id: int, enabled: bool) -> None:
|
|
149
|
+
"""Enable or disable the servo's position control (torque)."""
|
|
150
|
+
bridge.write_servo_register(servo_id, REG_TORQUE_SWITCH, 1, 1 if enabled else 0)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _goto(bridge: BridgeClient, servo_id: int, raw_step: int) -> None:
|
|
154
|
+
"""Command the servo to move to ``raw_step`` (0..4095)."""
|
|
155
|
+
bridge.write_servo_register(servo_id, REG_GOAL_POSITION, 2, _clamp_step(raw_step))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _move_smoothly(
|
|
159
|
+
bridge: BridgeClient, servo_id: int, from_step: int, to_step: int, step: int = DEFAULT_STEP
|
|
160
|
+
) -> None:
|
|
161
|
+
"""Walk the servo from ``from_step`` to ``to_step`` in small increments (no hard jump)."""
|
|
162
|
+
direction = 1 if to_step >= from_step else -1
|
|
163
|
+
pos = from_step
|
|
164
|
+
while (direction > 0 and pos < to_step) or (direction < 0 and pos > to_step):
|
|
165
|
+
pos = pos + direction * step if abs(to_step - pos) > step else to_step
|
|
166
|
+
_goto(bridge, servo_id, pos)
|
|
167
|
+
time.sleep(0.02)
|
|
168
|
+
_goto(bridge, servo_id, to_step)
|
|
169
|
+
time.sleep(0.15)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _measure_baseline(bridge: BridgeClient, servo_id: int, at_step: int) -> int:
|
|
173
|
+
"""Sample idle load at rest, to tell a genuine stall spike from normal noise/friction."""
|
|
174
|
+
_goto(bridge, servo_id, at_step)
|
|
175
|
+
time.sleep(0.3)
|
|
176
|
+
samples: List[int] = []
|
|
177
|
+
for _ in range(8):
|
|
178
|
+
load = _read_load_magnitude(bridge, servo_id)
|
|
179
|
+
if load is not None:
|
|
180
|
+
samples.append(load)
|
|
181
|
+
time.sleep(0.02)
|
|
182
|
+
if not samples:
|
|
183
|
+
raise RuntimeError(f"servo {servo_id}: no response while measuring the idle load baseline.")
|
|
184
|
+
return round(sum(samples) / len(samples))
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _sweep_to_limit(
|
|
188
|
+
bridge: BridgeClient,
|
|
189
|
+
servo_id: int,
|
|
190
|
+
start_step: int,
|
|
191
|
+
direction: int,
|
|
192
|
+
baseline: int,
|
|
193
|
+
margin: int,
|
|
194
|
+
step: int,
|
|
195
|
+
verbose: bool,
|
|
196
|
+
) -> int:
|
|
197
|
+
"""Step ``servo_id`` in ``direction`` (+1/-1) until it stalls against a mechanical stop.
|
|
198
|
+
|
|
199
|
+
Returns the last raw step the servo actually reached before the stall - i.e. the mechanical
|
|
200
|
+
limit itself, already backed off from whatever step first triggered the stall reading.
|
|
201
|
+
"""
|
|
202
|
+
pos = start_step
|
|
203
|
+
last_free_pos = start_step
|
|
204
|
+
consecutive_hits = 0
|
|
205
|
+
threshold = baseline + margin
|
|
206
|
+
|
|
207
|
+
for _ in range(MAX_SWEEP_STEPS):
|
|
208
|
+
next_pos = pos + direction * step
|
|
209
|
+
if next_pos <= 0 or next_pos >= STS3215_STEPS_PER_REV - 1:
|
|
210
|
+
last_free_pos = _clamp_step(next_pos)
|
|
211
|
+
break
|
|
212
|
+
|
|
213
|
+
_goto(bridge, servo_id, next_pos)
|
|
214
|
+
time.sleep(SETTLE_S)
|
|
215
|
+
|
|
216
|
+
loads: List[int] = []
|
|
217
|
+
for _ in range(SAMPLES_PER_STEP):
|
|
218
|
+
load = _read_load_magnitude(bridge, servo_id)
|
|
219
|
+
if load is not None:
|
|
220
|
+
loads.append(load)
|
|
221
|
+
time.sleep(0.01)
|
|
222
|
+
if not loads:
|
|
223
|
+
raise RuntimeError(f"servo {servo_id}: lost communication mid-sweep.")
|
|
224
|
+
peak_load = max(loads)
|
|
225
|
+
|
|
226
|
+
present = _read_present_position(bridge, servo_id)
|
|
227
|
+
tracking_error = None if present is None else abs(present - next_pos)
|
|
228
|
+
|
|
229
|
+
if verbose:
|
|
230
|
+
err_str = "?" if tracking_error is None else str(tracking_error)
|
|
231
|
+
print(
|
|
232
|
+
f" step {next_pos:4d} load={peak_load:4d} "
|
|
233
|
+
f"(threshold={threshold}) tracking_error={err_str}"
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
stalled = peak_load >= threshold
|
|
237
|
+
stuck = tracking_error is not None and tracking_error > step * 2 and peak_load >= baseline + margin // 2
|
|
238
|
+
|
|
239
|
+
if stalled or stuck:
|
|
240
|
+
consecutive_hits += 1
|
|
241
|
+
if consecutive_hits >= STALL_HITS_REQUIRED:
|
|
242
|
+
_goto(bridge, servo_id, last_free_pos)
|
|
243
|
+
time.sleep(0.2)
|
|
244
|
+
return last_free_pos
|
|
245
|
+
else:
|
|
246
|
+
consecutive_hits = 0
|
|
247
|
+
last_free_pos = next_pos
|
|
248
|
+
pos = next_pos
|
|
249
|
+
|
|
250
|
+
raise RuntimeError(
|
|
251
|
+
f"servo {servo_id}: no mechanical stop found after {MAX_SWEEP_STEPS} steps "
|
|
252
|
+
f"in direction {direction:+d} - aborting rather than keep pushing."
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def calibrate_servo(
|
|
257
|
+
bridge: BridgeClient,
|
|
258
|
+
servo_id: int,
|
|
259
|
+
margin: int = DEFAULT_MARGIN,
|
|
260
|
+
step: int = DEFAULT_STEP,
|
|
261
|
+
verbose: bool = False,
|
|
262
|
+
before_sweep: Optional[Callable[[int], None]] = None,
|
|
263
|
+
) -> SweepResult:
|
|
264
|
+
"""Sweep one servo to both mechanical stops and park it at the midpoint.
|
|
265
|
+
|
|
266
|
+
``before_sweep(raw_direction)``, if given, runs before each half-sweep (e.g. to refold the
|
|
267
|
+
rest of the leg); the idle load is then measured again, since the leg's weight changed.
|
|
268
|
+
"""
|
|
269
|
+
start = _read_present_position(bridge, servo_id)
|
|
270
|
+
if start is None:
|
|
271
|
+
raise RuntimeError(f"servo {servo_id}: not responding (present position read failed).")
|
|
272
|
+
|
|
273
|
+
_set_torque(bridge, servo_id, True)
|
|
274
|
+
|
|
275
|
+
def prepare(direction: int) -> int:
|
|
276
|
+
if before_sweep is not None:
|
|
277
|
+
before_sweep(direction)
|
|
278
|
+
baseline = _measure_baseline(bridge, servo_id, start)
|
|
279
|
+
print(f" idle load baseline: {baseline} (stall threshold: {baseline + margin})")
|
|
280
|
+
return baseline
|
|
281
|
+
|
|
282
|
+
baseline = prepare(-1)
|
|
283
|
+
print(" sweeping toward the low stop...")
|
|
284
|
+
min_step = _sweep_to_limit(bridge, servo_id, start, -1, baseline, margin, step, verbose)
|
|
285
|
+
print(f" low stop found at raw step {min_step}")
|
|
286
|
+
|
|
287
|
+
_move_smoothly(bridge, servo_id, min_step, start, step)
|
|
288
|
+
|
|
289
|
+
baseline = prepare(+1) if before_sweep is not None else baseline
|
|
290
|
+
print(" sweeping toward the high stop...")
|
|
291
|
+
max_step = _sweep_to_limit(bridge, servo_id, start, +1, baseline, margin, step, verbose)
|
|
292
|
+
print(f" high stop found at raw step {max_step}")
|
|
293
|
+
|
|
294
|
+
result = SweepResult(min_step=min_step, max_step=max_step)
|
|
295
|
+
if result.range_steps < MIN_PLAUSIBLE_RANGE_STEPS:
|
|
296
|
+
raise RuntimeError(
|
|
297
|
+
f"servo {servo_id}: measured range ({result.range_steps} steps) is implausibly "
|
|
298
|
+
"small - check the horn/linkage coupling and the --margin threshold before retrying."
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
_move_smoothly(bridge, servo_id, max_step, result.center_step, step)
|
|
302
|
+
print(f" parked at center step {result.center_step}")
|
|
303
|
+
return result
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _print_servo_snapshot(bridge: BridgeClient, id_to_joint: Dict[int, str]) -> None:
|
|
307
|
+
"""Print every servo's current raw position, so the operator can check leg clearance."""
|
|
308
|
+
state = bridge.get_state()
|
|
309
|
+
if state is None:
|
|
310
|
+
print(" [WARN] could not read the full state snapshot - check leg clearance manually.")
|
|
311
|
+
return
|
|
312
|
+
print(" current servo positions (raw steps) - make sure nothing else is in the way:")
|
|
313
|
+
row = " " + " ".join(
|
|
314
|
+
f"{id_to_joint.get(s['id'], '?'):>5}({s['id']:02d})={s['pos']:4d}" for s in state["servos"]
|
|
315
|
+
)
|
|
316
|
+
print(row)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _prompt_yes_no(question: str, default_no: bool = True) -> bool:
|
|
320
|
+
suffix = "[y/N]" if default_no else "[Y/n]"
|
|
321
|
+
answer = input(f"{question} {suffix} ").strip().lower()
|
|
322
|
+
if not answer:
|
|
323
|
+
return not default_no
|
|
324
|
+
return answer in ("y", "yes")
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def main() -> None:
|
|
328
|
+
"""Run the interactive servo center calibration CLI."""
|
|
329
|
+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
330
|
+
parser.add_argument("--joint", action="append", default=[], help="joint name to calibrate (repeatable)")
|
|
331
|
+
parser.add_argument("--all", action="store_true", help="calibrate every joint in config.yaml's id_map")
|
|
332
|
+
parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG_PATH, help="package defaults (config.yaml)")
|
|
333
|
+
parser.add_argument("--calibration", type=Path, default=USER_CALIBRATION_PATH, help="calibration file to update")
|
|
334
|
+
parser.add_argument("--port", default="/dev/ttyAMA0", help="serial port to the STM32 bridge")
|
|
335
|
+
parser.add_argument("--baudrate", type=int, default=DEFAULT_BAUDRATE)
|
|
336
|
+
parser.add_argument("--step", type=int, default=DEFAULT_STEP, help="raw steps per sweep increment")
|
|
337
|
+
parser.add_argument("--margin", type=int, default=DEFAULT_MARGIN, help="load spike (above idle) counted as a stall")
|
|
338
|
+
parser.add_argument("--dry-run", action="store_true", help="measure and print, but never write the calibration")
|
|
339
|
+
parser.add_argument("--yes", action="store_true", help="skip all confirmation prompts (unattended use)")
|
|
340
|
+
parser.add_argument("--verbose", action="store_true", help="print per-step load/tracking diagnostics")
|
|
341
|
+
args = parser.parse_args()
|
|
342
|
+
|
|
343
|
+
config = load_config(args.config, args.calibration)
|
|
344
|
+
id_map: Dict[str, int] = config["servos"]["id_map"]
|
|
345
|
+
id_to_joint: Dict[int, str] = {v: k for k, v in id_map.items()}
|
|
346
|
+
existing_offsets: Dict[str, int] = config["servos"].get("zero_offset_steps", {})
|
|
347
|
+
|
|
348
|
+
targets: List[str] = list(id_map) if args.all else list(dict.fromkeys(args.joint))
|
|
349
|
+
if not targets:
|
|
350
|
+
parser.error("pass at least one --joint <name> or use --all")
|
|
351
|
+
unknown = [j for j in targets if j not in id_map]
|
|
352
|
+
if unknown:
|
|
353
|
+
parser.error(f"unknown joint(s) {unknown}; known joints are: {sorted(id_map)}")
|
|
354
|
+
|
|
355
|
+
print("=" * 60)
|
|
356
|
+
print(" SERVO CENTER CALIBRATION")
|
|
357
|
+
print("=" * 60)
|
|
358
|
+
print(f"Joints to calibrate: {targets}")
|
|
359
|
+
print(
|
|
360
|
+
"\n/!\\ Each joint sweeps across its ENTIRE range of motion, and the other legs move\n"
|
|
361
|
+
" out of its way first. Lift Chromapi so no leg can touch the ground.\n"
|
|
362
|
+
)
|
|
363
|
+
if not args.yes and not _prompt_yes_no("Chromapi is clear and safe to move?"):
|
|
364
|
+
print("Aborted.")
|
|
365
|
+
return
|
|
366
|
+
|
|
367
|
+
bridge = BridgeClient(port=args.port, baudrate=args.baudrate)
|
|
368
|
+
if not bridge.connect():
|
|
369
|
+
print(f"[FAIL] Could not open serial port {args.port}.")
|
|
370
|
+
sys.exit(1)
|
|
371
|
+
|
|
372
|
+
accepted: Dict[str, int] = {}
|
|
373
|
+
try:
|
|
374
|
+
for joint in targets:
|
|
375
|
+
servo_id = id_map[joint]
|
|
376
|
+
print(f"\n--- {joint} (servo id {servo_id}) ---")
|
|
377
|
+
try:
|
|
378
|
+
_move_to_pose(bridge, config["servos"], clearance_pose(joint))
|
|
379
|
+
_print_servo_snapshot(bridge, id_to_joint)
|
|
380
|
+
before_sweep = _tibia_follows_femur(bridge, config["servos"], joint) if joint.endswith("_2") else None
|
|
381
|
+
result = calibrate_servo(
|
|
382
|
+
bridge, servo_id, margin=args.margin, step=args.step, verbose=args.verbose, before_sweep=before_sweep
|
|
383
|
+
)
|
|
384
|
+
except RuntimeError as e:
|
|
385
|
+
print(f" [FAIL] {e}")
|
|
386
|
+
continue
|
|
387
|
+
|
|
388
|
+
offset = result.center_step - STS3215_CENTER_STEP
|
|
389
|
+
previous = existing_offsets.get(joint, 0)
|
|
390
|
+
print(
|
|
391
|
+
f" range=[{result.min_step}, {result.max_step}] "
|
|
392
|
+
f"({result.range_steps} steps) center={result.center_step}"
|
|
393
|
+
)
|
|
394
|
+
print(f" zero_offset_steps: {previous} (current) -> {offset} (measured)")
|
|
395
|
+
|
|
396
|
+
if args.yes or _prompt_yes_no(f" Accept this offset for '{joint}'?", default_no=False):
|
|
397
|
+
accepted[joint] = offset
|
|
398
|
+
else:
|
|
399
|
+
print(" Skipped.")
|
|
400
|
+
print("\nFolding into the rest pose...")
|
|
401
|
+
servos = dict(config["servos"], zero_offset_steps={**config["servos"]["zero_offset_steps"], **accepted})
|
|
402
|
+
try:
|
|
403
|
+
_move_to_pose(bridge, servos, K.REST_POSE)
|
|
404
|
+
except RuntimeError as e: # never lose the measured offsets over the parking move
|
|
405
|
+
print(f" [WARN] {e}")
|
|
406
|
+
except KeyboardInterrupt:
|
|
407
|
+
print("\n[!] Interrupted - leaving the last-moved servo where it stopped.")
|
|
408
|
+
finally:
|
|
409
|
+
bridge.close()
|
|
410
|
+
|
|
411
|
+
if not accepted:
|
|
412
|
+
print("\nNo offsets to write.")
|
|
413
|
+
return
|
|
414
|
+
|
|
415
|
+
print("\nMeasured offsets:")
|
|
416
|
+
for joint, offset in accepted.items():
|
|
417
|
+
print(f" {joint}: {offset}")
|
|
418
|
+
|
|
419
|
+
if args.dry_run:
|
|
420
|
+
print("\n(--dry-run: calibration left untouched)")
|
|
421
|
+
return
|
|
422
|
+
|
|
423
|
+
if not args.yes and not _prompt_yes_no(f"Write these {len(accepted)} offset(s) to {args.calibration}?"):
|
|
424
|
+
print("Not written.")
|
|
425
|
+
return
|
|
426
|
+
|
|
427
|
+
path = save_calibration({"servos": {"zero_offset_steps": accepted}}, args.calibration)
|
|
428
|
+
print(f"\n[OK] {path} updated.")
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
if __name__ == "__main__":
|
|
432
|
+
main()
|
chromapi/utils/flash.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Flash the motherboard firmware (STM32) from the Raspberry Pi, through its ROM bootloader.
|
|
3
|
+
|
|
4
|
+
The servos lose their torque while the STM32 resets: make sure Chromapi is laid down.
|
|
5
|
+
|
|
6
|
+
Usage::
|
|
7
|
+
|
|
8
|
+
chromapi flash # the firmware shipped with this SDK
|
|
9
|
+
chromapi flash path/to/firmware.hex
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import logging
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Optional, Tuple
|
|
20
|
+
|
|
21
|
+
from chromapi.chromapi import load_config
|
|
22
|
+
from chromapi.hardware.battery import Battery
|
|
23
|
+
from chromapi.hardware.motherboard_bridge import BridgeClient
|
|
24
|
+
from chromapi.utils.health import port_users
|
|
25
|
+
|
|
26
|
+
FIRMWARE_DIR = Path(__file__).resolve().parents[1] / "assets" / "firmware"
|
|
27
|
+
FLASH_SCRIPT = FIRMWARE_DIR / "flash.sh"
|
|
28
|
+
BOOT_TIMEOUT_S = 8.0 # [s] for the flashed firmware to answer (IMU calibration first)
|
|
29
|
+
SHIPPED_HEX_RE = re.compile(r"chromapi_stm32_core_v(\d+\.\d+\.\d+)\.hex")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _version_key(version: str) -> Tuple[int, ...]:
|
|
33
|
+
return tuple(map(int, version.split(".")))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def shipped_firmware() -> Optional[Tuple[Path, str]]:
|
|
37
|
+
"""``(hex, version)`` of the newest firmware shipped with this SDK, None if none."""
|
|
38
|
+
found = [(path, match.group(1)) for path in FIRMWARE_DIR.glob("*.hex")
|
|
39
|
+
if (match := SHIPPED_HEX_RE.fullmatch(path.name))]
|
|
40
|
+
return max(found, key=lambda hex_version: _version_key(hex_version[1]), default=None)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def shipped_version() -> Optional[str]:
|
|
44
|
+
"""Version of the firmware shipped with this SDK; None if this install has none."""
|
|
45
|
+
shipped = shipped_firmware()
|
|
46
|
+
return shipped[1] if shipped else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def update_available(installed: Optional[str], shipped: Optional[str]) -> bool:
|
|
50
|
+
"""Whether ``shipped`` is newer than ``installed``."""
|
|
51
|
+
if shipped is None:
|
|
52
|
+
return False
|
|
53
|
+
if installed is None:
|
|
54
|
+
return True
|
|
55
|
+
return _version_key(shipped) > _version_key(installed)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def read_firmware(port: str) -> Optional[str]:
|
|
59
|
+
"""Firmware version string; None if the STM32 does not answer (or predates GET_VERSION)."""
|
|
60
|
+
bridge = BridgeClient(port=port)
|
|
61
|
+
if not bridge.connect():
|
|
62
|
+
return None
|
|
63
|
+
try:
|
|
64
|
+
version = bridge.get_version()
|
|
65
|
+
finally:
|
|
66
|
+
bridge.close()
|
|
67
|
+
return None if version is None else ".".join(map(str, version[1]))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def battery_percent(port: str) -> Optional[float]:
|
|
71
|
+
"""Charge estimate from ~1 s of readings; None if the STM32 does not answer."""
|
|
72
|
+
battery = Battery(load_config()["battery"])
|
|
73
|
+
bridge = BridgeClient(port=port)
|
|
74
|
+
if not bridge.connect():
|
|
75
|
+
return None
|
|
76
|
+
try:
|
|
77
|
+
for i in range(5):
|
|
78
|
+
snap = bridge.get_state(timeout=0.2)
|
|
79
|
+
if snap is not None:
|
|
80
|
+
battery.update(snap["power"]["voltage_V"], snap["power"]["current_A"], 0.2 * i)
|
|
81
|
+
finally:
|
|
82
|
+
bridge.close()
|
|
83
|
+
return battery.percent
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def main() -> int:
|
|
87
|
+
"""Check the port and the battery, confirm, flash, then read the new version back."""
|
|
88
|
+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
89
|
+
shipped = shipped_firmware()
|
|
90
|
+
parser.add_argument("hex", nargs="?", type=Path, default=shipped[0] if shipped else None,
|
|
91
|
+
help="firmware file (.hex); default: the one shipped with this SDK")
|
|
92
|
+
parser.add_argument("--port", default="/dev/ttyAMA0", help="serial port to the STM32")
|
|
93
|
+
parser.add_argument("--yes", action="store_true", help="do not ask for confirmation")
|
|
94
|
+
args = parser.parse_args()
|
|
95
|
+
|
|
96
|
+
if args.hex is None or not args.hex.is_file():
|
|
97
|
+
print(f"[!] {args.hex} not found: give the path of a firmware .hex")
|
|
98
|
+
return 1
|
|
99
|
+
users = port_users(args.port)
|
|
100
|
+
if users:
|
|
101
|
+
print(f"[!] {args.port} is open by {', '.join(users)}: stop it first (robot program, web app)")
|
|
102
|
+
return 1
|
|
103
|
+
|
|
104
|
+
before = read_firmware(args.port)
|
|
105
|
+
percent = battery_percent(args.port)
|
|
106
|
+
critical = load_config()["battery"]["critical_percent"]
|
|
107
|
+
if percent is not None and percent < critical:
|
|
108
|
+
print(f"[!] Battery at {percent:.0f} %: charge it before flashing")
|
|
109
|
+
return 1
|
|
110
|
+
print(f"Installed firmware: {before or 'unknown (not answering, or older than 2.0.0)'}")
|
|
111
|
+
print(f"Battery: {'unknown' if percent is None else f'{percent:.0f} %'}")
|
|
112
|
+
print(f"New firmware: {args.hex}")
|
|
113
|
+
if not args.yes and input("Lay Chromapi down: the servos go limp. Flash now? [y/N] ").strip().lower() != "y":
|
|
114
|
+
print("Cancelled.")
|
|
115
|
+
return 1
|
|
116
|
+
|
|
117
|
+
for attempt in (1, 2):
|
|
118
|
+
if subprocess.run(["bash", str(FLASH_SCRIPT), str(args.hex)], check=False).returncode == 0:
|
|
119
|
+
break
|
|
120
|
+
if attempt == 1:
|
|
121
|
+
print("[!] The bootloader did not answer: trying again")
|
|
122
|
+
else:
|
|
123
|
+
print("[!] Flash failed twice. The STM32 bootloader cannot be erased: check the wiring and the UART, then "
|
|
124
|
+
"run 'chromapi flash' again.")
|
|
125
|
+
return 1
|
|
126
|
+
|
|
127
|
+
# The firmware calibrates its IMU at boot before answering: its timeouts are expected, not warnings.
|
|
128
|
+
logging.getLogger("BridgeClient").setLevel(logging.ERROR)
|
|
129
|
+
deadline = time.monotonic() + BOOT_TIMEOUT_S # [s]
|
|
130
|
+
while time.monotonic() < deadline:
|
|
131
|
+
after = read_firmware(args.port)
|
|
132
|
+
if after is not None:
|
|
133
|
+
print(f"Done: firmware {after} (was {before or 'unknown'})")
|
|
134
|
+
return 0
|
|
135
|
+
time.sleep(0.5)
|
|
136
|
+
print("[!] Flashed, but the STM32 does not answer: power-cycle the robot and run 'chromapi version'")
|
|
137
|
+
return 1
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
if __name__ == "__main__":
|
|
141
|
+
sys.exit(main())
|