init: RoboCon 2027 BR 上位机 sru_ws(仅源码/文档/模型;排除构建产物与 venv)
- src/: sru_nav_ros2 (策略) + odin_ros_driver (0.14.x, ament ROS2) + techx_r2_chassis_control (串口桥) - 修复: 驱动目录此前是悬空 gitlink,clone 后为空 -> 现改为普通文件(55 个) - 排除: build/ install/ log/ venv/ .Trash-0/ __pycache__ 及驱动 map/log 运行期产物 - docs/: USAGE / PORT_NOTES / HANDOVER / ROS2_PORT_PLAN / 协议核查报告
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,37 @@
|
||||
cmake_minimum_required(VERSION 3.0.2)
|
||||
project(sru_nav_go2_ros1)
|
||||
|
||||
find_package(catkin REQUIRED COMPONENTS
|
||||
rospy
|
||||
std_msgs
|
||||
sensor_msgs
|
||||
geometry_msgs
|
||||
nav_msgs
|
||||
visualization_msgs
|
||||
cv_bridge
|
||||
tf2_ros
|
||||
)
|
||||
|
||||
catkin_python_setup()
|
||||
|
||||
catkin_package(
|
||||
CATKIN_DEPENDS
|
||||
rospy
|
||||
std_msgs
|
||||
sensor_msgs
|
||||
geometry_msgs
|
||||
nav_msgs
|
||||
visualization_msgs
|
||||
cv_bridge
|
||||
tf2_ros
|
||||
)
|
||||
|
||||
catkin_install_python(PROGRAMS
|
||||
scripts/sru_nav_node
|
||||
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
|
||||
)
|
||||
|
||||
install(DIRECTORY launch config models
|
||||
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
|
||||
OPTIONAL
|
||||
)
|
||||
@@ -0,0 +1,130 @@
|
||||
# sru_nav_go2_ros1
|
||||
|
||||
ROS 1 (Noetic) port of the SRU autonomous navigation controller, adapted for a
|
||||
**Unitree Go2 + Odin1** stack.
|
||||
|
||||
> 📘 **Want to reproduce or retarget this package?**
|
||||
> See **[`docs/PORTING_GUIDE.md`](docs/PORTING_GUIDE.md)** (中文)
|
||||
> or **[`docs/PORTING_GUIDE_EN.md`](docs/PORTING_GUIDE_EN.md)** (English)
|
||||
> for the full porting decision log + an AI agent slash command
|
||||
> (`/port-sru-to-ros`) that regenerates this package from the upstream
|
||||
> SRU repos and the paper, plus an automated `scripts/verify_port.sh`
|
||||
> acceptance script.
|
||||
|
||||
It is a near-1:1 port of
|
||||
`<upstream-package-path>/sru-robot-deployment/rl_nav_controller/rl_nav_controller/rl_nav_controller.py`
|
||||
with the following substitutions:
|
||||
|
||||
| Original (ROS2, B2W + ZedX + DLIO) | This port (ROS1, Go2 + Odin1) |
|
||||
| ----------------------------------------------------------- | ----------------------------------------- |
|
||||
| `/zed/zed_node/depth/depth_registered` (sensor_msgs/Image) | `/odin1/depth_img_competetion` |
|
||||
| `/dlio/odom_node/odom` (nav_msgs/Odometry) | `/odin1/odometry_highfreq` (~400 Hz) |
|
||||
| `/path_manager/path_manager_ros/nav_vel` (Twist) | `/cmd_vel` |
|
||||
| `rclpy` / Jazzy | `rospy` / Noetic |
|
||||
| `POLICY_SCALE = [1.5, 1.0, 1.0]` (wheeled B2W) | `POLICY_SCALE = [0.6, 0.3, 0.6]` (Go2) |
|
||||
|
||||
Inference is unchanged: ONNX VAE depth encoder (output 2560-dim latent) +
|
||||
LSTM SRU policy (hidden 512, h/c carried as explicit ONNX inputs/outputs).
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
sru_nav_go2_ros1/
|
||||
├── CMakeLists.txt
|
||||
├── package.xml
|
||||
├── setup.py
|
||||
├── README.md
|
||||
├── config/sru_nav.yaml # all runtime parameters
|
||||
├── launch/sru_nav_go2.launch # joy + static TF + main node
|
||||
├── models/ # symlinks to deployment_policies/
|
||||
│ ├── vae_encoder.onnx -> ../../sru-robot-deployment/.../vae_encoder.onnx
|
||||
│ └── nav_policy.onnx -> ../../sru-robot-deployment/.../nav_policy.onnx
|
||||
├── scripts/sru_nav_node # executable rospy entry point
|
||||
└── src/sru_nav_go2/ # importable Python package
|
||||
├── constants.py # tunables (Go2-conservative defaults)
|
||||
├── utils.py # quaternion/transform helpers (pure numpy)
|
||||
├── model.py # ONNX runtime wrapper (LearningModel)
|
||||
├── visualization.py # rviz Marker helpers
|
||||
├── waypoint_manager.py
|
||||
└── navigation_policy_node.py # ported NavigationPolicyNode (rospy)
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
Place this directory inside a catkin workspace and build:
|
||||
|
||||
```bash
|
||||
mkdir -p ~/sru_ws/src
|
||||
ln -s /home/lfd/project/SRU_Navigation/sru_nav_go2_ros1 ~/sru_ws/src/
|
||||
cd ~/sru_ws
|
||||
catkin_make # or catkin build
|
||||
source devel/setup.bash
|
||||
```
|
||||
|
||||
## Python dependencies (on Go2's NX, ROS Noetic / Python 3.8+)
|
||||
|
||||
```bash
|
||||
pip install numpy scipy opencv-python onnxruntime # or onnxruntime-gpu
|
||||
```
|
||||
|
||||
For Jetson with CUDA, install the JetPack-matched `onnxruntime-gpu` wheel from
|
||||
[NVIDIA's Jetson Zoo](https://elinux.org/Jetson_Zoo#ONNX_Runtime).
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
# 1) Bring up Odin1 (publishes /odin1/depth_img_competetion and /odin1/odometry)
|
||||
roslaunch odin_ros_driver odin1_ros.launch
|
||||
# Make sure config/control_command.yaml has senddepth: 1 and sendodom: 1.
|
||||
|
||||
# 2) Bring up your Go2 cmd_vel bridge (subscribes to /cmd_vel, drives sport mode)
|
||||
# (Your existing setup.)
|
||||
|
||||
# 3) Launch the SRU navigation node + joy
|
||||
roslaunch sru_nav_go2_ros1 sru_nav_go2.launch
|
||||
|
||||
# 4) Send a goal (in odom frame)
|
||||
rostopic pub /goal_pose geometry_msgs/PoseStamped "{
|
||||
header: {frame_id: 'odom'},
|
||||
pose: {position: {x: 3.0, y: 0.0, z: 0.0}, orientation: {w: 1.0}}
|
||||
}" --once
|
||||
```
|
||||
|
||||
## Tuning knobs (in `config/sru_nav.yaml`)
|
||||
|
||||
- `policy_scale` — start at `[0.6, 0.3, 0.6]`. Increase gradually after
|
||||
verifying tracking and safety on Go2.
|
||||
- `min_depth` / `max_depth` — depth clipping (meters). Default 0.25–10.0.
|
||||
- `control_frequency` — keep at 5 Hz (matches training).
|
||||
|
||||
## Static TF (camera mounting)
|
||||
|
||||
Override in the launch line, e.g.:
|
||||
|
||||
```bash
|
||||
roslaunch sru_nav_go2_ros1 sru_nav_go2.launch \
|
||||
odin1_x:=0.30 odin1_z:=0.22 odin1_pitch:=0.30
|
||||
```
|
||||
|
||||
This must reflect the **real** Odin1 mounting on Go2 (forward distance,
|
||||
height, downward pitch) for correct depth-to-body alignment.
|
||||
|
||||
## Safety
|
||||
|
||||
The joystick acts as a deadman switch. The robot will not move until you
|
||||
push the throttle axis (axis 4, default scale `1.0 + axis[4]`) above 0.
|
||||
After `JOYSTICK_TIMEOUT` (15 s) without a joy message the controller
|
||||
clamps the cmd_vel ratio to zero.
|
||||
|
||||
## Known caveats vs. the original deployment
|
||||
|
||||
1. Odin1's dense depth (`depth_img_competetion`) is computed host-side and is
|
||||
labelled "high computing power required" in the driver README. On Jetson
|
||||
Xavier NX this may bottleneck before the policy itself does — verify with
|
||||
`rostopic hz /odin1/depth_img_competetion` first.
|
||||
2. Odom twist frame: original code calls `convert_vel_frame` when
|
||||
`use_sim=False`, assuming world-frame twist. If Odin1 publishes twist
|
||||
already in `child_frame_id` (`odin1_base_link`) this would double-rotate.
|
||||
Verify on real hardware; if so, set `use_sim: true` in the YAML.
|
||||
3. The pretrained policy was trained on B2W kinematics. Zero-shot transfer
|
||||
to Go2 is unverified; treat the first runs as evaluation, not deployment.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Runtime parameters for sru_nav_node (Go2 + Odin1).
|
||||
# Load via: <rosparam command="load" file="$(find sru_nav_go2_ros1)/config/sru_nav.yaml"/>
|
||||
|
||||
# ---- Topics ---------------------------------------------------------------
|
||||
depth_topic: "/odin1/depth_img_competetion" # sensor_msgs/Image (32FC1, meters)
|
||||
odom_topic: "/odin1/odometry_highfreq" # nav_msgs/Odometry @ ~400 Hz (IMU rate), frame_id=odom, child=odin1_base_link
|
||||
# alt: /odin1/odometry @ ~10 Hz (SLAM rate, less drift but laggier)
|
||||
joy_topic: "/joy" # sensor_msgs/Joy (PS5-like layout)
|
||||
goal_topic: "/goal_pose" # geometry_msgs/PoseStamped
|
||||
cmd_vel_topic: "/cmd_vel" # geometry_msgs/Twist (consumed by Go2 sport mode)
|
||||
|
||||
# ---- Model files (leave empty -> auto-discover under <pkg>/models/) -------
|
||||
vae_model_path: ""
|
||||
policy_model_path: ""
|
||||
|
||||
# ---- Depth filter ---------------------------------------------------------
|
||||
min_depth: 0.25 # meters
|
||||
max_depth: 10.0 # meters
|
||||
|
||||
# ---- Control --------------------------------------------------------------
|
||||
control_frequency: 5.0 # Hz (matches training)
|
||||
# Conservative defaults for Go2 (original B2W used [1.5, 1.0, 1.0]). Tune up
|
||||
# gradually during real testing.
|
||||
policy_scale: [0.6, 0.3, 0.6] # [vx_max, vy_max, omega_max]
|
||||
|
||||
# ---- Sim flag -------------------------------------------------------------
|
||||
# When true the odom twist is treated as already in the base frame.
|
||||
use_sim: false
|
||||
|
||||
# ---- Joystick deadman -----------------------------------------------------
|
||||
# true (default, SAFE): /cmd_vel stays 0 until a /joy publisher exists AND
|
||||
# axes[4] (throttle trigger) is pushed; 15 s without
|
||||
# /joy forces a stop. Use this on real hardware.
|
||||
# false (TESTING ONLY) : skip the deadman; cmd_vel_ratio starts at 1.0 and
|
||||
# the timeout check is disabled. Useful for headless
|
||||
# / autonomous closed-loop tests with no operator.
|
||||
require_joystick: true
|
||||
@@ -0,0 +1,26 @@
|
||||
# Example waypoint list for scripts/waypoint_runner.py
|
||||
#
|
||||
# All waypoints are in the odometry frame (matches what /goal_pose expects).
|
||||
# z is optional; if 0 the main node substitutes the robot's current z.
|
||||
|
||||
frame_id: odom
|
||||
|
||||
# Arrival / timing
|
||||
arrive_threshold: 0.75 # meters (matches constants.ARRIVE_GOAL_THRESHOLD)
|
||||
settle_time: 1.5 # seconds the robot must stay within threshold
|
||||
per_goal_timeout: 60.0 # seconds before giving up on a single goal
|
||||
|
||||
# Stuck detection (script-side; no main-node changes required)
|
||||
stuck_window: 10.0 # seconds of trailing window
|
||||
stuck_displacement: 0.10 # meters; below this -> skip current goal
|
||||
|
||||
# Republish the same goal periodically to defend against missed messages.
|
||||
republish_interval: 5.0
|
||||
|
||||
# Append the script-start odom pose as a final goal after the list.
|
||||
return_home: true
|
||||
|
||||
waypoints:
|
||||
- [3.0, 0.0, 0.0]
|
||||
- [3.0, 2.0, 0.0]
|
||||
- [0.0, 2.0, 0.0]
|
||||
@@ -0,0 +1,271 @@
|
||||
# 部署指南:Go2 NX 上的 `sru_nav_go2_ros1`
|
||||
|
||||
环境前提(已确认):
|
||||
- Go2 onboard NX 已安装 **ROS 1 Noetic**
|
||||
- 已安装 **odin_ros_driver**(发布 `/odin1/*` 话题)
|
||||
- 已安装 **unitree_legged_sdk** + 一个把 `/cmd_vel` 桥接到 Go2 sport_mode 的节点
|
||||
- Odin1 depth 频率 = 10 Hz,odom_highfreq 频率 = 400 Hz
|
||||
|
||||
---
|
||||
|
||||
## 1. 把本包放进 catkin 工作空间
|
||||
|
||||
```bash
|
||||
mkdir -p ~/sru_ws/src
|
||||
ln -s /path/to/SRU_Navigation/sru_nav_go2_ros1 ~/sru_ws/src/sru_nav_go2_ros1
|
||||
cd ~/sru_ws
|
||||
catkin_make
|
||||
source devel/setup.bash
|
||||
```
|
||||
|
||||
> 模型 ONNX 文件位于 `sru_nav_go2_ros1/models/` 下(软链到 `sru-robot-deployment/.../deployment_policies/`)。
|
||||
> 部署到 Go2 NX 时如果没有原仓库,把 `vae_encoder.onnx` 与 `nav_policy.onnx` 直接拷到 `sru_nav_go2_ros1/models/` 即可。
|
||||
|
||||
---
|
||||
|
||||
## 2. 创建 Python conda 环境
|
||||
|
||||
为什么用 conda:onnxruntime / scipy 等 pip 包不污染系统 ROS python;NX (aarch64) 上 miniforge 是最稳的选择。
|
||||
|
||||
```bash
|
||||
cd ~/sru_ws/src/sru_nav_go2_ros1
|
||||
bash scripts/setup_conda_env.sh
|
||||
```
|
||||
|
||||
脚本会:
|
||||
1. 检测 `conda`(没有的话提示安装 miniforge for aarch64)
|
||||
2. 创建名为 `sru_nav` 的环境(**python=3.8**,与 Noetic 系统 python 匹配,才能复用 `rospy` / `cv_bridge`)
|
||||
3. 安装 `numpy / scipy / opencv-python / onnxruntime / rospkg / pyyaml / empy`
|
||||
4. 跑一系列 import sanity check,并尝试加载两个 ONNX 模型,打印输入输出维度
|
||||
|
||||
**GPU 加速(可选)**:标准 pip 的 `onnxruntime-gpu` 在 Jetson 上**不能用**。需要去 [NVIDIA Jetson Zoo](https://elinux.org/Jetson_Zoo#ONNX_Runtime) 下载 JetPack 匹配的 `onnxruntime_gpu-*-cp38-cp38-linux_aarch64.whl`,然后:
|
||||
|
||||
```bash
|
||||
conda activate sru_nav
|
||||
pip install ./onnxruntime_gpu-<ver>-cp38-cp38-linux_aarch64.whl
|
||||
```
|
||||
|
||||
不装 GPU 版本也能跑(CPU EP 上 5 Hz 推理在 NX 上一般够用,因为模型只有 ~28 MB)。
|
||||
|
||||
### 验证环境
|
||||
|
||||
```bash
|
||||
bash scripts/setup_conda_env.sh --check
|
||||
```
|
||||
|
||||
期望输出关键行:
|
||||
```
|
||||
[OK] numpy ...
|
||||
[OK] scipy ...
|
||||
[OK] cv2 ...
|
||||
[OK] onnxruntime ...
|
||||
ORT providers : ['CPUExecutionProvider'] # 或包含 CUDAExecutionProvider
|
||||
[OK] rospy ...
|
||||
[OK] cv_bridge ...
|
||||
```
|
||||
|
||||
如果 `rospy` / `cv_bridge` 失败:确认 `/opt/ros/noetic/lib/python3/dist-packages` 存在且 conda env 使用 python 3.8。
|
||||
|
||||
---
|
||||
|
||||
## 3. 启动流程
|
||||
|
||||
打开 4 个终端(或用 tmux)。
|
||||
|
||||
### Terminal 1 — Odin1 驱动
|
||||
|
||||
确保 `odin_ros_driver/config/control_command.yaml` 中:
|
||||
```yaml
|
||||
senddepth: 1 # 启用 dense depth
|
||||
sendodom: 1 # 启用 odom + odometry_highfreq
|
||||
```
|
||||
|
||||
```bash
|
||||
cd ../OAYN
|
||||
mamba activate neupan
|
||||
source ros_ws/devel/setup.zsh
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
sudo ntpdate -u ntp.aliyun.com
|
||||
roslaunch odin_ros_driver odin1_ros1.launch # 实际 launch 文件名以驱动包为准
|
||||
```
|
||||
|
||||
### Terminal 2 — Go2 cmd_vel 桥
|
||||
|
||||
你现有的 unitree_legged_sdk 桥接节点,它订阅 `/cmd_vel`,下发到 Go2 sport_mode。
|
||||
|
||||
```bash
|
||||
mamba activate sru_nav
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
source devel/setup.zsh
|
||||
rosrun unitree_control unitree_vel_controller __name:=vel_to_sdk
|
||||
```
|
||||
|
||||
### Terminal 3 — SRU 导航节点(本包)
|
||||
|
||||
```bash
|
||||
mamba activate sru_nav
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
cd src/sru_nav_go2_ros1
|
||||
bash scripts/launch_sru_nav.sh
|
||||
# require_joystick=true,必须接手柄,axes[4] 推油门,15 s 看护
|
||||
|
||||
bash scripts/launch_sru_nav.sh --no-deadman
|
||||
# require_joystick=false,cmd_vel_ratio 直接 1.0
|
||||
# 发一个 /goal_pose,policy 就会驱动 /cmd_vel
|
||||
```
|
||||
|
||||
`launch_sru_nav.sh` 自动做:source ROS → source catkin_ws → conda activate sru_nav → 把 `/opt/ros/noetic/lib/python3/dist-packages` 注入 `PYTHONPATH` → `roslaunch sru_nav_go2_ros1 sru_nav_go2.launch`。
|
||||
|
||||
如果手柄 `/joy` 已经在别处启动:
|
||||
```bash
|
||||
bash scripts/launch_sru_nav.sh --no-joy
|
||||
```
|
||||
|
||||
如果不需要静态 TF(你自己发了 `base_link → odin1_base_link`):
|
||||
```bash
|
||||
bash scripts/launch_sru_nav.sh --no-tf
|
||||
```
|
||||
|
||||
### Terminal 4 — 发目标 / 监控
|
||||
|
||||
```bash
|
||||
# 推一个 3 m 前方的目标(odom 帧)
|
||||
mamba activate sru_nav
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
source devel/setup.zsh
|
||||
rostopic pub /goal_pose geometry_msgs/PoseStamped \
|
||||
"{header: {frame_id: 'odom'},
|
||||
pose: {position: {x: 3.0, y: 0.0, z: 0.0}, orientation: {w: 1.0}}}" --once
|
||||
|
||||
# 检查输出
|
||||
rostopic hz /cmd_vel # 应稳定 ~5 Hz
|
||||
rostopic echo /cmd_vel -n 5
|
||||
```
|
||||
|
||||
# 或者发布连续waypoints
|
||||
```bash
|
||||
mamba activate sru_nav
|
||||
export ROS_MASTER_URI=http://localhost:11311
|
||||
export ROS_HOSTNAME=localhost
|
||||
export ROS_IP=127.0.0.1
|
||||
source devel/setup.zsh
|
||||
cd src/sru_nav_go2_ros1
|
||||
rosrun sru_nav_go2_ros1 waypoint_runner.py \
|
||||
--file config/waypoints_example.yaml
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 首跑前的 sanity check 命令
|
||||
|
||||
```bash
|
||||
# 4.1 频率检查
|
||||
rostopic hz /odin1/depth_img_competetion # 应 ~10 Hz
|
||||
rostopic hz /odin1/odometry_highfreq # 应 ~400 Hz
|
||||
|
||||
# 4.2 深度数据合理性
|
||||
rostopic echo /odin1/depth_img_competetion -n 1 | head -20
|
||||
# 关注 encoding:"32FC1", height/width, 不全为 0
|
||||
|
||||
# 4.3 odom frame
|
||||
rostopic echo /odin1/odometry_highfreq -n 1 | head -20
|
||||
# 关注 header.frame_id="odom", child_frame_id="odin1_base_link"
|
||||
|
||||
# 4.4 节点状态
|
||||
rosnode info /sru_nav_node
|
||||
rostopic list | grep sru_nav
|
||||
|
||||
# 4.5 关闭 Go2 cmd_vel 桥,单跑导航节点空载,看推理输出
|
||||
rostopic echo /cmd_vel
|
||||
# 拖动 Odin1 / 发个 /goal_pose,看 /cmd_vel 是否产生非零有界数值
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 如何判断 odom twist 的坐标系?
|
||||
|
||||
**这是上机前必须确认的**。理论上 `child_frame_id="odin1_base_link"` 暗示 twist 是 body frame,但很多 SLAM 实现仍在 world frame 输出 twist——必须实测。
|
||||
|
||||
### 方法 A:静止判断(最快)
|
||||
|
||||
让 Odin1 完全静止:
|
||||
```bash
|
||||
rostopic echo -n 20 /odin1/odometry_highfreq | grep -A2 twist
|
||||
```
|
||||
所有 `linear.*` 和 `angular.*` 都应该接近 0。这一步只能排除"非零偏置 bug",分不出 world/body。
|
||||
|
||||
### 方法 B:纯前进运动
|
||||
|
||||
让 Go2 静止站立,**手动**将 Odin1 沿其镜头方向(body +X)匀速推进 1 米,过程录制:
|
||||
```bash
|
||||
rosbag record -O /tmp/odom_test.bag /odin1/odometry_highfreq
|
||||
```
|
||||
然后:
|
||||
```bash
|
||||
rosbag play /tmp/odom_test.bag
|
||||
rqt_plot /odin1/odometry_highfreq/twist/twist/linear/x:y
|
||||
```
|
||||
- 如果 `linear.x` 是显著正值、`linear.y` 几乎 0 → **body frame**(已经是 base 系)
|
||||
- 如果 `linear.x` 与 `linear.y` 数值与机体当前 yaw 有关(旋转 Odin1 朝向再做同样测试,结果改变)→ **world frame**
|
||||
|
||||
### 方法 C:旋转判断(推荐,更确定)
|
||||
|
||||
把 Odin1 朝任意非零方向放置(比如绕 Z 转 90°),再沿 body +X 推进:
|
||||
- **body frame**:无论朝向如何,`linear.x` 总是正、`linear.y` ≈ 0
|
||||
- **world frame**:朝向 +Y 推进时 `linear.y` 是正、`linear.x` ≈ 0
|
||||
|
||||
### 方法 D:对比 dt 数值导数
|
||||
|
||||
```python
|
||||
# 对位置做数值导数,与 twist 对比
|
||||
import rosbag, numpy as np
|
||||
bag = rosbag.Bag('/tmp/odom_test.bag')
|
||||
ts, pos, twist_lin = [], [], []
|
||||
for _, msg, _ in bag.read_messages(topics=['/odin1/odometry_highfreq']):
|
||||
ts.append(msg.header.stamp.to_sec())
|
||||
pos.append([msg.pose.pose.position.x, msg.pose.pose.position.y, msg.pose.pose.position.z])
|
||||
twist_lin.append([msg.twist.twist.linear.x, msg.twist.twist.linear.y, msg.twist.twist.linear.z])
|
||||
ts, pos, twist_lin = map(np.array, (ts, pos, twist_lin))
|
||||
vel_world = np.diff(pos, axis=0) / np.diff(ts)[:, None]
|
||||
print('vel_world (sample):', vel_world[100])
|
||||
print('twist_lin (sample):', twist_lin[100])
|
||||
# 若两者数值在世界系几乎一致 → twist 是 world frame
|
||||
# 若 twist_lin 与 vel_world 大小相同但方向旋转 → twist 是 body frame
|
||||
```
|
||||
|
||||
### 根据结果配置本节点
|
||||
|
||||
- twist **是 world frame**:保持 `use_sim: false`(节点会按机体 quaternion 反旋转到 base 系,与原 DLIO 部署一致)。
|
||||
- twist **是 body frame**:在 `config/sru_nav.yaml` 把 `use_sim` 设为 `true`,节点会直接透传 twist。
|
||||
|
||||
---
|
||||
|
||||
## 6. 常见问题
|
||||
|
||||
| 现象 | 排查 |
|
||||
|---|---|
|
||||
| `pip` 报 `SSL: CERTIFICATE_VERIFY_FAILED ... certificate is not yet valid` | **系统时钟回退了**(Jetson 无 RTC 电池时常见)。`date` 看一下,然后 `sudo timedatectl set-ntp true && sudo systemctl restart systemd-timesyncd`,或离线 `sudo date -s "2026-05-28 14:55:00" && sudo hwclock --systohc`。`setup_conda_env.sh` 已加前置检测。 |
|
||||
| conda 报 `Unexpected error writing token file ... aau_token_host` | anaconda.org 遥测 bug,无害。脚本里 `export ANACONDA_ANON_USAGE=false` 已静音。 |
|
||||
| pip 太慢 / 拉不动 | `setup_conda_env.sh` 默认走清华源;若要换 `PIP_INDEX_URL=... bash scripts/setup_conda_env.sh`。 |
|
||||
| 节点启动后 `Odometry not ready, skipping depth callback.` | `rostopic hz /odin1/odometry_highfreq` 是否在跑?frame_id 是否正确? |
|
||||
| `/cmd_vel` 全是 0 | 手柄 deadman——`axes[4]` 必须推过 0;或 15 s 超时。看 `cmd_vel_ratio` 日志。 |
|
||||
| Twist 数值剧烈震荡 | 1) `policy_scale` 太大;2) odom twist 坐标系判错(world↔body 弄反);3) depth NaN 没被过滤 |
|
||||
| `cv_bridge` import 失败 | conda env 必须是 python 3.8;并且 `PYTHONPATH` 已包含 `/opt/ros/noetic/lib/python3/dist-packages` |
|
||||
| 推理速度跟不上 5 Hz | `rostopic hz /cmd_vel`;用 `nvtop`/`top` 看 NX 满载情况;考虑装 JetPack onnxruntime-gpu wheel |
|
||||
| Goal 发出后立即被忽略 | `/goal_pose` 的 `frame_id` 必须等于 `/odin1/odometry_highfreq` 的 `header.frame_id`(默认 `odom`) |
|
||||
|
||||
---
|
||||
|
||||
## 7. 紧急停止
|
||||
|
||||
- 手柄按下 `BUTTON_ABORT`(默认 button index 9) → 立刻发零速、放弃当前目标
|
||||
- 直接 `Ctrl+C` 杀掉 `sru_nav_node` → `/cmd_vel` 不再有发布者,Go2 桥应自动归零(依你的桥行为)
|
||||
- 关闭电源开关(终极手段)
|
||||
@@ -0,0 +1,441 @@
|
||||
# 把 SRU 导航策略移植到 Odin1 + ROS1 的完整复现指南
|
||||
|
||||
> 从论文 *Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation via End-to-End Reinforcement Learning* 与配套开源仓库
|
||||
> [`sru-project-website`](https://michaelfyang.github.io/sru-project-website/) 出发,把 SRU 端到端导航策略部署到 **Odin1 深度相机 + ROS1 Noetic + 任意能消费 `geometry_msgs/Twist`(`/cmd_vel`)的机器人**(默认硬件参考为 Unitree Go2)。本仓库 `sru_nav_go2_ros1` 即为此目标的产物。
|
||||
>
|
||||
> **English version**: see `PORTING_GUIDE_EN.md`.
|
||||
|
||||
---
|
||||
|
||||
## 0. 这份文档是什么 / 不是什么
|
||||
|
||||
**是**:一份「移植决策记录 + AI 复刻 prompt + 自动验收脚本」的三合一指南。读完即可:
|
||||
|
||||
1. 知道我们为什么这样改、改了哪些点;
|
||||
2. 用一个 slash command 让 AI agent(Cascade / Claude Code 等)从开源仓库与论文出发,**自动重新生成本仓库**;
|
||||
3. 用一个脚本一键校验生成结果是否合格。
|
||||
|
||||
**不是**:算法原理讲解(请直接读论文与原始代码仓)。
|
||||
|
||||
**适用读者**:
|
||||
- 已具备 Ubuntu + ROS1 + Python/conda 基本使用能力;
|
||||
- 持有 Unitree Go2(或任何能订阅 `/cmd_vel` 的腿足/轮式机器人)+ Odin1 深度相机;
|
||||
- 想在自己机器人上跑 SRU,或想验证「AI agent 是否能从论文+开源代码复刻一个真机部署包」。
|
||||
|
||||
> 0 门槛承诺:除上述前置技能外,所有路径、IP、机器人型号、摄像头型号都设计为**通过环境变量或参数覆盖**,不用改源码。
|
||||
|
||||
---
|
||||
|
||||
## 1. 上游来源
|
||||
|
||||
| 资产 | 链接 / 路径 | 在本移植里的角色 |
|
||||
|---|---|---|
|
||||
| 论文 | *Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation via End-to-End Reinforcement Learning* | 解释观测/动作空间、奖励、网络结构(VAE 深度编码器 + LSTM-SRU + actor head) |
|
||||
| 项目主页 | <https://michaelfyang.github.io/sru-project-website/> | 索引仓库、视频、论文 |
|
||||
| `sru-navigation-learning` | RL 训练代码(rsl_rl 风格)。给出 PPO/MDPO 算法、reward terms、observation manager | 用于核对 **reward 设计、动作 squash、观测层次**,并取得 ONNX 导出脚本 |
|
||||
| `sru-navigation-sim` | IsaacLab 环境,含 B2W / AOW 训练配置 | 取得 `policy_scaling`、随机化范围、观测形状(depth `64×5×8`)等关键数字 |
|
||||
| `sru-robot-deployment` | 原作者在 Unitree B2W + ZED-X 上的真机部署 | **本仓库直接对照重写的对象**:原版用 PyTorch + DLIO odom + 自研 SDK 桥;本仓库换成 ONNX + Odin1 odom + Go2 桥 |
|
||||
| `sru-pytorch-spatial-learning` | SRU/LSTM-SRU 单元的 PyTorch 实现 | 解释 RNN 隐状态形状(`rnn_hidden_size=512, num_layers=1`),导出 ONNX 时的状态展开方式 |
|
||||
| `sru-depth-pretraining` | VAE depth encoder 的预训练 | 取得 `vae_encoder.onnx` 的输入形状(`H×W` 深度图归一化后单通道)与潜变量维度 |
|
||||
|
||||
如果你不打算复刻、只想跑:把训练完得到的两个 onnx(`vae_encoder.onnx` + `nav_policy.onnx`)丢到 `sru_nav_go2_ros1/models/`,跳到 §6。
|
||||
|
||||
---
|
||||
|
||||
## 2. 移植目标矩阵
|
||||
|
||||
| 维度 | 原作者部署 (`sru-robot-deployment`) | 本仓库 (`sru_nav_go2_ros1`) | 抽象后接口 |
|
||||
|---|---|---|---|
|
||||
| 机器人 | Unitree **B2W**(轮足) | Unitree **Go2**(纯腿足) | 任何订阅 `/cmd_vel` (`geometry_msgs/Twist`, body frame) 的机器人 |
|
||||
| 深度传感 | ZED-X | **Odin1**(`32FC1` depth, ~10 Hz) | `~depth_topic` (`sensor_msgs/Image`, 32FC1, 米) |
|
||||
| 里程计 | DLIO(自研 LIO) | Odin1 `odometry_highfreq` | `~odom_topic` (`nav_msgs/Odometry`, world frame) |
|
||||
| 推理后端 | PyTorch JIT | **ONNX Runtime** | `models/{vae_encoder,nav_policy}.onnx` |
|
||||
| 计算平台 | x86 工控机 | **Jetson Orin NX (aarch64) + conda py3.8** | 任何 Linux + ROS1 Noetic + conda |
|
||||
| 控制频率 | ~10 Hz | **5 Hz**(与训练一致;Odin depth ~10 Hz 自然降采样) | `~control_frequency` |
|
||||
| 操作员手柄 | PS5 PerceptiveNavigationSE2 | 同 PS5 mapping,**新增 `require_joystick: false`** 头模式 | `--no-deadman` / yaml `require_joystick` |
|
||||
| 安装与启动 | rosinstall 全家桶 | **`setup_conda_env.sh` + `launch_sru_nav.sh`** 两脚本 | env vars `ENV_NAME / ROS_DISTRO / CATKIN_WS` 全部可覆盖 |
|
||||
|
||||
---
|
||||
|
||||
## 3. 核心移植决策(逐项说明动机与对照位置)
|
||||
|
||||
### 3.1 推理:PyTorch → ONNX Runtime
|
||||
|
||||
- **动机**:Jetson Orin NX 上装 PyTorch + cv_bridge + onnxruntime 的依赖网很容易爆;onnxruntime 单文件加载、CPU/GPU EP 切换简单;ARM wheel 现成。
|
||||
- **接口**:`@/sru_nav_go2_ros1/src/sru_nav_go2/model.py` 实现 `LearningModel`,分别加载 `vae_encoder.onnx`(深度→latent)与 `nav_policy.onnx`(latent + 状态向量 + 上一动作 + LSTM hidden → action mean + 新 hidden)。
|
||||
- **隐状态约定**:训练侧 `rnn_hidden_size=512, num_layers=1`;导出 ONNX 时把 `(h, c)` 作为输入输出张量,本端在每帧之间显式持有;`reset_hidden_state` 对应训练里 `is_first` 标志。
|
||||
- **action squash**:网络已包含 `tanh`,输出在 `(-1, 1)`。本端再乘 `policy_scale=[vx_max, vy_max, ω_max]`(默认 `[0.6, 0.3, 0.6]`)得到 SI 单位速度。
|
||||
|
||||
### 3.2 观测层:Odin1 替代 ZED-X + DLIO
|
||||
|
||||
- **深度图**:Odin1 发布 `sensor_msgs/Image` (`32FC1`,单位米)。`@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:209-225` 里做:
|
||||
1. `cv_bridge.imgmsg_to_cv2(passthrough)`;
|
||||
2. `nan_to_num(nan=0, posinf=2*max_depth, neginf=0)`;
|
||||
3. 截断到 `[min_depth, max_depth] = [0.25, 10.0] m`,超界置 0。
|
||||
- **里程计帧约定**:Odin1 odom 的 twist 是 **world frame**。我们在 `odom_callback` 里用机体四元数把它反旋到 body frame(与训练对齐)。如果你的 odom 已经是 body frame,把 `use_sim: true` 透传即可(`@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:189-197`)。
|
||||
- **goal 帧约定**:`/goal_pose.header.frame_id` 必须等于 odom 的 `frame_id`(默认 `odom`),否则节点直接拒绝 — 这是为了防止操作员误把机体系坐标当成 odom 系发出去。
|
||||
|
||||
### 3.3 动作下发:直接 `/cmd_vel`
|
||||
|
||||
- 原作者在 B2W 上自带 SDK 桥;Go2 直接用 unitree_legged_sdk 写一个订阅 `/cmd_vel` 的小节点(与本仓库分离)即可。本包**不**绑定具体桥。
|
||||
- `policy_scale` 默认 `[0.6, 0.3, 0.6]` 比训练侧 `[1.5, 1.0, 1.0]` 保守一半多,给真机留余量;训练时已经做过 `Uniform(0.6, 1.2)` 的 scale 随机化,所以网络对运行时缩放鲁棒。
|
||||
|
||||
### 3.4 安全:手柄 deadman 双模
|
||||
|
||||
| 模式 | 触发 | 行为 |
|
||||
|---|---|---|
|
||||
| 默认 (`require_joystick=true`) | 实机部署 | `cmd_vel_ratio=0`,必须 `/joy` 持续发布且 `axes[4]` 推到正才有速度;`>15 s` 无 joy → 强制归零 |
|
||||
| 测试 (`require_joystick=false`) | `--no-deadman` 或 yaml 改 false | 起步即 `cmd_vel_ratio=1.0`,无 joy 也跑。**只在抬轮 / 仿真 / 空旷场地**用 |
|
||||
|
||||
代码位置:`@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:118-121, 272-287`。
|
||||
|
||||
### 3.5 安装层:conda + 系统 ROS 共生
|
||||
|
||||
Jetson Orin NX 出厂有 ROS Noetic(系统 python3.8 + cv_bridge.so);同时我们要 onnxruntime / opencv / numpy 等只在 conda env 里好装。两个世界要打通:
|
||||
|
||||
1. **PYTHONPATH 注入**:`/opt/ros/noetic/lib/python3/dist-packages` 加到 conda python 的搜索路径,使 `rospy / cv_bridge / sensor_msgs / tf2_ros` 可 import。
|
||||
2. **shebang 锁定**:catkin_make 时必须 `-DPYTHON_EXECUTABLE=$(which python3)` **在 conda env 已激活** 状态下跑,否则 `devel/lib/.../sru_nav_node` 的 `#!` 会指向 `/usr/bin/python3`,import onnxruntime 失败。
|
||||
3. **ABI 冲突修复**:conda env 自带的 `libffi.so.7` 和系统 `libp11-kit.so.0` 版本符号不兼容,导致 `cv_bridge` 调 OpenCV 时崩溃(`undefined symbol: ffi_type_pointer, version LIBFFI_BASE_7.0`)。`launch_sru_nav.sh` 自动 `LD_PRELOAD=/lib/aarch64-linux-gnu/libffi.so.7` 提前加载系统 libffi。
|
||||
4. **rospy 隐性依赖**:`netifaces` / `defusedxml` 在系统 python 里靠 apt 提供,conda env 里要 pip 装。`setup_conda_env.sh` 已加进默认列表。
|
||||
5. **时钟检查**:Jetson 无 RTC 电池常导致系统时间回退,pip TLS 拒接握手。脚本里前置 `date` 检测并提示 `ntpdate / timedatectl`。
|
||||
|
||||
完整自动化脚本:`@/sru_nav_go2_ros1/scripts/setup_conda_env.sh` + `@/sru_nav_go2_ros1/scripts/launch_sru_nav.sh`。
|
||||
|
||||
### 3.6 故意删减项
|
||||
|
||||
| 训练里有的东西 | 部署里去掉的原因 |
|
||||
|---|---|
|
||||
| Heightmap / heightscan critic | Go2 不带 LiDAR/heightmap,需要的话外部话题再加 |
|
||||
| 距离/动量等 critic 通道 | critic 仅训练用,推理只跑 actor head |
|
||||
| MDPO / distillation 双 actor-critic 互蒸馏 | 训练阶段优化器结构,与导出后的 actor 无关 |
|
||||
| 训练时 reward terms 计算 | 部署不需要计算 reward |
|
||||
| Action scale randomization (`Uniform(0.6, 1.2)`) | 部署是固定缩放;网络已经被训练成对该范围鲁棒 |
|
||||
|
||||
---
|
||||
|
||||
## 4. 文件清单与职能
|
||||
|
||||
```
|
||||
sru_nav_go2_ros1/
|
||||
├── CMakeLists.txt # catkin 包定义;catkin_python_setup() + install scripts
|
||||
├── package.xml # 依赖:rospy, sensor_msgs, geometry_msgs, nav_msgs, cv_bridge, tf2_ros
|
||||
├── setup.py # 把 src/sru_nav_go2 装成 python 包
|
||||
├── README.md
|
||||
├── config/
|
||||
│ ├── sru_nav.yaml # 运行时全部 ROS 参数;唯一应该被用户改的文件
|
||||
│ └── waypoints_example.yaml # 多目标巡航示例(odom 系列点)
|
||||
├── launch/
|
||||
│ └── sru_nav_go2.launch # joy_node + static_tf + sru_nav_node
|
||||
├── models/
|
||||
│ ├── vae_encoder.onnx # 训练侧 export_onnx 产物
|
||||
│ └── nav_policy.onnx
|
||||
├── scripts/
|
||||
│ ├── setup_conda_env.sh # 创建 sru_nav env,装 onnxruntime/cv2/netifaces…
|
||||
│ ├── launch_sru_nav.sh # 一键启动 wrapper(含 LD_PRELOAD / PYTHONPATH 修复)
|
||||
│ ├── sru_nav_node # ROS 节点入口(catkin 安装时拷到 devel/lib/...)
|
||||
│ └── waypoint_runner.py # 顺序发 /goal_pose
|
||||
├── src/sru_nav_go2/
|
||||
│ ├── constants.py # 所有训练对齐常量(控制频率、轴键映射、scale 等)
|
||||
│ ├── model.py # ONNX Runtime 封装:VAE encoder + LSTM-SRU policy
|
||||
│ ├── navigation_policy_node.py # 主节点:odom/depth/joy/goal 回调 + cmd_vel 输出
|
||||
│ ├── utils.py # 四元数<->旋转、reproject 等数学小工具
|
||||
│ ├── visualization.py # rviz marker(目标向量、moving_goal、waypoint)
|
||||
│ └── waypoint_manager.py # 录制/回放 waypoint 列表
|
||||
└── docs/
|
||||
├── DEPLOY_GO2_NX.md # 部署到 NX 的实战记录
|
||||
└── PORTING_GUIDE.md # ← 你正在读的文件
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 用 AI Agent 自动复刻本仓库
|
||||
|
||||
我们提供 **同一份移植 prompt 的三种调用形式**(内容等价,挑顺手的用):
|
||||
|
||||
| 入口 | 适用工具 | 启动方式 |
|
||||
|---|---|---|
|
||||
| `.windsurf/workflows/port-sru-to-ros.md` | Cascade(Windsurf IDE) | 在 Cascade 聊天框里输 `/port-sru-to-ros` |
|
||||
| `.claude/commands/port-sru-to-ros.md` | Claude Code (CLI / IDE 插件) | `claude` 启动后 `/port-sru-to-ros` |
|
||||
| `docs/PORTING_PROMPT.md` | 任意支持自定义 prompt 的 agent(Cursor、Continue、Aider…) | 把整篇内容粘进系统提示 / 任务描述 |
|
||||
|
||||
三个文件由同一份「**真理 prompt**」生成,差异只在启动头与文件路径约定。下面是完整的 prompt 内容(放在 `.windsurf/workflows/port-sru-to-ros.md` 里以 frontmatter 起头)。
|
||||
|
||||
> ⚠️ **可重复性边界**:现役 LLM 在生成 ~1500 LoC 的 ROS 移植代码时,单次成功率不是 100%。我们用 **分阶段 workflow** 把任务切成 6 步,每步都有可 grep 的验收点;任意一步偏题立刻回滚重试,比一次性长 prompt 的成功率高一个数量级。
|
||||
|
||||
### 5.1 分阶段 workflow 概览
|
||||
|
||||
| 阶段 | 输入 | 输出 | 验收 |
|
||||
|---|---|---|---|
|
||||
| 1. **勘查** | 上游 5 个仓库 + 论文 | 摘要 `notes/upstream_recon.md`:算法、观测/动作、I/O 形状、训练超参 | 文件存在且包含网络层数、obs dims、policy_scale |
|
||||
| 2. **抽取推理路径** | `sru-navigation-learning` 的 export_onnx | `models/vae_encoder.onnx`、`models/nav_policy.onnx`、`docs/IO_SPEC.md` | onnxruntime 可加载,输入/输出名/形状记录 |
|
||||
| 3. **生成 ROS 包骨架** | 上一步 IO_SPEC | `package.xml / CMakeLists.txt / setup.py / launch/ / config/sru_nav.yaml` | `catkin_make` 通过 |
|
||||
| 4. **移植节点逻辑** | 原 `sru-robot-deployment` 节点 + IO_SPEC | `src/sru_nav_go2/{constants,model,utils,visualization,waypoint_manager,navigation_policy_node}.py` + `scripts/sru_nav_node` | 节点能 `roslaunch` 起来不 crash |
|
||||
| 5. **写部署脚本** | 目标 platform 信息 | `scripts/setup_conda_env.sh` + `scripts/launch_sru_nav.sh` | 在干净 env 上跑通 §6 验收命令 |
|
||||
| 6. **文档与验收** | 全部产物 | `README.md / docs/DEPLOY_*.md / scripts/verify_port.sh` | `bash scripts/verify_port.sh` 全绿 |
|
||||
|
||||
### 5.2 通用 prompt(与三个入口文件一致的核心内容)
|
||||
|
||||
```text
|
||||
你是一名熟悉 ROS1 Noetic、conda、ONNX Runtime 与 PyTorch 的高级工程师。
|
||||
|
||||
【任务】
|
||||
从以下上游资料出发,生成一个名为 `sru_nav_go2_ros1` 的 catkin 包,
|
||||
把论文《Spatially-Enhanced Recurrent Memory for Long-Range Mapless
|
||||
Navigation via End-to-End Reinforcement Learning》提出的端到端导航策略
|
||||
部署到 Odin1 深度相机 + ROS1 Noetic + 任意能消费
|
||||
`geometry_msgs/Twist (/cmd_vel)` 的机器人上。
|
||||
|
||||
【上游资料】
|
||||
- 论文 PDF(按用户提供的路径读取,例如 ./2506.05997v2.pdf)
|
||||
- 项目主页 https://michaelfyang.github.io/sru-project-website/
|
||||
- 仓库(按用户工作区下子文件夹):
|
||||
sru-navigation-learning — RL 训练 + ONNX 导出
|
||||
sru-navigation-sim — IsaacLab 环境与训练配置
|
||||
sru-robot-deployment — 原作者 B2W+ZED-X 真机部署(直接对标重写)
|
||||
sru-pytorch-spatial-learning — SRU/LSTM-SRU 单元
|
||||
sru-depth-pretraining — VAE depth encoder 预训练
|
||||
- 已存在的 onnx 模型(如有):models/{vae_encoder,nav_policy}.onnx
|
||||
|
||||
【硬约束】
|
||||
1. 目标传感器固定为 Odin1。深度话题默认 `/odin1/depth_img_competetion`
|
||||
(sensor_msgs/Image, 32FC1, 单位米);里程计默认
|
||||
`/odin1/odometry_highfreq` (nav_msgs/Odometry, world frame)。
|
||||
2. 控制输出固定为 `/cmd_vel` (geometry_msgs/Twist, body frame),由调用方
|
||||
桥接到具体机器人;本包不实现机器人 SDK 桥。
|
||||
3. 推理后端只能用 onnxruntime(不引入 PyTorch 运行时依赖)。
|
||||
4. 必须支持 conda env (默认 `sru_nav`, py3.8) 与系统 ROS 共生:
|
||||
- PYTHONPATH 注入 /opt/ros/<DISTRO>/lib/python3/dist-packages
|
||||
- 启动脚本 LD_PRELOAD 系统 libffi 修复 cv_bridge 的 ABI 冲突
|
||||
- catkin_make 时锁定 PYTHON_EXECUTABLE 为 conda python
|
||||
5. 所有路径、env、distro、机器人型号必须可被环境变量或 ROS 参数覆盖;
|
||||
不得在源码里硬写 `/home/<user>` 一类 path。
|
||||
6. 保留训练对齐的全部数值(control_frequency=5Hz, rnn_hidden=512,
|
||||
policy_scale 默认 [0.6,0.3,0.6],joystick axis 映射等)。
|
||||
7. 关键安全机制:手柄 deadman + 15 s 超时;提供 `require_joystick:
|
||||
false` 旁路开关,但默认必须为 true。
|
||||
|
||||
【输出文件清单】(缺一不可)
|
||||
package.xml, CMakeLists.txt, setup.py
|
||||
launch/sru_nav_go2.launch
|
||||
config/sru_nav.yaml, config/waypoints_example.yaml
|
||||
scripts/setup_conda_env.sh, scripts/launch_sru_nav.sh,
|
||||
scripts/sru_nav_node, scripts/waypoint_runner.py, scripts/verify_port.sh
|
||||
src/sru_nav_go2/{__init__.py, constants.py, model.py, utils.py,
|
||||
visualization.py, waypoint_manager.py,
|
||||
navigation_policy_node.py}
|
||||
docs/DEPLOY.md, docs/PORTING_GUIDE.md (中文), docs/PORTING_GUIDE_EN.md
|
||||
models/README.md (说明从训练侧导出 onnx 的步骤)
|
||||
|
||||
【工作流程】(必须按顺序,每步完成后 self-check 再进下一步)
|
||||
Step 1 — 勘查上游:读取仓库与论文,列出网络架构、观测维度、动作空间、
|
||||
rsl_rl 算法配置、reward 列表,输出到 notes/upstream_recon.md。
|
||||
Step 2 — IO 规范化:在训练仓里找到 export_onnx 入口,记录 vae_encoder
|
||||
与 nav_policy 的 input/output 名与 shape,写到 docs/IO_SPEC.md。
|
||||
Step 3 — 生成 catkin 骨架并 `catkin_make` 验证。
|
||||
Step 4 — 实现节点:以 sru-robot-deployment 的 node 为模板,
|
||||
替换传感器话题、剥离非 Odin 依赖、把 PyTorch 调用换成 onnxruntime。
|
||||
Step 5 — 编写两份脚本(setup_conda_env.sh / launch_sru_nav.sh),
|
||||
覆盖 §硬约束 4 的全部点。
|
||||
Step 6 — 生成 verify_port.sh:检查包结构、shebang 指向、ONNX 推理、
|
||||
rostopic 列表、yaml 必填字段。
|
||||
|
||||
【验收标准】(用户会跑 verify_port.sh 与下述命令)
|
||||
1. `catkin_make` 在干净 catkin_ws 下 0 warning 0 error。
|
||||
2. `bash scripts/setup_conda_env.sh --check` 全部通过。
|
||||
3. `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node` 指向
|
||||
conda env 的 python,不是 /usr/bin/python3。
|
||||
4. `roslaunch sru_nav_go2_ros1 sru_nav_go2.launch require_joystick:=false`
|
||||
起来后看到 `Navigation policy node is ready.` 且不刷错误。
|
||||
5. 用 `rostopic pub` 发任意 odom + 一帧 32FC1 depth + 一个 goal_pose,
|
||||
`/cmd_vel` 应输出非零 Twist。
|
||||
6. `bash scripts/verify_port.sh` 全部 PASS。
|
||||
|
||||
【回答方式】
|
||||
- 严禁直接生成 1000+ 行的单条回复;按 Step 拆分,每步先汇报计划再写文件。
|
||||
- 每步结束后跑相应 self-check,把命令与输出贴回;自检失败立即修复。
|
||||
- 如果上游仓库找不到某文件,明确报告并暂停,不得编造接口。
|
||||
```
|
||||
|
||||
完整可直接执行的版本见 `@/.windsurf/workflows/port-sru-to-ros.md` 与 `@/.claude/commands/port-sru-to-ros.md`。
|
||||
|
||||
### 5.3 怎样验证「这份 prompt 真的能复刻本仓库」?
|
||||
|
||||
把上述 workflow 在一台干净机器上跑完,最后做:
|
||||
|
||||
```bash
|
||||
diff -r --exclude=__pycache__ --exclude=.git \
|
||||
./generated_sru_nav_go2_ros1/ \
|
||||
./sru_nav_go2_ros1/
|
||||
```
|
||||
|
||||
预期:**结构完全一致;逐行 diff 应集中在注释 / 字面量顺序上,不应在数值常量、话题名、函数签名上有差异**。如果出现关键差异(例如 `policy_scale` 改成 `[1, 1, 1]`、忘记 LD_PRELOAD),说明 agent 没遵 prompt,回到对应 Step 重启。
|
||||
|
||||
---
|
||||
|
||||
## 6. 个性化与 0 门槛使用
|
||||
|
||||
所有「可能因人而异」的点都开成参数。最常见的三类:
|
||||
|
||||
### 6.1 路径
|
||||
|
||||
| 参数 | 默认 | 覆盖方式 |
|
||||
|---|---|---|
|
||||
| catkin workspace | `$HOME/code/odin_sru_nav` | `CATKIN_WS=/path bash scripts/launch_sru_nav.sh` |
|
||||
| conda env 名 | `sru_nav` | `ENV_NAME=my_env bash scripts/setup_conda_env.sh` |
|
||||
| ROS distro | `noetic` | `ROS_DISTRO=melodic bash scripts/launch_sru_nav.sh`(仅 py3 兼容版本) |
|
||||
| pip 镜像 | 清华源 | `PIP_INDEX_URL=https://pypi.org/simple bash scripts/setup_conda_env.sh` |
|
||||
|
||||
### 6.2 话题与帧
|
||||
|
||||
改 `config/sru_nav.yaml` 里这些字段,**不用改源码**:
|
||||
|
||||
```yaml
|
||||
depth_topic: "/your/depth" # sensor_msgs/Image (32FC1, meters)
|
||||
odom_topic: "/your/odometry" # nav_msgs/Odometry, world frame
|
||||
joy_topic: "/joy"
|
||||
goal_topic: "/goal_pose"
|
||||
cmd_vel_topic: "/cmd_vel"
|
||||
```
|
||||
|
||||
### 6.3 不同机器人
|
||||
|
||||
只需提供「订阅 `/cmd_vel` 的桥」。仓库**完全不感知机器人型号**。常见替换:
|
||||
|
||||
- Unitree Go2:用 `unitree_legged_sdk` 写 50 行的 cmd_vel→sport_mode 桥;
|
||||
- Unitree B2 / B2W:用官方 ROS1 桥;
|
||||
- Spot:`spot_ros` + `cmd_vel`;
|
||||
- 任何 ROS 仿真:直接订阅 `/cmd_vel`。
|
||||
|
||||
唯一需要改的可能是 TF:默认 launch 里发 `base_link → odin1_base_link` 的静态 TF,参数 `odin1_x / y / z / roll / pitch / yaw`,按你的相机安装位置改。
|
||||
|
||||
### 6.4 检查环境(你提到要写进文档与 prompt 的部分)
|
||||
|
||||
**第一次部署时建议跑一遍**:
|
||||
|
||||
```bash
|
||||
# 1) OS / ROS
|
||||
lsb_release -a # Ubuntu 20.04 推荐 (Noetic 配套)
|
||||
echo $ROS_DISTRO # 应为 noetic
|
||||
which roscore # /opt/ros/noetic/bin/roscore
|
||||
|
||||
# 2) Conda
|
||||
conda --version # ≥ 4.10
|
||||
conda env list | grep -E "sru_nav|base"
|
||||
|
||||
# 3) 时钟(Jetson 无 RTC 电池常坏)
|
||||
date # 确认是真实当前时间,否则 pip TLS 会拒接
|
||||
|
||||
# 4) 网络
|
||||
ping -c 2 8.8.8.8 || echo "WARN: no internet, pip will fail"
|
||||
|
||||
# 5) 硬件
|
||||
ls /dev/input/js* 2>/dev/null || echo "INFO: no joystick — use --no-deadman for headless tests"
|
||||
rostopic list 2>/dev/null | grep odin1 || echo "WARN: Odin1 driver not running"
|
||||
```
|
||||
|
||||
`scripts/verify_port.sh` 里把这一段固化为前置检查。
|
||||
|
||||
---
|
||||
|
||||
## 7. 验收脚本:`scripts/verify_port.sh`
|
||||
|
||||
设计成「**生成完代码后,开发者一键自检**」。完整列表见脚本本身(自带带 `[PASS]/[FAIL]/[WARN]` 标记),核心检查项:
|
||||
|
||||
| 检查项 | 命令 | 预期 |
|
||||
|---|---|---|
|
||||
| 包结构完整 | `find package.xml CMakeLists.txt setup.py launch config models scripts src/sru_nav_go2/{constants,model,navigation_policy_node}.py` | 全部存在 |
|
||||
| 模型可加载 | `python -c "import onnxruntime as ort; ort.InferenceSession('models/vae_encoder.onnx')"` | 不抛异常,打印 input shape |
|
||||
| catkin 通过 | `catkin_make -DPYTHON_EXECUTABLE=$(which python3)` | exit 0 |
|
||||
| shebang 正确 | `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node \| grep -q miniconda3.envs.${ENV_NAME}` | match |
|
||||
| 节点能起 | `timeout 8 roslaunch sru_nav_go2_ros1 sru_nav_go2.launch launch_joy:=false require_joystick:=false` | log 含 `Navigation policy node is ready` |
|
||||
| 关键参数存在 | `grep -E "policy_scale\|require_joystick\|control_frequency" config/sru_nav.yaml` | 三项都命中 |
|
||||
| LD_PRELOAD 修复 | `grep -q 'LD_PRELOAD.*libffi' scripts/launch_sru_nav.sh` | 命中 |
|
||||
|
||||
跑完终端打印 `ALL CHECKS PASSED` 才能放行真机。
|
||||
|
||||
---
|
||||
|
||||
## 8. 常见陷阱
|
||||
|
||||
按踩坑频率排序:
|
||||
|
||||
1. **catkin_make 时没在 conda env 里**:节点 shebang 烤进 `/usr/bin/python3`,运行时 `import onnxruntime` 失败。修:`conda activate sru_nav && catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=$(which python3)`。
|
||||
2. **`No module named netifaces / defusedxml`**:rospy 隐性依赖。`pip install netifaces defusedxml` 进 conda env,`setup_conda_env.sh` 已内置。
|
||||
3. **`libp11-kit.so.0: undefined symbol: ffi_type_pointer`**:conda libffi 抢加载。`launch_sru_nav.sh` 里的 `LD_PRELOAD` 已修,新平台只需把版本号 7→8 同步。
|
||||
4. **pip `certificate is not yet valid`**:Jetson 时钟回退。`sudo ntpdate -u ntp.aliyun.com && sudo hwclock --systohc`。
|
||||
5. **`/cmd_vel` 全 0**:deadman 模式默认开。要么接手柄推 `axes[4]`,要么 `--no-deadman`(仅测试)。
|
||||
6. **goal 被忽略**:`/goal_pose.frame_id` 必须等于 odom 的 `frame_id`。
|
||||
|
||||
---
|
||||
|
||||
## 9. 许可与致谢
|
||||
|
||||
- 算法与训练代码版权:原 SRU 作者团队,遵循其原 LICENSE。
|
||||
- 本部署移植包 `sru_nav_go2_ros1` 在 MIT-style 许可下开源;包含上游派生代码的部分文件保留各自原始 header。
|
||||
- Odin1 是第三方深度相机,本仓库不再分发其驱动。
|
||||
|
||||
如发现移植 bug 或想要一键支持更多机器人/相机,欢迎 issue + PR。
|
||||
|
||||
---
|
||||
|
||||
## 附录 A:与论文/训练代码核对的关键数字
|
||||
|
||||
| 名称 | 训练值 | 部署值 | 来源 |
|
||||
|---|---|---|---|
|
||||
| `control_frequency` | 10 Hz (env step) | 5 Hz | `constants.DEFAULT_CONTROL_FREQUENCY` |
|
||||
| `rnn_hidden_size` | 512 | 512 | `b2w/agents/rsl_rl_cfg.py:36` |
|
||||
| `rnn_num_layers` | 1 | 1 | 同上 |
|
||||
| `policy_scaling` | `[1.5, 1.0, 1.0]` × `Uniform(0.8,1.2)/(0.6,1.0)/(0.8,1.2)` | `policy_scale=[0.6,0.3,0.6]`(保守) | `navigation_env_cfg.py:163` |
|
||||
| `entropy_coef` | `0.00375` | n/a | `b2w/agents/rsl_rl_cfg.py:50` |
|
||||
| `value_loss_coef` | `0.02` | n/a | 同上 |
|
||||
| 深度图分辨率(VAE 输入) | 见 `image_input_dims=(64, 5, 8)` 编码后形状 | 任意输入分辨率,节点 resize 到训练规格 | `b2w/agents/rsl_rl_cfg.py:41` |
|
||||
| `min_depth / max_depth` | 0.25 / 10.0 m | 0.25 / 10.0 m | `constants.py` |
|
||||
| `JOYSTICK_TIMEOUT` | n/a | 15 s | `constants.py:16` |
|
||||
|
||||
附录里这张表是「训练-部署一致性」的最小验收清单。任何二次移植(换机器人 / 换相机)都应保留这些数字不变。
|
||||
|
||||
---
|
||||
|
||||
## 附录 B:从空机器开始的 0 门槛 quickstart
|
||||
|
||||
```bash
|
||||
# === 系统级(一次性,需 sudo) =============================================
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl git build-essential ros-noetic-desktop \
|
||||
ros-noetic-joy ros-noetic-tf2-tools \
|
||||
python3-catkin-tools
|
||||
|
||||
# === 装 miniconda(如已装可跳过) ==========================================
|
||||
curl -O https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-$(uname -m).sh
|
||||
bash Miniconda3-latest-Linux-$(uname -m).sh -b -p $HOME/miniconda3
|
||||
echo 'source $HOME/miniconda3/etc/profile.d/conda.sh' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
|
||||
# === 拉本仓库(替换成你的 fork / 仓库地址) ================================
|
||||
mkdir -p ~/code/odin_sru_nav/src
|
||||
cd ~/code/odin_sru_nav/src
|
||||
git clone https://github.com/<YOUR_FORK>/sru_nav_go2_ros1.git
|
||||
|
||||
# === 装 conda 依赖(含 onnxruntime / cv2 / netifaces ...) =================
|
||||
cd sru_nav_go2_ros1
|
||||
bash scripts/setup_conda_env.sh # 全自动;首次约 5–10 分钟
|
||||
bash scripts/setup_conda_env.sh --check # 自检全 OK 才继续
|
||||
|
||||
# === 编译(必须在 conda env 里) ===========================================
|
||||
conda activate sru_nav
|
||||
cd ~/code/odin_sru_nav
|
||||
catkin_make -DPYTHON_EXECUTABLE=$(which python3)
|
||||
source devel/setup.bash
|
||||
|
||||
# === 一键启动(默认安全模式:必须接手柄) ==================================
|
||||
cd src/sru_nav_go2_ros1
|
||||
bash scripts/launch_sru_nav.sh
|
||||
|
||||
# 或:抬轮 / 仿真 / 闭环回归测试(无手柄) ==================================
|
||||
bash scripts/launch_sru_nav.sh --no-deadman
|
||||
|
||||
# === 一键自检 ==============================================================
|
||||
bash scripts/verify_port.sh
|
||||
```
|
||||
|
||||
到这里只要 `verify_port.sh` 全绿,就能开始真机测试。
|
||||
@@ -0,0 +1,553 @@
|
||||
# Porting the SRU navigation policy to Odin1 + ROS1: full reproduction guide
|
||||
|
||||
> Starting from the paper *Spatially-Enhanced Recurrent Memory for Long-Range
|
||||
> Mapless Navigation via End-to-End Reinforcement Learning* and the
|
||||
> open-source repositories indexed at
|
||||
> [`sru-project-website`](https://michaelfyang.github.io/sru-project-website/),
|
||||
> this guide explains how to deploy the SRU end-to-end navigation policy on
|
||||
> **the Odin1 depth camera + ROS1 Noetic + any robot that consumes
|
||||
> `geometry_msgs/Twist` on `/cmd_vel`** (the reference platform is the
|
||||
> Unitree Go2). The package `sru_nav_go2_ros1` in this repository is the
|
||||
> output of that effort.
|
||||
>
|
||||
> **中文版**: see `PORTING_GUIDE.md`.
|
||||
|
||||
---
|
||||
|
||||
## 0. What this document is — and is not
|
||||
|
||||
**Is**: a three-in-one guide combining (a) the porting decision log, (b) a
|
||||
ready-to-use AI prompt that lets a coding agent regenerate this package
|
||||
from upstream, and (c) an automated acceptance script. After reading you
|
||||
should be able to:
|
||||
|
||||
1. understand which upstream pieces were changed and why,
|
||||
2. run a slash command in Cascade / Claude Code to recreate the package
|
||||
from the open-source repos and the paper,
|
||||
3. run a single script to verify the result.
|
||||
|
||||
**Is not**: an algorithm tutorial. For the model and reward design, read
|
||||
the paper and the upstream code directly.
|
||||
|
||||
**Audience**:
|
||||
- comfortable with Ubuntu + ROS1 + Python/conda,
|
||||
- has a Unitree Go2 (or any robot subscribing to `/cmd_vel`) plus an
|
||||
Odin1 depth camera,
|
||||
- wants to run SRU on their own robot, or to verify whether an AI agent
|
||||
can reproduce a real-robot deployment package from the paper + open
|
||||
code.
|
||||
|
||||
> Zero-barrier promise: every path, IP, robot model, and camera model is
|
||||
> overridable via environment variable or ROS parameter. No source code
|
||||
> edits required to retarget.
|
||||
|
||||
---
|
||||
|
||||
## 1. Upstream sources
|
||||
|
||||
| Asset | Link / path | Role in this port |
|
||||
|---|---|---|
|
||||
| Paper | *Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation via End-to-End Reinforcement Learning* | Defines the observation/action space, rewards, and network (depth VAE + LSTM-SRU + actor head) |
|
||||
| Project page | <https://michaelfyang.github.io/sru-project-website/> | Index of repos, videos, paper |
|
||||
| `sru-navigation-learning` | RL training code (rsl_rl-style); contains PPO/MDPO algorithms, reward terms, observation manager | Source of truth for **reward design, action squashing, observation order**, plus the ONNX export entry point |
|
||||
| `sru-navigation-sim` | IsaacLab task with B2W / AOW training configs | Provides `policy_scaling`, randomization ranges, observation shapes (depth `64×5×8`) |
|
||||
| `sru-robot-deployment` | Original B2W + ZED-X real-robot deployment by the authors | The **direct rewrite target**: original uses PyTorch + DLIO odom + a custom SDK bridge; this port uses ONNX + Odin1 odom + a Go2 bridge |
|
||||
| `sru-pytorch-spatial-learning` | PyTorch implementation of the SRU / LSTM-SRU cell | Explains RNN hidden-state shape (`rnn_hidden_size=512, num_layers=1`) and how `(h, c)` are exposed when exporting to ONNX |
|
||||
| `sru-depth-pretraining` | Pretraining of the depth VAE encoder | Provides the input shape (`H×W` normalized depth, single channel) and latent dim of `vae_encoder.onnx` |
|
||||
|
||||
If you only want to run, not reproduce: drop the two trained ONNX files
|
||||
(`vae_encoder.onnx` + `nav_policy.onnx`) into `sru_nav_go2_ros1/models/`
|
||||
and skip to §6.
|
||||
|
||||
---
|
||||
|
||||
## 2. Porting target matrix
|
||||
|
||||
| Aspect | Author deployment (`sru-robot-deployment`) | This package (`sru_nav_go2_ros1`) | Abstracted interface |
|
||||
|---|---|---|---|
|
||||
| Robot | Unitree **B2W** (wheeled-leg) | Unitree **Go2** (pure-leg) | Any robot consuming `/cmd_vel` (`geometry_msgs/Twist`, body frame) |
|
||||
| Depth sensor | ZED-X | **Odin1** (`32FC1`, ~10 Hz) | `~depth_topic` (`sensor_msgs/Image`, 32FC1, meters) |
|
||||
| Odometry | DLIO (custom LIO) | Odin1 `odometry_highfreq` | `~odom_topic` (`nav_msgs/Odometry`, world frame) |
|
||||
| Inference backend | PyTorch JIT | **ONNX Runtime** | `models/{vae_encoder,nav_policy}.onnx` |
|
||||
| Compute platform | x86 industrial PC | **Jetson Orin NX (aarch64) + conda py3.8** | Any Linux + ROS1 Noetic + conda |
|
||||
| Control rate | ~10 Hz | **5 Hz** (matches training; Odin depth ~10 Hz, naturally decimated) | `~control_frequency` |
|
||||
| Operator joystick | PS5 PerceptiveNavigationSE2 | Same PS5 mapping, **plus `require_joystick: false`** for headless | `--no-deadman` / yaml `require_joystick` |
|
||||
| Install / launch | rosinstall full stack | **`setup_conda_env.sh` + `launch_sru_nav.sh`** | env vars `ENV_NAME / ROS_DISTRO / CATKIN_WS`, all overridable |
|
||||
|
||||
---
|
||||
|
||||
## 3. Core porting decisions (motivation + reference)
|
||||
|
||||
### 3.1 Inference: PyTorch → ONNX Runtime
|
||||
|
||||
- **Why**: stacking PyTorch + cv_bridge + onnxruntime on a Jetson Orin NX
|
||||
rapidly snowballs into a dependency mess; onnxruntime ships a single
|
||||
shared-object loader, swaps CPU/GPU EP cleanly, and has prebuilt ARM
|
||||
wheels.
|
||||
- **Interface**: `@/sru_nav_go2_ros1/src/sru_nav_go2/model.py` implements
|
||||
`LearningModel`, which loads `vae_encoder.onnx` (depth → latent) and
|
||||
`nav_policy.onnx` (latent + state vector + last action + LSTM hidden →
|
||||
action mean + new hidden) as two separate sessions.
|
||||
- **Hidden-state contract**: training uses `rnn_hidden_size=512,
|
||||
num_layers=1`; the ONNX export carries `(h, c)` as input/output tensors
|
||||
and the deployment side holds them between frames. `reset_hidden_state`
|
||||
matches the training `is_first` flag.
|
||||
- **Action squash**: the network already includes `tanh`, so the output is
|
||||
in `(-1, 1)`. The deployment then multiplies by
|
||||
`policy_scale = [vx_max, vy_max, ω_max]` (default `[0.6, 0.3, 0.6]`)
|
||||
to obtain SI velocities.
|
||||
|
||||
### 3.2 Observations: Odin1 replaces ZED-X + DLIO
|
||||
|
||||
- **Depth**: Odin1 publishes `sensor_msgs/Image` (`32FC1`, meters). The
|
||||
callback `@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:209-225`:
|
||||
1. `cv_bridge.imgmsg_to_cv2(passthrough)`,
|
||||
2. `nan_to_num(nan=0, posinf=2*max_depth, neginf=0)`,
|
||||
3. clamps to `[min_depth, max_depth] = [0.25, 10.0] m`, out-of-range
|
||||
pixels set to 0.
|
||||
- **Odometry frame convention**: Odin1's `twist` is **world frame**. The
|
||||
`odom_callback` rotates it back to the body frame using the body
|
||||
quaternion (matching training). If your odom is already in body frame,
|
||||
set `use_sim: true` and the node passes `twist` straight through
|
||||
(`@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:189-197`).
|
||||
- **Goal frame contract**: `/goal_pose.header.frame_id` must equal the odom
|
||||
`frame_id` (default `odom`). Otherwise the node rejects the message —
|
||||
this guards against operators sending a body-frame coordinate as if it
|
||||
were odom-frame.
|
||||
|
||||
### 3.3 Action egress: straight to `/cmd_vel`
|
||||
|
||||
- The original B2W deployment ships its own SDK bridge; on Go2 a tiny
|
||||
separate node (subscribes to `/cmd_vel`, talks to `unitree_legged_sdk`
|
||||
sport mode) is enough. **This package is robot-agnostic** and does not
|
||||
bind to a specific bridge.
|
||||
- `policy_scale = [0.6, 0.3, 0.6]` is a deliberate halving versus the
|
||||
training value `[1.5, 1.0, 1.0]`, leaving margin for real-robot bring-up.
|
||||
Training already randomized scale by `Uniform(0.6, 1.2)`, so the network
|
||||
is robust to runtime scaling.
|
||||
|
||||
### 3.4 Safety: dual-mode joystick deadman
|
||||
|
||||
| Mode | Trigger | Behavior |
|
||||
|---|---|---|
|
||||
| Default (`require_joystick=true`) | Real-robot deployment | `cmd_vel_ratio=0` until `/joy` is published with `axes[4]` > 0; >15 s without `/joy` forces stop |
|
||||
| Test (`require_joystick=false`) | `--no-deadman` or yaml=false | `cmd_vel_ratio=1.0` from start, no `/joy` required. **Lifted-wheel / sim / open-field only** |
|
||||
|
||||
Source: `@/sru_nav_go2_ros1/src/sru_nav_go2/navigation_policy_node.py:118-121, 272-287`.
|
||||
|
||||
### 3.5 Install layer: conda + system ROS coexistence
|
||||
|
||||
The Jetson Orin NX ships ROS Noetic (system python 3.8 + cv_bridge.so).
|
||||
At the same time we want `onnxruntime / opencv / numpy / …` only inside a
|
||||
conda env. The two worlds must interoperate:
|
||||
|
||||
1. **`PYTHONPATH` injection**: prepend
|
||||
`/opt/ros/noetic/lib/python3/dist-packages` so the conda python can
|
||||
import `rospy / cv_bridge / sensor_msgs / tf2_ros`.
|
||||
2. **Shebang lock**: `catkin_make` must run with
|
||||
`-DPYTHON_EXECUTABLE=$(which python3)` **while the conda env is
|
||||
active**, otherwise `devel/lib/.../sru_nav_node`'s `#!` line will point
|
||||
at `/usr/bin/python3` and `import onnxruntime` fails at runtime.
|
||||
3. **ABI conflict fix**: the conda env ships `libffi.so.7`, but the system
|
||||
`libp11-kit.so.0` was linked against the system `libffi`'s versioned
|
||||
symbols. Without intervention `cv_bridge` crashes with
|
||||
`undefined symbol: ffi_type_pointer, version LIBFFI_BASE_7.0`.
|
||||
`launch_sru_nav.sh` automatically `LD_PRELOAD`s the system
|
||||
`libffi.so.7` so its symbols take priority.
|
||||
4. **Hidden rospy deps**: `netifaces` and `defusedxml` are provided to the
|
||||
system python via apt packages; the conda env needs them via pip.
|
||||
`setup_conda_env.sh` already lists both.
|
||||
5. **Clock check**: Jetson without an RTC battery often boots with a stale
|
||||
clock, breaking pip TLS. The script runs a `date` plausibility check
|
||||
and points to `ntpdate / timedatectl`.
|
||||
|
||||
Full automation: `@/sru_nav_go2_ros1/scripts/setup_conda_env.sh` +
|
||||
`@/sru_nav_go2_ros1/scripts/launch_sru_nav.sh`.
|
||||
|
||||
### 3.6 Deliberate omissions
|
||||
|
||||
| Present in training | Reason for omitting at deployment |
|
||||
|---|---|
|
||||
| Heightmap / heightscan critic | Go2 has no LiDAR/heightmap; can be added as an external topic if needed |
|
||||
| Critic-only observation channels | Critic exists only at training time; only the actor head runs at inference |
|
||||
| MDPO / mutual-distillation dual actor-critic | Optimizer-side mechanism; irrelevant to the exported actor |
|
||||
| Reward computation | Inference does not need rewards |
|
||||
| Action-scale randomization (`Uniform(0.6, 1.2)`) | Deployment uses a fixed scale; the network has been trained to be robust to this range |
|
||||
|
||||
---
|
||||
|
||||
## 4. File map and responsibilities
|
||||
|
||||
```
|
||||
sru_nav_go2_ros1/
|
||||
├── CMakeLists.txt # catkin def: catkin_python_setup() + install scripts
|
||||
├── package.xml # deps: rospy, sensor_msgs, geometry_msgs, nav_msgs, cv_bridge, tf2_ros
|
||||
├── setup.py # installs src/sru_nav_go2 as a Python package
|
||||
├── README.md
|
||||
├── config/
|
||||
│ ├── sru_nav.yaml # all runtime ROS params; the only file users normally touch
|
||||
│ └── waypoints_example.yaml # multi-goal tour example (odom-frame point list)
|
||||
├── launch/
|
||||
│ └── sru_nav_go2.launch # joy_node + static_tf + sru_nav_node
|
||||
├── models/
|
||||
│ ├── vae_encoder.onnx # exported from training side via export_onnx
|
||||
│ └── nav_policy.onnx
|
||||
├── scripts/
|
||||
│ ├── setup_conda_env.sh # creates the sru_nav env, installs onnxruntime / cv2 / netifaces …
|
||||
│ ├── launch_sru_nav.sh # one-liner launcher (with LD_PRELOAD / PYTHONPATH fixes)
|
||||
│ ├── sru_nav_node # ROS node entrypoint (catkin install copies it under devel/lib/…)
|
||||
│ ├── waypoint_runner.py # publishes /goal_pose in sequence
|
||||
│ └── verify_port.sh # acceptance script (see §7)
|
||||
├── src/sru_nav_go2/
|
||||
│ ├── constants.py # all training-aligned constants
|
||||
│ ├── model.py # ONNX Runtime wrapper: VAE encoder + LSTM-SRU policy
|
||||
│ ├── navigation_policy_node.py # main node: odom/depth/joy/goal callbacks + cmd_vel out
|
||||
│ ├── utils.py # quaternion ↔ rotation, projected gravity, etc.
|
||||
│ ├── visualization.py # rviz markers
|
||||
│ └── waypoint_manager.py # record / replay waypoint list
|
||||
└── docs/
|
||||
├── DEPLOY_GO2_NX.md # NX deployment field notes
|
||||
├── PORTING_GUIDE.md # Chinese version
|
||||
└── PORTING_GUIDE_EN.md # ← this file
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Reproducing this package with an AI agent
|
||||
|
||||
We ship **the same porting prompt in three call forms** (use whichever
|
||||
fits your tool):
|
||||
|
||||
| Entry | Tool | How to invoke |
|
||||
|---|---|---|
|
||||
| `.windsurf/workflows/port-sru-to-ros.md` | Cascade (Windsurf IDE) | type `/port-sru-to-ros` in the Cascade panel |
|
||||
| `.claude/commands/port-sru-to-ros.md` | Claude Code (CLI / IDE) | start `claude`, then `/port-sru-to-ros` |
|
||||
| `docs/PORTING_GUIDE.md` §5.2 | Any agent that accepts a custom prompt (Cursor, Continue, Aider, …) | paste §5.2 into the system / task prompt |
|
||||
|
||||
All three derive from one canonical prompt. Differences are limited to
|
||||
the launch header and per-tool path conventions.
|
||||
|
||||
> ⚠️ **Reproducibility caveat**: a single LLM round generating ~1500 LoC
|
||||
> of ROS porting code is not 100% reliable. We split the task into a
|
||||
> 6-step workflow so each step has a grep-able acceptance check; this
|
||||
> dramatically beats one-shot mega-prompts in success rate.
|
||||
|
||||
### 5.1 Workflow at a glance
|
||||
|
||||
| Step | Inputs | Outputs | Acceptance |
|
||||
|---|---|---|---|
|
||||
| 1. **Recon** | 5 upstream repos + paper | `notes/upstream_recon.md` summarizing arch, obs/action, IO shapes, training hyperparams | file exists and lists net depth, obs dims, policy_scale |
|
||||
| 2. **Extract inference** | `sru-navigation-learning` export entry | `models/vae_encoder.onnx`, `models/nav_policy.onnx`, `docs/IO_SPEC.md` | onnxruntime can load both; IO names recorded |
|
||||
| 3. **catkin skeleton** | Step 2 IO spec | `package.xml / CMakeLists.txt / setup.py / launch/ / config/sru_nav.yaml` | `catkin_make` succeeds |
|
||||
| 4. **Port the node** | Original `sru-robot-deployment` node + IO spec | `src/sru_nav_go2/{constants,model,utils,visualization,waypoint_manager,navigation_policy_node}.py` + `scripts/sru_nav_node` | `roslaunch` brings the node up cleanly |
|
||||
| 5. **Deployment scripts** | Target platform info | `scripts/setup_conda_env.sh` + `scripts/launch_sru_nav.sh` | clean-env smoke-test in §6 passes |
|
||||
| 6. **Docs + verify** | All above | `README.md / docs/DEPLOY_*.md / scripts/verify_port.sh` | `bash scripts/verify_port.sh` all green |
|
||||
|
||||
### 5.2 Canonical prompt (the body of all three entry files)
|
||||
|
||||
```text
|
||||
You are a senior engineer fluent in ROS1 Noetic, conda, ONNX Runtime, and
|
||||
PyTorch.
|
||||
|
||||
[Task]
|
||||
From the upstream sources below, generate a catkin package named
|
||||
`sru_nav_go2_ros1` that deploys the navigation policy from the paper
|
||||
"Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation
|
||||
via End-to-End Reinforcement Learning" onto an Odin1 depth camera +
|
||||
ROS1 Noetic + any robot consuming `geometry_msgs/Twist` on `/cmd_vel`.
|
||||
|
||||
[Upstream sources]
|
||||
- Paper PDF (path provided by user, e.g. ./2506.05997v2.pdf)
|
||||
- Project page: https://michaelfyang.github.io/sru-project-website/
|
||||
- Repos under user-provided `${UPSTREAM_DIR}`:
|
||||
sru-navigation-learning — RL training + ONNX export
|
||||
sru-navigation-sim — IsaacLab env + training configs
|
||||
sru-robot-deployment — original B2W+ZED-X deployment (the
|
||||
direct rewrite target)
|
||||
sru-pytorch-spatial-learning — SRU / LSTM-SRU cell
|
||||
sru-depth-pretraining — depth VAE pretraining
|
||||
- Pre-existing onnx files (if any):
|
||||
models/{vae_encoder,nav_policy}.onnx
|
||||
|
||||
[Hard constraints]
|
||||
1. Sensors are fixed to Odin1: depth `/odin1/depth_img_competetion`
|
||||
(sensor_msgs/Image, 32FC1, meters), odom
|
||||
`/odin1/odometry_highfreq` (nav_msgs/Odometry, world frame).
|
||||
2. Output is fixed to `/cmd_vel` (geometry_msgs/Twist, body frame). The
|
||||
bridge to a specific robot's SDK is out of scope.
|
||||
3. Only `onnxruntime` for inference. No PyTorch at runtime.
|
||||
4. Must coexist with system ROS python in a conda env (default
|
||||
`sru_nav`, py3.8):
|
||||
- inject /opt/ros/<DISTRO>/lib/python3/dist-packages into PYTHONPATH
|
||||
- LD_PRELOAD system libffi to fix cv_bridge ABI conflict
|
||||
- lock catkin_make's PYTHON_EXECUTABLE to conda python
|
||||
5. Every path / env / distro / robot model must be overridable via env
|
||||
vars or ROS params; never write `/home/<user>` into source files.
|
||||
6. Preserve all training-aligned numbers: control_frequency=5 Hz,
|
||||
rnn_hidden=512, default policy_scale=[0.6,0.3,0.6], joystick axis
|
||||
mapping, etc.
|
||||
7. Safety: joystick deadman + 15 s timeout, with a
|
||||
`require_joystick: false` bypass; default must be true.
|
||||
|
||||
[Output file list] (all required)
|
||||
package.xml, CMakeLists.txt, setup.py
|
||||
launch/sru_nav_go2.launch
|
||||
config/sru_nav.yaml, config/waypoints_example.yaml
|
||||
scripts/setup_conda_env.sh, scripts/launch_sru_nav.sh,
|
||||
scripts/sru_nav_node, scripts/waypoint_runner.py, scripts/verify_port.sh
|
||||
src/sru_nav_go2/{__init__.py, constants.py, model.py, utils.py,
|
||||
visualization.py, waypoint_manager.py,
|
||||
navigation_policy_node.py}
|
||||
docs/DEPLOY.md, docs/PORTING_GUIDE.md (Chinese), docs/PORTING_GUIDE_EN.md
|
||||
models/README.md (how to obtain / export the two ONNX files)
|
||||
|
||||
[Workflow] (must be sequential; self-check after each step)
|
||||
Step 1 — Recon: read repos and paper; emit notes/upstream_recon.md with
|
||||
net architecture, obs dims, action space, rsl_rl algorithm config,
|
||||
reward list.
|
||||
Step 2 — IO normalization: locate export_onnx in the training repo, log
|
||||
input/output names + shapes, emit docs/IO_SPEC.md.
|
||||
Step 3 — Generate catkin skeleton; verify with `catkin_make`.
|
||||
Step 4 — Port the node: use sru-robot-deployment as template, swap
|
||||
sensors, drop non-Odin deps, replace PyTorch calls with
|
||||
onnxruntime.
|
||||
Step 5 — Write the two scripts (setup + launcher), covering all of
|
||||
constraint #4.
|
||||
Step 6 — Generate verify_port.sh: package layout, shebang, ONNX load
|
||||
test, rostopic list, yaml fields.
|
||||
|
||||
[Acceptance] (the user will run verify_port.sh and the commands below)
|
||||
1. `catkin_make` in a clean workspace: 0 warnings, 0 errors.
|
||||
2. `bash scripts/setup_conda_env.sh --check` passes.
|
||||
3. `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node` points at conda
|
||||
python, not `/usr/bin/python3`.
|
||||
4. `roslaunch sru_nav_go2_ros1 sru_nav_go2.launch require_joystick:=false`
|
||||
prints `Navigation policy node is ready.` and emits no error spam.
|
||||
5. Synthetic odom + a 32FC1 depth frame + a goal_pose results in a
|
||||
non-zero `/cmd_vel`.
|
||||
6. `bash scripts/verify_port.sh` is all green.
|
||||
|
||||
[Response discipline]
|
||||
- Do not emit a single 1000+ line reply; chunk per step, summarize the
|
||||
plan first, then write files.
|
||||
- After each step run the listed self-check, paste the command and
|
||||
output, fix on failure before advancing.
|
||||
- If an upstream file is missing, halt and ask. Never fabricate APIs.
|
||||
```
|
||||
|
||||
The fully executable variants are in
|
||||
`@/.windsurf/workflows/port-sru-to-ros.md` and
|
||||
`@/.claude/commands/port-sru-to-ros.md`.
|
||||
|
||||
### 5.3 How do I prove that this prompt actually reproduces the package?
|
||||
|
||||
Run the workflow on a clean machine, then:
|
||||
|
||||
```bash
|
||||
diff -r --exclude=__pycache__ --exclude=.git \
|
||||
./generated_sru_nav_go2_ros1/ \
|
||||
./sru_nav_go2_ros1/
|
||||
```
|
||||
|
||||
Expected: **identical structure; line-level diffs concentrated in
|
||||
comments and literal ordering, not in numeric constants, topic names,
|
||||
or function signatures**. If you see drift on critical items
|
||||
(`policy_scale` becoming `[1, 1, 1]`, the LD_PRELOAD line missing, etc.),
|
||||
the agent did not follow the prompt — return to that step and retry.
|
||||
|
||||
---
|
||||
|
||||
## 6. Personalization and zero-barrier usage
|
||||
|
||||
Every "user-specific" knob is exposed as a parameter. The three most
|
||||
common categories:
|
||||
|
||||
### 6.1 Paths
|
||||
|
||||
| Parameter | Default | Override |
|
||||
|---|---|---|
|
||||
| catkin workspace | `$HOME/code/odin_sru_nav` | `CATKIN_WS=/path bash scripts/launch_sru_nav.sh` |
|
||||
| conda env name | `sru_nav` | `ENV_NAME=my_env bash scripts/setup_conda_env.sh` |
|
||||
| ROS distro | `noetic` | `ROS_DISTRO=melodic bash scripts/launch_sru_nav.sh` (py3-compatible only) |
|
||||
| pip mirror | Tsinghua | `PIP_INDEX_URL=https://pypi.org/simple bash scripts/setup_conda_env.sh` |
|
||||
|
||||
### 6.2 Topics and frames
|
||||
|
||||
Edit `config/sru_nav.yaml`; **do not edit source code**:
|
||||
|
||||
```yaml
|
||||
depth_topic: "/your/depth" # sensor_msgs/Image (32FC1, meters)
|
||||
odom_topic: "/your/odometry" # nav_msgs/Odometry, world frame
|
||||
joy_topic: "/joy"
|
||||
goal_topic: "/goal_pose"
|
||||
cmd_vel_topic: "/cmd_vel"
|
||||
```
|
||||
|
||||
### 6.3 Different robots
|
||||
|
||||
You only need a `/cmd_vel` bridge. The package is **robot-agnostic**.
|
||||
Common substitutions:
|
||||
|
||||
- Unitree Go2: ~50 LoC bridge wrapping `unitree_legged_sdk` sport mode
|
||||
- Unitree B2 / B2W: official ROS1 bridge
|
||||
- Boston Dynamics Spot: `spot_ros` + `cmd_vel`
|
||||
- Any ROS sim: subscribes to `/cmd_vel` directly
|
||||
|
||||
The only TF you may need to retune is the static
|
||||
`base_link → odin1_base_link` published by the launch file; the args
|
||||
`odin1_x / y / z / roll / pitch / yaw` mirror your camera mounting pose.
|
||||
|
||||
### 6.4 System-environment check (also embedded in the prompt)
|
||||
|
||||
Run once on a fresh host:
|
||||
|
||||
```bash
|
||||
# 1) OS / ROS
|
||||
lsb_release -a # Ubuntu 20.04 recommended (Noetic)
|
||||
echo $ROS_DISTRO # expect: noetic
|
||||
which roscore # /opt/ros/noetic/bin/roscore
|
||||
|
||||
# 2) Conda
|
||||
conda --version # ≥ 4.10
|
||||
conda env list | grep -E "sru_nav|base"
|
||||
|
||||
# 3) Clock (Jetsons without RTC battery often drift)
|
||||
date # must reflect real wall time
|
||||
|
||||
# 4) Network
|
||||
ping -c 2 8.8.8.8 || echo "WARN: no internet, pip will fail"
|
||||
|
||||
# 5) Hardware
|
||||
ls /dev/input/js* 2>/dev/null \
|
||||
|| echo "INFO: no joystick — use --no-deadman for headless tests"
|
||||
rostopic list 2>/dev/null | grep odin1 \
|
||||
|| echo "WARN: Odin1 driver not running"
|
||||
```
|
||||
|
||||
`scripts/verify_port.sh` codifies the same checks.
|
||||
|
||||
---
|
||||
|
||||
## 7. Acceptance script — `scripts/verify_port.sh`
|
||||
|
||||
Designed for the developer to **self-check immediately after generation**.
|
||||
The full set lives in the script itself (with `[PASS]/[FAIL]/[WARN]`
|
||||
markers); the most important checks:
|
||||
|
||||
| Check | Command | Expected |
|
||||
|---|---|---|
|
||||
| Package layout complete | look for `package.xml CMakeLists.txt setup.py launch config models scripts src/sru_nav_go2/{constants,model,navigation_policy_node}.py` | all present |
|
||||
| Models load | `python -c "import onnxruntime as ort; ort.InferenceSession('models/vae_encoder.onnx')"` | no exception, prints input shape |
|
||||
| catkin builds | `catkin_make -DPYTHON_EXECUTABLE=$(which python3)` | exit 0 |
|
||||
| Shebang correct | `head -1 devel/lib/sru_nav_go2_ros1/sru_nav_node \| grep -q miniconda3.envs.${ENV_NAME}` | match |
|
||||
| Node comes up | `timeout 8 roslaunch sru_nav_go2_ros1 sru_nav_go2.launch launch_joy:=false require_joystick:=false` | log contains `Navigation policy node is ready` |
|
||||
| Required yaml params | `grep -E "policy_scale\|require_joystick\|control_frequency" config/sru_nav.yaml` | all three matched |
|
||||
| LD_PRELOAD fix | `grep -q 'LD_PRELOAD.*libffi' scripts/launch_sru_nav.sh` | match |
|
||||
|
||||
The script exits with `ALL CHECKS PASSED` when (and only when) every
|
||||
check is green. Do not move to real-robot tests before that.
|
||||
|
||||
---
|
||||
|
||||
## 8. Common pitfalls
|
||||
|
||||
In rough order of how often they bite:
|
||||
|
||||
1. **Built `catkin_make` outside the conda env** → node shebang baked to
|
||||
`/usr/bin/python3`; `import onnxruntime` fails. Fix:
|
||||
`conda activate sru_nav && catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=$(which python3)`.
|
||||
2. **`No module named netifaces / defusedxml`** → rospy hidden deps.
|
||||
`pip install netifaces defusedxml` into the conda env. Already in
|
||||
`setup_conda_env.sh`.
|
||||
3. **`libp11-kit.so.0: undefined symbol: ffi_type_pointer`** → conda
|
||||
libffi is loaded first. The `LD_PRELOAD` fix in `launch_sru_nav.sh`
|
||||
covers it; on platforms with only `libffi.so.8` change the version
|
||||
number.
|
||||
4. **pip `certificate is not yet valid`** → Jetson clock drift. Fix:
|
||||
`sudo ntpdate -u ntp.aliyun.com && sudo hwclock --systohc`.
|
||||
5. **`/cmd_vel` is all zeros** → deadman is on by default. Either plug
|
||||
in the joystick and push `axes[4]`, or run with `--no-deadman` (test
|
||||
mode only).
|
||||
6. **Goal silently dropped** → `/goal_pose.frame_id` must equal the
|
||||
odom `frame_id`.
|
||||
|
||||
---
|
||||
|
||||
## 9. License & acknowledgments
|
||||
|
||||
- The algorithm and training code remain copyright of the original SRU
|
||||
authors under their original LICENSE.
|
||||
- This deployment port `sru_nav_go2_ros1` is released under an MIT-style
|
||||
license; files derived from upstream retain their original headers.
|
||||
- Odin1 is a third-party depth camera; this repo does not redistribute
|
||||
its driver.
|
||||
|
||||
If you find a porting bug or want first-class support for more robots /
|
||||
cameras, please open an issue or PR.
|
||||
|
||||
---
|
||||
|
||||
## Appendix A: training–deployment numeric cross-check
|
||||
|
||||
| Quantity | Training value | Deployment value | Source |
|
||||
|---|---|---|---|
|
||||
| `control_frequency` | 10 Hz (env step) | 5 Hz | `constants.DEFAULT_CONTROL_FREQUENCY` |
|
||||
| `rnn_hidden_size` | 512 | 512 | `b2w/agents/rsl_rl_cfg.py:36` |
|
||||
| `rnn_num_layers` | 1 | 1 | same file |
|
||||
| `policy_scaling` | `[1.5, 1.0, 1.0]` × `Uniform(0.8,1.2)/(0.6,1.0)/(0.8,1.2)` | `policy_scale=[0.6,0.3,0.6]` (conservative) | `navigation_env_cfg.py:163` |
|
||||
| `entropy_coef` | `0.00375` | n/a | `b2w/agents/rsl_rl_cfg.py:50` |
|
||||
| `value_loss_coef` | `0.02` | n/a | same file |
|
||||
| Depth resolution into the VAE | `image_input_dims=(64, 5, 8)` (post-encoder) | input depth resized at runtime | `b2w/agents/rsl_rl_cfg.py:41` |
|
||||
| `min_depth / max_depth` | 0.25 / 10.0 m | 0.25 / 10.0 m | `constants.py` |
|
||||
| `JOYSTICK_TIMEOUT` | n/a | 15 s | `constants.py:16` |
|
||||
|
||||
This appendix is the minimum viable consistency check. Any second-order
|
||||
port (different robot / different camera) should preserve these numbers
|
||||
verbatim.
|
||||
|
||||
---
|
||||
|
||||
## Appendix B: zero-barrier quickstart from a bare machine
|
||||
|
||||
```bash
|
||||
# === System packages (one-time, sudo) ====================================
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y curl git build-essential ros-noetic-desktop \
|
||||
ros-noetic-joy ros-noetic-tf2-tools \
|
||||
python3-catkin-tools
|
||||
|
||||
# === Install miniconda (skip if you already have one) ====================
|
||||
curl -O https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-$(uname -m).sh
|
||||
bash Miniconda3-latest-Linux-$(uname -m).sh -b -p $HOME/miniconda3
|
||||
echo 'source $HOME/miniconda3/etc/profile.d/conda.sh' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
|
||||
# === Clone this package ==================================================
|
||||
mkdir -p ~/code/odin_sru_nav/src
|
||||
cd ~/code/odin_sru_nav/src
|
||||
git clone https://github.com/<YOUR_FORK>/sru_nav_go2_ros1.git
|
||||
|
||||
# === Conda deps (onnxruntime / cv2 / netifaces / ...) ====================
|
||||
cd sru_nav_go2_ros1
|
||||
bash scripts/setup_conda_env.sh # 5–10 minutes the first time
|
||||
bash scripts/setup_conda_env.sh --check # all PASS before continuing
|
||||
|
||||
# === Build (must be inside the conda env) ================================
|
||||
conda activate sru_nav
|
||||
cd ~/code/odin_sru_nav
|
||||
catkin_make -DPYTHON_EXECUTABLE=$(which python3)
|
||||
source devel/setup.bash
|
||||
|
||||
# === Launch (default: safe mode, requires joystick) ======================
|
||||
cd src/sru_nav_go2_ros1
|
||||
bash scripts/launch_sru_nav.sh
|
||||
|
||||
# Or: lifted-wheel / sim / closed-loop regression (no joystick) ===========
|
||||
bash scripts/launch_sru_nav.sh --no-deadman
|
||||
|
||||
# === Self-check ==========================================================
|
||||
bash scripts/verify_port.sh
|
||||
```
|
||||
|
||||
When `verify_port.sh` is fully green, you are ready for real-robot
|
||||
testing.
|
||||
@@ -0,0 +1,55 @@
|
||||
<?xml version="1.0"?>
|
||||
<!--
|
||||
Launch the SRU navigation controller on Unitree Go2 + Odin1.
|
||||
Assumes the Odin1 ROS1 driver and a Go2 cmd_vel bridge are already running
|
||||
(or will be launched separately).
|
||||
-->
|
||||
<launch>
|
||||
<!-- ============================================================== -->
|
||||
<!-- Top-level arguments -->
|
||||
<!-- ============================================================== -->
|
||||
<arg name="sim" default="false" doc="Treat odom twist as already in base frame."/>
|
||||
<arg name="launch_joy" default="true" doc="Start a joy node alongside (PS5/PS4 etc.)."/>
|
||||
<arg name="launch_static_tf" default="true" doc="Publish a static TF base_link->odin1_base_link."/>
|
||||
<arg name="require_joystick" default="true" doc="If false, bypass the joystick deadman (TESTING ONLY)."/>
|
||||
|
||||
<!-- Odin1 mounting on Go2 (measure on the real platform!).
|
||||
xyz in meters (forward, left, up). rpy in radians.
|
||||
Default below: 25 cm forward of Go2 body center, 18 cm up, no roll/yaw,
|
||||
~20 deg downward pitch (matches original ZED X 0.349 rad config). -->
|
||||
<arg name="odin1_x" default="0.25"/>
|
||||
<arg name="odin1_y" default="0.0"/>
|
||||
<arg name="odin1_z" default="0.18"/>
|
||||
<arg name="odin1_roll" default="0.0"/>
|
||||
<arg name="odin1_pitch" default="0.349"/>
|
||||
<arg name="odin1_yaw" default="0.0"/>
|
||||
|
||||
<!-- ============================================================== -->
|
||||
<!-- Optional joy node -->
|
||||
<!-- ============================================================== -->
|
||||
<node if="$(arg launch_joy)" pkg="joy" type="joy_node" name="joy_node" output="screen">
|
||||
<param name="autorepeat_rate" value="50.0"/>
|
||||
<param name="deadzone" value="0.05"/>
|
||||
</node>
|
||||
|
||||
<!-- ============================================================== -->
|
||||
<!-- Static TF: Go2 base_link -> odin1_base_link -->
|
||||
<!-- Adjust args on the real robot. -->
|
||||
<!-- ============================================================== -->
|
||||
<node if="$(arg launch_static_tf)"
|
||||
pkg="tf2_ros" type="static_transform_publisher"
|
||||
name="static_tf_base_to_odin1"
|
||||
args="$(arg odin1_x) $(arg odin1_y) $(arg odin1_z)
|
||||
$(arg odin1_yaw) $(arg odin1_pitch) $(arg odin1_roll)
|
||||
base_link odin1_base_link"/>
|
||||
|
||||
<!-- ============================================================== -->
|
||||
<!-- SRU navigation node -->
|
||||
<!-- ============================================================== -->
|
||||
<node pkg="sru_nav_go2_ros1" type="sru_nav_node" name="sru_nav_node"
|
||||
output="screen" required="true">
|
||||
<rosparam command="load" file="$(find sru_nav_go2_ros1)/config/sru_nav.yaml"/>
|
||||
<param name="use_sim" value="$(arg sim)"/>
|
||||
<param name="require_joystick" value="$(arg require_joystick)"/>
|
||||
</node>
|
||||
</launch>
|
||||
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0"?>
|
||||
<package format="2">
|
||||
<name>sru_nav_go2_ros1</name>
|
||||
<version>0.1.0</version>
|
||||
<description>
|
||||
ROS1 (Noetic) port of the SRU Navigation controller for Unitree Go2 + Odin1.
|
||||
Loads the pretrained SRU policy (ONNX) and VAE depth encoder, subscribes to
|
||||
Odin1 depth/odom and a joystick, publishes /cmd_vel to Go2.
|
||||
</description>
|
||||
|
||||
<maintainer email="[email protected]">SRU Navigation Port</maintainer>
|
||||
<license>MIT</license>
|
||||
|
||||
<buildtool_depend>catkin</buildtool_depend>
|
||||
|
||||
<depend>rospy</depend>
|
||||
<depend>std_msgs</depend>
|
||||
<depend>sensor_msgs</depend>
|
||||
<depend>geometry_msgs</depend>
|
||||
<depend>nav_msgs</depend>
|
||||
<depend>visualization_msgs</depend>
|
||||
<depend>cv_bridge</depend>
|
||||
<depend>tf2_ros</depend>
|
||||
|
||||
<exec_depend>joy</exec_depend>
|
||||
|
||||
<export>
|
||||
</export>
|
||||
</package>
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env bash
|
||||
# -----------------------------------------------------------------------------
|
||||
# One-shot launcher for the SRU navigation node on Go2 NX.
|
||||
#
|
||||
# Combines a conda python env (onnxruntime, scipy, ...) with the system
|
||||
# ROS Noetic installation (rospy, cv_bridge). The trick:
|
||||
# 1) source /opt/ros/noetic/setup.bash -> ROS env
|
||||
# 2) source <catkin_ws>/devel/setup.bash -> our package
|
||||
# 3) conda activate sru_nav -> python with onnxruntime
|
||||
# 4) export PYTHONPATH=<ros dist-packages>:$PYTHONPATH so conda python
|
||||
# can still import rospy / cv_bridge / sensor_msgs / etc.
|
||||
#
|
||||
# Usage:
|
||||
# bash launch_sru_nav.sh # full launch (joy + static TF + node)
|
||||
# bash launch_sru_nav.sh --no-joy # if /joy is already provided elsewhere
|
||||
# bash launch_sru_nav.sh --no-deadman # TESTING: skip joystick deadman entirely
|
||||
# # (cmd_vel_ratio=1.0, no /joy needed).
|
||||
# # Robot WILL move on /goal_pose alone.
|
||||
# bash launch_sru_nav.sh --node-only # run just sru_nav_node (assume joy + TF already up)
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
set -eu
|
||||
|
||||
ENV_NAME="${ENV_NAME:-sru_nav}"
|
||||
ROS_DISTRO="${ROS_DISTRO:-noetic}"
|
||||
CATKIN_WS="${CATKIN_WS:-$HOME/code/odin_sru_nav}"
|
||||
|
||||
EXTRA_ARGS=""
|
||||
NODE_ONLY=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--no-joy) EXTRA_ARGS="$EXTRA_ARGS launch_joy:=false" ;;
|
||||
--no-tf) EXTRA_ARGS="$EXTRA_ARGS launch_static_tf:=false" ;;
|
||||
--no-deadman) EXTRA_ARGS="$EXTRA_ARGS require_joystick:=false launch_joy:=false" ;;
|
||||
--node-only) NODE_ONLY=1 ;;
|
||||
*) EXTRA_ARGS="$EXTRA_ARGS $arg" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# ---- 1) ROS env -------------------------------------------------------------
|
||||
if [ ! -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then
|
||||
echo "[ERROR] /opt/ros/${ROS_DISTRO}/setup.bash not found"; exit 1
|
||||
fi
|
||||
# shellcheck disable=SC1091
|
||||
source "/opt/ros/${ROS_DISTRO}/setup.bash"
|
||||
|
||||
if [ -f "${CATKIN_WS}/devel/setup.bash" ]; then
|
||||
# shellcheck disable=SC1091
|
||||
source "${CATKIN_WS}/devel/setup.bash"
|
||||
else
|
||||
echo "[WARN] ${CATKIN_WS}/devel/setup.bash not found. Did you catkin_make?"
|
||||
fi
|
||||
|
||||
# ---- 2) conda env -----------------------------------------------------------
|
||||
if ! command -v conda >/dev/null 2>&1; then
|
||||
echo "[ERROR] conda not found. Run setup_conda_env.sh first."; exit 1
|
||||
fi
|
||||
CONDA_BASE="$(conda info --base)"
|
||||
# shellcheck disable=SC1091
|
||||
source "${CONDA_BASE}/etc/profile.d/conda.sh"
|
||||
conda activate "${ENV_NAME}"
|
||||
|
||||
# ---- 3) Make rospy / cv_bridge importable from the conda python -------------
|
||||
ROS_PY_DIST="/opt/ros/${ROS_DISTRO}/lib/python3/dist-packages"
|
||||
export PYTHONPATH="${ROS_PY_DIST}:${PYTHONPATH:-}"
|
||||
|
||||
# Fix conda<->system libffi ABI conflict that breaks cv_bridge:
|
||||
# "libp11-kit.so.0: undefined symbol: ffi_type_pointer, version LIBFFI_BASE_7.0"
|
||||
# Force the system libffi (used to build libp11-kit) to load first.
|
||||
for _sys_libffi in \
|
||||
/lib/aarch64-linux-gnu/libffi.so.7 \
|
||||
/usr/lib/aarch64-linux-gnu/libffi.so.7 \
|
||||
/lib/x86_64-linux-gnu/libffi.so.7 \
|
||||
/usr/lib/x86_64-linux-gnu/libffi.so.7; do
|
||||
if [ -f "${_sys_libffi}" ]; then
|
||||
export LD_PRELOAD="${_sys_libffi}${LD_PRELOAD:+:${LD_PRELOAD}}"
|
||||
echo "[INFO] LD_PRELOAD += ${_sys_libffi}"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
echo "[INFO] python = $(which python)"
|
||||
echo "[INFO] PYTHONPATH = ${PYTHONPATH}"
|
||||
echo "[INFO] ROS_DISTRO = ${ROS_DISTRO}"
|
||||
echo "[INFO] CATKIN_WS = ${CATKIN_WS}"
|
||||
|
||||
# ---- Sanity: catkin wrapper must call conda's python (not system /usr/bin) ---
|
||||
WRAPPER="${CATKIN_WS}/devel/lib/sru_nav_go2_ros1/sru_nav_node"
|
||||
if [ -f "${WRAPPER}" ]; then
|
||||
WRAPPER_SHEBANG="$(head -n1 "${WRAPPER}")"
|
||||
CONDA_PY="$(which python)"
|
||||
case "${WRAPPER_SHEBANG}" in
|
||||
*"${CONDA_PY}"*|*"/usr/bin/env python"*)
|
||||
: # OK
|
||||
;;
|
||||
*)
|
||||
cat >&2 <<EOF
|
||||
[WARN] Catkin-generated wrapper shebang is NOT the conda python:
|
||||
wrapper : ${WRAPPER}
|
||||
shebang : ${WRAPPER_SHEBANG}
|
||||
conda py: ${CONDA_PY}
|
||||
It will likely fail with 'No module named cv2 / onnxruntime'.
|
||||
Fix:
|
||||
conda activate ${ENV_NAME}
|
||||
cd ${CATKIN_WS}
|
||||
catkin_make clean
|
||||
catkin_make -DPYTHON_EXECUTABLE=\$(which python3)
|
||||
EOF
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# ---- 4) Launch --------------------------------------------------------------
|
||||
if [ "$NODE_ONLY" -eq 1 ]; then
|
||||
exec rosrun sru_nav_go2_ros1 sru_nav_node \
|
||||
__ns:= \
|
||||
_vae_model_path:="" _policy_model_path:=""
|
||||
else
|
||||
# shellcheck disable=SC2086
|
||||
exec roslaunch sru_nav_go2_ros1 sru_nav_go2.launch $EXTRA_ARGS
|
||||
fi
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env bash
|
||||
# -----------------------------------------------------------------------------
|
||||
# Conda environment bootstrap for sru_nav_go2_ros1 on Go2 NX (Jetson Xavier NX)
|
||||
# -----------------------------------------------------------------------------
|
||||
# Goal: create a python env containing onnxruntime + cv2 + scipy + numpy that
|
||||
# works alongside system ROS Noetic (which provides rospy / cv_bridge).
|
||||
#
|
||||
# We do NOT install rospy / cv_bridge into conda. They come from /opt/ros/noetic
|
||||
# (system python3.8). To make them importable from the conda env we expose the
|
||||
# ROS site-packages via PYTHONPATH at run time (see launch_sru_nav.sh).
|
||||
#
|
||||
# Usage:
|
||||
# bash setup_conda_env.sh # create env and install deps
|
||||
# bash setup_conda_env.sh --gpu # try to install Jetson onnxruntime-gpu wheel
|
||||
# bash setup_conda_env.sh --check # just run sanity checks
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
set -eu
|
||||
|
||||
ENV_NAME="${ENV_NAME:-sru_nav}"
|
||||
PY_VER="${PY_VER:-3.8}" # match Noetic's system python so rospy works
|
||||
USE_GPU=0
|
||||
CHECK_ONLY=0
|
||||
SKIP_TIME_CHECK=0
|
||||
|
||||
# Silence anaconda.org's noisy "aau_token_host" telemetry warnings.
|
||||
export ANACONDA_ANON_USAGE=false
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--gpu) USE_GPU=1 ;;
|
||||
--check) CHECK_ONLY=1 ;;
|
||||
--skip-time-check) SKIP_TIME_CHECK=1 ;;
|
||||
*) echo "Unknown arg: $arg"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 0. System clock sanity. SSL fails with "certificate is not yet valid" when
|
||||
# the Jetson clock is rolled back (no RTC battery). Detect early.
|
||||
# -----------------------------------------------------------------------------
|
||||
if [ "$SKIP_TIME_CHECK" -eq 0 ]; then
|
||||
NOW_EPOCH=$(date +%s)
|
||||
# 2025-01-01 UTC = 1735689600. Treat anything before that as suspicious.
|
||||
if [ "$NOW_EPOCH" -lt 1735689600 ]; then
|
||||
cat >&2 <<EOF
|
||||
[ERROR] System clock looks wrong: $(date)
|
||||
This will break HTTPS/pip with "certificate is not yet valid".
|
||||
Fix it before continuing:
|
||||
|
||||
sudo timedatectl set-ntp true
|
||||
sudo systemctl restart systemd-timesyncd
|
||||
# or, offline:
|
||||
sudo date -s "$(date -u +'%Y-%m-%d %H:%M:%S' -d '@1748400000')"
|
||||
sudo hwclock --systohc
|
||||
|
||||
Then re-run this script. To override (NOT recommended) pass:
|
||||
bash $0 --skip-time-check
|
||||
EOF
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 1. Locate conda
|
||||
# -----------------------------------------------------------------------------
|
||||
if ! command -v conda >/dev/null 2>&1; then
|
||||
echo "[ERROR] conda not found. Install miniforge (recommended for aarch64):"
|
||||
echo " wget https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-Linux-aarch64.sh"
|
||||
echo " bash Miniforge3-Linux-aarch64.sh -b -p \$HOME/miniforge3"
|
||||
echo " source \$HOME/miniforge3/etc/profile.d/conda.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CONDA_BASE="$(conda info --base)"
|
||||
# shellcheck disable=SC1091
|
||||
source "${CONDA_BASE}/etc/profile.d/conda.sh"
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 2. Create env if missing
|
||||
# -----------------------------------------------------------------------------
|
||||
if [ "$CHECK_ONLY" -eq 0 ]; then
|
||||
if conda env list | awk '{print $1}' | grep -qx "${ENV_NAME}"; then
|
||||
echo "[INFO] Conda env '${ENV_NAME}' already exists. Skipping creation."
|
||||
else
|
||||
echo "[INFO] Creating conda env '${ENV_NAME}' with python=${PY_VER}"
|
||||
conda create -y -n "${ENV_NAME}" "python=${PY_VER}" pip
|
||||
fi
|
||||
fi
|
||||
|
||||
conda activate "${ENV_NAME}"
|
||||
|
||||
if [ "$CHECK_ONLY" -eq 0 ]; then
|
||||
echo "[INFO] Installing Python dependencies into '${ENV_NAME}'"
|
||||
# Optional: use a faster mirror (Tsinghua) if PIP_INDEX_URL is not already set.
|
||||
: "${PIP_INDEX_URL:=}"
|
||||
export PIP_INDEX_URL
|
||||
echo "[INFO] PIP_INDEX_URL=${PIP_INDEX_URL}"
|
||||
|
||||
python -m pip install --upgrade pip
|
||||
# Pin versions that are known to work on python 3.8 + ARM.
|
||||
# netifaces / defusedxml are needed by rospy at runtime (the system ROS
|
||||
# python gets them via apt 'python3-netifaces / python3-defusedxml', but
|
||||
# the conda python does not).
|
||||
python -m pip install \
|
||||
"numpy<2.0" \
|
||||
"scipy>=1.7,<1.11" \
|
||||
"opencv-python>=4.5,<5.0" \
|
||||
"rospkg" \
|
||||
"pyyaml" \
|
||||
"empy==3.3.4" \
|
||||
"netifaces" \
|
||||
"defusedxml"
|
||||
|
||||
if [ "$USE_GPU" -eq 1 ]; then
|
||||
cat <<'EOF'
|
||||
[INFO] --gpu requested. Standard pip onnxruntime-gpu does NOT work on Jetson.
|
||||
Download the JetPack-matched wheel from NVIDIA's Jetson Zoo:
|
||||
https://elinux.org/Jetson_Zoo#ONNX_Runtime
|
||||
Then install with e.g.:
|
||||
pip install ./onnxruntime_gpu-<ver>-cp38-cp38-linux_aarch64.whl
|
||||
Skipping automatic GPU wheel install.
|
||||
EOF
|
||||
python -m pip install "onnxruntime>=1.15,<1.18" # CPU fallback so node still runs
|
||||
else
|
||||
python -m pip install "onnxruntime>=1.15,<1.18"
|
||||
fi
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# 3. Sanity checks
|
||||
# -----------------------------------------------------------------------------
|
||||
echo
|
||||
echo "============================================================"
|
||||
echo " Sanity check: conda env '${ENV_NAME}'"
|
||||
echo "============================================================"
|
||||
python - <<'PYEOF'
|
||||
import sys, platform
|
||||
print(f"python : {sys.version.split()[0]} ({platform.machine()})")
|
||||
fail = []
|
||||
|
||||
def check(name, importer):
|
||||
try:
|
||||
mod = importer()
|
||||
ver = getattr(mod, "__version__", "?")
|
||||
print(f" [OK] {name:18s} {ver}")
|
||||
except Exception as e:
|
||||
print(f" [FAIL] {name}: {e}")
|
||||
fail.append(name)
|
||||
|
||||
check("numpy", lambda: __import__("numpy"))
|
||||
check("scipy", lambda: __import__("scipy"))
|
||||
check("cv2", lambda: __import__("cv2"))
|
||||
check("rospkg", lambda: __import__("rospkg"))
|
||||
check("netifaces", lambda: __import__("netifaces"))
|
||||
check("defusedxml", lambda: __import__("defusedxml"))
|
||||
check("onnxruntime", lambda: __import__("onnxruntime"))
|
||||
|
||||
try:
|
||||
import onnxruntime as ort
|
||||
print(f" ORT providers : {ort.get_available_providers()}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# rospy / cv_bridge come from /opt/ros/noetic; only succeed when PYTHONPATH is set.
|
||||
import os
|
||||
ros_path = "/opt/ros/noetic/lib/python3/dist-packages"
|
||||
if os.path.isdir(ros_path) and ros_path not in sys.path:
|
||||
sys.path.insert(0, ros_path)
|
||||
|
||||
check("rospy", lambda: __import__("rospy"))
|
||||
check("cv_bridge", lambda: __import__("cv_bridge"))
|
||||
|
||||
if fail:
|
||||
print(f"\n[WARN] Missing modules: {fail}")
|
||||
sys.exit(1)
|
||||
print("\n[OK] All imports passed.")
|
||||
PYEOF
|
||||
|
||||
echo
|
||||
echo "[INFO] Try loading the policy ONNX files (if present)..."
|
||||
# Resolve the package's models/ directory relative to THIS script.
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PKG_MODELS_DIR="$(cd "${SCRIPT_DIR}/../models" 2>/dev/null && pwd || echo '')"
|
||||
export PKG_MODELS_DIR
|
||||
python - <<'PYEOF'
|
||||
import os, sys
|
||||
candidates = [
|
||||
os.environ.get("PKG_MODELS_DIR", ""),
|
||||
os.path.expanduser("~/sru_ws/src/sru_nav_go2_ros1/models"),
|
||||
]
|
||||
candidates = [c for c in candidates if c]
|
||||
import onnxruntime as ort
|
||||
for d in candidates:
|
||||
vae = os.path.join(d, "vae_encoder.onnx")
|
||||
pol = os.path.join(d, "nav_policy.onnx")
|
||||
if os.path.exists(vae) and os.path.exists(pol):
|
||||
print(f" Found models in {d}")
|
||||
try:
|
||||
s1 = ort.InferenceSession(vae, providers=["CPUExecutionProvider"])
|
||||
s2 = ort.InferenceSession(pol, providers=["CPUExecutionProvider"])
|
||||
print(f" vae inputs : {[i.name+str(i.shape) for i in s1.get_inputs()]}")
|
||||
print(f" vae outputs : {[o.name+str(o.shape) for o in s1.get_outputs()]}")
|
||||
print(f" pol inputs : {[i.name+str(i.shape) for i in s2.get_inputs()]}")
|
||||
print(f" pol outputs : {[o.name+str(o.shape) for o in s2.get_outputs()]}")
|
||||
except Exception as e:
|
||||
print(f" [FAIL] {e}")
|
||||
break
|
||||
else:
|
||||
print(" (No models found; skipping ORT smoke test.)")
|
||||
PYEOF
|
||||
|
||||
echo
|
||||
echo "[DONE] Activate with: conda activate ${ENV_NAME}"
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""ROS1 entry point for the SRU navigation controller on Go2 + Odin1."""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import rospkg
|
||||
import rospy
|
||||
|
||||
from sru_nav_go2.navigation_policy_node import NavigationPolicyNode
|
||||
from sru_nav_go2 import constants
|
||||
|
||||
|
||||
def _resolve_model_path(param_value, default_basename):
|
||||
"""Resolve a model path: absolute path if given, else look under
|
||||
<package>/models/<default_basename>, else fall back to the original
|
||||
sru-robot-deployment/rl_nav_controller/deployment_policies/ folder if
|
||||
present alongside this package's workspace.
|
||||
"""
|
||||
if param_value and os.path.isabs(param_value) and os.path.exists(param_value):
|
||||
return param_value
|
||||
|
||||
rp = rospkg.RosPack()
|
||||
try:
|
||||
pkg_path = rp.get_path('sru_nav_go2_ros1')
|
||||
except rospkg.ResourceNotFound:
|
||||
pkg_path = None
|
||||
|
||||
candidates = []
|
||||
if param_value:
|
||||
candidates.append(param_value)
|
||||
if pkg_path:
|
||||
candidates.append(os.path.join(pkg_path, 'models', default_basename))
|
||||
# Sibling deployment_policies folder (when sources are checked out together)
|
||||
candidates.append(os.path.join(
|
||||
pkg_path, '..', '..', 'sru-robot-deployment',
|
||||
'rl_nav_controller', 'deployment_policies', default_basename))
|
||||
|
||||
for c in candidates:
|
||||
if c and os.path.exists(c):
|
||||
return os.path.abspath(c)
|
||||
|
||||
raise FileNotFoundError(
|
||||
'Could not locate {} (checked: {})'.format(default_basename, candidates)
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
rospy.init_node('sru_nav_node', anonymous=False)
|
||||
|
||||
# --- Topics ---------------------------------------------------------
|
||||
depth_topic = rospy.get_param('~depth_topic', '/odin1/depth_img_competetion')
|
||||
odom_topic = rospy.get_param('~odom_topic', '/odin1/odometry_highfreq')
|
||||
joy_topic = rospy.get_param('~joy_topic', '/joy')
|
||||
goal_topic = rospy.get_param('~goal_topic', '/goal_pose')
|
||||
cmd_vel_topic = rospy.get_param('~cmd_vel_topic', '/cmd_vel')
|
||||
|
||||
# --- Models ---------------------------------------------------------
|
||||
vae_param = rospy.get_param('~vae_model_path', '')
|
||||
pol_param = rospy.get_param('~policy_model_path', '')
|
||||
try:
|
||||
vae_model_path = _resolve_model_path(vae_param, 'vae_encoder.onnx')
|
||||
policy_model_path = _resolve_model_path(pol_param, 'nav_policy.onnx')
|
||||
except FileNotFoundError as exc:
|
||||
rospy.logerr(str(exc))
|
||||
sys.exit(1)
|
||||
rospy.loginfo('VAE encoder: {}'.format(vae_model_path))
|
||||
rospy.loginfo('Policy model: {}'.format(policy_model_path))
|
||||
|
||||
# --- Numeric params -------------------------------------------------
|
||||
min_depth = rospy.get_param('~min_depth', constants.DEFAULT_MIN_DEPTH)
|
||||
max_depth = rospy.get_param('~max_depth', constants.DEFAULT_MAX_DEPTH)
|
||||
control_frequency = rospy.get_param(
|
||||
'~control_frequency', constants.DEFAULT_CONTROL_FREQUENCY)
|
||||
policy_scale = rospy.get_param('~policy_scale', list(constants.POLICY_SCALE))
|
||||
use_sim = rospy.get_param('~use_sim', False)
|
||||
require_joystick = rospy.get_param('~require_joystick', True)
|
||||
|
||||
if not isinstance(policy_scale, (list, tuple)) or len(policy_scale) != 3:
|
||||
rospy.logwarn('Invalid ~policy_scale, falling back to {}'.format(
|
||||
list(constants.POLICY_SCALE)))
|
||||
policy_scale = list(constants.POLICY_SCALE)
|
||||
|
||||
NavigationPolicyNode(
|
||||
preprocess_model_path=vae_model_path,
|
||||
policy_model_path=policy_model_path,
|
||||
depth_topic=depth_topic,
|
||||
odom_topic=odom_topic,
|
||||
joy_topic=joy_topic,
|
||||
goal_topic=goal_topic,
|
||||
cmd_vel_topic=cmd_vel_topic,
|
||||
min_depth=min_depth,
|
||||
max_depth=max_depth,
|
||||
control_frequency=control_frequency,
|
||||
policy_scale=policy_scale,
|
||||
use_sim=use_sim,
|
||||
require_joystick=require_joystick,
|
||||
)
|
||||
|
||||
rospy.loginfo(
|
||||
'SRU navigation node spinning (sim={}, require_joystick={}).'
|
||||
.format(use_sim, require_joystick))
|
||||
rospy.spin()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
#!/usr/bin/env bash
|
||||
# -----------------------------------------------------------------------------
|
||||
# verify_port.sh — automated acceptance checks for sru_nav_go2_ros1
|
||||
#
|
||||
# Run after generating (or updating) the package to confirm the port is
|
||||
# self-consistent and ready for hardware testing.
|
||||
#
|
||||
# Usage:
|
||||
# bash scripts/verify_port.sh # full check
|
||||
# bash scripts/verify_port.sh --skip-roslaunch # skip the live node test
|
||||
# ENV_NAME=my_env CATKIN_WS=/path bash scripts/verify_port.sh
|
||||
#
|
||||
# Exit code: 0 if everything passes, 1 otherwise.
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
set -u
|
||||
|
||||
ENV_NAME="${ENV_NAME:-sru_nav}"
|
||||
ROS_DISTRO="${ROS_DISTRO:-noetic}"
|
||||
CATKIN_WS="${CATKIN_WS:-$HOME/code/odin_sru_nav}"
|
||||
|
||||
PKG_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
SKIP_ROSLAUNCH=0
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--skip-roslaunch) SKIP_ROSLAUNCH=1 ;;
|
||||
-h|--help)
|
||||
sed -n '2,15p' "$0"; exit 0 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
WARN=0
|
||||
|
||||
c_red() { printf "\033[31m%s\033[0m" "$1"; }
|
||||
c_green() { printf "\033[32m%s\033[0m" "$1"; }
|
||||
c_yellow() { printf "\033[33m%s\033[0m" "$1"; }
|
||||
|
||||
ok() { echo " [$(c_green PASS)] $1"; PASS=$((PASS+1)); }
|
||||
fail() { echo " [$(c_red FAIL)] $1"; FAIL=$((FAIL+1)); }
|
||||
warn() { echo " [$(c_yellow WARN)] $1"; WARN=$((WARN+1)); }
|
||||
info() { echo " [INFO] $1"; }
|
||||
|
||||
section() { echo; echo "=== $1 ==="; }
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "0. Environment"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
info "PKG_DIR = ${PKG_DIR}"
|
||||
info "CATKIN_WS = ${CATKIN_WS}"
|
||||
info "ENV_NAME = ${ENV_NAME}"
|
||||
info "ROS_DISTRO = ${ROS_DISTRO}"
|
||||
|
||||
# OS
|
||||
if grep -q "Ubuntu 20.04" /etc/os-release 2>/dev/null; then
|
||||
ok "Ubuntu 20.04 (Noetic-compatible)"
|
||||
else
|
||||
warn "OS is not Ubuntu 20.04 — Noetic may not run cleanly"
|
||||
fi
|
||||
|
||||
# ROS
|
||||
if [ -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then
|
||||
ok "ROS ${ROS_DISTRO} installed"
|
||||
else
|
||||
fail "/opt/ros/${ROS_DISTRO}/setup.bash not found"
|
||||
fi
|
||||
|
||||
# Conda
|
||||
if command -v conda >/dev/null 2>&1; then
|
||||
ok "conda available ($(conda --version))"
|
||||
else
|
||||
fail "conda not found in PATH"
|
||||
fi
|
||||
|
||||
# System clock
|
||||
year=$(date +%Y)
|
||||
if [ "$year" -ge 2024 ] && [ "$year" -le 2099 ]; then
|
||||
ok "system clock looks sane ($(date '+%Y-%m-%d %H:%M:%S'))"
|
||||
else
|
||||
fail "system clock implausible ($(date)) — pip TLS will fail"
|
||||
fi
|
||||
|
||||
# libffi
|
||||
if ls /lib/*-linux-gnu/libffi.so.7 2>/dev/null >/dev/null; then
|
||||
ok "system libffi.so.7 present (LD_PRELOAD target)"
|
||||
elif ls /lib/*-linux-gnu/libffi.so.8 2>/dev/null >/dev/null; then
|
||||
warn "only libffi.so.8 found — update launch_sru_nav.sh accordingly"
|
||||
else
|
||||
fail "no system libffi.so.* — cv_bridge will likely fail"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "1. Package layout"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
req_files=(
|
||||
"package.xml"
|
||||
"CMakeLists.txt"
|
||||
"setup.py"
|
||||
"launch/sru_nav_go2.launch"
|
||||
"config/sru_nav.yaml"
|
||||
"scripts/sru_nav_node"
|
||||
"scripts/launch_sru_nav.sh"
|
||||
"scripts/setup_conda_env.sh"
|
||||
"src/sru_nav_go2/__init__.py"
|
||||
"src/sru_nav_go2/constants.py"
|
||||
"src/sru_nav_go2/model.py"
|
||||
"src/sru_nav_go2/utils.py"
|
||||
"src/sru_nav_go2/visualization.py"
|
||||
"src/sru_nav_go2/waypoint_manager.py"
|
||||
"src/sru_nav_go2/navigation_policy_node.py"
|
||||
"models/vae_encoder.onnx"
|
||||
"models/nav_policy.onnx"
|
||||
)
|
||||
|
||||
for f in "${req_files[@]}"; do
|
||||
if [ -e "${PKG_DIR}/${f}" ]; then
|
||||
ok "${f}"
|
||||
else
|
||||
fail "missing: ${f}"
|
||||
fi
|
||||
done
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "2. YAML config — required parameters"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
YAML="${PKG_DIR}/config/sru_nav.yaml"
|
||||
if [ -f "$YAML" ]; then
|
||||
for key in depth_topic odom_topic joy_topic goal_topic cmd_vel_topic \
|
||||
min_depth max_depth control_frequency policy_scale \
|
||||
use_sim require_joystick; do
|
||||
if grep -E "^[[:space:]]*${key}[[:space:]]*:" "$YAML" >/dev/null; then
|
||||
ok "yaml has ${key}"
|
||||
else
|
||||
fail "yaml missing ${key}"
|
||||
fi
|
||||
done
|
||||
else
|
||||
fail "yaml not found"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "3. Constants — training-aligned numerics"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
CONSTS="${PKG_DIR}/src/sru_nav_go2/constants.py"
|
||||
if [ -f "$CONSTS" ]; then
|
||||
declare -A want=(
|
||||
[DEFAULT_CONTROL_FREQUENCY]="5"
|
||||
[DEFAULT_MIN_DEPTH]="0.25"
|
||||
[DEFAULT_MAX_DEPTH]="10"
|
||||
[JOYSTICK_TIMEOUT]="15"
|
||||
)
|
||||
for k in "${!want[@]}"; do
|
||||
if grep -E "^${k}\s*=\s*${want[$k]}" "$CONSTS" >/dev/null; then
|
||||
ok "${k} = ${want[$k]}"
|
||||
else
|
||||
warn "${k} not exactly ${want[$k]} — verify against training cfg"
|
||||
fi
|
||||
done
|
||||
else
|
||||
fail "constants.py not found"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "4. Launch script — coexistence fixes"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
LAUNCH_SH="${PKG_DIR}/scripts/launch_sru_nav.sh"
|
||||
if [ -f "$LAUNCH_SH" ]; then
|
||||
grep -q "LD_PRELOAD" "$LAUNCH_SH" && ok "LD_PRELOAD libffi fix present" \
|
||||
|| fail "no LD_PRELOAD libffi fix"
|
||||
grep -q "PYTHONPATH" "$LAUNCH_SH" && ok "ROS dist-packages injected to PYTHONPATH" \
|
||||
|| fail "no PYTHONPATH injection"
|
||||
grep -q "conda activate" "$LAUNCH_SH" && ok "conda activate in launcher" \
|
||||
|| fail "no conda activate"
|
||||
grep -q -- "--no-deadman" "$LAUNCH_SH" && ok "--no-deadman bypass present" \
|
||||
|| warn "no --no-deadman flag"
|
||||
fi
|
||||
|
||||
SETUP_SH="${PKG_DIR}/scripts/setup_conda_env.sh"
|
||||
if [ -f "$SETUP_SH" ]; then
|
||||
for pkg in onnxruntime netifaces defusedxml opencv-python rospkg empy; do
|
||||
grep -q "$pkg" "$SETUP_SH" \
|
||||
&& ok "setup installs ${pkg}" \
|
||||
|| fail "setup script missing ${pkg}"
|
||||
done
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "5. ONNX models — load test"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
if command -v python >/dev/null && python -c "import onnxruntime" 2>/dev/null; then
|
||||
for f in "models/vae_encoder.onnx" "models/nav_policy.onnx"; do
|
||||
full="${PKG_DIR}/${f}"
|
||||
if [ -f "$full" ]; then
|
||||
if python - <<EOF 2>/dev/null
|
||||
import onnxruntime as ort, sys
|
||||
s = ort.InferenceSession("${full}", providers=["CPUExecutionProvider"])
|
||||
print(" ${f} inputs:", [(i.name, i.shape) for i in s.get_inputs()])
|
||||
print(" ${f} outputs:", [(o.name, o.shape) for o in s.get_outputs()])
|
||||
EOF
|
||||
then
|
||||
ok "${f} loads in onnxruntime"
|
||||
else
|
||||
fail "${f} failed to load (corrupt or wrong opset?)"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
else
|
||||
warn "onnxruntime not importable in current shell — skipping load test"
|
||||
warn " hint: 'conda activate ${ENV_NAME}' before running verify_port.sh"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "6. catkin build artifacts (optional)"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
WRAPPER="${CATKIN_WS}/devel/lib/sru_nav_go2_ros1/sru_nav_node"
|
||||
if [ -f "$WRAPPER" ]; then
|
||||
ok "catkin wrapper exists: ${WRAPPER}"
|
||||
shebang=$(head -n1 "$WRAPPER")
|
||||
if echo "$shebang" | grep -qE "miniconda|anaconda|envs/${ENV_NAME}"; then
|
||||
ok "wrapper shebang points at conda python"
|
||||
info " shebang: ${shebang}"
|
||||
else
|
||||
fail "wrapper shebang is NOT conda python: ${shebang}"
|
||||
info " fix: 'conda activate ${ENV_NAME} && cd ${CATKIN_WS} && \\"
|
||||
info " catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=\$(which python3)'"
|
||||
fi
|
||||
else
|
||||
warn "no catkin build artifact — run catkin_make in conda env first"
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "7. Live roslaunch smoke test"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
if [ "$SKIP_ROSLAUNCH" -eq 1 ]; then
|
||||
info "skipped (--skip-roslaunch)"
|
||||
elif [ ! -f "${CATKIN_WS}/devel/setup.bash" ]; then
|
||||
warn "catkin workspace not built — skipping roslaunch test"
|
||||
else
|
||||
# shellcheck disable=SC1090
|
||||
source "/opt/ros/${ROS_DISTRO}/setup.bash" || true
|
||||
source "${CATKIN_WS}/devel/setup.bash" || true
|
||||
|
||||
if ! command -v roslaunch >/dev/null; then
|
||||
fail "roslaunch not on PATH after sourcing"
|
||||
else
|
||||
LOG=$(mktemp)
|
||||
timeout 12 roslaunch sru_nav_go2_ros1 sru_nav_go2.launch \
|
||||
launch_joy:=false launch_static_tf:=false \
|
||||
require_joystick:=false >"$LOG" 2>&1 &
|
||||
RPID=$!
|
||||
sleep 8
|
||||
if grep -q "Navigation policy node is ready" "$LOG"; then
|
||||
ok "node became ready within 8 s"
|
||||
else
|
||||
fail "node did not reach 'ready' state within 8 s"
|
||||
info " last 20 log lines:"
|
||||
tail -n 20 "$LOG" | sed 's/^/ /'
|
||||
fi
|
||||
kill "$RPID" 2>/dev/null
|
||||
wait "$RPID" 2>/dev/null
|
||||
rm -f "$LOG"
|
||||
fi
|
||||
fi
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
section "Summary"
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
echo " PASS=${PASS} FAIL=${FAIL} WARN=${WARN}"
|
||||
if [ "$FAIL" -gt 0 ]; then
|
||||
echo
|
||||
c_red "RESULT: FAIL"; echo
|
||||
exit 1
|
||||
elif [ "$WARN" -gt 0 ]; then
|
||||
echo
|
||||
c_yellow "RESULT: PASS WITH WARNINGS"; echo
|
||||
exit 0
|
||||
else
|
||||
echo
|
||||
c_green "ALL CHECKS PASSED"; echo
|
||||
exit 0
|
||||
fi
|
||||
@@ -0,0 +1,331 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sequential waypoint runner for sru_nav_go2_ros1.
|
||||
|
||||
Publishes a list of goals to /goal_pose one at a time, monitors the robot
|
||||
odometry to decide when each goal is reached (or has timed out, or the robot
|
||||
is stuck), then moves on to the next. After the last waypoint, optionally
|
||||
returns to the pose captured at script start.
|
||||
|
||||
Does NOT modify any code in sru_nav_go2_ros1. Works purely as an external
|
||||
client on top of the existing /goal_pose + /odin1/odometry_highfreq contract.
|
||||
|
||||
Usage
|
||||
-----
|
||||
# YAML file
|
||||
rosrun sru_nav_go2_ros1 waypoint_runner.py --file waypoints.yaml
|
||||
|
||||
# Command line (x,y[,z] tuples separated by spaces)
|
||||
rosrun sru_nav_go2_ros1 waypoint_runner.py \
|
||||
--waypoints "3,0 3,2 0,2" --return-home
|
||||
|
||||
YAML format
|
||||
-----------
|
||||
frame_id: odom
|
||||
arrive_threshold: 0.75 # meters, XY distance to consider 'arrived'
|
||||
settle_time: 1.5 # seconds the robot must stay within threshold
|
||||
per_goal_timeout: 60.0 # seconds before giving up on a goal
|
||||
stuck_window: 10.0 # seconds of trailing window for stuck check
|
||||
stuck_displacement: 0.10 # meters; below this in `stuck_window` -> skip
|
||||
republish_interval: 5.0 # seconds; re-publish the same goal periodically
|
||||
return_home: true
|
||||
waypoints:
|
||||
- [3.0, 0.0, 0.0]
|
||||
- [3.0, 2.0, 0.0]
|
||||
- [0.0, 2.0, 0.0]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rospy
|
||||
import yaml
|
||||
from geometry_msgs.msg import PoseStamped
|
||||
from nav_msgs.msg import Odometry
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Defaults (mirror sru_nav_go2_ros1/constants.py where applicable)
|
||||
# ---------------------------------------------------------------------------
|
||||
DEFAULTS = dict(
|
||||
frame_id='odom',
|
||||
arrive_threshold=0.75, # matches constants.ARRIVE_GOAL_THRESHOLD
|
||||
settle_time=1.5,
|
||||
per_goal_timeout=60.0,
|
||||
stuck_window=10.0,
|
||||
stuck_displacement=0.10,
|
||||
republish_interval=5.0,
|
||||
return_home=True,
|
||||
odom_topic='/odin1/odometry_highfreq',
|
||||
goal_topic='/goal_pose',
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Parsing
|
||||
# ---------------------------------------------------------------------------
|
||||
def _parse_inline_waypoints(text):
|
||||
"""Parse "x,y[,z] x,y[,z] ..." into list[list[float]]."""
|
||||
out = []
|
||||
if not text:
|
||||
return out
|
||||
for tok in text.split():
|
||||
parts = tok.split(',')
|
||||
if len(parts) not in (2, 3):
|
||||
raise ValueError(
|
||||
"Bad waypoint '{}': expected 'x,y' or 'x,y,z'".format(tok))
|
||||
xyz = [float(parts[0]), float(parts[1]),
|
||||
float(parts[2]) if len(parts) == 3 else 0.0]
|
||||
out.append(xyz)
|
||||
return out
|
||||
|
||||
|
||||
def _load_yaml(path):
|
||||
with open(path, 'r') as f:
|
||||
data = yaml.safe_load(f) or {}
|
||||
if 'waypoints' not in data or not data['waypoints']:
|
||||
raise ValueError("YAML '{}' has no 'waypoints' list.".format(path))
|
||||
norm = []
|
||||
for wp in data['waypoints']:
|
||||
if len(wp) not in (2, 3):
|
||||
raise ValueError("Bad waypoint {} (need 2 or 3 floats).".format(wp))
|
||||
x = float(wp[0]); y = float(wp[1])
|
||||
z = float(wp[2]) if len(wp) == 3 else 0.0
|
||||
norm.append([x, y, z])
|
||||
data['waypoints'] = norm
|
||||
return data
|
||||
|
||||
|
||||
def build_config(args):
|
||||
cfg = dict(DEFAULTS)
|
||||
if args.file:
|
||||
cfg.update({k: v for k, v in _load_yaml(args.file).items() if v is not None})
|
||||
# Command-line overrides win over YAML
|
||||
if args.waypoints:
|
||||
cfg['waypoints'] = _parse_inline_waypoints(args.waypoints)
|
||||
if args.frame_id is not None:
|
||||
cfg['frame_id'] = args.frame_id
|
||||
if args.timeout is not None:
|
||||
cfg['per_goal_timeout'] = float(args.timeout)
|
||||
if args.arrive_threshold is not None:
|
||||
cfg['arrive_threshold'] = float(args.arrive_threshold)
|
||||
if args.return_home is not None:
|
||||
cfg['return_home'] = args.return_home
|
||||
if 'waypoints' not in cfg or not cfg['waypoints']:
|
||||
raise ValueError("No waypoints provided (use --file or --waypoints).")
|
||||
return cfg
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Runner
|
||||
# ---------------------------------------------------------------------------
|
||||
class WaypointRunner(object):
|
||||
def __init__(self, cfg):
|
||||
self.cfg = cfg
|
||||
|
||||
self._pose = None # latest (x, y, z, t)
|
||||
self._pose_history = collections.deque() # entries: (t, x, y)
|
||||
self._home = None # (x, y, z) captured at first odom
|
||||
|
||||
self.goal_pub = rospy.Publisher(
|
||||
cfg['goal_topic'], PoseStamped, queue_size=1, latch=True)
|
||||
self.odom_sub = rospy.Subscriber(
|
||||
cfg['odom_topic'], Odometry, self._odom_cb, queue_size=20)
|
||||
|
||||
rospy.loginfo("waypoint_runner: waiting for first odom on '%s' ...",
|
||||
cfg['odom_topic'])
|
||||
self._wait_for_odom(timeout=30.0)
|
||||
self._home = (self._pose[0], self._pose[1], self._pose[2])
|
||||
rospy.loginfo("waypoint_runner: home pose captured at "
|
||||
"x=%.3f y=%.3f z=%.3f", *self._home)
|
||||
|
||||
# Give the latched publisher a moment so the first goal isn't lost.
|
||||
time.sleep(0.5)
|
||||
|
||||
# --------------------------------------------------------------- callbacks
|
||||
def _odom_cb(self, msg):
|
||||
t = msg.header.stamp.to_sec() or rospy.get_time()
|
||||
p = msg.pose.pose.position
|
||||
self._pose = (p.x, p.y, p.z, t)
|
||||
self._pose_history.append((t, p.x, p.y))
|
||||
# Trim history to a bit more than stuck_window
|
||||
cutoff = t - max(self.cfg['stuck_window'] * 2.0, 5.0)
|
||||
while self._pose_history and self._pose_history[0][0] < cutoff:
|
||||
self._pose_history.popleft()
|
||||
|
||||
def _wait_for_odom(self, timeout):
|
||||
t0 = time.time()
|
||||
rate = rospy.Rate(20)
|
||||
while not rospy.is_shutdown() and self._pose is None:
|
||||
if time.time() - t0 > timeout:
|
||||
raise RuntimeError(
|
||||
"No odometry received on '{}' within {:.1f}s.".format(
|
||||
self.cfg['odom_topic'], timeout))
|
||||
rate.sleep()
|
||||
|
||||
# ------------------------------------------------------------------ goals
|
||||
def _publish_goal(self, xyz):
|
||||
msg = PoseStamped()
|
||||
msg.header.stamp = rospy.Time.now()
|
||||
msg.header.frame_id = self.cfg['frame_id']
|
||||
msg.pose.position.x = float(xyz[0])
|
||||
msg.pose.position.y = float(xyz[1])
|
||||
msg.pose.position.z = float(xyz[2])
|
||||
msg.pose.orientation.w = 1.0
|
||||
self.goal_pub.publish(msg)
|
||||
|
||||
def _xy_dist(self, ax, ay, bx, by):
|
||||
return math.hypot(ax - bx, ay - by)
|
||||
|
||||
def _displacement_in_window(self, window):
|
||||
"""Max XY distance between any two samples within trailing `window` s."""
|
||||
# Snapshot first: _odom_cb runs in the subscriber thread and may
|
||||
# append/popleft while we iterate, which raises
|
||||
# "deque mutated during iteration".
|
||||
snapshot = list(self._pose_history)
|
||||
if not snapshot:
|
||||
return 0.0
|
||||
now = snapshot[-1][0]
|
||||
cutoff = now - window
|
||||
pts = [(x, y) for (t, x, y) in snapshot if t >= cutoff]
|
||||
if len(pts) < 2:
|
||||
return 0.0
|
||||
xs = [p[0] for p in pts]; ys = [p[1] for p in pts]
|
||||
# Bounding box diagonal is a cheap, monotone proxy for "did it move".
|
||||
return math.hypot(max(xs) - min(xs), max(ys) - min(ys))
|
||||
|
||||
def _run_goal(self, idx, total, xyz, label):
|
||||
cfg = self.cfg
|
||||
rospy.loginfo("\033[96m[%d/%d %s] -> x=%.3f y=%.3f z=%.3f\033[0m",
|
||||
idx, total, label, xyz[0], xyz[1], xyz[2])
|
||||
self._publish_goal(xyz)
|
||||
|
||||
t_start = time.time()
|
||||
t_last_pub = t_start
|
||||
within_since = None
|
||||
rate = rospy.Rate(10)
|
||||
|
||||
while not rospy.is_shutdown():
|
||||
now = time.time()
|
||||
elapsed = now - t_start
|
||||
|
||||
# 1) Timeout
|
||||
if elapsed > cfg['per_goal_timeout']:
|
||||
rospy.logwarn("[%d/%d %s] TIMEOUT after %.1fs; skipping.",
|
||||
idx, total, label, elapsed)
|
||||
return 'timeout'
|
||||
|
||||
# 2) Stuck check (only after the window has elapsed)
|
||||
if elapsed > cfg['stuck_window']:
|
||||
disp = self._displacement_in_window(cfg['stuck_window'])
|
||||
if disp < cfg['stuck_displacement']:
|
||||
rospy.logwarn(
|
||||
"[%d/%d %s] STUCK (disp=%.3fm < %.3fm in last %.1fs); "
|
||||
"skipping.", idx, total, label, disp,
|
||||
cfg['stuck_displacement'], cfg['stuck_window'])
|
||||
return 'stuck'
|
||||
|
||||
# 3) Arrived?
|
||||
x, y, _z, _t = self._pose
|
||||
d = self._xy_dist(x, y, xyz[0], xyz[1])
|
||||
if d <= cfg['arrive_threshold']:
|
||||
if within_since is None:
|
||||
within_since = now
|
||||
elif (now - within_since) >= cfg['settle_time']:
|
||||
rospy.loginfo(
|
||||
"\033[92m[%d/%d %s] ARRIVED (d=%.2fm, settled %.1fs)"
|
||||
"\033[0m", idx, total, label, d, cfg['settle_time'])
|
||||
return 'arrived'
|
||||
else:
|
||||
within_since = None
|
||||
|
||||
# 4) Periodic re-publish (protects against missed first publish)
|
||||
if (cfg['republish_interval'] > 0
|
||||
and (now - t_last_pub) >= cfg['republish_interval']):
|
||||
self._publish_goal(xyz)
|
||||
t_last_pub = now
|
||||
rospy.loginfo_throttle(
|
||||
5.0, "[%d/%d %s] re-published goal (d=%.2fm, t=%.1fs)",
|
||||
idx, total, label, d, elapsed)
|
||||
|
||||
rate.sleep()
|
||||
return 'shutdown'
|
||||
|
||||
def run(self):
|
||||
cfg = self.cfg
|
||||
wps = list(cfg['waypoints'])
|
||||
if cfg['return_home']:
|
||||
wps.append(list(self._home))
|
||||
total = len(wps)
|
||||
|
||||
results = []
|
||||
for i, wp in enumerate(wps, start=1):
|
||||
label = 'HOME' if (cfg['return_home'] and i == total) else 'WP'
|
||||
res = self._run_goal(i, total, wp, label)
|
||||
results.append((i, label, wp, res))
|
||||
if rospy.is_shutdown():
|
||||
break
|
||||
|
||||
# Summary
|
||||
rospy.loginfo("\033[95m===== waypoint_runner summary =====\033[0m")
|
||||
for i, label, wp, res in results:
|
||||
rospy.loginfo(" %2d/%d %s (%.2f, %.2f, %.2f) -> %s",
|
||||
i, total, label, wp[0], wp[1], wp[2], res)
|
||||
rospy.loginfo("\033[95m===================================\033[0m")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
def parse_args(argv):
|
||||
p = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument('--file', '-f', type=str, default=None,
|
||||
help='YAML file with waypoints and (optional) parameters.')
|
||||
p.add_argument('--waypoints', '-w', type=str, default=None,
|
||||
help='Space-separated "x,y[,z]" tuples (overrides YAML).')
|
||||
p.add_argument('--frame-id', type=str, default=None,
|
||||
help="Goal frame_id (default 'odom').")
|
||||
p.add_argument('--timeout', type=float, default=None,
|
||||
help='Per-goal timeout in seconds.')
|
||||
p.add_argument('--arrive-threshold', type=float, default=None,
|
||||
help='XY arrival threshold in meters.')
|
||||
g = p.add_mutually_exclusive_group()
|
||||
g.add_argument('--return-home', dest='return_home', action='store_true',
|
||||
default=None, help='Append start pose as final goal.')
|
||||
g.add_argument('--no-return-home', dest='return_home', action='store_false',
|
||||
help='Do not return to start pose after last waypoint.')
|
||||
return p.parse_args(argv)
|
||||
|
||||
|
||||
def main():
|
||||
args = parse_args(rospy.myargv()[1:])
|
||||
try:
|
||||
cfg = build_config(args)
|
||||
except (ValueError, OSError) as exc:
|
||||
sys.stderr.write('[waypoint_runner] config error: {}\n'.format(exc))
|
||||
sys.exit(2)
|
||||
|
||||
rospy.init_node('waypoint_runner', anonymous=False)
|
||||
|
||||
rospy.loginfo('waypoint_runner config:')
|
||||
for k in ('frame_id', 'arrive_threshold', 'settle_time',
|
||||
'per_goal_timeout', 'stuck_window', 'stuck_displacement',
|
||||
'republish_interval', 'return_home', 'odom_topic', 'goal_topic'):
|
||||
rospy.loginfo(' %s = %r', k, cfg[k])
|
||||
rospy.loginfo(' waypoints (%d):', len(cfg['waypoints']))
|
||||
for i, wp in enumerate(cfg['waypoints'], 1):
|
||||
rospy.loginfo(' %2d: (%.3f, %.3f, %.3f)', i, *wp)
|
||||
|
||||
runner = WaypointRunner(cfg)
|
||||
try:
|
||||
runner.run()
|
||||
except rospy.ROSInterruptException:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,11 @@
|
||||
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE catkin_make INSTEAD
|
||||
|
||||
from setuptools import setup
|
||||
from catkin_pkg.python_setup import generate_distutils_setup
|
||||
|
||||
setup_args = generate_distutils_setup(
|
||||
packages=['sru_nav_go2'],
|
||||
package_dir={'': 'src'},
|
||||
)
|
||||
|
||||
setup(**setup_args)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Constants and configuration values for the Go2 + Odin1 SRU navigation port.
|
||||
|
||||
Defaults are tuned conservatively for Unitree Go2 (no wheels, weaker lateral
|
||||
ability) versus the original B2W (wheeled). Override at runtime through the
|
||||
companion YAML / launch parameters.
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Control parameters
|
||||
# ---------------------------------------------------------------------------
|
||||
DEFAULT_CONTROL_FREQUENCY = 5.0 # Hz (matches training)
|
||||
DEFAULT_MIN_DEPTH = 0.25 # meters
|
||||
DEFAULT_MAX_DEPTH = 10.0 # meters
|
||||
ARRIVE_GOAL_THRESHOLD = 0.75 # meters
|
||||
NEAR_GOAL_THRESHOLD_MULTIPLIER = 2.0
|
||||
JOYSTICK_TIMEOUT = 15.0 # seconds (safety deadman timeout)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Policy output scaling. Original B2W used [1.5, 1.0, 1.0].
|
||||
# Go2 is conservative until verified safe in real hardware.
|
||||
# ---------------------------------------------------------------------------
|
||||
POLICY_SCALE = [0.6, 0.3, 0.6] # [linear_x, linear_y, angular_z]
|
||||
LATERAL_VELOCITY_SCALE = 0.6 # extra damping on linear_y
|
||||
|
||||
# Low-pass filter coefficients (alpha): output = a*new + (1-a)*prev
|
||||
LOW_PASS_FILTER_COEF = [0.9, 0.5, 0.5]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Joystick axis / button mappings (PS5-style, same as original)
|
||||
# ---------------------------------------------------------------------------
|
||||
JOYSTICK_AXIS_LINEAR_X = 1
|
||||
JOYSTICK_AXIS_LINEAR_Y = 0
|
||||
JOYSTICK_AXIS_LINEAR_Z = 3
|
||||
JOYSTICK_AXIS_ANGULAR_Z = 2
|
||||
JOYSTICK_AXIS_SMART = 5
|
||||
|
||||
BUTTON_RESET_HIDDEN_STATE = 2
|
||||
BUTTON_RECORD_WAYPOINT = 6
|
||||
BUTTON_CLEAR_WAYPOINT = 4
|
||||
BUTTON_SEND_GOAL = 10
|
||||
BUTTON_ABORT = 9
|
||||
BUTTON_TRIGGER_WAYPOINTS = 1
|
||||
BUTTON_FORWARD = 11
|
||||
BUTTON_BACKWARD = 12
|
||||
BUTTON_LEFT = 13
|
||||
BUTTON_RIGHT = 14
|
||||
BUTTON_UP = 3
|
||||
BUTTON_DOWN = 0
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Scales
|
||||
# ---------------------------------------------------------------------------
|
||||
LINEAR_SCALE = 1.0
|
||||
ANGULAR_SCALE = 1.0
|
||||
MOVING_SCALE = 0.2
|
||||
SMART_JOYSTICK_SCALE = 5.0
|
||||
SMART_JOYSTICK_UPDATE_FREQUENCY = 5.0 # Hz
|
||||
SMART_JOYSTICK_Z_SCALE = 0.25
|
||||
SMART_JOYSTICK_FILTER_ALPHA = 0.2
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Timer intervals
|
||||
# ---------------------------------------------------------------------------
|
||||
WAYPOINT_PUBLISH_INTERVAL = 0.2 # 5 Hz
|
||||
TARGET_VECTOR_PUBLISH_INTERVAL = 0.2 # 5 Hz
|
||||
TRIGGER_BUTTON_COOLDOWN = 1.0 # seconds
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Visualization
|
||||
# ---------------------------------------------------------------------------
|
||||
TWIST_MARKER_SCALE = 5.0
|
||||
TWIST_MARKER_ID = 0
|
||||
TARGET_VECTOR_MARKER_ID = 1
|
||||
MOVING_GOAL_MARKER_ID = 2
|
||||
WAYPOINTS_MARKER_ID = 3
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Physics
|
||||
# ---------------------------------------------------------------------------
|
||||
GRAVITY_MAGNITUDE = 9.81 # m/s^2
|
||||
@@ -0,0 +1,176 @@
|
||||
"""SRU Navigation learning model (ONNX Runtime).
|
||||
|
||||
Identical inference pipeline to the original ROS2 deployment. No ROS deps.
|
||||
"""
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import onnxruntime as ort
|
||||
|
||||
from sru_nav_go2 import constants
|
||||
from sru_nav_go2.utils import subtract_frame_transforms, transform_points
|
||||
|
||||
|
||||
# Model architecture constants (must match training-time export).
|
||||
STATE_DIM = 16 # linear_vel(3)+angular_vel(3)+gravity(3)+last_action(3)+target_pos_log(4)
|
||||
DEPTH_EMBEDDING_DIM = 2560 # 64 * 5 * 8 (flattened VAE output)
|
||||
POLICY_INPUT_DIM = STATE_DIM + DEPTH_EMBEDDING_DIM # 2576
|
||||
LSTM_HIDDEN_DIM = 512
|
||||
|
||||
|
||||
class LearningModel:
|
||||
"""RL navigation policy + depth VAE encoder (ONNX Runtime).
|
||||
|
||||
VAE encoder:
|
||||
depth_image [1, 1, 40, 64] -> mu [1, 64, 5, 8] -> flat [2560]
|
||||
Policy (LSTM):
|
||||
obs [1, 2576] + h_in [1, 1, 512] + c_in [1, 1, 512]
|
||||
-> raw_action [1, 3], h_out, c_out
|
||||
cmd_vel = tanh(raw_action) * POLICY_SCALE
|
||||
"""
|
||||
|
||||
def __init__(self, preprocess_model_path, policy_model_path,
|
||||
policy_scale=None, intra_op_num_threads=4):
|
||||
available_providers = ort.get_available_providers()
|
||||
|
||||
if 'CUDAExecutionProvider' in available_providers:
|
||||
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
|
||||
print('\033[92m' + 'Using device: CUDA (ONNX Runtime)' + '\033[0m')
|
||||
elif 'TensorrtExecutionProvider' in available_providers:
|
||||
providers = ['TensorrtExecutionProvider', 'CUDAExecutionProvider',
|
||||
'CPUExecutionProvider']
|
||||
print('\033[92m' + 'Using device: TensorRT (ONNX Runtime)' + '\033[0m')
|
||||
else:
|
||||
providers = ['CPUExecutionProvider']
|
||||
print('\033[93m' + 'Using device: CPU (ONNX Runtime)' + '\033[0m')
|
||||
|
||||
sess_options = ort.SessionOptions()
|
||||
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
||||
sess_options.intra_op_num_threads = int(intra_op_num_threads)
|
||||
|
||||
self.preprocess_session = ort.InferenceSession(
|
||||
preprocess_model_path, sess_options=sess_options, providers=providers
|
||||
)
|
||||
self.policy_session = ort.InferenceSession(
|
||||
policy_model_path, sess_options=sess_options, providers=providers
|
||||
)
|
||||
|
||||
self.preprocess_input_name = self.preprocess_session.get_inputs()[0].name
|
||||
self.preprocess_output_name = self.preprocess_session.get_outputs()[0].name
|
||||
|
||||
self.policy_input_names = {inp.name: inp for inp in self.policy_session.get_inputs()}
|
||||
self.policy_output_names = [out.name for out in self.policy_session.get_outputs()]
|
||||
|
||||
self._h_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
|
||||
self._c_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
|
||||
|
||||
if policy_scale is None:
|
||||
policy_scale = constants.POLICY_SCALE
|
||||
self._policy_scale = np.array(policy_scale, dtype=np.float32)
|
||||
|
||||
self.fake_run_once()
|
||||
print('\033[92m' + 'Learning model is ready (ONNX Runtime).' + '\033[0m')
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# Depth preprocessing
|
||||
# -----------------------------------------------------------------
|
||||
@staticmethod
|
||||
def _resize_bilinear(img, target_size):
|
||||
return cv2.resize(img, (target_size[1], target_size[0]),
|
||||
interpolation=cv2.INTER_LINEAR)
|
||||
|
||||
def depth_preprocess(self, img):
|
||||
"""Encode a depth image (H, W) into a 2560-dim latent."""
|
||||
img_resized = self._resize_bilinear(img, (40, 64))
|
||||
img_tensor = img_resized.astype(np.float32)[np.newaxis, np.newaxis, :, :]
|
||||
vae_output = self.preprocess_session.run(
|
||||
[self.preprocess_output_name],
|
||||
{self.preprocess_input_name: img_tensor},
|
||||
)[0]
|
||||
return vae_output.flatten()
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# Target encoding
|
||||
# -----------------------------------------------------------------
|
||||
def normalize_target_position(self, target_pos_w, robot_pos_w, robot_orientation_w):
|
||||
target_pos_w = np.array(target_pos_w, dtype=np.float32)[np.newaxis]
|
||||
robot_pos_w = np.array(robot_pos_w, dtype=np.float32)[np.newaxis]
|
||||
robot_orientation_w = np.array(robot_orientation_w, dtype=np.float32)[np.newaxis]
|
||||
|
||||
inv_pos, inv_rot = subtract_frame_transforms(robot_pos_w, robot_orientation_w)
|
||||
target_vec_b = transform_points(target_pos_w, inv_pos, inv_rot)
|
||||
|
||||
dist = np.linalg.norm(target_vec_b, axis=-1, keepdims=True) + 1e-6
|
||||
target_pos = target_vec_b / dist
|
||||
dist_log = np.log(dist + 1.0)
|
||||
|
||||
target_pos = np.concatenate((target_pos, dist_log), axis=-1).reshape(-1)
|
||||
return target_pos, target_vec_b
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# LSTM state management
|
||||
# -----------------------------------------------------------------
|
||||
def reset_hidden_state(self):
|
||||
self._h_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
|
||||
self._c_state = np.zeros((1, 1, LSTM_HIDDEN_DIM), dtype=np.float32)
|
||||
|
||||
# -----------------------------------------------------------------
|
||||
# Inference
|
||||
# -----------------------------------------------------------------
|
||||
def predict(self, linear_vel, angular_vel, gravity_vector, last_action,
|
||||
target_pos_w, robot_pos_w, robot_orientation_w, depth_image,
|
||||
is_reset=False):
|
||||
if is_reset:
|
||||
self.reset_hidden_state()
|
||||
|
||||
depth_embedding = self.depth_preprocess(depth_image)
|
||||
|
||||
target_pos_log, target_vec_b = self.normalize_target_position(
|
||||
target_pos_w, robot_pos_w, robot_orientation_w
|
||||
)
|
||||
|
||||
state_input = np.array(
|
||||
list(linear_vel) + list(angular_vel) + list(gravity_vector) +
|
||||
list(last_action) + target_pos_log.tolist(),
|
||||
dtype=np.float32,
|
||||
)
|
||||
|
||||
obs = np.concatenate([state_input, depth_embedding])[np.newaxis].astype(np.float32)
|
||||
|
||||
outputs = self.policy_session.run(
|
||||
None,
|
||||
{
|
||||
'obs': obs,
|
||||
'h_in': self._h_state,
|
||||
'c_in': self._c_state,
|
||||
},
|
||||
)
|
||||
|
||||
raw_action, h_out, c_out = outputs
|
||||
self._h_state = h_out
|
||||
self._c_state = c_out
|
||||
|
||||
cmd_vel = np.tanh(raw_action) * self._policy_scale
|
||||
cmd_vel = cmd_vel.squeeze(0)
|
||||
raw_action = raw_action.squeeze(0)
|
||||
|
||||
return cmd_vel, raw_action, target_vec_b
|
||||
|
||||
def fake_run_once(self):
|
||||
linear_vel = [0.0, 0.0, 0.0]
|
||||
angular_vel = [0.0, 0.0, 0.0]
|
||||
gravity_vector = [0.0, 0.0, -1.0]
|
||||
target_pos_w = [1.0, 0.0, 0.0]
|
||||
robot_pos_w = [0.0, 0.0, 0.0]
|
||||
robot_orientation_w = [1.0, 0.0, 0.0, 0.0]
|
||||
last_action = [0.0, 0.0, 0.0]
|
||||
depth_image = np.random.rand(600, 960).astype(np.float32)
|
||||
|
||||
cmd_vel, _, _ = self.predict(
|
||||
linear_vel, angular_vel, gravity_vector, last_action,
|
||||
target_pos_w, robot_pos_w, robot_orientation_w, depth_image,
|
||||
is_reset=True,
|
||||
)
|
||||
print('Warmup predicted cmd_vel: linear_x={:.4f}, linear_y={:.4f}, '
|
||||
'angular_z={:.4f}'.format(cmd_vel[0], cmd_vel[1], cmd_vel[2]))
|
||||
self.reset_hidden_state()
|
||||
@@ -0,0 +1,682 @@
|
||||
"""ROS1 (rospy) navigation policy node for Unitree Go2 + Odin1.
|
||||
|
||||
Direct port of the original ROS2 NavigationPolicyNode. Behaviour is preserved;
|
||||
only ROS API calls, time helpers, and topic defaults have been changed.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
import cv2 # noqa: F401 (kept for parity; cv2 import inside model.py)
|
||||
import numpy as np
|
||||
import rospy
|
||||
from cv_bridge import CvBridge
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
from nav_msgs.msg import Odometry
|
||||
from scipy.spatial.transform import Rotation as R
|
||||
from sensor_msgs.msg import Image, Joy
|
||||
from std_msgs.msg import Header
|
||||
from visualization_msgs.msg import Marker
|
||||
|
||||
from sru_nav_go2 import constants
|
||||
from sru_nav_go2.model import LearningModel
|
||||
from sru_nav_go2.utils import transform_points, yaw_quat
|
||||
from sru_nav_go2.visualization import VisualizationManager
|
||||
from sru_nav_go2.waypoint_manager import RospyLogger, WaypointManager
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
def _stamp_to_sec(stamp):
|
||||
"""ROS1 Time -> float seconds."""
|
||||
return stamp.secs + stamp.nsecs * 1e-9
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node
|
||||
# ---------------------------------------------------------------------------
|
||||
class NavigationPolicyNode(object):
|
||||
"""RL navigation controller node (ROS1)."""
|
||||
|
||||
def __init__(self,
|
||||
preprocess_model_path,
|
||||
policy_model_path,
|
||||
depth_topic,
|
||||
odom_topic,
|
||||
joy_topic,
|
||||
goal_topic,
|
||||
cmd_vel_topic,
|
||||
min_depth=constants.DEFAULT_MIN_DEPTH,
|
||||
max_depth=constants.DEFAULT_MAX_DEPTH,
|
||||
control_frequency=constants.DEFAULT_CONTROL_FREQUENCY,
|
||||
policy_scale=None,
|
||||
use_sim=False,
|
||||
require_joystick=True):
|
||||
# Configuration
|
||||
self.use_sim = use_sim
|
||||
self.require_joystick = bool(require_joystick)
|
||||
self.min_depth = float(min_depth)
|
||||
self.max_depth = float(max_depth)
|
||||
self.control_frequency = float(control_frequency)
|
||||
self.odom_ready = False
|
||||
self.arrive_goal_threshold = constants.ARRIVE_GOAL_THRESHOLD
|
||||
self.last_run_time = 0.0
|
||||
self.system_delay = constants.JOYSTICK_TIMEOUT
|
||||
|
||||
# ----- Publishers ------------------------------------------------
|
||||
self.cmd_vel_publisher = rospy.Publisher(cmd_vel_topic, Twist, queue_size=10)
|
||||
self.base_vel_publisher = rospy.Publisher(
|
||||
'~base_vel', Twist, queue_size=10)
|
||||
self.goal_pose_publisher = rospy.Publisher(goal_topic, PoseStamped, queue_size=1)
|
||||
|
||||
# Visualization
|
||||
self.twist_marker_publisher = rospy.Publisher(
|
||||
'~vis/twist_cmd_marker', Marker, queue_size=10)
|
||||
self.goal_vector_marker_publisher = rospy.Publisher(
|
||||
'~vis/goal_vector_marker', Marker, queue_size=10)
|
||||
self.moving_goal_marker_publisher = rospy.Publisher(
|
||||
'~vis/moving_goal_marker', Marker, queue_size=10)
|
||||
self.recorded_waypoints_marker_pub = rospy.Publisher(
|
||||
'~vis/recorded_waypoints_marker', Marker, queue_size=10)
|
||||
|
||||
# ----- Utilities --------------------------------------------------
|
||||
self.bridge = CvBridge()
|
||||
self.model = LearningModel(
|
||||
preprocess_model_path=preprocess_model_path,
|
||||
policy_model_path=policy_model_path,
|
||||
policy_scale=policy_scale,
|
||||
)
|
||||
self._logger = RospyLogger()
|
||||
self.waypoint_manager = WaypointManager(self._logger)
|
||||
self.visualization_manager = VisualizationManager()
|
||||
|
||||
# ----- Robot state -----------------------------------------------
|
||||
self.map_frame_id = None
|
||||
self.robot_frame_id = None
|
||||
self.robot_odom_time = 0.0
|
||||
self.robot_pos_w = None
|
||||
self.robot_orientation_w = None
|
||||
self.linear_vel_w = None
|
||||
self.angular_vel_w = None
|
||||
self.linear_vel = None
|
||||
self.angular_vel = None
|
||||
self.gravity_vector = None
|
||||
self.depth_image = None
|
||||
|
||||
# ----- Navigation state ------------------------------------------
|
||||
self.target_pos_w = None
|
||||
self.last_target_pos = None
|
||||
self.is_reset_hidden_state = False
|
||||
self.last_action = self._reset_last_action()
|
||||
self.prev_cmd = np.zeros(3)
|
||||
self.is_abort_goal = False
|
||||
|
||||
# ----- Joystick state --------------------------------------------
|
||||
self.joy_linear_x = 0.0
|
||||
self.joy_linear_y = 0.0
|
||||
self.joy_angular_z = 0.0
|
||||
# When require_joystick is False we want the robot to move at full
|
||||
# policy scale even with no /joy publisher (testing / headless runs).
|
||||
# When True (default, safe), ratio stays 0 until joy_callback fires.
|
||||
self.cmd_vel_ratio = 0.0 if self.require_joystick else 1.0
|
||||
self.joy_time = time.time()
|
||||
self.last_trigger_time = time.time()
|
||||
|
||||
# ----- Moving goal state -----------------------------------------
|
||||
self.moving_goal_delta = [0.0, 0.0, 0.0]
|
||||
|
||||
# ----- Smart joystick state --------------------------------------
|
||||
self.smart_joystick_goal = [0.0, 0.0, 0.0]
|
||||
self.prev_smart_joystick_goal = [0.0, 0.0, 0.0]
|
||||
self.smart_joystick_mode_active = False
|
||||
self.smart_joystick_goal_aborted = False
|
||||
self.latest_joystick_axes = [0.0, 0.0, 0.0]
|
||||
|
||||
# ----- Subscribers (created LAST so callbacks fire only after init)
|
||||
self.odom_subscriber = rospy.Subscriber(
|
||||
odom_topic, Odometry, self.odom_callback, queue_size=10)
|
||||
self.depth_subscriber = rospy.Subscriber(
|
||||
depth_topic, Image, self.depth_callback, queue_size=2)
|
||||
self.joy_subscriber = rospy.Subscriber(
|
||||
joy_topic, Joy, self.joy_callback, queue_size=10)
|
||||
self.target_position_subscriber = rospy.Subscriber(
|
||||
goal_topic, PoseStamped, self.target_position_callback, queue_size=1)
|
||||
|
||||
# ----- Timers ----------------------------------------------------
|
||||
rospy.Timer(rospy.Duration(constants.WAYPOINT_PUBLISH_INTERVAL),
|
||||
self._timer_publish_recorded_waypoints)
|
||||
rospy.Timer(rospy.Duration(constants.TARGET_VECTOR_PUBLISH_INTERVAL),
|
||||
self._timer_publish_target_vector)
|
||||
smart_joystick_interval = 1.0 / constants.SMART_JOYSTICK_UPDATE_FREQUENCY
|
||||
rospy.Timer(rospy.Duration(smart_joystick_interval),
|
||||
self._timer_update_smart_joystick_goal)
|
||||
|
||||
rospy.loginfo('\033[92mNavigation policy node is ready.\033[0m')
|
||||
|
||||
# =====================================================================
|
||||
# Callbacks
|
||||
# =====================================================================
|
||||
def odom_callback(self, odom_msg):
|
||||
# 1) odom timestamp
|
||||
self.robot_odom_time = _stamp_to_sec(odom_msg.header.stamp)
|
||||
|
||||
# 2) Frame IDs (once)
|
||||
if self.map_frame_id is None:
|
||||
self.map_frame_id = odom_msg.header.frame_id
|
||||
if self.robot_frame_id is None:
|
||||
self.robot_frame_id = odom_msg.child_frame_id
|
||||
|
||||
# 3) Robot pose
|
||||
self.robot_pos_w = [
|
||||
odom_msg.pose.pose.position.x,
|
||||
odom_msg.pose.pose.position.y,
|
||||
odom_msg.pose.pose.position.z,
|
||||
]
|
||||
self.robot_orientation_w = [
|
||||
odom_msg.pose.pose.orientation.w,
|
||||
odom_msg.pose.pose.orientation.x,
|
||||
odom_msg.pose.pose.orientation.y,
|
||||
odom_msg.pose.pose.orientation.z,
|
||||
]
|
||||
|
||||
# 4) Velocities from odom
|
||||
self.linear_vel_w = [
|
||||
odom_msg.twist.twist.linear.x,
|
||||
odom_msg.twist.twist.linear.y,
|
||||
odom_msg.twist.twist.linear.z,
|
||||
]
|
||||
self.angular_vel_w = [
|
||||
odom_msg.twist.twist.angular.x,
|
||||
odom_msg.twist.twist.angular.y,
|
||||
odom_msg.twist.twist.angular.z,
|
||||
]
|
||||
|
||||
# 5) Convert to base frame (real-hw) or pass-through (sim)
|
||||
if self.use_sim:
|
||||
self.linear_vel = list(self.linear_vel_w)
|
||||
self.angular_vel = list(self.angular_vel_w)
|
||||
else:
|
||||
self.linear_vel = self.convert_vel_frame(
|
||||
self.linear_vel_w, self.robot_orientation_w)
|
||||
self.angular_vel = self.convert_vel_frame(
|
||||
self.angular_vel_w, self.robot_orientation_w)
|
||||
|
||||
# 6) Publish converted base velocity for debug
|
||||
self.publish_base_vel(self.linear_vel, self.angular_vel)
|
||||
|
||||
# 7) Projected gravity in base frame
|
||||
self.gravity_vector = self.projected_gravity_vector(self.robot_orientation_w)
|
||||
|
||||
# 8) Mark odom available
|
||||
if not self.odom_ready:
|
||||
self.odom_ready = True
|
||||
|
||||
def depth_callback(self, depth_msg):
|
||||
if not self.odom_ready:
|
||||
rospy.logwarn_throttle(
|
||||
5.0, '\033[93mOdometry not ready, skipping depth callback.\033[0m')
|
||||
return
|
||||
|
||||
try:
|
||||
depth_array = self.bridge.imgmsg_to_cv2(depth_msg, desired_encoding='passthrough')
|
||||
depth_array = np.nan_to_num(
|
||||
depth_array, nan=0.0, posinf=self.max_depth * 2.0, neginf=0.0)
|
||||
depth_array = depth_array.astype(np.float32, copy=False)
|
||||
depth_array[depth_array > self.max_depth] = 0.0
|
||||
depth_array[depth_array < self.min_depth] = 0.0
|
||||
self.depth_image = depth_array
|
||||
except Exception as e:
|
||||
rospy.logerr('Error converting depth image: {}'.format(e))
|
||||
return
|
||||
|
||||
# Respect control frequency
|
||||
interval = 1.0 / self.control_frequency
|
||||
if (self.robot_odom_time - self.last_run_time) < interval:
|
||||
return
|
||||
self.last_run_time = self.robot_odom_time
|
||||
|
||||
self.generate_cmd_vel()
|
||||
|
||||
def generate_cmd_vel(self):
|
||||
# Visualize moving goal
|
||||
self.visualization_manager.publish_moving_goal_marker(
|
||||
self.moving_goal_delta, self.robot_pos_w, self.robot_orientation_w,
|
||||
self.robot_odom_time, self.map_frame_id, self.moving_goal_marker_publisher,
|
||||
)
|
||||
|
||||
if self.smart_joystick_mode_active:
|
||||
rospy.loginfo_throttle(
|
||||
1.0,
|
||||
'Smart joystick mode active - Goal: [{:.2f}, {:.2f}, {:.2f}]'.format(
|
||||
self.smart_joystick_goal[0], self.smart_joystick_goal[1],
|
||||
self.smart_joystick_goal[2],
|
||||
),
|
||||
)
|
||||
|
||||
is_arrived = self._check_goal_reached(self.target_pos_w, self.robot_pos_w)
|
||||
if is_arrived or self.is_abort_goal:
|
||||
twist = Twist()
|
||||
twist.linear.x = 0.0 + self.joy_linear_x
|
||||
twist.linear.y = 0.0 + self.joy_linear_y
|
||||
twist.angular.z = 0.0 + self.joy_angular_z
|
||||
self.cmd_vel_publisher.publish(twist)
|
||||
|
||||
if self.is_abort_goal:
|
||||
self.waypoint_manager.re_add_aborted_waypoint(self.target_pos_w)
|
||||
|
||||
self.target_pos_w = None
|
||||
self.is_abort_goal = False
|
||||
self.last_action = self._reset_last_action()
|
||||
rospy.loginfo('Target position reset.')
|
||||
|
||||
else:
|
||||
# Joystick deadman timeout (only when joystick is required)
|
||||
if self.require_joystick and \
|
||||
(self.robot_odom_time - self.joy_time > self.system_delay):
|
||||
self.cmd_vel_ratio = 0.0
|
||||
diff = self.robot_odom_time - self.joy_time
|
||||
rospy.logwarn_throttle(
|
||||
2.0,
|
||||
'\033[93mJoystick timeout, stopping the robot. Time diff: {:.4f}s\033[0m'
|
||||
.format(diff),
|
||||
)
|
||||
|
||||
rospy.loginfo_throttle(
|
||||
1.0,
|
||||
'cmd_vel_ratio: {:.4f} (require_joystick={})'.format(
|
||||
self.cmd_vel_ratio, self.require_joystick))
|
||||
|
||||
cmd, action, _target_vec_b = self.model.predict(
|
||||
self.linear_vel, self.angular_vel, self.gravity_vector,
|
||||
self.last_action, self.target_pos_w, self.robot_pos_w,
|
||||
self.robot_orientation_w, self.depth_image,
|
||||
self.is_reset_hidden_state,
|
||||
)
|
||||
|
||||
if self.is_reset_hidden_state:
|
||||
rospy.logwarn('\033[93mResetting hidden state.\033[0m')
|
||||
self.is_reset_hidden_state = False
|
||||
self.last_action = self._reset_last_action()
|
||||
|
||||
self.last_action = action.tolist()
|
||||
|
||||
twist = Twist()
|
||||
model_cmd = np.array([
|
||||
cmd[0].item() * self.cmd_vel_ratio,
|
||||
cmd[1].item() * self.cmd_vel_ratio * constants.LATERAL_VELOCITY_SCALE,
|
||||
cmd[2].item() * self.cmd_vel_ratio,
|
||||
])
|
||||
filter_coef = np.array(constants.LOW_PASS_FILTER_COEF)
|
||||
filt_model = filter_coef * model_cmd + (1 - filter_coef) * self.prev_cmd
|
||||
twist.linear.x = float(filt_model[0]) + self.joy_linear_x
|
||||
twist.linear.y = float(filt_model[1]) + self.joy_linear_y
|
||||
twist.angular.z = float(filt_model[2]) + self.joy_angular_z
|
||||
self.prev_cmd = filt_model
|
||||
self.cmd_vel_publisher.publish(twist)
|
||||
|
||||
self.visualization_manager.publish_twist_marker(
|
||||
twist, self.robot_odom_time, self.robot_frame_id,
|
||||
self.twist_marker_publisher,
|
||||
)
|
||||
|
||||
rospy.loginfo_throttle(
|
||||
1.0,
|
||||
'Published cmd_vel: linear_x={:.4f}, linear_y={:.4f}, angular_z={:.4f}'.format(
|
||||
twist.linear.x, twist.linear.y, twist.angular.z
|
||||
),
|
||||
)
|
||||
self._reset_joystick()
|
||||
|
||||
# =====================================================================
|
||||
# Velocity / orientation helpers
|
||||
# =====================================================================
|
||||
def publish_base_vel(self, linear_vel, angular_vel):
|
||||
twist = Twist()
|
||||
twist.linear.x = linear_vel[0]
|
||||
twist.linear.y = linear_vel[1]
|
||||
twist.angular.z = angular_vel[2]
|
||||
self.base_vel_publisher.publish(twist)
|
||||
|
||||
@staticmethod
|
||||
def convert_vel_frame(vel_vec, orientation_w):
|
||||
# quaternion is (w, x, y, z); scipy expects (x, y, z, w)
|
||||
quat_xyzw = [orientation_w[1], orientation_w[2], orientation_w[3], orientation_w[0]]
|
||||
rotation = R.from_quat(quat_xyzw)
|
||||
inv_rot = rotation.inv()
|
||||
return inv_rot.apply(np.array(vel_vec)).tolist()
|
||||
|
||||
@staticmethod
|
||||
def projected_gravity_vector(robot_orientation_w):
|
||||
quat_xyzw = [robot_orientation_w[1], robot_orientation_w[2],
|
||||
robot_orientation_w[3], robot_orientation_w[0]]
|
||||
rotation = R.from_quat(quat_xyzw)
|
||||
inv_rot = rotation.inv()
|
||||
gravity = np.array([0.0, 0.0, -constants.GRAVITY_MAGNITUDE])
|
||||
proj = inv_rot.apply(gravity)
|
||||
proj = proj / (np.linalg.norm(proj) + 1e-6)
|
||||
return proj.tolist()
|
||||
|
||||
# =====================================================================
|
||||
# Joystick handling
|
||||
# =====================================================================
|
||||
def joy_callback(self, joy_msg):
|
||||
if len(joy_msg.axes) <= max(
|
||||
constants.JOYSTICK_AXIS_LINEAR_X,
|
||||
constants.JOYSTICK_AXIS_LINEAR_Y,
|
||||
constants.JOYSTICK_AXIS_LINEAR_Z,
|
||||
constants.JOYSTICK_AXIS_ANGULAR_Z,
|
||||
constants.JOYSTICK_AXIS_SMART,
|
||||
4):
|
||||
rospy.logwarn_throttle(5.0, 'Joy message has too few axes; ignoring.')
|
||||
return
|
||||
|
||||
self.cmd_vel_ratio = (1.0 + joy_msg.axes[4]) * 1.0
|
||||
|
||||
if (len(joy_msg.buttons) > constants.BUTTON_ABORT and
|
||||
joy_msg.buttons[constants.BUTTON_ABORT] == 1):
|
||||
self.is_abort_goal = True
|
||||
rospy.logwarn('Abort goal')
|
||||
|
||||
dx, dy, dz = self._moving_xyz_with_buttons(joy_msg, scale=constants.MOVING_SCALE)
|
||||
self.moving_goal_delta[0] += dx
|
||||
self.moving_goal_delta[1] += dy
|
||||
self.moving_goal_delta[2] += dz
|
||||
|
||||
current_time = time.time()
|
||||
cooldown = constants.TRIGGER_BUTTON_COOLDOWN
|
||||
|
||||
if (not self.is_abort_goal
|
||||
and (current_time - self.last_trigger_time) > cooldown
|
||||
and len(joy_msg.buttons) > constants.BUTTON_SEND_GOAL
|
||||
and joy_msg.buttons[constants.BUTTON_SEND_GOAL] == 1):
|
||||
rospy.logwarn('Trigger moving goal')
|
||||
self._publish_moving_goal()
|
||||
self.last_trigger_time = current_time
|
||||
|
||||
if ((current_time - self.last_trigger_time) > cooldown
|
||||
and len(joy_msg.buttons) > constants.BUTTON_RECORD_WAYPOINT
|
||||
and joy_msg.buttons[constants.BUTTON_RECORD_WAYPOINT] == 1):
|
||||
self.waypoint_manager.record_waypoint(self.robot_pos_w)
|
||||
self.last_trigger_time = current_time
|
||||
|
||||
if ((current_time - self.last_trigger_time) > cooldown
|
||||
and len(joy_msg.buttons) > constants.BUTTON_CLEAR_WAYPOINT
|
||||
and joy_msg.buttons[constants.BUTTON_CLEAR_WAYPOINT] == 1):
|
||||
self.waypoint_manager.remove_last_waypoint()
|
||||
self.last_trigger_time = current_time
|
||||
|
||||
if (not self.is_abort_goal
|
||||
and (current_time - self.last_trigger_time) > cooldown
|
||||
and len(joy_msg.buttons) > constants.BUTTON_TRIGGER_WAYPOINTS
|
||||
and joy_msg.buttons[constants.BUTTON_TRIGGER_WAYPOINTS] == 1):
|
||||
rospy.logwarn('Trigger waypoints')
|
||||
if self.waypoint_manager.has_home_waypoints():
|
||||
self.waypoint_manager.start_home_waypoint_sequence()
|
||||
elif self.waypoint_manager.has_inversed_waypoints():
|
||||
self.waypoint_manager.start_inversed_waypoint_sequence()
|
||||
self.last_trigger_time = current_time
|
||||
|
||||
if joy_msg.axes[constants.JOYSTICK_AXIS_SMART] < -0.5:
|
||||
if not self.smart_joystick_mode_active:
|
||||
self.smart_joystick_mode_active = True
|
||||
self.smart_joystick_goal_aborted = False
|
||||
|
||||
if not self.smart_joystick_goal_aborted and self.target_pos_w is not None:
|
||||
self.is_abort_goal = True
|
||||
self.smart_joystick_goal_aborted = True
|
||||
rospy.loginfo('Smart joystick mode: aborting current navigation goal')
|
||||
|
||||
self.latest_joystick_axes = [
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_X],
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_Y],
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_Z],
|
||||
]
|
||||
else:
|
||||
if self.smart_joystick_mode_active:
|
||||
self.smart_joystick_mode_active = False
|
||||
self.is_abort_goal = True
|
||||
rospy.loginfo('Exiting smart joystick mode: aborting current navigation goal')
|
||||
|
||||
self._reset_smart_joystick_goal()
|
||||
self.joy_linear_x = (
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_X]
|
||||
* constants.LINEAR_SCALE * 1.5)
|
||||
self.joy_linear_y = (
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_LINEAR_Y]
|
||||
* constants.LINEAR_SCALE)
|
||||
self.joy_angular_z = (
|
||||
joy_msg.axes[constants.JOYSTICK_AXIS_ANGULAR_Z]
|
||||
* constants.ANGULAR_SCALE)
|
||||
|
||||
if (len(joy_msg.buttons) > constants.BUTTON_RESET_HIDDEN_STATE and
|
||||
joy_msg.buttons[constants.BUTTON_RESET_HIDDEN_STATE] == 1):
|
||||
self.is_reset_hidden_state = True
|
||||
rospy.logwarn('Force Reset hidden state')
|
||||
|
||||
self.joy_time = time.time()
|
||||
|
||||
def _generate_waypoint_using_joystick(self, linear_x, linear_y, linear_z):
|
||||
if self.robot_pos_w is None or self.robot_orientation_w is None:
|
||||
return
|
||||
|
||||
goal_offset_robot = np.array([
|
||||
linear_x * constants.SMART_JOYSTICK_SCALE,
|
||||
linear_y * constants.SMART_JOYSTICK_SCALE,
|
||||
linear_z * constants.SMART_JOYSTICK_SCALE * constants.SMART_JOYSTICK_Z_SCALE,
|
||||
], dtype=np.float32)
|
||||
|
||||
robot_ori = np.array(self.robot_orientation_w, dtype=np.float32)
|
||||
robot_yaw_ori = yaw_quat(robot_ori)
|
||||
|
||||
goal_offset_world = transform_points(
|
||||
goal_offset_robot[np.newaxis],
|
||||
np.zeros(3, dtype=np.float32)[np.newaxis],
|
||||
robot_yaw_ori[np.newaxis],
|
||||
)[0]
|
||||
|
||||
target_goal_world = [
|
||||
self.robot_pos_w[0] + goal_offset_world[0].item(),
|
||||
self.robot_pos_w[1] + goal_offset_world[1].item(),
|
||||
self.robot_pos_w[2] + goal_offset_world[2].item(),
|
||||
]
|
||||
|
||||
if self.prev_smart_joystick_goal == [0.0, 0.0, 0.0]:
|
||||
self.smart_joystick_goal = target_goal_world
|
||||
else:
|
||||
alpha = constants.SMART_JOYSTICK_FILTER_ALPHA
|
||||
self.smart_joystick_goal = [
|
||||
alpha * target_goal_world[0] + (1 - alpha) * self.prev_smart_joystick_goal[0],
|
||||
alpha * target_goal_world[1] + (1 - alpha) * self.prev_smart_joystick_goal[1],
|
||||
alpha * target_goal_world[2] + (1 - alpha) * self.prev_smart_joystick_goal[2],
|
||||
]
|
||||
self.prev_smart_joystick_goal = list(self.smart_joystick_goal)
|
||||
|
||||
def _publish_smart_joystick_goal(self):
|
||||
if self.robot_pos_w is None or self.robot_orientation_w is None:
|
||||
rospy.logwarn_throttle(
|
||||
5.0, 'Cannot publish smart joystick goal: robot pose not available')
|
||||
return
|
||||
self._publish_goal(self.smart_joystick_goal)
|
||||
|
||||
def _reset_smart_joystick_goal(self):
|
||||
self.smart_joystick_goal = [0.0, 0.0, 0.0]
|
||||
self.prev_smart_joystick_goal = [0.0, 0.0, 0.0]
|
||||
|
||||
@staticmethod
|
||||
def _moving_xyz_with_buttons(joy_msg, scale=1.0):
|
||||
def b(idx):
|
||||
return bool(joy_msg.buttons[idx]) if idx < len(joy_msg.buttons) else False
|
||||
|
||||
dx = scale * (b(constants.BUTTON_FORWARD) - b(constants.BUTTON_BACKWARD))
|
||||
dy = scale * (b(constants.BUTTON_LEFT) - b(constants.BUTTON_RIGHT))
|
||||
dz = (scale / 5.0) * (b(constants.BUTTON_UP) - b(constants.BUTTON_DOWN))
|
||||
return dx, dy, dz
|
||||
|
||||
# =====================================================================
|
||||
# Goal publishing
|
||||
# =====================================================================
|
||||
def _publish_goal(self, goal_pos):
|
||||
goal_pose = PoseStamped()
|
||||
goal_pose.header = Header()
|
||||
goal_pose.header.stamp = rospy.Time.from_sec(self.robot_odom_time)
|
||||
goal_pose.header.frame_id = self.map_frame_id if self.map_frame_id else 'odom'
|
||||
goal_pose.pose.position.x = float(goal_pos[0])
|
||||
goal_pose.pose.position.y = float(goal_pos[1])
|
||||
goal_pose.pose.position.z = float(goal_pos[2])
|
||||
goal_pose.pose.orientation.w = 1.0
|
||||
self.goal_pose_publisher.publish(goal_pose)
|
||||
|
||||
def _publish_moving_goal(self):
|
||||
if self.robot_pos_w is None or self.robot_orientation_w is None:
|
||||
rospy.logwarn('Cannot publish moving goal: robot pose/orientation not yet set.')
|
||||
return
|
||||
|
||||
robot_pos = np.array(self.robot_pos_w, dtype=np.float32)
|
||||
robot_ori = np.array(self.robot_orientation_w, dtype=np.float32)
|
||||
robot_yaw_ori = yaw_quat(robot_ori)
|
||||
|
||||
moving_goal_pos = np.array(self.moving_goal_delta, dtype=np.float32)
|
||||
moving_goal_pos_w = transform_points(
|
||||
moving_goal_pos[np.newaxis],
|
||||
robot_pos[np.newaxis],
|
||||
robot_yaw_ori[np.newaxis],
|
||||
)
|
||||
|
||||
self._publish_goal(moving_goal_pos_w[0].tolist())
|
||||
self._reset_moving_goal()
|
||||
|
||||
# =====================================================================
|
||||
# Timer callbacks
|
||||
# =====================================================================
|
||||
def _timer_publish_recorded_waypoints(self, _event):
|
||||
self.publish_recorded_waypoints()
|
||||
|
||||
def _timer_publish_target_vector(self, _event):
|
||||
self.publish_target_vector()
|
||||
|
||||
def _timer_update_smart_joystick_goal(self, _event):
|
||||
self.update_smart_joystick_goal()
|
||||
|
||||
def publish_recorded_waypoints(self):
|
||||
if self.robot_pos_w is None:
|
||||
return
|
||||
|
||||
self.visualization_manager.publish_waypoints_marker(
|
||||
self.waypoint_manager.waypoints_visualization,
|
||||
self.map_frame_id,
|
||||
self.recorded_waypoints_marker_pub,
|
||||
)
|
||||
|
||||
if (self.waypoint_manager.is_home_sequence_active()
|
||||
and self.waypoint_manager.has_home_waypoints()):
|
||||
if (self.target_pos_w is None
|
||||
or self._check_near_goal(self.target_pos_w, self.robot_pos_w)):
|
||||
next_wp = self.waypoint_manager.get_next_waypoint_home()
|
||||
rospy.loginfo('Publishing next waypoint: {}'.format(next_wp))
|
||||
self._publish_goal(next_wp)
|
||||
else:
|
||||
rospy.loginfo_throttle(1.0, 'Tracking the current waypoint ...')
|
||||
|
||||
if not self.waypoint_manager.has_home_waypoints():
|
||||
self.waypoint_manager.stop_home_waypoint_sequence()
|
||||
|
||||
if (self.waypoint_manager.is_inversed_sequence_active()
|
||||
and self.waypoint_manager.has_inversed_waypoints()):
|
||||
if (self.target_pos_w is None
|
||||
or self._check_near_goal(self.target_pos_w, self.robot_pos_w)):
|
||||
next_wp = self.waypoint_manager.get_next_waypoint_inversed()
|
||||
rospy.loginfo('Publishing next inversed waypoint: {}'.format(next_wp))
|
||||
self._publish_goal(next_wp)
|
||||
else:
|
||||
rospy.loginfo_throttle(1.0, 'Tracking the current waypoint ...')
|
||||
|
||||
if not self.waypoint_manager.has_inversed_waypoints():
|
||||
self.waypoint_manager.stop_inversed_waypoint_sequence()
|
||||
|
||||
self.waypoint_manager.reset_visualization_if_complete()
|
||||
|
||||
def publish_target_vector(self):
|
||||
if self.robot_pos_w is None or self.robot_orientation_w is None:
|
||||
return
|
||||
tgt = self.target_pos_w if self.target_pos_w is not None else self.last_target_pos
|
||||
if tgt is None:
|
||||
return
|
||||
|
||||
_, target_vec_b = self.model.normalize_target_position(
|
||||
tgt, self.robot_pos_w, self.robot_orientation_w
|
||||
)
|
||||
|
||||
self.visualization_manager.publish_target_vector_marker(
|
||||
target_vec_b, self.robot_odom_time, self.robot_frame_id,
|
||||
self.goal_vector_marker_publisher,
|
||||
)
|
||||
|
||||
def update_smart_joystick_goal(self):
|
||||
if not self.smart_joystick_mode_active:
|
||||
return
|
||||
self._generate_waypoint_using_joystick(
|
||||
self.latest_joystick_axes[0],
|
||||
self.latest_joystick_axes[1],
|
||||
self.latest_joystick_axes[2],
|
||||
)
|
||||
self._publish_smart_joystick_goal()
|
||||
|
||||
# =====================================================================
|
||||
# Goal callbacks & checks
|
||||
# =====================================================================
|
||||
def _check_near_goal(self, target_pos_w, robot_pos_w):
|
||||
if target_pos_w is None or robot_pos_w is None:
|
||||
return True
|
||||
dist = np.linalg.norm(np.array(target_pos_w[:2]) - np.array(robot_pos_w[:2]))
|
||||
threshold = self.arrive_goal_threshold * constants.NEAR_GOAL_THRESHOLD_MULTIPLIER
|
||||
if dist > threshold:
|
||||
return False
|
||||
rospy.loginfo('Near the current goal position.')
|
||||
return True
|
||||
|
||||
def _check_goal_reached(self, target_pos_w, robot_pos_w):
|
||||
if target_pos_w is None or robot_pos_w is None:
|
||||
return True
|
||||
dist = np.linalg.norm(np.array(target_pos_w[:2]) - np.array(robot_pos_w[:2]))
|
||||
if dist > self.arrive_goal_threshold:
|
||||
return False
|
||||
rospy.loginfo('Arrived at the goal position.')
|
||||
return True
|
||||
|
||||
def target_position_callback(self, msg):
|
||||
# If the goal arrives before odom, skip frame check.
|
||||
if self.map_frame_id is not None and msg.header.frame_id and \
|
||||
msg.header.frame_id != self.map_frame_id:
|
||||
rospy.logerr(
|
||||
'\033[91mTarget frame_id "{}" does not match odometry frame_id "{}"\033[0m'
|
||||
.format(msg.header.frame_id, self.map_frame_id)
|
||||
)
|
||||
return
|
||||
|
||||
goal_z = msg.pose.position.z
|
||||
if abs(goal_z) < 1e-3:
|
||||
if self.robot_pos_w is not None:
|
||||
goal_z = self.robot_pos_w[2]
|
||||
else:
|
||||
rospy.logwarn('Robot position not available, using received z for target.')
|
||||
|
||||
self.target_pos_w = [msg.pose.position.x, msg.pose.position.y, goal_z]
|
||||
self.last_target_pos = list(self.target_pos_w)
|
||||
|
||||
rospy.loginfo('Received target position: {}'.format(self.target_pos_w))
|
||||
|
||||
# =====================================================================
|
||||
# Misc reset helpers
|
||||
# =====================================================================
|
||||
def _reset_last_action(self):
|
||||
self.prev_cmd = np.zeros(3)
|
||||
return [0.0, 0.0, 0.0]
|
||||
|
||||
def _reset_joystick(self):
|
||||
self.joy_linear_x = 0.0
|
||||
self.joy_linear_y = 0.0
|
||||
self.joy_angular_z = 0.0
|
||||
|
||||
def _reset_moving_goal(self):
|
||||
self.moving_goal_delta = [0.0, 0.0, 0.0]
|
||||
rospy.loginfo('Reset moving goal delta.')
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Quaternion and transformation utilities using NumPy (no PyTorch dependency)."""
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def normalize(x: np.ndarray, eps: float = 1e-9) -> np.ndarray:
|
||||
"""Normalizes a given input array to unit length.
|
||||
|
||||
Args:
|
||||
x: Input array of shape (N, dims) or (dims,).
|
||||
eps: A small value to avoid division by zero. Defaults to 1e-9.
|
||||
|
||||
Returns:
|
||||
Normalized array of same shape as input.
|
||||
"""
|
||||
if x.ndim == 1:
|
||||
norm = np.linalg.norm(x)
|
||||
return x / max(norm, eps)
|
||||
else:
|
||||
norm = np.linalg.norm(x, axis=-1, keepdims=True)
|
||||
return x / np.clip(norm, eps, None)
|
||||
|
||||
|
||||
def yaw_quat(quat: np.ndarray) -> np.ndarray:
|
||||
"""Extract the yaw component of a quaternion.
|
||||
|
||||
Args:
|
||||
quat: The orientation in (w, x, y, z). Shape is (..., 4)
|
||||
|
||||
Returns:
|
||||
A quaternion with only yaw component.
|
||||
"""
|
||||
shape = quat.shape
|
||||
quat_yaw = quat.copy().reshape(-1, 4)
|
||||
qw = quat_yaw[:, 0]
|
||||
qx = quat_yaw[:, 1]
|
||||
qy = quat_yaw[:, 2]
|
||||
qz = quat_yaw[:, 3]
|
||||
yaw = np.arctan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
|
||||
quat_yaw[:] = 0.0
|
||||
quat_yaw[:, 3] = np.sin(yaw / 2)
|
||||
quat_yaw[:, 0] = np.cos(yaw / 2)
|
||||
quat_yaw = normalize(quat_yaw)
|
||||
return quat_yaw.reshape(shape)
|
||||
|
||||
|
||||
def quat_conjugate(q: np.ndarray) -> np.ndarray:
|
||||
"""Computes the conjugate of a quaternion.
|
||||
|
||||
Args:
|
||||
q: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
|
||||
|
||||
Returns:
|
||||
The conjugate quaternion in (w, x, y, z). Shape is (..., 4).
|
||||
"""
|
||||
shape = q.shape
|
||||
q = q.reshape(-1, 4)
|
||||
return np.concatenate((q[:, 0:1], -q[:, 1:]), axis=-1).reshape(shape)
|
||||
|
||||
|
||||
def quat_inv(q: np.ndarray) -> np.ndarray:
|
||||
"""Compute the inverse of a quaternion.
|
||||
|
||||
Args:
|
||||
q: The quaternion orientation in (w, x, y, z). Shape is (N, 4).
|
||||
|
||||
Returns:
|
||||
The inverse quaternion in (w, x, y, z). Shape is (N, 4).
|
||||
"""
|
||||
return normalize(quat_conjugate(q))
|
||||
|
||||
|
||||
def quat_mul(q1: np.ndarray, q2: np.ndarray) -> np.ndarray:
|
||||
"""Multiply two quaternions together.
|
||||
|
||||
Args:
|
||||
q1: The first quaternion in (w, x, y, z). Shape is (..., 4).
|
||||
q2: The second quaternion in (w, x, y, z). Shape is (..., 4).
|
||||
|
||||
Returns:
|
||||
The product of the two quaternions in (w, x, y, z). Shape is (..., 4).
|
||||
|
||||
Raises:
|
||||
ValueError: Input shapes of ``q1`` and ``q2`` are not matching.
|
||||
"""
|
||||
if q1.shape != q2.shape:
|
||||
msg = f"Expected input quaternion shape mismatch: {q1.shape} != {q2.shape}."
|
||||
raise ValueError(msg)
|
||||
|
||||
shape = q1.shape
|
||||
q1 = q1.reshape(-1, 4)
|
||||
q2 = q2.reshape(-1, 4)
|
||||
|
||||
w1, x1, y1, z1 = q1[:, 0], q1[:, 1], q1[:, 2], q1[:, 3]
|
||||
w2, x2, y2, z2 = q2[:, 0], q2[:, 1], q2[:, 2], q2[:, 3]
|
||||
|
||||
ww = (z1 + x1) * (x2 + y2)
|
||||
yy = (w1 - y1) * (w2 + z2)
|
||||
zz = (w1 + y1) * (w2 - z2)
|
||||
xx = ww + yy + zz
|
||||
qq = 0.5 * (xx + (z1 - x1) * (x2 - y2))
|
||||
w = qq - ww + (z1 - y1) * (y2 - z2)
|
||||
x = qq - xx + (x1 + w1) * (x2 + w2)
|
||||
y = qq - yy + (w1 - x1) * (y2 + z2)
|
||||
z = qq - zz + (z1 + y1) * (w2 - x2)
|
||||
|
||||
return np.stack([w, x, y, z], axis=-1).reshape(shape)
|
||||
|
||||
|
||||
def quat_apply(quat: np.ndarray, vec: np.ndarray) -> np.ndarray:
|
||||
"""Apply a quaternion rotation to a vector.
|
||||
|
||||
Args:
|
||||
quat: The quaternion in (w, x, y, z). Shape is (..., 4).
|
||||
vec: The vector in (x, y, z). Shape is (..., 3).
|
||||
|
||||
Returns:
|
||||
The rotated vector in (x, y, z). Shape is (..., 3).
|
||||
"""
|
||||
shape = vec.shape
|
||||
quat = quat.reshape(-1, 4)
|
||||
vec = vec.reshape(-1, 3)
|
||||
|
||||
xyz = quat[:, 1:]
|
||||
t = np.cross(xyz, vec) * 2
|
||||
return (vec + quat[:, 0:1] * t + np.cross(xyz, t)).reshape(shape)
|
||||
|
||||
|
||||
def matrix_from_quat(quaternions: np.ndarray) -> np.ndarray:
|
||||
"""Convert rotations given as quaternions to rotation matrices.
|
||||
|
||||
Args:
|
||||
quaternions: The quaternion orientation in (w, x, y, z). Shape is (..., 4).
|
||||
|
||||
Returns:
|
||||
Rotation matrices. The shape is (..., 3, 3).
|
||||
"""
|
||||
r, i, j, k = quaternions[..., 0], quaternions[..., 1], quaternions[..., 2], quaternions[..., 3]
|
||||
two_s = 2.0 / (quaternions * quaternions).sum(-1)
|
||||
|
||||
o = np.stack(
|
||||
(
|
||||
1 - two_s * (j * j + k * k),
|
||||
two_s * (i * j - k * r),
|
||||
two_s * (i * k + j * r),
|
||||
two_s * (i * j + k * r),
|
||||
1 - two_s * (i * i + k * k),
|
||||
two_s * (j * k - i * r),
|
||||
two_s * (i * k - j * r),
|
||||
two_s * (j * k + i * r),
|
||||
1 - two_s * (i * i + j * j),
|
||||
),
|
||||
axis=-1,
|
||||
)
|
||||
return o.reshape(quaternions.shape[:-1] + (3, 3))
|
||||
|
||||
|
||||
def subtract_frame_transforms(
|
||||
t01: np.ndarray, q01: np.ndarray, t02: np.ndarray = None, q02: np.ndarray = None
|
||||
) -> tuple:
|
||||
r"""Subtract transformations between two reference frames into a stationary frame.
|
||||
|
||||
It performs the following transformation operation: :math:`T_{12} = T_{01}^{-1} \times T_{02}`,
|
||||
where :math:`T_{AB}` is the homogeneous transformation matrix from frame A to B.
|
||||
|
||||
Args:
|
||||
t01: Position of frame 1 w.r.t. frame 0. Shape is (N, 3).
|
||||
q01: Quaternion orientation of frame 1 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
|
||||
t02: Position of frame 2 w.r.t. frame 0. Shape is (N, 3).
|
||||
Defaults to None, in which case the position is assumed to be zero.
|
||||
q02: Quaternion orientation of frame 2 w.r.t. frame 0 in (w, x, y, z). Shape is (N, 4).
|
||||
Defaults to None, in which case the orientation is assumed to be identity.
|
||||
|
||||
Returns:
|
||||
A tuple containing the position and orientation of frame 2 w.r.t. frame 1.
|
||||
Shape of the arrays are (N, 3) and (N, 4) respectively.
|
||||
"""
|
||||
q10 = quat_inv(q01)
|
||||
if q02 is not None:
|
||||
q12 = quat_mul(q10, q02)
|
||||
else:
|
||||
q12 = q10
|
||||
|
||||
if t02 is not None:
|
||||
t12 = quat_apply(q10, t02 - t01)
|
||||
else:
|
||||
t12 = quat_apply(q10, -t01)
|
||||
return t12, q12
|
||||
|
||||
|
||||
def transform_points(
|
||||
points: np.ndarray, pos: np.ndarray = None, quat: np.ndarray = None
|
||||
) -> np.ndarray:
|
||||
r"""Transform input points in a given frame to a target frame.
|
||||
|
||||
This function transform points from a source frame to a target frame. The transformation is defined by the
|
||||
position :math:`t` and orientation :math:`R` of the target frame in the source frame.
|
||||
|
||||
.. math::
|
||||
p_{target} = R_{target} \times p_{source} + t_{target}
|
||||
|
||||
Args:
|
||||
points: Points to transform. Shape is (N, P, 3) or (P, 3).
|
||||
pos: Position of the target frame. Shape is (N, 3) or (3,).
|
||||
Defaults to None, in which case the position is assumed to be zero.
|
||||
quat: Quaternion orientation of the target frame in (w, x, y, z). Shape is (N, 4) or (4,).
|
||||
Defaults to None, in which case the orientation is assumed to be identity.
|
||||
|
||||
Returns:
|
||||
Transformed points in the target frame. Shape is (N, P, 3) or (P, 3).
|
||||
|
||||
Raises:
|
||||
ValueError: If the inputs `points` is not of shape (N, P, 3) or (P, 3).
|
||||
ValueError: If the inputs `pos` is not of shape (N, 3) or (3,).
|
||||
ValueError: If the inputs `quat` is not of shape (N, 4) or (4,).
|
||||
"""
|
||||
points_batch = points.copy()
|
||||
is_batched = points_batch.ndim == 3
|
||||
|
||||
if points_batch.ndim == 2:
|
||||
points_batch = points_batch[np.newaxis] # (P, 3) -> (1, P, 3)
|
||||
if points_batch.ndim != 3:
|
||||
raise ValueError(f"Expected points to have dim = 2 or dim = 3: got shape {points.shape}")
|
||||
if not (pos is None or pos.ndim == 1 or pos.ndim == 2):
|
||||
raise ValueError(f"Expected pos to have dim = 1 or dim = 2: got shape {pos.shape}")
|
||||
if not (quat is None or quat.ndim == 1 or quat.ndim == 2):
|
||||
raise ValueError(f"Expected quat to have dim = 1 or dim = 2: got shape {quat.shape}")
|
||||
|
||||
# -- rotation
|
||||
if quat is not None:
|
||||
rot_mat = matrix_from_quat(quat)
|
||||
if rot_mat.ndim == 2:
|
||||
rot_mat = rot_mat[np.newaxis] # (3, 3) -> (1, 3, 3)
|
||||
# (N, P, 3) -> (N, 3, P)
|
||||
points_batch = np.transpose(points_batch, (0, 2, 1))
|
||||
# Apply rotation: (N, 3, 3) @ (N, 3, P) -> (N, 3, P)
|
||||
points_batch = np.matmul(rot_mat, points_batch)
|
||||
# (N, 3, P) -> (N, P, 3)
|
||||
points_batch = np.transpose(points_batch, (0, 2, 1))
|
||||
|
||||
# -- translation
|
||||
if pos is not None:
|
||||
if pos.ndim == 1:
|
||||
pos = pos[np.newaxis, np.newaxis, :] # (3,) -> (1, 1, 3)
|
||||
else:
|
||||
pos = pos[:, np.newaxis, :] # (N, 3) -> (N, 1, 3)
|
||||
points_batch = points_batch + pos
|
||||
|
||||
if not is_batched:
|
||||
points_batch = points_batch.squeeze(0) # (1, P, 3) -> (P, 3)
|
||||
|
||||
return points_batch
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Visualization utilities for the SRU navigation controller (ROS1 port)."""
|
||||
|
||||
import numpy as np
|
||||
import rospy
|
||||
from geometry_msgs.msg import Point, Quaternion, Vector3
|
||||
from std_msgs.msg import Header
|
||||
from visualization_msgs.msg import Marker
|
||||
|
||||
from sru_nav_go2 import constants
|
||||
from sru_nav_go2.utils import transform_points, yaw_quat
|
||||
|
||||
|
||||
def _stamp_from_sec(sec):
|
||||
"""Build a rospy.Time stamp from a float seconds value."""
|
||||
return rospy.Time.from_sec(float(sec))
|
||||
|
||||
|
||||
class VisualizationManager:
|
||||
"""Manages visualization markers for the navigation controller."""
|
||||
|
||||
def __init__(self, node=None):
|
||||
# `node` retained for API parity with the original class. Not used in ROS1.
|
||||
self.node = node
|
||||
|
||||
def publish_twist_marker(self, twist_msg, robot_odom_time, robot_frame_id, publisher):
|
||||
if robot_frame_id is None:
|
||||
return
|
||||
|
||||
marker = Marker()
|
||||
marker.header = Header()
|
||||
marker.header.stamp = _stamp_from_sec(robot_odom_time)
|
||||
marker.header.frame_id = robot_frame_id
|
||||
|
||||
marker.type = Marker.ARROW
|
||||
marker.action = Marker.ADD
|
||||
marker.id = constants.TWIST_MARKER_ID
|
||||
|
||||
start_point = Point(x=0.0, y=0.0, z=0.0)
|
||||
end_point = Point(
|
||||
x=twist_msg.linear.x * constants.TWIST_MARKER_SCALE,
|
||||
y=twist_msg.linear.y * constants.TWIST_MARKER_SCALE,
|
||||
z=0.0,
|
||||
)
|
||||
marker.points = [start_point, end_point]
|
||||
|
||||
marker.scale = Vector3(x=0.2, y=0.4, z=0.4)
|
||||
marker.color.r = 0.0
|
||||
marker.color.g = 0.0
|
||||
marker.color.b = 1.0
|
||||
marker.color.a = 0.8
|
||||
marker.pose.orientation = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0)
|
||||
marker.frame_locked = False
|
||||
|
||||
publisher.publish(marker)
|
||||
|
||||
def publish_target_vector_marker(self, target_vec_b, robot_odom_time, robot_frame_id, publisher):
|
||||
if robot_frame_id is None:
|
||||
return
|
||||
|
||||
marker = Marker()
|
||||
marker.header = Header()
|
||||
marker.header.stamp = _stamp_from_sec(robot_odom_time)
|
||||
marker.header.frame_id = robot_frame_id
|
||||
|
||||
marker.type = Marker.ARROW
|
||||
marker.action = Marker.ADD
|
||||
marker.id = constants.TARGET_VECTOR_MARKER_ID
|
||||
|
||||
vec = target_vec_b.flatten()
|
||||
|
||||
start_point = Point(x=0.0, y=0.0, z=0.0)
|
||||
end_point = Point(x=float(vec[0]), y=float(vec[1]), z=float(vec[2]))
|
||||
marker.points = [start_point, end_point]
|
||||
|
||||
marker.scale = Vector3(x=0.1, y=0.2, z=0.2)
|
||||
marker.pose.orientation = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0)
|
||||
marker.color.r = 0.0
|
||||
marker.color.g = 1.0
|
||||
marker.color.b = 0.0
|
||||
marker.color.a = 0.5
|
||||
marker.frame_locked = False
|
||||
|
||||
publisher.publish(marker)
|
||||
|
||||
def publish_moving_goal_marker(self, moving_goal_delta, robot_pos_w, robot_orientation_w,
|
||||
robot_odom_time, map_frame_id, publisher):
|
||||
if robot_pos_w is None or map_frame_id is None:
|
||||
return
|
||||
|
||||
robot_pos = np.array(robot_pos_w, dtype=np.float32)
|
||||
robot_ori = np.array(robot_orientation_w, dtype=np.float32)
|
||||
robot_yaw_ori = yaw_quat(robot_ori)
|
||||
moving_goal_pos = np.array(moving_goal_delta, dtype=np.float32)
|
||||
|
||||
moving_goal_pos_w = transform_points(
|
||||
moving_goal_pos[np.newaxis],
|
||||
robot_pos[np.newaxis],
|
||||
robot_yaw_ori[np.newaxis],
|
||||
)
|
||||
|
||||
marker = Marker()
|
||||
marker.header = Header()
|
||||
marker.header.stamp = _stamp_from_sec(robot_odom_time)
|
||||
marker.header.frame_id = map_frame_id
|
||||
|
||||
marker.type = Marker.ARROW
|
||||
marker.action = Marker.ADD
|
||||
marker.id = constants.MOVING_GOAL_MARKER_ID
|
||||
|
||||
start_point = Point(
|
||||
x=float(moving_goal_pos_w[0, 0]),
|
||||
y=float(moving_goal_pos_w[0, 1]),
|
||||
z=float(moving_goal_pos_w[0, 2]) + 1.0,
|
||||
)
|
||||
end_point = Point(
|
||||
x=float(moving_goal_pos_w[0, 0]),
|
||||
y=float(moving_goal_pos_w[0, 1]),
|
||||
z=float(moving_goal_pos_w[0, 2]),
|
||||
)
|
||||
marker.points = [start_point, end_point]
|
||||
|
||||
marker.scale = Vector3(x=0.3, y=0.6, z=0.6)
|
||||
marker.color.r = 1.0
|
||||
marker.color.g = 1.0
|
||||
marker.color.b = 0.0
|
||||
marker.color.a = 0.5
|
||||
marker.pose.orientation = Quaternion(w=1.0, x=0.0, y=0.0, z=0.0)
|
||||
marker.frame_locked = False
|
||||
|
||||
publisher.publish(marker)
|
||||
|
||||
def publish_waypoints_marker(self, waypoints_visualization, map_frame_id, publisher):
|
||||
"""Publish recorded waypoints as a CUBE_LIST marker.
|
||||
|
||||
Note: ROS2 version received a `clock`. In ROS1 we use rospy.Time.now().
|
||||
"""
|
||||
if map_frame_id is None:
|
||||
return
|
||||
|
||||
marker = Marker()
|
||||
marker.header.stamp = rospy.Time.now()
|
||||
marker.header.frame_id = map_frame_id
|
||||
marker.ns = 'recorded_waypoints'
|
||||
marker.id = constants.WAYPOINTS_MARKER_ID
|
||||
marker.type = Marker.CUBE_LIST
|
||||
marker.action = Marker.ADD
|
||||
marker.scale = Vector3(x=0.3, y=0.3, z=0.3)
|
||||
marker.color.r = 0.0
|
||||
marker.color.g = 1.0
|
||||
marker.color.b = 0.0
|
||||
marker.color.a = 1.0
|
||||
|
||||
marker.points = []
|
||||
for waypoint in waypoints_visualization:
|
||||
marker.points.append(Point(x=waypoint[0], y=waypoint[1], z=waypoint[2]))
|
||||
|
||||
publisher.publish(marker)
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Waypoint management for the SRU navigation controller (ROS1 port).
|
||||
|
||||
This module is logger-agnostic: pass any object with .info/.warn methods.
|
||||
For rospy a thin wrapper around rospy.loginfo / rospy.logwarn is provided.
|
||||
"""
|
||||
|
||||
from collections import deque
|
||||
|
||||
|
||||
class RospyLogger:
|
||||
"""Minimal logger duck-type matching the original rclpy logger interface."""
|
||||
|
||||
def __init__(self):
|
||||
import rospy
|
||||
self._rospy = rospy
|
||||
|
||||
def info(self, msg):
|
||||
self._rospy.loginfo(msg)
|
||||
|
||||
def warn(self, msg):
|
||||
self._rospy.logwarn(msg)
|
||||
|
||||
# Keep ROS2-style alias used in original code
|
||||
def warning(self, msg):
|
||||
self._rospy.logwarn(msg)
|
||||
|
||||
def error(self, msg):
|
||||
self._rospy.logerr(msg)
|
||||
|
||||
|
||||
class WaypointManager:
|
||||
"""Manages waypoint recording, tracking, and playback."""
|
||||
|
||||
def __init__(self, logger):
|
||||
self.logger = logger
|
||||
self.recorded_waypoints = deque()
|
||||
self.inversed_ordered_waypoints = deque()
|
||||
self.waypoints_visualization = deque()
|
||||
self.is_publish_waypoints_home = False
|
||||
self.is_publish_waypoints_inversed = False
|
||||
|
||||
def record_waypoint(self, robot_pos_w):
|
||||
if robot_pos_w is None:
|
||||
self.logger.warn('Robot position is not available yet.')
|
||||
return False
|
||||
|
||||
if len(self.recorded_waypoints) == 0 and len(self.inversed_ordered_waypoints) > 0:
|
||||
self.inversed_ordered_waypoints.clear()
|
||||
self.waypoints_visualization.clear()
|
||||
self.logger.info('Clear the inversed waypoints, and visualization waypoints.')
|
||||
|
||||
self.recorded_waypoints.append(robot_pos_w)
|
||||
self.inversed_ordered_waypoints.appendleft(robot_pos_w)
|
||||
self.waypoints_visualization.append(robot_pos_w)
|
||||
self.logger.info(
|
||||
'Waypoint recorded: {}, total waypoints: {}'.format(
|
||||
robot_pos_w, len(self.recorded_waypoints)
|
||||
)
|
||||
)
|
||||
return True
|
||||
|
||||
def remove_last_waypoint(self):
|
||||
removed_count = 0
|
||||
|
||||
if len(self.recorded_waypoints) > 0:
|
||||
self.recorded_waypoints.pop()
|
||||
removed_count += 1
|
||||
self.logger.info(
|
||||
'Removed last waypoint (home), total: {}'.format(len(self.recorded_waypoints))
|
||||
)
|
||||
|
||||
if len(self.inversed_ordered_waypoints) > 0:
|
||||
self.inversed_ordered_waypoints.popleft()
|
||||
removed_count += 1
|
||||
self.logger.info(
|
||||
'Removed last waypoint (inversed), total: {}'.format(
|
||||
len(self.inversed_ordered_waypoints)
|
||||
)
|
||||
)
|
||||
|
||||
if len(self.waypoints_visualization) > 0:
|
||||
self.waypoints_visualization.pop()
|
||||
removed_count += 1
|
||||
self.logger.info(
|
||||
'Removed last waypoint (visualization), total: {}'.format(
|
||||
len(self.waypoints_visualization)
|
||||
)
|
||||
)
|
||||
|
||||
if (len(self.waypoints_visualization) < len(self.recorded_waypoints) or
|
||||
len(self.waypoints_visualization) < len(self.inversed_ordered_waypoints)):
|
||||
raise ValueError(
|
||||
'The visualization waypoints is smaller than the recorded waypoints.'
|
||||
)
|
||||
|
||||
if removed_count == 0:
|
||||
self.logger.warn('No waypoints to remove.')
|
||||
|
||||
return removed_count > 0
|
||||
|
||||
def get_next_waypoint_home(self):
|
||||
if self.recorded_waypoints:
|
||||
return self.recorded_waypoints.pop()
|
||||
return None
|
||||
|
||||
def get_next_waypoint_inversed(self):
|
||||
if self.inversed_ordered_waypoints:
|
||||
return self.inversed_ordered_waypoints.pop()
|
||||
return None
|
||||
|
||||
def start_home_waypoint_sequence(self):
|
||||
if len(self.recorded_waypoints) > 0:
|
||||
self.is_publish_waypoints_home = True
|
||||
return True
|
||||
return False
|
||||
|
||||
def start_inversed_waypoint_sequence(self):
|
||||
if len(self.inversed_ordered_waypoints) > 0:
|
||||
self.is_publish_waypoints_inversed = True
|
||||
return True
|
||||
return False
|
||||
|
||||
def stop_home_waypoint_sequence(self):
|
||||
self.is_publish_waypoints_home = False
|
||||
|
||||
def stop_inversed_waypoint_sequence(self):
|
||||
self.is_publish_waypoints_inversed = False
|
||||
|
||||
def reset_visualization_if_complete(self):
|
||||
if (not self.recorded_waypoints and not self.inversed_ordered_waypoints
|
||||
and self.waypoints_visualization):
|
||||
self.logger.info('All waypoints are published, reset visualization.')
|
||||
self.waypoints_visualization.clear()
|
||||
return True
|
||||
return False
|
||||
|
||||
def re_add_aborted_waypoint(self, target_pos_w):
|
||||
if self.is_publish_waypoints_home:
|
||||
self.recorded_waypoints.append(target_pos_w)
|
||||
self.logger.info('Goal aborted - re-adding current goal as a recorded (home) waypoint.')
|
||||
if self.is_publish_waypoints_inversed:
|
||||
self.inversed_ordered_waypoints.appendleft(target_pos_w)
|
||||
self.logger.info(
|
||||
'Goal aborted: reinserting the current goal as recorded (inversed) waypoint.'
|
||||
)
|
||||
|
||||
def has_home_waypoints(self):
|
||||
return len(self.recorded_waypoints) > 0
|
||||
|
||||
def has_inversed_waypoints(self):
|
||||
return len(self.inversed_ordered_waypoints) > 0
|
||||
|
||||
def is_home_sequence_active(self):
|
||||
return self.is_publish_waypoints_home
|
||||
|
||||
def is_inversed_sequence_active(self):
|
||||
return self.is_publish_waypoints_inversed
|
||||
Reference in New Issue
Block a user