commit eba4570f4e3727fa7dcd5a8ff82ad55991a57a62 Author: kevin Date: Mon Oct 19 11:15:15 2026 +0800 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 / 协议核查报告 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f130899 --- /dev/null +++ b/.gitignore @@ -0,0 +1,97 @@ +# ===================================================================== +# RoboCon 2027 · BR 机器人代码仓库 —— 根目录 .gitignore +# 现仓库只保留 sru_ws/(ROS 2 Humble 自主导航工作区)。 +# 规则:只收录「构建产物 / 运行期数据 / 本地环境 / 私人工具状态」, +# 源码、配置、文档、模型一律保留。 +# ===================================================================== + +# --------------------------------------------------------------------- +# 1. ROS 2 (colcon) 构建与运行产物 +# sru_ws/{build,install,log} 全部是本地生成物,换机重建即可 +# --------------------------------------------------------------------- +build/ +install/ +log/ +.colcon/ +*.bag +*.bag.active +*.db3 +*.mcap +rosbag2_*/ +# ROS 2 日志目录可能出现在任意层级的包内 +**/log/ +**/.ros/ + +# --------------------------------------------------------------------- +# 2. Python(venv 是本地虚拟环境,体积大且平台相关,绝不能上传) +# --------------------------------------------------------------------- +venv/ +.venv/ +env/ +__pycache__/ +*.py[cod] +*$py.class +*.egg-info/ +.eggs/ +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +.ipynb_checkpoints/ +*.so + +# --------------------------------------------------------------------- +# 3. 桌面回收站(误删文件躺在 .Trash-0 里,不要入库) +# --------------------------------------------------------------------- +.Trash-0/ +.Trash-*/ +.local/share/Trash/ + +# --------------------------------------------------------------------- +# 4. 编辑器 / IDE 本地状态 +# --------------------------------------------------------------------- +.vscode/ +.idea/ +*.swp +*.swo +*~ +*.bak +*.orig + +# --------------------------------------------------------------------- +# 5. 操作系统杂物 +# --------------------------------------------------------------------- +.DS_Store +Thumbs.db +desktop.ini + +# --------------------------------------------------------------------- +# 6. 本地工具状态(AI 记忆、临时缓存等,属个人本地数据) +# 如果团队希望把 AI 工作日志一并公开,删掉下面这行即可 +# --------------------------------------------------------------------- +.workbuddy/ + +# --------------------------------------------------------------------- +# 7. Odin 驱动 / 传感器运行期数据(在上游包内也应忽略) +# --------------------------------------------------------------------- +recorddata/ +**/recorddata/ +/config/calib.yaml +**/map/*.pcd +*.pcd + +# --------------------------------------------------------------------- +# 8. 可选:上游只读参考快照(SRU-Odin ROS 1 蓝图 + Train 侧) +# 这是第三方仓库快照,若想保持本仓库精简,取消下一行注释 +# 取消前请确认团队不需要离线对照,且记得保留来源说明 +# --------------------------------------------------------------------- +# sru_ws/reference/ + +# --------------------------------------------------------------------- +# 9. 大文件提示:src/sru_nav_ros2/models/*.onnx 约 27 MB +# 目前 GitHub 单文件 < 100 MB 可正常上传; +# 若日后模型变大或频繁变更,建议改用 Git LFS 管理 *.onnx +# --------------------------------------------------------------------- +# *.onnx + +# 驱动运行期产物 +sru_ws/src/odin_ros_driver/map/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..9d2575f --- /dev/null +++ b/README.md @@ -0,0 +1,90 @@ +# RoboCon 2027 · BR 机器人代码仓库(上位机 / ROS 2) + +本仓库是 **RoboCon 2027 赛季 BR 机器人** 的**上位机代码**,工作区为 [`sru_ws/`](sru_ws/): + +| 模块 | 目录 | 技术栈 | 作用 | +|---|---|---|---| +| **自主导航** | [`sru_ws/`](sru_ws/) | ROS 2 Humble + Python + ONNX Runtime | 端到端无图导航:感知 → 策略 → 底盘速度指令 | + +> 下位机固件(STM32 底盘控制)已从本仓库移除,单独维护。 +> 上位机算出的 `[vx, vy, ω]` 速度指令通过 **串口(UART)** 下发给 STM32 底盘执行。 + +--- + +## 一、`sru_ws/` —— ROS 2 Humble 自主导航工作区 + +端到端**反应式**导航:**深度图 + 16 维状态 → ONNX 策略 → `/cmd_vel`**。没有地图、没有 SLAM、没有规划路径;**没有深度就不发任何速度指令**。 + +### 功能包(`src/`) + +| 包名 | 版本 | 语言 | 说明 | +|---|---|---|---| +| `odin_ros_driver` | 0.14.2 | C++ | Odin1 传感器 ROS 2 驱动(相机/里程计/深度图),源自上游 | +| `sru_nav_ros2` | 0.1.0 | Python | 导航策略节点 + 目标点运行器,加载 `models/*.onnx` | +| `techx_r2_chassis_control` | 0.2.0 | Python | 串口桥:`/cmd_vel` → R2 底盘 STM32 定长速度帧 | + +### 数据流 + +``` +/odin1/depth_img_competetion ─┐ +/odin1/odometry_highfreq ├─► sru_nav_node (ONNX RT) ─► /cmd_vel ─► chassis_serial_node ─► STM32 +/joy (deadman + 手动叠加) ┘ ▲ + ▲ └─ /goal_pose + /goal_yaw +``` + +### 快速开始 + +```bash +# 0. 环境(ROS 2 Humble) +source /opt/ros/humble/setup.bash +source sru_ws/venv/bin/activate +source sru_ws/install/setup.bash + +# 1. 构建 +cd sru_ws && colcon build + +# 2. 启动(三个终端) +ros2 launch odin_ros_driver odin1_ros2.launch.py # 终端 A:驱动 + 深度 + rviz2 +ros2 launch sru_nav_ros2 sru_nav.launch.py # 终端 B:导航策略 +ros2 launch techx_r2_chassis_control chassis_serial.launch.py # 终端 C:底盘串口桥 + +# 3. 下发目标点并观察输出 +ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" +ros2 topic echo /cmd_vel +``` + +### 文档索引 + +| 想了解 | 文档 | +|---|---| +| **怎么跑起来**(三步 source、三个终端、上机安全检查) | [`sru_ws/docs/USAGE.md`](sru_ws/docs/USAGE.md) | +| 原理 / 数据流 / 全部参数 / 排错速查 | `sru_ws/src/sru_nav_ros2/docs/DEPLOY_ROS2.md` | +| 交付与迁移(打包清单、为何 venv 不能拷贝) | `sru_ws/src/sru_nav_ros2/docs/HANDOVER_TEAM.md` | +| 本机环境适配与验收记录 | [`sru_ws/docs/PORT_NOTES_2026-09-28.md`](sru_ws/docs/PORT_NOTES_2026-09-28.md) | +| 文档总索引 | [`sru_ws/docs/README.md`](sru_ws/docs/README.md) | + +--- + +## 二、环境依赖 + +| 组件 | 版本 | +|---|---| +| ROS 2 | Humble | +| Python | 3.10 | +| ONNX Runtime | 见 `sru_ws/venv` 内版本(重建环境时按 `docs` 说明安装) | + +> `sru_ws/venv/` 是本地虚拟环境,**不入库**,换机后请按 `docs/USAGE.md` 重建。 + +--- + +## 三、关于大文件 + +- **模型文件**:`sru_ws/src/sru_nav_ros2/models/` 下两个 ONNX(合计约 27 MB)随仓库分发;若日后显著变大,建议改用 Git LFS。 +- **不进入版本控制**:`build/`、`install/`、`log/`、`venv/`、`.Trash-0/` 等,详见根目录 `.gitignore`。 + +--- + +## 四、致谢 + +- Odin1 驱动及 ROS 1 蓝图来自上游开源项目(见 `sru_ws/reference/SRU-Odin/LICENSE`)。 +- 各第三方组件版权归原作者所有。 diff --git a/sru_ws/docs/HANDOVER.md b/sru_ws/docs/HANDOVER.md new file mode 100644 index 0000000..514204e --- /dev/null +++ b/sru_ws/docs/HANDOVER.md @@ -0,0 +1,378 @@ +# 交接文档 —— SRU-Odin ROS1 → ROS2 Humble 移植 + +> **交接方**:Windows 侧会话(已完成仓库全面调研与方案设计) +> **接手方**:Ubuntu 22.04 侧 WorkBuddy +> **配套文件**:`PROMPT_ROS2_UBUNTU.md`(贴给 AI 的提示词)、`ROS2_PORT_PLAN.md`(详细迁移面与 API 对照表) +> **日期**:2026-09-22 + +--- + +## 1. 怎么用这份交接包 + +三步: + +1. **拷**:把 `handover/` 整个文件夹拷到优盘,带到 Ubuntu 那边的电脑 +2. **贴**:在 Ubuntu 侧 WorkBuddy 里,把 `PROMPT_ROS2_UBUNTU.md` 里「提示词开始 / 结束」之间的全文粘进对话框,回车 +3. **答**:AI 会先汇报环境检查结果并向你提问,按 `HANDOVER.md` 第 4、6、7 节的内容回答即可 + +建议把 `HANDOVER.md` 和 `ROS2_PORT_PLAN.md` 也放到 Ubuntu 侧的 `~/sru_ws/reference/` 下,方便 AI 随时读。 + +--- + +## 2. 优盘要拷什么 + +### 必需(共 3 个 md,体积极小) + +| 文件 | 作用 | +|---|---| +| `handover/PROMPT_ROS2_UBUNTU.md` | 贴给 Ubuntu 侧 AI 的提示词 | +| `handover/HANDOVER.md` | 本文件,人读的交接说明 | +| `handover/ROS2_PORT_PLAN.md` | 详细迁移面、ROS1→ROS2 API 逐点对照表(AI 需要它) | + +### 源码:**不用拷,直接 clone 更好** + +我已核实:源仓库的 `.gitignore` 里 `*.onnx` 是**被注释掉的**,两个模型都已入库;且本地工作区干净,`6a81ba7` 就是上游原样提交。 + +所以 Ubuntu 侧只要一条命令就能拿到**逐字节一致**的源码,包括 28 MB 的模型: + +```bash +mkdir -p ~/sru_ws/src ~/sru_ws/reference +cd ~/sru_ws/reference +git clone https://github.com/ManifoldTechLtd/SRU-Odin.git +cd SRU-Odin +git checkout 6a81ba77f46d4ab010d3d3354d54ec25ef730955 +``` + +### 无网络时的兜底:拷 `Deployment/` 目录(32 MB) + +若 Ubuntu 侧连不上 GitHub,把 Windows 这边这个目录拷到优盘: + +``` +F:\RC2027\odin1_SRU\SRU-Odin-orig\SRU-Odin\Deployment\ +``` + +→ 放到 Ubuntu 的 `~/sru_ws/reference/SRU-Odin/Deployment/`。 + +**只拷 `Deployment/` 就够了**(32 MB):A/B/C 三类要处理的文件、两个 ONNX 模型、config、launch、docs 全在里面。`Train/` 是 Isaac Sim 训练环境,与本次部署迁移无关,不用考。 + +### 校验拿到的源码是否完整 + +```bash +cd ~/sru_ws/reference/SRU-Odin/Deployment +ls -l models/ # 期望 20971407 和 7054074 字节 +sha256sum models/vae_encoder.onnx +# 期望 de70c217c91ef916b877d81c7a134e00d861d6b282f7de2489984b1818596cd0 +sha256sum models/nav_policy.onnx +# 期望 f1410cb77ee7897874d69ee7ba4c4814c2388810367b1ae4627bb3c12b523f1b +``` + +--- + +## 3. Ubuntu 侧环境准备 + +### 3.1 装 ROS2 与系统依赖 + +```bash +sudo apt update +sudo apt install -y \ + ros-humble-desktop \ + ros-humble-cv-bridge \ + ros-humble-joy \ + ros-humble-tf2-ros \ + ros-humble-rviz2 \ + python3-colcon-common-extensions + +source /opt/ros/humble/setup.bash +``` + +### 3.2 装 Python 依赖 + +```bash +pip3 install --user onnxruntime numpy scipy pyyaml +``` + +说明: +- **`scipy` 必需** —— 主节点用 `from scipy.spatial.transform import Rotation as R` 做速度坐标系反旋 +- **`pyyaml` 必需** —— `waypoint_runner` 读航点文件 +- **不要 pip 装 `opencv-python`** —— `cv_bridge` 依赖系统的 `python3-opencv`,再装 pip 版会出现 libopencv 双版本冲突(症状是 import cv_bridge 报符号错误)。`model.py` 用的 `cv2.resize` 由系统 opencv 提供就够 +- **不要装 conda** —— ROS2 用系统 python3.10 即可,ROS1 那套 conda 是历史包袱(见第 5.3 节) + +若 pip 报 `error: externally-managed-environment`,改用虚拟环境(但必须带 `--system-site-packages`,否则 import 不到 rclpy / cv_bridge): + +```bash +python3 -m venv --system-site-packages ~/sru_ws/venv +source ~/sru_ws/venv/bin/activate +pip install onnxruntime numpy scipy pyyaml +``` + +### 3.3 验证环境 + +```bash +ros2 --version +python3 -c "import rclpy, cv_bridge, numpy, scipy, yaml; print('ros + deps ok')" +python3 -c "import onnxruntime as ort; print(ort.get_available_providers())" +``` + +`get_available_providers()` 出现 `CPUExecutionProvider` 即可;模型合计 28 MB,CPU 推理在 5 Hz 下通常够用。 + +--- + +## 4. 任务摘要 + +### 4.1 一句话 + +把源仓库的 **ROS1 Noetic** 部署包(`Deployment/`,包名 `sru_nav_go2_ros1`)反向移植成 **ROS2 Humble** 的 ament_python 包 `sru_nav_ros2`,能跑通 `/cmd_vel` 输出。 + +### 4.2 为什么是「反向移植」而不是去改官方 ROS2 仓库 + +你原本的想法是「官方说 Odin1 支持 ROS2,去看 sru 官方源代码改话题」。我核实后发现官方那个 ROS2 仓库 + +`leggedrobotics/sru-robot-deployment` + +是 **ROS 2 Jazzy** + PyTorch CUDA venv(`~/ros2_torch`)+ ZED-X 深度 + DLIO 里程计 + 输出 `/path_manager/path_manager_ros/nav_vel`(**不是** `/cmd_vel`)+ C++ `b2w_controllers` 专用底层。要把它改成 Odin1 + 你的机器人,得同时动五处强耦合的东西。 + +而这个仓库的 ROS1 包**本来就是从 ROS2 机械改写来的**——其主节点文件头自己写着: + +> *"Direct port of the original ROS2 NavigationPolicyNode. Behaviour is preserved; only ROS API calls, time helpers, and topic defaults have been changed."* + +也就是说,**反向改回去等于撤销一次已知的机械变换**,路径最短,而且传感器(Odin1)、推理(ONNX 双模型)、参数(保守 policy_scale)、安全机制(手柄 deadman)全都已经按目标调好了,不用再对齐。 + +### 4.3 工作量分布(1942 行里只有 1120 行要改) + +| 分层 | 行数 | 文件 | 处理方式 | +|---|---|---|---| +| **A 零改动** | 508(26%) | `constants.py`、`model.py`、`utils.py` | 直接拷贝,只改 import 包名。三者**一行 ROS 调用都没有** | +| **B 轻改** | 314(16%) | `waypoint_manager.py`、`visualization.py` | 删 `RospyLogger` 包装类;注入 node clock 替代 `rospy.Time` | +| **C 重写** | 1120(58%) | `navigation_policy_node.py`(682)、`scripts/sru_nav_node`(107)、`scripts/waypoint_runner.py`(331) | 按 ROS2 API 改写 | + +加 launch / package.xml / CMakeLists / setup.py 全部按 ament_python 重写。 + +### 4.4 目标目录结构 + +``` +~/sru_ws/ +├── src/ +│ └── sru_nav_ros2/ # 新建的 ROS2 包(要交付的产物) +└── reference/ + └── SRU-Odin/ # 原仓库,只读蓝本 + └── Deployment/ +``` + +> ⚠️ **重要**:参考源码必须放在 `src/` **外面**。否则 `colcon build` 会去编译它的 catkin `CMakeLists.txt`,直接报错。 + +--- + +## 5. 硬性约束 + +### 5.1 绝对不能改的数值(与训练对齐,改了行为就废) + +``` +control_frequency = 5.0 Hz +rnn_hidden_size = 512 +rnn_num_layers = 1 +min_depth / max_depth = 0.25 / 10.0 m +ARRIVE_GOAL_THRESHOLD = 0.75 m +JOYSTICK_TIMEOUT = 15.0 s +LOW_PASS_FILTER_COEF = [0.9, 0.5, 0.5] +LATERAL_VELOCITY_SCALE = 0.6 +深度预处理链:nan_to_num → 裁剪 [0.25, 10.0] → resize (40, 64) +latent = 64×5×8 = 2560 维;obs 总维 2576 = 16(状态) + 2560(图像) +``` + +### 5.2 必须改对的四个语义点 + +| # | 项 | 处理 | +|---|---|---| +| 1 | `use_sim` 参数 | **改名为 `odom_twist_in_base_frame`**。它的真实语义是「odom twist 已在 body 系、直接透传」,与 ROS2 内置 `use_sim_time`(仿真时钟)毫无关系,沿用旧名必被后人误配 | +| 2 | 时间戳字段 | `secs/nsecs` → `sec/nanosec`。该值喂给控制频率门控,改错会导致推理频率失控 | +| 3 | 深度订阅 QoS | 用 `rclpy.qos.qos_profile_sensor_data`(BEST_EFFORT)。BEST_EFFORT 发布端 + RELIABLE 订阅端 = **静默收不到数据**,这是 ROS2 独有的坑 | +| 4 | 私有话题前缀 | `'~base_vel'` → `'~/base_vel'`。节点名保持 `sru_nav_node`,展开结果与 ROS1 一致,rviz 配置可复用 | + +### 5.3 不要移植的 ROS1 专属文件 + +`Deployment/scripts/` 下这三个脚本是 **ROS1 + conda 时代的历史包袱,在 ROS2 下完全不需要**,不要移植也不要参考: + +| 文件 | 为什么不要 | +|---|---| +| `setup_conda_env.sh` | ROS2 不需要 conda,用系统 python3.10 | +| `launch_sru_nav.sh` | 它做的三件事(注入 `PYTHONPATH=/opt/ros/noetic/...`、`LD_PRELOAD` 修 conda libffi 与系统 libp11-kit 的 ABI 冲突、检查 catkin wrapper 的 shebang)在 ROS2 下**全部不存在** | +| `verify_port.sh` | ROS1 专属自检脚本(且用户明确不要自检脚本) | + +顺带一提:ROS1 README 里列的 5 条常见故障,有 3 条在 ROS2 下自动消失——conda↔系统 ROS 的 libffi ABI 冲突、`PYTHONPATH` 手工注入、catkin 锁 `PYTHON_EXECUTABLE` 导致的 shebang 陷阱。**这是这次迁移最大的红利**,别把包袱一起搬过去。 + +### 5.4 安全默认值(不可擅自"优化") + +```yaml +policy_scale: [0.6, 0.3, 0.6] # 训练值本是 [1.5, 1.0, 1.0],部署刻意保守化一半以上 +require_joystick: true # 手柄 deadman,默认必须 true。false 仅限抬轮/仿真测试 +``` + +--- + +## 6. 存疑未决项(7 项,全部需要你上机实测) + +这些项**暂时存疑是完全可以接受的**——已经要求 AI 全部做成可配置项,不会阻塞开发。你实测后只改 `config/sru_nav.yaml` 即可。 + +### ⭐ 第 1 项最关键:Odin1 深度话题的真实名字 + +| | | +|---|---| +| **问题** | 本仓库代码里用的是 `/odin1/depth_img_competetion`,但 Odin1 驱动 `manifoldsdk/odin_ros_driver` 的主线文档只列出 `/odin1/odometry`、`/odin1/odometry_highfreq`、`/odin1/cloud_slam`、`/odin1/imu`、`/odin1/image`,**没有这个深度话题**。它对应驱动配置里 `senddepth: 1` 开启的 dense depth,可能只有部分版本或分支支持 | +| **临时默认** | 沿用 `/odin1/depth_img_competetion` | +| **实测命令** | `ros2 topic list \| grep -i odin`
`ros2 topic list \| grep -iE 'depth\|img'`
`ros2 topic hz /odin1/<候选>`(应 ~10 Hz)
`ros2 topic echo /odin1/<候选> --once --field encoding`(应为 `32FC1`) | +| **不确认的后果** | 节点收不到深度,`/cmd_vel` 恒为 0 | + +同时确认驱动配置:`grep -i senddepth /config/control_command.yaml` 应为 `1`;ROS2 下还需确认深度节点(`depth_image_ros2_node`)被 launch 起来了。 + +`/odin1/odometry_highfreq`(~300–400 Hz)和 `/odin1/odometry`(~10 Hz,SLAM 率,漂移更小但更滞后)两个里程计话题名与 ROS1 一致,可直接用。 + +### 第 2 项:深度与 odom 话题的 QoS + +| | | +|---|---| +| **临时默认** | 深度用 BEST_EFFORT;odom 默认 RELIABLE 但做成可配 | +| **实测命令** | `ros2 topic info -v /odin1/` → 看 `Reliability:` 字段 | +| **说明** | BEST_EFFORT 订阅端与两种发布端都兼容,是最安全选择。若实测发现驱动是 BEST_EFFORT 而代码用了 RELIABLE → 订阅静默失败(不报错,最难查) | + +### 第 3 项:odom 的 twist 是 world 系还是 body 系 + +| | | +|---|---| +| **临时默认** | `odom_twist_in_base_frame: false`(按 world 系处理,与 ROS1 包原默认一致) | +| **判据** | 规则:朝向 +Y 推进时 `linear.x≈0` 而 `linear.y>0` → **world 系**(保持默认);无论朝向如何 `linear.x` 恒为正、`linear.y≈0` → **body 系**(改为 `true`) | +| **实测方法** | ① 让 Odin1 静止:`ros2 topic echo /odin1/odometry_highfreq --field twist.twist.linear`,所有分量应接近 0(这一步只排除非零偏置)
② **推荐**:把 Odin1 朝向任意非零方向(如绕 Z 转 90°),手动沿其镜头方向(body +X)匀速推 1 米,同时看 `linear.x` / `linear.y` | +| **不确认的后果** | 速度指令剧烈震荡或方向错乱 | + +`Deployment/docs/DEPLOY_GO2_NX.md` 第 5 节有四种判定方法(含 rosbag + 数值导数对比),可直接参考。 + +### 第 4 项:odom 的 `header.frame_id` + +| | | +|---|---| +| **临时默认** | 不写死,代码运行时从 odom 消息里读(原实现就是这么做的) | +| **实测命令** | `ros2 topic echo /odin1/odometry_highfreq --once --field header` | +| **要记住的规则** | 发 `/goal_pose` 时 `frame_id` **必须**与该值一致,否则节点直接拒绝目标。这就是"发了目标机器人没反应"最常见的原因 | + +### 第 5 项:Odin1 实际装订位置 + +| | | +|---|---| +| **问题** | launch 里静态 TF `base_link → odin1_base_link` 的默认值 `(x=0.25, y=0, z=0.18, roll=0, pitch=0.349, yaw=0)` 是**从原 Go2 平台假设继承来的**,不是你的车 | +| **临时默认** | 沿用上述值,但在文档里标注"必须实测替换" | +| **要量什么** | Odin1 镜头中心相对机体中心的前向偏移、左向偏移、高度,以及向下俯仰角(弧度)。默认 `pitch=0.349` 约等于 20° 下俯 | +| **实测命令** | 若驱动已发 TF:`ros2 run tf2_ros tf2_echo base_link odin1_base_link`;否则用尺子量 | +| **不确认的后果** | 深度图视角与训练分布偏离,避障行为异常 | + +### 第 6 项:`/joy` 的轴与键索引 + +| | | +|---|---| +| **临时默认** | 沿用 `constants.py` 里现有 PS5 映射(`JOYSTICK_AXIS_LINEAR_X=1`、`JOYSTICK_AXIS_SMART=5`、`BUTTON_ABORT=9`、`BUTTON_SEND_GOAL=10` 等) | +| **实测命令** | `ros2 topic echo /joy`,逐个推摇杆/按键,记录 index | +| **说明** | Humble 的 joy 包默认轴映射与 ROS1 未必一致 | + +### 第 7 项:推理能否跟上 5 Hz + +| | | +|---|---| +| **临时默认** | `control_frequency: 5.0` 不变 | +| **实测命令** | `ros2 topic hz /cmd_vel`(应稳定 ~5 Hz);同时看 CPU 占用 | +| **说明** | 模型合计 28 MB,CPU EP 通常够用。跟不上再考虑装 JetPack 匹配的 `onnxruntime-gpu`(标准 pip 版在 Jetson 上不可用) | + +--- + +## 7. 上机验收清单 + +按顺序跑,每步都要过: + +```bash +# 0) 环境 +ros2 --version +python3 -c "import onnxruntime as ort; print(ort.get_available_providers())" + +# 1) 构建 +cd ~/sru_ws +source /opt/ros/humble/setup.bash +colcon build --symlink-install +source install/setup.bash + +# 2) 静态确认:新包内不应有残留 rospy +grep -rn "rospy" src/sru_nav_ros2/ ; echo "expect: no match" + +# 3) Odin1 驱动已启动的前提下,确认数据流 +ros2 topic list | grep odin1 +ros2 topic hz /odin1/ # ~10 Hz +ros2 topic hz /odin1/odometry_highfreq # ~300-400 Hz +ros2 topic info -v /odin1/ # 记下 Reliability + +# 4) 无手柄的闭环冒烟测试(务必先抬轮/架空!) +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false +# 期望日志:Navigation policy node is ready. + +# 5) 另开终端发目标 + 看输出 +ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" +ros2 topic hz /cmd_vel # 应 ~5 Hz +ros2 topic echo /cmd_vel +``` + +**最后一次检查**:确认 `frames` 一致 —— 发目标用的 `frame_id` 与 odom 的 `header.frame_id` 相同。 + +--- + +## 8. 常见排错速查 + +| 现象 | 排查方向 | +|---|---| +| 节点启动后一直刷 "Odometry not ready, skipping depth callback" | `/odin1/odometry_highfreq` 是否在跑;话题名是否与 yaml 一致 | +| `/cmd_vel` 全是 0 | ① 手柄 deadman(默认开着,`axes[4]` 必须推过 0,15 s 无 joy 强制归零)→ 测试用 `require_joystick:=false`;② 深度话题名错;③ odom twist 坐标系判反 | +| 订阅了但收不到深度,且不报错 | **QoS 不匹配**,改用 BEST_EFFORT;用 `ros2 topic info -v` 对比两端 | +| 发了 `/goal_pose` 机器人没反应 | `frame_id` 与 odom 的 `frame_id` 不一致(节点会直接拒绝并打 error 日志) | +| `cv_bridge` import 报符号错误 / OpenCV 冲突 | 卸掉 pip 版 `opencv-python`,只用 `ros-humble-cv-bridge` + 系统 `python3-opencv` | +| import rclpy 失败 | 没 `source /opt/ros/humble/setup.bash`,或 venv 建的时候漏了 `--system-site-packages` | +| Twist 数值剧烈震荡 | ① `policy_scale` 太大;② odom twist 坐标系判反;③ 深度 NaN 没被过滤 | +| Jetson 上 pip 报 `certificate is not yet valid` | 板子无 RTC 电池导致系统时间回退。`date` 看一下,然后 `sudo timedatectl set-ntp true` 或 `sudo ntpdate -u ntp.aliyun.com && sudo hwclock --systohc` | + +--- + +## 9. 紧急停止手段 + +| 手段 | 操作 | +|---|---| +| 手柄放弃当前目标 | 按 `BUTTON_ABORT`(默认 button index 9)→ 立刻发零速、放弃当前目标 | +| 杀掉导航节点 | `Ctrl+C` 停 `sru_nav_node` → `/cmd_vel` 不再有发布者,你的桥应自动归零(取决于桥的行为,**上机前先确认**) | +| 物理断电 | 终极手段 | + +**首次上机务必抬轮/架空**,确认 `/cmd_vel` 数值有界合理后再落地。 + +--- + +## 10. 关键事实速查 + +| 项 | 值 | +|---|---| +| 源仓库 | `https://github.com/ManifoldTechLtd/SRU-Odin` | +| 精确版本 | `main` @ `6a81ba77f46d4ab010d3d3354d54ec25ef730955`(2026-07-22,"add img encoder model") | +| ROS1 部署包 | `Deployment/`,包名 `sru_nav_go2_ros1`,catkin,32 MB | +| 论文 | DOI `10.1177/02783649251401926`(IJRR 2025) | +| Odin1 驱动 | `manifoldsdk/odin_ros_driver`,单代码库支持 ROS1/ROS2(`#ifdef ROS2`),ROS2 走 `./script/build_ros2.sh` + `ros2 launch odin_ros_driver odin1_ros2.launch.py`,官方推荐 Humble + Ubuntu 22.04 | +| 目标包名 / 节点名 | `sru_nav_ros2` / `sru_nav_node` | +| `/cmd_vel` 语义 | body 系 `geometry_msgs/Twist`,由调用方的桥接到具体机器人 | + +### ROS2 侧话题接口契约(与 ROS1 一致) + +| 话题 | 类型 | 方向 | 说明 | +|---|---|---|---| +| `/odin1/depth_img_competetion` ⚠️待实测 | `sensor_msgs/msg/Image` | 入 | 稠密深度,`32FC1`,单位米,~10 Hz | +| `/odin1/odometry_highfreq` | `nav_msgs/msg/Odometry` | 入 | ~300–400 Hz | +| `/joy` | `sensor_msgs/msg/Joy` | 入 | 手柄 | +| `/goal_pose` | `geometry_msgs/msg/PoseStamped` | 入/出 | `frame_id` 必须等于 odom 的 `frame_id` | +| `/cmd_vel` | `geometry_msgs/msg/Twist` | 出 | body 系速度指令 | + +### 模型 I/O 契约(不要改) + +| 模型 | 输入 | 输出 | +|---|---|---| +| `vae_encoder.onnx` | `input` `(B,1,40,64)` | `mu` `(B,64,5,8)` | +| `nav_policy.onnx` | `obs` `(B,2576)`, `h` `(1,B,512)`, `c` `(1,B,512)` | `actions` `(B,3)`, `h_new`, `c_new` | + +最终速度 = `tanh(actions) × policy_scale`,其中 `policy_scale = [0.6, 0.3, 0.6]` → `[vx, vy, ωz]`。 diff --git a/sru_ws/docs/PORT_NOTES_2026-09-28.md b/sru_ws/docs/PORT_NOTES_2026-09-28.md new file mode 100644 index 0000000..c726923 --- /dev/null +++ b/sru_ws/docs/PORT_NOTES_2026-09-28.md @@ -0,0 +1,204 @@ +# sru_nav_ros2 移植记录(本机:/home/xie/sru_nav_handover/sru_ws) + +> 按 `src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md` 执行。**未改动 `src/sru_nav_ros2/` 下任何一行代码或配置**, +> 只做了环境配置与验收。日期 2026-09-28。 + +--- + +## 1. 本机与文档假设的差异(先说清楚,后面所有命令都基于这个) + +| 项 | 文档假设 | 本机实际 | +|---|---|---| +| 工作区根 | `~/sru_ws` | **`/home/xie/sru_nav_handover/sru_ws`**(下文记作 `$WS`) | +| 系统 / 架构 | Ubuntu 22.04 / x86_64 | ✅ Ubuntu 22.04.5 LTS / x86_64,一致 | +| ROS 2 Humble | 需安装 | ✅ 已装 `/opt/ros/humble` | +| apt 依赖 7 项 | 需安装 | ✅ **全部已装**(desktop / cv-bridge / joy / tf2-ros / rviz2 / colcon / python3.10-venv) | +| Odin 驱动 | `~/catkin_ws` 已编译安装 | ⚠️ **不在 catkin_ws**,见 §5 | +| 当前 shell 用户 | 普通用户 | ⚠️ 本会话是 **root**;且 `/home/xie` 是 `drwxr-x--- root root`,普通用户 xie 目前**无法进入自己的家目录** | + +## 2. 本次实际做的事(改动清单) + +| # | 动作 | 位置 | +|---|---|---| +| 1 | 重建 venv(`--system-site-packages`) | `$WS/venv`(约 600 MB,未从开发机拷贝) | +| 2 | 装依赖 —— **见 §4 的两处本机适配** | `$WS/venv` 内 numpy 1.26.4 / onnxruntime 1.23.2 / scipy 1.11.4 | +| 3 | 往 activate 末尾追加两行 export | `$WS/venv/bin/activate`(`PYTHONNOUSERSITE=1` + 追加式 `PYTHONPATH`) | +| 4 | 补 `COLCON_IGNORE` | `$WS/reference/COLCON_IGNORE`(原本就有)、**新建** `$WS/venv/COLCON_IGNORE` | +| 5 | 构建 | `$WS/{build,install,log}` | +| 6 | 新建 pip 临时目录 | `/home/xie/.pip-tmp`(原因见 §4-A) | + +> 小副作用:`--upgrade pip` 时 pip 把被替换掉的旧 `pip` / `pip3` / `pip3.10` / `latest` 入口脚本 +> 挪到了工作区根的 `$WS/.Trash-0/`(当前的 `$WS/venv/bin/pip` 是好的、已验证可用)。 +> 对 colcon 无影响,可以留也可删。 + +**没有改**:`sru_nav_ros2/` 下任何 `.py` / `.yaml` / `launch` / `package.xml`;**没有动** `reference/`。 + +## 3. 验收原始输出(第三步四条) + +### ① `colcon list` — 只有一行,stderr 为空 ✅ +``` +sru_nav_ros2 src/sru_nav_ros2 (ros.ament_python) +``` + +### ② `colcon build --symlink-install` — 退出码 0 ✅ +``` +Starting >>> sru_nav_ros2 +Finished <<< sru_nav_ros2 [1.59s] +Summary: 1 package finished [2.00s] +BUILD_EXIT=0 +``` + +### ③ 依赖自检 ✅(一处偏差见 §4-B) +``` +PYTHONNOUSERSITE 1 +numpy 1.26.4 /home/xie/sru_nav_handover/sru_ws/venv/lib/python3.10/site-packages/numpy/__init__.py +cv2 4.5.5 /usr/local/lib/python3.10/dist-packages/cv2/__init__.py <-- 期望 4.5.4 @ /usr/lib/python3/dist-packages +scipy 1.11.4 /home/xie/sru_nav_handover/sru_ws/venv/lib/python3.10/site-packages/scipy/__init__.py +ort 1.23.2 ['AzureExecutionProvider', 'CPUExecutionProvider'] +CvBridge +``` + +### ④ launch 冒烟 ✅ +`ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false` +``` +[sru_nav_node-2] [INFO] [sru_nav_node]: VAE encoder: .../share/sru_nav_ros2/models/vae_encoder.onnx +[sru_nav_node-2] [INFO] [sru_nav_node]: Policy model: .../share/sru_nav_ros2/models/nav_policy.onnx +[sru_nav_node-2] [INFO] [sru_nav_node]: Navigation policy node is ready. +[sru_nav_node-2] [INFO] [sru_nav_node]: SRU navigation node spinning (odom_twist_in_base_frame=True, require_joystick=False). +``` +另:`ros2 pkg prefix sru_nav_ros2` → `$WS/install/sru_nav_ros2`;静态 TF 正常发布 +(`-0.268846, 0.028504, 0.067861` / 四元数 `0.008847,0.122404,-0.001091,0.992440`,`odin1_base_link`→`base_link`)。 + +## 4. 两处本机适配(与文档做法不同,但结论一致) + +### A. pip 的临时目录 /tmp 只有 10 MB +本机 `/tmp`、`/var`、`/dev/shm` 都是 **10 MB tmpfs**。第一次 `pip install onnxruntime`(wheel 17.4 MB) +直接 `OSError: [Errno 28] 设备上没有空间`。真机文件系统 `/` 有 632 GB 空闲。 +→ 做法:`export TMPDIR=/home/xie/.pip-tmp`(建在 `/` 上)后重跑,成功。 +**以后在本机跑 pip 都要加这一句**;`/tmp` 正常的终端可忽略。 + +### B. 两个"被误判为已满足"的包 —— 必须强制装 +`--system-site-packages` 的 venv 里,pip 会把系统路径中的包当成"已满足",于是: +- `numpy<2`:系统 `/usr/lib/python3/dist-packages/numpy` 是 **1.21.5**,且 `~/.local` 还有 1.26.4, + 两者都满足 `numpy<2` ⇒ pip 只回 `Requirement already satisfied`,**venv 里没有 numpy**。 + → 做法:`pip install --ignore-installed "numpy<2"`,强制装进 venv。 +- `scipy`:文档已预判,用精确版本号 `scipy==1.11.4` 解决(系统 scipy 1.8.0 被正确跳过、未卸载)。 + +另外:pip 装依赖时设了 `PYTHONNOUSERSITE=1`(排除 `~/.local`),否则依赖会落在用户级 site 而不是 venv。 + +### C. cv2 版本偏差(**唯一未达标项,未处理,等你决定**) +`sys.path` 里 `/usr/local/lib/python3.10/dist-packages` **排在** `/usr/lib/python3/dist-packages` **之前**, +而 `/usr/local/...` 下有一份**散装的 `cv2` 目录(4.5.5,无 dist-info,不是 pip 管理的)**, +它把 apt 的 4.5.4 顶掉了。 + +- apt 那份确实在:`/usr/lib/python3/dist-packages/cv2.cpython-310-x86_64-linux-gnu.so` = **4.5.4** +- 实测当前导入的是 4.5.5,`import cv2` 正常、`CvBridge()` 正常、launch 冒烟正常 +- ⚠️ **没动它**:`/home/xie/techx_R2_algorithm/` 下的 `light_signal_detector` 等节点也 `import cv2`, + 删/挪可能影响 Rc2026 那套。要不要对齐请你拍板。 + +## 5. Odin 驱动现状(不属于本包,但决定能不能真跑) + +本机有**三份**驱动源码树和**已编译**的安装: + +| 位置 | 状态 | +|---|---| +| `/home/xie/algorithm_test/odin_ws/src/odin_ros_driver` | 源码在,**未编译**(无 build/install) | +| `/home/xie/techx_R2_algorithm/r2_nav_ws2/src/odin_ros_driver` | 源码在,**已编译** → `r2_nav_ws2/install/odin_ros_driver` ✅ | +| `/home/xie/techx_R2_algorithm/r2_algorithm/src/odin_ros_driver` | 源码在,**已编译** → `r2_algorithm/install/odin_ros_driver` | + +`r2_nav_ws2` 已编译的四个可执行:`host_sdk_sample`、`pcd2depth_ros2_node`、`cloud_reprojection_ros2_node`、`image_overlay_node`。 + +**`algorithm_test/odin_ws` 那份 `config/control_command.yaml` 的实际取值**: +``` +senddtof: 1 ✅ sendrgb: 1 ✅ sendrgbcompressed: 1 +sendimu: 1 ✅ sendodom: 1 ✅ send_odom_baselink_tf: 1 ✅ +sendcloudslam: 1 sendcloudrender: 1 devstatuslog: 1 +senddepth: 0 ❌ ← 必须改成 1,否则永远没有深度、一条 /cmd_vel 都不发 +use_host_ros_time: 0 ⚠️ ← odom 用设备时钟,与 deadman 的 time.time() 不同基准 +``` + +⚠️ **关键提醒**:驱动读的是**编译期 `__FILE__` 反推出的源码树**里的配置。 +所以"该改哪一份"取决于**你实际启动的那个 install 是谁编译的**—— +启动 `r2_nav_ws2/install` 的驱动,就要改 `r2_nav_ws2/src/odin_ros_driver/config/control_command.yaml`。 +改完后必须**整体重启驱动**(这几个键是 `register_keys`,启动时下发给设备)。 + +## 6. 与文档描述不一致的地方 + +1. **"没有 Odin 数据源时每 5 s 刷 `Odometry not ready, skipping depth callback.`"——实测没有打印。** + 查源码(`navigation_policy_node.py:452-457`):这句在 `depth_callback()` **内部**,而 + `depth_callback` 只在**收到深度消息**时才被调用。完全没有数据源时一条深度都不来 ⇒ 这句话永不触发。 + 准确说法应是:**"有深度到达、但 odom 还没就绪"** 时才会每 5 s 刷。不是故障,属文档表述偏松。 +2. Ctrl-C 收尾时 `sru_nav_node` 打了一段 `KeyboardInterrupt` traceback(在 `destroy_node()` 里被信号打断)。 + 属**退出路径**的正常产物,与启动无关;不影响验收。 +3. `/tmp` 10 MB 的约束文档未提及(见 §4-A)。 + +## 7. 没确认的事项 + +- `cv2` 4.5.5 vs 要求的 4.5.4(§4-C)—— 未处理,等决定。 +- 驱动 `use_host_ros_time: 0` 导致的 deadman 时钟域问题(文档 §11 第 8 项)——真机开手柄前必须处理。 +- 装订外参 `base_link_*` 仍是从文档继承的 Rc2026 R2 实测值,**不是本机载体**。 +- 真机链路(深度到达 → 非零 `/cmd_vel`)本次**未验**,因为没有启动驱动(也无载体,安全默认不动)。 + +## 8. 下一步建议(对照 HANDOVER_TEAM §6.2 待测清单) + +1. 起驱动(用已编译的 `r2_nav_ws2/install`),先把**实际生效的那份** `control_command.yaml` 的 + `senddepth` 改 1,整体重启;再用 `dev_status.csv` 确认 `dtof_rx_odr` 等非 0。 +2. `ros2 topic hz /odin1/odometry_highfreq`、`/odin1/depth_img_competetion` 确认真实速率。 +3. 无载体先把链路跑通:`waypoint_runner --waypoints "3,0"`,看 `/cmd_vel` 是否非零有界 + (已知上限 `|vx|≤0.6`、`|vy|≤0.18`、`|ω|≤0.6`)。**务必先抬轮/架空。** +4. 上机前处理 deadman 时钟域(`use_host_ros_time` → 1 或 2)。 +5. 标定装订外参;再逐个试 `/joy` 轴/键索引。 +6. 密集路点必须 ≥ 3–5 m(`ARRIVE_GOAL_THRESHOLD=0.75`,间距 ≤0.75 m 一步都不走)。 + +--- + +## 9. 与目标的差异清单(逐条对照,2026-09-28 22:20 复核) + +### 9.1 对照「验收标准」(只差 1 项) + +| # | 标准 | 状态 | +|---|---|---| +| 1 | `colcon build --symlink-install` 退出码 0 | ✅ 达成 | +| 2 | `colcon list` 只有一行、stderr 为空 | ✅ 达成(实测 `sru_nav_ros2 src/sru_nav_ros2 (ros.ament_python)`) | +| 3 | 依赖自检 5 项 | ⚠️ **4/5 达成**。numpy 1.26.4✔(venv)、scipy 1.11.4✔(venv)、onnxruntime✔含 CPUExecutionProvider、CvBridge✔;**cv2 = 4.5.5 @ `/usr/local/lib/python3.10/dist-packages`,要求是 4.5.4 @ `/usr/lib/python3/dist-packages`** | +| 4 | launch 打印 ready 且 `odom_twist_in_base_frame=True` | ✅ 达成 | + +⇒ **验收层面只剩 cv2 版本这一处差异**(详见 §4-C,未处理,等拍板)。 + +### 9.2 对照「上机实测就绪」——未验证项(文档 §6.2 清单,全部仍待测) + +| # | 待测项 | 卡点 | +|---|---|---| +| 1 | 驱动把深度打开 | `senddepth: 0` 需改 1;**且要先确定哪份源码树生效**(编译期 `__FILE__`) | +| 2 | 深度/odom 真实速率 | 需起驱动后用 `dev_status.csv` + `ros2 topic hz` | +| 3 | 深度→非零 `/cmd_vel` 真机链路 | 需驱动 + 载体(本次未验,且未抬轮不动) | +| 4 | **deadman 时钟域** | `use_host_ros_time: 0` 未处理 ⇒ 开手柄可能"一上来就超时"或 deadman 失效 | +| 5 | 装订外参 `base_link_*` | 仍是 Rc2026 **R2 比赛车**实测值,不是本机载体 | +| 6 | `/goal_yaw` 朝向精度(±5°) | 从未在真机验证 | +| 7 | `/joy` 轴/键索引(17 个参数) | 沿用 PS5 映射,未在真手柄验 | +| 8 | odom twist 正负号手感 | 未验,判反会反向跑 | +| 9 | 驱动侧 ~1.5 Hz 速率问题 | `QoS(5)`→`QoS(50)`(驱动侧改动,须先报告) | +| 10 | `/cmd_vel` 桥 | 底盘侧桥是否存在、节点死后是否自动归零 —— **未确认,最易出事故的点** | + +⇒ 验收(静态)与上机(动态)之间差的是**物理世界**那一半,这一条与文档结论一致。 + +### 9.3 其它差异 + +- 本次会话是 root,且 `/home/xie` 为 `drwxr-x--- root root` ⇒ 普通用户 xie 目前进不了自己家目录。 +- 文档"无数据源时每 5 s 刷 `Odometry not ready...`"的表述不准确(见 §6 第 1 条)。 + +--- + +## 附:速查(本机路径版) + +```bash +WS=/home/xie/sru_nav_handover/sru_ws +source /opt/ros/humble/setup.bash && source $WS/venv/bin/activate +source $WS/install/setup.bash # --symlink-install:改代码/配置免重建,重启进程即可 + +ros2 launch sru_nav_ros2 sru_nav.launch.py # 正常(deadman 生效) +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false # 冒烟,先抬轮 + +ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" +ros2 topic hz /cmd_vel +``` diff --git a/sru_ws/docs/README.md b/sru_ws/docs/README.md new file mode 100644 index 0000000..34db579 --- /dev/null +++ b/sru_ws/docs/README.md @@ -0,0 +1,36 @@ +# sru_ws 文档索引 + +工作区根:`/home/xie/sru_nav_handover/sru_ws`(下文记作 `$WS`)。 + +## 想看什么,点哪里 + +| 想解决的问题 | 文档 | +|---|---| +| **怎么把这个工程跑起来** —— source 哪三行、三个终端怎么开、怎么发目标、上机前安全检查 | **[`USAGE.md`](USAGE.md)** ← 从这里开始 | +| 原理、数据流、全部参数、约 20 条排错速查(权威,约 1000 行) | [`../src/sru_nav_ros2/docs/DEPLOY_ROS2.md`](../src/sru_nav_ros2/docs/DEPLOY_ROS2.md) | +| 怎么把工程交付/迁移给队友或新机器(打包清单、venv 为何不能拷) | [`../src/sru_nav_ros2/docs/HANDOVER_TEAM.md`](../src/sru_nav_ros2/docs/HANDOVER_TEAM.md) | +| 本机(xie 的 Ubuntu 22.04)环境适配与验收记录 | [`PORT_NOTES_2026-09-28.md`](PORT_NOTES_2026-09-28.md) | +| 当初交给 AI 执行的移植提示词存档 | [`../src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md`](../src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md) | +| Odin1 驱动(上游)中文说明 52 KB | [`../src/odin_ros_driver/README.md`](../src/odin_ros_driver/README.md) | +| 驱动运行期服务操作 | [`../src/odin_ros_driver/docs/runtime_service_operations.md`](../src/odin_ros_driver/docs/runtime_service_operations.md) | +| 驱动重定位(relocalization)指南 | [`../src/odin_ros_driver/RELOCALIZATION_GUIDE.md`](../src/odin_ros_driver/RELOCALIZATION_GUIDE.md) | +| ROS 1 → ROS 2 移植方案与 API 对照表(**历史件,两处结论已被实测推翻**,以 `DEPLOY_ROS2.md` 为准) | [`HANDOVER.md`](HANDOVER.md)、[`ROS2_PORT_PLAN.md`](ROS2_PORT_PLAN.md) | +| 上游 ROS 1 蓝本自带的移植指南(中/英)与 Go2 NX 部署 | [`../reference/SRU-Odin/Deployment/docs/`](../reference/SRU-Odin/Deployment/docs/) | +| **学习笔记 / 飞书知识库素材**(含排版规范与模板) | [`../notes/`](../notes/) | + +## 文档都放在哪(本工作区的约定) + +| 位置 | 内容 | 能不能改 | +|---|---|---| +| `docs/` | **工作区级文档**(本目录):使用手册、移植记录、历史交接件、`assets/` 素材 | ✅ | +| `src/sru_nav_ros2/docs/` | 交付包自带文档。**会被 `setup.py` 安装到 `share/sru_nav_ros2/docs/`**,属包载荷 | ✅ 按需 | +| `src/odin_ros_driver/docs/` | 驱动上游文档 | ⚠️ 尽量只读 | +| `reference/SRU-Odin/` | 上游只读快照(ROS 1 蓝图 `Deployment/` + 训练侧 `Train/`) | ❌ **禁止修改**,只做 diff 对照 | +| `build/`、`install/` | colcon 构建产物 | ❌ 不要手改 | + +> `docs/` 与 `src/*/docs/` 的分工:前者是给人看的工作区文档,后者是随包发布的载荷。 +> 两处内容如有出入,以 `src/sru_nav_ros2/docs/DEPLOY_ROS2.md` 为准。 + +## 素材 + +- `assets/cam_in_ex.txt` —— Odin1 相机内参/外参摘录(`Tcl_0` 外参 + `cam_0` 内参)。 diff --git a/sru_ws/docs/ROS2_PORT_PLAN.md b/sru_ws/docs/ROS2_PORT_PLAN.md new file mode 100644 index 0000000..7b90727 --- /dev/null +++ b/sru_ws/docs/ROS2_PORT_PLAN.md @@ -0,0 +1,298 @@ +# SRU-Odin 从 ROS1 迁移到 ROS 2 Humble —— 方案与迁移清单 + +> 针对本地仓库 `F:\RC2027\odin1_SRU\SRU-Odin-orig\SRU-Odin`(`ManifoldTechLtd/SRU-Odin`) +> 本轮为**方案与迁移清单**,不含代码实现。 + +--- + +## 0. 已确认前提 + +| 项 | 确认结果 | 影响 | +|---|---|---| +| 目标发行版 | ROS 2 **Humble**(Ubuntu 22.04) | package.xml format=3、ament_python、`colcon build`、Humble 版 QoS API | +| 目标机器人 | 任意订阅 `/cmd_vel` 的平台 | 本包不绑定机型,另给桥接模板;`policy_scale` 保持保守默认 | +| 推理后端 | ONNX Runtime 双模型 | 复用仓库现成 `vae_encoder.onnx` + `nav_policy.onnx`,不引入 PyTorch | +| 本轮交付 | 方案 + 迁移清单 | 代码待你确认后再写 | + +--- + +## 1. 结论:走「反向移植」,不要走「官方 ROS2 仓库改话题」 + +你有两条路,我建议第一条。 + +| 维度 | 路线 A:反向移植本仓库(**推荐**) | 路线 B:拿官方 ROS2 源码改话题 | +|---|---|---| +| 起点 | `Deployment/`(ROS1,但传感器/模型/参数已全部按 Odin1 调好) | `leggedrobotics/sru-robot-deployment`(ROS2 Jazzy) | +| 要动的传感器 | 无,话题已是 `/odin1/*` | ZED-X → Odin1,含深度预处理口径对齐 | +| 要动的里程计 | 无,已是 `/odin1/odometry_highfreq` | DLIO → Odin1,含 twist 坐标系判定 | +| 要动的推理 | 无,已是 ONNX 双模型 | PyTorch JIT + `~/ros2_torch` venv → ONNX(或保留重依赖) | +| 要动的输出接口 | 无,已是 `/cmd_vel` | `/path_manager/path_manager_ros/nav_vel` → `/cmd_vel`,且要剥离 B2W 专用 C++ 底层 `b2w_controllers` | +| 要动的 ROS 版本 | ROS1 API → ROS2 API(机械改写) | 无 | +| 主要风险 | ROS1/ROS2 API 语义差异(可控、可查) | 平台耦合 + 依赖重,改动面大且互相牵连 | + +**路线 A 的额外依据**:本仓库 `navigation_policy_node.py` 文件头自己写着 + +> *"Direct port of the original ROS2 NavigationPolicyNode. Behaviour is preserved; only ROS API calls, time helpers, and topic defaults have been changed."* + +也就是说,**这个 ROS1 包本来就是从 ROS2 机械改写来的**,反向改写回去等于撤销一次已知的机械变换,路径最短、语义最清楚。而路线 B 的官方仓库是 ROS 2 **Jazzy** + Gazebo Harmonic,与 Odin1 驱动官方推荐的 Humble 也不同版本。 + +--- + +## 2. 事实核查(本次实际读盘 + 联网确认) + +### 2.1 本地仓库实测 + +- 克隆产物路径:`F:\RC2027\odin1_SRU\SRU-Odin-orig\SRU-Odin\` +- `Deployment/` 是 ROS1 catkin 包,包名 `sru_nav_go2_ros1`,构建文件为 `CMakeLists.txt` + `catkin_python_setup()` +- **模型真实可用,不是 LFS 指针**: + - `Deployment/models/nav_policy.onnx` — 7,054,074 字节 + - `Deployment/models/vae_encoder.onnx` — 20,971,407 字节 +- 代码行数(`wc -l` 实测):合计 **1942 行**(Python + 入口脚本) + +### 2.2 官方 ROS2 源仓库(`leggedrobotics/sru-robot-deployment`) + +| 项 | 实际值 | +|---|---| +| ROS 版本 | **Jazzy** | +| 仿真 | Gazebo Harmonic | +| 高层包 | `rl_nav_controller/`,`rl_nav_controller.py` 916 行 | +| 推理 | PyTorch CUDA 版,隔离在 `~/ros2_torch` venv | +| 深度 | ZED-X:`/zed/zed_node/depth/depth_registered` | +| 里程计 | DLIO | +| 速度输出 | `/path_manager/path_manager_ros/nav_vel`(**不是** `/cmd_vel`) | +| 底层 | C++ `b2w_controllers`(自带 ONNX locomotion policy) | + +### 2.3 Odin1 驱动的 ROS2 支持情况 + +- 官方驱动 `manifoldsdk/odin_ros_driver` **单代码库同时支持 ROS1/ROS2**(源码里用 `#ifdef ROS2` 条件编译),不是两套代码。 +- ROS2 构建:`./script/build_ros2.sh` +- ROS2 启动:`ros2 launch odin_ros_driver odin1_ros2.launch.py` +- 官方推荐 ROS2 LTS = **Humble**,OS = **Ubuntu 22.04** → 与你的选择完全一致 ✅ +- 驱动内已含 `depth_image_ros2_node`、`pcd2depth_ros2` 等 ROS2 节点。 + +> ⚠️ **必须实测的风险点**:驱动主线文档列出的话题是 +> `/odin1/odometry`、`/odin1/odometry_highfreq`、`/odin1/cloud_slam`、`/odin1/imu`、`/odin1/image`, +> **没有** `/odin1/depth_img_competetion`。 +> 该话题名来自本仓库,对应驱动 `config/control_command.yaml` 里 `senddepth: 1` 开启的 dense depth, +> 只有部分版本/分支有。**上机第一步必须用 `ros2 topic list` 确认真实深度话题名**,不能照抄。 + +--- + +## 3. 迁移面:1942 行里只有 1120 行需要改写 + +### 3.1 A 类 · 零改动(508 行,26%) + +| 文件 | 行数 | 为什么不用改 | +|---|---|---| +| `src/sru_nav_go2/constants.py` | 80 | 纯数值常量,无任何 ROS import | +| `src/sru_nav_go2/model.py` | 176 | 只依赖 `cv2` / `numpy` / `onnxruntime`,**不含一行 ROS 调用** | +| `src/sru_nav_go2/utils.py` | 252 | 纯 NumPy 四元数/变换数学 | + +→ 唯一改动:`from sru_nav_go2 import constants` 里的包名(若新包名不同)。 + +### 3.2 B 类 · 轻改(314 行,16%) + +| 文件 | 行数 | 改动点 | 改动量 | +|---|---|---|---| +| `waypoint_manager.py` | 157 | 删掉 `RospyLogger` 包装类(L10–28),直接把 `node.get_logger()` 传进去即可(rclpy logger 已有 `info/warn/warning/error`) | 删 ~18 行 | +| `visualization.py` | 157 | ① 删 `import rospy`;② `_stamp_from_sec()`(L13–15)改为注入的 node clock;③ `rospy.Time.now()`(L141)→ `self.node.get_clock().now().to_msg()`;④ `__init__` 里被注释为"retained for API parity, not used in ROS1"的 `node` 参数**在 ROS2 下真正派上用场** | 改 ~8 行 | + +### 3.3 C 类 · 按 ROS2 API 重写(1120 行,58%) + +| 文件 | 行数 | 重写要点 | +|---|---|---| +| `src/sru_nav_go2/navigation_policy_node.py` | 682 | 普通类 → `rclpy.node.Node` 子类;Publisher/Subscriber/Timer/参数/日志/时间戳全部换 API;回调组与 QoS 需明确 | +| `scripts/sru_nav_node` | 107 | 从独立可执行脚本 → `setup.py` 的 `console_scripts` 入口;`rospkg` → `ament_index_python` | +| `scripts/waypoint_runner.py` | 331 | `rospy.Publisher(latch=True)` → QoS `TRANSIENT_LOCAL`;`rospy.Rate` → 节点时钟 sleep;`rospy.myargv()` → `sys.argv` | +| `launch/*.launch` | 55 | XML + `rosparam` → `launch.py` + `parameters=[yaml]` | +| `CMakeLists.txt` / `package.xml` / `setup.py` | 47+29+11 | catkin → ament_python,全部换掉 | + +--- + +## 4. ROS1 → ROS2 API 逐点对照表 + +| 位置(ROS1 文件:行) | ROS1 写法 | ROS2 Humble 写法 | +|---|---|---| +| 节点 L38–41 | `rospy.init_node()` + `object` | `class NavigationPolicyNode(Node)` + `super().__init__('sru_nav_node')` | +| 参数 L52–56 | `rospy.get_param('~x', dft)` | `self.declare_parameter('x', dft)` + `self.get_parameter('x').value` | +| 发布者 L67–70 | `rospy.Publisher(t, Type, queue_size=10)` | `self.create_publisher(Type, t, 10)` | +| 私有话题 L68 | `'~base_vel'` | `'~/base_vel'`(节点名保持 `sru_nav_node` → 展开结果一致,rviz 配置可复用) | +| 可视化发布者 L73–80 | `rospy.Publisher('~vis/...', Marker, 10)` | `self.create_publisher(Marker, '~/vis/...', 10)` | +| 订阅者 L136–143 | `rospy.Subscriber(t, Type, cb, queue_size=N)` | `self.create_subscription(Type, t, cb, N)` | +| 定时器 L146–152 | `rospy.Timer(rospy.Duration(x), cb)` | `self.create_timer(x, cb)` | +| 时间戳解析 L30–32 | `stamp.secs + stamp.nsecs*1e-9` | `stamp.sec + stamp.nanosec*1e-9` | +| 取时间 L521 | `rospy.Time.from_sec(t)` | `rclpy.time.Time(seconds=t).to_msg()` | +| 节流日志 L216–217, L248, L284 | `rospy.loginfo_throttle(1.0, msg)` | `self.get_logger().info(msg, throttle_duration_sec=1.0)` | +| 主循环 L103 | `rospy.spin()` | `rclpy.spin(node)` + `try/finally` 收尾 | +| 图像转换 L221 | `CvBridge().imgmsg_to_cv2(msg,'passthrough')` | **接口不变**,仅需 `ros-humble-cv-bridge` | +| 找包路径 L23–25 | `rospkg.RosPack().get_path('pkg')` | `ament_index_python.packages.get_package_share_directory('pkg')` | +| 命令行 L305 | `rospy.myargv()[1:]` | `sys.argv[1:]`(注意 launch 会注入 `--ros-args`,需过滤) | +| 锁存发布 L133–134 | `queue_size=1, latch=True` | `QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL)` | +| 构建 | `catkin_make` | `colcon build --symlink-install` | +| 包定义 | `format="2"` + `catkin` | `format="3"` + `ament_python` | +| launch | `sru_nav_go2.launch` + `` | `sru_nav.launch.py` + `parameters=[os.path.join(share,'config','sru_nav.yaml')]` | +| 静态 TF | `tf2_ros static_transform_publisher x y z yaw pitch roll frame child` | 同节点同用法(8 位置参数形式两边都支持),建议改写成 `launch_ros.actions.Node(arguments=[...])` 并换成实测装订值 | +| 手柄 | `rosrun joy joy_node` | `ros2 run joy joy_node`(参数名 `autorepeat_rate` / `deadzone` 一致) | + +--- + +## 5. ROS2 专属陷阱(ROS1 里不存在,必须提前防) + +按危险程度排序: + +1. **QoS 不匹配 → 静默收不到数据**。这是 ROS2 最经典的坑,ROS1 完全没有。 + Odin 驱动若用 `rclcpp::SensorDataQoS()`(BEST_EFFORT)发布深度,而订阅端用默认 RELIABLE,**订阅直接连不上,且不一定报错**。 + 对策:深度订阅用 `qos_profile_sensor_data`(BEST_EFFORT,与两种发布端都兼容);上机用 `ros2 topic info -v /odin1/...` 看真实 QoS 再定。 + +2. **`use_sim` 参数名与 ROS2 内置 `use_sim_time` 极易混淆**。 + 本仓库 `use_sim` 的真实语义是"odom twist 已经是 body 系,直接透传"。ROS2 里 `use_sim_time` 是仿真时钟开关,两者含义完全不同。 + 对策:**改名为 `odom_twist_in_base_frame`**,并在 YAML 里写清注释。 + +3. **时间戳字段名 `secs/nsecs` → `sec/nanosec`**。漏改会 `AttributeError` 或时间戳恒为 0。 + 控制频率门控(`robot_odom_time - last_run_time < interval`)依赖这个值,改错会导致门控失效、推理频率失控。 + +4. **回调线程模型变化**。 + ROS1 下 `rospy.Timer` 回调在独立线程,而 `generate_cmd_vel()` 是**在 depth 回调里执行**的重活(含 ONNX 推理)。 + ROS2 默认 `rclpy.spin()` 是单线程 executor,所有回调串行 → **行为与 ROS1 等效,照搬即可**。 + 若为了提频改成 `MultiThreadedExecutor`,必须给各回调加 `MutuallyExclusiveCallbackGroup`,否则 LSTM 隐状态 `(h,c)` 会竞态,产生乱码速度指令。 + +5. **参数类型严格**。ROS2 参数声明后类型固定,`policy_scale` 必须声明为 double array。 + YAML 里若写 `policy_scale: [1, 1, 1]`(整数)会被拒,必须写 `[1.0, 1.0, 1.0]`。 + +6. **`/joy` 轴映射需实测**。Humble 的 `joy` 包默认轴映射与 ROS1 未必一致,`constants.py` 里的 PS5 轴/键索引(`JOYSTICK_AXIS_SMART = 5` 等)上机前要用 `ros2 topic echo /joy` 复核。 + +7. **cv_bridge 与 OpenCV 版本冲突**。Humble 的 `cv_bridge` 依赖系统 `python3-opencv`; + 若再用 pip 装 `opencv-python`,可能出现 `libopencv` 双版本冲突(症状是 cv_bridge 导入时报符号错误)。 + 对策:ROS2 侧只用 apt 的 `ros-humble-cv-bridge` + 系统 opencv,**只 pip 装 `onnxruntime`**。 + +### 顺带一个好消息:ROS1 侧三大部署痛点会消失 + +ROS1 README §9 里 5 条常见坑,有 3 条在 ROS2 下**根本不存在**,因为不再需要 conda 与系统 ROS 共生的 hack: + +| ROS1 坑 | ROS2 下 | +|---|---| +| conda `libffi` 与系统 `libp11-kit` ABI 冲突(`ffi_type_pointer` 未定义符号)→ `LD_PRELOAD` 硬修 | **消失**:不再需要 conda 与系统 ROS 混用 | +| `PYTHONPATH` 手工注入 `/opt/ros/noetic/lib/python3/dist-packages` | **消失**:Humble 原生 python3.10 直接可用 | +| `catkin_make -DPYTHON_EXECUTABLE=$(which python)` 锁 shebang,否则 import onnxruntime 失败 | **消失**:`colcon` + 系统解释器,无 shebang 陷阱 | +| `netifaces` / `defusedxml` 隐性依赖缺失 | **消失**:ROS2 不再依赖 netifaces | +| `zsh` 下 `setup.zsh: cd: -q` 报错 | 仍可能遇到,但 launch.py 不涉及 | + +剩下要保留的只有一条:**Jetson 无 RTC 电池导致系统时钟回退、pip TLS 握手失败** → 上机前 `date` 校验 + `ntpdate`。 + +--- + +## 6. 目标包结构 + +建议**新建独立包**(不改原 ROS1 包,方便 diff 对照): + +``` +F:\RC2027\odin1_SRU\ +└── src/ + └── sru_nav_ros2/ # ament_python 包 + ├── package.xml # format=3, ament_python + ├── setup.py # 入口: sru_nav_node / waypoint_runner + ├── setup.cfg + ├── resource/sru_nav_ros2 + ├── sru_nav_ros2/ + │ ├── __init__.py + │ ├── constants.py # A 类:原样拷贝 + │ ├── model.py # A 类:原样拷贝 + │ ├── utils.py # A 类:原样拷贝 + │ ├── waypoint_manager.py # B 类:删 RospyLogger + │ ├── visualization.py # B 类:注入 node clock + │ ├── navigation_policy_node.py # C 类:rclpy 重写 + │ ├── sru_nav_node.py # C 类:main() 入口 + │ └── waypoint_runner.py # C 类:rclpy 重写 + ├── launch/ + │ └── sru_nav.launch.py # joy + static TF + 导航节点 + ├── config/ + │ ├── sru_nav.yaml # 参数(含改名后的 odom_twist_in_base_frame) + │ └── waypoints_example.yaml # 原样拷贝 + ├── models/ + │ ├── vae_encoder.onnx # 20,971,407 B,从 Deployment/models 拷贝 + │ └── nav_policy.onnx # 7,054,074 B + └── docs/ + └── DEPLOY_ROS2.md +``` + +### 与 ROS1 包的命名对应 + +| ROS1 | ROS2 | 说明 | +|---|---|---| +| 包名 `sru_nav_go2_ros1` | `sru_nav_ros2` | 去掉机型与 ROS 版本后缀,因为本包已机型无关 | +| 节点名 `sru_nav_node` | `sru_nav_node` | **保持不变**,私有话题展开结果一致 | +| `config/sru_nav.yaml` | `config/sru_nav.yaml` | 字段基本照搬,仅 `use_sim` 改名 | +| `scripts/sru_nav_node` | `sru_nav_ros2.sru_nav_node:main` | console_scripts 入口 | + +--- + +## 7. 分步实施清单(每步带可 grep 的验收点) + +| 步骤 | 动作 | 验收 | +|---|---|---| +| **1. 环境底座** | Ubuntu 22.04 + `ros-humble-desktop` + `ros-humble-cv-bridge` + `ros-humble-joy` + `ros-humble-tf2-ros`;`pip3 install --user onnxruntime numpy scipy pyyaml`(若遇 `externally-managed-environment`,改用 `python3 -m venv --system-site-packages`) | `python3 -c "import rclpy, cv_bridge, onnxruntime; print('ok')"` 无报错 | +| **2. 建包骨架** | 建 §6 目录;写 `package.xml`(format=3) / `setup.py` / `setup.cfg` / `resource/`;`data_files` 把 `config/` `launch/` `models/` 装到 `share/` | `colcon build --symlink-install` 退出码 0;`ros2 pkg prefix sru_nav_ros2` 有输出 | +| **3. 搬 A 类+B 类** | 拷贝 `constants.py` / `model.py` / `utils.py` / `waypoint_manager.py` / `visualization.py`,改包名 import、删 `RospyLogger`、注入 node clock | `grep -rn "import rospy\|rospy\." sru_nav_ros2/` **零命中** | +| **4. 重写节点** | `navigation_policy_node.py` 按 §4 对照表全部改 rclpy;明确 QoS 与单线程 executor;`use_sim` → `odom_twist_in_base_frame` | `grep -n "create_publisher\|create_subscription\|create_timer\|declare_parameter"` 全部命中;`grep -c "rospy"` = 0 | +| **5. 入口与 launch** | `sru_nav_node.py` 用 `ament_index_python` 定位 `share/sru_nav_ros2/models`;`sru_nav.launch.py` 做 joy + static TF + 参数注入 | `ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false` 打印 `Navigation policy node is ready.` 且不刷错 | +| **6. 移植 waypoint_runner + 文档** | `waypoint_runner.py` 改 rclpy(latch → TRANSIENT_LOCAL QoS);写 `docs/DEPLOY_ROS2.md` | `ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0 3,2"` 能发目标 | + +### 上机验收命令(替换掉 ROS1 的 `rostopic` 一族) + +```bash +ros2 topic list | grep odin1 # ① 确认深度话题真实名字(关键) +ros2 topic info -v /odin1/depth_img_competetion # ② 看 QoS:RELIABLE 还是 BEST_EFFORT +ros2 topic hz /odin1/depth_img_competetion # ③ 应 ~10 Hz +ros2 topic hz /odin1/odometry_highfreq # ④ 应 ~300–400 Hz +ros2 topic echo /odin1/odometry_highfreq --once # ⑤ 看 frame_id / child_frame_id +ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" # ⑥ 发目标 +ros2 topic hz /cmd_vel # ⑦ 应稳定 ~5 Hz +``` + +--- + +## 8. `/cmd_vel` 桥(你的机型无关选择) + +本包只发布 `geometry_msgs/msg/Twist`,不绑定任何机型。桥由你选: + +| 平台 | 桥方案 | +|---|---| +| Unitree Go2 / B2 / B2W | `unitree_ros2` 官方包,或自写 50 行 sport_mode 桥(订阅 `/cmd_vel`) | +| 其他腿足/轮式 | 厂商 SDK 自写订阅节点 | +| 纯 ROS2 仿真 | 直接订阅 `/cmd_vel`,无需桥 | + +安全默认值保持不变,**首次上机务必先抬轮/架空**: + +```yaml +policy_scale: [0.6, 0.3, 0.6] # 训练值本是 [1.5, 1.0, 1.0],此处保守一半以上;确认安全后逐步升 +require_joystick: true # 必须接手柄、推油门 axes[4] 才有速度;首测可用 false 旁路 +``` + +--- + +## 9. 需要你实测/确认的未决项 + +| # | 项 | 为什么必须实测 | 不确认的后果 | +|---|---|---|---| +| 1 | Odin1 深度话题的真实名字 | 本仓库写 `/odin1/depth_img_competetion`,但驱动主线文档无此话题 | 节点收不到深度,`/cmd_vel` 恒为 0 | +| 2 | Odin1 深度/里程计的 QoS | ROS2 特有,驱动端用 RELIABLE 还是 BEST_EFFORT 未知 | 订阅静默失败(不报错) | +| 3 | odom 的 twist 是 world 还是 body 系 | 决定 `odom_twist_in_base_frame` 取 true/false | 速度指令剧烈震荡或方向错乱 | +| 4 | odom 的 `header.frame_id` | `/goal_pose` 的 frame_id 必须与之一致,否则目标被直接拒绝 | 发目标无反应 | +| 5 | Odin1 实际装订位置(xyz / rpy) | launch 里静态 TF 默认值来自 Go2 假设(x=0.25, z=0.18, pitch=0.349) | 深度图姿态与训练分布偏差,避障行为异常 | +| 6 | `/joy` 轴与键索引 | Humble joy 包映射可能与 ROS1 不同,`constants.py` 的 PS5 索引需复核 | 手柄控制错位、deadman 推不动 | +| 7 | 推理是否跟得上 5 Hz | 目标平台算力未知(模型合计 28 MB,CPU EP 一般够) | 控制频率掉到 5 Hz 以下,行为退化 | + +--- + +## 10. 本轮不做的事(待你确认后再进行) + +- 不写任何 ROS2 代码(本轮只要方案与清单) +- 不改动 `SRU-Odin-orig` 下的任何原文件 +- 不新增 ROS2 包目录(§6 结构为规划,尚未落盘) +- 不涉及训练侧(`Train/` 为 Isaac Sim 4.5 Docker,与本次部署迁移无关) + +--- + +## 附:一句话总结 + +这个仓库的 ROS1 包是**从 ROS2 机械改写来的**,其中 508 行(模型推理、数学工具、常量)与 ROS 完全无关、可直接复用,314 行只需删包装类与注入时钟,真正要重写的是 **682 行的主节点 + 三个入口/launch/构建文件**;Odin1 驱动本身自带 ROS2 分支且官方推荐 Humble,所以整件事的难点不在功能,而在 **QoS 对齐、时间戳字段、`use_sim` 改名、以及深度话题名要实测**这四件事上。 diff --git a/sru_ws/docs/USAGE.md b/sru_ws/docs/USAGE.md new file mode 100644 index 0000000..75d1963 --- /dev/null +++ b/sru_ws/docs/USAGE.md @@ -0,0 +1,470 @@ +# sru_ws 使用流程 —— SRU-Odin 无图端到端导航(ROS 2 Humble) + +> **本文件定位**:「怎么用」的操作手册,位于工作区文档目录 `docs/`。 +> 原理与细节在 `src/sru_nav_ros2/docs/DEPLOY_ROS2.md`(权威,约 1000 行); +> 交付/迁移流程在 `src/sru_nav_ros2/docs/HANDOVER_TEAM.md`;本机移植记录在 `docs/PORT_NOTES_2026-09-28.md`。 +> +> 核实日期:2026-09-30。路径以本机为准:`WS=/home/xie/sru_nav_handover/sru_ws`; +> 下文所有相对路径均相对 `$WS`。 + +--- + +## 0. 30 秒速查 + +```bash +export WS=/home/xie/sru_nav_handover/sru_ws +source /opt/ros/humble/setup.bash && source $WS/venv/bin/activate && source $WS/install/setup.bash + +# 终端 A:驱动(含深度节点、rviz2) +ros2 launch odin_ros_driver odin1_ros2.launch.py + +# 终端 B:控制器 +ros2 launch sru_nav_ros2 sru_nav.launch.py # 正常(手柄 deadman 生效) +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false # 冒烟(先抬轮!) + +# 终端 C:发目标 + 看输出 +ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" +ros2 topic echo /cmd_vel +``` + +**三句话记住这个工程**: + +1. 它是**端到端反应式策略**:`深度图 + 16 维状态 → ONNX → /cmd_vel`。没有地图、没有 SLAM、**没有规划路径**。 +2. **没有深度就一条 `/cmd_vel` 都不发** —— 且连 `cmd_vel_ratio:` / `Published cmd_vel:` 日志都不会出现。 +3. **到达只看 XY 距离(0.75 m)**,朝向要单独用 `/goal_yaw` 指定。 + +--- + +## 1. 数据流 + +``` +/odin1/depth_img_competetion ─┐ +/odin1/odometry_highfreq ├─► sru_nav_node ─► /cmd_vel ─► [你的底盘桥,自备] +/joy(deadman + 手动叠加) ┘ (ONNX Rt) + ▲ + └─ /goal_pose(位置) + /goal_yaw(朝向) +``` + +| 事实 | 说明 | +|---|---| +| 三个速度**同时**输出 | 动作空间是 SE2 `[vx, vy, ω]`,不是"先转好再走" | +| **机型无关** | 本包只发 `geometry_msgs/Twist` 到 `/cmd_vel`,桥自己写 | +| 推理只由 `depth_callback` 触发 | 深度不到 ⇒ 无 `/cmd_vel`,这是**特征签名**,别去查本包代码 | +| 节点名固定 `sru_nav_node` | 私有话题 `/sru_nav_node/vis/*` 与 ROS 1 蓝本一致,rviz 配置可复用 | +| 控制频率 5 Hz 是**上限** | 输入只来 ~1.5 Hz 时会如实地慢跑,逻辑不跑偏 | + +--- + +## 2. 目录与职责 + +| 路径 | 职责 | 能不能改 | +|---|---|---| +| `src/sru_nav_ros2/` | 交付包本体(含 2 个 ONNX,27 MB) | ✅ 按需 | +| `src/sru_nav_ros2/config/sru_nav.yaml` | **唯一调参入口**(39 个参数) | ✅ | +| `src/odin_ros_driver/` | Odin1 驱动源码(**编译期源码树**,配置由此处生效) | ⚠️ 见 §4.1 | +| `docs/` | **工作区文档统一目录** —— `README.md`(索引,先看这个)、本文件、`PORT_NOTES_2026-09-28.md`、`HANDOVER.md`、`ROS2_PORT_PLAN.md`、`assets/` | ✅ | +| `reference/` | 只剩 `COLCON_IGNORE` + `SRU-Odin/`(ROS 1 只读蓝本,`Deployment/models/*.onnx` 已删,与 `src/sru_nav_ros2/models/` 逐字节相同) | ❌ **禁止修改**(只做 diff 对照) | +| `venv/` | Python 隔离环境(numpy 1.26.4 / onnxruntime / scipy 1.11.4) | ❌ 不要动内部 | +| `install/`、`build/` | 构建产物(`install/` 是 source 对象) | ❌ 不要手改 | +| `src/*/docs/` | 包内文档(随包安装到 `share/`,属包载荷) | ✅ 按需 | + +> `log/`(colcon 构建日志)与 `src/odin_ros_driver/{log,map}/`(驱动运行期产物) +> 已按需清理:前者可随时由 `colcon build` 重建,后者驱动启动时会自动 `create_directories`。 + +--- + +## 3. 环境(本机已就绪) + +### 3.1 每次使用前必须 source 这三行(顺序无所谓,但三行都要) + +```bash +export WS=/home/xie/sru_nav_handover/sru_ws +source /opt/ros/humble/setup.bash +source $WS/venv/bin/activate +source $WS/install/setup.bash +``` + +`venv/bin/activate` 末尾有两行**不可删**(已在位): + +```bash +export PYTHONNOUSERSITE=1 +export PYTHONPATH="$WS/venv/lib/python3.10/site-packages${PYTHONPATH:+:$PYTHONPATH}" +``` + +- `PYTHONNOUSERSITE=1`:挡住 `~/.local` 里 pip 版的 numpy/opencv 顶掉系统版本(否则 `import cv2` 段错误)。 +- `PYTHONPATH` 必须**追加式**(`${PYTHONPATH:+:$PYTHONPATH}`):覆盖式会冲掉 ROS 路径 → + 立刻变成 `No module named 'cv_bridge'`。ROS 工具链 shebang 硬编码 `#!/usr/bin/python3`,靠这行才看得见 venv 里的 onnxruntime。 + +### 3.2 自检(30 秒) + +```bash +cd $WS && colcon list # 期望两行:odin_ros_driver / sru_nav_ros2,stderr 为空 +python - <<'PY' +import os, cv2, numpy, scipy, onnxruntime +from cv_bridge import CvBridge +print("NOUSERSITE", os.environ.get("PYTHONNOUSERSITE")) # 期望 1 +print("numpy ", numpy.__version__, numpy.__file__) # 期望 1.26.x @ venv +print("cv2 ", cv2.__version__, cv2.__file__) # 注意:本机是 4.5.5 @ /usr/local/...(见 §10) +print("scipy ", scipy.__version__) # 期望 1.11.4 @ venv +print("ort ", onnxruntime.__version__, onnxruntime.get_available_providers()) +print("CvBridge", CvBridge()) +PY +``` + +### 3.3 本机环境约束(会咬人的三条) + +| 约束 | 处理 | +|---|---| +| `/tmp`、`/var`、`/dev/shm` 只有 **10 MB** | 任何 pip 操作前先 `export TMPDIR=/home/xie/.pip-tmp` | +| `reference/COLCON_IGNORE` 与 `venv/COLCON_IGNORE` **必需** | 缺了 `colcon build` 会去爬 `reference/` 的 catkin 包和 site-packages,直接炸;两者已在位 | +| venv **不能拷贝迁移** | 里面全是绝对路径;换机器要在新机器重建(见 HANDOVER_TEAM §2.3) | + +--- + +## 4. 标准使用流程(3 个终端) + +### 4.1 终端 A —— 启动 Odin1 驱动 + +```bash +source /opt/ros/humble/setup.bash +source $WS/install/setup.bash +ros2 launch odin_ros_driver odin1_ros2.launch.py +``` + +一次会拉起:`host_sdk_sample`(主驱动)+ `pcd2depth_ros2_node`(深度)+ 重投影 + overlay + **rviz2**。 + +| 要点 | 说明 | +|---|---| +| **USB 独占** | 绝不能同时跑两个 `host_sdk_sample`;重启前先 Ctrl-C 掉旧的 | +| **启动顺序** | 深度节点会**等** `calib.yaml`(`$HOME/.ros/odin_ros_driver/calib.yaml`,由主驱动自动写出)。所以**驱动必须先起** | +| **生效的配置** | 三个可执行都用编译期 `__FILE__` 反推出**源码树**再读 config(`host_sdk_sample.cpp:2491`、`pcd2depth_ros2.cpp:147`)。本机编译在此工作区 ⇒ 生效文件 = **`$WS/src/odin_ros_driver/config/control_command.yaml`** | +| **`install/` 那份不生效** | 实测 `install/odin_ros_driver/share/.../control_command.yaml` 是**独立拷贝**且 `senddepth: 0`,而源码树份是 `1`。**别改错文件**,也别被它误导 | +| **三个键必须为 1**(当前源码树份已全为 1) | `senddtof`(= `/odin1/cloud_raw`)、`sendrgb`(= `/odin1/image`)、`senddepth`(= 稠密深度)。深度节点用 `message_filters` 同步 **{cloud_raw + image} 一对**,少一路 ⇒ **永远没有深度 ⇒ 一条 `/cmd_vel` 都不发** | +| 改完必须**整体重启驱动** | 这几个键属 `register_keys`,启动时下发给设备 | +| `use_host_ros_time: 0` | odom 时间戳是**设备时钟**,与主机墙钟不同基准 ⇒ 开手柄前必须处理(见 §10) | + +> 源码树份与 install 份的差异建议**同步一致**,避免下次误改。 + +### 4.2 确认"真的有数据"(关键一步,别用错判据) + +```bash +# ① 最权威:驱动自己写的设备状态日志 +CSV=$(ls -1t $WS/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv | head -1) +head -1 "$CSV"; tail -1 "$CSV" +``` + +期望(本机 2026-09-29 实测的一次健康采集,可直接对照): + +``` +rgb_rx_odr=10.19 dtof_rx_odr=10.33 slam_cloud_rx_odr=9.84 slam_odom_highfreq_rx_odr=396.37 +``` + +读法:`*_tx_odr` 是设备发送率,`*_rx_odr` 是主机接收率。**`*_rx_odr = 0.00` 的那一路就是没通**(多是对应的 `send*` 开关关着)。 + +```bash +# ② 辅助 +ros2 topic hz /odin1/odometry_highfreq # ~300-400 Hz(小消息,hz 可信) +ros2 topic hz /odin1/depth_img_competetion # ~1.2-1.9 Hz(本机实测,深度图小,hz 可信) +ros2 topic echo /odin1/depth_img_competetion --once --field encoding # 期望 32FC1 +``` + +⚠️ 判据陷阱: + +| 方法 | 可靠性 | +|---|---| +| `ros2 topic list` | ❌ 存在**任一**端点(哪怕只有订阅者)就会列出来 | +| `ros2 topic info` 的 `Publisher count` | ❌ 驱动启动就建好 publisher,没数据时照样是 1 | +| `ros2 topic hz` | ✅ 唯一可信,但要排除大消息假象 | +| `dev_status.csv` | ✅✅ 最权威 | + +`/odin1/image` 是 1600×1296 bgr8 ≈ **6.2 MB/帧**,Python 订阅者跟不上会把 RELIABLE 发布端一起拖慢(10 Hz 会显示成 0.3 Hz)——**这是测量假象**。深度图 / 云不存在这个问题。 + +### 4.3 终端 B —— 启动控制器 + +```bash +source /opt/ros/humble/setup.bash && source $WS/venv/bin/activate && source $WS/install/setup.bash + +ros2 launch sru_nav_ros2 sru_nav.launch.py # 正常:deadman 生效 +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false # 冒烟:先抬轮/架空 +``` + +期望日志(出现这 4 行 = 模型加载成功、参数生效): + +``` +[INFO] [sru_nav_node]: VAE encoder: .../share/sru_nav_ros2/models/vae_encoder.onnx +[INFO] [sru_nav_node]: Policy model: .../share/sru_nav_ros2/models/nav_policy.onnx +[INFO] [sru_nav_node]: Navigation policy node is ready. +[INFO] [sru_nav_node]: SRU navigation node spinning (odom_twist_in_base_frame=True, require_joystick=...) +``` + +**不是故障、别误判**: + +- 没发目标时 `/cmd_vel` **恒为 0** 并每秒刷 `Target position reset.` —— 蓝本原有设计。 +- `waypoint_runner` 约 10 s 后把原地不动的目标判为 `STUCK` 并跳过 —— 车确实没动,是它的设计行为。 + ⇒ 要看非零 `/cmd_vel`,盯**发目标后的头 10 秒**。 + +### 4.4 终端 C —— 发目标 + +见 §5。 + +--- + +## 5. 怎么发目标 + +### 5.1 推荐:`waypoint_runner`(外部客户端,不碰主节点) + +```bash +ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" +ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708" # 第 4 个数 = yaw(弧度),只对最后一点要求朝向 +ros2 run sru_nav_ros2 waypoint_runner --waypoints "0,0,0,1.5708" --no-return-home # 纯原地转到 90° +``` + +参数(`--help` 可查全部): + +| 参数 | 默认 | 说明 | +|---|---|---| +| `--waypoints` / `-w` | — | 空格分隔的 `"x,y[,z[,yaw]]"`(yaw 单位**弧度**) | +| `--file` / `-f` | — | 从 YAML 读航点(样例:`config/waypoints_example.yaml`) | +| `--frame-id` | `odom` | 必须等于 odom 的 `header.frame_id`,否则目标被拒 | +| `--timeout` | — | 单目标超时 | +| `--arrive-threshold` | — | XY 到达阈值(要与节点一致,默认 0.75 m) | +| `--goal-yaw-tolerance` | 0.0873 | 带 yaw 的路点的朝向容差(弧度),**必须与节点一致** | +| `--return-home` / `--no-return-home` | 默认回起点 | 走完是否回起点 | + +### 5.2 手发 + +```bash +# 位置 +ros2 topic pub --once /goal_pose geometry_msgs/msg/PoseStamped \ + '{header: {frame_id: odom}, pose: {position: {x: 3.0, y: 0.0}}}' + +# 朝向(弧度;NaN = 本目标不要求朝向) +ros2 topic pub --once --qos-durability transient_local \ + /goal_yaw std_msgs/msg/Float64 '{data: 1.5708}' +``` + +⚠️ `/goal_yaw` **必须带 `--qos-durability transient_local`**:节点是 TRANSIENT_LOCAL 订阅者, +`ros2 topic pub` 默认 VOLATILE 发布者 ⇒ **不兼容、消息被静默丢弃**(发了完全没反应)。 +`waypoint_runner` 内部已是正确的,不用管。 + +⚠️ `/goal_pose` 的 `orientation` 字段**从不被读取**(到达只看 XY 距离)。朝向只能走 `/goal_yaw`。 +⚠️ `frame_id` 与 odom 的 `header.frame_id` 不一致 ⇒ 节点直接 error 拒绝。 + +### 5.3 路点间距:必须 ≥ 3–5 m + +`ARRIVE_GOAL_THRESHOLD = 0.75 m` 且**发布即判到达**。所以: + +| 间距 | 结果 | +|---|---| +| ≤ 0.75 m | **一步都不走**(发布那一刻就已"到达") | +| 1.0 m | 每跳只推进 0.25 m,外加 1.5 s 静置,极慢 | +| 2.0 m | 可用但偏碎 | +| **3–5 m** | ✅ 推荐 | + +每跳实际推进量 = 间距 − 0.75 m。 + +--- + +## 6. 判断"在正常工作"的判据 + +| 观察点 | 含义 | +|---|---| +| 启动打印 `Navigation policy node is ready.` | 两个 ONNX 加载成功 | +| `spinning (odom_twist_in_base_frame=..., require_joystick=...)` 的值与你 YAML 一致 | 参数真的生效 | +| `Odometry not ready, skipping depth callback.` 不再刷新 | odom 已就绪(这条的意思是"还没收到 odom",不是故障) | +| 出现 `cmd_vel_ratio: 1.0000 (require_joystick=False)` | 深度已到、走推理分支 | +| 出现 `Published cmd_vel: linear_x=... linear_y=... angular_z=...` 且非零 | ✅ 推理链路通了 | +| `ros2 topic hz /cmd_vel` ≈ 5 Hz | 门控正常;本机实测只有 1.4–1.7 Hz(**上游慢**,见 §10) | +| `/cmd_vel` 全 0 | 先确认**你发了目标**;再查 deadman / 目标是否比 0.75 m 还近 | + +**安全上限的可证不变式**(实测已核对):`|linear_x| ≤ 0.6`、`|linear_y| ≤ 0.18`、`|angular_z| ≤ 0.6`。 +滤波是 `model_cmd` 与 `prev_cmd` 的**凸组合**(权重非负、和为 1)⇒ **不可能放大**。 + +### 在 rviz2 里看(可选) + +Fixed Frame 必须设 **`odom`**(本工程没有 `map`)。Add → By topic: + +| 加什么 | 含义 | +|---|---| +| `/sru_nav_node/vis/executed_path`(Path) | **实际走过的轨迹**(1 Hz 采样) | +| `/sru_nav_node/vis/goal_path`(Path) | 当前位置 → 当前目标的直线 | +| `/sru_nav_node/vis/twist_cmd_marker` | 策略发出的速度箭头 | +| `/sru_nav_node/vis/goal_vector_marker` | 目标方向单位箭头 | +| `/goal_pose`(Pose)、`/odin1/odometry_highfreq`(Odometry)、`/tf` | 目标、车体姿态、坐标树 | + +⚠️ 再说一次:**没有"规划路径"**。`executed_path` 是走过的地方,不是计划。 + +--- + +## 7. 调参 + +### 7.1 改哪里 —— ⚠️ 本机有个坑 + +节点读的参数文件是 launch 默认的 **`install/sru_nav_ros2/share/sru_nav_ros2/config/sru_nav.yaml`**。 +**实测该文件是独立拷贝(与 `src/` 那份 inode 不同,不是符号链接)**。所以: + +```bash +# 方案 A(最省事,临时生效):直接用 src 那份启动 +ros2 launch sru_nav_ros2 sru_nav.launch.py \ + params_file:=$WS/src/sru_nav_ros2/config/sru_nav.yaml + +# 方案 B(正式):改 src 后重建 +cd $WS && source /opt/ros/humble/setup.bash && source venv/bin/activate +colcon build --symlink-install # 约 2 s +# 重建后建议确认 install 份是否已变成符号链接: +# stat -c '%i %h %n' src/sru_nav_ros2/config/sru_nav.yaml install/sru_nav_ros2/share/sru_nav_ros2/config/sru_nav.yaml +# 若 inode 相同 ⇒ 以后改 src 即生效,免重建 +``` + +改完**必须重启进程**(改了不会热加载),但仍**不需要**重建(代码在 `build/` 侧是符号链接)。 + +### 7.2 绝对不能改的(与训练对齐,改了行为就废) + +``` +control_frequency = 5.0 Hz policy_scale = [0.6, 0.3, 0.6] ← 训练值是 [1.5,1.0,1.0],部署刻意保守 +require_joystick = true rnn_hidden_size = 512 / rnn_num_layers = 1 +min/max_depth = 0.25 / 10.0 m resize(40, 64);latent 2560;obs 2576 +ARRIVE_GOAL_THRESHOLD = 0.75 m JOYSTICK_TIMEOUT = 15.0 s +LOW_PASS_FILTER_COEF = [0.9,0.5,0.5] LATERAL_VELOCITY_SCALE = 0.6 +``` + +- 这些多数从 `constants.py` 取值,故意**不放进 YAML**,不给被误配的机会。 +- `constants.py` / `model.py` / `utils.py` 是**逐字节蓝本拷贝,不要改**。 +- 想改 `ARRIVE_GOAL_THRESHOLD`(例如降到训练值 0.5 m 以铺更密路点)属**要拍板**的改动,需同步改 runner 的 `--arrive-threshold`。 + +### 7.3 可以调的手柄 / 朝向参数(沿用 PS5 映射,**未在真手柄上验过**) + +```bash +ros2 param dump /sru_nav_node # 看当前全部取值 +ros2 param set /sru_nav_node goal_yaw_tolerance 0.05 # 临时改(重启失效) +``` + +`goal_yaw_*` 组 7 个:`tolerance`(默认 0.0873 ≈ ±5°)、`max_rate`(0.6 rad/s)、 +`decel`(0.8 rad/s²)、`update_frequency`(20 Hz)、`settle_time`(0.4 s)、`timeout`(15 s)、`topic`。 + +调参方向:容差不够小 → 降 `tolerance`;过冲 → 减 `max_rate` 或 `decel`;抖 → 加大 `settle_time`。 + +--- + +## 8. 首次上机安全流程 + +1. **抬轮 / 架空**,别落地。 +2. 先确认驱动数据流(§4.1–4.2),再起控制器。 +3. `require_joystick:=false` 跑冒烟,`ros2 topic echo /cmd_vel` 确认数值**有界合理**(§6 的上限)。 +4. 确认急停手段: + - 手柄按 `BUTTON_ABORT`(默认 index 9)→ 立刻发零速并放弃目标; + - Ctrl-C 停 `sru_nav_node` → **但必须先确认底盘桥会不会自动归零**(见下); + - 物理断电。 +5. 落地后先用**很慢**的 `policy_scale`(当前已是保守值)跑一次近目标(2–3 m),确认方向手感对了再放大。 + +⚠️ **`/cmd_vel` 桥(最容易出事故的点)**:本包只发 `Twist`,底盘桥自备。 +**上机前必须确认**:`sru_nav_node` 被杀掉后,桥**会不会自动归零**?不会的话,节点一死机器人会**保持最后一条速度指令继续跑**。 + +**开手柄前必须先处理**:`use_host_ros_time: 0` 导致 odom 是**设备时钟**,而 deadman 判断式是 +`odom 时间戳 − time.time() > 15 s`,**混算两个时间域** ⇒ 要么一上来就超时(`/cmd_vel` 恒 0), +要么 deadman 事实上失效(更危险)。**处理:把驱动的 `use_host_ros_time` 改成 `1` 或 `2` 后整体重启驱动。** +(`require_joystick:=false` 时这段逻辑不执行,所以无载体测试不受影响。) + +--- + +## 9. 排错速查(症状 → 原因) + +| 症状 | 原因 / 去处 | +|---|---| +| `/cmd_vel` **一条都没有**,日志里连 `cmd_vel_ratio:` / `Published cmd_vel:` 都不出现 | **深度没到**。`generate_cmd_vel` 只被 `depth_callback` 调用。查 §4.1 三个键 + §4.2 判据 | +| `/cmd_vel` 有输出但**全 0** | ① 根本没发目标(最常见,会刷 `Target position reset.`);② deadman(`axes[4]` 没推过);③ 目标距车 < 0.75 m | +| `ModuleNotFoundError: No module named 'onnxruntime'` | 没 `source venv/bin/activate`;或缺 `PYTHONPATH` 追加行(§3.1) | +| `No module named 'cv_bridge'` | `PYTHONPATH` 被**覆盖式**写法冲掉了 ROS 路径(§3.1) | +| `import cv2` 段错误 / `_ARRAY_API not found` | 缺 `PYTHONNOUSERSITE=1`;或 `~/.local` 里装了 pip 版 opencv(卸掉) | +| `colcon build` 报找不到 catkin / 冒出一堆无关包名 | `reference/` 或 `venv/` 缺 `COLCON_IGNORE` | +| `topic list` 里有 `/odin1/...` 但收不到数据 | 用 `ros2 topic hz` 判;`topic info` 的 Publisher count 不算数 | +| 深度没数据(3 种原因) | ① `senddepth: 0` → 深度节点打印 "Depth image will not be published." 后**直接退出**;② `sendrgb: 0` → 只来一半;③ **`senddtof: 0`**(最易漏,名字像"传感器开关",其实是"发原始点云") | +| 改了 `control_command.yaml` 毫无变化 | 改错文件了 —— 要改**源码树**那份(§4.1),且改完**整体重启驱动** | +| `waypoint_runner` 报 `No odometry received ... within 30.0s` | 驱动没起,或该话题无发布者。蓝本原始设计,不是 bug | +| 启动就崩 `AttributeError: ... has no attribute 'xxx'` | 改了代码但**没重启进程** | +| 铺密集路点但一步都不走 | 间距 ≤ 0.75 m(§5.3) | +| 位置到了但不自转对准 | 没发 `/goal_yaw`;或话题名不一致;或 deadman 超时(打印 `Joystick timeout during goal-heading alignment`) | +| 订阅了却收不到深度且不报错 | **QoS 不匹配**:BEST_EFFORT 发布端 + RELIABLE 订阅端 = 静默收不到。用 `ros2 topic info -v` 对比两端 | +| Twist 剧烈震荡 | ① `policy_scale` 太大;② `odom_twist_in_base_frame` 判反;③ 深度 NaN 没被过滤 | +| 其它 | `DEPLOY_ROS2.md` §8 排错速查表(约 20 条) | + +--- + +## 10. 已知限制 / 未验证项(上机前必读) + +### 10.1 已定性的"不是 bug 的 bug" + +| 项 | 结论 | +|---|---| +| `/cmd_vel` 只有 1.4–1.7 Hz,深度只有 1.2–1.9 Hz,而设备端是 10 Hz | **8 倍损耗发生在驱动的发布/DDS 环节**。本节点平均 CPU 只占 11%(89% 空等),**已排除本包**。`control_frequency: 5.0` 在代码里是**上限**不是目标值 ⇒ 本包只是如实转发上游速率,逻辑与 5 Hz 时一致 | +| 可疑点 | 驱动里两个大话题硬编码 `qos_sensor = rclcpp::QoS(5)`(odom 用 `QoS(4000)`,所以 odom 正常)。候选修法:`QoS(5)` → `QoS(50)`(1 行 + 重编)。⛔ **绝不能只把发布端改成 BEST_EFFORT**,会让现有 RELIABLE 读者静默收不到任何数据 | + +### 10.2 必须上机实测(本机未验) + +| # | 项 | 现状 | +|---|---|---| +| 1 | **Odin1 装订外参** | 默认值是 Rc2026 比赛车 R2 的实测装订(`base_link` 在 `odin1_base_link` 下 `-0.268846, 0.028504, 0.067861, 0.017828, 0.245433, 0`),**不是本机载体**。接车后必须重测,改 launch 参数 `base_link_x/y/z/roll/pitch/yaw` | +| 2 | 目标朝向精度(±5° 是设计目标) | 逻辑就位,**从未在真机验证** | +| 3 | `/joy` 轴/键索引(17 个参数) | 沿用 PS5 映射,未在真手柄上验 | +| 4 | **deadman 时钟域** | 见 §8,开手柄前必须先改 `use_host_ros_time` | +| 5 | odom twist 正负号手感 | 未验,判反会让车反向跑 | +| 6 | `/cmd_vel` 桥 | 底盘侧桥是否存在、节点死后是否自动归零 —— **未确认,最易出事故的点** | +| 7 | `/sru_nav_node/vis/*` 可视化 | 未在 rviz 里实地看过 | + +### 10.3 环境上的已知偏差(未处理) + +- **`cv2` 是 4.5.5 @ `/usr/local/lib/python3.10/dist-packages`**(散装目录,无 dist-info), + 而文档期望 4.5.4 @ `/usr/lib/python3/dist-packages`。 + 实测 `import cv2` 正常、`CvBridge()` 正常、launch 冒烟正常。 + ⚠️ **没动它**:`/home/xie/techx_R2_algorithm/` 下的 `light_signal_detector` 等节点也 `import cv2`, + 删/挪可能影响 Rc2026 那套。**要不要对齐需拍板。** +- 本次会话是 root,`/home/xie` 为 `drwxr-x--- root root` ⇒ 普通用户 xie 可能进不了自己家目录。 + +### 10.4 残余量(仅记录) + +Odin1 若带俯仰角安装,`odom_twist_in_base_frame: true` 下 `linear.x` 会被乘上约 `cos(pitch)`, +并出现一点虚假的 `linear.z`。参考工程也这么接受;精确补偿需要一次 TF 查询(属新增功能,未做)。 + +--- + +## 附录 A:关键路径一览(本机) + +| 东西 | 路径 | +|---|---| +| 工作区 | `/home/xie/sru_nav_handover/sru_ws` | +| venv | `$WS/venv`(activate 末尾两行 export 不可删) | +| 节点参数(调参入口) | `src/sru_nav_ros2/config/sru_nav.yaml`(生效副本在 `install/sru_nav_ros2/share/.../config/`,见 §7.1) | +| 模型 | `src/sru_nav_ros2/models/{vae_encoder,nav_policy}.onnx` | +| 驱动配置(**生效**) | `$WS/src/odin_ros_driver/config/control_command.yaml` | +| 标定(驱动自动写) | `$HOME/.ros/odin_ros_driver/calib.yaml` | +| 驱动设备状态日志 | `$WS/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv` | +| 节点日志(ROS 自带) | `$HOME/.ros/log/` | + +## 附录 B:记录数据(可选) + +```bash +# 写 $HOME 下,别写 /tmp(本机 /tmp 只有 10 MB) +rm -rf $HOME/depthbag && ros2 bag record -o $HOME/depthbag /odin1/depth_img_competetion /cmd_vel +# 前台跑,约 10 s 后按一次 Ctrl-C;然后 +ros2 bag info $HOME/depthbag # 用 Message count / Duration 手算速率 +``` + +## 附录 C:参数速查(命令行覆盖) + +```bash +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false # 旁路 deadman +ros2 launch sru_nav_ros2 sru_nav.launch.py launch_static_tf:=false # 不发静态 TF +ros2 launch sru_nav_ros2 sru_nav.launch.py odom_twist_in_base_frame:=false # 临时翻语义 +ros2 launch sru_nav_ros2 sru_nav.launch.py base_link_x:=-0.20 base_link_pitch:=0.0 # 装订外参 +ros2 launch sru_nav_ros2 sru_nav.launch.py params_file:=$WS/src/sru_nav_ros2/config/sru_nav.yaml +``` + +> `require_joystick` / `odom_twist_in_base_frame` 的 launch 默认值是**从 YAML 读出来的**(不是写死), +> 所以改 YAML 就够了;命令行 `:=` 只是临时覆盖。 + +--- + +**最后一句**:跑不通时先分清是"**本包**"还是"**物理世界那一半**"—— +`/cmd_vel` 完全没输出 ⇒ 找驱动的深度(§4); +`/cmd_vel` 有输出但数值/方向不对 ⇒ 找装订外参、twist 正负号、deadman(§8、§10.2)。 +**把日志原文发出来,比描述现象有用得多。** diff --git a/sru_ws/docs/assets/cam_in_ex.txt b/sru_ws/docs/assets/cam_in_ex.txt new file mode 100644 index 0000000..4503a0f --- /dev/null +++ b/sru_ws/docs/assets/cam_in_ex.txt @@ -0,0 +1,20 @@ +Tcl_0: [-0.002730, -0.999970, -0.007210, 0.030500, + 0.006180, 0.007190, -0.999960, -0.007700, + 0.999980, -0.002770, 0.006160, -0.004420, + 0.000000, 0.000000, 0.000000, 1.000000] +cam_0: + image_width: 1600 + image_height: 1296 + k2: -0.029021 + k3: 0.125546 + k4: -0.319762 + k5: 0.365260 + k6: -0.208654 + k7: 0.045440 + p1: 0.000000 + p2: 0.000000 + A11: 734.689860 + A12: 0.020513 + A22: 735.073544 + u0: 804.508941 + v0: 621.747400 diff --git a/sru_ws/reference/COLCON_IGNORE b/sru_ws/reference/COLCON_IGNORE new file mode 100644 index 0000000..6ef71b8 --- /dev/null +++ b/sru_ws/reference/COLCON_IGNORE @@ -0,0 +1,9 @@ +# colcon must not crawl this directory. +# +# `reference/` holds the read-only ROS 1 blueprint (ManifoldTechLtd/SRU-Odin, +# the `Deployment/` catkin package `sru_nav_go2_ros1` plus the Isaac Sim `Train/` +# tree). `colcon build` crawls the whole workspace recursively, not just `src/`, +# so without this marker it tries to catkin-build the ROS 1 package, which fails +# on Humble with: Could not find a package configuration file provided by "catkin". +# +# The mere existence of this file is what matters. See docs/DEPLOY_ROS2.md. diff --git a/sru_ws/reference/SRU-Odin/Deployment/3DPrints/odin1_mount.stl b/sru_ws/reference/SRU-Odin/Deployment/3DPrints/odin1_mount.stl new file mode 100644 index 0000000..9487ba8 Binary files /dev/null and b/sru_ws/reference/SRU-Odin/Deployment/3DPrints/odin1_mount.stl differ diff --git a/sru_ws/reference/SRU-Odin/Deployment/CMakeLists.txt b/sru_ws/reference/SRU-Odin/Deployment/CMakeLists.txt new file mode 100644 index 0000000..dab0d18 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/CMakeLists.txt @@ -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 +) diff --git a/sru_ws/reference/SRU-Odin/Deployment/README.md b/sru_ws/reference/SRU-Odin/Deployment/README.md new file mode 100644 index 0000000..e93a2ad --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/README.md @@ -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 +`/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. diff --git a/sru_ws/reference/SRU-Odin/Deployment/config/sru_nav.yaml b/sru_ws/reference/SRU-Odin/Deployment/config/sru_nav.yaml new file mode 100644 index 0000000..420510a --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/config/sru_nav.yaml @@ -0,0 +1,37 @@ +# Runtime parameters for sru_nav_node (Go2 + Odin1). +# Load via: + +# ---- 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 /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 diff --git a/sru_ws/reference/SRU-Odin/Deployment/config/waypoints_example.yaml b/sru_ws/reference/SRU-Odin/Deployment/config/waypoints_example.yaml new file mode 100644 index 0000000..dffc6d0 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/config/waypoints_example.yaml @@ -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] diff --git a/sru_ws/reference/SRU-Odin/Deployment/docs/DEPLOY_GO2_NX.md b/sru_ws/reference/SRU-Odin/Deployment/docs/DEPLOY_GO2_NX.md new file mode 100644 index 0000000..b77a32f --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/docs/DEPLOY_GO2_NX.md @@ -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--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 桥应自动归零(依你的桥行为) +- 关闭电源开关(终极手段) diff --git a/sru_ws/reference/SRU-Odin/Deployment/docs/PORTING_GUIDE.md b/sru_ws/reference/SRU-Odin/Deployment/docs/PORTING_GUIDE.md new file mode 100644 index 0000000..074910f --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/docs/PORTING_GUIDE.md @@ -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) | +| 项目主页 | | 索引仓库、视频、论文 | +| `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//lib/python3/dist-packages + - 启动脚本 LD_PRELOAD 系统 libffi 修复 cv_bridge 的 ABI 冲突 + - catkin_make 时锁定 PYTHON_EXECUTABLE 为 conda python +5. 所有路径、env、distro、机器人型号必须可被环境变量或 ROS 参数覆盖; + 不得在源码里硬写 `/home/` 一类 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//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` 全绿,就能开始真机测试。 diff --git a/sru_ws/reference/SRU-Odin/Deployment/docs/PORTING_GUIDE_EN.md b/sru_ws/reference/SRU-Odin/Deployment/docs/PORTING_GUIDE_EN.md new file mode 100644 index 0000000..c23dc5a --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/docs/PORTING_GUIDE_EN.md @@ -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 | | 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//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/` 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//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. diff --git a/sru_ws/reference/SRU-Odin/Deployment/launch/sru_nav_go2.launch b/sru_ws/reference/SRU-Odin/Deployment/launch/sru_nav_go2.launch new file mode 100644 index 0000000..50330db --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/launch/sru_nav_go2.launch @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sru_ws/reference/SRU-Odin/Deployment/package.xml b/sru_ws/reference/SRU-Odin/Deployment/package.xml new file mode 100644 index 0000000..d02a9d3 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/package.xml @@ -0,0 +1,29 @@ + + + sru_nav_go2_ros1 + 0.1.0 + + 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. + + + SRU Navigation Port + MIT + + catkin + + rospy + std_msgs + sensor_msgs + geometry_msgs + nav_msgs + visualization_msgs + cv_bridge + tf2_ros + + joy + + + + diff --git a/sru_ws/reference/SRU-Odin/Deployment/scripts/launch_sru_nav.sh b/sru_ws/reference/SRU-Odin/Deployment/scripts/launch_sru_nav.sh new file mode 100755 index 0000000..bd6bbb1 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/scripts/launch_sru_nav.sh @@ -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 /devel/setup.bash -> our package +# 3) conda activate sru_nav -> python with onnxruntime +# 4) export PYTHONPATH=:$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 <&2 </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--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}" diff --git a/sru_ws/reference/SRU-Odin/Deployment/scripts/sru_nav_node b/sru_ws/reference/SRU-Odin/Deployment/scripts/sru_nav_node new file mode 100755 index 0000000..da8e2dc --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/scripts/sru_nav_node @@ -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 + /models/, 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() diff --git a/sru_ws/reference/SRU-Odin/Deployment/scripts/verify_port.sh b/sru_ws/reference/SRU-Odin/Deployment/scripts/verify_port.sh new file mode 100755 index 0000000..0423199 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/scripts/verify_port.sh @@ -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 - </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 diff --git a/sru_ws/reference/SRU-Odin/Deployment/scripts/waypoint_runner.py b/sru_ws/reference/SRU-Odin/Deployment/scripts/waypoint_runner.py new file mode 100755 index 0000000..b07ccc3 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/scripts/waypoint_runner.py @@ -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() diff --git a/sru_ws/reference/SRU-Odin/Deployment/setup.py b/sru_ws/reference/SRU-Odin/Deployment/setup.py new file mode 100644 index 0000000..edda25a --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/setup.py @@ -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) diff --git a/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/__init__.py b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/constants.py b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/constants.py new file mode 100644 index 0000000..7941aa2 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/constants.py @@ -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 diff --git a/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/model.py b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/model.py new file mode 100644 index 0000000..4536011 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/model.py @@ -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() diff --git a/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/navigation_policy_node.py b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/navigation_policy_node.py new file mode 100644 index 0000000..fbdf2ec --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/navigation_policy_node.py @@ -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.') diff --git a/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/utils.py b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/utils.py new file mode 100644 index 0000000..87b439b --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/utils.py @@ -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 diff --git a/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/visualization.py b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/visualization.py new file mode 100644 index 0000000..29ed790 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/visualization.py @@ -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) diff --git a/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/waypoint_manager.py b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/waypoint_manager.py new file mode 100644 index 0000000..d113bdb --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Deployment/src/sru_nav_go2/waypoint_manager.py @@ -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 diff --git a/sru_ws/reference/SRU-Odin/LICENSE b/sru_ws/reference/SRU-Odin/LICENSE new file mode 100644 index 0000000..d3ef03b --- /dev/null +++ b/sru_ws/reference/SRU-Odin/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 ManifoldTech + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/sru_ws/reference/SRU-Odin/README.md b/sru_ws/reference/SRU-Odin/README.md new file mode 100644 index 0000000..198e7a9 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/README.md @@ -0,0 +1,516 @@ +# SRU × Odin: Mapless Navigation with Spatially-Enhanced Recurrent Memory + +

+ SRU × Odin1 Logo +

+ +

+ License: MIT + Isaac Sim 4.5.0 + ROS Noetic + Sensor: Odin1 + bilibili +

+ +

+ Deploy cutting-edge paper within half a day using Odin1. +

+ +

+ SRU Navigation Demo +

+ +--- + +## 1. Introduction + +**SRU × Odin** brings the ETH RSL **SRU** (*Spatially-Enhanced Recurrent Memory for +Long-Range Mapless Navigation via End-to-End Reinforcement Learning*) policy to a real +quadruped using a single **Odin1** spatial-memory sensor. The original work relies on a +**ZED-X** stereo camera for depth mapping and a **DLIO** LIO stack for high-precision +odometry tracking; this project collapses both of those subsystems into one compact sensor. + +> **Highlight — one sensor replaces two subsystems.** The **Odin1 spatial memory +> module completely replaces BOTH the depth-mapping functionality of the original ZED +> camera AND the high-precision odometry tracking from the DLIO LIO stack** used in the +> upstream paper. Odin1 publishes a depth stream (`sensor_msgs/Image`, meters, +> ~10 Hz) together with a high-frequency odometry topic, so a single device covers both +> exteroception and state estimation. + +> **Highlight — Code Generation.** You do not have to hand-write the deployment stack. A +> structured LLM prompt (`Prompt/PORTING_GUIDE.md`) lets an AI agent **automatically +> generate ready-to-use navigation deployment code for physical robots** — from ONNX I/O +> specification through the ROS node down to the launch scripts. + +**Paper:** *Spatially-Enhanced Recurrent Memory for Long-Range Mapless Navigation via +End-to-End Reinforcement Learning* — DOI: · +Project page: + +### Related Work + +- **[ManifoldTech Real2Sim Tutorial](https://github.com/ManifoldTechLtd/MT-Real2Sim-Tutorial)** — Transform the real world into a simulated environment using Q9000. +- **[Odin-Nav-Stack](https://github.com/ManifoldTechLtd/Odin-Nav-Stack)** — A full-stack navigation framework based on Odin, integrating end-to-end navigation (NeuPAN), classical navigation, modular navigation, VLM, YOLO object detection, and VLN (Vision-and-Language Navigation) into a unified system. + +--- + +## 2. Key Features + +- **End-to-end mapless navigation** — depth image + goal vector → velocity command + (`/cmd_vel`), with no occupancy grid, no SLAM map, and no global planner. +- **Spatially-enhanced recurrent memory** — a VAE depth encoder feeds an LSTM-SRU actor + (`rnn_hidden_size=512`, `num_layers=1`) that remembers where obstacles were. +- **One sensor, two subsystems replaced** — the Odin1 spatial memory module supplies BOTH + the depth mapping that upstream took from the ZED-X camera AND the high-precision + odometry that upstream took from the DLIO LIO stack. +- **Sensor-agnostic depth pipeline** — any depth image works; Odin1 is the + reference sensor, ZED-X the upstream original. +- **Robot-agnostic output** — publishes a body-frame `geometry_msgs/Twist`; any robot with + a `/cmd_vel` bridge can be driven. +- **ONNX Runtime inference** — no PyTorch at deployment time; single-file models, easy + CPU/GPU EP switching, ready-made aarch64 wheels for Jetson. +- **Reproducible Docker training** — Isaac Sim 4.5.0 + IsaacLab v2.1.1 image, one-click + training scripts, VRAM-aware environment scaling. +- **Prompt-driven deployment** — a physically tested ROS1 Noetic package plus a + prompt-driven workflow to regenerate it from scratch. + +--- + +## 3. System Architecture + +``` + ┌──────────────────────────── TRAINING (Isaac Sim 4.5 / Docker) ────────────────────────────┐ + │ │ + │ IsaacLab v2.1.1 + sru-navigation-sim task + rsl_rl (ActorCriticSRU: VAE + LSTM-SRU) │ + │ parallel envs ──► PPO/MDPO ──► checkpoints (outputs/logs/.../model_*.pt) │ + │ │ + └───────────────────────────────────────────┬────────────────────────────────────────────┘ + │ scripts/export_onnx.py + ▼ + ┌──────────────────────────────── POLICY EXPORT ────────────────────────────────┐ + │ model_best.pt ──► policy.onnx (obs[1,2576] + h/c[1,1,512] → act[1,3]) │ + │ (deployment split: vae_encoder.onnx + nav_policy.onnx) │ + └───────────────────────────────────────────┬──────────────────────────────────┘ + │ copy into Deployment/models/ + ▼ + ┌──────────────────────── DEPLOYMENT (Go2 + Odin1 + ROS1 Noetic) ─────────────────────┐ + │ │ + │ Odin1 driver ──► /odin1/depth_img_competetion (depth) │ + │ └─► /odin1/odometry_highfreq (odom) │ + │ │ │ + │ ▼ │ + │ sru_nav_node: depth ─► VAE encoder ─► latent ─┐ │ + │ odom + goal + prev_action ──────┼─► LSTM-SRU actor ─► /cmd_vel │ + │ LSTM (h,c) held across frames ──┘ (Twist, body frame) │ + │ │ │ + │ ▼ │ + │ cmd_vel bridge (unitree_legged_sdk) ──► sport-mode joint commands │ + └────────────────────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## 4. Repository Structure + +``` +SRU_GO2_ODIN1/ +├── Prompt/ +│ └── PORTING_GUIDE.md # Source-of-truth prompt for LLM-based code generation +├── Deployment/ # Tested, working ROS1 deployment package (reference) +│ ├── src/sru_nav_go2/ # ONNX inference node + helpers (Odin1) +│ ├── config/sru_nav.yaml # The ONLY file users normally edit +│ ├── launch/sru_nav_go2.launch +│ ├── scripts/ # setup_conda_env.sh, launch_sru_nav.sh, verify_port.sh +│ ├── models/ # vae_encoder.onnx + nav_policy.onnx (user-supplied) +│ └── docs/ # DEPLOY_GO2_NX.md, PORTING_GUIDE(_EN).md +├── Train/ # Isaac Sim 4.5 Docker training environment +│ ├── Dockerfile # Base: nvcr.io/nvidia/isaac-sim:4.5.0 +│ ├── docker-compose.yml # shm_size 16gb, NVIDIA runtime, cache volumes +│ ├── scripts/ # train_go2_scratch.sh, export_onnx.py +│ ├── mount/ # IsaacLab / rsl_rl / sru-navigation-sim (live-mounted) +│ └── outputs/logs/ # Checkpoints + TensorBoard logs +└── referee_readme/ # Style/structure reference READMEs +``` + +The three top-level directories map to the three phases of the project: + +| Directory | Role | +| -------------- | ------------------------------------------------------------------- | +| `Prompt/` | The porting prompt — regenerate the deployment package from scratch | +| `Deployment/` | Physically validated deployment code, a practical debugging reference | +| `Train/` | Reproducible Docker environment to (re)train the policy | + +--- + +## 5. Prompt-Based Code Generation & Deployment + +`Prompt/PORTING_GUIDE.md` is a **three-in-one document**: a porting decision log, an +AI-agent replication prompt, and an automated acceptance script. Its purpose is to let an +LLM agent (Cascade, Claude Code, Cursor, etc.) **regenerate the entire `sru_nav_go2_ros1` +deployment package** starting only from the SRU paper and the five upstream repositories. + +### 5.1 The Prompt + +Modern LLMs cannot reliably one-shot ~1500 lines of ROS porting code, so +`Prompt/PORTING_GUIDE.md` cuts the task into a **6-step phased workflow**: reconnaissance, +IO specification, catkin skeleton, node logic, deploy scripts, and docs & verify. Each step +ends with grep-able validation points, so any diverging step is rolled back and retried +before moving on. The prompt is plain Markdown and works with any LLM coding agent. + +### 5.2 `Deployment/` as a practical reference + +The `Deployment/` package is **not generated on the fly** — it is the physically tested, +real-hardware-validated code. Think of it as a highly practical reference rather than a +strict rulebook: if you hit problems while replicating the code through the prompt workflow, +diff your generated package against `Deployment/` to debug and troubleshoot the divergence. + +```bash +diff -r --exclude=__pycache__ --exclude=.git \ + ./generated_sru_nav_go2_ros1/ \ + ./Deployment/ +``` + +> **Tip:** Structure should be broadly similar; comments and literal ordering may differ. +> When something misbehaves, focus your comparison on the critical parameters +> (`policy_scale`, control frequency, topic names, ONNX tensor shapes) — those are the ones +> that must match for correct behavior. + +> The quality of code generated via the prompt workflow may vary depending on +> the capability of the LLM used. In some cases, the generated code may require further +> iteration and refinement with the LLM to achieve full functionality. Always validate +> against the `Deployment/` reference and run the acceptance checks before deploying to +> real hardware. + +--- + +## 6. Training Guide + +This is the core focus of the repository. Training is fully containerized around +**Isaac Sim 4.5.0 + IsaacLab v2.1.1** and the `sru-navigation-sim` task extension. + +### 6.1 Adaptation Notes + +**Sensor adaptation — ZED-X + DLIO → Odin1.** +The policy consumes a normalized single-channel depth image encoded by a VAE into a +`64×5×8` latent (2560 features). Upstream produced depth from a ZED-X stereo stream and +odometry from a DLIO LIO stack; here a single Odin1 sensor supplies both. The node ingests +Odin1's depth image, applies `nan_to_num`, clips to `[0.25, 10.0] m`, and +resizes to the training resolution `(40, 64)` before encoding — the network sees the same +tensor regardless of the physical sensor. + +**Robot kinematics — B2W → Unitree Go2.** +The upstream B2W is a wheeled-legged platform; the target here is the Unitree Go2. Because the +policy only emits a body-frame velocity command, the kinematic difference is absorbed by +the actuator bridge and by a conservative action scale. The deployment `policy_scale` +defaults to `[0.6, 0.3, 0.6]` (vs. the training `[1.5, 1.0, 1.0]`), leaving safety margin; +training randomized the action scale by `Uniform(0.6, 1.2)`, so the network is robust to +runtime rescaling. + +### 6.2 Quick Start — Docker Training + +#### Step 1 — Docker setup, NGC login, and build + +```bash +# NVIDIA NGC login is required to pull the Isaac Sim base image. +docker login nvcr.io +# Username: $oauthtoken +# Password: + +cd Train/ +cp .env.example .env # optional: add WANDB_API_KEY +docker compose build # first build > 20 min (network dependent) +``` + +The build pulls `nvcr.io/nvidia/isaac-sim:4.5.0`, installs IsaacLab `v2.1.1`, replaces the +bundled `rsl_rl` with the SRU-enhanced fork (`ActorCriticSRU` + MDPO/PPO), and installs the +`sru-navigation-sim` task extension. + +> **Warning — Shared memory is mandatory:** Isaac Sim's OmniGraph pipeline crashes (often as +> a silent segfault) if the container's shared memory is too small. Always run with at least +> **`--shm-size=4gb`** for `docker run`, or **`shm_size: '4gb'`** under the service in +> `docker-compose.yml`. This repository's `docker-compose.yml` and `train_go2_scratch.sh` +> already set `16gb` — do **not** lower this below `4gb`. + +#### Step 2 — Launch the container and verify + +```bash +docker compose up -d +docker compose exec sru-nav bash # working dir: /workspace/IsaacLab + +# Inside the container: confirm the task extension + registered tasks +./isaaclab.sh -p -m pip show isaaclab_nav_task +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py --help +``` + +You should see task IDs such as `Isaac-Nav-PPO-Go2-Dev-v0` and `Isaac-Nav-PPO-Go2-v0`. + +#### Step 3 — One-click training with environment variables + +From the host, `scripts/train_go2_scratch.sh` launches a cold-start training run inside a +disposable container (headless, 24 envs, 1000 iterations, `Isaac-Nav-PPO-Go2-Dev-v0` by +default). All knobs are overridable via environment variables: + +```bash +# Default: 24 envs, 1000 iter, headless (safe on a 12 GB card) +./scripts/train_go2_scratch.sh + +# Scale the parallel environment count to your GPU +NUM_ENVS=64 MAX_ITER=2000 ./scripts/train_go2_scratch.sh + +# GUI debugging with a handful of envs +GUI=1 NUM_ENVS=4 MAX_ITER=200 ./scripts/train_go2_scratch.sh + +# Pin a specific GPU and run the full PPO task +GPU=0 TASK=Isaac-Nav-PPO-Go2-v0 RUN_NAME=scratch_full ./scripts/train_go2_scratch.sh +``` + +> **VRAM Hardware Scaling Table** — pick `NUM_ENVS` to match your GPU: + +| GPU | VRAM | Recommended `NUM_ENVS` | +| ------------------- | ----- | ---------------------- | +| RTX 4090 | 24 GB | 64–128 | +| RTX 4070 / 5070 | 12 GB | 24 (default) | +| 8 GB Laptop GPU | 8 GB | 8–12 | + +> **Note:** On a 12 GB card, `GUI=1` combined with a large `NUM_ENVS` will OOM — keep GUI +> runs to ≤ 4 envs and use `--headless` (the default) for real training. + +Outputs land in `outputs/logs/rsl_rl//_/` on the host +(bind-mounted into the container). + +#### Step 4 — Monitor and export + +**Monitor** live metrics with TensorBoard: + +```bash +# TensorBoard (inside container) +docker compose exec sru-nav \ + ./isaaclab.sh -p -m tensorboard.main --logdir logs --bind_all +# then open http://:6006 +``` + +**Export** the trained checkpoint to ONNX. The exporter reconstructs `ActorCriticSRU` from +the checkpoint weight shapes (no Isaac Sim needed) and writes `policy.onnx`: + +```bash +python scripts/export_onnx.py \ + --checkpoint outputs/logs/scratch_reward_fix_v1/model_best.pt \ + --output-dir mount/ +``` + +Useful flags (from `scripts/export_onnx.py`): + +| Flag | Default | Description | +| -------------- | -------------- | ---------------------------------------- | +| `--checkpoint` | *(required)* | Path to the `.pt` checkpoint | +| `--output-dir` | `/export`| Output directory | +| `--filename` | `policy.onnx` | Output filename | +| `--jit` | off | Also export a TorchScript `policy.pt` | +| `--verbose` | off | Print inferred config + architecture | + +Copy the exported model(s) into `Deployment/models/` for on-robot inference. + +--- + +## 7. ONNX I/O Contract + +The training-side export (`export_onnx.py`) produces a **single combined actor** ONNX that +already ingests the fused observation vector: + +| Model | Tensor | Shape | Notes | +| ------------- | --------- | ----------------- | -------------------------------------- | +| `policy.onnx` | `obs` | `(1, 2576)` | 16 proprio + 2560 image latent (64×5×8)| +| (input) | `h_in` | `(1, 1, 512)` | LSTM hidden; zeros at episode start | +| (input) | `c_in` | `(1, 1, 512)` | LSTM cell; zeros at episode start | +| `policy.onnx` | `actions` | `(1, 3)` | `tanh` output in `(-1, 1)` | +| (output) | `h_out` | `(1, 1, 512)` | updated hidden state | +| (output) | `c_out` | `(1, 1, 512)` | updated cell state | + +The **deployment** package splits inference into two ONNX files so the depth encoder and the +recurrent actor can be validated independently: + +| Model | Inputs | Outputs | +| ------------------ | ---------------------------------------- | ---------------------------------- | +| `vae_encoder.onnx` | `input` `(B, 1, 40, 64)` | `mu` `(B, 64, 5, 8)` | +| `nav_policy.onnx` | `obs` `(B, 2576)`, `h` `(1, B, 512)`, `c` `(1, B, 512)` | `actions` `(B, 3)`, `h_new`, `c_new` | + +> **Note:** The node discovers tensor names via `session.get_inputs()[i].name` **and** +> asserts them against this contract at startup — a shape mismatch raises immediately rather +> than silently producing garbage commands. Final velocity = +> `tanh_output × policy_scale`, with `policy_scale = [0.6, 0.3, 0.6]` → `[vx, vy, ωz]`. + +--- + +## 8. Real-Hardware Deployment + +### 8.1 Hardware & Software Requirements + +| Component | Requirement | +| ---------------- | -------------------------------------------------------------------- | +| Robot | Unitree Go2 (or any `/cmd_vel` consumer quadruped) | +| Depth sensor | Odin1 (depth ~10 Hz + high-freq odometry); see launch file for physical mounting offsets | +| Compute | Jetson Orin NX (aarch64) or any Linux x86_64 | +| OS | Ubuntu 20.04 (native ROS Noetic) or `osrf/ros:noetic-desktop` docker | +| Middleware | ROS1 Noetic | +| Python env | conda `sru_go2`, Python **3.8** (bound to Noetic ABI — do not change)| +| Inference | `onnxruntime` (CPU) or `onnxruntime-gpu` (JetPack-matched wheel) | +| Operator input | Unitree remote control | + +### 8.2 ROS1 Interface + +| Topic | Type | Direction | Description | +| ------------------------------ | -------------------------- | --------- | ------------------------------------ | +| `/odin1/depth_img_competetion` | `sensor_msgs/Image` | in | dense float32 depth, meters, ~10 Hz | +| `/odin1/odometry_highfreq` | `nav_msgs/Odometry` | in | odom frame, ~400 Hz (IMU rate) | +| `/joy` | `sensor_msgs/Joy` | in | Unitree remote control input | +| `/goal_pose` | `geometry_msgs/PoseStamped`| in / out | goal; `frame_id` must equal odom frame| +| `/cmd_vel` | `geometry_msgs/Twist` | out | body-frame velocity command | + +> **Note:** `/goal_pose.header.frame_id` **must** match the odom `frame_id` (default +> `odom`); otherwise the node rejects the goal to prevent body-frame coordinates being +> published as odom-frame goals. + +### 8.3 Build & Environment Setup + +Because conda and system ROS coexist, the launch wrapper handles several ABI hazards +automatically (notably the conda/system `libffi` mismatch that otherwise triggers +`libp11-kit.so.0: undefined symbol: ffi_type_pointer`). You do not need to configure +anything by hand — `launch_sru_nav.sh` takes care of it. + +One-time setup then build inside the conda env at the workspace root: + +```bash +# 1) Create the conda env (installs onnxruntime, opencv, netifaces, defusedxml, ...) +bash scripts/setup_conda_env.sh +bash scripts/setup_conda_env.sh --check # ROS dist-packages may [FAIL] outside a container + +# 2) Build in the ACTIVATED conda env, at the workspace root +conda activate sru_go2 +cd $CATKIN_WS # folder containing src/ +catkin_make -DPYTHON_EXECUTABLE=$(which python) + +# 3) Self-check +cd $CATKIN_WS/src/sru_nav_go2_ros1 +bash scripts/verify_port.sh # all PASS when ONNX present +``` + +### 8.4 Three-Terminal Launch + +The first process to start brings up `roscore`. + +**Terminal 1 — Odin1 driver** + +```bash +conda activate neupan +roslaunch odin_ros_driver odin1_ros1.launch +# Ensure config/control_command.yaml has senddepth: 1 and sendodom: 1 +``` + +**Terminal 2 — `/cmd_vel` actuator bridge** + +```bash +conda activate sru_go2 +cd $CATKIN_WS && source devel/setup.bash +rosrun unitree_control unitree_vel_controller __name:=vel_to_sdk +``` + +**Terminal 3 — SRU navigation node** + +```bash +cd $CATKIN_WS/src/sru_nav_go2_ros1 +bash scripts/launch_sru_nav.sh require_joystick:=false +``` + +Setting `require_joystick:=false` stops the Unitree remote control from constantly +broadcasting zero-velocity commands. + +Send a goal (in the odom frame) and watch `/cmd_vel`: + +```bash +rostopic pub -1 /goal_pose geometry_msgs/PoseStamped \ + '{header: {frame_id: "odom"}, pose: {position: {x: 1.0, y: 0.0, z: 0.0}, orientation: {w: 1.0}}}' +rostopic echo /cmd_vel # expect a non-zero Twist stream +``` + +### 8.5 Configuration Notes + +Edit `Deployment/config/sru_nav.yaml` — the only file you normally touch: + +| Parameter | Default | Meaning | +| ------------------- | -------------------- | --------------------------------------------------- | +| `depth_topic` | `/odin1/depth_img_competetion` | depth image (meters) | +| `odom_topic` | `/odin1/odometry_highfreq` | world-frame odometry | +| `cmd_vel_topic` | `/cmd_vel` | output body-frame velocity | +| `control_frequency` | `5.0` | Hz — keep aligned with training | +| `policy_scale` | `[0.6, 0.3, 0.6]` | `[vx_max, vy_max, ωz_max]`; raise gradually | +| `min_depth`/`max_depth` | `0.25` / `10.0` | depth clip range (meters) | +| `use_sim` | `false` | `true` = odom twist already in base frame | +| `require_joystick` | `true` | `false` stops the remote from broadcasting zero-velocity locks (TESTING ONLY) | + +### 8.6 Camera Mounting + +Camera mounting is set in the launch file, which publishes a static TF +`base_link → odin1_base_link` (adjust to the real measured mount). Offsets are xyz in +meters (forward, left, up) and rpy in radians; defaults are `odin1_x=0.258`, `odin1_y=0.0`, +`odin1_z=0.154`, `odin1_roll=0.0`, `odin1_pitch=0.0` (0° downward), `odin1_yaw=0.0`: + +```bash +roslaunch sru_nav_go2 sru_nav_go2.launch odin1_x:=0.28 odin1_z:=0.154 odin1_pitch:=0.0 +``` + +--- + +## 9. Troubleshooting / Common Pitfalls + +| # | Problem | Solution | +| - | ------- | -------- | +| 1 | **`/cmd_vel` is all zeros.** Node logs "ready" but the robot never moves. | The Unitree remote control is holding the robot stationary with zero-velocity commands. On jack stands / sim, launch with `require_joystick:=false`. | +| 2 | **`ModuleNotFoundError: netifaces` / crash on first subscriber.** Node reaches "ready" then dies the moment a topic connects. | `netifaces` / `defusedxml` are missing in the conda env. `pip install netifaces defusedxml` (already built into `setup_conda_env.sh`). | +| 3 | **`libp11-kit.so.0: undefined symbol: ffi_type_pointer`.** | Conda's libffi clashes with system `cv_bridge`. Launch via `launch_sru_nav.sh` — the launch script handles this automatically. | +| 4 | **Node shebang points to `/usr/bin/python3`; ONNX import fails.** | `catkin_make` was run outside the conda env. `conda activate sru_go2 && cd $CATKIN_WS && catkin_make clean && catkin_make -DPYTHON_EXECUTABLE=$(which python)`. | +| 5 | **`zsh` terminal: `setup.zsh: line 7: cd: -q: invalid option`, script dies silently.** | `ZSH_VERSION` leaks into the bash subprocess. `launch_sru_nav.sh` fixes this by exporting `CATKIN_SHELL=bash` and unsetting `ZSH_VERSION`/`ZSH_NAME` before sourcing. | + +> **Note (bonus):** Isaac Sim training crashes with an OmniGraph shared-memory error → +> increase `shm_size` (≥ 4 GB, repo default 16 GB). Jetson pip TLS handshake failures → +> the RTC drained; run `sudo ntpdate -u ntp.aliyun.com && sudo hwclock --systohc`. + +--- + +## 10. Citation + +If you use this work, please cite the SRU paper: + +```bibtex +@article{yang2025sru, + author = {Yang, Fan and Frivik, Per and Hoeller, David and Wang, Chen and Cadena, Cesar and Hutter, Marco}, + title = {Spatially-enhanced recurrent memory for long-range mapless navigation via end-to-end reinforcement learning}, + journal = {The International Journal of Robotics Research}, + year = {2025}, + doi = {10.1177/02783649251401926}, + url = {https://doi.org/10.1177/02783649251401926} +} +``` + +Paper: · +Project page: + +--- + +## 11. Acknowledgments + +This project builds upon: + +--- + +## 12. License + +- **Algorithm & training code** — copyright of the original SRU author team (ETH RSL); + follows their upstream LICENSE. Files containing upstream-derived code retain their + original headers. +- **This deployment port** (`Deployment/`) — released under an **MIT-style** license. +- **Upstream sources:** `sru-navigation-learning`, `sru-navigation-sim`, + `sru-robot-deployment`, `sru-pytorch-spatial-learning`, `sru-depth-pretraining` + (see ). +- **Simulation stack:** NVIDIA Isaac Sim 4.5.0 + IsaacLab v2.1.1. +- **Odin1 driver:** . + +Issues and PRs — especially one-click support for additional robots or cameras — are welcome. diff --git a/sru_ws/reference/SRU-Odin/Train/.dockerignore b/sru_ws/reference/SRU-Odin/Train/.dockerignore new file mode 100644 index 0000000..8fd4912 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/.dockerignore @@ -0,0 +1,14 @@ +# Keep docker build context small. mount/IsaacLab and mount/sru-navigation-sim +# are needed by COPY in Dockerfile, so they MUST NOT be excluded. +outputs/ +log*.txt +auth_qrcode.png +*.tar.gz +*.tgz +**/__pycache__/ +**/*.pyc +**/.git/ +**/.gitignore +.windsurf/ +.vscode/ +.idea/ diff --git a/sru_ws/reference/SRU-Odin/Train/.env.example b/sru_ws/reference/SRU-Odin/Train/.env.example new file mode 100644 index 0000000..a18c11f --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/.env.example @@ -0,0 +1,3 @@ +# Copy to .env and fill in. +WANDB_API_KEY= +DISPLAY=:0 diff --git a/sru_ws/reference/SRU-Odin/Train/Dockerfile b/sru_ws/reference/SRU-Odin/Train/Dockerfile new file mode 100644 index 0000000..a99f26b --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/Dockerfile @@ -0,0 +1,148 @@ +# ===================================================================== +# SRU Navigation Sim - Reproducible Training Image +# Base: NVIDIA Isaac Sim 4.5.0 (matches IsaacLab v2.1.1 requirement) +# ===================================================================== +ARG ISAAC_SIM_VERSION=4.5.0 +FROM nvcr.io/nvidia/isaac-sim:${ISAAC_SIM_VERSION} + +ENV DEBIAN_FRONTEND=noninteractive \ + LANG=C.UTF-8 \ + ACCEPT_EULA=Y \ + PRIVACY_CONSENT=Y \ + OMNI_KIT_ALLOW_ROOT=1 + +# ---------- System deps ---------- +RUN apt-get update && apt-get install -y --no-install-recommends \ + git git-lfs curl wget vim ca-certificates build-essential \ + cmake ninja-build libgl1 libglib2.0-0 libsm6 libxext6 libxrender1 \ + libglu1-mesa libglib2.0-0 ncurses-term tmux htop \ + python3-pip && \ + git lfs install && \ + rm -rf /var/lib/apt/lists/* + +# Avoid "dubious ownership" inside containers +RUN git config --global --add safe.directory '*' + +# ---------- Configure pip mirror (optional) ---------- +# Default behavior uses the official PyPI. The global pip config is written so +# ALL python interpreters in the image (root, kit-bundled +# `_isaac_sim/kit/python`, system python3) pick it up. +# +# Override pip index if needed: --build-arg PIP_INDEX_URL=https://your-mirror/simple --build-arg PIP_TRUSTED_HOST=your-mirror-host +ARG PIP_INDEX_URL= +ARG PIP_TRUSTED_HOST= +RUN if [ -n "${PIP_INDEX_URL}" ]; then \ + mkdir -p /etc && printf "[global]\nindex-url = %s\ntrusted-host = %s\ntimeout = 120\nretries = 5\n" \ + "${PIP_INDEX_URL}" "${PIP_TRUSTED_HOST}" > /etc/pip.conf; \ + mkdir -p /root/.config/pip && cp /etc/pip.conf /root/.config/pip/pip.conf; \ + echo "[build] pip index -> ${PIP_INDEX_URL}"; \ + fi + +# Workspace +ARG ISAACLAB_VERSION=v2.1.1 +ENV ISAACLAB_PATH=/workspace/IsaacLab +WORKDIR /workspace + +# Optional build-time proxy (pass via: --build-arg HTTP_PROXY=... --build-arg HTTPS_PROXY=...) +# Useful when the host is behind GFW / corporate firewall and bare `git clone github.com` +# hits `GnuTLS recv error (-110)` / TLS resets. Leave empty to disable. +ARG HTTP_PROXY= +ARG HTTPS_PROXY= +ARG NO_PROXY= +ENV http_proxy=${HTTP_PROXY} \ + https_proxy=${HTTPS_PROXY} \ + no_proxy=${NO_PROXY} + +# Optional GitHub mirror prefix (e.g. https://ghproxy.com/ or https://gh-proxy.com/). +# When set, all subsequent github.com clones are rewritten through it via git insteadOf. +ARG GITHUB_MIRROR= +RUN if [ -n "${GITHUB_MIRROR}" ]; then \ + git config --global url."${GITHUB_MIRROR}https://github.com/".insteadOf "https://github.com/"; \ + echo "[build] github.com clones rewritten via ${GITHUB_MIRROR}"; \ + fi + +# Harden git for flaky networks (large postBuffer, low-speed timeout, no compression, +# disable smart-http v2 which is the layer that surfaces the GnuTLS reset on long clones). +RUN git config --global http.postBuffer 1048576000 && \ + git config --global http.lowSpeedLimit 1000 && \ + git config --global http.lowSpeedTime 600 && \ + git config --global core.compression 0 && \ + git config --global http.version HTTP/1.1 + +# ---------- Bring IsaacLab v2.1.1 into the image ---------- +# We COPY from the local build context (./mount/IsaacLab) instead of `git clone`, +# because on GFW-affected servers `git clone github.com` repeatedly fails with +# GnuTLS resets / connection timeouts. To set this up on the host: +# +# # one-shot: clone IsaacLab anywhere reachable from your build context +# git clone --depth 1 --branch v2.1.1 \ +# https://github.com/isaac-sim/IsaacLab.git /mount/IsaacLab +# +# If mount/IsaacLab is missing the build will abort here with a clear error. +COPY mount/IsaacLab ${ISAACLAB_PATH} +RUN test -d ${ISAACLAB_PATH}/source/isaaclab && \ + echo "[build] using local IsaacLab from mount/IsaacLab" + +# Symlink Isaac Sim into IsaacLab as required by isaaclab.sh +RUN ln -s /isaac-sim ${ISAACLAB_PATH}/_isaac_sim + +# ---------- Install IsaacLab (uses bundled python from isaac-sim) ---------- +WORKDIR ${ISAACLAB_PATH} +RUN ./isaaclab.sh --install + +# Workaround: the official --install loop builds extensions in PEP-517 isolation, +# which fails for source/isaaclab because the kit-python build env lacks pkg_resources. +# Reinstall every source/* extension with --no-build-isolation to guarantee `import isaaclab` works. +RUN for d in ${ISAACLAB_PATH}/source/*/; do \ + if [ -f "$d/setup.py" ]; then \ + ${ISAACLAB_PATH}/_isaac_sim/python.sh -m pip install --no-build-isolation --timeout 180 --retries 5 -e "$d" || exit 1; \ + fi; \ + done && \ + ${ISAACLAB_PATH}/_isaac_sim/python.sh -c "import isaaclab; print('isaaclab OK:', isaaclab.__file__)" + +# ---------- Replace bundled rsl_rl with SRU-enhanced fork ---------- +# sru-navigation-learning provides ActorCriticSRU + MDPO/SPO/PPO required by sru-navigation-sim. +# It installs under the package name `rsl_rl`, replacing any prior install. +RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip uninstall rsl-rl-lib -y || true +RUN rm -rf ${ISAACLAB_PATH}/_isaac_sim/kit/python/lib/python3.10/site-packages/rsl_rl +WORKDIR /workspace +RUN for i in 1 2 3 4 5; do \ + git clone --depth 1 https://github.com/leggedrobotics/sru-navigation-learning.git /workspace/rsl_rl && break; \ + echo "[retry $i] sru-navigation-learning clone failed, retrying in 10s..."; \ + rm -rf /workspace/rsl_rl; \ + sleep 10; \ + done && test -d /workspace/rsl_rl/.git +RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install --no-build-isolation --timeout 180 --retries 5 -e /workspace/rsl_rl +RUN ${ISAACLAB_PATH}/_isaac_sim/python.sh -c "from rsl_rl.modules import ActorCriticSRU; print('SRU OK')" + +# ---------- Clone & install sru-navigation-sim extension ---------- +ARG SRU_NAV_REPO=https://github.com/leggedrobotics/sru-navigation-sim.git +ARG SRU_NAV_REF=main +# Note: git network hardening already applied above (postBuffer / lowSpeedTime / +# HTTP/1.1 / optional GITHUB_MIRROR), so this block only retries. +RUN for i in 1 2 3 4 5; do \ + git clone --depth 1 --branch ${SRU_NAV_REF} \ + ${SRU_NAV_REPO} ${ISAACLAB_PATH}/source/isaaclab_nav_task && break; \ + echo "[retry $i] sru-navigation-sim clone failed, cleaning up and retrying in 10s..."; \ + rm -rf ${ISAACLAB_PATH}/source/isaaclab_nav_task; \ + sleep 10; \ + done && \ + test -d ${ISAACLAB_PATH}/source/isaaclab_nav_task +RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install -e \ + ${ISAACLAB_PATH}/source/isaaclab_nav_task + +# Useful Python packages for logging/visualization +RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip install \ + wandb tensorboard tensorboardX + +# Common runtime envs +ENV PYTHONUNBUFFERED=1 \ + NVIDIA_DRIVER_CAPABILITIES=all \ + NVIDIA_VISIBLE_DEVICES=all + +WORKDIR ${ISAACLAB_PATH} + +# Sanity check (non-fatal): list registered tasks +RUN ${ISAACLAB_PATH}/isaaclab.sh -p -m pip show isaaclab_nav_task || true + +CMD ["/bin/bash"] diff --git a/sru_ws/reference/SRU-Odin/Train/README.md b/sru_ws/reference/SRU-Odin/Train/README.md new file mode 100644 index 0000000..d9efdfc --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/README.md @@ -0,0 +1,248 @@ +# 🤖 SRU Navigation Training with Isaac Sim + +**Reproducible training pipeline for SRU (Spatially-Enhanced Recurrent Units) navigation policy, ported from B2W (wheeled-legged + ZedX depth) to Unitree Go2 (quadruped + LiDAR-derived depth).** + +Built on NVIDIA Isaac Sim 4.5.0 + IsaacLab v2.1.1, fully containerized with Docker. + +[![Isaac Sim](https://img.shields.io/badge/Isaac%20Sim-4.5.0-76B900?logo=nvidia)](https://developer.nvidia.com/isaac-sim) +[![IsaacLab](https://img.shields.io/badge/IsaacLab-v2.1.1-blue)](https://github.com/isaac-sim/IsaacLab) +[![Docker](https://img.shields.io/badge/Docker-Containerized-2496ED?logo=docker)](https://www.docker.com/) + +--- + +## ✨ Highlights + +- **Full B2W → Go2 port** — assets, cameras, terrain, rewards, termination conditions +- **4-stage training pipeline** — Smoke → Cold-start (1024 envs, 30k iter) → Curriculum continuation → PureMaze refinement +- **Evaluation toolchain** — termination rate stats, baseline comparison, collision analysis, depth ablation +- **Env-var driven config** — difficulty, terrain, GPU selection, seed — no code edits needed +- **Multi-GPU parallel training** — independent seeds across GPUs + +--- + +## 🏗️ Architecture + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Docker Container (~30GB) │ +│ │ +│ ┌───────────────┐ ┌──────────────────────────────────┐ │ +│ │ Isaac Sim │ │ IsaacLab v2.1.1 │ │ +│ │ 4.5.0 │ │ ┌────────────┐ ┌─────────────┐ │ │ +│ └───────┬───────┘ │ │ Nav Task │ │ rsl_rl │ │ │ +│ │ │ │ (Go2 Port) │ │ (SRU Fork) │ │ │ +│ ▼ │ └─────┬──────┘ └──────┬──────┘ │ │ +│ ┌───────────────┐ │ │ │ │ │ +│ │ PhysX / GPU │ │ ▼ ▼ │ │ +│ │ Simulation │◄──┤ ┌──────────────────────────┐ │ │ +│ └───────────────┘ │ │ PPO + ActorCriticSRU │ │ │ +│ │ └──────────────────────────┘ │ │ +│ └──────────────────────────────────┘ │ +│ │ +│ Depth → VAE Encoder (64×5×8) → SRU Policy → SE2 cmd │ +│ ↓ │ +│ policy_go2_jit.pt → Joint Actions │ +└─────────────────────────────────────────────────────────────┘ +``` + +--- + +## 📋 Prerequisites + +| Requirement | Minimum | Recommended | +|---|---|---| +| NVIDIA GPU | 12 GB VRAM | 24 GB+ | +| NVIDIA Driver | ≥ 570 | ≥ 570 (⚠️ avoid 595.x) | +| Docker | 24.0+ | Latest | +| NVIDIA Container Toolkit | Installed | Latest | +| Disk Space | 80 GB | 120 GB+ | +| NGC Access | Required | For `nvcr.io/nvidia/isaac-sim:4.5.0` | + +### VRAM Reference + +| GPU | NUM_ENVS | GO2_CELL_SIZE | +|---|---|---| +| RTX 5070 12 GB | 768–1024 | 1.0 | +| RTX 4090 24 GB | 2048–2820 | 1.0 / 2.0 | +| A100 80 GB | 8000+ | 1.0 / 2.0 | + +--- + +## 🚀 Quick Start + +### 1. Clone & Configure + +```bash +git clone https://github.com//sru-nav-docker.git +cd sru-nav-docker +cp .env.example .env +# Edit .env — set NGC credentials, GPU index, paths +``` + +### 2. Build the Image + +```bash +docker compose build # ~30 GB, takes 20-40 min on first build +``` + +### 3. Launch Container + +```bash +docker compose up -d +docker compose exec sru-nav bash +``` + +### 4. Smoke Test (~30 min) + +```bash +TASK=Isaac-Nav-PPO-Go2-Dev-v0 NUM_ENVS=24 MAX_ITER=300 \ +GO2_DIFFICULTY="0.0,0.4" GO2_INIT_LEVEL=0 \ +./scripts/train_go2_scratch.sh +``` + +If training starts and loss decreases — you're good to go. + +--- + +## 🏋️ Training Pipeline + +### Stage 1 — Cold Start (36–48h) + +```bash +TASK=Isaac-Nav-PPO-Go2-v0 NUM_ENVS=1024 MAX_ITER=30000 \ +GO2_DIFFICULTY="0.0,0.4" GO2_INIT_LEVEL=0 GO2_CELL_SIZE=1.0 \ +SEED=42 RUN_NAME=mixed_scratch_v1 \ +./scripts/train_go2_scratch.sh +``` + +### Stage 2 — Curriculum Continuation + +```bash +./scripts/continue_go2.sh --iters 10000 --from-iter 7400 +``` + +### Stage 3 — PureMaze Refinement + +```bash +TASK=Isaac-Nav-PPO-Go2-PureMaze-v0 NUM_ENVS=1024 MAX_ITER=10000 \ +./scripts/train_go2_scratch.sh +``` + +### Evaluation + +```bash +# Termination rate analysis +PLAY_DIFFICULTY="0.3,0.8" ./scripts/eval_terminations.sh --run-dir --from-iter + +# Baseline comparison +./scripts/compare_baselines.sh + +# Collision analysis +./scripts/analyze_collisions.sh +``` + +### Monitoring + +```bash +# TensorBoard +docker compose exec sru-nav ./isaaclab.sh -p -m tensorboard.main --logdir logs --bind_all + +# Or use Weights & Biases (configure WANDB_API_KEY in .env) +``` + +--- + +## ⚙️ Configuration + +All training behavior is controlled via environment variables — no code changes needed. + +| Variable | Type | Default | Description | +|---|---|---|---| +| `TASK` | str | `Isaac-Nav-PPO-Go2-Dev-v0` | Gym task ID | +| `NUM_ENVS` | int | `24` | Parallel environment count | +| `MAX_ITER` | int | `1000` | Max PPO iterations | +| `SEED` | int | `42` | Random seed | +| `GPU` | str | — | GPU device index | +| `RUN_NAME` | str | auto | Run directory name | +| `GO2_DIFFICULTY` | `"lo,hi"` | cfg default | Difficulty range | +| `GO2_INIT_LEVEL` | int | `5` | Initial max terrain row | +| `GO2_CELL_SIZE` | float | `1.0` | Terrain tile cell size (m) | +| `PLAY_DIFFICULTY` | `"lo,hi"` | — | Eval-time difficulty override | + +### Gym Tasks + +| Task ID | Purpose | Typical envs | +|---|---|---| +| `Isaac-Nav-PPO-Go2-v0` | Cold-start training (mixed terrain) | 1024–2048 | +| `Isaac-Nav-PPO-Go2-Dev-v0` | Smoke test / debugging | 24–32 | +| `Isaac-Nav-PPO-Go2-PureMaze-v0` | Stage-2 maze refinement | 1024 | +| `Isaac-Nav-PPO-Go2-Play-v0` | Playback & evaluation | 20 | + +--- + +## 📁 Project Structure + +``` +sru-nav-docker/ +├── Dockerfile # Image build recipe +├── docker-compose.yml # Container runtime config +├── .env.example # Environment variable template +├── scripts/ # Train / continue / play / eval / diagnostics +│ ├── train_go2_scratch.sh +│ ├── continue_go2.sh +│ ├── eval_terminations.sh +│ ├── compare_baselines.sh +│ └── ... +├── mount/ +│ ├── sru-navigation-sim/ # Task definitions + Go2 port +│ │ ├── isaaclab_nav_task/ # Env, rewards, terrain, obs +│ │ └── scripts/ # Entry points +│ └── rsl_rl/ # rsl_rl SRU fork (ActorCriticSRU, PPO) +├── IsaacLab/ # IsaacLab v2.1.1 source +├── assets/baselines/ # Pre-trained baseline checkpoints +├── outputs/logs/ # Training artifacts (TB + ckpt) +└── docs/handover/ # Handover documentation +``` + +--- + +## 🔑 Key Dependencies + +| Dependency | Source | +|---|---| +| Isaac Sim 4.5.0 | `nvcr.io/nvidia/isaac-sim:4.5.0` (NGC login required) | +| IsaacLab v2.1.1 | [isaac-sim/IsaacLab](https://github.com/isaac-sim/IsaacLab) | +| rsl_rl (SRU fork) | [leggedrobotics/sru-navigation-learning](https://github.com/leggedrobotics/sru-navigation-learning) | +| Nav Task | [leggedrobotics/sru-navigation-sim](https://github.com/leggedrobotics/sru-navigation-sim) | + +--- + +## 📖 Citation + +If you use this work, please cite the original SRU navigation paper: + +```bibtex +@article{yang2025sru, + author = {Yang, Fan and Frivik, Per and Hoeller, David and Wang, Chen and Cadena, Cesar and Hutter, Marco}, + title = {Spatially-enhanced recurrent memory for long-range mapless navigation via end-to-end reinforcement learning}, + journal = {The International Journal of Robotics Research}, + year = {2025}, + doi = {10.1177/02783649251401926}, + url = {https://doi.org/10.1177/02783649251401926} +} +``` + +--- + +## 🙏 Acknowledgments + +- **[ETH Legged Robotics](https://rsl.ethz.ch/)** — SRU navigation (original paper & codebase) +- **[NVIDIA Isaac Sim / IsaacLab](https://developer.nvidia.com/isaac-sim)** — Simulation platform +- **[Unitree Robotics](https://www.unitree.com/)** — Go2 quadruped platform + +--- + +## 📄 License + +See [LICENSE](./LICENSE) in the repository root. +Sub-components (IsaacLab, rsl_rl) retain their respective licenses. diff --git a/sru_ws/reference/SRU-Odin/Train/docker-compose.yml b/sru_ws/reference/SRU-Odin/Train/docker-compose.yml new file mode 100644 index 0000000..cad4650 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/docker-compose.yml @@ -0,0 +1,75 @@ +services: + sru-nav: + build: + context: . + dockerfile: Dockerfile + args: + ISAAC_SIM_VERSION: "4.5.0" + ISAACLAB_VERSION: "v2.1.1" + SRU_NAV_REPO: "https://github.com/leggedrobotics/sru-navigation-sim.git" + SRU_NAV_REF: "main" + # Optional, for CN servers behind GFW. Pass via env or shell: + # GITHUB_MIRROR=https://ghproxy.com/ docker compose build + # HTTP_PROXY=http://host:7890 HTTPS_PROXY=http://host:7890 docker compose build + GITHUB_MIRROR: "${GITHUB_MIRROR:-}" + HTTP_PROXY: "${HTTP_PROXY:-}" + HTTPS_PROXY: "${HTTPS_PROXY:-}" + NO_PROXY: "${NO_PROXY:-}" + PIP_INDEX_URL: "${PIP_INDEX_URL:-}" + PIP_TRUSTED_HOST: "${PIP_TRUSTED_HOST:-}" + image: sru-nav:latest + container_name: sru-nav + runtime: nvidia + stdin_open: true + tty: true + network_mode: host + ipc: host + shm_size: "16gb" + ulimits: + memlock: -1 + stack: 67108864 + environment: + - ACCEPT_EULA=Y + - PRIVACY_CONSENT=Y + - DISPLAY=${DISPLAY:-:0} + - NVIDIA_DRIVER_CAPABILITIES=all + - NVIDIA_VISIBLE_DEVICES=all + # Attempt to avoid RTX segfault on Blackwell (sm_120) by forcing true headless + - OMNI_KIT_HEADLESS=1 + # Optional: put your wandb key in a .env file next to compose + - WANDB_API_KEY=${WANDB_API_KEY:-} + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] + volumes: + # X11 for GUI (optional) + - /tmp/.X11-unix:/tmp/.X11-unix:rw + # Persist Isaac Sim caches across runs + - isaac-cache-kit:/isaac-sim/kit/cache + - isaac-cache-ov:/root/.cache/ov + - isaac-cache-pip:/root/.cache/pip + - isaac-cache-gl:/root/.cache/nvidia/GLCache + - isaac-cache-compute:/root/.nv/ComputeCache + - isaac-logs:/root/.nvidia-omniverse/logs + - isaac-data:/root/.local/share/ov/data + - isaac-docs:/root/Documents + # Persist training outputs (logs/checkpoints) + - ./outputs/logs:/workspace/IsaacLab/logs + # Optional: live-mount the extension for development. Uncomment to use: + # - ./sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task + working_dir: /workspace/IsaacLab + command: /bin/bash + +volumes: + isaac-cache-kit: + isaac-cache-ov: + isaac-cache-pip: + isaac-cache-gl: + isaac-cache-compute: + isaac-logs: + isaac-data: + isaac-docs: diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/LICENSE b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/LICENSE new file mode 100644 index 0000000..3262f7f --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Fan Yang, Per Frivik, Robotic Systems Lab, ETH Zurich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/config/extension.toml b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/config/extension.toml new file mode 100644 index 0000000..99d7637 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/config/extension.toml @@ -0,0 +1,22 @@ +[package] + +# Note: Semantic Versioning is used: https://semver.org/ +version = "0.1.0" + +# Description +title = "IsaacLab Navigation Extension - SRU Project" +description = "IsaacLab task extension for SRU visual navigation with hierarchical control, maze terrain generation, and depth-based RL." +readme = "docs/README.md" +repository = "https://github.com/michaelfyang/sru-pytorch-spatial-learning" +category = "robotics" +keywords = ["robotics", "rl", "navigation", "visual", "learning", "sru", "depth", "hierarchical", "maze", "isaaclab"] + +[dependencies] +"isaaclab" = {} +"isaaclab_assets" = {} + +[core] +reloadable = false + +[[python.module]] +name = "isaaclab_nav_task" diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/docs/README.md b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/docs/README.md new file mode 100644 index 0000000..f93f30e --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/docs/README.md @@ -0,0 +1,482 @@ +# IsaacLab Navigation Extension - SRU Project + +[![Paper](https://img.shields.io/badge/IJRR-2025-blue)](https://journals.sagepub.com/home/ijr) +[![Website](https://img.shields.io/badge/Project-Website-green)](https://michaelfyang.github.io/sru-project-website/) + +> **📌 Important Note**: This repository contains the **IsaacLab task extension** for the SRU project, providing diverse navigation environments with dynamic obstacle configurations and terrain variations. This repository does **not** include the `rsl_rl` learning module (network architectures, PPO/MDPO training algorithms). See the [project website](https://michaelfyang.github.io/sru-project-website/) for the complete navigation system. + +## Overview + +A standalone, self-contained IsaacLab task extension for visual navigation in Isaac Lab v2.1.1 (Isaac Sim 4.5). This repository provides: + +- **Environment**: Diverse navigation environments in IsaacLab with dynamic obstacle configurations and terrain variations +- **Task Definition**: Hierarchical control architecture interface for visual navigation with reinforcement learning +- **Simulation**: High-fidelity physics simulation with realistic depth sensor noise + +**Note**: This repository focuses on the simulation environment and task definition. The RL training infrastructure (neural network architectures, PPO/MDPO algorithms) is provided by the separate `rsl_rl` learning module. + +This extension implements a hierarchical control architecture for visual navigation: +- **High-level policy**: Learns to output SE2 velocity commands (vx, vy, omega) at 5Hz +- **Low-level policy**: Pre-trained locomotion policy that converts velocity commands to joint actions at 50Hz + +The extension is fully self-contained with all necessary robot models, materials, and pre-trained locomotion policies included. + +### What's Included + +- ✅ IsaacLab task extension for visual navigation environments +- ✅ Maze terrain generation with curriculum learning +- ✅ Self-contained assets: Robot models (USD), locomotion policies, depth encoders +- ✅ Multiple robot platforms: B2W (bipedal wheeled) and AoW-D (Anymal on Wheels) +- ✅ Observation definitions: Depth images, proprioception, goal commands +- ✅ Reward functions: Goal reaching, action smoothing, movement penalties +- ✅ Hierarchical action interface: SE2 velocity commands to low-level controllers +- ✅ Domain randomization: Camera pose, action scaling, low-pass filters, sensor delays +- ✅ Training scripts compatible with RSL-RL (PPO/MDPO algorithms) + +### What's NOT Included + +- ❌ `rsl_rl` learning module (network architectures, PPO/MDPO training algorithms) +- ❌ Neural network structures for high-level navigation policy +- ❌ On-policy RL training algorithms (PPO/MDPO implementations) + +**Note**: The `rsl_rl` package must be installed separately to train navigation policies. See the Installation section below. + +### Related Projects + +- [sru-pytorch-spatial-learning](https://github.com/michaelfyang/sru-pytorch-spatial-learning) - Core SRU architecture +- [SRU Project Website](https://michaelfyang.github.io/sru-project-website/) - Complete navigation system + +## Features + +- **Visual navigation** using depth cameras with realistic noise simulation +- **Maze terrain generation** with curriculum learning +- **Self-contained assets**: All robot models and locomotion policies included +- **Multiple robot platforms**: + - **B2W**: Bipedal wheeled robot (with ZedX camera) + - **AoW-D**: Anymal on Wheels (with ZedX camera) +- **Asymmetric actor-critic** with privileged critic observations +- **Curriculum learning** for terrain difficulty progression +- **Multiple algorithms**: MDPO and PPO support via RSL-RL +- **Domain randomization**: Camera pose, action scaling, low-pass filters, sensor delays + +## Installation + +### Prerequisites + +- Isaac Lab v2.1.1 installed and configured +- Isaac Sim 4.5.0 +- Python 3.10 +- PyTorch >= 2.5.1 + +### Step 1: Clone or Place the Extension + +This extension should be placed in the `source/` directory of your IsaacLab installation: + +```bash +# Navigate to your IsaacLab installation +cd /path/to/IsaacLab + +# If cloning this repository separately, place it in source/ +# Your directory structure should look like: +# IsaacLab/ +# ├── source/ +# │ ├── isaaclab/ +# │ ├── isaaclab_assets/ +# │ └── isaaclab_nav_task/ <- This extension +``` + +### Step 2: Install the Extension + +Install the extension in development mode from the IsaacLab root directory: + +```bash +# From IsaacLab root directory +./isaaclab.sh -p -m pip install -e source/isaaclab_nav_task + +# Or navigate to the extension directory +cd source/isaaclab_nav_task +../../isaaclab.sh -p -m pip install -e . +``` + +### Step 3: Install RSL-RL (Required for Training) + +This extension requires the `rsl_rl` package for training. Install the custom version with MDPO/PPO algorithms: + +```bash +# Clone and install custom rsl_rl (if not already installed) +cd /path/to/your/workspace +git clone https://github.com/leggedrobotics/rsl_rl.git +cd rsl_rl +pip install -e . +``` + +### Verify Installation + +Test that the extension is properly installed: + +```bash +# From IsaacLab root directory +./isaaclab.sh -p -m pip show isaaclab_nav_task + +# List available tasks +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py --help +``` + +You should see the task IDs listed (e.g., `Isaac-Nav-MDPO-B2W-v0`, `Isaac-Nav-PPO-AoW-D-v0`, etc.). + +## Available Tasks + +### B2W +| Task ID | Description | +|---------|-------------| +| `Isaac-Nav-MDPO-B2W-v0` | MDPO training | +| `Isaac-Nav-PPO-B2W-v0` | PPO training | +| `Isaac-Nav-MDPO-B2W-Play-v0` | MDPO playback | +| `Isaac-Nav-PPO-B2W-Play-v0` | PPO playback | +| `Isaac-Nav-MDPO-B2W-Dev-v0` | MDPO development | +| `Isaac-Nav-PPO-B2W-Dev-v0` | PPO development | + +### AoW-D +| Task ID | Description | +|---------|-------------| +| `Isaac-Nav-MDPO-AoW-D-v0` | MDPO training | +| `Isaac-Nav-PPO-AoW-D-v0` | PPO training | +| `Isaac-Nav-MDPO-AoW-D-Play-v0` | MDPO playback | +| `Isaac-Nav-PPO-AoW-D-Play-v0` | PPO playback | +| `Isaac-Nav-MDPO-AoW-D-Dev-v0` | MDPO development | +| `Isaac-Nav-PPO-AoW-D-Dev-v0` | PPO development | + +## Training + +### Using the standalone training script + +```bash +# Train B2W with PPO +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task Isaac-Nav-PPO-B2W-v0 --num_envs 4096 --headless + +# Train AoW-D with PPO +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task Isaac-Nav-PPO-AoW-D-v0 --num_envs 4096 --headless + +# Train with custom wandb run name +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task Isaac-Nav-MDPO-B2W-v0 --num_envs 4096 --headless \ + --run_name "experiment_v1_with_curriculum" + +# Train with multiple custom parameters +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task Isaac-Nav-PPO-B2W-v0 --num_envs 2048 --headless \ + --run_name "large_training_run" --seed 42 --max_iterations 20000 +``` + +### Development/Testing (smaller config with tensorboard) + +The `-Dev-v0` variants use tensorboard logging instead of wandb and have reduced iterations (300 vs 15000) for quick testing: + +```bash +# Quick test with small environment count +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task Isaac-Nav-PPO-B2W-Dev-v0 --num_envs 32 --headless +``` + +### Using the standard RSL-RL workflow + +```bash +# Train with RSL-RL +./isaaclab.sh -p source/standalone/workflows/rsl_rl/train.py \ + --task Isaac-Nav-MDPO-B2W-v0 --num_envs 4096 +``` + +## Playing Trained Policies + +```bash +# Play using standalone script +./isaaclab.sh -p source/isaaclab_nav_task/scripts/play.py \ + --task Isaac-Nav-MDPO-B2W-Play-v0 --num_envs 16 + +# Play with specific checkpoint +./isaaclab.sh -p source/isaaclab_nav_task/scripts/play.py \ + --task Isaac-Nav-MDPO-B2W-Play-v0 \ + --checkpoint /path/to/model.pt +``` + +## Architecture + +``` +isaaclab_nav_task/ +├── config/ +│ └── extension.toml # Extension metadata +├── docs/ +│ └── README.md # This file +├── scripts/ +│ ├── train.py # Training script +│ └── play.py # Playback script +├── setup.py # Installation script +├── pyproject.toml # Build configuration +└── isaaclab_nav_task/ + ├── __init__.py # Extension entry point + └── navigation/ + ├── __init__.py + ├── navigation_env_cfg.py # Base environment config + ├── assets/ # Robot configurations and data + │ ├── __init__.py + │ ├── b2w.py # B2W robot config + │ ├── aow_d.py # AoW-D robot config + │ └── data/ # Self-contained asset directory + │ ├── Robots/ # Robot USD models and materials + │ │ └── AoW-D/ # AoW-D robot assets + │ │ ├── aow_d.usd # Robot USD model + │ │ └── Props/ # Materials and textures + │ └── Policies/ # Pre-trained models + │ ├── depth_encoder/ # VAE depth encoders + │ │ └── vae_pretrain_new.pth (ZedX) + │ └── locomotion/ # Low-level locomotion policies + │ ├── aow_d/ # policy_blind_3_1.pt (1.7 MB) + │ └── b2w/ # policy_b2w_new_2.pt (2.0 MB) + ├── config/ + │ ├── rl_cfg.py # Base RL configurations + │ ├── b2w/ + │ │ ├── __init__.py # Task registration + │ │ ├── navigation_env_cfg.py + │ │ └── agents/ + │ │ └── rsl_rl_cfg.py + │ └── aow_d/ + │ ├── __init__.py + │ ├── navigation_env_cfg.py + │ └── agents/ + │ └── rsl_rl_cfg.py + ├── mdp/ + │ ├── observations.py # Observation functions (13 functions) + │ ├── rewards.py # Reward functions (5 functions) + │ ├── terminations.py # Termination conditions (4 functions) + │ ├── curriculums.py # Curriculum terms (1 function) + │ ├── events.py # Domain randomization events (5 functions) + │ ├── depth_utils/ # Depth processing utilities + │ │ ├── __init__.py + │ │ ├── camera_config.py # Camera configurations (ZedX) + │ │ └── depth_noise_encoder.py # VAE-based depth encoder + │ └── navigation/ + │ ├── goal_commands.py + │ ├── goal_commands_cfg.py + │ └── actions/ + │ ├── __init__.py + │ ├── navigation_se2_actions.py + │ └── navigation_se2_actions_cfg.py + └── terrains/ # Custom terrain generators + ├── __init__.py + ├── hf_terrains_maze.py # Maze terrain generation + ├── hf_terrains_maze_cfg.py # Maze terrain configs + ├── maze_config.py # Maze parameters + └── patches.py # TerrainImporter patches +``` + +## Compatibility + +- **Isaac Lab**: v2.1.1 +- **Isaac Sim**: 4.5.0 +- **Python**: 3.10 +- **PyTorch**: >= 2.5.1 + +## Self-Contained Assets + +The extension includes all necessary assets and does not depend on external asset repositories: + +### Robot Models (`assets/data/Robots/`) +- **AoW-D**: Complete USD model with materials and textures + - Used when AoW-D robots are not available in the base `isaaclab_assets` + - Includes all necessary Props and material textures (11 baked textures) + +### Pre-trained Policies (`assets/data/Policies/`) + +**Depth Encoders** (`depth_encoder/`): +- `vae_pretrain_new.pth`: ZedX camera encoder for B2W and AoW-D +- VAE architecture with RegNet backbone + Feature Pyramid Network + +**Locomotion Policies** (`locomotion/`): +- `aow_d/policy_blind_3_1.pt` (1.7 MB): AoW-D wheeled locomotion +- `b2w/policy_b2w_new_2.pt` (2.0 MB): B2W bipedal wheeled locomotion + +All locomotion policies are pre-trained and loaded by the hierarchical action controller. + +## Key Components + +### Navigation Environment (`navigation_env_cfg.py`) +- Defines the scene with terrain, robot, and sensors +- Configures observation groups for policy and critic +- Sets up reward terms for goal reaching and movement penalties +- Configures curriculum for terrain difficulty + +### MDP Components (`mdp/`) + +**Cleaned and optimized** - removed unused functions to improve maintainability: + +- **observations.py** (13 functions): Depth image processing, proprioception, goal direction, delay buffers +- **rewards.py** (5 functions): Goal reaching, action smoothing, movement penalties +- **terminations.py** (4 functions): Timeout, collision detection, angle limits, goal reaching +- **curriculums.py** (1 function): Backward movement penalty scheduling +- **events.py** (5 functions): Camera randomization, action scaling, delay buffer management + +### Navigation Actions (`mdp/navigation/actions/`) +- Hierarchical action space with SE2 velocity commands +- Integration with pre-trained low-level locomotion policies + +### Terrain Generation and Goal Sampling (`terrains/`) + +The extension includes custom maze terrain generators built on Isaac Lab's terrain generation system, providing diverse navigation environments with safe goal and spawn position sampling. + +**Key Features:** +- **Four terrain types**: Maze, non-maze/random, stairs, and pits +- **Curriculum learning**: 180 terrains organized in 6 difficulty levels +- **Safe position sampling**: Separate padding for goals (0.5m) and spawns (0.6m) +- **Mesh optimization**: ~80-99% vertex reduction for large-scale training +- **Explicit boolean masks**: Pre-computed valid positions for efficient sampling + +**Terrain Configuration:** +- Grid: 6 rows (difficulty) × 30 columns (variations) = 180 terrains +- Size: 30m × 30m per terrain with 0.1m resolution (300×300 cells) +- Proportions: 30% maze, 20% random, 30% stairs, 20% pits + +For detailed documentation on terrain generation, goal/spawn sampling, coordinate systems, and implementation details, see [TERRAIN_AND_GOALS.md](TERRAIN_AND_GOALS.md). + +### Depth Processing (`mdp/depth_utils/`) +- **DepthNoise**: Simulates realistic stereo camera noise using disparity-based filtering +- **DepthNoiseEncoder**: VAE-based depth encoder using RegNet backbone with Feature Pyramid Network +- **Camera Configurations**: Pre-defined configs for different camera types: + +| Camera | Robots | Resolution | Depth Range | Encoder | +|--------|--------|------------|-------------|---------| +| ZedX | B2W, AoW-D | 64x40 | 0.25-10.0m | `vae_pretrain_new.pth` | + +### Custom Robot Assets (`assets/`) + +Robot configuration modules define robot-specific parameters: + +**B2W** (`b2w.py`): +- Actuator configurations (position/velocity control) +- Initial joint states +- USD asset path (from base `isaaclab_assets`) + +**AoW-D** (`aow_d.py`): +- Actuator configurations for wheeled quadruped +- Initial joint states +- USD asset path (from local `assets/data/Robots/AoW-D/`) +- Uses local robot model when not available in base assets + +Both configurations integrate seamlessly with the hierarchical navigation controller and pre-trained locomotion policies. + +## Docker and Cluster Setup + +### Docker Modifications + +The Dockerfile includes: +1. **Custom RSL-RL**: Installs custom `rsl_rl` package in editable mode +2. **Git safe directories**: Prevents ownership errors in containers + +### Quick Start Workflow + +```bash +# 1. Build Docker image +./docker/container.sh start --suffix nav + +# 2. Push to cluster (converts to Singularity automatically) +./docker/cluster/cluster_interface.sh push base-nav + +# 3. Submit training job +./docker/cluster/cluster_interface.sh job base-nav \ + "--task Isaac-Nav-PPO-B2W-v0" \ + "--num_envs 2048" \ + "--max_iterations 10000" \ + "--headless" + +# 4. Monitor job +squeue -u $USER +``` + +### Configuration + +**Step 1**: Create `.env.base-nav` profile in `docker/` directory: +```bash +cp docker/.env.base docker/.env.base-nav +``` + +**Step 2**: Configure `docker/cluster/.env.cluster` before deployment: +- Set `CLUSTER_PYTHON_EXECUTABLE=source/isaaclab_nav_task/scripts/train.py` +- Add cluster credentials and paths + +**Step 3**: Add cluster-specific module loads in `docker/cluster/submit_job_slurm.sh`: +```bash +module load eth_proxy # Required for network access on ETH cluster +``` + +See the [IsaacLab cluster guide](https://isaac-sim.github.io/IsaacLab/main/source/deployment/cluster.html#cluster-guide) for details. + +### Training Examples + +```bash +# B2W with MDPO training (10k iterations) +./docker/cluster/cluster_interface.sh job base-nav \ + "--task Isaac-Nav-MDPO-B2W-v0" \ + "--num_envs 2048" \ + "--max_iterations 10000" \ + "--headless" + +# B2W with custom run name +./docker/cluster/cluster_interface.sh job base-nav \ + "--task Isaac-Nav-MDPO-B2W-v0" \ + "--num_envs 2048" \ + "--max_iterations 10000" \ + "--run_name experiment_v1_b2w" \ + "--headless" + +# AoW-D with MDPO training (10k iterations) +./docker/cluster/cluster_interface.sh job base-nav \ + "--task Isaac-Nav-MDPO-AoW-D-v0" \ + "--num_envs 2048" \ + "--max_iterations 10000" \ + "--headless" + +# Quick dev test with PPO training (300 iters, tensorboard) +./docker/cluster/cluster_interface.sh job base-nav \ + "--task Isaac-Nav-PPO-B2W-Dev-v0" \ + "--num_envs 32" \ + "--headless" +``` + +### Troubleshooting + +**Git ownership errors**: Rebuild Docker image (includes fix) or run in container: +```bash +git config --global --add safe.directory '*' +``` + +**Memory issues**: Reduce `--num_envs` or increase `#SBATCH --mem-per-cpu` + +## License + +MIT License - See [LICENSE](../LICENSE) file for details + +Copyright (c) 2025 Fan Yang, Per Frivik, Robotic Systems Lab, ETH Zurich + +## Citation + +If you use this codebase in your research, please cite: + +```bibtex +@article{yang2025sru, + author = {Yang, Fan and Frivik, Per and Hoeller, David and Wang, Chen and Cadena, Cesar and Hutter, Marco}, + title = {Spatially-enhanced recurrent memory for long-range mapless navigation via end-to-end reinforcement learning}, + journal = {The International Journal of Robotics Research}, + year = {2025}, + doi = {10.1177/02783649251401926}, + url = {https://doi.org/10.1177/02783649251401926} +} +``` + +## Contact + +**Authors**: +- Fan Yang (fanyang1@ethz.ch) +- Per Frivik (pfrivik@ethz.ch) + +**Affiliation**: Robotic Systems Lab, ETH Zurich diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/docs/TERRAIN_AND_GOALS.md b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/docs/TERRAIN_AND_GOALS.md new file mode 100644 index 0000000..e2d0765 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/docs/TERRAIN_AND_GOALS.md @@ -0,0 +1,340 @@ +# Terrain Generation and Goal Sampling + +This document provides detailed information about the terrain generation system and goal/spawn position sampling used in the SRU navigation simulation. + +## Table of Contents + +- [Terrain Generation System](#terrain-generation-system) + - [Architecture Overview](#architecture-overview) + - [Key Files](#key-files) + - [Mesh Optimization](#mesh-optimization) + - [Terrain Data Flow](#terrain-data-flow) + - [Maze Terrain Types](#maze-terrain-types) + - [Safety Padding](#safety-padding) + - [Terrain Configuration](#terrain-configuration) + - [Curriculum Learning](#curriculum-learning) +- [Goal and Spawn Sampling](#goal-and-spawn-sampling) + - [Architecture](#architecture) + - [Key Features](#key-features) + - [Coordinate System](#coordinate-system) + - [Terrain Index Mapping](#terrain-index-mapping) + - [Position Sampling](#position-sampling) + - [Robot Spawn Height](#robot-spawn-height) + +## Terrain Generation System + +The extension includes custom maze terrain generators built on Isaac Lab's terrain generation system. + +### Architecture Overview + +``` +Terrain Generation Flow: +┌────────────────────────────────────────────────────────────────────┐ +│ 1. HfMazeTerrainCfg │ +│ └─► maze_terrain() generates: │ +│ - heights: Height field for physics/rendering │ +│ - valid_mask: Valid goal positions (GOAL_PADDING=5 cells) │ +│ - spawn_mask: Valid spawn positions (SPAWN_PADDING=6 cells)│ +│ - platform_mask: Elevated platforms for curriculum │ +│ │ +│ 2. TerrainGenerator (patched) │ +│ └─► Collects height field data from all sub-terrains │ +│ └─► Concatenates into single tensors per attribute │ +│ │ +│ 3. TerrainImporter (patched) │ +│ └─► Stores on self._height_field_* attributes │ +│ │ +│ 4. RobotNavigationGoalCommand │ +│ └─► Reads from env.scene.terrain._height_field_* │ +│ └─► Creates PositionSampler with both masks │ +└────────────────────────────────────────────────────────────────────┘ +``` + +### Key Files + +| File | Purpose | +|------|---------| +| `hf_terrains_maze.py` | Terrain generation with explicit valid_mask/spawn_mask | +| `hf_terrains_maze_cfg.py` | Configuration dataclass (lines 41-51: mask storage attributes) | +| `terrain_constants.py` | Constants: PADDING (5/6 cells), HEIGHTS (0/200/300), VERTICAL_SCALE (0.005) | +| `patches.py` | Monkey-patches TerrainGenerator/TerrainImporter for mask storage | +| `maze_config.py` | MAZE_TERRAIN_CFG with sub-terrain configurations | + +### Mesh Optimization + +The extension includes automatic mesh optimization that significantly reduces GPU memory usage when training with many environments. This is especially important for large-scale RL training (4096+ environments). + +**How it works:** +- Uses hierarchical block-based approach (20x20 → 10x10 → 5x5 blocks) +- Flat terrain regions are simplified to just 2 triangles instead of full mesh detail +- Non-flat regions recursively subdivide until 5x5 blocks, then generate detailed mesh +- Applied automatically via monkey-patching when the extension is imported + +**Memory Reduction:** +| Terrain Type | Vertex Reduction | +|--------------|------------------| +| Flat terrain | ~99% | +| Maze-like | ~89% | +| Pits terrain | ~80% | +| Mixed terrain | ~79% | + +This optimization is transparent - it produces visually identical terrains while dramatically reducing the mesh vertex count. The patches are applied before any terrain generation occurs, ensuring all height-field terrains benefit from the optimization. + +### Terrain Data Flow + +The terrain system uses **explicit boolean masks** instead of height-based classification: + +```python +# During terrain generation (hf_terrains_maze.py) +terrain = TerrainData.create(width, height) # Lines 57-63 + +# Mark obstacles as invalid +terrain.set_obstacle(x_start, x_end, y_start, y_end, wall_height) # Lines 65-73 + +# Apply padding and create masks +terrain.apply_padding(PADDING.GOAL_PADDING) # Lines 92-97: 5 cells = 0.5m for goals +spawn_mask = terrain.create_spawn_mask(PADDING.SPAWN_PADDING) # Lines 99-104: 6 cells = 0.6m + +# Store on config for patches to pick up +cfg.height_field_visual = heights # For Z-lookup (terrain height) +cfg.height_field_valid_mask = valid_mask # For goal sampling (5 cell padding) +cfg.height_field_spawn_mask = spawn_mask # For spawn sampling (6 cell padding) +cfg.height_field_platform_mask = platform_mask # For curriculum learning +``` + +These masks are set in the maze terrain function and picked up by the patches system (patches.py:45-66), which stores them on `TerrainImporter` for access via `env.scene.terrain._height_field_*`. + +### Maze Terrain Types + +Four terrain types are available via `HfMazeTerrainCfg`: + +1. **Maze** (`non_maze_terrain=False, stairs=False`) + - DFS-generated maze with configurable wall openings + - Random obstacle shapes (pillars, bars, crosses, blocks) + - Optional stairs integration (`add_stairs_to_maze=True`) + +2. **Non-Maze/Random** (`non_maze_terrain=True`) + - Random obstacle placement (~15-35% coverage based on difficulty) + - Good for testing navigation without maze structure + +3. **Stairs** (`stairs=True`) + - 3x3 stair/platform structures with 4 cardinal stairways + - Elevated platforms marked for curriculum learning + - Tests robot climbing capabilities + +4. **Pits** (`dynamic_obstacles=True`) + - Pit rows with bridge crossings + - Mix of pit (60%) and wall (40%) obstacles + - Tests navigation over negative obstacles + +### Safety Padding + +Two padding levels ensure safe robot placement: + +| Padding Type | Cells | Meters | Purpose | +|--------------|-------|--------|---------| +| `GOAL_PADDING` | 5 | 0.5m | Goal positions (robot just needs to reach) | +| `SPAWN_PADDING` | 6 | 0.6m | Spawn positions (accounts for robot body) | + +The larger spawn padding accounts for: +- Robot body dimensions (~0.5m × 0.3m for quadrupeds) +- Random yaw orientation (diagonal ~0.58m requires ~0.3m clearance) +- Platform edge safety (prevent falling when spawning near stairs) +- Controller startup behavior + +These values are defined in `terrain_constants.py` as `PADDING.GOAL_PADDING` and `PADDING.SPAWN_PADDING`. + +### Terrain Configuration + +The main terrain configuration is defined in [maze_config.py](../source/isaaclab_nav_task/isaaclab_nav_task/navigation/terrains/maze_config.py): + +```python +MAZE_TERRAIN_CFG = TerrainGeneratorCfg( + size=(30.0, 30.0), # 30m × 30m per terrain tile + border_width=30.0, # Border around entire grid (not per-tile) + num_rows=6, # 6 difficulty levels + num_cols=30, # 30 terrain variations + horizontal_scale=0.1, # 0.1m per height field cell (300×300 cells) + vertical_scale=0.005, # Height conversion: value * 0.005 = meters + curriculum=False, # Random terrain, not progressive + difficulty_range=(0.5, 1.0), # Difficulty sampling range + sub_terrains={ + "maze": HfMazeTerrainCfg(proportion=0.3, open_probability=0.9, + random_wall_ratio=0.5, add_stairs_to_maze=True), + "non_maze": HfMazeTerrainCfg(proportion=0.2, non_maze_terrain=True, + random_wall_ratio=1.0), + "stairs": HfMazeTerrainCfg(proportion=0.3, stairs=True, + randomize_wall=False), + "pits": HfMazeTerrainCfg(proportion=0.2, dynamic_obstacles=True, + random_wall_ratio=1.0), + }, +) +``` + +**Global Parameters:** +- Total: **180 terrains** (6 rows × 30 cols), each 30m × 30m +- Height field: **300×300 cells per terrain** (0.1m resolution) +- `curriculum=False`: Random assignment across all 180 terrains + +### Curriculum Learning + +Terrains are organized in a grid with difficulty varying by row: +- **Rows** (`terrain_levels`): Difficulty levels (0.0 to 1.0) +- **Columns** (`terrain_types`): Different terrain types + +``` +Difficulty + 1.0 | [Hard Maze] [Random Obs] [Tall Stairs] [Deep Pits] ... + 0.8 | [Med Maze] [Med Obs] [Med Stairs] [Med Pits] ... + 0.5 | [Easy Maze] [Few Obs] [Low Stairs] [Shallow] ... + 0.0 | [Flat] [Flat] [Flat] [Flat] ... + └────────────────────────────────────────────────────── + maze non_maze stairs pits +``` + +## Goal and Spawn Sampling + +The goal command generator ([RobotNavigationGoalCommand](../source/isaaclab_nav_task/isaaclab_nav_task/navigation/mdp/navigation/goal_commands.py)) handles sampling valid goal and spawn positions from maze terrains using pre-computed boolean masks. + +### Architecture + +``` +┌────────────────────────────────────────────────────────────────────┐ +│ RobotNavigationGoalCommand (goal_commands.py:329-766) │ +│ └─► _initialize_position_sampling() (once, lines 415-471) │ +│ └─► Creates PositionSampler with: │ +│ - heights: Z-lookup for terrain height │ +│ - valid_mask: Goal positions (5 cells = 0.5m padding) │ +│ - spawn_mask: Spawn positions (6 cells = 0.6m padding) │ +│ - platform_mask: Curriculum learning targets │ +│ - platform_repeat_count: 10 (default, line 74) │ +│ - border_width: 0.0 (sub-terrain default, line 457) │ +│ │ +│ └─► _resample_command(env_ids) (each reset, lines 499-553) │ +│ └─► sample(): Goal from valid_mask (line 519) │ +│ └─► sample_spawn(): Spawn from spawn_mask (line 521) │ +│ └─► Convert local → world coordinates (lines 524-547) │ +└────────────────────────────────────────────────────────────────────┘ +``` + +### Key Features + +- **Pre-computed masks**: `valid_mask` and `spawn_mask` generated during terrain creation +- **Separate padding**: Goals (5 cells = 0.5m) vs spawns (6 cells = 0.6m) for robot body clearance +- **Platform repetition**: Stair platforms repeated 10x in sampling for curriculum learning (goal_commands.py:74, 154) +- **Efficient lookup**: Pre-built position tables enable O(1) random sampling +- **Coordinate conversion**: Handles mesh border offset and centering transform +- **Dynamic border calculation**: Border pixels computed from terrain config (goal_commands.py:107) + +### Coordinate System + +The terrain mesh uses a coordinate system with: +- **Border pixels**: Dynamically computed as `int(border_width / horizontal_scale) + 1` + - Sub-terrain configs default to `border_width=0.0` (from `HfTerrainBaseCfg`) + - With default values: `border_pixels = int(0.0 / 0.1) + 1 = 1` +- **Centering transform**: Mesh is centered at origin by `-terrain_size/2` + +```python +# Converting valid_mask index to local coordinates (goal_commands.py:283-284): +local_x = (x_idx + border_pixels) * horizontal_scale - terrain_size/2 +local_y = (y_idx + border_pixels) * horizontal_scale - terrain_size/2 + +# Example: terrain_size=30m, horizontal_scale=0.1m, border_width=0.0 +# border_pixels = 1 +# valid_mask[0, 0] → local position: (0.1 - 15, 0.1 - 15) = (-14.9, -14.9) +``` + +The `border_pixels` calculation is done in the `PositionSampler.__init__()` (goal_commands.py:107) to match the `@height_field_to_mesh` decorator behavior. + +### Terrain Index Mapping + +The terrain index formula depends on the generation mode: + +| Mode | Formula | Description | +|------|---------|-------------| +| `curriculum=True` | `level + type * num_rows` | Column-major (iterate rows first) | +| `curriculum=False` | `level * num_cols + type` | Row-major (iterate cols first) | + +```python +# In goal_commands.py: +def _get_terrain_indices(self, env_ids): + terrain = self.env.scene.terrain + levels = terrain.terrain_levels[env_ids] # row + types = terrain.terrain_types[env_ids] # col + + if terrain_cfg.curriculum: + return levels + types * num_rows # column-major + else: + return levels * num_cols + types # row-major +``` + +### Position Sampling + +**PositionSampler** (goal_commands.py:51-290) provides two sampling methods: + +```python +class PositionSampler: + def sample(terrain_indices) -> (x, y, z): + """Sample GOAL positions from valid_mask. + Uses platform repetition for curriculum learning. + Default platform_repeat_count=10 (goal_commands.py:74)""" + + def sample_spawn(terrain_indices) -> (x, y, z): + """Sample SPAWN positions from spawn_mask. + Larger padding (6 cells vs 5 cells) for robot body with random orientation.""" +``` + +**Implementation Details:** +- Pre-computes position tables during initialization (goal_commands.py:115-201) +- Platform positions are repeated 10x in goal sampling for curriculum learning +- Uses efficient O(1) random sampling from pre-built position tables +- Falls back to `valid_mask` if `spawn_mask` is not provided (goal_commands.py:99) + +**Sampling flow during episode reset:** + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ _resample_command(env_ids) (goal_commands.py:499-553) │ +├─────────────────────────────────────────────────────────────────┤ +│ 1. Get terrain indices for each environment (line 516) │ +│ - terrain_levels[env_ids] → row (difficulty) │ +│ - terrain_types[env_ids] → col (terrain type) │ +│ - Apply curriculum/random index formula (lines 473-493) │ +│ │ +│ 2. Sample goal position from valid_mask (line 519) │ +│ - Random sample from pre-computed goal position table │ +│ - Platform positions repeated 10x for curriculum weighting │ +│ - Uses GOAL_PADDING = 5 cells = 0.5m │ +│ │ +│ 3. Sample spawn position from spawn_mask (line 521) │ +│ - Random sample from pre-computed spawn position table │ +│ - Larger padding (SPAWN_PADDING = 6 cells = 0.6m) │ +│ - Ensures robot body clearance with random orientation │ +│ │ +│ 4. Convert to world coordinates (lines 524-547) │ +│ - Add terrain_origins[level, type] offset │ +│ - Goal: Add random height offset (0.2-0.8m) for marker │ +│ - Spawn: Add spawn_offset = 0.05m (NOT 0.5m!) │ +│ (robot's default_root_state already has standing height) │ +│ │ +│ 5. Update environment origins (lines 540-542) │ +│ - env.scene.terrain.env_origins[env_ids] = spawn position │ +│ - Robot will be reset to this position │ +└─────────────────────────────────────────────────────────────────┘ +``` + +### Robot Spawn Height + +The spawn height offset accounts for the robot's standing height: + +```python +# In _resample_command() (goal_commands.py:537-542): +spawn_offset = 0.05 # Small offset to prevent clipping into terrain + +# Note: robot's default_root_state already includes standing height (~0.5m) +terrain.env_origins[env_ids, 0] = terrain_origins[:, 0] + spawn_x +terrain.env_origins[env_ids, 1] = terrain_origins[:, 1] + spawn_y +terrain.env_origins[env_ids, 2] = spawn_z + spawn_offset # Just 5cm above terrain +``` + +**Key Change:** The implementation uses only a small 5cm offset because the robot's `default_root_state` configuration already includes the proper standing height (~0.5m). This ensures the robot spawns at the correct height without double-counting the base height. diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/__init__.py new file mode 100644 index 0000000..c3fd681 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/__init__.py @@ -0,0 +1,65 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +""" +Isaac Lab Navigation Tasks extension. + +This extension provides navigation tasks for robot learning with visual perception. + +On import, this module: +1. Applies monkey-patches to Isaac Lab terrain system for height field storage +2. Registers maze terrain types +3. Registers navigation task environments +""" + +import os +import toml + +# Conveniences to other module directories via relative paths +ISAACLAB_NAV_TASKS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../")) +"""Path to the extension source directory.""" + +ISAACLAB_NAV_TASKS_METADATA = toml.load(os.path.join(ISAACLAB_NAV_TASKS_EXT_DIR, "config", "extension.toml")) +"""Extension metadata dictionary parsed from the extension.toml file.""" + +# Configure the module-level variables +__version__ = ISAACLAB_NAV_TASKS_METADATA["package"]["version"] + +## +# Apply patches to Isaac Lab terrain system. +# This must be done before any terrain generation happens. +# IMPORTANT: Import patches directly from the module file, NOT through +# terrains/__init__.py, to avoid triggering terrain imports before patching. +## + +# Direct import from patches module to avoid loading terrains/__init__.py +import importlib.util +import os as _os +_patches_path = _os.path.join(_os.path.dirname(__file__), "terrains", "patches.py") +_spec = importlib.util.spec_from_file_location("patches", _patches_path) +_patches_module = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_patches_module) +_patches_module.apply_terrain_patches() +del _patches_path, _spec, _patches_module + +## +# Export terrain types for convenient access. +## + +from .terrains import ( + HfMazeTerrainCfg, + MAZE_TERRAIN_CFG, +) + +## +# Register Gym environments. +## + +from isaaclab_tasks.utils import import_packages + +# The blacklist is used to prevent importing configs from sub-packages +_BLACKLIST_PKGS = ["utils", "terrains"] +# Import all configs in this package +import_packages(__name__, _BLACKLIST_PKGS) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/__init__.py new file mode 100644 index 0000000..f0bc128 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Navigation task environments for Isaac Lab.""" + +from .navigation_env import NavigationEnv +from .navigation_env_cfg import * + +# Import robot-specific configurations +from .config import * diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/__init__.py new file mode 100644 index 0000000..7fce7a5 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Robot-specific configuration modules for navigation tasks.""" + +from .b2w import * +from .aow_d import * +from .go2 import * diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/__init__.py new file mode 100644 index 0000000..90b933c --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/__init__.py @@ -0,0 +1,78 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +import gymnasium as gym + +from . import agents, navigation_env_cfg + +## +# Register Gym environments. +## + +############################################################################################################## +# MDPO + +gym.register( + id="Isaac-Nav-MDPO-AoW-D-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavMDPORunnerCfg, + }, +) + +gym.register( + id="Isaac-Nav-MDPO-AoW-D-Play-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_PLAY, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavMDPORunnerCfg, + }, +) + +gym.register( + id="Isaac-Nav-MDPO-AoW-D-Dev-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_DEV, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavMDPORunnerDevCfg, + }, +) + +###################################################################################### +# PPO + +gym.register( + id="Isaac-Nav-PPO-AoW-D-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavPPORunnerCfg, + }, +) + +gym.register( + id="Isaac-Nav-PPO-AoW-D-Play-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_PLAY, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavPPORunnerCfg, + }, +) + +gym.register( + id="Isaac-Nav-PPO-AoW-D-Dev-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_DEV, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavPPORunnerDevCfg, + }, +) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/agents/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/agents/__init__.py new file mode 100644 index 0000000..e267b97 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/agents/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Agent configurations for AoW-D navigation tasks.""" + +from . import rsl_rl_cfg diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/agents/rsl_rl_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/agents/rsl_rl_cfg.py new file mode 100644 index 0000000..cbeed6a --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/agents/rsl_rl_cfg.py @@ -0,0 +1,119 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""RSL-RL agent configurations for AoW-D navigation tasks.""" + +from isaaclab.utils import configclass + +from isaaclab_nav_task.navigation.config.rl_cfg import ( + RslRlOnPolicyRunnerCfg, + RslRlPpoActorCriticCfg, + RslRlPpoAlgorithmCfg, +) + + +@configclass +class AowDNavMDPORunnerCfg(RslRlOnPolicyRunnerCfg): + """MDPO runner configuration for AoW-D navigation.""" + + num_steps_per_env = 16 + max_iterations = 15000 + save_interval = 500 + logger = "wandb" + seed = 50 + wandb_project = "isaaclab_nav_aow_d" + experiment_name = "aow_d_navigation_mdpo" + empirical_normalization = False + reward_shifting_value = 0.05 + policy = RslRlPpoActorCriticCfg( + class_name="ActorCriticSRU", + init_noise_std=1.0, + actor_hidden_dims=[512, 256, 128], + critic_hidden_dims=[512, 256, 128], + activation="elu", + rnn_hidden_size=512, + rnn_type="lstm_sru", + rnn_num_layers=1, + dropout=0.2, + num_cameras=1, + image_input_dims=(64, 5, 8), + ) + algorithm = RslRlPpoAlgorithmCfg( + class_name="MDPO", + value_loss_coef=0.02, + use_clipped_value_loss=True, + clip_param=0.2, + value_clip_param=0.2, + entropy_coef=0.00375, + num_learning_epochs=5, + num_mini_batches=4, + learning_rate=1.0e-3, + schedule="adaptive", + gamma=0.995, + lam=0.95, + desired_kl=0.01, + max_grad_norm=1.0, + ) + + +@configclass +class AowDNavMDPORunnerDevCfg(AowDNavMDPORunnerCfg): + """Development configuration for MDPO with reduced iterations.""" + + def __post_init__(self): + super().__post_init__() + self.max_iterations = 300 + self.experiment_name = "aow_d_navigation_mdpo_dev" + self.logger = "tensorboard" + + +@configclass +class AowDNavPPORunnerCfg(RslRlOnPolicyRunnerCfg): + """PPO runner configuration for AoW-D navigation.""" + + num_steps_per_env = 24 + max_iterations = 15000 + save_interval = 500 + logger = "wandb" + wandb_project = "isaaclab_nav_aow_d" + experiment_name = "aow_d_navigation_ppo" + empirical_normalization = False + policy = RslRlPpoActorCriticCfg( + class_name="ActorCriticSRU", + init_noise_std=1.0, + actor_hidden_dims=[512, 256, 128], + critic_hidden_dims=[512, 256, 128], + activation="elu", + rnn_hidden_size=256, + rnn_type="lstm_sru", + num_cameras=1, + image_input_dims=(64, 5, 8), + ) + algorithm = RslRlPpoAlgorithmCfg( + class_name="PPO", + value_loss_coef=0.1, + use_clipped_value_loss=True, + clip_param=0.2, + entropy_coef=0.005, + num_learning_epochs=5, + num_mini_batches=4, + learning_rate=1.0e-3, + schedule="adaptive", + gamma=0.995, + lam=0.95, + desired_kl=0.01, + max_grad_norm=1.0, + ) + + +@configclass +class AowDNavPPORunnerDevCfg(AowDNavPPORunnerCfg): + """Development configuration for PPO with reduced iterations.""" + + def __post_init__(self): + super().__post_init__() + self.max_iterations = 300 + self.experiment_name = "aow_d_navigation_ppo_dev" + self.logger = "tensorboard" diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/navigation_env_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/navigation_env_cfg.py new file mode 100644 index 0000000..5abbfd2 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/aow_d/navigation_env_cfg.py @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""AoW-D (Anymal on Wheels) specific configuration for navigation environment.""" + +from isaaclab.utils import configclass + +from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg +import isaaclab_nav_task.navigation.mdp as mdp + +from isaaclab_nav_task.navigation.assets import ANYMAL_D_ON_WHEELS_CFG # isort: skip + + +@configclass +class AowDNavigationEnvCfg(NavigationEnvCfg): + def __post_init__(self): + super().__post_init__() + + from isaaclab_nav_task.navigation.mdp.observations import initialize_depth_noise_generator + from isaaclab_nav_task.navigation.mdp.depth_utils.camera_config import get_camera_config + + initialize_depth_noise_generator(robot_name="aow_d", use_jit_precompiled=False) + + camera_config = get_camera_config("aow_d") + CAMERA_RESOLUTION = camera_config.resolution + + self.scene.robot = ANYMAL_D_ON_WHEELS_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + self.scene.terrain.max_init_terrain_level = 10 + self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0] + self.scene.terrain.terrain_generator.curriculum = False + +@configclass +class AowDNavigationEnvCfg_DEV(AowDNavigationEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.terrain.terrain_generator.num_rows = 1 + self.scene.terrain.terrain_generator.num_cols = 30 + self.scene.terrain.max_init_terrain_level = 10 + self.scene.terrain.terrain_generator.difficulty_range = [0.4, 0.8] + self.scene.terrain.terrain_generator.curriculum = True + self.scene.num_envs = 1 + +@configclass +class AowDNavigationEnvCfg_PLAY(AowDNavigationEnvCfg): + def __post_init__(self): + super().__post_init__() + + self.scene.num_envs = 20 + self.scene.env_spacing = 2.5 + self.scene.terrain.max_init_terrain_level = None + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 2 + self.scene.terrain.terrain_generator.num_cols = 2 + + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/__init__.py new file mode 100644 index 0000000..39ba82a --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/__init__.py @@ -0,0 +1,78 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +import gymnasium as gym + +from . import agents, navigation_env_cfg + +## +# Register Gym environments. +## + +############################################################################################################## +# MDPO + +gym.register( + id="Isaac-Nav-MDPO-B2W-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavMDPORunnerCfg, + }, +) + +gym.register( + id="Isaac-Nav-MDPO-B2W-Play-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_PLAY, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavMDPORunnerCfg, + }, +) + +gym.register( + id="Isaac-Nav-MDPO-B2W-Dev-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_DEV, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavMDPORunnerDevCfg, + }, +) + +###################################################################################### +# PPO + +gym.register( + id="Isaac-Nav-PPO-B2W-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavPPORunnerCfg, + }, +) + +gym.register( + id="Isaac-Nav-PPO-B2W-Play-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_PLAY, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavPPORunnerCfg, + }, +) + +gym.register( + id="Isaac-Nav-PPO-B2W-Dev-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_DEV, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavPPORunnerDevCfg, + }, +) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/agents/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/agents/__init__.py new file mode 100644 index 0000000..97c9703 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/agents/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Agent configurations for B2W navigation tasks.""" + +from . import rsl_rl_cfg diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/agents/rsl_rl_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/agents/rsl_rl_cfg.py new file mode 100644 index 0000000..34b7189 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/agents/rsl_rl_cfg.py @@ -0,0 +1,126 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""RSL-RL agent configurations for B2W navigation tasks.""" + +from isaaclab.utils import configclass + +from isaaclab_nav_task.navigation.config.rl_cfg import ( + RslRlOnPolicyRunnerCfg, + RslRlPpoActorCriticCfg, + RslRlPpoAlgorithmCfg, +) + + +@configclass +class B2WNavMDPORunnerCfg(RslRlOnPolicyRunnerCfg): + """MDPO runner configuration for B2W navigation.""" + + num_steps_per_env = 16 + max_iterations = 15000 + save_interval = 500 + logger = "wandb" + seed = 60 + wandb_project = "isaaclab_nav_b2w" + experiment_name = "b2w_navigation_mdpo" + empirical_normalization = False + reward_shifting_value = 0.05 + policy = RslRlPpoActorCriticCfg( + class_name="ActorCriticSRU", + init_noise_std=1.0, + actor_hidden_dims=[512, 256, 128], + critic_hidden_dims=[512, 256, 128], + activation="elu", + rnn_hidden_size=512, + rnn_type="lstm_sru", + rnn_num_layers=1, + dropout=0.2, + num_cameras=1, + image_input_dims=(64, 5, 8), # depth image: 64 channels * 5 * 8 = 2560 + height_input_dims=(64, 7, 7), # encoded height_scan_critic: 64*7*7 = 3136 + ) + algorithm = RslRlPpoAlgorithmCfg( + class_name="MDPO", + value_loss_coef=0.02, + use_clipped_value_loss=True, + clip_param=0.2, + value_clip_param=0.2, + entropy_coef=0.00375, + num_learning_epochs=5, + num_mini_batches=4, + learning_rate=1.0e-3, + schedule="exponential", + gamma=0.999, + lam=0.95, + desired_kl=0.01, + max_grad_norm=1.0, + ) + + +@configclass +class B2WNavMDPORunnerDevCfg(B2WNavMDPORunnerCfg): + """Development configuration for MDPO with reduced iterations.""" + + def __post_init__(self): + super().__post_init__() + self.max_iterations = 300 + self.experiment_name = "b2w_navigation_mdpo_dev" + self.logger = "tensorboard" + + +@configclass +class B2WNavPPORunnerCfg(RslRlOnPolicyRunnerCfg): + """PPO runner configuration for B2W navigation.""" + + num_steps_per_env = 16 + max_iterations = 15000 + save_interval = 500 + logger = "wandb" + seed = 60 + wandb_project = "isaaclab_nav_b2w" + experiment_name = "b2w_navigation_ppo" + empirical_normalization = False + reward_shifting_value = 0.05 + policy = RslRlPpoActorCriticCfg( + class_name="ActorCriticSRU", + init_noise_std=1.0, + actor_hidden_dims=[512, 256, 128], + critic_hidden_dims=[512, 256, 128], + activation="elu", + rnn_hidden_size=512, + rnn_type="lstm_sru", + rnn_num_layers=1, + dropout=0.2, + num_cameras=1, + image_input_dims=(64, 5, 8), # depth image: 64 channels * 5 * 8 = 2560 + height_input_dims=(64, 7, 7), # encoded height_scan_critic: 64*7*7 = 3136 + ) + algorithm = RslRlPpoAlgorithmCfg( + class_name="PPO", + value_loss_coef=0.02, + use_clipped_value_loss=True, + clip_param=0.2, + value_clip_param=0.2, + entropy_coef=0.00375, + num_learning_epochs=5, + num_mini_batches=4, + learning_rate=1.0e-3, + schedule="adaptive", + gamma=0.995, + lam=0.95, + desired_kl=0.01, + max_grad_norm=1.0, + ) + + +@configclass +class B2WNavPPORunnerDevCfg(B2WNavPPORunnerCfg): + """Development configuration for PPO with reduced iterations.""" + + def __post_init__(self): + super().__post_init__() + self.max_iterations = 300 + self.experiment_name = "b2w_navigation_ppo_dev" + self.logger = "tensorboard" diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/navigation_env_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/navigation_env_cfg.py new file mode 100644 index 0000000..2222a3c --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/b2w/navigation_env_cfg.py @@ -0,0 +1,139 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""B2W specific configuration for navigation environment.""" + +import os + +from isaaclab.utils import configclass +from isaaclab.managers import SceneEntityCfg + +from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg +import isaaclab_nav_task.navigation.mdp as mdp + +from isaaclab_nav_task.navigation.assets import B2W_CFG, ISAACLAB_NAV_TASKS_ASSETS_DIR # isort: skip + + +LEG_JOINT_NAMES = [".*hip_joint", ".*thigh_joint", ".*calf_joint"] +WHEEL_JOINT_NAMES = [".*foot_joint"] + +@configclass +class B2WNavigationEnvCfg(NavigationEnvCfg): + def __post_init__(self): + super().__post_init__() + + from isaaclab_nav_task.navigation.mdp.observations import initialize_depth_noise_generator + from isaaclab_nav_task.navigation.mdp.depth_utils.camera_config import get_camera_config + + initialize_depth_noise_generator(robot_name="b2w", use_jit_precompiled=False) + + camera_config = get_camera_config("b2w") + CAMERA_RESOLUTION = camera_config.resolution + + self.scene.robot = B2W_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + self.scene.raycast_camera.prim_path = "{ENV_REGEX_NS}/Robot/base_link" + self.scene.raycast_camera.offset.pos = (0.387, 0.0, 0.28) + self.scene.height_scanner_critic.prim_path = "{ENV_REGEX_NS}/Robot/base_link" + + self.terminations.base_contact.params = {"sensor_cfg": SceneEntityCfg("contact_forces", body_names=["base_link", ".*hip", ".*thigh"]), "threshold": 1.0} + + self.actions.velocity_command.low_level_position_action = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*hip_joint", ".*thigh_joint", ".*calf_joint"], scale=0.5, use_default_offset=True) + self.actions.velocity_command.low_level_velocity_action = mdp.JointVelocityActionCfg(asset_name="robot", joint_names=[".*foot_joint"], scale=5.0, use_default_offset=True) + self.actions.velocity_command.low_level_policy_file = os.path.join(ISAACLAB_NAV_TASKS_ASSETS_DIR, "Policies", "locomotion", "b2w", "policy_b2w_new_2.pt") + + self.rewards.joint_acc_l2_joint.params = {"asset_cfg": SceneEntityCfg("robot", joint_names=LEG_JOINT_NAMES+WHEEL_JOINT_NAMES)} + + self.terminations.base_contact.params = {"sensor_cfg": SceneEntityCfg("contact_forces", body_names=["base_link", ".*hip", ".*thigh"]), "threshold": 1.0} + + self.events.randomize_low_pass_filter_alpha.params = { + "alpha_range": (0.1, 0.6), + "action_term": "velocity_command", + "per_dimension": True, + "alpha_range_vx": (0.1, 0.6), + "alpha_range_vy": (0.1, 0.6), + "alpha_range_omega": (0.1, 0.6), + } + + self.scene.terrain.max_init_terrain_level = 10 + self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0] + self.scene.terrain.terrain_generator.curriculum = False + +@configclass +class B2WNavigationEnvCfg_DEV(B2WNavigationEnvCfg): + def __post_init__(self): + super().__post_init__() + self.scene.terrain.terrain_generator.num_rows = 2 + self.scene.terrain.terrain_generator.num_cols = 30 + self.scene.terrain.max_init_terrain_level = 10 + self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0] + self.scene.terrain.terrain_generator.curriculum = False + +@configclass +class B2WNavigationEnvCfg_PLAY(B2WNavigationEnvCfg): + def __post_init__(self): + super().__post_init__() + + self.scene.num_envs = 20 + self.scene.env_spacing = 2.5 + self.scene.terrain.max_init_terrain_level = None + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 2 + self.scene.terrain.terrain_generator.num_cols = 2 + + # ---- PLAY_DIFFICULTY="lo,hi": difficulty band ---- + lo, hi = 0.5, 1.0 + _play_diff = os.environ.get("PLAY_DIFFICULTY", "").strip() + if _play_diff: + _parts = _play_diff.replace(" ", "").split(",") + lo, hi = float(_parts[0]), float(_parts[1]) + self.scene.terrain.terrain_generator.difficulty_range = [lo, hi] + self.scene.terrain.terrain_generator.curriculum = False + print(f"[B2W PLAY] terrain difficulty_range = [{lo}, {hi}] (curriculum off)") + + sub_terrains = self.scene.terrain.terrain_generator.sub_terrains + + # PLAY_MAZE_ONLY=1: 100% maze sub-terrain + _maze_only = os.environ.get("PLAY_MAZE_ONLY", "").strip().lower() in ("1", "true", "yes") + if _maze_only and "maze" in sub_terrains: + for name in list(sub_terrains.keys()): + sub_terrains[name].proportion = 1.0 if name == "maze" else 0.0 + print(f"[B2W PLAY] PLAY_MAZE_ONLY=1 -> 100% maze sub-terrain") + + # PLAY_SUBTERRAIN_MIX="maze=1,non_maze=0,pits=0" + _mix = os.environ.get("PLAY_SUBTERRAIN_MIX", "").strip() + if _mix: + overrides = {} + for part in _mix.split(","): + if "=" not in part: + continue + k, v = part.split("=", 1) + overrides[k.strip()] = float(v.strip()) + for name, prop in overrides.items(): + if name in sub_terrains: + sub_terrains[name].proportion = prop + final = {n: sub_terrains[n].proportion for n in sub_terrains} + print(f"[B2W PLAY] PLAY_SUBTERRAIN_MIX -> {final}") + + # PLAY_CELL_SIZE: meters per maze cell + _play_cell = os.environ.get("PLAY_CELL_SIZE", "").strip() + if _play_cell: + new_cell = float(_play_cell) + for cfg_sub in sub_terrains.values(): + cfg_sub.cell_size = new_cell + tile_m = 15 * new_cell + self.scene.terrain.terrain_generator.size = (tile_m, tile_m) + print(f"[B2W PLAY] PLAY_CELL_SIZE={new_cell}m -> tile={tile_m}m") + + # PLAY_CLASSIC_MAZE=1: paper-style uniform walls + _classic = os.environ.get("PLAY_CLASSIC_MAZE", "").strip().lower() in ("1", "true", "yes") + if _classic and "maze" in sub_terrains: + sub_terrains["maze"].randomize_wall = False + sub_terrains["maze"].random_wall_ratio = 0.0 + print(f"[B2W PLAY] PLAY_CLASSIC_MAZE=1 -> classic uniform walls in maze") + + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/__init__.py new file mode 100644 index 0000000..7db8aa8 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/__init__.py @@ -0,0 +1,58 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +import gymnasium as gym + +from . import agents, navigation_env_cfg + +## +# Register Gym environments. +## + +############################################################################################################## +# PPO + +gym.register( + id="Isaac-Nav-PPO-Go2-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg, + # MixedCfg is the cold-start tuned variant of the Dev hyperparams; + # the original B2W-FT ``Go2NavPPORunnerCfg`` collapses exploration on a + # from-scratch run (init_std=0.5, entropy=0.001, clip=0.1). + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerMixedCfg, + }, +) + +gym.register( + id="Isaac-Nav-PPO-Go2-Play-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg_PLAY, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerCfg, + }, +) + +gym.register( + id="Isaac-Nav-PPO-Go2-Dev-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg_DEV, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerDevCfg, + }, +) + +gym.register( + id="Isaac-Nav-PPO-Go2-PureMaze-v0", + entry_point="isaaclab_nav_task.navigation:NavigationEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg_PureMaze, + "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerPureMazeCfg, + }, +) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/agents/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/agents/__init__.py new file mode 100644 index 0000000..7f31efe --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/agents/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Agent configurations for Go2 navigation tasks.""" + +from . import rsl_rl_cfg diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/agents/rsl_rl_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/agents/rsl_rl_cfg.py new file mode 100644 index 0000000..6445cc6 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/agents/rsl_rl_cfg.py @@ -0,0 +1,186 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""RSL-RL agent configurations for Unitree Go2 navigation tasks. + +The policy block is intentionally identical to ``B2WNavPPORunnerCfg`` so that a +B2W checkpoint can be warm-started via ``--resume`` / ``--load_run`` with +``strict=True`` state-dict loading. +""" + +from isaaclab.utils import configclass + +from isaaclab_nav_task.navigation.config.rl_cfg import ( + RslRlOnPolicyRunnerCfg, + RslRlPpoActorCriticCfg, + RslRlPpoAlgorithmCfg, +) + + +@configclass +class Go2NavPPORunnerCfg(RslRlOnPolicyRunnerCfg): + """PPO runner configuration for Go2 navigation, tuned for fine-tuning from a B2W checkpoint.""" + + num_steps_per_env = 16 + max_iterations = 5000 + save_interval = 200 + # Use TensorBoard by default; wandb requires WANDB_API_KEY and an interactive + # tty for first-time login, neither of which is available inside the headless + # docker container. All downstream cfgs (Dev / PureMaze) already override to + # tensorboard; the base now matches so the mixed-terrain task + # ``Isaac-Nav-PPO-Go2-v0`` no longer crashes on cold start. + logger = "tensorboard" + seed = 42 + wandb_project = "isaaclab_nav_go2" + experiment_name = "go2_navigation_ppo_ft_from_b2w" + empirical_normalization = False + reward_shifting_value = 0.05 + + # IMPORTANT: must match the B2W policy block byte-for-byte so that + # ActorCriticSRU.load_state_dict(..., strict=True) succeeds. + policy = RslRlPpoActorCriticCfg( + class_name="ActorCriticSRU", + init_noise_std=0.5, # ↓ vs 1.0: warm-start, less exploration noise + actor_hidden_dims=[512, 256, 128], + critic_hidden_dims=[512, 256, 128], + activation="elu", + rnn_hidden_size=512, + rnn_type="lstm_sru", + rnn_num_layers=1, + dropout=0.2, + num_cameras=1, + image_input_dims=(64, 5, 8), + height_input_dims=(64, 7, 7), + ) + + # Conservative fine-tuning hyperparameters: smaller LR, tighter clip, + # smaller KL target, lower grad-norm cap. + algorithm = RslRlPpoAlgorithmCfg( + class_name="PPO", + value_loss_coef=0.05, + use_clipped_value_loss=True, + clip_param=0.1, + value_clip_param=0.1, + entropy_coef=0.001, + num_learning_epochs=3, + num_mini_batches=4, + learning_rate=3.0e-4, + schedule="adaptive", + gamma=0.995, + lam=0.95, + desired_kl=0.005, + max_grad_norm=0.5, + ) + + +@configclass +class Go2NavPPORunnerDevCfg(Go2NavPPORunnerCfg): + """Dev cfg used by the smoke-test task (Isaac-Nav-PPO-Go2-Dev-v0). + + Unlike the production ``Go2NavPPORunnerCfg`` (whose hyperparameters are + deliberately conservative for warm-starting from a B2W checkpoint), the dev + cfg is meant for *from-scratch* Go2 training with the Odin1 camera. The + conservative FT settings (entropy_coef=0.001, desired_kl=0.005, clip=0.1, + lr=3e-4) caused exploration to collapse (noise_std plateaued at ~0.157) and + success to stall at ~0.5 by 23k iters. Here we re-open exploration and the + learning rate so the policy can escape that local optimum. + """ + + def __post_init__(self): + super().__post_init__() + self.max_iterations = 300 + self.experiment_name = "go2_navigation_ppo_dev" + self.logger = "tensorboard" + + # ---- Phase 1 (from-scratch, 0->2000): re-open exploration ---- + # init_noise_std only takes effect on a from-scratch run (a resumed + # run loads the std from the checkpoint, which was ~0.76 after Phase 1). + # Phase 1 broke the 0.5 plateau (success ~0.65, noise_std held at 0.76), + # but two issues appeared: (a) adaptive LR floored at 1e-5 because + # desired_kl=0.01 was too tight against clip=0.2/entropy=0.005, throttling + # late updates; (b) Loss/value_function spiked to ~127 around iter 1600. + # + # ---- Phase 2 (resume 2000->5000): refine & stabilise ---- + # Relax desired_kl so adaptive LR can climb off the 1e-5 floor, anneal + # exploration down, and tighten clip to curb the value-loss instability. + # + # ---- Phase 3 (resume 7000->14000, difficulty [0.2, 0.6]): ---- + # Kept Phase 2 hyperparams. Result: success 0.93, base_contact -71%, + # tip-over -76%. Confirmed depth is used and avoidance generalises when + # the task forces it. + # + # ---- Phase 4 (resume 14000->24000, difficulty [0.3, 0.8]): ---- + # noise_std fell to ~0.20 in Phase 3 (close to collapse). The Phase 4 + # difficulty jump (0.6 -> 0.8) demands fresh exploration on unseen + # terrain, so re-open entropy a notch. Result: success climbed 0 -> 0.88 + # (peak 0.91 @ iter 20519). But noise_std overshot to 0.33 by iter 23999, + # LR hit 1e-5 floor again, and success retreated from 0.905 -> 0.876. + # + # ---- Phase 5 (resume 24000->?, difficulty [0.3, 0.8]): refine ---- + # Anneal entropy back to let noise_std settle ~0.22-0.25 so the policy + # can stop trembling and finish the last refinement past 0.91 success. + self.policy.init_noise_std = 1.0 # only matters on a fresh run + self.algorithm.entropy_coef = 0.003 # 0.005 -> 0.003: anneal exploration for Phase 5 refinement + self.algorithm.desired_kl = 0.02 # 0.01 -> 0.02: let adaptive LR recover off the 1e-5 floor + self.algorithm.clip_param = 0.15 # 0.2 -> 0.15: smaller, more stable policy updates + self.algorithm.value_clip_param = 0.15 # 0.2 -> 0.15: match, curb value-loss spikes + self.algorithm.learning_rate = 1.0e-3 # adaptive ceiling reference + self.algorithm.num_learning_epochs = 5 # keep: more updates per batch + self.algorithm.max_grad_norm = 0.8 # 1.0 -> 0.8: tighten to damp the value-fn spike + + +@configclass +class Go2NavPPORunnerMixedCfg(Go2NavPPORunnerDevCfg): + """Cold-start hyperparameters for mixed-terrain training (maze + non_maze + + pits) on the full-size ``Isaac-Nav-PPO-Go2-v0`` task. + + Inherits from the Dev cfg (which already overrides the B2W-FT defaults to + something usable from scratch), but rolls the *exploration-heavy* knobs + BACK to the Phase 1/2 values that were proven to break the 0.5 plateau in + the dev curriculum, rather than the Phase 5 refinement settings the Dev cfg + currently sits at. + + Distilled lessons from the dev curriculum (see comments in + ``Go2NavPPORunnerDevCfg``): + * Phase 1 (entropy=0.005, init_std=1.0): broke success 0.5 -> 0.65 plateau + but kl=0.01 was too tight (LR floored at 1e-5). + * Phase 2 (kl=0.02, clip=0.15, epochs=5): unflored the LR and tamed the + Loss/value_function spike. + * Phase 5 (entropy=0.003): refinement-only, kills exploration too early + for a from-scratch run. + + Cold-start recipe = Phase 1 exploration + Phase 2 stability: + entropy=0.005, init_std=1.0, kl=0.02, clip=0.15, lr=1e-3, epochs=5, + grad_norm=0.8. + """ + + def __post_init__(self): + super().__post_init__() + # Independent experiment dir keeps mixed runs out of the dev TB tree. + self.experiment_name = "go2_navigation_ppo_mixed" + + # Override Dev's Phase 5 refinement back to cold-start values. + self.policy.init_noise_std = 1.0 # Phase 1: re-open exploration + self.algorithm.entropy_coef = 0.005 # Phase 1/4: cold-start exploration + self.algorithm.desired_kl = 0.02 # Phase 2: avoid 1e-5 LR floor + self.algorithm.clip_param = 0.15 # Phase 2: avoid value-loss spikes + self.algorithm.value_clip_param = 0.15 + self.algorithm.learning_rate = 1.0e-3 # adaptive ceiling + self.algorithm.num_learning_epochs = 5 + self.algorithm.max_grad_norm = 0.8 + + +@configclass +class Go2NavPPORunnerPureMazeCfg(Go2NavPPORunnerDevCfg): + """Hyperparameters for the pure-maze training task. + + Inherits the Phase 5 dev hyperparams (they shipped a strong checkpoint at + iter 27800 on the mixed terrain). Only the log directory differs so + pure-maze runs don't mix with the dev curriculum's TensorBoard history. + """ + + def __post_init__(self): + super().__post_init__() + self.experiment_name = "go2_navigation_ppo_puremaze" diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/navigation_env_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/navigation_env_cfg.py new file mode 100644 index 0000000..994d213 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/go2/navigation_env_cfg.py @@ -0,0 +1,445 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Unitree Go2 specific configuration for navigation environment.""" + +import os + +from isaaclab.utils import configclass +from isaaclab.managers import SceneEntityCfg + +from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg +import isaaclab_nav_task.navigation.mdp as mdp + +from isaaclab_nav_task.navigation.assets import GO2_CFG, ISAACLAB_NAV_TASKS_ASSETS_DIR # isort: skip + + +# Go2 has 12 leg joints (no wheels). Joint names use the underscore convention +# from the IsaacLab Go2 USD: FL_hip_joint, FL_thigh_joint, FL_calf_joint, ... +LEG_JOINT_NAMES = [".*_hip_joint", ".*_thigh_joint", ".*_calf_joint"] + + +@configclass +class Go2NavigationEnvCfg(NavigationEnvCfg): + """Navigation env for Unitree Go2 (legs-only quadruped). + + The locomotion checkpoint expected at + ``assets/data/Policies/locomotion/go2/policy_go2_jit.pt`` was converted from + a rsl_rl checkpoint trained on Isaac-Velocity-Flat-Unitree-Go2-v0: + - input : 48-dim observation (matches sru-navigation-sim's + LowLevelPolicyCfg) + - output : 12-dim joint position deltas (one per leg joint) + """ + + def __post_init__(self): + super().__post_init__() + + from isaaclab_nav_task.navigation.mdp.observations import initialize_depth_noise_generator + from isaaclab_nav_task.navigation.mdp.depth_utils.camera_config import get_camera_config + + initialize_depth_noise_generator(robot_name="go2", use_jit_precompiled=False) + camera_config = get_camera_config("go2") + # Camera resolution is consumed implicitly through the encoder; sru-nav + # always feeds (64, 40) into the VAE regardless of robot. + _ = camera_config + + # ---- Robot ---- + self.scene.robot = GO2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + # Go2's body link is named "base" in the IsaacLab USD (not "base_link" + # like B2W). + self.scene.raycast_camera.prim_path = "{ENV_REGEX_NS}/Robot/base" + # Real-robot Odin1 mount on Go2: 25.8 cm forward, 15.4 cm above body + # center, camera looking straight ahead (no pitch). + # NOTE: The extrinsic Tcl from the Odin1 calibration is camera-from-lidar, + # not camera-from-base. Until we have T_base_lidar (lidar pose in Go2 base + # frame), keep this measured mount offset rather than chaining Tcl. + self.scene.raycast_camera.offset.pos = (0.258, 0.0, 0.154) + self.scene.raycast_camera.offset.rot = (1.0, 0.0, 0.0, 0.0) + self.scene.height_scanner_critic.prim_path = "{ENV_REGEX_NS}/Robot/base" + + # ---- Camera intrinsics: Odin1 (LiDAR-aligned depth) ---- + # Real Odin1 @ 1600x1296: + # fx = 737.357, fy = 737.292, cx = 794.372, cy = 666.259 + # hFOV ~94.67 deg, vFOV ~82.65 deg + # To preserve the FOV while keeping the upstream downsample_factor=3 + # (raycast at 192x120 then downsample to the VAE-required 64x40), we + # scale the intrinsics linearly: + # fx_192 = 737.357 * 192/1600 = 88.48 px + # fy_120 = 737.292 * 120/1296 = 68.27 px + # cx_192 = 794.372 * 192/1600 = 95.32 px + # cy_120 = 666.259 * 120/1296 = 61.69 px + # Distortion (k2..k7) is ignored: raycast uses an ideal pinhole. The + # real-side pipeline must undistort before feeding the network. + # max_distance raised slightly because Odin1's wider FOV picks up more + # nearby clutter; keep 11 m to match upstream. + from isaaclab.sensors import patterns + self.scene.raycast_camera.max_distance = 11.0 + self.scene.raycast_camera.pattern_cfg = patterns.PinholeCameraPatternCfg.from_ros_camera_info( + fx=88.48, + fy=68.27, + cx=95.32, + cy=61.69, + width=192, + height=120, + downsample_factor=3, # 192x120 -> 64x40 to match VAE input + ) + + # ---- Goal placement ---- + # The default goal height offset (0.2-0.8 m above ground) is tuned for + # B2W's body height (~0.5-0.6 m). Go2 stands at ~0.3 m, so lower the + # range to (0.1, 0.4) m to keep the goal marker near the Go2 body. + # NOTE: success/termination is purely horizontal (xy), so this is mostly + # a visual fix + removes the small constant z-error in the 3D + # reach_goal_xy_soft reward term. + self.commands.robot_goal.goal_height_offset_range = (0.1, 0.4) + + # ---- Termination ---- + # Penalize/terminate if the body, hips, thighs, or head links hit + # something. Go2's main body is "base"; the front "head" is split into + # two extra rigid links ("Head_upper" / "Head_lower" in the upstream + # Unitree Go2 USD) which stick forward ~10cm past the base. Without + # those head links in the watch-list, GUI playback shows the snout + # visually crashing into walls while the base contact sensor stays + # silent and the episode does not terminate. Including them closes + # that loophole. + self.terminations.base_contact.params = { + "sensor_cfg": SceneEntityCfg( + "contact_forces", + body_names=["base", ".*_hip", ".*_thigh", "Head_upper", "Head_lower"], + ), + "threshold": 1.0, + } + + # Diagnostic-only: tighten `terrain_fall` so it actually fires when the + # robot drops into the pit terrain. The base default of -2.0m never + # triggered for Go2 (standing base_z ~+0.4m, typical pit depth 0.75-2.25m + # -> body z bottoms out around -1.1m, well above -2.0m), making + # `Episode_Termination/terrain_fall` permanently 0 across phases 1-5. + # -0.3m means: body must be ~0.7m below normal standing height to fire, + # which cleanly captures real pit falls without flagging walking dips. + # NOTE: `terrain_fall` is `time_out=True`, so it does NOT trigger the + # -50 `episode_termination` penalty -- this is purely a metric fix. + self.terminations.terrain_fall.params = {"fall_height_threshold": -0.3} + + # ---- Action interface (legs only, no wheels) ---- + self.actions.velocity_command.low_level_position_action = mdp.JointPositionActionCfg( + asset_name="robot", + joint_names=LEG_JOINT_NAMES, + scale=0.25, # MUST match the scale used to train policy_go2_jit.pt + use_default_offset=True, + ) + # Disable the velocity-action branch entirely (patched in + # navigation_se2_actions.py to be optional). + self.actions.velocity_command.low_level_velocity_action = None + self.actions.velocity_command.low_level_policy_file = os.path.join( + ISAACLAB_NAV_TASKS_ASSETS_DIR, + "Policies", "locomotion", "go2", "policy_go2_jit.pt", + ) + # SE2 command space scale: Go2 cannot match B2W's wheeled top speed, + # so we shrink the SRU command range to what Go2 can actually track. + # The high-level SRU policy was trained on B2W with [1.0, 1.0, 1.0]; we + # shrink each axis so the same network output produces feasible Go2 + # commands. + self.actions.velocity_command.scale = [0.6, 0.3, 0.7] + + # ---- Reward shaping ---- + self.rewards.joint_acc_l2_joint.params = { + "asset_cfg": SceneEntityCfg("robot", joint_names=LEG_JOINT_NAMES), + } + # Keep the B2W default termination penalty (-50.0). G0-G2 confirmed the + # Go2 locomotion JIT is stable enough that we do not need the relaxed + # -25 hedge anymore; restoring -50 makes wall hits / falls genuinely + # costly so the policy stops trading collisions for goal reward. + # (Only fires on `base_contact` + `large_pitch_angle`; `time_out`, + # `at_goal`, `terrain_fall` are all marked time_out=True and don't + # trigger this term.) + self.rewards.episode_termination.weight = -50.0 + + # Forward-facing depth camera only senses obstacles ahead of the robot. + # In G2.0 the agent learned to walk *backwards* (vx < 0) to hide obstacles + # from the camera and bypass forward-collision termination. Enable the + # backward-movement penalty (default weight is 0.0 in the base cfg). + # NOTE: the base CurriculumCfg disables this penalty after 500 global + # steps; if backward-walking re-emerges late in training, either delete + # ``curriculum.disable_backward_penalty`` or lift its ``disable_after_steps``. + self.rewards.backward_movement_penalty.weight = -1.0 + + # ---- Domain randomization ---- + # Go2 responds slower than wheels; widen the low-pass filter range. + self.events.randomize_low_pass_filter_alpha.params = { + "alpha_range": (0.3, 0.7), + "action_term": "velocity_command", + "per_dimension": True, + "alpha_range_vx": (0.3, 0.7), + "alpha_range_vy": (0.3, 0.7), + "alpha_range_omega": (0.3, 0.7), + } + + # ---- Terrain ---- + # The Go2 locomotion .pt is flat-trained, so start with easier terrain. + # Defaults assume RESUMING a non-trivial ckpt (max_init level 5, band + # [0.3, 0.8]). For a COLD START set GO2_DIFFICULTY="0.0,0.4" (and the + # env var GO2_INIT_LEVEL=0 if you want everyone to start at the easiest + # row), otherwise the policy gets dropped into mid-difficulty terrain + # and stalls. Curriculum stays ON in both cases so envs auto-promote + # toward the high end as they succeed. + lo, hi = 0.3, 0.8 + _diff = os.environ.get("GO2_DIFFICULTY", "").strip() + if _diff: + _parts = _diff.replace(" ", "").split(",") + lo, hi = float(_parts[0]), float(_parts[1]) + init_level = 5 + _lvl = os.environ.get("GO2_INIT_LEVEL", "").strip() + if _lvl: + init_level = int(_lvl) + self.scene.terrain.max_init_terrain_level = init_level + self.scene.terrain.terrain_generator.difficulty_range = [lo, hi] + self.scene.terrain.terrain_generator.curriculum = True + print(f"[Go2 Mixed] difficulty=[{lo}, {hi}], max_init_terrain_level={init_level} (curriculum on)") + + # Drop the dedicated stairs sub-terrain for Go2: the locomotion JIT is + # trained on flat ground only, climbing stairs is unreliable, and the + # platform_mask on stair tops would otherwise bias goal sampling + # towards stair platforms (see PositionSampler.platform_repeat_count=10 + # in mdp/navigation/goal_commands.py). + # NOTE: ``add_stairs_to_maze`` flag exists in HfMazeTerrainCfg but is + # never consumed by hf_terrains_maze.py, so the only real stair source + # is the ``"stairs"`` sub-terrain. We rebalance the remaining 3 to keep + # roughly the original maze:non_maze:pits ratio (3:2:2 -> ~0.43/0.29/0.29). + sub_terrains = self.scene.terrain.terrain_generator.sub_terrains + if "stairs" in sub_terrains: + del sub_terrains["stairs"] + if "maze" in sub_terrains: + sub_terrains["maze"].proportion = 0.43 + if "non_maze" in sub_terrains: + sub_terrains["non_maze"].proportion = 0.29 + if "pits" in sub_terrains: + sub_terrains["pits"].proportion = 0.28 + + # ---- Shrink tile size for 12 GB VRAM ---- + # Defaults: 30m x 30m tiles with horizontal_scale=0.1 -> 300x300 cells + # per tile heightfield, x 6 rows x 30 cols x 3 sub-terrains = ~16M + # heightfield cells + 3 sub-terrain collision meshes. On a 12 GB 5070 + # that OOMs above ~768 envs. Halve cell_size to 1.0m (matches what the + # PureMaze runs used, where 1024 envs ran stably): tile shrinks to + # 15m x 15m, heightfield drops 4x to ~4M cells. Override via env var + # GO2_CELL_SIZE if you want to go back to the paper-default 2.0m. + _cell = os.environ.get("GO2_CELL_SIZE", "1.0").strip() + if _cell: + new_cell = float(_cell) + for cfg_sub in sub_terrains.values(): + cfg_sub.cell_size = new_cell + # grid_size stays (15, 15) -> tile_size = 15 * cell_size meters. + tile_m = 15 * new_cell + self.scene.terrain.terrain_generator.size = (tile_m, tile_m) + print(f"[Go2 Mixed] cell_size={new_cell}m -> tile={tile_m}m " + f"(set GO2_CELL_SIZE=2.0 to restore paper defaults)") + + +@configclass +class Go2NavigationEnvCfg_DEV(Go2NavigationEnvCfg): + """Development configuration with smaller terrain and lower difficulty.""" + + def __post_init__(self): + super().__post_init__() + self.scene.terrain.terrain_generator.num_rows = 2 + self.scene.terrain.terrain_generator.num_cols = 30 + # The Go2 locomotion JIT is flat-trained. Starting at difficulty 0.3-0.8 + # with no curriculum produced ~16% tip-overs (large_pitch_angle) and + # stalled success at ~0.5. Start from the easiest terrain and let the + # curriculum ramp difficulty up as the policy succeeds. + # + # Phase 1/2 trained on [0.0, 0.4] (success ~0.86, depth confirmed used + # via ablation). Phase 3 raises the band so the avoidance behaviour + # generalises to denser obstacles / deeper pits. Control the band per + # run with DEV_DIFFICULTY="lo,hi" (default stays [0.0, 0.4]); e.g. + # DEV_DIFFICULTY="0.2,0.6" (recommended Phase 3 bridge) + # DEV_DIFFICULTY="0.3,0.8" (Phase 4, near paper level) + # max_init_terrain_level stays 0 so a resumed policy re-enters at the + # easy end of the new band and the curriculum re-ramps from there. + lo, hi = 0.0, 0.4 + _dev_diff = os.environ.get("DEV_DIFFICULTY", "").strip() + if _dev_diff: + _parts = _dev_diff.replace(" ", "").split(",") + lo, hi = float(_parts[0]), float(_parts[1]) + self.scene.terrain.max_init_terrain_level = 0 + self.scene.terrain.terrain_generator.difficulty_range = [lo, hi] + self.scene.terrain.terrain_generator.curriculum = True + print(f"[Go2 DEV] terrain difficulty_range = [{lo}, {hi}] (curriculum on)") + + +@configclass +class Go2NavigationEnvCfg_PureMaze(Go2NavigationEnvCfg): + """Pure-maze training configuration. + + All tiles are paper-style mazes: + * 100% ``maze`` sub-terrain (no ``non_maze`` / ``pits`` sub-terrains). + * Walls are uniform full-height rectangles (no randomized pillar/bar/cross + obstacles inserted into the maze pattern). + * Curriculum on, ramps difficulty from open to dense corridors. + + Env-var overrides: + * ``PUREMAZE_DIFFICULTY="lo,hi"``: difficulty band (default ``"0.0,1.0"``; + higher band -> denser corridors / more dead-ends). + * ``PUREMAZE_CELL_SIZE``: meters per maze cell (default 2.0). Lowering + tightens corridors; tile size scales accordingly so total terrain area + stays the same per tile in cells. + """ + + def __post_init__(self): + super().__post_init__() + + sub_terrains = self.scene.terrain.terrain_generator.sub_terrains + # Lock to 100% maze, paper-style walls. + for name in list(sub_terrains.keys()): + sub_terrains[name].proportion = 1.0 if name == "maze" else 0.0 + if "maze" in sub_terrains: + sub_terrains["maze"].randomize_wall = False + sub_terrains["maze"].random_wall_ratio = 0.0 + + # Difficulty range (curriculum on, ramps from easy to hard). + lo, hi = 0.0, 1.0 + _diff = os.environ.get("PUREMAZE_DIFFICULTY", "").strip() + if _diff: + _parts = _diff.replace(" ", "").split(",") + lo, hi = float(_parts[0]), float(_parts[1]) + self.scene.terrain.max_init_terrain_level = 0 + self.scene.terrain.terrain_generator.difficulty_range = [lo, hi] + self.scene.terrain.terrain_generator.curriculum = True + + # Cell size (corridor width). + _cell = os.environ.get("PUREMAZE_CELL_SIZE", "").strip() + if _cell: + new_cell = float(_cell) + for cfg_sub in sub_terrains.values(): + cfg_sub.cell_size = new_cell + tile_m = 15 * new_cell + self.scene.terrain.terrain_generator.size = (tile_m, tile_m) + print(f"[Go2 PureMaze] cell_size={new_cell}m -> tile={tile_m}m, " + f"corridor ~{new_cell * 0.6:.2f}-{new_cell * 0.9:.2f}m") + + # Terrain grid dimensions. Defaults are compact (3×10=30 tiles) to save + # VRAM; the original 6×30=180 tiles wasted mesh memory when most tiles + # were never visited (especially with few envs / play). Override via + # PUREMAZE_NUM_ROWS / PUREMAZE_NUM_COLS for large-scale training. + _rows = int(os.environ.get("PUREMAZE_NUM_ROWS", "3")) + _cols = int(os.environ.get("PUREMAZE_NUM_COLS", "10")) + self.scene.terrain.terrain_generator.num_rows = _rows + self.scene.terrain.terrain_generator.num_cols = _cols + + print(f"[Go2 PureMaze] 100% maze sub-terrain, classic walls, " + f"difficulty=[{lo}, {hi}] (curriculum on), " + f"grid={_rows}x{_cols}={_rows*_cols} tiles") + + +@configclass +class Go2NavigationEnvCfg_PLAY(Go2NavigationEnvCfg): + """Evaluation/visualization configuration.""" + + def __post_init__(self): + super().__post_init__() + + self.scene.num_envs = 20 + self.scene.env_spacing = 2.5 + self.scene.terrain.max_init_terrain_level = None + if self.scene.terrain.terrain_generator is not None: + self.scene.terrain.terrain_generator.num_rows = 2 + self.scene.terrain.terrain_generator.num_cols = 2 + + # ---- Evaluate on the SAME difficulty the policy was trained on ---- + # The base Go2NavigationEnvCfg uses difficulty_range=[0.3, 0.8], but + # the Dev curriculum (what model_*.pt was actually trained on) ran on + # [0.0, 0.4]. Replaying on [0.3, 0.8] shows the policy unseen-hard + # terrain and makes it look like it "can't avoid" obstacles. Default + # the PLAY difficulty to the training band for an honest read; allow + # an explicit stress-test override via PLAY_DIFFICULTY="lo,hi". + lo, hi = 0.0, 0.4 + _play_diff = os.environ.get("PLAY_DIFFICULTY", "").strip() + if _play_diff: + _parts = _play_diff.replace(" ", "").split(",") + lo, hi = float(_parts[0]), float(_parts[1]) + self.scene.terrain.terrain_generator.difficulty_range = [lo, hi] + # Fixed difficulty band for evaluation (no curriculum ramping). + self.scene.terrain.terrain_generator.curriculum = False + print(f"[Go2 PLAY] terrain difficulty_range = [{lo}, {hi}] (curriculum off)") + + # ---- Stress-test knobs for narrow-passage / dense-scene eval ---- + # PLAY_CELL_SIZE: meters per maze cell (default 2.0). Lowering this + # tightens corridor width without changing tile size: + # 2.0m -> 1.7m-2.0m open corridors (default; very wide for Go2) + # 1.5m -> 1.0m-1.3m corridors (Go2 fits comfortably with margin) + # 1.2m -> 0.7m-0.9m corridors (tight, real perception test) + # 1.0m -> 0.5m-0.7m corridors (Go2 body width ~0.3m -> very tight) + # NOTE: grid_size stays (15,15) so tile size shrinks proportionally + # (30m -> 15m at cell_size=1.0). To preserve outer terrain footprint, + # the tile size is rescaled below. + _play_cell = os.environ.get("PLAY_CELL_SIZE", "").strip() + # PLAY_MAZE_ONLY=1: force 100% maze sub-terrain (drop pits/non_maze) + # so every tile is a corridor navigation challenge -- no easy open + # tiles diluting the sample. + _maze_only = os.environ.get("PLAY_MAZE_ONLY", "").strip().lower() in ("1", "true", "yes") + + sub_terrains = self.scene.terrain.terrain_generator.sub_terrains + if _maze_only and "maze" in sub_terrains: + for name in list(sub_terrains.keys()): + sub_terrains[name].proportion = 1.0 if name == "maze" else 0.0 + print(f"[Go2 PLAY] PLAY_MAZE_ONLY=1 -> 100% maze sub-terrain") + + # PLAY_SUBTERRAIN_MIX="maze=0.5,non_maze=0.3,pits=0.2" + # Override any subset of sub-terrain proportions. Names not listed + # are left at their training-cfg default. Values do NOT need to sum + # to 1.0 (IsaacLab normalizes them internally before sampling). + # Setting a value to 0 effectively disables that sub-terrain. + _mix = os.environ.get("PLAY_SUBTERRAIN_MIX", "").strip() + if _mix: + overrides = {} + for part in _mix.split(","): + if "=" not in part: + continue + k, v = part.split("=", 1) + overrides[k.strip()] = float(v.strip()) + for name, prop in overrides.items(): + if name in sub_terrains: + sub_terrains[name].proportion = prop + else: + print(f"[Go2 PLAY] WARNING: unknown sub-terrain '{name}' " + f"(known: {list(sub_terrains.keys())})") + final = {n: sub_terrains[n].proportion for n in sub_terrains} + print(f"[Go2 PLAY] PLAY_SUBTERRAIN_MIX -> {final}") + + if _play_cell: + new_cell = float(_play_cell) + for cfg_sub in sub_terrains.values(): + cfg_sub.cell_size = new_cell + # Keep grid_size=(15,15) -> tile size = 15 * cell_size meters. + # Match outer tile size so the scene grid stays consistent. + tile_m = 15 * new_cell + self.scene.terrain.terrain_generator.size = (tile_m, tile_m) + print(f"[Go2 PLAY] PLAY_CELL_SIZE={new_cell}m -> tile={tile_m}m, " + f"corridor ~{new_cell * 0.6:.2f}-{new_cell * 0.9:.2f}m") + + # PLAY_CLASSIC_MAZE=1: reproduce paper-style mazes with uniform + # rectangular walls and clear corridors (no randomized pillar / bar + # / cross obstacles inserted into the maze pattern). Affects only + # the `maze` sub-terrain since `non_maze` and `pits` rely on the + # randomized shapes for their gameplay. + _classic = os.environ.get("PLAY_CLASSIC_MAZE", "").strip().lower() in ("1", "true", "yes") + if _classic and "maze" in sub_terrains: + sub_terrains["maze"].randomize_wall = False + sub_terrains["maze"].random_wall_ratio = 0.0 + print(f"[Go2 PLAY] PLAY_CLASSIC_MAZE=1 -> maze walls are full-height " + f"rectangles (no randomized obstacle shapes)") + + self.observations.policy.enable_corruption = False + self.events.base_external_force_torque = None + self.events.push_robot = None + + # Visualize the depth-camera ray hits + height scanner grid in the GUI. + # The RayCasterCamera draws a point per ray that hits geometry; the + # density / pattern of these points is the effective FOV / resolution. + self.scene.raycast_camera.debug_vis = True + if self.scene.height_scanner_critic is not None: + self.scene.height_scanner_critic.debug_vis = True diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/rl_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/rl_cfg.py new file mode 100644 index 0000000..585ca9b --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/config/rl_cfg.py @@ -0,0 +1,172 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Custom RSL-RL configuration classes for navigation tasks. + +These config classes replace the standard Isaac Lab RL configs to support +custom network architectures used in navigation tasks with depth camera inputs. +""" + +from dataclasses import MISSING +from typing import Literal, Optional + +from isaaclab.utils import configclass + + +@configclass +class RslRlPpoActorCriticCfg: + """Configuration for the PPO actor-critic networks with navigation extensions.""" + + class_name: str = "ActorCritic" + """The policy class name. Default is ActorCritic.""" + + init_noise_std: float = MISSING + """The initial noise standard deviation for the policy.""" + + actor_hidden_dims: list[int] = MISSING + """The hidden dimensions of the actor network.""" + + critic_hidden_dims: list[int] = MISSING + """The hidden dimensions of the critic network.""" + + activation: str = MISSING + """The activation function for the actor and critic networks.""" + + rnn_type: str = "lstm" + """The type of RNN to use.""" + + rnn_hidden_size: int = 256 + """The hidden size of the RNN.""" + + rnn_num_layers: int = 1 + """The number of layers in the RNN.""" + + dropout: float = 0.0 + """The dropout rate for the first layer of the actor and critic networks.""" + + # Visual inputs + num_cameras: int = 1 + """Number of depth cameras encoded into the observation (1 or 2).""" + + image_input_dims: tuple[int, int, int] = (64, 5, 8) + """Encoded depth feature shape as (C, H, W).""" + + height_input_dims: tuple[int, int, int] = (64, 7, 7) + """Encoded height scan feature shape as (C, H, W). Default is (64, 7, 7) for 64*7*7=3136 features.""" + + +@configclass +class RslRlPpoAlgorithmCfg: + """Configuration for the PPO algorithm.""" + + class_name: str = MISSING + """The algorithm class name. Default is PPO.""" + + value_loss_coef: float = MISSING + """The coefficient for the value loss.""" + + use_clipped_value_loss: bool = MISSING + """Whether to use clipped value loss.""" + + clip_param: float = MISSING + """The clipping parameter for the policy.""" + + value_clip_param: float = 0.2 + """The value clipping parameter. Default is 0.2.""" + + entropy_coef: float = MISSING + """The coefficient for the entropy loss.""" + + num_learning_epochs: int = MISSING + """The number of learning epochs per update.""" + + num_mini_batches: int = MISSING + """The number of mini-batches per update.""" + + learning_rate: float = MISSING + """The learning rate for the policy.""" + + schedule: str = MISSING + """The learning rate schedule.""" + + gamma: float = MISSING + """The discount factor.""" + + lam: float = MISSING + """The lambda parameter for Generalized Advantage Estimation (GAE).""" + + desired_kl: float = MISSING + """The desired KL divergence.""" + + max_grad_norm: float = MISSING + """The maximum gradient norm.""" + + +@configclass +class RslRlOnPolicyRunnerCfg: + """Configuration of the runner for on-policy algorithms.""" + + seed: Optional[int] = 42 + """The seed for the experiment. Default is 42.""" + + device: str = "cuda:0" + """The device for the rl-agent. Default is cuda:0.""" + + num_steps_per_env: int = MISSING + """The number of steps per environment per update.""" + + max_iterations: int = MISSING + """The maximum number of iterations.""" + + empirical_normalization: bool = MISSING + """Whether to use empirical normalization.""" + + policy: RslRlPpoActorCriticCfg = MISSING + """The policy configuration.""" + + algorithm: RslRlPpoAlgorithmCfg = MISSING + """The algorithm configuration.""" + + reward_shifting_value: float = 0.0 + """The value to shift the reward by. Default is 0.0.""" + + ## + # Checkpointing parameters + ## + + save_interval: int = MISSING + """The number of iterations between saves.""" + + experiment_name: str = MISSING + """The experiment name.""" + + run_name: str = "" + """The run name. Default is empty string.""" + + ## + # Logging parameters + ## + + logger: Literal["tensorboard", "neptune", "wandb"] = "tensorboard" + """The logger to use. Default is tensorboard.""" + + neptune_project: str = "isaaclab" + """The neptune project name. Default is "isaaclab".""" + + wandb_project: str = "isaaclab" + """The wandb project name. Default is "isaaclab".""" + + ## + # Loading parameters + ## + + resume: bool = False + """Whether to resume. Default is False.""" + + load_run: str = ".*" + """The run directory to load. Default is ".*" (all).""" + + load_checkpoint: str = "model_.*.pt" + """The checkpoint file to load. Default is "model_.*.pt" (all).""" diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/__init__.py new file mode 100644 index 0000000..cb3b432 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""MDP components for navigation tasks. + +This module provides observations, rewards, terminations, curriculums, +and actions specific to navigation tasks. +""" + +from isaaclab.envs.mdp import * # noqa: F401, F403 + +from .curriculums import * # noqa: F401, F403 +from .events import * # noqa: F401, F403 +from .rewards import * # noqa: F401, F403 +from .terminations import * # noqa: F401, F403 +from .observations import * # noqa: F401, F403 +from .navigation import * # noqa: F401, F403 +from .delay_manager import ObservationDelayManager, ObservationDelayManagerCfg, DelayBufferState # noqa: F401 diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/curriculums.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/curriculums.py new file mode 100644 index 0000000..6ef4e3f --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/curriculums.py @@ -0,0 +1,56 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Curriculum functions for navigation tasks. + +The functions can be passed to the :class:`isaaclab.managers.CurriculumTermCfg` object to enable +the curriculum introduced by the function. +""" +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +def disable_backward_penalty_after_steps( + env: ManagerBasedRLEnv, + env_ids: Sequence[int], + term_name: str = "backward_movement_penalty", + num_steps: int = 1000 +) -> torch.Tensor: + """Curriculum that disables the backward movement penalty after a certain number of steps. + + This helps with early training by preventing backward movement, but removes the constraint + later to allow more natural movement patterns. + + Args: + env: The learning environment. + env_ids: Not used since all environments are affected. + term_name: The name of the backward movement penalty term. + num_steps: The number of steps after which the penalty should be disabled. + + Returns: + Current step counter as float for logging purposes. + """ + if env.common_step_counter > num_steps: + # Check if the term exists and has a non-zero weight + if hasattr(env.reward_manager, 'get_term_cfg'): + try: + term_cfg = env.reward_manager.get_term_cfg(term_name) + if term_cfg.weight != 0.0: + # Disable the penalty by setting weight to 0 + term_cfg.weight = 0.0 + env.reward_manager.set_term_cfg(term_name, term_cfg) + print(f"Disabled backward movement penalty at step {env.common_step_counter}") + except KeyError: + # Term doesn't exist, which is fine + pass + + return torch.tensor(float(env.common_step_counter)) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/custom_noise.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/custom_noise.py new file mode 100644 index 0000000..f672149 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/custom_noise.py @@ -0,0 +1,106 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Custom noise configurations for navigation tasks.""" +from __future__ import annotations + +import torch +from typing import TYPE_CHECKING + +from isaaclab.utils import configclass +from isaaclab.utils.math import quat_from_euler_xyz, transform_points +from isaaclab.utils.noise import NoiseCfg + +if TYPE_CHECKING: + pass + + +@torch.jit.script +def goal_to_xyz(goal: torch.Tensor) -> torch.Tensor: + """Convert goal in (direction, log distance) format to (x, y, z) coordinates.""" + direction = goal[:, :3] # Extract directional vector + distance = torch.exp(goal[:, 3]) - 1 # Convert log distance back to distance + return direction * distance.unsqueeze(-1) # Scale direction by distance + + +@torch.jit.script +def xyz_to_goal(xyz: torch.Tensor) -> torch.Tensor: + """Convert (x, y, z) coordinates to (direction, log distance) format.""" + distance = torch.norm(xyz, dim=1, keepdim=True) + 1e-6 # Calculate distance + direction = xyz / distance # Normalize to get directional vector + distance = torch.log(1 + distance) # Convert distance to log distance + return torch.cat([direction, distance], dim=1) # Concatenate direction and log distance + + +@torch.inference_mode() +def delta_transformation_noise(data: torch.Tensor, cfg: "DeltaTransformationNoiseCfg") -> torch.Tensor: + """Delta transformation noise involving random rotation and translation. + + The output is returned in a new tensor (instead of modifying 'data' in-place). + """ + # Ensure the data has the shape (..., 3) for 3D coordinates, or (direction, log distance) + if data.shape[-1] not in (3, 4): + raise ValueError( + "Data must have shape (..., 3) for 3D coordinates, or (..., 4) for (direction, log distance)." + ) + + # Determine whether data is in (direction, log distance) format + unit_vec = data.shape[-1] == 4 + + # Convert to (x, y, z) if needed + if unit_vec: + coordinate = goal_to_xyz(data) + else: + coordinate = data + + # Generate small rotation noise (Rx, Ry, Rz) using uniform distribution + rotation_noise = torch.empty((data.shape[0], 3), device=data.device).uniform_(-cfg.rotation, cfg.rotation) + + # Convert Euler angles (Rx, Ry, Rz) to quaternions + quat_noise = quat_from_euler_xyz(rotation_noise[:, 0], rotation_noise[:, 1], rotation_noise[:, 2]) + + # Generate small translation noise (Tx, Ty, Tz) using uniform distribution + translation_noise = torch.empty((data.shape[0], 3), device=data.device).uniform_(-cfg.translation, cfg.translation) + + # Apply random rotation + translation + transformed_data = transform_points(coordinate.unsqueeze(1), translation_noise, quat_noise).squeeze(1) + + # If input was in goal format, convert back + if unit_vec: + transformed_data = xyz_to_goal(transformed_data) + + # Randomly apply the noise based on the probability + random_mask = torch.rand(data.shape[0], device=data.device) < cfg.noise_prob + + # Use torch.where to select transformed values on the mask + random_mask_expanded = random_mask.unsqueeze(-1) + output = torch.where(random_mask_expanded, transformed_data, data) + + if cfg.remove_dist: + if unit_vec: + # Zero out the distance component by directly assigning 0 + output[..., 3:] = 0 + else: + # Normalize the vector by its norm (avoiding division by zero) + norm = torch.norm(output, dim=-1, keepdim=True) + 1e-6 + output = output / norm + + return output + + +@configclass +class DeltaTransformationNoiseCfg(NoiseCfg): + """Configuration for small delta transformation noise involving rotation and translation.""" + + func = delta_transformation_noise + + rotation: float = 0.1 + """The maximum rotation angle in radians. Defaults to 0.1.""" + translation: float = 0.5 + """The maximum translation in meters. Defaults to 0.5.""" + noise_prob: float = 0.25 + """The probability of applying the noise. Defaults to 0.25.""" + remove_dist: bool = False + """Whether to remove the distance from the output. Defaults to False.""" diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/delay_manager.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/delay_manager.py new file mode 100644 index 0000000..6415d0b --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/delay_manager.py @@ -0,0 +1,272 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Standalone observation delay manager for simulating sensor delays.""" +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field + +import torch + +from isaaclab.utils import DelayBuffer, configclass + + +@configclass +class ObservationDelayManagerCfg: + """Configuration for the observation delay manager. + + This configuration controls the simulation of sensor delays, where each environment + can have a different random delay sampled from [0, max_delay] at episode reset. + """ + + enabled: bool = True + """Whether to enable delay simulation for observations.""" + + max_delay_lin_vel: int = 2 + """Maximum delay in timesteps for linear velocity observations.""" + + max_delay_ang_vel: int = 2 + """Maximum delay in timesteps for angular velocity observations.""" + + max_delay_projected_gravity: int = 2 + """Maximum delay in timesteps for projected gravity observations.""" + + max_delay_target_position: int = 2 + """Maximum delay in timesteps for target position/goal observations.""" + + max_delay_depth: int = 2 + """Maximum delay in timesteps for depth image observations.""" + + +@dataclass +class DelayBufferState: + """Container for a delay buffer and its associated time lags. + + This encapsulates the state needed for delayed observations: + - The buffer storing historical data + - Per-environment time lags (delays) + - Maximum delay configured for this buffer + """ + + buffer: DelayBuffer + time_lags: torch.Tensor + max_delay: int + + def compute(self, data: torch.Tensor) -> torch.Tensor: + """Append data and return delayed version.""" + return self.buffer.compute(data) + + def reset(self, env_ids: Sequence[int] | None = None): + """Reset buffer for specified environments.""" + self.buffer.reset(env_ids) + + def randomize_lags(self, env_ids: torch.Tensor, device: str): + """Randomize time lags for specified environments.""" + new_lags = torch.randint(0, self.max_delay + 1, (len(env_ids),), dtype=torch.int, device=device) + self.time_lags[env_ids] = new_lags + env_ids_list = env_ids.tolist() if env_ids is not None else None + self.buffer.set_time_lag(new_lags, env_ids_list) + + def set_lags(self, time_lags: torch.Tensor, env_ids: torch.Tensor | None = None): + """Set time lags for specified environments.""" + if env_ids is None: + self.time_lags[:] = time_lags + self.buffer.set_time_lag(time_lags) + else: + self.time_lags[env_ids] = time_lags + self.buffer.set_time_lag(time_lags, env_ids.tolist()) + + +class ObservationDelayManager: + """Standalone manager for simulating observation delays. + + This manager can be added to any environment to simulate sensor delays + without coupling to a specific action term. Each observation type can + have its own delay buffer with per-environment random delays. + + Usage: + # In environment config or __init__: + self.delay_manager = ObservationDelayManager(cfg, num_envs, device) + + # In observation functions: + delayed_vel = env.delay_manager.compute_delayed_lin_vel(current_vel) + + # On episode reset: + env.delay_manager.reset(env_ids) + env.delay_manager.randomize_lags(env_ids) + """ + + def __init__(self, cfg: ObservationDelayManagerCfg, num_envs: int, device: str): + """Initialize the observation delay manager. + + Args: + cfg: Configuration for delay buffers. + num_envs: Number of parallel environments. + device: Device for tensor operations. + """ + self.cfg = cfg + self.num_envs = num_envs + self.device = device + self._delay_enabled = cfg.enabled + + self._init_delay_buffers() + + def _create_delay_buffer_state(self, max_delay: int) -> DelayBufferState: + """Create a DelayBufferState with initialized buffer and random time lags.""" + buffer = DelayBuffer(max_delay, batch_size=self.num_envs, device=self.device) + time_lags = torch.randint(0, max_delay + 1, (self.num_envs,), dtype=torch.int, device=self.device) + buffer.set_time_lag(time_lags) + return DelayBufferState(buffer=buffer, time_lags=time_lags, max_delay=max_delay) + + def _init_delay_buffers(self): + """Initialize all delay buffers based on configuration.""" + if not self.cfg.enabled: + # No delays - set all delay states to None + self._delay_lin_vel: DelayBufferState | None = None + self._delay_ang_vel: DelayBufferState | None = None + self._delay_projected_gravity: DelayBufferState | None = None + self._delay_target_position: DelayBufferState | None = None + self._delay_depth_buffers: dict[str, DelayBufferState] = {} + self._max_delay_depth = 0 + return + + # Initialize delay buffer states for each observation type + self._delay_lin_vel = self._create_delay_buffer_state(self.cfg.max_delay_lin_vel) + self._delay_ang_vel = self._create_delay_buffer_state(self.cfg.max_delay_ang_vel) + self._delay_projected_gravity = self._create_delay_buffer_state(self.cfg.max_delay_projected_gravity) + self._delay_target_position = self._create_delay_buffer_state(self.cfg.max_delay_target_position) + # Depth buffers are created dynamically per camera + self._delay_depth_buffers: dict[str, DelayBufferState] = {} + self._max_delay_depth = self.cfg.max_delay_depth + + @property + def enabled(self) -> bool: + """Whether delay simulation is enabled.""" + return self._delay_enabled + + def get_or_create_depth_delay_buffer(self, camera_name: str) -> DelayBufferState: + """Get or create a delay buffer for a specific depth camera. + + Args: + camera_name: Name of the depth camera sensor. + + Returns: + DelayBufferState for the specified camera. + """ + if camera_name not in self._delay_depth_buffers: + self._delay_depth_buffers[camera_name] = self._create_delay_buffer_state(self._max_delay_depth) + return self._delay_depth_buffers[camera_name] + + def reset(self, env_ids: torch.Tensor): + """Reset all delay buffers for specified environments. + + Args: + env_ids: Environment indices to reset. + """ + env_ids_list = env_ids.tolist() if env_ids is not None else None + + if self._delay_lin_vel is not None: + self._delay_lin_vel.reset(env_ids_list) + if self._delay_ang_vel is not None: + self._delay_ang_vel.reset(env_ids_list) + if self._delay_projected_gravity is not None: + self._delay_projected_gravity.reset(env_ids_list) + if self._delay_target_position is not None: + self._delay_target_position.reset(env_ids_list) + + # Reset all depth buffers + for depth_buffer in self._delay_depth_buffers.values(): + depth_buffer.reset(env_ids_list) + + def randomize_lags(self, env_ids: torch.Tensor): + """Randomize time lags for all delay buffers. + + Args: + env_ids: Environment indices to randomize. + """ + if self._delay_lin_vel is not None: + self._delay_lin_vel.randomize_lags(env_ids, self.device) + if self._delay_ang_vel is not None: + self._delay_ang_vel.randomize_lags(env_ids, self.device) + if self._delay_projected_gravity is not None: + self._delay_projected_gravity.randomize_lags(env_ids, self.device) + if self._delay_target_position is not None: + self._delay_target_position.randomize_lags(env_ids, self.device) + + # Randomize all depth buffers + for depth_buffer in self._delay_depth_buffers.values(): + depth_buffer.randomize_lags(env_ids, self.device) + + # ============================================================================ + # Delayed observation computation methods + # ============================================================================ + + def compute_delayed_lin_vel(self, lin_vel: torch.Tensor) -> torch.Tensor: + """Compute delayed linear velocity observation. + + Args: + lin_vel: Current linear velocity tensor of shape (num_envs, 3). + + Returns: + Delayed linear velocity, or original if delays disabled. + """ + if self._delay_lin_vel is None: + return lin_vel + return self._delay_lin_vel.compute(lin_vel) + + def compute_delayed_ang_vel(self, ang_vel: torch.Tensor) -> torch.Tensor: + """Compute delayed angular velocity observation. + + Args: + ang_vel: Current angular velocity tensor of shape (num_envs, 3). + + Returns: + Delayed angular velocity, or original if delays disabled. + """ + if self._delay_ang_vel is None: + return ang_vel + return self._delay_ang_vel.compute(ang_vel) + + def compute_delayed_projected_gravity(self, projected_gravity: torch.Tensor) -> torch.Tensor: + """Compute delayed projected gravity observation. + + Args: + projected_gravity: Current projected gravity tensor of shape (num_envs, 3). + + Returns: + Delayed projected gravity, or original if delays disabled. + """ + if self._delay_projected_gravity is None: + return projected_gravity + return self._delay_projected_gravity.compute(projected_gravity) + + def compute_delayed_target_position(self, target_position: torch.Tensor) -> torch.Tensor: + """Compute delayed target position observation. + + Args: + target_position: Current target position tensor. + + Returns: + Delayed target position, or original if delays disabled. + """ + if self._delay_target_position is None: + return target_position + return self._delay_target_position.compute(target_position) + + def compute_delayed_depth(self, depth_features: torch.Tensor, camera_name: str) -> torch.Tensor: + """Compute delayed depth observation for a specific camera. + + Args: + depth_features: Encoded depth features of shape (num_envs, feature_dim). + camera_name: Name of the camera sensor. + + Returns: + Delayed depth features, or original if delays disabled. + """ + if not self._delay_enabled: + return depth_features + delay_buffer = self.get_or_create_depth_delay_buffer(camera_name) + return delay_buffer.compute(depth_features) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_noise_encoder.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_noise_encoder.py new file mode 100644 index 0000000..f5859ac --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_noise_encoder.py @@ -0,0 +1,332 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT +"""Depth noise encoder module for visual navigation. + +This module provides a VAE-based depth encoder with realistic stereo depth noise simulation. +""" +import os +from collections import OrderedDict +from typing import Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.models import regnet_x_400mf +from torchvision.ops import Conv2dNormActivation, FeaturePyramidNetwork + +from isaaclab_assets import ISAACLAB_ASSETS_DATA_DIR + +from .camera_config import CameraConfig + +# Default camera configuration (ZedX Camera for b2w and aow d) +DEFAULT_CAMERA_CONFIG = CameraConfig( + focal_length=25.0, + baseline=0.12, + min_depth=0.25, + max_depth=10.0, + depth_encoder_path=os.path.join(str(ISAACLAB_ASSETS_DATA_DIR), "Policies", "RSL-ETHZ/AoW_d/depth_encoder", "vae_pretrain_fuse.pth") +) + +class VAESampler(nn.Module): + def __init__(self, input_dim, latent_dim): + super(VAESampler, self).__init__() + self.input_dim = input_dim + self.latent_dim = latent_dim + self.conv = Conv2dNormActivation(input_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False) + + # Convolutional Layers for 2D mean and logvar + self.mean_layers = nn.Sequential( + Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False), + nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0) + ) + + self.logvar_layers = nn.Sequential( + Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False), + nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0) + ) + + def reparameterize(self, mu, logvar): + std = torch.exp(0.5 * logvar) + eps = torch.randn_like(std) + return mu + eps * std + + def forward(self, x): + x = self.conv(x) + x = self.mean_layers(x) + return x + +class EncoderFPN(nn.Module): + def __init__(self, in_channel, out_channel): + super(EncoderFPN, self).__init__() + encoder = regnet_x_400mf(weights=None) + # Remove classification head from the encoder + encoder = nn.Sequential(*list(encoder.children())[:-2]) + # Modify the first layer to accept the number of channels in the input image + encoder[0][0] = nn.Conv2d(in_channel, 32, kernel_size=3, stride=2, padding=1, bias=False) + self.enc = encoder[0] + self.enc_1 = encoder[1][:2] + self.enc_2 = encoder[1][2] + self.enc_3 = encoder[1][3] + + # Feature Pyramid Network + self.fpn = FeaturePyramidNetwork([64, 160, 400], out_channel) + + def forward(self, x): + raise NotImplementedError("Forward method must be implemented in the child class.") + + +class DepthEncoder(EncoderFPN): + """Depth image encoder using Feature Pyramid Network.""" + def __init__(self, out_channel): + super(DepthEncoder, self).__init__(1, out_channel) + + def forward(self, x): + # check if depth has channel dimension + if x.dim() == 3: + x = x.unsqueeze(1) + + out = OrderedDict() + x = self.enc(x) + out['feat1'] = self.enc_1(x) + out['feat2'] = self.enc_2(out['feat1']) + out['feat3'] = self.enc_3(out['feat2']) + + out = self.fpn(out) + + return out['feat1'] + + +class VAEDecoder(nn.Module): + def __init__(self, input_dim, out_dim): + super(VAEDecoder, self).__init__() + self.input_dim = input_dim + self.conv = Conv2dNormActivation(input_dim, input_dim, kernel_size=3, stride=1, padding=1, bias=False) + + self.decoder = nn.Sequential( + # Layer 0 + nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False), + nn.BatchNorm2d(input_dim), + nn.ReLU(inplace=True), + # Layer 1 + nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False), + nn.BatchNorm2d(input_dim), + nn.ReLU(inplace=True), + # Layer 2 + nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False), + nn.BatchNorm2d(input_dim), + nn.ReLU(inplace=True), + # Final Output Layer + nn.Conv2d(input_dim, out_dim, kernel_size=3, stride=1, padding=1) + ) # Expand the spatial dimensions by a factor of 2**4=16 + + def forward(self, z): + z = self.conv(z) + img = self.decoder(z) + return img + +class DepthDecoder(VAEDecoder): + def __init__(self, input_dim): + super(DepthDecoder, self).__init__(input_dim, 1) + +class VAENet(nn.Module): + def __init__(self, latent_dim): + super(VAENet, self).__init__() + self.depth_encoder = DepthEncoder(latent_dim) + + self.vae_sampler = VAESampler(latent_dim, latent_dim) + + self.depth_decoder = DepthDecoder(latent_dim) + + def forward(self, x): + x = self.depth_encoder(x) + x = self.vae_sampler(x) + return x + + def decode(self, z): + return self.depth_decoder(z) + +class DepthNoise(torch.nn.Module): + def __init__(self, + focal_length, + baseline, + min_depth, + max_depth, + filter_size=3, + inlier_thred_range=(0.01, 0.05), + prob_range=(0.4, 0.6), + invalid_disp=1e7 + ): + """ + A Simply PyTorch module to add realistic noise to depth images. + + Args: + focal_length (float): Focal length of the camera (in pixels). + baseline (float): Baseline distance between stereo cameras (in meters). + min_depth (float): Minimum depth value after clamping. + max_depth (float): Maximum depth value after clamping. + filter_size (int): Kernel size for local mean disparity computation. (tuning based on image resolution) + inlier_thred_range (tuple): Threshold range for normalized disparity differences. + prob_range (tuple): Probability range for matching pixels. + invalid_disp (float): Invalid disparity + + """ + super().__init__() + self.focal_length = focal_length + self.baseline = baseline + self.min_depth = min_depth + self.max_depth = max_depth + self.invalid_disp = invalid_disp + self.inlier_thred_range = inlier_thred_range + self.prob_range = prob_range + self.filter_size = filter_size + + weights, substitutes = self._compute_weights(filter_size) + self.register_buffer('weights', weights.view(1, 1, filter_size, filter_size)) + self.register_buffer('substitutes', substitutes.view(1, 1, filter_size, filter_size)) + + + def _compute_weights(self, filter_size): + """ + Compute weights and substitutes for disparity filtering. + + Args: + filter_size (int): Kernel size for local mean disparity computation. + """ + center = filter_size // 2 + idx = torch.arange(filter_size) - center + x_filter, y_filter = torch.meshgrid(idx, idx, indexing='ij') + sqr_radius = x_filter ** 2 + y_filter ** 2 + sqrt_radius = torch.sqrt(sqr_radius) + weights = 1 / torch.where(sqr_radius == 0, torch.ones_like(sqrt_radius), sqrt_radius) + weights = weights / weights.sum() + fill_weights = 1 / (1 + sqrt_radius) + fill_weights = torch.where(sqr_radius > filter_size, -1.0, fill_weights) + substitutes = (fill_weights > 0).float() + + return weights, substitutes + + def filter_disparity(self, disparity): + """ + Filter the disparity map using local mean disparity. + + Args: + disparity (torch.Tensor): Input disparity map tensor of shape (B, C, H, W). + """ + B, _, H, W = disparity.shape + device = disparity.device + center = self.filter_size // 2 + + output_disparity = torch.full_like(disparity, self.invalid_disp) + + prob = torch.rand(B, 1, 1, 1, device=device) * (self.prob_range[1] - self.prob_range[0]) + self.prob_range[0] + random_mask = (torch.rand(B, 1, H, W, device=device) < prob) + + # Compute mean disparity + weighted_disparity = F.conv2d(disparity, self.weights, padding=center) + + # Compute differences + differences = torch.abs(disparity - weighted_disparity) + + # Normalize differences based on current image statistics for consistent thresholding + differences_flat = differences.view(B, -1) # Flatten spatial dimensions + mean_diff = torch.mean(differences_flat, dim=1, keepdim=True) + std_diff = torch.std(differences_flat, dim=1, keepdim=True) + 1e-6 # Add epsilon to avoid division by zero + + # Normalize differences: (diff - mean) / std, then shift to [0, 1] range approximately + normalized_differences_flat = (differences_flat - mean_diff) / std_diff + normalized_differences = normalized_differences_flat.view_as(differences) + + # Use parameter-based threshold on normalized differences + threshold = torch.rand(B, 1, 1, 1, device=device) * (self.inlier_thred_range[1] - self.inlier_thred_range[0]) + self.inlier_thred_range[0] + update_mask = (normalized_differences < threshold) & random_mask + + # Compute output value: round with 1/32 precision + disparity = torch.round(disparity * 32.0) / 32.0 + + # Update output disparity + output_disparity = torch.where(update_mask, disparity, output_disparity) + + # Apply substitutes to fill neighboring pixels + filled_values = F.conv2d(update_mask.float() * disparity, self.substitutes, padding=center) + counts = F.conv2d(update_mask.float(), self.substitutes, padding=center) + 1e-9 + average_filled_values = filled_values / counts + output_disparity = torch.where(counts >= 1, average_filled_values, output_disparity) + + return output_disparity + + def forward(self, depth, add_noise: bool) -> torch.Tensor: + # correct input shape + if len(depth.shape) == 3: + depth = depth.unsqueeze(1) # add channel dimension + + # check dimension (B, 1, H, W) + assert depth.shape[1] == 1, "Input depth tensor must have shape (B, 1, H, W)." + assert len(depth.shape) == 4, "Input depth tensor must have shape (B, 1, H, W)." + + if add_noise: + # Clamp the depth values + depth = torch.clamp(depth, min=1. / self.invalid_disp) + + # Step 1: Convert depth to disparity + disparity = self.focal_length * self.baseline / depth + + # Step 2: Filter the disparity map + filtered_disparity = self.filter_disparity(disparity) + + # Step 3: Recompute depth from disparity + depth = self.focal_length * self.baseline / filtered_disparity + + # Step 4: Clamp the depth values + depth[depth < self.min_depth] = 0.0 + + # Step 5: Set invalid depth values to 0.0 (values outside valid range are not measurable) + depth[depth > self.max_depth] = 0.0 + + return depth + + +class DepthNoiseEncoder(torch.nn.Module): + def __init__(self, + feature_dim, + camera_config: CameraConfig = None + ): + """ + A Simply PyTorch module to add realistic noise to depth images. + + Args: + feature_dim (int): Number of output channels from the encoder. + camera_config (CameraConfig, optional): Camera configuration parameters. + If None, uses DEFAULT_CAMERA_CONFIG. + """ + super().__init__() + + # Use provided config or default + if camera_config is None: + camera_config = DEFAULT_CAMERA_CONFIG + + self.camera_config = camera_config + self.depth_noise = DepthNoise( + focal_length=camera_config.focal_length, + baseline=camera_config.baseline, + min_depth=camera_config.min_depth, + max_depth=camera_config.max_depth + ) + + self.encoder = VAENet(feature_dim) + + try: + self.encoder.load_state_dict(torch.load(camera_config.depth_encoder_path, weights_only=True), strict=True) + print('\033[92m' + f'Successfully loaded pre-trained weights from {camera_config.depth_encoder_path}' + '\033[0m') + except Exception as e: + print('\033[91m' + f'Failed to load pre-trained weights: {e}' + '\033[0m') + + def forward(self, depth: torch.Tensor, add_noise: bool = True) -> Tuple[torch.Tensor, torch.Tensor]: + noisy_depth = self.depth_noise(depth, add_noise) + encoded_depth = self.encoder(noisy_depth) # (B, 1, H, W) -> (B, C, H//8, W//8) + return encoded_depth, noisy_depth + + @torch.jit.export + def decode(self, z: torch.Tensor) -> torch.Tensor: + return self.encoder.decode(z) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_utils/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_utils/__init__.py new file mode 100644 index 0000000..678a229 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_utils/__init__.py @@ -0,0 +1,25 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Depth noise and encoding utilities for navigation tasks.""" + +from .camera_config import ( + CameraConfig, + ZEDX_CAMERA_CONFIG, + DEFAULT_CAMERA_CONFIG, + ROBOT_CAMERA_CONFIGS, + get_camera_config, +) +from .depth_noise_encoder import DepthNoiseEncoder, DepthNoise + +__all__ = [ + "CameraConfig", + "ZEDX_CAMERA_CONFIG", + "DEFAULT_CAMERA_CONFIG", + "ROBOT_CAMERA_CONFIGS", + "get_camera_config", + "DepthNoiseEncoder", + "DepthNoise", +] diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_utils/camera_config.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_utils/camera_config.py new file mode 100644 index 0000000..e343872 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_utils/camera_config.py @@ -0,0 +1,146 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Camera configuration parameters for different robots and camera types. + +This module provides camera-specific parameters for depth noise generation and encoding. +""" + +import os +from typing import Optional + +from isaaclab.utils import configclass + +# Local assets directory for this extension +# Path: depth_utils -> mdp -> navigation -> assets/data +_ASSETS_DIR = os.path.normpath( + os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "assets", "data") +) + + +def _get_encoder_path(model_filename: str) -> str: + """Helper function to construct encoder model path. + + Args: + model_filename: Name of the encoder model file (e.g., 'vae_pretrain_new.pth') + + Returns: + Full path to the encoder model file + """ + return os.path.join(_ASSETS_DIR, "Policies", "depth_encoder", model_filename) + + +@configclass +class CameraConfig: + """Configuration class for camera parameters. + + This class contains all camera-specific parameters needed for depth noise generation + and depth encoder initialization. + """ + + # Camera intrinsic parameters + focal_length: float = 25.0 + baseline: float = 0.12 + + # Depth range parameters + min_depth: float = 0.25 + max_depth: float = 10.0 + + # Camera resolution (width, height) + resolution: tuple[int, int] = (53, 30) + + # Depth encoder model path + depth_encoder_path: str = "" + + def __post_init__(self): + """Post-initialization to set default encoder path if not provided.""" + if not self.depth_encoder_path: + self.depth_encoder_path = _get_encoder_path("vae_pretrain_fuse.pth") + + +# Predefined camera configurations +ZEDX_CAMERA_CONFIG = CameraConfig( + focal_length=25.0, + baseline=0.12, + min_depth=0.25, + max_depth=10.0, + resolution=(64, 40), + depth_encoder_path=_get_encoder_path("vae_pretrain_new.pth"), +) +"""Configuration for ZedX camera (used with b2w and aow_d robots).""" + + +# ----------------------------------------------------------------------------- +# Odin1 (LiDAR-aligned depth on Unitree Go2) +# ----------------------------------------------------------------------------- +# Real intrinsics @ native 1600x1296 (from ROS calibration): +# fx = 737.357 px, fy = 737.292 px, cx = 794.372 px, cy = 666.259 px +# hFOV = 2*atan(W / 2fx) = 94.67 deg +# vFOV = 2*atan(H / 2fy) = 82.65 deg +# +# Scaled to VAE-fixed 64x40 input (keep FOV identical): +# fx_sim = 737.357 * 64/1600 = 29.49 px +# fy_sim = 737.292 * 40/1296 = 22.76 px +# cx_sim ~= 31.77 px (close to width/2) +# cy_sim ~= 20.56 px (close to height/2) +# +# Noise model caveat: the upstream DepthNoise module simulates *stereo* +# disparity-quantization noise (sigma_d proportional to d^2 / (fx * baseline)). +# Odin1 depth comes from LiDAR-to-image alignment, where the real noise is +# closer to a constant ~1-2 cm regardless of range. We keep the stereo-style +# noise as a coarse proxy (set focal_length=fx_sim, baseline=0.05 m) but if +# sim2real depth fidelity becomes a problem, swap in a constant-sigma noise +# model later. +ODIN1_CAMERA_CONFIG = CameraConfig( + focal_length=29.49, # pixels (NOT mm; matches sim pinhole fx) + baseline=0.05, # fudge: makes per-meter quantization noise sane + min_depth=0.25, + max_depth=10.0, + resolution=(64, 40), # do not change; VAE encoder input is fixed + depth_encoder_path=_get_encoder_path("vae_pretrain_new.pth"), +) +"""Configuration for Odin1 LiDAR-aligned depth (used with Go2).""" + + +# Default camera configuration +DEFAULT_CAMERA_CONFIG = ZEDX_CAMERA_CONFIG +"""Default camera configuration (ZedX camera settings).""" + +# Robot-to-camera mapping. Go2 now uses Odin1 (LiDAR-aligned depth). b2w and +# aow_d keep the original ZedX profile so the upstream paper results stay +# reproducible. +ROBOT_CAMERA_CONFIGS = { + "b2w": ZEDX_CAMERA_CONFIG, + "aow_d": ZEDX_CAMERA_CONFIG, + "go2": ODIN1_CAMERA_CONFIG, +} +"""Dictionary mapping robot names to their camera configurations.""" + + +def get_camera_config(robot_name: str, use_default_fallback: bool = False) -> CameraConfig: + """Get camera configuration for a specific robot. + + Args: + robot_name: Name of the robot (e.g., 'b2w', 'aow_d') + use_default_fallback: If True, return DEFAULT_CAMERA_CONFIG when robot not found + instead of raising an error (default: False) + + Returns: + Camera configuration for the specified robot + + Raises: + KeyError: If robot_name not found and use_default_fallback is False + """ + if robot_name in ROBOT_CAMERA_CONFIGS: + return ROBOT_CAMERA_CONFIGS[robot_name] + + if use_default_fallback: + return DEFAULT_CAMERA_CONFIG + + available_robots = ", ".join(sorted(ROBOT_CAMERA_CONFIGS.keys())) + raise KeyError( + f"Robot '{robot_name}' not found in camera configurations. " + f"Available robots: {available_robots}" + ) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_utils/depth_noise_encoder.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_utils/depth_noise_encoder.py new file mode 100644 index 0000000..7f5a5fd --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/depth_utils/depth_noise_encoder.py @@ -0,0 +1,361 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Depth noise generation and encoding for navigation tasks.""" + +import os +from collections import OrderedDict +from typing import Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.models import regnet_x_400mf +from torchvision.ops import Conv2dNormActivation, FeaturePyramidNetwork + +from isaaclab_assets import ISAACLAB_ASSETS_DATA_DIR + +from .camera_config import CameraConfig + +# Default camera configuration (ZedX Camera for b2w and aow d) +DEFAULT_CAMERA_CONFIG = CameraConfig( + focal_length=25.0, + baseline=0.12, + min_depth=0.25, + max_depth=10.0, + depth_encoder_path=os.path.join( + str(ISAACLAB_ASSETS_DATA_DIR), + "Policies", + "RSL-ETHZ/AoW_d/depth_encoder", + "vae_pretrain_fuse.pth" + ) +) + + +class VAESampler(nn.Module): + def __init__(self, input_dim, latent_dim): + super(VAESampler, self).__init__() + self.input_dim = input_dim + self.latent_dim = latent_dim + self.conv = Conv2dNormActivation( + input_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False + ) + + # Convolutional Layers for 2D mean and logvar + self.mean_layers = nn.Sequential( + Conv2dNormActivation( + latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False + ), + nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0) + ) + + self.logvar_layers = nn.Sequential( + Conv2dNormActivation( + latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False + ), + nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0) + ) + + def reparameterize(self, mu, logvar): + std = torch.exp(0.5 * logvar) + eps = torch.randn_like(std) + return mu + eps * std + + def forward(self, x): + x = self.conv(x) + x = self.mean_layers(x) + return x + + +class EncoderFPN(nn.Module): + def __init__(self, in_channel, out_channel): + super(EncoderFPN, self).__init__() + encoder = regnet_x_400mf(weights=None) + # Remove classification head from the encoder + encoder = nn.Sequential(*list(encoder.children())[:-2]) + # Modify the first layer to accept the number of channels in the input image + encoder[0][0] = nn.Conv2d(in_channel, 32, kernel_size=3, stride=2, padding=1, bias=False) + self.enc = encoder[0] + self.enc_1 = encoder[1][:2] + self.enc_2 = encoder[1][2] + self.enc_3 = encoder[1][3] + + # Feature Pyramid Network + self.fpn = FeaturePyramidNetwork([64, 160, 400], out_channel) + + def forward(self, x): + raise NotImplementedError("Forward method must be implemented in the child class.") + + +# Depth image encoder +class DepthEncoder(EncoderFPN): + def __init__(self, out_channel): + super(DepthEncoder, self).__init__(1, out_channel) + + def forward(self, x): + # check if depth has channel dimension + if x.dim() == 3: + x = x.unsqueeze(1) + + out = OrderedDict() + x = self.enc(x) + out['feat1'] = self.enc_1(x) + out['feat2'] = self.enc_2(out['feat1']) + out['feat3'] = self.enc_3(out['feat2']) + + out = self.fpn(out) + + return out['feat1'] + + +class VAEDecoder(nn.Module): + def __init__(self, input_dim, out_dim): + super(VAEDecoder, self).__init__() + self.input_dim = input_dim + self.conv = Conv2dNormActivation( + input_dim, input_dim, kernel_size=3, stride=1, padding=1, bias=False + ) + + self.decoder = nn.Sequential( + # Layer 0 + nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False), + nn.BatchNorm2d(input_dim), + nn.ReLU(inplace=True), + # Layer 1 + nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False), + nn.BatchNorm2d(input_dim), + nn.ReLU(inplace=True), + # Layer 2 + nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False), + nn.BatchNorm2d(input_dim), + nn.ReLU(inplace=True), + # Final Output Layer + nn.Conv2d(input_dim, out_dim, kernel_size=3, stride=1, padding=1) + ) # Expand the spatial dimensions by a factor of 2**4=16 + + def forward(self, z): + z = self.conv(z) + img = self.decoder(z) + return img + + +class DepthDecoder(VAEDecoder): + def __init__(self, input_dim): + super(DepthDecoder, self).__init__(input_dim, 1) + + +class VAENet(nn.Module): + def __init__(self, latent_dim): + super(VAENet, self).__init__() + self.depth_encoder = DepthEncoder(latent_dim) + + self.vae_sampler = VAESampler(latent_dim, latent_dim) + + self.depth_decoder = DepthDecoder(latent_dim) + + def forward(self, x): + x = self.depth_encoder(x) + x = self.vae_sampler(x) + return x + + def decode(self, z): + return self.depth_decoder(z) + + +class DepthNoise(torch.nn.Module): + def __init__( + self, + focal_length, + baseline, + min_depth, + max_depth, + filter_size=3, + inlier_thred_range=(0.01, 0.05), + prob_range=(0.4, 0.6), + invalid_disp=1e7 + ): + """A Simply PyTorch module to add realistic noise to depth images. + + Args: + focal_length (float): Focal length of the camera (in pixels). + baseline (float): Baseline distance between stereo cameras (in meters). + min_depth (float): Minimum depth value after clamping. + max_depth (float): Maximum depth value after clamping. + filter_size (int): Kernel size for local mean disparity computation. + inlier_thred_range (tuple): Threshold range for normalized disparity differences. + prob_range (tuple): Probability range for matching pixels. + invalid_disp (float): Invalid disparity + """ + super().__init__() + self.focal_length = focal_length + self.baseline = baseline + self.min_depth = min_depth + self.max_depth = max_depth + self.invalid_disp = invalid_disp + self.inlier_thred_range = inlier_thred_range + self.prob_range = prob_range + self.filter_size = filter_size + + weights, substitutes = self._compute_weights(filter_size) + self.register_buffer('weights', weights.view(1, 1, filter_size, filter_size)) + self.register_buffer('substitutes', substitutes.view(1, 1, filter_size, filter_size)) + + def _compute_weights(self, filter_size): + """Compute weights and substitutes for disparity filtering. + + Args: + filter_size (int): Kernel size for local mean disparity computation. + """ + center = filter_size // 2 + idx = torch.arange(filter_size) - center + x_filter, y_filter = torch.meshgrid(idx, idx, indexing='ij') + sqr_radius = x_filter ** 2 + y_filter ** 2 + sqrt_radius = torch.sqrt(sqr_radius) + weights = 1 / torch.where(sqr_radius == 0, torch.ones_like(sqrt_radius), sqrt_radius) + weights = weights / weights.sum() + fill_weights = 1 / (1 + sqrt_radius) + fill_weights = torch.where(sqr_radius > filter_size, -1.0, fill_weights) + substitutes = (fill_weights > 0).float() + + return weights, substitutes + + def filter_disparity(self, disparity): + """Filter the disparity map using local mean disparity. + + Args: + disparity (torch.Tensor): Input disparity map tensor of shape (B, C, H, W). + """ + B, _, H, W = disparity.shape + device = disparity.device + center = self.filter_size // 2 + + output_disparity = torch.full_like(disparity, self.invalid_disp) + + prob = ( + torch.rand(B, 1, 1, 1, device=device) + * (self.prob_range[1] - self.prob_range[0]) + + self.prob_range[0] + ) + random_mask = (torch.rand(B, 1, H, W, device=device) < prob) + + # Compute mean disparity + weighted_disparity = F.conv2d(disparity, self.weights, padding=center) + + # Compute differences + differences = torch.abs(disparity - weighted_disparity) + + # Normalize differences based on current image statistics + differences_flat = differences.view(B, -1) + mean_diff = torch.mean(differences_flat, dim=1, keepdim=True) + std_diff = torch.std(differences_flat, dim=1, keepdim=True) + 1e-6 + + normalized_differences_flat = (differences_flat - mean_diff) / std_diff + normalized_differences = normalized_differences_flat.view_as(differences) + + # Use parameter-based threshold on normalized differences + threshold = ( + torch.rand(B, 1, 1, 1, device=device) + * (self.inlier_thred_range[1] - self.inlier_thred_range[0]) + + self.inlier_thred_range[0] + ) + update_mask = (normalized_differences < threshold) & random_mask + + # Compute output value: round with 1/32 precision + disparity = torch.round(disparity * 32.0) / 32.0 + + # Update output disparity + output_disparity = torch.where(update_mask, disparity, output_disparity) + + # Apply substitutes to fill neighboring pixels + filled_values = F.conv2d(update_mask.float() * disparity, self.substitutes, padding=center) + counts = F.conv2d(update_mask.float(), self.substitutes, padding=center) + 1e-9 + average_filled_values = filled_values / counts + output_disparity = torch.where(counts >= 1, average_filled_values, output_disparity) + + return output_disparity + + def forward(self, depth, add_noise: bool) -> torch.Tensor: + # correct input shape + if len(depth.shape) == 3: + depth = depth.unsqueeze(1) # add channel dimension + + # check dimension (B, 1, H, W) + assert depth.shape[1] == 1, "Input depth tensor must have shape (B, 1, H, W)." + assert len(depth.shape) == 4, "Input depth tensor must have shape (B, 1, H, W)." + + if add_noise: + # Clamp the depth values + depth = torch.clamp(depth, min=1. / self.invalid_disp) + + # Step 1: Convert depth to disparity + disparity = self.focal_length * self.baseline / depth + + # Step 2: Filter the disparity map + filtered_disparity = self.filter_disparity(disparity) + + # Step 3: Recompute depth from disparity + depth = self.focal_length * self.baseline / filtered_disparity + + # Step 4: Clamp the depth values + depth[depth < self.min_depth] = 0.0 + + # Step 5: Set invalid depth values to 0.0 + depth[depth > self.max_depth] = 0.0 + + return depth + + +class DepthNoiseEncoder(torch.nn.Module): + def __init__( + self, + feature_dim, + camera_config: CameraConfig = None + ): + """A Simply PyTorch module to add realistic noise to depth images. + + Args: + feature_dim (int): Number of output channels from the encoder. + camera_config (CameraConfig, optional): Camera configuration parameters. + If None, uses DEFAULT_CAMERA_CONFIG. + """ + super().__init__() + + # Use provided config or default + if camera_config is None: + camera_config = DEFAULT_CAMERA_CONFIG + + self.camera_config = camera_config + self.depth_noise = DepthNoise( + focal_length=camera_config.focal_length, + baseline=camera_config.baseline, + min_depth=camera_config.min_depth, + max_depth=camera_config.max_depth + ) + + self.encoder = VAENet(feature_dim) + + try: + self.encoder.load_state_dict( + torch.load(camera_config.depth_encoder_path, weights_only=True), + strict=True + ) + print( + '\033[92m' + + f'Successfully loaded pre-trained weights from {camera_config.depth_encoder_path}' + + '\033[0m' + ) + except Exception as e: + print('\033[91m' + f'Failed to load pre-trained weights: {e}' + '\033[0m') + + def forward( + self, depth: torch.Tensor, add_noise: bool = True + ) -> Tuple[torch.Tensor, torch.Tensor]: + noisy_depth = self.depth_noise(depth, add_noise) + encoded_depth = self.encoder(noisy_depth) # (B, 1, H, W) -> (B, C, H//8, W//8) + return encoded_depth, noisy_depth + + @torch.jit.export + def decode(self, z: torch.Tensor) -> torch.Tensor: + return self.encoder.decode(z) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/events.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/events.py new file mode 100644 index 0000000..373a7bd --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/events.py @@ -0,0 +1,229 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Custom event functions for navigation tasks. + +These functions are ported from the internal Isaac Lab fork and provide +domain randomization and environment events specific to navigation tasks. +""" +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from isaaclab.envs import ManagerBasedEnv +from isaaclab.managers import SceneEntityCfg +from isaaclab.utils import math as math_utils + +if TYPE_CHECKING: + from isaaclab.sensors import RayCasterCamera + from isaaclab_nav_task.navigation.mdp import PerceptiveNavigationSE2Action + + +def randomize_camera_height( + env: ManagerBasedEnv, + env_ids: torch.Tensor, + height_range: float, + roll_angle_range: float, + pitch_angle_range: float, + yaw_angle_range: float, + asset_cfg: SceneEntityCfg = SceneEntityCfg("raycast_camera"), +): + """Randomize the camera's height and orientation around the original values. + + The function samples around the original camera offset and orientation: + - height: original height +- height_range (meters) + - roll: original roll +- roll_angle_range (degrees) + - pitch: original pitch +- pitch_angle_range (degrees) + - yaw: original yaw +- yaw_angle_range (degrees) + + Args: + env: The environment manager. + env_ids: The environment ids to randomize. + height_range: Range around original height (meters). + roll_angle_range: Range around original roll angle (degrees). + pitch_angle_range: Range around original pitch angle (degrees). + yaw_angle_range: Range around original yaw angle (degrees). + asset_cfg: Scene entity configuration for the camera. + """ + camera: RayCasterCamera = env.scene[asset_cfg.name] + + # Get original camera position and orientation + original_camera_pos = camera.cfg.offset.pos + original_camera_quat = camera.cfg.offset.rot + + # Sample position around original value + num_envs = env_ids.numel() + pos_delta = torch.zeros((num_envs, 3), device=env.device) + pos_delta[:, 0] = torch.randn(num_envs, device=env.device) * (height_range / 2.0) + pos_delta[:, 1] = torch.randn(num_envs, device=env.device) * (height_range / 2.0) + pos_delta[:, 0] = torch.clamp(pos_delta[:, 0], -height_range, height_range) + pos_delta[:, 1] = torch.clamp(pos_delta[:, 1], -height_range, height_range) + pos_delta[:, 2] = torch.rand(num_envs, device=env.device) * 2.0 * height_range - height_range + camera._offset_pos[env_ids] = torch.tensor(original_camera_pos, device=env.device) + pos_delta + + # Convert original quaternion to Euler angles (XYZ convention) + quat_tensor = torch.tensor(original_camera_quat, device=env.device).unsqueeze(0) + original_euler = math_utils.euler_xyz_from_quat(quat_tensor) + original_roll_deg = original_euler[0] * 180.0 / torch.pi + original_pitch_deg = original_euler[1] * 180.0 / torch.pi + original_yaw_deg = original_euler[2] * 180.0 / torch.pi + + # Sample angles around original values + roll_delta_deg = torch.randn(num_envs, device=env.device) * (roll_angle_range / 2.0) + roll_delta_deg = torch.clamp(roll_delta_deg, -roll_angle_range, roll_angle_range) + pitch_delta_deg = torch.rand(num_envs, device=env.device) * 2.0 * pitch_angle_range - pitch_angle_range + yaw_delta_deg = torch.randn(num_envs, device=env.device) * (yaw_angle_range / 2.0) + yaw_delta_deg = torch.clamp(yaw_delta_deg, -yaw_angle_range, yaw_angle_range) + + # Add deltas to original angles + sampled_roll_deg = original_roll_deg + roll_delta_deg + sampled_pitch_deg = original_pitch_deg + pitch_delta_deg + sampled_yaw_deg = original_yaw_deg + yaw_delta_deg + + # Convert to radians and build quaternion (XYZ convention) + sampled_roll_rad = sampled_roll_deg * torch.pi / 180.0 + sampled_pitch_rad = sampled_pitch_deg * torch.pi / 180.0 + sampled_yaw_rad = sampled_yaw_deg * torch.pi / 180.0 + + camera._offset_quat[env_ids] = math_utils.quat_from_euler_xyz(sampled_roll_rad, sampled_pitch_rad, sampled_yaw_rad) + + +def randomize_action_scale( + env: ManagerBasedEnv, + env_ids: torch.Tensor, + scale_range_x: tuple[float, float], + scale_range_y: tuple[float, float], + scale_range_theta: tuple[float, float], + scale_range_xb: float, + scale_range_yb: float, + scale_range_thetab: float, + action_term: str, +): + """Change the action scale in the scene. + + Args: + env: The environment manager. + env_ids: The environment ids to change the action scale in. + scale_range_x: The scale range for x. + scale_range_y: The scale range for y. + scale_range_theta: The scale range for theta. + scale_range_xb: The bias range for x. + scale_range_yb: The bias range for y. + scale_range_thetab: The bias range for theta. + action_term: Name of the action term. + """ + action_term_obj: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term] + + action_term_obj._policy_scaling[env_ids] = torch.tensor( + action_term_obj.cfg.policy_scaling, device=action_term_obj.device + ).expand(len(env_ids), -1) + + random_scales_x = ( + torch.rand(len(env_ids), 1, device=env.device) * (scale_range_x[1] - scale_range_x[0]) + scale_range_x[0] + ) + random_scales_y = ( + torch.rand(len(env_ids), 1, device=env.device) * (scale_range_y[1] - scale_range_y[0]) + scale_range_y[0] + ) + random_scales_theta = ( + torch.rand(len(env_ids), 1, device=env.device) * (scale_range_theta[1] - scale_range_theta[0]) + + scale_range_theta[0] + ) + random_scales_xb = (torch.rand(len(env_ids), 1, device=env.device) * 2 - 1) * scale_range_xb + random_scales_yb = (torch.rand(len(env_ids), 1, device=env.device) * 2 - 1) * scale_range_yb + random_scales_thetab = (torch.rand(len(env_ids), 1, device=env.device) * 2 - 1) * scale_range_thetab + + random_scales = torch.cat((random_scales_x, random_scales_y, random_scales_theta), dim=-1) + random_scales_b = torch.cat((random_scales_xb, random_scales_yb, random_scales_thetab), dim=-1) + + action_term_obj._policy_scaling[env_ids] *= random_scales + action_term_obj._policy_bias[env_ids, :] = random_scales_b + + +def reset_and_randomize_delay_buffer( + env: ManagerBasedEnv, + env_ids: torch.Tensor, +): + """Reset and randomize delay buffers. + + This function resets the delay buffers and randomizes the time lags for + all observation types. Requires env.delay_manager to exist. + + Args: + env: The environment manager (must have delay_manager attribute). + env_ids: The environment ids to reset. + """ + env.delay_manager.reset(env_ids) + env.delay_manager.randomize_lags(env_ids) + + +def randomize_low_pass_filter_alpha( + env: ManagerBasedEnv, + env_ids: torch.Tensor, + alpha_range: tuple[float, float], + action_term: str, + per_dimension: bool = True, + alpha_range_vx: tuple[float, float] | None = None, + alpha_range_vy: tuple[float, float] | None = None, + alpha_range_omega: tuple[float, float] | None = None, +): + """Randomize the low-pass filter alpha parameter for velocity command smoothing. + + Args: + env: The environment manager. + env_ids: The environment ids to randomize the alpha parameter for. + alpha_range: Tuple of (min_alpha, max_alpha) values. + action_term: Name of the action term to modify. + per_dimension: Whether to use different alpha for each dimension. + alpha_range_vx: Optional range for vx dimension. + alpha_range_vy: Optional range for vy dimension. + alpha_range_omega: Optional range for omega dimension. + """ + action_term_obj: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term] + + if per_dimension: + # Use dimension-specific ranges or fall back to global range + vx_range = alpha_range_vx if alpha_range_vx is not None else alpha_range + vy_range = alpha_range_vy if alpha_range_vy is not None else alpha_range + omega_range = alpha_range_omega if alpha_range_omega is not None else alpha_range + + alpha_vx = torch.rand(len(env_ids), device=env.device) * (vx_range[1] - vx_range[0]) + vx_range[0] + alpha_vy = torch.rand(len(env_ids), device=env.device) * (vy_range[1] - vy_range[0]) + vy_range[0] + alpha_omega = torch.rand(len(env_ids), device=env.device) * (omega_range[1] - omega_range[0]) + omega_range[0] + + if hasattr(action_term_obj, "_per_env_per_dim_low_pass_alpha"): + action_term_obj._per_env_per_dim_low_pass_alpha[env_ids, 0] = alpha_vx + action_term_obj._per_env_per_dim_low_pass_alpha[env_ids, 1] = alpha_vy + action_term_obj._per_env_per_dim_low_pass_alpha[env_ids, 2] = alpha_omega + else: + random_alpha = ( + torch.rand(len(env_ids), device=env.device) * (alpha_range[1] - alpha_range[0]) + alpha_range[0] + ) + if hasattr(action_term_obj, "_per_env_per_dim_low_pass_alpha"): + action_term_obj._per_env_per_dim_low_pass_alpha[env_ids] = random_alpha.unsqueeze(-1).expand(-1, 3) + + +def disable_backward_penalty_after_steps( + env: ManagerBasedEnv, + env_ids: torch.Tensor, + disable_after_steps: int, + action_term: str, +): + """Disable backward movement penalty after a certain number of steps. + + Args: + env: The environment manager. + env_ids: The environment ids. + disable_after_steps: Number of steps after which to disable the penalty. + action_term: Name of the action term. + """ + action_term_obj: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term] + + if hasattr(action_term_obj, "disable_backward_penalty"): + # Check which environments have exceeded the step threshold + if hasattr(env, "episode_length_buf"): + exceeded_steps = env.episode_length_buf[env_ids] >= disable_after_steps + action_term_obj.disable_backward_penalty[env_ids[exceeded_steps]] = True diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/heightscan_utils/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/heightscan_utils/__init__.py new file mode 100644 index 0000000..d5f0f16 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/heightscan_utils/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Height scan encoder utilities for navigation tasks.""" + +from .heightscan_encoder import HeightScanFeatEncoder + +__all__ = ["HeightScanFeatEncoder"] diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/heightscan_utils/heightscan_encoder.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/heightscan_utils/heightscan_encoder.py new file mode 100644 index 0000000..1d0d581 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/heightscan_utils/heightscan_encoder.py @@ -0,0 +1,192 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT +import os +import torch +import torch.nn as nn +from typing import Tuple +import torch.nn.functional as F +from collections import OrderedDict +from torchvision.ops import FeaturePyramidNetwork +from torchvision.models import regnet_x_400mf +from torchvision.ops import Conv2dNormActivation + +# Local path to the encoder weights (relative to this file's directory) +_ASSETS_DIR = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "assets", "data")) +HEIGHTSCAN_ENCODER_PATH = os.path.join(_ASSETS_DIR, "Policies", "heightscan_encoder", "vae_heightscan3.pth") + +class VAESampler(nn.Module): + def __init__(self, input_dim, latent_dim): + super(VAESampler, self).__init__() + self.input_dim = input_dim + self.latent_dim = latent_dim + self.conv = Conv2dNormActivation(input_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False) + + # Convolutional Layers for 2D mean and logvar + self.mean_layers = nn.Sequential( + Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False), + nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0) + ) + + self.logvar_layers = nn.Sequential( + Conv2dNormActivation(latent_dim, latent_dim, kernel_size=3, stride=1, padding=1, bias=False), + nn.Conv2d(latent_dim, latent_dim, kernel_size=1, stride=1, padding=0) + ) + + def reparameterize(self, mu, logvar): + std = torch.exp(0.5 * logvar) + eps = torch.randn_like(std) + return mu + eps * std + + def forward(self, x): + x = self.conv(x) + x = self.mean_layers(x) + return x + +class EncoderFPN(nn.Module): + def __init__(self, in_channel, out_channel): + super(EncoderFPN, self).__init__() + encoder = regnet_x_400mf(weights=None) + # Remove classification head from the encoder + encoder = nn.Sequential(*list(encoder.children())[:-2]) + # Modify the first layer to accept the number of channels in the input image + encoder[0][0] = nn.Conv2d(in_channel, 32, kernel_size=3, stride=2, padding=1, bias=False) + self.enc = encoder[0] + self.enc_1 = encoder[1][:2] + self.enc_2 = encoder[1][2] + self.enc_3 = encoder[1][3] + + # Feature Pyramid Network + self.fpn = FeaturePyramidNetwork([64, 160, 400], out_channel) + + def forward(self, x): + raise NotImplementedError("Forward method must be implemented in the child class.") + +# Depth image encoder +class HeightScanEncoder(EncoderFPN): + def __init__(self, out_channel): + super(HeightScanEncoder, self).__init__(1, out_channel) + + def forward(self, x): + # check if depth has channel dimension + if x.dim() == 3: + x = x.unsqueeze(1) + + out = OrderedDict() + x = self.enc(x) + out['feat1'] = self.enc_1(x) + out['feat2'] = self.enc_2(out['feat1']) + out['feat3'] = self.enc_3(out['feat2']) + + out = self.fpn(out) + + return out['feat1'] + +class VAEDecoder(nn.Module): + def __init__(self, input_dim, out_dim): + super(VAEDecoder, self).__init__() + self.input_dim = input_dim + self.conv = Conv2dNormActivation(input_dim, input_dim, kernel_size=3, stride=1, padding=1, bias=False) + + self.decoder = nn.Sequential( + # Layer 0 + nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False), + nn.BatchNorm2d(input_dim), + nn.ReLU(inplace=True), + # Layer 1 + nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False), + nn.BatchNorm2d(input_dim), + nn.ReLU(inplace=True), + # Layer 2 + nn.ConvTranspose2d(input_dim, input_dim, kernel_size=4, stride=2, padding=1, bias=False), + nn.BatchNorm2d(input_dim), + nn.ReLU(inplace=True), + # Final Output Layer + nn.Conv2d(input_dim, out_dim, kernel_size=3, stride=1, padding=1) + ) # Expand the spatial dimensions by a factor of 2**4=16 + + def forward(self, z): + z = self.conv(z) + img = self.decoder(z) + return img + +class HeightScanDecoder(VAEDecoder): + def __init__(self, input_dim): + super(HeightScanDecoder, self).__init__(input_dim, 1) + +class VAENet(nn.Module): + def __init__(self, latent_dim): + super(VAENet, self).__init__() + self.depth_encoder = HeightScanEncoder(latent_dim) + + self.vae_sampler = VAESampler(latent_dim, latent_dim) + + self.depth_decoder = HeightScanDecoder(latent_dim) + + def forward(self, x): + x = self.depth_encoder(x) + x = self.vae_sampler(x) + return x + + def decode(self, z): + return self.depth_decoder(z) + + +class HeightScanFeatEncoder(torch.nn.Module): + def __init__(self, + feature_dim, + ): + """ + A Simply PyTorch module to add realistic noise to depth images. + + Args: + feature_dim (int): Number of output channels from the encoder. + """ + super().__init__() + + self.encoder = VAENet(feature_dim) + + try: + self.encoder.load_state_dict(torch.load(HEIGHTSCAN_ENCODER_PATH, weights_only=True), strict=True) + print('\033[92m' + f'Successfully loaded pre-trained weights from {HEIGHTSCAN_ENCODER_PATH}' + '\033[0m') + except Exception as e: + print('\033[91m' + f'Failed to load pre-trained weights: {e}' + '\033[0m') + + def forward(self, scan: torch.Tensor) -> torch.Tensor: + encoded_scan = self.encoder(scan) # (B, 1, H, W) -> (B, C, H//8, W//8) + return encoded_scan + + @torch.jit.export + def decode(self, z: torch.Tensor) -> torch.Tensor: + return self.encoder.decode(z) + + +# Example usage +if __name__ == "__main__": + import cv2 + import numpy as np + + # parameters for the depth noise + feature_dim = 64 + + # Initialize the DepthNoise class + heightscan_feat_encoder = HeightScanFeatEncoder(feature_dim=feature_dim) + + # compile the depth_noise module + compiled_scan_encoder = torch.jit.script(heightscan_feat_encoder) + + # random height scan image + scan = np.random.rand(51, 51) * 5 + + # convert depth to tensor + scan = torch.tensor(scan).unsqueeze(0).unsqueeze(0).float() + clipped_scan = torch.clamp(scan, min=-5, max=5) + + # Add noise to the depth image + noisy_scan = compiled_scan_encoder(clipped_scan) + + noisy_scan = noisy_scan.numpy().squeeze().squeeze() + # check the min and max values of the noisy depth + print("Min depth: ", noisy_scan.min()) + print("Max depth: ", noisy_scan.max()) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/math_utils.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/math_utils.py new file mode 100644 index 0000000..4124c11 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/math_utils.py @@ -0,0 +1,50 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Custom math utilities for navigation tasks.""" +from __future__ import annotations + +import torch + + +@torch.jit.script +def vec_to_quat(v: torch.Tensor) -> torch.Tensor: + """Converts a unit vector to a quaternion representing the rotation from the X-axis to the vector v. + + Args: + v (torch.Tensor): A tensor of shape (..., 3) representing the unit vectors. + + Returns: + torch.Tensor: A tensor of shape (..., 4) representing the quaternions (w, x, y, z). + """ + # Ensure v is a unit vector + norm_v = v / torch.clamp(torch.norm(v, dim=-1, keepdim=True), min=1e-8) + + # Reference vector (X-axis) + a = torch.tensor([1.0, 0.0, 0.0], device=norm_v.device, dtype=norm_v.dtype).expand_as(norm_v) + + # Compute dot and cross products + dot = torch.sum(a * norm_v, dim=-1, keepdim=True) + w = torch.cross(a, norm_v, dim=-1) + + # Compute quaternion components + s = torch.sqrt((1.0 + dot) * 0.5).clamp(min=1e-8) # Avoid division by zero + q = torch.cat([s, w / (2.0 * s)], dim=-1) + + # Handle edge case when dot == -1 (vectors are opposite) + mask = (dot < -0.999999).squeeze(-1) + if mask.any(): + # Choose an arbitrary orthogonal vector + orthogonal = torch.cross( + a[mask], + torch.tensor([0.0, 1.0, 0.0], device=norm_v.device, dtype=norm_v.dtype).expand_as(a[mask]), + dim=-1 + ) + orthogonal = orthogonal / torch.clamp(torch.norm(orthogonal, dim=-1, keepdim=True), min=1e-8) + q[mask] = torch.cat([torch.zeros_like(s[mask]), orthogonal], dim=-1) + + # Normalize the quaternion + q = q / torch.clamp(torch.norm(q, dim=-1, keepdim=True), min=1e-8) + return q diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/__init__.py new file mode 100644 index 0000000..1a258bb --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Navigation-specific MDP components including goal commands and SE2 actions.""" + +from .goal_commands import * # noqa: F401, F403 +from .goal_commands_cfg import * # noqa: F401, F403 +from .actions import * # noqa: F401, F403 diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/actions/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/actions/__init__.py new file mode 100644 index 0000000..947624b --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/actions/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + + +from .navigation_se2_actions import PerceptiveNavigationSE2Action +from .navigation_se2_actions_cfg import PerceptiveNavigationSE2ActionCfg + +__all__ = ["PerceptiveNavigationSE2Action", "PerceptiveNavigationSE2ActionCfg"] \ No newline at end of file diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/actions/navigation_se2_actions.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/actions/navigation_se2_actions.py new file mode 100644 index 0000000..c3a5807 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/actions/navigation_se2_actions.py @@ -0,0 +1,249 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Navigation SE2 action term for hierarchical control.""" +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from isaaclab.envs import ManagerBasedRLEnv +from isaaclab.managers.action_manager import ActionTerm +from isaaclab.utils.assets import check_file_path, read_file + +if TYPE_CHECKING: + from .navigation_se2_actions_cfg import PerceptiveNavigationSE2ActionCfg + + +class PerceptiveNavigationSE2Action(ActionTerm): + """Actions to navigate a robot using hierarchical control with a pre-trained locomotion policy.""" + + cfg: PerceptiveNavigationSE2ActionCfg + _env: ManagerBasedRLEnv + + def __init__(self, cfg: PerceptiveNavigationSE2ActionCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + # Check if policy file exists + if not check_file_path(cfg.low_level_policy_file): + raise FileNotFoundError(f"Policy file '{cfg.low_level_policy_file}' does not exist.") + # Load pre-trained locomotion policy + file_bytes = read_file(self.cfg.low_level_policy_file) + self.low_level_policy = torch.jit.load(file_bytes, map_location=self.device) + self.low_level_policy.eval() + + # prepare joint position actions + self.low_level_position_action_term: ActionTerm = self.cfg.low_level_position_action.class_type(cfg.low_level_position_action, env) + # Velocity branch is optional (None for legs-only robots like Go2). + if self.cfg.low_level_velocity_action is not None: + self.low_level_velocity_action_term: ActionTerm | None = self.cfg.low_level_velocity_action.class_type(cfg.low_level_velocity_action, env) + else: + self.low_level_velocity_action_term = None + + # prepare buffers + self._action_dim = 3 # [vx, vy, omega] + + # set up buffers + self._init_buffers() + + # Low-pass filter state for velocity commands + self._prev_filtered_velocity_commands = torch.zeros((self.num_envs, self._action_dim), device=self.device) + self._low_pass_alpha = self.cfg.low_pass_filter_alpha if hasattr(self.cfg, 'low_pass_filter_alpha') else 0.8 + self._enable_low_pass_filter = self.cfg.enable_low_pass_filter if hasattr(self.cfg, 'enable_low_pass_filter') else True + # Per-environment per-dimension alpha values (initialized to default, can be randomized per episode) + # Shape: [num_envs, action_dim] where action_dim = 3 (vx, vy, omega) + self._per_env_per_dim_low_pass_alpha = torch.full((self.num_envs, self._action_dim), self._low_pass_alpha, device=self.device) + + + """ + Properties. + """ + + @property + def action_dim(self) -> int: + return self._action_dim + + @property + def raw_actions(self) -> torch.Tensor: + return self._raw_navigation_velocity_actions + + @property + def processed_actions(self) -> torch.Tensor: + return self._processed_navigation_velocity_actions + + @property + def filtered_velocity_commands(self) -> torch.Tensor: + """Get the current filtered (smoothed) velocity commands.""" + return self._prev_filtered_velocity_commands + + @property + def low_pass_alpha_values(self) -> torch.Tensor: + """Get the current per-environment per-dimension low-pass filter alpha values. + + Returns: + torch.Tensor: Alpha values with shape [num_envs, action_dim] where: + - action_dim = 3 for [vx, vy, omega] + - Each environment can have different alpha values for each command dimension + """ + return self._per_env_per_dim_low_pass_alpha + + @property + def low_level_actions(self) -> torch.Tensor: + if self.low_level_velocity_action_term is None: + return self._low_level_position_actions + return torch.cat((self._low_level_position_actions, self._low_level_velocity_actions), dim=1) + + @property + def low_level_position_actions(self) -> torch.Tensor: + return self._low_level_position_actions + + @property + def prev_low_level_position_actions(self) -> torch.Tensor: + return self._prev_low_level_position_actions + + @property + def low_level_velocity_actions(self) -> torch.Tensor: + return self._low_level_velocity_actions + + @property + def prev_low_level_velocity_actions(self) -> torch.Tensor: + return self._prev_low_level_velocity_actions + + """ + Operations. + """ + + def apply_low_pass_filter(self, velocity_commands: torch.Tensor) -> torch.Tensor: + """Apply low-pass filter to velocity commands for smoother locomotion. + + The low-pass filter implements exponential smoothing: + filtered_cmd(t) = alpha * filtered_cmd(t-1) + (1 - alpha) * new_cmd(t) + + Where alpha is the smoothing factor: + - alpha = 0.0: No smoothing (pass through) + - alpha = 1.0: Maximum smoothing (no change) + - alpha = 0.8: Good balance for locomotion (default) + + This implementation supports per-environment per-dimension alpha values, allowing: + - Different smoothing for vx, vy, and omega in each environment + - Independent control over linear and angular velocity response + + Args: + velocity_commands (torch.Tensor): Raw velocity commands [num_envs, 3] (vx, vy, omega) + + Returns: + torch.Tensor: Filtered velocity commands with same shape as input + """ + if not self._enable_low_pass_filter: + return velocity_commands + + # Use per-environment per-dimension alpha values for filtering + # Shape: [num_envs, action_dim] - already matches velocity_commands shape + alpha_values = self._per_env_per_dim_low_pass_alpha + + # Apply exponential smoothing (low-pass filter) with per-environment per-dimension alpha + filtered_commands = ( + alpha_values * self._prev_filtered_velocity_commands + + (1.0 - alpha_values) * velocity_commands + ) + + # Update previous filtered commands for next iteration + self._prev_filtered_velocity_commands.copy_(filtered_commands) + + return filtered_commands + + def process_actions(self, actions): + """Process low-level navigation actions. This function is called with a frequency of 10Hz. + + Args: + actions (torch.Tensor): The low-level navigation actions. + """ + # Store the raw low-level navigation actions + self._raw_navigation_velocity_actions[:] = actions + # Apply the affine transformations + if not self.cfg.use_raw_actions: + self._processed_navigation_velocity_actions = ( + self._raw_navigation_velocity_actions * self._scale + self._offset + ) + else: + self._processed_navigation_velocity_actions[:] = self._raw_navigation_velocity_actions + + if self.cfg.policy_distr_type == "gaussian": + # scale the actions to the range [-1, 1] for gaussian distribution + self._processed_navigation_velocity_actions = torch.tanh(self._processed_navigation_velocity_actions) + elif self.cfg.policy_distr_type == "beta": + # scale the actions to the range [-1, 1] for beta distribution + self._processed_navigation_velocity_actions = (self._processed_navigation_velocity_actions - 0.5) * 2.0 + else: + raise ValueError(f"Unknown policy distribution type: {self.cfg.policy_distr_type}") + + # compute the current speed of the robot to generate low-level actions based on the current speed + observations = self._env.observation_manager.compute_group(group_name=self.cfg.observation_group) + base_lin_vel = observations[:, 0:3] + vel_xyz = base_lin_vel.norm(dim=1, keepdim=True) + + # [vx, vy, omega] + self._processed_navigation_velocity_actions = (self._processed_navigation_velocity_actions + vel_xyz * self._policy_bias) * self._policy_scaling + + # Apply low-pass filter to smooth velocity commands and add delay effect + self._processed_navigation_velocity_actions = self.apply_low_pass_filter(self._processed_navigation_velocity_actions) + + @torch.inference_mode() + def apply_actions(self): + """Apply low-level actions for the simulator to the physics engine. This functions is called with the + simulation frequency of 200Hz. Since low-level locomotion runs at 50Hz, we need to decimate the actions.""" + + if self._counter % self.cfg.low_level_decimation == 0: + self._counter = 0 + self._prev_low_level_position_actions[:] = self._low_level_position_actions.clone() + if self.low_level_velocity_action_term is not None: + self._prev_low_level_velocity_actions[:] = self._low_level_velocity_actions.clone() + + # Get low level actions from low level policy + actions_phase = self.low_level_policy( + self._env.observation_manager.compute_group(group_name=self.cfg.observation_group) + ) + + # Process actions and bring them in the right order + pos_dim = self.low_level_position_action_term.action_dim + self._low_level_position_actions[:] = actions_phase[:, :pos_dim] + self.low_level_position_action_term.process_actions(self._low_level_position_actions) + if self.low_level_velocity_action_term is not None: + self._low_level_velocity_actions[:] = actions_phase[:, pos_dim:] + self.low_level_velocity_action_term.process_actions(self._low_level_velocity_actions) + + # Apply low level actions + self.low_level_position_action_term.apply_actions() + if self.low_level_velocity_action_term is not None: + self.low_level_velocity_action_term.apply_actions() + self._counter += 1 + + def reset_low_pass_filter(self, env_ids: torch.Tensor): + """Reset low-pass filter state for specified environments. + + Args: + env_ids: Environment indices to reset. + """ + self._prev_filtered_velocity_commands[env_ids] = 0.0 + + """ + Helper functions + """ + + def _init_buffers(self): + # Prepare buffers + self._raw_navigation_velocity_actions = torch.zeros(self.num_envs, self._action_dim, device=self.device) + self._processed_navigation_velocity_actions = torch.zeros((self.num_envs, self._action_dim), device=self.device) + self._low_level_position_actions = torch.zeros(self.num_envs, self.low_level_position_action_term.action_dim, device=self.device) + vel_dim = self.low_level_velocity_action_term.action_dim if self.low_level_velocity_action_term is not None else 0 + self._low_level_velocity_actions = torch.zeros(self.num_envs, vel_dim, device=self.device) + self._prev_low_level_position_actions = torch.zeros_like(self._low_level_position_actions) + self._prev_low_level_velocity_actions = torch.zeros_like(self._low_level_velocity_actions) + self._low_level_step_dt = self.cfg.low_level_decimation * self._env.physics_dt + self._counter = 0 + self._scale = torch.tensor(self.cfg.scale, device=self.device) + self._offset = torch.tensor(self.cfg.offset, device=self.device) + self._policy_scaling = torch.tensor(self.cfg.policy_scaling, device=self.device).repeat(self.num_envs, 1) + self._policy_bias = torch.zeros(self.num_envs, self._action_dim, device=self.device) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/actions/navigation_se2_actions_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/actions/navigation_se2_actions_cfg.py new file mode 100644 index 0000000..dd2d17a --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/actions/navigation_se2_actions_cfg.py @@ -0,0 +1,52 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +from __future__ import annotations + +from dataclasses import MISSING + +from isaaclab.managers.action_manager import ActionTerm, ActionTermCfg +from isaaclab.utils import configclass + +from .navigation_se2_actions import PerceptiveNavigationSE2Action + + +@configclass +class PerceptiveNavigationSE2ActionCfg(ActionTermCfg): + class_type: type[ActionTerm] = PerceptiveNavigationSE2Action + """ Class of the action term.""" + low_level_decimation: int = 4 + """Decimation factor for the low level action term.""" + use_raw_actions: bool = False + """Whether to use raw actions or not.""" + scale: list[float] = [1.0, 1.0, 1.0] + """Scale for the actions [vx, vy, w].""" + offset: list[float] = [0.0, 0.0, 0.0] + """Offset for the actions [vx, vy, w].""" + low_level_velocity_action: ActionTermCfg | None = None + """Configuration of the low level velocity action term. + + Set to ``None`` for legs-only quadrupeds (e.g. Go2) whose locomotion policy + only outputs joint position targets. The position-action branch then handles + all 12 leg joints, and the velocity-action branch is fully bypassed.""" + low_level_position_action: ActionTermCfg = MISSING + """Configuration of the low level position action term.""" + low_level_policy_file: str = MISSING + """Path to the low level policy file.""" + observation_group: str = "policy" + """Observation group to use for the low level policy.""" + policy_scaling: list[float] = [1.0, 1.0, 1.0] + """Policy dependent scaling for the actions [vx, vy, w].""" + reorder_joint_list: list[str] | None = None + """Reorder the joint actions given from the low-level policy to match the Isaac Sim order if policy has been + trained with a different order. Set to None to disable reordering.""" + policy_distr_type: str = "gaussian" + """Policy distribution type: 'gaussian', 'beta'.""" + # Low-pass filter parameters + enable_low_pass_filter: bool = True + """Whether to enable low-pass filtering for velocity commands.""" + low_pass_filter_alpha: float = 0.5 + """Low-pass filter smoothing factor (0.0 = no smoothing, 1.0 = maximum smoothing). + Formula: filtered_cmd = alpha * prev_filtered_cmd + (1 - alpha) * new_cmd""" diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/goal_commands.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/goal_commands.py new file mode 100644 index 0000000..d0a6a49 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/goal_commands.py @@ -0,0 +1,786 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Goal command generator for robot navigation tasks. + +Simplified architecture: +1. Terrain generation creates `valid_mask` (boolean mask of valid positions with safety padding) +2. This module samples goal/spawn positions uniformly from valid positions +3. Z-height is looked up from the visual height field + +The terrain module handles: +- Height field generation +- Obstacle detection +- Safety padding (dilation) +- Border exclusion +""" + +from __future__ import annotations + +import math +from collections.abc import Sequence +from typing import TYPE_CHECKING, Tuple, Optional + +import torch + +import isaaclab.utils.math as math_utils +from isaaclab.assets import Articulation +from isaaclab.managers import CommandTerm +from isaaclab.markers import VisualizationMarkers +from isaaclab.markers.config import ( + CUBOID_MARKER_CFG, + GREEN_ARROW_X_MARKER_CFG, + RED_ARROW_X_MARKER_CFG, +) +from isaaclab.utils.math import subtract_frame_transforms, transform_points, yaw_quat + +from isaaclab_nav_task.navigation.mdp.math_utils import vec_to_quat +from isaaclab_nav_task.terrains.terrain_constants import VERTICAL_SCALE + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + from .goal_commands_cfg import RobotNavigationGoalCommandCfg + + +# ============================================================================= +# Position Sampler (Simplified) +# ============================================================================= + +class PositionSampler: + """Samples positions uniformly from valid terrain cells. + + Uses pre-computed valid_mask from terrain generation (already has safety padding). + For spawn positions, uses spawn_mask with larger padding to account for robot body. + + Coordinate System: + - The height field has shape (num_cells_x, num_cells_y), e.g., (299, 299) + - Each cell is horizontal_scale meters (e.g., 0.1m) + - The mesh is generated with a border: border_pixels = int(border_width / horizontal_scale) + 1 + - Our valid_mask corresponds to the inner terrain (no border) + - Local coordinates are centered: (-terrain_size/2, -terrain_size/2) to (+terrain_size/2, +terrain_size/2) + - Border pixel offset is computed dynamically from terrain config (not hardcoded) + """ + + def __init__( + self, + heights: torch.Tensor, + valid_mask: torch.Tensor, + platform_mask: torch.Tensor, + terrain_size: float, + horizontal_scale: float, + device: torch.device, + platform_repeat_count: int = 10, + spawn_mask: torch.Tensor = None, + border_width: float = 0.0, + ): + """Initialize the sampler. + + Args: + heights: Height field (num_terrains, width, height) for Z-lookup. + valid_mask: Boolean mask of valid goal positions (num_terrains, width, height). + platform_mask: Boolean mask of platform positions for curriculum. + terrain_size: Size of each terrain in meters (full mesh size). + horizontal_scale: Resolution of height field in meters per cell. + device: Torch device. + platform_repeat_count: Repetition count for platform positions. + spawn_mask: Boolean mask of valid spawn positions with larger padding. + If None, defaults to valid_mask. + border_width: Border width around terrain in meters (from terrain config). + """ + self.device = device + self.terrain_size = terrain_size + self.horizontal_scale = horizontal_scale + self.heights = heights + self.valid_mask = valid_mask + self.platform_mask = platform_mask + # Use spawn_mask if provided, otherwise fall back to valid_mask + self.spawn_mask = spawn_mask if spawn_mask is not None else valid_mask + + # Use horizontal_scale as cell size (correct resolution) + self.cell_size = horizontal_scale + + # Compute border pixel offset dynamically based on terrain configuration + # Formula matches patches.py: border_pixels = int(border_width / horizontal_scale) + 1 + # This ensures valid_mask indices map correctly to mesh coordinates + self.border_pixels = int(border_width / horizontal_scale) + 1 + + # Mesh center offset (mesh is centered at origin after transform) + self.mesh_center = terrain_size / 2 # e.g., 30 / 2 = 15m + + # Build position tables for both goal and spawn sampling + self._build_position_tables(platform_repeat_count) + + def _build_position_tables(self, platform_repeat_count: int): + """Build pre-computed position tensors for efficient sampling. + + Creates two sets of position tables: + - Goal positions: from valid_mask with platform repetition for curriculum + - Spawn positions: from spawn_mask (larger padding for robot body clearance) + """ + num_terrains = self.valid_mask.shape[0] + + # ========================= + # Build GOAL position table (from valid_mask with platform repetition) + # ========================= + valid_indices = self.valid_mask.nonzero(as_tuple=False) + + # Build enhanced indices with platform repetition + enhanced_indices = [] + for terrain_idx in range(num_terrains): + terrain_valid = valid_indices[valid_indices[:, 0] == terrain_idx] + + if len(terrain_valid) == 0: + enhanced_indices.append(terrain_valid) + continue + + # Find platform positions + terrain_platform = self.platform_mask[terrain_idx] + platform_positions = terrain_platform.nonzero(as_tuple=False) + + if len(platform_positions) > 0: + # Check which valid positions are platforms (vectorized) + valid_xy = terrain_valid[:, 1:] # (num_valid, 2) + plat_xy = platform_positions # (num_platforms, 2) + + # Broadcast compare: (num_valid, 1, 2) vs (1, num_platforms, 2) + matches = (valid_xy.unsqueeze(1) == plat_xy.unsqueeze(0)).all(dim=2) + is_platform = matches.any(dim=1) + + # Repeat platform positions + platform_valid = terrain_valid[is_platform] + if len(platform_valid) > 0: + repeated = platform_valid.repeat(platform_repeat_count, 1) + terrain_valid = torch.cat([terrain_valid, repeated], dim=0) + + enhanced_indices.append(terrain_valid) + + # Count positions per terrain for goals + self.count_per_terrain = torch.zeros(num_terrains, dtype=torch.long, device=self.device) + for terrain_idx in range(num_terrains): + self.count_per_terrain[terrain_idx] = len(enhanced_indices[terrain_idx]) + + # Create padded tensor for goal positions + max_count = max(1, self.count_per_terrain.max().item()) + self.positions = torch.full( + (num_terrains, max_count, 3), -1, dtype=torch.long, device=self.device + ) + + # Fill goal position tables + for terrain_idx in range(num_terrains): + terrain_positions = enhanced_indices[terrain_idx] + num_pos = terrain_positions.shape[0] + if num_pos > 0: + self.positions[terrain_idx, :num_pos] = terrain_positions + + # ========================= + # Build SPAWN position table (from spawn_mask, no platform repetition) + # ========================= + spawn_indices = self.spawn_mask.nonzero(as_tuple=False) + + # Count spawn positions per terrain + self.spawn_count_per_terrain = torch.zeros(num_terrains, dtype=torch.long, device=self.device) + spawn_positions_list = [] + for terrain_idx in range(num_terrains): + terrain_spawn = spawn_indices[spawn_indices[:, 0] == terrain_idx] + self.spawn_count_per_terrain[terrain_idx] = len(terrain_spawn) + spawn_positions_list.append(terrain_spawn) + + # Create padded tensor for spawn positions + max_spawn_count = max(1, self.spawn_count_per_terrain.max().item()) + self.spawn_positions = torch.full( + (num_terrains, max_spawn_count, 3), -1, dtype=torch.long, device=self.device + ) + + # Fill spawn position tables + for terrain_idx in range(num_terrains): + terrain_positions = spawn_positions_list[terrain_idx] + num_pos = terrain_positions.shape[0] + if num_pos > 0: + self.spawn_positions[terrain_idx, :num_pos] = terrain_positions + + def sample(self, terrain_indices: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Sample GOAL positions for given terrain indices. + + Uses valid_mask with platform repetition for curriculum learning. + + Args: + terrain_indices: Tensor of terrain indices to sample from. + + Returns: + Tuple of (x, y, z) local coordinates in meters. + """ + return self._sample_from_table( + terrain_indices, + self.positions, + self.count_per_terrain + ) + + def sample_spawn(self, terrain_indices: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Sample SPAWN positions for given terrain indices. + + Uses spawn_mask with larger padding to account for: + - Robot body dimensions with random orientation + - Platform edge safety margins + - Controller startup behavior + + Args: + terrain_indices: Tensor of terrain indices to sample from. + + Returns: + Tuple of (x, y, z) local coordinates in meters. + """ + return self._sample_from_table( + terrain_indices, + self.spawn_positions, + self.spawn_count_per_terrain + ) + + def _sample_from_table( + self, + terrain_indices: torch.Tensor, + positions_table: torch.Tensor, + count_per_terrain: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Internal method to sample from a position table. + + Args: + terrain_indices: Tensor of terrain indices to sample from. + positions_table: Pre-computed position table (num_terrains, max_count, 3). + count_per_terrain: Number of valid positions per terrain. + + Returns: + Tuple of (x, y, z) local coordinates in meters. + """ + num_samples = terrain_indices.shape[0] + + # Random indices within valid range + valid_counts = count_per_terrain[terrain_indices].float().clamp(min=1) + random_indices = (torch.rand(num_samples, device=self.device) * valid_counts).long() + + # Lookup positions + selected = positions_table[terrain_indices, random_indices] # (n, 3) + is_valid = selected[:, 0] >= 0 + + local_x = torch.zeros(num_samples, device=self.device) + local_y = torch.zeros(num_samples, device=self.device) + local_z = torch.zeros(num_samples, device=self.device) + + if is_valid.any(): + valid_selected = selected[is_valid] + x_idx = valid_selected[:, 1] + y_idx = valid_selected[:, 2] + + # Convert to meters (accounting for border pixel offset) + # The mesh is generated with @height_field_to_mesh which adds a border + # border_pixels = int(border_width / horizontal_scale) + 1 (computed dynamically) + # Mesh vertex at (i, j) has position: (i * h_scale - terrain_size/2, j * h_scale - terrain_size/2) + # Our valid_mask[i, j] corresponds to mesh heights[i + border_pixels, j + border_pixels] + # So the world position for valid_mask[i, j] is: + # x = (i + border_pixels) * h_scale - terrain_size/2 + # y = (j + border_pixels) * h_scale - terrain_size/2 + local_x[is_valid] = (x_idx.float() + self.border_pixels) * self.cell_size - self.mesh_center + local_y[is_valid] = (y_idx.float() + self.border_pixels) * self.cell_size - self.mesh_center + + # Lookup Z from heights (our heights tensor matches valid_mask dimensions, no border offset needed) + height_values = self.heights[valid_selected[:, 0], x_idx, y_idx] + local_z[is_valid] = height_values.float() * VERTICAL_SCALE + + return local_x, local_y, local_z + + +# ============================================================================= +# Success Rate Tracker +# ============================================================================= + +class SuccessRateTracker: + """Tracks navigation success rates using a rolling buffer.""" + + def __init__(self, num_envs: int, device: torch.device, buffer_size: int = 10): + self.device = device + self.buffer_size = buffer_size + self.buffer = torch.full((num_envs, buffer_size), -1.0, device=device) + self.write_index = torch.zeros(num_envs, dtype=torch.long, device=device) + + def record_result(self, success: torch.Tensor, env_ids: torch.Tensor): + indices = self.write_index[env_ids] % self.buffer_size + self.buffer[env_ids, indices] = success[env_ids].float() + self.write_index[env_ids] += 1 + + def add(self, results: torch.Tensor, env_ids: torch.Tensor): + """Legacy alias.""" + self.record_result(results, env_ids) + + def clear(self, env_ids: torch.Tensor): + self.buffer[env_ids] = -1.0 + self.write_index[env_ids] = 0 + + def get_success_rate(self) -> torch.Tensor: + filled_count = (self.buffer >= 0).sum(dim=1).clamp(min=1) + success_count = (self.buffer > 0).sum(dim=1) + return success_count.float() / filled_count.float() + + +# ============================================================================= +# Main Navigation Goal Command Generator +# ============================================================================= + +class RobotNavigationGoalCommand(CommandTerm): + """Command generator for robot navigation goal positions. + + Samples goal and spawn positions from terrain-provided valid_mask. + """ + + cfg: RobotNavigationGoalCommandCfg + + def __init__(self, cfg: RobotNavigationGoalCommandCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + + self.env = env + self.robot: Articulation = env.scene[cfg.asset_name] + + # Terrain configuration + terrain_cfg = env.scene.terrain.cfg.terrain_generator + self.num_terrain_rows = terrain_cfg.num_rows + self.num_terrain_cols = terrain_cfg.num_cols + self.terrain_size = terrain_cfg.size[0] + + # Initialize buffers + self._init_command_buffers() + self._init_tracking_buffers() + self._init_metrics() + + # Position sampling (lazy initialization) + self._sampling_initialized = False + self._position_sampler: Optional[PositionSampler] = None + + def _init_command_buffers(self): + """Initialize command state buffers.""" + # Goal in body frame: [direction_x, direction_y, direction_z, log_distance] + self.goal_command_body = torch.zeros(self.num_envs, 4, device=self.device) + self.goal_command_body_unscaled = torch.ones(self.num_envs, 3, device=self.device) + + # World frame positions + self.goal_position_world = torch.zeros(self.num_envs, 3, device=self.device) + self.goal_position_world[:, 2] = 0.5 + + self.spawn_position_world = torch.zeros(self.num_envs, 3, device=self.device) + self.spawn_position_world[:, 2] = 0.5 + self.spawn_position_world[:, :2] = self.env.scene.env_origins[:, :2] + + self.spawn_heading_world = torch.zeros(self.num_envs, device=self.device) + + def _init_tracking_buffers(self): + """Initialize goal tracking buffers.""" + self.steps_at_goal = torch.zeros(self.num_envs, device=self.device) + self.time_at_goal = torch.zeros(self.num_envs, device=self.device) + self.required_steps_at_goal = 4.0 / self.env.step_dt + + self.initial_distance_to_goal = torch.zeros(self.num_envs, device=self.device) + self.distance_to_goal = torch.zeros(self.num_envs, device=self.device) + self.closest_distance_to_goal = torch.zeros(self.num_envs, device=self.device) + + self.total_distance_traveled = torch.zeros(self.num_envs, device=self.device) + self.previous_position = torch.zeros(self.num_envs, 3, device=self.device) + + self.goal_reach_count = torch.zeros(self.num_envs, device=self.device) + self.success_tracker = SuccessRateTracker(self.num_envs, self.device, buffer_size=10) + self.success_rate_buffer = torch.full((self.num_envs, 10), -1.0, device=self.device) + + def _init_metrics(self): + """Initialize performance metrics.""" + self.metrics["velocity_toward_goal"] = torch.zeros(self.num_envs, device=self.device) + self.metrics["velocity_magnitude"] = torch.zeros(self.num_envs, device=self.device) + self.metrics["success_rate"] = torch.zeros(self.num_envs, device=self.device) + + # ========================================================================= + # Command Interface + # ========================================================================= + + def __str__(self) -> str: + return f"NavigationGoalCommand:\n\tCommand dimension: {tuple(self.command.shape[1:])}\n" + + @property + def command(self) -> torch.Tensor: + return self.goal_command_body + + def _get_unscaled_command(self) -> torch.Tensor: + return self.goal_command_body_unscaled + + # ========================================================================= + # Position Sampling + # ========================================================================= + + def _initialize_position_sampling(self): + """Initialize position sampling from terrain-provided masks.""" + if self._sampling_initialized: + return + + # Get terrain data from scene.terrain (stored by patches system) + terrain = self.env.scene.terrain + + # Check for height field data + heights_raw = getattr(terrain, '_height_field_visual', None) + valid_mask_raw = getattr(terrain, '_height_field_valid_mask', None) + platform_mask_raw = getattr(terrain, '_height_field_platform_mask', None) + spawn_mask_raw = getattr(terrain, '_height_field_spawn_mask', None) + + if heights_raw is None or valid_mask_raw is None: + raise ValueError( + "No height field data found on terrain. " + "Ensure add_goal=True is set in terrain configuration and patches are applied." + ) + + # Move to device + heights = heights_raw.to(self.device) + valid_mask = valid_mask_raw.to(self.device) + + # Platform mask defaults to empty if not provided + if platform_mask_raw is not None: + platform_mask = platform_mask_raw.to(self.device) + else: + platform_mask = torch.zeros_like(valid_mask) + + # Spawn mask defaults to valid_mask if not provided + if spawn_mask_raw is not None: + spawn_mask = spawn_mask_raw.to(self.device) + else: + spawn_mask = valid_mask # Fall back to goal mask + + # Get terrain configuration parameters + terrain_cfg = self.env.scene.terrain.cfg.terrain_generator + horizontal_scale = terrain_cfg.horizontal_scale + # Note: border_width for height_field_to_mesh comes from sub-terrain config (HfTerrainBaseCfg), + # NOT from TerrainGeneratorCfg. Sub-terrain configs default to border_width=0.0. + # TerrainGeneratorCfg.border_width (e.g., 30.0) is for the outer grid border, not per-tile. + sub_terrain_border_width = 0.0 # Default from HfTerrainBaseCfg + + # Create sampler with both goal (valid_mask) and spawn (spawn_mask) masks + self._position_sampler = PositionSampler( + heights=heights, + valid_mask=valid_mask, + platform_mask=platform_mask, + terrain_size=self.terrain_size, + horizontal_scale=horizontal_scale, + device=self.device, + spawn_mask=spawn_mask, + border_width=sub_terrain_border_width, + ) + + self._sampling_initialized = True + + def _get_terrain_indices(self, env_ids: torch.Tensor) -> torch.Tensor: + """Get terrain indices for given environment IDs. + + The terrain index formula depends on the generation order: + - curriculum=True: column-major (row + col * num_rows) + - curriculum=False: row-major (row * num_cols + col) + + Note: terrain_levels corresponds to row, terrain_types to column. + """ + terrain = self.env.scene.terrain + levels = terrain.terrain_levels[env_ids] # row + types = terrain.terrain_types[env_ids] # col + + # Check if curriculum mode + terrain_cfg = self.env.scene.terrain.cfg.terrain_generator + if terrain_cfg.curriculum: + # Column-major order (curriculum mode iterates: for col: for row:) + return levels + types * self.num_terrain_rows + else: + # Row-major order (random mode uses np.unravel_index with (num_rows, num_cols)) + return levels * self.num_terrain_cols + types + + # ========================================================================= + # Command Sampling and Update + # ========================================================================= + + def _resample_command(self, env_ids: Sequence[int]): + """Sample new goal and spawn positions. + + Goal positions use valid_mask (smaller padding, robot just needs to reach). + Spawn positions use spawn_mask (larger padding for robot body clearance). + """ + self._initialize_position_sampling() + + if isinstance(env_ids, torch.Tensor): + env_ids_tensor = env_ids.clone().to(device=self.device, dtype=torch.long) + else: + env_ids_tensor = torch.as_tensor(env_ids, device=self.device, dtype=torch.long) + + # Reset tracking + self._reset_tracking_state(env_ids) + + # Get terrain indices + terrain_indices = self._get_terrain_indices(env_ids_tensor) + + # Sample goal positions (from valid_mask with smaller padding) + goal_x, goal_y, goal_z = self._position_sampler.sample(terrain_indices) + # Sample spawn positions (from spawn_mask with larger padding for robot body) + spawn_x, spawn_y, spawn_z = self._position_sampler.sample_spawn(terrain_indices) + + # Convert to world coordinates + terrain = self.env.scene.terrain + levels = terrain.terrain_levels[env_ids] + types = terrain.terrain_types[env_ids] + terrain_origins = terrain.terrain_origins[levels, types] + + # Update goal position + self.goal_position_world[env_ids, 0] = terrain_origins[:, 0] + goal_x + self.goal_position_world[env_ids, 1] = terrain_origins[:, 1] + goal_y + h_min, h_max = self.cfg.goal_height_offset_range + height_offset = torch.rand(len(env_ids), device=self.device) * (h_max - h_min) + h_min + self.goal_position_world[env_ids, 2] = goal_z + height_offset + + # Small spawn height offset to prevent clipping into terrain + # Note: The robot's default_root_state already includes standing height (~0.5m) + spawn_offset = 0.05 + + # Update spawn/env origin + terrain.env_origins[env_ids, 0] = terrain_origins[:, 0] + spawn_x + terrain.env_origins[env_ids, 1] = terrain_origins[:, 1] + spawn_y + terrain.env_origins[env_ids, 2] = spawn_z + spawn_offset + + # Track spawn position + self.spawn_position_world[env_ids, 0] = terrain_origins[:, 0] + spawn_x + self.spawn_position_world[env_ids, 1] = terrain_origins[:, 1] + spawn_y + self.spawn_position_world[env_ids, 2] = spawn_z + spawn_offset + + # Initialize distance metrics + self.initial_distance_to_goal[env_ids] = torch.norm( + self.robot.data.root_pos_w[env_ids] - self.goal_position_world[env_ids], dim=1 + ) + self.closest_distance_to_goal[env_ids] = self.initial_distance_to_goal[env_ids] + + def _reset_tracking_state(self, env_ids: Sequence[int]): + """Reset tracking state for specified environments.""" + self.steps_at_goal[env_ids] = 0 + self.time_at_goal[env_ids] = 0 + self.total_distance_traveled[env_ids] = 0.0 + self.previous_position[env_ids] = self.robot.data.root_pos_w[env_ids].clone() + + def _update_command(self): + """Update command in body frame.""" + # Transform goal to body frame + inverse_pos, inverse_rot = subtract_frame_transforms( + self.robot.data.root_pos_w, + self.robot.data.root_quat_w + ) + goal_in_body = transform_points( + self.goal_position_world.unsqueeze(1), + inverse_pos, + inverse_rot + ).squeeze(1) + + self.goal_command_body_unscaled = goal_in_body.clone() + + # Normalized direction and log distance + distance = torch.norm(goal_in_body, dim=-1, keepdim=True) + direction = goal_in_body / torch.clamp(distance, min=1e-6) + log_distance = torch.log(distance + 1.0) + + self.goal_command_body[:, :3] = direction + self.goal_command_body[:, 3:] = log_distance + + self._update_distance_tracking() + + def _update_distance_tracking(self): + """Update distance metrics.""" + self.distance_to_goal = torch.norm( + self.robot.data.root_pos_w - self.goal_position_world, dim=1 + ) + self.closest_distance_to_goal = torch.min( + self.closest_distance_to_goal, self.distance_to_goal + ) + + step_distance = torch.norm( + self.robot.data.root_pos_w - self.previous_position, dim=1 + ) + self.total_distance_traveled += step_distance + self.previous_position = self.robot.data.root_pos_w.clone() + + def _resample_spawn_positions(self, env_ids: Sequence[int]): + """Update spawn position tracking.""" + self.spawn_position_world[env_ids, :2] = self.env.scene.env_origins[env_ids, :2] + + # ========================================================================= + # Metrics and Reset + # ========================================================================= + + def _update_metrics(self): + """Update performance metrics.""" + position_error = self.goal_position_world - self.robot.data.root_pos_w[:, :3] + position_error_2d = position_error[:, :2] + velocity_2d = self.robot.data.root_state_w[:, 7:9] + + self.metrics["velocity_magnitude"] = torch.norm(velocity_2d, dim=1) + + direction_to_goal = position_error_2d / torch.clamp(torch.norm(position_error_2d, dim=1, keepdim=True), min=1e-6) + self.metrics["velocity_toward_goal"] = (velocity_2d * direction_to_goal).sum(dim=1) + self.metrics["success_rate"] = self.success_tracker.get_success_rate() + + def reset(self, env_ids: Sequence[int] | None = None) -> dict[str, float]: + """Reset command generator and compute episode metrics.""" + metrics_obs = self.env.observation_manager.compute_group(group_name="metrics") + success = metrics_obs["in_goal"][env_ids].squeeze(-1) + failed = ~success + + # Update legacy success rate buffer + self.success_rate_buffer[env_ids] = torch.roll( + self.success_rate_buffer[env_ids], 1, dims=1 + ) + rate = success.float() - failed.float() + rate[rate == 0] = -1 + self.success_rate_buffer[env_ids, 0] = rate + + # Reset command state + if env_ids is None: + env_ids = slice(None) + self.command_counter[env_ids] = 0 + self._resample(env_ids) + + # Return mean metrics + extras = {} + for name, value in self.metrics.items(): + extras[name] = torch.mean(value[env_ids]).item() + value[env_ids] = 0.0 + + return extras + + # ========================================================================= + # Success/Failure Tracking + # ========================================================================= + + def update_success(self, at_goal: torch.Tensor): + self.goal_reach_count += at_goal.int() + + def update_failures(self, failed: torch.Tensor): + self.goal_reach_count -= failed.int() + + # ========================================================================= + # Visualization + # ========================================================================= + + def _set_debug_vis_impl(self, debug_vis: bool): + if debug_vis: + self._setup_visualizers() + else: + self._hide_visualizers() + + def _setup_visualizers(self): + """Create visualization markers.""" + if not hasattr(self, "goal_marker"): + cfg = CUBOID_MARKER_CFG.copy() + cfg.prim_path = "/Visuals/Command/goal_position" + cfg.markers["cuboid"].size = (0.2, 0.2, 0.2) + cfg.markers["cuboid"].visual_material.diffuse_color = (0.0, 0.0, 1.0) + self.goal_marker = VisualizationMarkers(cfg) + + if not hasattr(self, "spawn_marker"): + cfg = CUBOID_MARKER_CFG.copy() + cfg.prim_path = "/Visuals/Command/spawn_position" + cfg.markers["cuboid"].size = (0.2, 0.2, 0.2) + cfg.markers["cuboid"].visual_material.diffuse_color = (1.0, 0.5, 0.0) + self.spawn_marker = VisualizationMarkers(cfg) + + if not hasattr(self, "desired_velocity_marker"): + cfg = GREEN_ARROW_X_MARKER_CFG.copy() + cfg.prim_path = "/Visuals/Command/desired_velocity" + cfg.markers["arrow"].scale = (0.5, 0.5, 0.5) + self.desired_velocity_marker = VisualizationMarkers(cfg) + + if not hasattr(self, "current_velocity_marker"): + cfg = RED_ARROW_X_MARKER_CFG.copy() + cfg.prim_path = "/Visuals/Command/current_velocity" + cfg.markers["arrow"].scale = (0.5, 0.5, 0.5) + self.current_velocity_marker = VisualizationMarkers(cfg) + + self.goal_marker.set_visibility(True) + self.spawn_marker.set_visibility(True) + self.desired_velocity_marker.set_visibility(True) + self.current_velocity_marker.set_visibility(True) + + def _hide_visualizers(self): + for name in ["goal_marker", "spawn_marker", "desired_velocity_marker", "current_velocity_marker"]: + if hasattr(self, name): + getattr(self, name).set_visibility(False) + + def _debug_vis_callback(self, event): + """Update visualization markers.""" + self.goal_marker.visualize(self.goal_position_world) + self.spawn_marker.visualize(self.spawn_position_world) + + arrow_position = self.robot.data.root_pos_w.clone() + arrow_position[:, 2] += 0.5 + + desired_scale, desired_quat = self._compute_velocity_arrow( + self.command[:, :3], is_goal_direction=True + ) + self.desired_velocity_marker.visualize(arrow_position, desired_quat, desired_scale) + + current_scale, current_quat = self._compute_velocity_arrow( + self.robot.data.root_lin_vel_b, is_goal_direction=False + ) + self.current_velocity_marker.visualize(arrow_position, current_quat, current_scale) + + def _compute_velocity_arrow( + self, + velocity: torch.Tensor, + is_goal_direction: bool + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Compute arrow visualization parameters.""" + base_scale = torch.tensor( + self.desired_velocity_marker.cfg.markers["arrow"].scale, + device=self.device + ).repeat(velocity.shape[0], 1) + + if not is_goal_direction: + velocity = velocity.clone() + velocity[:, 2] = 0.0 + + base_scale[:, 0] *= torch.norm(velocity, dim=1) * 3.0 + quat = vec_to_quat(velocity) + + if is_goal_direction: + quat = math_utils.quat_mul(self.robot.data.root_quat_w, quat) + else: + quat = math_utils.quat_mul(yaw_quat(self.robot.data.root_quat_w), quat) + + return base_scale, quat + + # ========================================================================= + # Utility Methods + # ========================================================================= + + def _is_position_in_bounds(self, position: torch.Tensor) -> torch.Tensor: + half_side = math.ceil(self.num_envs ** 0.5) * self.env.cfg.scene.env_spacing / 2 + return (position[:, :2].abs() < half_side).all(dim=1) + + def _clamp_to_bounds(self, position: torch.Tensor) -> torch.Tensor: + origins = self.env.scene.terrain.terrain_origins.view(-1, 3) + bounds_max = origins.max(dim=0)[0][:2] + bounds_min = origins.min(dim=0)[0][:2] + position[:, 0] = position[:, 0].clamp(bounds_min[0], bounds_max[0]) + position[:, 1] = position[:, 1].clamp(bounds_min[1], bounds_max[1]) + return position + + +# ============================================================================= +# Legacy Aliases +# ============================================================================= + +RobotNavigationGoalCommand.pos_command_b = property(lambda self: self.goal_command_body) +RobotNavigationGoalCommand.pos_command_w = property(lambda self: self.goal_position_world) +RobotNavigationGoalCommand.pos_spawn_w = property(lambda self: self.spawn_position_world) +RobotNavigationGoalCommand.closes_distance_to_goal = property( + lambda self: self.closest_distance_to_goal +) +RobotNavigationGoalCommand.time_at_goal_in_steps = property(lambda self: self.steps_at_goal) +RobotNavigationGoalCommand.required_time_at_goal_in_steps = property( + lambda self: self.required_steps_at_goal +) +RobotNavigationGoalCommand.goal_reached_buffer = property(lambda self: self.success_tracker) +RobotNavigationGoalCommand.goal_reached_counter = property(lambda self: self.goal_reach_count) +RobotNavigationGoalCommand.distance_traveled = property(lambda self: self.total_distance_traveled) +RobotNavigationGoalCommand.previous_pos_3d = property(lambda self: self.previous_position) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/goal_commands_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/goal_commands_cfg.py new file mode 100644 index 0000000..3c74047 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/navigation/goal_commands_cfg.py @@ -0,0 +1,45 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + + +from __future__ import annotations + +import math +from dataclasses import MISSING +from typing import TYPE_CHECKING, Literal + +from isaaclab.managers import CommandTermCfg +from isaaclab.utils import configclass +from isaaclab.utils.noise import AdditiveUniformNoiseCfg +from .goal_commands import RobotNavigationGoalCommand + + +""" +Base command generator. +""" + +@configclass +class RobotNavigationGoalCommandCfg(CommandTermCfg): + """Configuration for the robot goal command generator.""" + + class_type: type = RobotNavigationGoalCommand + + asset_name: str = MISSING + """Name of the asset in the environment for which the commands are generated.""" + + robot_to_goal_line_vis: bool = True + """If true, visualize the line from the robot to the goal.""" + + goal_height_offset_range: tuple[float, float] = (0.2, 0.8) + """Range (min, max) in meters for the random goal height offset above the ground. + + The goal cube is placed at ``terrain_ground_height + U(min, max)``. The default + (0.2, 0.8) is tuned for the B2W body height (~0.5-0.6 m). For shorter robots + such as the Go2 (standing height ~0.3 m), lower this range (e.g. (0.1, 0.4)) so + the goal marker sits near the robot body. Note: success/termination is purely + horizontal (xy), so this offset only affects visualization and the minor 3D + ``reach_goal_xy_soft`` reward term. + """ + diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/observations.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/observations.py new file mode 100644 index 0000000..e9f62ca --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/observations.py @@ -0,0 +1,507 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Observation functions for navigation tasks. + +These functions can be passed to :class:`isaaclab.managers.ObservationTermCfg` +to specify observations for the policy. +""" +from __future__ import annotations + +import os +from typing import TYPE_CHECKING, Optional, cast + +import torch +import matplotlib.pyplot as plt + +from isaaclab.assets import Articulation, RigidObject +from isaaclab.envs import ManagerBasedEnv, ManagerBasedRLEnv +from isaaclab.managers import SceneEntityCfg + +import isaaclab_nav_task.navigation.mdp as mdp + +from .depth_utils.camera_config import CameraConfig, DEFAULT_CAMERA_CONFIG, get_camera_config +from .depth_utils.depth_noise_encoder import DepthNoiseEncoder +from .heightscan_utils.heightscan_encoder import HeightScanFeatEncoder + +if TYPE_CHECKING: + from isaaclab_nav_task.navigation.mdp import PerceptiveNavigationSE2Action + from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand + +# Visualization state +_DEPTH_VIZ_WINDOWS: dict[str, dict] = {} + +# Global depth noise generator - will be initialized with camera config +DEPTH_NOISE_GENERATOR: Optional[DepthNoiseEncoder] = None +JIT_DEPTH_NOISE_GENERATOR: Optional[torch.jit.ScriptModule] = None + +# Global height scan encoder - initialized once on first use +HEIGHTSCAN_FEAT_ENCODER: Optional[HeightScanFeatEncoder] = None +JIT_HEIGHTSCAN_FEAT_ENCODER: Optional[torch.jit.ScriptModule] = None + +# Global flags/params for depth encoding +use_jit = True +min_depth = 0.0 +max_depth = 0.0 + + +def _update_depth_window(camera_name: str, depth_tensor: torch.Tensor, height: int, width: int, title: str) -> None: + """Update (or lazily create) a persistent matplotlib window for a camera. + + This enables continuous, non-blocking visualization across steps for one or more cameras. + """ + try: + # Convert to numpy and handle different tensor shapes + if depth_tensor.dim() == 4: # [B, 1, H, W] + depth_np = depth_tensor[0, 0].detach().cpu().numpy() + elif depth_tensor.dim() == 2: # [B, H*W] + depth_np = depth_tensor[0].detach().cpu().numpy().reshape(height, width) + else: + return + + # Lazily create window if missing + if camera_name not in _DEPTH_VIZ_WINDOWS: + plt.ion() + fig, ax = plt.subplots(1, 1, figsize=(8, 6)) + im = ax.imshow(depth_np, cmap="plasma", aspect="equal") + cbar = plt.colorbar(im, ax=ax, label="Depth (meters)") + ax.set_title(title) + ax.set_xlabel("Width (pixels)") + ax.set_ylabel("Height (pixels)") + _DEPTH_VIZ_WINDOWS[camera_name] = {"fig": fig, "ax": ax, "im": im, "cbar": cbar} + else: + handle = _DEPTH_VIZ_WINDOWS[camera_name] + im = handle["im"] + ax = handle["ax"] + ax.set_title(title) + im.set_data(depth_np) + # Optional: keep consistent color scaling per window + im.set_clim(vmin=depth_np.min(), vmax=depth_np.max()) + + # Lightweight draw + _DEPTH_VIZ_WINDOWS[camera_name]["fig"].canvas.draw_idle() + plt.pause(0.001) + except Exception as e: + print(f"Error updating depth window for {camera_name}: {e}") + + +def _ensure_depth_noise_generator_initialized( + camera_config: Optional[CameraConfig] = None, + use_jit_precompiled: bool = True, + feature_dim: int = 64, +): + """Ensure the depth noise generator is initialized with the correct configuration. + + This is called automatically by observation functions that need depth encoding. + If not explicitly initialized via initialize_depth_noise_generator(), it will use defaults. + + Args: + camera_config: The camera configuration to use. If None, uses DEFAULT_CAMERA_CONFIG. + use_jit_precompiled: Whether to use JIT compilation for faster inference. + feature_dim: Feature dimension for the encoder output. + """ + global DEPTH_NOISE_GENERATOR, JIT_DEPTH_NOISE_GENERATOR, use_jit, min_depth, max_depth + + # Only initialize if not already done + if DEPTH_NOISE_GENERATOR is not None: + return + + # Use provided camera config or default + config = camera_config if camera_config is not None else DEFAULT_CAMERA_CONFIG + + # Extract camera parameters + min_depth = config.min_depth + max_depth = config.max_depth + resolution = config.resolution + + print("=" * 80) + print("Initializing depth noise generator for navigation observation:") + print(f" Resolution: {resolution}") + print(f" Depth range: [{min_depth}, {max_depth}]") + print(f" Feature dim: {feature_dim}") + print(f" Encoder path: {config.depth_encoder_path}") + print(f" Use JIT: {use_jit_precompiled}") + + # Initialize encoder with the new simplified API + # The DepthNoiseEncoder now takes camera_config directly + DEPTH_NOISE_GENERATOR = DepthNoiseEncoder( + feature_dim=feature_dim, + camera_config=config, + ).to(torch.device("cuda")) + DEPTH_NOISE_GENERATOR.eval() + + # Create JIT version for inference (optional optimization) + use_jit = use_jit_precompiled + if use_jit: + # Try to find a JIT compiled version + jit_path = config.depth_encoder_path.replace('.pth', '_jit.pt') if config.depth_encoder_path else None + if jit_path and os.path.exists(jit_path): + print(f" Loading precompiled JIT model from: {jit_path}") + JIT_DEPTH_NOISE_GENERATOR = torch.jit.load(jit_path, map_location="cuda") + JIT_DEPTH_NOISE_GENERATOR = torch.jit.optimize_for_inference(JIT_DEPTH_NOISE_GENERATOR) + else: + print(f" JIT compilation requested but no precompiled model found.") + print(f" Creating JIT model from encoder...") + example_input = torch.randn(1, 1, resolution[1], resolution[0]).cuda() # (B, C, H, W) + JIT_DEPTH_NOISE_GENERATOR = torch.jit.trace(DEPTH_NOISE_GENERATOR, example_input) + JIT_DEPTH_NOISE_GENERATOR = torch.jit.optimize_for_inference(JIT_DEPTH_NOISE_GENERATOR) + else: + JIT_DEPTH_NOISE_GENERATOR = DEPTH_NOISE_GENERATOR + + print(" Depth noise generator initialized successfully") + print("=" * 80) + + +def initialize_depth_noise_generator( + camera_config: Optional[CameraConfig] = None, + robot_name: Optional[str] = None, + use_jit_precompiled: bool = True, + feature_dim: int = 64, +): + """Initialize the depth noise generator with specific configuration. + + This function should be called in the environment's __post_init__() to set up + the depth encoder before any observations are computed. + + Args: + camera_config: The camera configuration to use. If None and robot_name is provided, + uses the config for that robot. If both are None, uses DEFAULT_CAMERA_CONFIG. + robot_name: Name of the robot (e.g., 'b2w', 'aow_d'). If provided and + camera_config is None, automatically loads the appropriate camera config. + use_jit_precompiled: Whether to use JIT compilation for faster inference. Defaults to True. + feature_dim: Feature dimension for the encoder output. Defaults to 64. + + Examples: + # Using robot name (recommended for multi-robot training) + initialize_depth_noise_generator(robot_name="b2w") + + # Using explicit camera config + initialize_depth_noise_generator(camera_config=ZEDX_CAMERA_CONFIG) + """ + # If camera_config not provided, try to get it from robot_name + if camera_config is None and robot_name is not None: + camera_config = get_camera_config(robot_name, use_default_fallback=False) + + _ensure_depth_noise_generator_initialized(camera_config, use_jit_precompiled, feature_dim) + + +# ============================================================================ +# Observation Functions +# ============================================================================ + + +def generated_commands_reshaped( + env: ManagerBasedRLEnv, command_name: str, unsqueeze_pos: int = 1, flatten: bool = False +) -> torch.Tensor: + """The generated command from command term in the command manager with the given name.""" + if flatten: + return env.command_manager.get_command(command_name) + return env.command_manager.get_command(command_name).unsqueeze(unsqueeze_pos) + + +def base_lin_vel_delayed( + env: ManagerBasedEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Compute delayed root linear velocity. + + Requires env.delay_manager to exist. Each environment has a random delay + sampled from [0, max_delay] at episode reset. + + Args: + env: The environment object (must have delay_manager attribute). + asset_cfg: The name of the asset. + + Returns: + The delayed linear velocity in the asset's root frame. + """ + asset: RigidObject = env.scene[asset_cfg.name] + lin_vel = asset.data.root_lin_vel_b + return env.delay_manager.compute_delayed_lin_vel(lin_vel) + + +def base_ang_vel_delayed( + env: ManagerBasedEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Compute delayed root angular velocity. + + Requires env.delay_manager to exist. Each environment has a random delay + sampled from [0, max_delay] at episode reset. + + Args: + env: The environment object (must have delay_manager attribute). + asset_cfg: The name of the asset. + + Returns: + The delayed angular velocity in the asset's root frame. + """ + asset: RigidObject = env.scene[asset_cfg.name] + ang_vel = asset.data.root_ang_vel_b + return env.delay_manager.compute_delayed_ang_vel(ang_vel) + + +def projected_gravity_delayed( + env: ManagerBasedEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), +) -> torch.Tensor: + """Compute delayed projected gravity. + + Requires env.delay_manager to exist. Each environment has a random delay + sampled from [0, max_delay] at episode reset. + + Args: + env: The environment object (must have delay_manager attribute). + asset_cfg: The name of the asset. + + Returns: + The delayed projected gravity in the asset's root frame. + """ + asset: RigidObject = env.scene[asset_cfg.name] + projected_gravity = asset.data.projected_gravity_b + + return env.delay_manager.compute_delayed_projected_gravity(projected_gravity) + + +def height_scan_feat( + env: ManagerBasedEnv, sensor_cfg: SceneEntityCfg = SceneEntityCfg("height_scanner_critic"), offset: float = 0.5 +) -> torch.Tensor: + """Height scan feature from a ray caster sensor, encoded using a pre-trained VAE encoder. + + The height scan is reshaped to a 51x51 grid and encoded using a VAE encoder that + outputs a 64-channel, 7x7 spatial feature map (64*7*7 = 3136 features). + + Args: + env: The environment object. + sensor_cfg: The configuration of the height scanner sensor. + offset: Offset to subtract from the height values. Defaults to 0.5. + + Returns: + The encoded height scan features of shape (num_envs, 3136). + """ + global HEIGHTSCAN_FEAT_ENCODER, JIT_HEIGHTSCAN_FEAT_ENCODER + + # Initialize the encoder on first call + if HEIGHTSCAN_FEAT_ENCODER is None: + print("Initializing height scan feature encoder...") + HEIGHTSCAN_FEAT_ENCODER = HeightScanFeatEncoder(feature_dim=64).to(torch.device("cuda")) + HEIGHTSCAN_FEAT_ENCODER.eval() + JIT_HEIGHTSCAN_FEAT_ENCODER = torch.jit.script(HEIGHTSCAN_FEAT_ENCODER) + JIT_HEIGHTSCAN_FEAT_ENCODER = torch.jit.optimize_for_inference(JIT_HEIGHTSCAN_FEAT_ENCODER) + + # Get height scanner data + height_scanner = env.scene.sensors[sensor_cfg.name] + + # Compute height scan: sensor_height - hit_z - offset + scan_data = height_scanner.data.pos_w[:, 2].unsqueeze(1) - height_scanner.data.ray_hits_w[..., 2] - offset + + # Clamp the height scan data to the range [-5, 5] + scan_data = torch.clamp(scan_data, min=-5.0, max=5.0) + + # Expected grid size for the height scanner (51x51 = 2601 points) + H = W = 51 + + # Reshape the height scan data to a 2D grid + scan_data = scan_data.view(-1, H, W) + + # Encode using the pre-trained encoder + with torch.no_grad(): + encoded_scan = JIT_HEIGHTSCAN_FEAT_ENCODER(scan_data) + + # Flatten and return: (batch, 64, 7, 7) -> (batch, 3136) + return encoded_scan.view(env.num_envs, -1) + + +def generated_actions(env: ManagerBasedRLEnv, action_name: str) -> torch.Tensor: + """The generated action from action term in the action manager with the given name. + + Args: + env: The environment object. + action_name: The name of the action term. + + Returns: + The processed actions from the action term. + """ + return env.action_manager.get_term(action_name).processed_actions + + +def generated_commands_reshaped_delayed( + env: ManagerBasedRLEnv, + command_name: str, + unsqueeze_pos: int = 1, + flatten: bool = False, +) -> torch.Tensor: + """The generated command with delay applied. + + Requires env.delay_manager to exist. Each environment has a random delay + sampled from [0, max_delay] at episode reset. + + Args: + env: The environment object (must have delay_manager attribute). + command_name: The name of the command term. + unsqueeze_pos: Position to unsqueeze the command. + flatten: Whether to flatten the command. + + Returns: + The delayed command. + """ + if flatten: + command = env.command_manager.get_command(command_name) + return env.delay_manager.compute_delayed_target_position(command) + + command = env.command_manager.get_command(command_name).unsqueeze(unsqueeze_pos) + return env.delay_manager.compute_delayed_target_position(command) + + +def last_low_level_action( + env: ManagerBasedEnv, action_term: str, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot") +) -> torch.Tensor: + """The last low-level action. + + Args: + env: The environment object. + action_term: The name of the action term. + + Returns: + The last low-level action. + """ + action_term: PerceptiveNavigationSE2Action = env.action_manager._terms[action_term] + return action_term.low_level_actions[:, asset_cfg.joint_ids] + + +@torch.inference_mode() +def depth_image_prefect(env, sensor_cfg): + """Return the perfect (non-noisy) encoded depth image from the camera. + + Args: + env: The environment object. + sensor_cfg: The sensor configuration. + + Returns: + The encoded depth image features. + """ + # Ensure encoder is initialized + _ensure_depth_noise_generator_initialized() + + depth_camera = env.scene.sensors[sensor_cfg.name] + + # Get depth image tensor + depth_tensor = depth_camera.data.output["distance_to_image_plane"].view(env.num_envs, -1) + + # Handle NaN values by replacing them with 50.0 + depth_tensor = torch.nan_to_num(depth_tensor, nan=50.0, posinf=50.0, neginf=0.0) + + # Reshape the tensor to [B, 1, H, W] + H, W = depth_camera.image_shape + depth_tensor = depth_tensor.view(-1, 1, H, W) + + assert JIT_DEPTH_NOISE_GENERATOR is not None, ( + "Depth encoder JIT model is not initialized. Call initialize_depth_noise_generator first." + ) + model = cast(torch.jit.ScriptModule, JIT_DEPTH_NOISE_GENERATOR) + if use_jit: + depth_tensor[depth_tensor > max_depth] = 0.0 + encoded_depth_tensor = model(depth_tensor) + else: + encoded_depth_tensor, _ = model(depth_tensor) + + return encoded_depth_tensor.view(env.num_envs, -1) + + +@torch.no_grad() +def depth_image_noisy_delayed( + env, sensor_cfg, visualize: bool = False +): + """Return the noisy and delayed encoded depth image from the camera. + + Requires env.delay_manager to exist. Each environment has a random delay + sampled from [0, max_delay] at episode reset. + + Args: + env: The environment object (must have delay_manager attribute). + sensor_cfg: The sensor configuration. + visualize: Whether to visualize the depth image. + + Returns: + The delayed encoded depth image features. + """ + # Ensure encoder is initialized + _ensure_depth_noise_generator_initialized() + + depth_camera = env.scene.sensors[sensor_cfg.name] + + # Get depth image tensor + depth_tensor = depth_camera.data.output["distance_to_image_plane"].view(env.num_envs, -1) + + # Handle NaN values by replacing them with 50.0 + depth_tensor = torch.nan_to_num(depth_tensor, nan=50.0, posinf=50.0, neginf=0.0) + + # Reshape the tensor to [B, 1, H, W] + H, W = depth_camera.image_shape + depth_tensor = depth_tensor.view(-1, 1, H, W) + + assert JIT_DEPTH_NOISE_GENERATOR is not None, ( + "Depth encoder JIT model is not initialized. Call initialize_depth_noise_generator first." + ) + model = cast(torch.jit.ScriptModule, JIT_DEPTH_NOISE_GENERATOR) + if use_jit: + depth_tensor[depth_tensor > max_depth] = 0.0 # depth larger than depth max is invalid + depth_tensor[depth_tensor < min_depth] = 0.0 # depth smaller than depth min is invalid + encoded_depth_tensor = model(depth_tensor) + noisy_depth_tensor = depth_tensor + else: + encoded_depth_tensor, noisy_depth_tensor = model(depth_tensor) + + # Continuous visualization (single-env) with persistent windows + if visualize and env.num_envs == 1 and not use_jit: + camera_name = sensor_cfg.name if hasattr(sensor_cfg, "name") else "camera" + _update_depth_window(camera_name, noisy_depth_tensor, H, W, title=f"Depth (Noisy Delayed) - {camera_name}") + + encoded_depth_tensor_reshaped = encoded_depth_tensor.view(env.num_envs, -1) + + # Apply delay using env's delay manager + camera_name = sensor_cfg.name if hasattr(sensor_cfg, "name") else "depth" + return env.delay_manager.compute_delayed_depth(encoded_depth_tensor_reshaped, camera_name) + + +def in_goal( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + distance_threshold: float = 0.5, + goal_cmd_name: str = "robot_goal", +) -> torch.Tensor: + """Check if the robot is within the goal distance threshold. + + Args: + env: The learning environment. + asset_cfg: The name of the robot asset. + distance_threshold: The distance threshold to the goal. + goal_cmd_name: The name of the goal command. + + Returns: + Boolean tensor indicating whether the robot is within the goal. + """ + asset: Articulation = env.scene[asset_cfg.name] + goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name] + distance_goal = torch.norm(asset.data.root_pos_w[:, :2] - goal_cmd_generator.pos_command_w[:, :2], dim=1, p=2, keepdim=True) + return distance_goal < distance_threshold + + +def time_normalized(env: ManagerBasedRLEnv, command_name: str = "robot_goal") -> torch.Tensor: + """Time normalized to the maximum episode length. + + Args: + env: The learning environment. + command_name: The name of the goal command. + + Returns: + The normalized time (current step / max steps). + """ + T_max = env.max_episode_length + if hasattr(env, "episode_length_buf"): + t = env.episode_length_buf.unsqueeze(-1) + else: + t = torch.tensor([0.0]).repeat(env.num_envs, 1).to(env.device) + return t / T_max diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/rewards.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/rewards.py new file mode 100644 index 0000000..5d3c3c8 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/rewards.py @@ -0,0 +1,134 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Reward functions for navigation tasks. + +These functions can be passed to :class:`isaaclab.managers.RewardTermCfg` +to specify the reward function and its parameters. +""" +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch + +from isaaclab.assets import Articulation +from isaaclab.managers import SceneEntityCfg + +from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +def action_rate_l1(env: "ManagerBasedRLEnv") -> torch.Tensor: + """Penalize the rate of change of the actions using L1 kernel.""" + return torch.sum(torch.abs(env.action_manager.action - env.action_manager.prev_action), dim=1) + + +def lateral_movement(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: + """Reward the agent for moving laterally using L1-Kernel. + + Args: + env: The learning environment. + asset_cfg: The name of the robot asset. + + Returns: + Dense reward [0, +1] based on the lateral velocity. + """ + asset: Articulation = env.scene[asset_cfg.name] + # compute the reward + lateral_velocity = asset.data.root_lin_vel_b[:, 1] + reward = torch.abs(lateral_velocity) + return reward + + +def rot_movement(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: + """Reward the agent for rotating around the z-axis using an L2-Kernel. + + Args: + env: The learning environment. + asset_cfg: The name of the robot asset. + + Returns: + Dense reward [0, +1] based on the rotational velocity. + """ + asset: Articulation = env.scene[asset_cfg.name] + rot_vel_norm = torch.norm(asset.data.root_ang_vel_b, dim=1) + return rot_vel_norm + + +def reach_goal_xyz( + env: ManagerBasedRLEnv, + command_name: str, + sigmoid: float, + T_r: float, + probability: float, + flat: bool, + ratio: bool, +) -> torch.Tensor: + """Reward goal reaching with configurable sigmoid shaping. + + Args: + env: The learning environment. + command_name: Name of the goal command. + sigmoid: Sigmoid parameter for shaping. + T_r: Time reward scaling factor. + probability: Probability of random sampling. + flat: Whether to only consider xy error (ignore z). + ratio: Whether to scale by travel distance ratio. + + Returns: + Dense reward based on distance to goal. + """ + goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[command_name] + + t = env.episode_length_buf + T = env.max_episode_length + + if flat: + xyz_error = torch.norm(goal_cmd_generator._get_unscaled_command()[:, :2], dim=1) + else: + xyz_error = torch.norm(goal_cmd_generator._get_unscaled_command(), dim=1) + + reward = 1 / (1 + torch.square(xyz_error / sigmoid)) / T_r + + timeup_mask = t > (T - goal_cmd_generator.required_time_at_goal_in_steps) + random_mask = torch.rand_like(t.float()) < probability + timeup_mask = torch.logical_or(timeup_mask, random_mask) + + arrive_mask = goal_cmd_generator.time_at_goal > 0.0 + reward_mask = torch.logical_or(timeup_mask, arrive_mask) + + if ratio: + # Calculate the travel distance ratio relative to the initial goal distance + travel_distance = torch.max( + goal_cmd_generator.distance_traveled, goal_cmd_generator.initial_distance_to_goal + ) + travel_distance_ratio = goal_cmd_generator.initial_distance_to_goal / (travel_distance + 1e-6) + else: + travel_distance_ratio = torch.ones_like(reward) + + reward = reward * reward_mask.float() * travel_distance_ratio + + return reward + + +def backward_movement_penalty(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: + """Small penalty for backward movement as a regularization term. + + Args: + env: The learning environment. + asset_cfg: The name of the robot asset. + + Returns: + Penalty [0, +1] based on backward velocity (to be used with negative weight). + """ + asset: Articulation = env.scene[asset_cfg.name] + # compute the penalty + forward_velocity = asset.data.root_lin_vel_b[:, 0] + # Only penalize negative forward velocity (backward movement) + backward_velocity = torch.clamp(-forward_velocity, min=0.0, max=1.0) + return backward_velocity diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/terminations.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/terminations.py new file mode 100644 index 0000000..5e3883f --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/mdp/terminations.py @@ -0,0 +1,211 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Common functions that can be used to activate certain terminations. + +The functions can be passed to the :class:`isaaclab.managers.TerminationTermCfg` object to enable +the termination introduced by the function. +""" + +from __future__ import annotations + +import torch +from typing import TYPE_CHECKING + +from isaaclab.assets import Articulation +from isaaclab.managers import SceneEntityCfg +from isaaclab.sensors import ContactSensor +from isaaclab.utils.math import quat_inv, yaw_quat, quat_mul, euler_xyz_from_quat + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand + + +def euler_xyz_from_quat_wrapped(quat: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Convert quaternion to Euler angles (XYZ convention) with wrapping to [-pi, pi]. + + Args: + quat: Quaternion tensor of shape (..., 4) in (w, x, y, z) format. + + Returns: + Tuple of (roll, pitch, yaw) tensors. + """ + roll, pitch, yaw = euler_xyz_from_quat(quat) + # Wrap to [-pi, pi] + roll = torch.remainder(roll + torch.pi, 2 * torch.pi) - torch.pi + pitch = torch.remainder(pitch + torch.pi, 2 * torch.pi) - torch.pi + yaw = torch.remainder(yaw + torch.pi, 2 * torch.pi) - torch.pi + return roll, pitch, yaw + + +def time_out_navigation( + env: "ManagerBasedRLEnv", + goal_cmd_name: str = "robot_goal", + distance_threshold: float = 0.5 +) -> torch.Tensor: + """Terminate the episode when the episode length exceeds the maximum episode length. + + This also tracks success metrics by checking if the robot reached the goal before timeout. + """ + from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand + + goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name] + + termination = env.episode_length_buf >= env.max_episode_length + + env_ids = torch.where(termination)[0] + + distance_goal = torch.norm(goal_cmd_generator._get_unscaled_command()[:, :2], dim=1) + + # update time at goal + goal_cmd_generator.time_at_goal[distance_goal < distance_threshold] += 1 * env.step_dt + + if env_ids.numel() > 0: # Check if env_ids is not empty + success_masks = goal_cmd_generator.time_at_goal > 0.0 + value_buffer = torch.zeros_like(distance_goal) # init with 0: Fail + value_buffer[success_masks] = 1.0 # Success + goal_cmd_generator.goal_reached_buffer.add(value_buffer, env_ids) + + return termination + + +def illegal_contact_navigation( + env: "ManagerBasedRLEnv", + threshold: float, + sensor_cfg: SceneEntityCfg, + goal_cmd_name: str = "robot_goal", +) -> torch.Tensor: + """Terminate when the contact force on the sensor exceeds the force threshold.""" + from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand + + # extract the used quantities (to enable type-hinting) + contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] + net_contact_forces = contact_sensor.data.net_forces_w_history + goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name] + + termination = torch.any( + torch.max(torch.norm(net_contact_forces[:, :, sensor_cfg.body_ids], dim=-1), dim=1)[0] > threshold, dim=1 + ) + + env_ids = torch.where(termination)[0] + + if env_ids.numel() > 0: # Check if env_ids is not empty + goal_cmd_generator.goal_reached_buffer.add(torch.zeros_like(termination, dtype=torch.float), env_ids) + + return termination + + +def large_angle_termination_navigation( + env: "ManagerBasedRLEnv", + threshold: float, + goal_cmd_name: str = "robot_goal", +) -> torch.Tensor: + """Terminate when the robot exceeds a pitch or roll angle threshold.""" + from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand + + goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms[goal_cmd_name] + + # degree to rad + threshold_rad = threshold * torch.pi / 180.0 + + robot = env.scene["robot"] + yaw_q = yaw_quat(robot.data.root_quat_w) + base_quat_b = quat_mul(quat_inv(yaw_q), robot.data.root_quat_w) + robot_roll, robot_pitch, _ = euler_xyz_from_quat_wrapped(base_quat_b) + + termination = torch.logical_or(torch.abs(robot_pitch) > threshold_rad, torch.abs(robot_roll) > threshold_rad) + + env_ids = torch.where(termination)[0] + + if env_ids.numel() > 0: # Check if env_ids is not empty + goal_cmd_generator.goal_reached_buffer.add(torch.zeros_like(termination, dtype=torch.float), env_ids) + + return termination + + +def at_goal_navigation( + env: "ManagerBasedRLEnv", + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + distance_threshold: float = 0.5, + goal_cmd_name: str = "robot_goal", +) -> torch.Tensor: + """Terminate the episode when the goal is reached. + + Args: + env: The learning environment. + asset_cfg: The name of the robot asset. + distance_threshold: The distance threshold to the goal. + goal_cmd_name: The name of the goal command term. + + Returns: + Boolean tensor indicating whether the goal is reached. + """ + from isaaclab_nav_task.navigation.mdp.navigation.goal_commands import RobotNavigationGoalCommand + + # Extract the used quantities + asset: Articulation = env.scene[asset_cfg.name] + goal_cmd_generator: RobotNavigationGoalCommand = env.command_manager._terms.get(goal_cmd_name) + + # Calculate distance to goal + xy_error = torch.norm(goal_cmd_generator._get_unscaled_command()[:, :2], dim=1) + + # Check conditions for termination + at_goal = xy_error < distance_threshold + + # already at goal + already_at_goal = goal_cmd_generator.time_at_goal > 0.0 + at_goal = torch.logical_or(at_goal, already_at_goal) + + # Update the time at goal in steps + goal_cmd_generator.time_at_goal_in_steps[at_goal] += 1 # Increment if at goal + + # Determine if termination condition is met + termination = goal_cmd_generator.time_at_goal_in_steps > goal_cmd_generator.required_time_at_goal_in_steps + + # Update goal reached buffer if termination condition is met + env_ids = torch.where(termination)[0] + if env_ids.numel() > 0: # Check if any environments have met the termination condition + goal_cmd_generator.goal_reached_buffer.add(torch.ones_like(termination, dtype=torch.float), env_ids) + + return termination + + +def terrain_fall( + env: "ManagerBasedRLEnv", + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + fall_height_threshold: float = -1.0, + goal_cmd_name: str = "robot_goal", +) -> torch.Tensor: + """Terminate when the robot falls below a certain height threshold. + + This termination is triggered when the robot's z-position falls below a + specified threshold, indicating that the robot has fallen off the terrain + or into a deep pit. + + Args: + env: The learning environment. + asset_cfg: The configuration for the robot asset. + fall_height_threshold: The z-height below which the robot is considered fallen (in meters). + Default is -1.0m to account for pits which can be ~1.5m deep. + goal_cmd_name: The name of the goal command term. + + Returns: + Boolean tensor indicating whether the robot has fallen. + """ + # Direct tensor access for z-coordinate (avoids intermediate variable allocation) + termination = env.scene[asset_cfg.name].data.root_pos_w[:, 2] < fall_height_threshold + + # Early exit if no terminations (common case - avoids torch.where overhead) + if not termination.any(): + return termination + + # Update goal reached buffer with failure + goal_cmd = env.command_manager._terms.get(goal_cmd_name) + if goal_cmd is not None: + env_ids = termination.nonzero(as_tuple=False).squeeze(-1) + goal_cmd.goal_reached_buffer.add(torch.zeros(env.num_envs, dtype=torch.float, device=env.device), env_ids) + + return termination diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/navigation_env.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/navigation_env.py new file mode 100644 index 0000000..bd778f8 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/navigation_env.py @@ -0,0 +1,44 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Custom navigation environment with observation delay support.""" +from __future__ import annotations + +from typing import TYPE_CHECKING + +from isaaclab.envs import ManagerBasedRLEnv + +from isaaclab_nav_task.navigation.mdp.delay_manager import ObservationDelayManager + +if TYPE_CHECKING: + from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg + + +class NavigationEnv(ManagerBasedRLEnv): + """Navigation environment with observation delay manager. + + This environment extends the base ManagerBasedRLEnv to add support for + simulating sensor delays. The delay_manager is created before managers + are loaded, ensuring observations can access it during initialization. + """ + + cfg: NavigationEnvCfg + + def load_managers(self): + """Load managers with delay manager initialization. + + The delay_manager is created before other managers are loaded, + ensuring observations can access it during initialization. + """ + # Create the delay manager before loading other managers + # At this point, self.num_envs and self.device are available via scene + self.delay_manager = ObservationDelayManager( + cfg=self.cfg.delay_cfg, + num_envs=self.num_envs, + device=self.device, + ) + + # Now load all other managers + super().load_managers() diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/navigation_env_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/navigation_env_cfg.py new file mode 100644 index 0000000..a4e63c6 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/navigation/navigation_env_cfg.py @@ -0,0 +1,445 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Navigation environment configuration. + +This module provides the base environment configuration for navigation tasks +with visual perception using depth cameras. +""" + +import math +import os +from dataclasses import MISSING + +import isaaclab.sim as sim_utils +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import CurriculumTermCfg as CurrTerm +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import ContactSensorCfg, RayCasterCfg, patterns, RayCasterCameraCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR +from isaaclab.utils.noise import AdditiveUniformNoiseCfg as Unoise + +import isaaclab_nav_task.navigation.mdp as mdp +from isaaclab_nav_task.navigation.mdp.custom_noise import DeltaTransformationNoiseCfg +from isaaclab_nav_task.navigation.mdp.delay_manager import ObservationDelayManagerCfg +from isaaclab_nav_task.navigation.assets import ISAACLAB_NAV_TASKS_ASSETS_DIR + +## +# Pre-defined configs +## +from isaaclab_nav_task.terrains import MAZE_TERRAIN_CFG # isort: skip + +# Constants +LEG_JOINT_NAMES = [".*HAA", ".*HFE", ".*KFE"] +LEG_BODY_NAMES = [".*HIP", ".*THIGH", ".*SHANK"] +WHEEL_JOINT_NAMES = [".*WHEEL"] +WHEEL_BODY_NAMES = [".*WHEEL_L"] +PLANNING_FREQ = 5.0 # Hz + +## +# Scene definition +## + + +@configclass +class MySceneCfg(InteractiveSceneCfg): + """Configuration for the terrain scene with a legged robot.""" + + # ground terrain + terrain = TerrainImporterCfg( + prim_path="/World/ground", + terrain_type="generator", + terrain_generator=MAZE_TERRAIN_CFG, + max_init_terrain_level=0, + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + restitution=0.1, + static_friction=1.0, + dynamic_friction=0.8, + compliant_contact_stiffness=5e5, + compliant_contact_damping=300.0, + ), + visual_material=sim_utils.MdlFileCfg( + mdl_path=f"{ISAACLAB_NUCLEUS_DIR}/Materials/TilesMarbleSpiderWhiteBrickBondHoned/TilesMarbleSpiderWhiteBrickBondHoned.mdl", + project_uvw=True, + texture_scale=(0.25, 0.25), + ), + debug_vis=False, + ) + # robots + robot: ArticulationCfg = MISSING + + raycast_camera = RayCasterCameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + mesh_prim_paths=["/World/ground"], + update_period=0, + offset=RayCasterCameraCfg.OffsetCfg( + pos=(0.4761, 0.0035, 0.1055), rot=(0.9848078, 0.0, 0.1736482, 0.0), convention="world" # 20 degrees + ), + data_types=["distance_to_image_plane"], + debug_vis=False, + max_distance=11.0, + pattern_cfg=patterns.PinholeCameraPatternCfg.from_ros_camera_info( + # ZED camera parameters from ROS camera_info topic + fx=72.7025, + fy=72.7025, + cx=94.4457, + cy=62.5424, + width=192, + height=120, + downsample_factor=3, # Downsample from 192x120 to 64x40 + ), + ) + + height_scanner_critic = RayCasterCfg( + prim_path="{ENV_REGEX_NS}/Robot/base", + offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)), + # attach_yaw_only=True, + ray_alignment='yaw', + pattern_cfg=patterns.GridPatternCfg(resolution=0.2, size=[10.0, 10.0]), + debug_vis=False, + mesh_prim_paths=["/World/ground"], + ) + + contact_forces = ContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True) + # lights + sky_light = AssetBaseCfg( + prim_path="/World/skyLight", + spawn=sim_utils.DomeLightCfg( + intensity=750.0, + texture_file=f"{ISAAC_NUCLEUS_DIR}/Materials/Textures/Skies/PolyHaven/kloofendal_43d_clear_puresky_4k.hdr", + ), + ) + + +## +# MDP settings +## + + +@configclass +class CommandsCfg: + """Command specifications for the MDP.""" + + robot_goal = mdp.RobotNavigationGoalCommandCfg( + asset_name="robot", + # Large value to disable automatic resampling - goals only change on episode reset + # Note: math.inf doesn't work with PyTorch's uniform_(), so we use 1e9 (~31 years) + resampling_time_range=(1e9, 1e9), + debug_vis=True, + ) + + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + + velocity_command = mdp.PerceptiveNavigationSE2ActionCfg( + asset_name="robot", + low_level_position_action=mdp.JointPositionActionCfg( + asset_name="robot", joint_names=[".*HAA", ".*HFE", ".*KFE"], scale=0.5, use_default_offset=True + ), + low_level_velocity_action=mdp.JointVelocityActionCfg( + asset_name="robot", joint_names=[".*WHEEL"], scale=5.0, use_default_offset=True + ), + low_level_decimation=4, + low_level_policy_file=os.path.join( + ISAACLAB_NAV_TASKS_ASSETS_DIR, "Policies", "locomotion", "aow_d", "policy_blind_3_1.pt" + ), + observation_group="low_level_policy", + policy_scaling=[1.5, 1.0, 1.0], + use_raw_actions=True, + policy_distr_type="gaussian", + ) + + +@configclass +class ObservationsCfg: + """Observation specifications for the MDP.""" + + @configclass + class PolicyCfg(ObsGroup): + """Observations for policy group.""" + + base_lin_vel = ObsTerm( + func=mdp.base_lin_vel_delayed, noise=Unoise(n_min=-0.2, n_max=0.2) + ) + base_ang_vel = ObsTerm( + func=mdp.base_ang_vel_delayed, noise=Unoise(n_min=-0.1, n_max=0.1) + ) + projected_gravity = ObsTerm( + func=mdp.projected_gravity_delayed, noise=Unoise(n_min=-0.1, n_max=0.1) + ) + last_action = ObsTerm(func=mdp.last_action) + target_position = ObsTerm( + func=mdp.generated_commands_reshaped_delayed, + params={"command_name": "robot_goal", "flatten": True}, + noise=DeltaTransformationNoiseCfg(rotation=0.1, translation=0.5, noise_prob=0.1, remove_dist=False), + ) + depth_image = ObsTerm( + func=mdp.depth_image_noisy_delayed, params={"sensor_cfg": SceneEntityCfg("raycast_camera")} + ) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + @configclass + class CriticCfg(ObsGroup): + """Observations for critic group.""" + + base_lin_vel = ObsTerm(func=mdp.base_lin_vel) + base_ang_vel = ObsTerm(func=mdp.base_ang_vel) + projected_gravity = ObsTerm(func=mdp.projected_gravity) + last_action = ObsTerm(func=mdp.last_action) + target_position = ObsTerm( + func=mdp.generated_commands_reshaped, params={"command_name": "robot_goal", "flatten": True} + ) + time_normalized = ObsTerm(func=mdp.time_normalized, params={"command_name": "robot_goal"}) + height_scan_critic = ObsTerm( + func=mdp.height_scan_feat, params={"sensor_cfg": SceneEntityCfg("height_scanner_critic")} + ) + depth_image = ObsTerm(func=mdp.depth_image_prefect, params={"sensor_cfg": SceneEntityCfg("raycast_camera")}) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + @configclass + class LowLevelPolicyCfg(ObsGroup): + """Observations for low-level policy.""" + + base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.2, n_max=0.2)) + base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.1, n_max=0.1)) + projected_gravity = ObsTerm(func=mdp.projected_gravity, noise=Unoise(n_min=-0.1, n_max=0.1)) + velocity_commands = ObsTerm(func=mdp.generated_actions, params={"action_name": "velocity_command"}) + joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.2, n_max=0.2)) + joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5)) + actions = ObsTerm(func=mdp.last_low_level_action, params={"action_term": "velocity_command"}) + + def __post_init__(self): + self.enable_corruption = True + self.concatenate_terms = True + + @configclass + class MetricsCfg(ObsGroup): + """Observations for metrics tracking.""" + + in_goal = ObsTerm(func=mdp.in_goal) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = False + + # Observation groups + metrics: MetricsCfg = MetricsCfg() + policy: PolicyCfg = PolicyCfg() + critic: CriticCfg = CriticCfg() + low_level_policy: LowLevelPolicyCfg = LowLevelPolicyCfg() + +@configclass +class EventCfg: + """Configuration for events.""" + + # Startup events + physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*"), + "static_friction_range": (0.8, 1.2), + "dynamic_friction_range": (0.7, 1.0), + "restitution_range": (0.0, 0.1), + "num_buckets": 64, + }, + ) + + # Reset events + reset_base = EventTerm( + func=mdp.reset_root_state_uniform, + mode="reset", + params={ + "pose_range": {"x": (-0.0, 0.0), "y": (-0.0, 0.0), "yaw": (-math.pi, math.pi)}, + "velocity_range": {"x": (-0.0, 0.0), "y": (-0.0, 0.0), "z": (-0.0, 0.0)}, + }, + ) + + reset_robot_joints = EventTerm( + func=mdp.reset_joints_by_scale, + mode="reset", + params={"position_range": (0.5, 1.5), "velocity_range": (0.0, 0.0)}, + ) + + randomize_camera_height = EventTerm( + func=mdp.randomize_camera_height, + mode="reset", + params={ + "height_range": 0.1, + "roll_angle_range": 5.0, + "pitch_angle_range": 5.0, + "yaw_angle_range": 5.0, + "asset_cfg": SceneEntityCfg("raycast_camera"), + }, + ) + + randomize_action_scale = EventTerm( + func=mdp.randomize_action_scale, + mode="reset", + params={ + "scale_range_x": (0.8, 1.2), + "scale_range_y": (0.6, 1.0), + "scale_range_theta": (0.8, 1.2), + "scale_range_xb": 0.1, + "scale_range_yb": 0.2, + "scale_range_thetab": 0.1, + "action_term": "velocity_command", + }, + ) + + reset_delay_buffer = EventTerm( + func=mdp.reset_and_randomize_delay_buffer, + mode="reset", + ) + + randomize_low_pass_filter_alpha = EventTerm( + func=mdp.randomize_low_pass_filter_alpha, + mode="reset", + params={ + "alpha_range": (0.4, 0.9), + "action_term": "velocity_command", + "per_dimension": True, + "alpha_range_vx": (0.4, 0.9), + "alpha_range_vy": (0.4, 0.9), + "alpha_range_omega": (0.4, 0.9), + }, + ) + + # Interval events + push_robot = EventTerm( + func=mdp.push_by_setting_velocity, + mode="interval", + interval_range_s=(0.2, 5.0), + params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}}, + ) + +@configclass +class RewardsCfg: + """Reward terms for the MDP.""" + + # Penalties + joint_acc_l2_joint = RewTerm( + func=mdp.joint_acc_l2, + weight=-1e-7, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=LEG_JOINT_NAMES + WHEEL_JOINT_NAMES)}, + ) + + lateral_movement = RewTerm(func=mdp.lateral_movement, weight=-0.1) + rot_movement = RewTerm(func=mdp.rot_movement, weight=-1e-5) + action_rate_l1 = RewTerm(func=mdp.action_rate_l1, weight=-0.1) + episode_termination = RewTerm(func=mdp.is_terminated, weight=-50.0) + + # Goal rewards + reach_goal_xy_soft = RewTerm( + func=mdp.reach_goal_xyz, + weight=0.25, + params={"command_name": "robot_goal", "sigmoid": 2.5, "T_r": 1.0, "probability": 0.01, "flat": False, "ratio": False}, + ) + reach_goal_xy_tight = RewTerm( + func=mdp.reach_goal_xyz, + weight=1.5, + params={"command_name": "robot_goal", "sigmoid": 0.25, "T_r": 0.1, "probability": 0.01, "flat": True, "ratio": False}, + ) + + # Backward movement penalty (disabled by default, can be enabled via curriculum) + backward_movement_penalty = RewTerm(func=mdp.backward_movement_penalty, weight=-0.0) + + +@configclass +class TerminationsCfg: + """Termination terms for the MDP.""" + + time_out = DoneTerm(func=mdp.time_out_navigation, time_out=True, params={"distance_threshold": 0.5}) + base_contact = DoneTerm( + func=mdp.illegal_contact_navigation, + params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=["base", ".*HIP", ".*THIGH"]), "threshold": 1.0}, + ) + large_pitch_angle = DoneTerm(func=mdp.large_angle_termination_navigation, params={"threshold": 40}) + early_termination = DoneTerm(func=mdp.at_goal_navigation, time_out=True, params={"distance_threshold": 0.5}) + # Terrain fall termination (robot fell off terrain or into deep pit) + terrain_fall = DoneTerm( + func=mdp.terrain_fall, + time_out=True, + params={"fall_height_threshold": -2.0}, + ) + + +@configclass +class CurriculumCfg: + """Curriculum terms for the MDP.""" + + disable_backward_penalty = CurrTerm( + func=mdp.disable_backward_penalty_after_steps, + params={"disable_after_steps": 500, "action_term": "velocity_command"}, + ) + +## +# Environment configuration +## + + +@configclass +class NavigationEnvCfg(ManagerBasedRLEnvCfg): + """Configuration for the navigation environment with velocity-tracking.""" + + # Scene settings + scene: MySceneCfg = MySceneCfg(num_envs=2048, env_spacing=2.5, replicate_physics=False) + # Basic settings + observations: ObservationsCfg = ObservationsCfg() + actions: ActionsCfg = ActionsCfg() + commands: CommandsCfg = CommandsCfg() + # MDP settings + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + events: EventCfg = EventCfg() + curriculum: CurriculumCfg = CurriculumCfg() + # Observation delay configuration + delay_cfg: ObservationDelayManagerCfg = ObservationDelayManagerCfg() + + def __post_init__(self): + """Post initialization.""" + # Simulation settings: low_level_policy runs at 50Hz + self.sim.dt = 0.005 + self.is_finite_horizon = True + self.low_level_decimation = 4 + self.decimation = int((1 / self.sim.dt) / PLANNING_FREQ) + self.episode_length_s = 60.0 + self.sim.render_interval = self.low_level_decimation + self.sim.disable_contact_processing = True + self.sim.physics_material = self.scene.terrain.physics_material + + # Update sensor periods + if self.scene.height_scanner_critic is not None: + self.scene.height_scanner_critic.update_period = self.decimation * self.sim.dt + if self.scene.raycast_camera is not None: + self.scene.raycast_camera.update_period = self.decimation * self.sim.dt + if self.scene.contact_forces is not None: + self.scene.contact_forces.update_period = self.sim.dt + self.scene.contact_forces.history_length = self.decimation + + # Terrain curriculum settings + self.scene.terrain.max_init_terrain_level = 10 + self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0] + self.scene.terrain.terrain_generator.curriculum = False diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/__init__.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/__init__.py new file mode 100644 index 0000000..1d6d35f --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/__init__.py @@ -0,0 +1,63 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Maze terrain generation for navigation tasks. + +This module provides: +- Maze terrain generation with various obstacle types +- Stair/platform terrain for elevation training +- Pit terrain with negative obstacles +- Monkey-patches for Isaac Lab terrain system integration +- Optimized mesh generation for reduced GPU memory + +Key files: +- terrain_constants.py: Centralized height values and thresholds +- hf_terrains_maze.py: Terrain generation functions +- hf_terrains_maze_cfg.py: Terrain configurations +- patches.py: Isaac Lab integration patches +""" + +# Patches first (no Isaac Sim required) +from .patches import apply_terrain_patches + +# Constants (no Isaac Sim required) +from .terrain_constants import ( + HEIGHTS, + THRESHOLDS, + PADDING, + STAIRS, + HeightValues, + SamplingThresholds, + VERTICAL_SCALE, + HORIZONTAL_SCALE, + CELL_SIZE, + CELL_PIXELS, +) + +# Terrain generation (requires Isaac Sim) +from .hf_terrains_maze_cfg import HfMazeTerrainCfg +from .hf_terrains_maze import maze_terrain +from .maze_config import MAZE_TERRAIN_CFG + +__all__ = [ + # Patches + "apply_terrain_patches", + # Constants + "HEIGHTS", + "THRESHOLDS", + "PADDING", + "STAIRS", + "HeightValues", + "SamplingThresholds", + "VERTICAL_SCALE", + "HORIZONTAL_SCALE", + "CELL_SIZE", + "CELL_PIXELS", + # Terrain configs + "HfMazeTerrainCfg", + "MAZE_TERRAIN_CFG", + # Terrain functions + "maze_terrain", +] diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/hf_terrains_maze.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/hf_terrains_maze.py new file mode 100644 index 0000000..0363cfc --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/hf_terrains_maze.py @@ -0,0 +1,714 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Maze terrain generation for navigation tasks. + +This module generates terrain height fields with explicit valid position masks. +The key simplification is that terrain generation directly outputs: +- `heights`: Actual terrain heights for rendering/physics +- `valid_mask`: Boolean mask of valid goal/spawn positions + +This eliminates the need for complex height-based classification in goal sampling. + +The terrain data is stored on the config during generation, then picked up by +the patches system and stored on TerrainImporter for access via: +- self.env.scene.terrain._height_field_visual +- self.env.scene.terrain._height_field_valid_mask +- self.env.scene.terrain._height_field_platform_mask +""" + +from __future__ import annotations + +import numpy as np +from dataclasses import dataclass, field +from scipy.ndimage import binary_dilation, rotate, shift +from typing import TYPE_CHECKING, Tuple + +import torch + +from isaaclab.terrains.height_field.utils import height_field_to_mesh + +from .terrain_constants import HEIGHTS, PADDING, STAIRS, OBSTACLES, ObstacleType + +if TYPE_CHECKING: + from . import hf_terrains_maze_cfg + + +# ============================================================================= +# Terrain Data Container +# ============================================================================= + +@dataclass +class TerrainData: + """Container for terrain height field and valid position mask. + + Attributes: + heights: Height field for rendering/physics (actual terrain heights). + valid_mask: Boolean mask where True = valid for goals/spawns. + platform_mask: Boolean mask where True = elevated platform (for curriculum). + """ + heights: np.ndarray + valid_mask: np.ndarray + platform_mask: np.ndarray = field(default_factory=lambda: np.array([])) + + @classmethod + def create(cls, width: int, height: int) -> "TerrainData": + """Create empty terrain data with ground-level heights.""" + return cls( + heights=np.zeros((width, height), dtype=np.int16), + valid_mask=np.ones((width, height), dtype=bool), # Start all valid + platform_mask=np.zeros((width, height), dtype=bool), + ) + + def set_obstacle( + self, + x_start: int, x_end: int, + y_start: int, y_end: int, + height_value: int + ): + """Set a region as an obstacle (invalid for goals).""" + self.heights[x_start:x_end, y_start:y_end] = height_value + self.valid_mask[x_start:x_end, y_start:y_end] = False + + def set_platform( + self, + x_start: int, x_end: int, + y_start: int, y_end: int, + height_value: int + ): + """Set a region as a platform (valid for goals, elevated).""" + self.heights[x_start:x_end, y_start:y_end] = height_value + self.valid_mask[x_start:x_end, y_start:y_end] = True + self.platform_mask[x_start:x_end, y_start:y_end] = True + + def set_ground(self, x_start: int, x_end: int, y_start: int, y_end: int): + """Set a region as flat ground (valid for goals).""" + self.heights[x_start:x_end, y_start:y_end] = HEIGHTS.GROUND + self.valid_mask[x_start:x_end, y_start:y_end] = True + self.platform_mask[x_start:x_end, y_start:y_end] = False + + def apply_padding(self, padding_cells: int): + """Dilate invalid regions by padding cells for safety margin.""" + obstacles = ~self.valid_mask + kernel = np.ones((2 * padding_cells + 1, 2 * padding_cells + 1), dtype=bool) + dilated = binary_dilation(obstacles, structure=kernel) + self.valid_mask = ~dilated + + def create_spawn_mask(self, spawn_padding_cells: int) -> np.ndarray: + """Create a mask for spawn positions with larger padding than goals.""" + extra_padding = spawn_padding_cells - PADDING.GOAL_PADDING + if extra_padding > 0: + obstacles = ~self.valid_mask + kernel = np.ones((2 * extra_padding + 1, 2 * extra_padding + 1), dtype=bool) + dilated = binary_dilation(obstacles, structure=kernel) + return ~dilated + return self.valid_mask.copy() + + def exclude_borders(self, border_cells: int = 2): + """Mark terrain borders as invalid.""" + self.valid_mask[:border_cells, :] = False + self.valid_mask[-border_cells:, :] = False + self.valid_mask[:, :border_cells] = False + self.valid_mask[:, -border_cells:] = False + + def apply_height_transition_padding(self, height_threshold: int, padding_cells: int): + """Mark cells near height transitions as invalid.""" + grad_x = np.abs(np.diff(self.heights, axis=0, prepend=self.heights[:1, :])) + grad_y = np.abs(np.diff(self.heights, axis=1, prepend=self.heights[:, :1])) + grad_x_back = np.abs(np.diff(self.heights, axis=0, append=self.heights[-1:, :])) + grad_y_back = np.abs(np.diff(self.heights, axis=1, append=self.heights[:, -1:])) + + max_grad = np.maximum.reduce([grad_x, grad_y, grad_x_back, grad_y_back]) + transition_mask = (max_grad >= height_threshold).astype(bool) + + if padding_cells > 0: + kernel = np.ones((2 * padding_cells + 1, 2 * padding_cells + 1), dtype=bool) + transition_mask = binary_dilation(transition_mask, structure=kernel).astype(bool) + + self.valid_mask = self.valid_mask & ~transition_mask + + +def get_cell_bounds( + cell_x: int, cell_y: int, cell_pixels: int, max_x: int, max_y: int +) -> Tuple[int, int, int, int]: + """Get pixel bounds for a maze cell with clamping. + + Returns: + Tuple of (x_start, x_end, y_start, y_end). + """ + return ( + max(0, cell_x * cell_pixels), + min(max_x, (cell_x + 1) * cell_pixels), + max(0, cell_y * cell_pixels), + min(max_y, (cell_y + 1) * cell_pixels), + ) + + +# ============================================================================= +# Maze Generation +# ============================================================================= + +def generate_maze( + rng: np.random.Generator, + width: int, + height: int, + open_prob: float +) -> np.ndarray: + """Generate maze using DFS with random openings. + + Args: + rng: Random number generator for reproducibility. + width: Maze width in cells. + height: Maze height in cells. + open_prob: Probability of random wall removal. + + Returns: + 2D array where 1=wall, 0=path. + """ + maze = np.ones((width, height), dtype=np.uint8) + stack = [(0, 0)] + maze[0, 0] = 0 + + while stack: + x, y = stack[-1] + neighbors = [] + for dx, dy in [(-2, 0), (2, 0), (0, -2), (0, 2)]: + nx, ny = x + dx, y + dy + if 0 <= nx < width and 0 <= ny < height and maze[nx, ny] == 1: + neighbors.append((nx, ny)) + + if neighbors: + idx = rng.integers(len(neighbors)) + nx, ny = neighbors[idx] + maze[(x + nx) // 2, (y + ny) // 2] = 0 + maze[nx, ny] = 0 + stack.append((nx, ny)) + else: + stack.pop() + + # Random openings + maze[rng.random((width, height)) < open_prob] = 0 + return maze + + +def clear_center(maze: np.ndarray, terrain: TerrainData, cell_pixels: int): + """Clear the center area for spawning.""" + cx, cy = maze.shape[0] // 2, maze.shape[1] // 2 + + for dx in [-1, 0, 1]: + for dy in [-1, 0, 1]: + if abs(dx) + abs(dy) <= 1: # Plus shape + nx, ny = cx + dx, cy + dy + if 0 <= nx < maze.shape[0] and 0 <= ny < maze.shape[1]: + maze[nx, ny] = 0 + + x_start = (cx - 1) * cell_pixels + x_end = (cx + 2) * cell_pixels + y_start = (cy - 1) * cell_pixels + y_end = (cy + 2) * cell_pixels + terrain.set_ground(x_start, x_end, y_start, y_end) + + +# ============================================================================= +# Obstacle Generators +# ============================================================================= + +def make_pillar( + _rng: np.random.Generator, + size: int, + wall_height: int, + scale: float, + is_pit: bool, + thickness: int +) -> np.ndarray: + """Generate a centered pillar obstacle.""" + grid = np.zeros((size, size), dtype=np.int16) + h = int(wall_height * scale) * (-1 if is_pit else 1) + grid[thickness:size-thickness, thickness:size-thickness] = h + return grid + + +def make_bar( + rng: np.random.Generator, + size: int, + wall_height: int, + scale: float, + is_pit: bool, + thickness: int +) -> np.ndarray: + """Generate a rotated bar obstacle.""" + grid = np.zeros((size, size), dtype=np.int16) + center = size // 2 + h = int(wall_height * scale) + grid[center - thickness//2:center + thickness//2, :] = h + + angle = rng.uniform(-180, 180) + grid = rotate(grid, angle, reshape=False, order=1).astype(np.int16) + + if is_pit: + grid = -grid + return grid + + +def make_cross( + rng: np.random.Generator, + size: int, + wall_height: int, + scale: float, + is_pit: bool, + thickness: int +) -> np.ndarray: + """Generate a cross-shaped obstacle.""" + grid = np.zeros((size, size), dtype=np.int16) + center = size // 2 + h = int(wall_height * scale) + grid[center - thickness//2:center + thickness//2, :] = h + grid[:, center - thickness//2:center + thickness//2] = h + + angle = rng.uniform(-180, 180) + grid = rotate(grid, angle, reshape=False, order=1).astype(np.int16) + + if is_pit: + grid = -grid + return grid + + +def make_shifted_block( + rng: np.random.Generator, + size: int, + wall_height: int, + scale: float, + is_pit: bool, + thickness: int +) -> np.ndarray: + """Generate a randomly shifted block.""" + grid = np.zeros((size, size), dtype=np.int16) + h = int(wall_height * scale) + grid[thickness:size-thickness, thickness:size-thickness] = h + + room = max(0, size // 2 - thickness) + shift_amt = ( + rng.integers(-room, room + 1), + rng.integers(-room, room + 1) + ) + grid = shift(grid, shift=shift_amt, cval=0).astype(np.int16) + + if is_pit: + grid = -grid + return grid + + +# Obstacle generator lookup table +_OBSTACLE_GENERATORS = { + ObstacleType.PILLAR: make_pillar, + ObstacleType.BAR: make_bar, + ObstacleType.CROSS: make_cross, + ObstacleType.SHIFTED_BLOCK: make_shifted_block, +} + + +def make_random_obstacle( + rng: np.random.Generator, + size: int, + wall_height: int, + is_pit: bool | None = None, + pillar_weight: float | None = None +) -> np.ndarray: + """Generate a random obstacle type. + + Args: + rng: Random number generator. + size: Size of the obstacle grid in pixels. + wall_height: Height of walls in terrain units. + is_pit: Force pit (True) or wall (False). None = random. + pillar_weight: Weight for pillars (0-1). None = uniform distribution. + """ + scale = rng.uniform(OBSTACLES.SCALE_MIN, OBSTACLES.SCALE_MAX) + if is_pit is None: + is_pit = rng.random() < OBSTACLES.DEFAULT_PIT_PROB + thickness = rng.integers(OBSTACLES.THICKNESS_MIN, OBSTACLES.THICKNESS_MAX) + + # Select obstacle type (with optional pillar weighting) + if pillar_weight is not None and pillar_weight > 0: + # Weighted selection: pillar_weight for pillars, rest split evenly + other_weight = (1.0 - pillar_weight) / (ObstacleType.NUM_TYPES - 1) + weights = [other_weight] * ObstacleType.NUM_TYPES + weights[ObstacleType.PILLAR] = pillar_weight + obstacle_type = rng.choice(ObstacleType.NUM_TYPES, p=weights) + else: + # Uniform selection + obstacle_type = rng.integers(ObstacleType.NUM_TYPES) + + generator = _OBSTACLE_GENERATORS[obstacle_type] + return generator(rng, size, wall_height, scale, is_pit, thickness) + + +# ============================================================================= +# Stair/Platform Generator +# ============================================================================= + +class StairGenerator: + """Generates stair structures with platforms.""" + + LAYOUTS = [ + {"platforms": [(1, 0), (1, 1), (1, 2), (0, 1), (2, 1)], + "stairs": [(0, 0, "n"), (2, 2, "s"), (0, 2, "s"), (2, 0, "w")]}, + {"platforms": [(0, 1), (1, 1), (2, 1)], + "stairs": [(0, 0, "n"), (2, 2, "s"), (0, 2, "s"), (2, 0, "n")]}, + {"platforms": [(0, 1), (1, 1), (2, 1), (1, 0), (1, 2)], + "stairs": [(0, 0, "n"), (2, 2, "s"), (0, 2, "s"), (2, 0, "n")]}, + ] + + def __init__(self, wall_height: float, vertical_scale: float): + self.wall_height = wall_height + self.platform_height = int(wall_height - 0.5 / vertical_scale) + self.vertical_scale = vertical_scale + self._make_stair_templates() + + def _make_stair_templates(self): + """Create stair templates for each direction.""" + cell_px = STAIRS.SINGLE_CELL_PIXELS + step_res = cell_px // STAIRS.NUM_STEPS + + east = np.zeros((cell_px, cell_px), dtype=np.float32) + for i in range(STAIRS.NUM_STEPS): + h = STAIRS.STEP_HEIGHT_METERS * (i + 1) / self.vertical_scale + east[i * step_res:(i + 1) * step_res, :] = h + + self.templates = { + "e": east, + "n": rotate(east, 90), + "w": rotate(east, 180), + "s": rotate(east, 270), + } + + def generate(self, rng: np.random.Generator) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Generate a 3x3 stair/platform structure. + + Args: + rng: Random number generator. + + Returns: + Tuple of (heights, valid_mask, platform_mask). + """ + layout = self.LAYOUTS[rng.integers(len(self.LAYOUTS))] + size = STAIRS.STAIR_GRID_SIZE * STAIRS.SINGLE_CELL_PIXELS + cell_px = STAIRS.SINGLE_CELL_PIXELS + + heights = np.zeros((size, size), dtype=np.float32) + valid_mask = np.zeros((size, size), dtype=bool) + platform_mask = np.zeros((size, size), dtype=bool) + + for gx, gy in layout["platforms"]: + xs, xe = gx * cell_px, (gx + 1) * cell_px + ys, ye = gy * cell_px, (gy + 1) * cell_px + heights[xs:xe, ys:ye] = self.platform_height + valid_mask[xs:xe, ys:ye] = True + platform_mask[xs:xe, ys:ye] = True + + for gx, gy, direction in layout["stairs"]: + xs, xe = gx * cell_px, (gx + 1) * cell_px + ys, ye = gy * cell_px, (gy + 1) * cell_px + heights[xs:xe, ys:ye] = self.templates[direction] + + return heights, valid_mask, platform_mask + + +# ============================================================================= +# Main Terrain Generation +# ============================================================================= + +def _get_rng(cfg: "hf_terrains_maze_cfg.HfMazeTerrainCfg") -> np.random.Generator: + """Get RNG from config or create a new one.""" + if cfg.rng is not None: + return cfg.rng + # Fallback: create unseeded RNG (non-reproducible) + return np.random.default_rng() + + +@height_field_to_mesh +def maze_terrain(difficulty: float, cfg: "hf_terrains_maze_cfg.HfMazeTerrainCfg") -> np.ndarray: + """Generate maze terrain with obstacles and valid position mask. + + Args: + difficulty: Terrain difficulty (0-1). + cfg: Terrain configuration. + + Returns: + Height field for mesh generation. + """ + rng = _get_rng(cfg) + + # Setup dimensions + cell_pixels = int(cfg.cell_size / cfg.horizontal_scale) + wall_height = int(cfg.wall_height / cfg.vertical_scale) + terrain_w = int(cfg.size[0] / cfg.horizontal_scale) + terrain_h = int(cfg.size[1] / cfg.horizontal_scale) + + terrain = TerrainData.create(terrain_w, terrain_h) + stair_gen = StairGenerator(wall_height, cfg.vertical_scale) + + # Generate base pattern + if cfg.non_maze_terrain: + maze = np.zeros(cfg.grid_size, dtype=np.uint8) + obstacle_prob = difficulty * OBSTACLES.NON_MAZE_DENSITY + maze[rng.random(cfg.grid_size) < obstacle_prob] = 1 + else: + maze = generate_maze(rng, cfg.grid_size[0], cfg.grid_size[1], 1 - difficulty) + + clear_center(maze, terrain, cell_pixels) + + # Generate terrain features based on type + if cfg.dynamic_obstacles: + _add_pits(rng, terrain, cfg, difficulty, wall_height, cell_pixels) + elif cfg.stairs: + _add_stairs(rng, terrain, cfg, difficulty, wall_height, cell_pixels, stair_gen) + else: + _add_walls(rng, maze, terrain, cfg, wall_height, cell_pixels) + + clear_center(maze, terrain, cell_pixels) + + # Apply height transition padding for stair terrain + if cfg.stairs: + terrain.apply_height_transition_padding( + height_threshold=PADDING.HEIGHT_TRANSITION_THRESHOLD, + padding_cells=PADDING.HEIGHT_TRANSITION_PADDING + ) + + # Apply safety padding and border exclusion + terrain.apply_padding(PADDING.GOAL_PADDING) + terrain.exclude_borders(PADDING.BORDER_CELLS) + + # Create spawn mask with larger padding + spawn_mask = terrain.create_spawn_mask(PADDING.SPAWN_PADDING) + spawn_mask[:PADDING.BORDER_CELLS, :] = False + spawn_mask[-PADDING.BORDER_CELLS:, :] = False + spawn_mask[:, :PADDING.BORDER_CELLS] = False + spawn_mask[:, -PADDING.BORDER_CELLS:] = False + + # Store data on cfg for patches to pick up + if cfg.add_goal: + cfg.height_field_visual = torch.from_numpy(terrain.heights.copy()).unsqueeze(0) + cfg.height_field_valid_mask = torch.from_numpy(terrain.valid_mask.copy()).unsqueeze(0) + cfg.height_field_platform_mask = torch.from_numpy(terrain.platform_mask.copy()).unsqueeze(0) + cfg.height_field_spawn_mask = torch.from_numpy(spawn_mask.copy()).unsqueeze(0) + + return terrain.heights + + +# ============================================================================= +# Terrain Type Generators +# ============================================================================= + +def _add_walls( + rng: np.random.Generator, + maze: np.ndarray, + terrain: TerrainData, + cfg, + wall_height: int, + cell_pixels: int +): + """Add wall obstacles to terrain based on maze pattern.""" + # Use pillar weighting for non-maze terrain (more thin pillars) + pillar_weight = OBSTACLES.NON_MAZE_PILLAR_WEIGHT if cfg.non_maze_terrain else None + + for x in range(cfg.grid_size[0]): + for y in range(cfg.grid_size[1]): + if maze[x, y] != 1: + continue + + xs, xe, ys, ye = get_cell_bounds( + x, y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1] + ) + + if cfg.randomize_wall and rng.random() < cfg.random_wall_ratio: + obs = make_random_obstacle(rng, cell_pixels, wall_height, pillar_weight=pillar_weight) + terrain.heights[xs:xe, ys:ye] = obs[:xe - xs, :ye - ys] + terrain.valid_mask[xs:xe, ys:ye] = False + else: + h = int(wall_height * rng.uniform(OBSTACLES.SCALE_MIN, OBSTACLES.SCALE_MAX)) + terrain.set_obstacle(xs, xe, ys, ye, h) + + +def _add_stairs( + rng: np.random.Generator, + terrain: TerrainData, + cfg, + difficulty: float, + wall_height: int, + cell_pixels: int, + stair_gen: StairGenerator +): + """Add stair/platform structures to terrain.""" + grid_w, grid_h = cfg.grid_size + grid_middle = grid_w // 2 + excluded = set(range(grid_middle - 1, grid_middle + 1)) + + # Compute stair placement locations (avoid center and edges) + # Stairs are 3x3, so max position is grid_size - 4 to fit with margin + stair_margin = 1 + max_x = grid_w - STAIRS.STAIR_GRID_SIZE - stair_margin + max_y = grid_h - STAIRS.STAIR_GRID_SIZE - stair_margin + num_locations = 6 + x_locs = set(np.round(np.linspace(stair_margin, max_x, num_locations)).astype(int)) - excluded + y_locs = set(np.round(np.linspace(stair_margin, max_y, num_locations)).astype(int)) - excluded + + processed = set() + stair_size = STAIRS.STAIR_GRID_SIZE * STAIRS.SINGLE_CELL_PIXELS + stair_prob = difficulty * OBSTACLES.STAIRS_PLACEMENT_PROB + obstacle_prob = difficulty * OBSTACLES.STAIRS_OBSTACLE_DENSITY + + for x in range(grid_w): + for y in range(grid_h): + if (x, y) in processed: + continue + + # Try placing stair structure at valid locations + if x in x_locs and y in y_locs and rng.random() < stair_prob: + heights, valid, platform = stair_gen.generate(rng) + + xs = x * cell_pixels + xe = min(terrain.heights.shape[0], xs + stair_size) + ys = y * cell_pixels + ye = min(terrain.heights.shape[1], ys + stair_size) + + sx, sy = xe - xs, ye - ys + terrain.heights[xs:xe, ys:ye] = heights[:sx, :sy] + terrain.valid_mask[xs:xe, ys:ye] = valid[:sx, :sy] + terrain.platform_mask[xs:xe, ys:ye] = platform[:sx, :sy] + + # Mark 3x3 area as processed + for dx in range(3): + for dy in range(3): + processed.add((x + dx, y + dy)) + + elif rng.random() < obstacle_prob: + xs, xe, ys, ye = get_cell_bounds( + x, y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1] + ) + # Check if area is clear before placing + if terrain.valid_mask[xs + 1:xe - 1, ys + 1:ye - 1].all(): + obs = make_random_obstacle(rng, cell_pixels, wall_height) + terrain.heights[xs:xe, ys:ye] = obs[:xe - xs, :ye - ys] + terrain.valid_mask[xs:xe, ys:ye] = False + + +def _add_pits( + rng: np.random.Generator, + terrain: TerrainData, + cfg, + difficulty: float, + wall_height: int, + cell_pixels: int +): + """Add pit/trough obstacles to terrain. + + Layout: + - Two horizontal pit trenches with random bridges for crossing + - Random obstacles (mostly pits) scattered in the middle area + """ + grid_w, grid_h = cfg.grid_size + + # Pit trench rows (near top and bottom) + trench_offset = OBSTACLES.PITS_TRENCH_ROW_OFFSET + pit_rows = {trench_offset, grid_h - trench_offset - 1} + + # Generate bridge positions for crossing pit trenches + bridges = _generate_bridges(rng, grid_w) + + # Add pit trenches (negative height = troughs) + for pit_y in pit_rows: + for x in range(grid_w): + if x in bridges: + continue + xs, xe, ys, ye = get_cell_bounds( + x, pit_y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1] + ) + terrain.set_obstacle(xs, xe, ys, ye, -wall_height) + + # Add random obstacles in middle area (between pit trenches) + _add_middle_obstacles(rng, terrain, cfg, difficulty, wall_height, cell_pixels, pit_rows) + + +def _generate_bridges(rng: np.random.Generator, grid_width: int) -> set: + """Generate bridge positions across pit rows. + + Returns set of x-coordinates where bridges (gaps in pits) are placed. + Bridges are 2 cells wide for easier robot crossing. + """ + num_bridges = rng.integers(OBSTACLES.BRIDGE_COUNT_MIN, OBSTACLES.BRIDGE_COUNT_MAX) + margin = OBSTACLES.PITS_EDGE_MARGIN + available = list(range(margin, grid_width - margin)) + rng.shuffle(available) + + bridges = set() + for i in range(min(num_bridges, len(available))): + pos = available[i] + bridges.add(pos) + # Make bridges 2 cells wide + if pos + 1 < grid_width - margin: + bridges.add(pos + 1) + + return bridges + + +def _add_middle_obstacles( + rng: np.random.Generator, + terrain: TerrainData, + cfg, + difficulty: float, + wall_height: int, + cell_pixels: int, + pit_rows: set +): + """Add random obstacles in the middle area between pit rows.""" + grid_w, grid_h = cfg.grid_size + obstacle_prob = difficulty * OBSTACLES.PITS_DENSITY + + # Compute valid placement bounds (avoid edges and pit rows) + margin = OBSTACLES.PITS_EDGE_MARGIN + trench_offset = OBSTACLES.PITS_TRENCH_ROW_OFFSET + + x_range = range(margin, grid_w - margin) + # Middle area: between the two pit trenches, with 1 cell buffer + y_range = range(trench_offset + 1, grid_h - trench_offset - 1) + + # Iterate only over valid cells (more efficient) + for x in x_range: + for y in y_range: + if y in pit_rows: + continue + + if rng.random() < obstacle_prob: + xs, xe, ys, ye = get_cell_bounds( + x, y, cell_pixels, terrain.heights.shape[0], terrain.heights.shape[1] + ) + obs = _generate_pit_obstacle(rng, cell_pixels, wall_height) + terrain.heights[xs:xe, ys:ye] = obs[:xe - xs, :ye - ys] + terrain.valid_mask[xs:xe, ys:ye] = False + + +def _generate_pit_obstacle( + rng: np.random.Generator, + cell_pixels: int, + wall_height: int +) -> np.ndarray: + """Generate an obstacle for pit terrain with high pit probability. + + Distribution: + - 60% bars (75% negative/pits) -> 45% pit bars + - 40% random shapes (50% negative/pits) -> 20% pit shapes + - Total: ~65% negative obstacles + """ + if rng.random() < OBSTACLES.PITS_BAR_RATIO: + # Bar obstacle with high pit probability + is_pit = rng.random() < OBSTACLES.PITS_BAR_PIT_PROB + scale = rng.uniform(OBSTACLES.SCALE_MIN, OBSTACLES.SCALE_MAX) + thickness = rng.integers(OBSTACLES.THICKNESS_MIN, OBSTACLES.THICKNESS_MAX) + return make_bar(rng, cell_pixels, wall_height, scale, is_pit, thickness) + else: + # Random obstacle type (pillar, cross, block) with moderate pit probability + is_pit = rng.random() < OBSTACLES.PITS_RANDOM_PIT_PROB + return make_random_obstacle(rng, cell_pixels, wall_height, is_pit=is_pit) diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/hf_terrains_maze_cfg.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/hf_terrains_maze_cfg.py new file mode 100644 index 0000000..43cc1cf --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/hf_terrains_maze_cfg.py @@ -0,0 +1,111 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Configuration for maze height field terrains.""" + +from dataclasses import MISSING +from typing import Any, Optional + +import numpy as np +import torch + +from isaaclab.utils import configclass +from isaaclab.terrains.height_field.hf_terrains_cfg import HfTerrainBaseCfg + +from . import hf_terrains_maze + + +@configclass +class HfMazeTerrainCfg(HfTerrainBaseCfg): + """Configuration for a maze height field terrain. + + This terrain generates a procedural maze with configurable wall structures, + obstacles, and optional stairs. The maze can be used for navigation tasks + with various difficulty levels. + + Height Field Data (set during terrain generation): + - height_field_visual: Heights for Z-lookup (num_terrains, W, H) + - height_field_valid_mask: Valid goal positions with safety padding + - height_field_platform_mask: Platform positions for curriculum + - height_field_spawn_mask: Valid spawn positions with larger padding + """ + + function = hf_terrains_maze.maze_terrain + + # ========================================================================= + # Height Field Storage (populated during terrain generation) + # ========================================================================= + + height_field_visual: torch.Tensor = None + """Height field for Z-lookup (actual terrain heights).""" + + height_field_valid_mask: torch.Tensor = None + """Boolean mask of valid goal positions (padded with GOAL_PADDING).""" + + height_field_platform_mask: torch.Tensor = None + """Boolean mask of platform positions for curriculum learning.""" + + height_field_spawn_mask: torch.Tensor = None + """Boolean mask of valid spawn positions (larger padding for robot body).""" + + # ========================================================================= + # Maze Generation Parameters + # ========================================================================= + + maze: bool = True + """Flag indicating this is a maze terrain.""" + + open_probability: float = None + """Probability of a cell being open in the maze.""" + + grid_size: tuple[int, int] = (15, 15) + """Size of the maze grid (number of cells in width and height).""" + + cell_size: float = 2.0 + """Size of each cell in the maze grid (in meters).""" + + wall_height: float = 1.5 + """Height of the walls (in meters). Defaults to 1.5.""" + + # ========================================================================= + # Terrain Features + # ========================================================================= + + add_goal: Any = MISSING + """Enable goal sampling data generation.""" + + add_noise_to_flat: Any = MISSING + """Add noise to flat areas of the maze.""" + + randomize_wall: Any = MISSING + """Use randomized obstacle shapes instead of full walls.""" + + random_wall_ratio: float = 0.5 + """Mix ratio between randomized and standard walls. Defaults to 0.5.""" + + non_maze_terrain: bool = False + """Use non-maze terrain with random obstacles. Defaults to False.""" + + stairs: bool = False + """Add stairs to empty map. Defaults to False.""" + + add_stairs_to_maze: bool = False + """Add stairs to the maze. Defaults to False.""" + + dynamic_obstacles: bool = False + """Enable pit/trough obstacles. Defaults to False.""" + + # ========================================================================= + # Random Number Generator + # ========================================================================= + + rng: Optional[np.random.Generator] = None + """Random number generator for reproducible terrain generation. + + Set by the terrain generator (patches.py) before calling the terrain function. + If None, will create a new unseeded generator (non-reproducible). + """ + + diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/maze_config.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/maze_config.py new file mode 100644 index 0000000..a4516df --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/maze_config.py @@ -0,0 +1,72 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Configuration for maze terrains.""" + +from isaaclab.terrains.terrain_generator_cfg import TerrainGeneratorCfg + +from .hf_terrains_maze_cfg import HfMazeTerrainCfg + +MAZE_TERRAIN_CFG = TerrainGeneratorCfg( + size=(30.0, 30.0), + border_width=30.0, # Border around the entire terrain grid (not per-tile) + num_rows=6, + num_cols=30, + horizontal_scale=0.1, + vertical_scale=0.005, + slope_threshold=0.75, + use_cache=False, + curriculum=False, + difficulty_range=(0.5, 1.0), + sub_terrains={ + "maze": HfMazeTerrainCfg( + proportion=0.3, + open_probability=0.9, + grid_size=(15, 15), + cell_size=2.0, + add_noise_to_flat=False, + add_goal=True, + randomize_wall=True, + random_wall_ratio=0.5, + add_stairs_to_maze=True, + ), + "non_maze": HfMazeTerrainCfg( + proportion=0.2, + open_probability=0.9, + grid_size=(15, 15), + cell_size=2.0, + add_noise_to_flat=False, + add_goal=True, + randomize_wall=True, + random_wall_ratio=1.0, + non_maze_terrain=True, + ), + "stairs": HfMazeTerrainCfg( + proportion=0.3, + open_probability=0.9, + grid_size=(15, 15), + cell_size=2.0, + add_noise_to_flat=False, + add_goal=True, + randomize_wall=False, + random_wall_ratio=1.0, + non_maze_terrain=False, + stairs=True, + ), + "pits": HfMazeTerrainCfg( + proportion=0.2, + open_probability=0.9, + grid_size=(15, 15), + cell_size=2.0, + add_noise_to_flat=False, + add_goal=True, + randomize_wall=True, + random_wall_ratio=1.0, + non_maze_terrain=True, + dynamic_obstacles=True, # Enables pit/trough generation + ), + }, +) +"""Maze terrain configuration for navigation tasks.""" diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/patches.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/patches.py new file mode 100644 index 0000000..a9ba5c2 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/patches.py @@ -0,0 +1,550 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Monkey-patches for Isaac Lab terrain system to support navigation tasks. + +This module patches TerrainGenerator and TerrainImporter to: +1. Store height field data for goal/spawn sampling +2. Use optimized mesh generation to reduce GPU memory + +The patches add these attributes to TerrainImporter (accessed via env.scene.terrain): +- _height_field_visual: Heights for Z-lookup (num_terrains, W, H) +- _height_field_valid_mask: Valid goal positions with safety padding +- _height_field_platform_mask: Platform positions for curriculum +- _height_field_spawn_mask: Valid spawn positions with larger padding +""" + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING + +import numpy as np +import torch +import trimesh + +if TYPE_CHECKING: + from isaaclab.terrains.terrain_generator import TerrainGenerator + from isaaclab.terrains.terrain_importer import TerrainImporter + +# Flag to track if patches have been applied +_patches_applied = False + +# Shared storage for passing height field data from TerrainGenerator to TerrainImporter +# Works because TerrainImporter creates TerrainGenerator synchronously in __init__ +_height_field_storage = { + "height_field_visual": None, + "height_field_valid_mask": None, + "height_field_platform_mask": None, + "height_field_spawn_mask": None, +} + + +def apply_terrain_patches(): + """Apply monkey-patches to Isaac Lab terrain classes. + + Patches applied: + 1. height_field_to_mesh - optimized mesh generation (reduces GPU memory) + 2. TerrainGenerator - collects height field data for goal sampling + 3. TerrainImporter - stores height field data as attributes + 4. PinholeCameraPatternCfg - adds from_ros_camera_info convenience method + + Safe to call multiple times - patches are only applied once. + """ + global _patches_applied + if _patches_applied: + return + + _patch_height_field_to_mesh() + _patch_terrain_generator() + _patch_terrain_importer() + _patch_pinhole_camera_pattern_cfg() + + _patches_applied = True + + +def _convert_height_field_to_mesh_with_optimization_dynamic( + height_field: np.ndarray, horizontal_scale: float, vertical_scale: float, block_size: int = 20 +) -> tuple[np.ndarray, np.ndarray]: + """Convert a height-field array to a triangle mesh, optimizing large flat ground blocks (20x20, 10x10, 5x5). + + This function optimizes mesh generation by detecting flat regions and simplifying them + to just 2 triangles instead of generating full detail. It uses a hierarchical approach: + - 20x20 blocks are checked first + - Non-flat blocks are subdivided into 10x10, then 5x5 + - Only 5x5 or smaller blocks with height variation get full detail + + This can dramatically reduce vertex count for terrains with large flat areas, + significantly reducing GPU memory usage during simulation. + + Args: + height_field: The input height-field array. + horizontal_scale: The discretization of the terrain along the x and y axis. + vertical_scale: The discretization of the terrain along the z axis. + block_size: Initial block size for optimization (default 20). + + Returns: + The vertices and triangles of the mesh: + - **vertices** (np.ndarray(float)): Array of shape (num_vertices, 3). + - **triangles** (np.ndarray(int)): Array of shape (num_triangles, 3). + """ + num_rows, num_cols = height_field.shape + vertices = [] + triangles = [] + vertex_count = 0 + + def process_block(i, j, block_size): + """Process a block and decide whether to simplify or subdivide into smaller blocks.""" + nonlocal vertex_count + + # Skip if starting position is at or beyond the terrain bounds + if i >= num_rows or j >= num_cols: + return + + # Determine block dimensions within bounds of the height field + block_end_row = min(i + block_size + 1, num_rows) # +1 to handle the right and bottom edges + block_end_col = min(j + block_size + 1, num_cols) # +1 to handle the right and bottom edges + + # Extract the block of height data + block = height_field[i:block_end_row, j:block_end_col] + + # Skip empty or single-element blocks (can't form triangles) + if block.size == 0 or block.shape[0] < 2 or block.shape[1] < 2: + return + + # Check if the entire block is flat (all heights are the same) + if np.all(block == block[0, 0]): + # Simplify the block by using two large triangles for the whole flat region + v0 = [i * horizontal_scale, j * horizontal_scale, block[0, 0] * vertical_scale] + v1 = [block_end_row * horizontal_scale, j * horizontal_scale, block[0, 0] * vertical_scale] + v2 = [i * horizontal_scale, block_end_col * horizontal_scale, block[0, 0] * vertical_scale] + v3 = [block_end_row * horizontal_scale, block_end_col * horizontal_scale, block[0, 0] * vertical_scale] + + # Add the vertices for the large triangles + vertices.extend([v0, v1, v2, v3]) + + # Add the two triangles for the block + triangles.append([vertex_count, vertex_count + 1, vertex_count + 2]) + triangles.append([vertex_count + 1, vertex_count + 3, vertex_count + 2]) + + vertex_count += 4 + else: + # If block is not flat and the block size is larger than 5x5, subdivide into smaller blocks + if block_size > 5: + half_size = block_size // 2 + # Process each of the four quadrants of the block + process_block(i, j, half_size) + process_block(i + half_size, j, half_size) + process_block(i, j + half_size, half_size) + process_block(i + half_size, j + half_size, half_size) + else: + # If block size is 5x5 or smaller, generate detailed triangles for each grid point + for x in range(block_end_row - i): + for y in range(block_end_col - j): + # Get the height at this point + z = block[x, y] * vertical_scale + v = [(i + x) * horizontal_scale, (j + y) * horizontal_scale, z] + vertices.append(v) + + # Now create triangles for all internal points including the last row and last column + for x in range(block_end_row - i - 1): # Handle rows, including the last row + for y in range(block_end_col - j - 1): # Handle columns, including the last column + ind0 = vertex_count + x * (block_end_col - j) + y + ind1 = ind0 + 1 + ind2 = ind0 + (block_end_col - j) + ind3 = ind2 + 1 + + # Create two triangles for this grid cell + triangles.append([ind0, ind3, ind1]) + triangles.append([ind0, ind2, ind3]) + + vertex_count += (block_end_row - i) * (block_end_col - j) + + # Start by processing blocks with the initial block size (20x20) + for i in range(0, num_rows, block_size): + for j in range(0, num_cols, block_size): + process_block(i, j, block_size) + + vertices = np.array(vertices) + triangles = np.array(triangles) + + # Return vertices and triangles arrays + return vertices, triangles + + +def _patch_height_field_to_mesh(): + """Patch height_field_to_mesh decorator to use optimized mesh generation. + + This patch replaces the mesh generation in the height_field_to_mesh decorator + with an optimized version that reduces vertex count for flat terrain regions, + significantly reducing GPU memory usage during simulation with many environments. + """ + import copy + import functools + from isaaclab.terrains.height_field import utils as hf_utils + + def _patched_height_field_to_mesh(func): + """Patched decorator that uses optimized mesh generation.""" + @functools.wraps(func) + def wrapper(difficulty: float, cfg): + # check valid border width + if cfg.border_width > 0 and cfg.border_width < cfg.horizontal_scale: + raise ValueError( + f"The border width ({cfg.border_width}) must be greater than or equal to the" + f" horizontal scale ({cfg.horizontal_scale})." + ) + # allocate buffer for height field (with border) + width_pixels = int(cfg.size[0] / cfg.horizontal_scale) + 1 + length_pixels = int(cfg.size[1] / cfg.horizontal_scale) + 1 + border_pixels = int(cfg.border_width / cfg.horizontal_scale) + 1 + heights = np.zeros((width_pixels, length_pixels), dtype=np.int16) + # override size of the terrain to account for the border + sub_terrain_size = [width_pixels - 2 * border_pixels, length_pixels - 2 * border_pixels] + sub_terrain_size = [dim * cfg.horizontal_scale for dim in sub_terrain_size] + # update the config + terrain_size = copy.deepcopy(cfg.size) + cfg.size = tuple(sub_terrain_size) + # generate the height field + z_gen = func(difficulty, cfg) + # handle the border for the terrain + heights[border_pixels:-border_pixels, border_pixels:-border_pixels] = z_gen + # set terrain size back to config + cfg.size = terrain_size + + # PATCH: Use optimized mesh generation to reduce GPU memory usage + vertices, triangles = _convert_height_field_to_mesh_with_optimization_dynamic( + heights, cfg.horizontal_scale, cfg.vertical_scale, 20 + ) + mesh = trimesh.Trimesh(vertices=vertices, faces=triangles) + + # compute origin + x1 = int((cfg.size[0] * 0.5 - 1) / cfg.horizontal_scale) + x2 = int((cfg.size[0] * 0.5 + 1) / cfg.horizontal_scale) + y1 = int((cfg.size[1] * 0.5 - 1) / cfg.horizontal_scale) + y2 = int((cfg.size[1] * 0.5 + 1) / cfg.horizontal_scale) + origin_z = np.max(heights[x1:x2, y1:y2]) * cfg.vertical_scale + origin = np.array([0.5 * cfg.size[0], 0.5 * cfg.size[1], origin_z]) + # return mesh and origin + return [mesh], origin + + return wrapper + + # Apply patch to the height_field_to_mesh decorator + hf_utils.height_field_to_mesh = _patched_height_field_to_mesh + + +def _patch_terrain_generator(): + """Patch TerrainGenerator to collect height field data for goal sampling.""" + from isaaclab.terrains.terrain_generator import TerrainGenerator + from isaaclab.terrains.utils import color_meshes_by_height + from isaaclab.utils.timer import Timer + from isaaclab.utils.io import dump_yaml + from isaaclab.utils.dict import dict_to_md5_hash + + # Height field attribute names we collect + _HEIGHT_FIELD_ATTRS = [ + "height_field_visual", + "height_field_valid_mask", + "height_field_platform_mask", + "height_field_spawn_mask", + ] + + def _patched_init(self, cfg, device: str = "cpu"): + """Patched __init__ that collects height field data.""" + # Validate inputs + if len(cfg.sub_terrains) == 0: + raise ValueError("No sub-terrains specified in the configuration!") + if cfg.curriculum and cfg.difficulty_range is None: + raise ValueError("Curriculum learning requires 'difficulty_range' to be specified!") + + # Store inputs + self.cfg = cfg + self.device = device + + # Set common values for all sub-terrains + for sub_cfg in self.cfg.sub_terrains.values(): + sub_cfg.size = self.cfg.size + sub_cfg.horizontal_scale = self.cfg.horizontal_scale + sub_cfg.vertical_scale = self.cfg.vertical_scale + sub_cfg.slope_threshold = self.cfg.slope_threshold + + # Set seed for reproducibility + # - seed=None (default): random terrain each time (for training variety) + # - seed=: reproducible terrain (for debugging/evaluation) + # Note: Always create RNG because Isaac Lab's base code uses self.np_rng + self.np_rng = np.random.default_rng(self.cfg.seed) + self._reproducible = self.cfg.seed is not None + + # Initialize buffers + self.flat_patches = {} + self.terrain_meshes = [] + self.terrain_origins = np.zeros((self.cfg.num_rows, self.cfg.num_cols, 3)) + + # PATCH: Temporary lists to collect height field data during generation + self._height_field_lists = {attr: [] for attr in _HEIGHT_FIELD_ATTRS} + + # Generate terrains + if self.cfg.curriculum: + with Timer("[INFO] Generating terrains based on curriculum took"): + self._generate_curriculum_terrains() + else: + with Timer("[INFO] Generating terrains randomly took"): + self._generate_random_terrains() + + # Add border and combine meshes + self._add_terrain_border() + self.terrain_mesh = trimesh.util.concatenate(self.terrain_meshes) + + # PATCH: Consolidate collected height fields into tensors and store in shared storage + for attr in _HEIGHT_FIELD_ATTRS: + data_list = self._height_field_lists[attr] + if data_list: + setattr(self, attr, torch.cat(data_list, dim=0)) + _height_field_storage[attr] = getattr(self, attr) + else: + setattr(self, attr, None) + _height_field_storage[attr] = None + del self._height_field_lists # Free memory + + # Color the terrain mesh + if self.cfg.color_scheme == "height": + self.terrain_mesh = color_meshes_by_height(self.terrain_mesh) + elif self.cfg.color_scheme == "random": + self.terrain_mesh.visual.vertex_colors = self.np_rng.choice( + range(256), size=(len(self.terrain_mesh.vertices), 4) + ) + elif self.cfg.color_scheme != "none": + raise ValueError(f"Unknown color scheme: {self.cfg.color_scheme}") + + # Move flat patches to device + for name in self.flat_patches: + self.flat_patches[name] = self.flat_patches[name].to(self.device) + + def _patched_get_terrain_mesh(self, difficulty: float, cfg) -> tuple: + """Patched _get_terrain_mesh that collects height field data from each terrain.""" + # Copy configuration and set parameters + cfg = cfg.copy() + cfg.difficulty = float(difficulty) + cfg.seed = self.cfg.seed + + # Clear non-serializable fields for hashing + for attr in _HEIGHT_FIELD_ATTRS: + if hasattr(cfg, attr): + setattr(cfg, attr, None) + # Clear RNG for hashing (seed already included, RNG is derived from it) + if hasattr(cfg, 'rng'): + cfg.rng = None + + # Generate hash and cache paths + sub_terrain_hash = dict_to_md5_hash(cfg.to_dict()) + sub_terrain_cache_dir = os.path.join(self.cfg.cache_dir, sub_terrain_hash) + sub_terrain_obj_filename = os.path.join(sub_terrain_cache_dir, "mesh.obj") + sub_terrain_csv_filename = os.path.join(sub_terrain_cache_dir, "origin.csv") + sub_terrain_meta_filename = os.path.join(sub_terrain_cache_dir, "cfg.yaml") + + # Check cache + if self.cfg.use_cache and os.path.exists(sub_terrain_obj_filename): + mesh = trimesh.load_mesh(sub_terrain_obj_filename, process=False) + origin = np.loadtxt(sub_terrain_csv_filename, delimiter=",") + return mesh, origin + + # Set RNG for terrain generation (after hashing, before generation) + # Only pass RNG if seed was explicitly set (for reproducibility) + # Otherwise cfg.rng stays None and terrain uses fresh random each time + if hasattr(cfg, 'rng') and self._reproducible: + cfg.rng = self.np_rng.spawn(1)[0] + + # Generate mesh + meshes, origin = cfg.function(difficulty, cfg) + if not isinstance(meshes, list): + meshes = [meshes] + mesh = trimesh.util.concatenate(meshes) + + # Center the mesh + transform = np.eye(4) + transform[0:2, -1] = -cfg.size[0] * 0.5, -cfg.size[1] * 0.5 + mesh.apply_transform(transform) + origin += transform[0:3, -1] + + # PATCH: Collect height field data from cfg (set by terrain generation function) + for attr in _HEIGHT_FIELD_ATTRS: + if hasattr(cfg, attr): + data = getattr(cfg, attr) + if data is not None: + self._height_field_lists[attr].append(data) + setattr(cfg, attr, None) # Clear after collecting + + # Cache if enabled + if self.cfg.use_cache: + os.makedirs(sub_terrain_cache_dir, exist_ok=True) + mesh.export(sub_terrain_obj_filename) + np.savetxt(sub_terrain_csv_filename, origin, delimiter=",", header="x,y,z") + dump_yaml(sub_terrain_meta_filename, cfg) + + return mesh, origin + + # Apply patches + TerrainGenerator.__init__ = _patched_init + TerrainGenerator._get_terrain_mesh = _patched_get_terrain_mesh + + +def _patch_terrain_importer(): + """Patch TerrainImporter to store height field data as attributes. + + After TerrainGenerator populates shared storage, we capture the data + and store it as attributes on TerrainImporter for access via env.scene.terrain. + """ + from isaaclab.terrains.terrain_importer import TerrainImporter + + _original_importer_init = TerrainImporter.__init__ + + # Attribute names (with underscore prefix for storage on importer) + _HEIGHT_FIELD_ATTRS = [ + "height_field_visual", + "height_field_valid_mask", + "height_field_platform_mask", + "height_field_spawn_mask", + ] + + def _patched_importer_init(self, cfg): + """Patched __init__ that captures height field data from TerrainGenerator.""" + # Clear previous storage + for attr in _HEIGHT_FIELD_ATTRS: + _height_field_storage[attr] = None + + # Call original __init__ - creates TerrainGenerator which populates storage + _original_importer_init(self, cfg) + + # Capture height field data from storage and store as attributes + for attr in _HEIGHT_FIELD_ATTRS: + setattr(self, f"_{attr}", _height_field_storage.get(attr)) + + TerrainImporter.__init__ = _patched_importer_init + + +def _patch_pinhole_camera_pattern_cfg(): + """Patch PinholeCameraPatternCfg to add from_ros_camera_info method.""" + from isaaclab.sensors.ray_caster.patterns.patterns_cfg import PinholeCameraPatternCfg + + # Check if already patched + if hasattr(PinholeCameraPatternCfg, 'from_ros_camera_info'): + return + + # Add downsample_factor attribute if not present + if not hasattr(PinholeCameraPatternCfg, 'downsample_factor'): + PinholeCameraPatternCfg.downsample_factor = 1 + + # Store original from_intrinsic_matrix + _original_from_intrinsic_matrix = PinholeCameraPatternCfg.from_intrinsic_matrix + + @classmethod + def _patched_from_intrinsic_matrix( + cls, + intrinsic_matrix: list[float], + width: int, + height: int, + focal_length: float = 1.0, + downsample_factor: int = 1, + ) -> PinholeCameraPatternCfg: + """Create a PinholeCameraPatternCfg from an intrinsic matrix with downsampling support. + + Args: + intrinsic_matrix: The intrinsic matrix as a 9-element list [f_x, 0, c_x, 0, f_y, c_y, 0, 0, 1]. + width: Width of the image (in pixels). + height: Height of the image (in pixels). + focal_length: Focal length of the camera (in cm). Defaults to 1.0 cm. + downsample_factor: Downsampling factor for RL training. Defaults to 1 (no downsampling). + + Returns: + An instance of the PinholeCameraPatternCfg class. + """ + # Extract standard intrinsic parameters (in pixels) + f_x = intrinsic_matrix[0] + c_x = intrinsic_matrix[2] + f_y = intrinsic_matrix[4] + c_y = intrinsic_matrix[5] + + # Apply downsampling adjustments + if downsample_factor > 1: + f_x = f_x / downsample_factor + f_y = f_y / downsample_factor + c_x = c_x / downsample_factor + c_y = c_y / downsample_factor + width = width // downsample_factor + height = height // downsample_factor + + # Convert to USD camera parameters + horizontal_aperture = width * focal_length / f_x + vertical_aperture = height * focal_length / f_y + + # Convert principal point offset from pixels to physical units (cm) + horizontal_aperture_offset = (c_x - width / 2) * horizontal_aperture / width + vertical_aperture_offset = (c_y - height / 2) * vertical_aperture / height + + return cls( + focal_length=focal_length, + horizontal_aperture=horizontal_aperture, + vertical_aperture=vertical_aperture, + horizontal_aperture_offset=horizontal_aperture_offset, + vertical_aperture_offset=vertical_aperture_offset, + width=width, + height=height, + ) + + @classmethod + def from_ros_camera_info( + cls, + fx: float, + fy: float, + cx: float, + cy: float, + width: int, + height: int, + focal_length: float = 1.0, + downsample_factor: int = 1, + ) -> PinholeCameraPatternCfg: + """Create a PinholeCameraPatternCfg from ROS CameraInfo parameters. + + This is a convenience method for creating camera configurations directly from + ROS camera_info topic parameters, avoiding the need to construct the full + intrinsic matrix. + + Args: + fx: Focal length in x-direction (pixels). + fy: Focal length in y-direction (pixels). + cx: Principal point x-coordinate (pixels). + cy: Principal point y-coordinate (pixels). + width: Image width (pixels). + height: Image height (pixels). + focal_length: USD focal length scaling factor (cm). Defaults to 1.0 cm. + downsample_factor: Downsampling factor for RL training. Defaults to 1 (no downsampling). + + Returns: + A PinholeCameraPatternCfg instance. + + Example: + # From your camera info topic: + # K: [419.663, 0, 425.728, 0, 419.663, 238.272, 0, 0, 1] + # size: 848 x 480 + + # Original resolution + cfg = PinholeCameraPatternCfg.from_ros_camera_info( + fx=419.663, fy=419.663, cx=425.728, cy=238.272, + width=848, height=480 + ) + + # 4x downsampled for RL training (212x120) + cfg_rl = PinholeCameraPatternCfg.from_ros_camera_info( + fx=419.663, fy=419.663, cx=425.728, cy=238.272, + width=848, height=480, downsample_factor=4 + ) + """ + # Create intrinsic matrix in row-major format + intrinsic_matrix = [fx, 0, cx, 0, fy, cy, 0, 0, 1] + return cls.from_intrinsic_matrix(intrinsic_matrix, width, height, focal_length, downsample_factor) + + # Apply patches + PinholeCameraPatternCfg.from_intrinsic_matrix = _patched_from_intrinsic_matrix + PinholeCameraPatternCfg.from_ros_camera_info = from_ros_camera_info diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/terrain_constants.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/terrain_constants.py new file mode 100644 index 0000000..65adb74 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/isaaclab_nav_task/terrains/terrain_constants.py @@ -0,0 +1,341 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Constants for terrain generation and goal sampling. + +This module centralizes all height field values and terrain parameters used across +terrain generation and goal sampling code. Using these constants ensures consistency +and makes the height semantics explicit. + +Height Field Value Semantics (in discretized units): +==================================================== +The height field stores heights as integers where: + actual_height_meters = height_value * VERTICAL_SCALE + +Key height values: +- GROUND: 0 (flat walkable ground at z=0) +- PLATFORM: ~200 (flat raised platforms at ~1.0m, valid for goals) +- WALL: ~300 (obstacles/walls at ~1.5m, always excluded from goals) +- PIT: ~-300 (negative obstacles/troughs at ~-1.5m, always excluded) + +Goal Sampling Valid Ranges: +- Ground: -10 to 50 (allows small noise/variation) +- Platform: 150 to 250 (captures platform height with margin) +- Excluded: < -10 (pits) or > 250 (walls) +""" + +from dataclasses import dataclass +from typing import Tuple + + +# ============================================================================= +# Scale Factors +# ============================================================================= + +HORIZONTAL_SCALE: float = 0.1 +"""Horizontal resolution of height field in meters per cell.""" + +VERTICAL_SCALE: float = 0.005 +"""Vertical resolution of height field (height_meters = height_value * VERTICAL_SCALE).""" + +CELL_SIZE: float = 2.0 +"""Size of each maze cell in meters (default: 2m x 2m).""" + +CELL_PIXELS: int = int(CELL_SIZE / HORIZONTAL_SCALE) +"""Number of height field pixels per maze cell (20 at default scale).""" + + +# ============================================================================= +# Height Values (in discretized units, multiply by VERTICAL_SCALE for meters) +# ============================================================================= + +@dataclass(frozen=True) +class HeightValues: + """Standard height values for terrain features.""" + + # Ground level (valid for goals/spawn) + GROUND: int = 0 + + # Platform height: wall_height - 0.5m in vertical scale units + # = 1.5/0.005 - 0.5/0.005 = 300 - 100 = 200 + PLATFORM: int = 200 + + # Wall/obstacle height: 1.5m in vertical scale units + # = 1.5/0.005 = 300 + WALL: int = 300 + + # Pit/trough height (negative obstacle) + PIT: int = -300 + + @property + def platform_meters(self) -> float: + """Platform height in meters.""" + return self.PLATFORM * VERTICAL_SCALE + + @property + def wall_meters(self) -> float: + """Wall height in meters.""" + return self.WALL * VERTICAL_SCALE + + +HEIGHTS = HeightValues() +"""Singleton instance of standard height values.""" + + +# ============================================================================= +# Goal Sampling Thresholds +# ============================================================================= + +@dataclass(frozen=True) +class SamplingThresholds: + """Thresholds for classifying height values during goal/spawn sampling. + + These values match the old implementation for strict height classification. + """ + + # Ground range (strict: 0-10, allows minimal noise) + GROUND_MIN: int = 0 + GROUND_MAX: int = 10 + + # Platform range (strict: 195-205 for stair platforms at ~1.0m) + PLATFORM_MIN: int = 195 + PLATFORM_MAX: int = 205 + + # Wall threshold (anything above 10 is obstacle, but also check platform edges) + WALL_THRESHOLD: int = 10 + + # Pit threshold (anything below 0 is pit/excluded) + PIT_THRESHOLD: int = 0 + + # Edge detection threshold for Sobel filter (old: any edge > 0.0) + EDGE_THRESHOLD: float = 0.0 + + # Obstacle marker value (used to mark excluded cells) + OBSTACLE_MARKER: int = 110 + + # Extended platform range for edge detection (180-220) + # Used during padding to detect platform edges with safety margin + PLATFORM_EDGE_MIN: int = 180 + PLATFORM_EDGE_MAX: int = 220 + + +THRESHOLDS = SamplingThresholds() +"""Singleton instance of sampling thresholds.""" + + +# ============================================================================= +# Padding and Border Configuration +# ============================================================================= + +@dataclass(frozen=True) +class PaddingConfig: + """Configuration for obstacle padding and borders. + + These values match the old implementation for consistent safety margins. + With horizontal_scale=0.1m/cell, these translate to: + - GOAL_PADDING (3 cells) = 0.3m around obstacles for goal positions + - SPAWN_PADDING (8 cells) = 0.8m around obstacles for spawn positions + + The larger spawn padding accounts for: + - Robot body dimensions (~0.5m x 0.3m for quadrupeds) + - Random yaw orientation (diagonal ~0.58m requires ~0.3m radius) + - Platform edge clearance (prevent falling when spawning near stair edges) + - Controller startup imprecision + """ + + # Padding around obstacles for goals (in height field cells) + # 5 cells * 0.1m/cell = 0.5m padding (robot just needs to reach) + GOAL_PADDING: int = 5 + + # Larger padding for spawn positions (in height field cells) + # 6 cells * 0.1m/cell = 0.6m padding + # This accounts for: + # - Robot body radius (~0.5m) with worst-case orientation + # - Additional safety margin for platform edges + # - Controller startup behavior + SPAWN_PADDING: int = 6 + + # Border exclusion (keep away from terrain edges) + # Old implementation used 2 layers (inner + outer), we use 2 cells + BORDER_CELLS: int = 2 + + # Pillar expanded footprint size (5x5 cells around pillar center) + PILLAR_FOOTPRINT: int = 5 + + # Pillar safe margin from cell edges + PILLAR_EDGE_MARGIN: int = 2 + + # Height transition detection threshold (height field units) + # Marks cells with height differences >= this value as transitions + HEIGHT_TRANSITION_THRESHOLD: int = 100 + + # Padding around detected height transitions (in cells) + HEIGHT_TRANSITION_PADDING: int = 1 + + +PADDING = PaddingConfig() +"""Singleton instance of padding configuration.""" + + +# ============================================================================= +# Stair Configuration +# ============================================================================= + +@dataclass(frozen=True) +class StairConfig: + """Configuration for stair generation.""" + + # Number of steps in a staircase + NUM_STEPS: int = 5 + + # Height of each step in meters + STEP_HEIGHT_METERS: float = 0.2 + + # Grid size for 3x3 stair structures + STAIR_GRID_SIZE: int = 3 + + # Single cell size in pixels (same as CELL_PIXELS) + SINGLE_CELL_PIXELS: int = 20 + + @property + def step_height_units(self) -> float: + """Step height in discretized units.""" + return self.STEP_HEIGHT_METERS / VERTICAL_SCALE + + @property + def step_resolution(self) -> int: + """Pixels per step (cell_pixels / num_steps).""" + return self.SINGLE_CELL_PIXELS // self.NUM_STEPS + + +STAIRS = StairConfig() +"""Singleton instance of stair configuration.""" + + +# ============================================================================= +# Obstacle Structure Types +# ============================================================================= + +class ObstacleType: + """Enumeration of obstacle structure types for random generation.""" + + PILLAR = 0 + BAR = 1 + CROSS = 2 + SHIFTED_BLOCK = 3 + + # Total number of obstacle types + NUM_TYPES = 4 + + +# ============================================================================= +# Obstacle Generation Parameters +# ============================================================================= + +@dataclass(frozen=True) +class ObstacleConfig: + """Configuration for random obstacle generation. + + Controls the randomness parameters for obstacle shapes, sizes, and pit ratios. + All probabilities are in [0, 1] range. + """ + + # Height scale range (multiplier for wall_height) + SCALE_MIN: float = 0.5 + SCALE_MAX: float = 1.5 + + # Thickness range (margin cells from obstacle center) + # Higher thickness = thinner pillar, thicker bar + # Range 7-9: pillars 2-6 pixels (0.2-0.6m), bars 7-9 pixels (0.7-0.9m) + THICKNESS_MIN: int = 7 + THICKNESS_MAX: int = 10 # exclusive upper bound + + # Default pit probability when not specified + DEFAULT_PIT_PROB: float = 0.15 + + # Pit environment specific settings + PITS_BAR_RATIO: float = 0.6 # Ratio of bars vs random obstacles in pit terrain + PITS_BAR_PIT_PROB: float = 0.75 # Pit probability for bar obstacles + PITS_RANDOM_PIT_PROB: float = 0.5 # Pit probability for random obstacles + + # Bridge configuration for pit terrain + BRIDGE_COUNT_MIN: int = 3 + BRIDGE_COUNT_MAX: int = 6 # exclusive upper bound + + # Pit terrain layout (cell indices from grid edge) + PITS_TRENCH_ROW_OFFSET: int = 2 # Pit trenches at rows [offset, grid_h - offset - 1] + PITS_EDGE_MARGIN: int = 2 # Margin from grid edges for middle obstacles + + # Obstacle density multipliers (applied to difficulty) + NON_MAZE_DENSITY: float = 0.5 # For non-maze terrain (increased from 0.35) + PITS_DENSITY: float = 0.6 # For pit terrain middle area + STAIRS_OBSTACLE_DENSITY: float = 0.35 # For random obstacles in stair terrain + STAIRS_PLACEMENT_PROB: float = 0.75 # Probability of placing stairs at valid locations + + # Non-maze terrain pillar weight (higher = more pillars) + # Default uniform is 0.25 (1/4 types), 0.5 means ~50% pillars + NON_MAZE_PILLAR_WEIGHT: float = 0.5 + + +OBSTACLES = ObstacleConfig() +"""Singleton instance of obstacle configuration.""" + + +# ============================================================================= +# Helper Functions +# ============================================================================= + +def height_to_meters(height_value: int) -> float: + """Convert discretized height value to meters.""" + return height_value * VERTICAL_SCALE + + +def meters_to_height(meters: float) -> int: + """Convert meters to discretized height value.""" + return int(meters / VERTICAL_SCALE) + + +def is_valid_ground(height: int) -> bool: + """Check if height value represents valid ground.""" + return THRESHOLDS.GROUND_MIN <= height <= THRESHOLDS.GROUND_MAX + + +def is_valid_platform(height: int) -> bool: + """Check if height value represents valid platform.""" + return THRESHOLDS.PLATFORM_MIN <= height <= THRESHOLDS.PLATFORM_MAX + + +def is_valid_goal_position(height: int) -> bool: + """Check if height value is valid for goal/spawn placement.""" + return is_valid_ground(height) or is_valid_platform(height) + + +def is_obstacle(height: int) -> bool: + """Check if height value represents an obstacle (wall or pit).""" + return height > THRESHOLDS.WALL_THRESHOLD or height < THRESHOLDS.PIT_THRESHOLD + + +def is_pit(height: int) -> bool: + """Check if height value represents a pit.""" + return height < THRESHOLDS.PIT_THRESHOLD + + +def is_wall(height: int) -> bool: + """Check if height value represents a wall.""" + return height > THRESHOLDS.WALL_THRESHOLD + + +def cell_to_pixels(cell_idx: int) -> Tuple[int, int]: + """Convert cell index to pixel range. + + Args: + cell_idx: Cell index in maze grid. + + Returns: + Tuple of (start_pixel, end_pixel). + """ + start = cell_idx * CELL_PIXELS + end = (cell_idx + 1) * CELL_PIXELS + return start, end diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/pyproject.toml b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/pyproject.toml new file mode 100644 index 0000000..8a0620f --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools", "toml"] +build-backend = "setuptools.build_meta" diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/ablate_depth.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/ablate_depth.py new file mode 100644 index 0000000..9d69735 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/ablate_depth.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python3 +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Depth-ablation diagnostic for a trained navigation policy. + +Question this answers: *does the policy actually use the depth-camera input, +or has it learned to ignore it (perception-blind)?* + +Method +------ +1. Load the trained actor-critic exactly like ``play.py``. +2. Locate the ``depth_image`` slice inside the concatenated *policy* observation. +3. Roll the env out with the REAL on-policy actions, and at every step also + compute a counterfactual action where the depth slice is zeroed. Compare. +4. Also track the depth-feature statistics (std over envs/time) so we can tell + a *dead sensor* (constant features) apart from a policy that *ignores* + informative features. + +Verdict logic (printed at the end) +---------------------------------- +* depth features ~constant (std ~ 0) -> SENSOR/ENCODER dead (no signal) +* features vary, zeroing barely changes action -> LEARNED-BLIND (ignores depth) +* features vary, zeroing changes action a lot -> policy DOES use depth + +Usage (inside container, mirrors play.py): + ./isaaclab.sh -p source/isaaclab_nav_task/scripts/ablate_depth.py \ + --task Isaac-Nav-PPO-Go2-Play-v0 --num_envs 16 \ + --checkpoint --steps 300 --headless +""" + +from __future__ import annotations + +import argparse +import sys + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Depth-ablation diagnostic for a navigation policy.") +parser.add_argument("--num_envs", type=int, default=16, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task (use a *-Play-v0 variant).") +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint (.pt).") +parser.add_argument("--steps", type=int, default=300, help="Number of env steps to roll out.") +parser.add_argument("--warmup", type=int, default=20, help="Steps to skip before collecting stats (let resets settle).") +parser.add_argument("--seed", type=int, default=42, help="Seed.") + +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = parser.parse_known_args() + +# Cameras are mandatory for the depth observation. +args_cli.enable_cameras = True + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import gymnasium as gym +import torch + +from rsl_rl.runners import OnPolicyRunner + +import isaaclab_tasks # noqa: F401 +import isaaclab_nav_task # noqa: F401 + +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper + + +def _find_depth_slice(env) -> tuple[int, int, list[tuple[str, int]]]: + """Return (start, end, layout) of the ``depth_image`` term in the policy obs. + + layout is a list of (term_name, flat_dim) in concatenation order, for printing. + """ + om = env.unwrapped.observation_manager + names = om.active_terms["policy"] + dims = om.group_obs_term_dim["policy"] # list of shape-tuples per term + + layout: list[tuple[str, int]] = [] + offset = 0 + depth_start = depth_end = -1 + for name, shape in zip(names, dims): + flat = 1 + for s in shape: + flat *= s + layout.append((name, flat)) + if name == "depth_image": + depth_start, depth_end = offset, offset + flat + offset += flat + if depth_start < 0: + raise RuntimeError( + f"No 'depth_image' term found in policy obs group. Terms = {names}" + ) + return depth_start, depth_end, layout + + +def main(): + spec = gym.spec(args_cli.task) + env_cfg_class = spec.kwargs.get("env_cfg_entry_point") + agent_cfg_class = spec.kwargs.get("rsl_rl_cfg_entry_point") + + env_cfg: ManagerBasedRLEnvCfg = env_cfg_class() + agent_cfg: RslRlOnPolicyRunnerCfg = agent_cfg_class() + + if args_cli.num_envs is not None: + env_cfg.scene.num_envs = args_cli.num_envs + + env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None) + env = RslRlVecEnvWrapper(env) + + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + + # --- load checkpoint (same logic as play.py) --- + resume_path = args_cli.checkpoint + if not resume_path: + raise SystemExit("[ablate] --checkpoint is required for the diagnostic.") + print(f"[ablate] loading checkpoint: {resume_path}") + loaded = torch.load(resume_path, map_location="cpu", weights_only=False) + runner.alg.actor_critic.load_state_dict(loaded["model_state_dict"], strict=True) + if runner.empirical_normalization: + runner.obs_normalizer.load_state_dict(loaded["obs_norm_state_dict"]) + runner.critic_obs_normalizer.load_state_dict(loaded["critic_obs_norm_state_dict"]) + print(f"[ablate] checkpoint iter = {loaded.get('iter', '?')}") + + policy = runner.get_inference_policy(device=env.unwrapped.device) + + depth_start, depth_end, layout = _find_depth_slice(env) + print("=" * 78) + print("[ablate] policy observation layout (term : flat_dim):") + for name, flat in layout: + marker = " <-- DEPTH" if name == "depth_image" else "" + print(f" {name:<28} {flat:>5}{marker}") + print(f"[ablate] depth slice = [{depth_start}:{depth_end}] ({depth_end - depth_start} dims)") + print("=" * 78) + + obs, _ = env.get_observations() + + # accumulators + n = 0 + act_norm_sum = 0.0 # ||a_real|| + diff_norm_sum = 0.0 # ||a_real - a_zero|| + per_dim_abs_diff = None # mean |a_real - a_zero| per action dim + per_dim_abs_act = None # mean |a_real| per action dim + depth_feat_chunks = [] # collect depth slices to measure variability + + device = env.unwrapped.device + step = 0 + while simulation_app.is_running() and step < args_cli.steps: + with torch.inference_mode(): + a_real = policy(obs) + obs_zero = obs.clone() + obs_zero[:, depth_start:depth_end] = 0.0 + a_zero = policy(obs_zero) + + if step >= args_cli.warmup: + d = (a_real - a_zero) + diff_norm_sum += torch.linalg.vector_norm(d, dim=-1).mean().item() + act_norm_sum += torch.linalg.vector_norm(a_real, dim=-1).mean().item() + ad = d.abs().mean(dim=0) + aa = a_real.abs().mean(dim=0) + per_dim_abs_diff = ad if per_dim_abs_diff is None else per_dim_abs_diff + ad + per_dim_abs_act = aa if per_dim_abs_act is None else per_dim_abs_act + aa + depth_feat_chunks.append(obs[:, depth_start:depth_end].detach().clone()) + n += 1 + + with torch.inference_mode(): + obs, _, _, _ = env.step(a_real) + step += 1 + + # --- summarise --- + print("\n" + "=" * 78) + print(f"[ablate] collected {n} steps (after {args_cli.warmup} warmup), {args_cli.num_envs} envs") + if n == 0: + print("[ablate] no samples collected; increase --steps.") + else: + mean_act = act_norm_sum / n + mean_diff = diff_norm_sum / n + rel = (mean_diff / mean_act) if mean_act > 0 else float("nan") + per_dim_abs_diff = (per_dim_abs_diff / n).tolist() + per_dim_abs_act = (per_dim_abs_act / n).tolist() + + feats = torch.cat(depth_feat_chunks, dim=0) # (n*envs, depth_dim) + feat_std_over_samples = feats.std(dim=0).mean().item() # variability across time/envs + feat_abs_mean = feats.abs().mean().item() + + names_se2 = ["vx", "vy", "omega"] + print("\n-- ACTION SENSITIVITY TO DEPTH (real vs depth-zeroed) --") + print(f" mean ||a_real|| = {mean_act:.4f}") + print(f" mean ||a_real - a_zero|| = {mean_diff:.4f}") + print(f" RELATIVE action change = {rel*100:.2f}%") + print(" per-action-dim |diff| / |act|:") + for i, v in enumerate(per_dim_abs_diff): + nm = names_se2[i] if i < len(names_se2) else f"a{i}" + denom = per_dim_abs_act[i] if per_dim_abs_act[i] > 0 else float("nan") + print(f" {nm:<6} |diff|={v:.4f} |act|={per_dim_abs_act[i]:.4f} ratio={v/denom*100:.1f}%") + + print("\n-- DEPTH FEATURE SIGNAL (is the camera/encoder alive?) --") + print(f" feature |mean| = {feat_abs_mean:.4f}") + print(f" feature std over time/envs = {feat_std_over_samples:.4f}") + + print("\n-- VERDICT --") + if feat_std_over_samples < 1e-3: + print(" >> DEAD SIGNAL: depth features are ~constant. Camera/encoder is") + print(" not producing a varying signal (sensor/render/orientation bug).") + elif rel < 0.02: + print(" >> LEARNED-BLIND: features vary but zeroing them changes the action") + print(f" by only {rel*100:.2f}%. The policy effectively IGNORES depth.") + elif rel < 0.10: + print(f" >> WEAK USE: depth changes the action by {rel*100:.2f}% (marginal).") + else: + print(f" >> DEPTH IS USED: zeroing depth changes the action by {rel*100:.2f}%.") + print(" Perception is wired in; the failure is likely a difficulty/") + print(" generalisation gap, not blindness.") + print("=" * 78) + + env.close() + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/analyze_collisions.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/analyze_collisions.py new file mode 100755 index 0000000..26f5486 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/analyze_collisions.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python3 +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Instrumented collision analysis for a trained navigation policy. + +For every env-step, this script records: + * base_lin_vel_b[:, 0] -- forward velocity in body frame (m/s) + * max contact-force magnitude over the *termination sensor body subset* + (whatever ``terminations.base_contact.params['sensor_cfg'].body_ids`` is) + * the per-term ``base_contact`` done flag + +It maintains a per-env rolling buffer of the last K=16 steps so that, when a +collision fires for env i, we can dump the *pre-impact trajectory* (velocity + +peak force) for that env. The aggregated data is saved as a single .npz which +the companion script ``plot_collisions.py`` turns into figures. + +Outputs (under --out-dir, default ``logs/collisions/__``): + * collisions.npz full dump (see save_data()) + * summary.txt human-readable numbers +""" + +from __future__ import annotations + +import argparse +import os + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser() +parser.add_argument("--num_envs", type=int, default=32) +parser.add_argument("--task", type=str, required=True) +parser.add_argument("--checkpoint", type=str, required=True) +parser.add_argument("--steps", type=int, default=4000) +parser.add_argument("--warmup", type=int, default=20) +parser.add_argument("--seed", type=int, default=42) +parser.add_argument("--lookback", type=int, default=16, + help="How many pre-impact steps to capture per collision.") +parser.add_argument("--out-dir", type=str, default=None) +AppLauncher.add_app_launcher_args(parser) +args_cli, _ = parser.parse_known_args() +args_cli.enable_cameras = True + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import gymnasium as gym +import numpy as np +import torch + +from rsl_rl.runners import OnPolicyRunner + +import isaaclab_tasks # noqa: F401 +import isaaclab_nav_task # noqa: F401 +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.managers import SceneEntityCfg +from isaaclab.sensors import ContactSensor +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper + + +def main(): + spec = gym.spec(args_cli.task) + env_cfg: ManagerBasedRLEnvCfg = spec.kwargs["env_cfg_entry_point"]() + agent_cfg: RslRlOnPolicyRunnerCfg = spec.kwargs["rsl_rl_cfg_entry_point"]() + env_cfg.scene.num_envs = args_cli.num_envs + + env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None) + env = RslRlVecEnvWrapper(env) + device = env.unwrapped.device + N = args_cli.num_envs + + # ---- load policy ---- + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + loaded = torch.load(args_cli.checkpoint, map_location="cpu", weights_only=False) + runner.alg.actor_critic.load_state_dict(loaded["model_state_dict"], strict=True) + if runner.empirical_normalization: + runner.obs_normalizer.load_state_dict(loaded["obs_norm_state_dict"]) + runner.critic_obs_normalizer.load_state_dict(loaded["critic_obs_norm_state_dict"]) + print(f"[collisions] checkpoint iter = {loaded.get('iter', '?')}") + policy = runner.get_inference_policy(device=device) + + # ---- resolve the *exact* body subset used by the base_contact termination ---- + tm = env.unwrapped.termination_manager + tf = tm.get_term_cfg("base_contact") + sensor_cfg: SceneEntityCfg = tf.params["sensor_cfg"] + threshold = float(tf.params["threshold"]) + print(f"[collisions] base_contact threshold = {threshold} N") + print(f"[collisions] base_contact body_names spec = {sensor_cfg.body_names}") + + # NOTE: TerminationManager already resolved this SceneEntityCfg at env init, + # so body_ids is already populated; calling .resolve() again would raise. + body_ids = sensor_cfg.body_ids + contact_sensor: ContactSensor = env.unwrapped.scene.sensors[sensor_cfg.name] + print(f"[collisions] resolved body_ids = {list(body_ids) if not isinstance(body_ids, slice) else body_ids}") + + # episode_termination reward weight (for context in summary) + try: + ep_term_w = float(env.unwrapped.reward_manager.get_term_cfg("episode_termination").weight) + except Exception: + ep_term_w = float("nan") + + robot = env.unwrapped.scene["robot"] + + # ---- rolling buffers (K x N) for pre-impact dumps ---- + K = args_cli.lookback + vel_buf = torch.zeros(K, N, device=device) # base lin vel x (body frame) + speed_buf = torch.zeros(K, N, device=device) # |v_xy| (body frame) + force_buf = torch.zeros(K, N, device=device) # max contact force on subset + head = 0 # circular index + + # ---- collected data ---- + coll_traj_vel = [] # list of (K,) numpy arrays at the impact moment + coll_traj_speed = [] + coll_traj_force = [] + coll_impact_vel = [] # scalar at the IMPACT step (after termination flag flips) + coll_impact_speed = [] + coll_impact_force = [] + + # global histograms over all NON-terminating steps (for context) + all_vel_chunks = [] + all_force_chunks = [] + + n_steps_counted = 0 + n_collisions = 0 + n_success = 0 + n_timeout = 0 + + obs, _ = env.get_observations() + step = 0 + while simulation_app.is_running() and step < args_cli.steps: + # ------------------------------------------------------------- + # CRITICAL: measure state BEFORE env.step(), because IsaacLab + # auto-resets terminated envs INSIDE env.step() and that wipes + # both robot.data and contact_sensor.data for the dying envs. + # We do NOT lose the impact data: the contact force history + # buffer (decimation samples) accumulates within env.step(), + # so reading it on the *next* iteration's pre-step pass would + # be the natural way -- but at that point reset has zeroed it + # for dying envs. Compromise: at pre-step iter t+1, read + # sensor history (last decimation_count physics steps from + # iter t) for the envs that just died -- still works for envs + # whose sensor history isn't fully cleared by reset (depends + # on IsaacLab version). Velocity, on the other hand, must + # be sampled BEFORE the impact step; using buffer[head-1] + # (the prior iteration's measurement) gives us exactly that. + # ------------------------------------------------------------- + v_b = robot.data.root_lin_vel_b # (N, 3) -- state at start of iter t + v_fwd = v_b[:, 0] + v_xy = torch.norm(v_b[:, :2], dim=-1) + + net_force_hist = contact_sensor.data.net_forces_w_history # (N, H, B_total, 3) + f_mags = torch.norm(net_force_hist[:, :, body_ids, :], dim=-1) + peak_force, _ = f_mags.reshape(N, -1).max(dim=-1) # (N,) + + # Save what we *had* in the buffer before overwriting, in case + # we need to look at "1 step ago" specifically. + prev_head = (head - 1) % K + prev_vel = vel_buf[prev_head].clone() + prev_speed = speed_buf[prev_head].clone() + prev_force = force_buf[prev_head].clone() + + # Push into rolling buffer (newest at index `head`, then advance). + vel_buf[head] = v_fwd + speed_buf[head] = v_xy + force_buf[head] = peak_force + new_head = head + head = (head + 1) % K + + # ---- step the env (terminations + auto-reset happen in here) ---- + with torch.inference_mode(): + actions = policy(obs) + obs, _, _, _ = env.step(actions) + + # ---- post-step: read sensor history AGAIN for envs that just died; + # this captures the *peak* contact force during the impact step + # if the reset hasn't yet zeroed the history buffer. + post_force_hist = contact_sensor.data.net_forces_w_history + post_f_mags = torch.norm(post_force_hist[:, :, body_ids, :], dim=-1) + post_peak_force, _ = post_f_mags.reshape(N, -1).max(dim=-1) + + if step >= args_cli.warmup: + n_steps_counted += 1 + + done_bc = tm.get_term("base_contact").to(torch.bool) + done_to = tm.get_term("time_out").to(torch.bool) + done_succ = tm.get_term("early_termination").to(torch.bool) + + n_collisions += int(done_bc.sum().item()) + n_success += int(done_succ.sum().item()) + n_timeout += int(done_to.sum().item()) + + if done_bc.any(): + idxs = torch.where(done_bc)[0].cpu().tolist() + # Buffer order: oldest -> newest. Newest = just pushed at + # `new_head`. For envs that died THIS env.step(), the + # `new_head` sample is the pre-impact state at iter start. + order = [(head + i) % K for i in range(K)] + for i in idxs: + vt = vel_buf[order, i].cpu().numpy() + st = speed_buf[order, i].cpu().numpy() + ft = force_buf[order, i].cpu().numpy() + coll_traj_vel.append(vt) + coll_traj_speed.append(st) + coll_traj_force.append(ft) + # Pre-impact velocity = the value we measured BEFORE + # this env.step() (which contained the actual impact). + coll_impact_vel.append(float(v_fwd[i].item())) + coll_impact_speed.append(float(v_xy[i].item())) + # Impact force: take max of (a) pre-step reading, (b) post-step + # reading, (c) buffer max over the window -- whichever is + # largest is the best estimate of true peak force. + win_peak = float(force_buf[:, i].max().item()) + impact_f = max( + float(peak_force[i].item()), + float(post_peak_force[i].item()), + win_peak, + ) + coll_impact_force.append(impact_f) + + # Global samples (alive envs only). + alive = ~tm.dones.to(torch.bool) + if alive.any(): + all_vel_chunks.append(v_fwd[alive].cpu().numpy()) + # use post-step force for non-dying envs -- it includes + # in-step contacts the policy then recovers from. + all_force_chunks.append(post_peak_force[alive].cpu().numpy()) + + step += 1 + + # ---- save ---- + out_dir = args_cli.out_dir + if out_dir is None: + tag = os.path.splitext(os.path.basename(args_cli.checkpoint))[0] + out_dir = os.path.join("logs", "collisions", f"{args_cli.task}__{tag}") + os.makedirs(out_dir, exist_ok=True) + + impact_vel_arr = np.array(coll_impact_vel) + impact_speed_arr = np.array(coll_impact_speed) + impact_force_arr = np.array(coll_impact_force) + traj_vel_arr = np.stack(coll_traj_vel) if coll_traj_vel else np.zeros((0, K)) + traj_speed_arr = np.stack(coll_traj_speed) if coll_traj_speed else np.zeros((0, K)) + traj_force_arr = np.stack(coll_traj_force) if coll_traj_force else np.zeros((0, K)) + all_vel_arr = np.concatenate(all_vel_chunks) if all_vel_chunks else np.zeros((0,)) + all_force_arr = np.concatenate(all_force_chunks) if all_force_chunks else np.zeros((0,)) + + np.savez_compressed( + os.path.join(out_dir, "collisions.npz"), + impact_vel=impact_vel_arr, + impact_speed=impact_speed_arr, + impact_force=impact_force_arr, + traj_vel=traj_vel_arr, + traj_speed=traj_speed_arr, + traj_force=traj_force_arr, + all_vel=all_vel_arr, + all_force=all_force_arr, + threshold=np.array(threshold, dtype=np.float32), + ep_term_weight=np.array(ep_term_w, dtype=np.float32), + K=np.array(K), + num_envs=np.array(N), + steps=np.array(n_steps_counted), + n_collisions=np.array(n_collisions), + n_success=np.array(n_success), + n_timeout=np.array(n_timeout), + ) + + # ---- human summary ---- + def pct(x, total): + return 100.0 * x / max(total, 1) + + total_term = n_collisions + n_success + n_timeout + summary = [] + summary.append(f"task : {args_cli.task}") + summary.append(f"checkpoint : {args_cli.checkpoint}") + summary.append(f"steps counted : {n_steps_counted} (warmup={args_cli.warmup})") + summary.append(f"num envs : {N}") + summary.append(f"") + summary.append(f"base_contact threshold (training) : {threshold} N") + summary.append(f"episode_termination reward weight : {ep_term_w}") + summary.append(f"") + summary.append(f"terminations : success={n_success} collision={n_collisions} timeout={n_timeout}") + summary.append(f" success % : {pct(n_success, total_term):.1f}") + summary.append(f" collision % : {pct(n_collisions, total_term):.1f}") + summary.append(f" timeout % : {pct(n_timeout, total_term):.1f}") + summary.append(f"") + if impact_vel_arr.size > 0: + summary.append(f"AT IMPACT (n={impact_vel_arr.size})") + summary.append(f" v_fwd (body x) : mean={impact_vel_arr.mean():+.3f} median={np.median(impact_vel_arr):+.3f} " + f"p10={np.percentile(impact_vel_arr,10):+.3f} p90={np.percentile(impact_vel_arr,90):+.3f} " + f"std={impact_vel_arr.std():.3f} (m/s)") + summary.append(f" |v_xy| : mean={impact_speed_arr.mean():.3f} median={np.median(impact_speed_arr):.3f} " + f"p10={np.percentile(impact_speed_arr,10):.3f} p90={np.percentile(impact_speed_arr,90):.3f} (m/s)") + summary.append(f" peak force : mean={impact_force_arr.mean():.1f} median={np.median(impact_force_arr):.1f} " + f"p10={np.percentile(impact_force_arr,10):.1f} p90={np.percentile(impact_force_arr,90):.1f} " + f"max={impact_force_arr.max():.1f} (N)") + summary.append(f" force / threshold ratio : median {np.median(impact_force_arr)/threshold:.1f}x, " + f"max {impact_force_arr.max()/threshold:.1f}x") + n_slow = int((impact_speed_arr < 0.2).sum()) + n_fast = int((impact_speed_arr > 0.8).sum()) + summary.append(f" slow impacts (|v_xy|<0.2 m/s) : {n_slow} ({pct(n_slow, impact_speed_arr.size):.1f}%)") + summary.append(f" fast impacts (|v_xy|>0.8 m/s) : {n_fast} ({pct(n_fast, impact_speed_arr.size):.1f}%)") + else: + summary.append("NO COLLISIONS in this run.") + if all_vel_arr.size > 0: + summary.append(f"") + summary.append(f"GLOBAL (alive-step samples, n={all_vel_arr.size})") + summary.append(f" v_fwd : mean={all_vel_arr.mean():+.3f} median={np.median(all_vel_arr):+.3f} " + f"std={all_vel_arr.std():.3f} (m/s)") + summary.append(f" peak F : mean={all_force_arr.mean():.2f} median={np.median(all_force_arr):.2f} " + f"p99={np.percentile(all_force_arr,99):.2f} (N)") + + txt = "\n".join(summary) + with open(os.path.join(out_dir, "summary.txt"), "w") as f: + f.write(txt + "\n") + print("\n" + "=" * 78) + print(txt) + print("=" * 78) + print(f"\n[collisions] saved to: {out_dir}") + env.close() + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/convert_checkpoint.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/convert_checkpoint.py new file mode 100644 index 0000000..31e55d6 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/convert_checkpoint.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python3 +"""Convert old policy checkpoints to the new positional encoding structure. + +The old checkpoint uses: + attn_*_net.position_embedding.penc.inv_freq + +The new checkpoint uses: + attn_*_net.pos_encoding + +This script converts old checkpoints to the new format by: +1. Removing the old position_embedding.penc.inv_freq keys +2. Computing and adding the new pos_encoding tensors + +Usage: + ./isaaclab.sh -p scripts/convert_checkpoint.py --input --output + + # Or convert in-place: + ./isaaclab.sh -p scripts/convert_checkpoint.py --input --inplace +""" + +import argparse +import math +from pathlib import Path + +import torch + + +def _compute_positional_encoding_3d( + channels: int, D: int, H: int, W: int, device: torch.device, dtype: torch.dtype +) -> torch.Tensor: + """Compute 3D positional encoding for given spatial dimensions. + + This code is adapted from: https://github.com/tatp22/multidim-positional-encoding + + Args: + channels: Number of channels for the encoding. + D, H, W: Spatial dimensions (depth, height, width). + device: Device to create tensor on. + dtype: Data type for the encoding tensor. + + Returns: + Positional encoding tensor of shape (1, channels, D, H, W). + """ + org_channels = channels + channels = int(math.ceil(channels / 6) * 2) + if channels % 2: + channels += 1 + inv_freq = 1.0 / (10000 ** (torch.arange(0, channels, 2, device=device).float() / channels)) + + def get_emb(sin_inp: torch.Tensor) -> torch.Tensor: + emb = torch.stack((sin_inp.sin(), sin_inp.cos()), dim=-1) + return torch.flatten(emb, -2, -1) + + pos_x = torch.arange(D, device=device, dtype=inv_freq.dtype) + pos_y = torch.arange(H, device=device, dtype=inv_freq.dtype) + pos_z = torch.arange(W, device=device, dtype=inv_freq.dtype) + sin_inp_x = torch.einsum("i,j->ij", pos_x, inv_freq) + sin_inp_y = torch.einsum("i,j->ij", pos_y, inv_freq) + sin_inp_z = torch.einsum("i,j->ij", pos_z, inv_freq) + emb_x = get_emb(sin_inp_x).unsqueeze(1).unsqueeze(1) + emb_y = get_emb(sin_inp_y).unsqueeze(1) + emb_z = get_emb(sin_inp_z) + emb = torch.zeros((D, H, W, channels * 3), device=device, dtype=dtype) + emb[:, :, :, :channels] = emb_x + emb[:, :, :, channels : 2 * channels] = emb_y + emb[:, :, :, 2 * channels :] = emb_z + + # Convert from (D, H, W, ch) to (1, ch, D, H, W) format (channel-first with batch dim) + enc = emb[None, :, :, :, :org_channels] # (1, D, H, W, org_channels) + enc = enc.permute(0, 4, 1, 2, 3) # (1, org_channels, D, H, W) + return enc + + +def convert_checkpoint( + input_path: str, + output_path: str, + image_input_dims: tuple = (64, 5, 8), + height_input_dims: tuple = (64, 7, 7), + num_cameras: int = 1, + force: bool = False, +) -> None: + """Convert old checkpoint to new format. + + Args: + input_path: Path to the old checkpoint. + output_path: Path to save the converted checkpoint. + image_input_dims: Tuple of (C, H, W) for image input. + height_input_dims: Tuple of (C, H, W) for height map input. + num_cameras: Number of cameras (1 or 2). + force: Force re-compute pos_encoding even if already in new format. + """ + print(f"Loading checkpoint from: {input_path}") + checkpoint = torch.load(input_path, map_location="cpu", weights_only=False) + + state_dict = checkpoint["model_state_dict"] + + # Find old position_embedding keys to remove + old_keys = [k for k in state_dict.keys() if "position_embedding.penc.inv_freq" in k] + + # Check if new keys exist + new_keys = [k for k in state_dict.keys() if ".pos_encoding" in k] + + if not old_keys and not force: + print("No old position_embedding keys found. Checkpoint may already be in new format.") + if new_keys: + print(f"Found new pos_encoding keys: {new_keys}") + for k in new_keys: + print(f" {k}: {state_dict[k].shape}") + print("Checkpoint is already in new format. Use --force to re-compute pos_encoding.") + return + else: + print("Warning: Neither old nor new positional encoding keys found!") + return + + if old_keys: + print(f"Found {len(old_keys)} old position_embedding keys to convert:") + for k in old_keys: + print(f" - {k}") + # Remove old keys + for k in old_keys: + del state_dict[k] + + if new_keys and force: + print(f"Force mode: Replacing {len(new_keys)} existing pos_encoding keys:") + for k in new_keys: + print(f" - {k}: {state_dict[k].shape}") + # Remove existing pos_encoding keys to replace them + for k in new_keys: + del state_dict[k] + + # Compute and add new positional encodings + # For attn_image_net and attn_critic_image_net: spatial_dims = (num_cameras, H, W) + # For attn_height_net: spatial_dims = (1, H, W) + + image_channels = image_input_dims[0] + height_channels = height_input_dims[0] + + image_spatial_dims = (num_cameras, image_input_dims[1], image_input_dims[2]) + height_spatial_dims = (1, height_input_dims[1], height_input_dims[2]) + + print(f"\nComputing new positional encodings:") + print(f" - image_input_dims: {image_input_dims}, num_cameras: {num_cameras}") + print(f" - height_input_dims: {height_input_dims}") + print(f" - image spatial_dims (D, H, W): {image_spatial_dims}") + print(f" - height spatial_dims (D, H, W): {height_spatial_dims}") + + # Compute positional encodings + image_pos_enc = _compute_positional_encoding_3d( + image_channels, *image_spatial_dims, torch.device("cpu"), torch.float32 + ) + height_pos_enc = _compute_positional_encoding_3d( + height_channels, *height_spatial_dims, torch.device("cpu"), torch.float32 + ) + + print(f"\nNew positional encoding shapes:") + print(f" - attn_image_net.pos_encoding: {image_pos_enc.shape}") + print(f" - attn_height_net.pos_encoding: {height_pos_enc.shape}") + print(f" - attn_critic_image_net.pos_encoding: {image_pos_enc.shape}") + + # Add new keys + state_dict["attn_image_net.pos_encoding"] = image_pos_enc + state_dict["attn_height_net.pos_encoding"] = height_pos_enc + state_dict["attn_critic_image_net.pos_encoding"] = image_pos_enc.clone() + + # Save converted checkpoint + print(f"\nSaving converted checkpoint to: {output_path}") + torch.save(checkpoint, output_path) + print("Conversion complete!") + + +def main(): + parser = argparse.ArgumentParser( + description="Convert old policy checkpoints to new positional encoding structure." + ) + parser.add_argument( + "--input", "-i", + type=str, + required=True, + help="Path to the old checkpoint file." + ) + parser.add_argument( + "--output", "-o", + type=str, + default=None, + help="Path to save the converted checkpoint. If not specified, uses --inplace." + ) + parser.add_argument( + "--inplace", + action="store_true", + help="Convert the checkpoint in-place (overwrite the input file)." + ) + parser.add_argument( + "--image-dims", + type=str, + default="64,5,8", + help="Image input dimensions as C,H,W (default: 64,5,8)." + ) + parser.add_argument( + "--height-dims", + type=str, + default="64,7,7", + help="Height input dimensions as C,H,W (default: 64,7,7)." + ) + parser.add_argument( + "--num-cameras", + type=int, + default=1, + help="Number of cameras (default: 1)." + ) + parser.add_argument( + "--force", + action="store_true", + help="Force re-compute pos_encoding even if already in new format." + ) + + args = parser.parse_args() + + # Determine output path + if args.output: + output_path = args.output + elif args.inplace: + output_path = args.input + else: + # Default: add _converted suffix + input_path = Path(args.input) + output_path = str(input_path.parent / f"{input_path.stem}_converted{input_path.suffix}") + + # Parse dimensions + image_dims = tuple(int(x) for x in args.image_dims.split(",")) + height_dims = tuple(int(x) for x in args.height_dims.split(",")) + + if len(image_dims) != 3 or len(height_dims) != 3: + raise ValueError("Dimensions must be specified as C,H,W (3 values)") + + convert_checkpoint( + input_path=args.input, + output_path=output_path, + image_input_dims=image_dims, + height_input_dims=height_dims, + num_cameras=args.num_cameras, + force=args.force, + ) + + +if __name__ == "__main__": + main() diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/eval_jit_policy.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/eval_jit_policy.py new file mode 100755 index 0000000..4d2cd90 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/eval_jit_policy.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Headless evaluator for a *TorchScript JIT* navigation policy. + +Mirrors ``eval_terminations.py`` but instead of building an rsl_rl Runner and +loading a ``model_*.pt`` checkpoint, it directly loads a JIT-scripted +``ActorCriticSRU`` policy (e.g. the official upstream deployment policy +``nav_policy_new.pt``) and rolls it out in the IsaacLab navigation env. + +The JIT module exposes: + forward(observations: Tensor, reset: bool=False) -> actions: Tensor +with internal ``hidden_state`` / ``cell_state`` buffers sized +``(num_layers, 1, hidden_size)``. We resize those buffers to +``(num_layers, num_envs, hidden_size)`` after load so a single forward call +handles all envs in parallel, and we per-env zero them on episode reset. +""" + +from __future__ import annotations + +import argparse + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Evaluate a JIT navigation policy.") +parser.add_argument("--num_envs", type=int, default=32) +parser.add_argument("--task", type=str, required=True, help="Gym task id (use a *-Play-v0 variant).") +parser.add_argument("--jit_policy", type=str, required=True, help="In-container path to TorchScript .pt.") +parser.add_argument("--steps", type=int, default=2000) +parser.add_argument("--warmup", type=int, default=20) +parser.add_argument("--seed", type=int, default=42) + +AppLauncher.add_app_launcher_args(parser) +args_cli, _ = parser.parse_known_args() +args_cli.enable_cameras = True + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import gymnasium as gym +import torch + +import isaaclab_tasks # noqa: F401 +import isaaclab_nav_task # noqa: F401 + +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper + + +def main(): + # ---- env setup ---- + spec = gym.spec(args_cli.task) + env_cfg_class = spec.kwargs.get("env_cfg_entry_point") + env_cfg: ManagerBasedRLEnvCfg = env_cfg_class() + env_cfg.scene.num_envs = args_cli.num_envs + + env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None) + env = RslRlVecEnvWrapper(env) + device = env.unwrapped.device + num_envs = args_cli.num_envs + + # ---- policy load ---- + print(f"[eval-jit] loading JIT policy: {args_cli.jit_policy}") + model = torch.jit.load(args_cli.jit_policy, map_location=device) + model.eval() + print(f"[eval-jit] model loaded; type={type(model).__name__}") + + # Resize hidden state buffers from (num_layers, 1, hidden_size) to + # (num_layers, num_envs, hidden_size). Works because ``rnn`` is a generic + # LSTM-style cell that accepts any batch dim. + h = model.hidden_state + c = model.cell_state + print(f"[eval-jit] original hidden_state shape: {tuple(h.shape)}") + model.hidden_state = torch.zeros(h.shape[0], num_envs, h.shape[2], device=device, dtype=h.dtype) + model.cell_state = torch.zeros(c.shape[0], num_envs, c.shape[2], device=device, dtype=c.dtype) + print(f"[eval-jit] resized hidden_state shape: {tuple(model.hidden_state.shape)}") + + # ---- termination accounting ---- + tm = env.unwrapped.termination_manager + term_names = list(tm.active_terms) + print(f"[eval-jit] active termination terms: {term_names}") + counts = {name: 0 for name in term_names} + counts["__any__"] = 0 + + # ---- rollout ---- + obs, _ = env.get_observations() + prev_dones = torch.zeros(num_envs, dtype=torch.bool, device=device) + step = 0 + while simulation_app.is_running() and step < args_cli.steps: + # Zero hidden state for envs that just terminated (got reset internally + # by IsaacLab at the start of this step's env.step()). + if prev_dones.any(): + mask = prev_dones.to(torch.bool) + # buffer shape: (num_layers, num_envs, hidden_size) + model.hidden_state[:, mask, :] = 0 + model.cell_state[:, mask, :] = 0 + + with torch.inference_mode(): + actions = model(obs, False) + obs, _, dones, _ = env.step(actions) + + prev_dones = dones.to(torch.bool) + + if step >= args_cli.warmup: + for name in term_names: + counts[name] += int(tm.get_term(name).sum().item()) + counts["__any__"] += int(env.unwrapped.termination_manager.dones.sum().item()) + step += 1 + + # ---- report ---- + total = counts["__any__"] if counts["__any__"] > 0 else 1 + print("\n" + "=" * 78) + print(f"[eval-jit] steps counted = {args_cli.steps - args_cli.warmup}, num_envs = {num_envs}") + print(f"[eval-jit] total terminations observed = {counts['__any__']}") + print("\n TERM COUNT %-of-terms") + print(" " + "-" * 50) + for name in term_names: + c_n = counts[name] + pct = 100.0 * c_n / total + marker = "" + if name == "early_termination": + marker = " <- success" + elif name in ("base_contact", "large_pitch_angle"): + marker = " <- collision/tipover" + elif name == "terrain_fall": + marker = " <- PIT FALL" + elif name == "time_out": + marker = " <- ran out of time" + print(f" {name:<28} {c_n:>6} {pct:>5.1f}%{marker}") + print("=" * 78) + + env.close() + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/eval_terminations.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/eval_terminations.py new file mode 100644 index 0000000..5134883 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/eval_terminations.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Headless termination-breakdown evaluator for a trained navigation policy. + +Question this answers: *for a given checkpoint on a given task/difficulty, +what fraction of episodes end via each termination reason* -- including the +re-thresholded ``terrain_fall`` (now -0.3m for Go2) which is the only way to +distinguish *fell into a pit* from *bumped a wall*. + +The script mirrors ``play.py`` for env/policy setup, then counts the +TerminationManager's per-term done flags across a fixed number of env steps. +""" + +from __future__ import annotations + +import argparse + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Evaluate termination breakdown for a navigation policy.") +parser.add_argument("--num_envs", type=int, default=64, help="Number of parallel environments.") +parser.add_argument("--task", type=str, default=None, help="Gym task id (use a *-Play-v0 variant).") +parser.add_argument("--checkpoint", type=str, default=None, help="In-container path to model_*.pt.") +parser.add_argument("--steps", type=int, default=2000, help="Number of env.step() calls.") +parser.add_argument("--warmup", type=int, default=20, help="Steps to skip before counting (let resets settle).") +parser.add_argument("--seed", type=int, default=42, help="Seed.") + +AppLauncher.add_app_launcher_args(parser) +args_cli, _ = parser.parse_known_args() +args_cli.enable_cameras = True + +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +import gymnasium as gym +import torch + +from rsl_rl.runners import OnPolicyRunner + +import isaaclab_tasks # noqa: F401 +import isaaclab_nav_task # noqa: F401 + +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper + + +def main(): + spec = gym.spec(args_cli.task) + env_cfg_class = spec.kwargs.get("env_cfg_entry_point") + agent_cfg_class = spec.kwargs.get("rsl_rl_cfg_entry_point") + + env_cfg: ManagerBasedRLEnvCfg = env_cfg_class() + agent_cfg: RslRlOnPolicyRunnerCfg = agent_cfg_class() + env_cfg.scene.num_envs = args_cli.num_envs + + env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None) + env = RslRlVecEnvWrapper(env) + + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + + if not args_cli.checkpoint: + raise SystemExit("[eval] --checkpoint is required.") + print(f"[eval] loading checkpoint: {args_cli.checkpoint}") + loaded = torch.load(args_cli.checkpoint, map_location="cpu", weights_only=False) + runner.alg.actor_critic.load_state_dict(loaded["model_state_dict"], strict=True) + if runner.empirical_normalization: + runner.obs_normalizer.load_state_dict(loaded["obs_norm_state_dict"]) + runner.critic_obs_normalizer.load_state_dict(loaded["critic_obs_norm_state_dict"]) + print(f"[eval] checkpoint iter = {loaded.get('iter', '?')}") + + policy = runner.get_inference_policy(device=env.unwrapped.device) + + # Termination manager exposes per-term done flags as torch tensors. + tm = env.unwrapped.termination_manager + term_names = list(tm.active_terms) + print(f"[eval] active termination terms: {term_names}") + + # Per-term running counters (number of envs that ended via this reason). + counts = {name: 0 for name in term_names} + counts["__any__"] = 0 # any termination (sanity) + + # Print the relevant cfg knobs so the run is self-documenting. + try: + tf_params = env_cfg.terminations.terrain_fall.params + print(f"[eval] terrain_fall.fall_height_threshold = " + f"{tf_params.get('fall_height_threshold', 'default')}") + except Exception: + pass + + obs, _ = env.get_observations() + step = 0 + while simulation_app.is_running() and step < args_cli.steps: + with torch.inference_mode(): + actions = policy(obs) + obs, _, _, _ = env.step(actions) + + if step >= args_cli.warmup: + # Each per-term tensor is bool[num_envs]; sum gives this-step count. + for name in term_names: + term_tensor = tm.get_term(name) + counts[name] += int(term_tensor.sum().item()) + # Any-termination flag (rsl_rl wrapper resets on time_out OR done). + any_done = env.unwrapped.termination_manager.dones + counts["__any__"] += int(any_done.sum().item()) + step += 1 + + # -------- summarise -------- + total = counts["__any__"] if counts["__any__"] > 0 else 1 + print("\n" + "=" * 78) + print(f"[eval] steps counted = {args_cli.steps - args_cli.warmup}, num_envs = {args_cli.num_envs}") + print(f"[eval] total terminations observed = {counts['__any__']}") + print("\n TERM COUNT %-of-terms") + print(" " + "-" * 50) + for name in term_names: + c = counts[name] + pct = 100.0 * c / total + marker = "" + if name == "early_termination": + marker = " <- success" + elif name in ("base_contact", "large_pitch_angle"): + marker = " <- collision/tipover" + elif name == "terrain_fall": + marker = " <- PIT FALL (with new threshold)" + elif name == "time_out": + marker = " <- ran out of time" + print(f" {name:<28} {c:>6} {pct:>5.1f}%{marker}") + print("=" * 78) + + env.close() + + +if __name__ == "__main__": + main() + simulation_app.close() diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/play.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/play.py new file mode 100644 index 0000000..c28b680 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/play.py @@ -0,0 +1,277 @@ +#!/usr/bin/env python3 +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Play a trained navigation policy (PPO/MDPO) with automatic checkpoint loading. + +Usage: + python scripts/play.py --task [options] + +Arguments: + --task Task name (required, typically *-Play-v0 variant) + --checkpoint Path to model checkpoint (.pt file) + --use_last_checkpoint Use latest checkpoint from logs (default behavior) + --num_envs Number of parallel environments + --video Enable video recording + --video_length Video length in steps (default: 200) + +Examples: + python scripts/play.py --task Isaac-Navigation-B2W-Play-v0 + python scripts/play.py --task Isaac-Navigation-B2W-Play-v0 --checkpoint path/to/model.pt + python scripts/play.py --task Isaac-Navigation-B2W-Play-v0 --video --num_envs 16 + +Note: Automatically finds latest checkpoint if --checkpoint not specified. +""" + +from __future__ import annotations + +import argparse +import sys + +from isaaclab.app import AppLauncher + +# Add argparse arguments +parser = argparse.ArgumentParser(description="Play a trained navigation policy with RSL-RL.") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during play.") +parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.") +parser.add_argument("--use_last_checkpoint", action="store_true", help="Use last checkpoint from logs.") +parser.add_argument("--export_jit", action="store_true", default=False, help="Export policy as JIT module.") +parser.add_argument("--export_onnx", action="store_true", default=False, help="Export policy as ONNX model.") + +# Append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = parser.parse_known_args() + +# Always enable cameras +args_cli.enable_cameras = True + +# Launch simulation +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +# Import after launching simulation +import gymnasium as gym +import os +import re +import torch + +from rsl_rl.runners import OnPolicyRunner + +# Import Isaac Lab extensions +import isaaclab_tasks # noqa: F401 +import isaaclab_nav_task # noqa: F401 + +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper, export_policy_as_onnx + + +def find_latest_checkpoint(log_path: str, checkpoint_pattern: str = "model_.*.pt") -> str: + """Find the latest checkpoint file in the log directory. + + Args: + log_path: Base log directory path + checkpoint_pattern: Regex pattern for checkpoint files + + Returns: + Path to the latest checkpoint file + """ + # Find all run directories + if not os.path.exists(log_path): + raise ValueError(f"Log path does not exist: {log_path}") + + run_dirs = [] + for entry in os.scandir(log_path): + if entry.is_dir() and re.match(r"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}", entry.name): + run_dirs.append(entry.name) + + if not run_dirs: + raise ValueError(f"No run directories found in: {log_path}") + + # Sort to get latest run + run_dirs.sort() + latest_run = run_dirs[-1] + run_path = os.path.join(log_path, latest_run) + + # Find checkpoint files + checkpoint_files = [] + for f in os.listdir(run_path): + if re.match(checkpoint_pattern, f): + checkpoint_files.append(f) + + if not checkpoint_files: + raise ValueError(f"No checkpoint files matching '{checkpoint_pattern}' found in: {run_path}") + + # Sort to get latest checkpoint + checkpoint_files.sort(key=lambda m: f"{m:0>15}") + latest_checkpoint = checkpoint_files[-1] + + return os.path.join(run_path, latest_checkpoint) + + +def load_checkpoint_with_fallback(runner: OnPolicyRunner, checkpoint_path: str, load_optimizer: bool = True): + """Load checkpoint with fallback for PyTorch compatibility issues. + + Args: + runner: RSL-RL runner instance + checkpoint_path: Path to checkpoint file + load_optimizer: Whether to load optimizer state + """ + print(f"[INFO] Loading checkpoint from: {checkpoint_path}") + + # Load checkpoint to CPU first for compatibility + loaded_dict = torch.load(checkpoint_path, map_location='cpu', weights_only=False) + + # Load model state - handle both standard algorithms (PPO) and MDPO + if runner.is_mdpo: + # MDPO uses two actor-critics, load same state into both + runner.alg.actor_critic_1.load_state_dict(loaded_dict["model_state_dict"], strict=True) + runner.alg.actor_critic_2.load_state_dict(loaded_dict["model_state_dict"], strict=True) + else: + # Standard algorithms use one actor-critic + runner.alg.actor_critic.load_state_dict(loaded_dict["model_state_dict"], strict=True) + + # Load normalizers if using empirical normalization + if runner.empirical_normalization: + runner.obs_normalizer.load_state_dict(loaded_dict["obs_norm_state_dict"]) + runner.critic_obs_normalizer.load_state_dict(loaded_dict["critic_obs_norm_state_dict"]) + + # Load optimizer if requested + if load_optimizer: + if runner.is_mdpo: + runner.alg.optimizer_1.load_state_dict(loaded_dict["optimizer_state_dict"]) + else: + runner.alg.optimizer.load_state_dict(loaded_dict["optimizer_state_dict"]) + + runner.current_learning_iteration = loaded_dict["iter"] + print(f"[INFO] Loaded checkpoint from iteration {loaded_dict['iter']}") + + +def export_policy_jit(runner: OnPolicyRunner, checkpoint_path: str): + """Export policy as JIT module to an 'export' folder next to the checkpoint. + + Args: + runner: RSL-RL runner instance with loaded policy + checkpoint_path: Path to the checkpoint file (used to determine export location) + """ + # Determine export directory (create 'export' folder in the same directory as checkpoint) + checkpoint_dir = os.path.dirname(checkpoint_path) + export_dir = os.path.join(checkpoint_dir, "export") + + # Get the actor-critic module + if runner.is_mdpo: + actor_critic = runner.alg.actor_critic_1 + else: + actor_critic = runner.alg.actor_critic + + # Get normalizer if using empirical normalization + normalizer = runner.obs_normalizer if runner.empirical_normalization else None + + # Export using the module's export_jit method + print(f"[INFO] Exporting JIT policy to: {export_dir}") + actor_critic.export_jit(path=export_dir, filename="policy.pt", normalizer=normalizer) + print(f"[INFO] JIT export complete!") + + +def export_policy_onnx(runner: OnPolicyRunner, checkpoint_path: str): + """Export policy as ONNX model to an 'export' folder next to the checkpoint. + + Args: + runner: RSL-RL runner instance with loaded policy + checkpoint_path: Path to the checkpoint file (used to determine export location) + """ + # Determine export directory (create 'export' folder in the same directory as checkpoint) + checkpoint_dir = os.path.dirname(checkpoint_path) + export_dir = os.path.join(checkpoint_dir, "export") + + # Get the actor-critic module + if runner.is_mdpo: + actor_critic = runner.alg.actor_critic_1 + else: + actor_critic = runner.alg.actor_critic + + # Get normalizer if using empirical normalization + normalizer = runner.obs_normalizer if runner.empirical_normalization else None + + # Check if the module has export_onnx method + if not hasattr(actor_critic, "export_onnx"): + raise NotImplementedError( + f"ONNX export not implemented for {type(actor_critic).__name__}. " + "Please add an export_onnx method to this module." + ) + + # Export using the module's export_onnx method + print(f"[INFO] Exporting ONNX policy to: {export_dir}") + actor_critic.export_onnx(path=export_dir, filename="policy.onnx", normalizer=normalizer) + print(f"[INFO] ONNX export complete!") + + +def main(): + """Play navigation policy with RSL-RL.""" + # Parse command-line arguments + spec = gym.spec(args_cli.task) + env_cfg_class = spec.kwargs.get("env_cfg_entry_point") + agent_cfg_class = spec.kwargs.get("rsl_rl_cfg_entry_point") + + # Instantiate the configs + env_cfg: ManagerBasedRLEnvCfg = env_cfg_class() + agent_cfg: RslRlOnPolicyRunnerCfg = agent_cfg_class() + + # Override config from command line + if args_cli.num_envs is not None: + env_cfg.scene.num_envs = args_cli.num_envs + + # Create the environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + # Wrap the environment + env = RslRlVecEnvWrapper(env) + + # Get checkpoint path + if args_cli.checkpoint: + resume_path = args_cli.checkpoint + else: + # Get last checkpoint from log directory + log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) + resume_path = find_latest_checkpoint(log_root_path, checkpoint_pattern="model_.*.pt") + + # Create runner + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) + + # Load checkpoint with compatibility handling + load_checkpoint_with_fallback(runner, resume_path) + + # Export JIT if requested + if args_cli.export_jit: + export_policy_jit(runner, resume_path) + + # Export ONNX if requested + if args_cli.export_onnx: + export_policy_onnx(runner, resume_path) + + # Obtain policy for inference + policy = runner.get_inference_policy(device=env.unwrapped.device) + + # Reset environment + obs, _ = env.get_observations() + + # Simulate environment + while simulation_app.is_running(): + # Run policy + with torch.inference_mode(): + actions = policy(obs) + # Step environment + obs, _, _, _ = env.step(actions) + + # Close the environment + env.close() + + +if __name__ == "__main__": + # Run the main function + main() + # Close simulation + simulation_app.close() diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/plot_collisions.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/plot_collisions.py new file mode 100755 index 0000000..424dfa1 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/plot_collisions.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Render figures from a collisions.npz produced by analyze_collisions.py. + +Run on the *host* (matplotlib only, no Isaac). Writes PNGs next to the .npz. +""" +from __future__ import annotations +import argparse, os +import numpy as np +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("npz", help="Path to collisions.npz") + args = ap.parse_args() + + d = np.load(args.npz) + out_dir = os.path.dirname(os.path.abspath(args.npz)) + + thr = float(d["threshold"]) + ep_w = float(d["ep_term_weight"]) + K = int(d["K"]) + n_coll = int(d["n_collisions"]) + n_succ = int(d["n_success"]) + n_to = int(d["n_timeout"]) + + impact_vel = d["impact_vel"] + impact_speed = d["impact_speed"] + impact_force = d["impact_force"] + traj_vel = d["traj_vel"] + traj_speed = d["traj_speed"] + traj_force = d["traj_force"] + all_vel = d["all_vel"] + all_force = d["all_force"] + + # ===== Fig 1: impact velocity histogram ===== + fig, axes = plt.subplots(1, 2, figsize=(12, 4.5)) + + ax = axes[0] + if impact_vel.size > 0: + ax.hist(impact_vel, bins=40, color="#d9534f", alpha=0.85, edgecolor="white") + ax.axvline(impact_vel.mean(), color="black", ls="--", lw=1.5, + label=f"mean = {impact_vel.mean():+.2f} m/s") + ax.axvline(0.0, color="gray", ls=":", lw=1) + ax.set_xlabel("body-frame forward velocity at impact (m/s)") + ax.set_ylabel("# collisions") + ax.set_title(f"Velocity at collision (n={impact_vel.size})") + ax.legend() + ax.grid(alpha=0.3) + + ax = axes[1] + if impact_speed.size > 0: + ax.hist(impact_speed, bins=40, color="#5bc0de", alpha=0.85, edgecolor="white") + ax.axvline(impact_speed.mean(), color="black", ls="--", lw=1.5, + label=f"mean = {impact_speed.mean():.2f} m/s") + ax.axvline(0.2, color="orange", ls=":", lw=1, label="0.2 m/s (slow-impact cutoff)") + ax.set_xlabel("planar speed |v_xy| at impact (m/s)") + ax.set_ylabel("# collisions") + ax.set_title("Planar speed at collision") + ax.legend() + ax.grid(alpha=0.3) + fig.tight_layout() + fig.savefig(os.path.join(out_dir, "fig1_impact_velocity.png"), dpi=130) + plt.close(fig) + + # ===== Fig 2: contact force histogram (log scale) with threshold ===== + fig, ax = plt.subplots(figsize=(8, 5)) + if impact_force.size > 0: + bins = np.logspace(np.log10(max(thr * 0.5, 0.5)), + np.log10(max(impact_force.max() * 1.2, thr * 10)), 50) + ax.hist(impact_force, bins=bins, color="#f0ad4e", alpha=0.85, edgecolor="white", + label=f"impact peak force (n={impact_force.size})") + ax.axvline(thr, color="red", ls="--", lw=2, label=f"training threshold = {thr:.1f} N") + ax.axvline(np.median(impact_force), color="black", ls=":", lw=1.5, + label=f"median impact = {np.median(impact_force):.0f} N " + f"({np.median(impact_force)/thr:.0f}× thr)") + ax.set_xscale("log") + ax.set_xlabel("peak contact force on (base, hip, thigh) at impact (N, log)") + ax.set_ylabel("# collisions") + ax.set_title("Impact force vs training termination threshold") + ax.legend() + ax.grid(alpha=0.3, which="both") + fig.tight_layout() + fig.savefig(os.path.join(out_dir, "fig2_impact_force.png"), dpi=130) + plt.close(fig) + + # ===== Fig 3: pre-impact trajectory (median + IQR) ===== + if traj_vel.shape[0] > 0: + steps = np.arange(-K + 1, 1) + fig, axes = plt.subplots(1, 2, figsize=(12, 4.5), sharex=True) + + for ax, data, ylabel, title, color in [ + (axes[0], traj_speed, "planar speed |v_xy| (m/s)", "Speed leading up to collision", "#5bc0de"), + (axes[1], traj_force, "peak contact force (N)", "Force leading up to collision", "#f0ad4e"), + ]: + med = np.median(data, axis=0) + p25 = np.percentile(data, 25, axis=0) + p75 = np.percentile(data, 75, axis=0) + ax.fill_between(steps, p25, p75, color=color, alpha=0.35, label="IQR (25-75%)") + ax.plot(steps, med, color=color, lw=2.2, label="median") + ax.axvline(0, color="red", ls="--", lw=1.5, label="impact step") + ax.set_xlabel("env-step relative to impact") + ax.set_ylabel(ylabel) + ax.set_title(f"{title} (n={data.shape[0]})") + ax.legend() + ax.grid(alpha=0.3) + if axes[1].get_ylim()[1] > 5 * thr: + axes[1].set_yscale("symlog", linthresh=max(thr, 1.0)) + axes[1].axhline(thr, color="red", ls=":", lw=1) + fig.tight_layout() + fig.savefig(os.path.join(out_dir, "fig3_pre_impact.png"), dpi=130) + plt.close(fig) + + # ===== Fig 4: global v_fwd distribution (alive steps) vs at-impact ===== + fig, ax = plt.subplots(figsize=(8, 5)) + if all_vel.size > 0: + ax.hist(all_vel, bins=60, density=True, color="#5cb85c", alpha=0.55, + edgecolor="white", label=f"alive steps (n={all_vel.size})") + if impact_vel.size > 0: + ax.hist(impact_vel, bins=40, density=True, color="#d9534f", alpha=0.55, + edgecolor="white", label=f"at impact (n={impact_vel.size})") + ax.axvline(0, color="gray", ls=":", lw=1) + ax.set_xlabel("body-frame forward velocity v_fwd (m/s)") + ax.set_ylabel("density") + ax.set_title("Forward velocity: normal navigation vs at collision") + ax.legend() + ax.grid(alpha=0.3) + fig.tight_layout() + fig.savefig(os.path.join(out_dir, "fig4_vfwd_normal_vs_impact.png"), dpi=130) + plt.close(fig) + + # ===== short text summary ===== + lines = [] + lines.append(f"threshold = {thr} N ep_term_w = {ep_w}") + lines.append(f"terminations: success={n_succ} collision={n_coll} timeout={n_to}") + if impact_force.size > 0: + lines.append(f"impact force: median {np.median(impact_force):.1f} N " + f"({np.median(impact_force)/thr:.0f}x threshold), " + f"p90 {np.percentile(impact_force,90):.1f}, max {impact_force.max():.1f}") + if impact_speed.size > 0: + slow = (impact_speed < 0.2).mean() * 100 + fast = (impact_speed > 0.8).mean() * 100 + lines.append(f"impact |v_xy|: median {np.median(impact_speed):.2f} m/s " + f"slow<0.2: {slow:.0f}% fast>0.8: {fast:.0f}%") + print("\n".join(lines)) + print(f"\nfigures saved into: {out_dir}") + + +if __name__ == "__main__": + main() diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/train.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/train.py new file mode 100644 index 0000000..ab28157 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/scripts/train.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Train a navigation policy using RSL-RL (PPO/MDPO algorithms). + +Usage: + python scripts/train.py --task --num_envs [options] + +Arguments: + --task Task name (required) + --num_envs Number of parallel environments + --seed Random seed + --max_iterations Training iterations + --run_name Custom run name for logging + --video Enable video recording + --video_length Video length in steps (default: 200) + --video_interval Recording interval in steps (default: 2000) + +Examples: + python scripts/train.py --task Isaac-Navigation-B2W-v0 --num_envs 2048 + python scripts/train.py --task Isaac-Navigation-B2W-v0 --video --seed 42 + +Logs saved to: logs/rsl_rl/// +""" + +from __future__ import annotations + +import argparse +import sys + +# Add the parent directory to the path so we can import from the extension +from isaaclab.app import AppLauncher + +# Add argparse arguments +parser = argparse.ArgumentParser(description="Train a navigation policy with RSL-RL.") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") +parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") +parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).") +parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") +parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.") +parser.add_argument("--run_name", type=str, default=None, help="Name of the wandb run (appended to log directory).") +parser.add_argument("--checkpoint", type=str, default=None, help="Path to a checkpoint (.pt) to warm-start from before training begins.") +parser.add_argument("--load_optimizer", action="store_true", default=False, help="Also load the optimizer state from the checkpoint (default: only load model weights, recommended for cross-robot warm-start).") + +# Append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +args_cli, hydra_args = parser.parse_known_args() + +# always enable cameras to record video +if args_cli.video: + args_cli.enable_cameras = True + +# Launch simulation +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +# Import after launching simulation +import gymnasium as gym +import os +import torch +from datetime import datetime + +from rsl_rl.runners import OnPolicyRunner + +# Import Isaac Lab extensions +import isaaclab_tasks # noqa: F401 +import isaaclab_nav_task # noqa: F401 + +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.utils.dict import print_dict +from isaaclab.utils.io import dump_pickle, dump_yaml +from isaaclab_tasks.utils import get_checkpoint_path +from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry +from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper + +# Set torch backends for better performance +torch.backends.cuda.matmul.allow_tf32 = True +torch.backends.cudnn.allow_tf32 = True +torch.backends.cudnn.deterministic = False +torch.backends.cudnn.benchmark = False + + +def main(): + """Train navigation policy with RSL-RL.""" + # Load the configurations from the registry + env_cfg = load_cfg_from_registry(args_cli.task, "env_cfg_entry_point") + agent_cfg: RslRlOnPolicyRunnerCfg = load_cfg_from_registry(args_cli.task, "rsl_rl_cfg_entry_point") + + # Override config from command line + if args_cli.num_envs is not None: + env_cfg.scene.num_envs = args_cli.num_envs + if args_cli.seed is not None: + agent_cfg.seed = args_cli.seed + if args_cli.max_iterations is not None: + agent_cfg.max_iterations = args_cli.max_iterations + if args_cli.run_name is not None: + agent_cfg.run_name = args_cli.run_name + + # Create the environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + # Wrap the environment + env = RslRlVecEnvWrapper(env) + + # Specify log directory + log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) + log_root_path = os.path.abspath(log_root_path) + print(f"[INFO] Logging experiment in directory: {log_root_path}") + # Specify run directory based on timestamp + log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + if agent_cfg.run_name: + log_dir += f"_{agent_cfg.run_name}" + log_dir = os.path.join(log_root_path, log_dir) + + # Create runner + runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device) + + # Optional: warm-start from an existing checkpoint (e.g. cross-robot fine-tuning). + if args_cli.checkpoint is not None: + ckpt_path = os.path.abspath(args_cli.checkpoint) + if not os.path.isfile(ckpt_path): + raise FileNotFoundError(f"Checkpoint not found: {ckpt_path}") + print(f"[INFO] Warm-starting from checkpoint: {ckpt_path}") + print(f"[INFO] load_optimizer = {args_cli.load_optimizer}") + runner.load(ckpt_path, load_optimizer=args_cli.load_optimizer) + + # Write git state to log + runner.add_git_repo_to_log(__file__) + # Save configuration + dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg) + dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg) + dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg) + dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg) + + # Run training + runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True) + + # Close the environment + env.close() + + +if __name__ == "__main__": + # Run the main function + main() + # Close simulation + simulation_app.close() diff --git a/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/setup.py b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/setup.py new file mode 100644 index 0000000..d92fe9a --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/mount/sru-navigation-sim/setup.py @@ -0,0 +1,65 @@ +# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich. +# All rights reserved. +# +# SPDX-License-Identifier: MIT + +"""Installation script for the 'isaaclab_nav_task' python package. + +IsaacLab task extension for SRU (Spatially-enhanced Recurrent Unit) visual navigation project. +Provides hierarchical control architecture, maze terrain generation with curriculum learning, +and depth-based reinforcement learning for legged robot navigation. +""" + +import os +import toml + +from setuptools import setup + +# Obtain the extension data from the extension.toml file +EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__)) +# Read the extension.toml file +EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml")) + +# Minimum dependencies required prior to installation +INSTALL_REQUIRES = [ + # generic + "numpy<2", + "torch>=2.5.1", + "torchvision>=0.14.1", + # io + "h5py", + # visualization + "tensorboard", +] + +PYTORCH_INDEX_URL = ["https://download.pytorch.org/whl/cu128"] + +# Installation operation +setup( + name="isaaclab_nav_task", + author="Fan Yang, Per Frivik", + author_email="fanyang1@ethz.ch, pfrivik@ethz.ch", + maintainer="Fan Yang, Per Frivik", + maintainer_email="fanyang1@ethz.ch, pfrivik@ethz.ch", + url=EXTENSION_TOML_DATA["package"]["repository"], + version=EXTENSION_TOML_DATA["package"]["version"], + description=EXTENSION_TOML_DATA["package"]["description"], + keywords=EXTENSION_TOML_DATA["package"]["keywords"], + include_package_data=True, + python_requires=">=3.10", + install_requires=INSTALL_REQUIRES, + dependency_links=PYTORCH_INDEX_URL, + packages=["isaaclab_nav_task"], + classifiers=[ + "Natural Language :: English", + "Programming Language :: Python :: 3.10", + "Isaac Sim :: 4.5.0", + "Isaac Lab :: 2.1.1", + "License :: OSI Approved :: MIT License", + "Intended Audience :: Science/Research", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Topic :: Scientific/Engineering :: Robotics", + ], + zip_safe=False, + license="MIT", +) diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/ablate_depth.sh b/sru_ws/reference/SRU-Odin/Train/scripts/ablate_depth.sh new file mode 100755 index 0000000..dbb0f47 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/ablate_depth.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +# Depth-ablation diagnostic: does the trained Go2 policy actually USE the depth +# camera, or has it learned to ignore it (perception-blind)? +# +# Runs headless inside the container, rolls out the policy, and compares the +# action with vs without the depth slice zeroed. Prints a verdict. +# +# Examples: +# # Latest run, latest checkpoint +# ./scripts/ablate_depth.sh +# +# # Specific run + iter +# ./scripts/ablate_depth.sh --run-dir 2026-06-16_09-24-44_phase2 --from-iter 6998 +# +# # More steps / envs for tighter stats +# ./scripts/ablate_depth.sh --from-iter 6998 --envs 32 --steps 400 +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +# ---- defaults ---- +TASK="Isaac-Nav-PPO-Go2-Play-v0" +EXPERIMENT="go2_navigation_ppo_dev" +NUM_ENVS=16 +STEPS=300 +FROM_ITER="" +RUN_DIR="" +CHECKPOINT="" +SEED=42 + +usage() { sed -n '1,18p' "$0"; exit 0; } + +while [[ $# -gt 0 ]]; do + case "$1" in + --from-iter) FROM_ITER="$2"; shift 2 ;; + --run-dir) RUN_DIR="$2"; shift 2 ;; + --checkpoint) CHECKPOINT="$2"; shift 2 ;; + --task) TASK="$2"; shift 2 ;; + --experiment) EXPERIMENT="$2"; shift 2 ;; + --envs) NUM_ENVS="$2"; shift 2 ;; + --steps) STEPS="$2"; shift 2 ;; + --seed) SEED="$2"; shift 2 ;; + -h|--help) usage ;; + *) echo "[error] Unknown arg: $1" >&2; usage ;; + esac +done + +HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT" + +# ---- resolve checkpoint (same scheme as play_go2.sh) ---- +if [[ -z "$CHECKPOINT" ]]; then + if [[ -z "$RUN_DIR" ]]; then + RUN_DIR="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)" + [[ -z "$RUN_DIR" ]] && { echo "[error] No runs under $HOST_LOG_ROOT" >&2; exit 1; } + fi + RUN_PATH="$HOST_LOG_ROOT/$RUN_DIR" + [[ -d "$RUN_PATH" ]] || { echo "[error] Run dir not found: $RUN_PATH" >&2; exit 1; } + + if [[ -n "$FROM_ITER" ]]; then + HOST_CKPT="$RUN_PATH/model_${FROM_ITER}.pt" + [[ -f "$HOST_CKPT" ]] || { echo "[error] Checkpoint not found: $HOST_CKPT" >&2; exit 1; } + else + HOST_CKPT="$(ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null | sort -V | tail -n 1)" + [[ -z "$HOST_CKPT" ]] && { echo "[error] No model_*.pt in $RUN_PATH" >&2; exit 1; } + fi + CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}" +else + HOST_CKPT="${CHECKPOINT/\/workspace\/IsaacLab\/logs/$REPO_ROOT\/outputs\/logs}" +fi + +cat </ + --from-iter N model_.pt + --checkpoint PATH explicit in-container ckpt (overrides above) + --envs N (default: $NUM_ENVS) + --steps N (default: $STEPS) + --seed N (default: $SEED) + +Forwarded env vars: PLAY_DIFFICULTY PLAY_SUBTERRAIN_MIX PLAY_MAZE_ONLY + PLAY_CELL_SIZE PLAY_CLASSIC_MAZE +EOF + exit 0 +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --task) TASK="$2"; shift 2 ;; + --experiment) EXPERIMENT="$2"; shift 2 ;; + --run-dir) RUN_DIR="$2"; shift 2 ;; + --from-iter) FROM_ITER="$2"; shift 2 ;; + --checkpoint) CHECKPOINT="$2"; shift 2 ;; + --envs) NUM_ENVS="$2"; shift 2 ;; + --steps) STEPS="$2"; shift 2 ;; + --seed) SEED="$2"; shift 2 ;; + -h|--help) usage ;; + *) echo "[error] $1" >&2; usage ;; + esac +done + +HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT" +if [[ -z "$CHECKPOINT" ]]; then + [[ -z "$RUN_DIR" || -z "$FROM_ITER" ]] && { echo "[error] need --run-dir + --from-iter or --checkpoint" >&2; exit 1; } + HOST_CKPT="$HOST_LOG_ROOT/$RUN_DIR/model_${FROM_ITER}.pt" + [[ -f "$HOST_CKPT" ]] || { echo "[error] not found: $HOST_CKPT" >&2; exit 1; } + CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}" +fi + +TAG="${RUN_DIR:-$(basename "$(dirname "$CHECKPOINT")")}_iter${FROM_ITER:-unknown}" +HOST_OUT="$REPO_ROOT/outputs/collisions/$TAG" +CTR_OUT="/workspace/IsaacLab/logs/collisions/$TAG" +mkdir -p "$HOST_OUT" + +echo "[collisions] task=$TASK" +echo "[collisions] ckpt(ctr)=$CHECKPOINT" +echo "[collisions] out(host)=$HOST_OUT" + +docker run --rm --gpus all \ + -e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \ + -e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \ + -e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \ + -e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \ + -e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \ + -e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \ + -e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \ + --shm-size=16g --network host --ipc host \ + --ulimit memlock=-1 --ulimit stack=67108864 \ + -v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \ + -v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \ + -v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \ + --entrypoint bash sru-nav:latest -lc \ + "./isaaclab.sh -p source/isaaclab_nav_task/scripts/analyze_collisions.py \ + --task $TASK \ + --num_envs $NUM_ENVS \ + --steps $STEPS \ + --seed $SEED \ + --checkpoint $CHECKPOINT \ + --out-dir $CTR_OUT \ + --headless && \ + ./isaaclab.sh -p source/isaaclab_nav_task/scripts/plot_collisions.py $CTR_OUT/collisions.npz" +echo "[collisions] done -> $HOST_OUT" +ls -la "$HOST_OUT" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/check_go2_registration.py b/sru_ws/reference/SRU-Odin/Train/scripts/check_go2_registration.py new file mode 100644 index 0000000..79fba36 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/check_go2_registration.py @@ -0,0 +1,19 @@ +"""Verify Go2 nav tasks are registered correctly. Must be launched via isaaclab.sh -p.""" + +from isaaclab.app import AppLauncher + +# Headless minimal launcher +app_launcher = AppLauncher(headless=True, enable_cameras=False) +simulation_app = app_launcher.app + +import gymnasium as gym # noqa: E402 +import isaaclab_nav_task # noqa: F401, E402 + +ids = sorted(s for s in gym.envs.registry.keys() if "Go2" in s or "B2W" in s) +print("=" * 60) +print("Registered Go2 + B2W tasks:") +print("=" * 60) +for i in ids: + print(f" {i}") + +simulation_app.close() diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/compare_baselines.sh b/sru_ws/reference/SRU-Odin/Train/scripts/compare_baselines.sh new file mode 100755 index 0000000..dcfee79 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/compare_baselines.sh @@ -0,0 +1,190 @@ +#!/usr/bin/env bash +# Apples-to-apples comparison: my-Go2-policy vs official-B2W-policy on the +# SAME pure-maze scene (same seed, same PLAY_* env vars => same maze layouts). +# +# Bodies differ (Go2 quadruped vs B2W wheeled), but the terrain topology is +# identical, so success-rate / failure-mode breakdowns are directly comparable +# as a "policy + body" combo. +# +# Example: +# ./scripts/compare_baselines.sh \ +# --go2-run 2026-06-23_11-13-55_puremaze_tight_corridors \ +# --go2-iter 32200 \ +# --b2w-jit assets/baselines/b2w_nav_policy_new.pt \ +# --cell-size 2.0 \ +# --difficulty "0.8,1.0" \ +# --envs 32 --steps 2000 --seed 42 +set -euo pipefail +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +# ---- defaults ---- +GO2_EXPERIMENT="go2_navigation_ppo_puremaze" +GO2_RUN="" +GO2_ITER="" +B2W_JIT="" +CELL_SIZE="2.0" +DIFFICULTY="0.8,1.0" +NUM_ENVS=32 +STEPS=2000 +SEED=42 +OUT_DIR="$REPO_ROOT/outputs/compare/$(date +%Y%m%d_%H%M%S)" + +usage() { + cat </). + --go2-iter N Go2 model_.pt iter. + +Required (B2W side): + --b2w-jit PATH Host path to TorchScript B2W policy (e.g. nav_policy_new.pt). + +Options: + --go2-experiment N Go2 experiment subdir (default: $GO2_EXPERIMENT). + --cell-size F PLAY_CELL_SIZE in meters (default: $CELL_SIZE). + NOTE: B2W body is large; cell<1.5 usually impossible. + --difficulty "l,h" PLAY_DIFFICULTY band (default: "$DIFFICULTY"). + --envs N Parallel envs (default: $NUM_ENVS). + --steps N env.step() count (default: $STEPS). + --seed N Shared seed for both runs (default: $SEED). + --out-dir PATH Where to write logs+diff (default: outputs/compare/). + -h, --help + +Both runs share: + PLAY_MAZE_ONLY=1 (100% maze sub-terrain) + PLAY_CLASSIC_MAZE=1 (paper-style uniform walls) + PLAY_DIFFICULTY=\$DIFFICULTY + PLAY_CELL_SIZE=\$CELL_SIZE + --seed \$SEED, --num_envs \$NUM_ENVS, --steps \$STEPS +EOF + exit 0 +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --go2-run) GO2_RUN="$2"; shift 2 ;; + --go2-iter) GO2_ITER="$2"; shift 2 ;; + --go2-experiment) GO2_EXPERIMENT="$2"; shift 2 ;; + --b2w-jit) B2W_JIT="$2"; shift 2 ;; + --cell-size) CELL_SIZE="$2"; shift 2 ;; + --difficulty) DIFFICULTY="$2"; shift 2 ;; + --envs) NUM_ENVS="$2"; shift 2 ;; + --steps) STEPS="$2"; shift 2 ;; + --seed) SEED="$2"; shift 2 ;; + --out-dir) OUT_DIR="$2"; shift 2 ;; + -h|--help) usage ;; + *) echo "[error] Unknown arg: $1" >&2; usage ;; + esac +done + +[[ -z "$GO2_RUN" || -z "$GO2_ITER" || -z "$B2W_JIT" ]] && \ + { echo "[error] --go2-run, --go2-iter, --b2w-jit are required." >&2; usage; } + +mkdir -p "$OUT_DIR" +GO2_LOG="$OUT_DIR/go2_eval.log" +B2W_LOG="$OUT_DIR/b2w_eval.log" +DIFF_TABLE="$OUT_DIR/comparison.md" + +# Shared env vars for both runs. +export PLAY_MAZE_ONLY=1 +export PLAY_CLASSIC_MAZE=1 +export PLAY_DIFFICULTY="$DIFFICULTY" +export PLAY_CELL_SIZE="$CELL_SIZE" + +cat <>> running Go2 eval ..." +"$REPO_ROOT/scripts/eval_terminations.sh" \ + --task Isaac-Nav-PPO-Go2-Play-v0 \ + --experiment "$GO2_EXPERIMENT" \ + --run-dir "$GO2_RUN" \ + --from-iter "$GO2_ITER" \ + --envs "$NUM_ENVS" --steps "$STEPS" --seed "$SEED" \ + 2>&1 | tee "$GO2_LOG" + +# ---- 2. B2W (official JIT) on maze ---- +echo "[compare] >>> running B2W eval ..." +"$REPO_ROOT/scripts/eval_jit_baseline.sh" \ + --task Isaac-Nav-PPO-B2W-Play-v0 \ + --jit-policy "$B2W_JIT" \ + --envs "$NUM_ENVS" --steps "$STEPS" --seed "$SEED" \ + 2>&1 | tee "$B2W_LOG" + +# ---- 3. Parse both logs and produce a side-by-side table ---- +python3 - "$GO2_LOG" "$B2W_LOG" "$DIFF_TABLE" <<'PY' +import re, sys, pathlib +go2_log, b2w_log, out_md = sys.argv[1], sys.argv[2], sys.argv[3] + +def parse(path): + """Extract per-term counts from an eval-style log.""" + text = pathlib.Path(path).read_text() + rows = {} + # lines look like: " early_termination 1234 45.6% <- success" + for m in re.finditer(r"^\s{2}([a-z_]+)\s+(\d+)\s+([\d.]+)%", text, re.M): + rows[m.group(1)] = (int(m.group(2)), float(m.group(3))) + return rows + +g = parse(go2_log) +b = parse(b2w_log) +all_terms = sorted(set(g) | set(b)) + +# Ordering: success first, then collisions, then time_out, then rest. +priority = {"early_termination": 0, "base_contact": 1, "large_pitch_angle": 2, + "terrain_fall": 3, "time_out": 4} +all_terms.sort(key=lambda n: (priority.get(n, 99), n)) + +lines = [] +lines.append("# Go2-policy vs official-B2W-policy on identical maze scenes\n") +lines.append("| termination | Go2 count | Go2 % | B2W count | B2W % | meaning |") +lines.append("|----------------------|-----------|--------|-----------|--------|---------|") +meaning = { + "early_termination": "**success** (reached goal)", + "base_contact": "collision (body hit wall)", + "large_pitch_angle": "tipped over", + "terrain_fall": "fell into pit", + "time_out": "ran out of time", +} +for t in all_terms: + gc, gp = g.get(t, (0, 0.0)) + bc, bp = b.get(t, (0, 0.0)) + lines.append(f"| `{t:<20}` | {gc:>9} | {gp:>5.1f}% | {bc:>9} | {bp:>5.1f}% | {meaning.get(t,'')} |") + +# Summary delta on success rate. +g_succ = g.get("early_termination", (0, 0.0))[1] +b_succ = b.get("early_termination", (0, 0.0))[1] +lines.append("") +lines.append(f"**Success rate:** Go2 = **{g_succ:.1f}%**, B2W = **{b_succ:.1f}%**, " + f"Δ = **{g_succ - b_succ:+.1f}** pp (Go2 - B2W)") + +out = "\n".join(lines) + "\n" +pathlib.Path(out_md).write_text(out) +print("\n" + "=" * 78) +print(out) +print(f"[compare] wrote {out_md}") +PY + +echo "" +echo "[compare] all done." +echo " setup: $OUT_DIR/setup.txt" +echo " go2 log: $GO2_LOG" +echo " b2w log: $B2W_LOG" +echo " table: $DIFF_TABLE" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/continue_go2.sh b/sru_ws/reference/SRU-Odin/Train/scripts/continue_go2.sh new file mode 100755 index 0000000..2c68fe5 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/continue_go2.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# Continue training the Go2 SRU navigation policy with explicit CLI flags. +# +# Examples: +# # Continue from the latest checkpoint of the latest run, train 1000 more iters. +# ./scripts/continue_go2.sh --iters 1000 +# +# # Resume from a specific iteration of the latest run. +# ./scripts/continue_go2.sh --iters 2000 --from-iter 1000 +# +# # Resume from a specific run directory + iteration. +# ./scripts/continue_go2.sh --iters 500 \ +# --run-dir 2026-06-12_08-16-50_resume_from_33 --from-iter 600 +# +# # Pin an exact checkpoint file (in-container path). +# ./scripts/continue_go2.sh --iters 500 \ +# --checkpoint /workspace/IsaacLab/logs/rsl_rl/go2_navigation_ppo_dev/2026-06-12_08-16-50_resume_from_33/model_1000.pt +# +# # GUI mode, fewer envs. +# ./scripts/continue_go2.sh --iters 200 --envs 8 --gui +# +# # Switch to the full-PPO task (different experiment_name dir). +# ./scripts/continue_go2.sh --iters 2000 --task Isaac-Nav-PPO-Go2-v0 \ +# --experiment go2_navigation_ppo_ft_from_b2w +# +# Behavior: +# - --load-optimizer is ON by default (true PPO resume); disable with --no-load-optimizer. +# - A new timestamped run directory is created; old runs are preserved. +# - The new run's --max_iterations is the *absolute* PPO iteration target, +# so set it to (start_iter + extra_iters). For convenience you can pass +# --extra-iters N which will be added to the resumed start_iter. +# +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +# ---- defaults ---- +TASK="Isaac-Nav-PPO-Go2-Dev-v0" +EXPERIMENT="go2_navigation_ppo_dev" # log subdir under outputs/logs/rsl_rl/ +NUM_ENVS=1024 +ITERS="" # absolute target iteration count +EXTRA_ITERS="" # alternative: N more iters past the resumed checkpoint +FROM_ITER="" # specific iteration number to resume from +RUN_DIR="" # specific run dir name under / +CHECKPOINT="" # explicit in-container checkpoint path (overrides everything) +SEED=42 +RUN_NAME="" # auto-generated if empty +GUI=0 +LOAD_OPTIMIZER=1 + +usage() { + sed -n '1,30p' "$0" + echo + echo "Flags:" + echo " --iters N Absolute target PPO iteration count (overrides max_iterations)." + echo " --extra-iters N Iters to train past the resumed start (alternative to --iters)." + echo " --from-iter N Resume from model_.pt within the chosen run dir." + echo " --run-dir NAME Run dir name under outputs/logs/rsl_rl//." + echo " --checkpoint PATH Explicit in-container checkpoint path (overrides above)." + echo " --task NAME Gym task id (default: $TASK)." + echo " --experiment NAME Log subdir to scan (default: $EXPERIMENT)." + echo " --envs N Parallel envs (default: $NUM_ENVS)." + echo " --seed N Seed (default: $SEED)." + echo " --run-name STR Suffix for the new run dir (default: resume_from_)." + echo " --gui Show Isaac Sim GUI (X11)." + echo " --no-load-optimizer Load model only (cold optimizer)." + echo " -h, --help Show this help." + exit 0 +} + +# ---- arg parsing ---- +while [[ $# -gt 0 ]]; do + case "$1" in + --iters) ITERS="$2"; shift 2 ;; + --extra-iters) EXTRA_ITERS="$2"; shift 2 ;; + --from-iter) FROM_ITER="$2"; shift 2 ;; + --run-dir) RUN_DIR="$2"; shift 2 ;; + --checkpoint) CHECKPOINT="$2"; shift 2 ;; + --task) TASK="$2"; shift 2 ;; + --experiment) EXPERIMENT="$2"; shift 2 ;; + --envs) NUM_ENVS="$2"; shift 2 ;; + --seed) SEED="$2"; shift 2 ;; + --run-name) RUN_NAME="$2"; shift 2 ;; + --gui) GUI=1; shift ;; + --no-load-optimizer) LOAD_OPTIMIZER=0; shift ;; + -h|--help) usage ;; + *) echo "[error] Unknown arg: $1" >&2; usage ;; + esac +done + +HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT" + +# ---- resolve checkpoint ---- +if [[ -z "$CHECKPOINT" ]]; then + if [[ -z "$RUN_DIR" ]]; then + RUN_DIR="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)" + [[ -z "$RUN_DIR" ]] && { echo "[error] No runs under $HOST_LOG_ROOT" >&2; exit 1; } + fi + RUN_PATH="$HOST_LOG_ROOT/$RUN_DIR" + [[ -d "$RUN_PATH" ]] || { echo "[error] Run dir not found: $RUN_PATH" >&2; exit 1; } + + if [[ -n "$FROM_ITER" ]]; then + HOST_CKPT="$RUN_PATH/model_${FROM_ITER}.pt" + [[ -f "$HOST_CKPT" ]] || { echo "[error] Checkpoint not found: $HOST_CKPT" >&2; exit 1; } + else + HOST_CKPT="$(ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null | sort -V | tail -n 1)" + [[ -z "$HOST_CKPT" ]] && { echo "[error] No model_*.pt in $RUN_PATH" >&2; exit 1; } + fi + CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}" +else + HOST_CKPT="${CHECKPOINT/\/workspace\/IsaacLab\/logs/$REPO_ROOT\/outputs\/logs}" +fi + +# ---- derive start iter from filename if possible ---- +START_ITER="$(basename "$HOST_CKPT" | sed -nE 's/model_([0-9]+)\.pt/\1/p')" +[[ -z "$START_ITER" ]] && START_ITER=0 + +# ---- resolve target iteration count ---- +if [[ -z "$ITERS" && -n "$EXTRA_ITERS" ]]; then + ITERS=$(( START_ITER + EXTRA_ITERS )) +fi +if [[ -z "$ITERS" ]]; then + echo "[error] Must provide --iters N (absolute) or --extra-iters N (relative)." >&2 + exit 1 +fi + +[[ -z "$RUN_NAME" ]] && RUN_NAME="resume_from_${START_ITER}" + +# ---- GUI plumbing ---- +HEADLESS_FLAG="--headless" +EXTRA_DOCKER_ARGS=() +if [[ "$GUI" == "1" ]]; then + HEADLESS_FLAG="" + xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true + EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}" + -v /tmp/.X11-unix:/tmp/.X11-unix:rw + -v "$HOME/.Xauthority:/root/.Xauthority:ro") +fi + +OPT_FLAG="" +[[ "$LOAD_OPTIMIZER" == "1" ]] && OPT_FLAG="--load_optimizer" + +cat < mean_actions + +Usage: + /workspace/IsaacLab/_isaac_sim/python.sh /tmp/convert_rsl_rl_ckpt_to_jit.py \ + +""" + +import sys +import torch +import torch.nn as nn + + +def infer_actor_dims(state_dict): + """Walk actor.{0,2,4,...}.weight to recover layer sizes & activation slots.""" + layer_dims = [] + indices = sorted( + int(k.split(".")[1]) + for k in state_dict + if k.startswith("actor.") and k.endswith(".weight") + ) + for idx in indices: + w = state_dict[f"actor.{idx}.weight"] + if w.ndim != 2: + continue + if not layer_dims: + layer_dims.append(w.shape[1]) # in_features of first Linear + layer_dims.append(w.shape[0]) # out_features + return layer_dims, indices + + +def build_actor_mlp(layer_dims, linear_indices, activation_name="elu"): + """Build an nn.Sequential mirroring rsl_rl's actor: + Linear -> Activation -> Linear -> Activation -> ... -> Linear (no final activation).""" + if activation_name.lower() == "elu": + act_cls = nn.ELU + elif activation_name.lower() == "relu": + act_cls = nn.ReLU + elif activation_name.lower() == "tanh": + act_cls = nn.Tanh + else: + raise ValueError(f"unknown activation: {activation_name}") + + # rsl_rl stores layers at indices 0, 2, 4, ... (activations live in odd slots). + # We reconstruct that exact layout so load_state_dict by name works. + layers = [] + n_linears = len(layer_dims) - 1 + for i in range(n_linears): + layers.append(nn.Linear(layer_dims[i], layer_dims[i + 1])) + if i < n_linears - 1: + layers.append(act_cls()) + return nn.Sequential(*layers) + + +class DeployableActor(nn.Module): + """Wraps the actor MLP and provides a clean forward(obs) -> mean_actions.""" + + def __init__(self, actor: nn.Module): + super().__init__() + self.actor = actor + + def forward(self, obs: torch.Tensor) -> torch.Tensor: + return self.actor(obs) + + +def main(): + if len(sys.argv) != 3: + print("usage: convert_rsl_rl_ckpt_to_jit.py ") + sys.exit(1) + src, dst = sys.argv[1], sys.argv[2] + + print(f"[convert] loading checkpoint: {src}") + ckpt = torch.load(src, map_location="cpu", weights_only=False) + + sd_full = ckpt["model_state_dict"] if "model_state_dict" in ckpt else ckpt + # Strip critic / std from state dict for the actor-only deployable model. + actor_sd = {k: v for k, v in sd_full.items() if k.startswith("actor.")} + print(f"[convert] actor weights: {len(actor_sd)} tensors") + + layer_dims, linear_indices = infer_actor_dims(sd_full) + print(f"[convert] actor MLP shape: {' -> '.join(map(str, layer_dims))}") + print(f"[convert] action_dim = {layer_dims[-1]}, obs_dim = {layer_dims[0]}") + + actor = build_actor_mlp(layer_dims, linear_indices, activation_name="elu") + # Strip the "actor." prefix so the bare Sequential can load by index keys. + stripped_sd = {k[len("actor."):]: v for k, v in actor_sd.items()} + missing, unexpected = actor.load_state_dict(stripped_sd, strict=True) + assert not missing and not unexpected, (missing, unexpected) + print(f"[convert] state_dict loaded ✓") + + deploy = DeployableActor(actor).eval() + + # Sanity forward pass + with torch.inference_mode(): + fake = torch.zeros(2, layer_dims[0]) + out = deploy(fake) + print(f"[convert] forward sanity: in={tuple(fake.shape)} -> out={tuple(out.shape)}") + print(f"[convert] zero-input output[0]: {out[0].numpy().round(3).tolist()}") + + # Trace OR script. We use script since the MLP is straight-line code. + scripted = torch.jit.script(deploy) + scripted.save(dst) + print(f"[convert] saved TorchScript model: {dst}") + + # Verify round-trip + reloaded = torch.jit.load(dst, map_location="cpu") + with torch.inference_mode(): + out2 = reloaded(fake) + assert torch.allclose(out, out2, atol=1e-6), "round-trip mismatch!" + print(f"[convert] round-trip torch.jit.load() works ✓") + + +if __name__ == "__main__": + main() diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/eval_jit_baseline.sh b/sru_ws/reference/SRU-Odin/Train/scripts/eval_jit_baseline.sh new file mode 100755 index 0000000..2d0d4f4 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/eval_jit_baseline.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +# Evaluate a TorchScript JIT navigation policy (e.g. the official B2W baseline +# nav_policy_new.pt) on the IsaacLab navigation env, with the same PLAY_* +# terrain env vars as eval_terminations.sh. +# +# Example: baseline on dense paper-style maze +# PLAY_DIFFICULTY="0.8,1.0" \ +# PLAY_SUBTERRAIN_MIX="maze=1,non_maze=0,pits=0" \ +# PLAY_CLASSIC_MAZE=1 \ +# ./scripts/eval_jit_baseline.sh \ +# --task Isaac-Nav-PPO-B2W-Play-v0 \ +# --jit-policy assets/baselines/b2w_nav_policy_new.pt \ +# --envs 32 --steps 2000 +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +TASK="Isaac-Nav-PPO-B2W-Play-v0" +JIT_HOST="" +NUM_ENVS=32 +STEPS=2000 +SEED=42 + +usage() { + cat <&2; usage ;; + esac +done + +[[ -z "$JIT_HOST" ]] && { echo "[error] --jit-policy is required." >&2; exit 1; } +# Resolve to absolute path +if [[ "$JIT_HOST" != /* ]]; then JIT_HOST="$REPO_ROOT/$JIT_HOST"; fi +[[ -f "$JIT_HOST" ]] || { echo "[error] JIT file not found: $JIT_HOST" >&2; exit 1; } + +JIT_CTR="/workspace/baseline_policy.pt" + +cat <&2; usage ;; + esac +done + +HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT" + +if [[ -z "$CHECKPOINT" ]]; then + if [[ -z "$RUN_DIR" ]]; then + RUN_DIR="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)" + [[ -z "$RUN_DIR" ]] && { echo "[error] No runs under $HOST_LOG_ROOT" >&2; exit 1; } + fi + RUN_PATH="$HOST_LOG_ROOT/$RUN_DIR" + [[ -d "$RUN_PATH" ]] || { echo "[error] Run dir not found: $RUN_PATH" >&2; exit 1; } + + if [[ -n "$FROM_ITER" ]]; then + HOST_CKPT="$RUN_PATH/model_${FROM_ITER}.pt" + [[ -f "$HOST_CKPT" ]] || { echo "[error] Checkpoint not found: $HOST_CKPT" >&2; exit 1; } + else + HOST_CKPT="$(ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null | sort -V | tail -n 1)" + [[ -z "$HOST_CKPT" ]] && { echo "[error] No model_*.pt in $RUN_PATH" >&2; exit 1; } + fi + CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}" +else + HOST_CKPT="${CHECKPOINT/\/workspace\/IsaacLab\/logs/$REPO_ROOT\/outputs\/logs}" +fi + +cat </model_4600.pt + + # Export and also save JIT + python scripts/export_onnx.py --checkpoint --jit + + # Override output location + python scripts/export_onnx.py --checkpoint --output-dir ./exported + +Requirements: + - torch + - The rsl_rl fork must be importable (pip-installed or on PYTHONPATH) + +ONNX model interface (ActorCriticSRU, single camera): + Inputs: + - obs: (1, num_actor_obs) — flattened observation vector + - h_in: (num_layers, 1, hidden) — LSTM hidden state (zeros at episode start) + - c_in: (num_layers, 1, hidden) — LSTM cell state (zeros at episode start) + Outputs: + - actions: (1, num_actions) + - h_out: (num_layers, 1, hidden) — updated hidden state + - c_out: (num_layers, 1, hidden) — updated cell state +""" +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path + +import torch + + +def infer_config_from_state_dict(sd: dict) -> dict: + """Infer ActorCriticSRU constructor args from checkpoint weight shapes.""" + + # --- image_input_dims and num_cameras --- + # attn_image_net cross-attention query projection weight: (Q, image_dim) + # The first linear in CrossAttentionFuseModule is the query proj. + # We look for attn_image_net.0.weight or similar. + attn_keys = [k for k in sd if k.startswith("attn_image_net.") and "weight" in k] + if not attn_keys: + raise ValueError("Cannot find attn_image_net weights in checkpoint") + # image_dim = out_features of the query projection + # CrossAttentionFuseModule: q_proj weight shape = (image_dim, image_dim) + # Find the first weight (query proj) + attn_w = sd[attn_keys[0]] + image_dim = attn_w.shape[0] # output features + + # num_image_features = image_dim * H * W + # We can get it from the actor input: actor_proprioceptive_input_dim + num_image_features = num_actor_obs + # But we need H, W separately. Get from attn_image_net spatial reshape. + # CrossAttentionFuseModule stores no spatial dims as parameters. + # Instead, infer from total image features: look at the first linear of actor + # which takes mlp_input_dim_actor = actor_proprioceptive_input_dim + image_dim + # num_image_features = image_dim * H * W + # We need H, W from image_input_dims=(C, H, W) where C=image_dim. + # Check if there's a pattern in the attn weights that reveals spatial dims. + # Fallback: use the known Go2 config defaults. + # The Go2 config uses image_input_dims=(64, 5, 8), height_input_dims=(64, 7, 7). + # image_dim=64, H=5, W=8 -> num_image_features = 64*5*8 = 2560 + # We can infer num_image_features from the observation dimension: + # num_actor_obs = actor_proprioceptive_input_dim + num_image_features * num_cameras + # actor_proprioceptive_input_dim = mlp_input_dim_actor - image_dim + # mlp_input_dim_actor = memory_a input size = rnn input_size + + # Get rnn input_size from memory_a.rnn weight + rnn_keys = [k for k in sd if k.startswith("memory_a.") and "weight_ih" in k] + if not rnn_keys: + raise ValueError("Cannot find memory_a.rnn.weight_ih in checkpoint") + rnn_input_size = sd[rnn_keys[0]].shape[1] # input size of LSTM + rnn_hidden_size = sd[rnn_keys[0]].shape[0] // 4 # LSTM has 4 gates + + # mlp_input_dim_actor = rnn_input_size + # actor_proprioceptive_input_dim = mlp_input_dim_actor - image_dim + actor_proprioceptive_input_dim = rnn_input_size - image_dim + + # Get num_image_features from the linear_dropout_actor or actor first layer + # linear_dropout_actor.linear weight: (actor_hidden_dims[0], rnn_hidden_size) + ld_keys = [k for k in sd if k.startswith("linear_dropout_actor.") and "weight" in k] + if ld_keys: + actor_hidden_0 = sd[ld_keys[0]].shape[0] + else: + actor_hidden_0 = 512 # default + + # Get num_actions from actor last layer + actor_linear_keys = [k for k in sd if k.startswith("actor.") and "weight" in k] + if not actor_linear_keys: + raise ValueError("Cannot find actor weights in checkpoint") + # Last actor layer weight: (num_actions, actor_hidden_dims[-1]) + last_actor_w = sd[actor_linear_keys[-1]] + num_actions = last_actor_w.shape[0] + + # Infer num_cameras: num_actor_obs = actor_proprioceptive_input_dim + num_image_features * num_cameras + # We need num_actor_obs. We can get it from the attn_image_net input. + # CrossAttentionFuseModule q_proj input = image_dim, k_proj input = info_dim = actor_proprioceptive_input_dim + # But we still can't directly get num_image_features. + # However, for Go2 with 1 camera: num_image_features = image_dim * H * W = 64 * 5 * 8 = 2560 + # For 2 cameras: num_actor_obs = actor_proprioceptive + 2 * num_image_features + # We can try both and see which gives a "reasonable" obs dim. + # Actually, we can get num_image_features from the attn_image_net more carefully. + # CrossAttentionFuseModule reshapes image (B, C, H, W) -> (B, H*W, C) then projects. + # The number of spatial tokens = H * W. This doesn't show up as a weight shape. + # + # Strategy: use known Go2 defaults (image_input_dims=(64,5,8), num_cameras=1) + # and verify consistency. + H, W = 5, 8 # Go2 default + num_image_features = image_dim * H * W + num_cameras = 1 # Go2 default + + num_actor_obs = actor_proprioceptive_input_dim + num_image_features * num_cameras + + # Infer height_input_dims for critic (not needed for actor export but for constructor) + height_dim = image_dim # default 64 + hH, hW = 7, 7 # Go2 default + num_height_features = height_dim * hH * hW + + # critic_proprioceptive_input_dim = num_critic_obs - num_height_features - num_image_features * num_cameras - 1 + # We need num_critic_obs. Get from critic rnn input. + critic_rnn_keys = [k for k in sd if k.startswith("memory_c.") and "weight_ih" in k] + if critic_rnn_keys: + critic_rnn_input = sd[critic_rnn_keys[0]].shape[1] + critic_proprioceptive = critic_rnn_input - image_dim - height_dim + num_critic_obs = critic_proprioceptive + num_height_features + num_image_features * num_cameras + 1 + else: + num_critic_obs = num_actor_obs # fallback + + # rnn_num_layers + rnn_num_layers = len([k for k in sd if k.startswith("memory_a.") and "weight_ih_l" in k]) + if rnn_num_layers == 0: + rnn_num_layers = 1 + + # actor_hidden_dims from actor weights + actor_hidden_dims = [] + for k in sorted(actor_linear_keys): + w = sd[k] + actor_hidden_dims.append(w.shape[1]) + # Last layer's shape[0] is num_actions, not a hidden dim + if actor_hidden_dims: + actor_hidden_dims[-1] = actor_hidden_dims[-1] # keep last hidden + # Actually actor weights: layer0 (h1, in), layer1 (h2, h1), ..., layerN (num_actions, hN) + # So hidden_dims = [in_of_first] ... no, hidden_dims = [h1, h2, ..., hN] + # weight shapes: (h1, in), (h2, h1), ..., (num_actions, hN) + # hidden_dims = [out of each layer except last] = [h1, h2, ..., hN] + actor_hidden_dims = [] + for i, k in enumerate(sorted(actor_linear_keys)): + w = sd[k] + if i < len(actor_linear_keys) - 1: + actor_hidden_dims.append(w.shape[0]) # output dim = next hidden + # last layer: shape[0] = num_actions + + config = { + "num_actor_obs": num_actor_obs, + "num_critic_obs": num_critic_obs, + "num_actions": num_actions, + "actor_hidden_dims": actor_hidden_dims if actor_hidden_dims else [512, 256, 128], + "critic_hidden_dims": actor_hidden_dims if actor_hidden_dims else [512, 256, 128], + "activation": "elu", + "init_noise_std": 1.0, + "image_input_dims": (image_dim, H, W), + "height_input_dims": (height_dim, hH, hW), + "rnn_type": "lstm_sru", + "dropout": 0.2, + "rnn_hidden_size": rnn_hidden_size, + "rnn_num_layers": rnn_num_layers, + "time_embed_dim": 8, + "num_cameras": num_cameras, + } + + return config + + +def main(): + parser = argparse.ArgumentParser(description="Export SRU navigation policy checkpoint to ONNX.") + parser.add_argument("--checkpoint", type=str, required=True, + help="Path to model checkpoint (.pt file)") + parser.add_argument("--output-dir", type=str, default=None, + help="Output directory (default: /export)") + parser.add_argument("--filename", type=str, default="policy.onnx", + help="Output filename (default: policy.onnx)") + parser.add_argument("--jit", action="store_true", + help="Also export JIT (policy.pt)") + parser.add_argument("--verbose", action="store_true", + help="Print inferred config and model architecture") + args = parser.parse_args() + + checkpoint_path = Path(args.checkpoint).resolve() + if not checkpoint_path.exists(): + print(f"[error] Checkpoint not found: {checkpoint_path}", file=sys.stderr) + sys.exit(1) + + # Load checkpoint + print(f"[export_onnx] Loading checkpoint: {checkpoint_path}") + ckpt = torch.load(str(checkpoint_path), map_location="cpu", weights_only=False) + sd = ckpt["model_state_dict"] + print(f"[export_onnx] Checkpoint iteration: {ckpt.get('iter', 'unknown')}") + + # Infer model config from weights + config = infer_config_from_state_dict(sd) + if args.verbose: + print("\n[export_onnx] Inferred config:") + for k, v in config.items(): + print(f" {k}: {v}") + print() + + # Build model + from rsl_rl.modules import ActorCriticSRU + + model = ActorCriticSRU(**config) + model.load_state_dict(sd, strict=True) + model.eval() + model.to("cpu") + + print(f"[export_onnx] Model loaded successfully") + print(f" num_actor_obs: {config['num_actor_obs']}") + print(f" num_actions: {config['num_actions']}") + print(f" num_cameras: {config['num_cameras']}") + print(f" image_dims: {config['image_input_dims']}") + print(f" rnn_hidden: {config['rnn_hidden_size']}") + + # Determine output directory + if args.output_dir: + output_dir = Path(args.output_dir) + else: + output_dir = checkpoint_path.parent / "export" + + # Export ONNX + print(f"\n[export_onnx] Exporting ONNX to: {output_dir}/{args.filename}") + model.export_onnx(path=str(output_dir), filename=args.filename) + + # Optionally export JIT + if args.jit: + jit_filename = args.filename.replace(".onnx", ".pt") + if jit_filename == args.filename: + jit_filename = "policy.pt" + print(f"\n[export_onnx] Exporting JIT to: {output_dir}/{jit_filename}") + model.export_jit(path=str(output_dir), filename=jit_filename) + + print(f"\n[export_onnx] Done! Output: {output_dir}") + + +if __name__ == "__main__": + main() diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/inspect_run.py b/sru_ws/reference/SRU-Odin/Train/scripts/inspect_run.py new file mode 100755 index 0000000..c093e63 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/inspect_run.py @@ -0,0 +1,218 @@ +#!/usr/bin/env python3 +"""Inspect a SRU-Go2 training run: dump TensorBoard scalars + ckpt summary. + +Usage: + python scripts/inspect_run.py --run outputs/logs/rsl_rl// + python scripts/inspect_run.py --latest # auto-pick newest run + python scripts/inspect_run.py --latest --experiment go2_navigation_ppo_dev + python scripts/inspect_run.py --run --tags Train/mean_reward Loss/value_function + +The script tries `tensorboard` first, falls back to `tbparse`, then to a +minimal pure-protobuf reader. Prints a compact markdown-friendly summary +that can be pasted directly into docs/RUN_LOG.md. +""" +from __future__ import annotations + +import argparse +import glob +import os +import re +import sys +from pathlib import Path +from typing import Dict, List, Tuple + +REPO_ROOT = Path(__file__).resolve().parents[1] +DEFAULT_LOG_ROOT = REPO_ROOT / "outputs" / "logs" / "rsl_rl" + +# Tags worth surfacing by default (rsl_rl + custom). The script will keep only +# the ones that actually appear in the events file. +DEFAULT_TAGS = [ + "Train/mean_reward", + "Train/mean_episode_length", + "Train/learning_rate", + "Loss/value_function", + "Loss/surrogate", + "Loss/entropy", + "Policy/mean_noise_std", + "Train/mean_success_rate", + "Train/mean_collision_rate", +] + + +def _find_latest_run(experiment: str | None) -> Path: + if experiment: + roots = [DEFAULT_LOG_ROOT / experiment] + else: + roots = sorted([p for p in DEFAULT_LOG_ROOT.iterdir() if p.is_dir()]) + candidates: List[Path] = [] + for root in roots: + if not root.exists(): + continue + for entry in root.iterdir(): + if entry.is_dir() and re.match(r"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}", entry.name): + candidates.append(entry) + if not candidates: + raise SystemExit(f"[inspect_run] No runs under {DEFAULT_LOG_ROOT}") + candidates.sort(key=lambda p: p.stat().st_mtime) + return candidates[-1] + + +def _read_scalars(run_dir: Path) -> Dict[str, List[Tuple[int, float]]]: + """Read all scalar tags from the run's tfevents files. + + Returns mapping: tag -> list[(step, value)] sorted by step. + Tries tensorboard.EventAccumulator; falls back to tbparse; then raw protobuf. + """ + files = sorted(glob.glob(str(run_dir / "events.out.tfevents.*"))) + if not files: + raise SystemExit(f"[inspect_run] No tfevents in {run_dir}") + + # --- attempt 1: tensorboard --- + try: + from tensorboard.backend.event_processing.event_accumulator import EventAccumulator + acc = EventAccumulator(str(run_dir), size_guidance={"scalars": 0}) + acc.Reload() + out: Dict[str, List[Tuple[int, float]]] = {} + for tag in acc.Tags().get("scalars", []): + out[tag] = [(e.step, e.value) for e in acc.Scalars(tag)] + return out + except Exception as e: + print(f"[inspect_run] tensorboard path failed: {e}; trying tbparse", file=sys.stderr) + + # --- attempt 2: tbparse --- + try: + from tbparse import SummaryReader # type: ignore + reader = SummaryReader(str(run_dir), pivot=False) + df = reader.scalars + out2: Dict[str, List[Tuple[int, float]]] = {} + for tag, group in df.groupby("tag"): + group = group.sort_values("step") + out2[tag] = list(zip(group["step"].astype(int), group["value"].astype(float))) + return out2 + except Exception as e: + print(f"[inspect_run] tbparse failed: {e}; trying raw protobuf", file=sys.stderr) + + # --- attempt 3: raw protobuf via tensorflow --- + try: + import tensorflow as tf # type: ignore + out3: Dict[str, List[Tuple[int, float]]] = {} + for f in files: + for raw in tf.data.TFRecordDataset(f): + ev = tf.compat.v1.Event.FromString(raw.numpy()) + if not ev.summary: + continue + for v in ev.summary.value: + if v.HasField("simple_value"): + out3.setdefault(v.tag, []).append((int(ev.step), float(v.simple_value))) + for k in out3: + out3[k].sort() + return out3 + except Exception as e: + raise SystemExit( + f"[inspect_run] All readers failed. Install one of:\n" + f" pip install tensorboard\n pip install tbparse\n" + f"Last error: {e}" + ) + + +def _summarize(series: List[Tuple[int, float]]) -> dict: + if not series: + return {} + steps = [s for s, _ in series] + vals = [v for _, v in series] + peak_idx = max(range(len(vals)), key=lambda i: vals[i]) + min_idx = min(range(len(vals)), key=lambda i: vals[i]) + # last-decile mean to smooth jitter + tail = vals[max(0, len(vals) - max(1, len(vals) // 10)) :] + return { + "start_step": steps[0], + "start_val": vals[0], + "end_step": steps[-1], + "end_val": vals[-1], + "peak_step": steps[peak_idx], + "peak_val": vals[peak_idx], + "min_step": steps[min_idx], + "min_val": vals[min_idx], + "tail_mean": sum(tail) / len(tail), + "n_points": len(series), + } + + +def _ckpt_summary(run_dir: Path) -> dict: + ckpts = sorted(run_dir.glob("model_*.pt"), key=lambda p: int(re.findall(r"model_(\d+)\.pt", p.name)[0])) + if not ckpts: + return {} + latest = ckpts[-1] + iter_n = int(re.findall(r"model_(\d+)\.pt", latest.name)[0]) + return { + "count": len(ckpts), + "latest": latest.name, + "latest_iter": iter_n, + "size_mb": latest.stat().st_size / 1024 / 1024, + "all_iters": [int(re.findall(r"model_(\d+)\.pt", p.name)[0]) for p in ckpts], + } + + +def _md_table(rows: List[List[str]], header: List[str]) -> str: + out = ["| " + " | ".join(header) + " |", "| " + " | ".join(["---"] * len(header)) + " |"] + for r in rows: + out.append("| " + " | ".join(r) + " |") + return "\n".join(out) + + +def main(): + ap = argparse.ArgumentParser() + g = ap.add_mutually_exclusive_group() + g.add_argument("--run", type=str, help="Path to a run directory (host).") + g.add_argument("--latest", action="store_true", help="Pick newest run under outputs/logs/rsl_rl/.") + ap.add_argument("--experiment", type=str, default=None, help="Restrict --latest to this experiment subdir.") + ap.add_argument("--tags", nargs="*", default=None, help="Override the tag whitelist; pass tag names.") + ap.add_argument("--all-tags", action="store_true", help="Print every scalar tag found.") + args = ap.parse_args() + + if args.run: + run_dir = Path(args.run).resolve() + else: + run_dir = _find_latest_run(args.experiment) + if not run_dir.exists(): + raise SystemExit(f"[inspect_run] Not a dir: {run_dir}") + + print(f"# Run inspection\n") + print(f"- **dir**: `{run_dir}`") + ck = _ckpt_summary(run_dir) + if ck: + print(f"- **checkpoints**: {ck['count']} files, latest `{ck['latest']}` " + f"(iter {ck['latest_iter']}, {ck['size_mb']:.1f} MB)") + print(f"- **all iters saved**: {ck['all_iters']}") + print() + + scalars = _read_scalars(run_dir) + tags = args.tags or (list(scalars.keys()) if args.all_tags else DEFAULT_TAGS) + rows = [] + for tag in tags: + if tag not in scalars: + continue + s = _summarize(scalars[tag]) + if not s: + continue + rows.append([ + f"`{tag}`", + f"{s['start_val']:.3g} @ {s['start_step']}", + f"{s['end_val']:.3g} @ {s['end_step']}", + f"{s['peak_val']:.3g} @ {s['peak_step']}", + f"{s['min_val']:.3g} @ {s['min_step']}", + f"{s['tail_mean']:.3g}", + str(s["n_points"]), + ]) + + print("## Scalars\n") + if rows: + print(_md_table(rows, ["tag", "start", "end", "peak", "min", "tail-mean(10%)", "n"])) + else: + print("_no matching tags found_") + print(f"\navailable tags: {sorted(scalars.keys())}") + print() + + +if __name__ == "__main__": + main() diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/open_isaacsim_gui.sh b/sru_ws/reference/SRU-Odin/Train/scripts/open_isaacsim_gui.sh new file mode 100755 index 0000000..a12ef92 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/open_isaacsim_gui.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Launch the Isaac Sim full GUI (no task, no policy) in the project's docker. +# Use this to manually inspect USDs (e.g. drag the Go2 USD into the stage, +# expand link tree, view collision meshes). +# +# Usage: +# ./scripts/open_isaacsim_gui.sh +# +# To open the Go2 USD inside the GUI: +# 1. File -> Open -> paste the URL printed below into the file picker +# 2. Or drag it from the Content browser (left panel): +# Robots/Unitree/Go2/go2.usd +set -e + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true + +cat </Isaac/Robots/Unitree/Go2/go2.usd +or via the cloud asset path used by IsaacLab: + \$ISAACLAB_NUCLEUS_DIR/Robots/Unitree/Go2/go2.usd + +EOF + +docker run --rm --gpus all \ + -e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \ + -e DISPLAY="${DISPLAY:-:1}" \ + -e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \ + --shm-size=16g --network host --ipc host \ + --ulimit memlock=-1 --ulimit stack=67108864 \ + -v /tmp/.X11-unix:/tmp/.X11-unix:rw \ + -v "$HOME/.Xauthority:/root/.Xauthority:ro" \ + -v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \ + -v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \ + --entrypoint bash sru-nav:latest -lc \ + "/isaac-sim/isaac-sim.sh" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/play_b2w_jit.sh b/sru_ws/reference/SRU-Odin/Train/scripts/play_b2w_jit.sh new file mode 100755 index 0000000..2dae298 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/play_b2w_jit.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash +# Visualize / evaluate a TorchScript JIT navigation policy (e.g. the official +# upstream B2W baseline ``nav_policy_new.pt``) in the IsaacLab pure-maze env. +# +# Examples: +# # GUI viewer, 4 envs, paper-style classic maze +# PLAY_CLASSIC_MAZE=1 PLAY_DIFFICULTY="0.8,1.0" \ +# ./scripts/play_b2w_jit.sh --jit-policy assets/baselines/b2w_nav_policy_new.pt +# +# # Headless stats run (no GUI) +# PLAY_CLASSIC_MAZE=1 PLAY_DIFFICULTY="0.8,1.0" \ +# ./scripts/play_b2w_jit.sh \ +# --jit-policy assets/baselines/b2w_nav_policy_new.pt \ +# --headless --envs 32 --steps 2000 +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +# ---- defaults (GUI-friendly) ---- +TASK="Isaac-Nav-PPO-B2W-Play-v0" +JIT_HOST="" +NUM_ENVS=4 +STEPS=100000 # huge so the viewer just keeps running until user closes it +SEED=42 +HEADLESS=0 + +usage() { + cat <= ~1.5) + PLAY_CLASSIC_MAZE=1 paper-style uniform walls +EOF + exit 0 +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --jit-policy) JIT_HOST="$2"; shift 2 ;; + --task) TASK="$2"; shift 2 ;; + --envs) NUM_ENVS="$2"; shift 2 ;; + --steps) STEPS="$2"; shift 2 ;; + --seed) SEED="$2"; shift 2 ;; + --headless) HEADLESS=1; shift ;; + -h|--help) usage ;; + *) echo "[error] Unknown arg: $1" >&2; usage ;; + esac +done + +[[ -z "$JIT_HOST" ]] && { echo "[error] --jit-policy is required." >&2; exit 1; } +if [[ "$JIT_HOST" != /* ]]; then JIT_HOST="$REPO_ROOT/$JIT_HOST"; fi +[[ -f "$JIT_HOST" ]] || { echo "[error] JIT file not found: $JIT_HOST" >&2; exit 1; } + +JIT_CTR="/workspace/baseline_policy.pt" + +# ---- GUI plumbing (same as play_go2.sh) ---- +EXTRA_DOCKER_ARGS=() +HEADLESS_FLAG="" +if [[ "$HEADLESS" == "0" ]]; then + xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true + EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}" + -v /tmp/.X11-unix:/tmp/.X11-unix:rw + -v "$HOME/.Xauthority:/root/.Xauthority:ro") +else + HEADLESS_FLAG="--headless" +fi + +cat </model_500.pt +# +# # Headless replay (no GUI), e.g. on a server +# ./scripts/play_go2.sh --from-iter 800 --headless --envs 1 +# +# # Browse a different experiment dir (e.g. full PPO) +# ./scripts/play_go2.sh --experiment go2_navigation_ppo_ft_from_b2w --from-iter 5000 +# +# Notes: +# * --run-dir is the timestamped folder name under +# outputs/logs/rsl_rl//. +# * If neither --run-dir nor --checkpoint is given, the latest run is picked. +# * If --from-iter is omitted, the latest model_*.pt in the run dir is used. +# * The Play task disables corruption / pushes / large terrain to make the +# viewer behave well; that is decided by --task (default: Play-v0). +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +# ---- defaults ---- +TASK="Isaac-Nav-PPO-Go2-Play-v0" +EXPERIMENT="go2_navigation_ppo_dev" +NUM_ENVS=4 +FROM_ITER="" +RUN_DIR="" +CHECKPOINT="" +HEADLESS=0 +SEED=42 +EXPORT_ONNX=0 +EXPORT_JIT=0 + +usage() { + sed -n '1,30p' "$0" + echo + echo "Flags:" + echo " --from-iter N Replay model_.pt within the chosen run dir." + echo " --run-dir NAME Run dir name under outputs/logs/rsl_rl//." + echo " --checkpoint PATH Explicit IN-CONTAINER path (overrides --run-dir/--from-iter)." + echo " --task NAME Gym task id (default: $TASK)." + echo " --experiment NAME Log subdir (default: $EXPERIMENT)." + echo " --envs N Parallel envs (default: $NUM_ENVS)." + echo " --seed N Seed (default: $SEED)." + echo " --headless Run without GUI (faster, no X11)." + echo " --export-onnx Also export policy to /export/policy.onnx." + echo " --export-jit Also export policy to /export/policy.pt (TorchScript)." + echo " -h, --help Show this help." + exit 0 +} + +# ---- arg parsing ---- +while [[ $# -gt 0 ]]; do + case "$1" in + --from-iter) FROM_ITER="$2"; shift 2 ;; + --run-dir) RUN_DIR="$2"; shift 2 ;; + --checkpoint) CHECKPOINT="$2"; shift 2 ;; + --task) TASK="$2"; shift 2 ;; + --experiment) EXPERIMENT="$2"; shift 2 ;; + --envs) NUM_ENVS="$2"; shift 2 ;; + --seed) SEED="$2"; shift 2 ;; + --headless) HEADLESS=1; shift ;; + --export-onnx) EXPORT_ONNX=1; shift ;; + --export-jit) EXPORT_JIT=1; shift ;; + -h|--help) usage ;; + *) echo "[error] Unknown arg: $1" >&2; usage ;; + esac +done + +HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT" + +# ---- resolve checkpoint ---- +if [[ -z "$CHECKPOINT" ]]; then + if [[ -z "$RUN_DIR" ]]; then + RUN_DIR="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)" + [[ -z "$RUN_DIR" ]] && { echo "[error] No runs under $HOST_LOG_ROOT" >&2; exit 1; } + fi + RUN_PATH="$HOST_LOG_ROOT/$RUN_DIR" + [[ -d "$RUN_PATH" ]] || { echo "[error] Run dir not found: $RUN_PATH" >&2; exit 1; } + + if [[ -n "$FROM_ITER" ]]; then + HOST_CKPT="$RUN_PATH/model_${FROM_ITER}.pt" + if [[ ! -f "$HOST_CKPT" ]]; then + echo "[error] Checkpoint not found: $HOST_CKPT" >&2 + echo "[hint] Available iters in $RUN_DIR:" >&2 + ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null \ + | sed -nE 's/.*model_([0-9]+)\.pt/ \1/p' \ + | paste -sd ' ' >&2 + exit 1 + fi + else + HOST_CKPT="$(ls -1 "$RUN_PATH"/model_*.pt 2>/dev/null | sort -V | tail -n 1)" + [[ -z "$HOST_CKPT" ]] && { echo "[error] No model_*.pt in $RUN_PATH" >&2; exit 1; } + fi + CHECKPOINT="${HOST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}" +else + HOST_CKPT="${CHECKPOINT/\/workspace\/IsaacLab\/logs/$REPO_ROOT\/outputs\/logs}" +fi + +# ---- GUI plumbing ---- +EXTRA_DOCKER_ARGS=() +HEADLESS_FLAG="" +if [[ "$HEADLESS" == "0" ]]; then + xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true + EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}" + -v /tmp/.X11-unix:/tmp/.X11-unix:rw + -v "$HOME/.Xauthority:/root/.Xauthority:ro") +else + HEADLESS_FLAG="--headless" +fi + +cat < if none was provided. +if [[ -z "${CHECKPOINT:-}" ]]; then + HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/$EXPERIMENT" + LATEST_RUN="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)" + if [[ -z "$LATEST_RUN" ]]; then + echo "[error] No runs found under $HOST_LOG_ROOT and no CHECKPOINT given." >&2 + exit 1 + fi + LATEST_CKPT="$(ls -1 "$HOST_LOG_ROOT/$LATEST_RUN"/model_*.pt 2>/dev/null | sort -V | tail -n 1)" + if [[ -z "$LATEST_CKPT" ]]; then + echo "[error] No model_*.pt found in $HOST_LOG_ROOT/$LATEST_RUN" >&2 + exit 1 + fi + # Map host path -> in-container path. + CHECKPOINT="${LATEST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}" +fi + +xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true + +echo "[host] DISPLAY=${DISPLAY:-:1}" +echo "[host] task=$TASK num_envs=$NUM_ENVS" +echo "[host] checkpoint (in container) = $CHECKPOINT" + +docker run --rm --gpus all \ + -e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \ + -e DISPLAY="${DISPLAY:-:1}" \ + -e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \ + -e PLAY_DIFFICULTY="${PLAY_DIFFICULTY:-}" \ + -e PLAY_CELL_SIZE="${PLAY_CELL_SIZE:-}" \ + -e PLAY_MAZE_ONLY="${PLAY_MAZE_ONLY:-}" \ + -e PLAY_CLASSIC_MAZE="${PLAY_CLASSIC_MAZE:-}" \ + -e PLAY_SUBTERRAIN_MIX="${PLAY_SUBTERRAIN_MIX:-}" \ + --shm-size=16g --network host --ipc host \ + --ulimit memlock=-1 --ulimit stack=67108864 \ + -v /tmp/.X11-unix:/tmp/.X11-unix:rw \ + -v "$HOME/.Xauthority:/root/.Xauthority:ro" \ + -v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \ + -v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \ + -v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \ + --entrypoint bash sru-nav:latest -lc \ + "./isaaclab.sh -p source/isaaclab_nav_task/scripts/play.py \ + --task $TASK \ + --num_envs $NUM_ENVS \ + --checkpoint $CHECKPOINT" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/probe_pt.py b/sru_ws/reference/SRU-Odin/Train/scripts/probe_pt.py new file mode 100644 index 0000000..7022882 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/probe_pt.py @@ -0,0 +1,224 @@ +"""Diagnose a TorchScript locomotion .pt file's interface. + +Run inside the sru-nav container; mount this script at /tmp/probe_pt.py. + +Reports: + 1. TorchScript graph code (top-level forward signature) + 2. State-dict key names + shapes (gives clues about layer order / obs slicing) + 3. Tries common observation dimensions to find the input width + 4. Output dimension (= number of joint targets the policy emits) + 5. A quick "what zero input produces" check (sanity for output range) +""" + +import os +import sys +import torch + +DEFAULT_PT = ( + "/workspace/IsaacLab/source/isaaclab_nav_task/isaaclab_nav_task/" + "navigation/assets/data/Policies/locomotion/go2/policy_go2.pt" +) +PT_PATH = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_PT + +assert os.path.isfile(PT_PATH), f"File not found: {PT_PATH}" +print(f"[probe] loading: {PT_PATH}") +print(f"[probe] file size: {os.path.getsize(PT_PATH) / 1e6:.2f} MB") + +device = "cuda" if torch.cuda.is_available() else "cpu" +print(f"[probe] device: {device}") + +is_torchscript = False +model = None +raw_obj = None +try: + model = torch.jit.load(PT_PATH, map_location=device) + model.eval() + is_torchscript = True + print(f"[probe] format: TorchScript ✓") + print(f"[probe] type: {type(model).__name__}") +except Exception as e: + print(f"[probe] torch.jit.load FAILED: {str(e).splitlines()[0][:120]}") + print(f"[probe] → falling back to torch.load() (pickle)") + try: + raw_obj = torch.load(PT_PATH, map_location=device, weights_only=False) + print(f"[probe] format: pickle (torch.save) — NOT TorchScript") + print(f"[probe] top-level type: {type(raw_obj).__name__}") + except Exception as e2: + print(f"[probe] torch.load ALSO failed: {e2}") + sys.exit(1) + +if not is_torchscript: + print("\n=========================================================") + print(" ⚠ This file is NOT a TorchScript model.") + print(" sru-navigation-sim calls `torch.jit.load(.pt)` which will fail.") + print(" You need to either:") + print(" (a) Re-export your policy with torch.jit.script(model).save(...)") + print(" (b) Provide the original nn.Module class so we wrap+script it") + print("=========================================================\n") + + # Inspect the loaded object + print("=========================================================") + print(" Contents of torch.load() output") + print("=========================================================") + if isinstance(raw_obj, dict): + print(f" dict with {len(raw_obj)} top-level keys:") + for k, v in raw_obj.items(): + t = type(v).__name__ + extra = "" + if isinstance(v, torch.Tensor): + extra = f" shape={tuple(v.shape)} dtype={v.dtype}" + elif isinstance(v, dict): + extra = f" ({len(v)} sub-keys)" + print(f" [{k!r}] {t}{extra}") + # If it has 'model_state_dict' or 'state_dict' or is itself a state_dict, dump shapes + sd = None + for key in ["model_state_dict", "state_dict", "model", "policy"]: + if key in raw_obj and isinstance(raw_obj[key], dict): + sd = raw_obj[key] + print(f"\n → Found state-dict under key {key!r}") + break + if sd is None and all(isinstance(v, torch.Tensor) for v in raw_obj.values()): + sd = raw_obj + print(f"\n → Top-level dict appears to be a state_dict itself") + if sd is not None: + print(f"\n State-dict keys & shapes ({len(sd)} entries):") + for i, (k, v) in enumerate(sd.items()): + shape = tuple(v.shape) if isinstance(v, torch.Tensor) else type(v).__name__ + print(f" [{i:2d}] {k:60s} {shape}") + if i >= 50: + print(f" ... ({len(sd) - 51} more)") + break + # First Linear's in_features + first_linear_in = None + for k, v in sd.items(): + if isinstance(v, torch.Tensor) and v.ndim == 2 and "weight" in k.lower(): + first_linear_in = v.shape[1] + print(f"\n → first 2D-weight key {k!r} has in_features = {first_linear_in}") + print(f" most likely D_obs = {first_linear_in}") + break + # Last Linear's out_features + last_linear_out = None + last_linear_key = None + for k, v in sd.items(): + if isinstance(v, torch.Tensor) and v.ndim == 2 and "weight" in k.lower(): + last_linear_out = v.shape[0] + last_linear_key = k + if last_linear_out is not None: + print(f" → last 2D-weight key {last_linear_key!r} has out_features = {last_linear_out}") + print(f" most likely action_dim = {last_linear_out}") + elif isinstance(raw_obj, torch.nn.Module): + print(f" → It's a raw nn.Module instance (untraced). Class: {type(raw_obj).__name__}") + print(f" → We can try to forward it directly without TorchScript.") + model = raw_obj + model.eval() + is_torchscript = False + else: + print(f" (unsupported type: {type(raw_obj)})") + print("\n[probe] done — see message above for next steps.") + sys.exit(0) + +print("\n=========================================================") +print("1. TorchScript .code (forward signature & top-level graph)") +print("=========================================================") +try: + code = getattr(model, "code", None) + if code is None: + print("(no .code attribute -- model may be a ScriptFunction)") + else: + print(code[:4000]) +except Exception as e: + print(f"(error reading .code: {e})") + +print("\n=========================================================") +print("2. State dict keys & shapes") +print("=========================================================") +sd = model.state_dict() +print(f"total params: {sum(v.numel() for v in sd.values()):,}") +for i, (k, v) in enumerate(sd.items()): + print(f" [{i:2d}] {k:60s} {tuple(v.shape)}") + if i >= 40: + print(f" ... ({len(sd) - 41} more)") + break + +# First Linear layer's input dim is a strong hint for D_obs +first_weight = next( + (v for k, v in sd.items() if v.ndim == 2 and ("weight" in k or k.endswith(".weight"))), + None, +) +hint_obs = first_weight.shape[1] if first_weight is not None else None +if hint_obs is not None: + print(f"\n[probe] first Linear weight has in_features = {hint_obs}") + print(f" → most likely D_obs = {hint_obs}") + +print("\n=========================================================") +print("3. Trying input dimensions (looking for the one that works)") +print("=========================================================") +# Common Go2 obs dims: +# 33 = 3+3+3+3+12+12 (no last_action) +# 45 = 3+3+3+3+12+12+12 (with last_action of joint dim) +# 48 = 3+3+3+3+12+12+12+3 (with last_action including vel cmd) +# 52 = 3+3+3+3+12+12+16 (sru-nav-sim LowLevelPolicyCfg, with B2W-style last_action=16) +# 60 = 3+3+3+3+12+12+12+12 (joint pos+vel+pos+vel duplicated) +# 235 = with height_scan (legged_gym style) +candidate_dims = [33, 36, 39, 42, 45, 48, 51, 52, 60, 96, 235] +if hint_obs is not None and hint_obs not in candidate_dims: + candidate_dims.insert(0, hint_obs) + +working_dims = [] +for d in candidate_dims: + try: + with torch.inference_mode(): + out = model(torch.zeros(2, d, device=device)) + if isinstance(out, tuple): + shapes = [tuple(o.shape) for o in out if isinstance(o, torch.Tensor)] + print(f" D_obs = {d:3d} ✓ (tuple output, shapes={shapes})") + else: + print(f" D_obs = {d:3d} ✓ output shape = {tuple(out.shape)}") + working_dims.append((d, tuple(out.shape))) + except Exception as e: + msg = str(e).split("\n")[0][:90] + print(f" D_obs = {d:3d} ✗ {msg}") + +print("\n=========================================================") +print("4. Summary") +print("=========================================================") +if not working_dims: + print(" ⚠ NO standard input dim worked.") + print(" → Inspect step-2 first-Linear in_features and try that exact size.") + print(f" → Expected: D_obs = {hint_obs}") +else: + for d, out_shape in working_dims: + n_out = out_shape[1] if len(out_shape) >= 2 else None + print(f" D_obs = {d}, output_dim = {n_out}") + if n_out == 12: + print(" → 12 outputs = pure leg joint targets (Go2 has 12 leg joints).") + print(" You'll use `low_level_velocity_action = None` (the patched action term).") + elif n_out == 16: + print(" → 16 outputs matches B2W layout (12 legs + 4 wheels).") + print(" Adapter must zero-pad if your Go2 only emits 12.") + elif n_out == 18: + print(" → 18 outputs = 12 legs + something extra (maybe 6 dummy?).") + else: + print(f" → {n_out} outputs is unusual; verify against your training task.") + +print("\n=========================================================") +print("5. Probing zero-input output magnitude (sanity)") +print("=========================================================") +if working_dims: + d, _ = working_dims[0] + with torch.inference_mode(): + out = model(torch.zeros(1, d, device=device)) + if isinstance(out, torch.Tensor): + print(f" output[0] (first 12 dims): " + f"{out[0, :12].cpu().numpy().round(3).tolist()}") + print(f" output stats: mean={out.mean().item():.3f}, " + f"std={out.std().item():.3f}, " + f"min={out.min().item():.3f}, max={out.max().item():.3f}") + if out.abs().max() > 5.0: + print(" ⚠ Output magnitude > 5; policy likely emits raw joint angles or torques.") + print(" Standard IsaacLab convention: tanh-bounded ∈ [-1, 1].") + elif out.abs().max() < 0.05: + print(" ⚠ Output extremely small; may be a state_dict-only file (not a working policy).") + else: + print(" ✓ Output magnitude looks reasonable.") +print("\n[probe] done") diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/probe_pt.sh b/sru_ws/reference/SRU-Odin/Train/scripts/probe_pt.sh new file mode 100755 index 0000000..53cf2cd --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/probe_pt.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Run probe_pt.py inside the sru-nav container against the Go2 locomotion .pt. +# Usage: +# ./scripts/probe_pt.sh # uses default path under mount/ +# ./scripts/probe_pt.sh /custom/path/in/host # absolute host path +set -e + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +HOST_PT="${1:-$REPO_ROOT/mount/sru-navigation-sim/isaaclab_nav_task/navigation/assets/data/Policies/locomotion/go2/policy_go2.pt}" + +if [[ ! -f "$HOST_PT" ]]; then + echo "ERROR: .pt not found at: $HOST_PT" + echo " Copy your Go2 locomotion .pt there first." + exit 1 +fi + +echo "[host] probing: $HOST_PT" +echo "[host] file size: $(du -h "$HOST_PT" | cut -f1)" + +# Translate the host path to the corresponding container path (the mount). +HOST_NAV_SIM="$REPO_ROOT/mount/sru-navigation-sim" +CONTAINER_NAV_SIM="/workspace/IsaacLab/source/isaaclab_nav_task" +if [[ "$HOST_PT" == "$HOST_NAV_SIM"/* ]]; then + CONTAINER_PT="${HOST_PT/$HOST_NAV_SIM/$CONTAINER_NAV_SIM}" +else + echo "ERROR: .pt must live under $HOST_NAV_SIM (the live-mounted folder)." + echo " Got: $HOST_PT" + exit 1 +fi +echo "[host] container path: $CONTAINER_PT" + +docker run --rm --gpus all \ + -e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \ + --shm-size=4g --ipc host \ + -v "$REPO_ROOT/scripts/probe_pt.py:/tmp/probe_pt.py:ro" \ + -v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \ + --entrypoint bash sru-nav:latest -lc \ + "/workspace/IsaacLab/_isaac_sim/python.sh /tmp/probe_pt.py '$CONTAINER_PT'" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/train_aow_d_mdpo.sh b/sru_ws/reference/SRU-Odin/Train/scripts/train_aow_d_mdpo.sh new file mode 100755 index 0000000..5209a7f --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/train_aow_d_mdpo.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -e +cd /workspace/IsaacLab +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task Isaac-Nav-MDPO-AoW-D-v0 \ + --num_envs ${NUM_ENVS:-2048} \ + --max_iterations ${MAX_ITERS:-10000} \ + --headless \ + "$@" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/train_b2w_dev.sh b/sru_ws/reference/SRU-Odin/Train/scripts/train_b2w_dev.sh new file mode 100755 index 0000000..4da1426 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/train_b2w_dev.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Quick dev/smoke-test (300 iters, tensorboard). +set -e +cd /workspace/IsaacLab +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task Isaac-Nav-PPO-B2W-Dev-v0 \ + --num_envs ${NUM_ENVS:-32} \ + --headless \ + "$@" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/train_b2w_ppo.sh b/sru_ws/reference/SRU-Odin/Train/scripts/train_b2w_ppo.sh new file mode 100755 index 0000000..dd4b1bd --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/train_b2w_ppo.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# Run inside the container. +set -e +cd /workspace/IsaacLab +./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task Isaac-Nav-PPO-B2W-v0 \ + --num_envs ${NUM_ENVS:-4096} \ + --headless \ + "$@" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/train_go2_continue.sh b/sru_ws/reference/SRU-Odin/Train/scripts/train_go2_continue.sh new file mode 100755 index 0000000..68a29d8 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/train_go2_continue.sh @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# Continue training the Go2 SRU navigation policy from the latest dev checkpoint. +# +# Defaults: headless (no GUI for speed), Dev task (same cfg as the previous +# 33-iter run), warm-start with optimizer state so PPO truly resumes. +# +# Usage: +# ./scripts/train_go2_continue.sh # 1000 iter, 24 envs +# NUM_ENVS=32 MAX_ITER=2000 ./scripts/train_go2_continue.sh +# CHECKPOINT=/workspace/IsaacLab/logs/.../model_33.pt ./scripts/train_go2_continue.sh +# GUI=1 ./scripts/train_go2_continue.sh # show Isaac Sim GUI +# TASK=Isaac-Nav-PPO-Go2-v0 ./scripts/train_go2_continue.sh # full PPO task (5000 iter cap) +# +# Notes: +# * CHECKPOINT must be the IN-CONTAINER path under /workspace/IsaacLab/logs/... +# * --load_optimizer keeps PPO momentum / adaptive-LR state, so loss curves +# look continuous instead of restarting cold. +# * RTX 5070 has 12 GB VRAM. 24 envs headless is conservative; tune up if free. +set -e + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +NUM_ENVS="${NUM_ENVS:-24}" +MAX_ITER="${MAX_ITER:-1000}" +TASK="${TASK:-Isaac-Nav-PPO-Go2-Dev-v0}" +GUI="${GUI:-0}" +SEED="${SEED:-42}" +RUN_NAME="${RUN_NAME:-resume_from_33}" + +# Auto-pick the latest dev checkpoint if none provided. +if [[ -z "${CHECKPOINT:-}" ]]; then + HOST_LOG_ROOT="$REPO_ROOT/outputs/logs/rsl_rl/go2_navigation_ppo_dev" + LATEST_RUN="$(ls -1 "$HOST_LOG_ROOT" 2>/dev/null | sort | tail -n 1 || true)" + if [[ -z "$LATEST_RUN" ]]; then + echo "[error] No previous runs under $HOST_LOG_ROOT and no CHECKPOINT given." >&2 + exit 1 + fi + LATEST_CKPT="$(ls -1 "$HOST_LOG_ROOT/$LATEST_RUN"/model_*.pt 2>/dev/null | sort -V | tail -n 1)" + if [[ -z "$LATEST_CKPT" ]]; then + echo "[error] No model_*.pt found in $HOST_LOG_ROOT/$LATEST_RUN" >&2 + exit 1 + fi + CHECKPOINT="${LATEST_CKPT/$REPO_ROOT\/outputs\/logs/\/workspace\/IsaacLab\/logs}" +fi + +HEADLESS_FLAG="--headless" +EXTRA_DOCKER_ARGS=() +if [[ "$GUI" == "1" ]]; then + HEADLESS_FLAG="" + xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true + EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}" + -v /tmp/.X11-unix:/tmp/.X11-unix:rw + -v "$HOME/.Xauthority:/root/.Xauthority:ro") +fi + +echo "[host] task=$TASK num_envs=$NUM_ENVS max_iter=$MAX_ITER gui=$GUI" +echo "[host] checkpoint (in container) = $CHECKPOINT" +echo "[host] run_name=$RUN_NAME seed=$SEED" + +docker run --rm --gpus all \ + -e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \ + -e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \ + --shm-size=16g --network host --ipc host \ + --ulimit memlock=-1 --ulimit stack=67108864 \ + "${EXTRA_DOCKER_ARGS[@]}" \ + -v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \ + -v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \ + -v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \ + --entrypoint bash sru-nav:latest -lc \ + "./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task $TASK \ + --num_envs $NUM_ENVS \ + --max_iterations $MAX_ITER \ + --seed $SEED \ + --run_name $RUN_NAME \ + --checkpoint $CHECKPOINT \ + --load_optimizer \ + $HEADLESS_FLAG" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/train_go2_gui.sh b/sru_ws/reference/SRU-Odin/Train/scripts/train_go2_gui.sh new file mode 100755 index 0000000..0f8fed7 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/train_go2_gui.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Train Go2 nav with the Isaac Sim GUI visible (X11 forwarded from host). +# Default: 30 iterations, small env count, so you can watch the dogs walking. +# +# Usage: +# ./scripts/train_go2_gui.sh # 30 iter, 32 envs, GUI +# NUM_ENVS=16 MAX_ITER=100 ./scripts/train_go2_gui.sh +# +set -e + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +NUM_ENVS="${NUM_ENVS:-32}" +MAX_ITER="${MAX_ITER:-30}" +TASK="${TASK:-Isaac-Nav-PPO-Go2-Dev-v0}" + +# Allow the docker user (any UID) to talk to the host X server. +# This affects only the local user's X server. +xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true + +echo "[host] DISPLAY=${DISPLAY:-:1}" +echo "[host] task=$TASK num_envs=$NUM_ENVS max_iterations=$MAX_ITER" + +docker run --rm --gpus all \ + -e ACCEPT_EULA=Y -e PRIVACY_CONSENT=Y \ + -e DISPLAY="${DISPLAY:-:1}" \ + -e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \ + --shm-size=16g --network host --ipc host \ + --ulimit memlock=-1 --ulimit stack=67108864 \ + -v /tmp/.X11-unix:/tmp/.X11-unix:rw \ + -v "$HOME/.Xauthority:/root/.Xauthority:ro" \ + -v "$REPO_ROOT/outputs/logs:/workspace/IsaacLab/logs" \ + -v "$REPO_ROOT/mount/sru-navigation-sim:/workspace/IsaacLab/source/isaaclab_nav_task" \ + -v "$REPO_ROOT/mount/rsl_rl:/workspace/rsl_rl" \ + --entrypoint bash sru-nav:latest -lc \ + "./isaaclab.sh -p source/isaaclab_nav_task/scripts/train.py \ + --task $TASK \ + --num_envs $NUM_ENVS \ + --max_iterations $MAX_ITER" diff --git a/sru_ws/reference/SRU-Odin/Train/scripts/train_go2_scratch.sh b/sru_ws/reference/SRU-Odin/Train/scripts/train_go2_scratch.sh new file mode 100755 index 0000000..5761249 --- /dev/null +++ b/sru_ws/reference/SRU-Odin/Train/scripts/train_go2_scratch.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# Train the Go2 SRU navigation policy FROM SCRATCH (no checkpoint). +# +# Defaults: headless, 24 envs, 1000 iter, Dev task, seed=42. +# Use this when you intentionally want a cold start (e.g. after sweeping +# reward / action / terrain shaping where the previous policy mean has +# collapsed into a degenerate solution and resuming would just re-learn it). +# +# Usage: +# ./scripts/train_go2_scratch.sh # 1000 iter, 24 envs, headless +# NUM_ENVS=16 MAX_ITER=500 ./scripts/train_go2_scratch.sh +# GUI=1 NUM_ENVS=4 MAX_ITER=200 ./scripts/train_go2_scratch.sh +# TASK=Isaac-Nav-PPO-Go2-v0 RUN_NAME=scratch_full ./scripts/train_go2_scratch.sh +# +# Notes: +# * No --checkpoint flag is passed, so the agent + critic are re-initialised. +# * RTX 5070 (12 GB VRAM): 24 envs headless is the safe default. GUI + 32 +# envs OOMs (G0.0 lesson). +# * Output goes to outputs/logs/rsl_rl//_/. +set -e + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +NUM_ENVS="${NUM_ENVS:-24}" +MAX_ITER="${MAX_ITER:-1000}" +TASK="${TASK:-Isaac-Nav-PPO-Go2-Dev-v0}" +GUI="${GUI:-0}" +SEED="${SEED:-42}" +RUN_NAME="${RUN_NAME:-scratch_reward_fix_v1}" +# GPU selection. Set GPU=0 / GPU=1 / GPU=0,1 to pin specific cards. +# Empty (default) = all visible GPUs (--gpus all). The container sees the selected +# GPU(s) as cuda:0,cuda:1,... so the training process always uses cuda:0 inside. +GPU="${GPU:-}" + +GPU_FLAG="--gpus all" +if [[ -n "$GPU" ]]; then + GPU_FLAG="--gpus device=${GPU}" +fi + +HEADLESS_FLAG="--headless" +EXTRA_DOCKER_ARGS=() +if [[ "$GUI" == "1" ]]; then + HEADLESS_FLAG="" + xhost +local:root >/dev/null 2>&1 || xhost +local:docker >/dev/null 2>&1 || true + EXTRA_DOCKER_ARGS+=(-e "DISPLAY=${DISPLAY:-:1}" + -v /tmp/.X11-unix:/tmp/.X11-unix:rw + -v "$HOME/.Xauthority:/root/.Xauthority:ro") +fi + +cat < expect: stays upright, ~0 velocity + 2. Forward walk (0.5, 0.0, 0.0) -> expect: moves +X, vx ~ 0.3 m/s + 3. Backward walk (-0.5, 0.0, 0.0) -> expect: moves -X, vx ~ -0.3 m/s + 4. Lateral right (0.0, 0.5, 0.0) -> expect: moves +Y (limited) + 5. Rotate (yaw) (0.0, 0.0, 0.5) -> expect: omega ~ 0.35 rad/s + +Run: + ./isaaclab.sh -p /tmp/validate_go2_locomotion.py --num_envs 4 --headless +""" + +from __future__ import annotations + +import argparse + +from isaaclab.app import AppLauncher + +parser = argparse.ArgumentParser() +parser.add_argument("--task", default="Isaac-Nav-PPO-Go2-Dev-v0") +parser.add_argument("--num_envs", type=int, default=4) +parser.add_argument("--phase_seconds", type=float, default=3.0) +AppLauncher.add_app_launcher_args(parser) +args = parser.parse_args() +args.headless = True +args.enable_cameras = True # depth camera obs needed by env + +app_launcher = AppLauncher(args) +simulation_app = app_launcher.app + +import torch # noqa: E402 +import gymnasium as gym # noqa: E402 + +import isaaclab_nav_task # noqa: F401, E402 +from isaaclab_tasks.utils.parse_cfg import parse_env_cfg # noqa: E402 + + +def main(): + env_cfg = parse_env_cfg( + args.task, device="cuda:0", num_envs=args.num_envs, use_fabric=True + ) + env = gym.make(args.task, cfg=env_cfg) + print(f"[validate] action_space = {env.action_space}") + print(f"[validate] observation_space (policy group) = " + f"{env.observation_space['policy'].shape}") + + obs, _ = env.reset() + device = env.unwrapped.device + + # Phase definitions: (label, command, num_steps) + # The env decimation is 4 (low-level @ 50 Hz), and the high-level step is + # called at 10 Hz (env.step). So phase_seconds * 10 = num steps. + phase_steps = int(args.phase_seconds * 10) + phases = [ + ("stand_still", torch.tensor([ 0.0, 0.0, 0.0])), + ("forward", torch.tensor([ 0.7, 0.0, 0.0])), + ("backward", torch.tensor([-0.7, 0.0, 0.0])), + ("lateral_right", torch.tensor([ 0.0, 0.7, 0.0])), + ("yaw_rotate", torch.tensor([ 0.0, 0.0, 0.7])), + ] + + # Probe sensors + robot = env.unwrapped.scene["robot"] + + print("\n" + "=" * 78) + print(f"{'phase':<16} {'cmd (vx,vy,ω)':<22} " + f"{'measured (vx,vy,ω)':<22} " + f"{'h(m)':>6} {'pitch':>7} {'falls':>6}") + print("=" * 78) + + fails = [] + for label, cmd in phases: + # Fresh reset per phase so prior falls / terrain placement don't bias + # the next phase's height measurement. + env.reset() + cmd_batch = cmd.to(device).unsqueeze(0).expand(args.num_envs, -1).contiguous() + # Reset stats for this phase + v_lin_sum = torch.zeros(3, device=device) + omega_sum = torch.zeros(1, device=device) + height_sum = torch.zeros(1, device=device) + pitch_max = 0.0 + n_steps = 0 + falls = 0 + + for _ in range(phase_steps): + obs, _, terminated, truncated, _ = env.step(cmd_batch) + n_steps += 1 + base_lin_vel = robot.data.root_lin_vel_b # body frame, (N, 3) + base_ang_vel = robot.data.root_ang_vel_b + root_pos = robot.data.root_pos_w # (N, 3) + grav_b = robot.data.projected_gravity_b # (N, 3) + v_lin_sum += base_lin_vel.mean(dim=0) + omega_sum += base_ang_vel[:, 2].mean().unsqueeze(0) + height_sum += root_pos[:, 2].mean().unsqueeze(0) + # pitch = angle between projected_gravity_b and (-Z body) = (0,0,-1) + pitch_now = ( + torch.acos(torch.clamp(-grav_b[:, 2], -1.0, 1.0)) + .max().item() + ) + pitch_max = max(pitch_max, pitch_now) + falls += int(terminated.any().item() or truncated.any().item()) + + v_lin = (v_lin_sum / n_steps).cpu().numpy().round(3).tolist() + omega = (omega_sum / n_steps).item() + h_avg = (height_sum / n_steps).item() + + # Height threshold uses world-frame Z; the rough terrain in the dev env + # can place the robot on top of features up to ~0.25 m, so allow up + # to 0.65 m total for a healthy Go2 body (~0.40 m default standing). + ok_height = 0.20 < h_avg < 0.70 + ok_pitch = pitch_max < 0.6 + ok_overall = ok_height and ok_pitch + flag = "✓" if ok_overall else "✗" + + cmd_str = f"({cmd[0]:+.1f},{cmd[1]:+.1f},{cmd[2]:+.1f})" + meas_str = f"({v_lin[0]:+.2f},{v_lin[1]:+.2f},{omega:+.2f})" + print(f"{flag} {label:<14} {cmd_str:<22} {meas_str:<22} " + f"{h_avg:>6.3f} {pitch_max:>6.2f}r {falls:>6d}") + + # Per-phase pass criteria + if label == "stand_still": + if abs(v_lin[0]) > 0.15 or abs(v_lin[1]) > 0.15: + fails.append(f"{label}: drifting at zero command " + f"(v_lin={v_lin})") + elif label == "forward": + if v_lin[0] < 0.10: + fails.append(f"{label}: not moving forward " + f"(vx={v_lin[0]:.2f})") + elif label == "backward": + if v_lin[0] > -0.10: + fails.append(f"{label}: not moving backward " + f"(vx={v_lin[0]:.2f})") + elif label == "yaw_rotate": + if abs(omega) < 0.10: + fails.append(f"{label}: not rotating (ω={omega:.2f})") + + if not ok_height: + fails.append(f"{label}: body too low/high (h={h_avg:.2f})") + if not ok_pitch: + fails.append(f"{label}: tilted over (max pitch={pitch_max:.2f} rad)") + + print("=" * 78) + if fails: + print("\n⚠ FAILED CHECKS:") + for f in fails: + print(f" - {f}") + print("\nLikely causes:") + print(" • Action scale mismatch (training used different scale)") + print(" • Joint order mismatch between policy output and IsaacLab USD") + print(" • Observation order mismatch") + else: + print("\n✅ ALL LOCOMOTION CHECKS PASSED") + print(" Go2 stands, walks forward/back, and rotates as commanded.") + print(" Locomotion contract with sru-navigation-sim is correct.") + + env.close() + simulation_app.close() + + +if __name__ == "__main__": + main() diff --git a/sru_ws/src/odin_ros_driver/.gitignore b/sru_ws/src/odin_ros_driver/.gitignore new file mode 100644 index 0000000..5829d8f --- /dev/null +++ b/sru_ws/src/odin_ros_driver/.gitignore @@ -0,0 +1,4 @@ +recorddata/ +/config/calib.yaml +/log +/map \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/CHANGELOG.md b/sru_ws/src/odin_ros_driver/CHANGELOG.md new file mode 100644 index 0000000..c1a5fa9 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/CHANGELOG.md @@ -0,0 +1,38 @@ +0.14.4 2260910 +1.modify lidar_api_type.h RGB comments +2.update sdk to fix signal printf backtrace + +0.14.3 20260903 +1.Fix crash problem + +0.14.2 20260825 +1. Add RGB DTOF filter +2. Fix USB disconnect deadlock issue +3. Add RGB parameter configuration +4. Add save_map, reset_algo, get_device_logs service + +0.14.1 20260809 +1. Fixed the SDK's USB memory leak issue +2. Fixed the problem of 'transfer no mem' caused by USB buffer full during machine transfer + +0.13.1 20260724 +1.modify frame_id for image topic +2.fix tf transform fail in ROS2 Jazzy +3.Fix the issue where the driver's initial configuration could not read the calibration file + +0.13.0 20260709 +1.add large file transfer + +v0.11.0 2026_0618 +Required Minimum Firmware Version:0.12.0 +1.Reduce cloud slam latency +2.Improve get mapping result + +v0.10.5 2026_0525 +1.modify recorddata format,add device_id、algorithm_version key +2.fix download map fail when in slam mode(USB2.0) +3.fix upload map fail when in relocalization mode(USB2.0) + +v0.10.4 2026_0522 +1.fix usb2.0 heartBeat timeout to cause soft detaching +2.add custom_init_pose_search_radius and custom_init_pose_max_rot_deg in control_command.yaml \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/CMakeLists.txt b/sru_ws/src/odin_ros_driver/CMakeLists.txt new file mode 100644 index 0000000..af916a0 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/CMakeLists.txt @@ -0,0 +1,508 @@ +cmake_minimum_required(VERSION 3.5) +project(odin_ros_driver) + + +if(DEFINED BUILD_SYSTEM) + set(ROS_VERSION ${BUILD_SYSTEM}) + message(STATUS "ROS_VERSION: ${ROS_VERSION}") +elseif(DEFINED ENV{ROS_DISTRO}) + if("$ENV{ROS_DISTRO}" MATCHES "foxy|galactic|humble|iron|rolling") + set(ROS_VERSION "ROS2") + else() + set(ROS_VERSION "ROS1") + endif() +elseif(DEFINED ENV{ROS_VERSION}) + if("$ENV{ROS_VERSION}" EQUAL "2") + set(ROS_VERSION "ROS2") + else() + set(ROS_VERSION "ROS1") + endif() +else() + # Attempt automatic detection + if(COMMAND catkin_package) + set(ROS_VERSION "ROS1") + elseif(COMMAND ament_package) + set(ROS_VERSION "ROS2") + else() + # Default to ROS2 + set(ROS_VERSION "ROS2") + message(WARNING "Unable to determine ROS version, defaulting to ROS2") + endif() +endif() + +# Add compile definitions after detecting ROS version +if(ROS_VERSION STREQUAL "ROS2") + add_definitions(-DROS2) + message(STATUS "Defining ROS2") +else() + add_definitions(-DROS1) + message(STATUS "Defining ROS1") +endif() + +message(STATUS "Build system: ${ROS_VERSION}") + +# Platform detection +execute_process( + COMMAND uname -m + OUTPUT_VARIABLE ARCH + OUTPUT_STRIP_TRAILING_WHITESPACE +) + +if(ARCH STREQUAL "x86_64") + set(TARGET_PLATFORM "x86") + message(STATUS "Detected x86_64 architecture") +elseif(ARCH MATCHES "arm|aarch64") + set(TARGET_PLATFORM "arm") + message(STATUS "Detected ARM architecture: ${ARCH}") +else() + message(WARNING "Unsupported architecture: ${ARCH}. Using default settings") + set(TARGET_PLATFORM "unknown") +endif() + +# Set library path +set(LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/lib") +message(STATUS "Library directory: ${LIB_DIR}") + +# Set library name based on platform +if(TARGET_PLATFORM STREQUAL "arm") + set(LYD_HOST_API_LIB_NAME "lydHostApi_arm") +else() + set(LYD_HOST_API_LIB_NAME "lydHostApi_amd") +endif() + +# Find precompiled lydHostApi library +find_library(LYD_HOST_API_LIB + NAMES + ${LYD_HOST_API_LIB_NAME} + lib${LYD_HOST_API_LIB_NAME}.a + lib${LYD_HOST_API_LIB_NAME}.so + PATHS ${LIB_DIR} + NO_DEFAULT_PATH +) + +if(LYD_HOST_API_LIB) + message(STATUS "Found lydHostApi library: ${LYD_HOST_API_LIB}") +else() + file(GLOB LIB_FILES "${LIB_DIR}/lib${LYD_HOST_API_LIB_NAME}.*") + if(LIB_FILES) + message(STATUS "Found library files: ${LIB_FILES}") + set(LYD_HOST_API_LIB ${LIB_FILES}) + else() + message(FATAL_ERROR "Could not find precompiled lydHostApi library in ${LIB_DIR}") + endif() +endif() + +# Set common compile options +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Set optimization flags +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O2") + +# Symbolization support for the SDK crash handler. +# -g keeps DWARF info so addr2line can report file/line, the frame-pointer and +# unwind-table flags keep the stack walkable, and CMAKE_ENABLE_EXPORTS adds +# -rdynamic so symbols pulled in from the static SDK archive land in .dynsym +# and become visible to dladdr()/backtrace_symbols() at runtime. +option(ODIN_ENABLE_BACKTRACE "Keep symbols and frame pointers for crash backtraces" ON) +if(ODIN_ENABLE_BACKTRACE) + set(BACKTRACE_FLAGS "-g -fno-omit-frame-pointer -funwind-tables -fasynchronous-unwind-tables") + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${BACKTRACE_FLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${BACKTRACE_FLAGS}") + set(CMAKE_ENABLE_EXPORTS ON) + message(STATUS "Backtrace symbols enabled (-g, frame pointers, -rdynamic)") +endif() + +# Find common dependencies +find_package(PkgConfig REQUIRED) +find_package(OpenCV REQUIRED) +find_package(Eigen3 REQUIRED) +find_package(PCL REQUIRED) +find_package(yaml-cpp REQUIRED) +find_package(OpenSSL REQUIRED) +pkg_check_modules(LIBUSB REQUIRED libusb-1.0) + +# Shared include directories +include_directories( + include + ${EIGEN3_INCLUDE_DIRS} + ${OpenCV_INCLUDE_DIRS} + ${PCL_INCLUDE_DIRS} + ${yaml-cpp_INCLUDE_DIR} + ${LIBUSB_INCLUDE_DIRS} + ${CMAKE_CURRENT_SOURCE_DIR}/include +) + +# Shared library list +set(COMMON_LIBS + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ${yaml-cpp_LIBRARIES} + ${OPENSSL_LIBRARIES} + ${LIBUSB_LIBRARIES} + pthread + rt + ${CMAKE_DL_LIBS} + ${LYD_HOST_API_LIB} +) + +# ===== ROS1 Configuration ===== +if(ROS_VERSION STREQUAL "ROS1") + message(STATUS "Configuring for ROS1 build") + + find_package(catkin REQUIRED COMPONENTS + roscpp + std_msgs + sensor_msgs + nav_msgs + cv_bridge + tf + image_transport + message_generation + ) + + # ---- AE/AWB debug services ---- + # Declare custom .srv files; catkin generates ros1 message headers for them. + add_service_files( + FILES + GetAe.srv + GetAwb.srv + SetAe.srv + SetAwb.srv + GetDeviceLogs.srv + SaveMap.srv + ResetAlgo.srv + ) + generate_messages( + DEPENDENCIES + std_msgs + ) + + include_directories(${catkin_INCLUDE_DIRS}) + + catkin_package( + CATKIN_DEPENDS roscpp std_msgs sensor_msgs nav_msgs cv_bridge image_transport message_runtime + INCLUDE_DIRS include + ) + + # Set output directories + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/lib/${PROJECT_NAME}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/lib) + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CATKIN_DEVEL_PREFIX}/lib) + + add_executable(host_sdk_sample + src/host_sdk_sample.cpp + src/yaml_parser.cpp + src/rawCloudRender.cpp + src/camera_pose_visualization.cpp + ) + target_link_libraries(host_sdk_sample + ${catkin_LIBRARIES} + ${COMMON_LIBS} + ${LYD_HOST_API_LIB} + ${LIBUSB_LIBRARIES} + yaml-cpp + ${OpenCV_LIBS} + pthread + usb-1.0 + ) + # Make sure the AE/AWB srv headers are generated before host_sdk_sample + # is compiled (catkin's generate_messages produces this target). + add_dependencies(host_sdk_sample ${PROJECT_NAME}_generate_messages_cpp) + + add_library(pointcloud_depth_converter src/pointcloud_depth_converter.cpp) + target_link_libraries(pointcloud_depth_converter + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + add_library(depth_image_ros_node src/depth_image_ros_node.cpp) + target_link_libraries(depth_image_ros_node + pointcloud_depth_converter + ${catkin_LIBRARIES} + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + add_executable(pcd2depth_node src/pcd2depth_ros.cpp) + target_link_libraries(pcd2depth_node + depth_image_ros_node + ${catkin_LIBRARIES} + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + + add_library(cloud_reprojector src/cloud_reprojector.cpp) + target_link_libraries(cloud_reprojector + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + + add_executable(cloud_reprojection_node src/cloud_reprojection_ros.cpp) + target_link_libraries(cloud_reprojection_node + cloud_reprojector + ${catkin_LIBRARIES} + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + + add_executable(image_overlay_node src/image_overlay_node.cpp) + target_link_libraries(image_overlay_node + ${catkin_LIBRARIES} + ${OpenCV_LIBS} + ) + + # Installation rules + install(TARGETS host_sdk_sample + RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} + ) + + install(DIRECTORY include/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + ) + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/config") + install(DIRECTORY config/ + DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/config + ) + endif() + +# ===== ROS2 Configuration ===== +elseif(ROS_VERSION STREQUAL "ROS2") + message(STATUS "Configuring for ROS2 build") + + # Find all necessary ROS2 packages + find_package(ament_cmake REQUIRED) + find_package(rclcpp REQUIRED) + find_package(std_msgs REQUIRED) + find_package(sensor_msgs REQUIRED) + find_package(nav_msgs REQUIRED) + find_package(visualization_msgs REQUIRED) + find_package(cv_bridge REQUIRED) + find_package(image_transport REQUIRED) + find_package(pcl_conversions REQUIRED) + find_package(message_filters REQUIRED) + find_package(tf2 REQUIRED) + find_package(tf2_ros REQUIRED) + find_package(geometry_msgs REQUIRED) + find_package(tf2_geometry_msgs REQUIRED) + find_package(ament_index_cpp REQUIRED) + + # ---- AE/AWB debug services ---- + # Generate C++ bindings for the 4 .srv files in srv/. The generated + # headers are linked into host_sdk_sample so it can host the services. + find_package(rosidl_default_generators REQUIRED) + rosidl_generate_interfaces(${PROJECT_NAME} + "srv/GetAe.srv" + "srv/GetAwb.srv" + "srv/SetAe.srv" + "srv/SetAwb.srv" + "srv/GetDeviceLogs.srv" + "srv/SaveMap.srv" + "srv/ResetAlgo.srv" + ) + + # Create executable + add_executable(host_sdk_sample + src/host_sdk_sample.cpp + src/yaml_parser.cpp + src/rawCloudRender.cpp + src/camera_pose_visualization.cpp + ) + + # Link libraries + target_link_libraries(host_sdk_sample + ${COMMON_LIBS} + yaml-cpp + usb-1.0 + ) + + # Link the generated AE/AWB srv typesupport into host_sdk_sample so it + # can host the 4 debug services. + rosidl_get_typesupport_target(cpp_typesupport_target + ${PROJECT_NAME} "rosidl_typesupport_cpp") + target_link_libraries(host_sdk_sample "${cpp_typesupport_target}") + + # Add ROS2 dependencies + ament_target_dependencies(host_sdk_sample + rclcpp + std_msgs + sensor_msgs + nav_msgs + visualization_msgs + cv_bridge + image_transport + tf2 + tf2_ros + geometry_msgs + tf2_geometry_msgs + ament_index_cpp + ) + + add_library(pointcloud_depth_converter_ros2 src/pointcloud_depth_converter.cpp) + target_link_libraries(pointcloud_depth_converter_ros2 + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + + add_library(depth_image_ros2_node_lib src/depth_image_ros2_node.cpp) + target_link_libraries(depth_image_ros2_node_lib + pointcloud_depth_converter_ros2 + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + + ament_target_dependencies(depth_image_ros2_node_lib + rclcpp + sensor_msgs + std_msgs + cv_bridge + image_transport + pcl_conversions + message_filters + ) + + add_executable(pcd2depth_ros2_node src/pcd2depth_ros2.cpp) + target_link_libraries(pcd2depth_ros2_node + depth_image_ros2_node_lib + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + yaml-cpp + ) + + ament_target_dependencies(pcd2depth_ros2_node + rclcpp + sensor_msgs + std_msgs + cv_bridge + image_transport + pcl_conversions + message_filters + ) + + add_library(cloud_reprojector_ros2 src/cloud_reprojector.cpp) + target_compile_definitions(cloud_reprojector_ros2 PRIVATE ROS2) + target_link_libraries(cloud_reprojector_ros2 + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + ) + + add_executable(cloud_reprojection_ros2_node src/cloud_reprojection_ros.cpp) + target_compile_definitions(cloud_reprojection_ros2_node PRIVATE ROS2) + target_link_libraries(cloud_reprojection_ros2_node + cloud_reprojector_ros2 + ${OpenCV_LIBS} + ${PCL_LIBRARIES} + yaml-cpp + ) + ament_target_dependencies(cloud_reprojection_ros2_node + rclcpp + sensor_msgs + nav_msgs + cv_bridge + image_transport + pcl_conversions + message_filters + ) + + add_executable(image_overlay_node src/image_overlay_node.cpp) + target_compile_definitions(image_overlay_node PRIVATE ROS2) + target_link_libraries(image_overlay_node + ${OpenCV_LIBS} + ) + ament_target_dependencies(image_overlay_node + rclcpp + sensor_msgs + cv_bridge + image_transport + message_filters + ) + + # Installation rules - ensure all install targets are defined before ament_package() + # Install executable + install(TARGETS + host_sdk_sample + pcd2depth_ros2_node + cloud_reprojection_ros2_node + image_overlay_node + depth_image_ros2_node_lib + pointcloud_depth_converter_ros2 + cloud_reprojector_ros2 + EXPORT export_${PROJECT_NAME} + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION lib/${PROJECT_NAME} + ) + + # Install package.xml + install(FILES package.xml + DESTINATION share/${PROJECT_NAME} + ) + + # Install headers + install(DIRECTORY include/ + DESTINATION include + ) + # Install launch_ROS2 directory + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/launch_ROS2") + install(DIRECTORY launch_ROS2/ + DESTINATION share/${PROJECT_NAME}/launch + ) + message(STATUS "Installing launch_ROS2 directory to share/${PROJECT_NAME}/launch") + else() + message(WARNING "launch_ROS2 directory not found") + endif() + # Install config files + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/config") + install(DIRECTORY config/ + DESTINATION share/${PROJECT_NAME}/config + ) + endif() + + # Install launch files + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/launch") + install(DIRECTORY launch/ + DESTINATION share/${PROJECT_NAME}/launch + ) + endif() + ament_export_targets(export_${PROJECT_NAME}) + # Declare dependencies + ament_export_dependencies( + rclcpp + std_msgs + sensor_msgs + nav_msgs + visualization_msgs + cv_bridge + image_transport + pcl_conversions + message_filters + tf2 + tf2_ros + geometry_msgs + tf2_geometry_msgs + ament_index_cpp + ) + + ament_package() + message(STATUS "Install targets added") + +else() + message(FATAL_ERROR "Invalid ROS_VERSION: ${ROS_VERSION}") +endif() + +# ARM platform specific link options +if(TARGET_PLATFORM STREQUAL "arm") + set_target_properties(host_sdk_sample PROPERTIES + LINK_FLAGS "-Wl,--no-as-needed -Wl,--rpath=${LIB_DIR}" + ) + message(STATUS "Adding ARM-specific link options and RPATH") +endif() + +# Add debug information +message(STATUS "=======================================") +message(STATUS "Project: ${PROJECT_NAME}") +message(STATUS "ROS_VERSION: ${ROS_VERSION}") +message(STATUS "Target platform: ${TARGET_PLATFORM}") +message(STATUS "lydHostApi library: ${LYD_HOST_API_LIB}") +message(STATUS "libusb library: ${LIBUSB_LIBRARIES}") +message(STATUS "=======================================") + diff --git a/sru_ws/src/odin_ros_driver/LICENSE b/sru_ws/src/odin_ros_driver/LICENSE new file mode 100644 index 0000000..54665e1 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 Manifold Tech Ltd. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sru_ws/src/odin_ros_driver/README.md b/sru_ws/src/odin_ros_driver/README.md new file mode 100644 index 0000000..e119809 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/README.md @@ -0,0 +1,1046 @@ +# Odin_ROS_Driver Readme + +ROS driver suite for Odin sensor modules (Manifold Tech Ltd.) + +Odin1 wiki: https://manifoldtechltd.github.io/wiki/Odin1/Cover.html + +## Odin_ROS_Driver + +Compatibility: + +● ROS 1(LTS Release: Noetic recommended) + +● ROS 2(LTS Release: Humble recommended) + +## Important Notice: + +This driver package provides core functionality for point cloud SLAM applications and targets specific use cases. It is intended exclusively for technical professionals conducting secondary development. End users must perform scenario-specific optimization and custom development to align with operational requirements in practical deployment environments. + +## 1. Version + +Current version: v0.14.4 + +Required device firmware version: v0.14.0 + +## 2. Preparation + +### 2.1 OS Requirement + +● Ubuntu 20.04 for ROS Noetic and ROS2 Foxy; + +● Ubuntu 22.04 for ROS2 Humble; + +● Ubuntu 18.04 is currently not supported; + +● Ubuntu 24.04 is not officially supported but may work with some modifications. + +### 2.2 Dependencies + +● Opencv >= 4.2.0(recommand 4.5.5/4.8.0. Make sure only one version of opencv is installed) + +● yaml-cpp + +● thread + +● OpenSSL + +● Eigen3 + +### 2.3 Dependencies Install + +#### 2.3.1 System +```shell +sudo apt update +sudo apt-get install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev +``` + +#### 2.3.2 yaml-cpp +```shell +sudo apt update +sudo apt install -y libyaml-cpp-dev +``` + +#### 2.3.3 libusb +```shell +sudo apt update +sudo apt install -y libusb-1.0-0-dev +``` + +#### 2.3.4 opencv +```shell +sudo apt update +sudo apt-get install libopencv-dev +``` + +#### 2.3.4 ROS install + +For ROS Noetic installation, please refer to: +[ROS Noetic installation instructions](https://wiki.ros.org/noetic/Installation) + +For ROS2 Foxy installation, please refer to: +[ROS Foxy installation instructions](https://docs.ros.org/en/foxy/Installation/Ubuntu-Install-Debians.html) + +For ROS2 Humble installation, please refer to: +[ROS Humble installation instructions](https://docs.ros.org/en/humble/Installation/Ubuntu-Install-Debians.html) + +## 3. Preparation + +### 3.1 Create Udev rules +```shell +sudo vim /etc/udev/rules.d/99-odin-usb.rules +``` +Add the following content to the 99-odin-usb.rules file +```shell +SUBSYSTEM=="usb", ATTR{idVendor}=="2207", ATTR{idProduct}=="0019", MODE="0666", GROUP="plugdev" +``` +Reload rules and reinsert devices +```shell +sudo udevadm control --reload +sudo udevadm trigger +``` +### 3.2 OS Requirement +```shell +git clone https://github.com/manifoldsdk/odin_ros_driver.git catkin_ws/src/odin_ros_driver +``` +Note: +Please clone the source code into the "[ros_workspace]/src/" folder, otherwise compilation errors will occur. + +### 3.3 make + +#### 3.3.1 ROS1 (Noetic for example): + +```shell +source /opt/ros/noetic/setup.bash +./script/build_ros.sh +``` + +#### 3.3.2 ROS2 (Foxy for example): + +```shell +source /opt/ros/foxy/setup.bash +./script/build_ros2.sh +``` + +### 3.4 run: + +#### 3.4.1 ROS1 (Noetic for example): + +```shell +source [ros_workspace]/devel/setup.bash +roslaunch odin_ros_driver [launch file] +``` +● odin_ros_driver: package name; + +● launch file: launch file; + +● ros_workspace: User's ROS environment workspace; +```shell +roslaunch odin_ros_driver odin1_ros1.launch +``` +#### 3.4.2 ROS2 (Foxy for example): + +```shell +source [ros2_workspace]/install/setup.bash +ros2 launch odin_ros_driver [launch file] +``` +● odin_ros_driver: package name; + +● launch file: launch file; + +● ros2_workspace: User's ROS2 environment workspace; + +ROS2 Demo Launch Instructions: +```shell +ros2 launch odin_ros_driver odin1_ros2.launch.py +``` + +### 3.5 Operation Mode: + +The operation mode can be configured via the `custom_map_mode` parameter in config/control_command.yaml. + +#### Odometry mode + +Set `custom_map_mode = 0` to enable odometry mode. In this mode, the map frame and odom frame share the same pose. + +If the odom data is found to drift, the script command "./set_param.sh algo_reset 1" can be used to dynamically reset the algorithm. + +#### SLAM mode + +Set `custom_map_mode = 1` to enable slam mode. This mode provides a complete SLAM system that builds upon the Odometry Mode by adding **loop closure detection** and **map saving** capabilities. + +After launching the driver, odin1 will automatically perform mapping and cache map data. When the scene capture is complete, users need to execute `./set_param.sh save_map 1` in the driver's source directory to save all map data collected since the program started. The map will be saved to the location specified by the `mapping_result_dest_dir` and `mapping_result_file_name` parameters in config/control_command.yaml. If these parameters are not specified, default values will be used. + +After the initial save, you can execute the command again to save a new map. Each save operation will generate a new map file. (Please allow at least 5 seconds between consecutive save operations) + +The map origin corresponds to the odom coordinate system's origin at the program's startup. + +##### Relocalization mode + +To enable relocalization, set `custom_map_mode = 2` and specify the absolute path to the pre-built map using the `relocalization_map_abs_path` parameter in config/control_command.yaml. + +Once launched, odin1 will initiate the relocalization process based on the current viewpoint and the specified map. To ensure a high success rate, it is recommended to starting within 1 meter ±10 degrees of the original position and orientation from the SLAM trajectory. + +Note that relocalization performance is highly environment-dependent. In highly distinctive scenes, successful matching may occur even beyond the 1m/10° range, while other environments may require more stringent conditions. We advise testing in your target environment to determine practical tolerances. + +If relocalization fails initially, the system will temporarily operate in a fallback SLAM mode (map saving is disabled in this state). During this time, you can freely move odin1. It will continue relocalization attempts in the background. Once successful, the TF between map and odom frames will be published. (Tip: Gently shaking or moving the device after initialization can help improve relocalization accuracy.) + +The following topics are published in the odom frame: `/odin1/cloud_slam, /odin1/odom, /odin1/highodom and /odin1/path`. To obtain these in the map frame, apply the TF from odom frame to map frame. + +## 4. File structure and data format +### 4.1 File structure +```shell +Odin_ROS_Driver/ // ROS1/ROS2 driver package + 3rdparty/ // Third-party libraries + src/ + host_sdk_sample.cpp // Example source code + yaml_parser.cpp // Source code for reading yaml parameters + rawCloudRender.cpp // Source code for RenderCloud + depth_image_ros_node.cpp //depth_image_ros_node + depth_image_ros2_node.cpp //depth_image_ros2_node + pcd2depth_ros.cpp //Source code for pcd2depth_ros + pcd2depth_ros2.cpp //Source code for pcd2depth_ros2 + pointcloud_depth_converter.cpp //Source code for pointcloud_depth_converter + cloud_reprojection_ros.cpp //Source code for cloud reprojection node (ROS1/ROS2) + cloud_reprojector.cpp //Core logic for cloud reprojection + lib/ + liblydHostApi_amd.a // Static library for AMD platform + liblydHostApi_arm.a // Static library for ARM platform + include/ + host_sdk_sample.h // Example header file + lidar_api_type.h // API data structure header file + lidar_api.h // API function declarations + yaml_parser.h // Parameter file reading header file + rawCloudRender.h // API about RenderCloud + data_logger.h // LOG about save_data + depth_image_ros_node.hpp // depth_image_ros_node + depth_image_ros2_node.hpp // depth_image_ros2_node + pointcloud_depth_converter.hpp // pointcloud_depth_convert + cloud_reprojection_ros_node.hpp // cloud_reprojection_ros_node (ROS1/ROS2) + cloud_reprojector.hpp // Core class for cloud reprojection + config/ + control_command.yaml // Control parameter file for driver + calib.yaml // Machine calibration yaml,differ for each individual device. Retrieved from the device everytime it connects to ROS driver + launch_ROS1/ + odin1_ros1.launch // ROS1 launch file + launch_ROS2/ + odin1_ros2.launch.py // ROS2 launch file + script/ + build_ros1.sh // Installation script for ROS1 + build_ros2.sh // Installation script for ROS2 + recorddata/ // holds recorded data that can import into MindCloud + log/ // holds log files + Driver_{timestamp}/ // holds all log folders for each time driver started + Conn_{timestamp}/ // holds all log files for each odin1 device connection + dev_status.csv // device status log file + README.md // Usage instructions + CMakeLists.txt // CMake build file + License // License file +``` +### 4.2 File structure +| Launch File Name | Description | +|--------------------------|-------------| +| odin1_ros1.launch | Launch file for ROS1 - Odin1 Basic Operations Demo | +| odin1_ros2.launch.py | Launch file for ROS2 - Odin1 Basic Operations Demo | + + +### 4.3 ROS topics +Internal parameters of the Odin ROS driver are defined in config/control_command.yaml. Below are descriptions of the commonly used parameters: + +| Topic |control_command.yaml | Detailed Description | +|---------------------|----------------------|----------------------| +| odin1/imu | sendimu | Imu Topic | +| odin1/image | sendrgb | RGB Camera Topic, decoded from original jpeg data from device, bgr8 format | +| odin1/image_undistort | sendrgbundistort | undistorted RGB Camera Topic, processed with calib.yaml from device | +| odin1/image/compressed | sendrgbcompressed | RGB Camera compressed Topic, original jpeg data from device | +| odin1/cloud_raw | senddtof | Raw_Cloud Topic | +| odin1/cloud_render | sendcloudrender | Render_Cloud Topic, processed with raw point cloud, rgb image, and calib.yaml from device | +| odin1/cloud_slam | sendcloudslam | Slam_PointCloud Topic | +| odin1/odometry | sendodom | Odom Topic | +| odin1/odometry_high | sendodom | high frequency Odom Topic | +| odin1/path | showpath | Odom Path Topic | +| tf | sendodom | tf tree Topic | +| odin1/depth_img_competetion | senddepth | Dense depth image Topic. Demo, high computing power required. One-to-one with odin1/image_undistort. To utilize the data please directly subscribe to this topic instead of echoing it. Original value is already depth data, no need for further convert. | +| odin1/depth_img_competetion_cloud | senddepth | Dense Depth_Cloud Topic. Demo, high computing power required | +| odin1/reprojected_image | sendreprojection | Reprojected cloud to image Topic. Projects cloud_slam to camera image using odometry. Processed on host device. | + +### 4.4 Data format + +1. The raw point cloud (cloud_raw) has the following fields: +``` +float32 x // X axis, in meters +float32 y // Y axis, in meters +float32 z // Z axis, in meters +uint8 intensity // Reflectivity, range 0–255 +uint16 confidence // Point confidence, actual value range from 0 to around 1300 in typical scene, higher value means more reliable. Recommanded filtering threshold is 30-35, should be adjusted accordingly. +float32 offset_time // Time offset relative to the base timestamp unit: s +``` + +To work with this custom format in PCL, first define the point type: +```cpp +/*** LS ***/ +namespace ls_ros { + struct EIGEN_ALIGN16 Point { + float x; + float y; + float z; + uint8_t intensity; + uint16_t confidence; + float offset_time; + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + }; +} // namespace ls_ros + +POINT_CLOUD_REGISTER_POINT_STRUCT(ls_ros::Point, + (float, x, x) + (float, y, y) + (float, z, z) + (uint8_t, intensity, intensity) + (uint16_t, confidence, confidence) + (float offset_time , offset_time) +) +``` +Then, you can easily convert a ROS sensor_msgs::PointCloud2 message into a PCL point cloud: +``` +pcl::PointCloud ls_cloud; +pcl::fromROSMsg(*msg, ls_cloud); +``` + +2. The slam point cloud (cloud_slam) and directly rendered point cloud (cloud_render) has the following fields: +``` +float32 x // X axis, in meters +float32 y // Y axis, in meters +float32 z // Z axis, in meters +float32 rgb // RGB value +``` + +### 4.5 Other functionalities + +|control_command.yaml | Detailed Description | +|-----------------------|----------------------| +| use_host_ros_time | Time synchronization mode: 0 - use odin internal system time as data timestamp (typical and recommended); 1 - use host ROS time upon receive (not recommended for most users); 2 - align odin1 time to host time via NTP-like synchronization, timestamp is the sensor data reception time on host time axis. | +| strict_usb3.0_check | Strict USB3.0 check, if off, allow connection even if usb connection is below usb 3.0 | +| recorddata | Record data in specific format that can be imported into MindCloud(TM) for post-processing. Please be aware that this will consume a lot of storage space. Testing shows 9.5G for 10mins of data. The per-frame timestamps written into the recorded files (IMU / image / point cloud / pose / rotate) follow the same alignment policy as `use_host_ros_time`, so under NTP mode (`use_host_ros_time=1` or `2`) the recorded timestamps are NTP-aligned host time instead of odin1 boot time.
录制文件 (IMU / 图像 / 点云 / Pose / Rotate) 中每帧的时间戳与 `use_host_ros_time` 采用相同对齐策略:在 NTP 模式 (`use_host_ros_time=1` 或 `2`) 下,录制时间戳为 NTP 对齐后的主机时间,而非 odin1 开机时间。 | +| devstatuslog | Device status logging, currently save device status (soc temperature, cpu usage, ram usage, dtof sensor temp .etc) and data tx & rx rate to devstatus.csv under log folder. A new file will be created every time the driver is started. | +| showcamerapose | Display Camera Pose and Field of View. | +| custom_map_mode | Operation Modes: Mode 0 - Odometry mode: The map frame and odom frame share the same pose. Mode 1 - Mapping (with loop closure) mode: This mode supports map saving. Mode 2 - Relocalization mode: Requires specifying the absolute path to the map file. After successful relocalization, it will output the TF relationship between the map and odom frames.| +| custom_init_pos | Initialization Position (currently unused). | +| relocalization_map_abs_path | Absolute Path to Map File: Used for relocalization mode. | +| mapping_result_dest_dir and mapping_result_file_name| Path and Name for Saving Maps in Mapping Mode: If not specified, default values will be used. | + +### 4.6 Runtime AE/AWB Tuning via ROS Service / 通过 ROS Service 在线调节 AE/AWB + +The driver hosts four ROS services that let a side terminal tune the +camera's auto exposure (AE) and auto white balance (AWB) at runtime, +while the main data streams keep flowing. The same SDK call is shared +with the driver's main control path and serialised by an internal +mutex, so it is safe to invoke these services concurrently with normal +operation. + +驱动启动后会注册 4 个 ROS Service,允许在不重启 driver 的前提下,从另一个终端动态调节 +相机的自动曝光(AE)和自动白平衡(AWB)。底层 SDK 调用与驱动主控制路径共享同一把 +互斥锁,因此可以与正常数据流并发调用。 + +**Service list / Service 一览** + +| Service name | Type / 类型 | Purpose / 用途 | +|---|---|---| +| `/odin1/get_ae` | `odin_ros_driver/srv/GetAe` | Query current AE status / 查询当前 AE 状态 | +| `/odin1/get_awb` | `odin_ros_driver/srv/GetAwb` | Query current AWB status / 查询当前 AWB 状态 | +| `/odin1/set_ae` | `odin_ros_driver/srv/SetAe` | Set AE mode and (manual) exposure / gain / 设置 AE 模式和手动曝光/增益 | +| `/odin1/set_awb` | `odin_ros_driver/srv/SetAwb` | Set AWB mode and (manual) R/B gain / 设置 AWB 模式和手动 R/B 增益 | + +#### 4.6.1 Request fields, ranges, physical meaning / 请求字段、范围与物理含义 + +**`SetAe.Request`** + +| Field | Range / 范围 | Meaning / 含义 | +|---|---|---| +| `mode` | `0` (AUTO) or / 或 `1` (MANUAL) | `0` = device runs its own AE loop, the two floats below are ignored / 设备自动调 AE,下方参数被忽略
`1` = device locks AE and applies the provided values / 设备锁 AE 并应用提供的值 | +| `exposure_time` | `0.0001` ~ `0.033` s (manual only / 仅手动模式) | Sensor exposure time per frame. Longer = brighter but more motion blur / 每帧传感器曝光时间。越长越亮但运动模糊增大 | +| `gain` | `1.0` ~ `64.0` (manual only / 仅手动模式) | Analog gain. Higher = brighter output but worse SNR / 模拟增益。越大越亮但信噪比越差 | + +**`SetAwb.Request`** + +| Field | Range / 范围 | Meaning / 含义 | +|---|---|---| +| `mode` | `0` (AUTO) or / 或 `1` (MANUAL) | `0` = device runs its own AWB loop / 设备自动 AWB
`1` = device locks AWB and applies provided gains / 设备锁定 AWB 并应用所给增益 | +| `rgain` | `0.1` ~ `4.0` (manual only / 仅手动模式) | R channel gain. Higher `rgain` vs `bgain` shifts the image warm (yellow/red) / R 通道增益,相对 bgain 越大,画面越偏暖 | +| `bgain` | `0.1` ~ `4.0` (manual only / 仅手动模式) | B channel gain. Higher `bgain` vs `rgain` shifts the image cool (blue) / B 通道增益,相对 rgain 越大,画面越偏冷 | + +> Gr / Gb channels are fixed to 1.0 by the device and are not adjustable. +> Gr / Gb 通道被设备固定为 1.0,不可调节。 + +#### 4.6.2 Response fields / 响应字段 + +All four services return a `success` (bool) and `rc` (int32). Get +services additionally return the queried state. +4 个 Service 都返回 `success` (bool) 与 `rc` (int32)。Get 类还会返回查询到的状态字段。 + +**`GetAe.Response`** + +| Field | Typical range / 典型范围 | Meaning / 含义 | +|---|---|---| +| `exposure_time` | `0.0001`~`0.033` s | Current exposure / 当前曝光时间 | +| `gain` | `1.0`~`64.0` | Current analog gain / 当前模拟增益 | +| `iso` | `100`~`6400` | Equivalent ISO / 等效 ISO | +| `brightness` | `0`~`255` | Average frame brightness / 平均帧亮度 | +| `is_converged` | `0` or `1` | `1` = AE settled / AE 已收敛 | +| `env_lv` | `0`~`15` | Ambient luminance index, higher = brighter / 环境光强度指数,越大越亮 | +| `fps` | `~10` / `~14.5` / `~29` | Current frame rate / 当前帧率 | + +**`GetAwb.Response`** + +| Field | Typical range / 典型范围 | Meaning / 含义 | +|---|---|---| +| `rgain` / `bgain` | `0.1`~`4.0` | R / B channel gain / R / B 通道增益 | +| `grgain` / `gbgain` | `1.0` (fixed / 固定) | Gr / Gb gain, device-fixed / Gr / Gb 增益,设备固定 | +| `cct` | `2500`~`8000` K | Correlated color temperature / 相关色温 | +| `ccri` | `-50`~`50` | Color temp deviation index, 0 = on Planckian locus / 色温偏离指数,0 表示在普朗克轨迹上 | +| `is_converged` | `0` or `1` | `1` = AWB settled / AWB 已收敛 | + +#### 4.6.3 `rc` return code / `rc` 返回码 + +| `rc` | Meaning / 含义 | +|---|---| +| `0` | Success / 成功 | +| `400` | Device payload too short / 设备载荷过短 | +| `401` | Device opcode not supported / 设备不支持该 opcode | +| `402` | Device parameter length wrong / 参数长度错误 | +| `403` | **Parameter out of range** / 参数越界 — most common when manual values exceed the table above / 手动值超出上表范围时最常见 | +| `404` | Device-side socket error / 设备端 socket 错误 | +| `405` | Device-side `ae_control` did not respond / 设备端 `ae_control` 无应答(确认 lydapp 已运行) | +| `255` (`0xFF`) | Unknown opcode reported by ae_control / ae_control 报未知 opcode | +| `-1` | SDK not initialised / SDK 未初始化 | +| `-2` ~ `-5` | USB transfer / timeout / malformed reply / USB 传输异常、超时、应答畸形 | +| `-100` | **Driver has not opened the device yet** / driver 还未打开设备,请等设备连接成功 | + +#### 4.6.4 Usage examples / 调用示例 + +ROS2 (Humble) — start the driver in one terminal, then in a side terminal: +ROS2(Humble)—— 在一个终端启动 driver,在另一个终端: + +```bash +source install/setup.bash + +# Query current state / 查询当前状态 +ros2 service call /odin1/get_ae odin_ros_driver/srv/GetAe +ros2 service call /odin1/get_awb odin_ros_driver/srv/GetAwb + +# Set AE to AUTO / 设置 AE 为自动 +ros2 service call /odin1/set_ae odin_ros_driver/srv/SetAe "{mode: 0}" + +# Set AE to MANUAL with 10 ms exposure and gain 4.0 +# 设置 AE 为手动,10 毫秒曝光,增益 4.0 +ros2 service call /odin1/set_ae odin_ros_driver/srv/SetAe \ + "{mode: 1, exposure_time: 0.010, gain: 4.0}" + +# Set AWB to MANUAL with rgain=1.5, bgain=2.0 +# 设置 AWB 为手动,rgain=1.5、bgain=2.0 +ros2 service call /odin1/set_awb odin_ros_driver/srv/SetAwb \ + "{mode: 1, rgain: 1.5, bgain: 2.0}" + +# Restore AUTO / 一键回自动 +ros2 service call /odin1/set_ae odin_ros_driver/srv/SetAe "{mode: 0}" +ros2 service call /odin1/set_awb odin_ros_driver/srv/SetAwb "{mode: 0}" + +# Inspect srv definition / 查看 srv 完整定义 +ros2 interface show odin_ros_driver/srv/SetAe +``` + +ROS1 (Noetic) — start the driver, then in a side terminal: +ROS1(Noetic)—— 启动 driver 后,新开终端: + +```bash +source devel/setup.bash + +# Query / 查询 +rosservice call /odin1/get_ae +rosservice call /odin1/get_awb + +# Set AE manual / 设置 AE 手动 +rosservice call /odin1/set_ae "{mode: 1, exposure_time: 0.010, gain: 4.0}" + +# Set AWB manual / 设置 AWB 手动 +rosservice call /odin1/set_awb "{mode: 1, rgain: 1.5, bgain: 2.0}" + +# Restore AUTO (ROS1 requires all fields to be present) +# 一键回自动(ROS1 要求填齐全部字段) +rosservice call /odin1/set_ae "{mode: 0, exposure_time: 0.0, gain: 0.0}" +rosservice call /odin1/set_awb "{mode: 0, rgain: 0.0, bgain: 0.0}" + +# Inspect srv definition / 查看 srv 完整定义 +rossrv show odin_ros_driver/SetAe +``` + +#### 4.6.5 Recommended starting points by scene / 不同场景推荐起步参数 + +**AE (`exposure_time`, `gain`)** + +| Scene / 场景 | `exposure_time` | `gain` | +|---|---|---| +| Bright outdoor / 明亮室外 | `0.001` ~ `0.005` s | `1.0` ~ `2.0` | +| Normal indoor / 普通室内 | `0.008` ~ `0.015` s | `2.0` ~ `8.0` | +| Dim light / 暗光环境 | `0.020` ~ `0.030` s | `8.0` ~ `32.0` | +| Very dark / 极暗 | `0.033` s | `32.0` ~ `64.0` | + +**AWB (`rgain`, `bgain`)** + +| Target tone / 目标色调 | `rgain` | `bgain` | +|---|---|---| +| Warm (tungsten, sunset) / 暖(钨丝灯、夕阳) | `2.0` ~ `2.5` | `1.0` ~ `1.2` | +| Neutral (D65 daylight) / 中性(D65 日光) | `1.5` ~ `1.7` | `1.8` ~ `2.0` | +| Cool (cloudy, fluorescent) / 冷(阴天、荧光) | `1.2` ~ `1.4` | `2.2` ~ `2.6` | +| Very cool / 极冷 | `1.0` | `3.0` ~ `4.0` | + +#### 4.6.6 Caveats / 注意事项 + +- The service blocks for up to ~10 s waiting for the device to reply; + typical latency is tens of milliseconds. + Service 最长阻塞约 10 秒等设备应答;正常几十毫秒返回。 +- Manual mode is **not** persisted across driver / device restart; + it falls back to AUTO on each new connection. + 手动模式**不会**跨重启保留;每次重连默认回到 AUTO。 +- `rc = -100` means the driver has not yet opened the device. + Wait until the driver logs `device connected` before calling. + 返回 `rc = -100` 表示 driver 还没打开设备,等到 driver 日志显示 `device connected` 再调用。 +- The effective maximum `exposure_time` is bounded by the frame + period `1 / fps`. With `dtof_fps = 290` (29 Hz, period ~34 ms) + the upper limit 0.033 s is already at the frame boundary. + 最大可用 `exposure_time` 受帧周期 `1/fps` 限制。在 `dtof_fps = 290`(29 Hz、周期 ~34 ms)下,上限 0.033 s 已经贴到帧边界。 + +## 4.7 Runtime Device Control / 运行时设备控制 + +In addition to the AE/AWB services above, the driver exposes several runtime ROS services and supports the `set_param.sh` command-file interface for operations such as saving maps, resetting the algorithm, and retrieving device logs. + +除上述 AE/AWB 服务外,driver 还暴露了若干运行时 ROS Service,并支持 `set_param.sh` 命令文件接口,用于保存地图、复位算法、拉取设备日志等操作。 + +See [docs/runtime_service_operations.md](docs/runtime_service_operations.md) for the full list of services, `set_param.sh` usage, request/response fields and examples. + +完整服务列表、`set_param.sh` 用法、请求/响应字段及调用示例见 [docs/runtime_service_operations.md](docs/runtime_service_operations.md)。 + +## 5. FAQ +### 5.1 Segmentation fault upon re-launching host SDK +**Error Message** +No device connected after 60 seconds + +**Solution** +1. Please power on Odin module again # Disconnect and reconnect odin power + +2. Reinitialize Odin SDK # Execute SDK after device reboot + + +### 5.2 Library binding failure during compilation + +**Error Message** +ld: cannot find -llydHostApi or symbol lookup errors + +**Resolution** + +1. Clean previous build artifacts + +ROS1 +```shell +rm -rf devel/ build/ +``` +ROS2 +```shell +rm -rf devel/ install/ log/ +``` +2. Re-run script installation + +### 5.3 Docker GUI passthrough failure + +**Error Message** +Unable to open X display or No protocol specified + +**Resolution** +```shell +xhost + #This command enables graphical passthrough to Docker containers +``` + +### 5.4 ROS driver exit with get version failed error + +**Error Message** +```shell +: get device version fail. +get version failed. +``` + +**Resolution** + +Device firmware version is too low, please update to latest version. + + +### 5.5 RVIZ has not responded for a long time + +**Error Message** +Rviz does not respond, and after a while the terminal prints Device disconnected, waiting for reconnection... + +**Resolution** + +Please power on Odin module again + +### 5.6 Device not responding + +**Error Message** +Missed ok response from device,probably wrong interaction procedure. + +**Resolution** + +Please adopt the solution mentioned in 5.1 + +### 5.7 Device has no external calibration file + +**Error Message** +ERROR:Missing camera node 'cam_0' + +**Resolution** + +Please plug and unplug the USB again + +### 5.8 ROS Driver report device disconnected immediately after stream started + +**Error Message** + +```shell +Device ready and streams activated +Device detaching... +Wating for device reconnection... +Device disconnected, waiting for reconnection... +``` + +**Reason** + +Mostly common on ros2 environment and connected to complex network environment, such as office wifi & ethernet. ROS2 default to broadcast, and complex network environment will cause ros2 publish to block, leading to device disconnection. + +**Resolution** + +If cross-device communication is not required, please restrict ros2 to localhost only with: +```shell +export ROS_LOCALHOST_ONLY=1 +``` + +If cross-device communication is required, please simplify the network environment as much as possible. Mini local network with only required devices is recommended. + +### 5.9 ROS Driver died immediately after stream started + +**Error Message** + +```shell +Device ready and streams activated +[host_sdk_sample-2] process has died ...... +``` + +**Test** + +Disable odin1/image with sendrgb = 0 in control_command.yaml and try again. If the driver now works, it is likely that the issue is related to multiple version of opencv is installed on the system. + +**Resolution** + +Purge the unused version of opencv and maintain a single complete version, then rebuild the driver and try again. + +### 5.10 ROS Driver printing "TF_OLD_DATA ignoring data" warning + +**Error Message** + +```shell +[rviz2-3] Warning: TF_OLD_DATA ignoring data from the past for frame odin1_base_link at time 20.547632 according to authority Authority undetectable +[rviz2-3] Possible reasons are listed at http://wiki.ros.org/tf/Errors%20explained +[rviz2-3] at line 294 in ./src/buffer_core.cpp +``` + +**Reason** + +This is a ros & rviz feature to warn user that some tf data is being ignored due to timestamp conflicts. It happens when user keeps ros driver running and power-cycles odin device, which cause odin's internal system time being reset and now data timestamps conflicts with old data recieved by rviz during last run. + +**Resolution** + +There's a reset button on bottom of rviz gui. Click on this button will reset rviz's internal state and stop the warning. + +### 5.11 ROS Driver printing "unknown cmd code: xx" error + +**Error Message** + +```shell +: unknow command code 21. +``` + +**Reason** + +This is due to ros driver version mismatch with device firmware version, resulting in ros driver unable to decode new data added in newer firmware. + +**Resolution** + +Please make sure you are using most up-to-date ros driver and device firmware. + +### 5.12 USB device access error (LIBUSB_ERROR_BUSY or LIBUSB_ERROR_ACCESS) + +**Error Message** + +```shell +libusb: error [udev_hotplug_event] ignoring udev action bind +LIBUSB_ERROR_BUSY +``` + +or + +```shell +libusb: error [_get_usbfs_fd] libusb couldn't open USB device /dev/bus/usb/xxx/xxx, errno=13 +LIBUSB_ERROR_ACCESS +``` + +**Reason** + +- **LIBUSB_ERROR_BUSY**: Another process is already using the USB device. This commonly happens when multiple instances of the ROS driver are running, or another application (such as a previous crashed instance) still holds the device handle. + +- **LIBUSB_ERROR_ACCESS**: The current user does not have permission to access the USB device. This is typically caused by missing udev rules or insufficient user privileges. + +**Resolution** + +For **LIBUSB_ERROR_BUSY**: + +1. Check if another instance of the driver is running: +```shell +ps aux | grep host_sdk_sample +``` + +2. Kill any existing instances: +```shell +killall host_sdk_sample +``` + +3. If the issue persists, unplug and replug the USB device to reset the device state. + +For **LIBUSB_ERROR_ACCESS**: + +1. Add udev rules for the device. Create a file `/etc/udev/rules.d/99-odin.rules` with the following content: +```shell +SUBSYSTEM=="usb", ATTR{idVendor}=="2207", ATTR{idProduct}=="0019", MODE="0666", GROUP="plugdev" +``` + +2. Reload udev rules: +```shell +sudo udevadm control --reload-rules +sudo udevadm trigger +``` + +3. Alternatively, run the driver with sudo (not recommended for production): +```shell +sudo -E ros2 launch odin_ros_driver odin_ros_driver.launch.py +``` + +4. Make sure your user is in the `plugdev` group: +```shell +sudo usermod -aG plugdev $USER +``` +Then log out and log back in for the group change to take effect. + +### 5.13 ros2 bag drops high-frequency topics (IMU / odometry_highfreq) / ros2 bag 录制丢失高频话题(IMU / odometry_highfreq) + +**Symptom / 现象** + +When recording with `ros2 bag record`, low-frequency topics (cloud, image, odometry, wiwc) are intact, but `/odin1/imu` (400 Hz) and `/odin1/odometry_highfreq` (400 Hz) show missing samples — analysis scripts report inter-message intervals that are 2× or more of the expected period, while no drop is reported on the SDK side or by an online subscriber such as `ros2 topic hz`. + +使用 `ros2 bag record` 录制时,低频话题(cloud、image、odometry、wiwc)完整无丢,但 `/odin1/imu`(400 Hz)和 `/odin1/odometry_highfreq`(400 Hz)会出现丢帧——分析脚本上看到消息间隔达到正常周期的 2 倍以上,而 SDK 侧不报丢,独立的 `ros2 topic hz` 订阅者也看不到丢。 + +**Reason / 原因** + +The driver publishes `/odin1/imu` and `/odin1/odometry_highfreq` with `RELIABLE` QoS. By default `ros2 bag record` subscribes with `history = keep_last`, `depth = 10`, which only buffers ~25 ms of samples at 400 Hz. Whenever the recorder is briefly delayed (disk flush, mcap/sqlite chunk write, scheduler jitter), its subscription queue overflows and DDS silently drops the oldest samples on the **subscriber side**. The SDK and publisher are unaffected, which is why no drop appears in the driver logs or in `ros2 topic hz`. + +驱动以 `RELIABLE` QoS 发布 `/odin1/imu` 与 `/odin1/odometry_highfreq`。`ros2 bag record` 默认订阅使用 `history = keep_last`、`depth = 10`,在 400 Hz 下只能缓冲约 25 ms。一旦录制端有短暂阻塞(落盘 flush、mcap/sqlite chunk 写入、调度抖动),订阅队列就会溢出,DDS 在**订阅端**静默丢掉最旧的样本。SDK 与 publisher 不受影响,因此驱动日志和 `ros2 topic hz` 都看不到丢。 + +**Resolution / 解决方案** + +Use the provided QoS override file `script/rosbag2_qos.yaml` to raise the subscriber-side queue depth on the recorder for the two high-rate topics: + +使用本仓库提供的 QoS 配置 `script/rosbag2_qos.yaml`,把高频话题的录制订阅 depth 拉大: + +```yaml +# script/rosbag2_qos.yaml +/odin1/imu: + reliability: reliable + history: keep_last + depth: 4000 + +/odin1/odometry_highfreq: + reliability: reliable + history: keep_last + depth: 4000 +``` + +Apply it when recording / 录制时通过 `--qos-profile-overrides-path` 应用: + +```shell +ros2 bag record -a \ + --qos-profile-overrides-path src/odin_ros_driver/script/rosbag2_qos.yaml \ + -o my_bag +``` + +Or only the high-rate topics / 也可以只录制高频话题: + +```shell +ros2 bag record \ + --qos-profile-overrides-path src/odin_ros_driver/script/rosbag2_qos.yaml \ + -o my_bag \ + /odin1/imu /odin1/odometry_highfreq /odin1/odometry /odin1/wiwc /odin1/cloud_raw +``` + +**Optional further tuning / 可选的进一步优化** + +If drops still occur after applying the override (typically on slower disks), try the following in addition / 套用上述 override 后仍有丢包时(通常发生在慢盘上),可叠加以下措施: + +```shell +# Use mcap backend with a larger internal cache (faster than sqlite3). +# 使用 mcap 后端 + 更大的内部缓存(比 sqlite3 快)。 +ros2 bag record -s mcap --max-cache-size 1073741824 \ + --qos-profile-overrides-path src/odin_ros_driver/script/rosbag2_qos.yaml \ + -o my_bag \ + /odin1/imu /odin1/odometry_highfreq ... + +# Enlarge kernel UDP socket buffers (the most common hidden bottleneck for +# 400 Hz RELIABLE traffic, default is only 208 KB). +# 放大内核 UDP socket buffer(400 Hz RELIABLE 流量最常见的隐藏瓶颈,默认仅 208 KB)。 +sudo sysctl -w net.core.rmem_max=33554432 +sudo sysctl -w net.core.wmem_max=33554432 +``` + +**Does ROS1 have the same problem? / ROS1 是否存在同样的问题?** + +No. ROS1 uses TCP-based publish/subscribe with a single `queue_size` parameter on each side, and has no QoS profile mismatch between publisher and subscriber. The ROS1 publisher path in this driver already sizes the IMU and `odometry_highfreq` publishers to `queue_size = 4000` (`include/host_sdk_sample.h`, see `initialize_publishers` ROS1 branch), and `rosbag record` uses TCP transport which is reliable by construction. As a result this specific drop pattern does not occur under ROS1; no additional configuration is required. + +不存在。ROS1 使用基于 TCP 的发布/订阅,发布端与订阅端各自只有一个 `queue_size` 参数,不存在 ROS2 那种 QoS profile 不匹配的问题。本驱动 ROS1 路径已经把 IMU 与 `odometry_highfreq` 的发布队列设置为 `queue_size = 4000`(见 `include/host_sdk_sample.h` 中 `initialize_publishers` 的 ROS1 分支),并且 `rosbag record` 使用 TCP 传输本身即可靠传递。因此在 ROS1 下不会出现该丢帧现象,也不需要额外配置。 + +### 5.14 On Ubuntu 24.04 (ROS2 Jazzy) point clouds / TF fail to transform in RViz / Ubuntu 24.04(ROS2 Jazzy)下 RViz 点云 / TF 无法转换 + +**Symptom / 现象** + +On Ubuntu 24.04 (ROS2 Jazzy), when the RViz **Fixed Frame** is set to `odom`, `cloud_raw` (in the `lidar` frame) fails to display and RViz reports a transform / extrapolation error for the `odom -> imu -> lidar` chain. On Ubuntu 22.04 (Humble) the same setup works. + +在 Ubuntu 24.04(ROS2 Jazzy)下,当 RViz 的 **Fixed Frame** 设为 `odom` 时,`cloud_raw`(`lidar` 系)无法显示,RViz 对 `odom -> imu -> lidar` 链条报 transform / 外推(extrapolation)错误。相同配置在 Ubuntu 22.04(Humble)下却正常。 + +**Reason / 原因** + +The device point-cloud timestamp is typically ~100 ms ahead of the odometry timestamp. ROS2 Jazzy's tf2 performs a strict timestamp lookup and will not extrapolate, so when the TF is published only at the odometry rate (and only at the odometry timestamp), tf2 cannot find a transform bracketing the cloud timestamp and the lookup fails. + +设备点云时间戳通常比里程计时间戳超前约 100 ms。ROS2 Jazzy 的 tf2 采用严格的时间戳查找且不做外推(extrapolation),因此当 TF 只在里程计频率、且只按里程计时间戳发布时,tf2 找不到能覆盖点云时间戳的变换,查找失败。 + +**Resolution / 解决方案** + +Set `tf_extra_publish_rate` to a value greater than `0` (e.g. `100`) in `config/control_command.yaml`. This starts an extra timer that keeps re-publishing the `odom -> imu` and `imu -> lidar` transforms at the configured rate with advancing timestamps, so tf2 always has a transform covering the cloud timestamp. + +在 `config/control_command.yaml` 中把 `tf_extra_publish_rate` 设为大于 `0` 的值(例如 `100`)。它会启动一个额外的定时器,按设定频率、以推进的时间戳持续补发 `odom -> imu` 与 `imu -> lidar` 变换,使 tf2 始终有覆盖点云时间戳的变换。 + +```yaml +# config/control_command.yaml +tf_extra_publish_rate: 100 # 0: off; >0: rate in Hz (recommended on ROS2 Jazzy / Ubuntu 24.04) +``` + +On Ubuntu 22.04 (Humble) or ROS1 this is usually not required and the parameter can be left at `0`. + +在 Ubuntu 22.04(Humble)或 ROS1 下通常不需要该配置,参数可保持为 `0`。 + +### 5.15 USB "transfer no mem" / "transfer error" on low-performance hosts / 低性能主机上出现 "transfer no mem" / "transfer error" + +**Symptom / 现象** + +```shell +: submit x transfer fail LIBUSB_ERROR_NO_MEM. +: transfer error: LIBUSB_TRANSFER_ERROR. +``` + +The driver runs fine on a powerful PC but, when deployed on a lower-performance board (e.g. an embedded ARM host), after a while the SDK starts reporting `LIBUSB_ERROR_NO_MEM` on send, followed by a cascade of `transfer error`. The module's sending rate is constant; the only thing that changed is the host the SDK runs on. + +驱动在性能强的 PC 上运行正常,但部署到性能较弱的板子(例如嵌入式 ARM 主机)上跑一段时间后,SDK 发送时开始报 `LIBUSB_ERROR_NO_MEM`,随后接连出现 `transfer error`。模组的发送速率是恒定的,唯一改变的条件是 SDK 运行在哪台机器上。 + +**Reason / 原因** + +libusb async transfers queued to the kernel consume a limited per-device usbfs memory pool (`/sys/module/usbcore/parameters/usbfs_memory_mb`, default **16 MB**). On a slow host the single libusb event thread reaps completed transfers more slowly than new ones are submitted, so outstanding OUT (send) transfers pile up in the usbfs pool until submission fails with `LIBUSB_ERROR_NO_MEM`. Once submission starts failing, subsequent transfers report `LIBUSB_TRANSFER_ERROR`. + +libusb 异步传输提交到内核后,会占用每个设备有限的 usbfs 内存池(`/sys/module/usbcore/parameters/usbfs_memory_mb`,默认 **16 MB**)。在慢主机上,单一的 libusb 事件线程回收已完成传输的速度跟不上新传输的提交速度,于是在途的 OUT(发送)传输在 usbfs 池中不断堆积,直到提交失败并返回 `LIBUSB_ERROR_NO_MEM`。一旦提交开始失败,后续传输就会报 `LIBUSB_TRANSFER_ERROR`。 + +**Resolution / 解决方案** + +1. Raise the usbfs memory limit at runtime (takes effect immediately, resets on reboot) / 在运行时调大 usbfs 内存上限(立即生效,重启后失效): + +```shell +# Check current value / 查看当前值 (default 16) +cat /sys/module/usbcore/parameters/usbfs_memory_mb + +# Raise to 128 MB / 调大到 128 MB +echo 128 | sudo tee /sys/module/usbcore/parameters/usbfs_memory_mb +``` + +2. Make it persistent across reboots / 让配置在重启后仍生效(二选一): + +```shell +# Option A: kernel boot parameter (edit GRUB / board bootargs) +# 方式 A:内核启动参数(编辑 GRUB / 板子的 bootargs) +usbcore.usbfs_memory_mb=128 + +# Option B: modprobe config +# 方式 B:modprobe 配置 +echo "options usbcore usbfs_memory_mb=128" | sudo tee /etc/modprobe.d/usbcore.conf +``` + +**Note / 说明** + +Raising `usbfs_memory_mb` is a mitigation that increases headroom. The SDK USB layer already bounds the number of in-flight OUT transfers (flow control) and releases transfer buffers on every terminal state to prevent the memory leaks that previously turned a transient error into a runaway. Keeping a larger usbfs pool (e.g. 128 MB) is still recommended on slow hosts or when transferring large files (e.g. relocalization maps). + +调大 `usbfs_memory_mb` 属于提高余量的缓解措施。SDK 的 USB 层已经对在途 OUT 传输数量做了上限限制(流控),并在每个终止状态释放传输缓冲,避免了此前"瞬时错误演变为不可恢复的内存泄漏雪崩"的问题。在慢主机上或传输大文件(如重定位地图)时,仍建议保留较大的 usbfs 池(例如 128 MB)。 + +### 5.16 Driver crashes when publishing RGB due to cv_bridge / OpenCV version mismatch (without touching the system) / 出图时因 cv_bridge 与 OpenCV 版本不匹配崩溃(不动系统的解法) + +**Symptom / 现象** + +The driver connects and activates streams, but crashes (segfault / heap corruption) as soon as the first RGB frame is published. This is the same root cause as 5.9, seen when the host has **two OpenCV versions** installed: the ROS `cv_bridge` (from `/opt/ros/`) was compiled against one OpenCV (e.g. 4.2.0), while the driver links a different one (e.g. 4.5.4). + +驱动能连上、数据流也激活,但一发布第一帧 RGB 就崩溃(段错误 / 堆损坏)。这与 5.9 是同一根因,出现在主机装了**两个 OpenCV 版本**时:ROS 的 `cv_bridge`(来自 `/opt/ros/`)是针对某个 OpenCV(如 4.2.0)编译的,而驱动链接了另一个(如 4.5.4)。 + +**Reason / 原因** + +With `sendrgb: 1`, the host decodes RGB with `cv::imdecode(...)` and publishes via `cv_bridge::toImageMsg()`. If the driver's OpenCV differs from `cv_bridge`'s, the same process loads two `libopencv_core` copies; a `cv::Mat` created by one and released by the other crosses an ABI boundary and corrupts the heap → crash on the first RGB frame. + +开启 `sendrgb: 1` 时,主机用 `cv::imdecode(...)` 解码 RGB,再经 `cv_bridge::toImageMsg()` 发布。若驱动的 OpenCV 与 `cv_bridge` 的不一致,同一进程会加载两份 `libopencv_core`;一个 `cv::Mat` 由其中一方创建、另一方释放,跨越 ABI 边界导致堆损坏 → 第一帧 RGB 到来时崩溃。 + +**Which ROS distros are affected? / 哪些 ROS 版本会受影响?** + +This is **not** specific to any one ROS version. The crash happens whenever `cv_bridge`'s OpenCV ≠ the driver's OpenCV, regardless of ROS1 or ROS2. In practice, the most common trigger is on **Jetson / embedded platforms** where NVIDIA preinstalls a different OpenCV than the one ROS apt packages were compiled against. + +这**不是**某个 ROS 版本独有的问题。只要 `cv_bridge` 的 OpenCV ≠ 驱动的 OpenCV,无论 ROS1 还是 ROS2 都会崩。实际中最常见的触发场景是 **Jetson / 嵌入式平台**,NVIDIA 预装的 OpenCV 与 ROS apt 仓库编译 `cv_bridge` 时用的版本不一致。 + +| ROS Distro | Type | vision_opencv branch | Typical system OpenCV | +|---|---|---|---| +| Kinetic (Ubuntu 16.04) | ROS1 | `kinetic` | 3.3.1 | +| Melodic (Ubuntu 18.04) | ROS1 | `melodic` | 3.2 / 3.4 | +| Noetic (Ubuntu 20.04) | ROS1 | `noetic` | 4.2.0 (apt) / 4.5.4 (Jetson) | +| Foxy (Ubuntu 20.04) | ROS2 | `foxy` | 4.2.0 | +| Galactic (Ubuntu 20.04) | ROS2 | `galactic` | 4.2.0 | +| Humble (Ubuntu 22.04) | ROS2 | `humble` | 4.5.x | +| Iron (Ubuntu 22.04) | ROS2 | `iron` | 4.5.x | +| Jazzy (Ubuntu 24.04) | ROS2 | `rolling` | 4.5.x / 4.6.x | + +> If your system has only one OpenCV and it matches `cv_bridge`'s, you will **not** hit this bug — the driver builds and runs out of the box. +> 如果系统只有一个 OpenCV 且与 `cv_bridge` 一致,你**不会**遇到此问题——驱动开箱即编即跑。 + +**Resolution / 解决方案** + +5.9 suggests purging the extra OpenCV. If you must keep multiple OpenCV versions on the system, the alternative below **rebuilds `cv_bridge` inside the workspace** against the OpenCV the driver uses, so the driver and `cv_bridge` share one OpenCV. All artifacts go into the workspace only — **the system `/opt/ros` and system OpenCV are never modified**. + +5.9 的做法是卸载多余的 OpenCV。如果你必须在系统上保留多个 OpenCV 版本,可用下面的替代方案:**在工作区内基于驱动所用的 OpenCV 重新编译 `cv_bridge`**,让驱动与 `cv_bridge` 使用同一份 OpenCV。所有产物只落在工作区内,**系统 `/opt/ros` 与系统 OpenCV 完全不会被改动**。 + +The driver's `CMakeLists.txt` reads the OpenCV version recorded in `cv_bridge-extras.cmake` and pins the driver to that exact version. It prefers a `cv_bridge` from the current workspace / a sourced overlay over the one in `/opt/ros`. If no `cv_bridge` is provided by the workspace and the exact version is unavailable, it falls back to the system default OpenCV with a warning (so a self-consistent single-OpenCV machine still builds out of the box). + +驱动的 `CMakeLists.txt` 会读取 `cv_bridge-extras.cmake` 里记录的 OpenCV 版本,并把驱动锁定到该版本;查找时优先使用当前工作区 / 已 source 的 overlay 里的 `cv_bridge`,其次才是 `/opt/ros`。若工作区未提供 `cv_bridge` 且系统缺该精确版本,则回退到系统默认 OpenCV 并给出警告(因此单一、一致 OpenCV 的机器仍可开箱即编)。 + +**Step 0 — Identify your ROS distro / 步骤零 —— 确认你的 ROS 发行版** + +```shell +echo $ROS_DISTRO +# Example output: noetic (ROS1) +# Example output: foxy (ROS2) +``` + +Use the matching branch from the table above for all commands below. The examples use `$ROS_DISTRO` as a placeholder — replace it (or export it) with your actual distro name. + +以下命令中用 `$ROS_DISTRO` 作为占位符,请替换为你的实际发行版名称(或直接 `export ROS_DISTRO=<你的发行版>`)。 + +**Step 1 — Download vision_opencv (matching your ROS distro branch) / 步骤一 —— 下载 vision_opencv(分支要与 ROS 发行版对应)** + +Clone it into the workspace `src/` next to `odin_ros_driver`. Use the branch matching your ROS distro from the table above. + +克隆到工作区 `src/` 下、与 `odin_ros_driver` 并列。分支要与你的 ROS 发行版对应(见上方表格)。 + +```shell +cd /src +git clone -b $ROS_DISTRO https://github.com/ros-perception/vision_opencv.git +``` + +> If `git clone -b $ROS_DISTRO` fails, your distro name may differ from the branch name (e.g. Jazzy → `rolling`). Check the table above and substitute the correct branch. +> 如果 `git clone -b $ROS_DISTRO` 失败,可能是发行版名与分支名不一致(如 Jazzy → `rolling`)。请对照上方表格替换为正确的分支名。 + +**Step 2 — Build cv_bridge FIRST, then build the driver / 步骤二 —— 先编 cv_bridge,再编驱动** + +**Order matters: `cv_bridge` must be built into the workspace before the driver.** The driver's `CMakeLists.txt` reads the workspace `cv_bridge-extras.cmake` at configure time to pin its OpenCV; if `cv_bridge` is not in the workspace yet, the driver only sees the system `cv_bridge` and links a mismatched OpenCV. + +**顺序很重要:必须先把 `cv_bridge` 编进工作区,再编驱动。** 驱动的 `CMakeLists.txt` 在配置阶段读取工作区的 `cv_bridge-extras.cmake` 来锁定 OpenCV;若此时工作区里还没有 `cv_bridge`,驱动只会看到系统 `cv_bridge`,从而链接到不匹配的 OpenCV。 + +**ROS1 (catkin_make):** + +```shell +# (1) Build cv_bridge into the workspace FIRST. +# 先把 cv_bridge 编进工作区。 +source /opt/ros/$ROS_DISTRO/setup.bash +cd +catkin_make -DBUILD_SYSTEM=ROS1 -DCATKIN_WHITELIST_PACKAGES="cv_bridge" -j$(nproc) + +# (2) Then build the driver. It now finds the workspace cv_bridge and pins the +# driver's OpenCV to the exact same version (do NOT clean build/devel here). +# 再编驱动。它会找到工作区的 cv_bridge 并把驱动 OpenCV 锁到同一版本(此步不要清 build/devel)。 +cd /src/odin_ros_driver/script +./build_ros.sh +``` + +> **Simplest option / 最简做法**: a single full build compiles everything in the correct dependency order automatically — `catkin_make` builds `cv_bridge` (a dependency) before the driver, so you don't have to think about ordering: +> 一条全量编译命令会**按依赖顺序自动**先编 `cv_bridge`、再编驱动,无需关心顺序: +> ```shell +> cd && catkin_make -DBUILD_SYSTEM=ROS1 -j$(nproc) +> ``` + +**ROS2 (colcon):** + +```shell +# (1) Build cv_bridge into the workspace FIRST. +# 先把 cv_bridge 编进工作区。 +source /opt/ros/$ROS_DISTRO/setup.bash +cd +colcon build --packages-select cv_bridge + +# (2) Then build the driver. Source the overlay so the driver finds the workspace cv_bridge. +# 再编驱动。先 source overlay,让驱动找到工作区的 cv_bridge。 +source /install/setup.bash +colcon build --packages-select odin_ros_driver +``` + +**Verification / 验证** + +```shell +# ROS1 +source /opt/ros/$ROS_DISTRO/setup.bash +source /devel/setup.bash +ldd /devel/lib/odin_ros_driver/host_sdk_sample | grep -iE 'cv_bridge|opencv_core' + +# ROS2 +source /opt/ros/$ROS_DISTRO/setup.bash +source /install/setup.bash +ldd /install/odin_ros_driver/lib/odin_ros_driver/host_sdk_sample | grep -iE 'cv_bridge|opencv_core' +``` + +- Before Step 2 (crash) / 步骤二之前(会崩):`libcv_bridge.so => /opt/ros/$ROS_DISTRO/lib/...`, and a mismatched `libopencv_core.so.` is mixed in / 且混入不匹配的 `libopencv_core.so.<旧版本>`。 +- After Step 2 (fixed) / 步骤二之后(已修复):`libcv_bridge.so => /...`, and all `libopencv_*` are a single consistent version / 且所有 `libopencv_*` 为同一个版本。 + +Then run the driver and confirm `/odin1/image` publishes steadily without crashing. + +随后运行驱动,确认 `/odin1/image` 稳定发布且不再崩溃。 + +> Important / 重要: run in a clean ROS environment; do not mix another ROS distro into `LD_LIBRARY_PATH` (e.g. don't source both noetic and foxy), or `cv_bridge` may resolve back to a mismatched OpenCV. +> 请在干净的 ROS 环境中运行;不要把另一个 ROS 发行版混入 `LD_LIBRARY_PATH`(如同时 source noetic 和 foxy),否则 `cv_bridge` 可能又解析回不匹配的 OpenCV。 + +## 6. Contact Information​​ + +You can contact our support through support@manifoldtech.cn + +To help diagnose the issue, please provide the following details to our FAE engineer: + +1. Current firmware version​​ +```shell +[device_version_capture]: ros_driver_version: [Version Number] +``` +2. Photos of power adapter and converter cable​​ in use. + +3. Does the issue happen occasionally or consistently? + +4. Provide images of the problem scenario. + +5. Did the troubleshooting methods in ​​Section V​​ resolve the issue? + +6. Expected timeline for issue resolution. diff --git a/sru_ws/src/odin_ros_driver/RELOCALIZATION_GUIDE.md b/sru_ws/src/odin_ros_driver/RELOCALIZATION_GUIDE.md new file mode 100644 index 0000000..e6e12c2 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/RELOCALIZATION_GUIDE.md @@ -0,0 +1,642 @@ +# Relocalization Guide / 重定位使用指南 + +This guide explains how to use the relocalization feature in Odin ROS Driver, including automatic relocalization and init position relocalization modes. + +本指南介绍如何使用 Odin ROS Driver 的重定位功能,包括自动重定位和指定初始位置重定位两种模式。 + +--- + +## Table of Contents / 目录 + +1. [Overview / 概述](#overview--概述) +2. [Prerequisites / 前提条件](#prerequisites--前提条件) +3. [Mode 1: Auto Relocalization / 自动重定位](#mode-1-auto-relocalization--自动重定位) +4. [Mode 2: Init Position Relocalization / 指定初始位置重定位](#mode-2-init-position-relocalization--指定初始位置重定位) +5. [init_pos Format / init_pos 格式说明](#init_pos-format--init_pos-格式说明) +6. [Configuration Examples / 配置示例](#configuration-examples--配置示例) +7. [Programmatic API / 编程接口](#programmatic-api--编程接口) +8. [Troubleshooting / 故障排除](#troubleshooting--故障排除) + +--- + +## Overview / 概述 + +### English + +Relocalization mode (`custom_map_mode: 2`) allows Odin to localize itself within a pre-built map. There are two approaches: + +| Mode | Description | Use Case | +|------|-------------|----------| +| **Auto Relocalization** | Algorithm automatically searches for position in the map | Starting position is unknown or within recommended range | +| **Init Position Relocalization** | User provides an initial pose estimate via `init_pos` | Starting position is known, faster convergence needed | + +### 中文 + +重定位模式(`custom_map_mode: 2`)允许 Odin 在预先构建的地图中进行自我定位。有两种方式: + +| 模式 | 描述 | 适用场景 | +|------|------|----------| +| **自动重定位** | 算法自动在地图中搜索位置 | 起始位置未知,或在推荐范围内 | +| **指定初始位置重定位** | 用户通过 `init_pos` 提供初始位姿估计 | 起始位置已知,需要更快收敛 | + +--- + +## Prerequisites / 前提条件 + +### English + +1. **Pre-built map file**: A `.bin` map file created in SLAM mode (`custom_map_mode: 1`) +2. **Map file path**: Know the absolute path to your map file +3. **Starting position**: For init position mode, know the approximate starting pose in map coordinates + +### 中文 + +1. **预构建的地图文件**:在 SLAM 模式(`custom_map_mode: 1`)下创建的 `.bin` 地图文件 +2. **地图文件路径**:知道地图文件的绝对路径 +3. **起始位置**:对于指定初始位置模式,需要知道在地图坐标系中的大致起始位姿 + +--- + +## Mode 1: Auto Relocalization / 自动重定位 + +### English + +In auto relocalization mode, the algorithm automatically searches for the device's position within the map based on current sensor observations. + +**Configuration** (`config/control_command.yaml`): + +```yaml +register_keys: + custom_map_mode: 2 + relocalization_map_abs_path: "/path/to/your/map.bin" + # custom_init_pos is NOT set or uses default [0,0,0,0,0,0,1] +``` + +**Recommended Starting Conditions**: +- Within **1 meter** of a position on the original SLAM trajectory +- Within **±10 degrees** of the original orientation +- In a visually distinctive area of the map + +**Behavior**: +1. On startup, Odin attempts to match current observations with the map +2. If successful, TF between `map` and `odom` frames is published +3. If unsuccessful, system operates in fallback SLAM mode (map saving disabled) +4. Relocalization attempts continue in background until successful + +**Tips**: +- Gently shaking or moving the device after startup can improve relocalization accuracy +- Highly distinctive scenes may allow successful matching beyond the 1m/10° range + +### 中文 + +在自动重定位模式下,算法根据当前传感器观测自动在地图中搜索设备位置。 + +**配置** (`config/control_command.yaml`): + +```yaml +register_keys: + custom_map_mode: 2 + relocalization_map_abs_path: "/path/to/your/map.bin" + # custom_init_pos 不设置或使用默认值 [0,0,0,0,0,0,1] +``` + +**推荐起始条件**: +- 距离原始 SLAM 轨迹上某点 **1 米**以内 +- 朝向与原始方向偏差在 **±10 度**以内 +- 位于地图中视觉特征明显的区域 + +**行为**: +1. 启动时,Odin 尝试将当前观测与地图匹配 +2. 如果成功,发布 `map` 和 `odom` 坐标系之间的 TF +3. 如果失败,系统进入后备 SLAM 模式(地图保存功能禁用) +4. 后台持续尝试重定位直到成功 + +**提示**: +- 启动后轻轻晃动或移动设备可以提高重定位精度 +- 在特征明显的场景中,可能在超出 1m/10° 范围时也能成功匹配 + +--- + +## Mode 2: Init Position Relocalization / 指定初始位置重定位 + +### English + +In init position relocalization mode, you provide an initial pose estimate to help the algorithm converge faster. + +**Configuration** (`config/control_command.yaml`): + +```yaml +register_keys: + custom_map_mode: 2 + relocalization_map_abs_path: "/path/to/your/map.bin" + custom_init_pos: [x, y, z, qx, qy, qz, qw] +``` + +**When to Use**: +- You know the approximate starting position (e.g., from external localization system) +- Starting position is far from the recommended 1m/10° range +- You need faster relocalization convergence +- Deploying in a fixed docking station with known pose + +**Behavior**: +1. Algorithm uses provided `init_pos` as initial pose estimate +2. Searches for matches in the vicinity of the provided position +3. Faster convergence compared to auto mode when estimate is accurate + +### 中文 + +在指定初始位置重定位模式下,您提供初始位姿估计以帮助算法更快收敛。 + +**配置** (`config/control_command.yaml`): + +```yaml +register_keys: + custom_map_mode: 2 + relocalization_map_abs_path: "/path/to/your/map.bin" + custom_init_pos: [x, y, z, qx, qy, qz, qw] +``` + +**适用场景**: +- 您知道大致的起始位置(例如,来自外部定位系统) +- 起始位置远离推荐的 1m/10° 范围 +- 需要更快的重定位收敛速度 +- 部署在已知位姿的固定充电桩 + +**行为**: +1. 算法使用提供的 `init_pos` 作为初始位姿估计 +2. 在提供位置的附近搜索匹配 +3. 当估计准确时,比自动模式收敛更快 + +--- + +## init_pos Format / init_pos 格式说明 + +### English + +`init_pos` is an array of **7 float values** representing position and orientation: + +```yaml +custom_init_pos: [x, y, z, qx, qy, qz, qw] +``` + +| Index | Parameter | Description | Unit | +|-------|-----------|-------------|------| +| 0 | x | X position in map frame | meters | +| 1 | y | Y position in map frame | meters | +| 2 | z | Z position in map frame | meters | +| 3 | qx | Quaternion X component | - | +| 4 | qy | Quaternion Y component | - | +| 5 | qz | Quaternion Z component | - | +| 6 | qw | Quaternion W component | - | + +**Important Notes**: +- The quaternion must be normalized: `sqrt(qx² + qy² + qz² + qw²) ≈ 1.0` +- Coordinates are relative to the **map frame** (world frame at SLAM start) +- Default value `[0, 0, 0, 0, 0, 0, 1]` represents origin with no rotation + +**Common Quaternion Values**: + +| Orientation | qx | qy | qz | qw | +|-------------|----|----|----|----| +| No rotation (identity) | 0 | 0 | 0 | 1 | +| 90° around Z-axis | 0 | 0 | 0.707 | 0.707 | +| 180° around Z-axis | 0 | 0 | 1 | 0 | +| -90° around Z-axis | 0 | 0 | -0.707 | 0.707 | + +### 中文 + +`init_pos` 是一个包含 **7 个 float 值**的数组,表示位置和朝向: + +```yaml +custom_init_pos: [x, y, z, qx, qy, qz, qw] +``` + +| 索引 | 参数 | 描述 | 单位 | +|------|------|------|------| +| 0 | x | 地图坐标系中的 X 位置 | 米 | +| 1 | y | 地图坐标系中的 Y 位置 | 米 | +| 2 | z | 地图坐标系中的 Z 位置 | 米 | +| 3 | qx | 四元数 X 分量 | - | +| 4 | qy | 四元数 Y 分量 | - | +| 5 | qz | 四元数 Z 分量 | - | +| 6 | qw | 四元数 W 分量 | - | + +**重要说明**: +- 四元数必须归一化:`sqrt(qx² + qy² + qz² + qw²) ≈ 1.0` +- 坐标相对于**地图坐标系**(SLAM 启动时的世界坐标系) +- 默认值 `[0, 0, 0, 0, 0, 0, 1]` 表示原点且无旋转 + +**常用四元数值**: + +| 朝向 | qx | qy | qz | qw | +|------|----|----|----|----| +| 无旋转(单位四元数) | 0 | 0 | 0 | 1 | +| 绕 Z 轴旋转 90° | 0 | 0 | 0.707 | 0.707 | +| 绕 Z 轴旋转 180° | 0 | 0 | 1 | 0 | +| 绕 Z 轴旋转 -90° | 0 | 0 | -0.707 | 0.707 | + +--- + +## Configuration Examples / 配置示例 + +### Example 1: Auto Relocalization / 自动重定位示例 + +```yaml +register_keys: + custom_map_mode: 2 + relocalization_map_abs_path: "/home/user/maps/office_map.bin" +``` + +### Example 2: Init Position at Origin / 在原点指定初始位置 + +```yaml +register_keys: + custom_map_mode: 2 + relocalization_map_abs_path: "/home/user/maps/office_map.bin" + custom_init_pos: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] +``` + +### Example 3: Init Position with Offset / 带偏移的初始位置 + +Position at (5.2, -3.1, 0) with 90° rotation around Z-axis: + +位置在 (5.2, -3.1, 0),绕 Z 轴旋转 90°: + +```yaml +register_keys: + custom_map_mode: 2 + relocalization_map_abs_path: "/home/user/maps/warehouse_map.bin" + custom_init_pos: [5.2, -3.1, 0.0, 0.0, 0.0, 0.707, 0.707] +``` + +### Example 4: Docking Station Pose / 充电桩位置 + +Known docking station at (10.5, 2.3, 0) facing -X direction (180° rotation): + +已知充电桩位置在 (10.5, 2.3, 0),朝向 -X 方向(旋转 180°): + +```yaml +register_keys: + custom_map_mode: 2 + relocalization_map_abs_path: "/home/user/maps/factory_map.bin" + custom_init_pos: [10.5, 2.3, 0.0, 0.0, 0.0, 1.0, 0.0] +``` + +--- + +## Programmatic API / 编程接口 + +### English + +You can also set `init_pos` programmatically using the `lidar_set_custom_parameter` API. This is useful for: +- Dynamic relocalization during runtime +- Integration with external localization systems +- Setting initial pose from robot's last known position + +#### API Function + +```cpp +#include "lidar_api.h" + +/** + * @brief Set a custom parameter on the device + * @param device Device handle obtained from lidar_open_device() + * @param param_name Parameter name (e.g., "init_pos") + * @param value_data Pointer to the parameter data + * @param value_length Size of the data in bytes + * @return 0 on success, -1 on error, -2 if file transfer in progress + */ +int lidar_set_custom_parameter(device_handle device, + const char* param_name, + const void* value_data, + size_t value_length); +``` + +#### Complete Example + +```cpp +#include "lidar_api.h" +#include +#include + +// Helper function to create quaternion from yaw angle (rotation around Z-axis) +void yaw_to_quaternion(float yaw_rad, float* qx, float* qy, float* qz, float* qw) { + *qx = 0.0f; + *qy = 0.0f; + *qz = sinf(yaw_rad / 2.0f); + *qw = cosf(yaw_rad / 2.0f); +} + +int set_init_position(device_handle device, + float x, float y, float z, + float qx, float qy, float qz, float qw) { + // init_pos format: [x, y, z, qx, qy, qz, qw] - 7 floats + float init_pos[7] = {x, y, z, qx, qy, qz, qw}; + + int result = lidar_set_custom_parameter( + device, + "init_pos", // Parameter name + init_pos, // Data pointer + sizeof(init_pos) // 7 * sizeof(float) = 28 bytes + ); + + if (result == 0) { + printf("Successfully set init_pos: [%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f]\n", + x, y, z, qx, qy, qz, qw); + } else { + printf("Failed to set init_pos, error code: %d\n", result); + } + + return result; +} + +// Usage examples: + +// Example 1: Set position at origin with no rotation +void example_origin(device_handle device) { + set_init_position(device, + 0.0f, 0.0f, 0.0f, // x, y, z + 0.0f, 0.0f, 0.0f, 1.0f // qx, qy, qz, qw (identity) + ); +} + +// Example 2: Set position with 90° yaw rotation +void example_with_rotation(device_handle device) { + float qx, qy, qz, qw; + float yaw_degrees = 90.0f; + float yaw_rad = yaw_degrees * M_PI / 180.0f; + + yaw_to_quaternion(yaw_rad, &qx, &qy, &qz, &qw); + + set_init_position(device, + 5.2f, -3.1f, 0.0f, // x, y, z + qx, qy, qz, qw // quaternion from yaw + ); +} + +// Example 3: Set position from external localization system +void example_from_external_localization(device_handle device, + double ext_x, double ext_y, double ext_yaw) { + float qx, qy, qz, qw; + yaw_to_quaternion((float)ext_yaw, &qx, &qy, &qz, &qw); + + set_init_position(device, + (float)ext_x, (float)ext_y, 0.0f, + qx, qy, qz, qw + ); +} +``` + +#### ROS Integration Example + +```cpp +#include "lidar_api.h" +#include // ROS1 +// or +#include // ROS2 + +// Callback for /initialpose topic (from RViz "2D Pose Estimate" tool) +void initialPoseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg, + device_handle device) { + float init_pos[7] = { + (float)msg->pose.pose.position.x, + (float)msg->pose.pose.position.y, + (float)msg->pose.pose.position.z, + (float)msg->pose.pose.orientation.x, + (float)msg->pose.pose.orientation.y, + (float)msg->pose.pose.orientation.z, + (float)msg->pose.pose.orientation.w + }; + + int result = lidar_set_custom_parameter(device, "init_pos", init_pos, sizeof(init_pos)); + + if (result == 0) { + ROS_INFO("Set init_pos from RViz: [%.2f, %.2f, %.2f]", + init_pos[0], init_pos[1], init_pos[2]); + } else { + ROS_ERROR("Failed to set init_pos: %d", result); + } +} +``` + +#### Important Notes + +1. **Call timing**: Set `init_pos` **before** starting the stream with `lidar_start_stream()` +2. **Map mode**: Ensure `custom_map_mode` is set to `2` (relocalization mode) +3. **Map file**: The relocalization map must be set via `lidar_set_relocalization_map()` or YAML config +4. **Thread safety**: `lidar_set_custom_parameter` is thread-safe but blocks until response received + +### 中文 + +您也可以使用 `lidar_set_custom_parameter` API 以编程方式设置 `init_pos`。适用于: +- 运行时动态重定位 +- 与外部定位系统集成 +- 从机器人上次已知位置设置初始位姿 + +#### API 函数 + +```cpp +#include "lidar_api.h" + +/** + * @brief 在设备上设置自定义参数 + * @param device 从 lidar_open_device() 获取的设备句柄 + * @param param_name 参数名称(如 "init_pos") + * @param value_data 指向参数数据的指针 + * @param value_length 数据大小(字节) + * @return 成功返回 0,错误返回 -1,文件传输中返回 -2 + */ +int lidar_set_custom_parameter(device_handle device, + const char* param_name, + const void* value_data, + size_t value_length); +``` + +#### 完整示例 + +```cpp +#include "lidar_api.h" +#include +#include + +// 辅助函数:从偏航角(绕 Z 轴旋转)创建四元数 +void yaw_to_quaternion(float yaw_rad, float* qx, float* qy, float* qz, float* qw) { + *qx = 0.0f; + *qy = 0.0f; + *qz = sinf(yaw_rad / 2.0f); + *qw = cosf(yaw_rad / 2.0f); +} + +int set_init_position(device_handle device, + float x, float y, float z, + float qx, float qy, float qz, float qw) { + // init_pos 格式: [x, y, z, qx, qy, qz, qw] - 7 个 float + float init_pos[7] = {x, y, z, qx, qy, qz, qw}; + + int result = lidar_set_custom_parameter( + device, + "init_pos", // 参数名 + init_pos, // 数据指针 + sizeof(init_pos) // 7 * sizeof(float) = 28 字节 + ); + + if (result == 0) { + printf("成功设置 init_pos: [%.3f, %.3f, %.3f, %.3f, %.3f, %.3f, %.3f]\n", + x, y, z, qx, qy, qz, qw); + } else { + printf("设置 init_pos 失败,错误码: %d\n", result); + } + + return result; +} + +// 使用示例: + +// 示例 1:在原点设置位置,无旋转 +void example_origin(device_handle device) { + set_init_position(device, + 0.0f, 0.0f, 0.0f, // x, y, z + 0.0f, 0.0f, 0.0f, 1.0f // qx, qy, qz, qw(单位四元数) + ); +} + +// 示例 2:设置带 90° 偏航旋转的位置 +void example_with_rotation(device_handle device) { + float qx, qy, qz, qw; + float yaw_degrees = 90.0f; + float yaw_rad = yaw_degrees * M_PI / 180.0f; + + yaw_to_quaternion(yaw_rad, &qx, &qy, &qz, &qw); + + set_init_position(device, + 5.2f, -3.1f, 0.0f, // x, y, z + qx, qy, qz, qw // 从偏航角计算的四元数 + ); +} + +// 示例 3:从外部定位系统设置位置 +void example_from_external_localization(device_handle device, + double ext_x, double ext_y, double ext_yaw) { + float qx, qy, qz, qw; + yaw_to_quaternion((float)ext_yaw, &qx, &qy, &qz, &qw); + + set_init_position(device, + (float)ext_x, (float)ext_y, 0.0f, + qx, qy, qz, qw + ); +} +``` + +#### ROS 集成示例 + +```cpp +#include "lidar_api.h" +#include // ROS1 +// 或 +#include // ROS2 + +// /initialpose 话题的回调函数(来自 RViz 的 "2D Pose Estimate" 工具) +void initialPoseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msg, + device_handle device) { + float init_pos[7] = { + (float)msg->pose.pose.position.x, + (float)msg->pose.pose.position.y, + (float)msg->pose.pose.position.z, + (float)msg->pose.pose.orientation.x, + (float)msg->pose.pose.orientation.y, + (float)msg->pose.pose.orientation.z, + (float)msg->pose.pose.orientation.w + }; + + int result = lidar_set_custom_parameter(device, "init_pos", init_pos, sizeof(init_pos)); + + if (result == 0) { + ROS_INFO("从 RViz 设置 init_pos: [%.2f, %.2f, %.2f]", + init_pos[0], init_pos[1], init_pos[2]); + } else { + ROS_ERROR("设置 init_pos 失败: %d", result); + } +} +``` + +#### 重要说明 + +1. **调用时机**:在调用 `lidar_start_stream()` 启动数据流**之前**设置 `init_pos` +2. **地图模式**:确保 `custom_map_mode` 设置为 `2`(重定位模式) +3. **地图文件**:必须通过 `lidar_set_relocalization_map()` 或 YAML 配置设置重定位地图 +4. **线程安全**:`lidar_set_custom_parameter` 是线程安全的,但会阻塞直到收到响应 + +--- + +## Troubleshooting / 故障排除 + +### Relocalization Fails / 重定位失败 + +**English**: +- Ensure starting position is within recommended range (1m/10°) +- Check that the map file path is correct and file exists +- Verify the environment hasn't changed significantly since mapping +- Try gently moving the device to provide more observations + +**中文**: +- 确保起始位置在推荐范围内(1m/10°) +- 检查地图文件路径是否正确且文件存在 +- 验证环境自建图以来没有显著变化 +- 尝试轻轻移动设备以提供更多观测 + +### init_pos Not Taking Effect / init_pos 未生效 + +**English**: +- Verify `custom_map_mode` is set to `2` +- Check that `custom_init_pos` has exactly 7 values +- Ensure quaternion is normalized (sum of squares ≈ 1) +- Restart the driver after modifying configuration + +**中文**: +- 验证 `custom_map_mode` 设置为 `2` +- 检查 `custom_init_pos` 是否恰好有 7 个值 +- 确保四元数已归一化(平方和 ≈ 1) +- 修改配置后重启驱动程序 + +### TF Not Published / TF 未发布 + +**English**: +- Relocalization may still be in progress +- Check ROS logs for relocalization status messages +- System operates in fallback mode until relocalization succeeds + +**中文**: +- 重定位可能仍在进行中 +- 检查 ROS 日志中的重定位状态消息 +- 系统在重定位成功前以后备模式运行 + +### Map File Not Found / 地图文件未找到 + +**English**: +- Use absolute path (starting with `/`) +- Check file permissions +- Verify file extension is `.bin` + +**中文**: +- 使用绝对路径(以 `/` 开头) +- 检查文件权限 +- 验证文件扩展名为 `.bin` + +--- + +## Related Topics / 相关话题 + +| Topic | Description | +|-------|-------------| +| `/odin1/odometry` | Odometry in odom frame | +| `/odin1/odometry_highfreq` | High-frequency odometry | +| `/odin1/cloud_slam` | SLAM point cloud in odom frame | +| `/tf` | Transform tree (includes map→odom after successful relocalization) | + +--- + +## See Also / 参见 + +- [README.md](README.md) - Main documentation +- [config/control_command.yaml](config/control_command.yaml) - Configuration file + diff --git a/sru_ws/src/odin_ros_driver/config/control_command.yaml b/sru_ws/src/odin_ros_driver/config/control_command.yaml new file mode 100644 index 0000000..52b304f --- /dev/null +++ b/sru_ws/src/odin_ros_driver/config/control_command.yaml @@ -0,0 +1,140 @@ +register_keys: + # if off, allow connection even if usb connection is below usb 3.0 + # ATTENTION: usb 3.0 is always recommended, as advance functionality like SLAM mode requires usb 3.0 for reliable map file transfer + strict_usb3.0_check: 0 # 0: off: 1: on; + + # 0: use odin internal system time as data time stamp, typical and recommended; + # 1: use host ros time (upon receive) as data time stamp, only use if you specifically require this setup, not recommended for most users + # 2: align odin1 time to host time, timestamp is the sensor data reception time on host time axis + use_host_ros_time: 0 # Changed to 0 to use device timestamp without PTP offset correction + + streamctrl: 1 # 0: off; 1: on + + # original rgb data in jpeg format from device + sendrgbcompressed: 1 # 0: off; 1: on + + # RGB data, decoded from original jpeg data from device, bgr8 format + # Processed on host device + sendrgb: 1 # 0: off; 1: on + + # undistort rgb image processed from decoded rgb data. + # depends on sendrgb. related camera parameters can be found in ws/src/odin_ros_driver/config/calib.yaml + # Processed on host device + sendrgbundistort: 0 # 0: off; 1: on. + + # IMU data + sendimu: 1 # 0: off; 1: on + + # SDK IMU smooth sending feature + # When enabled, SDK will send IMU data at precise intervals (default 400Hz) + # using a dedicated high-priority thread to reduce jitter and timing variance + enable_imu_smooth: 0 # 0: disable SDK IMU smooth sending; 1: enable (default) + + # SDK IMU smooth sending frequency in Hz (only effective when enable_imu_smooth = 1) + imu_smooth_frequency: 400 # 1-1000 Hz, recommended 400 Hz + + # Odometry data + sendodom: 1 # 0: off; 1: on + + # TF from odom to imu. Leave it on unless you specifically need it off. + # ATTENTION: critical for rviz to show cloud_raw. + send_odom_baselink_tf: 1 # 0: off; 1: on. + + # Extra TF publish rate (Hz) for odom->imu transform. + # 0: disabled (TF only published with odom data, at actual rate) + # >0: additionally publish TF at this rate using a timer (e.g. 50 for 50Hz) + # Useful for ROS2 Jazzy where tf2 has strict timestamp lookup + tf_extra_publish_rate: 0 # 0: off; >0: rate in Hz + + # raw dtof data + senddtof: 1 # 0: off; 1: on + cloud_raw_confidence_threshold: 35 # please refer to readme for more details + + # dtof sensor frame rate. Supported values: 100 (10fps) or 145 (14.5fps) + # Higher frame rate provides smoother point cloud data but may increase data bandwidth + # Note: value is multiplied by 10 (e.g., 145 means 14.5fps) + dtof_fps: 100 # 100: 10fps; + # 145: 14.5fps + + ######################################################## + # RGB camera configuration (format, resolution, frame rate) + # RGB 摄像头配置(格式、分辨率、帧率) + # + # Applied via lidar_set_rgb_parameter() before streaming starts. + # 在数据流启动前通过 lidar_set_rgb_parameter() 下发。 + # + # ATTENTION: not all combinations are valid; invalid values will + # cause device connection failure. 无效组合会导致设备连接失败。 + # + # RGB frame rate is coupled with the DTOF frame rate, so both must + # be set to one of the matching pairs below (3 tiers supported): + # RGB 帧率与 DTOF 帧率联动,二者需按下表配对设置(支持三档): + # + # rgb_fps | dtof_fps | RGB actual rate | DTOF actual rate + # --------+----------+----------------+---------------- + # 100 | 100 | 10.264 Hz | 10.0 Hz + # 145 | 145 | 14.472 Hz | 14.5 Hz + # 290 | 100 | 28.92 Hz | 10.0 Hz + ######################################################## + + rgb_format: 1 # 0: NV12 ; 1: MJPEG(default) + rgb_width: 1600 # Image width in pixels / 图像宽度(像素) + rgb_height: 1296 # Image height in pixels / 图像高度(像素) + rgb_fps: 100 # Frame rate * 10 (300 = 30fps, 145 = 14.5fps) / 帧率×10 + + # slam cloud data + sendcloudslam: 1 # 0: off; 1: on + + # processed with raw point cloud, rgb image, and calib.yaml from device + # Processed on host device + sendcloudrender: 1 # 0: off; 1: on + + # depth completion demo, high computing resource usage. + # for more information please refer to the readme file. + # Processed on host device + senddepth: 1 # 0: off; 1: on + + # cloud reprojection demo, projects cloud_slam to camera image using odometry + # Processed on host device + sendreprojection: 0 # 0: off; 1: on + + # image overlay settings - overlays reprojected points on camera image + # Processed on host device + sendoverlay: 0 # 0: off; 1: on + overlay_reprojected_topic: "/odin1/reprojected_image" # reprojected image topic + overlay_camera_topic: "/odin1/image/undistorted" # camera image topic (undistorted) + overlay_output_topic: "/odin1/overlay_image" # output overlay image topic + overlay_alpha: 0.6 # blend alpha (0.0-1.0, higher = more reproj color) + + # record rgb, odometry, and slam cloud data as proprietary olx format for further processing in MindCloud(TM) software. + # save path: ws/src/odin_ros_driver/recorddata/{record_start_time}/ + # ATTENTION: please copy the full folder for post-processing. + recorddata: 0 # 0: off; 1: on + + # Save device runtime status info to ws/src/odin_ros_driver/log/Driver_{drvier_start_time}/Conn_{device_connection_time}/dev_status.csv + devstatuslog: 1 # 0: off; 1: on. + + save_log: 0 # 0: off; 1: on; + + # raw dtof sensor intensity data in gray format, mostly for debug purpose. + pubintensitygray: 0 # 0: off; 1: on + + showpath: 0 # 0: off; 1: on + showcamerapose: 0 # 0: off; 1: on + + custom_map_mode: 1 # 0: Odometry mode 1: SLAM mode 2: Relocalization mode + custom_init_pos: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] + custom_init_pose_search_radius: 4.0 # max position offset in meters, recommended <= 10 + custom_init_pose_max_rot_deg: 180.0 # max rotation offset in degrees, up to 180 + relocalization_map_abs_path: "" # must be set for Relocalization mode or will fail + + # To get the mapping result file, please use the set_param.sh script provided: "./set_param.sh save_map 1" + mapping_result_dest_dir: "" # "": if not specified, save to default location of {ws}/src/odin_ros_driver/map/{driver_start_time}/ + mapping_result_file_name: "" # "": if not specified, save to location above with default file name of map_{map_save_time}.bin + + # Image mask transfer settings + sendimagemask: 0 # 0: off; 1: on - transfer image mask to device on startup + image_mask_abs_path: "" # absolute path to the image mask file (e.g., /path/to/mask.png(1600x1296 resolution) + + # Algorithm reset settings + resetalgo: 0 # 0: off; 1: on - send algo_reset command to device on startup diff --git a/sru_ws/src/odin_ros_driver/config/odin_ros.rviz b/sru_ws/src/odin_ros_driver/config/odin_ros.rviz new file mode 100644 index 0000000..3e58e4a --- /dev/null +++ b/sru_ws/src/odin_ros_driver/config/odin_ros.rviz @@ -0,0 +1,438 @@ +Panels: + - Class: rviz/Displays + Help Height: 0 + Name: Displays + Property Tree Widget: + Expanded: + - /Global Options1 + - /Odometry1 + - /slam1 + - /TF1/Frames1 + Splitter Ratio: 0.4993045926094055 + Tree Height: 495 + - Class: rviz/Selection + Name: Selection + - Class: rviz/Tool Properties + Expanded: + - /2D Pose Estimate1 + - /2D Nav Goal1 + - /Publish Point1 + Name: Tool Properties + Splitter Ratio: 0.5886790156364441 + - Class: rviz/Views + Expanded: + - /Current View1 + Name: Views + Splitter Ratio: 0.5 + - Class: rviz/Time + Name: Time + SyncMode: 0 + SyncSource: Image +Preferences: + PromptSaveOnExit: true +Toolbars: + toolButtonStyle: 2 +Visualization Manager: + Class: "" + Displays: + - Alpha: 0.5 + Cell Size: 1 + Class: rviz/Grid + Color: 160; 160; 164 + Enabled: true + Line Style: + Line Width: 0.029999999329447746 + Value: Lines + Name: Grid + Normal Cell Count: 0 + Offset: + X: 0 + Y: 0 + Z: 0 + Plane: XY + Plane Cell Count: 10 + Reference Frame: + Value: true + - Class: rviz/Image + Enabled: true + Image Topic: /odin1/image + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: Image + Normalize Range: true + Queue Size: 2 + Transport Hint: raw + Unreliable: false + Value: true + - Class: rviz/Image + Enabled: false + Image Topic: /odin1/image/undistorted + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: Image_undistort + Normalize Range: true + Queue Size: 2 + Transport Hint: raw + Unreliable: false + Value: false + - Class: rviz/Image + Enabled: false + Image Topic: /odin1/reprojected_image + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: cloudslam_reprojected + Normalize Range: true + Queue Size: 2 + Transport Hint: raw + Unreliable: false + Value: false + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz/PointCloud2 + Color: 255; 255; 255 + Color Transformer: Intensity + Decay Time: 0 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Min Color: 0; 0; 0 + Name: raw + Position Transformer: XYZ + Queue Size: 10 + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Points + Topic: /odin1/cloud_raw + Unreliable: false + Use Fixed Frame: true + Use rainbow: true + Value: false + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 1.8493094444274902 + Min Value: -0.13891705870628357 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 0 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Min Color: 0; 0; 0 + Name: render + Position Transformer: XYZ + Queue Size: 10 + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Points + Topic: /odin1/cloud_render + Unreliable: false + Use Fixed Frame: true + Use rainbow: true + Value: false + - Class: rviz/Group + Displays: + - Angle Tolerance: 0.10000000149011612 + Class: rviz/Odometry + Covariance: + Orientation: + Alpha: 0.5 + Color: 255; 255; 127 + Color Style: Unique + Frame: Local + Offset: 1 + Scale: 1 + Value: true + Position: + Alpha: 0.30000001192092896 + Color: 204; 51; 204 + Scale: 1 + Value: true + Value: false + Enabled: true + Keep: 1 + Name: Odometry + Position Tolerance: 0.10000000149011612 + Queue Size: 1 + Shape: + Alpha: 1 + Axes Length: 1 + Axes Radius: 0.10000000149011612 + Color: 255; 25; 0 + Head Length: 0.30000001192092896 + Head Radius: 0.10000000149011612 + Shaft Length: 1 + Shaft Radius: 0.05000000074505806 + Value: Axes + Topic: /odin1/odometry + Unreliable: false + Value: true + - Angle Tolerance: 0.10000000149011612 + Class: rviz/Odometry + Covariance: + Orientation: + Alpha: 0.5 + Color: 255; 255; 127 + Color Style: Unique + Frame: Local + Offset: 1 + Scale: 1 + Value: true + Position: + Alpha: 0.30000001192092896 + Color: 204; 51; 204 + Scale: 1 + Value: true + Value: true + Enabled: false + Keep: 100 + Name: Odometry_high + Position Tolerance: 0.10000000149011612 + Queue Size: 10 + Shape: + Alpha: 1 + Axes Length: 1 + Axes Radius: 0.10000000149011612 + Color: 52; 101; 164 + Head Length: 0.30000001192092896 + Head Radius: 0.10000000149011612 + Shaft Length: 1 + Shaft Radius: 0.05000000074505806 + Value: Arrow + Topic: /odin1/odometry_highfreq + Unreliable: false + Value: false + - Class: rviz/MarkerArray + Enabled: false + Marker Topic: /odin1/camera_pose_visual + Name: camera_view + Namespaces: + {} + Queue Size: 100 + Value: false + Enabled: true + Name: Odometry + - Class: rviz/Group + Displays: + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: rgb + Class: rviz/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 0 + Enabled: true + Invert Rainbow: false + Max Color: 255; 255; 255 + Min Color: 0; 0; 0 + Name: slam_current + Position Transformer: XYZ + Queue Size: 10 + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Points + Topic: /odin1/cloud_slam + Unreliable: false + Use Fixed Frame: true + Use rainbow: true + Value: true + - Alpha: 0.10000000149011612 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 5 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Min Color: 0; 0; 0 + Name: slam_decay + Position Transformer: XYZ + Queue Size: 10 + Selectable: true + Size (Pixels): 1 + Size (m): 0.009999999776482582 + Style: Points + Topic: /odin1/cloud_slam + Unreliable: false + Use Fixed Frame: true + Use rainbow: true + Value: false + - Class: rviz/MarkerArray + Enabled: false + Marker Topic: /odin1/path + Name: path + Namespaces: + {} + Queue Size: 100 + Value: false + Enabled: true + Name: slam + - Class: rviz/Group + Displays: + - Class: rviz/Image + Enabled: true + Image Topic: /odin1/depth_img_competetion + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: dense_depth_image + Normalize Range: true + Queue Size: 2 + Transport Hint: raw + Unreliable: false + Value: true + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 0 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Min Color: 0; 0; 0 + Name: dense_depth_cloud + Position Transformer: XYZ + Queue Size: 10 + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Points + Topic: /odin1/depth_img_competetion_cloud + Unreliable: false + Use Fixed Frame: true + Use rainbow: true + Value: false + Enabled: false + Name: dense_depth_demo + - Class: rviz/TF + Enabled: true + Filter (blacklist): "" + Filter (whitelist): "" + Frame Timeout: 15 + Frames: + All Enabled: true + imu: + Value: true + odom: + Value: true + Marker Alpha: 1 + Marker Scale: 1 + Name: TF + Show Arrows: true + Show Axes: true + Show Names: true + Tree: + odom: + imu: + {} + Update Interval: 0 + Value: true + Enabled: true + Global Options: + Background Color: 48; 48; 48 + Default Light: true + Fixed Frame: odom + Frame Rate: 30 + Name: root + Tools: + - Class: rviz/Interact + Hide Inactive Objects: true + - Class: rviz/MoveCamera + - Class: rviz/Select + - Class: rviz/FocusCamera + - Class: rviz/Measure + - Class: rviz/SetInitialPose + Theta std deviation: 0.2617993950843811 + Topic: /initialpose + X std deviation: 0.5 + Y std deviation: 0.5 + - Class: rviz/SetGoal + Topic: /move_base_simple/goal + - Class: rviz/PublishPoint + Single click: true + Topic: /clicked_point + Value: true + Views: + Current: + Class: rviz/Orbit + Distance: 16.25591278076172 + Enable Stereo Rendering: + Stereo Eye Separation: 0.05999999865889549 + Stereo Focal Distance: 1 + Swap Stereo Eyes: false + Value: false + Field of View: 0.7853981852531433 + Focal Point: + X: 0 + Y: 0 + Z: 0 + Focal Shape Fixed Size: false + Focal Shape Size: 0.05000000074505806 + Invert Z Axis: false + Name: Current View + Near Clip Distance: 0.009999999776482582 + Pitch: 1.010398030281067 + Target Frame: odom + Yaw: 0.8753980994224548 + Saved: ~ +Window Geometry: + Displays: + collapsed: false + Height: 1016 + Hide Left Dock: false + Hide Right Dock: false + Image: + collapsed: false + Image_undistort: + collapsed: false + QMainWindow State: 000000ff00000000fd0000000400000000000001e70000033afc020000000cfb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000b0fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003d0000022c000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d006100670065010000026f000001080000001600fffffffb0000002200640065006e00730065005f00640065007000740068005f0069006d006100670065000000047d000001730000001600fffffffb0000001e0049006d006100670065005f0075006e0064006900730074006f007200740000000568000000df0000001600fffffffb0000002a0063006c006f007500640073006c0061006d005f0072006500700072006f006a0065006300740065006400000002b2000000c50000001600ffffff000000010000015f0000033afc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003d0000033a000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000007380000005efc0100000002fb0000000800540069006d0065010000000000000738000003bc00fffffffb0000000800540069006d00650100000000000004500000000000000000000003e60000033a00000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + Selection: + collapsed: false + Time: + collapsed: false + Tool Properties: + collapsed: false + Views: + collapsed: false + Width: 1848 + X: 72 + Y: 27 + cloudslam_reprojected: + collapsed: false + dense_depth_image: + collapsed: false diff --git a/sru_ws/src/odin_ros_driver/config/odin_ros2.rviz b/sru_ws/src/odin_ros_driver/config/odin_ros2.rviz new file mode 100644 index 0000000..92368ec --- /dev/null +++ b/sru_ws/src/odin_ros_driver/config/odin_ros2.rviz @@ -0,0 +1,499 @@ +Panels: + - Class: rviz_common/Displays + Help Height: 0 + Name: Displays + Property Tree Widget: + Expanded: + - /Global Options1 + - /Status1 + - /Image1/Topic1 + - /cloudslam_reprojected1 + - /Odometry1 + - /slam1 + - /dense_depth_demo1 + Splitter Ratio: 0.5 + Tree Height: 593 + - Class: rviz_common/Selection + Name: Selection + - Class: rviz_common/Tool Properties + Expanded: + - /2D Goal Pose1 + - /Publish Point1 + Name: Tool Properties + Splitter Ratio: 0.5886790156364441 + - Class: rviz_common/Views + Expanded: + - /Current View1 + Name: Views + Splitter Ratio: 0.5 +Visualization Manager: + Class: "" + Displays: + - Alpha: 0.5 + Cell Size: 1 + Class: rviz_default_plugins/Grid + Color: 160; 160; 164 + Enabled: true + Line Style: + Line Width: 0.029999999329447746 + Value: Lines + Name: Grid + Normal Cell Count: 0 + Offset: + X: 0 + Y: 0 + Z: 0 + Plane: XY + Plane Cell Count: 10 + Reference Frame: + Value: true + - Class: rviz_default_plugins/Image + Enabled: true + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: Image + Normalize Range: true + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/image + Value: true + - Class: rviz_default_plugins/Image + Enabled: false + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: Image_undistort + Normalize Range: true + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/image/undistorted + Value: false + - Class: rviz_default_plugins/Image + Enabled: false + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: cloudslam_reprojected + Normalize Range: true + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/reprojected_image + Value: false + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz_default_plugins/PointCloud2 + Color: 255; 255; 255 + Color Transformer: Intensity + Decay Time: 0 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Max Intensity: 239 + Min Color: 0; 0; 0 + Min Intensity: 0 + Name: raw + Position Transformer: XYZ + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Points + Topic: + Depth: 5 + Durability Policy: Volatile + Filter size: 10 + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/cloud_raw + Use Fixed Frame: true + Use rainbow: true + Value: false + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 1.8730175495147705 + Min Value: -0.12252448499202728 + Value: true + Axis: Z + Channel Name: rgb + Class: rviz_default_plugins/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 0 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Max Intensity: 2.3509885615147286e-38 + Min Color: 0; 0; 0 + Min Intensity: 0 + Name: render + Position Transformer: XYZ + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Points + Topic: + Depth: 5 + Durability Policy: Volatile + Filter size: 10 + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/cloud_render + Use Fixed Frame: true + Use rainbow: true + Value: false + - Class: rviz_common/Group + Displays: + - Angle Tolerance: 0.10000000149011612 + Class: rviz_default_plugins/Odometry + Covariance: + Orientation: + Alpha: 0.5 + Color: 255; 255; 127 + Color Style: Unique + Frame: Local + Offset: 1 + Scale: 1 + Value: true + Position: + Alpha: 0.30000001192092896 + Color: 204; 51; 204 + Scale: 1 + Value: true + Value: true + Enabled: true + Keep: 1 + Name: Odometry + Position Tolerance: 0.10000000149011612 + Shape: + Alpha: 1 + Axes Length: 1 + Axes Radius: 0.10000000149011612 + Color: 255; 25; 0 + Head Length: 0.30000001192092896 + Head Radius: 0.10000000149011612 + Shaft Length: 1 + Shaft Radius: 0.05000000074505806 + Value: Axes + Topic: + Depth: 5 + Durability Policy: Volatile + Filter size: 10 + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/odometry + Value: true + - Angle Tolerance: 0.10000000149011612 + Class: rviz_default_plugins/Odometry + Covariance: + Orientation: + Alpha: 0.5 + Color: 255; 255; 127 + Color Style: Unique + Frame: Local + Offset: 1 + Scale: 1 + Value: true + Position: + Alpha: 0.30000001192092896 + Color: 204; 51; 204 + Scale: 1 + Value: true + Value: true + Enabled: false + Keep: 10 + Name: Odometry_high + Position Tolerance: 0.10000000149011612 + Shape: + Alpha: 1 + Axes Length: 1 + Axes Radius: 0.10000000149011612 + Color: 98; 160; 234 + Head Length: 0.30000001192092896 + Head Radius: 0.10000000149011612 + Shaft Length: 1 + Shaft Radius: 0.05000000074505806 + Value: Arrow + Topic: + Depth: 5 + Durability Policy: Volatile + Filter size: 10 + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/odometry_highfreq + Value: false + - Class: rviz_default_plugins/MarkerArray + Enabled: false + Name: camera_view + Namespaces: + {} + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/camera_pose_visual + Value: false + Enabled: true + Name: Odometry + - Class: rviz_common/Group + Displays: + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz_default_plugins/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 0 + Enabled: true + Invert Rainbow: false + Max Color: 255; 255; 255 + Max Intensity: 4096 + Min Color: 0; 0; 0 + Min Intensity: 0 + Name: slam_current + Position Transformer: XYZ + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Points + Topic: + Depth: 5 + Durability Policy: Volatile + Filter size: 10 + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/cloud_slam + Use Fixed Frame: true + Use rainbow: true + Value: true + - Alpha: 0.10000000149011612 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz_default_plugins/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 10 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Max Intensity: 4096 + Min Color: 0; 0; 0 + Min Intensity: 0 + Name: slam_deacy + Position Transformer: XYZ + Selectable: true + Size (Pixels): 1 + Size (m): 0.009999999776482582 + Style: Points + Topic: + Depth: 5 + Durability Policy: Volatile + Filter size: 10 + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/cloud_slam + Use Fixed Frame: true + Use rainbow: true + Value: false + - Class: rviz_default_plugins/MarkerArray + Enabled: false + Name: path + Namespaces: + {} + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/path + Value: false + Enabled: true + Name: slam + - Class: rviz_common/Group + Displays: + - Class: rviz_default_plugins/Image + Enabled: true + Max Value: 1 + Median window: 5 + Min Value: 0 + Name: dense_depth_image + Normalize Range: true + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/depth_img_competetion + Value: true + - Alpha: 1 + Autocompute Intensity Bounds: true + Autocompute Value Bounds: + Max Value: 10 + Min Value: -10 + Value: true + Axis: Z + Channel Name: intensity + Class: rviz_default_plugins/PointCloud2 + Color: 255; 255; 255 + Color Transformer: RGB8 + Decay Time: 0 + Enabled: false + Invert Rainbow: false + Max Color: 255; 255; 255 + Max Intensity: 4096 + Min Color: 0; 0; 0 + Min Intensity: 0 + Name: dense_depth_cloud + Position Transformer: XYZ + Selectable: true + Size (Pixels): 3 + Size (m): 0.009999999776482582 + Style: Flat Squares + Topic: + Depth: 5 + Durability Policy: Volatile + Filter size: 10 + History Policy: Keep Last + Reliability Policy: Reliable + Value: /odin1/depth_img_competetion_cloud + Use Fixed Frame: true + Use rainbow: true + Value: false + Enabled: false + Name: dense_depth_demo + - Class: rviz_default_plugins/TF + Enabled: true + Frame Timeout: 15 + Frames: + All Enabled: true + imu: + Value: true + odom: + Value: true + Marker Scale: 1 + Name: TF + Show Arrows: true + Show Axes: true + Show Names: false + Tree: + odom: + imu: + {} + Update Interval: 0 + Value: true + Enabled: true + Global Options: + Background Color: 48; 48; 48 + Fixed Frame: odom + Frame Rate: 30 + Name: root + Tools: + - Class: rviz_default_plugins/Interact + Hide Inactive Objects: true + - Class: rviz_default_plugins/MoveCamera + - Class: rviz_default_plugins/Select + - Class: rviz_default_plugins/FocusCamera + - Class: rviz_default_plugins/Measure + Line color: 128; 128; 0 + - Class: rviz_default_plugins/SetInitialPose + Covariance x: 0.25 + Covariance y: 0.25 + Covariance yaw: 0.06853891909122467 + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /initialpose + - Class: rviz_default_plugins/SetGoal + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /goal_pose + - Class: rviz_default_plugins/PublishPoint + Single click: true + Topic: + Depth: 5 + Durability Policy: Volatile + History Policy: Keep Last + Reliability Policy: Reliable + Value: /clicked_point + Transformation: + Current: + Class: rviz_default_plugins/TF + Value: true + Views: + Current: + Class: rviz_default_plugins/Orbit + Distance: 10.9336576461792 + Enable Stereo Rendering: + Stereo Eye Separation: 0.05999999865889549 + Stereo Focal Distance: 1 + Swap Stereo Eyes: false + Value: false + Focal Point: + X: 0.2568470537662506 + Y: 2.1451337337493896 + Z: 0.3774382472038269 + Focal Shape Fixed Size: false + Focal Shape Size: 0.05000000074505806 + Invert Z Axis: false + Name: Current View + Near Clip Distance: 0.009999999776482582 + Pitch: 0.3953983187675476 + Target Frame: odom + Value: Orbit (rviz) + Yaw: 3.230407953262329 + Saved: ~ +Window Geometry: + Displays: + collapsed: false + Height: 1016 + Hide Left Dock: false + Hide Right Dock: false + Image: + collapsed: false + Image_undistort: + collapsed: false + QMainWindow State: 000000ff00000000fd0000000400000000000001d40000039efc020000000cfb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003d0000028e000000c900fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb0000000a0049006d00610067006501000002d10000010a0000002800fffffffb0000002200640065006e00730065005f00640065007000740068005f0069006d006100670065000000023e0000007a0000002800fffffffb0000001e0049006d006100670065005f0075006e0064006900730074006f00720074000000028f0000014c0000002800fffffffb0000002a0063006c006f007500640073006c0061006d005f0072006500700072006f006a006500630074006500640000000310000000cb0000002800ffffff000000010000010f0000039efc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003d0000039e000000a400fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000004420000003efc0100000002fb0000000800540069006d00650100000000000004420000000000000000fb0000000800540069006d00650100000000000004500000000000000000000004910000039e00000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + Selection: + collapsed: false + Tool Properties: + collapsed: false + Views: + collapsed: false + Width: 1920 + X: 540 + Y: 124 + cloudslam_reprojected: + collapsed: false + dense_depth_image: + collapsed: false diff --git a/sru_ws/src/odin_ros_driver/docs/runtime_service_operations.md b/sru_ws/src/odin_ros_driver/docs/runtime_service_operations.md new file mode 100644 index 0000000..e7dab6c --- /dev/null +++ b/sru_ws/src/odin_ros_driver/docs/runtime_service_operations.md @@ -0,0 +1,167 @@ +# Runtime Service and Parameter Operations / 运行时服务与参数操作 + +This document describes how to control the Odin ROS driver at runtime through `set_param.sh` and ROS services. + +本文档说明如何通过 `set_param.sh` 命令文件和 ROS Service 在运行时控制 Odin ROS driver。 + +--- + +## 1. set_param.sh (Command File) / 命令文件 + +`set_param.sh` writes a `set ` line to `/tmp/odin_command.txt`. The driver polls this file every second and executes the command. + +`set_param.sh` 会把 `set ` 写入 `/tmp/odin_command.txt`,driver 每秒轮询该文件并执行。 + +```shell +# Save map / 保存地图 +./set_param.sh save_map 1 + +# Reset algorithm / 复位算法 +./set_param.sh algo_reset 1 + +# Unknown keys are rejected by the device with an error / 未知键会被设备拒绝并报错 +./set_param.sh map 1 # ERROR: "map" is not a valid device parameter +``` + +### Supported command parameters / 支持的命令参数 + +| Parameter / 参数 | Accepted values / 取值 | Description / 说明 | +|---|---|---| +| `save_map` | `0` or `1` | `1` triggers map saving in background; `0` sets the parameter to 0. `1` 在后台触发地图保存,`0` 设置参数为 0。 | +| `algo_reset` | `0` or `1` | Sends the `algo_reset` command to the device. 向设备发送 `algo_reset` 命令。 | +| `spad_filter` | `0` or `1` | Enables/disables the host-side SPAD crosstalk filter. 启用/禁用主机端 SPAD 串扰滤波。 | + +--- + +## 2. ROS Services / ROS 服务 + +The driver registers the following services while running. All services return `success` (bool) and `rc` (int32). Device must be connected before calling, otherwise `rc = -100` is returned. + +driver 运行期间注册以下服务。所有服务返回 `success` (bool) 和 `rc` (int32)。调用前设备必须已连接,否则返回 `rc = -100`。 + +### 2.1 AE/AWB Services / AE/AWB 服务 + +See `README.md` section `4.6` for `/odin1/get_ae`, `/odin1/get_awb`, `/odin1/set_ae`, `/odin1/set_awb`. + +AE/AWB 服务 `/odin1/get_ae`、`/odin1/get_awb`、`/odin1/set_ae`、`/odin1/set_awb` 详见 `README.md` 4.6 节。 + +### 2.2 Device Log Retrieval / 设备日志获取 + +**Service / 服务**: `/odin1/get_device_logs` +**Type / 类型**: `odin_ros_driver/srv/GetDeviceLogs` + +**Request / 请求** + +| Field | Type | Description / 说明 | +|---|---|---| +| `dest_dir` | `string` | Destination directory for the device log archive. 设备日志压缩包保存目录。 | + +**Response / 响应** + +| Field | Type | Description / 说明 | +|---|---|---| +| `success` | `bool` | `true` if `rc == 0`. 当 `rc == 0` 时为 true。 | +| `rc` | `int32` | `0`=ok, `-1`=invalid args, `-2`=transfer in progress, `-3`=timeout/stall. | + +**Usage / 调用** + +ROS2: +```bash +ros2 service call /odin1/get_device_logs odin_ros_driver/srv/GetDeviceLogs '{dest_dir: "/tmp/odin_logs"}' +``` + +ROS1: +```bash +rosservice call /odin1/get_device_logs '{dest_dir: "/tmp/odin_logs"}' +``` + +### 2.3 Save Map / 保存地图 + +**Service / 服务**: `/odin1/save_map` +**Type / 类型**: `odin_ros_driver/srv/SaveMap` + +**Request / 请求** + +| Field | Type | Description / 说明 | +|---|---|---| +| `value` | `int32` | `1` triggers map saving in background. Other values are forwarded as the `save_map` custom parameter. `1` 在后台触发地图保存,其他值转发为 `save_map` 自定义参数。 | + +**Response / 响应** + +| Field | Type | Description / 说明 | +|---|---|---| +| `success` | `bool` | `true` if the request was accepted. 请求被接受时为 true。 | +| `rc` | `int32` | `0`=ok, `-2`=another map transfer already in progress. | + +**Usage / 调用** + +ROS2: +```bash +ros2 service call /odin1/save_map odin_ros_driver/srv/SaveMap '{value: 1}' +``` + +ROS1: +```bash +rosservice call /odin1/save_map '{value: 1}' +``` + +When `value = 1`, the driver builds the output path from `mapping_result_dest_dir` and `mapping_result_file_name` in `config/control_command.yaml`, then starts a background transfer. Progress is printed in the driver log. + +`value = 1` 时,driver 根据 `config/control_command.yaml` 中的 `mapping_result_dest_dir` 和 `mapping_result_file_name` 构建输出路径,然后在后台开始传输,进度会打印在 driver 日志中。 + +### 2.4 Reset Algorithm / 复位算法 + +**Service / 服务**: `/odin1/reset_algo` +**Type / 类型**: `odin_ros_driver/srv/ResetAlgo` + +**Request / 请求** + +| Field | Type | Description / 说明 | +|---|---|---| +| `value` | `int32` | `1` sends the `algo_reset` command. `1` 发送 `algo_reset` 命令。 | + +**Response / 响应** + +| Field | Type | Description / 说明 | +|---|---|---| +| `success` | `bool` | `true` if `rc == 0`. | +| `rc` | `int32` | SDK return code from `lidar_set_custom_parameter`. `lidar_set_custom_parameter` 的返回码。 | + +**Usage / 调用** + +ROS2: +```bash +ros2 service call /odin1/reset_algo odin_ros_driver/srv/ResetAlgo '{value: 1}' +``` + +ROS1: +```bash +rosservice call /odin1/reset_algo '{value: 1}' +``` + +--- + +## 3. Return Code Convention / 返回码说明 + +All services and command-file operations share the same `rc` convention where applicable: + +| `rc` | Meaning / 含义 | +|---|---| +| `0` | Success / 成功 | +| `-1` | Invalid arguments / 参数无效 | +| `-2` | Another transfer already in progress / 另一次传输正在进行 | +| `-3` | Transfer timeout or stalled / 传输超时或卡死 | +| `-100` | Driver has not connected to the device yet / driver 尚未连接到设备 | + +--- + +## 4. Configuration Parameters / 配置参数 + +Parameters related to runtime operations in `config/control_command.yaml`: + +| Parameter / 参数 | Description / 说明 | +|---|---| +| `custom_map_mode` | `0` = Odometry, `1` = SLAM (supports `save_map`), `2` = Relocalization. `0` 里程计模式,`1` SLAM 建图模式(支持 `save_map`),`2` 重定位模式。 | +| `mapping_result_dest_dir` | Directory for saved maps. 保存地图的目录。 | +| `mapping_result_file_name` | File name for saved map. 保存地图的文件名。 | +| `relocalization_map_abs_path` | Absolute path to pre-built map for relocalization. 重定位所需的预建地图绝对路径。 | diff --git a/sru_ws/src/odin_ros_driver/include/camera_pose_visualization.h b/sru_ws/src/odin_ros_driver/include/camera_pose_visualization.h new file mode 100755 index 0000000..8317215 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/camera_pose_visualization.h @@ -0,0 +1,78 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#ifdef ROS2 +#include +#include +#include +#include +#include +#else +#include +#include +#include +#include +#include +#endif +#include +#include + +class camera_pose_visualization { + public: + std::string m_marker_ns; + + camera_pose_visualization(float r, float g, float b, float a); + + void setImageBoundaryColor(float r, float g, float b, float a = 1.0); + void setOpticalCenterConnectorColor(float r, float g, float b, float a = 1.0); + void setScale(double s); + void setLineWidth(double width); + + void add_pose(const Eigen::Vector3d& p, const Eigen::Quaterniond& q); + void reset(); + + #ifdef ROS2 + using ColorRGBA = std_msgs::msg::ColorRGBA; + using Marker = visualization_msgs::msg::Marker; + using MarkerArray = visualization_msgs::msg::MarkerArray; + using Header = std_msgs::msg::Header; + using Publisher = rclcpp::Publisher; + #else + using ColorRGBA = std_msgs::ColorRGBA; + using Marker = visualization_msgs::Marker; + using MarkerArray = visualization_msgs::MarkerArray; + using Header = std_msgs::Header; + using Publisher = ros::Publisher; + #endif + + void publish_by(Publisher& pub, const Header& header); + void add_edge(const Eigen::Vector3d& p0, const Eigen::Vector3d& p1); + void add_loopedge(const Eigen::Vector3d& p0, const Eigen::Vector3d& p1); + private: + std::vector m_markers; + ColorRGBA m_image_boundary_color; + ColorRGBA m_optical_center_connector_color; + double m_scale; + double m_line_width; + + static const Eigen::Vector3d imlt; + static const Eigen::Vector3d imlb; + static const Eigen::Vector3d imrt; + static const Eigen::Vector3d imrb; + static const Eigen::Vector3d oc ; + static const Eigen::Vector3d lt0 ; + static const Eigen::Vector3d lt1 ; + static const Eigen::Vector3d lt2 ; +}; diff --git a/sru_ws/src/odin_ros_driver/include/cloud_reprojection_ros_node.hpp b/sru_ws/src/odin_ros_driver/include/cloud_reprojection_ros_node.hpp new file mode 100644 index 0000000..8527628 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/cloud_reprojection_ros_node.hpp @@ -0,0 +1,122 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#ifdef ROS2 + #include + #include + #include + #include + #include + // cv_bridge header: ROS2 humble+ provides cv_bridge.hpp; ROS2 jazzy removes the legacy .h. + // Prefer .hpp when available, fall back to .h for older ROS distros (e.g. foxy/galactic). + #if defined(__has_include) + # if __has_include() + # include + # else + # include + # endif + #else + # include + #endif + #include + #include + #include + #include +#else + #include + #include + #include + #include + #include + #include + #include + #include + #include +#endif + +#include +#include +#include + +#include "cloud_reprojector.hpp" + +#include +#include + +#ifdef ROS2 +class CloudReprojectionRosNode : public rclcpp::Node +{ +public: + CloudReprojectionRosNode(const rclcpp::NodeOptions& options = rclcpp::NodeOptions()); + +private: + using PointCloud2 = sensor_msgs::msg::PointCloud2; + using Odometry = nav_msgs::msg::Odometry; + using Image = sensor_msgs::msg::Image; + + std::string cloud_slam_topic_; + std::string odometry_topic_; + std::string wiwc_topic_; + std::string reprojected_image_topic_; + + message_filters::Subscriber cloud_sub_; + message_filters::Subscriber odom_sub_; + message_filters::Subscriber wiwc_sub_; + + typedef message_filters::sync_policies::ApproximateTime MySyncPolicy; + typedef message_filters::Synchronizer Sync; + std::shared_ptr sync_; + + image_transport::Publisher reprojected_image_pub_; + + std::unique_ptr reprojector_; + + void loadParameters(); + void syncCallback(const PointCloud2::ConstSharedPtr& cloud_msg, + const Odometry::ConstSharedPtr& odom_msg, + const Odometry::ConstSharedPtr& wiwc_msg); +}; +#else +class CloudReprojectionRosNode +{ +public: + CloudReprojectionRosNode(ros::NodeHandle& nh, ros::NodeHandle& pnh); + +private: + ros::NodeHandle nh_, pnh_; + + std::string cloud_slam_topic_; + std::string odometry_topic_; + std::string wiwc_topic_; + std::string reprojected_image_topic_; + + message_filters::Subscriber cloud_sub_; + message_filters::Subscriber odom_sub_; + message_filters::Subscriber wiwc_sub_; + + typedef message_filters::sync_policies::ApproximateTime MySyncPolicy; + typedef message_filters::Synchronizer Sync; + std::shared_ptr sync_; + + ros::Publisher reprojected_image_pub_; + + std::unique_ptr reprojector_; + + void loadParameters(); + void syncCallback(const sensor_msgs::PointCloud2ConstPtr& cloud_msg, + const nav_msgs::OdometryConstPtr& odom_msg, + const nav_msgs::OdometryConstPtr& wiwc_msg); +}; +#endif diff --git a/sru_ws/src/odin_ros_driver/include/cloud_reprojector.hpp b/sru_ws/src/odin_ros_driver/include/cloud_reprojector.hpp new file mode 100644 index 0000000..77939fc --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/cloud_reprojector.hpp @@ -0,0 +1,86 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "polynomial_camera.hpp" + +#include + +class CloudReprojector +{ +public: + struct CameraParams + { + int image_width = 1600; + int image_height = 1296; + double A11 = 0.0, A12 = 0.0, A22 = 0.0; + double u0 = 0.0, v0 = 0.0; + double k2 = 0.0, k3 = 0.0, k4 = 0.0, k5 = 0.0, k6 = 0.0, k7 = 0.0; + }; + + struct ExtrinsicParams + { + Eigen::Matrix4d Tcl = Eigen::Matrix4d::Identity(); // camera to lidar + Eigen::Matrix4d Til = Eigen::Matrix4d::Identity(); // lidar to imu (fixed) + Eigen::Matrix4d Tic = Eigen::Matrix4d::Identity(); // camera to imu (calculated) + }; + + struct OdomPose + { + Eigen::Quaterniond orientation = Eigen::Quaterniond::Identity(); + Eigen::Vector3d position = Eigen::Vector3d::Zero(); + }; + + CloudReprojector(); + ~CloudReprojector() = default; + + bool initialize(const CameraParams& cam_params, const ExtrinsicParams& ext_params); + + cv::Mat reprojectCloud(const pcl::PointCloud& cloud_odom, + const OdomPose& odom_pose); + + void setPointRadius(int radius) { point_radius_ = radius; } + int getPointRadius() const { return point_radius_; } + + const CameraParams& getCameraParams() const { return camera_params_; } + const ExtrinsicParams& getExtrinsicParams() const { return extrinsic_params_; } + + // Update extrinsic parameters at runtime with real-time values from module + void updateExtrinsics(const Eigen::Matrix4d& Tcl, const Eigen::Matrix4d& Til) { + extrinsic_params_.Tcl = Tcl; + extrinsic_params_.Til = Til; + extrinsic_params_.Tic = calculateTic(Tcl, Til); + } + + static Eigen::Matrix4d calculateTic(const Eigen::Matrix4d& Tcl, const Eigen::Matrix4d& Til); + +private: + Eigen::Matrix4d odomPoseToMatrix(const OdomPose& odom) const; + + cv::Mat projectCloudToImage(const pcl::PointCloud& cloud_in_cam) const; + + CameraParams camera_params_; + ExtrinsicParams extrinsic_params_; + std::unique_ptr camera_model_; + + int point_radius_ = 4; + bool initialized_ = false; +}; diff --git a/sru_ws/src/odin_ros_driver/include/data_logger.h b/sru_ws/src/odin_ros_driver/include/data_logger.h new file mode 100644 index 0000000..bbf3945 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/data_logger.h @@ -0,0 +1,240 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class BinaryDataLogger { +public: + struct Options { + public: + // Number of frames per batch before flushing to disk + size_t batch_size = 20; + // Base directory to place time-stamped run directory under + // If empty, will use $ODIN_DATA_DIR or default to $HOME/OdinData + std::filesystem::path base_dir; + }; + + explicit BinaryDataLogger(const Options& opts) { + namespace fs = std::filesystem; + // Determine base dir + fs::path base = opts.base_dir; + if (base.empty()) { + const char* env_dir = std::getenv("ODIN_DATA_DIR"); + if (env_dir && *env_dir) { + base = fs::path(env_dir); + } else { + const char* home = std::getenv("HOME"); + base = home && *home ? fs::path(home) / "OdinData" : fs::current_path() / "OdinData"; + } + } + // Make timestamp folder name: YYYYMMDD_HHMMSS + auto now = std::chrono::system_clock::now(); + std::time_t t = std::chrono::system_clock::to_time_t(now); + std::tm tm{}; + #ifdef _WIN32 + localtime_s(&tm, &t); + #else + localtime_r(&t, &tm); + #endif + char buf[32]; + std::strftime(buf, sizeof(buf), "%Y%m%d_%H%M%S", &tm); + root_dir_ = base / buf; + fs::create_directories(root_dir_); + fs::create_directories(root_dir_ / "image"); + // Convert to std::string + std::string timestamp(buf); + created_at_ = timestamp; + // Compose file name + std::filesystem::path pcFile = root_dir_ / ("MT" + timestamp + ".olx"); + // Create placeholder files (device_id / firmware / algorithm filled later via update_info_file) + write_info_file_unlocked(); + write_text_file(root_dir_ / "image" / "cam_in_ex.txt", "# camera intrinsics/extrinsics TBD\n"); + + // Init writers + pose_writer_ = std::make_unique(root_dir_ / "OdinPose.bin", opts.batch_size); + cloud_writer_ = std::make_unique(pcFile, opts.batch_size); + //cloud_writer_ = std::make_unique(root_dir_ / "OdinPointCloud.olx", opts.batch_size); + image_writer_ = std::make_unique(root_dir_ / "OdinImage.bin", opts.batch_size); + roatation_writer_ = std::make_unique(root_dir_ / "OdinRotate.bin", opts.batch_size); + imu_writer_ = std::make_unique(root_dir_ / "OdinIMU.bin", opts.batch_size); + } + + ~BinaryDataLogger() { + // Ensure all writers flush on destruction + if (pose_writer_) pose_writer_->shutdown(); + if (cloud_writer_) cloud_writer_->shutdown(); + if (image_writer_) image_writer_->shutdown(); + if (roatation_writer_) roatation_writer_->shutdown(); + if (imu_writer_) imu_writer_->shutdown(); + } + + const std::filesystem::path& root_dir() const { return root_dir_; } + + // Update info.txt with device_id (SN) / firmware (SoC) / algorithm version. + // Safe to call multiple times; latest values win. + void update_info_file(const std::string& device_id, + const std::string& firmware_version, + const std::string& algorithm_version) { + std::lock_guard lk(info_mtx_); + device_id_ = device_id; + firmware_version_ = firmware_version; + algorithm_version_ = algorithm_version; + write_info_file_unlocked(); + } + + // Enqueue ready-to-write frame blobs (already formatted as per spec) + void enqueuePoseFrame(std::vector&& blob) { + if (pose_writer_) pose_writer_->enqueue(std::move(blob)); + } + void enqueuePointCloudFrame(std::vector&& blob) { + if (cloud_writer_) cloud_writer_->enqueue(std::move(blob)); + } + void enqueueImageFrame(std::vector&& blob) { + if (image_writer_) image_writer_->enqueue(std::move(blob)); + } + void enqueueRotateFrame(std::vector&& blob) { + if (roatation_writer_) roatation_writer_->enqueue(std::move(blob)); + } + void enqueueIMUFrame(std::vector&& blob) { + if (imu_writer_) imu_writer_->enqueue(std::move(blob)); + } + +private: + struct Writer { + explicit Writer(const std::filesystem::path& filepath, size_t batch) + : file_path(filepath), batch_size(batch), stop(false) { + worker = std::thread([this]() { this->run(); }); + } + ~Writer() { + shutdown(); + } + void enqueue(std::vector&& frame) { + { + std::lock_guard lk(mtx); + pending.emplace_back(std::move(frame)); + if (pending.size() >= batch_size) { + swap_pending_unlocked(); + } + } + cv.notify_one(); + } + void shutdown() { + { + std::lock_guard lk(mtx); + if (stop) return; + // Move leftovers to write buffer + if (!pending.empty()) { + swap_pending_unlocked(); + } + stop = true; + } + cv.notify_one(); + if (worker.joinable()) worker.join(); + } + private: + void swap_pending_unlocked() { + if (!pending.empty()) { + write_queue.emplace_back(std::move(pending)); + pending.clear(); + } + } + void run() { + std::ofstream out(file_path, std::ios::binary | std::ios::app); + if (!out.is_open()) { + // If file can't be opened, silently drop (or could add logging hook) + return; + } + for (;;) { + std::vector> batch; + { + std::unique_lock lk(mtx); + cv.wait(lk, [&]{ return stop || !write_queue.empty(); }); + if (!write_queue.empty()) { + batch = std::move(write_queue.front()); + write_queue.pop_front(); + } else if (stop) { + break; + } + } + if (!batch.empty()) { + for (auto& frame : batch) { + if (!frame.empty()) { + out.write(reinterpret_cast(frame.data()), static_cast(frame.size())); + } + } + out.flush(); + } + } + } + std::filesystem::path file_path; + size_t batch_size; + std::mutex mtx; + std::condition_variable cv; + std::vector> pending; // accumulate frames + std::deque>> write_queue; // queued batches + std::thread worker; + bool stop; + }; + + static void write_text_file(const std::filesystem::path& p, const std::string& content) { + std::ofstream f(p, std::ios::out | std::ios::trunc); + if (f.is_open()) { + f << content; + } + } + + // Render info.txt from current member fields. Caller must hold info_mtx_. + void write_info_file_unlocked() { + std::ostringstream oss; + oss << "device=OdinOne\n" + << "pointcloud=xyzrgbi\n"; + if (!device_id_.empty()) { + oss << "device_id=" << device_id_ << "\n"; + } + if (!firmware_version_.empty()) { + oss << "firmware_version=" << firmware_version_ << "\n"; + } + if (!algorithm_version_.empty()) { + oss << "algorithm_version=" << algorithm_version_ << "\n"; + } + oss << "created_at=" << created_at_ << "\n"; + write_text_file(root_dir_ / "image" / "info.txt", oss.str()); + } + + std::filesystem::path root_dir_; + std::string created_at_; + std::string device_id_; + std::string firmware_version_; + std::string algorithm_version_; + std::mutex info_mtx_; + std::unique_ptr pose_writer_; + std::unique_ptr cloud_writer_; + std::unique_ptr image_writer_; + std::unique_ptr roatation_writer_; + std::unique_ptr imu_writer_; +}; diff --git a/sru_ws/src/odin_ros_driver/include/depth_image_ros2_node.hpp b/sru_ws/src/odin_ros_driver/include/depth_image_ros2_node.hpp new file mode 100644 index 0000000..1cf5d92 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/depth_image_ros2_node.hpp @@ -0,0 +1,95 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +#include +// cv_bridge header: ROS2 humble+ provides cv_bridge.hpp; ROS2 jazzy removes the legacy .h. +// Prefer .hpp when available, fall back to .h for older ROS distros (e.g. foxy/galactic). +#if defined(__has_include) +# if __has_include() +# include +# else +# include +# endif +#else +# include +#endif +#include + +#include +#include +#include + +#include + +#include "pointcloud_depth_converter.hpp" + +#include +#include + +class DepthImageRos2Node : public rclcpp::Node +{ +public: + explicit DepthImageRos2Node(const rclcpp::NodeOptions & options = rclcpp::NodeOptions()); + + void initialize(); + +private: + std::string cloud_raw_topic_; + std::string color_compressed_topic_; + std::string color_raw_topic_; + std::string depth_image_topic_; + std::string depth_cloud_topic_; + + message_filters::Subscriber cloud_sub_; + message_filters::Subscriber color_compressed_sub_; + message_filters::Subscriber color_sub_; + + typedef message_filters::sync_policies::ApproximateTime< + sensor_msgs::msg::PointCloud2, + // sensor_msgs::msg::CompressedImage, + sensor_msgs::msg::Image> MySyncPolicy; + typedef message_filters::Synchronizer Sync; + std::shared_ptr sync_; + + std::shared_ptr it_; + image_transport::Publisher depth_image_pub_; + rclcpp::Publisher::SharedPtr depth_cloud_pub_; + + std::unique_ptr depth_converter_; + + + PointCloudToDepthConverter::CameraParams loadCameraParams(); + + void syncCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg, + // const sensor_msgs::msg::CompressedImage::ConstSharedPtr image_msg, + const sensor_msgs::msg::Image::ConstSharedPtr color_msg); + + + void publishDepthImage(const cv::Mat &img, + const std_msgs::msg::Header &header, + const std::string &encoding = "32FC1"); + + void publishDepthCloud(const pcl::PointCloud &colored_cloud, + const std_msgs::msg::Header &header); +}; diff --git a/sru_ws/src/odin_ros_driver/include/depth_image_ros_node.hpp b/sru_ws/src/odin_ros_driver/include/depth_image_ros_node.hpp new file mode 100644 index 0000000..fb1a816 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/depth_image_ros_node.hpp @@ -0,0 +1,83 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include + +#include "pointcloud_depth_converter.hpp" + +#include +#include + + +class DepthImageRosNode +{ +public: + DepthImageRosNode(ros::NodeHandle &nh, ros::NodeHandle &pnh); + +private: + ros::NodeHandle nh_, pnh_; + image_transport::ImageTransport it_; + + + std::string cloud_raw_topic_; + std::string color_raw_topic_; + std::string color_compressed_topic_; + std::string depth_image_topic_; + std::string depth_cloud_topic_; + + message_filters::Subscriber cloud_sub_; + message_filters::Subscriber color_sub_; + message_filters::Subscriber color_compressed_sub_; + + typedef message_filters::sync_policies::ApproximateTime MySyncPolicy; + typedef message_filters::Synchronizer Sync; + std::shared_ptr sync_; + + image_transport::Publisher depth_image_pub_; + ros::Publisher depth_cloud_pub_; + + std::unique_ptr depth_converter_; + + PointCloudToDepthConverter::CameraParams loadCameraParams(); + + + void syncCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg, + const sensor_msgs::ImageConstPtr &image_msg); + + + void publishDepthImage(const cv::Mat &img, + const std_msgs::Header &header, + const std::string &encoding = "32FC1"); + + + void publishDepthCloud(const pcl::PointCloud &colored_cloud, + const std_msgs::Header &header); +}; diff --git a/sru_ws/src/odin_ros_driver/include/host_sdk_sample.h b/sru_ws/src/odin_ros_driver/include/host_sdk_sample.h new file mode 100644 index 0000000..f162c2c --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/host_sdk_sample.h @@ -0,0 +1,2154 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// cv_bridge header: ROS2 humble+ provides cv_bridge.hpp; ROS2 jazzy removes the legacy .h. +// Prefer .hpp when available, fall back to .h for older ROS distros (e.g. foxy/galactic). +#if defined(__has_include) +# if __has_include() +# include +# else +# include +# endif +#else +# include +#endif +#include +#include +#include +#include +#include "data_logger.h" +#include "lidar_api.h" +#include "lidar_api_type.h" +#include "rawCloudRender.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "polynomial_camera.hpp" +#include "camera_pose_visualization.h" + +struct CameraParams { + int width, height; + double fx, fy, cx, cy, skew; + double k2, k3, k4, k5, k6, k7; + double p1, p2; +}; + +enum class OdometryType { + STANDARD = LIDAR_DT_SLAM_ODOMETRY, + HIGHFREQ = LIDAR_DT_SLAM_ODOMETRY_HIGHFREQ, + TRANSFORM = LIDAR_DT_SLAM_ODOMETRY_TF +}; + +#define LOG_LEVEL_NONE 0 +#define LOG_LEVEL_ERROR 1 +#define LOG_LEVEL_WARN 2 +#define LOG_LEVEL_INFO 3 +#define LOG_LEVEL_DEBUG 4 + + +extern int g_log_level; +extern int g_sendcloudrender; +extern int g_use_host_ros_time; +double get_ptp_smoothed_delay(); +double get_ptp_smoothed_offset(); +#ifdef ROS2 + + #include "rclcpp/rclcpp.hpp" + #include "std_msgs/msg/string.hpp" + #include + #include + #include "sensor_msgs/msg/image.hpp" + #include "sensor_msgs/msg/imu.hpp" + #include "sensor_msgs/msg/point_cloud2.hpp" + #include "sensor_msgs/point_cloud2_iterator.hpp" + #include + #include + #include + #include + #include + #include "tf2/LinearMath/Quaternion.h" + #include "tf2_ros/transform_broadcaster.h" + namespace ros { + using namespace rclcpp; + using namespace std_msgs::msg; + using namespace sensor_msgs::msg; + using namespace nav_msgs::msg; + using namespace visualization_msgs::msg; + using Time = builtin_interfaces::msg::Time; + } + + + #define LOG_ERROR(...) + #define LOG_WARN(...) + #define LOG_INFO(...) + #define LOG_DEBUG(...) +#else + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + namespace ros { + using namespace ::ros; + using namespace sensor_msgs; + using namespace nav_msgs; + } + + + #define LOG_ERROR(...) \ + if (g_log_level >= LOG_LEVEL_ERROR) { \ + ROS_ERROR(__VA_ARGS__); \ + } + #define LOG_WARN(...) \ + if (g_log_level >= LOG_LEVEL_WARN) { \ + ROS_WARN(__VA_ARGS__); \ + } + #define LOG_INFO(...) \ + if (g_log_level >= LOG_LEVEL_INFO) { \ + ROS_INFO(__VA_ARGS__); \ + } + #define LOG_DEBUG(...) \ + if (g_log_level >= LOG_LEVEL_DEBUG) { \ + ROS_DEBUG(__VA_ARGS__); \ + } +#endif + + +#ifdef ROS2 + namespace sensor_msgs { + using PointField = msg::PointField; + } +#else + namespace sensor_msgs { + using PointField = ::sensor_msgs::PointField; + } +#endif + +// Common definitions +#define PAI 3.14159265358979323846 +#define DTOF_NUM_ROW_PER_GROUP 6 +// Common functions +inline ros::Time ns_to_ros_time(uint64_t timestamp_ns) { + ros::Time t; + #ifdef ROS2 + t.sec = static_cast(timestamp_ns / 1000000000); + t.nanosec = static_cast(timestamp_ns % 1000000000); + #else + t.sec = static_cast(timestamp_ns / 1000000000); + t.nsec = static_cast(timestamp_ns % 1000000000); + #endif + return t; +} + +inline uint64_t ros_time_to_ns(const ros::Time &t) { + #ifdef ROS2 + return static_cast(t.sec) * 1000000000ULL + t.nanosec; + #else + return static_cast(t.sec) * 1000000000ULL + t.nsec; + #endif +} + +// Compute an "aligned" nanosecond timestamp for offline recording (recorddata files). +// Mirrors the policy used by make_aligned_stamp() so that recorded timestamps stay +// consistent with the timestamps that are published over ROS topics. +// g_use_host_ros_time == 0 : raw sensor timestamp (odin1 boot time, no alignment) +// g_use_host_ros_time == 1 : host wall-clock now (NTP-synced if the host is NTP-synced) +// g_use_host_ros_time == 2 : sensor timestamp aligned via smoothed PTP offset (NTP/PTP mode) +// +// g_use_host_ros_time == 0 : +// g_use_host_ros_time == 1 : +// g_use_host_ros_time == 2 : +inline uint64_t aligned_stamp_ns(uint64_t sensor_timestamp_ns) { + if (g_use_host_ros_time == 1) { + const auto now = std::chrono::system_clock::now().time_since_epoch(); + return static_cast( + std::chrono::duration_cast(now).count()); + } + if (g_use_host_ros_time == 2) { + const double offset_s = get_ptp_smoothed_offset(); + const int64_t offset_ns = static_cast(offset_s * 1e9); + const int64_t base_ns = static_cast(sensor_timestamp_ns); + const int64_t aligned_ns = base_ns - offset_ns; + return (aligned_ns < 0) ? 0ULL : static_cast(aligned_ns); + } + return sensor_timestamp_ns; +} + +inline ros::Time make_aligned_stamp(uint64_t sensor_timestamp_ns +#ifdef ROS2 + , const rclcpp::Node::SharedPtr& node +#endif + ) { + if (g_use_host_ros_time == 1) { + #ifdef ROS2 + return node->now(); + #else + return ros::Time::now(); + #endif + } + + uint64_t ts_ns = sensor_timestamp_ns; + if (g_use_host_ros_time == 2) { + const double offset_s = get_ptp_smoothed_offset(); + const int64_t offset_ns = static_cast(offset_s * 1e9); + const int64_t base_ns = static_cast(sensor_timestamp_ns); + const int64_t aligned_ns = base_ns - offset_ns; + ts_ns = (aligned_ns < 0) ? 0ULL : static_cast(aligned_ns); + } + + return ns_to_ros_time(ts_ns); +} + +class RosNodeControlInterface { + public: + virtual ~RosNodeControlInterface() = default; + virtual void setDtofSubframeODR(int odr) = 0; + virtual int getDtofSubframeODR() const = 0; + virtual void setSendOdomBaseLinkTF(bool send_odom_baselink_tf) = 0; + virtual bool sendOdomBaseLinkTF() const = 0; + virtual void setCloudRawConfidenceThreshold(int threshold) = 0; + virtual int cloudRawConfidenceThreshold() const = 0; + virtual void setTfExtraPublishRate(int rate_hz) = 0; + virtual int getTfExtraPublishRate() const = 0; + }; + +RosNodeControlInterface* getRosNodeControl(); + +// Multi-sensor publisher class +class MultiSensorPublisher { +public: + #ifdef ROS2 + MultiSensorPublisher(rclcpp::Node::SharedPtr node) + : node_(node),cameraposevisual_ {1.0f, 0.0f, 0.0f, 1.0f} { + initialize_publishers(); + // initialize_data_logger(); + } + #else + MultiSensorPublisher(ros::NodeHandle& nh) + : cameraposevisual_(1.0f, 0.0f, 0.0f, 1.0f) { + initialize_publishers(nh); + // initialize_data_logger(); + } + #endif + + std::filesystem::path get_root_dir() const { return root_dir_; } + + void set_log_level(int level) { + g_log_level = level; + } + // Optional external logger setter + void set_data_logger(std::shared_ptr logger) { + data_logger_ = std::move(logger); + } + + // Forward device identity / version metadata into the binary data logger's info.txt. + // No-op if logger is not initialized (e.g. recorddata=0). + void update_data_logger_info(const std::string& device_id, + const std::string& firmware_version, + const std::string& algorithm_version) { + if (data_logger_) { + data_logger_->update_info_file(device_id, firmware_version, algorithm_version); + } + } + + int get_pose_index() { + return pose_index_.load(); + } + + int get_cloud_index() { + return cloud_index_.load(); + } + + int get_image_index() { + return image_index_.load(); + } + + int get_wcwi_index() { + return wcwi_index_.load(); + } + + rawCloudRender render_; + void publishImu(imu_convert_data_t *stream) { + #ifdef ROS2 + sensor_msgs::msg::Imu imu_msg; + #else + ros::Imu imu_msg; + #endif + + #ifdef ROS2 + imu_msg.header.stamp = make_aligned_stamp(stream->stamp, node_); + #else + imu_msg.header.stamp = make_aligned_stamp(stream->stamp); + #endif + imu_msg.header.frame_id = "imu"; + + imu_msg.linear_acceleration.y = -1 * stream->accel_x; + imu_msg.linear_acceleration.x = stream->accel_y; + imu_msg.linear_acceleration.z = stream->accel_z; + + imu_msg.angular_velocity.y = -1 * stream->gyro_x; + imu_msg.angular_velocity.x = stream->gyro_y; + imu_msg.angular_velocity.z = stream->gyro_z; + + imu_msg.orientation.x = 0.0; + imu_msg.orientation.y = 0.0; + imu_msg.orientation.z = 0.0; + imu_msg.orientation.w = 1.0; + + #ifdef ROS2 + imu_pub_->publish(std::move(imu_msg)); + #else + imu_pub_.publish(imu_msg); + #endif + + if(data_logger_) { + // Align IMU timestamp with the same policy as ROS publish path + const double ts_sec = static_cast(aligned_stamp_ns(stream->stamp)) / 1e9; + float ax = imu_msg.linear_acceleration.x; + float ay = imu_msg.linear_acceleration.y; + float az = imu_msg.linear_acceleration.z; + float wx = imu_msg.angular_velocity.x; + float wy = imu_msg.angular_velocity.y; + float wz = imu_msg.angular_velocity.z; + + std::vector blob; + blob.reserve(sizeof(double) + sizeof(float) * 6); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(ts_sec); + append_pod(ax); + append_pod(ay); + append_pod(az); + append_pod(wx); + append_pod(wy); + append_pod(wz); + data_logger_->enqueueIMUFrame(std::move(blob)); + } + } +#ifdef ROS2 + using ImageMsg = sensor_msgs::msg::Image; + using PointCloud2Msg = sensor_msgs::msg::PointCloud2; + using ImageConstPtr = ImageMsg::ConstSharedPtr; + using PointCloud2ConstPtr = PointCloud2Msg::ConstSharedPtr; +#else + using ImageMsg = sensor_msgs::Image; + using PointCloud2Msg = sensor_msgs::PointCloud2; + using ImageConstPtr = sensor_msgs::ImageConstPtr; + using PointCloud2ConstPtr = sensor_msgs::PointCloud2ConstPtr; +#endif +void try_process_pair() { + // Record queue status + size_t rgb_size, pcd_size; + { + std::lock_guard lock1(rgb_queue_mutex_); + std::lock_guard lock2(pcd_queue_mutex_); + rgb_size = rgb_image_queue_.size(); + pcd_size = pcd_queue_.size(); + } + + while (true) { + ImageConstPtr rgb_msg = nullptr; + PointCloud2ConstPtr pcd_msg = nullptr; + + // Get a pair of data from queues (with lock protection) + { + std::lock_guard lock1(rgb_queue_mutex_); + std::lock_guard lock2(pcd_queue_mutex_); + + if (!rgb_image_queue_.empty() && !pcd_queue_.empty()) { + rgb_msg = rgb_image_queue_.front(); + pcd_msg = pcd_queue_.front(); + } + } + + if (!rgb_msg || !pcd_msg) { + break; + } + + // timestamp + uint64_t rgb_stamp = ros_time_to_ns(rgb_msg->header.stamp); + uint64_t pcd_stamp = ros_time_to_ns(pcd_msg->header.stamp); + int64_t time_diff = static_cast(rgb_stamp) - static_cast(pcd_stamp); + int64_t abs_time_diff = std::abs(time_diff); + + // Check if time difference is within allowed range (50ms) + const int64_t MAX_TIME_DIFF = 50000000; // 50ms in nanoseconds + if (abs_time_diff > MAX_TIME_DIFF) { + // Remove older timestamped message + { + std::lock_guard lock1(rgb_queue_mutex_); + std::lock_guard lock2(pcd_queue_mutex_); + + if (time_diff > 0) { + // RGB timestamp is newer, remove PCD + pcd_queue_.pop_front(); + } else { + // PCD timestamp is newer, remove RGB + rgb_image_queue_.pop_front(); + } + } + + // Try next pair + continue; + } + + // Time difference within allowed range, process data pair + { + std::lock_guard lock1(rgb_queue_mutex_); + std::lock_guard lock2(pcd_queue_mutex_); + + // Remove messages from queues + rgb_image_queue_.pop_front(); + pcd_queue_.pop_front(); + } + + // Process data pair + process_pair(rgb_msg, pcd_msg); + } +} +bool validate_render_parameters(std::vector>& rgb_image, + capture_Image_List_t* cloud_stream, + int pcd_idx) +{ + // 1. Check RGB image validity + if (rgb_image.empty()) { + #ifndef ROS2 + ROS_ERROR("Invalid RGB image: empty vector"); + #endif + return false; + } + + // Check RGB image dimension consistency + const size_t height = rgb_image.size(); + const size_t width = (height > 0) ? rgb_image[0].size() : 0; + + if (height == 0 || width == 0) { + #ifndef ROS2 + ROS_ERROR("Invalid RGB image dimensions: %zux%zu", + height, width); + #endif + return false; + } + + // 2. Check point cloud stream pointer validity + if (!cloud_stream) { + #ifndef ROS2 + ROS_ERROR("Invalid cloud stream: null pointer"); + #endif + return false; + } + + // 3. Check point cloud index validity + if (pcd_idx < 0 || pcd_idx >= 10) { + #ifndef ROS2 + ROS_ERROR("Invalid pcd index: %d (must be 0-9)", pcd_idx); + #endif + return false; + } + + // 4. Check point cloud data validity + buffer_List_t& cloud = cloud_stream->imageList[pcd_idx]; + if (!cloud.pAddr) { + #ifndef ROS2 + ROS_ERROR("Invalid cloud data: null pointer"); + #endif + return false; + } + + if (cloud.width <= 0 || cloud.height <= 0) { + #ifndef ROS2 + ROS_ERROR("Invalid cloud dimensions: %dx%d", + cloud.width, cloud.height); + #endif + return false; + } + + return true; +} + +void process_pair(const ImageConstPtr &rgb_msg, const PointCloud2ConstPtr &pcd_msg) +{ + auto start_time = std::chrono::steady_clock::now(); + + const int input_image_width = rgb_msg->width; + const int input_image_height = rgb_msg->height; + + // Verify input image format + if (rgb_msg->encoding != "bgr8") { + #ifndef ROS2 + ROS_ERROR("Unsupported image format: %s. Only bgr8 is supported.", + rgb_msg->encoding.c_str()); + #endif + return; + } + + // Prepare point cloud data stream + capture_Image_List_t cloud_stream; + const int pcd_idx = 2; + cloud_stream.imageList[pcd_idx].height = pcd_msg->height; + cloud_stream.imageList[pcd_idx].width = pcd_msg->width; + + const auto total_point_num = pcd_msg->width * pcd_msg->height; + sensor_msgs::PointCloud2ConstIterator iter_x(*pcd_msg, "x"); + sensor_msgs::PointCloud2ConstIterator iter_y(*pcd_msg, "y"); + sensor_msgs::PointCloud2ConstIterator iter_z(*pcd_msg, "z"); + std::vector cloud_flat; + cloud_flat.reserve(total_point_num * 4); + + for (; iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z) { + cloud_flat.push_back(*iter_y * -1000.0f); + cloud_flat.push_back(*iter_z * 1000.0f); + cloud_flat.push_back(*iter_x * 1000.0f); + cloud_flat.push_back(0.0f); + } + cloud_stream.imageList[pcd_idx].pAddr = cloud_flat.data(); + + + if (input_image_height > 0 && input_image_width > 0) { + // Use BGR8 image data directly + std::vector> rgb_image(input_image_height, std::vector(input_image_width)); + + // Convert BGR8 data to required format for rendering + const uint8_t* bgr_data = rgb_msg->data.data(); + for (int y = 0; y < input_image_height; ++y) { + for (int x = 0; x < input_image_width; ++x) { + // Start position of each pixel (BGR format) + int idx = y * rgb_msg->step + x * 3; + + // Extract RGB values and combine into 32-bit integer + uint8_t b = bgr_data[idx]; + uint8_t g = bgr_data[idx + 1]; + uint8_t r = bgr_data[idx + 2]; + uint32_t rgb_int = (r << 16) | (g << 8) | b; + + // Convert to float + float rgb_float; + std::memcpy(&rgb_float, &rgb_int, sizeof(float)); + rgb_image[y][x] = rgb_float; + } + } + // Render colored point cloud + std::vector rgbCloud_flat; + render_.render(rgb_image, &cloud_stream, pcd_idx, rgbCloud_flat); + const int valid_point_num = rgbCloud_flat.size() / 4; + + // Create and publish RGB point cloud + PointCloud2Msg output_msg; + output_msg.header.frame_id = "lidar"; + output_msg.header.stamp = rgb_msg->header.stamp; // Use original image timestamp + output_msg.height = 1; + output_msg.width = valid_point_num; + + sensor_msgs::PointCloud2Modifier modifier(output_msg); + modifier.setPointCloud2Fields( + 4, + "x", 1, sensor_msgs::PointField::FLOAT32, + "y", 1, sensor_msgs::PointField::FLOAT32, + "z", 1, sensor_msgs::PointField::FLOAT32, + "rgb", 1, sensor_msgs::PointField::FLOAT32 + ); + modifier.resize(valid_point_num); + + sensor_msgs::PointCloud2Iterator iter_res_x(output_msg, "x"); + sensor_msgs::PointCloud2Iterator iter_res_y(output_msg, "y"); + sensor_msgs::PointCloud2Iterator iter_res_z(output_msg, "z"); + sensor_msgs::PointCloud2Iterator iter_res_rgb(output_msg, "rgb"); + + for (int i = 0; i < valid_point_num; i++) { + *iter_res_x = rgbCloud_flat[4*i]; ++iter_res_x; + *iter_res_y = rgbCloud_flat[4*i+1]; ++iter_res_y; + *iter_res_z = rgbCloud_flat[4*i+2]; ++iter_res_z; + *iter_res_rgb = rgbCloud_flat[4*i+3]; ++iter_res_rgb; + } + + #ifdef ROS2 + rgbcloud_pub_->publish(output_msg); + #else + rgbcloud_pub_.publish(output_msg); + #endif + } +} + +void publishIntensityCloud(capture_Image_List_t* stream, int idx) +{ + // Check index validity + if (idx < 0 || idx >= 10) { + #ifndef ROS2 + ROS_ERROR("Invalid index %d for intensity cloud", idx); + #endif + return; + } + + // Check point cloud data validity + buffer_List_t &cloud = stream->imageList[idx]; + if (!cloud.pAddr) { + #ifndef ROS2 + ROS_ERROR("Invalid point cloud: null data pointer at index %d", idx); + #endif + return; + } + + if (cloud.width <= 0 || cloud.height <= 0) { + #ifndef ROS2 + ROS_ERROR("Invalid point cloud dimensions: %dx%d at index %d", + cloud.width, cloud.height, idx); + #endif + return; + } + + #ifdef ROS2 + auto msg = std::make_shared(); + #else + auto msg = boost::make_shared(); + #endif + + // Set message header + msg->header.frame_id = "lidar"; + #ifdef ROS2 + msg->header.stamp = make_aligned_stamp(cloud.timestamp, node_); + #else + msg->header.stamp = make_aligned_stamp(cloud.timestamp); + #endif + + msg->height = cloud.height; + msg->width = cloud.width; + msg->is_dense = false; + msg->is_bigendian = false; + + // Set point cloud fields + sensor_msgs::PointCloud2Modifier modifier(*msg); + modifier.setPointCloud2Fields( + 6, + "x", 1, sensor_msgs::PointField::FLOAT32, + "y", 1, sensor_msgs::PointField::FLOAT32, + "z", 1, sensor_msgs::PointField::FLOAT32, + "intensity", 1, sensor_msgs::PointField::UINT8, + "confidence", 1, sensor_msgs::PointField::UINT16, + "offset_time", 1, sensor_msgs::PointField::FLOAT32 + ); + modifier.resize(msg->height * msg->width); + + + sensor_msgs::PointCloud2Iterator iter_x(*msg, "x"); + sensor_msgs::PointCloud2Iterator iter_y(*msg, "y"); + sensor_msgs::PointCloud2Iterator iter_z(*msg, "z"); + sensor_msgs::PointCloud2Iterator iter_intensity(*msg, "intensity"); + sensor_msgs::PointCloud2Iterator iter_confidence(*msg, "confidence"); + sensor_msgs::PointCloud2Iterator iter_offsettime(*msg, "offset_time"); + + float* xyz_data_f = static_cast(cloud.pAddr); + int total_points = cloud.height * cloud.width; + //std::cout << stream->imageCount << std::endl; + float dtof_subframe_odr = getRosNodeControl()->getDtofSubframeODR() / 1000.0f; + // printf("dtof_subframe_odr: %f\n", dtof_subframe_odr); + + if (stream->imageCount == 4) { + + uint8_t* intensity_data = static_cast(stream->imageList[2].pAddr); + uint16_t* confidence_data = static_cast(stream->imageList[3].pAddr); + int confidence_threshold = getRosNodeControl()->cloudRawConfidenceThreshold(); + for (int i = 0; i < total_points; ++i) { + if (confidence_data[i] < confidence_threshold) { + *iter_x = 0.0f; ++iter_x; + *iter_y = 0.0f; ++iter_y; + *iter_z = 0.0f; ++iter_z; + *iter_intensity = 0; ++iter_intensity; + *iter_confidence = 0; ++iter_confidence; + *iter_offsettime = 0.0f; ++iter_offsettime; + } else { + // XYZ point + *iter_x = xyz_data_f[i * 3 + 2] / 1000.0f; ++iter_x; + *iter_y = -xyz_data_f[i * 3 + 0] / 1000.0f; ++iter_y; + *iter_z = xyz_data_f[i * 3 + 1] / 1000.0f; ++iter_z; + + *iter_intensity = intensity_data[i]; ++iter_intensity; + *iter_confidence = confidence_data[i]; ++iter_confidence; + + if (dtof_subframe_odr > 0.0) { + int line_num = i / 256; + int group = line_num / DTOF_NUM_ROW_PER_GROUP; + float timestamp_offset = group * 1.0 / dtof_subframe_odr; + + *iter_offsettime = timestamp_offset; + ++iter_offsettime; + } + } + } + } else { + uint16_t* intensity_data = static_cast(stream->imageList[2].pAddr); + + for (int i = 0; i < total_points; ++i) { + *iter_x = xyz_data_f[i * 4 + 2] / 1000.0f; ++iter_x; + *iter_y = -xyz_data_f[i * 4 + 0] / 1000.0f; ++iter_y; + *iter_z = xyz_data_f[i * 4 + 1] / 1000.0f; ++iter_z; + + float intensity = (intensity_data[i] - 10) * 255.0f / (12500 - 10); + if (intensity > 255) { + *iter_intensity = 255; + } else if (intensity < 0) { + *iter_intensity = 0; + } else { + *iter_intensity = static_cast(intensity); + } + ++iter_intensity; + + *iter_confidence = 0; + ++iter_confidence; + } + } + + // Only cache point cloud if cloud_render is enabled + if (g_sendcloudrender) { + std::lock_guard lock(pcd_queue_mutex_); + + // Create deep copy of point cloud + #ifdef ROS2 + auto msg_copy = std::make_shared(*msg); + #else + auto msg_copy = boost::make_shared(); + *msg_copy = *msg; // Deep copy + #endif + + // Queue management + if (pcd_queue_.size() >= 10) { + pcd_queue_.pop_front(); + } + + // Add to queue (using copy) + pcd_queue_.push_back(msg_copy); + } + + // Publish point cloud + #ifdef ROS2 + cloud_pub_->publish(*msg); + #else + cloud_pub_.publish(msg); + #endif +} + +void publishGrayUInt8(capture_Image_List_t *stream, int idx) { + ImageMsg msg; + #ifdef ROS2 + msg.header.stamp = make_aligned_stamp(stream->imageList[idx].timestamp, node_); + #else + msg.header.stamp = make_aligned_stamp(stream->imageList[idx].timestamp); + #endif + msg.header.frame_id = "map"; + + int width = stream->imageList[idx].width; + int height = stream->imageList[idx].height; + + msg.height = height; + msg.width = width; + msg.encoding = "mono8"; + msg.is_bigendian = false; + msg.step = width * sizeof(uint8_t); + + size_t image_size = msg.step * height; + + msg.data.resize(image_size); + + memcpy(msg.data.data(), stream->imageList[idx].pAddr, image_size); + + #ifdef ROS2 + intensity_gray_pub_->publish(msg); + #else + intensity_gray_pub_.publish(msg); + #endif +} + +void publishRgb(capture_Image_List_t *stream) { + buffer_List_t &image = stream->imageList[0]; + + cv::Mat decoded_image; + std::vector raw_data; + + if (image.format == LIDAR_RGB_FMT_NV12) { + // NV12 format: Y plane (width*height) + interleaved UV plane (width*height/2) + // Total size = width * height * 3 / 2 + cv::Mat nv12_mat(image.height * 3 / 2, image.width, CV_8UC1, image.pAddr); + cv::cvtColor(nv12_mat, decoded_image, cv::COLOR_YUV2BGR_NV12); + + // Store raw NV12 data for logging + raw_data.assign(static_cast(image.pAddr), + static_cast(image.pAddr) + image.length); + } else { + // MJPEG format: decode JPEG data to bgr8 + std::vector jpeg_data(static_cast(image.pAddr), + static_cast(image.pAddr) + image.length); + decoded_image = cv::imdecode(jpeg_data, cv::IMREAD_COLOR); + raw_data = std::move(jpeg_data); + } + + if (decoded_image.empty()) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("publishRgb"), "Failed to decode RGB image (format=%d)", image.format); + #else + ROS_WARN("Failed to decode RGB image (format=%d)", image.format); + #endif + return; + } + + cv_bridge::CvImage cv_image; + #ifdef ROS2 + cv_image.header.stamp = make_aligned_stamp(stream->imageList[0].timestamp, node_); + #else + cv_image.header.stamp = make_aligned_stamp(stream->imageList[0].timestamp); + #endif + cv_image.encoding = "bgr8"; + cv_image.image = decoded_image; + + if (g_sendcloudrender) { + std::lock_guard lock(rgb_queue_mutex_); + if (rgb_image_queue_.size() >= 10) { + rgb_image_queue_.pop_front(); + } + rgb_image_queue_.push_back(cv_image.toImageMsg()); + } + + // Enqueue binary logging for image + if (data_logger_) { + const uint32_t idx_now = image_index_.fetch_add(1, std::memory_order_relaxed); + const double ts_sec = static_cast(aligned_stamp_ns(stream->imageList[0].timestamp)) / 1e9; + const uint32_t raw_size = static_cast(raw_data.size()); + std::vector blob; + blob.reserve(sizeof(uint32_t) + sizeof(double) + sizeof(uint32_t) + raw_size); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(idx_now); + append_pod(ts_sec); + append_pod(raw_size); + blob.insert(blob.end(), raw_data.begin(), raw_data.end()); + data_logger_->enqueueImageFrame(std::move(blob)); + } + + // undistort image + cv::Mat undistorted_image = cv::Mat::zeros(decoded_image.size(), decoded_image.type()); + cv_bridge::CvImage cv_undistorted_image; + + if (m_undistort_map_init_success) { + cv::remap(decoded_image, undistorted_image, m_undistort_map_x, m_undistort_map_y, cv::INTER_LINEAR); + #ifdef ROS2 + cv_undistorted_image.header.stamp = make_aligned_stamp(stream->imageList[0].timestamp, node_); + #else + cv_undistorted_image.header.stamp = make_aligned_stamp(stream->imageList[0].timestamp); + #endif + cv_undistorted_image.encoding = "bgr8"; + cv_undistorted_image.image = undistorted_image; + } + + #ifdef ROS2 + { + rgb_pub_->publish(*cv_image.toImageMsg()); + if (m_undistort_map_init_success) { + undistort_rgb_pub_->publish(*cv_undistorted_image.toImageMsg()); + } + + // Compressed image: MJPEG uses original JPEG data; NV12 publishes raw NV12 bytes + sensor_msgs::msg::CompressedImage compressed_msg; + compressed_msg.header.stamp = make_aligned_stamp(stream->imageList[0].timestamp, node_); + if (image.format == LIDAR_RGB_FMT_NV12) { + compressed_msg.format = "nv12"; + } else { + compressed_msg.format = "jpeg"; + } + compressed_msg.data = raw_data; + compressed_rgb_pub_->publish(compressed_msg); + } + #else + { + rgb_pub_.publish(cv_image.toImageMsg()); + if (m_undistort_map_init_success) { + undistort_rgb_pub_.publish(cv_undistorted_image.toImageMsg()); + } + + // Compressed image: MJPEG uses original JPEG data; NV12 publishes raw NV12 bytes + sensor_msgs::CompressedImagePtr compressed_msg(new sensor_msgs::CompressedImage()); + compressed_msg->header.stamp = make_aligned_stamp(stream->imageList[0].timestamp); + if (image.format == LIDAR_RGB_FMT_NV12) { + compressed_msg->format = "nv12"; + } else { + compressed_msg->format = "jpeg"; + } + compressed_msg->data = raw_data; + compressed_rgb_pub_.publish(compressed_msg); + } + #endif + +} + + + void publishPC2XYZRGBA(capture_Image_List_t* stream, int idx) + { + #ifdef ROS2 + sensor_msgs::msg::PointCloud2 msg; + msg.header.frame_id = "odom"; + msg.header.stamp = make_aligned_stamp(stream->imageList[0].timestamp, node_); + + //RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Point cloudrgba %ld",stream->imageList[0].timestamp); + + size_t pt_size = sizeof(int32_t) * 3 + sizeof(int32_t) * 4; + uint32_t points = stream->imageList[idx].length / pt_size; + + msg.height = 1; + msg.width = points; + msg.is_dense = false; + + sensor_msgs::PointCloud2Modifier modifier(msg); + modifier.setPointCloud2Fields( + 4, + "x", 1, sensor_msgs::msg::PointField::FLOAT32, + "y", 1, sensor_msgs::msg::PointField::FLOAT32, + "z", 1, sensor_msgs::msg::PointField::FLOAT32, + "rgb", 1, sensor_msgs::msg::PointField::FLOAT32 + ); + modifier.resize(msg.width * msg.height); + + sensor_msgs::PointCloud2Iterator iter_x(msg, "x"); + sensor_msgs::PointCloud2Iterator iter_y(msg, "y"); + sensor_msgs::PointCloud2Iterator iter_z(msg, "z"); + sensor_msgs::PointCloud2Iterator iter_rgb(msg, "rgb"); + #else + sensor_msgs::PointCloud2 msg; + msg.header.frame_id = "odom"; + msg.header.stamp = make_aligned_stamp(stream->imageList[0].timestamp); + + size_t pt_size = sizeof(int32_t) * 3 + sizeof(int32_t) * 4; + uint32_t points = stream->imageList[idx].length / pt_size; + + msg.height = 1; + msg.width = points; + msg.is_dense = false; + + sensor_msgs::PointCloud2Modifier modifier(msg); + modifier.setPointCloud2Fields( + 4, + "x", 1, sensor_msgs::PointField::FLOAT32, + "y", 1, sensor_msgs::PointField::FLOAT32, + "z", 1, sensor_msgs::PointField::FLOAT32, + "rgb", 1, sensor_msgs::PointField::FLOAT32 + ); + modifier.resize(msg.width * msg.height); + + sensor_msgs::PointCloud2Iterator iter_x(msg, "x"); + sensor_msgs::PointCloud2Iterator iter_y(msg, "y"); + sensor_msgs::PointCloud2Iterator iter_z(msg, "z"); + sensor_msgs::PointCloud2Iterator iter_rgb(msg, "rgb"); + #endif + + // Shared data processing logic + int32_t* xyz_data = static_cast(stream->imageList[idx].pAddr); + + for(uint32_t i = 0; i < points; i++) { + int32_t* ptr = xyz_data + 7*i; + +#ifdef ROS2 + *iter_x = static_cast(ptr[0]) / 10000.0f; ++iter_x; + *iter_y = static_cast(ptr[1]) / 10000.0f; ++iter_y; + *iter_z = static_cast(ptr[2]) / 10000.0f; ++iter_z; +#else + *iter_x = (1.0 * ptr[0]) / 1e4; ++iter_x; + *iter_y = (1.0 * ptr[1]) / 1e4; ++iter_y; + *iter_z = (1.0 * ptr[2]) / 1e4; ++iter_z; +#endif + + uint8_t r = ptr[3] & 0xff; + uint8_t g = ptr[4] & 0xff; + uint8_t b = ptr[5] & 0xff; + uint8_t a = ptr[6] & 0xff; + + uint32_t packed_rgb = (static_cast(r) << 16) | + (static_cast(g) << 8) | + static_cast(b); + + float rgb_float; + std::memcpy(&rgb_float, &packed_rgb, sizeof(float)); + + *iter_rgb = rgb_float; ++iter_rgb; + } + + // Enqueue binary logging for point cloud (XYZRGB per point) + if (data_logger_ && points > 0) { + // Align point cloud timestamp with the same policy as ROS publish path (NTP mode -> NTP time) + const double ts_sec = static_cast(aligned_stamp_ns(stream->imageList[0].timestamp)) / 1e9; + const uint32_t idx_now = cloud_index_.fetch_add(1, std::memory_order_relaxed); + // Compute total blob size: header + per-point payload + const size_t header_size = sizeof(uint32_t) + sizeof(double) + sizeof(uint32_t); + const size_t point_size = sizeof(float) * 3 + sizeof(uint8_t) * 4; + std::vector blob; + blob.reserve(header_size + static_cast(points) * point_size); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(idx_now); + append_pod(ts_sec); + append_pod(points); + + for (uint32_t i = 0; i < points; ++i) { + int32_t* ptr = xyz_data + 7 * i; + float fx = static_cast(ptr[0]) / 10000.0f; + float fy = static_cast(ptr[1]) / 10000.0f; + float fz = static_cast(ptr[2]) / 10000.0f; + uint8_t r = static_cast(ptr[3] & 0xff); + uint8_t g = static_cast(ptr[4] & 0xff); + uint8_t b = static_cast(ptr[5] & 0xff); + uint8_t a = static_cast(ptr[6] & 0xff); + append_pod(fx); + append_pod(fy); + append_pod(fz); + blob.push_back(r); + blob.push_back(g); + blob.push_back(b); + blob.push_back(a); + } + data_logger_->enqueuePointCloudFrame(std::move(blob)); + } + +#ifdef ROS2 + xyzrgbacloud_pub_->publish(std::move(msg)); +#else + xyzrgbacloud_pub_.publish(msg); +#endif + } + + void recordrotate(capture_Image_List_t* stream) { + if(data_logger_) { + uint32_t data_len = stream->imageList[0].length; + if (data_len == sizeof(ros_odom_convert_complete_t)) { + ros_odom_convert_complete_t* odom_data = (ros_odom_convert_complete_t*)stream->imageList[0].pAddr; + const uint32_t idx_now = wcwi_index_.fetch_add(1, std::memory_order_relaxed); + // Align WIWC/rotate timestamp with the same policy as ROS publish path (NTP mode -> NTP time) + const double ts_sec = static_cast(aligned_stamp_ns(odom_data->timestamp_ns)) / 1e9; + float pose_arr[4]; + pose_arr[0] = static_cast((odom_data->orient[0]) / 1e6); + pose_arr[1] = static_cast((odom_data->orient[1]) / 1e6); + pose_arr[2] = static_cast((odom_data->orient[2]) / 1e6); + pose_arr[3] = static_cast((odom_data->orient[3]) / 1e6); + + // Save only rotate (pose_arr) to bin file + std::vector blob; + blob.reserve(sizeof(uint32_t) + sizeof(double) + sizeof(float) * 4); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(idx_now); + append_pod(ts_sec); + for (int i = 0; i < 4; ++i) append_pod(pose_arr[i]); + data_logger_->enqueueRotateFrame(std::move(blob)); + + // Build TCL matrix (4x4) from pose_cov + Eigen::Matrix4d T_CL = Eigen::Matrix4d::Identity(); + for (int idx = 0; idx < 16; ++idx) { + T_CL(idx / 4, idx % 4) = static_cast(odom_data->pose_cov[idx]); + } + // Force last row to be [0, 0, 0, 1] for valid transformation matrix + T_CL(3, 0) = 0.0; T_CL(3, 1) = 0.0; T_CL(3, 2) = 0.0; T_CL(3, 3) = 1.0; + + // Build TIL matrix (4x4) from twist_cov + Eigen::Matrix4d T_IL = Eigen::Matrix4d::Identity(); + for (int idx = 0; idx < 16; ++idx) { + T_IL(idx / 4, idx % 4) = static_cast(odom_data->twist_cov[idx]); + } + // Force last row to be [0, 0, 0, 1] for valid transformation matrix + T_IL(3, 0) = 0.0; T_IL(3, 1) = 0.0; T_IL(3, 2) = 0.0; T_IL(3, 3) = 1.0; + + // Debug print to compare with cloud_reprojection values + // static int host_print_count = 0; + // if (host_print_count++) { + // std::cout << "=== host_sdk_sample T_CL from odom_data->pose_cov ===" << std::endl; + // std::cout << T_CL << std::endl; + // std::cout << "=== host_sdk_sample T_IL from odom_data->twist_cov ===" << std::endl; + // std::cout << T_IL << std::endl; + // } + + // Extract rotation and translation from T_CL + Eigen::Matrix3d RCL = T_CL.block<3, 3>(0, 0); + Eigen::Vector3d TCL = T_CL.block<3, 1>(0, 3); + + // Extract rotation and translation from T_IL + Eigen::Matrix3d RIL = T_IL.block<3, 3>(0, 0); + Eigen::Vector3d TIL = T_IL.block<3, 1>(0, 3); + + // Debug print extracted RCL and TCL + // static int rcl_print_count = 0; + // if (rcl_print_count++ ) { + // std::cout << "=== host_sdk_sample RCL (3x3 rotation from T_CL) ===" << std::endl; + // std::cout << RCL << std::endl; + // std::cout << "=== host_sdk_sample TCL (3x1 translation from T_CL) ===" << std::endl; + // std::cout << TCL.transpose() << std::endl; + // std::cout << "=== host_sdk_sample RIL (3x3 rotation from T_IL) ===" << std::endl; + // std::cout << RIL << std::endl; + // std::cout << "=== host_sdk_sample TIL (3x1 translation from T_IL) ===" << std::endl; + // std::cout << TIL.transpose() << std::endl; + // } + + // Save RIL, TIL, RCL, TCL to YAML file + static int save_count = 0; + static int index_count = 0; + save_count++; + + bool should_save = true; // Always save, or modify this condition as needed + if (should_save || save_count % 1 == 0 || index_count == 0) { + std::string OUTPUT_PATH = root_dir_.string(); + std::ofstream yaml_file; + if(index_count == 0) + yaml_file.open(OUTPUT_PATH + "/calib_online.yaml"); + else + yaml_file.open(OUTPUT_PATH + "/calib_online.yaml", std::ios::app); + + if (yaml_file.is_open()) { + yaml_file << "frame:\n"; + yaml_file << " index: " << index_count << "\n"; + yaml_file << " timestamp: " << std::fixed << std::setprecision(10) << ts_sec << "\n"; + yaml_file << " cam_num: 1\n"; + + // Save TCL (camera-lidar translation) in the same format as Tcl_0 + yaml_file << " Tcl_0: [\n"; + Eigen::Matrix4d T_CL_output = Eigen::Matrix4d::Identity(); + T_CL_output.block<3, 3>(0, 0) = RCL; + T_CL_output.block<3, 1>(0, 3) = TCL; + for (int i = 0; i < 4; i++) { + yaml_file << " "; + for (int j = 0; j < 4; j++) { + yaml_file << std::fixed << std::setprecision(10) << T_CL_output(i, j); + if (i != 3 || j != 3) yaml_file << ", "; + } + if (i != 3) yaml_file << "\n"; + } + yaml_file << "\n ]\n\n"; + + // Save TIL (IMU-lidar transformation) as body_T_lidar + yaml_file << " body_T_lidar: !!opencv-matrix\n"; + yaml_file << " rows: 4\n"; + yaml_file << " cols: 4\n"; + yaml_file << " dt: d\n"; + yaml_file << " data: [ "; + Eigen::Matrix4d T_IL_output = Eigen::Matrix4d::Identity(); + T_IL_output.block<3, 3>(0, 0) = RIL; + T_IL_output.block<3, 1>(0, 3) = TIL; + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + yaml_file << std::fixed << std::setprecision(10) << T_IL_output(i, j); + if (i != 3 || j != 3) yaml_file << ","; + } + if (i != 3) yaml_file << "\n "; + } + yaml_file << "]\n\n"; + + index_count++; + yaml_file.close(); + } + } + } + } + + } + + // Publish WIWC data (T_CL and T_IL extrinsics) as a separate topic + void publishWiwc(capture_Image_List_t* stream) { + uint32_t data_len = stream->imageList[0].length; + if (data_len != sizeof(ros_odom_convert_complete_t)) { + return; + } + + ros_odom_convert_complete_t* odom_data = (ros_odom_convert_complete_t*)stream->imageList[0].pAddr; + +#ifdef ROS2 + auto msg = nav_msgs::msg::Odometry(); + msg.header.stamp = make_aligned_stamp(odom_data->timestamp_ns, node_); + msg.header.frame_id = "odom"; +#else + nav_msgs::Odometry msg; + msg.header.stamp = make_aligned_stamp(odom_data->timestamp_ns); + msg.header.frame_id = "odom"; +#endif + + // Store T_CL in pose.covariance (first 16 elements) + // Force last row to be [0, 0, 0, 1] for valid transformation matrix + for (int i = 0; i < 16; ++i) { + msg.pose.covariance[i] = odom_data->pose_cov[i]; + } + msg.pose.covariance[12] = 0.0; + msg.pose.covariance[13] = 0.0; + msg.pose.covariance[14] = 0.0; + msg.pose.covariance[15] = 1.0; + // Fill remaining with zeros + for (int i = 16; i < 36; ++i) { + msg.pose.covariance[i] = 0.0; + } + + // Store T_IL in twist.covariance (first 16 elements) + // Force last row to be [0, 0, 0, 1] for valid transformation matrix + for (int i = 0; i < 16; ++i) { + msg.twist.covariance[i] = odom_data->twist_cov[i]; + } + msg.twist.covariance[12] = 0.0; + msg.twist.covariance[13] = 0.0; + msg.twist.covariance[14] = 0.0; + msg.twist.covariance[15] = 1.0; + // Fill remaining with zeros + for (int i = 16; i < 36; ++i) { + msg.twist.covariance[i] = 0.0; + } + +#ifdef ROS2 + wiwc_publisher_->publish(msg); +#else + wiwc_publisher_.publish(msg); +#endif + + // Cache extrinsics for til/wc TF computation in publishOdometry + { + // Build T_IL (IMU/body to LiDAR) from twist.covariance + Eigen::Matrix4d T_IL = Eigen::Matrix4d::Identity(); + for (int i = 0; i < 16; ++i) { + T_IL(i / 4, i % 4) = msg.twist.covariance[i]; + } + T_IL(3, 0) = 0.0; T_IL(3, 1) = 0.0; T_IL(3, 2) = 0.0; T_IL(3, 3) = 1.0; + + // Build T_CL (Camera to LiDAR) from pose.covariance + Eigen::Matrix4d T_CL = Eigen::Matrix4d::Identity(); + for (int i = 0; i < 16; ++i) { + T_CL(i / 4, i % 4) = msg.pose.covariance[i]; + } + T_CL(3, 0) = 0.0; T_CL(3, 1) = 0.0; T_CL(3, 2) = 0.0; T_CL(3, 3) = 1.0; + + // T_IL from SDK is body_T_lidar (imu -> lidar, pose of lidar in imu frame, + // matches the fixed extrinsic spec T^imu_lidar), use it directly without inverting + Eigen::Matrix4d T_base_lidar = T_IL; + + // Cache for use in publishOdometry (til and wc computation) + { + std::lock_guard lock(extrinsics_mutex_); + cached_T_base_lidar_ = T_base_lidar; + cached_T_CL_ = T_CL; + has_cached_extrinsics_ = true; + } + } + } + + void publishOdometry(capture_Image_List_t* stream, OdometryType odom_type, bool show_path, bool show_camerapose) { + +#ifdef ROS2 + auto msg = nav_msgs::msg::Odometry(); +#else + ros::Odometry msg; +#endif + + msg.header.frame_id = "odom"; + msg.child_frame_id = "imu"; + + //RCLCPP_INFO(rclcpp::get_logger("device_cb"), "odom %ld",odom_data->timestamp_ns); + + uint32_t data_len = stream->imageList[0].length; + if (data_len == sizeof(ros_odom_convert_complete_t)) { + + ros_odom_convert_complete_t* odom_data = (ros_odom_convert_complete_t*)stream->imageList[0].pAddr; + #ifdef ROS2 + msg.header.stamp = make_aligned_stamp(odom_data->timestamp_ns, node_); + #else + msg.header.stamp = make_aligned_stamp(odom_data->timestamp_ns); + #endif + + msg.pose.pose.position.x = static_cast(odom_data->pos[0]) / 1e6; + msg.pose.pose.position.y = static_cast(odom_data->pos[1]) / 1e6; + msg.pose.pose.position.z = static_cast(odom_data->pos[2]) / 1e6; + + msg.pose.pose.orientation.x = static_cast(odom_data->orient[0]) / 1e6; + msg.pose.pose.orientation.y = static_cast(odom_data->orient[1]) / 1e6; + msg.pose.pose.orientation.z = static_cast(odom_data->orient[2]) / 1e6; + msg.pose.pose.orientation.w = static_cast(odom_data->orient[3]) / 1e6; + + // Enqueue binary logging for pose + if ((odom_type == OdometryType::STANDARD) && data_logger_) { + const uint32_t idx_now = pose_index_.fetch_add(1, std::memory_order_relaxed); + // Align pose timestamp with the same policy as ROS publish path (NTP mode -> NTP time) + const double ts_sec = static_cast(aligned_stamp_ns(odom_data->timestamp_ns)) / 1e9; + float pose_arr[7]; + pose_arr[0] = static_cast(msg.pose.pose.position.x); + pose_arr[1] = static_cast(msg.pose.pose.position.y); + pose_arr[2] = static_cast(msg.pose.pose.position.z); + pose_arr[3] = static_cast(msg.pose.pose.orientation.x); + pose_arr[4] = static_cast(msg.pose.pose.orientation.y); + pose_arr[5] = static_cast(msg.pose.pose.orientation.z); + pose_arr[6] = static_cast(msg.pose.pose.orientation.w); + std::vector blob; + blob.reserve(sizeof(uint32_t) + sizeof(double) + sizeof(float) * 7); + auto append_pod = [&](const auto& v) { + const uint8_t* p = reinterpret_cast(&v); + blob.insert(blob.end(), p, p + sizeof(v)); + }; + append_pod(idx_now); + append_pod(ts_sec); + for (int i = 0; i < 7; ++i) append_pod(pose_arr[i]); + data_logger_->enqueuePoseFrame(std::move(blob)); + } + + msg.twist.twist.linear.x = static_cast(odom_data->linear_velocity[0]) / 1e6; + msg.twist.twist.linear.y = static_cast(odom_data->linear_velocity[1]) / 1e6; + msg.twist.twist.linear.z = static_cast(odom_data->linear_velocity[2]) / 1e6; + + msg.twist.twist.angular.x = static_cast(odom_data->angular_velocity[0]) / 1e6; + msg.twist.twist.angular.y = static_cast(odom_data->angular_velocity[1]) / 1e6; + msg.twist.twist.angular.z = static_cast(odom_data->angular_velocity[2]) / 1e6; + + // Copy original covariance data + for (int i = 0; i < 36; ++i) { + msg.pose.covariance[i] = odom_data->pose_cov[i]; + } + + for (int i = 0; i < 36; ++i) { + msg.twist.covariance[i] = odom_data->twist_cov[i]; + } + + } else if (data_len == sizeof(ros2_odom_convert_t)) { + + ros2_odom_convert_t* odom_data = (ros2_odom_convert_t*)stream->imageList[0].pAddr; + #ifdef ROS2 + msg.header.stamp = make_aligned_stamp(odom_data->timestamp_ns, node_); + #else + msg.header.stamp = make_aligned_stamp(odom_data->timestamp_ns); + #endif + + msg.pose.pose.position.x = static_cast(odom_data->pos[0]) / 1e6; + msg.pose.pose.position.y = static_cast(odom_data->pos[1]) / 1e6; + msg.pose.pose.position.z = static_cast(odom_data->pos[2]) / 1e6; + + msg.pose.pose.orientation.x = static_cast(odom_data->orient[0]) / 1e6; + msg.pose.pose.orientation.y = static_cast(odom_data->orient[1]) / 1e6; + msg.pose.pose.orientation.z = static_cast(odom_data->orient[2]) / 1e6; + msg.pose.pose.orientation.w = static_cast(odom_data->orient[3]) / 1e6; + } + +#ifdef ROS2 + switch(odom_type) { + case OdometryType::STANDARD: + { + if (getRosNodeControl()->sendOdomBaseLinkTF()) { + geometry_msgs::msg::TransformStamped transformStamped; + transformStamped.header.stamp = msg.header.stamp; + transformStamped.header.frame_id = "odom"; + transformStamped.child_frame_id = "imu"; + transformStamped.transform.translation.x = msg.pose.pose.position.x; + transformStamped.transform.translation.y = msg.pose.pose.position.y; + transformStamped.transform.translation.z = msg.pose.pose.position.z; + transformStamped.transform.rotation.x = msg.pose.pose.orientation.x; + transformStamped.transform.rotation.y = msg.pose.pose.orientation.y; + transformStamped.transform.rotation.z = msg.pose.pose.orientation.z; + transformStamped.transform.rotation.w = msg.pose.pose.orientation.w; + + // Cache for timer re-publishing + { + std::lock_guard lock(tf_cache_mutex_); + cached_tf_.msg = transformStamped; + cached_tf_.cache_time = std::chrono::steady_clock::now(); + cached_tf_.orig_stamp_sec = msg.header.stamp.sec + msg.header.stamp.nanosec * 1e-9; + has_cached_tf_ = true; + } + + if (getRosNodeControl()->getTfExtraPublishRate() > 0) { + // Burst-publish TF covering the next 200ms immediately + // so tf2 can interpolate for any cloud that arrives + // (cloud device timestamp is typically ~100ms ahead of odom) + double base_sec = msg.header.stamp.sec + msg.header.stamp.nanosec * 1e-9; + for (int i = 0; i <= 10; ++i) { + double t_sec = base_sec + i * 0.020; // 0, 20, 40, ... 200 ms + auto tf_copy = transformStamped; + tf_copy.header.stamp.sec = static_cast(t_sec); + tf_copy.header.stamp.nanosec = static_cast((t_sec - static_cast(t_sec)) * 1e9); + tf_broadcaster->sendTransform(tf_copy); + } + } else { + // Simple mode: publish TF only at odom timestamp + tf_broadcaster->sendTransform(transformStamped); + } + + // Publish til (imu -> lidar) and wc (odom -> camera_0) + { + std::lock_guard lock(extrinsics_mutex_); + if (has_cached_extrinsics_) { + // til: imu -> lidar (dynamic extrinsic from wiwc) + Eigen::Quaterniond q_til(cached_T_base_lidar_.block<3,3>(0,0)); + q_til.normalize(); + + geometry_msgs::msg::TransformStamped tf_til; + tf_til.header.frame_id = "imu"; + tf_til.child_frame_id = "lidar"; + tf_til.transform.translation.x = cached_T_base_lidar_(0, 3); + tf_til.transform.translation.y = cached_T_base_lidar_(1, 3); + tf_til.transform.translation.z = cached_T_base_lidar_(2, 3); + tf_til.transform.rotation.x = q_til.x(); + tf_til.transform.rotation.y = q_til.y(); + tf_til.transform.rotation.z = q_til.z(); + tf_til.transform.rotation.w = q_til.w(); + + // wc: odom -> camera_0 (T_wc = T_wi * T_base_lidar * T_CL^-1) + // cached_T_CL_ is Tcl (camera <- lidar, optical convention: z fwd, x right, y down), + // the chain needs T_lidar_camera (lidar <- camera), so invert it here + Eigen::Matrix4d T_wi_mat = Eigen::Matrix4d::Identity(); + Eigen::Quaterniond q_wi( + msg.pose.pose.orientation.w, + msg.pose.pose.orientation.x, + msg.pose.pose.orientation.y, + msg.pose.pose.orientation.z); + q_wi.normalize(); + T_wi_mat.block<3,3>(0,0) = q_wi.toRotationMatrix(); + T_wi_mat(0,3) = msg.pose.pose.position.x; + T_wi_mat(1,3) = msg.pose.pose.position.y; + T_wi_mat(2,3) = msg.pose.pose.position.z; + + Eigen::Matrix4d T_wc = T_wi_mat * cached_T_base_lidar_ * cached_T_CL_.inverse(); + Eigen::Quaterniond q_wc(T_wc.block<3,3>(0,0)); + q_wc.normalize(); + + geometry_msgs::msg::TransformStamped tf_wc; + tf_wc.header.frame_id = "odom"; + tf_wc.child_frame_id = "camera_0"; + tf_wc.transform.translation.x = T_wc(0, 3); + tf_wc.transform.translation.y = T_wc(1, 3); + tf_wc.transform.translation.z = T_wc(2, 3); + tf_wc.transform.rotation.x = q_wc.x(); + tf_wc.transform.rotation.y = q_wc.y(); + tf_wc.transform.rotation.z = q_wc.z(); + tf_wc.transform.rotation.w = q_wc.w(); + + if (getRosNodeControl()->getTfExtraPublishRate() > 0) { + // Burst-publish over the next 200ms so tf2 can + // interpolate for clouds whose timestamp is ahead of odom + double base_sec = msg.header.stamp.sec + msg.header.stamp.nanosec * 1e-9; + for (int i = 0; i <= 10; ++i) { + double t_sec = base_sec + i * 0.020; // 0, 20, ... 200 ms + int32_t s = static_cast(t_sec); + uint32_t ns = static_cast((t_sec - s) * 1e9); + + auto til_copy = tf_til; + til_copy.header.stamp.sec = s; + til_copy.header.stamp.nanosec = ns; + tf_broadcaster->sendTransform(til_copy); + + auto wc_copy = tf_wc; + wc_copy.header.stamp.sec = s; + wc_copy.header.stamp.nanosec = ns; + tf_broadcaster->sendTransform(wc_copy); + } + } else { + tf_til.header.stamp = msg.header.stamp; + tf_wc.header.stamp = msg.header.stamp; + tf_broadcaster->sendTransform(tf_til); + tf_broadcaster->sendTransform(tf_wc); + } + } + } + } + odom_publisher_->publish(msg); + + // Publish odom trajectory as visualization markers (green lines connecting adjacent points) + static visualization_msgs::msg::Marker marker; + static std::vector path_points; + + if (show_path) { + marker.header = msg.header; + marker.ns = "odom_trajectory"; + marker.id = 0; + marker.type = visualization_msgs::msg::Marker::LINE_STRIP; + marker.action = visualization_msgs::msg::Marker::ADD; + marker.pose.orientation.w = 1.0; + marker.scale.x = 0.02; // Line width + marker.color.r = 0.0; + marker.color.g = 1.0; + marker.color.b = 0.0; + marker.color.a = 1.0; + + geometry_msgs::msg::Point pt; + pt.x = msg.pose.pose.position.x; + pt.y = msg.pose.pose.position.y; + pt.z = msg.pose.pose.position.z; + path_points.push_back(pt); + + // Keep only recent points to avoid memory issues (e.g., last 1000 points) + if (path_points.size() > 30000) { + path_points.erase(path_points.begin()); + } + + marker.points = path_points; + + // Publish marker array + static visualization_msgs::msg::MarkerArray marker_array; + marker_array.markers.clear(); // Clear previous markers + marker_array.markers.push_back(marker); + path_publisher_->publish(marker_array); + } + + if (show_camerapose) { + // camera pose visualization (ROS2) + Eigen::Vector3d P(msg.pose.pose.position.x, + msg.pose.pose.position.y, + msg.pose.pose.position.z); + Eigen::Quaterniond R(msg.pose.pose.orientation.w, + msg.pose.pose.orientation.x, + msg.pose.pose.orientation.y, + msg.pose.pose.orientation.z); + if (extrinsic_ok_) { + P = P + R * t_ic_; + R = R * R_ic_; + } + cameraposevisual_.reset(); + cameraposevisual_.add_pose(P, R); + cameraposevisual_.publish_by(*pub_camera_pose_visual_, msg.header); + } + } + break; + case OdometryType::HIGHFREQ: + odom_highfreq_publisher_->publish(std::move(msg)); + break; + case OdometryType::TRANSFORM: + { + geometry_msgs::msg::TransformStamped transformStamped; + transformStamped.header.stamp = msg.header.stamp; + transformStamped.header.frame_id = "odom"; + transformStamped.child_frame_id = "map"; + transformStamped.transform.translation.x = msg.pose.pose.position.x; + transformStamped.transform.translation.y = msg.pose.pose.position.y; + transformStamped.transform.translation.z = msg.pose.pose.position.z; + transformStamped.transform.rotation.x = msg.pose.pose.orientation.x; + transformStamped.transform.rotation.y = msg.pose.pose.orientation.y; + transformStamped.transform.rotation.z = msg.pose.pose.orientation.z; + transformStamped.transform.rotation.w = msg.pose.pose.orientation.w; + tf_broadcaster->sendTransform(transformStamped); + } + break; + } +#else + switch(odom_type) { + case OdometryType::STANDARD: + { + if (getRosNodeControl()->sendOdomBaseLinkTF()) { + geometry_msgs::TransformStamped transformStamped; + transformStamped.header.stamp = msg.header.stamp; + transformStamped.header.frame_id = "odom"; + transformStamped.child_frame_id = "imu"; + transformStamped.transform.translation.x = msg.pose.pose.position.x; + transformStamped.transform.translation.y = msg.pose.pose.position.y; + transformStamped.transform.translation.z = msg.pose.pose.position.z; + transformStamped.transform.rotation.x = msg.pose.pose.orientation.x; + transformStamped.transform.rotation.y = msg.pose.pose.orientation.y; + transformStamped.transform.rotation.z = msg.pose.pose.orientation.z; + transformStamped.transform.rotation.w = msg.pose.pose.orientation.w; + tf_broadcaster->sendTransform(transformStamped); + + // Publish til (imu -> lidar) and wc (odom -> camera_0) + std::lock_guard lock(extrinsics_mutex_); + if (has_cached_extrinsics_) { + // til: imu -> lidar (dynamic extrinsic from wiwc) + Eigen::Quaterniond q_til(cached_T_base_lidar_.block<3,3>(0,0)); + q_til.normalize(); + + geometry_msgs::TransformStamped tf_til; + tf_til.header.stamp = msg.header.stamp; + tf_til.header.frame_id = "imu"; + tf_til.child_frame_id = "lidar"; + tf_til.transform.translation.x = cached_T_base_lidar_(0, 3); + tf_til.transform.translation.y = cached_T_base_lidar_(1, 3); + tf_til.transform.translation.z = cached_T_base_lidar_(2, 3); + tf_til.transform.rotation.x = q_til.x(); + tf_til.transform.rotation.y = q_til.y(); + tf_til.transform.rotation.z = q_til.z(); + tf_til.transform.rotation.w = q_til.w(); + tf_broadcaster->sendTransform(tf_til); + + // wc: odom -> camera_0 (T_wc = T_wi * T_base_lidar * T_CL^-1) + // cached_T_CL_ is Tcl (camera <- lidar, optical convention: z fwd, x right, y down), + // the chain needs T_lidar_camera (lidar <- camera), so invert it here + Eigen::Matrix4d T_wi_mat = Eigen::Matrix4d::Identity(); + Eigen::Quaterniond q_wi( + msg.pose.pose.orientation.w, + msg.pose.pose.orientation.x, + msg.pose.pose.orientation.y, + msg.pose.pose.orientation.z); + q_wi.normalize(); + T_wi_mat.block<3,3>(0,0) = q_wi.toRotationMatrix(); + T_wi_mat(0,3) = msg.pose.pose.position.x; + T_wi_mat(1,3) = msg.pose.pose.position.y; + T_wi_mat(2,3) = msg.pose.pose.position.z; + + Eigen::Matrix4d T_wc = T_wi_mat * cached_T_base_lidar_ * cached_T_CL_.inverse(); + Eigen::Quaterniond q_wc(T_wc.block<3,3>(0,0)); + q_wc.normalize(); + + geometry_msgs::TransformStamped tf_wc; + tf_wc.header.stamp = msg.header.stamp; + tf_wc.header.frame_id = "odom"; + tf_wc.child_frame_id = "camera_0"; + tf_wc.transform.translation.x = T_wc(0, 3); + tf_wc.transform.translation.y = T_wc(1, 3); + tf_wc.transform.translation.z = T_wc(2, 3); + tf_wc.transform.rotation.x = q_wc.x(); + tf_wc.transform.rotation.y = q_wc.y(); + tf_wc.transform.rotation.z = q_wc.z(); + tf_wc.transform.rotation.w = q_wc.w(); + tf_broadcaster->sendTransform(tf_wc); + } + } + odom_publisher_.publish(msg); + + if (show_path) { + // Publish odom trajectory as visualization markers (green lines connecting adjacent points) + static visualization_msgs::Marker marker; + static std::vector path_points; + + marker.header = msg.header; + marker.ns = "odom_trajectory"; + marker.id = 0; + marker.type = visualization_msgs::Marker::LINE_STRIP; + marker.action = visualization_msgs::Marker::ADD; + marker.pose.orientation.w = 1.0; + marker.scale.x = 0.02; // Line width + marker.color.r = 0.0; + marker.color.g = 1.0; + marker.color.b = 0.0; + marker.color.a = 1.0; + + geometry_msgs::Point pt; + pt.x = msg.pose.pose.position.x; + pt.y = msg.pose.pose.position.y; + pt.z = msg.pose.pose.position.z; + path_points.push_back(pt); + + // Keep only recent points to avoid memory issues (e.g., last 1000 points) + if (path_points.size() > 30000) { + path_points.erase(path_points.begin()); + } + + marker.points = path_points; + + // Publish marker array + static visualization_msgs::MarkerArray marker_array; + marker_array.markers.clear(); // Clear previous markers + marker_array.markers.push_back(marker); + path_publisher_.publish(marker_array); + } + + if (show_camerapose) { + // camera pose visualization (ROS1) + Eigen::Vector3d P(msg.pose.pose.position.x, + msg.pose.pose.position.y, + msg.pose.pose.position.z); + Eigen::Quaterniond R(msg.pose.pose.orientation.w, + msg.pose.pose.orientation.x, + msg.pose.pose.orientation.y, + msg.pose.pose.orientation.z); + + if (extrinsic_ok_) { + P = P + R * t_ic_; + R = R * R_ic_; + } + cameraposevisual_.reset(); + cameraposevisual_.add_pose(P, R); + cameraposevisual_.publish_by(pub_camera_pose_visual_, msg.header); + } + } + break; + case OdometryType::HIGHFREQ: + odom_highfreq_publisher_.publish(msg); + break; + case OdometryType::TRANSFORM: + { + geometry_msgs::TransformStamped transformStamped; + transformStamped.header.stamp = msg.header.stamp; + transformStamped.header.frame_id = "odom"; + transformStamped.child_frame_id = "map"; + transformStamped.transform.translation.x = msg.pose.pose.position.x; + transformStamped.transform.translation.y = msg.pose.pose.position.y; + transformStamped.transform.translation.z = msg.pose.pose.position.z; + transformStamped.transform.rotation.x = msg.pose.pose.orientation.x; + transformStamped.transform.rotation.y = msg.pose.pose.orientation.y; + transformStamped.transform.rotation.z = msg.pose.pose.orientation.z; + transformStamped.transform.rotation.w = msg.pose.pose.orientation.w; + tf_broadcaster->sendTransform(transformStamped); + } + break; + } +#endif + } + + void initialize_data_logger(std::string data_dir = "") { + + try { + BinaryDataLogger::Options opts; + opts.batch_size = 100; + opts.base_dir = data_dir; + data_logger_ = std::make_shared(opts); + root_dir_ = data_logger_->root_dir(); + #ifdef ROS2 + RCLCPP_INFO(node_->get_logger(), "Data logger initialized at %s", root_dir_.c_str()); + #endif + } catch (...) { + // Swallow logger initialization failures to avoid affecting runtime + #ifdef ROS2 + RCLCPP_INFO(node_->get_logger(), "Failed to initialize data logger"); + #endif + data_logger_.reset(); + } + } + + int loadCameraParams(const std::string& yaml_file) { + try { + YAML::Node config = YAML::LoadFile(yaml_file); + + YAML::Node cam_node = config["cam_0"]; + + m_camera_params.width = cam_node["image_width"].as(); + m_camera_params.height = cam_node["image_height"].as(); + + double A11 = cam_node["A11"].as(); + double A12 = cam_node["A12"].as(); + double A22 = cam_node["A22"].as(); + double u0 = cam_node["u0"].as(); + double v0 = cam_node["v0"].as(); + + m_camera_params.fx = A11; + m_camera_params.fy = A22; + m_camera_params.cx = u0; + m_camera_params.cy = v0; + m_camera_params.skew = A12; + + m_camera_params.k2 = cam_node["k2"].as(); + m_camera_params.k3 = cam_node["k3"].as(); + m_camera_params.k4 = cam_node["k4"].as(); + m_camera_params.k5 = cam_node["k5"].as(); + m_camera_params.k6 = cam_node["k6"].as(); + m_camera_params.k7 = cam_node["k7"].as(); + m_camera_params.p1 = cam_node["p1"].as(); + m_camera_params.p2 = cam_node["p2"].as(); +#if 0 + std::cout << "成功读取相机参数:" << std::endl; + std::cout << "图像尺寸: " << m_camera_params.width << "x" << m_camera_params.height << std::endl; + std::cout << "焦距: fx=" << m_camera_params.fx << ", fy=" << m_camera_params.fy << std::endl; + std::cout << "主点: cx=" << m_camera_params.cx << ", cy=" << m_camera_params.cy << std::endl; + std::cout << "倾斜: " << m_camera_params.skew << std::endl; + std::cout << "畸变系数: k2=" << m_camera_params.k2 << ", k3=" << m_camera_params.k3 + << ", k4=" << m_camera_params.k4 << ", k5=" << m_camera_params.k5 + << ", k6=" << m_camera_params.k6 << ", k7=" << m_camera_params.k7 << std::endl; +#endif + m_cam = std::make_unique(m_camera_params.width, m_camera_params.height, + m_camera_params.fx, m_camera_params.fy, m_camera_params.cx, m_camera_params.cy, m_camera_params.skew, + m_camera_params.k2, m_camera_params.k3, m_camera_params.k4, m_camera_params.k5, m_camera_params.k6, m_camera_params.k7); + + // Load extrinsic Tcl_0 (camera to lidar) + extrinsic_ok_ = false; + if (config["Tcl_0"]) { + auto T = config["Tcl_0"]; + if (T.IsSequence() && T.size() == 16) { + Eigen::Matrix4d Tcl; + for (int i = 0; i < 16; ++i) Tcl(i/4, i%4) = T[i].as(); + T_cl_ = Tcl; + } + std::cout << "Tcl: " << T_cl_ << std::endl; + + Eigen::Matrix4d Tic = T_il_ * T_cl_.inverse(); + Eigen::Matrix3d Ric = Tic.block<3,3>(0,0); + Eigen::Vector3d tic = Tic.block<3,1>(0,3); + R_ic_ = Eigen::Quaterniond(Ric); + t_ic_ = tic; + extrinsic_ok_ = true; + } + + m_cam_init_success = true; + return 0; + } catch (const std::exception& e) { + std::cerr << "读取YAML文件失败: " << e.what() << std::endl; + m_cam_init_success = false; + return -1; + } + } + + void buildUndistortMap() + { + m_undistort_map_x.create(m_camera_params.height, m_camera_params.width, CV_32F); + m_undistort_map_y.create(m_camera_params.height, m_camera_params.width, CV_32F); + + for (int v_out = 0; v_out < m_camera_params.height; ++v_out) { + for (int u_out = 0; u_out < m_camera_params.width; ++u_out) { + double x_norm = (u_out - m_cam->cx()) / m_cam->fx(); + double y_norm = (v_out - m_cam->cy()) / m_cam->fy(); + + // remove skew + x_norm = x_norm - y_norm * m_cam->skew() / m_cam->fx(); + + Eigen::Vector2d uv(x_norm, y_norm); + Eigen::Vector2d distorted_pixel = m_cam->world2cam(uv); + + m_undistort_map_x.at(v_out, u_out) = static_cast(distorted_pixel[0]); + m_undistort_map_y.at(v_out, u_out) = static_cast(distorted_pixel[1]); + } + } + m_undistort_map_init_success = true; + } + +private: + // Add the following member variables + std::mutex rgb_queue_mutex_; + std::deque rgb_image_queue_; + const size_t max_rgb_queue_size_ = 10; // Cache up to 10 image frames + + std::mutex pcd_queue_mutex_; + std::deque pcd_queue_; + const size_t max_pcd_queue_size_ = 10; // Maximum cache frames + + // Binary logger and frame indices + std::shared_ptr data_logger_; + std::atomic pose_index_{0}; + std::atomic cloud_index_{0}; + std::atomic image_index_{0}; + std::atomic wcwi_index_{0}; + + std::filesystem::path root_dir_; + + // Updated helper functions + ImageConstPtr getLatestRgbImage() { + std::lock_guard lock(rgb_queue_mutex_); + return (!rgb_image_queue_.empty()) ? rgb_image_queue_.back() : nullptr; + } + + PointCloud2ConstPtr getLatestIntensityCloud() { + std::lock_guard lock(pcd_queue_mutex_); + return (!pcd_queue_.empty()) ? pcd_queue_.back() : nullptr; + } + std::vector getRgbImageQueueSnapshot() { + std::lock_guard lock(rgb_queue_mutex_); + std::vector images; + for (const auto& msg : rgb_image_queue_) { + try { + cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(*msg, "bgr8"); + images.push_back(cv_ptr->image.clone()); + } catch (cv_bridge::Exception& e) { + #ifndef ROS2 + ROS_ERROR("cv_bridge exception: %s", e.what()); + #endif + } + } + return images; + } + + CameraParams m_camera_params; + std::unique_ptr m_cam; + bool m_cam_init_success; + bool m_undistort_map_init_success = false; + cv::Mat m_undistort_map_x; + cv::Mat m_undistort_map_y; + Eigen::Quaterniond R_ic_ {Eigen::Quaterniond::Identity()}; + Eigen::Vector3d t_ic_ {Eigen::Vector3d::Zero()}; + bool extrinsic_ok_ {false}; + Eigen::Matrix4d T_il_ = (Eigen::Matrix4d() << + 1.0, 0.0, 0.0, 0.00347, + 0.0, 1.0, 0.0, 0.03447, + 0.0, 0.0, 1.0, 0.02174, + 0.0, 0.0, 0.0, 1.0).finished(); + Eigen::Matrix4d T_cl_ = Eigen::Matrix4d::Identity(); // Camera->Lidar from YAML +#ifdef ROS2 + std::vector getIntensityCloudQueueSnapshot() { + std::lock_guard lock(pcd_queue_mutex_); + std::vector clouds; + + for (const auto& msg_ptr : pcd_queue_) { + clouds.push_back(*msg_ptr); + } + + return clouds; + } +#else + std::vector getIntensityCloudQueueSnapshot() { + std::lock_guard lock(pcd_queue_mutex_); + std::vector clouds; + + for (const auto& msg_ptr : pcd_queue_) { + clouds.push_back(*msg_ptr); + } + + return clouds; + } +#endif + + void initialize_publishers() { + #ifdef ROS2 + // Small data with queue depth 1 + auto qos_small = rclcpp::QoS(4000) + .reliability(RMW_QOS_POLICY_RELIABILITY_RELIABLE) + .durability(RMW_QOS_POLICY_DURABILITY_VOLATILE); + + // Large sensor data with larger queue to avoid blocking + auto qos_sensor = rclcpp::QoS(5) + .reliability(RMW_QOS_POLICY_RELIABILITY_RELIABLE) + .durability(RMW_QOS_POLICY_DURABILITY_VOLATILE); + + imu_pub_ = node_->create_publisher("odin1/imu", qos_small); + rgb_pub_ = node_->create_publisher("odin1/image", qos_sensor); + cloud_pub_ = node_->create_publisher("odin1/cloud_raw", qos_sensor); + xyzrgbacloud_pub_ = node_->create_publisher("odin1/cloud_slam", qos_sensor); + odom_publisher_ = node_->create_publisher("odin1/odometry", qos_sensor); + odom_highfreq_publisher_ = node_->create_publisher("odin1/odometry_highfreq", qos_small); + path_publisher_ = node_->create_publisher("odin1/path", qos_sensor); + pub_camera_pose_visual_ = node_->create_publisher("odin1/camera_pose_visual", qos_sensor); + rgbcloud_pub_ = node_->create_publisher("odin1/cloud_render", qos_sensor); + compressed_rgb_pub_ = node_->create_publisher("odin1/image/compressed", qos_sensor); + undistort_rgb_pub_ = node_->create_publisher("odin1/image/undistorted", qos_sensor); + intensity_gray_pub_ = node_->create_publisher("odin1/image/intensity_gray", qos_sensor); + wiwc_publisher_ = node_->create_publisher("odin1/wiwc", qos_sensor); + tf_broadcaster = std::make_unique(node_); + #endif + } + +public: + #ifdef ROS2 + void startTfExtraPublishTimer() { + int rate_hz = getRosNodeControl()->getTfExtraPublishRate(); + if (rate_hz <= 0) return; // Disabled, TF only published at actual odom rate + + int period_ms = 1000 / rate_hz; + tf_thread_running_.store(true); + tf_thread_ = std::thread([this, period_ms]() { + while (tf_thread_running_.load()) { + std::this_thread::sleep_for(std::chrono::milliseconds(period_ms)); + if (!tf_thread_running_.load()) break; + if (!getRosNodeControl()->sendOdomBaseLinkTF()) continue; + + std::lock_guard lock(tf_cache_mutex_); + if (!has_cached_tf_) continue; + + auto now = std::chrono::steady_clock::now(); + double elapsed = std::chrono::duration(now - cached_tf_.cache_time).count(); + double new_sec = cached_tf_.orig_stamp_sec + elapsed; + + // Ensure strictly monotonic timestamps + if (new_sec <= cached_tf_.last_published_sec) { + new_sec = cached_tf_.last_published_sec + 0.001; + } + cached_tf_.last_published_sec = new_sec; + + auto tf_copy = cached_tf_.msg; + // Convert new_sec to ROS time + int32_t sec = static_cast(new_sec); + uint32_t nanosec = static_cast((new_sec - sec) * 1e9); + tf_copy.header.stamp.sec = sec; + tf_copy.header.stamp.nanosec = nanosec; + tf_broadcaster->sendTransform(tf_copy); + + // Also republish til (imu -> lidar) at the same timestamp so the + // odom -> imu -> lidar chain stays valid between odom updates + { + std::lock_guard ext_lock(extrinsics_mutex_); + if (has_cached_extrinsics_) { + Eigen::Quaterniond q_til(cached_T_base_lidar_.block<3,3>(0,0)); + q_til.normalize(); + + geometry_msgs::msg::TransformStamped tf_til; + tf_til.header.stamp.sec = sec; + tf_til.header.stamp.nanosec = nanosec; + tf_til.header.frame_id = "imu"; + tf_til.child_frame_id = "lidar"; + tf_til.transform.translation.x = cached_T_base_lidar_(0, 3); + tf_til.transform.translation.y = cached_T_base_lidar_(1, 3); + tf_til.transform.translation.z = cached_T_base_lidar_(2, 3); + tf_til.transform.rotation.x = q_til.x(); + tf_til.transform.rotation.y = q_til.y(); + tf_til.transform.rotation.z = q_til.z(); + tf_til.transform.rotation.w = q_til.w(); + tf_broadcaster->sendTransform(tf_til); + } + } + } + }); + } + + void stopTfExtraPublishTimer() { + tf_thread_running_.store(false); + if (tf_thread_.joinable()) { + tf_thread_.join(); + } + } + #endif + + #ifdef ROS1 + void initialize_publishers(ros::NodeHandle& nh) { + imu_pub_ = nh.advertise("odin1/imu", 4000); + rgb_pub_ = nh.advertise("odin1/image", 5); + cloud_pub_ = nh.advertise("odin1/cloud_raw", 5); + xyzrgbacloud_pub_ = nh.advertise("odin1/cloud_slam", 5); + odom_publisher_ = nh.advertise("odin1/odometry", 5); + odom_highfreq_publisher_ = nh.advertise("odin1/odometry_highfreq", 4000); + path_publisher_ = nh.advertise("odin1/path", 5); + pub_camera_pose_visual_ = nh.advertise("odin1/camera_pose_visual", 5); + rgbcloud_pub_ = nh.advertise("odin1/cloud_render", 5); + compressed_rgb_pub_ = nh.advertise("odin1/image/compressed", 5); + undistort_rgb_pub_ = nh.advertise("odin1/image/undistorted", 5); + intensity_gray_pub_ = nh.advertise("odin1/image/intensity_gray", 5); + wiwc_publisher_ = nh.advertise("odin1/wiwc", 5); + tf_broadcaster = std::make_unique(); + } + #endif + + // Cached extrinsics from WIWC data for til/wc computation in publishOdometry + std::mutex extrinsics_mutex_; + Eigen::Matrix4d cached_T_base_lidar_ = Eigen::Matrix4d::Identity(); // imu -> lidar (T_IL inverse) + Eigen::Matrix4d cached_T_CL_ = Eigen::Matrix4d::Identity(); + bool has_cached_extrinsics_ = false; + + #ifdef ROS2 + rclcpp::Node::SharedPtr node_; + rclcpp::Publisher::SharedPtr imu_pub_; + rclcpp::Publisher::SharedPtr rgb_pub_; + rclcpp::Publisher::SharedPtr cloud_pub_; + rclcpp::Publisher::SharedPtr xyzrgbacloud_pub_; + rclcpp::Publisher::SharedPtr odom_publisher_; + rclcpp::Publisher::SharedPtr odom_highfreq_publisher_; + rclcpp::Publisher::SharedPtr path_publisher_; + rclcpp::Publisher::SharedPtr rendered_cloud_pub_; + rclcpp::Publisher::SharedPtr rgbcloud_pub_; + rclcpp::Publisher::SharedPtr rgbFromnv12_pub_; + rclcpp::Publisher::SharedPtr compressed_rgb_pub_; // New compressed image publisher + rclcpp::Publisher::SharedPtr undistort_rgb_pub_; + rclcpp::Publisher::SharedPtr intensity_gray_pub_; + rclcpp::Publisher::SharedPtr pub_camera_pose_visual_; + rclcpp::Publisher::SharedPtr wiwc_publisher_; + camera_pose_visualization cameraposevisual_; + std::unique_ptr tf_broadcaster; + std::thread tf_thread_; + std::atomic tf_thread_running_{false}; + + // Cached TF for timer-based re-publishing + struct CachedTf { + geometry_msgs::msg::TransformStamped msg; + std::chrono::steady_clock::time_point cache_time; + double orig_stamp_sec{0.0}; // original device timestamp in seconds + double last_published_sec{0.0}; // monotonicity guard + }; + std::mutex tf_cache_mutex_; + CachedTf cached_tf_; + bool has_cached_tf_ = false; + #else + ros::Publisher imu_pub_; + ros::Publisher rgb_pub_; + ros::Publisher cloud_pub_; + ros::Publisher xyzrgbacloud_pub_; + ros::Publisher odom_publisher_; + ros::Publisher odom_highfreq_publisher_; + ros::Publisher path_publisher_; + ros::Publisher pub_camera_pose_visual_; + camera_pose_visualization cameraposevisual_; + ros::Publisher rendered_cloud_pub_; + ros::Publisher rgbcloud_pub_; + ros::Publisher rgbFromnv12_pub_; + ros::Publisher compressed_rgb_pub_; // New compressed image publisher + ros::Publisher undistort_rgb_pub_; + ros::Publisher intensity_gray_pub_; + ros::Publisher wiwc_publisher_; + std::unique_ptr tf_broadcaster; + #endif +}; + +class CommandLineControl { +public: + using Callback = std::function; + + + void register_key(const std::string& key, int default_value = 0) { + std::lock_guard lock(mtx); + kv_map[key] = default_value; + } + + void set(const std::string& key, int value) { + Callback cb_to_invoke = nullptr; + { + std::lock_guard lock(mtx); + auto it = kv_map.find(key); + if (it != kv_map.end()) { + if (it->second != value) { + it->second = value; + cb_to_invoke = callback; + } + } else { + return; + } + } + + if (cb_to_invoke) { + cb_to_invoke(key, value); + } + } + + int get(const std::string& key) const { + std::lock_guard lock(mtx); + auto it = kv_map.find(key); + return (it != kv_map.end()) ? it->second : -1; + } + + + void register_callback(Callback cb) { + std::lock_guard lock(mtx); + callback = cb; + } + +private: + std::unordered_map kv_map; + std::thread input_thread; + std::atomic running; + mutable std::mutex mtx; + Callback callback; + +}; + +#define STREAMCTRL "streamctrl" /* start/stop all streams */ +#define SENDRGB "sendrgb" /* send RGB data */ +#define SENDIMU "sendimu" /* send IMU data */ +#define SENDODOM "sendodom" /* send odometry data */ +#define SENDDTOF "senddtof" /* send raw cloud data */ +#define SENDCLOUDSLAM "sendcloudslam" /* send rgb cloud data */ +#define EXIT "q" /* exit sample */ \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/include/image_overlay_node.hpp b/sru_ws/src/odin_ros_driver/include/image_overlay_node.hpp new file mode 100644 index 0000000..c0e6817 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/image_overlay_node.hpp @@ -0,0 +1,101 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#ifdef ROS2 + #include + #include + // cv_bridge header: ROS2 humble+ provides cv_bridge.hpp; ROS2 jazzy removes the legacy .h. + // Prefer .hpp when available, fall back to .h for older ROS distros (e.g. foxy/galactic). + #if defined(__has_include) + # if __has_include() + # include + # else + # include + # endif + #else + # include + #endif + #include +#else + #include + #include + #include + #include + #include + #include +#endif + +#include +#include +#include + +#ifdef ROS2 +class ImageOverlayNode : public rclcpp::Node +{ +public: + ImageOverlayNode(const rclcpp::NodeOptions& options = rclcpp::NodeOptions()); + +private: + using Image = sensor_msgs::msg::Image; + + std::string reprojected_topic_; + std::string camera_topic_; + std::string overlay_topic_; + double alpha_; // blend alpha for overlay + + rclcpp::Subscription::SharedPtr reproj_sub_; + rclcpp::Subscription::SharedPtr camera_sub_; + rclcpp::Publisher::SharedPtr overlay_pub_; + + // Cache latest images + cv::Mat latest_reproj_img_; + cv::Mat latest_camera_img_; + std_msgs::msg::Header latest_header_; + std::mutex mutex_; + + void reprojCallback(Image::ConstSharedPtr msg); + void cameraCallback(Image::ConstSharedPtr msg); + void publishOverlay(); +}; +#else +#include +class ImageOverlayNode +{ +public: + ImageOverlayNode(ros::NodeHandle& nh, ros::NodeHandle& pnh); + +private: + ros::NodeHandle nh_, pnh_; + + std::string reprojected_topic_; + std::string camera_topic_; + std::string overlay_topic_; + double alpha_; // blend alpha for overlay + + ros::Subscriber reproj_sub_; + ros::Subscriber camera_sub_; + ros::Publisher overlay_pub_; + + // Cache latest images + cv::Mat latest_reproj_img_; + cv::Mat latest_camera_img_; + std_msgs::Header latest_header_; + std::mutex mutex_; + + void reprojCallback(const sensor_msgs::ImageConstPtr& msg); + void cameraCallback(const sensor_msgs::ImageConstPtr& msg); + void publishOverlay(); +}; +#endif diff --git a/sru_ws/src/odin_ros_driver/include/lidar_api.h b/sru_ws/src/odin_ros_driver/include/lidar_api.h new file mode 100644 index 0000000..b21e78d --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/lidar_api.h @@ -0,0 +1,803 @@ +#ifndef LIDAR_API_H +#define LIDAR_API_H + +/** + * @file lidar_api.h + * @brief LiDAR device API for controlling and accessing LiDAR sensor data + * + * This header provides the public interface for interacting with LiDAR devices. + * It includes functions for device management, data streaming control, and + * device configuration. + * + * @copyright Copyright (c) 2025, Manifold Tech Limited, All Rights Reserved + * @version 1.0 + * + * ┌──────────────────────────────────────────────────────────────────────────────┐ + * │ QUICK START │ + * ├──────────────────────────────────────────────────────────────────────────────┤ + * │ 1. API Call Sequence (typical usage): │ + * │ │ + * │ lidar_system_init(device_cb) // Initialize system, register device cb│ + * │ ↓ │ + * │ [Wait for device_cb with attach=true to get device info] │ + * │ ↓ │ + * │ lidar_create_device(&dev_info, &handle) // Create device handle │ + * │ ↓ │ + * │ lidar_register_stream_callback(handle, cb_info) // Register data callback│ + * │ ↓ │ + * │ lidar_open_device(handle) // Connect to device │ + * │ ↓ │ + * │ lidar_set_mode(handle, mode) // Set RAW or SLAM mode │ + * │ ↓ │ + * │ lidar_start_stream(handle, type, odr) // Start specific data stream │ + * │ ↓ │ + * │ [Data arrives via registered callback] │ + * │ ↓ │ + * │ lidar_stop_stream(handle, type) // Stop data stream │ + * │ ↓ │ + * │ lidar_close_device(handle) // Disconnect │ + * │ ↓ │ + * │ lidar_destory_device(handle) // Release device handle │ + * │ ↓ │ + * │ lidar_system_deinit() // Cleanup system resources │ + * │ │ + * ├──────────────────────────────────────────────────────────────────────────────┤ + * │ 2. Operating Modes and Available Data Types: │ + * │ │ + * │ LIDAR_MODE_RAW: │ + * │ - LIDAR_DT_RAW_RGB (RGB camera image, NV12 format) │ + * │ - LIDAR_DT_RAW_IMU (IMU data at 400Hz) │ + * │ - LIDAR_DT_RAW_DTOF (DTOF depth + point cloud + confidence) │ + * │ - LIDAR_DT_DEV_STATUS (Device status info) │ + * │ - LIDAR_DT_NTP (PTP/NTP sync data) │ + * │ │ + * │ LIDAR_MODE_SLAM: │ + * │ - All RAW mode types, plus: │ + * │ - LIDAR_DT_SLAM_CLOUD (SLAM point cloud, XYZRGBA) │ + * │ - LIDAR_DT_SLAM_ODOMETRY (SLAM odometry at ~10Hz) │ + * │ - LIDAR_DT_SLAM_ODOMETRY_HIGHFREQ (Odometry at IMU rate ~400Hz) │ + * │ - LIDAR_DT_SLAM_ODOMETRY_TF (Map-Odom transform) │ + * │ │ + * ├──────────────────────────────────────────────────────────────────────────────┤ + * │ 3. activate_stream_type vs start_stream: │ + * │ │ + * │ lidar_activate_stream_type(): │ + * │ - Configure which stream types are enabled in device │ + * │ - Can enable multiple types before starting │ + * │ - Does NOT start data transmission │ + * │ │ + * │ lidar_start_stream(): │ + * │ - Actually starts data transmission for the specified type │ + * │ - Callback will begin receiving data after this call │ + * │ │ + * │ Typical flow: │ + * │ activate_stream_type(LIDAR_DT_RAW_IMU); // Enable IMU │ + * │ activate_stream_type(LIDAR_DT_RAW_DTOF); // Enable DTOF │ + * │ start_stream(LIDAR_DT_RAW_IMU, ...); // Start IMU stream │ + * │ start_stream(LIDAR_DT_RAW_DTOF, ...); // Start DTOF stream │ + * │ │ + * ├──────────────────────────────────────────────────────────────────────────────┤ + * │ 4. Callback Notes (IMPORTANT): │ + * │ │ + * │ Thread Safety: │ + * │ - Callbacks are invoked from internal SDK threads │ + * │ - Different data types may use different threads │ + * │ - User callback code must be thread-safe │ + * │ │ + * │ Data Lifetime: │ + * │ - Data pointers (pAddr) are ONLY valid during callback execution │ + * │ - If you need to keep data, COPY it before callback returns │ + * │ - Do NOT store or dereference pAddr after callback returns │ + * │ │ + * │ Performance: │ + * │ - Avoid blocking or time-consuming operations in callback │ + * │ - Long callback execution may cause data loss or jitter │ + * │ - For heavy processing, copy data and process in separate thread │ + * │ │ + * ├──────────────────────────────────────────────────────────────────────────────┤ + * │ 5. Error Codes: │ + * │ 0 : Success │ + * │ -1 : General failure │ + * │ -2 : Invalid parameter │ + * │ -3 : Device not found / not connected │ + * │ -4 : Operation timeout │ + * │ -5 : Resource allocation failed │ + * │ │ + * └──────────────────────────────────────────────────────────────────────────────┘ + */ + +#include "lidar_api_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Initialize the LiDAR system + * + * Must be called before any other lidar function to set up the system resources. + * This function starts device discovery and will invoke the callback when devices + * are found or disconnected. + * + * @param cb Callback function for device events: + * - Called with attach=true when a new device is discovered + * - Called with attach=false when a device is disconnected + * - The lidar_device_info_t contains serial number to identify the device + * + * Example callback: + * void device_callback(const lidar_device_info_t* info, bool attach) { + * if (attach) { + * printf("Device connected: %s\n", info->serial); + * // Save info for lidar_create_device() + * } else { + * printf("Device disconnected: %s\n", info->serial); + * } + * } + * + * @return int 0 on success, negative error code on failure + */ +int lidar_system_init(lidar_device_callback_t cb); + +/** + * @brief Deinitialize the LiDAR system + * + * Releases all resources allocated by the system. Should be called when + * application is shutting down. + * + * @return int 0 on success, negative error code on failure + */ +int lidar_system_deinit(void); + +/** + * @brief Create a handle for a LiDAR device + * + * Creates a device handle using the device info received from the device callback. + * The handle is used for all subsequent operations on the device. + * + * @param dev_info Information about the LiDAR device (from lidar_system_init callback) + * - serial: Device serial number (required, used to identify device) + * - model: Device model string + * - online: Device connection status + * @param device [OUTPUT] Pointer to receive the device handle upon success + * @return int 0 on success, negative error code on failure + * + * @note The dev_info should be the same structure received from the device callback + */ +int lidar_create_device(lidar_device_info_t *dev_info, device_handle *device); + +/** + * @brief Destroy a LiDAR device handle + * + * Releases resources associated with the device handle. Must be called + * when the device is no longer needed. + * + * @param device Handle to the device to destroy + * @return int 0 on success, negative error code on failure + */ +int lidar_destory_device(device_handle device); + +/** + * @brief Register callback function for receiving LiDAR data streams + * + * Sets up a callback function that will be called when new data is available. + * All data types use the same callback; use lidar_data_t.type to distinguish. + * + * @param device Handle to the target device + * @param cb Callback info structure: + * - data_callback: Function pointer, signature: void(const lidar_data_t*, void*) + * - user_data: User context pointer passed to callback (can be NULL) + * + * Example: + * void data_callback(const lidar_data_t* data, void* user_data) { + * switch (data->type) { + * case LIDAR_DT_RAW_IMU: + * imu_convert_data_t* imu = (imu_convert_data_t*)data->stream.imageList[0].pAddr; + * // Process IMU data (COPY if needed, pointer invalid after return) + * break; + * case LIDAR_DT_RAW_DTOF: + * // data->stream.imageList[0]: depth + * // data->stream.imageList[1]: point cloud XYZ + * // data->stream.imageList[2]: confidence + * // data->stream.imageList[3]: intensity + * break; + * } + * } + * + * @return int 0 on success, negative error code on failure + * + * @warning Callback is invoked from SDK internal threads. Avoid blocking operations. + * @warning Data pointers are only valid during callback execution. Copy if needed. + */ +int lidar_register_stream_callback(device_handle device, lidar_data_callback_info_t cb); + +/** + * @brief Unregister stream callback for a device + * + * Stops the device from calling back when new data is available. + * + * @param device Handle to the target device + * @return int 0 on success, negative error code on failure + */ +int lidar_unregister_stream_callback(device_handle device); + +/** + * @brief Open a LiDAR device for communication + * + * Establishes a connection to the physical device. + * + * @param device Handle to the device to open + * @return int 0 on success, negative error code on failure + */ +int lidar_open_device(device_handle device); + +/** + * @brief Close a LiDAR device + * + * Closes the connection to the physical device. + * + * @param device Handle to the device to close + * @return int 0 on success, negative error code on failure + */ +int lidar_close_device(device_handle device); + +/** + * @brief Set the operating mode of the LiDAR device + * + * Must be called after lidar_open_device() and before lidar_start_stream(). + * Mode determines which data types are available for streaming. + * + * @param device Handle to the target device + * @param mode Operating mode to set: + * - LIDAR_MODE_RAW: Raw sensor data (RGB, IMU, DTOF) + * - LIDAR_MODE_SLAM: SLAM processing enabled (adds odometry, point cloud) + * @return int 0 on success, negative error code on failure + */ +int lidar_set_mode(device_handle device, int mode); + +/** + * @brief Start data streaming from the device + * + * Begins the flow of data from the device for the specified type. + * After calling this function, registered callbacks will start receiving data. + * + * @param device Handle to the target device + * @param type Type of data stream to start (lidar_data_type_e): + * - LIDAR_DT_RAW_RGB: RGB camera frames + * - LIDAR_DT_RAW_IMU: IMU data at 400Hz + * - LIDAR_DT_RAW_DTOF: Depth sensor data + * - LIDAR_DT_SLAM_CLOUD: SLAM point cloud (requires SLAM mode) + * - LIDAR_DT_SLAM_ODOMETRY: SLAM odometry (requires SLAM mode) + * - etc. (see lidar_data_type_e in lidar_api_type.h) + * @param dtof_subframe_odr [OUTPUT] Returns DTOF subframe interval in microseconds. + * Only meaningful when type=LIDAR_DT_RAW_DTOF. + * For other types, this value can be ignored. + * @return int 0 on success, negative error code on failure + * + * @note You can start multiple stream types simultaneously by calling this + * function multiple times with different types. + */ +int lidar_start_stream(device_handle device, int type, uint32_t &dtof_subframe_odr); + +/** + * @brief Stop data streaming from the device + * + * Stops the flow of data from the device for the specified type. + * + * @param device Handle to the target device + * @param type Type of data stream to stop + * @return int 0 on success, negative error code on failure + */ +int lidar_stop_stream(device_handle device, int type); + +/** + * @brief Activate a specific stream type on the device + * + * Enables a specific data stream type in the device configuration. + * This configures the device to be ready for the stream type, but does NOT + * start actual data transmission. Call lidar_start_stream() to begin streaming. + * + * Use this to pre-configure multiple stream types before starting them: + * activate_stream_type(handle, LIDAR_DT_RAW_IMU); + * activate_stream_type(handle, LIDAR_DT_RAW_DTOF); + * start_stream(handle, LIDAR_DT_RAW_IMU, odr); + * start_stream(handle, LIDAR_DT_RAW_DTOF, odr); + * + * @param device Handle to the target device + * @param type Type of data stream to activate (lidar_data_type_e) + * @return int 0 on success, negative error code on failure + * + * @see lidar_start_stream() to actually begin data transmission + * @see lidar_deactivate_stream_type() to disable a stream type + */ +int lidar_activate_stream_type(device_handle device, int type); + +/** + * @brief Deactivate a specific stream type on the device + * + * Disables a specific data stream type in the device configuration. + * + * @param device Handle to the target device + * @param type Type of data stream to deactivate + * @return int 0 on success, negative error code on failure + */ +int lidar_deactivate_stream_type(device_handle device, int type); + +/** + * @brief Get the calibration file from the device + * @param device Handle to the target device + * @return int 0 on success, negative error code on failure + */ +int lidar_get_calib_file(device_handle device, const char* path); + +/** + * @brief Get device calibration parameters + * + * Retrieves the current calibration parameters from the device. + * + * @param device Handle to the target device + * @param param Pointer to receive the calibration parameters + * @return int 0 on success, negative error code on failure + */ +int lidar_get_calibration(device_handle device, lidar_calibration_t* param); + +/** + * @brief Set device calibration parameters + * + * Applies new calibration parameters to the device. + * + * @param device Handle to the target device + * @param param Pointer to the calibration parameters to set + * @return int 0 on success, negative error code on failure + */ +int lidar_set_calibration(device_handle device, const lidar_calibration_t *param); + +/** + * @brief Set log verbosity level + * + * Controls the amount of log information generated by the LiDAR API. + * + * @param level Log level to set (see level definitions in lidar_api_type.h) + */ +void lidar_log_set_level(lidar_log_level_e level); + +/** + * @brief Get the version information of the LiDAR device + * + * Retrieves version information including firmware, system, and application versions. + * + * @param device Handle to the target device + * @param version struct Pointer to receive the version information + * @return int 0 on success, negative error code on failure + */ +int lidar_get_version(device_handle device,lidar_fireware_version_t *version); + +/** + * @brief Set custom algorithm parameters for the device + * + * Sends custom parameter settings to the device. + * + * @param device Handle to the target device + * @param param_name String name of the parameter to set + * @param value_data Pointer to the value data to set for the parameter + * @param value_length Length of the value data in bytes + * @return int 0 on success, negative error code on failure + */ +int lidar_set_custom_parameter(device_handle device, const char* param_name, const void* value_data, size_t value_length); + +/** + * @brief Get custom algorithm parameters for the device + * + * Get custom parameter settings from the device. + * + * @param device Handle to the target device + * @param param_name String name of the parameter to get + * @param value Integer value to get for the parameter + * @return int 0 on success, negative error code on failure + */ +int lidar_get_custom_parameter(device_handle device, const char* param_name, int* value); + +/** + * @brief Get custom algorithm parameters for the device + * + * Get custom parameter settings from the device. + * + * @param device Handle to the target device + * @param param_name String name of the parameter to get + * @param value Integer value to get for the parameter + * @return int 0 on success, negative error code on failure + */ +int lidar_get_custom_parameter(device_handle device, const char* param_name, int* value); + +/** + * @brief Set the map file used for relocalization + * + * Read & send specified map file to device for relocalization + * + * @param device Handle to the target device + * @param abs_path Absolute path to the map file + * @return int 0 on success, otherwise on failure + */ + int lidar_set_relocalization_map(device_handle device, const char* abs_path); + + /** + * @brief Get the mapping result file from device + * + * Read & send specified map file from device to host + * + * @param device Handle to the target device + * @param dest_dir Destination directory to save the map file + * @param file_name File name to save the map file + * @return int 0 on success, -1 on failure without error code, error code (> 0) otherwise + */ + int lidar_get_mapping_result(device_handle device, const char* dest_dir, const char* file_name); + +/** + * @brief Retrieve device logs to the host. + * + * Requests the device to collect its logs and transfer them to the host. The + * resulting file is written into dest_dir. + * + * @param device Device handle. + * @param dest_dir Destination directory on host (must exist). + * @return 0 on success, negative on failure. + * -1: general error + * -2: another transfer in progress + * -3: transfer timeout/stall + */ +int lidar_get_logs(device_handle device, const char *dest_dir); + +/** + * @brief Save the current map to a file on the host. Synchronous, all-in-one API. + * + * Internally drives the complete save-map state machine, so callers do not need + * to coordinate the multi-step protocol themselves: + * 1) Set custom parameter save_map = 1 on the device (kicks off generation). + * 2) Poll save_map until the device resets it to 0 (map generation finished). + * 3) Pull the resulting file via the standard mapping-result transfer (same as + * lidar_get_mapping_result). + * 4) Return the final status to the caller. + * + * This is the recommended entry point for saving a map. The lower-level pair + * (lidar_set_custom_parameter("save_map") + lidar_get_mapping_result) remains + * available for advanced use cases. + * + * 同步保存地图到主机上的文件。一站式 API,内部完成「触发生成 → 等待设备完成 → + * 拉取文件」的完整流程,调用方无需自行轮询和处理异步状态。 + * + * @param device Device handle. + * @param dest_dir Host directory to save the file into (must already exist). + * @param file_name File name (e.g. "map.bin"). + * @param gen_timeout_ms Maximum time (ms) to wait for the device to finish + * generating the map. Pass 0 to use the default (300000 ms). + * @return int + * 0 success, file saved at dest_dir/file_name + * -1 invalid arguments (null device/dir, SDK not initialized, etc.) + * -2 device is busy with another file transfer + * -3 timed out waiting for the device to finish map generation + * -4 file transfer stalled or failed (see logs for details) + * other negative values are propagated from the underlying transfer. + */ +int lidar_save_map(device_handle device, + const char *dest_dir, + const char *file_name, + uint32_t gen_timeout_ms); + +/** + * @brief Set the image mask file for the device + * + * Read & send specified image mask file to device + * + * @param device Handle to the target device + * @param abs_path Absolute path to the image mask file (e.g., mask.png) + * @return int 0 on success, -1 on failure, -2 if file transfer in progress + */ + int lidar_set_image_mask(device_handle device, const char* abs_path); + + /** + * @brief enable encrypted device log + * + * enable encrypted device log, save to specified directory + * Please send to our support when needed + * + * @param device Handle to the target device + * @param dest_dir Destination directory to save the encrypted logs + * @return int 0 on success, -1 on failure + */ + int lidar_enable_encrypted_device_log(device_handle device, const char* dest_dir); + + +/** + * @brief Set the depth parameters for the device + * + * This function must be called before starting data stream. + * + * @param device Handle to the target device + * @param params Pointer to the depth parameters to set + * @return int 0 on success, negative error code on failure + */ +int lidar_set_depth_parameter(device_handle device, const lidar_depth_para_t *params); + +/** + * @brief Set RGB camera configuration (format, resolution, frame rate) + * + * Configures the RGB image sensor before streaming starts. Must be called + * after lidar_open_device() and before lidar_start_stream(). + * + * The device replies with CMD_CODE_OK on success or CMD_CODE_FAIL if the + * requested combination is unsupported. + * + * RGB frame rate is coupled with the DTOF frame rate. Only three frame-rate + * tiers are supported (the fps field in lidar_rgb_para_t is multiplied by 10): + * + ######################################################## + # RGB camera configuration (format, resolution, frame rate) + # RGB 摄像头配置(格式、分辨率、帧率) + # + # Applied via lidar_set_rgb_parameter() before streaming starts. + # 在数据流启动前通过 lidar_set_rgb_parameter() 下发。 + # + # ATTENTION: not all combinations are valid; invalid values will + # cause device connection failure. 无效组合会导致设备连接失败。 + # + # RGB frame rate is coupled with the DTOF frame rate, so both must + # be set to one of the matching pairs below (3 tiers supported): + # RGB 帧率与 DTOF 帧率联动,二者需按下表配对设置(支持三档): + # + # rgb_fps | dtof_fps | RGB actual rate | DTOF actual rate + # --------+----------+----------------+---------------- + # 100 | 100 | 10.264 Hz | 10.0 Hz + # 145 | 145 | 14.472 Hz | 14.5 Hz + # 290 | 100 | 28.92 Hz | 10.0 Hz + ######################################################## + * + * An invalid combination will cause device connection failure. + * + * @param device Handle to the target device + * @param params Pointer to RGB configuration parameters (see lidar_rgb_para_t) + * @return int 0 on success, negative error code on failure + */ +int lidar_set_rgb_parameter(device_handle device, const lidar_rgb_para_t *params); + +/** + * @brief Enable or disable IMU smooth sending feature + * + * When enabled, IMU data will be sent at precise intervals (default 400Hz) + * using a dedicated high-priority thread to reduce jitter and timing variance. + * When disabled, IMU data will be sent immediately upon reception. + * + * @param enable 1 to enable smooth sending, 0 to disable + * @return int 0 on success, -1 on failure + */ +int lidar_enable_imu_smooth_sending(int enable); + +/** + * @brief Set IMU smooth sending frequency + * + * Set the target frequency for IMU smooth sending. Only effective when + * smooth sending is enabled via lidar_enable_imu_smooth_sending(). + * + * @param frequency_hz Target frequency in Hz (1-1000 Hz, recommended 400 Hz) + * @return int 0 on success, -1 on failure + */ +int lidar_set_imu_smooth_frequency(uint32_t frequency_hz); + +/** + * @brief Enable or disable SPAD crosstalk filter for DTOF point cloud + * + * When enabled, the SDK applies a multi-stage noise filter on raw DTOF + * point cloud data before delivering it to the user callback: + * - String noise detection (gradient-based) + * - Crosstalk detection (confidence-based edge point detection) + * - Distance filtering (min/max range) + * - FOV edge filtering (135 degrees) + * - Intensity threshold filtering (distance-dependent) + * - Confidence filtering (distance-dependent) + * + * Filtered points have their XYZ values set to 0.0 in the callback data. + * Only applies to the new 4-channel DTOF format (depth + xyz + intensity + confidence). + * Has no effect on the legacy 3-channel format. + * + * @param enable 1 to enable SPAD crosstalk filter, 0 to disable + * @return int 0 on success, -1 on failure (SDK not initialized) + */ +int lidar_enable_spad_filter(int enable); + +/** + * @brief Reset the USB connection to the device + * + * Performs a USB port reset on the device (libusb_reset_device). This + * re-enumerates the device on the host without requiring a physical + * re-plug. The device handle should typically be reopened after the + * device reconnects. + * + * @param device Handle to the target device + * @return int 0 on success, negative error code on failure + */ +int lidar_reset_usb(device_handle device); + +/** + * @brief Query the current device initial/running state. + * + * Returns the latest state reported by the device through heartbeats. The + * value corresponds to ::lidar_device_initial_state_e (NONE, + * NOT_INITIALIZED, INITIALIZED, STREAMING, STREAM_STOPPED). Callers that + * need to wait until the device is fully booted (for example before + * uploading a relocalization map) should poll this until it becomes + * LIDAR_DEVICE_STREAMING (or LIDAR_DEVICE_INITIALIZED at minimum). + * + * + * @param state Output pointer that receives the current state. Must not be NULL. + * @return int 0 on success, negative error code on failure. + */ +int lidar_get_device_state(lidar_device_initial_state_e *state); + +/** + * @brief Send a host-defined pass-through user-data blob to the device. + * + * The device forwards data[] as-is to SLAM via shared memory + * ("user_data_shm"). No acknowledgment is returned from the device + * (fire-and-forget). An SDK-internal monotonic counter is packed into + * the on-wire frameId field so SLAM can still distinguish consecutive + * frames without the caller having to manage an id. + * + * Preconditions: + * - SDK initialized and the device opened (lidar_open_device). + * - SLAM has been started on the device side; otherwise the device + * silently drops the frame and logs a warning. + * + * Constraints: + * - blob != NULL. + * - 0 < blob_len <= 8 MiB (8 * 1024 * 1024). + * - Sending faster than SLAM can consume causes device-side timeouts + * and dropped frames. Pace according to SLAM throughput. + * + * @param device Handle returned by lidar_create_device / lidar_open_device. + * @param blob Pointer to user payload. + * @param blob_len Length in bytes. + * @return int 0 on success, negative error code on failure. + */ +int lidar_send_user_data(device_handle device, + const void *blob, uint32_t blob_len); + +/* --------------------------------------------------------------------- + * Camera AE / AWB control APIs. + * + * All four APIs are synchronous (send + wait response) and serialised by + * an internal mutex (the same mutex protecting other control commands). + * Return value convention: + * == 0 success + * > 0 device-side error, see lidar_ae_error_e / lidar_rgb_error_e + * < 0 SDK-side error (not initialised, bad argument, USB failure, + * response timeout, malformed reply, ...) + * + * Wire-level details: sdk/api/Host_USB_AE_Protocol.md. + * ------------------------------------------------------------------- */ + +/** + * @brief Query current AE (auto exposure) state. + * + * Sends AE opcode 0x01 and decodes the 25-byte little-endian payload + * returned by the device-side ae_control service. + * + * Output fields and their physical meaning: + * exposure_time : current exposure time in seconds (manual range + * 0.0001 .. 0.033; in auto mode it varies with + * scene illumination). + * gain : current analog gain (manual range 1.0 .. 64.0; + * higher = brighter but noisier). + * iso : equivalent ISO, typically 100 .. 6400. + * brightness : average frame brightness (0 .. 255). + * is_converged : 1 = AE has settled, 0 = still adjusting. + * env_lv : ambient luminance index, typically 0 .. 15 + * (higher = brighter scene). + * fps : actual frame rate, follows dtof_fps config + * (~10 / 14.5 / 29 Hz). + * + * @param device Device handle returned by lidar_create_device / lidar_open_device. + * @param out Output buffer, must not be NULL. + * @return See return value convention above. + */ +int lidar_get_ae_info(device_handle device, lidar_ae_info_t *out); + +/** + * @brief Query current AWB (auto white balance) state. + * + * Sends AE opcode 0x30 and decodes the 25-byte little-endian payload. + * + * Output fields and their physical meaning: + * rgain : R channel gain (manual range 0.1 .. 4.0). + * grgain : Gr channel gain, always 1.0 (device-fixed). + * gbgain : Gb channel gain, always 1.0 (device-fixed). + * bgain : B channel gain (manual range 0.1 .. 4.0). + * cct : correlated color temperature in Kelvin + * (typically 2500 .. 8000 K). + * ccri : color temperature deviation index (-50 .. 50, + * signed; 0 means on the Planckian locus). + * is_converged : 1 = AWB has settled, 0 = still adjusting. + * + * @param device Device handle. + * @param out Output buffer, must not be NULL. + * @return See return value convention above. + */ +int lidar_get_awb_info(device_handle device, lidar_awb_info_t *out); + +/** + * @brief Set AE mode and (in manual mode) exposure/gain. + * + * Behaviour: + * - mode == LIDAR_CAM_MODE_AUTO : sends opcode 0x02 only; + * exposure_time / gain are ignored. + * - mode == LIDAR_CAM_MODE_MANUAL : sends opcode 0x03 to switch to + * manual AE, then opcode 0x06 to + * apply (exposure_time, gain). + * + * Parameter ranges and physical meaning + * (manual mode only; out-of-range returns rc = 403): + * + * exposure_time : 0.0001 s .. 0.033 s + * Sensor exposure time per frame. Longer = brighter but more + * motion blur and lower effective fps if it exceeds the frame + * period (1/fps). For dtof_fps = 290 (29 Hz, period ~34 ms) the + * upper bound 0.033 s is already at the frame limit. + * + * gain : 1.0 .. 64.0 + * Analog gain applied to the raw sensor signal. Higher = brighter + * output but worse SNR. Typical sweet spot: 1.0 .. 8.0 for daylight, + * 8.0 .. 32.0 for indoor / dim light, 32.0 .. 64.0 only when image + * must be visible at any cost. + * + * Recommended starting points by scene: + * bright outdoor : exposure 0.001~0.005 s, gain 1.0~2.0 + * normal indoor : exposure 0.008~0.015 s, gain 2.0~8.0 + * dim light : exposure 0.020~0.030 s, gain 8.0~32.0 + * + * @param device Device handle. + * @param mode See lidar_cam_mode_e. + * @param exposure_time Exposure time in seconds (manual mode only). + * @param gain Analog gain (manual mode only). + * @return See return value convention above. + */ +int lidar_set_ae_param(device_handle device, lidar_cam_mode_e mode, + float exposure_time, float gain); + +/** + * @brief Set AWB mode and (in manual mode) R/B channel gains. + * + * Behaviour: + * - mode == LIDAR_CAM_MODE_AUTO : sends opcode 0x31 only; + * rgain / bgain are ignored. + * - mode == LIDAR_CAM_MODE_MANUAL : sends opcode 0x32 to switch to + * manual AWB, then opcode 0x33 to + * apply (rgain, bgain). Gr/Gb are + * fixed to 1.0 by the device. + * + * Parameter ranges and physical meaning + * (manual mode only; out-of-range returns rc = 403): + * + * rgain : 0.1 .. 4.0 + * Multiplier on the R channel before color matrix. Higher rgain + * relative to bgain shifts the image toward warm (yellow/red). + * + * bgain : 0.1 .. 4.0 + * Multiplier on the B channel. Higher bgain relative to rgain + * shifts the image toward cool (blue). + * + * Color-temperature cookbook (approximate): + * warm (tungsten, sunset) : rgain ~2.0..2.5, bgain ~1.0..1.2 + * neutral (daylight D65) : rgain ~1.5..1.7, bgain ~1.8..2.0 + * cool (cloudy, fluor.) : rgain ~1.2..1.4, bgain ~2.2..2.6 + * + * @param device Device handle. + * @param mode See lidar_cam_mode_e. + * @param rgain R channel gain (manual mode only). + * @param bgain B channel gain (manual mode only). + * @return See return value convention above. + */ +int lidar_set_awb_param(device_handle device, lidar_cam_mode_e mode, + float rgain, float bgain); + +#ifdef __cplusplus +} +#endif + +#endif // LIDAR_API_H diff --git a/sru_ws/src/odin_ros_driver/include/lidar_api_type.h b/sru_ws/src/odin_ros_driver/include/lidar_api_type.h new file mode 100644 index 0000000..c22ef0d --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/lidar_api_type.h @@ -0,0 +1,503 @@ +#ifndef LIDAR_TYPES_H +#define LIDAR_TYPES_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define LIDAR_SERIAL_MAX 64 +#define LIDAR_MODEL_MAX 64 +#define LIDAR_IP_MAX 64 + +typedef void * device_handle; + +typedef enum { + LIDAR_LOG_ERROR = 0, + LIDAR_LOG_WARN, + LIDAR_LOG_INFO, + LIDAR_LOG_DEBUG, +} lidar_log_level_e; + +typedef enum { + LIDAR_OTA_ALGORITHM, + LIDAR_OTA_FIRMWARE, + LIDAR_OTA_SCRIPT, + LIDAR_OTA_CALIBRATION +} lidar_ota_type_e; + +typedef enum { + LIDAR_MODE_RAW, + LIDAR_MODE_SLAM, +} lidar_mode_e; + +/** + * @brief Data types for lidar_data_callback_t + * + * Each type corresponds to a specific stream format in lidar_data_t.stream (capture_Image_List_t). + * + * ┌─────────────────────────────────────────────────────────────────────────────────────────────┐ + * │ LIDAR_DT_RAW_RGB │ + * │ imageCount: 1 │ + * │ imageList[0]: NV12 image data │ + * │ - pAddr: uint8_t* (Y plane followed by UV plane) │ + * │ - width: 1600, height: 1296 │ + * │ - length: width * height * 3 / 2 bytes │ + * ├─────────────────────────────────────────────────────────────────────────────────────────────┤ + * │ LIDAR_DT_RAW_IMU │ + * │ imageCount: 1 │ + * │ imageList[0]: IMU data │ + * │ - pAddr: imu_convert_data_t* │ + * │ - accel[3]: float (m/s^2) │ + * │ - gyro[3]: float (rad/s) │ + * │ - stamp: uint64_t (ns) │ + * │ - sequence: uint64_t │ + * │ - length: sizeof(imu_convert_data_t) │ + * ├─────────────────────────────────────────────────────────────────────────────────────────────┤ + * │ LIDAR_DT_RAW_DTOF │ + * │ imageCount: 4 │ + * │ Resolution: 256 x 192 │ + * │ imageList[0]: Depth image │ + * │ - pAddr: float* (depth in meters) │ + * │ - length: 256 * 192 * sizeof(float) │ + * │ imageList[1]: Point cloud XYZ │ + * │ - pAddr: float* (x,y,z interleaved) │ + * │ - length: 256 * 192 * 3 * sizeof(float) │ + * │ imageList[2]: Intensity/Reflectivity │ + * │ - pAddr: uint8_t* │ + * │ - length: 256 * 192 * sizeof(uint8_t) │ + * │ imageList[3]: Confidence │ + * │ - pAddr: uint16_t* │ + * │ - length: 256 * 192 * sizeof(uint16_t) │ + * ├─────────────────────────────────────────────────────────────────────────────────────────────┤ + * │ LIDAR_DT_SLAM_CLOUD │ + * │ imageCount: 1 │ + * │ imageList[0]: SLAM point cloud (XYZRGBA, fixed-point on the wire) │ + * │ - pAddr: slam_cloud_point_t* (7 * int32_t per point, see struct below) │ + * │ - length: num_points * sizeof(slam_cloud_point_t) ( == num_points * 28 bytes ) │ + * │ xyz are stored in 0.1 mm units: meters = xyz * SLAM_CLOUD_XYZ_TO_M │ + * ├─────────────────────────────────────────────────────────────────────────────────────────────┤ + * │ LIDAR_DT_SLAM_ODOMETRY / LIDAR_DT_SLAM_ODOMETRY_HIGHFREQ / LIDAR_DT_SLAM_ODOMETRY_TF │ + * │ imageCount: 1 │ + * │ imageList[0]: Odometry data │ + * │ - pAddr: ros_odom_convert_complete_t* │ + * │ - timestamp_ns: uint64_t │ + * │ - pos[3]: int64_t (x,y,z in μm, divide by 1e6 for meters) │ + * │ - orient[4]: int64_t (quaternion x,y,z,w, divide by 1e6) │ + * │ - linear_velocity[3]: int64_t │ + * │ - angular_velocity[3]: int64_t │ + * │ - pose_cov[36]: double │ + * │ - twist_cov[36]: double │ + * │ - length: sizeof(ros_odom_convert_complete_t) │ + * ├─────────────────────────────────────────────────────────────────────────────────────────────┤ + * │ LIDAR_DT_DEV_STATUS │ + * │ imageCount: 1 │ + * │ imageList[0]: Device status │ + * │ - pAddr: lidar_device_status_t* │ + * │ - length: sizeof(lidar_device_status_t) │ + * ├─────────────────────────────────────────────────────────────────────────────────────────────┤ + * │ LIDAR_DT_NTP │ + * │ imageCount: 1 │ + * │ imageList[0]: PTP/NTP sync data │ + * │ - pAddr: ptp_sync_data_t* │ + * │ - delay: double │ + * │ - offset: double │ + * │ - length: sizeof(ptp_sync_data_t) │ + * └─────────────────────────────────────────────────────────────────────────────────────────────┘ + */ +typedef enum { + LIDAR_DT_NONE = 0, /**< No data */ + LIDAR_DT_RAW_RGB, /**< RGB image (NV12 format, 1536x1280) */ + LIDAR_DT_RAW_IMU, /**< IMU data (imu_convert_data_t) */ + LIDAR_DT_RAW_DTOF, /**< DTOF raw data (depth + xyz + confidence + intensity, 256x192) */ + LIDAR_DT_SLAM_CLOUD, /**< SLAM point cloud (XYZRGBA) */ + LIDAR_DT_SLAM_ODOMETRY, /**< SLAM odometry (ros_odom_convert_complete_t) */ + LIDAR_DT_DEV_STATUS, /**< Device status (lidar_device_status_t) */ + LIDAR_DT_SLAM_ODOMETRY_HIGHFREQ,/**< High frequency odometry (ros_odom_convert_complete_t) */ + LIDAR_DT_SLAM_ODOMETRY_TF, /**< Map-Odom TF transform (ros_odom_convert_complete_t) */ + LIDAR_DT_SLAM_WIWC, /**< WIWC odometry */ + LIDAR_DT_NTP /**< PTP/NTP sync data (ptp_sync_data_t) */ +} lidar_data_type_e; + +typedef struct { + int8_t serial[LIDAR_SERIAL_MAX]; + int8_t model[LIDAR_MODEL_MAX]; + bool online; + uint32_t initial_state; +} lidar_device_info_t; + +typedef struct { + float x, y, z; + float intensity; +} lidar_point_t; + + +typedef struct { + float intrinsics[9]; + float extrinsics[16]; +} lidar_calibration_t; + + +#define DEVICE_MAX_CH_NUMBER 4 + +typedef struct { + uint64_t timestamp_ns; + int64_t pos[3]; + int64_t orient[4]; +} ros2_odom_convert_t; + +typedef struct { + uint64_t timestamp_ns; + int64_t pos[3]; // x, y, z in μm + int64_t orient[4]; // quaternion x, y, z, w in 1e6 precision + int64_t linear_velocity[3]; + int64_t angular_velocity[3]; + double pose_cov[36]; + double twist_cov[36]; +} ros_odom_convert_complete_t; + +typedef struct { + double delay; + double offset; +} ptp_sync_data_t; + +/* --------------------------------------------------------------------- + * SLAM cloud wire format. + * + * One LIDAR_DT_SLAM_CLOUD point on the bus is a 7 * int32_t record: + * xyz[0..2] : x, y, z in 0.1 mm fixed-point. + * meters = xyz * SLAM_CLOUD_XYZ_TO_M. + * rgba[0..3]: r, g, b, a; each stored in the low byte of an int32_t. + * + * Consumers (SDK hooks, ROS driver, etc.) should reference this struct + * and the scale macro below as the single source of truth rather than + * re-hardcoding the stride or the divisor. + * ------------------------------------------------------------------- */ +#define SLAM_CLOUD_XYZ_TO_M (1.0e-4) /* device 0.1mm units -> meters */ +#define SLAM_CLOUD_XYZ_FROM_M (1.0e4) /* meters -> device 0.1mm units */ + +typedef struct { + int32_t xyz[3]; /* x, y, z in 0.1 mm fixed-point */ + int32_t rgba[4]; /* r, g, b, a; only low byte of each is meaningful */ +} slam_cloud_point_t; + +typedef struct icm_6aixs_data_t { + int16_t aacx; + int16_t aacy; + int16_t aacz; + int16_t gyrox; + int16_t gyroy; + int16_t gyroz; + uint8_t valid; + uint32_t nums; + uint8_t fsync_pack; + uint16_t interval; + uint64_t stamp; +} icm_6aixs_data_t; + +typedef struct { + float accel_x; + float accel_y; + float accel_z; + float gyro_x; + float gyro_y; + float gyro_z; + uint64_t stamp; + uint64_t sequence; +} imu_convert_data_t; + + typedef struct { + uint32_t length; + uint64_t sequence; + uint64_t timestamp; + uint64_t interval; + void* pAddr; + uint32_t width; + uint32_t height; + uint32_t format; /**< Pixel format: 0=NV12, 1=MJPEG (see lidar_rgb_format_e); 0 for non-RGB frames */ +} buffer_List_t; + +typedef struct capture_Image_List_t { + uint32_t imageCount; + buffer_List_t imageList[DEVICE_MAX_CH_NUMBER]; +} capture_Image_List_t; + +typedef struct { + uint32_t type; + capture_Image_List_t stream; +} lidar_data_t; + +typedef void (*lidar_device_callback_t)(const lidar_device_info_t* device, bool attach); +typedef void (*lidar_data_callback_t)(const lidar_data_t *data, void *user_data); + +typedef struct { + lidar_data_callback_t data_callback; + void *user_data; +} lidar_data_callback_info_t; + +typedef struct { + int major; + int minor; + int patch; +}lidar_version_t; + +typedef struct { + lidar_version_t kernel_version; + lidar_version_t mcu_version; + lidar_version_t soc_version; + lidar_version_t Daemon_proc_version; + lidar_version_t slam_version; +} lidar_fireware_version_t; + +/** + * @brief RGB image sensor frame rate + * + */ + typedef struct{ + + int configured_odr;/*rgb image sensor frame rate, offset: */ + int tx_odr;/*The actual rgb image sensor frame rate, offset: */ + +} lidar_rgb_sensor_status_t; + +/** + * @brief DTOF Lidar frame rate + * + */ +typedef struct{ + + int configured_odr;/* dtof lidar sensor frame rate, offset: */ + int tx_odr;/*The actual dtof lidar sensor frame rate, offset: */ + int subframe_odr;/*DTOF 6行为一组 这个是组间隔时间*/ + short tx_temp;/* dtof lidar tx temp offset: */ + short rx_temp;/* dtof lidar rx temp offset: */ + +} lidar_dtof_sensor_status_t; + +/** + * @brief IMU Sensor + * + */ +typedef struct{ + + int configured_odr; + int tx_odr; + +} lidar_imu_sensor_status_t; + +typedef struct{ + + int package_temp;/*SOC整体温度*/ + // int bigcore_temp;/*大核集群温度:4*A76*/ + // int littlecore_temp;/*小核集群温度:4*A53*/ + int cpu_temp; + int center_temp;/*SOC中心温度:4*A53*/ + int gpu_temp;/* GPU模块温度 */ + int npu_temp;/* NPU模块温度 */ + +} lidar_soc_thermal_t; +typedef struct +{ + double uptime_seconds; + lidar_soc_thermal_t soc_thermal; /*offset: 0*/ + + int cpu_use_rate[8];/*cpu 使用率,offset: */ + int ram_use_rate;/*运行内存使用率 ,offset: */ + + lidar_rgb_sensor_status_t rgb_sensor; + lidar_dtof_sensor_status_t dtof_sensor; + lidar_imu_sensor_status_t imu_sensor; + + int slam_cloud_tx_odr; /* Actual frame rate of slam cloud offset: */ + int slam_odom_tx_odr; /* Actual frame rate of slam odom offset: */ + int slam_odom_highfreq_tx_odr; /* Actual frame rate of slam odom offset: */ + +} lidar_device_status_t; + +typedef enum { + LIDAR_DEVICE_NONE = 0, + LIDAR_DEVICE_NOT_INITIALIZED, + LIDAR_DEVICE_INITIALIZED, + LIDAR_DEVICE_STREAMING, + LIDAR_DEVICE_STREAM_STOPPED, +} lidar_device_initial_state_e; + +typedef enum { + LIDAR_DEPTH_ODR_10HZ = 0, + LIDAR_DEPTH_ODR_14_5HZ = 1, + LIDAR_DEPTH_ODR_29HZ = 2, +} lidar_depth_odr_e; + +typedef struct { + lidar_depth_odr_e odr; +} lidar_depth_para_t; + +/* --------------------------------------------------------------------- + * RGB camera configuration types. + * + * The host SDK sends the configuration through the standard USB control + * channel (CMD_CODE_CONTROL_CMD + SYS_CONTROL_RGB_SET_CONFIG). The + * device-side lydapp applies the settings to the RGB image sensor before + * streaming starts. See sdk/api/Host_USB_RGB_Config_Protocol.md for the + * wire-level details. + * ------------------------------------------------------------------- */ + +/** + * @brief RGB camera pixel format + */ +typedef enum { + LIDAR_RGB_FMT_NV12 = 0, /**< NV12 (default, 1536x1280) */ + LIDAR_RGB_FMT_MJPEG = 1, /**< Motion JPEG compressed */ +} lidar_rgb_format_e; + +/** + * @brief RGB camera configuration parameters + * + * Used with lidar_set_rgb_parameter(). Must be called after + * lidar_open_device() and before lidar_start_stream(). + * + * Field meaning and valid ranges: + * format : pixel format, see lidar_rgb_format_e + * width : image width in pixels (device-dependent, e.g. 1600) + * height : image height in pixels (device-dependent, e.g. 1296) + * fps : target frame rate * 10 (e.g. 300 = 30fps, 145 = 14.5fps) + * + * Not all combinations are valid. Invalid combinations return rc = -1 + * with device-side CMD_CODE_FAIL. Use lidar_get_device_status() to + * verify the actual configured_odr after setting. + */ +typedef struct { + lidar_rgb_format_e format; + uint32_t width; + uint32_t height; + uint32_t fps; +} lidar_rgb_para_t; + +/* --------------------------------------------------------------------- + * Camera AE / AWB control types. + * + * The host SDK forwards AE/AWB requests through the USB control channel + * (CMD_CODE_CONTROL_CMD + SYS_CONTROL_AE_UDP). The device-side lydapp + * relays them via UDP loopback to its ISP service. See + * sdk/api/Host_USB_AE_Protocol.md for the wire-level details. + * ------------------------------------------------------------------- */ + +/** + * @brief AE/AWB control mode used by lidar_set_ae_param / lidar_set_awb_param. + * + * - AUTO : the device runs its own AE/AWB convergence loop. The two + * float parameters of the corresponding Set call are ignored. + * - MANUAL : the device locks AE/AWB and applies the user-supplied + * (exposure_time, gain) or (rgain, bgain). Out-of-range + * values are rejected with rc = 403 + * (LIDAR_AE_PARAM_OUT_OF_RANGE). + */ +typedef enum { + LIDAR_CAM_MODE_AUTO = 0, /**< switch to auto AE / AWB */ + LIDAR_CAM_MODE_MANUAL = 1, /**< switch to manual AE / AWB and apply params */ +} lidar_cam_mode_e; + +/** + * @brief Current AE status returned by lidar_get_ae_info(). + * + * Field-by-field meaning and typical range: + * + * exposure_time : current sensor exposure time, in seconds. + * Manual-mode valid range: 0.0001 .. 0.033. + * In auto mode varies with scene illumination. + * gain : current analog gain (linear, not dB). + * Manual-mode valid range: 1.0 .. 64.0. + * Higher value = brighter output but worse SNR. + * iso : equivalent ISO speed, typically 100 .. 6400. + * Derived from gain; informational only. + * brightness : average frame brightness in [0, 255]. AE target + * converges toward a mid-range value. + * is_converged : 1 = AE has settled, 0 = still adjusting. + * env_lv : ambient luminance index, typically 0 .. 15 + * (higher = brighter scene). + * fps : actual frame rate in Hz, follows dtof_fps config + * (~10 / 14.5 / 29). + */ +typedef struct { + float exposure_time; /**< current exposure time (s), 0.0001..0.033 */ + float gain; /**< current analog gain, 1.0..64.0 */ + int32_t iso; /**< equivalent ISO, ~100..6400 */ + float brightness; /**< average frame brightness, 0..255 */ + uint8_t is_converged; /**< 1 = AE converged, 0 = not converged */ + float env_lv; /**< ambient luminance level, ~0..15 */ + float fps; /**< current frame rate (Hz) */ +} lidar_ae_info_t; + +/** + * @brief Current AWB status returned by lidar_get_awb_info(). + * + * Field-by-field meaning and typical range: + * + * rgain : R channel gain. Manual-mode valid range: 0.1 .. 4.0. + * Raising rgain relative to bgain shifts the image + * toward warm (yellow/red). + * grgain : Gr channel gain. Device-fixed at 1.0, not adjustable. + * gbgain : Gb channel gain. Device-fixed at 1.0, not adjustable. + * bgain : B channel gain. Manual-mode valid range: 0.1 .. 4.0. + * Raising bgain relative to rgain shifts the image + * toward cool (blue). + * cct : correlated color temperature in Kelvin, typically + * 2500 .. 8000 K. + * ccri : color temperature deviation index, signed value + * roughly in -50 .. 50; 0 = on the Planckian locus. + * is_converged : 1 = AWB has settled, 0 = still adjusting. + */ +typedef struct { + float rgain; /**< R channel gain, 0.1..4.0 */ + float grgain; /**< Gr channel gain, device-fixed 1.0 */ + float gbgain; /**< Gb channel gain, device-fixed 1.0 */ + float bgain; /**< B channel gain, 0.1..4.0 */ + float cct; /**< color temperature (K), ~2500..8000 */ + float ccri; /**< color temperature deviation, ~-50..50 */ + uint8_t is_converged; /**< 1 = AWB converged, 0 = not converged */ +} lidar_awb_info_t; + +/** + * @brief AE/AWB device-side error codes. + * + * Mapped to positive return values of lidar_get_ae_info / lidar_set_ae_param / + * lidar_get_awb_info / lidar_set_awb_param when the device replies with + * CMD_CODE_FAIL. See Host_USB_AE_Protocol.md section 6. + */ +typedef enum { + LIDAR_AE_OK = 0, + LIDAR_AE_BAD_REQUEST = 400, /**< payload too short */ + LIDAR_AE_UNSUPPORTED_OPCODE = 401, + LIDAR_AE_BAD_PARAM_LEN = 402, + LIDAR_AE_PARAM_OUT_OF_RANGE = 403, + LIDAR_AE_SOCKET_ERROR = 404, + LIDAR_AE_NO_RESPONSE = 405, /**< ae_control UDP timeout */ + LIDAR_AE_UNKNOWN_OPCODE = 0xFF,/**< status byte from ae_control */ +} lidar_ae_error_e; + +/** + * @brief RGB config device-side error codes. + * + * Mapped to positive return values of lidar_set_rgb_parameter when the + * device replies with CMD_CODE_FAIL, or returned directly by the SDK + * for host-side pre-checks (e.g. LIDAR_RGB_DTOF_NOT_CONFIGURED). + * See Host_USB_RGB_Config_Protocol.md section 8. + */ +typedef enum { + LIDAR_RGB_OK = 0, + LIDAR_RGB_BAD_REQUEST = 500, /**< payload too short */ + LIDAR_RGB_UNSUPPORTED_FORMAT = 501, /**< format not NV12/MJPEG */ + LIDAR_RGB_UNSUPPORTED_RESOLUTION = 502, /**< resolution not supported */ + LIDAR_RGB_UNSUPPORTED_FPS = 503, /**< fps not in capability table */ + LIDAR_RGB_INVALID_COMBINATION = 504, /**< rgb fps + dtof odr combo invalid */ + LIDAR_RGB_DTOF_NOT_CONFIGURED = 505, /**< dtof not set, call lidar_set_depth_parameter first */ +} lidar_rgb_error_e; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/sru_ws/src/odin_ros_driver/include/odin_calib_path.h b/sru_ws/src/odin_ros_driver/include/odin_calib_path.h new file mode 100644 index 0000000..9f059db --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/odin_calib_path.h @@ -0,0 +1,48 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#ifndef ODIN_CALIB_PATH_H +#define ODIN_CALIB_PATH_H + +#include +#include + +// Single source of truth for the calibration file location, shared by the +// writer (host_sdk_sample) and every reader (cloud_reprojection, pcd2depth). +// Header-only inline functions avoid multiple-definition across translation units. +namespace odin_ros_driver { + +// Resolve the writable runtime directory that stores calib.yaml. +// Priority: ODIN_CALIB_DIR -> ROS_HOME -> ~/.ros -> /tmp. +// Works for both ROS1 and ROS2 (~/.ros is the shared default ROS_HOME). +inline std::string GetOdinRuntimeDir() { + if (const char* custom = std::getenv("ODIN_CALIB_DIR")) { + return std::string(custom); + } + if (const char* ros_home = std::getenv("ROS_HOME")) { + return std::string(ros_home) + "/odin_ros_driver"; + } + if (const char* home = std::getenv("HOME")) { + return std::string(home) + "/.ros/odin_ros_driver"; + } + return "/tmp/odin_ros_driver"; +} + +// Canonical calib.yaml path shared by writer and all readers. +inline std::string GetOdinCalibFile() { + return GetOdinRuntimeDir() + "/calib.yaml"; +} + +} // namespace odin_ros_driver + +#endif // ODIN_CALIB_PATH_H diff --git a/sru_ws/src/odin_ros_driver/include/pointcloud_depth_converter.hpp b/sru_ws/src/odin_ros_driver/include/pointcloud_depth_converter.hpp new file mode 100644 index 0000000..ae9226e --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/pointcloud_depth_converter.hpp @@ -0,0 +1,93 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include + + +class PointCloudToDepthConverter +{ +public: + + struct CameraParams + { + int image_width; + int image_height; + double A11, A12, A22; + double u0, v0; + double k2, k3, k4, k5, k6, k7; + double scale; + int point_sampling_rate; + Eigen::Matrix4d Tcl; + }; + + + struct ProcessResult + { + cv::Mat depth_image; + pcl::PointCloud colored_cloud; + bool success; + std::string error_message; + }; + + + explicit PointCloudToDepthConverter(const CameraParams ¶ms); + + + ProcessResult processCloudAndImage(const pcl::PointCloud &cloud, + const cv::Mat &image); + + cv::Mat customResize(const cv::Mat& src, const cv::Size& size); + const CameraParams &getCameraParams() const { return params_; } + + + void updateCameraParams(const CameraParams ¶ms); + +private: + CameraParams params_; + + Eigen::Matrix3d K_; + Eigen::Matrix3d Kl_; + Eigen::Matrix4d K_4x4_; + Eigen::Matrix4d Kcl_; + + cv::Mat map_x_, map_y_; + cv::Mat inv_map_x_, inv_map_y_; + + int scaled_width_, scaled_height_; + + + void initializeInternalParams(); + + + void createDistortionMaps(); + + cv::Mat projectCloudToDepth(const pcl::PointCloud &cloud_in_cam); + + + cv::Mat postProcessDepthImage(const cv::Mat &depth_img); + + + pcl::PointCloud generateColoredCloud(const cv::Mat &depth_img, + const cv::Mat &color_img); + + + std::pair validateInputs(const pcl::PointCloud &cloud, + const cv::Mat &image); +}; \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/include/polynomial_camera.hpp b/sru_ws/src/odin_ros_driver/include/polynomial_camera.hpp new file mode 100644 index 0000000..1de15cb --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/polynomial_camera.hpp @@ -0,0 +1,144 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#pragma once + +#include +#include + +namespace mini_vikit { + +using namespace Eigen; + +class PolynomialCamera { +private: + const double fx_, fy_; + const double cx_, cy_; + const double skew_; + bool distortion_; + double k2_, k3_, k4_, k5_, k6_, k7_; + +public: + EIGEN_MAKE_ALIGNED_OPERATOR_NEW + + PolynomialCamera(double width, double height, + double fx, double fy, double cx, double cy, double skew, + double k2=0.0, double k3=0.0, double k4=0.0, + double k5=0.0, double k6=0.0, double k7=0.0) + : fx_(fx), fy_(fy), cx_(cx), cy_(cy), skew_(skew), + distortion_(std::abs(k2) > 1e-7) { + k2_ = k2; k3_ = k3; k4_ = k4; k5_ = k5; k6_ = k6; k7_ = k7; + } + + Vector3d cam2world(const double& u, const double& v) const { + Vector3d xyz; + if (!distortion_) { + double y = (v - cy_) / fy_; + double x = (u - cx_ - y * skew_) / fx_; + xyz << x, y, 1.0; + } else { + double y = (v - cy_) / fy_; + double x = (u - cx_ - y * skew_) / fx_; + + const double thetad = std::sqrt(x * x + y * y); + double theta = thetad; + + for (int i = 0; i < 7; ++i) { + const double theta2 = theta * theta; + const double theta3 = theta2 * theta; + const double theta4 = theta3 * theta; + const double theta5 = theta4 * theta; + const double theta6 = theta5 * theta; + theta = thetad / (1.0 + k2_ * theta + k3_ * theta2 + k4_ * theta3 + + k5_ * theta4 + k6_ * theta5 + k7_ * theta6); + } + + const double scaling = std::tan(theta) / thetad; + x *= scaling; + y *= scaling; + xyz << x, y, 1.0; + } + return xyz.normalized(); + } + + Vector3d cam2world(const Vector2d& px) const { + return cam2world(px[0], px[1]); + } + + Vector2d world2cam(const Vector3d& xyz) const { + Vector2d px; + if (!distortion_) { + px[0] = fx_ * xyz[0] + cx_; + px[1] = fy_ * xyz[1] + cy_; + } else { + double xd, yd; + const double r = std::sqrt(xyz(1) * xyz(1) + xyz(0) * xyz(0)); + const double theta = std::acos(xyz(2) / xyz.norm()); + const double thetad = thetad_from_theta(theta); + const double scaling = thetad / r; + xd = xyz[0] * scaling; + yd = xyz[1] * scaling; + px[0] = xd * fx_ + yd * skew_ + cx_; + px[1] = yd * fy_ + cy_; + } + return px; + } + + Vector2d world2cam(const Vector2d& uv) const { + Vector2d px; + if (!distortion_) { + px[0] = fx_ * uv[0] + cx_; + px[1] = fy_ * uv[1] + cy_; + } else { + double xd, yd; + const double r = uv.norm(); + if (r < 1e-8) { + return uv; + } + const double theta = std::atan(r); + const double thetad = thetad_from_theta(theta); + const double scaling = thetad / r; + xd = uv[0] * scaling; + yd = uv[1] * scaling; + px[0] = xd * fx_ + yd * skew_ + cx_; + px[1] = yd * fy_ + cy_; + } + return px; + } + + inline double thetad_from_theta(const double theta) const { + const double theta2 = theta * theta; + const double theta3 = theta2 * theta; + const double theta4 = theta3 * theta; + const double theta5 = theta4 * theta; + const double theta6 = theta5 * theta; + const double theta7 = theta6 * theta; + const double thetad = theta + k2_ * theta2 + k3_ * theta3 + + k4_ * theta4 + k5_ * theta5 + k6_ * theta6 + k7_ * theta7; + return thetad; + } + + double fx() const { return fx_; } + double fy() const { return fy_; } + double cx() const { return cx_; } + double cy() const { return cy_; } + double skew() const { return skew_; } + bool has_distortion() const { return distortion_; } + + double k2() const { return k2_; } + double k3() const { return k3_; } + double k4() const { return k4_; } + double k5() const { return k5_; } + double k6() const { return k6_; } + double k7() const { return k7_; } +}; +} // namespace mini_vikit diff --git a/sru_ws/src/odin_ros_driver/include/rawCloudRender.h b/sru_ws/src/odin_ros_driver/include/rawCloudRender.h new file mode 100644 index 0000000..1781229 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/rawCloudRender.h @@ -0,0 +1,83 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#ifndef RGBCLOUD_H +#define RGBCLOUD_H + +#include +#include +#include +#include "lidar_api.h" + +namespace GlobalCameraParams { + extern float g_fx; + extern float g_fy; + extern float g_cx; + extern float g_cy; + extern float g_skew; + extern float g_k2; + extern float g_k3; + extern float g_k4; + extern float g_k5; + extern float g_k6; + extern float g_k7; + extern Eigen::Matrix4f g_T_camera_lidar; +} + +class rawCloudRender { +public: + + + bool init(const std::string& yamlFilePath); + + void nv12buffer_2_rgb(buffer_List_t &image, std::vector>& rgb_image); + void render(std::vector>& rgb_image, capture_Image_List_t* pcdStream, int pcdIdx, std::vector& rgbCloud_flat); + + void print_camera_calib(); + + int getImageWidth() const { return image_width_; } + int getImageHeight() const { return image_height_; } + + + +private: + std::string model_type_; + std::string camera_name_; + int image_width_; + int image_height_; + int frame_size_; + bool opencv_available_; + + // 4x4 transformation matrix (T_camera_lidar) + Eigen::Matrix4f T_camera_lidar_; + + float k2_; + float k3_; + float k4_; + float k5_; + float k6_; + float k7_; + float p1_; + float p2_; + float A11_fx_; + float A12_skew_; + float A22_fy_; + float u0_cx_; + float v0_cy_; + bool isFast_; + int numDiff_; + float maxIncidentAngle_; + + +}; + +#endif // RGBCLOUD_H diff --git a/sru_ws/src/odin_ros_driver/include/yaml_parser.h b/sru_ws/src/odin_ros_driver/include/yaml_parser.h new file mode 100644 index 0000000..2c750d7 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/include/yaml_parser.h @@ -0,0 +1,149 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +#ifndef YAML_PARSER_H +#define YAML_PARSER_H + +#include +#include +#include +#include +#include +#include +#include +#include "lidar_api.h" + +namespace odin_ros_driver { + +// Data type enum for supporting different value types +enum class DataType { + INT_TYPE, + FLOAT_ARRAY_TYPE, + INT_ARRAY_TYPE, +}; + +// Generic parameter value holder +struct ParameterValue { + DataType type; + std::vector data; + + ParameterValue() : type(DataType::INT_TYPE) {} + + template + void setData(const T& value) { + const uint8_t* ptr = reinterpret_cast(&value); + data.assign(ptr, ptr + sizeof(T)); + } + + template + void setArray(const std::vector& arr) { + const uint8_t* ptr = reinterpret_cast(arr.data()); + data.assign(ptr, ptr + arr.size() * sizeof(T)); + } + + size_t getSize() const { + return data.size(); + } + + const void* getData() const { + return data.empty() ? nullptr : data.data(); + } +}; + +class YamlParser { +public: + YamlParser(const std::string& config_file); + + bool loadConfig(); + const std::map& getRegisterKeys() const; + const std::map& getRegisterKeysStrVal() const; + const std::map& getCustomParameters() const; + void printConfig() const; + bool applyCustomParameters(device_handle device); + int getCustomParameterInt(const std::string& param_name, int default_value) const; + + int getCustomMapMode(int default_value) const { + auto it = custom_parameters_.find("map_mode"); + if (it != custom_parameters_.end() && it->second.type == DataType::INT_TYPE) { + printf("custom_map_mode = %d\n", *(int*)it->second.getData()); + return *(int*)it->second.getData(); + } else { + return default_value; + } + }; + +private: + std::string config_file_; + std::map register_keys_; + std::map register_keys_str_val_; + std::map register_keys_float_val_; + std::map custom_parameters_; + + // Keys whose YAML value is a string (not int). + std::unordered_set allowed_key_w_str_val = { + "relocalization_map_abs_path", + "mapping_result_dest_dir", + "mapping_result_file_name", + "image_mask_abs_path", + "overlay_reprojected_topic", + "overlay_camera_topic", + "overlay_output_topic" + }; + + // Keys whose YAML value is a floating-point number (not int). + std::unordered_set allowed_key_w_float_val = { + "overlay_alpha" + }; + + // Whitelist of all recognized integer-valued keys. + // Any key not in this set (and not custom_*, string, or float) will trigger an error. + std::unordered_set allowed_key_w_int_val = { + "streamctrl", + "sendrgbcompressed", + "sendrgb", + "sendrgbundistort", + "sendimu", + "enable_imu_smooth", + "imu_smooth_frequency", + "sendodom", + "send_odom_baselink_tf", + "tf_extra_publish_rate", + "senddtof", + "cloud_raw_confidence_threshold", + "dtof_fps", + "rgb_format", + "rgb_width", + "rgb_height", + "rgb_fps", + "sendcloudslam", + "sendcloudrender", + "senddepth", + "sendreprojection", + "sendoverlay", + "recorddata", + "devstatuslog", + "save_log", + "pubintensitygray", + "showpath", + "showcamerapose", + "strict_usb3.0_check", + "use_host_ros_time", + "showfps", + "log_devel", + "sendimagemask", + "resetalgo" + }; +}; + +} + +#endif \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/launch_ROS1/odin1_ros1.launch b/sru_ws/src/odin_ros_driver/launch_ROS1/odin1_ros1.launch new file mode 100644 index 0000000..47f83df --- /dev/null +++ b/sru_ws/src/odin_ros_driver/launch_ROS1/odin1_ros1.launch @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/launch_ROS2/odin1_ros2.launch.py b/sru_ws/src/odin_ros_driver/launch_ROS2/odin1_ros2.launch.py new file mode 100644 index 0000000..de153ac --- /dev/null +++ b/sru_ws/src/odin_ros_driver/launch_ROS2/odin1_ros2.launch.py @@ -0,0 +1,116 @@ + +# USAGE: ros2 launch odin_ros_driver odin1_ros2.launch.py +import os +import yaml +from ament_index_python.packages import get_package_share_directory +from launch import LaunchDescription +from launch.actions import DeclareLaunchArgument +from launch.substitutions import LaunchConfiguration +from launch_ros.actions import Node + +def get_odin_runtime_dir(): + # Resolve the writable runtime directory that stores calib.yaml. + # Priority: ODIN_CALIB_DIR -> ROS_HOME -> ~/.ros -> /tmp. + # Must stay in sync with get_odin_runtime_dir() in host_sdk_sample.cpp. + custom = os.environ.get('ODIN_CALIB_DIR') + if custom: + return custom + ros_home = os.environ.get('ROS_HOME') + if ros_home: + return os.path.join(ros_home, 'odin_ros_driver') + home = os.environ.get('HOME') + if home: + return os.path.join(home, '.ros', 'odin_ros_driver') + return '/tmp/odin_ros_driver' + + +def generate_launch_description(): + # Get package directory + package_dir = get_package_share_directory('odin_ros_driver') + + # Shared, writable calib.yaml path (matches host_sdk_sample writer) + calib_file_path = os.path.join(get_odin_runtime_dir(), 'calib.yaml') + + # Declare configuration parameter + config_file_arg = DeclareLaunchArgument( + 'config_file', + default_value=os.path.join(package_dir, 'config', 'control_command.yaml'), + description='Path to the control config YAML file' + ) + + # Add RViz2 configuration file parameter + rviz_config_arg = DeclareLaunchArgument( + 'rviz_config', + default_value=os.path.join(package_dir, 'config', 'odin_ros2.rviz'), + description='Path to RViz2 config file' + ) + + # Create main node + host_sdk_node = Node( + package='odin_ros_driver', + executable='host_sdk_sample', + name='host_sdk_sample', + output='screen', + # arguments=['--ros-args', '--log-level', 'debug'], + parameters=[{ + 'config_file': LaunchConfiguration('config_file') + }] + ) + + pcd2depth_config_path = os.path.join(package_dir, 'config', 'control_command.yaml') + with open(pcd2depth_config_path, 'r') as f: + pcd2depth_params = yaml.safe_load(f) + pcd2depth_params['calib_file_path'] = calib_file_path + pcd2depth_node = Node( + package='odin_ros_driver', + executable='pcd2depth_ros2_node', + name='pcd2depth_ros2_node', + output='screen', + parameters=[pcd2depth_params] + ) + + # Cloud reprojection node + reprojection_config_path = os.path.join(package_dir, 'config', 'control_command.yaml') + with open(reprojection_config_path, 'r') as f: + reprojection_params = yaml.safe_load(f) + reprojection_params['calib_file_path'] = calib_file_path + cloud_reprojection_node = Node( + package='odin_ros_driver', + executable='cloud_reprojection_ros2_node', + name='cloud_reprojection_ros2_node', + output='screen', + parameters=[reprojection_params] + ) + + # Image overlay node - overlays reprojected points on camera image + overlay_config_path = os.path.join(package_dir, 'config', 'control_command.yaml') + with open(overlay_config_path, 'r') as f: + overlay_params = yaml.safe_load(f) + image_overlay_node = Node( + package='odin_ros_driver', + executable='image_overlay_node', + name='image_overlay_node', + output='screen', + parameters=[overlay_params] + ) + + # Create RViz2 node - loads specified configuration file + rviz_node = Node( + package='rviz2', + executable='rviz2', + name='rviz2', + output='screen', + arguments=['-d', LaunchConfiguration('rviz_config')] + ) + + # Create launch description + ld = LaunchDescription() + ld.add_action(config_file_arg) + ld.add_action(rviz_config_arg) # Add RViz configuration argument + ld.add_action(host_sdk_node) + ld.add_action(pcd2depth_node) + ld.add_action(cloud_reprojection_node) + ld.add_action(image_overlay_node) + ld.add_action(rviz_node) # Add RViz node + + return ld diff --git a/sru_ws/src/odin_ros_driver/lib/liblydHostApi_amd.a b/sru_ws/src/odin_ros_driver/lib/liblydHostApi_amd.a new file mode 100644 index 0000000..bcd0173 Binary files /dev/null and b/sru_ws/src/odin_ros_driver/lib/liblydHostApi_amd.a differ diff --git a/sru_ws/src/odin_ros_driver/lib/liblydHostApi_arm.a b/sru_ws/src/odin_ros_driver/lib/liblydHostApi_arm.a new file mode 100644 index 0000000..be0b755 Binary files /dev/null and b/sru_ws/src/odin_ros_driver/lib/liblydHostApi_arm.a differ diff --git a/sru_ws/src/odin_ros_driver/package.xml b/sru_ws/src/odin_ros_driver/package.xml new file mode 100755 index 0000000..fa5516c --- /dev/null +++ b/sru_ws/src/odin_ros_driver/package.xml @@ -0,0 +1,33 @@ + + + odin_ros_driver + 0.14.2 + ROS2 driver for Odin sensor + rlk + Apache 2.0 + + ament_cmake + + rclcpp + + std_msgs + sensor_msgs + nav_msgs + geometry_msgs + cv_bridge + image_transport + pcl_conversions + message_filters + tf2 + tf2_ros + tf2_geometry_msgs + ament_index_cpp + + rosidl_default_generators + rosidl_default_runtime + rosidl_interface_packages + + + ament_cmake + + \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/package_ros1.xml b/sru_ws/src/odin_ros_driver/package_ros1.xml new file mode 100644 index 0000000..e529db4 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/package_ros1.xml @@ -0,0 +1,33 @@ + + + odin_ros_driver + 0.14.4 + ROS driver for Odin sensor + rlk + Apache 2.0 + + + catkin + + + roscpp + std_msgs + sensor_msgs + nav_msgs + cv_bridge + image_transport + + + message_generation + message_runtime + + + eigen + opencv + yaml-cpp + + + + catkin + + diff --git a/sru_ws/src/odin_ros_driver/package_ros2.xml b/sru_ws/src/odin_ros_driver/package_ros2.xml new file mode 100644 index 0000000..29a91d4 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/package_ros2.xml @@ -0,0 +1,33 @@ + + + odin_ros_driver + 0.14.4 + ROS2 driver for Odin sensor + rlk + Apache 2.0 + + ament_cmake + + rclcpp + + std_msgs + sensor_msgs + nav_msgs + geometry_msgs + cv_bridge + image_transport + pcl_conversions + message_filters + tf2 + tf2_ros + tf2_geometry_msgs + ament_index_cpp + + rosidl_default_generators + rosidl_default_runtime + rosidl_interface_packages + + + ament_cmake + + \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/script/build_ros.sh b/sru_ws/src/odin_ros_driver/script/build_ros.sh new file mode 100755 index 0000000..28218ad --- /dev/null +++ b/sru_ws/src/odin_ros_driver/script/build_ros.sh @@ -0,0 +1,128 @@ +#!/bin/bash + +# Get the directory where the script is located (Odin_ROS_Driver directory) +PKG_DIR="$(cd "$(dirname "$0")/.."; pwd)" +# Calculate the workspace root directory (contains devel, build, src) +WORKSPACE_ROOT="$(dirname "$(dirname "$PKG_DIR")")" +# Workspace source directory (contains all packages) +WORKSPACE_SRC="${WORKSPACE_ROOT}/src" +PROJECT_NAME="odin_ros_driver" + +# Define color codes +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +# Clean workspace function +clean_workspace() { + echo -e "${YELLOW}Cleaning build directories${NC}" + + # Clean build artifacts in workspace + rm -rf "${WORKSPACE_ROOT}/build" + rm -rf "${WORKSPACE_ROOT}/install" + rm -rf "${WORKSPACE_ROOT}/log" + rm -rf "${WORKSPACE_ROOT}/devel" + + echo -e "${GREEN}Cleanup complete${NC}" +} + +# Run node function +run_node() { + echo -e "${YELLOW}Running ROS1 node${NC}" + + # Check if environment file exists + if [ ! -f "${WORKSPACE_ROOT}/devel/setup.bash" ]; then + echo -e "${RED}Could not find devel/setup.bash, please build the project with ./build_ros1.sh first${NC}" + return 1 + fi + + # Source environment and run node + source "${WORKSPACE_ROOT}/devel/setup.bash" + +} + +# Build workspace function +build_workspace() { + echo -e "${YELLOW}Workspace structure:${NC}" + echo " Workspace root: ${WORKSPACE_ROOT}" + echo " Source directory: ${WORKSPACE_SRC}" + echo " Package directory: ${PKG_DIR}" + echo " ROS version: ROS1" + + echo -e "${YELLOW}Starting ROS1 project build...${NC}" + + # Clean + cd $WS_DIR + rm -rf build devel install + + # Ensure ROS1 environment is loaded + if [ -f "/opt/ros/noetic/setup.bash" ]; then + source "/opt/ros/noetic/setup.bash" + elif [ -f "/opt/ros/melodic/setup.bash" ]; then + source "/opt/ros/melodic/setup.bash" + else + echo -e "${RED}Could not find ROS1 setup.bash file. Please ensure ROS1 is installed.${NC}" + return 1 + fi + + # Create temporary package.xml + if [ -f "${PKG_DIR}/package_ros1.xml" ]; then + echo "Creating temporary package.xml (using package_ros1.xml)" + cp "${PKG_DIR}/package_ros1.xml" "${PKG_DIR}/package.xml" + TEMP_PACKAGE=true + elif [ -f "${PKG_DIR}/package.xml" ]; then + echo "Using existing package.xml" + else + echo -e "${RED}Could not find package.xml in package directory${NC}" + return 1 + fi + + # Set build system variable + export BUILD_SYSTEM=ROS1 + + # Switch to workspace root and build + cd "${WORKSPACE_ROOT}" || return 1 + catkin_make -DBUILD_SYSTEM=ROS1 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -j$(nproc) + BUILD_RESULT=$? + + # If build successful, source environment + if [[ $BUILD_RESULT -eq 0 ]]; then + echo -e "${GREEN}ROS1 build successful, loading environment: source devel/setup.bash${NC}" + source "${WORKSPACE_ROOT}/devel/setup.bash" + else + echo -e "${RED}ROS1 build failed, please check error logs${NC}" + fi + + +} + +# Help function +show_help() { + echo -e "${YELLOW}Usage:${NC}" + echo " ./build_ros.sh # Build project" + echo " ./build_ros.sh -c # Clean build artifacts" + echo " ./build_ros.sh -h # Show help information" + echo "" + echo -e "${YELLOW}Current configuration:${NC}" + echo " Project name: ${PROJECT_NAME}" + echo " Package directory: ${PKG_DIR}" + echo " Workspace root: ${WORKSPACE_ROOT}" + echo " Source directory: ${WORKSPACE_SRC}" +} + +# Main +case "$1" in + -c|--clean) + clean_workspace + ;; + -r|--run) + run_node + ;; + -h|--help) + show_help + ;; + *) + build_workspace + ;; +esac \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/script/build_ros2.sh b/sru_ws/src/odin_ros_driver/script/build_ros2.sh new file mode 100755 index 0000000..fee138d --- /dev/null +++ b/sru_ws/src/odin_ros_driver/script/build_ros2.sh @@ -0,0 +1,172 @@ +#!/bin/bash + +# Get the directory where the script is located (Odin_ROS_Driver directory) +PKG_DIR="$(cd "$(dirname "$0")/.."; pwd)" +# Calculate the workspace root directory (contains devel, build, src) +WORKSPACE_ROOT="$(dirname "$(dirname "$PKG_DIR")")" +# Workspace source directory (contains all packages) +WORKSPACE_SRC="${WORKSPACE_ROOT}/src" +PROJECT_NAME="odin_ros_driver" +PACKAGE_DIR_NAME=$(basename "$PKG_DIR") + +# Define color codes +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +# Extract package name from package.xml +get_package_name() { + local package_xml="$1" + if [ -f "$package_xml" ]; then + # Extract content of tag + grep -oP '\K[^<]+' "$package_xml" | head -1 + else + echo "" + fi +} + +# Clean workspace function +clean_workspace() { + echo -e "${YELLOW}Cleaning build directories${NC}" + + # Clean build artifacts in workspace + rm -rf "${WORKSPACE_ROOT}/build" + rm -rf "${WORKSPACE_ROOT}/install" + rm -rf "${WORKSPACE_ROOT}/log" + rm -rf "${WORKSPACE_ROOT}/devel" + + echo -e "${GREEN}Cleanup complete${NC}" +} + +# Run node function +run_node() { + echo -e "${YELLOW}Running ROS2 node${NC}" + + # Check if environment file exists + if [ ! -f "${WORKSPACE_ROOT}/install/setup.bash" ]; then + echo -e "${RED}Could not find install/setup.bash, please build the project with ./build_ros2.sh first${NC}" + return 1 + fi + + # Source environment and run node + source "${WORKSPACE_ROOT}/install/setup.bash" + +} + +# Build workspace function +build_workspace() { + echo -e "${YELLOW}Workspace structure:${NC}" + echo " Workspace root: ${WORKSPACE_ROOT}" + echo " Source directory: ${WORKSPACE_SRC}" + echo " Package directory: ${PKG_DIR}" + echo " Directory name: ${PACKAGE_DIR_NAME}" + echo " ROS version: ROS2" + + echo -e "${YELLOW}Starting ROS2 project build...${NC}" + + cd $WS_DIR + rm -rf build install log + # Ensure ROS2 environment is loaded. + # 1) Prefer the currently active distro (ROS_DISTRO env var) if its setup.bash exists. + # 2) Otherwise probe a known list of ROS2 distros from newest to oldest. + ROS2_DISTRO_CANDIDATES=("rolling" "jazzy" "iron" "humble" "galactic" "foxy") + ROS2_SETUP_BASH="" + + if [ -n "${ROS_DISTRO}" ] && [ -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then + ROS2_SETUP_BASH="/opt/ros/${ROS_DISTRO}/setup.bash" + else + for distro in "${ROS2_DISTRO_CANDIDATES[@]}"; do + if [ -f "/opt/ros/${distro}/setup.bash" ]; then + ROS2_SETUP_BASH="/opt/ros/${distro}/setup.bash" + break + fi + done + fi + + if [ -n "${ROS2_SETUP_BASH}" ]; then + echo -e "${GREEN}Sourcing ROS2 environment: ${ROS2_SETUP_BASH}${NC}" + # shellcheck disable=SC1090 + source "${ROS2_SETUP_BASH}" + else + echo -e "${RED}Could not find ROS2 setup.bash file. Please ensure ROS2 is installed.${NC}" + return 1 + fi + + # Create temporary package.xml + if [ -f "${PKG_DIR}/package_ros2.xml" ]; then + echo "Creating temporary package.xml (using package_ros2.xml)" + cp "${PKG_DIR}/package_ros2.xml" "${PKG_DIR}/package.xml" + TEMP_PACKAGE=true + elif [ -f "${PKG_DIR}/package.xml" ]; then + echo "Using existing package.xml" + TEMP_PACKAGE=false + else + echo -e "${RED}Could not find package.xml in package directory${NC}" + return 1 + fi + + # Extract package name from package.xml + PACKAGE_NAME=$(get_package_name "${PKG_DIR}/package.xml") + if [ -z "$PACKAGE_NAME" ]; then + echo -e "${RED}Failed to extract package name from package.xml${NC}" + return 1 + fi + echo " Package name: ${PACKAGE_NAME}" + + # Set build system variable + export BUILD_SYSTEM=ROS2 + + # Switch to workspace root and build + cd "${WORKSPACE_ROOT}" || return 1 + + # Build with correct package name + colcon build \ + --packages-select "${PACKAGE_NAME}" \ + --parallel-workers $(nproc) \ + --cmake-args \ + -DBUILD_SYSTEM=ROS2 \ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON + + BUILD_RESULT=$? + + # If build successful, source environment + if [[ $BUILD_RESULT -eq 0 ]]; then + echo -e "${GREEN}ROS2 build successful, loading environment: source install/setup.bash${NC}" + source "${WORKSPACE_ROOT}/install/setup.bash" + + else + echo -e "${RED}ROS2 build failed, please check error logs${NC}" + fi + +} + +# Help function +show_help() { + echo -e "${YELLOW}Usage:${NC}" + echo " ./build_ros2.sh # Build project" + echo " ./build_ros2.sh -c # Clean build artifacts" + echo " ./build_ros2.sh -h # Show help information" + echo "" + echo -e "${YELLOW}Current configuration:${NC}" + echo " Project name: ${PROJECT_NAME}" + echo " Package directory: ${PKG_DIR}" + echo " Workspace root: ${WORKSPACE_ROOT}" + echo " Source directory: ${WORKSPACE_SRC}" +} + +# Main program +case "$1" in + -c|--clean) + clean_workspace + ;; + -r|--run) + run_node + ;; + -h|--help) + show_help + ;; + *) + build_workspace + ;; +esac \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/script/rosbag2_qos.yaml b/sru_ws/src/odin_ros_driver/script/rosbag2_qos.yaml new file mode 100644 index 0000000..5f26738 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/script/rosbag2_qos.yaml @@ -0,0 +1,18 @@ +# rosbag2_qos.yaml +# QoS overrides for rosbag2 recording +# 用于 rosbag2 录制的 QoS 配置 +# +# Usage / 使用方法: +# ros2 bag record -a --qos-profile-overrides-path rosbag2_qos.yaml + +# High frequency data (IMU 400Hz, Odom 100Hz) +# 高频数据 (IMU 400Hz, 里程计 100Hz) +/odin1/imu: + reliability: reliable + history: keep_last + depth: 4000 + +/odin1/odometry_highfreq: + reliability: reliable + history: keep_last + depth: 4000 diff --git a/sru_ws/src/odin_ros_driver/set_param.sh b/sru_ws/src/odin_ros_driver/set_param.sh new file mode 100755 index 0000000..076091c --- /dev/null +++ b/sru_ws/src/odin_ros_driver/set_param.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# Usage: ./set_param.sh +# Example: ./set_param.sh save_map 1 + +if [ $# -ne 2 ]; then + echo "Usage: $0 " + echo "Example: $0 save_map 1" + exit 1 +fi + +PARAM_NAME=$1 +VALUE=$2 + +COMMAND_FILE="/tmp/odin_command.txt" + +# Create the command file with the parameter +echo "set $PARAM_NAME $VALUE" > "$COMMAND_FILE" + +echo "Command sent: set $PARAM_NAME $VALUE" +echo "Command file: $COMMAND_FILE" diff --git a/sru_ws/src/odin_ros_driver/src/camera_pose_visualization.cpp b/sru_ws/src/odin_ros_driver/src/camera_pose_visualization.cpp new file mode 100755 index 0000000..7cd5dbe --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/camera_pose_visualization.cpp @@ -0,0 +1,232 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "camera_pose_visualization.h" + +const Eigen::Vector3d camera_pose_visualization::imlt = Eigen::Vector3d(-1.0, -0.5, 1.0); +const Eigen::Vector3d camera_pose_visualization::imrt = Eigen::Vector3d( 1.0, -0.5, 1.0); +const Eigen::Vector3d camera_pose_visualization::imlb = Eigen::Vector3d(-1.0, 0.5, 1.0); +const Eigen::Vector3d camera_pose_visualization::imrb = Eigen::Vector3d( 1.0, 0.5, 1.0); +const Eigen::Vector3d camera_pose_visualization::lt0 = Eigen::Vector3d(-0.7, -0.5, 1.0); +const Eigen::Vector3d camera_pose_visualization::lt1 = Eigen::Vector3d(-0.7, -0.2, 1.0); +const Eigen::Vector3d camera_pose_visualization::lt2 = Eigen::Vector3d(-1.0, -0.2, 1.0); +const Eigen::Vector3d camera_pose_visualization::oc = Eigen::Vector3d(0.0, 0.0, 0.0); + +#ifdef ROS2 +using GeometryPoint = geometry_msgs::msg::Point; +#else +using GeometryPoint = geometry_msgs::Point; +#endif + +void Eigen2Point(const Eigen::Vector3d& v, GeometryPoint& p) { + p.x = v.x(); + p.y = v.y(); + p.z = v.z(); +} + +camera_pose_visualization::camera_pose_visualization(float r, float g, float b, float a) + : m_marker_ns("camera_pose_visualization"), m_scale(0.3), m_line_width(0.03) { + m_image_boundary_color.r = r; + m_image_boundary_color.g = g; + m_image_boundary_color.b = b; + m_image_boundary_color.a = a; + m_optical_center_connector_color.r = r; + m_optical_center_connector_color.g = g; + m_optical_center_connector_color.b = b; + m_optical_center_connector_color.a = a; +} + +void camera_pose_visualization::setImageBoundaryColor(float r, float g, float b, float a) { + m_image_boundary_color.r = r; + m_image_boundary_color.g = g; + m_image_boundary_color.b = b; + m_image_boundary_color.a = a; +} + +void camera_pose_visualization::setOpticalCenterConnectorColor(float r, float g, float b, float a) { + m_optical_center_connector_color.r = r; + m_optical_center_connector_color.g = g; + m_optical_center_connector_color.b = b; + m_optical_center_connector_color.a = a; +} + +void camera_pose_visualization::setScale(double s) { + m_scale = s; +} +void camera_pose_visualization::setLineWidth(double width) { + m_line_width = width; +} +void camera_pose_visualization::add_edge(const Eigen::Vector3d& p0, const Eigen::Vector3d& p1) { + Marker marker; + + marker.ns = m_marker_ns; + marker.id = m_markers.size() + 1; +#ifdef ROS2 + marker.type = Marker::LINE_LIST; + marker.action = Marker::ADD; +#else + marker.type = visualization_msgs::Marker::LINE_LIST; + marker.action = visualization_msgs::Marker::ADD; +#endif + marker.scale.x = 0.005; + + marker.color.g = 1.0f; + marker.color.a = 1.0; + + GeometryPoint point0, point1; + + Eigen2Point(p0, point0); + Eigen2Point(p1, point1); + + marker.points.push_back(point0); + marker.points.push_back(point1); + + m_markers.push_back(marker); +} + +void camera_pose_visualization::add_loopedge(const Eigen::Vector3d& p0, const Eigen::Vector3d& p1) { + Marker marker; + + marker.ns = m_marker_ns; + marker.id = m_markers.size() + 1; +#ifdef ROS2 + marker.type = Marker::LINE_LIST; + marker.action = Marker::ADD; +#else + marker.type = visualization_msgs::Marker::LINE_LIST; + marker.action = visualization_msgs::Marker::ADD; +#endif + marker.scale.x = 0.04; + //marker.scale.x = 0.3; + + marker.color.r = 1.0f; + marker.color.b = 1.0f; + marker.color.a = 1.0; + + GeometryPoint point0, point1; + + Eigen2Point(p0, point0); + Eigen2Point(p1, point1); + + marker.points.push_back(point0); + marker.points.push_back(point1); + + m_markers.push_back(marker); +} + + +void camera_pose_visualization::add_pose(const Eigen::Vector3d& p, const Eigen::Quaterniond& q) { + Marker marker; + + marker.ns = m_marker_ns; + marker.id = m_markers.size() + 1; +#ifdef ROS2 + marker.type = Marker::LINE_STRIP; + marker.action = Marker::ADD; +#else + marker.type = visualization_msgs::Marker::LINE_STRIP; + marker.action = visualization_msgs::Marker::ADD; +#endif + marker.scale.x = m_line_width; + + marker.pose.position.x = 0.0; + marker.pose.position.y = 0.0; + marker.pose.position.z = 0.0; + marker.pose.orientation.w = 1.0; + marker.pose.orientation.x = 0.0; + marker.pose.orientation.y = 0.0; + marker.pose.orientation.z = 0.0; + + + GeometryPoint pt_lt, pt_lb, pt_rt, pt_rb, pt_oc, pt_lt0, pt_lt1, pt_lt2; + + Eigen2Point(q * (m_scale * imlt) + p, pt_lt); + Eigen2Point(q * (m_scale * imlb) + p, pt_lb); + Eigen2Point(q * (m_scale * imrt) + p, pt_rt); + Eigen2Point(q * (m_scale * imrb) + p, pt_rb); + Eigen2Point(q * (m_scale * lt0 ) + p, pt_lt0); + Eigen2Point(q * (m_scale * lt1 ) + p, pt_lt1); + Eigen2Point(q * (m_scale * lt2 ) + p, pt_lt2); + Eigen2Point(q * (m_scale * oc ) + p, pt_oc); + + // image boundaries + marker.points.push_back(pt_lt); + marker.points.push_back(pt_lb); + marker.colors.push_back(m_image_boundary_color); + marker.colors.push_back(m_image_boundary_color); + + marker.points.push_back(pt_lb); + marker.points.push_back(pt_rb); + marker.colors.push_back(m_image_boundary_color); + marker.colors.push_back(m_image_boundary_color); + + marker.points.push_back(pt_rb); + marker.points.push_back(pt_rt); + marker.colors.push_back(m_image_boundary_color); + marker.colors.push_back(m_image_boundary_color); + + marker.points.push_back(pt_rt); + marker.points.push_back(pt_lt); + marker.colors.push_back(m_image_boundary_color); + marker.colors.push_back(m_image_boundary_color); + + // top-left indicator + marker.points.push_back(pt_lt0); + marker.points.push_back(pt_lt1); + marker.colors.push_back(m_image_boundary_color); + marker.colors.push_back(m_image_boundary_color); + + marker.points.push_back(pt_lt1); + marker.points.push_back(pt_lt2); + marker.colors.push_back(m_image_boundary_color); + marker.colors.push_back(m_image_boundary_color); + + // optical center connector + marker.points.push_back(pt_lt); + marker.points.push_back(pt_oc); + marker.colors.push_back(m_optical_center_connector_color); + marker.colors.push_back(m_optical_center_connector_color); + + + marker.points.push_back(pt_lb); + marker.points.push_back(pt_oc); + marker.colors.push_back(m_optical_center_connector_color); + marker.colors.push_back(m_optical_center_connector_color); + + marker.points.push_back(pt_rt); + marker.points.push_back(pt_oc); + marker.colors.push_back(m_optical_center_connector_color); + marker.colors.push_back(m_optical_center_connector_color); + + marker.points.push_back(pt_rb); + marker.points.push_back(pt_oc); + marker.colors.push_back(m_optical_center_connector_color); + marker.colors.push_back(m_optical_center_connector_color); + + m_markers.push_back(marker); +} + +void camera_pose_visualization::reset() { + m_markers.clear(); +} + +void camera_pose_visualization::publish_by( Publisher& pub, const Header& header ) { + MarkerArray markerArray_msg; + + for (auto& marker : m_markers) { + marker.header = header; + markerArray_msg.markers.push_back(marker); + } + + pub.publish(markerArray_msg); +} \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/src/cloud_reprojection_ros.cpp b/sru_ws/src/odin_ros_driver/src/cloud_reprojection_ros.cpp new file mode 100644 index 0000000..5b303a2 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/cloud_reprojection_ros.cpp @@ -0,0 +1,507 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "cloud_reprojection_ros_node.hpp" +#include "odin_calib_path.h" + +#include +#include +#include +#include + +#ifdef ROS2 + #include + #include + #include +#else + #include +#endif + +// Fixed Til (T_imu_lidar): lidar position in imu frame, transforms from lidar to imu +// TODO: Fill in the actual Til values for your sensor setup +static Eigen::Matrix4d getFixedTil() +{ + Eigen::Matrix4d Til = Eigen::Matrix4d::Identity(); + Til(0, 3) = -0.02663; + Til(1, 3) = 0.03447; + Til(2, 3) = 0.02174; + return Til; +} + +static bool fileExists(const std::string& filename) { + struct stat buffer; + return (stat(filename.c_str(), &buffer) == 0); +} + +#ifdef ROS2 +// Helper function to get package source directory for ROS2 +static std::string get_package_source_directory() { + std::string current_file = __FILE__; + size_t pos = current_file.find("/src/cloud_reprojection_ros.cpp"); + if (pos != std::string::npos) { + return current_file.substr(0, pos); + } + return ""; +} + +// ==================== ROS2 Implementation ==================== + +CloudReprojectionRosNode::CloudReprojectionRosNode(const rclcpp::NodeOptions& options) + : Node("cloud_reprojection_node", options) +{ + loadParameters(); + + RCLCPP_INFO_STREAM(this->get_logger(), + "\n cloud_slam_topic: " << cloud_slam_topic_ + << "\n odometry_topic: " << odometry_topic_ + << "\n wiwc_topic: " << wiwc_topic_ + << "\n reprojected_image_topic: " << reprojected_image_topic_); + + cloud_sub_.subscribe(this, cloud_slam_topic_); + odom_sub_.subscribe(this, odometry_topic_); + wiwc_sub_.subscribe(this, wiwc_topic_); + + sync_ = std::make_shared(MySyncPolicy(10), cloud_sub_, odom_sub_, wiwc_sub_); + sync_->registerCallback(std::bind(&CloudReprojectionRosNode::syncCallback, this, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + + reprojected_image_pub_ = image_transport::create_publisher(this, reprojected_image_topic_); + + RCLCPP_INFO(this->get_logger(), "CloudReprojectionRosNode initialized successfully"); +} + +void CloudReprojectionRosNode::loadParameters() +{ + // Declare and get parameters + this->declare_parameter("cloud_slam_topic", "/odin1/cloud_slam"); + this->declare_parameter("odometry_topic", "/odin1/odometry"); + this->declare_parameter("wiwc_topic", "/odin1/wiwc"); + this->declare_parameter("reprojected_image_topic", "/odin1/reprojected_image"); + + cloud_slam_topic_ = this->get_parameter("cloud_slam_topic").as_string(); + odometry_topic_ = this->get_parameter("odometry_topic").as_string(); + wiwc_topic_ = this->get_parameter("wiwc_topic").as_string(); + reprojected_image_topic_ = this->get_parameter("reprojected_image_topic").as_string(); + + // Load camera parameters from calib.yaml in the shared runtime dir + std::string calib_file = odin_ros_driver::GetOdinCalibFile(); + RCLCPP_INFO(this->get_logger(), "========== [CALIB] READ <- %s ==========", calib_file.c_str()); + + YAML::Node calib_config; + try { + calib_config = YAML::LoadFile(calib_file); + } catch (const std::exception& e) { + RCLCPP_ERROR(this->get_logger(), "Failed to load calib.yaml: %s", e.what()); + rclcpp::shutdown(); + return; + } + + CloudReprojector::CameraParams cam_params; + try { + cam_params.image_width = calib_config["cam_0"]["image_width"].as(); + cam_params.image_height = calib_config["cam_0"]["image_height"].as(); + cam_params.A11 = calib_config["cam_0"]["A11"].as(); + cam_params.A12 = calib_config["cam_0"]["A12"].as(); + cam_params.A22 = calib_config["cam_0"]["A22"].as(); + cam_params.u0 = calib_config["cam_0"]["u0"].as(); + cam_params.v0 = calib_config["cam_0"]["v0"].as(); + cam_params.k2 = calib_config["cam_0"]["k2"].as(); + cam_params.k3 = calib_config["cam_0"]["k3"].as(); + cam_params.k4 = calib_config["cam_0"]["k4"].as(); + cam_params.k5 = calib_config["cam_0"]["k5"].as(); + cam_params.k6 = calib_config["cam_0"]["k6"].as(); + cam_params.k7 = calib_config["cam_0"]["k7"].as(); + } catch (const std::exception& e) { + RCLCPP_ERROR(this->get_logger(), "Failed to parse camera parameters: %s", e.what()); + rclcpp::shutdown(); + return; + } + + // Load extrinsic parameters + CloudReprojector::ExtrinsicParams ext_params; + try { + auto Tcl_vec = calib_config["Tcl_0"].as>(); + + if (Tcl_vec.size() == 16) + { + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) + ext_params.Tcl(i, j) = Tcl_vec[i * 4 + j]; + } + else + { + RCLCPP_ERROR(this->get_logger(), "Tcl_0 has invalid size: %zu (expected 16)", Tcl_vec.size()); + rclcpp::shutdown(); + return; + } + } catch (const std::exception& e) { + RCLCPP_ERROR(this->get_logger(), "Failed to parse Tcl_0: %s", e.what()); + rclcpp::shutdown(); + return; + } + + ext_params.Til = getFixedTil(); + ext_params.Tic = CloudReprojector::calculateTic(ext_params.Tcl, ext_params.Til); + + RCLCPP_INFO_STREAM(this->get_logger(), "Loaded Tcl (camera to lidar):\n" << ext_params.Tcl); + RCLCPP_INFO_STREAM(this->get_logger(), "Fixed Til (lidar to imu):\n" << ext_params.Til); + RCLCPP_INFO_STREAM(this->get_logger(), "Calculated Tic:\n" << ext_params.Tic); + + RCLCPP_INFO(this->get_logger(), "Camera intrinsics:"); + RCLCPP_INFO(this->get_logger(), "Image size: %dx%d", cam_params.image_width, cam_params.image_height); + RCLCPP_INFO(this->get_logger(), "Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f", + cam_params.A11, cam_params.A12, cam_params.A22, cam_params.u0, cam_params.v0); + + reprojector_ = std::make_unique(); + if (!reprojector_->initialize(cam_params, ext_params)) + { + RCLCPP_ERROR(this->get_logger(), "Failed to initialize CloudReprojector"); + rclcpp::shutdown(); + } +} + +void CloudReprojectionRosNode::syncCallback( + const PointCloud2::ConstSharedPtr& cloud_msg, + const Odometry::ConstSharedPtr& odom_msg, + const Odometry::ConstSharedPtr& wiwc_msg) +{ + // Debug: print that syncCallback is called + static int sync_count = 0; + // RCLCPP_INFO(this->get_logger(), "=== syncCallback called, count: %d ===", ++sync_count); + + pcl::PointCloud cloud_odom; + pcl::fromROSMsg(*cloud_msg, cloud_odom); + + if (cloud_odom.empty()) + { + RCLCPP_WARN(this->get_logger(), "Empty cloud_slam received"); + return; + } + + // Extract real-time extrinsics from WIWC message covariance fields + // pose.covariance contains T_CL (first 16 values), twist.covariance contains T_IL (first 16 values) + Eigen::Matrix4d T_CL = Eigen::Matrix4d::Identity(); + Eigen::Matrix4d T_IL = Eigen::Matrix4d::Identity(); + for (int i = 0; i < 16; ++i) { + T_CL(i / 4, i % 4) = wiwc_msg->pose.covariance[i]; + T_IL(i / 4, i % 4) = wiwc_msg->twist.covariance[i]; + } + + // Update extrinsics if valid (not identity matrix) + bool T_CL_valid = (T_CL - Eigen::Matrix4d::Identity()).norm() > 1e-6; + bool T_IL_valid = (T_IL - Eigen::Matrix4d::Identity()).norm() > 1e-6; + + // // Debug print to compare with host_sdk_sample values + // static int print_count = 0; + // if (print_count++) { + // // Extract rotation (3x3) and translation (3x1) from T_CL + // Eigen::Matrix3d RCL = T_CL.block<3,3>(0,0); + // Eigen::Vector3d TCL = T_CL.block<3,1>(0,3); + // RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection RCL (3x3 rotation from T_CL) ===\n" << RCL); + // RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection TCL (3x1 translation from T_CL) ===\n" << TCL.transpose()); + + // // Extract rotation (3x3) and translation (3x1) from T_IL + // Eigen::Matrix3d RIL = T_IL.block<3,3>(0,0); + // Eigen::Vector3d TIL = T_IL.block<3,1>(0,3); + // RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection RIL (3x3 rotation from T_IL) ===\n" << RIL); + // RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection TIL (3x1 translation from T_IL) ===\n" << TIL.transpose()); + + // RCLCPP_INFO(this->get_logger(), "T_CL_valid: %d, T_IL_valid: %d", T_CL_valid, T_IL_valid); + // if (T_CL_valid && T_IL_valid) { + // Eigen::Matrix4d Tic = CloudReprojector::calculateTic(T_CL, T_IL); + // RCLCPP_INFO_STREAM(this->get_logger(), "=== cloud_reprojection calculated Tic ===\n" << Tic); + // } + // } + + if (T_CL_valid && T_IL_valid) { + reprojector_->updateExtrinsics(T_CL, T_IL); + } + + CloudReprojector::OdomPose odom_pose; + odom_pose.orientation = Eigen::Quaterniond( + odom_msg->pose.pose.orientation.w, + odom_msg->pose.pose.orientation.x, + odom_msg->pose.pose.orientation.y, + odom_msg->pose.pose.orientation.z + ); + odom_pose.position = Eigen::Vector3d( + odom_msg->pose.pose.position.x, + odom_msg->pose.pose.position.y, + odom_msg->pose.pose.position.z + ); + + cv::Mat reprojected_img = reprojector_->reprojectCloud(cloud_odom, odom_pose); + + auto img_msg = cv_bridge::CvImage(cloud_msg->header, "bgr8", reprojected_img).toImageMsg(); + reprojected_image_pub_.publish(*img_msg); +} + +// ==================== ROS2 Main ==================== +int main(int argc, char** argv) +{ + rclcpp::init(argc, argv); + + auto temp_node = std::make_shared("cloud_reprojection_check"); + + // Check if reprojection is enabled from control_command.yaml + std::string package_path = get_package_source_directory(); + std::string config_file = package_path + "/config/control_command.yaml"; + + try { + YAML::Node config = YAML::LoadFile(config_file); + std::cout << "config: " << config_file << std::endl; + if (!config["register_keys"] || !config["register_keys"]["sendreprojection"]) { + RCLCPP_INFO(temp_node->get_logger(), "sendreprojection parameter not found, cloud reprojection disabled."); + rclcpp::shutdown(); + return 0; + } + + int sendreprojection = config["register_keys"]["sendreprojection"].as(); + if (sendreprojection == 0) { + RCLCPP_INFO(temp_node->get_logger(), "Cloud reprojection will not be published."); + rclcpp::shutdown(); + return 0; + } + } catch (const std::exception& e) { + RCLCPP_ERROR(temp_node->get_logger(), "Failed to read config: %s", e.what()); + rclcpp::shutdown(); + return 1; + } + + // Wait for calib.yaml file to be generated by host_sdk_sample + std::string calib_file = odin_ros_driver::GetOdinCalibFile(); + RCLCPP_INFO(temp_node->get_logger(), "========== [CALIB] WAIT <- %s ==========", calib_file.c_str()); + + int wait_count = 0; + while (rclcpp::ok() && !fileExists(calib_file)) { + if (wait_count % 10 == 0) { + RCLCPP_INFO(temp_node->get_logger(), "Still waiting for calib.yaml file..."); + } + std::this_thread::sleep_for(std::chrono::milliseconds(5000)); + wait_count++; + + // Timeout after 5 seconds + if (wait_count > 10) { + RCLCPP_ERROR(temp_node->get_logger(), "Timeout waiting for calib.yaml file"); + rclcpp::shutdown(); + return 1; + } + } + + if (!rclcpp::ok()) { + RCLCPP_INFO(temp_node->get_logger(), "Node shutdown before calib.yaml file was found."); + return 0; + } + + RCLCPP_INFO(temp_node->get_logger(), "Found calib.yaml file! Starting cloud reprojection node..."); + + auto node = std::make_shared(); + + RCLCPP_INFO(node->get_logger(), "CloudReprojectionRosNode started"); + + rclcpp::spin(node); + rclcpp::shutdown(); + + return 0; +} + +#else +// ==================== ROS1 Implementation ==================== + +CloudReprojectionRosNode::CloudReprojectionRosNode(ros::NodeHandle& nh, ros::NodeHandle& pnh) + : nh_(nh), pnh_(pnh) +{ + loadParameters(); + + ROS_INFO_STREAM("\n cloud_slam_topic: " << cloud_slam_topic_ + << "\n odometry_topic: " << odometry_topic_ + << "\n wiwc_topic: " << wiwc_topic_ + << "\n reprojected_image_topic: " << reprojected_image_topic_); + + cloud_sub_.subscribe(nh_, cloud_slam_topic_, 1); + odom_sub_.subscribe(nh_, odometry_topic_, 1); + wiwc_sub_.subscribe(nh_, wiwc_topic_, 1); + + sync_ = std::make_shared(MySyncPolicy(10), cloud_sub_, odom_sub_, wiwc_sub_); + sync_->registerCallback(boost::bind(&CloudReprojectionRosNode::syncCallback, this, _1, _2, _3)); + + reprojected_image_pub_ = nh_.advertise(reprojected_image_topic_, 1); + + ROS_INFO("CloudReprojectionRosNode initialized successfully"); +} + +void CloudReprojectionRosNode::loadParameters() +{ + pnh_.param("cloud_slam_topic", cloud_slam_topic_, std::string("/odin1/cloud_slam")); + pnh_.param("odometry_topic", odometry_topic_, std::string("/odin1/odometry")); + pnh_.param("wiwc_topic", wiwc_topic_, std::string("/odin1/wiwc")); + pnh_.param("reprojected_image_topic", reprojected_image_topic_, std::string("/odin1/reprojected_image")); + + // Load camera parameters + CloudReprojector::CameraParams cam_params; + pnh_.param("cam_0/image_width", cam_params.image_width, 1600); + pnh_.param("cam_0/image_height", cam_params.image_height, 1296); + pnh_.param("cam_0/A11", cam_params.A11, 0.0); + pnh_.param("cam_0/A12", cam_params.A12, 0.0); + pnh_.param("cam_0/A22", cam_params.A22, 0.0); + pnh_.param("cam_0/u0", cam_params.u0, 0.0); + pnh_.param("cam_0/v0", cam_params.v0, 0.0); + pnh_.param("cam_0/k2", cam_params.k2, 0.0); + pnh_.param("cam_0/k3", cam_params.k3, 0.0); + pnh_.param("cam_0/k4", cam_params.k4, 0.0); + pnh_.param("cam_0/k5", cam_params.k5, 0.0); + pnh_.param("cam_0/k6", cam_params.k6, 0.0); + pnh_.param("cam_0/k7", cam_params.k7, 0.0); + + // Load extrinsic parameters + CloudReprojector::ExtrinsicParams ext_params; + std::vector Tcl_vec_param; + if (pnh_.getParam("Tcl_0", Tcl_vec_param) && Tcl_vec_param.size() == 16) + { + for (int i = 0; i < 4; ++i) + for (int j = 0; j < 4; ++j) + ext_params.Tcl(i, j) = Tcl_vec_param[i * 4 + j]; + } + else + { + ROS_ERROR("Tcl_0 param missing or invalid."); + ros::shutdown(); + return; + } + + ext_params.Til = getFixedTil(); + ext_params.Tic = CloudReprojector::calculateTic(ext_params.Tcl, ext_params.Til); + + ROS_INFO_STREAM("Loaded Tcl (camera to lidar):\n" << ext_params.Tcl); + ROS_INFO_STREAM("Fixed Til (lidar to imu):\n" << ext_params.Til); + ROS_INFO_STREAM("Calculated Tic:\n" << ext_params.Tic); + + ROS_INFO("Camera intrinsics:"); + ROS_INFO("Image size: %dx%d", cam_params.image_width, cam_params.image_height); + ROS_INFO("Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f", + cam_params.A11, cam_params.A12, cam_params.A22, cam_params.u0, cam_params.v0); + + reprojector_ = std::make_unique(); + if (!reprojector_->initialize(cam_params, ext_params)) + { + ROS_ERROR("Failed to initialize CloudReprojector"); + ros::shutdown(); + } +} + +void CloudReprojectionRosNode::syncCallback( + const sensor_msgs::PointCloud2ConstPtr& cloud_msg, + const nav_msgs::OdometryConstPtr& odom_msg, + const nav_msgs::OdometryConstPtr& wiwc_msg) +{ + pcl::PointCloud cloud_odom; + pcl::fromROSMsg(*cloud_msg, cloud_odom); + + if (cloud_odom.empty()) + { + ROS_WARN("Empty cloud_slam received"); + return; + } + + // Extract real-time extrinsics from WIWC message covariance fields + // pose.covariance contains T_CL (first 16 values), twist.covariance contains T_IL (first 16 values) + Eigen::Matrix4d T_CL = Eigen::Matrix4d::Identity(); + Eigen::Matrix4d T_IL = Eigen::Matrix4d::Identity(); + for (int i = 0; i < 16; ++i) { + T_CL(i / 4, i % 4) = wiwc_msg->pose.covariance[i]; + T_IL(i / 4, i % 4) = wiwc_msg->twist.covariance[i]; + } + + // Update extrinsics if valid (not identity matrix) + bool T_CL_valid = (T_CL - Eigen::Matrix4d::Identity()).norm() > 1e-6; + bool T_IL_valid = (T_IL - Eigen::Matrix4d::Identity()).norm() > 1e-6; + if (T_CL_valid && T_IL_valid) { + reprojector_->updateExtrinsics(T_CL, T_IL); + } + + CloudReprojector::OdomPose odom_pose; + odom_pose.orientation = Eigen::Quaterniond( + odom_msg->pose.pose.orientation.w, + odom_msg->pose.pose.orientation.x, + odom_msg->pose.pose.orientation.y, + odom_msg->pose.pose.orientation.z + ); + odom_pose.position = Eigen::Vector3d( + odom_msg->pose.pose.position.x, + odom_msg->pose.pose.position.y, + odom_msg->pose.pose.position.z + ); + + cv::Mat reprojected_img = reprojector_->reprojectCloud(cloud_odom, odom_pose); + + sensor_msgs::ImagePtr img_msg = cv_bridge::CvImage(cloud_msg->header, "bgr8", reprojected_img).toImageMsg(); + reprojected_image_pub_.publish(img_msg); +} + +// ==================== ROS1 Main ==================== +int main(int argc, char **argv) +{ + ros::init(argc, argv, "cloud_reprojection"); + ros::NodeHandle nh; + ros::NodeHandle pnh("~"); + + // Check if reprojection is enabled + int sendreprojection = 0; + pnh.param("register_keys/sendreprojection", sendreprojection, 0); + if(sendreprojection == 0) + { + ROS_INFO("Cloud reprojection will not be published."); + return 0; + } + + std::string calib_file_path; + pnh.param("calib_file_path", calib_file_path, ""); + if (calib_file_path.empty()) { + calib_file_path = odin_ros_driver::GetOdinCalibFile(); + } + + ROS_INFO("========== [CALIB] WAIT <- %s ==========", calib_file_path.c_str()); + while(ros::ok() && !fileExists(calib_file_path)) + { + ROS_INFO_THROTTLE(5, "Still waiting for calib.yaml file..."); + ros::Duration(0.5).sleep(); + ros::spinOnce(); + } + + if(!ros::ok()) + { + ROS_INFO("Node shutdown before calib.yaml file was found."); + return 0; + } + + ROS_INFO("Found calib.yaml file! Loading parameters..."); + + std::string node_name = ros::this_node::getName(); + std::string rosparam_command = "rosparam load " + calib_file_path + " " + node_name; + int result = system(rosparam_command.c_str()); + + if(result == 0) + { + ROS_INFO("Successfully loaded parameters from calib.yaml to namespace: %s", node_name.c_str()); + } + else + { + ROS_ERROR("Failed to load parameters from calib.yaml"); + return 1; + } + + CloudReprojectionRosNode reprojection_node(nh, pnh); + ros::spin(); + return 0; +} +#endif diff --git a/sru_ws/src/odin_ros_driver/src/cloud_reprojector.cpp b/sru_ws/src/odin_ros_driver/src/cloud_reprojector.cpp new file mode 100644 index 0000000..9a924d3 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/cloud_reprojector.cpp @@ -0,0 +1,128 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "cloud_reprojector.hpp" +#include + +CloudReprojector::CloudReprojector() +{ +} + +bool CloudReprojector::initialize(const CameraParams& cam_params, const ExtrinsicParams& ext_params) +{ + camera_params_ = cam_params; + extrinsic_params_ = ext_params; + + if (camera_params_.A11 < 1e-6 || camera_params_.A22 < 1e-6 || + camera_params_.u0 < 1e-6 || camera_params_.v0 < 1e-6) + { + return false; + } + + camera_model_ = std::make_unique( + camera_params_.image_width, camera_params_.image_height, + camera_params_.A11, camera_params_.A22, + camera_params_.u0, camera_params_.v0, + camera_params_.A12, + camera_params_.k2, camera_params_.k3, camera_params_.k4, + camera_params_.k5, camera_params_.k6, camera_params_.k7 + ); + + initialized_ = true; + return true; +} + +Eigen::Matrix4d CloudReprojector::calculateTic(const Eigen::Matrix4d& Tcl, const Eigen::Matrix4d& Til) +{ + // Tic = Til * Tlc = Til * Tcl.inverse() + Eigen::Matrix4d Tlc = Tcl.inverse(); + return Til * Tlc; +} + +Eigen::Matrix4d CloudReprojector::odomPoseToMatrix(const OdomPose& odom) const +{ + Eigen::Matrix4d T = Eigen::Matrix4d::Identity(); + T.block<3, 3>(0, 0) = odom.orientation.toRotationMatrix(); + T(0, 3) = odom.position.x(); + T(1, 3) = odom.position.y(); + T(2, 3) = odom.position.z(); + return T; +} + +cv::Mat CloudReprojector::reprojectCloud(const pcl::PointCloud& cloud_odom, + const OdomPose& odom_pose) +{ + if (!initialized_) + { + return cv::Mat(); + } + + // T_odom_imu: imu pose in odom frame + Eigen::Matrix4d T_odom_imu = odomPoseToMatrix(odom_pose); + + // T_imu_odom: transforms points from odom frame to imu frame + Eigen::Matrix4d T_imu_odom = T_odom_imu.inverse(); + + // T_cam_imu = Tic.inverse(): transforms from imu to camera + Eigen::Matrix4d T_cam_imu = extrinsic_params_.Tic.inverse(); + + // T_cam_odom: transforms points from odom frame to camera frame + Eigen::Matrix4d T_cam_odom = T_cam_imu * T_imu_odom; + + pcl::PointCloud cloud_in_cam; + pcl::transformPointCloud(cloud_odom, cloud_in_cam, T_cam_odom); + + return projectCloudToImage(cloud_in_cam); +} + +cv::Mat CloudReprojector::projectCloudToImage(const pcl::PointCloud& cloud_in_cam) const +{ + cv::Mat img = cv::Mat::zeros(camera_params_.image_height, camera_params_.image_width, CV_8UC3); + img.setTo(cv::Scalar(255, 255, 255)); + + const double fx = camera_model_->fx(); + const double fy = camera_model_->fy(); + const double cx = camera_model_->cx(); + const double cy = camera_model_->cy(); + + for (const auto& pt : cloud_in_cam) + { + if (pt.z <= 0.01) + continue; + + int u_int, v_int; + if (1) + { + // Pinhole projection (undistorted image) + u_int = static_cast(std::round(fx * pt.x / pt.z + cx)); + v_int = static_cast(std::round(fy * pt.y / pt.z + cy)); + } + else + { + // Distorted projection (original image) + Eigen::Vector3d pt_cam(pt.x, pt.y, pt.z); + Eigen::Vector2d uv = camera_model_->world2cam(pt_cam); + u_int = static_cast(std::round(uv[0])); + v_int = static_cast(std::round(uv[1])); + } + + if (u_int >= 0 && u_int < camera_params_.image_width && + v_int >= 0 && v_int < camera_params_.image_height) + { + cv::circle(img, cv::Point(u_int, v_int), point_radius_, + cv::Scalar(pt.b, pt.g, pt.r), -1); + } + } + + return img; +} \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/src/depth_image_ros2_node.cpp b/sru_ws/src/odin_ros_driver/src/depth_image_ros2_node.cpp new file mode 100644 index 0000000..b2e8c4c --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/depth_image_ros2_node.cpp @@ -0,0 +1,172 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "depth_image_ros2_node.hpp" +#include + +DepthImageRos2Node::DepthImageRos2Node(const rclcpp::NodeOptions & options) + : Node("depth_image_ros2_node", options) +{ + PointCloudToDepthConverter::CameraParams camera_params = loadCameraParams(); + + depth_converter_ = std::make_unique(camera_params); + + cloud_raw_topic_ = this->declare_parameter("cloud_raw_topic", "/odin1/cloud_raw"); + color_compressed_topic_ = this->declare_parameter("color_compressed_topic", "/odin1/image/compressed"); + color_raw_topic_ = this->declare_parameter("color_raw_topic", "/odin1/image"); + depth_image_topic_ = this->declare_parameter("depth_image_topic", "/odin1/depth_img_competetion"); + depth_cloud_topic_ = this->declare_parameter("depth_cloud_topic", "/odin1/depth_img_competetion_cloud"); + + RCLCPP_INFO_STREAM(this->get_logger(), + "\n cloud_raw_topic: " << cloud_raw_topic_ + << "\n color_compressed_topic: " << color_compressed_topic_ + << "\n color_raw_topic: " << color_raw_topic_ + << "\n depth_image_topic: " << depth_image_topic_ + << "\n depth_cloud_topic: " << depth_cloud_topic_); +} + +void DepthImageRos2Node::initialize() +{ + cloud_sub_.subscribe(this, cloud_raw_topic_); + color_compressed_sub_.subscribe(this, color_compressed_topic_); + color_sub_.subscribe(this, color_raw_topic_); + + sync_ = std::make_shared(MySyncPolicy(10), cloud_sub_, color_sub_); + sync_->registerCallback(std::bind(&DepthImageRos2Node::syncCallback, this, + std::placeholders::_1, std::placeholders::_2)); + + it_ = std::make_shared(shared_from_this()); + depth_image_pub_ = it_->advertise(depth_image_topic_, 1); + depth_cloud_pub_ = this->create_publisher(depth_cloud_topic_, 1); + + RCLCPP_INFO(this->get_logger(), "DepthImageRos2Node initialized successfully"); +} + +PointCloudToDepthConverter::CameraParams DepthImageRos2Node::loadCameraParams() +{ + PointCloudToDepthConverter::CameraParams params; + + params.image_width = this->declare_parameter("cam_0.image_width", 1600); + params.image_height = this->declare_parameter("cam_0.image_height", 1296); + params.A11 = this->declare_parameter("cam_0.A11", 0.0); + params.A12 = this->declare_parameter("cam_0.A12", 0.0); + params.A22 = this->declare_parameter("cam_0.A22", 0.0); + params.u0 = this->declare_parameter("cam_0.u0", 0.0); + params.v0 = this->declare_parameter("cam_0.v0", 0.0); + + params.k2 = this->declare_parameter("cam_0.k2", 0.0); + params.k3 = this->declare_parameter("cam_0.k3", 0.0); + params.k4 = this->declare_parameter("cam_0.k4", 0.0); + params.k5 = this->declare_parameter("cam_0.k5", 0.0); + params.k6 = this->declare_parameter("cam_0.k6", 0.0); + params.k7 = this->declare_parameter("cam_0.k7", 0.0); + + params.scale = this->declare_parameter("scale", 7.0); + params.point_sampling_rate = this->declare_parameter("point_sampling_rate", 5); + + std::vector Tcl_vec_param = this->declare_parameter>("Tcl_0", std::vector(16, 0.0)); + if (Tcl_vec_param.size() == 16) + { + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + params.Tcl(i, j) = Tcl_vec_param[i * 4 + j]; + } + } + } + else + { + RCLCPP_ERROR(this->get_logger(), "Tcl_0 param missing or invalid, colored reproject cloud disabled."); + rclcpp::shutdown(); + } + + if (params.A11 < 1e-6 || params.A22 < 1e-6 || params.u0 < 1e-6 || params.v0 < 1e-6) + { + RCLCPP_ERROR(this->get_logger(), "Invalid camera intrinsics A11 or A22"); + rclcpp::shutdown(); + } + + RCLCPP_INFO(this->get_logger(), "Camera intrinsics:"); + RCLCPP_INFO(this->get_logger(), "Image size: %dx%d", params.image_width, params.image_height); + RCLCPP_INFO(this->get_logger(), "Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f", + params.A11, params.A12, params.A22, params.u0, params.v0); + RCLCPP_INFO(this->get_logger(), "Distortions: k2=%f k3=%f k4=%f k5=%f k6=%f k7=%f", + params.k2, params.k3, params.k4, params.k5, params.k6, params.k7); + RCLCPP_INFO(this->get_logger(), "Scale: %f, Point sampling rate: %d", params.scale, params.point_sampling_rate); + RCLCPP_INFO_STREAM(this->get_logger(), "Extrinsics (Tcl):\n" << params.Tcl); + + return params; +} + +void DepthImageRos2Node::syncCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg, + // const sensor_msgs::msg::CompressedImage::ConstSharedPtr image_msg, + const sensor_msgs::msg::Image::ConstSharedPtr color_msg) +{ + pcl::PointCloud cloud; + pcl::fromROSMsg(*cloud_msg, cloud); + if (cloud.empty()) + { + RCLCPP_WARN(this->get_logger(), "Empty point cloud received"); + return; + } + + cv::Mat img_raw; + try + { + // img_raw = cv::imdecode(cv::Mat(image_msg->data), cv::IMREAD_COLOR); + cv_bridge::CvImageConstPtr cv_ptr = cv_bridge::toCvShare(color_msg, "bgr8"); + img_raw = cv_ptr->image; + if (img_raw.empty()) + { + RCLCPP_WARN(this->get_logger(), "Failed to decode compressed image"); + return; + } + } + catch (const cv_bridge::Exception &e) + { + RCLCPP_ERROR(this->get_logger(), "cv_bridge: %s", e.what()); + return; + } + + auto result = depth_converter_->processCloudAndImage(cloud, img_raw); + + if (!result.success) + { + RCLCPP_WARN(this->get_logger(), "Data processing failed: %s", result.error_message.c_str()); + return; + } + + publishDepthImage(result.depth_image, cloud_msg->header); + publishDepthCloud(result.colored_cloud, cloud_msg->header); +} + +void DepthImageRos2Node::publishDepthImage(const cv::Mat &img, + const std_msgs::msg::Header &header, + const std::string &encoding) +{ + sensor_msgs::msg::Image::SharedPtr depth_msg = cv_bridge::CvImage(header, encoding, img).toImageMsg(); + depth_image_pub_.publish(*depth_msg); +} + +void DepthImageRos2Node::publishDepthCloud(const pcl::PointCloud &colored_cloud, + const std_msgs::msg::Header &header) +{ + if (!colored_cloud.points.empty()) + { + sensor_msgs::msg::PointCloud2 cloud_msg; + pcl::toROSMsg(colored_cloud, cloud_msg); + cloud_msg.header = header; + depth_cloud_pub_->publish(cloud_msg); + } +} diff --git a/sru_ws/src/odin_ros_driver/src/depth_image_ros_node.cpp b/sru_ws/src/odin_ros_driver/src/depth_image_ros_node.cpp new file mode 100644 index 0000000..fb4aa55 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/depth_image_ros_node.cpp @@ -0,0 +1,165 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "depth_image_ros_node.hpp" +#include + +DepthImageRosNode::DepthImageRosNode(ros::NodeHandle &nh, ros::NodeHandle &pnh) + : nh_(nh), pnh_(pnh), it_(nh_) +{ + PointCloudToDepthConverter::CameraParams camera_params = loadCameraParams(); + + depth_converter_ = std::make_unique(camera_params); + pnh_.param("cloud_raw_topic", cloud_raw_topic_, std::string("/odin1/cloud_raw")); + pnh_.param("color_raw_topic", color_raw_topic_, std::string("/odin1/image")); + pnh_.param("color_compressed_topic_", color_compressed_topic_, std::string("/odin1/image/compressed")); + pnh_.param("depth_image_topic", depth_image_topic_, std::string("/odin1/depth_img_competetion")); + pnh_.param("depth_cloud_topic", depth_cloud_topic_, std::string("/odin1/depth_img_competetion_cloud")); + + ROS_INFO_STREAM("\n cloud_raw_topic: " << cloud_raw_topic_ + << "\n color_raw_topic: " << color_raw_topic_ + << "\n color_compressed_topic: " << color_compressed_topic_ + << "\n depth_image_topic: " << depth_image_topic_ + << "\n depth_cloud_topic: " << depth_cloud_topic_); + + cloud_sub_.subscribe(nh_, cloud_raw_topic_, 1); + color_sub_.subscribe(nh_, color_raw_topic_, 1); + color_compressed_sub_.subscribe(nh_, color_compressed_topic_, 1); + + sync_ = std::make_shared(MySyncPolicy(10), cloud_sub_, color_sub_); + sync_->registerCallback(boost::bind(&DepthImageRosNode::syncCallback, this, _1, _2)); + + depth_image_pub_ = it_.advertise(depth_image_topic_, 1); + depth_cloud_pub_ = nh_.advertise(depth_cloud_topic_, 1); + + ROS_INFO("DepthImageRosNode initialized successfully"); +} + +PointCloudToDepthConverter::CameraParams DepthImageRosNode::loadCameraParams() +{ + PointCloudToDepthConverter::CameraParams params; + + pnh_.param("cam_0/image_width", params.image_width, 1600); + pnh_.param("cam_0/image_height", params.image_height, 1296); + pnh_.param("cam_0/A11", params.A11, 0.0); + pnh_.param("cam_0/A12", params.A12, 0.0); + pnh_.param("cam_0/A22", params.A22, 0.0); + pnh_.param("cam_0/u0", params.u0, 0.0); + pnh_.param("cam_0/v0", params.v0, 0.0); + + pnh_.param("cam_0/k2", params.k2, 0.0); + pnh_.param("cam_0/k3", params.k3, 0.0); + pnh_.param("cam_0/k4", params.k4, 0.0); + pnh_.param("cam_0/k5", params.k5, 0.0); + pnh_.param("cam_0/k6", params.k6, 0.0); + pnh_.param("cam_0/k7", params.k7, 0.0); + + pnh_.param("scale", params.scale, 7.0); + pnh_.param("point_sampling_rate", params.point_sampling_rate, 5); + + std::vector Tcl_vec_param; + if (pnh_.getParam("Tcl_0", Tcl_vec_param) && Tcl_vec_param.size() == 16) + { + for (int i = 0; i < 4; ++i) + { + for (int j = 0; j < 4; ++j) + { + params.Tcl(i, j) = Tcl_vec_param[i * 4 + j]; + } + } + } + else + { + ROS_ERROR("Tcl_0 param missing or invalid, colored reproject cloud disabled."); + ros::shutdown(); + } + + if (params.A11 < 1e-6 || params.A22 < 1e-6 || params.u0 < 1e-6 || params.v0 < 1e-6) + { + ROS_ERROR("Invalid camera intrinsics A11 or A22"); + ros::shutdown(); + } + + ROS_INFO("Camera intrinsics:"); + ROS_INFO("Image size: %dx%d", params.image_width, params.image_height); + ROS_INFO("Intrinsics: A11=%f A12=%f A22=%f u0=%f v0=%f", + params.A11, params.A12, params.A22, params.u0, params.v0); + ROS_INFO("Distortions: k2=%f k3=%f k4=%f k5=%f k6=%f k7=%f", + params.k2, params.k3, params.k4, params.k5, params.k6, params.k7); + ROS_INFO("Scale: %f, Point sampling rate: %d", params.scale, params.point_sampling_rate); + ROS_INFO_STREAM("Extrinsics (Tcl):\n" + << params.Tcl); + + return params; +} + +void DepthImageRosNode::syncCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg, + const sensor_msgs::ImageConstPtr &image_msg) +{ + pcl::PointCloud cloud; + pcl::fromROSMsg(*cloud_msg, cloud); + if (cloud.empty()) + { + ROS_WARN("Empty point cloud received"); + return; + } + + cv::Mat img_raw; + try + { + // img_raw = cv::imdecode(cv::Mat(image_msg->data), cv::IMREAD_COLOR); + cv_bridge::CvImageConstPtr cv_ptr = cv_bridge::toCvShare(image_msg, "bgr8"); + img_raw = cv_ptr->image; + if (img_raw.empty()) + { + ROS_WARN("Failed to decode compressed image"); + return; + } + } + catch (const cv_bridge::Exception &e) + { + ROS_ERROR("cv_bridge: %s", e.what()); + return; + } + + auto result = depth_converter_->processCloudAndImage(cloud, img_raw); + + if (!result.success) + { + ROS_WARN("Data processing failed: %s", result.error_message.c_str()); + return; + } + + publishDepthImage(result.depth_image, cloud_msg->header); + publishDepthCloud(result.colored_cloud, cloud_msg->header); +} + +void DepthImageRosNode::publishDepthImage(const cv::Mat &img, + const std_msgs::Header &header, + const std::string &encoding) +{ + sensor_msgs::ImagePtr depth_msg = cv_bridge::CvImage(header, encoding, img).toImageMsg(); + depth_image_pub_.publish(depth_msg); +} + +void DepthImageRosNode::publishDepthCloud(const pcl::PointCloud &colored_cloud, + const std_msgs::Header &header) +{ + if (!colored_cloud.points.empty()) + { + sensor_msgs::PointCloud2 cloud_msg; + pcl::toROSMsg(colored_cloud, cloud_msg); + cloud_msg.header = header; + depth_cloud_pub_.publish(cloud_msg); + } +} diff --git a/sru_ws/src/odin_ros_driver/src/host_sdk_sample.cpp b/sru_ws/src/odin_ros_driver/src/host_sdk_sample.cpp new file mode 100644 index 0000000..7582bea --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/host_sdk_sample.cpp @@ -0,0 +1,2866 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "host_sdk_sample.h" +#include "yaml_parser.h" +#include "rawCloudRender.h" +#include "odin_calib_path.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// #include +#include +#include +#ifdef ROS2 + #include + #include + // AE/AWB debug services (custom .srv generated from this package). + #include "odin_ros_driver/srv/get_ae.hpp" + #include "odin_ros_driver/srv/get_awb.hpp" + #include "odin_ros_driver/srv/set_ae.hpp" + #include "odin_ros_driver/srv/set_awb.hpp" + #include "odin_ros_driver/srv/get_device_logs.hpp" + #include "odin_ros_driver/srv/save_map.hpp" + #include "odin_ros_driver/srv/reset_algo.hpp" +#else + #include + #include + // AE/AWB debug services (custom .srv generated by catkin). + #include "odin_ros_driver/GetAe.h" + #include "odin_ros_driver/GetAwb.h" + #include "odin_ros_driver/SetAe.h" + #include "odin_ros_driver/SetAwb.h" + #include "odin_ros_driver/GetDeviceLogs.h" + #include "odin_ros_driver/SaveMap.h" + #include "odin_ros_driver/ResetAlgo.h" +#endif +#define ros_driver_version "0.14.4" +#define required_firmware_version_major 0 +#define required_firmware_version_minor 13 +#define required_firmware_version_patch 0 + +// Global variable declarations +static device_handle odinDevice = nullptr; +static std::atomic deviceConnected(false); +static std::atomic deviceDisconnected(false); // Device disconnection flag +static std::mutex device_mutex; // Device operation mutex lock +static std::atomic g_connection_timeout(false); +static std::atomic g_map_transfer_in_progress(false); // True while a map file transfer is running +static std::atomic g_usb_version_error(false); +static std::atomic g_shutdown_requested(false); // Signal handler flag +#ifdef ROS2 + std::shared_ptr g_ros_object = nullptr; +#else + MultiSensorPublisher* g_ros_object = nullptr; +#endif + +int g_log_level = LOG_LEVEL_INFO; +int g_show_fps = 0; // FPS display toggle control + +// Custom parameter monitoring +static std::atomic g_param_monitor_running(false); +static std::thread g_param_monitor_thread; + +// Command file monitoring +static std::string g_command_file_path = ""; + +static std::mutex g_rgb_mutex; +static std::shared_ptr g_latest_bgr; +static uint64_t g_latest_rgb_timestamp = 0; +static bool g_has_rgb = false; +static capture_Image_List_t g_latest_rgb; +static bool g_renderer_initialized = false; +static std::shared_ptr g_renderer = nullptr; +std::string calib_file_ = ""; +static std::shared_ptr g_parser = nullptr; + +static constexpr size_t PTP_SMOOTH_WINDOW_SIZE = 300; +static std::mutex g_ptp_mutex; +static std::deque g_ptp_delay_buf; +static std::deque g_ptp_offset_buf; +static std::atomic g_ptp_delay_smooth{0.0}; +static std::atomic g_ptp_offset_smooth{0.0}; + +// IMU dedicated processing thread +static std::atomic g_imu_thread_running(false); +static std::thread g_imu_thread; +static std::queue g_imu_queue; +static std::mutex g_imu_queue_mutex; +static std::condition_variable g_imu_queue_cv; +static const size_t IMU_QUEUE_MAX_SIZE = 8000; + +double get_ptp_smoothed_delay() { + return g_ptp_delay_smooth.load(std::memory_order_relaxed); +} + +double get_ptp_smoothed_offset() { + return g_ptp_offset_smooth.load(std::memory_order_relaxed); +} + + // usb device +static std::string TARGET_VENDOR = "2207"; +static std::string TARGET_PRODUCT = "0019"; +// Global configuration variables +int g_sendrgb = 1; +int g_sendimu = 1; +int g_senddtof = 1; +int g_sendodom = 1; +int g_send_odom_baselink_tf = 0; +int g_tf_extra_publish_rate = 0; + +// SDK IMU smooth sending configuration +int g_enable_imu_smooth = 0; +int g_imu_smooth_frequency = 400; +int g_sendcloudslam = 0; +int g_sendcloudrender = 0; +int g_sendrgb_compressed = 0; +int g_sendrgb_undistort = 0; +int g_record_data = 0; +int g_devstatus_log = 0; +int g_pub_intensity_gray = 0; +int g_show_path = 0; +int g_show_camerapose = 0; +int g_strict_usb3_0_check = 0; +int g_use_host_ros_time = 0; +int g_save_log = 0; +int g_cloud_raw_confidence_threshold = 35; +int g_dtof_fps = 145; // DTOF sensor frame rate: 100 (10fps) or 145 (14.5fps) + +// RGB camera configuration +int g_rgb_format = 0; // 0: NV12; 1: MJPEG +int g_rgb_width = 1600; // Image width in pixels +int g_rgb_height = 1296; // Image height in pixels +int g_rgb_fps = 100; // Frame rate * 10 (300 = 30fps) + +std::filesystem::path log_root_dir_; +int g_custom_map_mode = 0; +bool g_relocalization_success_msg_printed = false; + +std::string g_relocalization_map_abs_path = ""; +std::string g_mapping_result_dest_dir = ""; +std::string g_mapping_result_file_name = ""; + +int g_send_image_mask = 0; +std::string g_image_mask_abs_path = ""; + +int g_reset_algo = 0; + +const char* DEV_STATUS_CSV_FILE = "dev_status.csv"; +FILE* dev_status_csv_file = nullptr; + +std::filesystem::path map_root_dir_; + +char driver_start_time[32]; + +typedef struct { + struct timespec start = {0, 0}; + struct timespec last = {0, 0}; + int count = 0; + std::mutex fps_mutex; +} fpsHandle; + +void update_count(fpsHandle* handle) { + struct timespec now; + std::lock_guard lock(handle->fps_mutex); + clock_gettime(CLOCK_MONOTONIC, &now); + if (handle->count == 0) { + handle->start = now; + } else { + handle->last = now; + } + handle->count++; +} + +double cal_fps(fpsHandle* handle, const char* name, bool print = false) +{ + std::lock_guard lock(handle->fps_mutex); + if (handle->count < 2) { + return 0.0; + } + double elapsed = (handle->last.tv_sec - handle->start.tv_sec) + + (handle->last.tv_nsec - handle->start.tv_nsec) / 1e9; + double fps = (handle->count - 1) / elapsed; + if (print) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "%s FPS: %f (count: %d, elapsed: %f)", name, fps, handle->count, elapsed); + #else + ROS_INFO("%s FPS: %f (count: %d, elapsed: %f)", name, fps, handle->count, elapsed); + #endif + } + handle->start = handle->last; + handle->count = 1; + return fps; +} + +static fpsHandle rgb_rx_fps; +static fpsHandle dtof_rx_fps; +static fpsHandle imu_rx_fps; +static fpsHandle slam_cloud_rx_fps; +static fpsHandle slam_odom_rx_fps; +static fpsHandle slam_odom_highfreq_rx_fps; + +class RosNodeControlImpl : public RosNodeControlInterface { + public: + void setDtofSubframeODR(int interval) override { + dtof_subframe_interval_time = interval; + } + + int getDtofSubframeODR() const override { + return dtof_subframe_interval_time; + } + + void setSendOdomBaseLinkTF(bool send_odom_baselink_tf) override { + pub_odom_baselink_tf = send_odom_baselink_tf; + } + + bool sendOdomBaseLinkTF() const override { + return pub_odom_baselink_tf; + } + + void setCloudRawConfidenceThreshold(int threshold) { + cloud_raw_confidence_threshold = threshold; + } + int cloudRawConfidenceThreshold() const { + return cloud_raw_confidence_threshold; + } + + void setTfExtraPublishRate(int rate_hz) override { + tf_extra_publish_rate = rate_hz; + } + + int getTfExtraPublishRate() const override { + return tf_extra_publish_rate; + } + private: + int dtof_subframe_interval_time = 0; + bool pub_use_host_ros_time = false; + bool pub_odom_baselink_tf = false; + int cloud_raw_confidence_threshold = 35; + int tf_extra_publish_rate = 0; + }; + +static RosNodeControlImpl g_rosNodeControlImpl; + +RosNodeControlInterface* getRosNodeControl() { + return &g_rosNodeControlImpl; +} + +// Return resident memory (RSS) in **megabytes** for a given PID +double read_rss_mb(pid_t pid) { + std::string path = "/proc/" + std::to_string(pid) + "/status"; + std::ifstream in(path); + if (!in) return 0.0; + std::string key; + long kb = 0; + while (in >> key) { + if (key == "VmRSS:") { // VmRSS is reported in kB + in >> kb; + break; + } + in.ignore(std::numeric_limits::max(), '\n'); + } + return kb / 1024.0; // convert to MB +} + +double read_pss_mb(pid_t pid) { + std::string path = "/proc/" + std::to_string(pid) + "/smaps_rollup"; + std::ifstream in(path); + if (!in) return 0.0; + std::string key; + long kb = 0; + while (in >> key) { + if (key == "Pss:") { // Proportional Set Size in kB + in >> kb; + break; + } + in.ignore(std::numeric_limits::max(), '\n'); + } + return kb / 1024.0; // convert to MB +} + +// Recursively collect child PIDs of the given pid +void collect_children(pid_t pid, std::vector& all) { + std::string task_path = "/proc/" + std::to_string(pid) + + "/task/" + std::to_string(pid) + "/children"; + std::ifstream in(task_path); + pid_t child; + while (in >> child) { + all.push_back(child); + collect_children(child, all); + } +} + +void clear_all_queues(); +static void stop_imu_thread(); + +static bool convert_calib_to_cam_in_ex(const std::string& calib_path, const std::filesystem::path& out_path); + +// Signal handler for Ctrl+C +static void signal_handler(int signum) { + if (signum == SIGINT || signum == SIGTERM) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("signal_handler"), "Received signal %d, shutting down...", signum); + #else + ROS_INFO("Received signal %d, shutting down...", signum); + #endif + + g_shutdown_requested = true; + + // Stop TF extra publish thread + #ifdef ROS2 + if (g_ros_object) { + g_ros_object->stopTfExtraPublishTimer(); + } + #endif + + // Stop IMU dedicated thread + stop_imu_thread(); + + // Stop custom parameter monitoring thread + g_param_monitor_running = false; + if (g_param_monitor_thread.joinable()) { + g_param_monitor_thread.join(); + } + + // Close device + if (odinDevice) { + // Convert calib.yaml to cam_in_ex.txt at program end + if (g_ros_object) { + const std::filesystem::path out_path = g_ros_object->get_root_dir() / "image" / "cam_in_ex.txt"; + (void)convert_calib_to_cam_in_ex(calib_file_, out_path); + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "pose_index: %d", g_ros_object->get_pose_index()); + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "cloud_index: %d", g_ros_object->get_cloud_index()); + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "image_index: %d", g_ros_object->get_image_index()); + #else + ROS_INFO("pose_index: %d", g_ros_object->get_pose_index()); + ROS_INFO("cloud_index: %d", g_ros_object->get_cloud_index()); + ROS_INFO("image_index: %d", g_ros_object->get_image_index()); + #endif + } + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("signal_handler"), "Closing device..."); + #else + ROS_INFO("Closing device..."); + #endif + + if (lidar_stop_stream(odinDevice, LIDAR_MODE_SLAM)) + { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "lidar_stop_stream failed"); + #else + ROS_INFO("lidar_stop_stream failed"); + #endif + } + odinDevice = nullptr; + } + + // Deinitialize lidar system + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("signal_handler"), "Deinitializing lidar system..."); + #else + ROS_INFO("Deinitializing lidar system..."); + #endif + lidar_system_deinit(); + + // Close CSV file + if (dev_status_csv_file) { + std::fflush(dev_status_csv_file); + fclose(dev_status_csv_file); + dev_status_csv_file = nullptr; + } + + // IMPORTANT: destroy ROS publishers/subscribers BEFORE shutting down + // the ROS context. Otherwise the global g_ros_object (a shared_ptr) + // is destroyed by static finalizers AFTER rclcpp::shutdown(), which + // triggers a flood of "Failed to delete datawriter" / + // "Error in destruction of rcl publisher handle: cannot publish data". + // Mirrors the clean-exit ordering at the end of main(). + // 必须在关闭 ROS 上下文之前先析构 publisher/subscriber。否则全局 + // g_ros_object(shared_ptr)会在 rclcpp::shutdown() 之后由静态析构器 + // 销毁,rmw 层会刷出大量 "Failed to delete datawriter" / + // "Error in destruction of rcl publisher handle" 噪声。此处与 main() + // 末尾的正常退出顺序保持一致。 + #ifdef ROS2 + if (g_ros_object) { + g_ros_object.reset(); + } + rclcpp::shutdown(); + #else + if (g_ros_object) { + delete g_ros_object; + g_ros_object = nullptr; + } + ros::shutdown(); + #endif + + exit(0); + } +} + +// Custom parameter monitoring function +// Note: Map transfer is now triggered directly in process_command_file() when save_map=1 is set, +// so this monitor no longer needs to detect state changes. It's kept for potential future use +// or for monitoring other parameters. +static void custom_parameter_monitor() { + while (g_param_monitor_running && deviceConnected) { + // Currently no active monitoring needed since map transfer is triggered directly + // in process_command_file() when save_map=1 is set. + // This loop is kept for potential future parameter monitoring needs. + + // Sleep for 1 second (1Hz) + std::this_thread::sleep_for(std::chrono::seconds(1)); + } +} + +// Process command from file +static void process_command_file() { + if (!std::filesystem::exists(g_command_file_path)) { + return; + } + + std::ifstream file(g_command_file_path); + if (!file.is_open()) { + return; + } + + std::string line; + if (std::getline(file, line)) { + file.close(); + + // Delete the command file after reading + std::filesystem::remove(g_command_file_path); + + if (line.empty()) return; + + std::istringstream iss(line); + std::string command, param_name, value_str; + + if (!(iss >> command >> param_name >> value_str)) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("command_processor"), "Invalid command format. Usage: set "); + #else + ROS_WARN("Invalid command format. Usage: set "); + #endif + return; + } + + if (command == "set") { + if (!deviceConnected || !odinDevice) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("command_processor"), "Device not connected!"); + #else + ROS_WARN("Device not connected!"); + #endif + return; + } + + try { + int value = std::stoi(value_str); + + // Early reject: if a map transfer is already running, ignore new save_map=1 requests + // to avoid spurious "Successfully set save_map = 1" followed by background failure. + if (param_name == "save_map" && value == 1 && g_map_transfer_in_progress.load()) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("command_processor"), + "Map transfer already in progress, ignoring this save_map=1 request. Please wait for current transfer to complete."); + #else + ROS_WARN("Map transfer already in progress, ignoring this save_map=1 request. Please wait for current transfer to complete."); + #endif + return; + } + + // Special handling for "save_map = 1": delegate the entire flow (set -> poll + // -> fetch) to the SDK's unified lidar_save_map() API. We deliberately skip + // the generic lidar_set_custom_parameter() call here, because lidar_save_map() + // already issues that set internally; doing it twice could re-trigger map + // generation on the device side after it already completed once. + if (param_name == "save_map" && value == 1) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("command_processor"), + "Successfully set %s = %d", param_name.c_str(), value); + #else + ROS_INFO("Successfully set %s = %d", param_name.c_str(), value); + #endif + { + auto now = std::chrono::system_clock::now(); + std::time_t t = std::chrono::system_clock::to_time_t(now); + std::tm tm{}; + #ifdef _WIN32 + localtime_s(&tm, &t); + #else + localtime_r(&t, &tm); + #endif + char map_save_time[32]; + std::strftime(map_save_time, sizeof(map_save_time), "%Y%m%d_%H%M%S", &tm); + + std::string map_dir = g_mapping_result_dest_dir != "" ? g_mapping_result_dest_dir : map_root_dir_.string(); + std::string map_name = g_mapping_result_file_name != "" ? g_mapping_result_file_name : "map_" + std::string(map_save_time) + ".bin"; + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("command_processor"), + "Map save triggered, will transfer to [%s/%s]", map_dir.c_str(), map_name.c_str()); + #else + ROS_INFO("Map save triggered, will transfer to [%s/%s]", map_dir.c_str(), map_name.c_str()); + #endif + + // Mark transfer as in-progress BEFORE spawning the thread to avoid + // race conditions with subsequent set save_map=1 calls. + g_map_transfer_in_progress.store(true); + + // Run save-map in a background thread so we don't block the command processor. + // All the orchestration (trigger -> poll -> fetch) is now handled inside + // the SDK's lidar_save_map() one-shot API, so this side just blocks on it + // and reports the final outcome. + std::thread([map_dir, map_name]() { + // 0 = use SDK default generation timeout (120s). + int ret = lidar_save_map(odinDevice, map_dir.c_str(), map_name.c_str(), 0); + // Always clear the in-progress flag when this thread exits + g_map_transfer_in_progress.store(false); + + if (ret == 0) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("map_transfer"), "Map transfer completed: %s/%s", map_dir.c_str(), map_name.c_str()); + #else + ROS_INFO("Map transfer completed: %s/%s", map_dir.c_str(), map_name.c_str()); + #endif + } else if (ret == -2) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("map_transfer"), "Map transfer skipped: device is busy with another transfer"); + #else + ROS_WARN("Map transfer skipped: device is busy with another transfer"); + #endif + } else { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("map_transfer"), "Map transfer failed, error code: %d", ret); + #else + ROS_WARN("Map transfer failed, error code: %d", ret); + #endif + } + }).detach(); + } + return; // save_map=1 handled, skip the generic set path below + } + + // Special handling for "spad_filter": host-side SPAD crosstalk filter + // toggle, not a device-side parameter, so call lidar_enable_spad_filter() + // directly instead of lidar_set_custom_parameter(). + if (param_name == "spad_filter") { + int ret = lidar_enable_spad_filter(value); + if (ret == 0) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("command_processor"), + "Successfully set %s = %d", param_name.c_str(), value); + #else + ROS_INFO("Successfully set %s = %d", param_name.c_str(), value); + #endif + } else { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("command_processor"), + "Failed to set %s = %d, error: %d", param_name.c_str(), value, ret); + #else + ROS_ERROR("Failed to set %s = %d, error: %d", param_name.c_str(), value, ret); + #endif + } + return; + } + + // Generic path for all other parameters (and save_map=0 / save_map=N>1). + int result = lidar_set_custom_parameter(odinDevice, param_name.c_str(), &value, sizeof(int)); + if (result == 0) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("command_processor"), + "Successfully set %s = %d", param_name.c_str(), value); + #else + ROS_INFO("Successfully set %s = %d", param_name.c_str(), value); + #endif + } else if (result == -2) { + // Device is transferring file, this is expected if user triggers save_map again + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("command_processor"), + "Device is busy transferring file, please wait for current transfer to complete"); + #else + ROS_INFO("Device is busy transferring file, please wait for current transfer to complete"); + #endif + } else { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("command_processor"), + "Failed to set %s = %d, error: %d", param_name.c_str(), value, result); + #else + ROS_ERROR("Failed to set %s = %d, error: %d", param_name.c_str(), value, result); + #endif + } + } catch (const std::exception& e) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("command_processor"), "Invalid value: %s", value_str.c_str()); + #else + ROS_ERROR("Invalid value: %s", value_str.c_str()); + #endif + } + } else { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("command_processor"), "Unknown command: %s", command.c_str()); + #else + ROS_WARN("Unknown command: %s", command.c_str()); + #endif + } + } else { + file.close(); + } +} + +// detect USB3.0 +bool isUsb3OrHigher(const std::string& vendorId, const std::string& productId) { + std::string command = "lsusb -d " + vendorId + ":" + productId + " -v | grep 'bcdUSB'"; + + std::array buffer; + std::string result; + std::unique_ptr pipe(popen(command.c_str(), "r"), pclose); + if (!pipe) { + throw std::runtime_error("popen() failed!"); + } + while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { + result += buffer.data(); + } + + if (result.empty()) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("usb_check"), "Failed to get USB version information"); + #else + ROS_ERROR("Failed to get USB version information"); + #endif + return false; + } + + // find bcdUSB + size_t pos = result.find("bcdUSB"); + if (pos == std::string::npos) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("usb_check"), "bcdUSB field not found in lsusb output"); + #else + ROS_ERROR("bcdUSB field not found in lsusb output"); + #endif + return false; + } + + std::string versionStr = result.substr(pos + 7); // "bcdUSB" + space + float version = std::stof(versionStr); + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("usb_check"), "Detected USB version: %.1f", version); + #else + ROS_INFO("Detected USB version: %.1f", version); + #endif + if (!g_strict_usb3_0_check) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("usb_check"), "Strict USB3.0 check disabled"); + #else + ROS_INFO("Strict USB3.0 check disabled"); + #endif + return true; + } + return version >= 3.0; +} + +bool isUsbDevicePresent(const std::string& vendorId, const std::string& productId) { + std::ifstream devicesList("/sys/bus/usb/devices"); + if (devicesList.is_open()) { + std::string line; + while (std::getline(devicesList, line)) { + if (line.find('.') != std::string::npos) continue; + if (line.empty()) continue; + + std::string vendorPath = "/sys/bus/usb/devices/" + line + "/idVendor"; + std::ifstream vendorFile(vendorPath); + if (vendorFile.is_open()) { + std::string vendorContent; + if (std::getline(vendorFile, vendorContent)) { + vendorContent.erase(vendorContent.find_last_not_of(" \n\r\t") + 1); + + std::string productPath = "/sys/bus/usb/devices/" + line + "/idProduct"; + std::ifstream productFile(productPath); + if (productFile.is_open()) { + std::string productContent; + if (std::getline(productFile, productContent)) { + productContent.erase(productContent.find_last_not_of(" \n\r\t") + 1); + + if (vendorContent == vendorId && productContent == productId) { + return true; + } + } + productFile.close(); + } + } + vendorFile.close(); + } + } + devicesList.close(); + } + return false; +} +// Convert calib.yaml to cam_in_ex.txt +static bool convert_calib_to_cam_in_ex(const std::string& calib_path, const std::filesystem::path& out_path) { + try { + if (calib_path.empty()) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), "calib_file_ is empty, skip writing cam_in_ex.txt"); + #else + ROS_WARN("calib_file_ is empty, skip writing cam_in_ex.txt"); + #endif + return false; + } + + YAML::Node root = YAML::LoadFile(calib_path); + + // Read Tcl_0 matrix (16 values) + std::array Tcl{}; + YAML::Node tcl = root["Tcl_0"]; + for (size_t i = 0; i < 16; ++i) { + if (tcl && tcl.IsSequence() && i < tcl.size()) { + Tcl[i] = tcl[i].as(); + } else { + // Default last row to [0,0,0,1] if missing, others 0 + Tcl[i] = (i == 15) ? 1.0 : 0.0; + } + } + + // Read cam_0 parameters (with defaults) + YAML::Node cam0 = root["cam_0"]; + auto get_i = [&](const char* key, int def) -> int { + return (cam0 && cam0[key]) ? cam0[key].as() : def; + }; + auto get_d = [&](const char* key, double def) -> double { + return (cam0 && cam0[key]) ? cam0[key].as() : def; + }; + + int image_width = get_i("image_width", 0); + int image_height = get_i("image_height", 0); + double k2 = get_d("k2", 0.0); + double k3 = get_d("k3", 0.0); + double k4 = get_d("k4", 0.0); + double k5 = get_d("k5", 0.0); + double k6 = get_d("k6", 0.0); + double k7 = get_d("k7", 0.0); + double p1 = get_d("p1", 0.0); + double p2 = get_d("p2", 0.0); + double A11 = get_d("A11", 0.0); + double A12 = get_d("A12", 0.0); + double A22 = get_d("A22", 0.0); + double u0 = get_d("u0", 0.0); + double v0 = get_d("v0", 0.0); + + // Ensure parent directory exists + std::error_code ec; + std::filesystem::create_directories(out_path.parent_path(), ec); + + // Truncate file then write content + std::ofstream ofs(out_path, std::ios::out | std::ios::trunc); + if (!ofs.is_open()) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Failed to open cam_in_ex.txt for write: %s", out_path.string().c_str()); + #else + ROS_ERROR("Failed to open cam_in_ex.txt for write: %s", out_path.string().c_str()); + #endif + return false; + } + + auto fmt = [](double v) { + std::ostringstream ss; ss.setf(std::ios::fixed); ss << std::setprecision(6) << v; return ss.str(); + }; + + // Write Tcl_0 with line breaks every 4 elements + ofs << "Tcl_0: ["; + for (int i = 0; i < 16; ++i) { + if (i > 0) { + ofs << ", "; + if (i % 4 == 0) ofs << "\n "; + } + ofs << fmt(Tcl[i]); + } + ofs << "]\n"; + + // Write cam_0 block + ofs << "cam_0: \n"; + ofs << " image_width: " << image_width << "\n"; + ofs << " image_height: " << image_height << "\n"; + ofs << " k2: " << fmt(k2) << "\n"; + ofs << " k3: " << fmt(k3) << "\n"; + ofs << " k4: " << fmt(k4) << "\n"; + ofs << " k5: " << fmt(k5) << "\n"; + ofs << " k6: " << fmt(k6) << "\n"; + ofs << " k7: " << fmt(k7) << "\n"; + ofs << " p1: " << fmt(p1) << "\n"; + ofs << " p2: " << fmt(p2) << "\n"; + ofs << " A11: " << fmt(A11) << "\n"; + ofs << " A12: " << fmt(A12) << "\n"; + ofs << " A22: " << fmt(A22) << "\n"; + ofs << " u0: " << fmt(u0) << "\n"; + ofs << " v0: " << fmt(v0) << "\n"; + + ofs.flush(); + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Wrote cam_in_ex.txt to: %s", out_path.string().c_str()); + #else + ROS_INFO("Wrote cam_in_ex.txt to: %s", out_path.string().c_str()); + #endif + return true; + } catch (const std::exception& e) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Failed to convert calib.yaml: %s", e.what()); + #else + ROS_ERROR("Failed to convert calib.yaml: %s", e.what()); + #endif + return false; + } +} + +// Get package share path +std::string get_package_share_path(const std::string& package_name) { +#ifdef ROS2 + try { + return ament_index_cpp::get_package_share_directory(package_name); + } catch (const std::exception& e) { + throw std::runtime_error("Package not found: " + std::string(e.what())); + } +#else + try { + return ros::package::getPath(package_name); + } catch (const ros::InvalidNameException& e) { + throw std::runtime_error("Package not found: " + std::string(e.what())); + } +#endif +} + +std::string get_package_source_directory() { + // 获取当前源文件的绝对路径 + std::filesystem::path current_file(__FILE__); + + // 回溯到包根目录(包含package.xml的目录) + auto path = current_file.parent_path(); + while (!path.empty() && !std::filesystem::exists(path / "package.xml")) { + path = path.parent_path(); + } + + if (path.empty()) { + throw std::runtime_error("Failed to locate package root directory"); + } + + return path.string(); +} + +std::string get_package_path(const std::string& package_name) { + #ifdef ROS2 + return ament_index_cpp::get_package_share_directory(package_name); + #else + return ros::package::getPath(package_name); + #endif +} + +// Clear all queues +void clear_all_queues() { + // Reset state variables + g_latest_bgr.reset(); + g_latest_rgb_timestamp = 0; + g_has_rgb = false; + + // Clear IMU queue + { + std::lock_guard lock(g_imu_queue_mutex); + while (!g_imu_queue.empty()) { + g_imu_queue.pop(); + } + } +} + +// IMU dedicated processing thread routine +static void imu_thread_routine() +{ + // Try to set higher thread priority for IMU processing + pthread_t this_thread = pthread_self(); + struct sched_param param; + param.sched_priority = 70; + + int ret = pthread_setschedparam(this_thread, SCHED_FIFO, ¶m); + if (ret != 0) { + ret = pthread_setschedparam(this_thread, SCHED_RR, ¶m); + } + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("imu_thread"), "IMU dedicated thread started (priority: %d)", param.sched_priority); + #else + ROS_INFO("IMU dedicated thread started (priority: %d)", param.sched_priority); + #endif + + while (g_imu_thread_running) { + std::unique_lock lock(g_imu_queue_mutex); + + // Wait for IMU data + g_imu_queue_cv.wait(lock, []() { + return !g_imu_queue.empty() || !g_imu_thread_running; + }); + + if (!g_imu_thread_running) { + break; + } + + // Process all pending IMU data + while (!g_imu_queue.empty() && g_imu_thread_running) { + imu_convert_data_t imu_data = g_imu_queue.front(); + g_imu_queue.pop(); + lock.unlock(); + + // Publish IMU data + if (g_ros_object && g_sendimu) { + g_ros_object->publishImu(&imu_data); + } + + lock.lock(); + } + } + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("imu_thread"), "IMU dedicated thread exiting"); + #else + ROS_INFO("IMU dedicated thread exiting"); + #endif +} + +// Start IMU dedicated thread +static void start_imu_thread() +{ + if (!g_imu_thread_running) { + // 先确保之前的线程已经结束,避免 terminate called without an active exception + if (g_imu_thread.joinable()) { + g_imu_thread.join(); + } + g_imu_thread_running = true; + g_imu_thread = std::thread(imu_thread_routine); + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("imu_thread"), "IMU dedicated thread created"); + #else + ROS_INFO("IMU dedicated thread created"); + #endif + } +} + +// Stop IMU dedicated thread +static void stop_imu_thread() +{ + if (g_imu_thread_running) { + g_imu_thread_running = false; + g_imu_queue_cv.notify_all(); + if (g_imu_thread.joinable()) { + g_imu_thread.join(); + } + + // Clear queue + std::lock_guard lock(g_imu_queue_mutex); + while (!g_imu_queue.empty()) { + g_imu_queue.pop(); + } + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("imu_thread"), "IMU dedicated thread stopped"); + #else + ROS_INFO("IMU dedicated thread stopped"); + #endif + } +} + +// Lidar data callback +static void lidar_data_callback(const lidar_data_t *data, void *user_data) +{ + // If device is not connected, ignore all data + if (!deviceConnected) { + return; + } + + // Check g_ros_object before using it + if (!g_ros_object) { + return; + } + + device_handle *dev_handle = static_cast(user_data); + if(!dev_handle || !data) { + printf("Invalid device handle or data.\n"); + return; + } + imu_convert_data_t *imudata = nullptr; + lidar_device_status_t *dev_info_data; + + pid_t self = getpid(); + std::vector pids; + + double total_mb = 0.0; + + switch(data->type) { + case LIDAR_DT_NONE: + printf("empty lidar data type: %x\n", data->type); + break; + case LIDAR_DT_RAW_RGB: + if (g_sendrgb) { + g_ros_object->publishRgb((capture_Image_List_t *)&data->stream); + } + update_count(&rgb_rx_fps); + break; + case LIDAR_DT_RAW_IMU: + if (g_sendimu) { + imudata = (imu_convert_data_t *)data->stream.imageList[0].pAddr; + // Enqueue IMU data for dedicated thread processing + { + std::lock_guard lock(g_imu_queue_mutex); + if (g_imu_queue.size() >= IMU_QUEUE_MAX_SIZE) { + g_imu_queue.pop(); // Drop oldest if full + } + g_imu_queue.push(*imudata); + } + g_imu_queue_cv.notify_one(); + } + update_count(&imu_rx_fps); + break; + case LIDAR_DT_RAW_DTOF: + if (g_senddtof ) { + g_ros_object->publishIntensityCloud((capture_Image_List_t *)&data->stream, 1); + } + if (g_pub_intensity_gray) { + g_ros_object->publishGrayUInt8((capture_Image_List_t *)&data->stream, 2); + } + update_count(&dtof_rx_fps); + break; + case LIDAR_DT_SLAM_CLOUD: + if (g_sendcloudslam) { + g_ros_object->publishPC2XYZRGBA((capture_Image_List_t *)&data->stream, 0); + } + update_count(&slam_cloud_rx_fps); + break; + case LIDAR_DT_SLAM_ODOMETRY: + if (g_sendodom) { + g_ros_object->publishOdometry((capture_Image_List_t *)&data->stream, OdometryType::STANDARD, g_show_path, g_show_camerapose); + } + update_count(&slam_odom_rx_fps); + break; + case LIDAR_DT_DEV_STATUS: + dev_info_data = (lidar_device_status_t *)data->stream.imageList[0].pAddr; + + pids.push_back(self); + collect_children(self, pids); + for (pid_t p : pids) { + total_mb += read_pss_mb(p); // read_rss_mb(p); + } + + if (g_devstatus_log) { + if (dev_status_csv_file) { + // append the data row + int rc = 0; + rc = std::fprintf(dev_status_csv_file, "%.2f,%d,%d,%d,%d,%d,", + dev_info_data->uptime_seconds, + dev_info_data->soc_thermal.package_temp, + dev_info_data->soc_thermal.cpu_temp, + dev_info_data->soc_thermal.center_temp, + dev_info_data->soc_thermal.gpu_temp, + dev_info_data->soc_thermal.npu_temp); + if (rc < 0) { + printf("Failed to write to dev_status_csv_file\n"); + } + + rc = std::fprintf(dev_status_csv_file, "%d,%d,", + dev_info_data->dtof_sensor.tx_temp, + dev_info_data->dtof_sensor.rx_temp); + if (rc < 0) { + printf("Failed to write to dev_status_csv_file\n"); + } + + for (int i = 0; i < 8; i++) { + rc = std::fprintf(dev_status_csv_file, "%d,", dev_info_data->cpu_use_rate[i]); + } + rc = std::fprintf(dev_status_csv_file, "%d,", dev_info_data->ram_use_rate); + + rc = std::fprintf(dev_status_csv_file, "%.2f,%.2f,%.2f,", + ((float)dev_info_data->rgb_sensor.configured_odr)/1000, + ((float)dev_info_data->rgb_sensor.tx_odr)/1000, + cal_fps(&rgb_rx_fps, "rgb_rx") + ); + if (rc < 0) { + printf("Failed to write to dev_status_csv_file\n"); + } + + rc = std::fprintf(dev_status_csv_file, "%.2f,%.2f,%.2f,", + ((float)dev_info_data->dtof_sensor.configured_odr)/1000, + ((float)dev_info_data->dtof_sensor.tx_odr)/1000, + cal_fps(&dtof_rx_fps, "dtof_rx") + ); + if (rc < 0) { + printf("Failed to write to dev_status_csv_file\n"); + } + + rc = std::fprintf(dev_status_csv_file, "%.2f,%.2f,%.2f,", + ((float)dev_info_data->imu_sensor.configured_odr)/1000, + ((float)dev_info_data->imu_sensor.tx_odr)/1000, + cal_fps(&imu_rx_fps, "imu_rx") + ); + if (rc < 0) { + printf("Failed to write to dev_status_csv_file\n"); + } + + rc = std::fprintf(dev_status_csv_file, "%.2f,%.2f,%.2f,%.2f,%.2f,%.2f,", + ((float)dev_info_data->slam_cloud_tx_odr)/1000, + cal_fps(&slam_cloud_rx_fps, "slam_cloud_rx"), + ((float)dev_info_data->slam_odom_tx_odr)/1000, + cal_fps(&slam_odom_rx_fps, "slam_odom_rx"), + ((float)dev_info_data->slam_odom_highfreq_tx_odr)/1000, + cal_fps(&slam_odom_highfreq_rx_fps, "slam_odom_highfreq_rx")); + if (rc < 0) { + printf("Failed to write to dev_status_csv_file\n"); + } + + rc = std::fprintf(dev_status_csv_file, "%.2f\n", total_mb); + if (rc < 0) { + printf("Failed to write to dev_status_csv_file\n"); + } + + std::fflush(dev_status_csv_file); + } + } + if (g_show_fps) { + printf("\n [dev_info] [soc_thermal]: package_temp:%dC \n", + dev_info_data->soc_thermal.package_temp); + printf("\n [dev_info] [soc_thermal]: cpu:%dC \n", + dev_info_data->soc_thermal.cpu_temp); + printf("\n [dev_info] [soc_thermal]: center_temp:%dC \n", + dev_info_data->soc_thermal.center_temp); + printf("\n [dev_info] [soc_thermal]: gpu_temp:%dC \n", + dev_info_data->soc_thermal.gpu_temp); + printf("\n [dev_info] [soc_thermal]: npu_temp:%dC \n", + dev_info_data->soc_thermal.npu_temp); + + for ( int i=0;i<8;i++) + { + printf("\n [dev_info] [cpu]: cpu_use_rate-core[%d]:%d%% \n", + i, + dev_info_data->cpu_use_rate[i]); + + } + printf("\n [dev_info] [cpu]: ram_use_rate:%d%% \n", + dev_info_data->ram_use_rate); + + printf("\n [dev_info] [rgb]: configured_odr: %.2f HZ, tx_odr: %.2f HZ, rx_odr: %.2f HZ \n", + ((float)dev_info_data->rgb_sensor.configured_odr)/1000, + ((float)dev_info_data->rgb_sensor.tx_odr)/1000, + cal_fps(&rgb_rx_fps, "rgb_rx") + ); + + printf("\n [dev_info] [dtof]: configured_odr: %.2f HZ, tx_odr: %.2f HZ, rx_odr: %.2f HZ \n", + ((float)dev_info_data->dtof_sensor.configured_odr)/1000, + ((float)dev_info_data->dtof_sensor.tx_odr)/1000, + cal_fps(&dtof_rx_fps, "dtof_rx") + ); + printf("\n [dev_info] [dtof]: subframe_odr: %.2f \n", + ((float)dev_info_data->dtof_sensor.subframe_odr)/1000); + printf("\n [dev_info] [dtof]: txtemp:%dC, rxtemp:%dC \n", dev_info_data->dtof_sensor.tx_temp, dev_info_data->dtof_sensor.rx_temp); + + printf("\n [dev_info] [imu]: configured_odr: %.2f HZ, tx_odr: %.2f HZ, rx_odr: %.2f HZ\n", + ((float) dev_info_data->imu_sensor.configured_odr)/1000, + ((float) dev_info_data->imu_sensor.tx_odr)/1000, + cal_fps(&imu_rx_fps, "imu_rx") + ); + + printf("\n [dev_info] [slam]: slam_cloud_tx_odr: %.2f HZ, rx_odr: %.2f HZ \n", + ((float)dev_info_data->slam_cloud_tx_odr)/1000, + cal_fps(&slam_cloud_rx_fps, "slam_cloud_rx") + ); + + printf("\n [dev_info] [slam]: slam_odom_tx_odr: %.2f HZ, rx_odr: %.2f HZ \n", + ((float)dev_info_data->slam_odom_tx_odr)/1000, + cal_fps(&slam_odom_rx_fps, "slam_odom_rx") + ); + + printf("\n [dev_info] [slam]: slam_odom_highfreq_tx_odr: %.2f HZ, rx_odr: %.2f HZ \n", + ((float)dev_info_data->slam_odom_highfreq_tx_odr)/1000, + cal_fps(&slam_odom_highfreq_rx_fps, "slam_odom_highfreq_rx") + ); + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("dev_info"), "Total RAM (parent + children): %.2f MB", total_mb); + #else + ROS_INFO("Total RAM (parent + children): %.2f MB", total_mb); + #endif + + printf("\n------------------------------------------\n"); + } + break; + case LIDAR_DT_SLAM_ODOMETRY_HIGHFREQ: + { + if (g_sendodom) { + g_ros_object->publishOdometry((capture_Image_List_t *)&data->stream, OdometryType::HIGHFREQ, false, false); + } + update_count(&slam_odom_highfreq_rx_fps); + } + break; + case LIDAR_DT_SLAM_ODOMETRY_TF: + { + if (g_custom_map_mode == 2) { + g_ros_object->publishOdometry((capture_Image_List_t *)&data->stream, OdometryType::TRANSFORM, false, false); + if (!g_relocalization_success_msg_printed) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("odom"), "relocalization success!"); + #else + ROS_INFO("relocalization success!"); + #endif + g_relocalization_success_msg_printed = true; + } + } + } + break; + case LIDAR_DT_SLAM_WIWC: + { + // Always publish WIWC data for real-time extrinsics + g_ros_object->publishWiwc((capture_Image_List_t *)&data->stream); + + if(g_record_data ) { + g_ros_object->recordrotate((capture_Image_List_t *)&data->stream); + } + } + break; + case LIDAR_DT_NTP: + { + uint32_t data_len = data->stream.imageList[0].length; + if (data_len == sizeof(ptp_sync_data_t)) { + ptp_sync_data_t* ptp_data = (ptp_sync_data_t*)data->stream.imageList[0].pAddr; + { + std::lock_guard lock(g_ptp_mutex); + g_ptp_delay_buf.push_back(ptp_data->delay); + g_ptp_offset_buf.push_back(ptp_data->offset); + + if (g_ptp_delay_buf.size() > PTP_SMOOTH_WINDOW_SIZE) { + g_ptp_delay_buf.pop_front(); + } + if (g_ptp_offset_buf.size() > PTP_SMOOTH_WINDOW_SIZE) { + g_ptp_offset_buf.pop_front(); + } + + double delay_sum = 0.0; + for (double v : g_ptp_delay_buf) delay_sum += v; + double offset_sum = 0.0; + for (double v : g_ptp_offset_buf) offset_sum += v; + + if (!g_ptp_delay_buf.empty()) { + g_ptp_delay_smooth.store(delay_sum / static_cast(g_ptp_delay_buf.size()), std::memory_order_relaxed); + } + if (!g_ptp_offset_buf.empty()) { + g_ptp_offset_smooth.store(offset_sum / static_cast(g_ptp_offset_buf.size()), std::memory_order_relaxed); + } + } + + // std::cout << std::setprecision(16) + // << "PTP delay: " << ptp_data->delay + // << " offset:" << ptp_data->offset + // << " smooth_delay:" << get_ptp_smoothed_delay() + // << " smooth_offset:" << get_ptp_smoothed_offset() + // << std::endl; + } + } + break; + default: + printf("Unknown lidar data type: %x", data->type); + return; + } +} + +static void lidar_device_callback(const lidar_device_info_t* device, bool attach) +{ + int type = LIDAR_MODE_SLAM; + // int type = LIDAR_MODE_RAW; + static std::chrono::steady_clock::time_point software_connect_start; + static bool software_connect_timing = false; + + if(attach == true) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Hardware connected, starting software connection..."); + #else + ROS_INFO("Hardware connected, starting software connection..."); + #endif + if (!isUsb3OrHigher(TARGET_VENDOR, TARGET_PRODUCT)) { + #ifdef ROS2 + RCLCPP_FATAL(rclcpp::get_logger("device_cb"), + "Device connected to USB 2.0 port. This device requires USB 3.0 or higher. Exiting program."); + #else + ROS_FATAL("Device connected to USB 2.0 port. This device requires USB 3.0 or higher. Exiting program."); + #endif + + g_usb_version_error = true; + system("pkill -f rviz"); + exit(1); + return; + } + + software_connect_start = std::chrono::steady_clock::now(); + software_connect_timing = true; + + if (odinDevice) { + odinDevice = nullptr; + } + + if (lidar_create_device(const_cast(device), &odinDevice)) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Create device failed"); + #else + ROS_ERROR("Create device failed"); + #endif + return; + } + const std::string package_name = "odin_ros_driver"; + std::string config_dir = ""; + #ifdef ROS2 + char* ros_workspace = std::getenv("COLCON_PREFIX_PATH"); + if (ros_workspace) { + std::string workspace_path(ros_workspace); + size_t pos = workspace_path.find("/install"); + if (pos != std::string::npos) { + config_dir = workspace_path.substr(0, pos) + "/src/odin_ros_driver/config"; + } else { + config_dir = ament_index_cpp::get_package_share_directory(package_name) + "/config"; + } + } else { + config_dir = ament_index_cpp::get_package_share_directory(package_name) + "/config"; + } + #else + config_dir = ros::package::getPath(package_name) + "/config"; + #endif + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), + "========== [CALIB] SAVE DIR (primary): %s | BACKUP DIR: %s ==========", + odin_ros_driver::GetOdinRuntimeDir().c_str(), config_dir.c_str()); + #else + ROS_INFO("========== [CALIB] SAVE DIR (primary): %s | BACKUP DIR: %s ==========", + odin_ros_driver::GetOdinRuntimeDir().c_str(), config_dir.c_str()); + #endif + + std::filesystem::path per_con_log_root_dir; + { + auto connection_time = std::chrono::system_clock::now(); + std::time_t t = std::chrono::system_clock::to_time_t(connection_time); + std::tm tm{}; + #ifdef _WIN32 + localtime_s(&tm, &t); + #else + localtime_r(&t, &tm); + #endif + char buf[32]; + std::strftime(buf, sizeof(buf), "%Y%m%d_%H%M%S", &tm); + std::string folder_name = std::string("Conn_") + std::string(buf); + std::filesystem::path base_log_dir = log_root_dir_.empty() + ? std::filesystem::path(config_dir) + : log_root_dir_; + per_con_log_root_dir = base_log_dir / folder_name; + + std::error_code per_con_dir_err; + std::filesystem::create_directories(per_con_log_root_dir, per_con_dir_err); + if (per_con_dir_err) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), + "Failed to create per-connection log directory %s: %s", + per_con_log_root_dir.c_str(), + per_con_dir_err.message().c_str()); + #else + ROS_WARN("Failed to create per-connection log directory %s: %s", + per_con_log_root_dir.c_str(), + per_con_dir_err.message().c_str()); + #endif + } + } + + auto now = std::chrono::steady_clock::now(); + auto elapsed = std::chrono::duration_cast(now - software_connect_start); + if (elapsed.count() >= 60) { + #ifdef ROS2 + RCLCPP_FATAL(rclcpp::get_logger("device_cb"), + "Software connection timed out after 60 seconds. Exiting program."); + #else + ROS_FATAL("Software connection timed out after 60 seconds. Exiting program."); + #endif + + if (odinDevice) { + lidar_close_device(odinDevice); + lidar_destory_device(odinDevice); + odinDevice = nullptr; + } + + g_connection_timeout = true; + return; + } + + lidar_fireware_version_t version; + if(lidar_get_version(odinDevice,&version)) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Failed to get device firmware version, potential incompatible, please upgrade device firmware and retry."); + #else + ROS_ERROR("Failed to get device firmware version, potential incompatible, please upgrade device firmware and retry."); + #endif + system("pkill -f rviz"); + system("pkill -f host_sdk_sample"); + exit(1); + } + else { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger(__func__), "ros_driver_version:%s, recommended_firmware_version:%d.%d.%d", ros_driver_version, required_firmware_version_major, required_firmware_version_minor, required_firmware_version_patch); + RCLCPP_INFO(rclcpp::get_logger(__func__), "get version success."); + RCLCPP_INFO(rclcpp::get_logger(__func__), "kernel_version: V%d.%d.%d",version.kernel_version.major,version.kernel_version.minor,version.kernel_version.patch); + RCLCPP_INFO(rclcpp::get_logger(__func__), "mcu_version: V%d.%d.%d",version.mcu_version.major,version.mcu_version.minor,version.mcu_version.patch); + RCLCPP_INFO(rclcpp::get_logger(__func__), "soc_version: V%d.%d.%d",version.soc_version.major,version.soc_version.minor,version.soc_version.patch); + RCLCPP_INFO(rclcpp::get_logger(__func__), "Daemon_proc_version: V%d.%d.%d",version.Daemon_proc_version.major,version.Daemon_proc_version.minor,version.Daemon_proc_version.patch); + RCLCPP_INFO(rclcpp::get_logger(__func__), "slam_version: V%d.%d.%d",version.slam_version.major,version.slam_version.minor,version.slam_version.patch); + #else + ROS_INFO("ros_driver_version:%s, recommended_min_firmware_version:%d.%d.%d", ros_driver_version, required_firmware_version_major, required_firmware_version_minor, required_firmware_version_patch); + ROS_INFO("get version success."); + ROS_INFO("kernel_version: V%d.%d.%d",version.kernel_version.major,version.kernel_version.minor,version.kernel_version.patch); + ROS_INFO("mcu_version: V%d.%d.%d",version.mcu_version.major,version.mcu_version.minor,version.mcu_version.patch); + ROS_INFO("soc_version: V%d.%d.%d",version.soc_version.major,version.soc_version.minor,version.soc_version.patch); + ROS_INFO("Daemon_proc_version: V%d.%d.%d",version.Daemon_proc_version.major,version.Daemon_proc_version.minor,version.Daemon_proc_version.patch); + ROS_INFO("slam_version: V%d.%d.%d",version.slam_version.major,version.slam_version.minor,version.slam_version.patch); + #endif + + // Lexicographic compare on (major, minor, patch): treat the three + // fields as a single ordered tuple. e.g. 0.12.0 must be considered + // higher than 0.11.99, and 0.11.11 lower than 0.12.0. + const bool soc_version_too_low = + (version.soc_version.major < required_firmware_version_major) || + (version.soc_version.major == required_firmware_version_major && + version.soc_version.minor < required_firmware_version_minor) || + (version.soc_version.major == required_firmware_version_major && + version.soc_version.minor == required_firmware_version_minor && + version.soc_version.patch < required_firmware_version_patch); + if (soc_version_too_low) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger(__func__),"The soc version is too low, please upgrade the device firmware to at least %d.%d.%d\n",required_firmware_version_major,required_firmware_version_minor,required_firmware_version_patch); + #else + ROS_ERROR("The soc version is too low, please upgrade the device firmware to at least %d.%d.%d\n",required_firmware_version_major,required_firmware_version_minor,required_firmware_version_patch); + #endif + system("pkill -f rviz"); + system("pkill -f host_sdk_sample"); + exit(1); + } + } + + if (g_save_log) { + if (lidar_enable_encrypted_device_log(const_cast(device), per_con_log_root_dir.c_str())) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Enable log failed"); + #else + ROS_ERROR("Enable log failed"); + #endif + lidar_close_device(odinDevice); + lidar_destory_device(odinDevice); + odinDevice = nullptr; + return; + } + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Encrypted device log enabled at: %s", per_con_log_root_dir.c_str()); + #else + ROS_INFO("Encrypted device log enabled at: %s", per_con_log_root_dir.c_str()); + #endif + } else { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Encrypted device log disabled via configuration"); + #else + ROS_INFO("Encrypted device log disabled via configuration"); + #endif + } + + bool need_open_device = true; + bool get_calib_file = true; + switch (device->initial_state) { + case LIDAR_DEVICE_NOT_INITIALIZED: + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Device state: not initialized, performing full setup"); + #else + ROS_INFO("Device state: not initialized, performing full setup"); + #endif + break; + case LIDAR_DEVICE_INITIALIZED: + need_open_device = false; + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Device state: initialized, skip opening device"); + #else + ROS_INFO("Device state: initialized, skip opening device"); + #endif + break; + case LIDAR_DEVICE_STREAMING: + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), "Device state: streaming, this should not happen, exitting..."); + #else + ROS_WARN("Device state: streaming, this should not happen, exitting..."); + #endif + system("pkill -f rviz"); + exit(1); + break; + case LIDAR_DEVICE_STREAM_STOPPED: + need_open_device = false; + get_calib_file = false; + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Device state: stream stopped, resume streaming"); + #else + ROS_INFO("Device state: stream stopped, resume streaming"); + #endif + break; + default: + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), "Unknown device initial state: %d", device->initial_state); + #else + ROS_WARN("Unknown device initial state: %d", device->initial_state); + #endif + break; + } + + if (need_open_device) { + if (lidar_open_device(odinDevice)) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Open device failed"); + #else + ROS_ERROR("Open device failed"); + #endif + lidar_destory_device(odinDevice); + odinDevice = nullptr; + return; + } + } + + // Primary calib storage: writable runtime dir (~/.ros/odin_ros_driver by default), + // independent of the source/install tree so it works for both ROS1 and ROS2. + std::string calib_runtime_dir = odin_ros_driver::GetOdinRuntimeDir(); + std::error_code ec_mkdir; + std::filesystem::create_directories(calib_runtime_dir, ec_mkdir); + + std::string calib_config = calib_runtime_dir + "/calib.yaml"; + calib_file_ = calib_config; + // Also fetch when the calib file is missing at the target path, so a resume + // (STREAM_STOPPED) on a fresh runtime dir still produces calib.yaml. + bool need_calib_file = get_calib_file || !std::filesystem::exists(calib_config); + if (need_calib_file) { + if (lidar_get_calib_file(odinDevice, calib_runtime_dir.c_str())) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Failed to get calibration file"); + #else + ROS_ERROR("Failed to get calibration file"); + #endif + lidar_close_device(odinDevice); + lidar_destory_device(odinDevice); + odinDevice = nullptr; + return; + } + + // Print the primary save path + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "========== [CALIB] SAVED -> %s ==========", calib_config.c_str()); + #else + ROS_INFO("========== [CALIB] SAVED -> %s ==========", calib_config.c_str()); + #endif + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Successfully retrieved calibration files"); + #else + ROS_INFO("Successfully retrieved calibration files"); + #endif + } else { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Skipping calibration retrieval for current device state"); + #else + ROS_INFO("Skipping calibration retrieval for current device state"); + #endif + } + + // Always mirror the primary calib to the package config dir as a backup, + // regardless of whether it was freshly fetched or reused (resume case). + if (std::filesystem::exists(calib_config)) { + try { + std::filesystem::create_directories(config_dir); + std::filesystem::path backup_path = std::filesystem::path(config_dir) / "calib.yaml"; + std::filesystem::copy_file(calib_config, backup_path, + std::filesystem::copy_options::overwrite_existing); + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "========== [CALIB] BACKUP -> %s ==========", backup_path.string().c_str()); + #else + ROS_INFO("========== [CALIB] BACKUP -> %s ==========", backup_path.string().c_str()); + #endif + } catch (const std::exception& e) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), "Failed to save calibration backup to config dir: %s", e.what()); + #else + ROS_WARN("Failed to save calibration backup to config dir: %s", e.what()); + #endif + } + } + + // Push device identity / version into the binary data logger's info.txt. + // SN is parsed from the first comment line of calib.yaml (e.g. "# O1-P010100043"). + // No-op when recorddata=0 (logger not initialized). + if (g_ros_object) { + char fw_buf[48]; + char algo_buf[48]; + std::snprintf(fw_buf, sizeof(fw_buf), "%d.%d.%d", + version.soc_version.major, + version.soc_version.minor, + version.soc_version.patch); + std::snprintf(algo_buf, sizeof(algo_buf), "%d.%d.%d", + version.slam_version.major, + version.slam_version.minor, + version.slam_version.patch); + std::string sn; + if (std::filesystem::exists(calib_config)) { + std::ifstream calib_in(calib_config); + std::string first_line; + if (calib_in.is_open() && std::getline(calib_in, first_line)) { + // Strip leading '#' and any whitespace, take token until end-of-line / whitespace. + size_t pos = first_line.find_first_not_of("# \t"); + if (pos != std::string::npos) { + size_t end = first_line.find_first_of(" \t\r\n", pos); + sn = first_line.substr(pos, end == std::string::npos ? std::string::npos : end - pos); + } + } + } + g_ros_object->update_data_logger_info(sn, fw_buf, algo_buf); + } + + if (std::filesystem::exists(calib_config)) { + g_renderer = std::make_shared(); + if (g_renderer->init(calib_config)) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Point cloud renderer initialized"); + #else + ROS_INFO("Point cloud renderer initialized"); + #endif + } else { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Failed to initialize point cloud renderer"); + #else + ROS_ERROR("Failed to initialize point cloud renderer"); + #endif + } + } else { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), "Renderer config file not found: %s", calib_config.c_str()); + #else + ROS_WARN("Renderer config file not found: %s", calib_config.c_str()); + #endif + } + + + // Set DTOF sensor frame rate based on configuration + // Supported values: 100 (10fps) or 145 (14.5fps) + lidar_depth_para_t dtofpara; + if (g_dtof_fps == 100) { + dtofpara.odr = LIDAR_DEPTH_ODR_10HZ; + } else if (g_dtof_fps == 145) { + dtofpara.odr = LIDAR_DEPTH_ODR_14_5HZ; + } else if (g_dtof_fps == 290){ + dtofpara.odr = LIDAR_DEPTH_ODR_29HZ; + } else { + // Default to 14.5Hz if invalid value + dtofpara.odr = LIDAR_DEPTH_ODR_14_5HZ; + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("ros[host_sdk_sample]"), + "Invalid dtof_fps value: %d, using default 14.5fps", g_dtof_fps); + #else + ROS_WARN("Invalid dtof_fps value: %d, using default 14.5fps", g_dtof_fps); + #endif + } + + if(lidar_set_depth_parameter(odinDevice, &dtofpara)) { + printf("set depth parameter failed.\n"); + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("ros[host_sdk_sample]"), "set depth parameter failed"); + #else + ROS_WARN("set depth parameter failed"); + #endif + return; + } + + // Log the configured frame rate + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("ros[host_sdk_sample]"), + "DTOF sensor frame rate set to %.1f fps", g_dtof_fps / 10.0); + #else + ROS_INFO("DTOF sensor frame rate set to %.1f fps", g_dtof_fps / 10.0); + #endif + + // Set RGB camera configuration (format, resolution, frame rate) + // Must be called before lidar_start_stream() and lidar_activate_stream_type() + if (g_sendrgb) { + lidar_rgb_para_t rgbPara; + rgbPara.format = (lidar_rgb_format_e)g_rgb_format; + rgbPara.width = (uint32_t)g_rgb_width; + rgbPara.height = (uint32_t)g_rgb_height; + rgbPara.fps = (uint32_t)g_rgb_fps; + int rgb_rc = lidar_set_rgb_parameter(odinDevice, &rgbPara); + if (rgb_rc) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("ros[host_sdk_sample]"), + "set RGB parameter failed (rc=%d): format=%d, %dx%d@%d", rgb_rc, g_rgb_format, g_rgb_width, g_rgb_height, g_rgb_fps); + #else + ROS_WARN("set RGB parameter failed (rc=%d): format=%d, %dx%d@%d", rgb_rc, g_rgb_format, g_rgb_width, g_rgb_height, g_rgb_fps); + #endif + } else { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("ros[host_sdk_sample]"), + "RGB camera configured: format=%d, %dx%d@%.1ffps", g_rgb_format, g_rgb_width, g_rgb_height, g_rgb_fps / 10.0); + #else + ROS_INFO("RGB camera configured: format=%d, %dx%d@%.1ffps", g_rgb_format, g_rgb_width, g_rgb_height, g_rgb_fps / 10.0); + #endif + } + } + + if (lidar_set_mode(odinDevice, type)) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Set mode failed"); + #else + ROS_ERROR("Set mode failed"); + #endif + lidar_close_device(odinDevice); + lidar_destory_device(odinDevice); + odinDevice = nullptr; + return; + } + + // Apply custom parameters after setting mode + if (g_parser && !g_parser->applyCustomParameters(odinDevice)) { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), "Some custom parameters failed to apply"); + #else + ROS_WARN("Some custom parameters failed to apply"); + #endif + } + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Custom map mode: %d", g_custom_map_mode); + #else + ROS_INFO("Custom map mode: %d", g_custom_map_mode); + #endif + + // save_map=0 initialization is deferred to after lidar_start_stream() + // because the device only accepts this parameter when streaming is active. + // See the post-stream block below. + if (g_custom_map_mode == 2) { + bool result = false; + int retryTime = 3; + if (g_relocalization_map_abs_path != "" && std::filesystem::exists(g_relocalization_map_abs_path)) { + while(retryTime-- > 0) + { + result = (lidar_set_relocalization_map(odinDevice, g_relocalization_map_abs_path.c_str()) == 0); + if(result) + { + break; + } + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Relocalization map set retry...,%d",retryTime); + #else + ROS_INFO("Relocalization map set retry...,%d",retryTime); + #endif + } + } else { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Relocalization map invlalid"); + #else + ROS_ERROR("Relocalization map invlalid"); + #endif + } + if (result) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Relocalization map set successfully"); + #else + ROS_INFO("Relocalization map set successfully"); + #endif + } else { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Relocalization map path set fail"); + #else + ROS_ERROR("Relocalization map path set fail"); + #endif + lidar_close_device(odinDevice); + lidar_destory_device(odinDevice); + odinDevice = nullptr; + return; + } + } + + // Transfer image mask if enabled + if (g_send_image_mask == 1) { + if (g_image_mask_abs_path != "" && std::filesystem::exists(g_image_mask_abs_path)) { + int ret = lidar_set_image_mask(odinDevice, g_image_mask_abs_path.c_str()); + if (ret == 0) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Image mask set successfully: %s", g_image_mask_abs_path.c_str()); + #else + ROS_INFO("Image mask set successfully: %s", g_image_mask_abs_path.c_str()); + #endif + } else { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Failed to set image mask: %s, error: %d", g_image_mask_abs_path.c_str(), ret); + #else + ROS_ERROR("Failed to set image mask: %s, error: %d", g_image_mask_abs_path.c_str(), ret); + #endif + } + } else { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), "Image mask path not set or file not found: %s", g_image_mask_abs_path.c_str()); + #else + ROS_WARN("Image mask path not set or file not found: %s", g_image_mask_abs_path.c_str()); + #endif + } + } + + // Send algo_reset command if enabled + if (g_reset_algo == 1) { + int reset_value = 1; + int ret = lidar_set_custom_parameter(odinDevice, "algo_reset", &reset_value, sizeof(int)); + if (ret == 0) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Algo reset command sent successfully"); + #else + ROS_INFO("Algo reset command sent successfully"); + #endif + } else { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Failed to send algo reset command, error: %d", ret); + #else + ROS_ERROR("Failed to send algo reset command, error: %d", ret); + #endif + } + } + + lidar_data_callback_info_t data_callback_info; + data_callback_info.data_callback = lidar_data_callback; + data_callback_info.user_data = &odinDevice; + + if (lidar_register_stream_callback(odinDevice, data_callback_info)) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device"), "Register callback failed"); + #else + ROS_ERROR("Register callback failed"); + #endif + lidar_close_device(odinDevice); + lidar_destory_device(odinDevice); + odinDevice = nullptr; + return; + } + + std::string dev_status_csv_file_path_ = per_con_log_root_dir / "dev_status.csv"; + + if (dev_status_csv_file) { + std::fflush(dev_status_csv_file); + fclose(dev_status_csv_file); + dev_status_csv_file = nullptr; + } + + // Open the file in append mode + dev_status_csv_file = fopen(dev_status_csv_file_path_.c_str(), "a"); + if (!dev_status_csv_file) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("init"), "Failed to open dev_status CSV file"); + #else + ROS_ERROR("Failed to open dev_status CSV file"); + #endif + } else { + const char* header = + "uptime_seconds,package_temp,cpu_temp,center_temp,gpu_temp,npu_temp,dtof_tx_temp,dtof_rx_temp," + "cpu0,cpu1,cpu2,cpu3,cpu4,cpu5,cpu6,cpu7,ram_use(%)," + "rgb_configured_odr,rgb_tx_odr,rgb_rx_odr,dtof_configured_odr,dtof_tx_odr,dtof_rx_odr,imu_configured_odr,imu_tx_odr,imu_rx_odr," + "slam_cloud_tx_odr,slam_cloud_rx_odr,slam_odom_tx_odr,slam_odom_rx_odr,slam_odom_highfreq_tx_odr,slam_odom_highfreq_rx_odr," + "host_ram_use(mb)\n"; + fprintf(dev_status_csv_file, "%s", header); + std::fflush(dev_status_csv_file); + } + + uint32_t dtof_subframe_odr = 0; + if (lidar_start_stream(odinDevice, type, dtof_subframe_odr)) { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), "Start stream failed"); + #else + ROS_ERROR("Start stream failed"); + #endif + lidar_close_device(odinDevice); + lidar_destory_device(odinDevice); + odinDevice = nullptr; + return; + } + + if (dtof_subframe_odr > 0) { + g_rosNodeControlImpl.setDtofSubframeODR(dtof_subframe_odr); + } + + // 根据配置激活或关闭流类型 + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), + "Stream config: RGB=%d, IMU=%d, ODOM=%d, DTOF=%d, CLOUD_SLAM=%d", + g_sendrgb, g_sendimu, g_sendodom, g_senddtof, g_sendcloudslam); + #else + ROS_INFO("Stream config: RGB=%d, IMU=%d, ODOM=%d, DTOF=%d, CLOUD_SLAM=%d", + g_sendrgb, g_sendimu, g_sendodom, g_senddtof, g_sendcloudslam); + #endif + + if (g_sendrgb) { + lidar_activate_stream_type(odinDevice, LIDAR_DT_RAW_RGB); + } else { + lidar_deactivate_stream_type(odinDevice, LIDAR_DT_RAW_RGB); + } + if (g_sendimu) { + lidar_activate_stream_type(odinDevice, LIDAR_DT_RAW_IMU); + } else { + lidar_deactivate_stream_type(odinDevice, LIDAR_DT_RAW_IMU); + } + if (g_sendodom) { + lidar_activate_stream_type(odinDevice, LIDAR_DT_SLAM_ODOMETRY); + } else { + lidar_deactivate_stream_type(odinDevice, LIDAR_DT_SLAM_ODOMETRY); + } + if (g_senddtof) { + lidar_activate_stream_type(odinDevice, LIDAR_DT_RAW_DTOF); + } else { + lidar_deactivate_stream_type(odinDevice, LIDAR_DT_RAW_DTOF); + } + if (g_sendcloudslam) { + lidar_activate_stream_type(odinDevice, LIDAR_DT_SLAM_CLOUD); + } else { + lidar_deactivate_stream_type(odinDevice, LIDAR_DT_SLAM_CLOUD); + } + + // Initialize save_map=0 after streaming is active, since the device + // only accepts this parameter when streaming is active. This clears + // any residual save_map=1 from a previous session. + if (g_custom_map_mode == 1) { + int save_map_init_value = 0; + int result = lidar_set_custom_parameter(odinDevice, "save_map", &save_map_init_value, sizeof(int)); + + if (result == 0) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), + "Successfully initialized %s = %d", "save_map", save_map_init_value); + #else + ROS_INFO("Successfully initialized %s = %d", "save_map", save_map_init_value); + #endif + } else { + #ifdef ROS2 + RCLCPP_ERROR(rclcpp::get_logger("device_cb"), + "Failed to initialize %s = %d, error: %d", "save_map", save_map_init_value, result); + #else + ROS_ERROR("Failed to initialize %s = %d, error: %d", "save_map", save_map_init_value, result); + #endif + } + } + + software_connect_timing = false; + deviceConnected = true; + deviceDisconnected = false; + + // Start IMU dedicated thread + start_imu_thread(); + + // Start custom parameter monitoring thread + // 先确保之前的线程已经结束,避免 terminate called without an active exception + if (g_param_monitor_thread.joinable()) { + g_param_monitor_running = false; + g_param_monitor_thread.join(); + } + g_param_monitor_running = true; + g_param_monitor_thread = std::thread(custom_parameter_monitor); + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), + "Command interface ready. Use: echo 'set save_map 1' > %s", g_command_file_path.c_str()); + #else + ROS_INFO("Command interface ready. Use: echo 'set save_map 1' > %s", g_command_file_path.c_str()); + #endif + + if (std::filesystem::exists(calib_config)) { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "========== [CALIB] READ <- %s ==========", calib_config.c_str()); + #else + ROS_INFO("========== [CALIB] READ <- %s ==========", calib_config.c_str()); + #endif + bool load_status = g_ros_object->loadCameraParams(calib_config); + if (g_sendrgb_undistort && load_status == 0) { + g_ros_object->buildUndistortMap(); + } + } else { + #ifdef ROS2 + RCLCPP_WARN(rclcpp::get_logger("device_cb"), + "========== [CALIB] NOT FOUND <- %s (skip camera params load) ==========", calib_config.c_str()); + #else + ROS_WARN("========== [CALIB] NOT FOUND <- %s (skip camera params load) ==========", calib_config.c_str()); + #endif + } + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Software connection successful in %ld seconds", + std::chrono::duration_cast(std::chrono::steady_clock::now() - software_connect_start).count()); + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Device ready and streams activated"); + #else + ROS_INFO("Software connection successful in %ld seconds", + std::chrono::duration_cast(std::chrono::steady_clock::now() - software_connect_start).count()); + ROS_INFO("Device ready and streams activated"); + #endif + } else { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Device detaching..."); + #else + ROS_INFO("Device detaching..."); + #endif + + deviceConnected = false; + deviceDisconnected = true; + + // Stop IMU dedicated thread + stop_imu_thread(); + + // Stop custom parameter monitoring thread + g_param_monitor_running = false; + if (g_param_monitor_thread.joinable()) { + g_param_monitor_thread.join(); + } + + + clear_all_queues(); + + if (dev_status_csv_file) { + std::fflush(dev_status_csv_file); + fclose(dev_status_csv_file); + dev_status_csv_file = nullptr; + } + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "Waiting for device reconnection..."); + #else + ROS_INFO("Waiting for device reconnection..."); + #endif + } +} + +int main(int argc, char *argv[]) +{ +#ifdef ROS2 + rclcpp::init(argc, argv); + auto node = std::make_shared("lydros_node"); + g_ros_object = std::make_shared(node); + + // ----------------------------------------------------------------- + // AE/AWB debug services (ROS2). Allow a side terminal to tune the + // camera AE/AWB at runtime via `ros2 service call`, while the + // driver keeps streaming. + // + // /odin1/get_ae odin_ros_driver/srv/GetAe - query AE state + // /odin1/get_awb odin_ros_driver/srv/GetAwb - query AWB state + // /odin1/set_ae odin_ros_driver/srv/SetAe - set AE mode/params + // /odin1/set_awb odin_ros_driver/srv/SetAwb - set AWB mode/params + // + // Request semantics (set_ae / set_awb): + // mode == 0 (AUTO) : device runs its own AE/AWB loop; the + // float fields in the request are ignored. + // mode == 1 (MANUAL) : device locks AE/AWB and applies the + // provided values. Out-of-range values are + // rejected by the device with rc = 403. + // + // Parameter ranges (manual mode): + // set_ae .exposure_time : 0.0001 s .. 0.033 s + // set_ae .gain : 1.0 .. 64.0 + // set_awb.rgain : 0.1 .. 4.0 + // set_awb.bgain : 0.1 .. 4.0 + // + // Response rc convention (all 4 services): + // 0 success (success = true) + // 400.. device-side error, see lidar_ae_error_e / lidar_rgb_error_e + // -100 driver has not opened the device yet + // <0 other SDK-side error (USB / timeout / malformed reply) + // + // Concurrency: the underlying SDK calls are serialised by an + // internal mutex shared with other control commands, so no extra + // locking is required here. + // ----------------------------------------------------------------- + auto srv_get_ae = node->create_service( + "/odin1/get_ae", + [](const std::shared_ptr /*req*/, + std::shared_ptr res) { + if (odinDevice == nullptr) { + res->success = false; + res->rc = -100; + return; + } + lidar_ae_info_t info{}; + int rc = lidar_get_ae_info(odinDevice, &info); + res->rc = rc; + res->success = (rc == 0); + res->exposure_time = info.exposure_time; + res->gain = info.gain; + res->iso = info.iso; + res->brightness = info.brightness; + res->is_converged = info.is_converged; + res->env_lv = info.env_lv; + res->fps = info.fps; + }); + + auto srv_get_awb = node->create_service( + "/odin1/get_awb", + [](const std::shared_ptr /*req*/, + std::shared_ptr res) { + if (odinDevice == nullptr) { + res->success = false; + res->rc = -100; + return; + } + lidar_awb_info_t info{}; + int rc = lidar_get_awb_info(odinDevice, &info); + res->rc = rc; + res->success = (rc == 0); + res->rgain = info.rgain; + res->grgain = info.grgain; + res->gbgain = info.gbgain; + res->bgain = info.bgain; + res->cct = info.cct; + res->ccri = info.ccri; + res->is_converged = info.is_converged; + }); + + auto srv_set_ae = node->create_service( + "/odin1/set_ae", + [](const std::shared_ptr req, + std::shared_ptr res) { + if (odinDevice == nullptr) { + res->success = false; + res->rc = -100; + return; + } + lidar_cam_mode_e mode = (req->mode == 1) + ? LIDAR_CAM_MODE_MANUAL : LIDAR_CAM_MODE_AUTO; + int rc = lidar_set_ae_param(odinDevice, mode, + req->exposure_time, req->gain); + res->rc = rc; + res->success = (rc == 0); + }); + + auto srv_set_awb = node->create_service( + "/odin1/set_awb", + [](const std::shared_ptr req, + std::shared_ptr res) { + if (odinDevice == nullptr) { + res->success = false; + res->rc = -100; + return; + } + lidar_cam_mode_e mode = (req->mode == 1) + ? LIDAR_CAM_MODE_MANUAL : LIDAR_CAM_MODE_AUTO; + int rc = lidar_set_awb_param(odinDevice, mode, + req->rgain, req->bgain); + res->rc = rc; + res->success = (rc == 0); + }); + + auto srv_get_device_logs = node->create_service( + "/odin1/get_device_logs", + [](const std::shared_ptr req, + std::shared_ptr res) { + if (odinDevice == nullptr) { + res->success = false; + res->rc = -100; + return; + } + int rc = lidar_get_logs(odinDevice, req->dest_dir.c_str()); + res->rc = rc; + res->success = (rc == 0); + }); + + auto srv_save_map = node->create_service( + "/odin1/save_map", + [](const std::shared_ptr req, + std::shared_ptr res) { + if (odinDevice == nullptr) { + res->success = false; + res->rc = -100; + return; + } + int value = req->value; + if (value == 1) { + if (g_map_transfer_in_progress.load()) { + res->rc = -2; + res->success = false; + RCLCPP_WARN(rclcpp::get_logger("service"), + "Map transfer already in progress, ignoring save_map=1 request"); + return; + } + auto now = std::chrono::system_clock::now(); + std::time_t t = std::chrono::system_clock::to_time_t(now); + std::tm tm{}; + #ifdef _WIN32 + localtime_s(&tm, &t); + #else + localtime_r(&t, &tm); + #endif + char map_save_time[32]; + std::strftime(map_save_time, sizeof(map_save_time), "%Y%m%d_%H%M%S", &tm); + std::string map_dir = g_mapping_result_dest_dir != "" ? g_mapping_result_dest_dir : map_root_dir_.string(); + std::string map_name = g_mapping_result_file_name != "" ? g_mapping_result_file_name : "map_" + std::string(map_save_time) + ".bin"; + RCLCPP_INFO(rclcpp::get_logger("service"), + "Map save triggered, will transfer to [%s/%s]", map_dir.c_str(), map_name.c_str()); + g_map_transfer_in_progress.store(true); + std::thread([map_dir, map_name]() { + int ret = lidar_save_map(odinDevice, map_dir.c_str(), map_name.c_str(), 0); + g_map_transfer_in_progress.store(false); + if (ret == 0) { + RCLCPP_INFO(rclcpp::get_logger("map_transfer"), "Map transfer completed: %s/%s", map_dir.c_str(), map_name.c_str()); + } else if (ret == -2) { + RCLCPP_WARN(rclcpp::get_logger("map_transfer"), "Map transfer skipped: device is busy with another transfer"); + } else { + RCLCPP_WARN(rclcpp::get_logger("map_transfer"), "Map transfer failed, error code: %d", ret); + } + }).detach(); + res->rc = 0; + res->success = true; + } else { + int rc = lidar_set_custom_parameter(odinDevice, "save_map", &value, sizeof(int)); + res->rc = rc; + res->success = (rc == 0); + } + }); + + auto srv_reset_algo = node->create_service( + "/odin1/reset_algo", + [](const std::shared_ptr req, + std::shared_ptr res) { + if (odinDevice == nullptr) { + res->success = false; + res->rc = -100; + return; + } + int value = req->value; + int rc = lidar_set_custom_parameter(odinDevice, "algo_reset", &value, sizeof(int)); + res->rc = rc; + res->success = (rc == 0); + }); + + RCLCPP_INFO(node->get_logger(), + "Services ready: " + "/odin1/get_ae /odin1/get_awb /odin1/set_ae /odin1/set_awb; " + "/odin1/get_device_logs /odin1/save_map /odin1/reset_algo"); +#else + ros::init(argc, argv, "lydros_node"); + ros::NodeHandle nh; + g_ros_object = new MultiSensorPublisher(nh); + + // ----------------------------------------------------------------- + // AE/AWB debug services (ROS1). Same service names, srv schema, + // parameter ranges and rc convention as the ROS2 branch above + // (see the comment block before the ROS2 create_service calls). + // A side terminal can invoke these via `rosservice call ...`. + // ----------------------------------------------------------------- + ros::ServiceServer srv_get_ae = nh.advertiseService< + odin_ros_driver::GetAe::Request, + odin_ros_driver::GetAe::Response>( + "/odin1/get_ae", + boost::function( + [](odin_ros_driver::GetAe::Request & /*req*/, + odin_ros_driver::GetAe::Response &res) -> bool { + if (odinDevice == nullptr) { + res.success = false; + res.rc = -100; + return true; + } + lidar_ae_info_t info{}; + int rc = lidar_get_ae_info(odinDevice, &info); + res.rc = rc; + res.success = (rc == 0); + res.exposure_time = info.exposure_time; + res.gain = info.gain; + res.iso = info.iso; + res.brightness = info.brightness; + res.is_converged = info.is_converged; + res.env_lv = info.env_lv; + res.fps = info.fps; + return true; + })); + + ros::ServiceServer srv_get_awb = nh.advertiseService< + odin_ros_driver::GetAwb::Request, + odin_ros_driver::GetAwb::Response>( + "/odin1/get_awb", + boost::function( + [](odin_ros_driver::GetAwb::Request & /*req*/, + odin_ros_driver::GetAwb::Response &res) -> bool { + if (odinDevice == nullptr) { + res.success = false; + res.rc = -100; + return true; + } + lidar_awb_info_t info{}; + int rc = lidar_get_awb_info(odinDevice, &info); + res.rc = rc; + res.success = (rc == 0); + res.rgain = info.rgain; + res.grgain = info.grgain; + res.gbgain = info.gbgain; + res.bgain = info.bgain; + res.cct = info.cct; + res.ccri = info.ccri; + res.is_converged = info.is_converged; + return true; + })); + + ros::ServiceServer srv_set_ae = nh.advertiseService< + odin_ros_driver::SetAe::Request, + odin_ros_driver::SetAe::Response>( + "/odin1/set_ae", + boost::function( + [](odin_ros_driver::SetAe::Request &req, + odin_ros_driver::SetAe::Response &res) -> bool { + if (odinDevice == nullptr) { + res.success = false; + res.rc = -100; + return true; + } + lidar_cam_mode_e mode = (req.mode == 1) + ? LIDAR_CAM_MODE_MANUAL : LIDAR_CAM_MODE_AUTO; + int rc = lidar_set_ae_param(odinDevice, mode, + req.exposure_time, req.gain); + res.rc = rc; + res.success = (rc == 0); + return true; + })); + + ros::ServiceServer srv_set_awb = nh.advertiseService< + odin_ros_driver::SetAwb::Request, + odin_ros_driver::SetAwb::Response>( + "/odin1/set_awb", + boost::function( + [](odin_ros_driver::SetAwb::Request &req, + odin_ros_driver::SetAwb::Response &res) -> bool { + if (odinDevice == nullptr) { + res.success = false; + res.rc = -100; + return true; + } + lidar_cam_mode_e mode = (req.mode == 1) + ? LIDAR_CAM_MODE_MANUAL : LIDAR_CAM_MODE_AUTO; + int rc = lidar_set_awb_param(odinDevice, mode, + req.rgain, req.bgain); + res.rc = rc; + res.success = (rc == 0); + return true; + })); + + ros::ServiceServer srv_get_device_logs = nh.advertiseService< + odin_ros_driver::GetDeviceLogs::Request, + odin_ros_driver::GetDeviceLogs::Response>( + "/odin1/get_device_logs", + boost::function( + [](odin_ros_driver::GetDeviceLogs::Request &req, + odin_ros_driver::GetDeviceLogs::Response &res) -> bool { + if (odinDevice == nullptr) { + res.success = false; + res.rc = -100; + return true; + } + int rc = lidar_get_logs(odinDevice, req.dest_dir.c_str()); + res.rc = rc; + res.success = (rc == 0); + return true; + })); + + ros::ServiceServer srv_save_map = nh.advertiseService< + odin_ros_driver::SaveMap::Request, + odin_ros_driver::SaveMap::Response>( + "/odin1/save_map", + boost::function( + [](odin_ros_driver::SaveMap::Request &req, + odin_ros_driver::SaveMap::Response &res) -> bool { + if (odinDevice == nullptr) { + res.success = false; + res.rc = -100; + return true; + } + int value = req.value; + if (value == 1) { + if (g_map_transfer_in_progress.load()) { + res.rc = -2; + res.success = false; + ROS_WARN("Map transfer already in progress, ignoring save_map=1 request"); + return true; + } + auto now = std::chrono::system_clock::now(); + std::time_t t = std::chrono::system_clock::to_time_t(now); + std::tm tm{}; + #ifdef _WIN32 + localtime_s(&tm, &t); + #else + localtime_r(&t, &tm); + #endif + char map_save_time[32]; + std::strftime(map_save_time, sizeof(map_save_time), "%Y%m%d_%H%M%S", &tm); + std::string map_dir = g_mapping_result_dest_dir != "" ? g_mapping_result_dest_dir : map_root_dir_.string(); + std::string map_name = g_mapping_result_file_name != "" ? g_mapping_result_file_name : "map_" + std::string(map_save_time) + ".bin"; + ROS_INFO("Map save triggered, will transfer to [%s/%s]", map_dir.c_str(), map_name.c_str()); + g_map_transfer_in_progress.store(true); + std::thread([map_dir, map_name]() { + int ret = lidar_save_map(odinDevice, map_dir.c_str(), map_name.c_str(), 0); + g_map_transfer_in_progress.store(false); + if (ret == 0) { + ROS_INFO("Map transfer completed: %s/%s", map_dir.c_str(), map_name.c_str()); + } else if (ret == -2) { + ROS_WARN("Map transfer skipped: device is busy with another transfer"); + } else { + ROS_WARN("Map transfer failed, error code: %d", ret); + } + }).detach(); + res.rc = 0; + res.success = true; + } else { + int rc = lidar_set_custom_parameter(odinDevice, "save_map", &value, sizeof(int)); + res.rc = rc; + res.success = (rc == 0); + } + return true; + })); + + ros::ServiceServer srv_reset_algo = nh.advertiseService< + odin_ros_driver::ResetAlgo::Request, + odin_ros_driver::ResetAlgo::Response>( + "/odin1/reset_algo", + boost::function( + [](odin_ros_driver::ResetAlgo::Request &req, + odin_ros_driver::ResetAlgo::Response &res) -> bool { + if (odinDevice == nullptr) { + res.success = false; + res.rc = -100; + return true; + } + int value = req.value; + int rc = lidar_set_custom_parameter(odinDevice, "algo_reset", &value, sizeof(int)); + res.rc = rc; + res.success = (rc == 0); + return true; + })); + + ROS_INFO("Services ready: " + "/odin1/get_ae /odin1/get_awb /odin1/set_ae /odin1/set_awb; " + "/odin1/get_device_logs /odin1/save_map /odin1/reset_algo"); +#endif + + // Register signal handlers for Ctrl+C + signal(SIGINT, signal_handler); + signal(SIGTERM, signal_handler); + + try { + #ifdef ROS2 + std::string package_path = get_package_source_directory(); + std::cout << "package_path: " << package_path << std::endl; + #else + std::string package_path = get_package_share_path("odin_ros_driver"); + #endif + std::string config_dir = package_path + "/config"; + std::string config_file = config_dir + "/control_command.yaml"; + + // Initialize command file path to /tmp/odin_command.txt + g_command_file_path = "/tmp/odin_command.txt"; + + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("init"), "Command file path set to: %s", g_command_file_path.c_str()); + #else + ROS_INFO("Command file path set to: %s", g_command_file_path.c_str()); + #endif + + g_parser = std::make_shared(config_file); + if (!g_parser->loadConfig()) { + #ifdef ROS2 + RCLCPP_ERROR(node->get_logger(), "Failed to load config file: %s", config_file.c_str()); + #else + ROS_ERROR("Failed to load config file: %s", config_file.c_str()); + #endif + return -1; + } + + auto keys = g_parser->getRegisterKeys(); + auto keys_w_str_val = g_parser->getRegisterKeysStrVal(); + g_parser->printConfig(); + + auto get_key_value = [&](const std::string& key, int default_value) -> int { + auto it = keys.find(key); + return it != keys.end() ? it->second : default_value; + }; + + g_sendrgb = get_key_value("sendrgb", 1); + g_sendimu = get_key_value("sendimu", 1); + g_senddtof = get_key_value("senddtof", 1); + + // SDK IMU smooth sending configuration + g_enable_imu_smooth = get_key_value("enable_imu_smooth", 0); + g_imu_smooth_frequency = get_key_value("imu_smooth_frequency", 400); + g_cloud_raw_confidence_threshold = get_key_value("cloud_raw_confidence_threshold", 35); + g_rosNodeControlImpl.setCloudRawConfidenceThreshold(g_cloud_raw_confidence_threshold); + g_dtof_fps = get_key_value("dtof_fps", 145); // Read DTOF frame rate from config (100=10fps, 145=14.5fps) + g_rgb_format = get_key_value("rgb_format", 0); // 0: NV12; 1: MJPEG + g_rgb_width = get_key_value("rgb_width", 1536); + g_rgb_height = get_key_value("rgb_height", 1280); + g_rgb_fps = get_key_value("rgb_fps", 300); // 300 = 30fps + g_sendodom = get_key_value("sendodom", 1); + g_send_odom_baselink_tf = get_key_value("send_odom_baselink_tf", 0); + g_tf_extra_publish_rate = get_key_value("tf_extra_publish_rate", 0); + g_sendcloudslam = get_key_value("sendcloudslam", 0); + g_sendcloudrender = get_key_value("sendcloudrender", 1); + g_sendrgb_compressed = get_key_value("sendrgbcompressed", 1); + g_sendrgb_undistort = get_key_value("sendrgbundistort", 0); + g_record_data = get_key_value("recorddata", 0); + g_show_fps = get_key_value("showfps", 0); + g_devstatus_log = get_key_value("devstatuslog", 0); + g_pub_intensity_gray = get_key_value("pubintensitygray", 0); + g_show_path = get_key_value("showpath", 0); + g_show_camerapose = get_key_value("showcamerapose", 0); + g_log_level = get_key_value("log_devel", LOG_LEVEL_INFO); + g_strict_usb3_0_check = get_key_value("strict_usb3.0_check", 1); + g_use_host_ros_time = get_key_value("use_host_ros_time", 0); + g_save_log = get_key_value("save_log", 0); + + if (g_send_odom_baselink_tf) { + g_rosNodeControlImpl.setSendOdomBaseLinkTF(true); + } + + g_rosNodeControlImpl.setTfExtraPublishRate(g_tf_extra_publish_rate); + #ifdef ROS2 + g_ros_object->startTfExtraPublishTimer(); + #endif + + auto get_key_str_value = [&](const std::string& key, const std::string& default_value) -> std::string { + auto it = keys_w_str_val.find(key); + return it != keys_w_str_val.end() ? it->second : default_value; + }; + + g_relocalization_map_abs_path = get_key_str_value("relocalization_map_abs_path", ""); + g_mapping_result_dest_dir = get_key_str_value("mapping_result_dest_dir", ""); + g_mapping_result_file_name = get_key_str_value("mapping_result_file_name", ""); + g_image_mask_abs_path = get_key_str_value("image_mask_abs_path", ""); + + g_send_image_mask = get_key_value("sendimagemask", 0); + g_reset_algo = get_key_value("resetalgo", 0); + g_custom_map_mode = g_parser->getCustomMapMode(2); + + lidar_log_set_level(LIDAR_LOG_INFO); + + const std::string package_name = "odin_ros_driver"; + std::string data_dir = ""; + std::string log_dir = ""; + std::string map_dir = ""; + #ifdef ROS2 + char* ros_workspace = std::getenv("COLCON_PREFIX_PATH"); + if (ros_workspace) { + std::string workspace_path(ros_workspace); + size_t pos = workspace_path.find("/install"); + if (pos != std::string::npos) { + data_dir = workspace_path.substr(0, pos) + "/src/odin_ros_driver/recorddata"; + log_dir = workspace_path.substr(0, pos) + "/src/odin_ros_driver/log"; + map_dir = workspace_path.substr(0, pos) + "/src/odin_ros_driver/map"; + } else { + data_dir = ament_index_cpp::get_package_share_directory(package_name) + "/recorddata"; + log_dir = ament_index_cpp::get_package_share_directory(package_name) + "/log"; + map_dir = ament_index_cpp::get_package_share_directory(package_name) + "/map"; + } + } else { + data_dir = ament_index_cpp::get_package_share_directory(package_name) + "/recorddata"; + log_dir = ament_index_cpp::get_package_share_directory(package_name) + "/log"; + map_dir = ament_index_cpp::get_package_share_directory(package_name) + "/map"; + } + #else + data_dir = ros::package::getPath(package_name) + "/recorddata"; + log_dir = ros::package::getPath(package_name) + "/log"; + map_dir = ros::package::getPath(package_name) + "/map"; + #endif + + if (g_record_data) { + g_ros_object->initialize_data_logger(data_dir); + } + + auto now = std::chrono::system_clock::now(); + std::time_t t = std::chrono::system_clock::to_time_t(now); + std::tm tm{}; + #ifdef _WIN32 + localtime_s(&tm, &t); + #else + localtime_r(&t, &tm); + #endif + std::strftime(driver_start_time, sizeof(driver_start_time), "%Y%m%d_%H%M%S", &tm); + + if (g_devstatus_log) { + std::string folder_name = std::string("Driver_") + std::string(driver_start_time); + log_root_dir_ = std::filesystem::path(log_dir) / folder_name; + std::filesystem::create_directories(log_root_dir_); + } + + if (g_custom_map_mode == 1 && g_mapping_result_dest_dir == "") { + map_root_dir_ = std::filesystem::path(map_dir) / driver_start_time; + std::filesystem::create_directories(map_root_dir_); + } + + if (lidar_system_init(lidar_device_callback)) { + #ifdef ROS2 + RCLCPP_ERROR(node->get_logger(), "Lidar system init failed"); + #else + ROS_ERROR("Lidar system init failed"); + #endif + return -1; + } + + // Re-arm SIGINT/SIGTERM handlers: lidar_system_init() installs the + // SDK's internal crash handler which overrides our handlers above and + // prints a backtrace on Ctrl+C / kill, confusing users. + signal(SIGINT, signal_handler); + signal(SIGTERM, signal_handler); + + // Configure SDK IMU smooth sending AFTER lidar_system_init + // SDK now defaults to disabled, only enable if configured + if (g_enable_imu_smooth) { + lidar_enable_imu_smooth_sending(1); + lidar_set_imu_smooth_frequency(g_imu_smooth_frequency); + #ifdef ROS2 + RCLCPP_INFO(node->get_logger(), "Enabling SDK IMU smooth sending at %d Hz", g_imu_smooth_frequency); + #else + ROS_INFO("Enabling SDK IMU smooth sending at %d Hz", g_imu_smooth_frequency); + #endif + } else { + #ifdef ROS2 + RCLCPP_INFO(node->get_logger(), "SDK IMU smooth sending disabled"); + #else + ROS_INFO("SDK IMU smooth sending disabled"); + #endif + } + + + bool usbPresent = false; + bool usbVersionChecked = false; + while (!deviceConnected) { + #ifdef ROS2 + if (!rclcpp::ok()) { + break; + } + #else + if (!ros::ok()) // ROS1 shutdown check + { + break; + } + #endif + + usbPresent = isUsbDevicePresent(TARGET_VENDOR, TARGET_PRODUCT); + if (usbPresent) { + if (!usbVersionChecked) { + usbVersionChecked = true; + + if (!isUsb3OrHigher(TARGET_VENDOR, TARGET_PRODUCT)) { + #ifdef ROS2 + RCLCPP_FATAL(node->get_logger(), + "Device connected to USB 2.0 port. This device requires USB 3.0 or higher. Exiting program.Please use USB 3.0 and restart the device."); + #else + ROS_FATAL("Device connected to USB 2.0 port. This device requires USB 3.0 or higher. Exiting program .Please use USB 3.0 and restart the device."); + #endif + + lidar_system_deinit(); + return 1; + } + } + } + + #ifdef ROS2 + std::this_thread::sleep_for(std::chrono::seconds(1)); + #else + ros::Duration(1.0).sleep(); + #endif + } + } catch (const std::exception& e) { + #ifdef ROS2 + RCLCPP_ERROR(node->get_logger(), "Exception: %s", e.what()); + #else + ROS_ERROR("Exception: %s", e.what()); + #endif + lidar_system_deinit(); + return -1; + } + + if (!deviceConnected) { + #ifdef ROS2 + if (g_ros_object) { + g_ros_object->stopTfExtraPublishTimer(); + g_ros_object.reset(); // destroys all publishers/subscribers + } + node.reset(); // destroy the node first + rclcpp::shutdown(); + #else + if (g_ros_object) { + delete g_ros_object; + g_ros_object = nullptr; + } + ros::shutdown(); + #endif + return 1; + } + + bool disconnect_msg_printed = false; + #ifdef ROS2 + // Create 10Hz Rate object + rclcpp::Rate rate(10); + + while (rclcpp::ok()) { + rclcpp::spin_some(node); + // Check device disconnection status + if (deviceDisconnected.load()) { + if (!disconnect_msg_printed) { + RCLCPP_INFO(node->get_logger(), "Device disconnected, waiting for reconnection..."); + disconnect_msg_printed = true; + } + + // Wait 0.1 seconds + rate.sleep(); + continue; // Skip rest of this loop iteration + } + + // Data processing when device is connected + if (g_sendcloudrender) { + g_ros_object->try_process_pair(); + } + + // Check for command file + if (deviceConnected) { + process_command_file(); + } + + disconnect_msg_printed = false; + + // Wait 0.1 seconds + rate.sleep(); + } + rclcpp::shutdown(); + #else + // Create 10Hz Rate object + ros::Rate rate(10); + while (ros::ok()) { + ros::spinOnce(); + + // Check device disconnection status + if (deviceDisconnected.load()) { + if (!disconnect_msg_printed) { + ROS_INFO("Device disconnected, waiting for reconnection..."); + disconnect_msg_printed = true; + } + + // Wait 0.1 seconds + rate.sleep(); + continue; // Skip rest of this loop iteration + } + + // Data processing when device is connected + if (g_sendcloudrender) { + g_ros_object->try_process_pair(); + } + + // Check for command file + if (deviceConnected) { + process_command_file(); + } + + disconnect_msg_printed = false; + + // Wait 0.1 seconds + rate.sleep(); + } + ros::shutdown(); + #endif + + // Cleanup on normal program exit + if (odinDevice) { + // Convert calib.yaml to cam_in_ex.txt at program end + if (g_ros_object) { + const std::filesystem::path out_path = g_ros_object->get_root_dir() / "image" / "cam_in_ex.txt"; + (void)convert_calib_to_cam_in_ex(calib_file_, out_path); + } + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "pose_index: %d", g_ros_object->get_pose_index()); + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "cloud_index: %d", g_ros_object->get_cloud_index()); + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "image_index: %d", g_ros_object->get_image_index()); + #else + ROS_INFO("pose_index: %d", g_ros_object->get_pose_index()); + ROS_INFO("cloud_index: %d", g_ros_object->get_cloud_index()); + ROS_INFO("image_index: %d", g_ros_object->get_image_index()); + #endif + // Perform cleanup on normal exit + // if(lidar_stop_stream(odinDevice, LIDAR_MODE_SLAM)) + // { + // #ifdef ROS2 + // RCLCPP_INFO(rclcpp::get_logger("device_cb"), "lidar_stop_stream failed"); + // #else + // ROS_INFO("lidar_stop_stream failed"); + // #endif + // } + + if(lidar_unregister_stream_callback(odinDevice)) + { + #ifdef ROS2 + RCLCPP_INFO(rclcpp::get_logger("device_cb"), "lidar_unregister_stream_callback failed"); + #else + ROS_INFO("lidar_unregister_stream_callback failed"); + #endif + } + // lidar_close_device(odinDevice); + // lidar_destory_device(odinDevice); + + if (dev_status_csv_file) { + std::fflush(dev_status_csv_file); + fclose(dev_status_csv_file); + dev_status_csv_file = nullptr; + } + } + + // Stop custom parameter monitoring thread on exit + g_param_monitor_running = false; + if (g_param_monitor_thread.joinable()) { + g_param_monitor_thread.join(); + } + + + // lidar_system_deinit(); + + + + return 0; +} diff --git a/sru_ws/src/odin_ros_driver/src/image_overlay_node.cpp b/sru_ws/src/odin_ros_driver/src/image_overlay_node.cpp new file mode 100644 index 0000000..43de7bf --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/image_overlay_node.cpp @@ -0,0 +1,254 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "image_overlay_node.hpp" + +#ifdef ROS2 +// ==================== ROS2 Implementation ==================== + +ImageOverlayNode::ImageOverlayNode(const rclcpp::NodeOptions& options) + : Node("image_overlay_node", options) +{ + // Read from register_keys (same structure as control_command.yaml) + this->declare_parameter("register_keys.overlay_reprojected_topic", "/odin1/reprojected_image"); + this->declare_parameter("register_keys.overlay_camera_topic", "/odin1/image/undistorted"); + this->declare_parameter("register_keys.overlay_output_topic", "/odin1/overlay_image"); + this->declare_parameter("register_keys.overlay_alpha", 0.6); + + reprojected_topic_ = this->get_parameter("register_keys.overlay_reprojected_topic").as_string(); + camera_topic_ = this->get_parameter("register_keys.overlay_camera_topic").as_string(); + overlay_topic_ = this->get_parameter("register_keys.overlay_output_topic").as_string(); + alpha_ = this->get_parameter("register_keys.overlay_alpha").as_double(); + + RCLCPP_INFO(this->get_logger(), "Subscribing to: %s and %s", + reprojected_topic_.c_str(), camera_topic_.c_str()); + RCLCPP_INFO(this->get_logger(), "Publishing to: %s (alpha=%.2f)", overlay_topic_.c_str(), alpha_); + + // Independent subscriptions - no synchronization needed + reproj_sub_ = this->create_subscription( + reprojected_topic_, 10, + std::bind(&ImageOverlayNode::reprojCallback, this, std::placeholders::_1)); + + camera_sub_ = this->create_subscription( + camera_topic_, 10, + std::bind(&ImageOverlayNode::cameraCallback, this, std::placeholders::_1)); + + overlay_pub_ = this->create_publisher(overlay_topic_, 10); + + RCLCPP_INFO(this->get_logger(), "ImageOverlayNode initialized (no-sync mode)"); +} + +void ImageOverlayNode::reprojCallback(Image::ConstSharedPtr msg) +{ + try { + cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, "bgr8"); + { + std::lock_guard lock(mutex_); + latest_reproj_img_ = cv_ptr->image.clone(); + latest_header_ = msg->header; + } + } catch (cv_bridge::Exception& e) { + RCLCPP_ERROR(this->get_logger(), "cv_bridge exception (reproj): %s", e.what()); + return; + } + publishOverlay(); +} + +void ImageOverlayNode::cameraCallback(Image::ConstSharedPtr msg) +{ + try { + cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, "bgr8"); + { + std::lock_guard lock(mutex_); + latest_camera_img_ = cv_ptr->image.clone(); + } + } catch (cv_bridge::Exception& e) { + RCLCPP_ERROR(this->get_logger(), "cv_bridge exception (camera): %s", e.what()); + return; + } + publishOverlay(); +} + +void ImageOverlayNode::publishOverlay() +{ + cv::Mat reproj_copy, camera_copy; + std_msgs::msg::Header header_copy; + + { + std::lock_guard lock(mutex_); + if (latest_reproj_img_.empty() || latest_camera_img_.empty()) { + return; + } + reproj_copy = latest_reproj_img_.clone(); + camera_copy = latest_camera_img_.clone(); + header_copy = latest_header_; + } + + if (reproj_copy.size() != camera_copy.size()) { + RCLCPP_WARN(this->get_logger(), + "Image sizes don't match: reproj(%dx%d) vs camera(%dx%d)", + reproj_copy.cols, reproj_copy.rows, + camera_copy.cols, camera_copy.rows); + return; + } + + // Create overlay using alpha blending + // Replace white background in reproj with camera image, keep colored points + cv::Mat overlay = camera_copy.clone(); + + // Blend: where reproj has color (non-white), show reproj color semi-transparently + // where reproj is white (background), show camera image + + for (int y = 0; y < reproj_copy.rows; ++y) { + for (int x = 0; x < reproj_copy.cols; ++x) { + cv::Vec3b reproj_pixel = reproj_copy.at(y, x); + // Check if pixel is not white (has point cloud color) + if (reproj_pixel[0] < 250 || reproj_pixel[1] < 250 || reproj_pixel[2] < 250) { + // Blend reproj color with camera color + cv::Vec3b cam_pixel = camera_copy.at(y, x); + overlay.at(y, x) = cv::Vec3b( + static_cast(alpha_ * reproj_pixel[0] + (1 - alpha_) * cam_pixel[0]), + static_cast(alpha_ * reproj_pixel[1] + (1 - alpha_) * cam_pixel[1]), + static_cast(alpha_ * reproj_pixel[2] + (1 - alpha_) * cam_pixel[2]) + ); + } + // else: keep camera image (already in overlay) + } + } + + auto overlay_msg = cv_bridge::CvImage(header_copy, "bgr8", overlay).toImageMsg(); + overlay_pub_->publish(*overlay_msg); +} + +// ==================== ROS2 Main ==================== +int main(int argc, char **argv) +{ + rclcpp::init(argc, argv); + + auto node = std::make_shared(); + + rclcpp::spin(node); + rclcpp::shutdown(); + return 0; +} + +#else +// ==================== ROS1 Implementation ==================== + +ImageOverlayNode::ImageOverlayNode(ros::NodeHandle& nh, ros::NodeHandle& pnh) + : nh_(nh), pnh_(pnh) +{ + // Read from register_keys (same structure as control_command.yaml) + pnh_.param("register_keys/overlay_reprojected_topic", reprojected_topic_, "/odin1/reprojected_image"); + pnh_.param("register_keys/overlay_camera_topic", camera_topic_, "/odin1/image/undistorted"); + pnh_.param("register_keys/overlay_output_topic", overlay_topic_, "/odin1/overlay_image"); + pnh_.param("register_keys/overlay_alpha", alpha_, 0.6); + + ROS_INFO("Subscribing to: %s and %s", reprojected_topic_.c_str(), camera_topic_.c_str()); + ROS_INFO("Publishing to: %s (alpha=%.2f)", overlay_topic_.c_str(), alpha_); + + // Independent subscriptions - no synchronization needed + reproj_sub_ = nh_.subscribe(reprojected_topic_, 10, &ImageOverlayNode::reprojCallback, this); + camera_sub_ = nh_.subscribe(camera_topic_, 10, &ImageOverlayNode::cameraCallback, this); + + overlay_pub_ = nh_.advertise(overlay_topic_, 10); + + ROS_INFO("ImageOverlayNode initialized (no-sync mode)"); +} + +void ImageOverlayNode::reprojCallback(const sensor_msgs::ImageConstPtr& msg) +{ + try { + cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, "bgr8"); + { + std::lock_guard lock(mutex_); + latest_reproj_img_ = cv_ptr->image.clone(); + latest_header_ = msg->header; + } + } catch (cv_bridge::Exception& e) { + ROS_ERROR("cv_bridge exception (reproj): %s", e.what()); + return; + } + publishOverlay(); +} + +void ImageOverlayNode::cameraCallback(const sensor_msgs::ImageConstPtr& msg) +{ + try { + cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg, "bgr8"); + { + std::lock_guard lock(mutex_); + latest_camera_img_ = cv_ptr->image.clone(); + } + } catch (cv_bridge::Exception& e) { + ROS_ERROR("cv_bridge exception (camera): %s", e.what()); + return; + } + publishOverlay(); +} + +void ImageOverlayNode::publishOverlay() +{ + cv::Mat reproj_copy, camera_copy; + std_msgs::Header header_copy; + + { + std::lock_guard lock(mutex_); + if (latest_reproj_img_.empty() || latest_camera_img_.empty()) { + return; + } + reproj_copy = latest_reproj_img_.clone(); + camera_copy = latest_camera_img_.clone(); + header_copy = latest_header_; + } + + if (reproj_copy.size() != camera_copy.size()) { + ROS_WARN_THROTTLE(2, "Image sizes don't match: reproj(%dx%d) vs camera(%dx%d)", + reproj_copy.cols, reproj_copy.rows, camera_copy.cols, camera_copy.rows); + return; + } + + // Create overlay using alpha blending + cv::Mat overlay = camera_copy.clone(); + + for (int y = 0; y < reproj_copy.rows; ++y) { + for (int x = 0; x < reproj_copy.cols; ++x) { + cv::Vec3b reproj_pixel = reproj_copy.at(y, x); + if (reproj_pixel[0] < 250 || reproj_pixel[1] < 250 || reproj_pixel[2] < 250) { + cv::Vec3b cam_pixel = camera_copy.at(y, x); + overlay.at(y, x) = cv::Vec3b( + static_cast(alpha_ * reproj_pixel[0] + (1 - alpha_) * cam_pixel[0]), + static_cast(alpha_ * reproj_pixel[1] + (1 - alpha_) * cam_pixel[1]), + static_cast(alpha_ * reproj_pixel[2] + (1 - alpha_) * cam_pixel[2]) + ); + } + } + } + + sensor_msgs::ImagePtr overlay_msg = cv_bridge::CvImage(header_copy, "bgr8", overlay).toImageMsg(); + overlay_pub_.publish(overlay_msg); +} + +// ==================== ROS1 Main ==================== +int main(int argc, char **argv) +{ + ros::init(argc, argv, "image_overlay_node"); + ros::NodeHandle nh; + ros::NodeHandle pnh("~"); + + ImageOverlayNode node(nh, pnh); + + ros::spin(); + return 0; +} +#endif diff --git a/sru_ws/src/odin_ros_driver/src/pcd2depth_ros.cpp b/sru_ws/src/odin_ros_driver/src/pcd2depth_ros.cpp new file mode 100644 index 0000000..3c673d5 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/pcd2depth_ros.cpp @@ -0,0 +1,78 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include +#include + +#include "depth_image_ros_node.hpp" +#include "odin_calib_path.h" + +bool fileExists(const std::string& filename) { + struct stat buffer; + return (stat(filename.c_str(), &buffer) == 0); +} + +int main(int argc, char **argv) +{ + ros::init(argc, argv, "depth_projector"); + ros::NodeHandle nh; + ros::NodeHandle pnh("~"); + int senddepth=0; + pnh.param("register_keys/senddepth", senddepth, 0); + if(senddepth==0) + { + ROS_INFO("Depth image will not be published."); + return 0; + } + + std::string calib_file_path; + pnh.param("calib_file_path", calib_file_path, ""); + if (calib_file_path.empty()) { + calib_file_path = odin_ros_driver::GetOdinCalibFile(); + } + + ROS_INFO("========== [CALIB] WAIT <- %s ==========", calib_file_path.c_str()); + while(ros::ok() && !fileExists(calib_file_path)) + { + ROS_INFO_THROTTLE(5, "Still waiting for calib.yaml file..."); + ros::Duration(0.5).sleep(); + ros::spinOnce(); + } + + if(!ros::ok()) + { + ROS_INFO("Node shutdown before calib.yaml file was found."); + return 0; + } + + ROS_INFO("Found calib.yaml file! Loading parameters..."); + + std::string node_name = ros::this_node::getName(); + std::string rosparam_command = "rosparam load " + calib_file_path + " " + node_name; + int result = system(rosparam_command.c_str()); + + if(result == 0) + { + ROS_INFO("Successfully loaded parameters from calib.yaml to namespace: %s", node_name.c_str()); + } + else + { + ROS_ERROR("Failed to load parameters from calib.yaml"); + return 1; + } + + DepthImageRosNode projector(nh, pnh); + ros::spin(); + return 0; +} diff --git a/sru_ws/src/odin_ros_driver/src/pcd2depth_ros2.cpp b/sru_ws/src/odin_ros_driver/src/pcd2depth_ros2.cpp new file mode 100644 index 0000000..2cf3bbd --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/pcd2depth_ros2.cpp @@ -0,0 +1,242 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include "depth_image_ros2_node.hpp" +#include "odin_calib_path.h" +#include +bool fileExists(const std::string& filename) { + struct stat buffer; + return (stat(filename.c_str(), &buffer) == 0); +} + +bool loadCalibParameters(std::shared_ptr node, const std::string& calib_file_path) { + try { + RCLCPP_INFO(node->get_logger(), "========== [CALIB] READ <- %s ==========", calib_file_path.c_str()); + + YAML::Node config = YAML::LoadFile(calib_file_path); + + if (config["cam_num"]) { + int cam_num = config["cam_num"].as(); + node->declare_parameter("cam_num", cam_num); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_num = %d", cam_num); + } + + if (config["img_topic_0"]) { + std::string img_topic = config["img_topic_0"].as(); + node->declare_parameter("img_topic_0", img_topic); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: img_topic_0 = %s", img_topic.c_str()); + } + + if (config["Tcl_0"]) { + std::vector tcl_matrix = config["Tcl_0"].as>(); + node->declare_parameter("Tcl_0", tcl_matrix); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: Tcl_0 (transform matrix with %zu elements)", tcl_matrix.size()); + } + + if (config["cam_0"]) { + YAML::Node cam_0 = config["cam_0"]; + + if (cam_0["cam_model"]) { + std::string cam_model = cam_0["cam_model"].as(); + node->declare_parameter("cam_0.cam_model", cam_model); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.cam_model = %s", cam_model.c_str()); + } + + if (cam_0["image_width"]) { + int image_width = cam_0["image_width"].as(); + node->declare_parameter("cam_0.image_width", image_width); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.image_width = %d", image_width); + } + + if (cam_0["image_height"]) { + int image_height = cam_0["image_height"].as(); + node->declare_parameter("cam_0.image_height", image_height); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.image_height = %d", image_height); + } + + std::vector distortion_params = {"k2", "k3", "k4", "k5", "k6", "k7", "p1", "p2"}; + for (const auto& param : distortion_params) { + if (cam_0[param]) { + double value = cam_0[param].as(); + node->declare_parameter("cam_0." + param, value); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.%s = %f", param.c_str(), value); + } + } + + std::vector intrinsic_params = {"A11", "A12", "A22", "u0", "v0"}; + for (const auto& param : intrinsic_params) { + if (cam_0[param]) { + double value = cam_0[param].as(); + node->declare_parameter("cam_0." + param, value); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.%s = %f", param.c_str(), value); + } + } + + if (cam_0["isFast"]) { + int is_fast = cam_0["isFast"].as(); + node->declare_parameter("cam_0.isFast", is_fast); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.isFast = %d", is_fast); + } + + if (cam_0["numDiff"]) { + int num_diff = cam_0["numDiff"].as(); + node->declare_parameter("cam_0.numDiff", num_diff); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.numDiff = %d", num_diff); + } + + if (cam_0["maxIncidentAngle"]) { + int max_incident_angle = cam_0["maxIncidentAngle"].as(); + node->declare_parameter("cam_0.maxIncidentAngle", max_incident_angle); + RCLCPP_INFO(node->get_logger(), "Loaded parameter: cam_0.maxIncidentAngle = %d", max_incident_angle); + } + } + + RCLCPP_INFO(node->get_logger(), "Successfully loaded all parameters from calib.yaml"); + return true; + + } catch (const YAML::Exception& e) { + RCLCPP_ERROR(node->get_logger(), "YAML parsing error: %s", e.what()); + return false; + } catch (const std::exception& e) { + RCLCPP_ERROR(node->get_logger(), "Error loading calib parameters: %s", e.what()); + return false; + } +} +std::string get_package_source_directory() { + // 使用 rcpputils::fs::path 替代 std::filesystem::path + rcpputils::fs::path current_file(__FILE__); + + // 回溯到包根目录 + auto path = current_file.parent_path(); + + // 使用 rcpputils::fs::exists 替代 std::filesystem::exists + while (!path.empty() && !rcpputils::fs::exists(path / "package.xml")) { + path = path.parent_path(); + } + + if (path.empty()) { + throw std::runtime_error("Failed to locate package root directory"); + } + + return path.string(); +} +int main(int argc, char **argv) +{ + rclcpp::init(argc, argv); + + + auto node = std::make_shared("pcd2depth_node"); + RCLCPP_INFO(node->get_logger(), "Node created"); + std::string package_path = get_package_source_directory(); + RCLCPP_INFO(node->get_logger(), "Package path: %s", package_path.c_str()); + + std::string config_file = package_path + "/config/control_command.yaml"; + RCLCPP_INFO(node->get_logger(), "Loading config from: %s", config_file.c_str()); + + YAML::Node config = YAML::LoadFile(config_file); + + if (!config["register_keys"]) { + throw std::runtime_error("Missing 'register_keys' section"); + } + + if (!config["register_keys"]["senddepth"]) { + throw std::runtime_error("Missing 'senddepth' parameter"); + } + int senddepth = config["register_keys"]["senddepth"].as(); + std::cout << "senddepth: " << senddepth << std::endl; + if(senddepth == 0) + { + RCLCPP_INFO(node->get_logger(), "Depth image will not be published."); + return 0; + } + + std::string calib_file_path = node->declare_parameter("calib_file_path", ""); + if (calib_file_path.empty()) { + calib_file_path = odin_ros_driver::GetOdinCalibFile(); + } + + RCLCPP_INFO(node->get_logger(), "========== [CALIB] WAIT <- %s ==========", calib_file_path.c_str()); + while(rclcpp::ok() && !fileExists(calib_file_path)) + { + RCLCPP_INFO_THROTTLE(node->get_logger(), *node->get_clock(), 5000, "Still waiting for calib.yaml file..."); + rclcpp::sleep_for(std::chrono::milliseconds(500)); // 等待0.5秒后再检查 + rclcpp::spin_some(node); + } + + if(!rclcpp::ok()) + { + RCLCPP_INFO(node->get_logger(), "Node shutdown before calib.yaml file was found."); + return 0; + } + + RCLCPP_INFO(node->get_logger(), "Found calib.yaml file! Loading parameters..."); + + if (!loadCalibParameters(node, calib_file_path)) { + RCLCPP_ERROR(node->get_logger(), "Failed to load parameters from calib.yaml file"); + return 1; + } + + rclcpp::NodeOptions depth_node_options; + + std::vector params_override; + + try { + params_override.push_back(rclcpp::Parameter("cam_0.image_width", node->get_parameter("cam_0.image_width").as_int())); + params_override.push_back(rclcpp::Parameter("cam_0.image_height", node->get_parameter("cam_0.image_height").as_int())); + params_override.push_back(rclcpp::Parameter("cam_0.A11", node->get_parameter("cam_0.A11").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.A12", node->get_parameter("cam_0.A12").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.A22", node->get_parameter("cam_0.A22").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.u0", node->get_parameter("cam_0.u0").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.v0", node->get_parameter("cam_0.v0").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k2", node->get_parameter("cam_0.k2").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k3", node->get_parameter("cam_0.k3").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k4", node->get_parameter("cam_0.k4").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k5", node->get_parameter("cam_0.k5").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k6", node->get_parameter("cam_0.k6").as_double())); + params_override.push_back(rclcpp::Parameter("cam_0.k7", node->get_parameter("cam_0.k7").as_double())); + params_override.push_back(rclcpp::Parameter("Tcl_0", node->get_parameter("Tcl_0").as_double_array())); + + depth_node_options.parameter_overrides(params_override); + + RCLCPP_INFO(node->get_logger(), "Parameters successfully prepared for DepthImageRos2Node"); + } + catch (const std::exception& e) { + RCLCPP_ERROR(node->get_logger(), "Error preparing parameters for DepthImageRos2Node: %s", e.what()); + return 1; + } + try + { + auto depth_node = std::make_shared(depth_node_options); + + depth_node->initialize(); + + rclcpp::executors::MultiThreadedExecutor executor; + executor.add_node(depth_node); + executor.spin(); + } + catch (const std::exception& e) + { + RCLCPP_ERROR(node->get_logger(), "Error creating depth node: %s", e.what()); + return 1; + } + + rclcpp::shutdown(); + return 0; +} diff --git a/sru_ws/src/odin_ros_driver/src/pointcloud_depth_converter.cpp b/sru_ws/src/odin_ros_driver/src/pointcloud_depth_converter.cpp new file mode 100644 index 0000000..cc15533 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/pointcloud_depth_converter.cpp @@ -0,0 +1,376 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "pointcloud_depth_converter.hpp" +#include +#include + +PointCloudToDepthConverter::PointCloudToDepthConverter(const CameraParams ¶ms) + : params_(params) +{ + initializeInternalParams(); + createDistortionMaps(); +} + +void PointCloudToDepthConverter::initializeInternalParams() +{ + scaled_width_ = static_cast(params_.image_width / params_.scale); + scaled_height_ = static_cast(params_.image_height / params_.scale); + + K_ = Eigen::Matrix3d::Identity(); + K_(0, 0) = params_.A11; + K_(0, 1) = params_.A12; + K_(0, 2) = params_.u0; + K_(1, 1) = params_.A22; + K_(1, 2) = params_.v0; + + Kl_ = Eigen::Matrix3d::Identity(); + Kl_(0, 0) = params_.A11 / params_.scale; + Kl_(0, 1) = 0.0; + Kl_(0, 2) = params_.u0 / params_.scale; + Kl_(1, 1) = params_.A22 / params_.scale; + Kl_(1, 2) = params_.v0 / params_.scale; + + K_4x4_ = Eigen::Matrix4d::Identity(); + K_4x4_.block<3, 3>(0, 0) = Kl_; + + Kcl_ = K_4x4_ * params_.Tcl; +} + +void PointCloudToDepthConverter::createDistortionMaps() +{ + map_x_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1); + map_y_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1); + + + for (int u = 0; u < params_.image_width; ++u) + { + for (int v = 0; v < params_.image_height; ++v) + { + double y = (v - params_.v0) / params_.A22; + double x = (u - params_.u0 - params_.A12 * y) / params_.A11; + + double r = sqrt(x * x + y * y); + double theta = atan(r); + + double theta_d = theta + params_.k2 * pow(theta, 2) + params_.k3 * pow(theta, 3) + + params_.k4 * pow(theta, 4) + params_.k5 * pow(theta, 5) + + params_.k6 * pow(theta, 6) + params_.k7 * pow(theta, 7); + + double x_distorted = x * (r / theta_d); + double y_distorted = y * (r / theta_d); + + map_x_.at(v, u) = static_cast(x_distorted * params_.A11 + params_.A12 * y_distorted + params_.u0); + map_y_.at(v, u) = static_cast(y_distorted * params_.A22 + params_.v0); + } + } + + inv_map_x_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1); + inv_map_y_ = cv::Mat::zeros(params_.image_height, params_.image_width, CV_32FC1); + for (int u = 0; u < params_.image_width; ++u) + { + for (int v = 0; v < params_.image_height; ++v) + { + double y = (v - params_.v0) / params_.A22; + double x = (u - params_.u0 - params_.A12 * y) / params_.A11; + + double r = sqrt(x * x + y * y); + double theta = atan(r); + + double theta_d = theta + params_.k2 * pow(theta, 2) + params_.k3 * pow(theta, 3) + + params_.k4 * pow(theta, 4) + params_.k5 * pow(theta, 5) + + params_.k6 * pow(theta, 6) + params_.k7 * pow(theta, 7); + + double x_distorted = x * (theta_d / r); + double y_distorted = y * (theta_d / r); + + inv_map_x_.at(v, u) = static_cast(x_distorted * params_.A11 + params_.A12 * y_distorted + params_.u0); + inv_map_y_.at(v, u) = static_cast(y_distorted * params_.A22 + params_.v0); + } + } +} + +PointCloudToDepthConverter::ProcessResult PointCloudToDepthConverter::processCloudAndImage( + const pcl::PointCloud &cloud, + const cv::Mat &image) +{ + ProcessResult result; + result.success = false; + + auto validation_result = validateInputs(cloud, image); + if (!validation_result.first) + { + result.error_message = validation_result.second; + return result; + } + + try + { + pcl::PointCloud cloud_in_cam; + pcl::transformPointCloud(cloud, cloud_in_cam, Kcl_); + + cv::Mat depth_img = projectCloudToDepth(cloud_in_cam); + + cv::Mat processed_depth = postProcessDepthImage(depth_img); + + pcl::PointCloud colored_cloud = generateColoredCloud(processed_depth, image); + + result.depth_image = processed_depth; + result.colored_cloud = colored_cloud; + result.success = true; + } + catch (const std::exception &e) + { + result.error_message = std::string("Processing error: ") + e.what(); + } + + return result; +} + +cv::Mat PointCloudToDepthConverter::projectCloudToDepth(const pcl::PointCloud &cloud_in_cam) +{ + cv::Mat depth_img = cv::Mat::zeros(scaled_height_, scaled_width_, CV_32FC1); + + for (const auto &camera_point : cloud_in_cam) + { + if (camera_point.z <= 0) + continue; + + int u = static_cast(std::round(camera_point.x / camera_point.z)); + int v = static_cast(std::round(camera_point.y / camera_point.z)); + + if (u >= 0 && u < scaled_width_ && v >= 0 && v < scaled_height_) + { + depth_img.at(v, u) = static_cast(camera_point.z); + + for (int du = -1; du <= 1; ++du) + { + for (int dv = -1; dv <= 1; ++dv) + { + int nu = u + du; + int nv = v + dv; + if (nu >= 0 && nu < scaled_width_ && nv >= 0 && nv < scaled_height_) + { + if (depth_img.at(nv, nu) == 0.0f) + { + depth_img.at(nv, nu) = static_cast(camera_point.z); + } + } + } + } + } + } + + return depth_img; +} + +cv::Mat PointCloudToDepthConverter::postProcessDepthImage(const cv::Mat &depth_img) { + if (depth_img.empty()) { + std::cerr << "ERROR: Input depth image is empty!" << std::endl; + return cv::Mat(); + } + + if (depth_img.data == nullptr) { + std::cerr << "ERROR: Input depth image has null data pointer!" << std::endl; + return cv::Mat(); + } + + if (depth_img.rows <= 0 || depth_img.cols <= 0) { + std::cerr << "ERROR: Invalid input dimensions: " + << depth_img.rows << "x" << depth_img.cols << std::endl; + return cv::Mat(); + } + + if (params_.image_width <= 0 || params_.image_height <= 0) { + std::cerr << "ERROR: Invalid target size: " + << params_.image_width << "x" << params_.image_height << std::endl; + return cv::Mat(); + } + + cv::Mat safe_input = depth_img.clone(); + if (safe_input.empty()) { + std::cerr << "ERROR: Failed to create safe copy of input image!" << std::endl; + return cv::Mat(); + } + + + cv::Mat depth_img_upsampled; + try { + depth_img_upsampled = customResize(safe_input, cv::Size(1600, 1296)); + } catch (const std::exception& e) { + std::cerr << "ERROR: Custom resize failed: " << e.what() << std::endl; + return cv::Mat(); + } + + if (depth_img_upsampled.empty()) { + std::cerr << "ERROR: Resized image is empty!" << std::endl; + return cv::Mat(); + } + + if (depth_img_upsampled.rows != 1296 || depth_img_upsampled.cols != 1600) { + std::cerr << "ERROR: Resized image has wrong dimensions: " + << depth_img_upsampled.cols << "x" << depth_img_upsampled.rows + << " (expected " << 1600 << "x" << 1296 << ")" << std::endl; + return cv::Mat(); + } + + + cv::Mat grad_x, grad_y, grad_magnitude; + try { + cv::Sobel(depth_img_upsampled, grad_x, CV_32F, 1, 0, 3); + cv::Sobel(depth_img_upsampled, grad_y, CV_32F, 0, 1, 3); + cv::magnitude(grad_x, grad_y, grad_magnitude); + } catch (const cv::Exception& e) { + std::cerr << "ERROR: Sobel/magnitude failed: " << e.what() << std::endl; + return cv::Mat(); + } + + if (grad_magnitude.type() != CV_32F) { + std::cerr << "ERROR: grad_magnitude has wrong type: " + << grad_magnitude.type() << " (expected CV_32F)" << std::endl; + return cv::Mat(); + } + + + cv::Mat threshold_mask; + try { + cv::threshold(grad_magnitude, threshold_mask, 0.75, 1, cv::THRESH_BINARY); + threshold_mask.convertTo(threshold_mask, CV_8U); + + + depth_img_upsampled.setTo(0, threshold_mask); + } catch (const cv::Exception& e) { + std::cerr << "ERROR: Threshold mask failed: " << e.what() << std::endl; + return cv::Mat(); + } + + return depth_img_upsampled; +} + +cv::Mat PointCloudToDepthConverter::customResize(const cv::Mat& src, const cv::Size& size) { + if (src.empty()) { + throw std::runtime_error("Source image is empty"); + } + + if (size.width <= 0 || size.height <= 0) { + throw std::runtime_error("Invalid target size"); + } + + + cv::Mat dst(size.height, size.width, src.type()); + + float scale_x = src.cols / static_cast(size.width); + float scale_y = src.rows / static_cast(size.height); + + if (src.channels() != 1 || src.type() != CV_32F) { + throw std::runtime_error("Unsupported image type - expected single channel float"); + } + + + for (int y = 0; y < dst.rows; y++) { + + int src_y = static_cast(y * scale_y); + src_y = std::min(src_y, src.rows - 1); + + for (int x = 0; x < dst.cols; x++) { + int src_x = static_cast(x * scale_x); + src_x = std::min(src_x, src.cols - 1); + dst.at(y, x) = src.at(src_y, src_x); + } + } + + return dst; +} +pcl::PointCloud PointCloudToDepthConverter::generateColoredCloud( + const cv::Mat &depth_img, const cv::Mat &color_img) +{ + cv::Mat depth_undistorted, color_undistorted; + depth_undistorted = depth_img.clone(); + cv::remap(color_img, color_undistorted, inv_map_x_, inv_map_y_, cv::INTER_LINEAR); + + pcl::PointCloud cloud_colored; + + Eigen::Matrix4d Tlc = params_.Tcl.inverse(); + + for (int v = 0; v < depth_undistorted.rows; v += params_.point_sampling_rate) + { + for (int u = 0; u < depth_undistorted.cols; u += params_.point_sampling_rate) + { + float depth = depth_undistorted.at(v, u); + if (depth > 0.1f && depth < 100.0f) + { + double y_cam = (v - params_.v0) * depth / params_.A22; + double x_cam = ((u - params_.u0) * depth - params_.A12 * y_cam)/ params_.A11; + + double z_cam = depth; + + Eigen::Vector4d point_cam(x_cam, y_cam, z_cam, 1.0); + + Eigen::Vector4d point_lidar = Tlc * point_cam; + + pcl::PointXYZRGB point; + point.x = static_cast(point_lidar[0]); + point.y = static_cast(point_lidar[1]); + point.z = static_cast(point_lidar[2]); + + if (u < color_undistorted.cols && v < color_undistorted.rows) + { + cv::Vec3b color = color_undistorted.at(v, u); + point.b = color[0]; + point.g = color[1]; + point.r = color[2]; + } + else + { + point.r = point.g = point.b = 255; + } + + cloud_colored.points.push_back(point); + } + } + } + + cloud_colored.width = cloud_colored.points.size(); + cloud_colored.height = 1; + cloud_colored.is_dense = false; + + return cloud_colored; +} + +std::pair PointCloudToDepthConverter::validateInputs( + const pcl::PointCloud &cloud, const cv::Mat &image) +{ + if (cloud.empty()) + { + return {false, "Empty point cloud"}; + } + + if (image.empty()) + { + return {false, "Empty image"}; + } + + if (params_.A11 < 1e-6 || params_.A22 < 1e-6) + { + return {false, "Invalid camera intrinsics"}; + } + + return {true, ""}; +} + +void PointCloudToDepthConverter::updateCameraParams(const CameraParams ¶ms) +{ + params_ = params; + initializeInternalParams(); + createDistortionMaps(); +} diff --git a/sru_ws/src/odin_ros_driver/src/rawCloudRender.cpp b/sru_ws/src/odin_ros_driver/src/rawCloudRender.cpp new file mode 100644 index 0000000..13c47a6 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/rawCloudRender.cpp @@ -0,0 +1,299 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "rawCloudRender.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct ValidPointInfo { + float x; + float y; + float z; + int u; + int v; +}; + + +namespace GlobalCameraParams { + float g_fx = 0.0f; + float g_fy = 0.0f; + float g_cx = 0.0f; + float g_cy = 0.0f; + float g_skew = 0.0f; + float g_k2 = 0.0f; + float g_k3 = 0.0f; + float g_k4 = 0.0f; + float g_k5 = 0.0f; + float g_k6 = 0.0f; + float g_k7 = 0.0f; + Eigen::Matrix4f g_T_camera_lidar = Eigen::Matrix4f::Identity(); +} +bool raw_debug=0; +bool rawCloudRender::init(const std::string& yamlFilePath) { + YAML::Node config; + try { + config = YAML::LoadFile(yamlFilePath); + } catch (const YAML::BadFile& e) { + std::cerr << "Error: Could not open file '" << yamlFilePath << "' - " << e.what() << std::endl; + return false; + } catch (const YAML::ParserException& e) { + std::cerr << "Error: YAML parsing failed - " << e.what() << std::endl; + return false; + } catch (const std::exception& e) { + std::cerr << "Unexpected error: " << e.what() << std::endl; + return false; + } + + // Intrinsic parameters node (cam_0) + const std::string cam_node_name = "cam_0"; + if (!config[cam_node_name]) { + std::cerr << "Error: Missing camera node '" << cam_node_name << "'" << std::endl; + return false; + } + YAML::Node cam_node = config[cam_node_name]; + + // Directly access Tcl_0 node + const std::string tcl_node_name = "Tcl_0"; + if (!config[tcl_node_name]) { + std::cerr << "Error: Missing transformation matrix node '" << tcl_node_name << "'" << std::endl; + return false; + } + YAML::Node tclNode = config[tcl_node_name]; + if (tclNode.size() != 16) { + std::cerr << "Error: Transformation matrix must be 4x4 (16 elements)" << std::endl; + return false; + } + + // === Read intrinsic parameters === + GlobalCameraParams::g_k2 = cam_node["k2"].as(); + GlobalCameraParams::g_k3 = cam_node["k3"].as(); + GlobalCameraParams::g_k4 = cam_node["k4"].as(); + GlobalCameraParams::g_k5 = cam_node["k5"].as(); + GlobalCameraParams::g_k6 = cam_node["k6"].as(); + GlobalCameraParams::g_k7 = cam_node["k7"].as(); + + GlobalCameraParams::g_fx = cam_node["A11"].as(); + GlobalCameraParams::g_skew = cam_node["A12"].as(); + GlobalCameraParams::g_fy = cam_node["A22"].as(); + + GlobalCameraParams::g_cx = cam_node["u0"].as(); + GlobalCameraParams::g_cy = cam_node["v0"].as(); + + // === Read extrinsic transformation matrix === + GlobalCameraParams::g_T_camera_lidar << + tclNode[0].as(), tclNode[1].as(), tclNode[2].as(), tclNode[3].as(), + tclNode[4].as(), tclNode[5].as(), tclNode[6].as(), tclNode[7].as(), + tclNode[8].as(), tclNode[9].as(), tclNode[10].as(), tclNode[11].as(), + tclNode[12].as(), tclNode[13].as(), tclNode[14].as(), tclNode[15].as(); + + // === Display key parameters concisely === + std::cout << "=== Camera Calibration Parameters ===" << std::endl; + std::cout << "Intrinsics:" << std::endl; + std::cout << " fx: " << GlobalCameraParams::g_fx + << ", fy: " << GlobalCameraParams::g_fy + << ", cx: " << GlobalCameraParams::g_cx + << ", cy: " << GlobalCameraParams::g_cy << std::endl; + std::cout << "Distortion: k2=" << GlobalCameraParams::g_k2 + << ", k3=" << GlobalCameraParams::g_k3 << std::endl; + + Eigen::Vector3f translation = GlobalCameraParams::g_T_camera_lidar.block<3,1>(0,3); + Eigen::Matrix3f rotation = GlobalCameraParams::g_T_camera_lidar.block<3,3>(0,0); + std::cout << "Extrinsics:" << std::endl; + std::cout << " Translation: [" << translation.x() << ", " + << translation.y() << ", " << translation.z() << "]" << std::endl; + std::cout << " Rotation (euler angles): " + << rotation.eulerAngles(0,1,2).transpose() * 180/M_PI << "°" << std::endl; + + return true; +} +void rawCloudRender::render(std::vector>& rgb_image, + capture_Image_List_t* pcd_stream, + int pcdIdx, + std::vector& rgbCloud_flat) +{ + // Initialize constants + constexpr float inv_1000 = 0.001f; + const float fx = GlobalCameraParams::g_fx; + const float fy = GlobalCameraParams::g_fy; + const float cx = GlobalCameraParams::g_cx; + const float cy = GlobalCameraParams::g_cy; + const float skew = GlobalCameraParams::g_skew; + const float k2 = GlobalCameraParams::g_k2; + const float k3 = GlobalCameraParams::g_k3; + const float k4 = GlobalCameraParams::g_k4; + const float k5 = GlobalCameraParams::g_k5; + const float k6 = GlobalCameraParams::g_k6; + const float k7 = GlobalCameraParams::g_k7; + const Eigen::Matrix4f& T = GlobalCameraParams::g_T_camera_lidar; + + // Precompute matrix elements + const float T00 = T(0,0), T01 = T(0,1), T02 = T(0,2), T03 = T(0,3); + const float T10 = T(1,0), T11 = T(1,1), T12 = T(1,2), T13 = T(1,3); + const float T20 = T(2,0), T21 = T(2,1), T22 = T(2,2), T23 = T(2,3); + + // Initialize lookup table + static std::array dist_table; + static bool table_init = [&](){ + for (size_t i=0; i= 10) { + std::cerr << "ERROR: Invalid pcd_stream or index in render function" << std::endl; + return; + } + + buffer_List_t& pcd_buffer = pcd_stream->imageList[pcdIdx]; + const int total_points = pcd_buffer.height * pcd_buffer.width; + + if (!pcd_buffer.pAddr) { + std::cerr << "ERROR: Null point cloud data pointer in render function" << std::endl; + return; + } + + float* data = static_cast(pcd_buffer.pAddr); + + // Prepare output + rgbCloud_flat.clear(); + rgbCloud_flat.resize(total_points * 4); // Preallocate maximum space + float* output_ptr = rgbCloud_flat.data(); + + // Get image dimensions + const int img_height = 1296; + const int img_width = 1600; + + // Process point cloud + int valid_count = 0; + for (int idx = 0; idx < total_points; ++idx) + { + float* pf = data + idx*4; + + // Quick check for invalid points + if (std::abs(pf[0]) < 1e-5f && std::abs(pf[1]) < 1e-5f && std::abs(pf[2]) < 1e-5f) { + continue; + } + + // Coordinate transformation + const float x = pf[2] * inv_1000; + const float y = -pf[0] * inv_1000; + const float z = pf[1] * inv_1000; + + // Manual matrix transformation + const float x1 = T00*x + T01*y + T02*z + T03; + const float y1 = T10*x + T11*y + T12*z + T13; + const float z1 = T20*x + T21*y + T22*z + T23; + + // Check for points behind camera + if (z1 <= 0.0f) continue; + + // Calculate projection + const float x1_sq = x1*x1; + const float y1_sq = y1*y1; + const float z1_sq = z1*z1; + + const float norm = std::sqrt(x1_sq + y1_sq + z1_sq); + if (norm < 1e-7f) continue; + + const float r = std::sqrt(x1_sq + y1_sq); + if (r < 1e-7f) continue; + + const float cost = z1 / norm; + const float theta = std::acos(cost); + + // Safe table lookup + const size_t table_idx = static_cast(theta * (2.0f/M_PI) * dist_table.size()); + const size_t safe_idx = std::min(table_idx, dist_table.size()-1); + const float thetad = dist_table[safe_idx]; + + const float scaling = thetad / r; + const float xd = x1 * scaling; + const float yd = y1 * scaling; + const float pd_2d_x = xd * fx + yd * skew + cx; + const float pd_2d_y = yd * fy + cy; + + // Quick boundary check + const int u = static_cast(pd_2d_x); + const int v = static_cast(pd_2d_y); + + // Strict boundary check + if (u < 0 || u >= img_width || v < 0 || v >= img_height) { + continue; + } + + // Safe image data access + if (v < static_cast(rgb_image.size()) && u < static_cast(rgb_image[v].size())) { + *output_ptr++ = x; + *output_ptr++ = y; + *output_ptr++ = z; + *output_ptr++ = rgb_image[v][u]; + valid_count++; + } else { + // Handle invalid coordinates + static bool warned = false; + if (!warned) { + if(raw_debug) + { + std::cerr << "WARNING: Invalid image coordinates: u=" << u << ", v=" << v + << " (image size: " << rgb_image.size() << "x" + << (rgb_image.empty() ? 0 : rgb_image[0].size()) << ")" << std::endl; + } + + warned = true; + } + } + } + // Resize output + rgbCloud_flat.resize(output_ptr - rgbCloud_flat.data()); + if(raw_debug) + { + std::cout << "Render completed: " << total_points << " points processed, " + << valid_count << " valid points (" + << (100.0 * valid_count / total_points) << "%)" << std::endl; + } +} +void rawCloudRender::print_camera_calib() { + std::cout << model_type_ << std::endl; + std::cout << image_width_ << std::endl; + std::cout << image_height_ << std::endl; + + std::cout << "T_camera_lidar" << std::endl; + std::cout << T_camera_lidar_(0,0) << " " << T_camera_lidar_(0,1) << " " << T_camera_lidar_(0,2) << " " << T_camera_lidar_(0,3) << std::endl; + std::cout << T_camera_lidar_(1,0) << " " << T_camera_lidar_(1,1) << " " << T_camera_lidar_(1,2) << " " << T_camera_lidar_(1,3) << std::endl; + std::cout << T_camera_lidar_(2,0) << " " << T_camera_lidar_(2,1) << " " << T_camera_lidar_(2,2) << " " << T_camera_lidar_(2,3) << std::endl; + std::cout << T_camera_lidar_(3,0) << " " << T_camera_lidar_(3,1) << " " << T_camera_lidar_(3,2) << " " << T_camera_lidar_(3,3) << std::endl; + + std::cout << "cam" << std::endl; + std::cout << k2_ << std::endl; + std::cout << k3_ << std::endl; + std::cout << k4_ << std::endl; + std::cout << k5_ << std::endl; + std::cout << k6_ << std::endl; + std::cout << k7_ << std::endl; + + std::cout << A11_fx_ << std::endl; + std::cout << A12_skew_ << std::endl; + std::cout << A22_fy_ << std::endl; + std::cout << u0_cx_ << std::endl; + std::cout << v0_cy_ << std::endl; +} \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/src/yaml_parser.cpp b/sru_ws/src/odin_ros_driver/src/yaml_parser.cpp new file mode 100644 index 0000000..48fa1db --- /dev/null +++ b/sru_ws/src/odin_ros_driver/src/yaml_parser.cpp @@ -0,0 +1,249 @@ +/* +Copyright 2025 Manifold Tech Ltd.(www.manifoldtech.com.co) +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "yaml_parser.h" +#include +#include +#include +#include +#include + +#include +namespace odin_ros_driver { + +YamlParser::YamlParser(const std::string& config_file) + : config_file_(config_file) {} + +bool YamlParser::loadConfig() { + try { + std::cerr << "Loading config file: " << config_file_ << std::endl; + + // Check if file exists + if (!std::filesystem::exists(config_file_)) { + std::cerr << "Config file not found: " << config_file_ << std::endl; + return false; + } + + // Print file contents + std::ifstream file(config_file_); + std::string content((std::istreambuf_iterator(file)), + std::istreambuf_iterator()); + std::cerr << "Config file content:\n" << content << "\n--- End of file ---" << std::endl; + + // Load YAML + YAML::Node config = YAML::LoadFile(config_file_); + + // Check if 'register_keys' node exists + if (!config["register_keys"]) { + std::cerr << "Missing 'register_keys' section in config file" << std::endl; + return false; + } + + YAML::Node register_keys = config["register_keys"]; + register_keys_.clear(); + register_keys_str_val_.clear(); + custom_parameters_.clear(); + + // Print number of key-value pairs found + std::cerr << "Found " << register_keys.size() << " keys in config" << std::endl; + + for (YAML::const_iterator it = register_keys.begin(); it != register_keys.end(); ++it) { + std::string key = it->first.as(); + const YAML::Node& value_node = it->second; + + // Convert key to lowercase + std::transform(key.begin(), key.end(), key.begin(), + [](unsigned char c){ return std::tolower(c); }); + + // Check if this is a custom parameter + if (key.substr(0, 7) == "custom_") { + std::string param_name = key.substr(7); + + // Handle different value types + if (value_node.IsScalar()) { + // Single scalar value (int or float) + try { + int int_value = value_node.as(); + ParameterValue param_value; + param_value.type = DataType::INT_TYPE; + param_value.setData(int_value); + custom_parameters_[param_name] = param_value; + std::cerr << "Loaded custom parameter (int): " << param_name << " = " << int_value << std::endl; + } catch (...) { + try { + double float_value = value_node.as(); + ParameterValue param_value; + param_value.type = DataType::FLOAT_ARRAY_TYPE; + std::vector float_array = {static_cast(float_value)}; + param_value.setArray(float_array); + custom_parameters_[param_name] = param_value; + std::cerr << "Loaded custom parameter (float): " << param_name << " = " << float_value << std::endl; + } catch (const std::exception& e) { + std::cerr << "Failed to parse custom parameter " << param_name << ": " << e.what() << std::endl; + } + } + } else if (value_node.IsSequence()) { + // Array of values + size_t array_size = value_node.size(); + if (array_size == 0) { + std::cerr << "Empty array for custom parameter: " << param_name << std::endl; + continue; + } + + // Try to detect if it's a float or int array based on first element + try { + // Try to parse as float array first + std::vector float_array; + for (size_t i = 0; i < array_size; ++i) { + float_array.push_back(value_node[i].as()); + } + ParameterValue param_value; + param_value.type = DataType::FLOAT_ARRAY_TYPE; + param_value.setArray(float_array); + custom_parameters_[param_name] = param_value; + + std::cerr << "Loaded custom parameter (float array): " << param_name << " = ["; + for (size_t i = 0; i < float_array.size(); ++i) { + if (i > 0) std::cerr << ", "; + std::cerr << std::fixed << std::setprecision(4) << float_array[i]; + } + std::cerr << "]" << std::endl; + } catch (const std::exception& e) { + std::cerr << "Failed to parse custom parameter array " << param_name << ": " << e.what() << std::endl; + } + } + } else if (allowed_key_w_str_val.find(key) != allowed_key_w_str_val.end()) { + try { + std::string value = value_node.as(); + register_keys_str_val_[key] = value; + std::cerr << "Loaded key: " << key << " = " << value << std::endl; + } catch (const std::exception& e) { + std::cerr << "Failed to parse key " << key << ": " << e.what() << std::endl; + } + } else if (allowed_key_w_float_val.find(key) != allowed_key_w_float_val.end()) { + try { + double value = value_node.as(); + register_keys_float_val_[key] = value; + std::cerr << "Loaded key: " << key << " = " << value << std::endl; + } catch (const std::exception& e) { + std::cerr << "Failed to parse key " << key << ": " << e.what() << std::endl; + } + } else if (allowed_key_w_int_val.find(key) != allowed_key_w_int_val.end()) { + // Regular (non-custom) integer parameter + try { + int value = value_node.as(); + register_keys_[key] = value; + std::cerr << "Loaded key: " << key << " = " << value << std::endl; + } catch (const std::exception& e) { + std::cerr << "Failed to parse key " << key << ": " << e.what() << std::endl; + } + } else { + std::cerr << "[ERROR] Unknown/unsupported key in register_keys: '" << key + << "'. Please check spelling or remove it." << std::endl; + } + } + + return true; + } catch (const YAML::Exception& e) { + std::cerr << "YAML exception: " << e.what() << std::endl; + return false; + } catch (const std::exception& e) { + std::cerr << "Exception: " << e.what() << std::endl; + return false; + } +} + +const std::map& YamlParser::getRegisterKeys() const { + return register_keys_; +} + +const std::map& YamlParser::getCustomParameters() const { + return custom_parameters_; +} + +const std::map& YamlParser::getRegisterKeysStrVal() const { + return register_keys_str_val_; +} + +void YamlParser::printConfig() const { + std::cerr << "Configuration Keys:" << std::endl; + if (register_keys_.empty()) { + std::cerr << " (int val empty)" << std::endl; + } else { + for (const auto& [key, value] : register_keys_) { + std::cerr << " " << key << ": " << value << std::endl; + } + } + + if (register_keys_str_val_.empty()) { + std::cerr << " (str_val empty)" << std::endl; + } else { + for (const auto& [key, value] : register_keys_str_val_) { + std::cerr << " " << key << ": " << value << std::endl; + } + } + + std::cerr << "Custom Parameters:" << std::endl; + if (custom_parameters_.empty()) { + std::cerr << " (custom param empty)" << std::endl; + } else { + for (const auto& [key, param_val] : custom_parameters_) { + std::cerr << " " << key << ": (size=" << param_val.getSize() << " bytes)"; + if (param_val.type == DataType::INT_TYPE && param_val.getSize() == sizeof(int)) { + int int_val = *reinterpret_cast(param_val.getData()); + std::cerr << " = " << int_val; + } else if (param_val.type == DataType::FLOAT_ARRAY_TYPE && param_val.getSize() % sizeof(float) == 0) { + size_t count = param_val.getSize() / sizeof(float); + const float* float_arr = reinterpret_cast(param_val.getData()); + std::cerr << " = ["; + for (size_t i = 0; i < count; ++i) { + if (i > 0) std::cerr << ", "; + std::cerr << std::fixed << std::setprecision(4) << float_arr[i]; + } + std::cerr << "]"; + } + std::cerr << std::endl; + } + } +} + +bool YamlParser::applyCustomParameters(device_handle device) { + bool success = true; + + for (const auto& [param_name, param_value] : custom_parameters_) { + std::cerr << "Setting custom parameter: " << param_name << " (size=" << param_value.getSize() << " bytes)" << std::endl; + + int result = lidar_set_custom_parameter(device, param_name.c_str(), param_value.getData(), param_value.getSize()); + if (result != 0) { + std::cerr << "Failed to set custom parameter " << param_name << ": error code " << result << std::endl; + success = false; + } else { + std::cerr << "Successfully set custom parameter " << param_name << std::endl; + } + } + + return success; +} + +int YamlParser::getCustomParameterInt(const std::string& param_name, int default_value) const { + auto it = custom_parameters_.find(param_name); + if (it != custom_parameters_.end()) { + const ParameterValue& param_value = it->second; + if (param_value.type == DataType::INT_TYPE && param_value.getSize() == sizeof(int)) { + return *reinterpret_cast(param_value.getData()); + } + } + return default_value; +} + +} \ No newline at end of file diff --git a/sru_ws/src/odin_ros_driver/srv/GetAe.srv b/sru_ws/src/odin_ros_driver/srv/GetAe.srv new file mode 100644 index 0000000..46a6b8f --- /dev/null +++ b/sru_ws/src/odin_ros_driver/srv/GetAe.srv @@ -0,0 +1,13 @@ +# Query current AE (auto exposure) state. +# Request: empty. +# Response: success + raw return code + decoded fields. +--- +bool success # true if rc == 0 +int32 rc # 0=ok, >0=device error (400..405 or 0xFF), <0=SDK error +float32 exposure_time # seconds (manual range 0.0001 .. 0.033) +float32 gain # analog gain +int32 iso # equivalent ISO +float32 brightness # average frame brightness +uint8 is_converged # 1=converged, 0=not converged +float32 env_lv # ambient luminance level +float32 fps # current frame rate diff --git a/sru_ws/src/odin_ros_driver/srv/GetAwb.srv b/sru_ws/src/odin_ros_driver/srv/GetAwb.srv new file mode 100644 index 0000000..aa36770 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/srv/GetAwb.srv @@ -0,0 +1,13 @@ +# Query current AWB (auto white balance) state. +# Request: empty. +# Response: success + raw return code + decoded fields. +--- +bool success # true if rc == 0 +int32 rc # 0=ok, >0=device error (400..405 or 0xFF), <0=SDK error +float32 rgain +float32 grgain +float32 gbgain +float32 bgain +float32 cct # color temperature in Kelvin +float32 ccri # color temperature deviation +uint8 is_converged # 1=converged, 0=not converged diff --git a/sru_ws/src/odin_ros_driver/srv/GetDeviceLogs.srv b/sru_ws/src/odin_ros_driver/srv/GetDeviceLogs.srv new file mode 100644 index 0000000..c2ab4d6 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/srv/GetDeviceLogs.srv @@ -0,0 +1,9 @@ +# Retrieve device logs from the Odin sensor. +# +# Request: destination directory to save the log archive. +# Response: success flag and raw return code. + +string dest_dir +--- +bool success # true if rc == 0 +int32 rc # 0=ok, -1=invalid args, -2=transfer in progress, -3=timeout/stall diff --git a/sru_ws/src/odin_ros_driver/srv/ResetAlgo.srv b/sru_ws/src/odin_ros_driver/srv/ResetAlgo.srv new file mode 100644 index 0000000..a91a912 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/srv/ResetAlgo.srv @@ -0,0 +1,8 @@ +# Send algorithm reset command to the Odin device. +# +# value == 1 : send algo_reset command. +# other : forwarded as "algo_reset" custom parameter. +int32 value +--- +bool success # true if rc == 0 +int32 rc # 0=ok, see lidar_set_custom_parameter error codes diff --git a/sru_ws/src/odin_ros_driver/srv/SaveMap.srv b/sru_ws/src/odin_ros_driver/srv/SaveMap.srv new file mode 100644 index 0000000..66ac6cb --- /dev/null +++ b/sru_ws/src/odin_ros_driver/srv/SaveMap.srv @@ -0,0 +1,12 @@ +# Trigger map save on the Odin device. +# +# value == 1 : start the save-map flow (uses the configured +# mapping_result_dest_dir and mapping_result_file_name; +# runs in a background thread because the transfer may +# take a long time). +# value == 0 : just set the "save_map" custom parameter to 0. +# other : forwarded as "save_map" custom parameter. +int32 value +--- +bool success # true if the request was accepted (or rc == 0) +int32 rc # 0=ok, -2=another map transfer already in progress diff --git a/sru_ws/src/odin_ros_driver/srv/SetAe.srv b/sru_ws/src/odin_ros_driver/srv/SetAe.srv new file mode 100644 index 0000000..d21aa1e --- /dev/null +++ b/sru_ws/src/odin_ros_driver/srv/SetAe.srv @@ -0,0 +1,14 @@ +# Set AE (auto exposure) mode and (in manual mode) exposure / gain. +# +# mode == 0 (AUTO) : sends opcode 0x02 only; exposure_time and gain ignored. +# mode == 1 (MANUAL) : sends opcode 0x03 then 0x06 (exposure_time, gain). +# +# Valid manual ranges (device-enforced; out-of-range returns rc=403): +# exposure_time : 0.0001 s .. 0.033 s +# gain : 1.0 .. 64.0 +uint8 mode +float32 exposure_time +float32 gain +--- +bool success +int32 rc # 0=ok, >0=device error (400..405 or 0xFF), <0=SDK error diff --git a/sru_ws/src/odin_ros_driver/srv/SetAwb.srv b/sru_ws/src/odin_ros_driver/srv/SetAwb.srv new file mode 100644 index 0000000..be46a11 --- /dev/null +++ b/sru_ws/src/odin_ros_driver/srv/SetAwb.srv @@ -0,0 +1,15 @@ +# Set AWB (auto white balance) mode and (in manual mode) R/B gains. +# +# mode == 0 (AUTO) : sends opcode 0x31 only; rgain and bgain ignored. +# mode == 1 (MANUAL) : sends opcode 0x32 then 0x33 (rgain, bgain). +# Gr/Gb are fixed to 1.0 by the device. +# +# Valid manual ranges: +# rgain : 0.1 .. 4.0 +# bgain : 0.1 .. 4.0 +uint8 mode +float32 rgain +float32 bgain +--- +bool success +int32 rc # 0=ok, >0=device error (400..405 or 0xFF), <0=SDK error diff --git a/sru_ws/src/sru_nav_ros2/config/sru_nav.yaml b/sru_ws/src/sru_nav_ros2/config/sru_nav.yaml new file mode 100644 index 0000000..f25bace --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/config/sru_nav.yaml @@ -0,0 +1,260 @@ +# ============================================================================= +# sru_nav_node — runtime parameters (SRU-Odin, ROS 2 Humble) +# +# Loaded by launch/sru_nav.launch.py via +# parameters=[os.path.join(share, 'config', 'sru_nav.yaml')] +# +# This is a *node parameter file*, so the top-level key is the node name +# `sru_nav_node`. That name is deliberately identical to the ROS 1 package's +# node name, so that the ROS 1 private-topic names `~base_vel` / `~vis/*` expand +# to exactly the same fully-qualified topics under ROS 2 (`/sru_nav_node/...`) +# and existing rviz configs keep working. +# +# Items marked VERIFY were never validated on real hardware. Every one of them +# is exposed here on purpose: measure it, then change this file only — no code +# edits are required. +# ============================================================================= + +sru_nav_node: + ros__parameters: + + # ------------------------------------------------------------- topics ---- + # RESOLVED (was open item 1): this name is CONFIRMED correct. It is the + # default value of the `depth_image_topic` parameter in + # odin_ros_driver/src/depth_image_ros2_node.cpp, and the Rc2026 reference + # project references it in 38 places. It simply is not in the driver's + # mainline docs because it belongs to the pcd2depth depth node. + # Still worth a sanity check on the robot: + # ros2 topic hz /odin1/depth_img_competetion # expect ~10 Hz + # ros2 topic echo /odin1/depth_img_competetion --once --field encoding # 32FC1 + depth_topic: "/odin1/depth_img_competetion" # sensor_msgs/msg/Image, 32FC1, meters + odom_topic: "/odin1/odometry_highfreq" # nav_msgs/msg/Odometry @ ~300-400 Hz + # alt: /odin1/odometry (~10 Hz SLAM rate, + # less drift but laggier) + joy_topic: "/joy" # sensor_msgs/msg/Joy + goal_topic: "/goal_pose" # geometry_msgs/msg/PoseStamped + # frame_id MUST equal odom's + # header.frame_id, or the goal is rejected + cmd_vel_topic: "/cmd_vel" # geometry_msgs/msg/Twist, body frame + + # ============= DRIVER PREREQUISITES (verified on this machine) ========== + # This node publishes /cmd_vel ONLY from generate_cmd_vel(), which is called + # ONLY from depth_callback() -- exactly like the ROS 1 blueprint (one call + # site in each). So with no depth arriving you get NO /cmd_vel at all, and + # not even the once-per-second `cmd_vel_ratio:` / `Published cmd_vel:` log + # lines. That is the signature to look for when diagnosing. + # + # 1) Endpoints are not data. `/odin1/depth_img_competetion` appears in + # `ros2 topic list` (and shows Subscription count 1) as soon as THIS node + # subscribes to it, and the driver creates its publishers at startup even + # when it streams nothing. `ros2 topic info` counts endpoints, so it can + # read "Publisher count: 1" with zero data flowing. Use: + # ros2 topic hz /odin1/depth_img_competetion # the only real check + # BUT beware for the RGB topic: `/odin1/image` is 1600x1296 bgr8 (~6.2 MB + # per frame, NOT scaled -- calib.yaml: image_width/height = 1600x1296). + # A Python `ros2 topic hz` subscriber cannot keep up with that, and since + # the publisher is RELIABLE with a small queue it gets dragged down too -- + # so `hz` can read ~0.3 Hz on a stream that is actually fine (the driver's + # own dev_status.csv showed 10.2 Hz for it). Cross-check with that CSV + # before believing a low number on /odin1/image. + # + # NOTE the depth image is NOT full resolution: the depth node divides the + # camera size by the `scale` parameter (default 7.0, and control_command.yaml + # sets no override): + # pointcloud_depth_converter.cpp:27-28 scaled_w/h = image_w/h / scale + # => 1600/7 x 1296/7 = 228x185 32FC1, i.e. only ~165 KiB per frame. + # So the depth stream is small: a low `/cmd_vel` rate is then NOT this + # node being swamped, and `ros2 topic hz` on the depth topic is trustworthy. + # + # 2) The driver reads its config from the SOURCE TREE, not from install/. + # All three driver binaries resolve it with get_package_source_directory(), + # which walks up from the compile-time `__FILE__` until it finds + # package.xml (host_sdk_sample.cpp:869 & :2491, pcd2depth_ros2.cpp:122, + # cloud_reprojection_ros.cpp:48). For this machine the compiled-in path is + # /home/kevin/catkin_ws/src/odin_ros_driver/src/*.cpp + # (confirmed in build/odin_ros_driver/CMakeFiles/*/src/*.cpp.o.d), so the + # file that is actually read is + # ~/catkin_ws/src/odin_ros_driver/config/control_command.yaml + # Editing the copy under install/odin_ros_driver/share/... has NO effect. + # + # 3) THREE keys must be flipped there -- all ship as 0 on this machine: + # senddtof: 1 # "send raw cloud data" (host_sdk_sample.h:2152) -- + # # this is /odin1/cloud_raw. It is gated TWICE: + # # the device stream is deactivated + # # (host_sdk_sample.cpp:1950 lidar_deactivate_stream_type + # # LIDAR_DT_RAW_DTOF) and the publish itself is skipped + # # (host_sdk_sample.cpp:1057 if (g_senddtof)). + # # Without it the depth node's ApproximateTime sync -- + # # which needs the PAIR {/odin1/cloud_raw, /odin1/image} + # # (depth_image_ros2_node.cpp:40-44) -- can never fire. + # senddepth: 1 # else pcd2depth logs "Depth image will not be + # # published." and returns 0 (pcd2depth_ros2.cpp:164) + # sendrgb: 1 # else /odin1/image (raw bgr8) is never produced + # These are `register_keys`, pushed to the device at startup, so RESTART + # the whole driver after editing. `sendodom: 1` + `send_odom_baselink_tf: 1` + # are already on and are what feed this node's odom. + # + # The driver's own device-status log is the authoritative rate check -- far + # better than `ros2 topic hz` for the multi-MB topics (see the doc): + # tail -1 ~/catkin_ws/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv + # A healthy run shows rgb_rx_odr ~10, dtof_rx_odr ~10, slam_cloud_rx_odr ~10, + # slam_odom_highfreq_rx_odr ~400. A 0.00 in *_rx_odr means that stream is off. + # + # Start / restart the driver (this launch brings up the depth node too): + # source /opt/ros/humble/setup.bash + # source ~/catkin_ws/install/setup.bash + # ros2 launch odin_ros_driver odin1_ros2.launch.py + # Never run two host_sdk_sample processes at once: the Odin1 USB link is + # exclusive, so Ctrl-C the old one first. + # + # MIND use_host_ros_time: it is 0 on this machine, i.e. the odom stamp comes + # from the ODIN DEVICE clock, not the host wall clock. The control-frequency + # gate below is unaffected (odom time vs odom time), but the joystick deadman + # compares odom time against `time.time()` -- with require_joystick: true that + # domain mismatch can make the timeout fire instantly or never. See + # docs/DEPLOY_ROS2.md §11 item 8. + # ======================================================================= + + # ------------------------------------------------------------- models ---- + # Leave empty to auto-discover /sru_nav_ros2/models/*.onnx + vae_model_path: "" + policy_model_path: "" + + # ------------------------------------------------------- depth filter ---- + # Training-aligned. Do not change unless you know what you are doing. + min_depth: 0.25 # meters + max_depth: 10.0 # meters + + # ------------------------------------------------------------ control ---- + control_frequency: 5.0 # Hz — matches training + # [vx_max, vy_max, omega_max]. + # Training used [1.5, 1.0, 1.0]; these are the deliberately conservative + # deployment values. NOTE: ROS 2 params are strictly typed — these MUST be + # written as floats. `policy_scale: [1, 1, 1]` (ints) is rejected. + policy_scale: [0.6, 0.3, 0.6] + + # ---------------------------------------------------------- semantics ---- + # Renamed from the ROS 1 `use_sim`. It has NOTHING to do with the ROS 2 + # built-in `use_sim_time`; the old name was a misnomer. + # true -> odom twist is already in a body frame -> pass it through + # false -> odom twist is in the world frame -> rotate it into the body frame + # + # RESOLVED (was open item 3) from the Rc2026 reference project, + # src/driver/vehicle_driver/script/calib/calib_chassis_speed.py: + # "twist.twist.linear.x/y -> linear velocity (odin1_base_link frame)" + # "odin1 velocity is in odin1_base_link frame. If the Odin mounting + # orientation matches the chassis forward direction, linear.x is the + # forward/backward speed directly." + # So the Odin1 driver reports the twist in odin1_base_link, i.e. a BODY frame: + # this must be `true`, and the world->body rotation must NOT be applied. + # + # Residual caveat: with a non-zero Odin1 pitch/roll that frame is tilted w.r.t. + # the platform, so linear.x is scaled by ~cos(pitch) and a small spurious + # linear.z shows up. The reference project accepts this (same comment above); + # removing it exactly would require the mounting extrinsic, i.e. a TF lookup. + # + # This is the value the node runs with. The launch file also exposes it as + # `odom_twist_in_base_frame:=` for a per-run flip, and its launch + # default is read FROM THIS FILE (launch/sru_nav.launch.py::_yaml_default), + # so the two can never disagree. Editing the line below is enough. + odom_twist_in_base_frame: true + + # ---------------------------------------------------------------- QoS ---- + # CONFIRMED from the driver source on this machine -- both publishers are + # RELIABLE: + # host_sdk_sample.h:1928 qos_sensor = QoS(5).reliability(RELIABLE) + # host_sdk_sample.h:1937 odom_highfreq_publisher_ -> qos_small + # = QoS(4000).reliability(RELIABLE) + # depth_image_ros2_node.cpp:49 image_transport advertise() -> falls back to + # rmw_qos_profile_default (= RELIABLE, depth 10) + # + # We still default to BEST_EFFORT on purpose: a BEST_EFFORT subscriber is + # compatible with BOTH RELIABLE and BEST_EFFORT publishers, whereas a RELIABLE + # subscriber silently receives NOTHING from a BEST_EFFORT publisher. Flip to + # true if you want an exact match with this driver (no drops under load). + depth_qos_reliable: false # false = BEST_EFFORT (compatible with both) + odom_qos_reliable: true # true = RELIABLE (matches the driver) + + # ------------------------------------------------------------- deadman --- + # true (SAFE, default): /cmd_vel stays 0 until a /joy publisher exists AND + # the throttle/smart axis is pushed; 15 s without /joy + # forces a stop. Keep this on real hardware. + # false (TESTING ONLY) : bypass the deadman; useful for headless closed-loop + # tests with no operator. Overridable from the launch + # file via `require_joystick:=false`. + require_joystick: true + + # ---------------------------------------------------- joystick mapping --- + # VERIFY (item 6): Humble's `joy` package may map axes/buttons differently + # from ROS 1. Drive each stick/button and read `ros2 topic echo /joy`, then + # correct the indices below. Defaults mirror the PS5 layout in constants.py. + joy_axis_linear_x: 1 + joy_axis_linear_y: 0 + joy_axis_linear_z: 3 + joy_axis_angular_z: 2 + joy_axis_smart: 5 + + joy_button_reset_hidden_state: 2 + joy_button_record_waypoint: 6 + joy_button_clear_waypoint: 4 + joy_button_send_goal: 10 + joy_button_abort: 9 + joy_button_trigger_waypoints: 1 + joy_button_forward: 11 + joy_button_backward: 12 + joy_button_left: 13 + joy_button_right: 14 + joy_button_up: 3 + joy_button_down: 0 + + # ===================================================================== + # GOAL HEADING (final yaw) -- ROS 2 ADDITION, not in the ROS 1 blueprint + # ===================================================================== + # The policy has NO heading input: its 16-dim state is + # [linear_vel(3), angular_vel(3), gravity(3), last_action(3), target(4)] + # and the target is only a body-frame direction + log distance. Arrival is + # also position-only (`||target_xy - robot_xy|| <= ARRIVE_GOAL_THRESHOLD`). + # So a goal heading cannot be expressed through the policy at all. + # + # Instead, once the position goal has been reached, this node runs its own + # in-place rotation stage until the heading is aligned, then releases the + # goal as usual. It is a SEPARATE 20 Hz timer, deliberately NOT part of + # `generate_cmd_vel`: that function is driven by the depth callback and only + # runs at ~1.5 Hz in practice (0.66 s per step = ~19 deg per step at + # 0.6 rad/s), which cannot align anything precisely. + # + # How to use: + # * publish the heading on `goal_yaw_topic` (std_msgs/msg/Float64, radians, + # in the SAME frame as /goal_pose, i.e. odom; 0 = odom +X, CCW positive) + # * NaN means "no heading requirement for this goal" + # * waypoint_runner sets both for you: + # ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708" + # (4th number = yaw; intermediate waypoints simply omit it, so only the + # waypoints that carry a yaw are aligned) + # * a goal published AT the robot's current position with a yaw is just a + # "turn in place to this heading" command + # + # Behaviour is unchanged when no heading is ever published. + goal_yaw_topic: "/goal_yaw" # std_msgs/msg/Float64, radians, odom frame + + # Precision / motion of the in-place rotation. + # tolerance : stop when |error| <= this. 0.0873 rad = 5 deg. + # Achievable floor is set by (a) the Odin1 yaw estimate, + # (b) the chassis' yaw dead-zone / minimum turn rate and + # (c) the 20 Hz discretisation -- so verify on the robot. + # max_rate : hard cap on |angular.z| during alignment. Kept equal to the + # policy's own yaw cap (policy_scale[2] = 0.6) so the stage is + # never more aggressive than normal driving. + # decel : braking profile. |w| = min(max_rate, sqrt(2*decel*|error|)) + # -> full rate far away, tapers to zero at the target, which is + # what removes the overshoot. + # frequency : 20 Hz is ample and stays far below the odom rate. + # settle_time: the error must stay inside the tolerance this long before the + # goal is declared done (rejects transients / overshoot). + # timeout : give up and log the residual error rather than spin forever. + goal_yaw_tolerance: 0.0873 # rad (+/- 5 deg) + goal_yaw_max_rate: 0.6 # rad/s + goal_yaw_decel: 0.8 # rad/s^2 + goal_yaw_update_frequency: 20.0 # Hz (own timer, NOT control_frequency) + goal_yaw_settle_time: 0.4 # s + goal_yaw_timeout: 15.0 # s diff --git a/sru_ws/src/sru_nav_ros2/config/waypoints_example.yaml b/sru_ws/src/sru_nav_ros2/config/waypoints_example.yaml new file mode 100644 index 0000000..dffc6d0 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/config/waypoints_example.yaml @@ -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] diff --git a/sru_ws/src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md b/sru_ws/src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md new file mode 100644 index 0000000..70d18e5 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md @@ -0,0 +1,152 @@ +# AI Agent 提示词(整段复制粘贴给新机器上的 AI Agent) + +> **用法**:在新机器上打开 AI Agent,把下面「─── 提示词开始 ───」到「─── 提示词结束 ───」 +> 之间的**全文**粘进对话框发送。 +> +> 配套资料(都在包里,Agent 需要自己读): +> - `docs/HANDOVER_TEAM.md` ← 交接流程与清单(先读这个) +> - `docs/DEPLOY_ROS2.md` ← **权威细节**(环境原理、话题契约、排错表、存疑项状态) +> +> 如果你已经手动把环境装好了,就把「第二步」跳过,直接告诉 Agent「环境已装好,从验收开始」。 + +--- + +─── 提示词开始 ─── + +你是一名熟悉 ROS 2 Humble、rclpy、ONNX Runtime 与机器人真机部署的高级工程师。请帮我把一个**已经移植完成**的 ROS 2 包在这台机器上跑起来,并为上机实测做好准备。 + +## 一、任务背景(`~/sru_ws/src/sru_nav_ros2/`,已存在,不要重写) + +这是把 SRU-Odin 的 ROS 1 部署代码反向移植成 **ROS 2 Humble `ament_python` 包**的结果, +用于 **Odin1 传感器上的无图端到端导航**: + +``` +/odin1/depth_img_competetion ─┐ + ├─► sru_nav_node ─► /cmd_vel (geometry_msgs/Twist) +/odin1/odometry_highfreq ─────┘ ▲ + └── /goal_pose(位置) + /goal_yaw(朝向) +``` + +**先读这两份文档再动手**:`docs/HANDOVER_TEAM.md`(交接流程、打包与安全须知)、 +`docs/DEPLOY_ROS2.md`(权威细节;环境原理在 §2,话题契约在 §4,参数在 §5,排错在 §8)。 + +**这个包已经在开发机上验证过的部分(不要从头重验)**: +`colcon build --symlink-install` 通过;节点启动打印 `Navigation policy node is ready.`; +两个 ONNX 正确加载;深度话题到达且 `encoding == 32FC1`;**带目标时 `/cmd_vel` 输出非零且有界** +(`|linear_x|≤0.6`、`|linear_y|≤0.18`、`|angular_z|≤0.6`);`/goal_pose`、`/goal_yaw` 收发正常; +`waypoint_runner` 全流程正常;静态 TF 正常;整包检索 ROS 1 客户端库名零命中。 + +## 二、环境配置(严格按顺序;**所有路径按本机家目录替换,不要把 `/home/kevin` 抄进去**) + +1. **确认前提**:`lsb_release -a` 应为 Ubuntu 22.04;`uname -m` 记下架构 + (若**不是 x86_64**,先告诉我,`onnxruntime`/`scipy` 的 wheel 可用性要单独确认)。 +2. **apt 包**: + ```bash + sudo apt update + sudo apt install -y ros-humble-desktop ros-humble-cv-bridge ros-humble-joy \ + ros-humble-tf2-ros ros-humble-rviz2 python3-colcon-common-extensions python3.10-venv + ``` +3. **重建 venv(⚠️ 千万不要从开发机拷 `venv/` 过来,里面全是绝对路径)**: + ```bash + /usr/bin/python3 -m venv --system-site-packages ~/sru_ws/venv + ~/sru_ws/venv/bin/pip install --upgrade pip + ~/sru_ws/venv/bin/pip install "numpy<2" onnxruntime + ~/sru_ws/venv/bin/pip install "scipy==1.11.4" # 必须精确版本号,原因见 DEPLOY_ROS2 §2.2 + ``` + **不要 `pip install opencv-python`** —— 本包用系统 `python3-opencv`(与 `cv_bridge` 同源)。 +4. **往 venv 的 activate 末尾追加两行**(把路径换成本机真实路径): + ```bash + echo "export PYTHONNOUSERSITE=1" >> ~/sru_ws/venv/bin/activate + echo "export PYTHONPATH=\"$HOME/sru_ws/venv/lib/python3.10/site-packages\${PYTHONPATH:+:\$PYTHONPATH}\"" >> ~/sru_ws/venv/bin/activate + ``` + 这两行是**必需**的,不要删、不要改成赋值覆盖: + - `PYTHONNOUSERSITE=1`:`--system-site-packages` 的 venv **不会**禁用用户级 site, + `~/.local` 里的 pip 版 numpy2/opencv 会顶掉系统版 ⇒ `cv_bridge` 崩、`import cv2` 段错误。 + - `PYTHONPATH` **追加**:`colcon`/`ros2` 的 shebang 硬编码 `#!/usr/bin/python3`, + 所以节点永远跑在系统 python 下(**激活 venv 改变不了**),不加这行就 + `ModuleNotFoundError: No module named 'onnxruntime'`。**只能追加**,覆盖式会冲掉 ROS 路径 ⇒ 无 `cv_bridge`。 +5. **两个 `COLCON_IGNORE`(缺了 `colcon build` 必炸)**: + ```bash + touch ~/sru_ws/reference/COLCON_IGNORE ~/sru_ws/venv/COLCON_IGNORE + ``` + 原因:colcon 从工作区根**递归爬全部子目录**(不是只爬 `src/`),否则会去构建蓝本的 catkin 包 + (Humble 没 catkin ⇒ 致命)、`isaaclab_nav_task`、以及 venv 里 setuptools 自带的 `my-test-package`。 + +## 三、验收标准(这些全部通过才算装好) + +```bash +source /opt/ros/humble/setup.bash && source ~/sru_ws/venv/bin/activate +cd ~/sru_ws && colcon build --symlink-install && source install/setup.bash +ros2 pkg prefix sru_nav_ros2 +``` + +| # | 标准 | 期望 | +|---|---|---| +| 1 | `colcon build --symlink-install` | 退出码 0 | +| 2 | `colcon list` | **只有一行** `sru_nav_ros2 src/sru_nav_ros2 (ros.ament_python)`,stderr 为空 | +| 3 | 依赖自检 | `numpy` 在 **venv** 下且为 `1.26.x`;`cv2` 为 **4.5.4** 且路径在 `/usr/lib/python3/dist-packages`;`scipy` 为 **1.11.4** 且在 venv 下;`onnxruntime.get_available_providers()` 含 `CPUExecutionProvider`;`CvBridge()` 能构造 | +| 4 | `ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false` | 打印 `Navigation policy node is ready.`,且 `odom_twist_in_base_frame=True` | + +没有 Odin 数据源时,节点会每 5 s 刷 `Odometry not ready, skipping depth callback.` —— **这是预期行为,不是故障**。 + +## 四、⛔ 绝对不能改的东西 + +- **数值硬约束**(与训练对齐,改了行为就废):`control_frequency=5.0`、`rnn_hidden_size=512`、 + `rnn_num_layers=1`、深度 `0.25~10.0 m`、`resize(40,64)`、latent 2560、obs 2576、 + `ARRIVE_GOAL_THRESHOLD=0.75`、`JOYSTICK_TIMEOUT=15.0`、`LOW_PASS_FILTER_COEF=[0.9,0.5,0.5]`、 + `LATERAL_VELOCITY_SCALE=0.6`。 +- **安全默认值,禁止"优化"**:`policy_scale=[0.6,0.3,0.6]`(训练值本是 `[1.5,1.0,1.0]`,部署刻意保守化)、 + `require_joystick=true`。 +- `sru_nav_ros2/constants.py`、`model.py`、`utils.py` 是**逐字节原样的蓝本拷贝** —— **不要改**。 + 新增常量也不要往 `constants.py` 里塞,放到用它的模块里。 +- **不要改** `~/sru_ws/reference/` 下的任何东西(只读蓝本,留着 diff 用)。 +- **不要"顺手优化"**:策略输出链路、低通滤波、频率门控、QoS 都不要动。 + 发现疑点先报告,由我决定。 + +## 五、已知问题(**不要当成 bug 去修**) + +| # | 现象 / 问题 | 说明 | +|---|---|---| +| 1 | 深度与 `/cmd_vel` 实测只有 **~1.5 Hz**(设备端是 10 Hz) | **已定性:瓶颈在 Odin 驱动的发布/DDS 交付,不在本包**(本节点平均 CPU 只占 11%,89% 时间在空等)。`control_frequency` 是**上限**不是目标值。候选修法在驱动侧(把硬编码的 `QoS(5)` 改成 `QoS(50)`,或发布/订阅**成对**改 BEST_EFFORT)—— ⛔ **绝不能只改发布端**。**这属于驱动侧改动,先报告再动** | +| 2 | Odin1 装订外参默认值是 **Rc2026 比赛车**的实测值,不是我们的载体 | 必须重测,见 `HANDOVER_TEAM.md` §6.2 第 1 项 | +| 3 | 目标朝向(`/goal_yaw`,到点后原地自转对准)**从未在真机上验证** | ±5° 是**设计目标**不是实测结论。逻辑在 `update_goal_yaw()`(20 Hz 独立定时器) | +| 4 | `/joy` 的手柄轴/键索引沿用 PS5 映射,**没在真手柄上验过** | 需要逐个推 | +| 5 | 驱动的 `use_host_ros_time` 可能是 `0`(设备时钟),与主机墙钟不同基准 | 而 deadman 判断式把两者相减 ⇒ 可能"一上来就超时"或"deadman 失效"。开手柄前必须处理 | +| 6 | **路点间距 ≤ 0.75 m 时机器人一步都不走** | 因为 `ARRIVE_GOAL_THRESHOLD=0.75 m` 且发布即判到达。**用 3–5 m 间距** | +| 7 | odom twist 直接透传,但 Odin1 若带俯仰角安装会有残余量 | `linear.x` 会被乘 `cos(pitch)`,并有轻微虚假 `linear.z`;参考工程也这么接受 | + +## 六、执行纪律(请严格遵守) + +1. **不要写自检脚本 / 验收脚本**,不要做离线模拟验证,不要复算算法或数括号配平。 + 只做必要的静态核对(语法、参数名前后一致、残留旧引用),结论用文字告诉我。 +2. **不要"先做一堆环境探测"**:装完就按第三步验收,把**实际输出**贴给我。不要凭"沙箱里 import 不到" + 就改写实现或换方案。 +3. **正规方式不可用时停下来问我**:如果某个依赖装不上、或必须确认权限/系统资源才能继续, + 告诉我「正规方式 X 不可用,我不会自行改用替代方案」并说明需要我决定什么, + **不要自己发明替代实现、mock 核心依赖、静默降级或改用非官方 hack**。 +4. **改代码前先问**。除了环境配置和跑验收,任何对 `src/sru_nav_ros2/` 的修改都先说明理由和改动面, + 我确认后再动手。修复要**先给根因、再做最小修复**,仍然用正规方法。 +5. **不要自作聪明加功能**。之前没提过的功能/优化,只提建议,我采纳了再加。 +6. **安全第一**:任何会让机器人动的操作(发目标、跑 runner、改 `policy_scale`), + **必须我明确说"已抬轮/可以动"之后再做**。默认只做静态与只读的验证。 +7. **交付时讲清楚**:改了哪些文件/函数/配置、实现流程是怎样的、关键调用链与数据流在哪、 + 怎么运行或触发、以及你没能确认的事项。不要只丢结果。 + +## 七、做完之后请汇报 + +1. 第三步验收的**原始输出**(尤其 `colcon list`、依赖自检、launch 日志那行)。 +2. 你改过的任何文件的清单与原因。 +3. 你**没能**确认、或与文档描述不一致的地方。 +4. 你对「下一步该测什么」的建议(对照 `HANDOVER_TEAM.md` §6.2 的待测清单)。 + +─── 提示词结束 ─── + +--- + +## 附:如果环境已经手动装好 + +把上面提示词里的「二、环境配置」整段跳过,改成告诉 Agent: + +> 环境我已经按 `docs/HANDOVER_TEAM.md` 装好了,venv 也重建并追加了两行 export。 +> 你从「三、验收标准」开始,逐条跑并把原始输出给我。 +> 之后不要动代码,等我说可以上机动了再往下。 diff --git a/sru_ws/src/sru_nav_ros2/docs/DEPLOY_ROS2.md b/sru_ws/src/sru_nav_ros2/docs/DEPLOY_ROS2.md new file mode 100644 index 0000000..7e5e030 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/docs/DEPLOY_ROS2.md @@ -0,0 +1,1242 @@ +# DEPLOY_ROS2 — `sru_nav_ros2` 部署与上机指南 + +> 适用环境:**Ubuntu 22.04 + ROS 2 Humble** +> 对应 ROS 1 蓝本:`reference/SRU-Odin/Deployment/`(catkin 包 `sru_nav_go2_ros1`,只读,不要改) +> +> 本包**不绑定机型**:只把 `geometry_msgs/msg/Twist` 发到 `/cmd_vel`,桥接由你自备。 + +--- + +## 0. 一句话说明 + +把 SRU 策略(VAE 深度编码器 + LSTM-SRU 递归策略)跑在 **Odin1 空间记忆传感器**上: + +``` +/odin1/depth_img_competetion ┐ +/odin1/odometry_highfreq ├─► sru_nav_node ─► /cmd_vel +/joy ┘ (ONNX Runtime) +``` + +推理走 **ONNX Runtime 双模型**(`vae_encoder.onnx` + `nav_policy.onnx`),**不依赖 PyTorch,也不需要 conda**。 + +--- + +## 1. 目录与职责 + +| 路径 | 角色 | +|---|---| +| `~/sru_ws/src/sru_nav_ros2/` | 本包(ament_python,要交付的产物) | +| `~/sru_ws/reference/SRU-Odin/` | 只读蓝本,方便日后 diff 对照。**禁止修改** | +| `~/sru_ws/venv/` | 隔离的 Python 环境(onnxruntime / scipy / numpy) | +| `models/*.onnx` | 两个模型随包提交(20.9 MB + 7.1 MB),安装到 `share/sru_nav_ros2/models/` | + +包内文件: + +``` +sru_nav_ros2/ +├── package.xml / setup.py / setup.cfg / resource/ +├── sru_nav_ros2/ +│ ├── constants.py # 纯数值常量(训练对齐,勿改) +│ ├── utils.py # 纯 NumPy 四元数/变换 +│ ├── model.py # ONNX 双模型推理 +│ ├── waypoint_manager.py # 航点记录/回放 +│ ├── visualization.py # rviz marker +│ ├── navigation_policy_node.py # 主节点 +│ ├── sru_nav_node.py # 入口:ros2 run sru_nav_ros2 sru_nav_node +│ └── waypoint_runner.py # 入口:ros2 run sru_nav_ros2 waypoint_runner +├── launch/sru_nav.launch.py +├── config/sru_nav.yaml # 32 个参数,唯一调参入口 +├── config/waypoints_example.yaml +└── docs/DEPLOY_ROS2.md # 本文件 +``` + +--- + +## 2. 环境前置 + +### 2.1 apt 包 + +```bash +sudo apt update +sudo apt install -y \ + ros-humble-desktop \ + ros-humble-cv-bridge \ + ros-humble-joy \ + ros-humble-tf2-ros \ + ros-humble-rviz2 \ + python3-colcon-common-extensions \ + python3.10-venv +``` + +### 2.2 Python 依赖放进 venv + +```bash +/usr/bin/python3 -m venv --system-site-packages ~/sru_ws/venv +~/sru_ws/venv/bin/pip install --upgrade pip +~/sru_ws/venv/bin/pip install "numpy<2" onnxruntime +~/sru_ws/venv/bin/pip install "scipy==1.11.4" +``` + +两个细节,都不是可选项: + +- **`--system-site-packages`** —— venv 必须能看到 ROS 2 的 `rclpy` / `cv_bridge`,否则白建。 +- **`"numpy<2"`** —— 系统 numpy 是 1.21.5,新版 onnxruntime 要求 `numpy>=1.21.6`,不锁会顺手装入 numpy 2.x, + 而 numpy 2.x 会让 `cv_bridge` 报 `_ARRAY_API not found`、`import cv2` 段错误。 +- **`scipy==1.11.4` 用了精确版本号** —— 这是必需的。`--system-site-packages` 的 venv 里, + pip 会把 `/usr/lib/python3/dist-packages` 中的包**当成"已满足"**,因此 `pip install scipy`(哪怕是范围约束) + 只会打印 `Requirement already satisfied` 而**不装进 venv**,运行时仍命中 apt 的 scipy 1.8.0, + 它 pin 了 `numpy<1.25`,与 venv 的 numpy 1.26.4 不匹配。给精确版本号才能强制安装。 + 1.11.x 要求 `numpy>=1.21.6,<1.28.0`,且是按 numpy 1.2x 编译的,与 numpy 1.26.4 自洽。 + +### 2.3 ⚠️ 为什么 venv 的 activate 里必须追加两行 export + +`~/sru_ws/venv/bin/activate` 末尾必须有: + +```bash +export PYTHONNOUSERSITE=1 +export PYTHONPATH="/home/kevin/sru_ws/venv/lib/python3.10/site-packages${PYTHONPATH:+:$PYTHONPATH}" +``` + +**第一行(`PYTHONNOUSERSITE=1`)**:`--system-site-packages` 建的 venv,CPython **不会**禁用用户级 site +(见 `/usr/lib/python3.10/site.py` 第 555–559 行:只有 `include-system-site-packages != true` 时才走 +`ENABLE_USER_SITE = False` 分支)。于是 `~/.local/lib/python3.10/site-packages` 照旧进 `sys.path`, +而那里的 pip 版 `numpy 2.2.6` + `opencv-python 5.0.0` 会顶掉系统版本。 +这**必须**只放 venv 的 activate,**不要**写进 `~/.bashrc`(会连累你其它依赖 `~/.local` 的项目)。 + +**第二行(`PYTHONPATH` 追加)**:`/usr/bin/colcon` 和 `/opt/ros/humble/bin/ros2` 的第一行都是 + +``` +#!/usr/bin/python3 +``` + +也就是说 ROS 2 工具链本身**硬编码跑在系统 python 上**。激活 venv 只影响 PATH 上的裸 `python`/`pip`, +**改变不了 colcon 自己的解释器**。因此 ament_python 生成的 `console_scripts` 入口脚本 +(`install/sru_nav_ros2/lib/sru_nav_ros2/sru_nav_node`)的 shebang **永远是 `#!/usr/bin/python3`**, +于是节点进程跑在系统 python 下,**看不见 venv 里的 onnxruntime**,启动即报: + +``` +ModuleNotFoundError: No module named 'onnxruntime' +``` + +把 venv 的 site-packages 挂进 `PYTHONPATH` 就解决了。 + +> ⚠️ **必须"追加",不能赋值覆盖**。写成 `PYTHONPATH=` 会把 `source setup.bash` 注入的 +> `/opt/ros/humble/local/lib/python3.10/dist-packages` 冲掉,立刻变成 +> `ModuleNotFoundError: No module named 'cv_bridge'`。 + +### 2.4 ⚠️ 为什么 `reference/` 和 `venv/` 里要有 `COLCON_IGNORE` + +``` +~/sru_ws/reference/COLCON_IGNORE +~/sru_ws/venv/COLCON_IGNORE +``` + +**`colcon build` 是从工作区根目录递归爬全部子目录的,不是只爬 `src/`。** 没有这两个标记文件,它会: + +| 被误判成包 | 位置 | 后果 | +|---|---|---| +| `sru_nav_go2_ros1` | `reference/SRU-Odin/Deployment/`(有 `package.xml` + catkin `CMakeLists.txt`) | **致命**:Humble 没有 catkin,`find_package(catkin)` 失败 | +| `isaaclab_nav_task` | `reference/SRU-Odin/Train/mount/sru-navigation-sim/`(有 `setup.py`) | 被当成 Python 包一起构建 | +| `my-test-package` | `venv/.../pkg_resources/tests/data/my-test-package-source/`(setuptools 自带测试样例) | 同上,外加 numpy/scipy 大量 site-packages `setup.py` 刷屏 | + +标记文件放在**父目录** `reference/`、`venv/` 即可,**不要**放进 `reference/SRU-Odin/` 内部(那会污染只读蓝本)。 +`build/`、`install/`、`log/` 不用管,colcon 运行时自己会放同名标记。 + +**自检**(不触发构建): + +```bash +cd ~/sru_ws && colcon list +# 期望只输出一行: +# sru_nav_ros2 src/sru_nav_ros2 (ros.ament_python) +# 且 stderr 完全为空 +``` + +### 2.5 ⚠️ 驱动前置:怎么把 Odin1 数据流真正跑起来 + +#### 0) 本节点为什么"没有深度就完全没有 `/cmd_vel`" + +`/cmd_vel` **只**由 `generate_cmd_vel()` 发布,而 `generate_cmd_vel()` **只**被 `depth_callback()` 调用 —— +这与 ROS 1 蓝本**完全一致**(两边都只有一处调用点)。所以没有深度到达时: + +- `/cmd_vel` 一条都不发 +- 连每秒一次的 `cmd_vel_ratio: ...` 和 `Published cmd_vel: ...` 日志都不会出现 + +**这两条日志的全然缺席,就是"深度没到"的特征签名**,不用去别处找原因。 + +#### 1) 端点 ≠ 数据,别被 `topic info` 骗 + +`ros2 topic list` 里出现 `/odin1/odometry_highfreq` **不代表有人在发** —— 只要存在**任何一个**端点 +(比如本节点的订阅),话题就会被列出来。而 `ros2 topic info` 数的是**端点**: + +- 本节点一订阅,`Subscription count` 立刻变 1,哪怕没人发 +- 驱动启动时就把 publisher 建好了,所以 `Publisher count: 1` 也可能是**没有任何数据**的空壳 + +**唯一可信的判据是 `ros2 topic hz`**(它统计真实到达的消息): + +```bash +ros2 topic hz /odin1/odometry_highfreq # 应有输出(~300-400 Hz) +ros2 topic hz /odin1/depth_img_competetion # 应有输出(~10 Hz) +``` + +若 `hz` 打印 `WARNING: topic [...] does not appear to be published yet`,就是**真的没数据**, +此时 `topic info` 显示的 `Publisher count` 是多少都不作数。 + +⚠️ **但 `hz` 对"大图"话题本身也不可靠**:`/odin1/image` 是 1600×1296 bgr8(≈ **6.2 MB/帧**, +**不缩放**),而驱动发布端是 **RELIABLE + 小队列** —— Python 写的 `ros2 topic hz` 订阅者跟不上时会把 +发布端一起拖慢,于是**明明 10 Hz 的流会显示成 0.3 Hz**(驱动自己的 `dev_status.csv` 显示 `rgb_rx_odr = 10.2`)。 +所以低速率不要急着下结论,用下面 §2.5.1 的设备状态日志交叉验证。 + +> ⚠️ **但深度话题不是大图**:深度节点会把相机尺寸除以 `scale` 参数(默认 **7.0**, +> 而 `control_command.yaml` 没有覆盖它)—— +> `pointcloud_depth_converter.cpp:27-28`:`scaled_w/h = image_w/h / scale` +> ⇒ 1600/7 × 1296/7 = **228×185 的 32FC1,仅约 165 KiB/帧**。 +> 所以深度话题**不存在"大消息拖慢"问题**,它的 `hz` 是可信的; +> 若深度只有 ~1 Hz,说明是**上游产出慢**,不是本节点忙不过来(见 §11 第 7 项)。 + +#### 2) 启动驱动 + +驱动已编译安装在 `~/catkin_ws/install/odin_ros_driver`。官方 launch 会一次把 +`host_sdk_sample` + `pcd2depth_ros2_node`(深度)+ 重投影 + overlay + rviz2 全部拉起: + +```bash +source /opt/ros/humble/setup.bash +source ~/catkin_ws/install/setup.bash +ros2 launch odin_ros_driver odin1_ros2.launch.py +``` + +⚠️ **绝不能同时跑两个 `host_sdk_sample`** —— Odin1 的 USB 链路是独占的。重启驱动前先 Ctrl-C 掉旧的。 + +#### 3) 必须改**三处**配置,否则永远没有深度 + +⚠️ **要改的是源码树里那份,不是 `install/` 里那份。** + +驱动的三个可执行文件都用 `get_package_source_directory()` 定位配置 —— 它从**编译期的 `__FILE__`** +逐级向上找到含 `package.xml` 的目录 +(`host_sdk_sample.cpp:869` 与 `:2491`、`pcd2depth_ros2.cpp:122`、`cloud_reprojection_ros.cpp:48`)。 +本机编译进去的路径是 `/home/kevin/catkin_ws/src/odin_ros_driver/src/*.cpp` +(证据:`build/odin_ros_driver/CMakeFiles/*/src/*.cpp.o.d` 里就是这个绝对路径),所以**实际被读的文件**是: + +``` +~/catkin_ws/src/odin_ros_driver/config/control_command.yaml ← 改这份 +~/catkin_ws/install/odin_ros_driver/share/odin_ros_driver/config/control_command.yaml ← 改了没用 +``` + +三个键都要改(本机出厂都是 `0`): + +```yaml +senddtof: 1 # 原始点云 /odin1/cloud_raw ← 最容易漏、也最致命的一个 +senddepth: 1 # 稠密深度图 /odin1/depth_img_competetion +sendrgb: 1 # 解码后的 RGB /odin1/image (bgr8) +``` + +**为什么三个都必需**:深度节点用 `message_filters` 的 `ApproximateTime` 同步**一对**输入 +(`depth_image_ros2_node.hpp:68`、`.cpp:40-44`): + +``` +{ /odin1/cloud_raw } + { /odin1/image (raw bgr8) } --> 同步后才产出深度图 +``` + +- `sendrgb: 0` → `/odin1/image` 从不产出 → 只来一半,同步器永不触发 +- **`senddtof: 0` → `/odin1/cloud_raw` 从不产出** → 同样只来一半。这个键最容易漏,因为它的名字 + 看起来像"DTOF 传感器开关",实际定义是 `#define SENDDTOF "senddtof" /* send raw cloud data */` + (`host_sdk_sample.h:2152`)。它在**两处**被双重门控: + - 设备端直接关流:`host_sdk_sample.cpp:1950` `else lidar_deactivate_stream_type(..., LIDAR_DT_RAW_DTOF)` + - 主循环再拦一次:`host_sdk_sample.cpp:1057` `case LIDAR_DT_RAW_DTOF: if (g_senddtof) publishIntensityCloud(...)` + + 症状很好认:驱动自己的设备状态日志里 `dtof_tx_odr ≈ 10` 但 `dtof_rx_odr = 0.00` + (设备在发 DTOF,只是主机不收 —— 因为 `senddtof` 关着;**这不代表设备坏了**)。 + +这三个键属于 `register_keys`,是**启动时下发给设备**的,所以改完必须**整体重启驱动**。 + +顺带确认这几项(默认已是对的): + +- `sendodom: 1` + `send_odom_baselink_tf: 1` —— 本节点的 odom 来源、以及 `odom → odin1_base_link` + +#### 2.5.1 📊 判断"真实速率"的权威手段:驱动自己的设备状态日志 + +驱动在 `devstatuslog: 1` 时会按连接持续写一份 CSV,里面**分列记录设备端发送率与主机端接收率**。 +这是判断"某路数据到底通没通"最硬的证据,比 `ros2 topic hz` 可靠得多(不受大消息拖累): + +```bash +CSV=$(ls -1t ~/catkin_ws/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv | head -1) +head -1 "$CSV" # 表头 +tail -1 "$CSV" # 最新一行 +``` + +关键列(一次正常的采集应当是): + +| 列 | 正常值 | 含义 | +|---|---|---| +| `rgb_tx_odr` / `rgb_rx_odr` | ~10 / ~10 | RGB:设备发 10 Hz,主机也收到 10 Hz | +| `dtof_tx_odr` / `dtof_rx_odr` | ~10 / **0** ← 若 `senddtof: 0` | 原始点云流:**0 就说明这路没通** | +| `imu_tx_odr` / `imu_rx_odr` | ~400 / **0** ← 若 `sendimu: 0` | IMU 流 | +| `slam_cloud_tx_odr` / `slam_cloud_rx_odr` | ~10 / ~10 | `/odin1/cloud_slam` | +| `slam_odom_highfreq_tx_odr` / `slam_odom_highfreq_rx_odr` | ~400 / ~400 | 本节点的 odom 来源 | + +**读法**:`*_tx_odr` 是设备侧发送率,`*_rx_odr` 是主机侧接收率。 +**`*_rx_odr = 0.00` 的那一路就是没通**(大概率被对应的 `send*` 开关关着)。 + +#### 4) `use_host_ros_time` 要留意(本机是 `0`) + +驱动配置里有原文注释,三个取值: + +| 值 | 含义 | +|---|---| +| `0` | 用 **Odin 设备内部时间**做时间戳(官方注释:typical and recommended)—— **本机就是这个值** | +| `1` | 用主机 ROS 时间(收到时刻)打时间戳 | +| `2` | 把设备时间对齐到主机时间轴 | + +`0` 的影响:odom 时间戳来自**设备时钟**,与主机墙钟不是同一时间基准。 + +- 对**控制频率门控**无影响(它比较的是 odom 时间与 odom 时间,自洽) +- 对**手柄 deadman** 有影响:判断式是 `odom 时间戳 − time.time() > 15.0`,两个时间域混算 → + 可能「立刻超时」或「永不超时」。详见 §11 第 8 项 + +#### 核实命令(改完配置、重启驱动后按顺序跑) + +```bash +# 首选:驱动自己的设备状态日志(对多 MB 话题最可靠,见 §2.5.1) +CSV=$(ls -1t ~/catkin_ws/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv | head -1) +head -1 "$CSV"; tail -1 "$CSV" +# 期望:rgb_rx_odr ~10、dtof_rx_odr ~10(改 senddtof 前是 0.00)、slam_cloud_rx_odr ~10、 +# slam_odom_highfreq_rx_odr ~400 + +# 辅以话题检查(大图话题的 hz 数值可能偏低,属测量假象,以 CSV 为准) +ros2 topic hz /odin1/depth_img_competetion # 决定性;低数值先与 CSV 交叉验证 +ros2 topic echo /odin1/depth_img_competetion --once --field encoding # 32FC1 +ros2 topic hz /odin1/odometry_highfreq # ~300-400 Hz(小消息,hz 可信) +ros2 topic echo /odin1/odometry_highfreq --once --field header # frame_id: odom +``` + +#### QoS 对照(已从驱动源码确认) + +| 话题 | 发布端 QoS | 依据 | +|---|---|---| +| `/odin1/odometry_highfreq` | **RELIABLE**, KEEP_LAST depth 4000 | `host_sdk_sample.h:1937` 用 `qos_small` | +| `/odin1/odometry`、各点云/RGB | **RELIABLE**, depth 5 | `host_sdk_sample.h:1928` `qos_sensor` | +| `/odin1/depth_img_competetion` | **RELIABLE**, depth 10 | `depth_image_ros2_node.cpp:49` 走 `image_transport`,落到 `rmw_qos_profile_default`(= RELIABLE, depth 10)| + +所以本包 `odom_qos_reliable: true` 与驱动**完全匹配**;深度默认用 BEST_EFFORT 也与 RELIABLE 发布端**兼容** +(BEST_EFFORT 订阅端能吃 RELIABLE 发布端的数据,反之才不行)。想完全匹配可把 `depth_qos_reliable` 改成 `true`。 + +--- + +## 3. 构建与运行 + +```bash +# ---- 构建(每次都要先 source 两个环境)---- +source /opt/ros/humble/setup.bash +source ~/sru_ws/venv/bin/activate +cd ~/sru_ws && colcon build --symlink-install +source install/setup.bash + +# ---- 正常运行(手柄 deadman 生效,安全默认)---- +ros2 launch sru_nav_ros2 sru_nav.launch.py + +# ---- 无手柄的冒烟测试(TESTING ONLY,务必先抬轮/架空!)---- +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false +``` + +期望日志: + +``` +[sru_nav_node-2] [INFO] [...] [sru_nav_node]: VAE encoder: .../share/sru_nav_ros2/models/vae_encoder.onnx +[sru_nav_node-2] [INFO] [...] [sru_nav_node]: Policy model: .../share/sru_nav_ros2/models/nav_policy.onnx +[sru_nav_node-2] [INFO] [...] [sru_nav_node]: Navigation policy node is ready. +[sru_nav_node-2] [INFO] [...] [sru_nav_node]: SRU navigation node spinning (odom_twist_in_base_frame=True, require_joystick=False). +``` + +> 如果没有 Odin1 数据源,会看到每 5 秒一次的 +> `Odometry not ready, skipping depth callback.` —— **这是预期行为**(在等 odom),不是故障。 + +### launch 参数 + +| 参数 | 默认 | 说明 | +|---|---|---| +| `params_file` | `share/sru_nav_ros2/config/sru_nav.yaml` | 参数文件路径 | +| `odom_twist_in_base_frame` | `true` | 原 ROS 1 的 `sim`。含义是"odom 的 twist 已在 body 系,直接透传",**与 ROS 2 的 `use_sim_time` 无关**。默认值已按参考工程实测改为 `true`(见 §11 第 3 项) | +| `require_joystick` | `true` | 手柄 deadman。`false` 仅供测试 | +| `launch_joy` | `true` | 是否顺带起 `joy_node` | +| `launch_static_tf` | `true` | 是否发布静态 TF `odin1_base_link → base_link` | +| `base_link_x/y/z/roll/pitch/yaw` | 见下 | **`base_link` 在 `odin1_base_link` 下的位姿**,必须按你的载体实测替换(见 §11 第 5 项) | + +> ⚠️ **`odom_twist_in_base_frame` 与 `require_joystick` 的 launch 默认值是从 +> `config/sru_nav.yaml` 里读出来的**,不是写死的。原因:ROS 2 里 `parameters` 列表 +> **后者覆盖前者**,所以只要 launch 里硬编码一个默认值,它就会**盖掉 YAML** —— +> 这正是本包踩过的坑:YAML 已改成 `true`,但 launch 里写死 `false`,节点实际跑在 `false`。 +> 现在 `launch/sru_nav.launch.py::_yaml_default()` 直接读 YAML 取值,两边不可能再矛盾: +> **改 YAML 就够了**;想临时翻一次就用 `odom_twist_in_base_frame:=false` 这类命令行覆盖。 +> (`ros2 launch` 在 Humble 不支持 `--ros-args -p`,所以这两个键必须保留 launch 参数才能从命令行翻。) + +> **TF 方向与 ROS 1 蓝本相反,这是有意为之。** 驱动自己会广播 `odom → odin1_base_link` +> (`control_command.yaml` 里 `send_odom_baselink_tf: 1`),所以机器人侧只需补上 +> `odin1_base_link → base_link`,TF 树才完整:`odom → odin1_base_link → base_link`。 +> 这正是 Rc2026 参考工程的树形。若按蓝本那样发 `base_link → odin1_base_link`, +> `odin1_base_link` 会同时有两个父节点,TF 树直接断掉。 +> +> 参数含义随之改变:现在描述的是"**车体中心在 Odin1 坐标系里的位置**", +> 是"传感器装在哪"的**逆变换**。 +> 默认值取自 Rc2026 比赛车 R2 的**实测装订**(`x=-0.268846, y=0.028504, z=0.067861, +> roll=0.017828, pitch=0.245433, yaw=0.0`)—— 那是同一款传感器在同类小车上的真实标定结果, +> 比从 Go2 平台继承的假设值有意义得多,**但它不是你的载体,接车后必须重测**。 + +--- + +## 4. 话题接口 + +| 话题 | 类型 | 方向 | 说明 | +|---|---|---|---| +| `/odin1/depth_img_competetion` | `sensor_msgs/msg/Image` | 入 | 稠密深度,`32FC1`,单位米,~10 Hz。✅ **名字已确认**:它就是驱动 `depth_image_ros2_node.cpp` 里 `depth_image_topic` 参数的默认值。⚠️ **但驱动默认不发它** —— 必须先开 `senddepth: 1` 并起 `pcd2depth_ros2_node`,见 §2.5 | +| `/odin1/odometry_highfreq` | `nav_msgs/msg/Odometry` | 入 | ~300–400 Hz。`header.frame_id = odom`,`child_frame_id = odin1_base_link`;**twist 已在 `odin1_base_link`(body)系**,不要再做世界系→体系旋转。备选 `/odin1/odometry`(~10 Hz,漂移更小但更滞后) | +| `/joy` | `sensor_msgs/msg/Joy` | 入 | 手柄 | +| `/goal_pose` | `geometry_msgs/msg/PoseStamped` | 入/出 | `frame_id` **必须**等于 odom 的 `header.frame_id`,否则目标被直接拒绝。⚠️ 它的 `orientation` 字段**从不被读取**(到达判定只看 XY 距离) | +| `/goal_yaw` | `std_msgs/msg/Float64` | 入 | **ROS 2 新增**:目标的朝向要求(弧度、odom 系),`NaN` = 本目标无朝向要求。详见 §6.4 | +| `/cmd_vel` | `geometry_msgs/msg/Twist` | 出 | body 系速度指令 | +| `/sru_nav_node/base_vel` | `geometry_msgs/msg/Twist` | 出 | 调试用:转换后的 base 系速度(原 ROS 1 的 `~base_vel`) | +| `/sru_nav_node/vis/*` | `visualization_msgs/msg/Marker` | 出 | 4 个 rviz 可视化 marker:`twist_cmd_marker`、`goal_vector_marker`、`moving_goal_marker`、`recorded_waypoints_marker`(含义见 §6.3) | +| `/sru_nav_node/vis/executed_path` | `nav_msgs/msg/Path` | 出 | **ROS 2 新增**:实际走过的轨迹(1 Hz 采样,上限 600 点 ≈ 10 min) | +| `/sru_nav_node/vis/goal_path` | `nav_msgs/msg/Path` | 出 | **ROS 2 新增**:当前位置 → 当前目标的直线(2 点) | + +节点名保持 `sru_nav_node`,所以私有话题(`~/base_vel`、`~/vis/*`)展开结果与 ROS 1 完全一致, +**原有 rviz 配置可直接复用**。 + +> ⚠️ 这两个 `Path` 都**不是"规划出来的路径"** —— 本节点是端到端反应式策略,没有规划器。 +> 见 §6.3 的说明。 + +### 模型 I/O 契约(不要改) + +| 模型 | 输入 | 输出 | +|---|---|---| +| `vae_encoder.onnx` | `input` `(B,1,40,64)` | `mu` `(B,64,5,8)` | +| `nav_policy.onnx` | `obs` `(B,2576)`, `h` `(1,B,512)`, `c` `(1,B,512)` | `actions` `(B,3)`, `h_new`, `c_new` | + +最终速度 = `tanh(actions) × policy_scale`。 + +--- + +## 5. 参数 + +全部 **39** 个参数都在 `config/sru_nav.yaml`(顶层键是节点名 `sru_nav_node`)。 +**调参只改这个文件,不需要动代码。** 实测后可用 `ros2 param dump /sru_nav_node` 回写。 + +其中 7 个属于「目标朝向」这项 ROS 2 新增功能,见 §6.4: + +| 参数 | 默认 | 作用 | +|---|---|---| +| `goal_yaw_topic` | `/goal_yaw` | 朝向要求的输入话题(`std_msgs/Float64`,弧度) | +| `goal_yaw_tolerance` | `0.0873` | 停止容差(≈ 5.00°) | +| `goal_yaw_max_rate` | `0.6` | 自转速度上限(rad/s),与策略自身的 `policy_scale[2]` 对齐 | +| `goal_yaw_decel` | `0.8` | 制动曲线用(rad/s²),越大越早减速 | +| `goal_yaw_update_frequency` | `20.0` | 自转阶段自己的定时器频率(**不是** `control_frequency`) | +| `goal_yaw_settle_time` | `0.4` | 进入容差后必须保持这么久才算成功 | +| `goal_yaw_timeout` | `15.0` | 超时放弃并打印残余误差 | + +### 绝对不能改的(与训练对齐,改了行为就废) + +``` +control_frequency = 5.0 Hz +rnn_hidden_size = 512 +rnn_num_layers = 1 +min_depth / max_depth = 0.25 / 10.0 m +ARRIVE_GOAL_THRESHOLD = 0.75 m +JOYSTICK_TIMEOUT = 15.0 s +LOW_PASS_FILTER_COEF = [0.9, 0.5, 0.5] +LATERAL_VELOCITY_SCALE = 0.6 +深度预处理链:nan_to_num → 裁剪 [0.25, 10.0] → resize (40, 64) +latent = 64×5×8 = 2560 维;obs 总维 = 2576 = 16(状态) + 2560(图像) +``` + +上面这些**故意不放进 YAML**(除 `min_depth`/`max_depth`/`control_frequency` 是 ROS 1 原有的可配项), +从 `constants.py` 取值,不给被误配的机会。 + +### 安全默认值,禁止"优化" + +```yaml +policy_scale: [0.6, 0.3, 0.6] # 训练值本是 [1.5, 1.0, 1.0],部署刻意保守一半以上;确认安全后再逐步升 +require_joystick: true # 手柄 deadman,默认必须 true +``` + +> ROS 2 参数类型严格:`policy_scale` 必须写**浮点**。`[1, 1, 1]`(整数)会被拒。 + +--- + +## 6. 上机核对清单(按顺序跑) + +```bash +# 0) 环境 +ros2 --version +python3 -c "import onnxruntime as ort; print(ort.get_available_providers())" + +# 1) 构建(见 §3) +cd ~/sru_ws && colcon build --symlink-install && source install/setup.bash + +# 2) 静态确认:Python 模块里不应残留任何 ROS 1 客户端库调用 +# 检索词 = ROS 1 的 Python 客户端库名(见 docs/HANDOVER.md),整包应为零命中。 +# 本文件刻意不写出那个名字 —— 否则这条检索会命中文档自身。 + +# 3) 驱动侧:先按 §2.5 起驱动,并把源码树那份 control_command.yaml 里的 +# senddtof / senddepth / sendrgb 都改成 1,然后整体重启驱动。 +# 怎么判断"有没有数据": +# · `topic list` 只代表"存在端点",不够; +# · `topic info` 的 Publisher count 也不够 —— 驱动建了 publisher 但没数据时它照样是 1; +# · `topic hz` 是标准判据,但对 6-8 MB 的大图会因为订阅端跟不上而偏低(假象); +# · 最硬的证据是驱动自己写的设备状态日志(§2.5.1)。 +CSV=$(ls -1t ~/catkin_ws/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv | head -1) +head -1 "$CSV"; tail -1 "$CSV" +# 期望:rgb_rx_odr ~10、dtof_rx_odr ~10、slam_cloud_rx_odr ~10、slam_odom_highfreq_rx_odr ~400 +# (若 dtof_rx_odr = 0.00 ==> senddtof 还是 0) +ros2 topic echo /odin1/depth_img_competetion --once --field encoding # 期望 32FC1 +ros2 topic hz /odin1/odometry_highfreq # 期望 ~300-400 Hz +ros2 topic echo /odin1/odometry_highfreq --once --field header # 期望 frame_id: odom + +# 4) 启动控制器(无手柄,先别让车动) +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false +# 期望:Navigation policy node is ready. +# SRU navigation node spinning (odom_twist_in_base_frame=True, require_joystick=False). +# 随后应每秒出现(这两条来自 generate_cmd_vel,只有深度到了才会有): +# cmd_vel_ratio: 1.0000 (require_joystick=False) +# Published cmd_vel: linear_x=..., linear_y=..., angular_z=... +# 若这两条一直不出现 ==> 深度没到,回到 §2.5,不要去查本包代码。 + +# 5) 静态 TF 方向(父 odin1_base_link → 子 base_link,与驱动自带的 odom→odin1_base_link 串成树) +ros2 run tf2_ros tf2_echo odin1_base_link base_link + +# 6) 另开终端发目标 + 看输出 +ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" +ros2 topic hz /cmd_vel # 期望稳定 ~5 Hz +ros2 topic echo /cmd_vel # 期望有非零数值 +``` + +### 6.1 🧪 只有 Odin1、没有实机载体时怎么验证 + +好消息:整条链路**不依赖底盘**就能验证。节点只订阅 Odin1 的两路数据、只发布 `/cmd_vel`; +没有载体时 `/cmd_vel` 没有消费者,但**该不该有输出、数值对不对,全都能看出来**。 + +```bash +# 终端 A:先起 Odin1 驱动(这一步不做,后面全是空的) +# ① 确认「源码树里那份」control_command.yaml 里三个键都是 1: +# senddtof / senddepth / sendrgb (见 §2.5) +# ② 启动: +source /opt/ros/humble/setup.bash +source ~/catkin_ws/install/setup.bash +ros2 launch odin_ros_driver odin1_ros2.launch.py +# ③ 确认"真有数据到达"——优先看驱动自己的设备状态日志(§2.5.1,对大图最可靠): +CSV=$(ls -1t ~/catkin_ws/src/odin_ros_driver/log/Driver_*/Conn_*/dev_status.csv | head -1) +head -1 "$CSV"; tail -1 "$CSV" +# 期望:rgb_rx_odr ~10、dtof_rx_odr ~10、slam_cloud_rx_odr ~10、slam_odom_highfreq_rx_odr ~400 +# 辅助(小消息可信,大图偏低属测量假象): +ros2 topic hz /odin1/odometry_highfreq # ~300-400 Hz + +# 终端 B:控制器 +source /opt/ros/humble/setup.bash && source ~/sru_ws/venv/bin/activate +source ~/sru_ws/install/setup.bash +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false + +# 终端 C:发一个目标,然后看输出 +ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" +ros2 topic hz /cmd_vel +ros2 topic echo /cmd_vel +ros2 topic echo /sru_nav_node/base_vel # 调试:从 odom 解出的速度 +``` + +**怎么判断"能用"**: + +| 观察点 | 说明 | +|---|---| +| 启动即打印 `Navigation policy node is ready.` | 模型加载成功(两个 ONNX session 都起来了) | +| `SRU navigation node spinning (odom_twist_in_base_frame=..., ...)` 里的值与你 YAML 一致 | 参数确实生效了。**若不一致,见 §8「参数值和你改的 YAML 不一致」** | +| `Odometry not ready, skipping depth callback.` **不再刷新** | 说明 odom 已就绪。这条日志的意思是"还没收到 odom",**不是故障** | +| 出现 `cmd_vel_ratio: 1.0000 (require_joystick=False)` | 说明深度已到、且走的是**推理分支**(这条只在推目标时才打印) | +| 出现 `Published cmd_vel: linear_x=... linear_y=... angular_z=...` 且数值非零 | 推理链路通了,深度也在被消费 | +| `ros2 topic hz /cmd_vel` ≈ 5 Hz | 控制频率门控正常(`control_frequency: 5.0`)。**若明显低于 5 Hz,见 §11 第 7 项** | +| `/cmd_vel` 全 0 | 见 §8。**先确认你发了目标** —— 没目标时节点本来就会发 0 并刷 `Target position reset.` | + +**没有载体时属于正常现象、别误判为故障**: + +- **没发目标时 `/cmd_vel` 恒为 0,并每秒刷 `Target position reset.`** —— 蓝本原有设计,逐行一致。 + 要在终端 A 之外再起 `waypoint_runner`(或在另一个终端 `ros2 topic pub /goal_pose ...`)才会进入推理分支。 +- `waypoint_runner` 会在 ~10 s 后把目标判为 `STUCK` 并跳过 —— 因为车确实不动,这是它的设计行为。 + 所以要看"非零 `/cmd_vel`",得盯**发目标后的头 10 秒**;之后它会回 HOME,而 HOME 距车 0 m < 0.75 m 阈值, + 会立刻判"已到达"、又变回 0。 +- 目标会被反复重发(`republish_interval: 5.0`),日志里有 `re-published goal` 是正常的。 + +**没有载体时无法验证的**(等有车再做):装订 TF 的数值(§11 第 5 项)、 +`odom_twist_in_base_frame` 的正负号(第 3 项,现按参考工程定为 `true`)、deadman 时钟同源性(第 8 项)。 + +### 6.2 📋 单 Odin1 已验证 / 未验证清单(下机前对照) + +> ⚠️ **不需要 `colcon build`**:`--symlink-install` 下 `build/sru_nav_ros2/` 里的 +> `sru_nav_ros2/`、`launch/`、`config/`、`docs/` **全是指向 `src/` 的符号链接**(已核实 +> `readlink -f` 解析到源码)。所以改完 launch / config / 代码,**直接重启 launch 就是新的**。 + +**✅ 已在单 Odin1 上验证** + +| 项 | 证据 | +|---|---| +| `colcon build --symlink-install` 退出码 0 | ✅ | +| `colcon list` 只列出本包、stderr 为空 | ✅ 两个 `COLCON_IGNORE` 生效 | +| 整包检索 ROS 1 的 Python 客户端库名 → 零命中(检索词见 §6 第 2 步说明;本文件刻意不写出它) | ✅ | +| 节点启动打印 `Navigation policy node is ready.` | ✅ | +| 两个 ONNX 从 `share/sru_nav_ros2/models/` 正确加载 | ✅ | +| odom 订阅成功、`robot_odom_time` 粒度正常推进 | ✅ 门控出现 0.198 s 间隔 | +| 深度话题到达且 `encoding == 32FC1` | ✅ | +| 推理被触发(`Published cmd_vel:` 出现) | ✅ | +| **带目标时输出非零且有界的 `/cmd_vel`** | ✅ 实测三帧:`(-0.2428, -0.0856, -0.2607)` → `(0.3944, -0.1519, -0.4938)` → `(0.5490, -0.1630, -0.5224)`,且 `cmd_vel_ratio: 1.0000` | +| `/goal_pose` 收发正常(`Received target position`) | ✅ | +| `waypoint_runner` 全流程(等 odom → 发目标 → 5 s 重发 → STUCK 跳过 → 回 HOME 判到达) | ✅ | +| 静态 TF `odin1_base_link → base_link` | ✅ | +| 环境(venv / `PYTHONPATH` 追加 / `PYTHONNOUSERSITE`) | ✅ 已实测 | +| `odom_twist_in_base_frame` 修正生效 | ✅ 启动日志打印 `odom_twist_in_base_frame=True` | + +#### 安全上限的可证不变式(已用实测数值核对) + +输出被两道约束夹住,且**滤波不会突破它**: + +```python +model.py:153 cmd_vel = np.tanh(raw_action) * self._policy_scale # |cmd[i]| <= policy_scale[i] + model_cmd[1] = cmd[1] * LATERAL_VELOCITY_SCALE # linear_y 再乘 0.6 +node filt = LOW_PASS_FILTER_COEF * model_cmd + (1 - coef) * prev_cmd +``` + +`LOW_PASS_FILTER_COEF = [0.9, 0.5, 0.5]`,`1 - coef = [0.1, 0.5, 0.5]` —— **权重非负且和为 1**, +所以 `filt` 是 `model_cmd` 与 `prev_cmd` 的**凸组合** ⇒ **不可能放大**(归纳可得)。 + +| 分量 | 理论上限 | 实测最大 | | +|---|---|---|---| +| `linear_x` | `policy_scale[0]` = **0.6** | 0.5490 | ✅ | +| `linear_y` | `policy_scale[1] × 0.6` = **0.18** | 0.1630 | ✅ | +| `angular_z` | `policy_scale[2]` = **0.6** | 0.5224 | ✅ | + +⇒ **安全缩放链路端到端正确**:没有超限、没有放大、`cmd_vel_ratio` 被正确遵守。 +(这也是"无载体也能验"的一条硬指标。) + +**❌ 尚未验证** + +| # | 项 | 为什么重要 | +|---|---|---| +| 1 | `~/vis/*` 可视化话题(含新增的 `executed_path` / `goal_path`) | 未在 rviz 里实地看过;话题名与配法见 §6.3。不影响控制,只影响 rviz 观感 | +| 2 | **目标朝向自转(§6.4,本次新增)** | 逻辑与参数已就位,但**只有接了底盘才能验证**:实际残差、是否过冲、底盘死区能支持多小的容差。±5° 是设计目标,不是实测结论 | +| 3 | `/joy` 手柄路径 + deadman | 存疑项 #6 / #8。`use_host_ros_time: 0` ⇒ odom 是**设备时钟**,deadman 判断式却拿它与 `time.time()` 相减,**时钟域问题是真实存在的**,开手柄前必须处理 | +| 4 | 装订外参、twist 正负号手感 | 存疑项 #5 / #3,**必须实车** | + +**下机前最后三步(约 10 分钟)** + +```bash +source /opt/ros/humble/setup.bash && source ~/sru_ws/venv/bin/activate +source ~/sru_ws/install/setup.bash # 无需 colcon build(symlink-install) + +# ① 起控制器,确认这一行的参数值是 True +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false +# SRU navigation node spinning (odom_twist_in_base_frame=True, require_joystick=False) + +# ② 另开终端:发目标(车不动没关系,只看数值),盯前 10 秒 +ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0" +# cmd_vel_ratio: 1.0000 (require_joystick=False) +# Published cmd_vel: linear_x=..., linear_y=..., angular_z=... ← 应非零 + +# ③ 独立确认话题上真的有非零 Twist +ros2 topic echo /cmd_vel --once +``` + +⚠️ **必须先发目标** —— 没有目标时节点**故意**发 0 并刷 `Target position reset.`(蓝本原样行为,见 §8)。 + +--- + +### 6.3 🖥️ 在 rviz2 里看路径与其它可视化 + +#### 先澄清一件事:**没有"规划的路径"这回事** + +本节点是**端到端反应式策略**(深度图 + 16 维状态 → 网络 → `/cmd_vel`),**里面没有规划器**: + +- 没有全局/局部路径规划,没有地图,没有 SLAM +- 每次唯一的决策入口是 `model.predict(...)`,输出直接是速度 + +所以任何"从 A 到 B 的规划路线"都不会存在。rviz 里能画出来的是下面两类东西, +它们描述的是**实际发生的事**和**当前在追什么目标**,而不是计划: + +| 话题 | 类型 | 含义 | 坐标系 | +|---|---|---|---| +| `~/vis/executed_path` | `Path` | **实际走过的轨迹**(1 Hz 采样你踩过的点) | `odom` | +| `~/vis/goal_path` | `Path` | **当前位置 → 当前目标的直线**(2 点,随目标更新) | `odom` | +| `~/vis/goal_vector_marker` | `Marker` | 目标方向的**单位箭头**(长 1 m,只表方向、不表距离) | `odin1_base_link` | +| `~/vis/twist_cmd_marker` | `Marker` | 当前速度指令箭头(随 `TWIST_MARKER_SCALE=5` 放大) | `odin1_base_link` | +| `~/vis/moving_goal_marker` | `Marker` | moving-goal 功能的落点(未启用时长度 0) | `odom` | +| `~/vis/recorded_waypoints_marker` | `Marker` | 已记录的路点(绿方块)。**注意:`waypoint_runner` 走的是它自己的列表,不会填这个 marker** | `odom` | +| `/goal_pose` | `PoseStamped` | 目标本身(`waypoint_runner` 或遥控发的) | `odom` | + +#### 打开 rviz2 并配好 + +```bash +source /opt/ros/humble/setup.bash +rviz2 +``` + +1. **Fixed Frame 改成 `odom`**(左上 Global Options)。默认 `map` 在本工程不存在。 +2. 左下 **Add → By topic**,逐个点开,把下面这些加进来: + + | 加什么 | 建议设置 | + |---|---| + | `/sru_nav_node/vis/executed_path` → **Path** | `Line Style` 用 `Lines`,`Color` 选亮蓝;`Pose Style` 设 `None` | + | `/sru_nav_node/vis/goal_path` → **Path** | 同上,颜色选亮红 —— 这条就是"它在朝哪走" | + | `/sru_nav_node/vis/goal_vector_marker` → **Marker** | 绿色箭头 = 策略收到的目标方向 | + | `/sru_nav_node/vis/twist_cmd_marker` → **Marker** | 蓝色箭头 = 策略发出的速度 | + | `/sru_nav_node/vis/recorded_waypoints_marker` → **Marker** | 绿方块 = 已记录路点 | + | `/goal_pose` → **Pose** | 目标位置,`Shape` 用 `Axes` 或 `Arrow` | + | `/odin1/odometry_highfreq` → **Odometry** | 可选,看车体姿态 | + | `/tf` 与 `/tf_static` → **TF** | 建议打开,用来确认坐标系有没有断 | + + 也可以直接点 **By display type** 自己建,Topic 手填上面的名字。 +3. 存成配置(`File → Save Config As`),下次 `rviz2 -d <你的.rviz>` 一步打开。 + +#### 只有 Odin1、没有载体时会发生什么 + +- `executed_path` **只会是一个点** —— 车不动,odom 不动,轨迹自然不增长。 + 它是给**接车之后**看策略实际跑成什么形状用的,现在就配好,那天直接有图。 +- `goal_path` **现在就有效**:发一个目标就会立刻出现一条 `(0,0) → (3,0)` 的直线, + 换目标时这条线跟着变。这是没有载体时唯一能看出"它瞄准哪里"的路径类显示。 +- 目标相关的两个显示(`goal_path`、`/goal_pose`)都需要**先发目标**才出现: + `ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0"` + +#### 不显示时按顺序查 + +| 现象 | 原因 | +|---|---| +| 什么都没画出来 | Fixed Frame 不是 `odom`,或 TF 树没建起来 | +| Marker 不显示、Path 正常 | Marker 的坐标系是 `odin1_base_link`,需要驱动发 `odom → odin1_base_link`(`send_odom_baselink_tf: 1`)。查:`ros2 run tf2_ros tf2_echo odom odin1_base_link` | +| Marker 时隐时现 | odom 时间戳来自**设备时钟**(本机 `use_host_ros_time: 0`),与墙钟差很远时 rviz 的 TF 缓存窗口会吃不消。把 TF 的 `Cache Length` 调大,或改用 `Path`/`Odometry` 这类不依赖逐帧 TF 的显示 | +| `twist_cmd_marker` 一直不动 | 它是**在推理分支里**发的(`generate_cmd_vel`)—— 没发目标时该分支不执行,自然没有这个 marker。这与 `/cmd_vel` 的签名一致(见 §8) | + +--- + +### 6.4 🎯 目标朝向:到点后原地自转对准(ROS 2 新增) + +#### 为什么需要单独做 + +策略**无法表达目标朝向**: + +- 观测 16 维 = 线速度3 + 角速度3 + 重力3 + 上一动作3 + 目标向量4,目标向量只是 + **body 系单位方向 + log 距离**,没有"期望朝向"这一维; +- 到达判定是 `‖target_xy − robot_xy‖ ≤ 0.75`,**只看位置**; +- `target_position_callback` 只读 `pose.position`,**从不读 `pose.orientation`** + —— 所以往 `/goal_pose` 里塞姿态四元数是没用的,会被静默忽略。 + +⇒ 朝向只能由本包自己在"位置已到达"之后补一个**原地自转阶段**。 + +#### 怎么用 + +朝向走**独立话题**(位置发 `/goal_pose`、朝向发 `/goal_yaw`),语义无歧义、且完全向后兼容: + +```bash +# 位姿 + 朝向一起发:位置在 odom 系,朝向是弧度(0 = odom +X,逆时针为正) +ros2 topic pub --once /goal_pose geometry_msgs/msg/PoseStamped \ + '{header: {frame_id: odom}, pose: {position: {x: 3.0, y: 0.0}}}' +ros2 topic pub --once /goal_yaw std_msgs/msg/Float64 '{data: 1.5708}' # 90 度 +ros2 topic pub --once /goal_yaw std_msgs/msg/Float64 '{data: .nan}' # 取消朝向要求 +``` + +用 runner 更省事 —— **第 4 个数就是 yaw(弧度)**,省略就表示该点不需要朝向: + +```bash +# 只有最后一个路点要求朝向:前面的只给 x,y +ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708" + +# 纯"原地转到 90 度":把目标点设在自己当前位置上再给个 yaw 即可 +ros2 run sru_nav_ros2 waypoint_runner --waypoints "0,0,0,1.5708" --no-return-home +``` + +> runner 启动时会把每个路点的 yaw **同时按弧度和角度**打印出来 +> (`yaw=1.5708 rad (90.0 deg)`),一眼就能看出单位写错。 + +#### 内部怎么实现的(`navigation_policy_node.py`) + +| 环节 | 位置 | +|---|---| +| 接收朝向 | `goal_yaw_callback`:`NaN` → 清空要求;否则归一化到 `(-π, π]` | +| 新目标自动清空朝向 | `target_position_callback` 里 `_is_new_goal_position()`:**位置变了**才清(runner 每 5 s 重发同一目标不会打断自转) | +| 是否还需要自转 | `_yaw_stage_pending()`:无副作用谓词,`goal_yaw_w` 存在 + 位置已到达 | +| 自转控制器 | `update_goal_yaw()`:**独立 20 Hz 定时器**,用 odom 时间计 dt | +| 结束/超时 | `_finish_yaw_alignment()`:打印残余误差与耗时,发一次零速,释放目标 | + +**为什么必须是独立定时器**:`generate_cmd_vel` 只被 `depth_callback` 调用、且被 +`control_frequency` 门控,实测**只有 ~1.5 Hz**(每步 0.66 s,0.6 rad/s 就是 **19°/步**)—— +用它自转必然来回摆。所以自转走自己的 20 Hz 定时器,并且: + +- `generate_cmd_vel` 的"已到达"分支在自转期间**不发零速**(否则会和自转的 ω 抢 `/cmd_vel`)、 + 也**不释放目标**,只打印 `Position reached; aligning to the goal heading ...` +- 自转期间**仍然尊重 deadman**:`require_joystick: true` 且手柄超时 → 立即放弃自转并停 + +**控制律("精准"是这几条凑出来的)** + +1. 误差**绕最短方向**回绕到 `(-π, π]` +2. **制动曲线**:`|ω| = min(max_rate, sqrt(2·decel·|error|))` —— 远处全速,近了自动减速,**从根上避免过冲** +3. **死区 + 稳定判定**:进入容差后还要连续保持 `goal_yaw_settle_time` 才判成功 +4. **超时保护**:`goal_yaw_timeout` 到点就放弃并打印残余误差(不会无限打转) +5. 最终误差与耗时打进日志:`Goal heading aligned: residual error 1.83 deg (took 2.4s)` + +#### ⚠️ 精度能到多少 + +容差默认 **±5°**,实测能到多少取决于三件事,**都要接车后标定**: + +| 限制 | 说明 | +|---|---| +| odom 偏航精度 | 这是**地板**:只能做到"按 Odin1 报的姿态对准" | +| 底盘 yaw 死区 / 最小可转速度 | 若底盘转不了那么慢,就得放宽容差或加大 `goal_yaw_settle_time` | +| 20 Hz 离散化 | 在 ±5° 处 `ω ≈ 0.37 rad/s`,每步转 1.07°,相对 5° 带宽很小 ⇒ 通常落在 1–3° | + +调参方向:容差不够小 → 降 `goal_yaw_tolerance`;过冲 → 减小 `goal_yaw_max_rate` 或减小 `goal_yaw_decel`; +抖 → 加大 `goal_yaw_settle_time`。 + +#### ⚠️⚠️ 想铺"密集路点"必须先解决这个冲突(很重要) + +**如果路点间距 ≤ 0.75 m,机器人会一条速度都不发、原地不动。** 原因很硬: + +- 节点用 `ARRIVE_GOAL_THRESHOLD = 0.75 m` 判到达(`_check_goal_reached`),一旦到达就**发零速并释放目标**; +- 新目标如果本来就落在 0.75 m 内,**发布的那一刻就已经"到达"** ⇒ 走"已到达"分支 ⇒ 不动。 + +由此推出:**每跳实际推进量 = 间距 − 0.75 m**。 + +| 间距 | 实际情况 | +|---|---| +| ≤ 0.75 m | **完全不动** | +| 1.0 m | 每跳只走 0.25 m;外加 runner 每跳 `settle_time = 1.5 s` 的静止等待 ⇒ 极慢 | +| 2.0 m | 每跳走 1.25 m,可用但偏碎 | +| **3–5 m** | ✅ 推荐:既有"面包屑"的引导效果,又不被阈值和静置时间吃掉 | + +> 参考:**训练侧的到达阈值是 0.5 m**(`isaaclab_nav_task/.../mdp/terminations.py:132`), +> 部署蓝本用的 0.75 m 更松。所以想把路点铺到 1 m 以内,就得把节点的 +> `ARRIVE_GOAL_THRESHOLD` 降到 0.5 并同步 runner 的 `--arrive-threshold` 0.5 +> —— **那是对文档 §5「绝对不能改」清单的改动**,需要明确拍板,不能顺手改。 + +给反应式策略铺面包屑**思路本身是对的**(它没有全局规划,面包屑相当于一个稀疏的引导), +但要按上面的间距来,否则会适得其反。 + +#### 无载体自测(只有 Odin1、没有底盘时怎么验) + +**两个前提事实**: + +1. 自转阶段**只需要 odom,不需要深度**。它读的是 `robot_orientation_w` / `robot_odom_time` / + `robot_pos_w`,全部来自 `/odin1/odometry_highfreq`。所以**不必先开 `senddepth`**。 + (对照:策略推理那条链必须有深度,见 §2.5。) +2. 这个控制器是个**纯反馈环,反馈量就是 odom 的偏航角**。所以你可以**用手转动 Odin1**, + 让环闭合 —— 这能验证除底盘之外的所有环节。 + +**步骤** + +```bash +# ① 驱动先起(只要 odom 有数据即可),确认"转动传感器时姿态真的会变" +ros2 topic echo /odin1/odometry_highfreq --field pose.pose.orientation +# ⚠️ 用手转一圈,四元数必须跟着变。若不变,后面的就不用测了(反馈量是死的)。 + +# ② 起控制器:必须 require_joystick:=false,否则 deadman 会立刻中断自转;不需要手柄 +source /opt/ros/humble/setup.bash && source ~/sru_ws/venv/bin/activate +source ~/sru_ws/install/setup.bash +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false + +# ③ 另开终端:发"原地转到 90°" +# 位置用当前点即可(距原点几厘米 < 0.75 m,会立刻判定"位置已到达") +ros2 topic pub --once /goal_pose geometry_msgs/msg/PoseStamped \ + "{header: {frame_id: odom}, pose: {position: {x: 0.0, y: 0.0}}}" +ros2 topic pub --once --qos-durability transient_local \ + /goal_yaw std_msgs/msg/Float64 "{data: 1.5708}" + +# ④ 观察指令 +ros2 topic echo /cmd_vel +``` + +⚠️ ④ 里的 `--qos-durability transient_local` **不能省**:节点是 TRANSIENT_LOCAL 订阅者, +而 `ros2 topic pub` 默认是 VOLATILE 发布者 —— **这是不兼容组合,消息会被静默丢弃** +(和 §2.5 开头那条"BEST_EFFORT 发布端 + RELIABLE 订阅端"是同一类坑,方向相反)。用 `waypoint_runner` 则不用管,它本来就是对的。 + +**该看到什么** + +1. 节点日志:`Received goal heading: 1.5708 rad (90.0 deg)`,紧接着 + `Goal heading stage: rotating in place to 90.0 deg (tolerance 5.0 deg, max rate 0.60 rad/s)` +2. `/cmd_vel` 上 `linear.x = linear.y = 0`(纯自转),`angular.z` 非零。 + **符号**告诉你要往哪边转(CCW 为正);**大小**服从制动曲线: + 90° 时 `min(0.6, √(2×0.8×1.5708)) = 0.6 rad/s`(满速) +3. **用手朝着那个方向慢慢转传感器**,你会看到 `|angular.z|` 随误差减小而**逐渐下降** + (5° → ≈0.374;1° → ≈0.167)—— 这证明制动曲线在工作 +4. 进到 5° 以内并保持 0.4 s,日志出现 + `Goal heading aligned: residual error X.XX deg (took Y.Ys)`,随后 `Target position reset.` + +**顺带验证超时兜底**:发个目标朝向然后**什么都别动**,15 s 后应看到 +`Goal heading not reached within 15.0s (residual ...); giving up.` + `Goal heading abandoned`。 + +**只有 Odin 能验 / 不能验** + +| | 项 | +|---|---| +| ✅ 能验 | 话题链路、`NaN` 语义、新目标清空朝向、自转阶段触发、**转向符号**、制动曲线数值、settle 判定、结束残差日志、超时兜底 | +| ❌ 不能验 | 最终能到几度、会不会过冲、底盘 yaw 死区支持多小的容差 —— **手转只是"近似底盘",能验逻辑不能替代标定** | + +#### 不生效时怎么查 + +| 现象 | 原因 | +|---|---| +| 位置到了但完全不转 | ① 没发 `/goal_yaw`(或发了 `NaN`);② 日志里没有 `Received goal heading` ⇒ 话题名不一致;③ `require_joystick: true` 但手柄 deadman 超时 → 会打印 `Joystick timeout during goal-heading alignment` | +| runner 不推进到下一个路点 | 这是**设计如此**:带 yaw 的路点要等朝向收敛才算 ARRIVED。看它的 `yaw_err=` 有没有停在 5° 以内 | +| 转到位了但一直不结束 | 看向日志有没有 `Goal heading aligned`;没有的话多半是底盘死区太大,误差卡在容差外,等 `goal_yaw_timeout` 后放弃 | +| 日志报 `Goal heading abandoned` | 超时或被 deadman/abort 打断,会打印残余误差,据此判断是容差太严还是底盘转不动 | + +--- + +## 7. `/cmd_vel` 桥(机型无关) + +本包只发布 `geometry_msgs/msg/Twist`,不绑定任何机型: + +| 平台 | 桥方案 | +|---|---| +| Unitree Go2 / B2 / B2W | `unitree_ros2` 官方包,或自写一个订阅 `/cmd_vel` 的 sport_mode 桥 | +| 其它腿足 / 轮式 | 厂商 SDK 自写订阅节点 | +| 纯 ROS 2 仿真 | 直接订阅 `/cmd_vel`,无需桥 | + +**上机前先确认**:`sru_nav_node` 被杀掉后,你的桥是否会自动归零(取决于桥的实现)。 + +--- + +## 8. 排错速查 + +| 现象 | 排查方向 | +|---|---| +| `ModuleNotFoundError: No module named 'onnxruntime'` | venv 的 activate 里缺 `PYTHONPATH` 追加那一行(§2.3)。注意入口脚本 shebang 永远是 `#!/usr/bin/python3`,靠 PYTHONPATH 桥接 | +| `ModuleNotFoundError: No module named 'cv_bridge'` | `PYTHONPATH` 被**覆盖**写法冲掉了 ROS 路径(§2.3)。必须是 `${PYTHONPATH:+:$PYTHONPATH}` 追加式 | +| `import cv_bridge` 报符号错误 / `_ARRAY_API not found` / `import cv2` 段错误 | venv 的 activate 里缺 `PYTHONNOUSERSITE=1`;或 `~/.local` 里装了 pip 版 `opencv-python`(卸掉) | +| `colcon build` 报 `Could not find a package configuration file provided by "catkin"` | `reference/` 或 `venv/` 里缺 `COLCON_IGNORE`(§2.4) | +| **`ros2 topic list` 里有 `/odin1/...` 却收不到数据** | 用 **`ros2 topic hz `** 判断。⚠️ `topic list` 只代表"存在端点";连 `topic info` 的 `Publisher count: 1` 也不算数 —— 驱动启动时就把 publisher 建好了,没数据时它照样是 1(§2.5) | +| `hz` 报 `does not appear to be published yet` | 见下三行。这一条就是"真的没有数据"的判据 | +| 深度话题没有数据(第 1 种原因) | `senddepth` 还是 `0`;此时 `pcd2depth_ros2_node` 打印 "Depth image will not be published." 后**直接 `return 0` 退出**(`pcd2depth_ros2.cpp:164`)。另外确认 `pcd2depth_ros2_node` 真的在跑:`ros2 node list` 应能看到它 | +| 深度话题没有数据(第 2 种原因) | `sendrgb` 还是 `0` → `/odin1/image` 不产出 → 深度节点的 `message_filters` 同步需要 **`cloud_raw` + `image` 一对**(`depth_image_ros2_node.cpp:40-44`),只来一半则回调永不触发 | +| **深度话题没有数据(第 3 种原因,最易漏)** | **`senddtof` 还是 `0`** → `/odin1/cloud_raw` 不产出(即使 `senddepth`/`sendrgb` 都开了,也还是只来一半)。`senddtof` 定义是 `/* send raw cloud data */`(`host_sdk_sample.h:2152`),在设备端关流 + 主循环双重门控(`.cpp:1950` / `.cpp:1057`)。**判据**:设备状态日志里 `dtof_tx_odr ≈ 10` 但 `dtof_rx_odr = 0.00` | +| **`ros2 topic hz` 在 `/odin1/image` 上显示极低(如 0.3 Hz),但数据其实正常** | 测量假象。`/odin1/image` 是 1600×1296 bgr8 ≈ **6.2 MB/帧**,发布端 RELIABLE + 小队列,Python 订阅者跟不上会拖慢发布端。**用 §2.5.1 的 `dev_status.csv` 交叉验证**(`rgb_rx_odr = 10.2`),别据此判定故障。⚠️ **深度话题不适用这条**:它是 228×185(≈165 KiB),`hz` 可信 | +| 想知道某路数据到底通没通 | 读驱动自己写的设备状态日志(§2.5.1):`*_rx_odr = 0.00` 就是没通,且能一眼看出是哪个 `send*` 开关 | +| 改了 `control_command.yaml` 但毫无变化 | **改错文件了**。驱动用 `get_package_source_directory()`(从编译期 `__FILE__` 向上找 `package.xml`)读配置,本机实际读的是 **`~/catkin_ws/src/odin_ros_driver/config/control_command.yaml`**,不是 `install/` 里那份。改完还要**整体重启驱动**(`register_keys` 是启动时下发给设备的) | +| `waypoint_runner` 报 `No odometry received ... within 30.0s` | 驱动没起,或该话题没有发布者。**这是蓝本原始设计**(等不到 odom 就退出),不是 bug;先按 §2.5 起驱动 | +| 节点启动后一直刷 `Odometry not ready, skipping depth callback` | `/odin1/odometry_highfreq` 是否在跑;`odom_topic` 参数是否与实际话题名一致 | +| **`/cmd_vel` 一条都没有,且日志里连 `cmd_vel_ratio:` / `Published cmd_vel:` 都不出现** | **深度没到**(本特性签名,见 §2.5 第 0 节)。`generate_cmd_vel()` 只由 `depth_callback()` 触发,与 ROS 1 蓝本一致;先按 §2.5 把深度打通,不要把时间花在本包代码上 | +| **`/cmd_vel` 有输出但全是 0**(情形 1:最常见) | **根本没发目标**。没有目标时 `_check_goal_reached(None, ...)` 返回 `True`,节点走"已到达"分支、发零速并(未节流地)刷 `Target position reset.` —— 这是蓝本的原始设计(ROS 1 那边逐行相同),不是故障。发个目标即可:`ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0"` | +| **节点日志里某个参数值和你改的 YAML 不一致** | 该键同时被 launch 参数覆盖了。ROS 2 里 `parameters` 列表**后者胜**,硬编码的 launch 默认值会静默盖掉 YAML。本包已让 `odom_twist_in_base_frame` / `require_joystick` 的 launch 默认值**从 YAML 读取**(`_yaml_default()`),若仍不一致就检查是否在命令行传了 `:=` 覆盖 | +| **`/cmd_vel` 有输出但全是 0**(情形 2) | 其它原因:① 手柄 deadman(`axes[4]` 必须推过 0;`require_joystick:=false` 先旁路);② `odom_twist_in_base_frame` 判反;③ **deadman 时钟不同源**(见 §11 第 8 项);④ 目标距离 < `ARRIVE_GOAL_THRESHOLD`(0.75 m)→ 立刻判定"已到达" | +| **启动就崩:`AttributeError: 'NavigationPolicyNode' object has no attribute 'xxx_publisher'`**(或 `NameError: name 'Path' is not defined`) | 这是**代码与运行版本不一致**,不是逻辑错。依次查:① 是不是改了源码却没**重启 launch**(改 `.py` 本来就免 `colcon build`,但进程必须重启才会加载新代码);② 确认改动**真的落盘**:`grep -n "xxx_publisher" src/sru_nav_ros2/sru_nav_ros2/navigation_policy_node.py`;③ `build/sru_nav_ros2/sru_nav_ros2/` 是指向源码的**目录级符号链接**(`readlink -f` 可验证),所以它看到的就是源码内容,不需要重建 | +| **铺了"密集路点"但机器人一步都不走** | 路点间距 ≤ `ARRIVE_GOAL_THRESHOLD`(0.75 m)时,新目标**发布即判定到达** ⇒ 走"已到达"分支发零速。**间距必须明显大于 0.75 m**(推荐 3–5 m)。详见 §6.4 末尾 | +| 位置到了但不自转对准朝向 | 见 §6.4 的排错表(没发 `/goal_yaw`、话题名不一致、deadman 超时、或容差比底盘死区还小) | +| 订阅了但收不到深度,且不报错 | **QoS 不匹配**。ROS 2 里 BEST_EFFORT 发布端 + RELIABLE 订阅端 = 静默收不到。深度默认用 BEST_EFFORT(与两种发布端都兼容);用 `ros2 topic info -v` 对比两端 | +| 发了 `/goal_pose` 但机器人没反应 | `frame_id` 与 odom 的 `header.frame_id` 不一致,节点会直接打 error 拒绝 | +| Twist 数值剧烈震荡 | ① `policy_scale` 太大;② `odom_twist_in_base_frame` 判反;③ 深度 NaN 没被过滤 | +| Jetson 上 pip 报 `certificate is not yet valid` | 板子无 RTC 电池导致系统时间回退。`date` 看一下,然后 `sudo timedatectl set-ntp true` | + +--- + +## 9. 应急停止 + +| 手段 | 操作 | +|---|---| +| 手柄放弃当前目标 | 按 `BUTTON_ABORT`(默认 button index 9)→ 立刻发零速并放弃当前目标 | +| 杀掉导航节点 | `Ctrl+C` 停 `sru_nav_node` → `/cmd_vel` 不再有发布者(**取决于桥的行为,上机前先确认**) | +| 物理断电 | 终极手段 | + +**首次上机务必抬轮 / 架空**,确认 `/cmd_vel` 数值有界合理后再落地。 + +--- + +## 10. 与 ROS 1 蓝本的差异 / 没有移植的东西 + +**逐点改名 / 改写(必须记住的 5 条)** + +1. `use_sim` → **`odom_twist_in_base_frame`**(旧名极易与 ROS 2 内置的 `use_sim_time` 混淆)。 + ⚠️ 默认值也从 `false` 改成了 **`true`**,依据见 §11 第 3 项 +2. 时间戳字段 `secs/nsecs` → **`sec/nanosec`**。该值喂给控制频率门控,改错会导致推理频率失控 +3. 深度订阅默认用 **BEST_EFFORT**(驱动实测为 RELIABLE 发布端,但 BEST_EFFORT 订阅端与两种发布端 + 都兼容,作为默认更安全) +4. 私有话题 `~x` → **`~/x`** +5. **静态 TF 的方向反过来了**:蓝本是 `base_link → odin1_base_link`,本包是 + **`odin1_base_link → base_link`**。因为驱动自己会发 `odom → odin1_base_link`, + 只有这样 TF 树才完整;照抄蓝本会让 `odin1_base_link` 有两个父节点。详见 §3 + +**新增(蓝本没有的东西,都是加法,不影响任何控制行为)** + +- `~/vis/executed_path` 与 `~/vis/goal_path`(`nav_msgs/Path`,1 Hz)—— 供 rviz 画出实际轨迹与 + "当前位置→目标"的直线。**蓝本一个路径话题都没有**(它的策略是端到端反应式的,本来就没有规划路径)。 + 实现在 `visualization.py::publish_executed_path` / `publish_goal_path`, + 周期常量也在那里(`PATH_PUBLISH_INTERVAL` / `PATH_MAX_POINTS`),**刻意没有放进 A 类原样的 + `constants.py`**,以保持那个文件与蓝本逐字节一致。配法见 §6.3。 +- **目标朝向 / 到点后原地自转**(`/goal_yaw` 话题 + 7 个 `goal_yaw_*` 参数 + 一个 20 Hz 定时器)。 + 蓝本**完全没有朝向概念**(到达只看 XY 距离,`pose.orientation` 从不被读取),所以这是一条新增链路。 + 关键设计取舍:自转**不挂在 `generate_cmd_vel` 上**,因为它只有 ~1.5 Hz,做不了精确对准。见 §6.4。 + **未发布 `/goal_yaw` 时整条链路休眠,行为与蓝本一致。** + +**驱动侧的坑(不属于本包,但会直接决定本包能不能跑起来)**:见 §2.5。四条要点: +驱动读的是**源码树**里的 `control_command.yaml`(`__FILE__` 反推,`install/` 那份无效); +`senddtof`(`/odin1/cloud_raw`)、`senddepth`、`sendrgb`(`/odin1/image`)**三个键都要开**; +判断数据看驱动自己的 `dev_status.csv`(§2.5.1),`topic info` 的结点计数不算数、 +`topic hz` 对大图会偏低; + +**没有移植的三样东西**(它们是 ROS 1 + conda 时代的历史包袱,在 ROS 2 下不存在): + +- `Deployment/scripts/setup_conda_env.sh` —— ROS 2 用系统 python3.10,不需要 conda +- `Deployment/scripts/launch_sru_nav.sh` —— 它做的三件事(注入 `PYTHONPATH=/opt/ros/noetic/...`、 + 用 `LD_PRELOAD` 修 conda libffi 与系统 libp11-kit 的 ABI 冲突、检查 catkin wrapper 的 shebang) + 在 ROS 2 下**全都不需要** +- `Deployment/scripts/verify_port.sh` —— ROS 1 专属自检脚本 + +顺带一提:ROS 1 README 里列的常见故障,有多条在 ROS 2 下自动消失(conda↔系统 ROS 的 ABI 冲突、 +`PYTHONPATH` 手工注入、catkin 锁 `PYTHON_EXECUTABLE` 导致的 shebang 陷阱)。 + +**因此本包的 shebang 问题换了个形式出现**:不再是 catkin 锁死 shebang,而是 ROS 2 工具链 +硬编码 `#!/usr/bin/python3`(§2.3)。这是本次移植新增的坑,已验证并解决。 + +--- + +## 11. 存疑项状态(8 项,其中 4 项已解决) + +改完只需要动 `config/sru_nav.yaml` 或 launch 参数,**不需要改代码**。 + +### ✅ 已解决(有实证;代码与配置已按结论设好) + +| # | 项目 | 结论 | 证据 | +|---|---|---|---| +| 1 | Odin1 深度话题名 | **`/odin1/depth_img_competetion` 正确** | `odin_ros_driver/src/depth_image_ros2_node.cpp:27` —— 它是 `depth_image_topic` 参数的**默认值**;Rc2026 工程引用 38 处。主线文档查不到它,只是因为它属于 `pcd2depth` 深度节点。⚠️ 但驱动默认 `senddepth: 0`,必须手动打开(见 §2.5) | +| 2 | 深度 / odom 的 QoS | **两者的发布端都是 RELIABLE**。本包的 `odom_qos_reliable: true` 与驱动完全匹配;深度默认 BEST_EFFORT,与 RELIABLE 发布端兼容 | 驱动源码:`host_sdk_sample.h:1928` `qos_sensor = QoS(5).reliability(RELIABLE)`;`:1937` `odom_highfreq` 用 `qos_small = QoS(4000).reliability(RELIABLE)`;`depth_image_ros2_node.cpp:49` 经 `image_transport` 落到 `rmw_qos_profile_default`(= RELIABLE, depth 10)。Rc2026 用 RELIABLE 订阅深度是旁证 | +| 3 | odom 的 twist 是 world 还是 body 系 | **body 系 → `odom_twist_in_base_frame: true`** | `vehicle_driver/script/calib/calib_chassis_speed.py`:`twist.twist.linear.x/y -> linear velocity (odin1_base_link frame)`,并注明 *"odin1 velocity is in odin1_base_link frame"*。**默认值已从 `false` 改为 `true`** | +| 4 | odom 的 `header.frame_id` | **`odom`**,`child_frame_id` 是 `odin1_base_link` | 驱动配置 `send_odom_baselink_tf: 1`(注释「odom → base_link 的 TF 广播」)+ Rc2026 的 TF 树。`waypoint_runner` 的默认 `frame_id: odom` 正好对上 | + +### ⏳ 仍需上机实测 + +| # | 项目 | 现状 | 怎么测 | +|---|---|---|---| +| 5 | Odin1 装订外参 xyz / rpy | 默认值已换成 **Rc2026 R2 比赛车的实测装订**(`base_link` 在 `odin1_base_link` 下:`-0.268846, 0.028504, 0.067861, 0.017828, 0.245433, 0`)。**这不是你的载体,接车后必须重测** | 尺子量,或 `ros2 run tf2_ros tf2_echo odin1_base_link base_link`;更规范的做法是参考工程那样做**原地慢转圆拟合**(他们用 `calib_odin_mount.py`)。launch 参数 `base_link_*` | +| 6 | `/joy` 轴与键索引 | 沿用 `constants.py` 的 PS5 映射 | **参考工程帮不上 —— 它是全自动车,整个工程完全没有 `/joy`。** 用 `ros2 topic echo /joy` 逐个推,改 17 个 `joy_axis_*` / `joy_button_*` 参数 | +| 7 | 推理能否跟上 5 Hz | `control_frequency: 5.0` | **⚠️ 已有不利实测**:深度链路打通后,`ros2 topic hz /cmd_vel` 只有 **1.4–1.7 Hz**(`min: 0.198 s` 说明 0.2 s 门控本身正常、5 Hz 是能达到的,只是**输入来得不够快**)。
**已排除"本节点算不过来"**:`sru_nav_node` 累计 CPU 仅 47 s / 约 419 s ≈ **11%**,即 89% 时间在空等;且深度图只有 228×185(≈165 KiB),不是大消息。
⇒ 瓶颈在**上游 `pcd2depth_ros2_node` 的产出率**(它是全机最忙的进程,累计 CPU 398 s / 约 1160 s ≈ **34%**)。
**待查**:`pcd2depth` 用 `ApproximateTime(10)` 同步 `{/odin1/cloud_raw, /odin1/image}`,而 `/odin1/image` 是 6.2 MB 的大图 —— 若它到达深度节点的速率本身很低,同步器就只能按最慢那路出图。用 `ros2 bag record`(C++ 消费者)+ `ros2 bag info` 量真实产出率来定论。
**注意**:`depth_callback` 是**先做完整预处理再判频率门控**(蓝本原样保留,未改)—— 但既然本节点 CPU 只用了 11%,**优化这段预处理解决不了问题** | +| **8** | **deadman 的时钟是否同源** | ⚠️ **本机不同源**:驱动配置是 `use_host_ros_time: 0`,即 odom 时间戳来自 **Odin 设备内部时钟**,与主机墙钟不是同一基准(我们先前依据 Rc2026 的配置误判为 `1`,已更正) | 判断式是 `robot_odom_time − time.time() > 15.0`,两个时间域混算。后果两极:odom 时间远大于墙钟 → 立刻超时、`/cmd_vel` 恒为 0;远小于 → 差值恒负、**deadman 失效**(更危险)。**关掉 `require_joystick` 时这段逻辑不执行,所以无载体测试不受影响。** 开手柄前需处理:把 `use_host_ros_time` 改成 `1`(主机 ROS 时间)或 `2`(对齐到主机时间轴)后重启驱动 | + +### 一个仍需留意的残余量(仅记录,未新增功能) + +`odom_twist_in_base_frame: true` 让 twist 直接透传,但 Odin1 若带俯仰角安装,`odin1_base_link` 是**倾斜**的: +`linear.x` 会被乘上约 `cos(pitch)`,并出现一点虚假的 `linear.z`。Rc2026 也是这么接受的 +(同一处注释:*"If the Odin mounting orientation matches the chassis forward direction, ... Otherwise an +extra rotation compensation is needed."*)。要精确补偿需要装订外参(即一次 TF 查询),属于新增功能,本次未做。 + +--- + +## 11.1 已定位:速率瓶颈在驱动侧(`/cmd_vel` 1.4–1.7 Hz ← 深度 1.85 Hz) + +**已知事实**(2026-09-24 实测): + +| 事实 | 数值 | 推论 | +|---|---|---| +| `ros2 topic hz /cmd_vel` | **1.4–1.7 Hz**,`min: 0.198 s` | 0.2 s 门控本身正常、**5 Hz 是能达到的**,是**输入不够快** | +| `sru_nav_node` 平均 CPU | 47 s / 约 419 s ≈ **11%** | **本节点 89% 时间在空等** ⇒ 优化 `depth_callback` 的预处理**没用** | +| 深度图体积 | 1600/7 × 1296/7 = **228×185 32FC1 ≈ 165 KiB** | 不是大消息 ⇒ 深度话题的 `hz` **可信**,且本节点不可能被它压垮 | +| `pcd2depth_ros2_node` 平均 CPU | 398 s / 约 1160 s ≈ **34%** | 全机最忙的进程,**瓶颈嫌疑最大** | + +> 体积的推导链(source 级):`pointcloud_depth_converter.cpp:27-28` 用 +> `scaled_w/h = image_w/h / scale`;`depth_image_ros2_node.cpp:74` 的 `scale` 默认 **7.0**; +> 而 `pcd2depth_ros2.cpp:196-215` 构造节点时的 `params_override` **只含 `cam_0.*` 与 `Tcl_0`, +> 没有 `scale`** ⇒ 默认值生效。(标定是它自己读 `calib.yaml` 后注入的,不是 `--params-file`。) + +**下一步:先跑这一条(不需要 bag,最便宜)** + +```bash +ros2 topic hz /odin1/depth_img_competetion +``` + +**已测(2026-09-24 14:42)**:**≈ 1.85 Hz**,`min: 0.079 s`(会突发到 ~12.6 Hz)、`max: 5.101 s`。 +这是"配对上来就连出一串、配不上就长时间空档"的**饥饿模式**。 + +⚠️ **两次测量(一次本节点缺席、一次在场)都是同一量级**: + +| 时刻 | 深度话题 `hz` | `sru_nav_node` | 备注 | +|---|---|---|---| +| 14:30 | (未直接测) | **在跑** | 同期 `/cmd_vel` ≈ **1.4–1.7 Hz** | +| 14:42 | **≈ 1.85 Hz**(18 s 窗口,仍在上升) | 已停(14:37:38 Ctrl-C) | `Subscription count = 0` | +| 14:49 | **≈ 1.16 Hz**(147 s / 171 条) | **在跑** | | + +**"是不是本节点把深度拖慢了?"——不是,有两条独立理由:** + +1. **函数下界论证**(只用已有数据):`/cmd_vel` 只由 `generate_cmd_vel()` 发布,而它**只**被 + `depth_callback()` 调用(与 ROS 1 蓝本一致,两边各只有 1 处调用点)。 + ⇒ **`/cmd_vel` 的速率必然是深度速率的函数下界**:某时刻 `/cmd_vel = X Hz` ⇒ 同时刻深度 ≥ X Hz。 + 14:30 测到 `/cmd_vel` ≈ 1.4–1.7 Hz **且当时本节点在跑** ⇒ **当时深度 ≥ 1.7 Hz**, + 与"本节点缺席时的 1.85 Hz"**同档**。⇒ 本节点在场并未把深度压下去。 + 1.16 Hz 与 1.85 Hz 的差别是**这个流自身的 run-to-run 波动**。 +2. **机理上也不该有影响**:本节点的深度订阅是 **BEST_EFFORT**(`qos_profile_sensor_data`)。 + DDS 的反压(等 ACK)只对**同为 RELIABLE** 的读者成立,BEST_EFFORT 读者不回 ACK、不阻塞发布端。 + 而深度发布端本来也只有它一个常驻消费者(overlay / reprojection 都因 `send*: 0` 关着)。 + +另外 **CPU 争抢也排除**:`load average ≈ 3.0`,机器远未跑满;本节点平均只占 **11% 单核**。 + +⇒ **结论:深度话题自身在 1.2–1.9 Hz 之间波动,瓶颈在驱动侧;本节点只是如实转发上游速率。** + +**`pcd2depth_ros2_node` 的日志在哪** + +1. **终端**:你跑 `ros2 launch odin_ros_driver odin1_ros2.launch.py` 的那个终端,行前缀 `[pcd2depth_ros2_node-N]`。 +2. **落盘(更保险,每个进程一个文件)**: + ```bash + ls -lt ~/.ros/log/pcd2depth_ros2_node_*.log | head -3 # 最新的在最前 + tail -40 "$(ls -1t ~/.ros/log/pcd2depth_ros2_node_*.log | head -1)" + ``` + +**它实际打印了什么(14:20 那次,已核对)** + +``` +Package path: /home/kevin/catkin_ws/src/odin_ros_driver +Loading config from: /home/kevin/catkin_ws/src/odin_ros_driver/config/control_command.yaml ← 源码树配置的运行期实证 +Found calib.yaml file! Loading parameters... +Image size: 1600x1296 +Scale: 7.000000, Point sampling rate: 5 ← scale=7.0 运行期确认 ⇒ 深度图 228x185 +DepthImageRos2Node initialized successfully +``` + +**没有任何 `Empty point cloud received` / `Data processing failed`** ⇒ 同步器**不是配对失败**, +而是"喂进来的就这么慢"。 + +> 另注:`ros2 node list` 里会出现**两次** `/pcd2depth_ros2_node`,这不是两个实例 —— +> `/odin1/image` 的 `Subscription count = 1`、深度话题 `Publisher count = 1` 可以证伪。 +> 原因是 launch 的 `name='pcd2depth_ros2_node'` 生成 `-r __node:=...`,**同一进程里的助手节点也被一起重映射了**, +> 于是同进程出现两个同名节点对象 —— launch 日志里那句 +> `Publisher already registered for provided node name` 说的正是这个,属良性。 + +**最省的一步:量出同步器的"另一路"——已测,两路都慢** + +```bash +ros2 topic hz /odin1/cloud_raw # 已测:≈ 1.3 Hz(min 0.096 s / max 1.76 s) +``` + +**全链路实测对照(这张表就是结论)** + +| 位置 | 速率 | 来源 | +|---|---|---| +| 设备 → `host_sdk`(RGB) | **10.22 Hz** | `dev_status.csv` 的 `rgb_rx_odr` | +| 设备 → `host_sdk`(DTOF 原始云) | **10.26 Hz** | `dev_status.csv` 的 `dtof_rx_odr` | +| `host_sdk` → ROS:`/odin1/cloud_raw` | **≈ 1.3 Hz** | 实测 | +| `host_sdk` → ROS:`/odin1/image` | 很低(Python `hz` 曾读到 0.3 Hz) | 实测 | +| `pcd2depth` → ROS:`/odin1/depth_img_competetion` | **1.16–1.85 Hz** | 实测 | +| 本包 → ROS:`/cmd_vel` | **1.4–1.7 Hz** | 实测 | + +⇒ **设备到主机是 10 Hz,主机到 ROS 订阅者只剩 ~1.3 Hz —— 8 倍的损耗发生在 `host_sdk` 内部到 ROS 的这段。** +而**云(点云,不是 6.2 MB 大图)也只有 1.3 Hz** ⇒ 不能只归因于"RGB 太大"。 + +**两个大消息的实际体积(实测)** + +| 话题 | 体积 | 备注 | +|---|---|---| +| `/odin1/cloud_raw` | **933,888 B ≈ 0.89 MB**(`width: 49152` 点、`point_step: 19`、`height: 1`) | `frame_id: lidar`;`stamp.sec: 4001` = 设备 uptime ⇒ **再证 `use_host_ros_time: 0`** | +| `/odin1/image` | **6.2 MB**(1600×1296 bgr8) | | +| `/odin1/odometry_highfreq` | ~几十字节 × ~400 Hz | 唯一**不受影响**的大频率流 | + +⚠️ **0.89 MB 远不足以压垮 Python 订阅端**(对比 6.2 MB 的 RGB 那个明显假象)—— +⇒ **云的 ~1.5 Hz 是真实速率,不是测量假象**,两路大消息都真的低。 + +### ✅ 已排除:`publishIntensityCloud` 本身跑得动 10 Hz + +读 `host_sdk_sample.h:616-771` 全函数: + +- `publishIntensityCloud()` 由 DTOF 回调每秒调用 10.26 次(`host_sdk.cpp:1058`), + 每帧只做两件轻活:**两个 49152 点的填充循环** + 一个 0.89 MB 的深拷贝入队; +- `cloud_pub_->publish(*msg)` 在 **L767 是无条件执行的**(`if (g_sendcloudrender)` 只包住 + 「入队做 render 用」那段,**不**门控发布); +- 函数内只有 3 个针对**非法数据**的提前 return,没有任何节流 / 频率限制。 + +⇒ **发布函数本身能轻松维持 10 Hz**;而 `dev_status.csv` 的 `dtof_rx_odr = 10.26` +是在**计数器位于 publish 之后**的前提下测到的 —— 说明循环那时确实跑满 10 Hz +(而且那段时间 `pcd2depth` 正在消费)。 + +**⇒ 剩下的唯一解释:样本在 DDS 交付环节丢了**,且只影响那两个用 +**硬编码 `qos_sensor = QoS(5)`** 的大话题(odom 用 `QoS(4000)`,一切正常)。 +与「0.89 MB 不是大消息」这条一起看,最可能是 **RELIABLE + history 只有 5** 的样本淘汰行为。 + +⚠️ **我无法从外部把 DDS 的具体机理钉死** —— 要确认需要**在驱动侧**动手: +在 `publish()` 前后加计数器重编,或者打开 Fast DDS 的日志/统计。 +这已经超出本包范围,也超出"只看不写"的边界。 + +**可以试的驱动侧候选修法(1 行 + 重编)** + +| 改法 | 说明 | +|---|---| +| `host_sdk_sample.h:1928` 的 `QoS(5)` → 更大的 history(如 `QoS(50)`) | 最保守,不破坏 QoS 兼容性。注意内存:RGB 话题 50×6.2 MB ≈ 310 MB,云 50×0.89 ≈ 45 MB | +| 把**发布端与订阅端同时**改成 BEST_EFFORT | 有效但要**成对改**:只把发布端改 BEST_EFFORT 会让现有的 RELIABLE 读者(`pcd2depth`)**静默收不到任何数据**(§2.5 第 1 点的那个 ROS 2 陷阱) | + +⛔ **不要**只把发布端改成 BEST_EFFORT。 + +**机理(与源码对上)**:`host_sdk.cpp` 的接收循环是 + +```cpp +case LIDAR_DT_RAW_DTOF: + if (g_senddtof) { g_ros_object->publishIntensityCloud(...); } // 发布 + ... + update_count(&dtof_rx_fps); // 计数器在发布【之后】 +``` + +`dev_status.csv` 的 10.26 Hz 来自这个**发布之后**的计数器 ⇒ **循环本身跑满 10 Hz、`publish()` 没有阻塞**。 +发布端的 QoS 是 `host_sdk_sample.h:1928` 的 +`qos_sensor = QoS(5).reliability(RELIABLE)` —— **RELIABLE + 只有 5 个样本的 history**。 +样本大(云 MB 级、图 6.2 MB)而读者追不上时,新样本会把还没被取走的旧样本**直接挤掉**, +于是读者只拿到一小部分 ⇒ **1.3 Hz 是"历史被覆盖"的结果,不是发布端在等**。 + +⇒ **瓶颈最可能是"读者太慢"**(`pcd2depth` 的 `message_filters::Subscriber` 是默认 **RELIABLE**, +与发布端配对;而它的 `syncCallback` 每帧要做 `pcl::fromROSMsg` + 投影 + 着色)。 +注意 odom 不受影响,因为它的 history 是 **4000**(`qos_small`)而不是 5。 + +**两条待测** + +1. **云到底多大** —— ✅ 已测:**0.89 MB / 49152 点**(见上表)。结论:**云的 1.5 Hz 是真实的**。 +2. **去掉 `pcd2depth` 的消费** —— 已做:只起 `ros2 run odin_ros_driver host_sdk_sample`, + 结果**仍是 ≈ 1.5 Hz**(2.56 → 1.37 → 1.44)。 + + ⚠️ **两个注意点**(诚实记录,别过度解读这个结果): + - **它无法做到真正的"零消费者"** —— `ros2 topic hz` 命令自己就是一个订阅者。 + 所以这个实验只能排除"**`pcd2depth` 这个读者**",不能排除"**任何读者**"。 + - 你那次粘贴里没有 `ros2 run` 的回显,之后 ROS 图已清空,**我无法回查当时图里是否真的只有 `host_sdk_sample`**。 + 请你确认一下;若只起了它,那么结论就是「**读者不是原因,问题在发布端/DDS 侧**」。 + +**✅ 本包不需要为这个速率做任何改动** + +`control_frequency: 5.0` 在代码里是**上限**(门控 `robot_odom_time - last_run_time < 1/f`), +不是目标值:**输入慢就自然慢,不会算错、不会越界、不会跑飞**。 +所以在 ~1.5 Hz 输入下,本节点只是**以 1.5 Hz 忠实运行**,逻辑与 5 Hz 时完全一致。 +它只影响**策略表现**(训练是 5 Hz),不影响本包代码的正确性。 + +**其它候选原因(并存,供判断)** + +| # | 候选 | 说明 | +|---|---|---| +| a | **读者太慢 + history=5** | 见上。若确认,`scale` / `point_sampling_rate` 调小工作量会让 `pcd2depth` 更快,间接提升深度速率 | +| b | **每帧算法成本** | `syncCallback` 里 `pcl::fromROSMsg` + `transformPointCloud` + `projectCloudToDepth` + `generateColoredCloud`(后者遍历整幅深度图去采 RGB) | +| c | **RGB 6.2 MB 太大** | 它只是用于 `/odin1/depth_img_competetion_cloud` 的着色和输入校验,**本包不消费**;`sendrgbcompressed: 0` 可白省一路(`/odin1/image/compressed` 无人订阅) | + +**降工作量实验**(驱动侧配置,改数据语义,**未做,等用户决定**): + +```yaml +# ~/catkin_ws/src/odin_ros_driver/config/control_command.yaml +scale: 14 # 输出 114x92(默认 7 → 228x185),generateColoredCloud 规模降到 1/4 +# 或 +point_sampling_rate: 10 # 降采样点云(默认 5) +``` + +**第 2 步(可选,更严格):用 C++ 消费者交叉验证** + +```bash +# 前台跑,等约 10 秒后按一次 Ctrl-C(rosbag2 就是为 Ctrl-C 设计的) +rm -rf ~/depthbag && ros2 bag record -o ~/depthbag /odin1/depth_img_competetion +ros2 bag info ~/depthbag # 用 Message count / Duration 手算速率 +``` + +⚠️ 两个实测踩过的坑(都会让 bag **录不出目录**): +1. **后台跑 + 终端设了 `tostop`** ⇒ 进程刚起就被 `SIGTTOU` 停住(显示 `已停止`),bag 目录没建。 + 要么前台跑,要么把输出重定向:`... > ~/bag.log 2>&1 &`。 +2. **`kill -INT %1` 打到陈旧作业**(shell 里有遗留 job 时 `%1` 不是新作业)⇒ 新作业收不到 SIGINT、 + metadata 不写。用 `$!` 拿 PID:`BAGPID=$!; sleep 12; kill -INT $BAGPID; wait $BAGPID`。 +3. 别想当然用 `/tmp`(可能是很小的 tmpfs);写到 `$HOME` 下更稳。 +4. 收尾务必**真正杀掉**遗留录制进程:被 STOP 的 RELIABLE 订阅者不回 ACK, + 可能把 RELIABLE 发布端一起拖住,污染后续所有测量(`pkill -9 -f "bag record"`)。 + +**第 3 步:取 `pcd2depth_ros2_node` 自己的日志(最能说明原因)** + +它启动时会打印 `Image size: ...`、`Scale: ... , Point sampling rate: ...`, +运行中若同步失败会刷 `Empty point cloud received` / `Data processing failed`。 +**这些行就是判断 `ApproximateTime(10)` 为何配对不上的直接证据。** + +**已定位的疑点**:`pcd2depth` 用 `ApproximateTime(10)` 同步 +`{/odin1/cloud_raw, /odin1/image}`,而 `/odin1/image` 是 **6.2 MB、RELIABLE↔RELIABLE** +(`message_filters::Subscriber` 默认 QoS 与 `host_sdk` 的 `qos_sensor` 都是 RELIABLE)—— +同步器的出图速率受限于最慢那一路。若这一路本身就很慢,深度必然慢,且**修法在驱动侧而非本包**。 + diff --git a/sru_ws/src/sru_nav_ros2/docs/HANDOVER_TEAM.md b/sru_ws/src/sru_nav_ros2/docs/HANDOVER_TEAM.md new file mode 100644 index 0000000..e3c51ae --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/docs/HANDOVER_TEAM.md @@ -0,0 +1,569 @@ +# 交接文档:SRU-Odin 无图端到端导航(ROS 2 Humble)→ 迁移到新机器上机实测 + +> **给谁看**:接手移植、并要在我们自己的机器人上做实车测试的人(以及他那边的 AI Agent)。 +> **配套文档**: +> - `DEPLOY_ROS2.md` ← **本包的权威细节**(环境原理、话题契约、排错、存疑项状态,约 1000 行)。本文件是**入门流程 + 交接清单**,细节都在它里面。 +> - `AI_AGENT_PROMPT.md` ← 整段复制给你那边的 AI Agent 用的提示词。 +> +> 读完本文件应该能独立把这套装起来、跑起来、并对"什么已验证 / 什么没验证"心里有数。 + +--- + +## 0. 这个包是什么 + +把 SRU-Odin(ManifoldTech 的 Odin1 空间记忆传感器 + ETH RSL 的 SRU 策略)的 **ROS 1 部署代码**反向移植成 +**ROS 2 Humble** 的 `ament_python` 包,用于**无图、无 GPS 的端到端导航**。 + +``` +/odin1/depth_img_competetion ─┐ + ├─► sru_nav_node ─► /cmd_vel (geometry_msgs/Twist) +/odin1/odometry_highfreq ─────┘ ▲ + │ + /goal_pose (位置) + /goal_yaw (朝向) +``` + +**几个必须先建立的认知**: + +| 事实 | 说明 | +|---|---| +| 它是**端到端反应式策略**,不是导航栈 | 没有地图、没有 SLAM、没有规划器。唯一决策入口是一次 ONNX 前向:`深度图 + 16 维状态 → [vx, vy, ω]`。所以**不存在"规划出的路径"** | +| 三个速度是**同时**输出的 | 动作空间是 SE2 三自由度 `[vx, vy, ω]`,一次算出来一起发。**不是"先转好再走"**;因为横移被限得比前进小 3 倍多,实际会边走边转(弧线接近) | +| **机型无关** | 本包只发布 `Twist` 到 `/cmd_vel`,不绑定任何底盘,桥上你自己接 | +| 没有深度就**一条 `/cmd_vel` 都不发** | 推理只由 `depth_callback` 触发。看到 `/cmd_vel` 全无输出,先查驱动有没有把深度开起来 | +| **到达判定只看 XY 距离** | 0.75 m 内就算到,**不要求朝向**。朝向是另外用 `/goal_yaw` 指定的(见 §4.5) | +| 节点名固定 `sru_nav_node` | 私有话题 `~/vis/*` 等的展开结果与 ROS 1 一致 | + +--- + +## 1. 交付物与打包(**先看这节,最容易在这里出错**) + +### 1.1 带什么 / 不带什么 + +| 路径 | 体积 | 带不带 | 说明 | +|---|---|---|---| +| `src/sru_nav_ros2/` | 28 MB | ✅ **必需** | 交付包本体(含两个 ONNX,27 MB) | +| `reference/COLCON_IGNORE` | 528 B | ✅ **必需** | 见 §2.5,缺了 `colcon build` 会炸 | +| `reference/SRU-Odin/Deployment/` | 32 MB | ✅ 建议 | ROS 1 只读蓝本,方便日后 diff 对照 | +| `docs/HANDOVER.md`、`docs/ROS2_PORT_PLAN.md` | 小 | ✅ 建议 | 当初的移植方案(**注意:其中两处结论已被实测推翻,以 `DEPLOY_ROS2.md` 为准**);2026-09-30 起由 `reference/` 移入 `docs/` | +| `reference/SRU-Odin/Train/` | 342 MB | ⬜ 可选 → **建议带精简版(打包后约 130 KB)** | 训练侧代码与配置,是部署代码的"规格书"(见 §1.4)。**整目录 342 MB 里只有约 800 KB(87 个文件)是代码/配置**,其余全是权重与地形资源 | +| `reference/SRU-Odin/` 其它(`Img/`、`Prompt/`、README) | 小 | ⬜ 可选 | | +| **`venv/`** | 266 MB | ❌ **千万不要拷** | **见 §1.2,必须在新机器上重建** | +| `build/`、`install/`、`log/` | <1 MB | ❌ 不要 | 构建产物,`colcon` 会重新生成 | + +**一句话**:`src/` 必需;`docs/` 整个带走;`reference/` 里只留 `Deployment/` + 那个 `COLCON_IGNORE` 就够(约 60 MB)。 + +### 1.2 ⚠️ 为什么 `venv/` 不能拷过去 —— 这是最容易翻车的一处 + +本机(也就是开发机)的路径是 `/home/kevin/sru_ws/`,而你那边大概率不是。venv **到处都是绝对路径**: + +| 位置 | 内容 | +|---|---| +| `venv/bin/activate` | 我们追加的 `export PYTHONPATH="/home/kevin/sru_ws/venv/lib/python3.10/site-packages..."` | +| `venv/pyvenv.cfg` | `home = /usr/bin`、`command = ... /home/kevin/sru_ws/venv` | +| `venv/bin/*` 下所有入口脚本 | shebang 指向 `/home/kevin/sru_ws/venv/bin/python` | + +拷过去只会得到一堆指向不存在路径的脚本。**正确做法是在新机器上重建**(§2.3),重建后激活就能用。 + +### 1.3 打包(**已实测可用**,产物 ≈ 51 MB) + +```bash +cd ~ +TAR_OPTS=( + --exclude='sru_ws/build' --exclude='sru_ws/install' --exclude='sru_ws/log' + --exclude='sru_ws/venv' + --exclude='*/__pycache__' + --exclude='*/assets' --exclude='*.usd' --exclude='*.jpg' + --exclude='*.pth' --exclude='*.pt' +) +tar czf sru_nav_handover.tgz "${TAR_OPTS[@]}" \ + sru_ws/src/sru_nav_ros2 \ + sru_ws/docs \ + sru_ws/reference/COLCON_IGNORE \ + sru_ws/reference/SRU-Odin/Deployment \ + sru_ws/reference/SRU-Odin/README.md \ + sru_ws/reference/SRU-Odin/LICENSE \ + sru_ws/reference/SRU-Odin/Train +``` + +实测结果(本机):**53,696,793 字节 ≈ 51 MB**,181 个条目。 +`--exclude='*/assets'` 等几条同时把**精简版 Train** 里的权重/地形/图片排除掉了(见 §1.4), +所以 `Train/` 也一并带上了。 + +**归档内部结构就是 `sru_ws/…`**,所以队友在**家目录**直接解压即得文档描述的布局: + +```bash +cd ~ && tar xzf sru_nav_handover.tgz # 解出 ~/sru_ws/{src,reference} +``` + +> 已验证:归档内两个 ONNX 与源文件**逐字节一致**(`cmp` 通过)、包内容与源树 `diff -r` 完全一致、 +> `venv/` / `build/` / `install/` / `log/` / `__pycache__` / 权重 / 地形 / 图片**均未进入归档**。 + +> 另一条路:**直接用 git 传 `src/sru_nav_ros2/` 一个目录**(它是自包含的), +> `reference/` 那边自己 `git clone https://github.com/ManifoldTechLtd/SRU-Odin` 到 +> `~/sru_ws/reference/SRU-Odin`,然后 checkout `6a81ba77f46d4ab010d3d3354d54ec25ef730955`。 + +### 1.4 `Train/` 值得带什么(如果你要带的话) + +`Train/` 是**训练侧**(Isaac Sim 4.5 + IsaacLab 的 Docker 环境),**不能用来部署**, +但它是**部署代码的规格书** —— 凡是"部署必须与训练一致"的地方,最终都要以它为准。 +开发过程中它就是靠这个目录定下了下面这些结论(而不是"相信交接文档"): + +| 用 `Train/` 定下的结论 | 出处 | +|---|---| +| 目标向量归一化公式 `log(distance + 1.0)` + 方向分量 —— **独立验证了 `model.py` 与 ONNX 的 I/O 契约** | `mdp/navigation/goal_commands.py` | +| 动作空间是 **SE2 三维 `[vx, vy, ω]`**(同时输出,不是"先转后走") | `navigation_se2_actions.py` 的 `self._action_dim = 3` | +| 训练用的动作尺度是 **`policy_scaling = [1.5, 1.0, 1.0]`** —— 证实部署里的 `policy_scale` 就是它对应的旋钮 | `navigation_env_cfg.py` | +| 训练**到达阈值 0.5 m**(部署蓝本用 0.75 m,更松) | `mdp/terminations.py` | +| 低通 α 随机范围 `(0.1, 0.6)` ⇒ 部署的 `[0.1, 0.5, 0.5]` 落在训练区间内 | `config/b2w/navigation_env_cfg.py` | + +另外 `mount/sru-navigation-sim/scripts/` 里有几个**方法值得借鉴**的脚本: + +- **`ablate_depth.py`** —— 判断"策略到底有没有真在用深度,还是学会了忽略(perception-blind)"。 + 这个思路可以搬到我们的部署侧做上机前验证:**把深度输入置零/替换,看 `/cmd_vel` 有没有跟着变**。 +- `export_onnx.py` —— ONNX 是从 checkpoint 怎么导出来的。以后要重训/换模型,这是唯一依据。 +- `analyze_collisions.py` / `eval_terminations.py` / `inspect_run.py` —— 训练侧的分析工具。 + +⚠️ **别搞混**:`Train/` 里的 `.pt` / `.pth` 是**低层步态策略**(给腿足/轮腿底盘走的)和 **VAE 预训练权重**, +**不是**我们部署用的 `nav_policy.onnx` / `vae_encoder.onnx`,**不要**拿它们去替换模型。 + +**精简打包(342 MB → 打包后约 130 KB)**: + +```bash +tar czf sru_nav_train_slim.tgz \ + --exclude='*/assets/*' --exclude='*.usd' --exclude='*.jpg' \ + --exclude='*.pth' --exclude='*.pt' --exclude='*/__pycache__' \ + -C ~/sru_ws/reference/SRU-Odin Train +# 实测:打包后约 130 KB(129,517 B),解压后约 800 KB / 87 个文件 +# 排除掉的正是那 341 MB 的权重(.pt/.pth)、地形(.usd)与图片(.jpg) +``` + +--- + +## 2. 新机器上的环境安装 + +### 2.1 前提(先确认,不满足就别往下走) + +| 项 | 要求 | +|---|---| +| 系统 | **Ubuntu 22.04**(Jammy)。ROS 2 Humble 只支持这个 LTS | +| CPU 架构 | **先确认 `uname -m`**。本包在 `x86_64` 上验证过;若是 **ARM(如 Jetson)**,`onnxruntime` / `scipy` 的 wheel 可用性不同,需要单独确认,可能装不上 | +| 磁盘 | 至少 2 GB 余量(包 28 MB + venv ~300 MB + ROS) | +| ROS 2 | Humble,**必须已装**(本包不自带) | +| 网络 | 装 apt / pip 时可用 | + +### 2.2 apt 包 + +```bash +sudo apt update +sudo apt install -y \ + ros-humble-desktop \ + ros-humble-cv-bridge \ + ros-humble-joy \ + ros-humble-tf2-ros \ + ros-humble-rviz2 \ + python3-colcon-common-extensions \ + python3.10-venv +``` + +### 2.3 建 venv(**在新机器上重建,不要拷**) + +```bash +/usr/bin/python3 -m venv --system-site-packages ~/sru_ws/venv +~/sru_ws/venv/bin/pip install --upgrade pip +~/sru_ws/venv/bin/pip install "numpy<2" onnxruntime +~/sru_ws/venv/bin/pip install "scipy==1.11.4" +``` + +三个参数/版本**都不是可选项**: + +- **`--system-site-packages`**:venv 必须能看到 ROS 2 的 `rclpy` / `cv_bridge`,否则白建。 +- **`"numpy<2"`**:不锁的话 pip 会装 numpy 2.x,而 numpy 2.x 会让 `cv_bridge` 报 + `_ARRAY_API not found`、`import cv2` 直接段错误。 +- **`scipy==1.11.4` 用精确版本号**:`--system-site-packages` 的 venv 里,pip 会把 + `/usr/lib/python3/dist-packages` 的包**当成"已满足"**,写 `pip install scipy`(哪怕是 `scipy<1.14`) + 只会回 `Requirement already satisfied` 而**不装进 venv**,运行时仍命中 apt 的 scipy 1.8.0 + (它 pin 了 `numpy<1.25`,与 venv 的 numpy 1.26.4 冲突)。**必须给精确版本号**才能强制装进去。 + +> **绝对不要 `pip install opencv-python`**:本包用的是系统 `python3-opencv`(4.5.4), +> 与 `cv_bridge` 同源。装了 pip 版会把系统版顶掉,回到上面那个崩溃状态。 + +### 2.4 往 venv 的 activate 里追加两行(**把路径换成你的**) + +```bash +cat >> ~/sru_ws/venv/bin/activate <<'EOF' +export PYTHONNOUSERSITE=1 +export PYTHONPATH="__YOUR_VENV__/lib/python3.10/site-packages${PYTHONPATH:+:$PYTHONPATH}" +EOF +# 把 __YOUR_VENV__ 换成真实路径,例如 /home/你的用户名/sru_ws/venv +sed -i "s|__YOUR_VENV__|$HOME/sru_ws/venv|" ~/sru_ws/venv/bin/activate +tail -3 ~/sru_ws/venv/bin/activate # 确认两行在里面,且路径正确 +``` + +**这两行分别在治什么病**(完整原理见 `DEPLOY_ROS2.md` §2.3): + +- **`PYTHONNOUSERSITE=1`**:`--system-site-packages` 建的 venv,CPython **不会**禁用用户级 site, + 于是 `~/.local/lib/python3.10/site-packages` 照旧进 `sys.path`。那里如果有 pip 版 numpy 2 / opencv, + 就会顶掉系统版 → `cv_bridge` 崩、`import cv2` 段错误。 + **只放 venv 的 activate,不要写进 `~/.bashrc`**(会连累你其它项目)。 +- **`PYTHONPATH` 追加**:`/usr/bin/colcon` 与 `ros2` 的 shebang **硬编码 `#!/usr/bin/python3`**, + 所以 `console_scripts` 入口脚本**永远跑在系统 python 上**(激活 venv 改变不了这一点), + 它看不见 venv 里的 `onnxruntime` → 启动即 `ModuleNotFoundError: No module named 'onnxruntime'`。 + 把 venv 的 site-packages 挂到 `PYTHONPATH` 才是正解。 + ⚠️ **必须"追加"(保留 `$PYTHONPATH`)**:覆盖式赋值会冲掉 `source setup.bash` 注入的 ROS 路径, + 立刻变成 `No module named 'cv_bridge'`。 + +### 2.5 ⚠️ 两个 `COLCON_IGNORE`(重建 venv 后**必须**立刻补上 venv 那个) + +```bash +mkdir -p ~/sru_ws/reference ~/sru_ws/src +touch ~/sru_ws/reference/COLCON_IGNORE +touch ~/sru_ws/venv/COLCON_IGNORE # ← 重建 venv 后容易忘,忘了 colcon 必炸 +``` + +**为什么**:`colcon build` 是从工作区根目录**递归爬全部子目录**的,**不是只爬 `src/`**。没有这两个标记它会: + +| 被误判成包 | 位置 | 后果 | +|---|---|---| +| `sru_nav_go2_ros1` | `reference/SRU-Odin/Deployment/`(有 `package.xml` + catkin `CMakeLists.txt`) | **致命**:Humble 没有 catkin,`find_package(catkin)` 直接失败 | +| `isaaclab_nav_task` | `reference/SRU-Odin/Train/.../`(有 `setup.py`) | 被当 Python 包一起构建 | +| `my-test-package` | `venv/.../pkg_resources/tests/data/my-test-package-source/` | 同上,外加几千个 site-packages 的 `setup.py` 刷屏报错 | + +> 标记文件放在**父目录**(`reference/`、`venv/`),**不要**放进 `reference/SRU-Odin/` 内部(会污染只读蓝本)。 + +### 2.6 环境验收(这四条全绿再往下) + +```bash +source /opt/ros/humble/setup.bash +source ~/sru_ws/venv/bin/activate + +# ① 依赖齐全、版本正确 +python - <<'PY' +import os, cv2, numpy, scipy, yaml, onnxruntime, rclpy +from cv_bridge import CvBridge +print("PYTHONNOUSERSITE", os.environ.get("PYTHONNOUSERSITE")) # 期望 1 +print("numpy ", numpy.__version__, numpy.__file__) # 期望 1.26.x,在 venv 下 +print("cv2 ", cv2.__version__, cv2.__file__) # 期望 4.5.4,在 /usr/lib/python3/dist-packages +print("scipy ", scipy.__version__, scipy.__file__) # 期望 1.11.4,在 venv 下 +print("ort ", onnxruntime.__version__, onnxruntime.get_available_providers()) +print("CvBridge", CvBridge()) +PY + +# ② colcon 只认到我们的包,且无噪音 +cd ~/sru_ws && colcon list +# 期望只有一行:sru_nav_ros2 src/sru_nav_ros2 (ros.ament_python) +``` + +**关键期望值**:`cv2` 必须是 **4.5.4** 且路径在 `/usr/lib/python3/dist-packages`(不是 `~/.local`、 +也不是 venv 里);`numpy`/`scipy` 必须在 **venv** 下。 + +--- + +## 3. 构建与运行 + +```bash +source /opt/ros/humble/setup.bash +source ~/sru_ws/venv/bin/activate +cd ~/sru_ws && colcon build --symlink-install +source install/setup.bash + +# 正常启动(手柄 deadman 生效,安全默认) +ros2 launch sru_nav_ros2 sru_nav.launch.py + +# 无手柄冒烟测试(TESTING ONLY,务必先抬轮/架空) +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false +``` + +**期望日志**: + +``` +[sru_nav_node-2] [INFO] [...] VAE encoder: .../share/sru_nav_ros2/models/vae_encoder.onnx +[sru_nav_node-2] [INFO] [...] Policy model: .../share/sru_nav_ros2/models/nav_policy.onnx +[sru_nav_node-2] [INFO] [...] Navigation policy node is ready. +[sru_nav_node-2] [INFO] [...] SRU navigation node spinning (odom_twist_in_base_frame=True, require_joystick=False). +``` + +> **不是故障,别误判**: +> - 没有 Odin 数据源时,每 5 s 刷一次 `Odometry not ready, skipping depth callback.` —— 在等 odom。 +> - **没发目标时 `/cmd_vel` 恒为 0,并每秒刷 `Target position reset.`** —— 蓝本原有设计。 +> - `waypoint_runner` 约 10 s 后会把原地不动的目标判为 `STUCK` 并跳过 —— 车确实不动,是它的设计行为。 + +> 💡 `--symlink-install` 下 `install/`、`build/` 里全是指向 `src/` 的**符号链接**: +> 改代码 / launch / config **不需要重新 `colcon build`**,重启 launch 即可 +> (但**必须重启进程**,改了不会热加载)。 + +--- + +## 4. 功能包怎么用 + +### 4.1 两个可执行入口 + +| 入口 | 作用 | +|---|---| +| `ros2 run sru_nav_ros2 sru_nav_node` | 主节点(也是 launch 起的那个)。订阅深度/odom/手柄/目标,发布 `/cmd_vel` | +| `ros2 run sru_nav_ros2 waypoint_runner --waypoints "…"` | 外部航点客户端。按顺序发目标、等到达/超时/卡住、可选回起点。**不碰主节点** | + +### 4.2 话题接口 + +| 话题 | 类型 | 方向 | 说明 | +|---|---|---|---| +| `/odin1/depth_img_competetion` | `sensor_msgs/Image` | 入 | 稠密深度,**`32FC1`、单位米**、约 228×185(`1600/scale × 1296/scale`,`scale=7.0`) | +| `/odin1/odometry_highfreq` | `nav_msgs/Odometry` | 入 | 约 300–400 Hz。`frame_id = odom`、`child_frame_id = odin1_base_link`,**twist 已在 body 系** | +| `/joy` | `sensor_msgs/Joy` | 入 | 手柄(deadman + 手动速度叠加 + 智能摇杆功能) | +| `/goal_pose` | `geometry_msgs/PoseStamped` | 入/出 | 目标**位置**。`frame_id` 必须等于 odom 的 `header.frame_id`,否则被拒。⚠️ 它的 `orientation` 字段**从不被读取** | +| `/goal_yaw` | `std_msgs/Float64` | 入 | 目标**朝向**(弧度、odom 系)。`NaN` = 本目标无朝向要求。见 §4.5 | +| `/cmd_vel` | `geometry_msgs/Twist` | 出 | 速度指令(body 系)。**机型无关,桥上你自己接** | +| `/sru_nav_node/base_vel` | `geometry_msgs/Twist` | 出 | 调试用:转换后的 base 系速度 | +| `/sru_nav_node/vis/*` | `Marker` ×4 | 出 | rviz 用:速度箭头、目标方向箭头、moving goal、已记录路点 | +| `/sru_nav_node/vis/executed_path` | `nav_msgs/Path` | 出 | 实际走过的轨迹(1 Hz 采样) | +| `/sru_nav_node/vis/goal_path` | `nav_msgs/Path` | 出 | 当前位置 → 当前目标的直线 | + +### 4.3 launch 参数 + +| 参数 | 默认 | 说明 | +|---|---|---| +| `params_file` | `share/sru_nav_ros2/config/sru_nav.yaml` | 参数文件路径 | +| `require_joystick` | `true` | 手柄 deadman。`false` **仅供测试** | +| `launch_joy` | `true` | 是否顺带起 `joy_node` | +| `launch_static_tf` | `true` | 是否发布静态 TF `odin1_base_link → base_link` | +| `base_link_x/y/z/roll/pitch/yaw` | Rc2026 比赛车实测值 | **`base_link` 在 `odin1_base_link` 下的位姿,必须按我们的载体实测替换**(见 §6 第 5 项) | +| `odom_twist_in_base_frame` | `true` | 语义见下 | + +⚠️ 后两个参数(`require_joystick` / `odom_twist_in_base_frame`)的 **launch 默认值是从 YAML 里读出来的**, +不是写死的。原因:ROS 2 的 `parameters` 列表**后者覆盖前者**,launch 里硬编码的默认值会**静默盖掉 YAML** +(这个包踩过)。所以**改参数只改 `config/sru_nav.yaml` 就够了**;想临时翻一次用 +`odom_twist_in_base_frame:=false` 这种命令行覆盖。 + +⚠️ **TF 方向与 ROS 1 蓝本相反,是有意为之**:驱动自己会广播 `odom → odin1_base_link`, +所以机器人侧只需补 `odin1_base_link → base_link`,TF 树才完整 +(`odom → odin1_base_link → base_link`)。按蓝本发会让你有两个父节点,TF 树直接断。 + +### 4.4 参数(39 个,全在 `config/sru_nav.yaml`) + +分组速查: + +| 组 | 数量 | 说明 | +|---|---|---| +| 话题名 | 6 | `*_topic`,含 `goal_yaw_topic` | +| 模型路径 | 2 | 留空即从 `share/sru_nav_ros2/models/` 找 | +| 深度裁剪 | 2 | `min_depth` / `max_depth` | +| 控制 | 2 | `control_frequency`(**上限**,不是目标值)、`policy_scale` | +| 语义 / QoS | 3 | `odom_twist_in_base_frame`、`depth_qos_reliable`、`odom_qos_reliable` | +| 手柄 | 1 + 17 | `require_joystick` + 轴/键索引(沿用 constants.py 的 PS5 映射,**未在真手柄上验证过**) | +| 目标朝向 | 7 | `goal_yaw_*`,见 §4.5 | + +**⛔ 绝对不要改的**(与训练对齐,改了行为就废): + +``` +control_frequency = 5.0 Hz policy_scale = [0.6, 0.3, 0.6] ← 训练值是 [1.5,1.0,1.0],部署刻意保守 +require_joystick = true rnn_hidden_size = 512 / rnn_num_layers = 1 +min/max_depth = 0.25 / 10.0 m resize(40, 64);latent 2560;obs 2576 +ARRIVE_GOAL_THRESHOLD = 0.75 m JOYSTICK_TIMEOUT = 15.0 s +LOW_PASS_FILTER_COEF = [0.9,0.5,0.5] LATERAL_VELOCITY_SCALE = 0.6 +``` + +> 这些**故意不放进 YAML**,从 `constants.py` 取值,不给被误配的机会。 +> `constants.py` / `model.py` / `utils.py` 三个文件是**逐字节原样**的蓝本拷贝,**不要改**。 + +### 4.5 目标朝向(本包新增功能,蓝本没有) + +策略**无法表达朝向**(观测里没有这一维,到达也只看 XY 距离)。所以本包补了一条链路: +**位置到达后,用自己的 20 Hz 定时器原地自转对准,然后才释放目标**。 + +```bash +# runner:第 4 个数就是 yaw(弧度);前面几点省略它 ⇒ 只有最后一点要求朝向 +ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708" + +# 手发:位置走 /goal_pose,朝向走 /goal_yaw +ros2 topic pub --once --qos-durability transient_local \ + /goal_yaw std_msgs/msg/Float64 "{data: 1.5708}" # 90°;发 NaN 则取消朝向要求 +``` + +⚠️ 手发 `/goal_yaw` **必须带 `--qos-durability transient_local`**:节点是 TRANSIENT_LOCAL 订阅者, +`ros2 topic pub` 默认 VOLATILE 发布者,**不兼容 ⇒ 消息被静默丢弃**(发了完全没反应)。 + +关键参数:`goal_yaw_tolerance`(默认 0.0873 ≈ **±5°**)、`goal_yaw_max_rate`(0.6 rad/s)、 +`goal_yaw_timeout`(15 s)。完整说明(含无载体自测方法)见 `DEPLOY_ROS2.md` **§6.4**。 + +### 4.6 在 rviz 里看 + +Fixed Frame 设 **`odom`**,Add → By topic 加: +`vis/executed_path`(Path)、`vis/goal_path`(Path)、`vis/twist_cmd_marker`、`vis/goal_vector_marker`、 +`/goal_pose`(Pose)、`/odin1/odometry_highfreq`(Odometry),建议再打开 `/tf`。 +⚠️ 再说一次:**`executed_path` 是"实际走过的轨迹",不是"规划路径"** —— 这策略没有规划器。 + +### 4.7 `/cmd_vel` 桥(接车的接口) + +本包只发 `geometry_msgs/msg/Twist`。你们的底盘需要一个订阅 `/cmd_vel` 的桥(厂商 SDK 自写节点)。 + +**上机前必须确认一件事**:`sru_nav_node` 被杀掉之后,你的桥**会不会自动归零**? +如果不会,节点一死机器人会**保持最后一条速度指令**继续跑 —— 这是最容易出事故的点。 + +--- + +## 5. Odin1 驱动前置(不属于本包,但决定本包能不能跑) + +### 5.1 深度默认是**关**的,必须改三个键 + +⚠️ **要改的是"源码树"里那份,不是 `install/` 里那份。** + +驱动三个可执行文件都用 `get_package_source_directory()` 定位配置 —— 它从**编译期的 `__FILE__`** +逐级向上找到含 `package.xml` 的目录。所以**实际被读的文件**是: + +``` +<你的驱动源码目录>/src/odin_ros_driver/config/control_command.yaml ← 改这份 +.../install/odin_ros_driver/share/odin_ros_driver/config/*.yaml ← 改了没用 +``` + +三个键(出厂都是 `0`): + +```yaml +senddtof: 1 # = "send raw cloud data",它才是 /odin1/cloud_raw 的开关 +senddepth: 1 # 稠密深度图 /odin1/depth_img_competetion +sendrgb: 1 # 解码后的 RGB /odin1/image +``` + +**为什么三个都要开**: + +- `senddepth: 0` 时深度节点打印 `Depth image will not be published.` 后**直接退出**; +- 深度节点用 `message_filters` 同步 **`{/odin1/cloud_raw, /odin1/image}` 一对**, + 少任何一路,回调永不触发 ⇒ **永远没有深度 ⇒ `/cmd_vel` 一条都不发**。 + +这三个键属 `register_keys`(启动时下发给设备)⇒ **改完必须整体重启驱动**。 +⚠️ **Odin1 的 USB 链路是独占的,不能同时跑两个 `host_sdk_sample`**,重启前先 Ctrl-C 掉旧的。 + +### 5.2 启动与验证 + +```bash +source /opt/ros/humble/setup.bash +source /sru_nav_handover/sru_ws/install/setup.bash +ros2 launch odin_ros_driver odin1_ros2.launch.py +``` + +**验证判据(很重要,别用错方法)**: + +| 方法 | 可靠性 | +|---|---| +| `ros2 topic list` | ❌ 只要存在**任一**端点(哪怕只有订阅者)就会列出来 | +| `ros2 topic info` 的 `Publisher count` | ❌ 驱动启动时就建好了 publisher,没数据时它照样是 1 | +| **`ros2 topic hz `** | ✅ 唯一可信,但它会明确打印 `does not appear to be published yet` | +| **驱动自己写的设备状态 CSV** | ✅✅ 最权威 | + +```bash +# 最权威:设备端发送率 vs 主机端接收率;rx = 0.00 的那一路就是没通 +CSV=$(ls -1t <驱动源码目录>/log/Driver_*/Conn_*/dev_status.csv | head -1) +head -1 "$CSV"; tail -1 "$CSV" +# 健康值:rgb_rx_odr ~10、dtof_rx_odr ~10、slam_cloud_rx_odr ~10、slam_odom_highfreq_rx_odr ~400 +``` + +⚠️ **大消息的 `hz` 会骗人**:`/odin1/image` 是 6.2 MB/帧、发布端 RELIABLE + 小队列, +Python 订阅者跟不上会把发布端一起拖慢(实测把 10 Hz 显示成 0.3 Hz)。 +(深度图只有约 165 KiB,它的 `hz` **可信**。) + +--- + +## 6. ⚠️ 已知问题 / 必须上机实测(**本节最重要**) + +### 6.1 一条已经定性的"不是问题的问题" + +**`/cmd_vel` 实测只有 1.4–1.7 Hz,深度也只有约 1.5 Hz,而设备端是 10 Hz。** + +已经查到的事实:设备到主机是 10 Hz;主机到 ROS 订阅者只剩约 1.5 Hz —— **8 倍的损耗发生在 +Odin 驱动的发布/DDS 交付环节**。本节点平均 CPU 只占 11%(89% 时间在空等), +**已排除本包**(`control_frequency: 5.0` 在代码里是**上限**不是目标值,输入慢就自然慢, +逻辑与 5 Hz 时完全一致,不会算错)。 + +可疑点是驱动里两个大话题硬编码的 `qos_sensor = rclcpp::QoS(5)`(odom 用的是 `QoS(4000)`,所以odom正常)。 +**候选修法(驱动侧,1 行 + 重编)**:把 `QoS(5)` 改成 `QoS(50)`;或发布/订阅**成对**改成 BEST_EFFORT。 +⛔ **绝对不能只把发布端改成 BEST_EFFORT** —— 会让现有的 RELIABLE 读者**静默收不到任何数据**。 + +### 6.2 必须上机实测的清单 + +| # | 项 | 现状 | 怎么测 | 影响 | +|---|---|---|---|---| +| 1 | **Odin1 装订外参 xyz/rpy** | 默认值是 **Rc2026 比赛车 R2 的实测装订**(`base_link` 在 `odin1_base_link` 下 `-0.268846, 0.028504, 0.067861, 0.017828, 0.245433, 0`)—— **不是我们的载体** | 尺子量 + `ros2 run tf2_ros tf2_echo odin1_base_link base_link`;更规范的是原地慢转做圆拟合 | 直接用错的装订会让目标方向偏差,越远越明显 | +| 2 | **目标朝向的精度(±5° 是设计目标)** | 逻辑已就位,**从未在真机上验证** | 发 `--waypoints "0,0,0,1.5708"` 看日志里的 `Goal heading aligned: residual error X deg` | 到点后的姿态不达标;底盘 yaw 死区大时会超时放弃 | +| 3 | **`/joy` 轴与键索引** | 沿用 `constants.py` 的 PS5 映射,**没在真手柄上验过** | `ros2 topic echo /joy` 逐个推摇杆/按键,改 17 个 `joy_axis_*` / `joy_button_*` 参数 | 手柄不好使;deadman 可能一直触发 | +| 4 | **deadman 的时钟域** | ⚠️ 本机驱动是 `use_host_ros_time: 0` = 用 **Odin 设备内部时间**打时间戳,与主机墙钟**不同基准**。而 deadman 判断式是 `odom 时间戳 − time.time() > 15 s`,**混算两个时间域** | 对比 `ros2 topic echo /odin1/odometry_highfreq --once --field header.stamp` 与 `date +%s` | 两个极端:odom 时间远大于墙钟 → **一上来就超时、`/cmd_vel` 恒为 0**;远小于 → 差值恒负、**deadman 事实上失效**(更危险)。**处理办法:把驱动的 `use_host_ros_time` 设成 `1`(主机时间)或 `2`(对齐到主机时间轴)后重启驱动**。关 `require_joystick` 时不受影响 | +| 5 | **odom twist 的正负号手感 / `odom_twist_in_base_frame`** | 已按参考工程定为 `true`(twist 已在 body 系,直接透传),**方向手感未验证** | 架空后手动推/转机器人,看 `/sru_nav_node/base_vel` 与预期方向是否一致 | 判反了会让车往反方向跑 | +| 6 | **铺密集路点会踩到达阈值** | `ARRIVE_GOAL_THRESHOLD = 0.75 m`,且**发布即判到达** ⇒ **路点间距 ≤ 0.75 m 时机器人一步都不走**。每跳实际只推进"间距 − 0.75 m" | 用间距 ≥ 3–5 m 的航点 | 密集面包屑适得其反。想更密需要把阈值降到训练值 **0.5 m**(属"绝对不能改"清单,**要拍板**) | +| 7 | **装订带俯仰角的残余量** | `odom_twist_in_base_frame: true` 让 twist 透传,但 Odin1 若带俯仰角安装,`odin1_base_link` 是倾斜的:`linear.x` 会被乘上约 `cos(pitch)`,并出现一点虚假的 `linear.z` | 观察 `/sru_nav_node/base_vel` 里有没有不该有的 `linear.z` | 速度略偏小 + 一点噪声。参考工程也是这么接受的;要精确补偿需要一次 TF 查询(属新增功能,未做) | +| 8 | **手柄 deadman 之外的 `/joy` 高级功能**(智能摇杆、按钮发目标/回起点/记录路点) | 代码完整但从未实测 | 按 `constants.py` 的按钮定义逐个试 | 可能按错按钮触发意外动作 | + +**其它可能还存在的问题** + +- **`/cmd_vel` 只有一个发布者**(本节点)。自转对准期间因为用的是**独立定时器**, + `generate_cmd_vel` 会主动"让路"不发零速,避免两个来源抢话题 —— 这点已验证。 +- 若驱动用的是**另一台机器的另一份源码目录**,注意 §5.1 那条:**生效的 config 是编译期路径对应的那份**。 +- **CPU 架构**:若是 ARM 小电脑,`onnxruntime` / `scipy` 的 wheel 需要单独确认(见 §2.1)。 + +--- + +## 7. 首次上机安全流程 + +1. **抬轮 / 架空**,别落地。 +2. 先确认驱动数据流(§5.2),再起控制器。 +3. 用 `require_joystick:=false` 跑冒烟,`ros2 topic echo /cmd_vel` 看数值是否**有界合理** + (已知上限:`|linear_x| ≤ 0.6`、`|linear_y| ≤ 0.18`、`|angular_z| ≤ 0.6`)。 +4. 确认急停手段可用: + - 手柄按 `BUTTON_ABORT`(默认 index 9)→ 立刻发零速并放弃当前目标; + - Ctrl-C 停 `sru_nav_node` → **但要先确认桥会不会自动归零**(§4.7); + - 物理断电。 +5. 落地后先用**很慢的** `policy_scale`(当前已是保守值)跑一次近目标(2–3 m), + 确认方向手感对了再放大。 + +--- + +## 8. 出问题先看哪里 + +| 症状 | 去哪看 | +|---|---| +| 节点起不来、`ModuleNotFoundError: onnxruntime` | §2.4(`PYTHONPATH` 那行);确认是 `source ~/sru_ws/venv/bin/activate` 之后再 `ros2 launch` | +| `import cv2` 段错误 / `cv_bridge` 报 `_ARRAY_API not found` | §2.4(`PYTHONNOUSERSITE`);检查 `cv2.__file__` 是不是被 `~/.local` 顶掉了 | +| `colcon build` 报 catkin 找不到 / 冒出一堆无关包名 | §2.5(`COLCON_IGNORE`) | +| 起崩报 `AttributeError: ... has no attribute 'xxx'` | 改了代码但**没重启进程**;或改动没真落盘 | +| `/cmd_vel` 一条都没有 | **没有深度**(§5.1)。日志里 `cmd_vel_ratio:` 与 `Published cmd_vel:` 会**全然不出现** | +| `/cmd_vel` 恒为 0 | ① 没发目标(正常分支,会刷 `Target position reset.`);② deadman(§6.2 #4);③ 目标比 0.75 m 还近 | +| 订阅了但收不到深度、且不报错 | **QoS 不匹配**:ROS 2 里 BEST_EFFORT 发布端 + RELIABLE 订阅端 = 静默收不到。用 `ros2 topic info -v` 对比两端 | +| 其它 | **`DEPLOY_ROS2.md` §8 排错速查表**(约 20 条现象→原因) | + +--- + +## 9. 速查 + +```bash +# 环境 +source /opt/ros/humble/setup.bash && source ~/sru_nav_handover/sru_ws/venv/bin/activate +source ~/sru_nav_handover/sru_ws/install/setup.bash + +# 起控制器(正常 / 无手柄冒烟) +ros2 launch sru_nav_ros2 sru_nav.launch.py +ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false launch_joy:=false + +# 发目标(位置 + 朝向;前面几点省略 yaw ⇒ 只最后一点要求朝向) +ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708" + +# 只看数据(唯一可信的判据) +ros2 topic hz /odin1/odometry_highfreq +ros2 topic hz /odin1/depth_img_competetion +ros2 topic echo /cmd_vel + +# 参数 +ros2 param dump /sru_nav_node # 看当前值 +ros2 param set /sru_nav_node goal_yaw_tolerance 0.05 +``` + +**目录职责** + +| 路径 | 说明 | +|---|---| +| `src/sru_nav_ros2/` | 交付包(本文件所在处) | +| `src/sru_nav_ros2/docs/DEPLOY_ROS2.md` | **权威细节文档** | +| `src/sru_nav_ros2/docs/AI_AGENT_PROMPT.md` | 给你那边的 AI Agent 的提示词 | +| `reference/SRU-Odin/Deployment/` | ROS 1 只读蓝本,**禁止修改**(留着 diff 用) | +| `venv/` | 在新机器上重建(§2.3) | + +--- + +**最后一句话**:功能链路在开发机上已经跑通(深度 → 推理 → 非零 `/cmd_vel` 都实测过), +**没验证的都是"需要物理世界"的那些** —— 装订、朝向精度、手柄、正负号手感,以及那个驱动侧的速率问题。 +有问题把**日志原文**发回来,比描述现象有用得多。 diff --git a/sru_ws/src/sru_nav_ros2/launch/sru_nav.launch.py b/sru_ws/src/sru_nav_ros2/launch/sru_nav.launch.py new file mode 100644 index 0000000..46a51ea --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/launch/sru_nav.launch.py @@ -0,0 +1,191 @@ +"""Launch the SRU navigation controller (Odin1 + ONNX policy) on ROS 2 Humble. + +Starts three things: + +1. ``joy_node`` -- optional gamepad driver (PS5/PS4 style) +2. ``static_transform_publisher`` -- optional static TF odin1_base_link -> base_link +3. ``sru_nav_node`` -- the controller: Odin1 depth + odometry in, + geometry_msgs/Twist on /cmd_vel out + +The Odin1 driver (``odin_ros_driver``) and the /cmd_vel bridge to your platform +are NOT launched here; bring them up separately. + +Typical use:: + + # normal run, joystick deadman armed (safe default) + ros2 launch sru_nav_ros2 sru_nav.launch.py + + # headless / bench test with no gamepad (TESTING ONLY) + ros2 launch sru_nav_ros2 sru_nav.launch.py require_joystick:=false + +All tunables come from ``config/sru_nav.yaml``, installed to the package share +directory. Only the two safety-relevant switches are additionally exposed as +launch arguments, so they can be flipped from the command line; everything else +is changed in the YAML (no code edits needed). + +IMPORTANT -- the defaults of those two launch arguments are read *from the YAML* +rather than hardcoded. In ROS 2 a later entry in the ``parameters`` list wins, +so a hardcoded launch default silently overrides the parameter file: exactly how +``odom_twist_in_base_frame`` once stayed ``false`` while the YAML said ``true``. +Sourcing the default from the file keeps a single source of truth. +""" + +import os +import yaml + +from ament_index_python.packages import get_package_share_directory +from launch import LaunchDescription +from launch.actions import DeclareLaunchArgument +from launch.conditions import IfCondition +from launch.substitutions import LaunchConfiguration +from launch_ros.actions import Node +from launch_ros.parameter_descriptions import ParameterValue + + +def _yaml_default(params_file, name, fallback): + """Value of ``name`` as written in the shipped parameter file. + + Used as the default of the launch arguments below so a launch default can + never contradict ``config/sru_nav.yaml``. Falls back to ``fallback`` if the + file cannot be read, so a broken YAML still lets the launch start and fail + with the node's own (clearer) error message instead. + """ + try: + with open(params_file, 'r') as f: + params = yaml.safe_load(f)['sru_nav_node']['ros__parameters'] + return str(params[name]).lower() + except Exception: + return fallback + + +def generate_launch_description(): + share_dir = get_package_share_directory('sru_nav_ros2') + default_params_file = os.path.join(share_dir, 'config', 'sru_nav.yaml') + + # ---- launch arguments ---------------------------------------------------- + declared_arguments = [ + DeclareLaunchArgument( + 'params_file', default_value=default_params_file, + description='Node parameter file (defaults to config/sru_nav.yaml ' + 'in the package share directory).'), + DeclareLaunchArgument( + 'odom_twist_in_base_frame', + default_value=_yaml_default(default_params_file, + 'odom_twist_in_base_frame', 'true'), + description='Treat the odom twist as already expressed in the body ' + 'frame and pass it through (renamed from the ROS 1 `sim` ' + 'argument; NOT related to use_sim_time). Default is ' + 'taken from config/sru_nav.yaml.'), + DeclareLaunchArgument( + 'require_joystick', + default_value=_yaml_default(default_params_file, + 'require_joystick', 'true'), + description='Joystick deadman. `false` bypasses it and is TESTING ' + 'ONLY. Default is taken from config/sru_nav.yaml.'), + DeclareLaunchArgument( + 'launch_joy', default_value='true', + description='Start a joy_node alongside (PS5/PS4 etc.).'), + DeclareLaunchArgument( + 'launch_static_tf', default_value='true', + description='Publish the static TF base_link -> odin1_base_link.'), + + # ---- base_link mounting: MEASURE THESE ON YOUR OWN ROBOT ------------- + # The Odin1 driver already broadcasts `odom -> odin1_base_link` + # (control_command.yaml: send_odom_baselink_tf: 1), so the only TF the + # robot side needs to supply is `odin1_base_link -> base_link`. That is + # exactly the chain the Rc2026 reference project builds: + # odom -> odin1_base_link -> base_link + # Publishing it the other way round (base_link -> odin1_base_link) would + # give odin1_base_link two parents and break the TF tree. + # + # The numbers therefore mean "where the platform centre (base_link) sits + # in the Odin1 frame" -- the INVERSE of "where the sensor is bolted on". + # xyz in metres, rpy in radians. + # + # Defaults are the Rc2026 R2 competition robot's MEASURED mounting + # (challenge1_z1.launch.py). They are NOT your platform: re-measure with + # a ruler / `tf2_echo`, or by circle-fitting a slow in-place rotation + # (the reference project ships calib_odin_mount.py for that). + DeclareLaunchArgument( + 'base_link_x', default_value='-0.268846', + description='base_link origin in odin1_base_link, x [m]. VERIFY on your robot.'), + DeclareLaunchArgument( + 'base_link_y', default_value='0.028504', + description='base_link origin in odin1_base_link, y [m]. VERIFY on your robot.'), + DeclareLaunchArgument( + 'base_link_z', default_value='0.067861', + description='base_link origin in odin1_base_link, z [m]. VERIFY on your robot.'), + DeclareLaunchArgument( + 'base_link_roll', default_value='0.017828', + description='base_link roll in the Odin1 frame [rad]. VERIFY on your robot.'), + DeclareLaunchArgument( + 'base_link_pitch', default_value='0.245433', + description='base_link pitch in the Odin1 frame [rad]. VERIFY on your robot.'), + DeclareLaunchArgument( + 'base_link_yaw', default_value='0.0', + description='base_link yaw in the Odin1 frame [rad]. VERIFY on your robot.'), + ] + + # ---- 1. joy_node --------------------------------------------------------- + joy_node = Node( + package='joy', + executable='joy_node', + name='joy_node', + output='screen', + condition=IfCondition(LaunchConfiguration('launch_joy')), + parameters=[{ + 'autorepeat_rate': 50.0, + 'deadzone': 0.05, + }], + ) + + # ---- 2. static TF odin1_base_link -> base_link --------------------------- + # Direction matches the Rc2026 reference project: the driver owns + # odom -> odin1_base_link, this node only supplies the platform offset. + # Humble's static_transform_publisher documents only the named-flag form; + # the ROS 1 positional form (x y z yaw pitch roll frame child) is gone from + # its usage text, and the ROS 1 ordering was yaw,pitch,roll -- so the flags + # below are spelled out explicitly rather than copied positionally. + static_tf_node = Node( + package='tf2_ros', + executable='static_transform_publisher', + name='static_tf_odin1_to_base', + output='screen', + condition=IfCondition(LaunchConfiguration('launch_static_tf')), + arguments=[ + '--x', LaunchConfiguration('base_link_x'), + '--y', LaunchConfiguration('base_link_y'), + '--z', LaunchConfiguration('base_link_z'), + '--roll', LaunchConfiguration('base_link_roll'), + '--pitch', LaunchConfiguration('base_link_pitch'), + '--yaw', LaunchConfiguration('base_link_yaw'), + '--frame-id', 'odin1_base_link', + '--child-frame-id', 'base_link', + ], + ) + + # ---- 3. the controller --------------------------------------------------- + # YAML first, then the two switches: in ROS 2 parameter lists later entries + # win, so these launch arguments override the file. That is intended -- they + # exist so a run can be flipped from the command line -- and it is safe only + # because their defaults are read from the same YAML (see _yaml_default). + # `ParameterValue` is required to coerce the LaunchConfiguration string into + # a real bool: the node declares these as bool, and handing it the string + # 'false' would be rejected. + nav_node = Node( + package='sru_nav_ros2', + executable='sru_nav_node', + name='sru_nav_node', + output='screen', + parameters=[ + LaunchConfiguration('params_file'), + { + 'odom_twist_in_base_frame': ParameterValue( + LaunchConfiguration('odom_twist_in_base_frame'), value_type=bool), + 'require_joystick': ParameterValue( + LaunchConfiguration('require_joystick'), value_type=bool), + }, + ], + ) + + return LaunchDescription(declared_arguments + [joy_node, static_tf_node, nav_node]) diff --git a/sru_ws/src/sru_nav_ros2/models/nav_policy.onnx b/sru_ws/src/sru_nav_ros2/models/nav_policy.onnx new file mode 100644 index 0000000..101e49a Binary files /dev/null and b/sru_ws/src/sru_nav_ros2/models/nav_policy.onnx differ diff --git a/sru_ws/src/sru_nav_ros2/models/vae_encoder.onnx b/sru_ws/src/sru_nav_ros2/models/vae_encoder.onnx new file mode 100644 index 0000000..35e16bc Binary files /dev/null and b/sru_ws/src/sru_nav_ros2/models/vae_encoder.onnx differ diff --git a/sru_ws/src/sru_nav_ros2/package.xml b/sru_ws/src/sru_nav_ros2/package.xml new file mode 100644 index 0000000..0d5d571 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/package.xml @@ -0,0 +1,44 @@ + + + + sru_nav_ros2 + 0.1.0 + + ROS 2 (Humble) port of the SRU navigation controller. + Loads the pretrained SRU policy (nav_policy.onnx) and the VAE depth encoder + (vae_encoder.onnx) through ONNX Runtime, subscribes to Odin1 depth / odometry + and a joystick, and publishes geometry_msgs/Twist on /cmd_vel. + Robot-agnostic: the /cmd_vel bridge to the actual platform is provided by the + caller (see docs/DEPLOY_ROS2.md). + + + SRU Navigation Port + MIT + + ament_python + + + rclpy + std_msgs + sensor_msgs + geometry_msgs + nav_msgs + visualization_msgs + cv_bridge + tf2_ros + joy + ament_index_python + launch + launch_ros + + + + + ament_python + + diff --git a/sru_ws/src/sru_nav_ros2/resource/sru_nav_ros2 b/sru_ws/src/sru_nav_ros2/resource/sru_nav_ros2 new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/resource/sru_nav_ros2 @@ -0,0 +1 @@ + diff --git a/sru_ws/src/sru_nav_ros2/setup.cfg b/sru_ws/src/sru_nav_ros2/setup.cfg new file mode 100644 index 0000000..d3a6c10 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/setup.cfg @@ -0,0 +1,4 @@ +[develop] +script_dir=$base/lib/sru_nav_ros2 +[install] +install_scripts=$base/lib/sru_nav_ros2 diff --git a/sru_ws/src/sru_nav_ros2/setup.py b/sru_ws/src/sru_nav_ros2/setup.py new file mode 100644 index 0000000..0169f23 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/setup.py @@ -0,0 +1,37 @@ +import os +from glob import glob + +from setuptools import find_packages, setup + +package_name = 'sru_nav_ros2' + +setup( + name=package_name, + version='0.1.0', + packages=find_packages(exclude=['test']), + data_files=[ + # ament index marker: makes `ros2 pkg prefix` / `ros2 launch` find us. + ('share/ament_index/resource_index/packages', + ['resource/' + package_name]), + ('share/' + package_name, ['package.xml']), + # Runtime assets, reachable through ament_index_python.get_package_share_directory(). + (os.path.join('share', package_name, 'config'), glob('config/*.yaml')), + (os.path.join('share', package_name, 'launch'), glob('launch/*.launch.py')), + (os.path.join('share', package_name, 'models'), glob('models/*.onnx')), + (os.path.join('share', package_name, 'docs'), glob('docs/*.md')), + ], + install_requires=['setuptools'], + zip_safe=True, + maintainer='SRU Navigation Port', + maintainer_email='user@example.com', + description=('ROS 2 (Humble) port of the SRU navigation controller: ' + 'ONNX VAE depth encoder + SRU policy, Odin1 depth/odometry in, ' + 'geometry_msgs/Twist on /cmd_vel out.'), + license='MIT', + entry_points={ + 'console_scripts': [ + 'sru_nav_node = sru_nav_ros2.sru_nav_node:main', + 'waypoint_runner = sru_nav_ros2.waypoint_runner:main', + ], + }, +) diff --git a/sru_ws/src/sru_nav_ros2/sru_nav_ros2/__init__.py b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/__init__.py @@ -0,0 +1 @@ + diff --git a/sru_ws/src/sru_nav_ros2/sru_nav_ros2/constants.py b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/constants.py new file mode 100644 index 0000000..7941aa2 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/constants.py @@ -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 diff --git a/sru_ws/src/sru_nav_ros2/sru_nav_ros2/model.py b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/model.py new file mode 100644 index 0000000..bfcd780 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/model.py @@ -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_ros2 import constants +from sru_nav_ros2.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() diff --git a/sru_ws/src/sru_nav_ros2/sru_nav_ros2/navigation_policy_node.py b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/navigation_policy_node.py new file mode 100644 index 0000000..439a5e0 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/navigation_policy_node.py @@ -0,0 +1,1119 @@ +"""ROS 2 (rclpy) navigation policy node for the SRU controller + Odin1. + +Reverse port of the ROS 1 ``sru_nav_go2_ros1`` node, which was itself a +mechanical port of the original ROS 2 ``NavigationPolicyNode``. Behaviour is +preserved; only ROS API calls, time helpers, topic defaults and the parameter +names listed in ``ROS2_PORT_PLAN.md`` have been changed. + +Every tunable lives in a ROS 2 parameter (see ``config/sru_nav.yaml``), so no +edit here is ever needed to adapt the node to a new robot or a new Odin1 driver +build. Defaults are taken from :mod:`sru_nav_ros2.constants` so there is +exactly one source of truth on the code side. +""" + +import math +import os +import time + +import cv2 # noqa: F401 (kept for parity with the ROS 1 port; model.py imports it too) +import numpy as np +from ament_index_python.packages import PackageNotFoundError, get_package_share_directory +from cv_bridge import CvBridge +from geometry_msgs.msg import PoseStamped, Twist +from nav_msgs.msg import Odometry, Path +from rclpy.node import Node +from rclpy.qos import ( + DurabilityPolicy, + QoSHistoryPolicy, + QoSProfile, + QoSReliabilityPolicy, + qos_profile_sensor_data, +) +from rclpy.time import Time +from scipy.spatial.transform import Rotation as R +from sensor_msgs.msg import Image, Joy +from std_msgs.msg import Float64, Header +from visualization_msgs.msg import Marker + +from sru_nav_ros2 import constants +from sru_nav_ros2.model import LearningModel +from sru_nav_ros2.utils import transform_points, yaw_quat +from sru_nav_ros2.visualization import PATH_PUBLISH_INTERVAL, VisualizationManager +from sru_nav_ros2.waypoint_manager import WaypointManager + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- +def _stamp_to_sec(stamp): + """ROS 2 ``builtin_interfaces/Time`` -> float seconds. + + Careful: ROS 1 and ROS 2 name the two integer fields differently. Using the + old spelling here raises AttributeError; getting the nanosecond scaling wrong + silently corrupts the value. This value feeds the control-frequency gate + (``robot_odom_time - last_run_time < interval``), so a wrong conversion + would silently break the rate limiting and let the policy run flat out. + """ + return stamp.sec + stamp.nanosec * 1e-9 + + +# --------------------------------------------------------------------------- +# Node +# --------------------------------------------------------------------------- +class NavigationPolicyNode(Node): + """RL navigation controller node (ROS 2 Humble).""" + + def __init__(self): + super().__init__('sru_nav_node') + + self._declare_parameters() + self._load_parameters() + + # ----- Publishers ------------------------------------------------ + # Private topics keep the ROS 1 ``~`` prefix, now spelled ``~/``. + # The node name is unchanged ('sru_nav_node'), so they expand to the + # exact same fully-qualified names as before and rviz configs still + # apply. + self.cmd_vel_publisher = self.create_publisher(Twist, self.cmd_vel_topic, 10) + self.base_vel_publisher = self.create_publisher(Twist, '~/base_vel', 10) + self.goal_pose_publisher = self.create_publisher(PoseStamped, self.goal_topic, 1) + + # Visualization + self.twist_marker_publisher = self.create_publisher( + Marker, '~/vis/twist_cmd_marker', 10) + self.goal_vector_marker_publisher = self.create_publisher( + Marker, '~/vis/goal_vector_marker', 10) + self.moving_goal_marker_publisher = self.create_publisher( + Marker, '~/vis/moving_goal_marker', 10) + self.recorded_waypoints_marker_pub = self.create_publisher( + Marker, '~/vis/recorded_waypoints_marker', 10) + + # Paths: the travelled trajectory and the robot->goal straight line. + # ROS 2 additions -- the ROS 1 blueprint published no paths at all. + self.executed_path_publisher = self.create_publisher( + Path, '~/vis/executed_path', 1) + self.goal_path_publisher = self.create_publisher( + Path, '~/vis/goal_path', 1) + + # ----- Utilities -------------------------------------------------- + self.bridge = CvBridge() + + vae_model_path = self._resolve_model_path(self.vae_model_path, 'vae_encoder.onnx') + policy_model_path = self._resolve_model_path(self.policy_model_path, 'nav_policy.onnx') + self.get_logger().info('VAE encoder: {}'.format(vae_model_path)) + self.get_logger().info('Policy model: {}'.format(policy_model_path)) + + self.model = LearningModel( + preprocess_model_path=vae_model_path, + policy_model_path=policy_model_path, + policy_scale=self.policy_scale, + ) + # ROS 2 has no RospyLogger shim: the node logger already exposes + # info/warn/warning/error. + self.waypoint_manager = WaypointManager(self.get_logger()) + self.visualization_manager = VisualizationManager(self) + + # ----- Robot state ----------------------------------------------- + self.odom_ready = False + 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.arrive_goal_threshold = constants.ARRIVE_GOAL_THRESHOLD + self.last_run_time = 0.0 + self.system_delay = constants.JOYSTICK_TIMEOUT + 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 + + # ----- Goal-heading (in-place alignment) state -------------------- + # `goal_yaw_w` is None when the current goal carries no heading, which is + # what keeps the whole stage dormant and the behaviour identical to the + # ROS 1 blueprint. The rotation itself is driven by its own 20 Hz timer. + self.goal_yaw_w = None + self.yaw_align_active = False + self.yaw_align_start_time = 0.0 + self.yaw_align_last_time = 0.0 + self.yaw_settle_accum = 0.0 + + # ----- 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) + # The depth stream is sensor data: a BEST_EFFORT subscriber is + # compatible with BOTH publisher policies, while a RELIABLE subscriber + # against a BEST_EFFORT publisher silently receives nothing (a ROS 2 + # only trap). Hence BEST_EFFORT by default. + if self.depth_qos_reliable: + depth_qos = QoSProfile( + history=QoSHistoryPolicy.KEEP_LAST, + depth=2, + reliability=QoSReliabilityPolicy.RELIABLE, + ) + else: + depth_qos = qos_profile_sensor_data + + odom_qos = QoSProfile( + history=QoSHistoryPolicy.KEEP_LAST, + depth=10, + reliability=(QoSReliabilityPolicy.RELIABLE if self.odom_qos_reliable + else QoSReliabilityPolicy.BEST_EFFORT), + ) + + self.odom_subscriber = self.create_subscription( + Odometry, self.odom_topic, self.odom_callback, odom_qos) + self.depth_subscriber = self.create_subscription( + Image, self.depth_topic, self.depth_callback, depth_qos) + self.joy_subscriber = self.create_subscription( + Joy, self.joy_topic, self.joy_callback, 10) + self.target_position_subscriber = self.create_subscription( + PoseStamped, self.goal_topic, self.target_position_callback, 1) + + # Goal heading. TRANSIENT_LOCAL to match waypoint_runner's latched goal + # publisher, so a heading published before this node subscribed is still + # delivered (that is what ROS 1 `latch=True` did for the goal itself). + goal_yaw_qos = QoSProfile( + history=QoSHistoryPolicy.KEEP_LAST, + depth=1, + durability=DurabilityPolicy.TRANSIENT_LOCAL, + ) + self.goal_yaw_subscriber = self.create_subscription( + Float64, self.goal_yaw_topic, self.goal_yaw_callback, goal_yaw_qos) + + # ----- Timers ---------------------------------------------------- + # rclpy timer callbacks take no arguments, so the ROS 1 `_timer_*` + # wrappers (which only swallowed the ROS 1 TimerEvent) are gone. + self.create_timer(constants.WAYPOINT_PUBLISH_INTERVAL, + self.publish_recorded_waypoints) + self.create_timer(constants.TARGET_VECTOR_PUBLISH_INTERVAL, + self.publish_target_vector) + self.create_timer(PATH_PUBLISH_INTERVAL, self.publish_paths) + self.create_timer(1.0 / constants.SMART_JOYSTICK_UPDATE_FREQUENCY, + self.update_smart_joystick_goal) + # Goal-heading rotation runs on its OWN timer: `generate_cmd_vel` is + # driven by the depth callback (~1.5 Hz here) and is far too coarse to + # align a heading precisely. + self.create_timer(1.0 / self.goal_yaw_update_frequency, + self.update_goal_yaw) + + self.get_logger().info( + '\033[92mNavigation policy node is ready.\033[0m') + self.get_logger().info( + 'SRU navigation node spinning (odom_twist_in_base_frame={}, ' + 'require_joystick={}).'.format( + self.odom_twist_in_base_frame, self.require_joystick)) + + # ===================================================================== + # Parameters + # ===================================================================== + def _declare_parameters(self): + """Declare every runtime parameter, defaulting to the ROS 1 values.""" + d = self.declare_parameter + + # ---- Topics ------------------------------------------------------- + d('depth_topic', '/odin1/depth_img_competetion') + d('odom_topic', '/odin1/odometry_highfreq') + d('joy_topic', '/joy') + d('goal_topic', '/goal_pose') + d('cmd_vel_topic', '/cmd_vel') + + # ---- Model files (empty -> look under /sru_nav_ros2/models/) + d('vae_model_path', '') + d('policy_model_path', '') + + # ---- Depth filter ------------------------------------------------- + d('min_depth', constants.DEFAULT_MIN_DEPTH) + d('max_depth', constants.DEFAULT_MAX_DEPTH) + + # ---- Control ------------------------------------------------------ + d('control_frequency', constants.DEFAULT_CONTROL_FREQUENCY) + d('policy_scale', list(constants.POLICY_SCALE)) + + # ---- Semantics ---------------------------------------------------- + # Renamed from the ROS 1 `use_sim`: it means "the odom twist is already + # in the body frame, pass it through". Unrelated to `use_sim_time`. + d('odom_twist_in_base_frame', False) + + # ---- QoS ---------------------------------------------------------- + d('depth_qos_reliable', False) + d('odom_qos_reliable', True) + + # ---- Joystick deadman --------------------------------------------- + d('require_joystick', True) + + # ---- Joystick axis / button indices (defaults = PS5 layout) ------- + d('joy_axis_linear_x', constants.JOYSTICK_AXIS_LINEAR_X) + d('joy_axis_linear_y', constants.JOYSTICK_AXIS_LINEAR_Y) + d('joy_axis_linear_z', constants.JOYSTICK_AXIS_LINEAR_Z) + d('joy_axis_angular_z', constants.JOYSTICK_AXIS_ANGULAR_Z) + d('joy_axis_smart', constants.JOYSTICK_AXIS_SMART) + + d('joy_button_reset_hidden_state', constants.BUTTON_RESET_HIDDEN_STATE) + d('joy_button_record_waypoint', constants.BUTTON_RECORD_WAYPOINT) + d('joy_button_clear_waypoint', constants.BUTTON_CLEAR_WAYPOINT) + d('joy_button_send_goal', constants.BUTTON_SEND_GOAL) + d('joy_button_abort', constants.BUTTON_ABORT) + d('joy_button_trigger_waypoints', constants.BUTTON_TRIGGER_WAYPOINTS) + d('joy_button_forward', constants.BUTTON_FORWARD) + d('joy_button_backward', constants.BUTTON_BACKWARD) + d('joy_button_left', constants.BUTTON_LEFT) + d('joy_button_right', constants.BUTTON_RIGHT) + d('joy_button_up', constants.BUTTON_UP) + d('joy_button_down', constants.BUTTON_DOWN) + + # ---- Goal heading / in-place alignment (ROS 2 addition) ----------- + # The ROS 1 blueprint had no heading target: arrival is position-only. + d('goal_yaw_topic', '/goal_yaw') + d('goal_yaw_tolerance', 0.0873) # rad (+/- 5 deg) + d('goal_yaw_max_rate', 0.6) # rad/s + d('goal_yaw_decel', 0.8) # rad/s^2 + d('goal_yaw_update_frequency', 20.0) # Hz + d('goal_yaw_settle_time', 0.4) # s + d('goal_yaw_timeout', 15.0) # s + + def _load_parameters(self): + """Read the declared parameters into plain attributes.""" + p = self.get_parameter + + self.depth_topic = p('depth_topic').value + self.odom_topic = p('odom_topic').value + self.joy_topic = p('joy_topic').value + self.goal_topic = p('goal_topic').value + self.cmd_vel_topic = p('cmd_vel_topic').value + + self.vae_model_path = p('vae_model_path').value + self.policy_model_path = p('policy_model_path').value + + self.min_depth = float(p('min_depth').value) + self.max_depth = float(p('max_depth').value) + + self.control_frequency = float(p('control_frequency').value) + self.policy_scale = list(p('policy_scale').value) + if len(self.policy_scale) != 3: + self.get_logger().warn( + 'Invalid policy_scale {}, falling back to {}'.format( + self.policy_scale, list(constants.POLICY_SCALE))) + self.policy_scale = list(constants.POLICY_SCALE) + + self.odom_twist_in_base_frame = bool(p('odom_twist_in_base_frame').value) + self.depth_qos_reliable = bool(p('depth_qos_reliable').value) + self.odom_qos_reliable = bool(p('odom_qos_reliable').value) + self.require_joystick = bool(p('require_joystick').value) + + self.joy_axis_linear_x = int(p('joy_axis_linear_x').value) + self.joy_axis_linear_y = int(p('joy_axis_linear_y').value) + self.joy_axis_linear_z = int(p('joy_axis_linear_z').value) + self.joy_axis_angular_z = int(p('joy_axis_angular_z').value) + self.joy_axis_smart = int(p('joy_axis_smart').value) + + self.joy_button_reset_hidden_state = int(p('joy_button_reset_hidden_state').value) + self.joy_button_record_waypoint = int(p('joy_button_record_waypoint').value) + self.joy_button_clear_waypoint = int(p('joy_button_clear_waypoint').value) + self.joy_button_send_goal = int(p('joy_button_send_goal').value) + self.joy_button_abort = int(p('joy_button_abort').value) + self.joy_button_trigger_waypoints = int(p('joy_button_trigger_waypoints').value) + self.joy_button_forward = int(p('joy_button_forward').value) + self.joy_button_backward = int(p('joy_button_backward').value) + self.joy_button_left = int(p('joy_button_left').value) + self.joy_button_right = int(p('joy_button_right').value) + self.joy_button_up = int(p('joy_button_up').value) + self.joy_button_down = int(p('joy_button_down').value) + + self.goal_yaw_topic = p('goal_yaw_topic').value + self.goal_yaw_tolerance = float(p('goal_yaw_tolerance').value) + self.goal_yaw_max_rate = float(p('goal_yaw_max_rate').value) + self.goal_yaw_decel = float(p('goal_yaw_decel').value) + self.goal_yaw_update_frequency = float(p('goal_yaw_update_frequency').value) + self.goal_yaw_settle_time = float(p('goal_yaw_settle_time').value) + self.goal_yaw_timeout = float(p('goal_yaw_timeout').value) + if self.goal_yaw_update_frequency <= 0.0: + self.get_logger().warn( + 'goal_yaw_update_frequency must be > 0, falling back to 20.0 Hz') + self.goal_yaw_update_frequency = 20.0 + + def _resolve_model_path(self, param_value, default_basename): + """Resolve a model path. + + An absolute path that exists wins; otherwise the installed + ``/sru_nav_ros2/models/`` is used. (The ROS 1 port also + probed a sibling ``sru-robot-deployment`` checkout; that path was a + development convenience tied to the ROS 1 catkin layout and does not + translate to an installed ament package, so it was dropped.) + """ + if param_value and os.path.isabs(param_value) and os.path.exists(param_value): + return param_value + + candidates = [] + if param_value: + candidates.append(param_value) + try: + share = get_package_share_directory('sru_nav_ros2') + candidates.append(os.path.join(share, 'models', default_basename)) + except PackageNotFoundError: + self.get_logger().warn( + 'Package sru_nav_ros2 not found on the ament index; ' + 'cannot auto-discover models.') + + 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)) + + # ===================================================================== + # 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) Pass-through (odom twist already in body frame) or rotate into it + if self.odom_twist_in_base_frame: + 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: + self.get_logger().warn( + '\033[93mOdometry not ready, skipping depth callback.\033[0m', + throttle_duration_sec=5.0) + 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: + self.get_logger().error('Error converting depth image: {}'.format(e)) + return + + # Respect control frequency (gated on the ODOM clock, not wall time) + 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: + self.get_logger().info( + 'Smart joystick mode active - Goal: [{:.2f}, {:.2f}, {:.2f}]'.format( + self.smart_joystick_goal[0], self.smart_joystick_goal[1], + self.smart_joystick_goal[2], + ), + throttle_duration_sec=1.0) + + is_arrived = self._check_goal_reached(self.target_pos_w, self.robot_pos_w) + if is_arrived or self.is_abort_goal: + twist = Twist() + if self._yaw_stage_pending(): + # Goal-heading stage in progress: the 20 Hz `update_goal_yaw` + # timer owns /cmd_vel until the heading is aligned. Publish + # nothing here -- these zeros would fight its rotation -- and do + # not release the goal yet. + self.get_logger().info( + 'Position reached; aligning to the goal heading ...', + throttle_duration_sec=2.0) + else: + 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() + self.get_logger().info('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 + self.get_logger().warn( + '\033[93mJoystick timeout, stopping the robot. Time diff: ' + '{:.4f}s\033[0m'.format(diff), + throttle_duration_sec=2.0) + + self.get_logger().info( + 'cmd_vel_ratio: {:.4f} (require_joystick={})'.format( + self.cmd_vel_ratio, self.require_joystick), + throttle_duration_sec=1.0) + + 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: + self.get_logger().warn('\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, + ) + + self.get_logger().info( + 'Published cmd_vel: linear_x={:.4f}, linear_y={:.4f}, angular_z={:.4f}'.format( + twist.linear.x, twist.linear.y, twist.angular.z), + throttle_duration_sec=1.0) + 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( + self.joy_axis_linear_x, + self.joy_axis_linear_y, + self.joy_axis_linear_z, + self.joy_axis_angular_z, + self.joy_axis_smart, + 4): + self.get_logger().warn( + 'Joy message has too few axes; ignoring.', throttle_duration_sec=5.0) + return + + self.cmd_vel_ratio = (1.0 + joy_msg.axes[4]) * 1.0 + + if (len(joy_msg.buttons) > self.joy_button_abort and + joy_msg.buttons[self.joy_button_abort] == 1): + self.is_abort_goal = True + self.get_logger().warn('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) > self.joy_button_send_goal + and joy_msg.buttons[self.joy_button_send_goal] == 1): + self.get_logger().warn('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) > self.joy_button_record_waypoint + and joy_msg.buttons[self.joy_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) > self.joy_button_clear_waypoint + and joy_msg.buttons[self.joy_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) > self.joy_button_trigger_waypoints + and joy_msg.buttons[self.joy_button_trigger_waypoints] == 1): + self.get_logger().warn('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[self.joy_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 + self.get_logger().info( + 'Smart joystick mode: aborting current navigation goal') + + self.latest_joystick_axes = [ + joy_msg.axes[self.joy_axis_linear_x], + joy_msg.axes[self.joy_axis_linear_y], + joy_msg.axes[self.joy_axis_linear_z], + ] + else: + if self.smart_joystick_mode_active: + self.smart_joystick_mode_active = False + self.is_abort_goal = True + self.get_logger().info( + 'Exiting smart joystick mode: aborting current navigation goal') + + self._reset_smart_joystick_goal() + self.joy_linear_x = ( + joy_msg.axes[self.joy_axis_linear_x] + * constants.LINEAR_SCALE * 1.5) + self.joy_linear_y = ( + joy_msg.axes[self.joy_axis_linear_y] + * constants.LINEAR_SCALE) + self.joy_angular_z = ( + joy_msg.axes[self.joy_axis_angular_z] + * constants.ANGULAR_SCALE) + + if (len(joy_msg.buttons) > self.joy_button_reset_hidden_state and + joy_msg.buttons[self.joy_button_reset_hidden_state] == 1): + self.is_reset_hidden_state = True + self.get_logger().warn('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: + self.get_logger().warn( + 'Cannot publish smart joystick goal: robot pose not available', + throttle_duration_sec=5.0) + 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] + + def _moving_xyz_with_buttons(self, joy_msg, scale=1.0): + # Not a staticmethod any more: the button indices are per-instance + # parameters now. + def b(idx): + return bool(joy_msg.buttons[idx]) if idx < len(joy_msg.buttons) else False + + dx = scale * (b(self.joy_button_forward) - b(self.joy_button_backward)) + dy = scale * (b(self.joy_button_left) - b(self.joy_button_right)) + dz = (scale / 5.0) * (b(self.joy_button_up) - b(self.joy_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 = Time(seconds=self.robot_odom_time).to_msg() + 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: + self.get_logger().warn( + '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 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() + self.get_logger().info( + 'Publishing next waypoint: {}'.format(next_wp)) + self._publish_goal(next_wp) + else: + self.get_logger().info( + 'Tracking the current waypoint ...', throttle_duration_sec=1.0) + + 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() + self.get_logger().info( + 'Publishing next inversed waypoint: {}'.format(next_wp)) + self._publish_goal(next_wp) + else: + self.get_logger().info( + 'Tracking the current waypoint ...', throttle_duration_sec=1.0) + + 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 publish_paths(self): + """Publish the travelled trajectory and the robot->goal straight line. + + Both are ``nav_msgs/Path`` in the odometry frame, so rviz draws them as + ordinary lines. Note what they mean: the policy is reactive, so NEITHER + is a "planned path" -- there is no planner in this node. They show what + actually happened and which goal is currently being chased, which is what + you need in order to judge the policy's behaviour visually. + """ + if self.robot_pos_w is None: + return + + self.visualization_manager.publish_executed_path( + self.robot_pos_w, self.map_frame_id, self.robot_odom_time, + self.executed_path_publisher, + ) + + goal = self.target_pos_w if self.target_pos_w is not None else self.last_target_pos + if goal is None: + return + + self.visualization_manager.publish_goal_path( + self.robot_pos_w, goal, self.map_frame_id, self.robot_odom_time, + self.goal_path_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 heading / in-place alignment -- ROS 2 addition + # + # The policy cannot express a goal heading at all (its 16-dim state carries + # only a body-frame direction + log distance, and arrival is position-only), + # so once the position goal has been reached this node rotates in place with + # its own controller until the heading is aligned, and only then releases the + # goal. Everything here is dormant while no heading is published. + # ===================================================================== + def goal_yaw_callback(self, msg): + """Receive the heading requirement for the current goal (rad, odom frame). + + NaN is the explicit "no heading required" value -- that is also what + waypoint_runner publishes for waypoints that carry no 4th number. + """ + yaw = float(msg.data) + if math.isnan(yaw): + if self.goal_yaw_w is not None: + self.get_logger().info('Goal heading cleared.') + self.goal_yaw_w = None + return + + # Normalise to (-pi, pi] so logs match what the controller sees. + self.goal_yaw_w = math.atan2(math.sin(yaw), math.cos(yaw)) + self.get_logger().info( + 'Received goal heading: {:.4f} rad ({:.1f} deg)'.format( + self.goal_yaw_w, math.degrees(self.goal_yaw_w))) + + def _is_new_goal_position(self, new_pos): + """True when `new_pos` differs from the goal currently being tracked. + + waypoint_runner re-publishes the same goal every few seconds; those + re-publishes must not wipe the heading requirement mid-alignment. + """ + if self.target_pos_w is None: + return True + return (abs(new_pos[0] - self.target_pos_w[0]) > 1e-2 + or abs(new_pos[1] - self.target_pos_w[1]) > 1e-2) + + def _yaw_stage_pending(self): + """True while the goal heading still has to be aligned ("do not release"). + + Deliberately a side-effect-free predicate -- no logging, no publishing. + It is called from both the ~1.5 Hz control tick and the 20 Hz yaw timer, + and only `update_goal_yaw` is allowed to command the rotation. + """ + if self.goal_yaw_w is None or self.is_abort_goal: + return False + if self.target_pos_w is None or self.robot_pos_w is None: + return False + dist = np.linalg.norm( + np.array(self.target_pos_w[:2]) - np.array(self.robot_pos_w[:2])) + return bool(dist <= self.arrive_goal_threshold) + + def _goal_yaw_error(self): + """Signed shortest-arc heading error [rad], wrapped to (-pi, pi].""" + # Quaternion is (w, x, y, z); scipy expects (x, y, z, w). + quat_xyzw = [self.robot_orientation_w[1], self.robot_orientation_w[2], + self.robot_orientation_w[3], self.robot_orientation_w[0]] + yaw = R.from_quat(quat_xyzw).as_euler('zyx')[0] + return math.atan2(math.sin(self.goal_yaw_w - yaw), + math.cos(self.goal_yaw_w - yaw)) + + def _start_yaw_alignment(self): + self.yaw_align_active = True + self.yaw_align_start_time = self.robot_odom_time + self.yaw_align_last_time = self.robot_odom_time + self.yaw_settle_accum = 0.0 + self.get_logger().info( + '\033[96mGoal heading stage: rotating in place to {:.1f} deg ' + '(tolerance {:.1f} deg, max rate {:.2f} rad/s).\033[0m'.format( + math.degrees(self.goal_yaw_w), + math.degrees(self.goal_yaw_tolerance), + self.goal_yaw_max_rate)) + + def _finish_yaw_alignment(self, residual): + if residual is None: + self.get_logger().warn( + '\033[93mGoal heading abandoned; goal released as-is.\033[0m') + else: + self.get_logger().info( + '\033[92mGoal heading aligned: residual error {:.2f} deg ' + '(took {:.1f}s).\033[0m'.format( + math.degrees(residual), + self.robot_odom_time - self.yaw_align_start_time)) + self.yaw_align_active = False + self.yaw_settle_accum = 0.0 + self.goal_yaw_w = None + # Release the goal here so the stage cannot re-arm on the runner's next + # periodic re-publish of that same waypoint. The ~1.5 Hz control tick + # then does its usual zero + 'Target position reset.' bookkeeping. + self.target_pos_w = None + # Command an explicit stop -- the control tick may be up to 0.66 s away. + self.cmd_vel_publisher.publish(Twist()) + + def update_goal_yaw(self): + """In-place rotation stage: ~20 Hz, paced by the odom clock.""" + if not self.yaw_align_active: + if self._yaw_stage_pending(): + self._start_yaw_alignment() + return + + if self.robot_orientation_w is None: + return + + if self.is_abort_goal or self.target_pos_w is None: + # Goal aborted or released elsewhere: drop out without claiming + # success and without touching the caller's goal bookkeeping. + self.get_logger().warn( + 'Goal-heading alignment cancelled (goal aborted or released).', + throttle_duration_sec=2.0) + self.yaw_align_active = False + self.yaw_settle_accum = 0.0 + self.goal_yaw_w = None + self.cmd_vel_publisher.publish(Twist()) + return + + now = self.robot_odom_time + dt = now - self.yaw_align_last_time + self.yaw_align_last_time = now + if dt <= 0.0: + dt = 1.0 / self.goal_yaw_update_frequency + + # The deadman still applies: never keep rotating on a stale joystick. + if self.require_joystick and (now - self.joy_time > self.system_delay): + self.get_logger().warn( + 'Joystick timeout during goal-heading alignment; aborting.', + throttle_duration_sec=2.0) + self._finish_yaw_alignment(None) + return + + error = self._goal_yaw_error() + + # Settle check: staying inside the tolerance for `settle_time` is what + # makes the result repeatable instead of "it stopped somewhere in band". + if abs(error) <= self.goal_yaw_tolerance: + self.yaw_settle_accum += dt + if self.yaw_settle_accum >= self.goal_yaw_settle_time: + self._finish_yaw_alignment(error) + return + else: + self.yaw_settle_accum = 0.0 + + if (now - self.yaw_align_start_time) > self.goal_yaw_timeout: + self.get_logger().warn( + 'Goal heading not reached within {:.1f}s (residual {:.1f} deg); ' + 'giving up.'.format( + self.goal_yaw_timeout, math.degrees(error))) + self._finish_yaw_alignment(None) + return + + # Braking profile: full rate far away, tapering to zero at the target, so + # the rotation cannot overshoot the band it is aiming for. + rate = min(self.goal_yaw_max_rate, + math.sqrt(2.0 * self.goal_yaw_decel * abs(error))) + twist = Twist() + twist.angular.z = math.copysign(rate, error) + self.cmd_vel_publisher.publish(twist) + + # ===================================================================== + # 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 + self.get_logger().info('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 + self.get_logger().info('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: + self.get_logger().error( + '\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: + self.get_logger().warn( + 'Robot position not available, using received z for target.') + + new_pos = [msg.pose.position.x, msg.pose.position.y, goal_z] + if self._is_new_goal_position(new_pos): + # A new goal carries no heading until one is published for it. This + # is also what lets a heading-less goal cancel a pending alignment. + self.goal_yaw_w = None + + self.target_pos_w = new_pos + self.last_target_pos = list(new_pos) + + self.get_logger().info( + '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] + self.get_logger().info('Reset moving goal delta.') diff --git a/sru_ws/src/sru_nav_ros2/sru_nav_ros2/sru_nav_node.py b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/sru_nav_node.py new file mode 100644 index 0000000..6b8f338 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/sru_nav_node.py @@ -0,0 +1,34 @@ +"""Console entry point for the SRU navigation controller (ROS 2 Humble). + +Installed as the ``sru_nav_node`` executable through ``setup.py`` +``console_scripts``:: + + ros2 run sru_nav_ros2 sru_nav_node + +It owns only the rclpy lifecycle. Everything else -- parameter declaration, +model resolution, publishers, subscribers and timers -- lives in +:class:`~sru_nav_ros2.navigation_policy_node.NavigationPolicyNode`. +""" + +import rclpy + +from sru_nav_ros2.navigation_policy_node import NavigationPolicyNode + + +def main(args=None): + rclpy.init(args=args) + node = None + try: + node = NavigationPolicyNode() + rclpy.spin(node) + except KeyboardInterrupt: + pass + finally: + if node is not None: + node.destroy_node() + if rclpy.ok(): + rclpy.shutdown() + + +if __name__ == '__main__': + main() diff --git a/sru_ws/src/sru_nav_ros2/sru_nav_ros2/utils.py b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/utils.py new file mode 100644 index 0000000..87b439b --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/utils.py @@ -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 diff --git a/sru_ws/src/sru_nav_ros2/sru_nav_ros2/visualization.py b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/visualization.py new file mode 100644 index 0000000..0d60271 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/visualization.py @@ -0,0 +1,232 @@ +"""Visualization utilities for the SRU navigation controller (ROS 2 port).""" + +from collections import deque + +import numpy as np +from geometry_msgs.msg import Point, PoseStamped, Quaternion, Vector3 +from nav_msgs.msg import Path +from rclpy.time import Time +from std_msgs.msg import Header +from visualization_msgs.msg import Marker + +from sru_nav_ros2 import constants +from sru_nav_ros2.utils import transform_points, yaw_quat + + +# --------------------------------------------------------------------------- +# Path (trajectory) visualization. +# +# ROS 2 ADDITION -- the ROS 1 blueprint had no path output at all. Nothing here +# is a "planned path": the policy is reactive and end-to-end, so there is no +# planner and no route to draw. What these two topics show is (a) where the +# robot has actually been and (b) which goal it is currently chasing. +# --------------------------------------------------------------------------- +PATH_PUBLISH_INTERVAL = 1.0 # seconds; also the trajectory sampling period +PATH_MAX_POINTS = 600 # trail cap (~10 min at 1 Hz); keeps the message small + + +class VisualizationManager: + """Manages visualization markers for the navigation controller.""" + + def __init__(self, node=None): + # The `node` argument used to be dead weight ("retained for API parity, + # not used in ROS1"). Under ROS 2 it is genuinely needed: every marker + # stamp is produced through this node's clock. + self.node = node + # Travelled trajectory, in the odometry frame. Bounded, so publishing + # it stays cheap no matter how long the node runs. + self._trail = deque(maxlen=PATH_MAX_POINTS) + + def _stamp_from_sec(self, sec): + """Build a ``builtin_interfaces/msg/Time`` for an absolute float-seconds value. + + ROS 2 counterpart of the ROS 1 global ``Time.from_sec()``. The numeric value + is preserved: the odom timestamp is converted as-is and is NOT replaced by + the current time. Only the clock type is taken from the injected node, so + the stamp stays on the same clock the node runs on. + """ + return Time( + seconds=float(sec), + clock_type=self.node.get_clock().clock_type, + ).to_msg() + + 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 = self._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 = self._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 = self._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. + + This is the one marker whose stamp genuinely means "now" (the ROS 1 port + used the global ``Time.now()`` here), so it reads the injected node's clock. + """ + if map_frame_id is None: + return + + marker = Marker() + marker.header.stamp = self.node.get_clock().now().to_msg() + 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) + + # ------------------------------------------------------------------- + # Paths (ros2 addition -- see the note above the constants) + # ------------------------------------------------------------------- + def publish_executed_path(self, robot_pos_w, map_frame_id, robot_odom_time, publisher): + """Append the current pose to the travelled trajectory and republish it. + + The trail is sampled once per call, so the caller's timer period is both + the sampling period and the publish period. + """ + if robot_pos_w is None or map_frame_id is None: + return + + self._trail.append(tuple(float(v) for v in robot_pos_w)) + publisher.publish(self._build_path( + list(self._trail), map_frame_id, robot_odom_time)) + + def publish_goal_path(self, robot_pos_w, goal_pos_w, map_frame_id, robot_odom_time, publisher): + """Straight line from the robot to the goal it is currently chasing. + + Two poses only, so it is cheap enough to refresh at the control rate. + """ + if robot_pos_w is None or goal_pos_w is None or map_frame_id is None: + return + + publisher.publish(self._build_path( + [tuple(float(v) for v in robot_pos_w), + tuple(float(v) for v in goal_pos_w)], + map_frame_id, robot_odom_time)) + + def _build_path(self, points, frame_id, robot_odom_time): + path = Path() + path.header = Header() + path.header.stamp = self._stamp_from_sec(robot_odom_time) + path.header.frame_id = frame_id + + for point in points: + pose = PoseStamped() + pose.header = path.header + pose.pose.position.x = point[0] + pose.pose.position.y = point[1] + pose.pose.position.z = point[2] + pose.pose.orientation.w = 1.0 + path.poses.append(pose) + + return path diff --git a/sru_ws/src/sru_nav_ros2/sru_nav_ros2/waypoint_manager.py b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/waypoint_manager.py new file mode 100644 index 0000000..baab7ae --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/waypoint_manager.py @@ -0,0 +1,139 @@ +"""Waypoint management for the SRU navigation controller (ROS 2 port). + +This module is logger-agnostic: pass any object exposing .info/.warn/.warning/.error. +Under ROS 2 you pass the node's own logger, i.e. ``node.get_logger()`` +(``rclpy.impl.rcutils_logger.RcutilsLogger``), which already provides all four +methods. The ROS 1 ``RospyLogger`` shim that wrapped the module-level loginfo / +logwarn helpers therefore has no counterpart here and was dropped. +""" + +from collections import deque + + +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 diff --git a/sru_ws/src/sru_nav_ros2/sru_nav_ros2/waypoint_runner.py b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/waypoint_runner.py new file mode 100644 index 0000000..bdf14f7 --- /dev/null +++ b/sru_ws/src/sru_nav_ros2/sru_nav_ros2/waypoint_runner.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +"""Sequential waypoint runner for sru_nav_ros2 (ROS 2 Humble). + +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. + +A waypoint may also carry a GOAL HEADING (the optional 4th number, in RADIANS, +odom frame). It is published on its own latched topic (`goal_yaw_topic`) as a +std_msgs/Float64, where NaN means "no heading requirement"; the navigation node +rotates in place to align after reaching the position. This runner additionally +waits for that heading before advancing, so it never walks a waypoint list +mid-rotation. + +It does NOT touch the navigation node: it is purely an external client on top of +the existing /goal_pose + /goal_yaw + /odin1/odometry_highfreq contract. + +Usage +----- + # YAML file + ros2 run sru_nav_ros2 waypoint_runner --file waypoints.yaml + + # Command line (x,y[,z[,yaw]] tuples separated by spaces) + ros2 run sru_nav_ros2 waypoint_runner --waypoints "3,0 3,2 0,2" + + # Only the LAST waypoint requires a heading: leave the earlier ones at x,y + ros2 run sru_nav_ros2 waypoint_runner --waypoints "1,0 2,0 3,0,0,1.5708" + +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 + goal_yaw_topic: /goal_yaw # std_msgs/Float64, radians + goal_yaw_tolerance: 0.0873 # radians (5 deg); match the node's parameter + goal_yaw_settle_time: 0.4 # seconds the heading must hold inside tolerance + waypoints: + - [3.0, 0.0, 0.0] # position only + - [3.0, 2.0, 0.0, 1.5708] # position + heading (rad) +""" + +import argparse +import collections +import math +import sys +import time + +import rclpy +import yaml +from geometry_msgs.msg import PoseStamped +from nav_msgs.msg import Odometry +from rclpy.node import Node +from rclpy.qos import DurabilityPolicy, QoSHistoryPolicy, QoSProfile +from rclpy.utilities import remove_ros_args +from scipy.spatial.transform import Rotation as R +from std_msgs.msg import Float64 + + +# --------------------------------------------------------------------------- +# Defaults (mirror sru_nav_ros2/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', + # Goal heading (ROS 2 addition). Published on its own latched topic, so a + # position-only goal stays exactly as it was before this feature existed. + goal_yaw_topic='/goal_yaw', + goal_yaw_tolerance=0.0873, # rad (+/- 5 deg), must match the node's + goal_yaw_settle_time=0.4, # s the heading must hold inside tolerance +) + + +# --------------------------------------------------------------------------- +# Parsing +# --------------------------------------------------------------------------- +def _parse_inline_waypoints(text): + """Parse "x,y[,z[,yaw]] x,y[,z[,yaw]] ..." into list[list[float|None]]. + + The heading is the 4th number, in RADIANS, in the same frame as the position + (odom). A waypoint that omits it carries no heading and -- since the runner + publishes NaN for it -- the node simply does not rotate there. So "only the + last waypoint needs a heading" is expressed just by leaving the earlier ones + at 2 or 3 numbers: --waypoints "1,0 2,0 3,0,0,1.5708" + """ + out = [] + if not text: + return out + for tok in text.split(): + parts = tok.split(',') + if len(parts) not in (2, 3, 4): + raise ValueError( + "Bad waypoint '{}': expected 'x,y' / 'x,y,z' / 'x,y,z,yaw'".format(tok)) + out.append([ + float(parts[0]), + float(parts[1]), + float(parts[2]) if len(parts) >= 3 else 0.0, + float(parts[3]) if len(parts) == 4 else None, + ]) + 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, 4): + raise ValueError( + "Bad waypoint {} (need 2, 3 or 4 floats; the 4th is the goal " + "heading in radians).".format(wp)) + x = float(wp[0]); y = float(wp[1]) + z = float(wp[2]) if len(wp) >= 3 else 0.0 + yaw = float(wp[3]) if len(wp) == 4 else None + norm.append([x, y, z, yaw]) + 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.goal_yaw_tolerance is not None: + cfg['goal_yaw_tolerance'] = float(args.goal_yaw_tolerance) + 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(Node): + def __init__(self, cfg, odom_wait_timeout=30.0): + super().__init__('waypoint_runner') + 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._yaw = None # latest yaw [rad], odom frame + + self._log_config() + + # ROS 1 used queue_size=1, latch=True. `latch` has no direct ROS 2 + # equivalent; the idiomatic replacement is a TRANSIENT_LOCAL durability + # publisher. (It only matters for a late-joining TRANSIENT_LOCAL + # subscriber; the navigation node subscribes VOLATILE, exactly like the + # ROS 1 node did, so live-delivery behaviour is unchanged.) + goal_qos = QoSProfile( + history=QoSHistoryPolicy.KEEP_LAST, + depth=1, + durability=DurabilityPolicy.TRANSIENT_LOCAL, + ) + self.goal_pub = self.create_publisher(PoseStamped, cfg['goal_topic'], goal_qos) + # Goal heading travels on its own latched topic. A position-only goal + # therefore publishes NaN here, which the node reads as "no heading + # requirement" -- that is what keeps backward compatibility exact. + self.goal_yaw_pub = self.create_publisher( + Float64, cfg['goal_yaw_topic'], goal_qos) + self.odom_sub = self.create_subscription( + Odometry, cfg['odom_topic'], self._odom_cb, 20) + + self.get_logger().info( + "waypoint_runner: waiting for first odom on '{}' ...".format( + cfg['odom_topic'])) + self._wait_for_odom(timeout=odom_wait_timeout) + self._home = (self._pose[0], self._pose[1], self._pose[2]) + self.get_logger().info( + 'waypoint_runner: home pose captured at x={:.3f} y={:.3f} z={:.3f}'.format( + *self._home)) + + # Give the publisher a moment so the first goal isn't lost. + time.sleep(0.5) + + # --------------------------------------------------------------- logging + def _log_config(self): + self.get_logger().info('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', + 'goal_yaw_topic', 'goal_yaw_tolerance', 'goal_yaw_settle_time'): + self.get_logger().info(' {} = {!r}'.format(k, self.cfg[k])) + self.get_logger().info( + ' waypoints ({}):'.format(len(self.cfg['waypoints']))) + for i, wp in enumerate(self.cfg['waypoints'], 1): + # The yaw is echoed in degrees as well: it is radians on the wire, + # and seeing both makes a unit slip obvious at a glance. + yaw_txt = ('none' if wp[3] is None + else '{:.4f} rad ({:.1f} deg)'.format(wp[3], math.degrees(wp[3]))) + self.get_logger().info( + ' {:2d}: ({:.3f}, {:.3f}, {:.3f}) yaw={}'.format( + i, wp[0], wp[1], wp[2], yaw_txt)) + + # --------------------------------------------------------------- callbacks + def _odom_cb(self, msg): + # ROS 1 read the stamp as float seconds and fell back to the current ROS + # time when it was zero; ROS 2 spells the two integer fields sec/nanosec + # and reads "now" from the node clock. + stamp = msg.header.stamp + t = stamp.sec + stamp.nanosec * 1e-9 + if not t: + t = self.get_clock().now().nanoseconds * 1e-9 + p = msg.pose.pose.position + self._pose = (p.x, p.y, p.z, t) + # Base heading in the odom frame, needed for the goal-heading check. + q = msg.pose.pose.orientation + self._yaw = R.from_quat([q.x, q.y, q.z, q.w]).as_euler('zyx')[0] + 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 _spin_once(self, timeout_sec): + """Pump callbacks for up to `timeout_sec`. + + `rclpy.spin()` is single-threaded, so the scripted loop below drives the + executor itself; that also replaces the ROS 1 fixed-rate sleep as the loop + pacing mechanism. + """ + rclpy.spin_once(self, timeout_sec=timeout_sec) + + def _wait_for_odom(self, timeout): + t0 = time.time() + while rclpy.ok() 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)) + self._spin_once(0.05) + + # ------------------------------------------------------------------ goals + def _publish_goal(self, wp): + """Publish a waypoint: position on the goal topic, heading on the yaw topic. + + Both are latched and are sent together so the node can pair them; a + heading-less waypoint sends NaN, which means "no heading requirement". + """ + msg = PoseStamped() + msg.header.stamp = self.get_clock().now().to_msg() + msg.header.frame_id = self.cfg['frame_id'] + msg.pose.position.x = float(wp[0]) + msg.pose.position.y = float(wp[1]) + msg.pose.position.z = float(wp[2]) + msg.pose.orientation.w = 1.0 + self.goal_pub.publish(msg) + + yaw_msg = Float64() + yaw_msg.data = float('nan') if wp[3] is None else float(wp[3]) + self.goal_yaw_pub.publish(yaw_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: the odometry callback 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, wp, label): + cfg = self.cfg + xyz = wp[:3] + yaw_goal = wp[3] + self.get_logger().info( + '\033[96m[{}/{} {}] -> x={:.3f} y={:.3f} z={:.3f}{}\033[0m'.format( + idx, total, label, xyz[0], xyz[1], xyz[2], + '' if yaw_goal is None + else ' yaw={:.4f} rad ({:.1f} deg)'.format( + yaw_goal, math.degrees(yaw_goal)))) + self._publish_goal(wp) + + t_start = time.time() + t_last_pub = t_start + within_since = None + + while rclpy.ok(): + now = time.time() + elapsed = now - t_start + + # 1) Timeout + if elapsed > cfg['per_goal_timeout']: + self.get_logger().warn( + '[{}/{} {}] TIMEOUT after {:.1f}s; skipping.'.format( + 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']: + self.get_logger().warn( + '[{}/{} {}] STUCK (disp={:.3f}m < {:.3f}m in last {:.1f}s); ' + 'skipping.'.format( + idx, total, label, disp, cfg['stuck_displacement'], + cfg['stuck_window'])) + return 'stuck' + + # 3) Arrived? Position always; heading too when this waypoint asked + # for one. The node rotates in place after reaching the position, + # so waiting for the heading here is what keeps the runner from + # advancing to the next waypoint mid-rotation. + x, y, _z, _t = self._pose + d = self._xy_dist(x, y, xyz[0], xyz[1]) + pos_ok = d <= cfg['arrive_threshold'] + + yaw_err = None + yaw_ok = True + if yaw_goal is not None: + if self._yaw is None: + yaw_ok = False + else: + yaw_err = math.atan2(math.sin(yaw_goal - self._yaw), + math.cos(yaw_goal - self._yaw)) + yaw_ok = abs(yaw_err) <= cfg['goal_yaw_tolerance'] + + if pos_ok and yaw_ok: + if within_since is None: + within_since = now + elif (now - within_since) >= cfg['settle_time']: + detail = 'd={:.2f}m'.format(d) + if yaw_err is not None: + detail += ', yaw_err={:.1f}deg'.format(math.degrees(yaw_err)) + self.get_logger().info( + '\033[92m[{}/{} {}] ARRIVED ({}, settled {:.1f}s)' + '\033[0m'.format(idx, total, label, detail, 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(wp) + t_last_pub = now + self.get_logger().info( + '[{}/{} {}] re-published goal (d={:.2f}m, t={:.1f}s)'.format( + idx, total, label, d, elapsed), + throttle_duration_sec=5.0) + + self._spin_once(0.1) + return 'shutdown' + + def run(self): + cfg = self.cfg + wps = list(cfg['waypoints']) + if cfg['return_home']: + # Home carries no heading: returning is a pure position goal. + wps.append([self._home[0], self._home[1], self._home[2], None]) + 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 not rclpy.ok(): + break + + # Summary + self.get_logger().info( + '\033[95m===== waypoint_runner summary =====\033[0m') + for i, label, wp, res in results: + yaw_txt = 'none' if wp[3] is None else '{:.1f}deg'.format( + math.degrees(wp[3])) + self.get_logger().info( + ' {:2d}/{} {} ({:.2f}, {:.2f}, {:.2f}) yaw={} -> {}'.format( + i, total, label, wp[0], wp[1], wp[2], yaw_txt, res)) + self.get_logger().info( + '\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[,yaw]]" tuples (overrides YAML). ' + 'The optional 4th number is a goal heading in RADIANS.') + 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.') + p.add_argument('--goal-yaw-tolerance', type=float, default=None, + help='Heading tolerance in RADIANS for waypoints that carry a ' + 'yaw (default 0.0873 = 5 deg). Must match the node\'s ' + 'goal_yaw_tolerance.') + 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=None): + # `ros2 run` / launch may append ROS-specific arguments (`--ros-args ...`); + # strip them before argparse sees them. This replaces the ROS 1 + # argument-filtering helper. + argv = sys.argv if args is None else args + script_argv = remove_ros_args(argv)[1:] + + try: + cfg = build_config(parse_args(script_argv)) + except (ValueError, OSError) as exc: + sys.stderr.write('[waypoint_runner] config error: {}\n'.format(exc)) + sys.exit(2) + + rclpy.init(args=argv) + runner = None + try: + runner = WaypointRunner(cfg) + runner.run() + except KeyboardInterrupt: + pass + finally: + if runner is not None: + runner.destroy_node() + if rclpy.ok(): + rclpy.shutdown() + + +if __name__ == '__main__': + main() diff --git a/sru_ws/src/techx_r2_chassis_control/config/chassis_serial.yaml b/sru_ws/src/techx_r2_chassis_control/config/chassis_serial.yaml new file mode 100644 index 0000000..3c80cdf --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/config/chassis_serial.yaml @@ -0,0 +1,63 @@ +# ============================================================================= +# chassis_serial_node — 运行参数(R2 底盘串口桥) +# +# 本文件是本节点所有可调项的**唯一真源**。launch/chassis_serial.launch.py 里 port 的 +# launch 参数默认值就是从这里反读的,因此 launch 文件不可能再与它冲突。ROS 2 中 +# parameters 列表按顺序应用、后者胜,所以 launch 文件只可能覆盖 port,且只在你显式 +# 传 port:=... 时才发生。 +# +# install 出来的是**拷贝**(setup.py 用拷贝方式安装 config/*.yaml),所以改 src/ 下的 +# 本文件必须重新编译才生效。想改完即用、免重建,就把它直接指给节点: +# ros2 launch techx_r2_chassis_control chassis_serial.launch.py \ +# params_file:=$HOME/sru_ws/src/techx_r2_chassis_control/config/chassis_serial.yaml +# ============================================================================= + +chassis_serial_node: + ros__parameters: + + # 串口设备。两种命名风格**只能选一种**,并与你的 udev 规则保持一致 + # —— 本包不自带 .rules 文件: + # /dev/ttyUSB0 内核原始名;与枚举顺序有关,重启或插入其他 USB 串口设备后 + # 可能改名 + # /dev/r2_chassis 绑定到适配器序列号的 udev 稳定别名(需你自建规则) + # 请在真机上核实:这两个路径在裸开发机上都不存在,且节点打不开设备时会直接抛错。 + port: /dev/ttyUSB0 + + baudrate: 115200 + + # 这个值会传给 serial.Serial(),但节点**从不回读**任何帧 + # (见 protocol.py:只做 上位机 -> STM32 单向),所以它对行为完全无影响。 + serial_timeout_sec: 0.02 + + # 下行发帧率。**固定定时器**:每隔 1/velocity_rate_hz 秒就写一帧,与 /cmd_vel 到达 + # 快慢无关,因此数值没变时也在重发同样的字节。带宽不是瓶颈 —— 每帧 10 B,按此速率 + # 只占 115200 8N1 的约 2.6%。 + velocity_rate_hz: 30.0 + + # /cmd_vel 静默超过这么久,就进入 stale 分支(见下方 send_zero_on_timeout)。 + # 注意:上游策略发 /cmd_vel 的实际速率只有约 1.4-1.7 Hz(周期约 0.66 s,受 Odin + # 深度流限制),**比本超时更长**。配合 send_zero_on_timeout: true,就意味着每 + # 0.66 s 里约有 0.46 s 在发零速帧 —— 轮子会走走停停。请在真机上核实;若确实如此, + # 应把它放宽到 >= 1.0。 + cmd_vel_timeout_sec: 0.2 + + # true = stale 期间持续发零速帧把链路撑住(启动瞬间也算 stale,因为 + # _last_cmd_time 初值为 0.0)。 + # false = stale 期间完全不发,启动阶段同样不发。 + # 两种取值下,下位机都**必须**实现自己的超时:本节点写失败的那一帧,与 STM32 + # 从未收到的那一帧,是无法区分的。 + send_zero_on_timeout: true + + # 输出限幅,作用在 /cmd_vel 各分量**乘 1000 转线上格式之前**。 + # 现值已低于上游策略能给出的值,因而几乎每一步都在生效: + # 纯策略、摇杆回中 : |vx| <= 0.6, |wz| <= 0.6 + # 策略 + 摇杆推到底 : |vx| <= 2.7, |wz| <= 2.2 + # 截断是**静默**的 —— 策略节点收不到任何反馈,无从察觉。 + # 这是策略选择而非协议限制:线上格式本身能表达 ±32.767(int16 × 1000)。 + max_vx_m_s: 0.5 + max_vy_m_s: 0.5 + max_wz_rad_s: 0.5 + + # true = 30 Hz 每帧打一行 INFO,含完整十六进制负载。 + # 按默认速率会非常吵;只在调试协议时打开。 + log_velocity_frames: true diff --git a/sru_ws/src/techx_r2_chassis_control/docs/R2底盘串口协议_v2.pdf b/sru_ws/src/techx_r2_chassis_control/docs/R2底盘串口协议_v2.pdf new file mode 100644 index 0000000..a83875c Binary files /dev/null and b/sru_ws/src/techx_r2_chassis_control/docs/R2底盘串口协议_v2.pdf differ diff --git a/sru_ws/src/techx_r2_chassis_control/docs/build_protocol_pdf.py b/sru_ws/src/techx_r2_chassis_control/docs/build_protocol_pdf.py new file mode 100644 index 0000000..fab0a5b --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/docs/build_protocol_pdf.py @@ -0,0 +1,559 @@ +# -*- coding: utf-8 -*- +"""生成本包的串口协议 PDF 说明(下位机接收模块对接用)。 + +用法: + source $WS/venv/bin/activate + python src/techx_r2_chassis_control/docs/build_protocol_pdf.py + +依赖:reportlab(已在 $WS/venv 内)+ 系统中文字体 arphic/uming.ttc。 +示例帧与 CRC 全部由 ../techx_r2_chassis_control/protocol.py 现算,保证与代码一致。 + +注意(踩过的坑): + 1. 正文里的减号不要用 U+2212(−),UMing 没有该字形,会渲染成空白框;用 ASCII 连字符。 + 2. 代码块必须做 HTML 转义,否则代码里的 " None: + pdfmetrics.registerFont(TTFont(CJK, CJK_FONT_PATH, subfontIndex=CJK_SUBFONT_INDEX)) + pdfmetrics.registerFontFamily(CJK, normal=CJK, bold=CJK, italic=CJK, boldItalic=CJK) + + +# ---------------------------------------------------------------- styles +def build_styles() -> dict: + s = {} + s["title"] = ParagraphStyle( + "title", fontName=CJK, fontSize=20, leading=27, textColor=ACCENT, spaceAfter=4, alignment=TA_LEFT + ) + s["subtitle"] = ParagraphStyle( + "subtitle", fontName=CJK, fontSize=10.5, leading=16, textColor=MUTED, spaceAfter=2 + ) + s["h1"] = ParagraphStyle( + "h1", fontName=CJK, fontSize=13.5, leading=19, textColor=ACCENT, spaceBefore=13, spaceAfter=5 + ) + s["h2"] = ParagraphStyle( + "h2", fontName=CJK, fontSize=11.5, leading=17, textColor=INK, spaceBefore=9, spaceAfter=3 + ) + s["body"] = ParagraphStyle( + "body", fontName=CJK, fontSize=9.8, leading=15.6, textColor=INK, spaceAfter=4 + ) + s["bullet"] = ParagraphStyle( + "bullet", parent=s["body"], leftIndent=11, bulletIndent=2, spaceAfter=1.5 + ) + s["code"] = ParagraphStyle( + "code", fontName=MONO, fontSize=8.1, leading=11.6, textColor=INK + ) + s["cell"] = ParagraphStyle( + "cell", fontName=CJK, fontSize=8.8, leading=12.6, textColor=INK + ) + s["cellh"] = ParagraphStyle( + "cellh", fontName=CJK, fontSize=8.8, leading=12.6, textColor=colors.white + ) + s["cellc"] = ParagraphStyle( + "cellc", fontName=MONO, fontSize=8.6, leading=12.6, textColor=INK + ) + s["byteidx"] = ParagraphStyle( + "byteidx", fontName=CJK, fontSize=7.6, leading=10, textColor=MUTED, alignment=TA_CENTER + ) + s["bytename"] = ParagraphStyle( + "bytename", fontName=CJK, fontSize=9, leading=12, textColor=colors.white, alignment=TA_CENTER + ) + s["footnote"] = ParagraphStyle( + "footnote", fontName=CJK, fontSize=8.4, leading=13, textColor=MUTED, spaceAfter=3 + ) + return s + + +STYLES = build_styles() + + +def esc_code(text: str) -> str: + """代码块转义:先转义 HTML 实体,再保留空格与换行。""" + text = text.replace("&", "&").replace("<", "<").replace(">", ">") + return text.replace("\n", "
").replace(" ", " ") + + +def code_block(text: str, width: float): + inner = Paragraph(esc_code(text), STYLES["code"]) + return Table([[inner]], colWidths=[width], + style=TableStyle([ + ("BACKGROUND", (0, 0), (-1, -1), CODE_BG), + ("BOX", (0, 0), (-1, -1), 0.5, RULE), + ("LEFTPADDING", (0, 0), (-1, -1), 4.5 * mm), + ("RIGHTPADDING", (0, 0), (-1, -1), 4.5 * mm), + ("TOPPADDING", (0, 0), (-1, -1), 3.2 * mm), + ("BOTTOMPADDING", (0, 0), (-1, -1), 3.2 * mm), + ])) + + +def note(text: str, width: float, kind: str = "warn"): + bg, line = (WARN_BG, WARN_LINE) if kind == "warn" else (OK_BG, OK_LINE) + return Table([[Paragraph(text, STYLES["cell"])]], colWidths=[width], + style=TableStyle([ + ("BACKGROUND", (0, 0), (-1, -1), bg), + ("LINEBEFORE", (0, 0), (0, -1), 2.2, line), + ("LEFTPADDING", (0, 0), (-1, -1), 4 * mm), + ("RIGHTPADDING", (0, 0), (-1, -1), 4 * mm), + ("TOPPADDING", (0, 0), (-1, -1), 3 * mm), + ("BOTTOMPADDING", (0, 0), (-1, -1), 3 * mm), + ])) + + +def data_table(rows, col_widths, code_cols=(), align_center=()): + body = [] + for r_i, row in enumerate(rows): + out = [] + for c_i, cell in enumerate(row): + if isinstance(cell, str): + st = STYLES["cellh"] if r_i == 0 else (STYLES["cellc"] if c_i in code_cols else STYLES["cell"]) + out.append(Paragraph(cell, st)) + else: + out.append(cell) + body.append(out) + t = Table(body, colWidths=col_widths, repeatRows=1) + t.setStyle(TableStyle([ + ("BACKGROUND", (0, 0), (-1, 0), CELL_HDR), + ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, CELL_ALT]), + ("GRID", (0, 0), (-1, -1), 0.4, RULE), + ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), + ("LEFTPADDING", (0, 0), (-1, -1), 2.6 * mm), + ("RIGHTPADDING", (0, 0), (-1, -1), 2.6 * mm), + ("TOPPADDING", (0, 0), (-1, -1), 2.0 * mm), + ("BOTTOMPADDING", (0, 0), (-1, -1), 2.0 * mm), + *[("ALIGN", (c, 1), (c, -1), "CENTER") for c in align_center], + ])) + return t + + +# ---------------------------------------------------------------- examples +def frames(): + ex = [ + ("静止(停车)", 0.0, 0.0, 0.0), + ("前进", 0.25, 0.0, 0.0), + ("后退", -0.20, 0.0, 0.0), + ("左横移", 0.0, 0.15, 0.0), + ("原地右转", 0.0, 0.0, -0.30), + ("斜向 + 转向", 0.10, 0.05, 0.20), + ("极限值(前进满速)", 2.5, 0.0, 0.0), + ("极限值(旋转满速)", 0.0, 0.0, 1.5), + ] + out = [] + for name, vx, vy, wz in ex: + raw = P.pack_velocity_frame(vx * P.VX_SCALE, vy * P.VY_SCALE, wz * P.OMEGA_SCALE) + out.append((name, vx, vy, wz, raw)) + return out + + +def main() -> None: + register_fonts() + + doc = BaseDocTemplate( + OUT_PDF, + pagesize=A4, + leftMargin=17 * mm, + rightMargin=17 * mm, + topMargin=16 * mm, + bottomMargin=16 * mm, + title="R2 底盘串口通信协议 v2", + author="techx_r2_chassis_control", + subject="下位机(STM32)接收模块实现说明", + ) + W = doc.width + + def on_page(canv, d): + canv.saveState() + canv.setStrokeColor(RULE) + canv.setLineWidth(0.5) + y = A4[1] - 12 * mm + canv.line(doc.leftMargin, y, A4[0] - doc.rightMargin, y) + canv.setFont(CJK, 7.8) + canv.setFillColor(MUTED) + canv.drawString(doc.leftMargin, y + 2.6 * mm, "R2 底盘串口通信协议 v2 · 下位机接收模块实现说明") + canv.drawRightString(A4[0] - doc.rightMargin, y + 2.6 * mm, "第 %d 页" % d.page) + canv.line(doc.leftMargin, 12 * mm, A4[0] - doc.rightMargin, 12 * mm) + canv.restoreState() + + doc.addPageTemplates([PageTemplate( + id="main", + frames=[Frame(doc.leftMargin, doc.bottomMargin, W, doc.height, id="f")], + onPage=on_page)]) + + F = [] + add = F.append + + def h1(t): + add(Paragraph(t, STYLES["h1"])) + + def h2(t): + add(Paragraph(t, STYLES["h2"])) + + def para(t): + add(Paragraph(t, STYLES["body"])) + + def bullets(items, numbered=False): + for i, t in enumerate(items): + add(Paragraph(t, STYLES["bullet"], bulletText=("%d." % (i + 1)) if numbered else "·")) + + # ------------------------------------------------------------ 封面 + add(Paragraph("R2 底盘串口通信协议 v2", STYLES["title"])) + add(Paragraph("下位机(STM32)接收模块实现说明 —— 上位机到 下位机 单向速度指令", STYLES["subtitle"])) + add(HRFlowable(width="100%", thickness=1.4, color=ACCENT, spaceBefore=5, spaceAfter=7)) + + add(data_table([ + ["项目", "内容"], + ["协议版本", "v2(定长 10 字节,只发速度指令)"], + ["上位机实现", "ROS 2 包 techx_r2_chassis_control,节点 chassis_serial_node"], + ["通信方向", "上位机 → 下位机,单向。下位机无需回包,协议不含任何上行帧"], + ["文档用途", "供下位机开发者实现接收 / 校验 / 解析模块;帧示例与 CRC 由上位机代码现算,可直接作测试向量"], + ], [24 * mm, W - 24 * mm])) + + add(Spacer(1, 6)) + add(note( + "一句话总结:上位机每 33 ms 发一帧 10 字节数据,帧内就是 vx、vy、omega 三个 int16 小端数值加一个 CRC16。" + "下位机要做的事只有三件——按 10 字节切帧、校验 CRC、把三个数取出来驱动电机;" + "另外建议加一条「超时未收到合法帧就停车」的兜底逻辑。", W, kind="ok")) + add(Spacer(1, 3)) + + # ------------------------------------------------------------ 1 + h1("1. 概述") + para("上位机运行 ROS 2 导航 / 遥控栈,把最终速度指令发布在 /cmd_vel" + "(geometry_msgs/Twist)话题上。本节点订阅该话题,取出线速度 x、线速度 y、角速度 z 三个分量," + "换算成整数后按本协议打包,经串口写入下位机。整条链路是单向的:上位机只发,从不读串口," + "因此协议里没有应答、没有序号、没有回读状态。" % MONO) + para("下位机侧要实现的收帧逻辑,本质是一个「固定长度 + 帧头 + CRC」的字节流解析器。需要注意的是:" + "帧头 AA 55 会偶然出现在数据区里(速度值恰好为 0x55AA 或 0xAA55 时)," + "所以不能靠搜索帧头来切帧——必须以「10 字节固定帧 + CRC 校验通过」作为唯一的帧确认条件。" + "这一点在第 6 节展开。" % MONO) + + # ------------------------------------------------------------ 2 + h1("2. 物理层参数") + add(data_table([ + ["参数", "取值", "说明"], + ["波特率", "115200 bps", "可通过上位机参数 baudrate 修改,下位机需保持一致"], + ["数据位 / 校验 / 停止位", "8 / None / 1", "即 8N1,无奇偶校验"], + ["流控", "无", "软件与硬件流控都不使用"], + ["电平", "按硬件设计", "上位机侧通过 USB-TTL 适配器转为串口设备节点(默认 /dev/r2_chassis)"], + ["帧率", "默认 30 Hz", "即约 33 ms 一帧;上位机参数 velocity_rate_hz 可调"], + ["链路方向", "上位机 → 下位机", "下位机发回的任何字节上位机都不会读取,请勿依赖上行通道"], + ], [38 * mm, 32 * mm, W - 70 * mm])) + + # ------------------------------------------------------------ 3 + h1("3. 帧结构(定长 10 字节)") + para("所有多字节数值均为小端(little-endian,低字节在前)。") + add(data_table([ + ["偏移", "长度", "字段", "类型", "单位", "说明"], + ["0", "2", "header", "uint8[2]", "—", "固定 0xAA 0x55"], + ["2", "2", "vx", "int16 LE", "mm/s", "机体坐标系前后方向,前进为正"], + ["4", "2", "vy", "int16 LE", "mm/s", "机体坐标系左右方向,左移为正"], + ["6", "2", "omega", "int16 LE", "mrad/s", "绕 Z 轴角速度,逆时针(左转)为正"], + ["8", "2", "crc16", "uint16 LE", "—", "CRC16-MODBUS,覆盖 byte0 ~ byte7"], + ], [14 * mm, 14 * mm, 20 * mm, 21 * mm, 17 * mm, W - 86 * mm], code_cols=(2,), align_center=(0, 1, 4))) + + add(Spacer(1, 4)) + cells = [("byte 0-1", "AA 55"), ("byte 2-3", "vx"), ("byte 4-5", "vy"), + ("byte 6-7", "omega"), ("byte 8-9", "crc16")] + widths = [22 * mm, 25 * mm, 25 * mm, 30 * mm, 30 * mm] + scale = (W - 8 * mm) / sum(widths) + widths = [w * scale for w in widths] + bd = Table([[Paragraph(c[0], STYLES["byteidx"]) for c in cells], + [Paragraph(c[1], STYLES["bytename"]) for c in cells]], colWidths=widths) + bd.setStyle(TableStyle([ + ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), + ("TOPPADDING", (0, 0), (-1, 0), 1.2 * mm), + ("BOTTOMPADDING", (0, 0), (-1, 0), 0.8 * mm), + ("TOPPADDING", (0, 1), (-1, 1), 0.8 * mm), + ("BOTTOMPADDING", (0, 1), (-1, 1), 1.6 * mm), + ("LEFTPADDING", (0, 0), (-1, -1), 1.6 * mm), + ("RIGHTPADDING", (0, 0), (-1, -1), 1.6 * mm), + ("BACKGROUND", (0, 1), (0, 1), colors.HexColor("#5F5E5A")), + ("BACKGROUND", (1, 1), (3, 1), colors.HexColor("#185FA5")), + ("BACKGROUND", (4, 1), (4, 1), colors.HexColor("#993C1D")), + ("BOX", (0, 1), (0, 1), 0.6, colors.white), + ("BOX", (1, 1), (3, 1), 0.6, colors.white), + ("BOX", (4, 1), (4, 1), 0.6, colors.white), + ])) + add(KeepTogether([bd, Spacer(1, 3), + Paragraph("图 1 帧字节布局(灰色 = 帧头,蓝色 = 速度数据区,橙色 = 校验)", + STYLES["footnote"])])) + + # ------------------------------------------------------------ 4 + h1("4. 字段语义与数值换算") + para("三个字段都是 int16(-32768 ~ 32767),单位分别为 mm/s、mm/s、mrad/s,即「米每秒 × 1000」" + "和「弧度每秒 × 1000」,全部靠 1000 这一个比例常数换算,下位机侧反算则是除以 1000。" + "符号约定与 geometry_msgs/Twist 一致。") + add(data_table([ + ["字段", "上位机换算(→ 下发值)", "下位机反算", "实际上限", "int16 满量程"], + ["vx", "mm/s = round(vx_m_s × 1000)", "vx_m_s = vx / 1000.0", "±2500", "±32767"], + ["vy", "mm/s = round(vy_m_s × 1000)", "vy_m_s = vy / 1000.0", "±2500", "±32767"], + ["omega", "mrad/s = round(wz_rad_s × 1000)", "wz_rad_s = omega / 1000.0", "±1500", "±32767"], + ], [13 * mm, 66 * mm, 52 * mm, 18 * mm, 27 * mm], code_cols=(1, 2), align_center=(3, 4))) + add(Spacer(1, 3)) + add(Paragraph("实际上限指上位机下发前的限幅:vx/vy 为 ±2500(±2.5 m/s),omega 为 ±1500(±1.5 rad/s)," + "下位机收到的数值不会超出该范围;仍建议下位机做一次范围钳制作为防御性处理。", + STYLES["footnote"])) + + # ------------------------------------------------------------ 5 + h1("5. CRC16-MODBUS 校验") + para("校验算法为标准 CRC16-MODBUS:多项式 0x8005(反射形式 0xA001),初值 0xFFFF," + "输入输出都不做取反,也没有最终异或。计算范围是 byte0 ~ byte7(帧头 + 数据)," + "算出的 16 位结果以小端写入 byte8、byte9(低字节在前)。") + h2("5.1 接收端校验要点") + bullets([ + "先按小端把 byte8、byte9 拼成期望值:expect = byte8 | (byte9 << 8)" % MONO, + "再对前 8 字节算 CRC,与 expect 比较,不相等即丢帧", + "多项式、初值、位序三者任一不同都会和上位机对不上,请直接使用下面的参考实现", + ]) + add(KeepTogether([ + Paragraph("5.2 C 参考实现(可直接抄进 STM32)", STYLES["h2"]), + code_block( + "/* CRC16-MODBUS: poly=0xA001, init=0xFFFF, no reflect in/out, no final xor */\n" + "uint16_t crc16_modbus(const uint8_t *buf, uint16_t len)\n" + "{\n" + " uint16_t crc = 0xFFFF;\n" + " for (uint16_t i = 0; i < len; i++) {\n" + " crc ^= (uint16_t)buf[i];\n" + " for (int b = 0; b < 8; b++) {\n" + " if (crc & 0x0001) crc = (crc >> 1) ^ 0xA001;\n" + " else crc = (crc >> 1);\n" + " crc &= 0xFFFF;\n" + " }\n" + " }\n" + " return crc;\n" + "}\n" + "\n" + "/* usage: after a full 10-byte frame f[] has arrived */\n" + "uint16_t expect = (uint16_t)f[8] | ((uint16_t)f[9] << 8);\n" + "if (crc16_modbus(f, 8) != expect) { /* drop this frame */ }", + W)])) + + # ------------------------------------------------------------ 6 + h1("6. 接收端实现建议") + add(note( + "关键坑:帧头不可作为切帧依据。数据区里的 vx / vy / omega 是任意 int16," + "完全可能等于 0x55AA 或 0xAA55,从而在字节流里造出一个假的 AA 55。" + "正确做法是固定 10 字节切帧 + CRC 判定:只有 10 字节对齐且 CRC 通过的帧才采信。" + "若 CRC 失败,不要整帧丢弃后从下一帧开始,而应逐个字节滑动重同步(丢 1 字节再试)," + "这样偶发干扰后最多丢一帧就能重新对齐。" % MONO, W)) + + h2("6.1 推荐收帧流程") + bullets([ + "串口用 DMA + 空闲中断(IDLE)收数据,或中断驱动填环形缓冲,按 10 字节一帧取出;", + "检查字节 0、1 是否为 0xAA 0x55。不是则丢弃 1 字节,回到上一步;", + "对前 8 字节算 CRC16,与 byte8 / byte9(小端拼接)比对。失败则丢弃 1 字节并重新对齐;", + "校验通过:按小端解析 vx、vy、omega,并刷新「最后一次有效帧到达时间」;", + "把三个值写入电机控制环节(可按需再做死区与斜率限制);", + "另设一个定时器:若距上次有效帧超过 300 ~ 500 ms,则强制 vx = vy = omega = 0 并置故障标志。", + ], numbered=True) + + add(Spacer(1, 4)) + add(KeepTogether([code_block( + "/* 10-byte fixed frame + CRC resync */\n" + "static uint8_t buf[10];\n" + "static uint16_t len = 0;\n" + "static uint32_t last_ok_ms = 0;\n" + "\n" + "void on_rx_byte(uint8_t b)\n" + "{\n" + " buf[len++] = b;\n" + " if (len < 10) return;\n" + "\n" + " if (buf[0] == 0xAA && buf[1] == 0x55\n" + " && crc16_modbus(buf, 8) == ((uint16_t)buf[8] | ((uint16_t)buf[9] << 8))) {\n" + " int16_t vx = (int16_t)((uint16_t)buf[2] | ((uint16_t)buf[3] << 8));\n" + " int16_t vy = (int16_t)((uint16_t)buf[4] | ((uint16_t)buf[5] << 8));\n" + " int16_t omega = (int16_t)((uint16_t)buf[6] | ((uint16_t)buf[7] << 8));\n" + " apply_velocity(vx, vy, omega); /* units: mm/s, mm/s, mrad/s */\n" + " last_ok_ms = now_ms();\n" + " len = 0; /* whole frame consumed */\n" + " } else {\n" + " memmove(buf, buf + 1, 9); /* shift by 1 byte and retry */\n" + " len = 9;\n" + " }\n" + "}\n" + "\n" + "/* watchdog: call from a 100 Hz ~ 1 kHz task */\n" + "void safety_tick(void)\n" + "{\n" + " if (now_ms() - last_ok_ms > 400) apply_velocity(0, 0, 0);\n" + "}", + W)])) + + h2("6.2 超时停车约定") + para("上位机的行为:只要 200 ms 内没有收到新的 /cmd_vel,它就持续发送全零帧(vx = vy = omega = 0)," + "而不是停发。也就是说链路正常运行时下位机一定会持续收到帧——「收不到帧」本身就意味着异常" + "(上位机崩溃、串口断开、线缆松动)。所以下位机必须自带超时停车,不能只依赖上位机发零帧。") + para("上位机零速帧的固定字节为 %s,可用它作为「停车帧」的识别基准。" + % (MONO, P.frame_to_hex(P.pack_velocity_frame(0, 0, 0)))) + + # ------------------------------------------------------------ 7 + add(PageBreak()) + h1("7. 示例帧(可直接作单元测试向量)") + para("下表全部由上位机代码 protocol.py 现算生成,与实际下发的字节完全一致。" + "建议下位机把这些帧灌进解析函数做回归测试。" % MONO) + rows = [["场景", "vx (m/s)", "vy (m/s)", "omega (rad/s)", "payload byte2~byte7", "完整 10 字节帧"]] + for name, vx, vy, wz, raw in frames(): + rows.append([name, "%+.2f" % vx, "%+.2f" % vy, "%+.3f" % wz, + P.frame_to_hex(raw[2:8]), P.frame_to_hex(raw)]) + add(data_table(rows, [31 * mm, 15 * mm, 15 * mm, 20 * mm, 40 * mm, W - 121 * mm], + code_cols=(1, 2, 3, 4, 5), align_center=(1, 2, 3))) + + add(Spacer(1, 7)) + h2("7.1 逐字节解释示例:前进 0.25 m/s") + raw = P.pack_velocity_frame(0.25 * P.VX_SCALE, 0, 0) + bytes_hex = ["%02X" % b for b in raw] + meaning = [ + "帧头高字节,固定 0xAA", + "帧头低字节,固定 0x55", + "vx 低字节:250 mm/s = 0x00FA", + "vx 高字节", + "vy 低字节:0 mm/s", + "vy 高字节", + "omega 低字节:0 mrad/s", + "omega 高字节", + "CRC16 低字节", + "CRC16 高字节", + ] + rows = [["字节位置", "值", "含义"]] + [["byte %d" % i, bytes_hex[i], meaning[i]] for i in range(10)] + add(data_table(rows, [24 * mm, 16 * mm, W - 40 * mm], code_cols=(1,), align_center=(1,))) + add(Spacer(1, 3)) + add(Paragraph("整帧:%s;CRC16-MODBUS 计算结果为 " + "0x%04X(小端写入即 %s %s)。" + % (MONO, P.frame_to_hex(raw), MONO, + P.crc16_modbus(bytes(b"\xAA\x55" + raw[2:8])), bytes_hex[8], bytes_hex[9]), + STYLES["footnote"])) + + # ------------------------------------------------------------ 8 + h1("8. 上位机侧行为(对接需知)") + add(data_table([ + ["参数(ROS 2 参数名)", "默认值", "对下位机的影响"], + ["velocity_rate_hz", "30.0", "发包频率,决定下位机收到帧的节奏"], + ["cmd_vel_timeout_sec", "0.2", "超过该时长无新指令即发零速帧"], + ["send_zero_on_timeout", "true", "置 false 则超时后直接停发(此时下位机的超时兜底更关键)"], + ["max_vx_m_s / max_vy_m_s", "2.5 / 2.5", "下发前的限幅,vx / vy 不会超过 ±2500"], + ["max_wz_rad_s", "1.5", "下发前的角速度限幅,omega 不会超过 ±1500"], + ["baudrate", "115200", "必须与下位机一致"], + ["port", "/dev/...", "上位机侧串口设备名(默认 /dev/r2_chassis),与下位机无关"], + ], [46 * mm, 26 * mm, W - 72 * mm], code_cols=(0,), align_center=(1,))) + + h2("8.1 上电与重启行为") + bullets([ + "上位机节点启动后立刻按帧率发帧,在收到第一条 /cmd_vel 之前发的都是零速帧;", + "没有任何握手、心跳或使能流程。下位机随时上电都能从下一帧开始正常接收;", + "下位机重启不需要通知上位机,只要按 10 字节切帧即可重新同步;", + "上位机不会因为下位机不回包而报错——它根本不读串口。", + ]) + + # ------------------------------------------------------------ 9 + h1("9. 下位机自检清单") + add(data_table([ + ["#", "检查项", "通过标准"], + ["1", "串口参数", "115200 8N1,无流控"], + ["2", "收帧切分", "以 10 字节为单位处理,不用搜帧头切帧"], + ["3", "CRC 实现", "对 byte0~7 算 0xA001 / 0xFFFF,结果与 byte8、byte9(小端)一致"], + ["4", "字节序", "vx / vy / omega 按小端拼 int16,负数能正确解析(如 0xFF9C = -100)"], + ["5", "重同步", "灌入含假帧头或坏 CRC 的脏字节流后,能在 1 ~ 2 帧内恢复对齐"], + ["6", "超时停车", "停发数据 300 ~ 500 ms 后电机速度归零并置标志"], + ["7", "示例帧回归", "第 7 节所有示例帧的解析结果与表中数值一致"], + ["8", "零速帧", "收到全零帧后电机确实停止(而不是仅写入变量)"], + ], [9 * mm, 30 * mm, W - 39 * mm], align_center=(0,))) + + add(Spacer(1, 6)) + add(note("负数字节序自检用例:int16 -100 = 0xFF9C,小端下发为 9C FF" + "(低字节 9C 在前,高字节 FF 在后)。若解析出 +155 之类的怪值," + "说明字节序或符号扩展写错了。" % MONO, W, kind="ok")) + + # ------------------------------------------------------------ 附录 + add(PageBreak()) + h1("附录 A 上位机发送侧实现(Python,节选自 protocol.py)") + add(code_block( + "FRAME_LEN = 10\n" + "HEADER = b\"\\xAA\\x55\"\n" + "VX_SCALE = VY_SCALE = OMEGA_SCALE = 1000.0 # m/s->mm/s, rad/s->mrad/s\n" + "\n" + "def pack_velocity_frame(vx_mm_s, vy_mm_s, omega_mrad_s):\n" + " payload = bytearray(HEADER)\n" + " payload.extend(struct.pack(\"docs/build_protocol_pdf.py 自动生成;协议若有改动," + "重新运行该脚本即可得到与新版固件一致的新版 PDF。协议权威定义见 " + "techx_r2_chassis_control/protocol.py 文件头注释。" + % (MONO, MONO), STYLES["footnote"])) + + doc.build(F) + print("written:", OUT_PDF, os.path.getsize(OUT_PDF), "bytes") + + +if __name__ == "__main__": + main() diff --git a/sru_ws/src/techx_r2_chassis_control/docs/协议落地核查报告_2026-10-03.md b/sru_ws/src/techx_r2_chassis_control/docs/协议落地核查报告_2026-10-03.md new file mode 100644 index 0000000..fdc4d0f --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/docs/协议落地核查报告_2026-10-03.md @@ -0,0 +1,242 @@ +# R2 底盘协议 · 上位机侧核查与自检手册 + +- 日期:2026-10-03 +- 范围:**仅 `src/techx_r2_chassis_control`(ROS 2 上位机包)**,不涉及下位机固件 +- 权威实现:`techx_r2_chassis_control/protocol.py` +- 接口契约文档:`docs/R2底盘串口协议_v2.pdf` + +--- + +## 0. 一句话 + +上位机这一侧**实现是正确的**:帧格式、CRC、字节序、量纲都已用交叉验证跑通(§7 验证记录)。 +真正需要你「掌握」的不是写它,而是**能回答下面 6 个问题**——它们全都指向「协议契约」和「失效路径」,而这两样代码里没有。 + +--- + +## Q1 · 为什么是小端 ` bytes: + return struct.pack("h", -100) # b'\xff\x9c' ← 大端:高字节在前 +``` + +`-0.1 m/s` × 1000 = `-100 mm/s` = `0xFF9C`,小端上线就是 `9C FF`。 +上位机产出 `AA 55 9C FF 00 ...`(见 §7)。**记住这个 `9C FF`——它是判断字节序写错的最快特征。** + +**为什么这件事必须你来定**:字节序是两边各自手工拼装的约定,不是代码内部的自洽性。编译器不会帮你检查,测试也不会自动发现——只有协议文档能定它。 + +--- + +## Q2 · CRC 覆盖哪几个字节?校验失败时谁负责? + +### CRC 参数(`protocol.py:58-69`) + +| 参数 | 值 | +|---|---| +| 多项式 | `0xA001`(MODBUS 反射形式) | +| 初值 | `0xFFFF` | +| 输入/输出位反转 | 无 | +| 最终异或 | 无 | +| **覆盖范围** | **`byte0..byte7`(帧头 + 三个 int16),不含 CRC 自身** | +| CRC 字段摆放 | `byte8` 低字节、`byte9` 高字节 | + +代码里的实现与文档一致: + +```python +payload.extend(struct.pack("32 m/s 的输入,物理上不可能。 +3. **限幅后不回写**(`chassis_serial_node.py:72-81`): + +```python +def _on_cmd_vel(self, msg: Twist) -> None: + self._latest_vx_m_s = self._clamp(msg.linear.x, ...) # 只存内部变量 +``` + + `msg` 本身没被修改,也没有任何反馈话题。**下游节点不知道指令被截断了**——`/cmd_vel` 上写着 3.0 m/s,实际发出去的是 2.5 m/s,`ros2 topic echo /cmd_vel` 看不出来。 + → 排查「车走不到预期速度」时,这是一个会骗人的地方。诊断方法:把 `log_velocity_frames` 打开,对比日志里的 `TX vx=...` 与 `/cmd_vel` 的原值。 + +**结论**:`int16` 的 1 mm/s 台阶**不是抖动的可能原因**。真正需要你判断的是: + +- **下游(下位机舵轮解算)的死区有多大?** 如果它的死区折算成线速度比 1 mm/s 粗(这类代码的死区常设 0.1 rad/s 量级),那么**主导精度的是那个死区,不是协议量化**。 +- **节拍是否对齐?** 上位机 30 Hz 定频发送,下位机以什么频率消费?两个不同频率之间如果没有缓冲,会造成速度指令被随机取样,**这才是低速顿挫的典型成因**,而且它属于**契约层**——需要在协议文档里规定下位机的消费节拍(或规定「每当收到合法帧立即更新目标值」)。 + +量化、死区、采样节拍,这三者的关系是排查慢速抖动的固定顺序:**先比粗细,再比频率。** + +--- + +## Q6 · 架空状态下怎么证明「下位机收到的是同一条帧」? + +上位机侧现有条件:**串口单向,无 ACK,没有回读**。`test_cmd_vel_pub.py` 只发 `/cmd_vel`,不验证任何东西。 + +分三步补,从便宜到贵: + +### 第 1 步(现在就能做,不需要硬件)——固化自检向量 + +把 §7 的 5 条帧交给下位机做单元测试。**这是唯一能跨过「上位机怎么打包」与「下位机怎么解包」边界、且不需要任何硬件的验证手段。** + +| 输入 (m/s, m/s, rad/s) | 线上 10 字节 | 期望解出 | +|---|---|---| +| `(+0.000, +0.000, +0.000)` | `AA 55 00 00 00 00 00 00 CF 09` | `(0, 0, 0)` | +| `(+0.100, +0.000, +0.000)` | `AA 55 64 00 00 00 00 00 C7 2D` | `(+0.1, 0, 0)` | +| `(-0.100, +0.000, +0.000)` | `AA 55 9C FF 00 00 00 00 C6 81` | `(-0.1, 0, 0)` | +| `(+0.000, +0.100, +0.000)` | `AA 55 00 00 64 00 00 00 D0 39` | `(0, +0.1, 0)` | +| `(+0.000, +0.000, +0.100)` | `AA 55 00 00 00 00 64 00 E5 C9` | `(0, 0, +0.1)` | + +> 价值:**任一侧改代码,跑这张表就知道有没有破协议。** 它把「口头约定」变成了「可执行断言」。建议直接放进协议文档附录。 + +### 第 2 步(架空抬轮)——上位机侧发送留痕 + +给 `chassis_serial_node` 加一个**只读**诊断:把每帧的 `frame_to_hex()` 和时间戳记进环形缓冲,发布到 `~/tx_trace`(`std_msgs/String`),默认关闭。 +- 纯观测,不改发送逻辑、不改安全默认值。 +- 用 `ros2 topic echo` 就能逐帧核对「打算发什么」和「实际写了什么字节」。 +- 注意这只能证明**上位机发出了什么**,证明不了下位机收到了。 + +### 第 3 步(唯一能证明「下位机真的执行了」的办法)——要求下位机回读 + +请下位机增加一条**上行帧**(建议用 `55 AA` 起头,与下行 `AA 55` 对称,避免误判),内容为「当前执行的 vx/vy/ω + 本地时间戳」,10 Hz 即可。上位机订阅后与已发送命令做时间对齐比对。 + +- 这一步会把「单向无回读」的架构改掉,属于**架构决策,需要你拍板**,不是改个参数。 +- 收益:直接得到「指令延迟」「CRC 失败率」「失联次数」三个可量化验收指标,也是 §Q3 那条安全边界唯一的验证方式。 + +--- + +## 附 A · 上位机包体检清单(本包实测) + +| # | 位置 | 现象 | 性质 | +|---|---|---|---| +| 1 | `chassis_serial_node.py:32` | `serial_timeout_sec: 0.02` 声明并传给了 `serial.Serial`,但节点从不 `read()` ⇒ **零影响的死参数** | 无害,但说明参数未逐个确认 | +| 2 | `config/chassis_serial.yaml:12` | `log_velocity_frames: true` ⇒ 30 Hz 每帧打一行 hex 日志。**默认值是否合适要人工判断** | 需决策 | +| 3 | `chassis_serial_node.py:62` | `1.0 / max(1.0, rate_hz)` ⇒ `velocity_rate_hz` 传 0 时**静默降级成 1 Hz**,不报错也不告警 | 静默降级 | +| 4 | `chassis_serial_node.py:57,85` | `_last_cmd_time = 0.0` 初值 ⇒ 启动瞬间即判 stale。配 `send_zero_on_timeout: true` 时会先发零速帧(正确);若设为 `false`,节点启动后**完全不发帧**,下位机必须自己有兜底 | 跨设备安全边界 | +| 5 | `chassis_serial_node.py:72-81` | 限幅结果不回写 `msg`、无反馈话题 ⇒ 下游无法感知截断 | 可观测性缺口 | +| 6 | `yaml:3` vs `launch/chassis_serial.launch.py:14,24` | yaml 写 `port: /dev/ttyUSB0`,launch 的 `port_arg` 默认 `/dev/r2_chassis` 且作为**后置参数覆盖** ⇒ **yaml 里的 port 永远不生效**。两处必须统一 | **真实缺陷** | +| 7 | `chassis_serial_node.py:98` | `self._serial.write(frame)` 未检查返回值是否 == `FRAME_LEN` | 建议加固 | +| 8 | `chassis_serial_node.py:76` | 用 `time.monotonic()` 计时(正确做法);注意不要改成 `time.time()`——墙钟会因 NTP 跳变导致误判 | 已正确 | + +**第 6 条是这里唯一需要改代码的**:`launch` 里的 `port` 覆盖会让 yaml 配置失效。两种修法(需你确认): +- 删掉 `launch` 的 `port_arg` 默认覆盖,只保留 `DeclareLaunchArgument('port', default_value='')` 并在为空时不传该参数; +- 或把 yaml 与 launch 的默认值统一为同一个设备路径(并配 udev 规则固定设备名)。 + +--- + +## 附 B · 自己验证协议一致性的方法(不需要硬件) + +不要「读一遍觉得对」就结束。用**独立实现 + 随机交叉验证**: + +1. 按 `docs/R2底盘串口协议_v2.pdf` 的文字描述,**不看 `protocol.py`**,另外写一份最小实现; +2. 用 5000 组随机 8 字节 payload 对比两份实现的 `crc16_modbus()`; +3. 用 3000 组随机 `(vx, vy, ω)`(含超限值)跑「打包 → 解包」闭环,比对是否等于「限幅+四舍五入」后的期望值。 + +本次核查按此方法执行,结果见 §7。 + +--- + +## 7. 验证记录(2026-10-03 实测) + +| 项目 | 方法 | 结果 | +|---|---|---| +| CRC16-MODBUS 一致性 | 5000 组随机 8 字节 payload,对照独立实现 | **不一致 0 组** | +| 端到端 pack → parse 闭环 | 3000 组随机 `(vx, vy, ω)`(含 ±3.5 / ±2.0 超限) | **失败 0 组** | +| 负值字节序 | `-0.1 m/s` → 是否产出 `9C FF` | **通过** | +| 双重限幅一致性 | 上位机 ±2.5 / ±2.5 / ±1.5 与协议文档一致 | **通过** | +| 溢出风险 | `int16` 满量程 ±32.767 m/s vs 限幅 ±2.5 m/s | **不可能溢出** | + +**可直接粘贴的断言**: + +```python +from techx_r2_chassis_control.protocol import pack_velocity_frame, frame_to_hex +assert frame_to_hex(pack_velocity_frame(0, 0, 0)) == "AA 55 00 00 00 00 00 00 CF 09" +assert frame_to_hex(pack_velocity_frame(100, 0, 0)) == "AA 55 64 00 00 00 00 00 C7 2D" +assert frame_to_hex(pack_velocity_frame(-100, 0, 0)) == "AA 55 9C FF 00 00 00 00 C6 81" +assert frame_to_hex(pack_velocity_frame(0, 100, 0)) == "AA 55 00 00 64 00 00 00 D0 39" +assert frame_to_hex(pack_velocity_frame(0, 0, 100)) == "AA 55 00 00 00 00 64 00 E5 C9" +``` diff --git a/sru_ws/src/techx_r2_chassis_control/launch/chassis_serial.launch.py b/sru_ws/src/techx_r2_chassis_control/launch/chassis_serial.launch.py new file mode 100644 index 0000000..a228f91 --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/launch/chassis_serial.launch.py @@ -0,0 +1,93 @@ +"""启动 R2 底盘串口桥(/cmd_vel -> STM32 速度帧)。 + +本节点所有可调项的唯一真源是 config/chassis_serial.yaml。这里额外把 port 暴露成 launch +参数,因为台架调试时常需要临时换个设备;它的默认值**从 yaml 反读**,两者因此不可能不一致。 + +重要 —— 为什么过去改 yaml 对 port 完全无效: +ROS 2 里 parameters 是一个**列表**,按顺序应用、**后者胜**。本文件旧版写的是:: + + parameters=[LaunchConfiguration('config'), {'port': LaunchConfiguration('port')}] + +而 port 的 launch 默认值被硬编码成 /dev/r2_chassis。于是第二段字典永远压过参数文件, +config/chassis_serial.yaml 里写的 port 变成死信 —— 无论怎么改 yaml 都改不动它。 +这与 sru_nav_ros2/launch/sru_nav.launch.py 中记录的失败模式同源(当年 +odom_twist_in_base_frame 一直是 false,而 yaml 写的是 true),修法也相同:默认值从文件读。 + +关于 install 拷贝:setup.py 是用**拷贝**方式安装 config/*.yaml 的,所以 +install/.../share/techx_r2_chassis_control/config/ 下是另一个文件;改 src/ 里的 yaml +必须重新编译才生效。用 params_file:= 直接指向源码树可以免重建(该参数就是为此存在), +长期方案是 colcon build --symlink-install。 + +典型用法:: + + ros2 launch techx_r2_chassis_control chassis_serial.launch.py + + # 台架测试临时换设备 + ros2 launch techx_r2_chassis_control chassis_serial.launch.py port:=/dev/ttyUSB0 + + # 改完即用,不必重新编译 + ros2 launch techx_r2_chassis_control chassis_serial.launch.py \\ + params_file:=$HOME/sru_ws/src/techx_r2_chassis_control/config/chassis_serial.yaml + +警告 —— 节点在构造函数里就打开串口,且下位机没有独立的失联兜底: +任何能触达 /cmd_vel 的测试都必须先让轮子离地。 +""" + +import os +import yaml + +from ament_index_python.packages import get_package_share_directory +from launch import LaunchDescription +from launch.actions import DeclareLaunchArgument +from launch.substitutions import LaunchConfiguration +from launch_ros.actions import Node + + +def _yaml_default(params_file, name, fallback): + """读取参数文件里 name 的写法值。 + + 有意**不做** .lower()。sru_nav_ros2/launch/sru_nav.launch.py 里的同名助手末尾带 + .lower(),那是为读布尔值写的;照抄到这里会把设备路径 /dev/ttyUSB0 变成 /dev/ttyusb0。 + + 文件读不出来时回落到 fallback,这样 yaml 坏了也仍能启动,让节点自己报更清楚的错, + 而不是死在 launch 系统里。 + """ + try: + with open(params_file, 'r') as f: + params = yaml.safe_load(f)['chassis_serial_node']['ros__parameters'] + return str(params[name]) + except Exception: + return fallback + + +def generate_launch_description(): + pkg_share = get_package_share_directory('techx_r2_chassis_control') + default_params_file = os.path.join(pkg_share, 'config', 'chassis_serial.yaml') + + declared_arguments = [ + DeclareLaunchArgument( + 'params_file', default_value=default_params_file, + description='节点参数文件(默认取包 share 目录下的 config/chassis_serial.yaml)。' + '安装出来的是拷贝而非符号链接 —— 把它指向 src/ 下那份即可改完即用、' + '无需重新编译。'), + DeclareLaunchArgument( + 'port', default_value=_yaml_default(default_params_file, 'port', '/dev/ttyUSB0'), + description='串口设备。默认值从 config/chassis_serial.yaml 反读,该文件即唯一真源;' + '临时覆盖一次用 port:=...。'), + ] + + chassis_node = Node( + package='techx_r2_chassis_control', + executable='chassis_serial_node', + name='chassis_serial_node', + output='screen', + # 顺序有意义:第 0 项是参数文件,第 1 项是命令行覆盖。后者胜 —— 这是故意的 + # (port:=... 就靠它生效),而它之所以安全,只因为上面 port 的默认值正是从 + # 同一个文件读出来的。 + parameters=[ + LaunchConfiguration('params_file'), + {'port': LaunchConfiguration('port')}, + ], + ) + + return LaunchDescription(declared_arguments + [chassis_node]) diff --git a/sru_ws/src/techx_r2_chassis_control/package.xml b/sru_ws/src/techx_r2_chassis_control/package.xml new file mode 100644 index 0000000..e204111 --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/package.xml @@ -0,0 +1,19 @@ + + + techx_r2_chassis_control + 0.2.0 + Python serial bridge: /cmd_vel -> R2 chassis STM32 velocity frames. + techx + MIT + + ament_python + rclpy + geometry_msgs + + ament_lint_auto + ament_lint_common + + + ament_python + + diff --git a/sru_ws/src/techx_r2_chassis_control/resource/techx_r2_chassis_control b/sru_ws/src/techx_r2_chassis_control/resource/techx_r2_chassis_control new file mode 100644 index 0000000..e69de29 diff --git a/sru_ws/src/techx_r2_chassis_control/setup.cfg b/sru_ws/src/techx_r2_chassis_control/setup.cfg new file mode 100644 index 0000000..49fa6f7 --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/setup.cfg @@ -0,0 +1,4 @@ +[develop] +script_dir=$base/lib/techx_r2_chassis_control +[install] +install_scripts=$base/lib/techx_r2_chassis_control diff --git a/sru_ws/src/techx_r2_chassis_control/setup.py b/sru_ws/src/techx_r2_chassis_control/setup.py new file mode 100644 index 0000000..84e37f2 --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/setup.py @@ -0,0 +1,30 @@ +from setuptools import setup +from glob import glob +import os + +package_name = 'techx_r2_chassis_control' + +setup( + name=package_name, + version='0.2.0', + packages=[package_name], + data_files=[ + ('share/ament_index/resource_index/packages', ['resource/' + package_name]), + ('share/' + package_name, ['package.xml']), + (os.path.join('share', package_name, 'launch'), glob('launch/*.launch.py')), + (os.path.join('share', package_name, 'config'), glob('config/*.yaml')), + ], + install_requires=['setuptools', 'pyserial'], + zip_safe=True, + maintainer='techx', + maintainer_email='todo@example.com', + description='Python serial bridge: /cmd_vel -> R2 chassis STM32 velocity frames.', + license='MIT', + tests_require=['pytest'], + entry_points={ + 'console_scripts': [ + 'chassis_serial_node = techx_r2_chassis_control.chassis_serial_node:main', + 'test_cmd_vel_pub = techx_r2_chassis_control.test_cmd_vel_pub:main', + ], + }, +) diff --git a/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/__init__.py b/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/chassis_serial_node.py b/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/chassis_serial_node.py new file mode 100644 index 0000000..5d159e2 --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/chassis_serial_node.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +import threading +import time + +import rclpy +from rclpy.node import Node +from geometry_msgs.msg import Twist + +try: + import serial +except ImportError as exc: # pragma: no cover - runtime dependency on robot + serial = None + +from .protocol import ( + OMEGA_SCALE, + VX_SCALE, + VY_SCALE, + frame_to_hex, + pack_velocity_frame, +) + + +class ChassisSerialNode(Node): + """Bridge /cmd_vel -> STM32 serial velocity frames.""" + + def __init__(self) -> None: + super().__init__("chassis_serial_node") + + self.declare_parameter("port", "/dev/ttyUSB0") + self.declare_parameter("baudrate", 115200) + self.declare_parameter("serial_timeout_sec", 0.02) + self.declare_parameter("velocity_rate_hz", 30.0) + self.declare_parameter("cmd_vel_timeout_sec", 0.2) + self.declare_parameter("send_zero_on_timeout", True) + self.declare_parameter("max_vx_m_s", 2.5) + self.declare_parameter("max_vy_m_s", 2.5) + self.declare_parameter("max_wz_rad_s", 1.5) + self.declare_parameter("log_velocity_frames", False) + + if serial is None: + raise RuntimeError("pyserial is not installed. Install with: sudo apt install python3-serial") + + self._port = self.get_parameter("port").value + self._baudrate = int(self.get_parameter("baudrate").value) + self._serial = serial.Serial( + self._port, + self._baudrate, + timeout=float(self.get_parameter("serial_timeout_sec").value), + ) + self.get_logger().info(f"Opened chassis serial port {self._port} @ {self._baudrate}") + + self._write_lock = threading.Lock() + self._latest_vx_m_s = 0.0 + self._latest_vy_m_s = 0.0 + self._latest_wz_rad_s = 0.0 + self._last_cmd_time = 0.0 + + self.create_subscription(Twist, "/cmd_vel", self._on_cmd_vel, 10) + + rate_hz = float(self.get_parameter("velocity_rate_hz").value) + self.create_timer(1.0 / max(1.0, rate_hz), self._velocity_timer_cb) + + def destroy_node(self) -> bool: + try: + if self._serial is not None and self._serial.is_open: + self._serial.close() + except Exception: + pass + return super().destroy_node() + + def _on_cmd_vel(self, msg: Twist) -> None: + self._latest_vx_m_s = self._clamp(msg.linear.x, float(self.get_parameter("max_vx_m_s").value)) + self._latest_vy_m_s = self._clamp(msg.linear.y, float(self.get_parameter("max_vy_m_s").value)) + self._latest_wz_rad_s = self._clamp(msg.angular.z, float(self.get_parameter("max_wz_rad_s").value)) + self._last_cmd_time = time.monotonic() + + @staticmethod + def _clamp(value: float, limit: float) -> float: + limit = abs(float(limit)) + return max(-limit, min(limit, float(value))) + + def _velocity_timer_cb(self) -> None: + timeout_sec = float(self.get_parameter("cmd_vel_timeout_sec").value) + stale = self._last_cmd_time <= 0.0 or (time.monotonic() - self._last_cmd_time) > timeout_sec + + if stale: + if not bool(self.get_parameter("send_zero_on_timeout").value): + return + vx = vy = wz = 0.0 + else: + vx = self._latest_vx_m_s + vy = self._latest_vy_m_s + wz = self._latest_wz_rad_s + + frame = pack_velocity_frame(vx * VX_SCALE, vy * VY_SCALE, wz * OMEGA_SCALE) + with self._write_lock: + self._serial.write(frame) + self._serial.flush() + + if bool(self.get_parameter("log_velocity_frames").value): + self.get_logger().info( + f"TX vx={vx * VX_SCALE:.0f}mm/s vy={vy * VY_SCALE:.0f}mm/s " + f"omega={wz * OMEGA_SCALE:.0f}mrad/s | {frame_to_hex(frame)}" + ) + + +def main(args=None) -> None: + rclpy.init(args=args) + node = ChassisSerialNode() + try: + rclpy.spin(node) + except KeyboardInterrupt: + pass + finally: + node.destroy_node() + rclpy.shutdown() + + +if __name__ == "__main__": + main() diff --git a/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/protocol.py b/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/protocol.py new file mode 100644 index 0000000..32a826b --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/protocol.py @@ -0,0 +1,117 @@ +"""R2 chassis serial protocol, v2 (velocity only). + +Frame layout, fixed 10 bytes, little endian: + + Byte0-1 0xAA 0x55 header + Byte2-3 vx int16, mm/s + Byte4-5 vy int16, mm/s + Byte6-7 omega int16, mrad/s + Byte8-9 CRC16-MODBUS over byte0..byte7 + +Host -> STM32 only. The host never reads frames back, so there is no receive +command set. + +Sign convention follows geometry_msgs/Twist: + vx = linear.x (m/s, forward positive) + vy = linear.y (m/s, left positive) + omega = angular.z (rad/s, counter-clockwise positive) +""" + +from __future__ import annotations + +from dataclasses import dataclass +import struct + +FRAME_LEN = 10 +HEADER = b"\xAA\x55" + +VX_SCALE = 1000.0 # m/s -> mm/s +VY_SCALE = 1000.0 # m/s -> mm/s +OMEGA_SCALE = 1000.0 # rad/s -> mrad/s + + +class ProtocolError(ValueError): + """Raised when a serial frame is malformed.""" + + +@dataclass(frozen=True) +class VelocityCommand: + """Parsed chassis velocity frame.""" + + vx_mm_s: int + vy_mm_s: int + omega_mrad_s: int + + @property + def vx_m_s(self) -> float: + return self.vx_mm_s / VX_SCALE + + @property + def vy_m_s(self) -> float: + return self.vy_mm_s / VY_SCALE + + @property + def omega_rad_s(self) -> float: + return self.omega_mrad_s / OMEGA_SCALE + + +def crc16_modbus(data: bytes) -> int: + """Compute CRC16-MODBUS, polynomial 0xA001, init 0xFFFF.""" + crc = 0xFFFF + for byte in data: + crc ^= byte + for _ in range(8): + if crc & 0x0001: + crc = (crc >> 1) ^ 0xA001 + else: + crc >>= 1 + crc &= 0xFFFF + return crc + + +def clamp_i16(value: float | int) -> int: + return max(-32768, min(32767, int(round(value)))) + + +def i16_to_le(value: int) -> bytes: + return struct.pack(" int: + return struct.unpack_from(" int: + return struct.unpack_from(" bytes: + """Build a 10-byte velocity frame for the STM32.""" + payload = bytearray(HEADER) + payload.extend(i16_to_le(vx_mm_s)) + payload.extend(i16_to_le(vy_mm_s)) + payload.extend(i16_to_le(omega_mrad_s)) + payload.extend(struct.pack(" VelocityCommand: + """Parse a velocity frame. Used by tooling and lower-machine-side tests.""" + raw = bytes(raw) + if len(raw) != FRAME_LEN: + raise ProtocolError(f"frame length must be {FRAME_LEN}, got {len(raw)}") + if raw[0:2] != HEADER: + raise ProtocolError("invalid frame header") + expected_crc = le_to_u16(raw, 8) + actual_crc = crc16_modbus(raw[:8]) + if expected_crc != actual_crc: + raise ProtocolError(f"crc mismatch expected=0x{expected_crc:04X}, actual=0x{actual_crc:04X}") + return VelocityCommand( + vx_mm_s=le_to_i16(raw, 2), + vy_mm_s=le_to_i16(raw, 4), + omega_mrad_s=le_to_i16(raw, 6), + ) + + +def frame_to_hex(frame: bytes | bytearray) -> str: + return " ".join(f"{b:02X}" for b in bytes(frame)) diff --git a/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/test_cmd_vel_pub.py b/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/test_cmd_vel_pub.py new file mode 100644 index 0000000..cdbb025 --- /dev/null +++ b/sru_ws/src/techx_r2_chassis_control/techx_r2_chassis_control/test_cmd_vel_pub.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import argparse +import time + +import rclpy +from rclpy.node import Node +from geometry_msgs.msg import Twist + + +class CmdVelPublisher(Node): + def __init__(self, vx: float, vy: float, omega: float, rate_hz: float, duration_sec: float) -> None: + super().__init__("test_cmd_vel_pub") + self._publisher = self.create_publisher(Twist, "/cmd_vel", 10) + self._vx = vx + self._vy = vy + self._omega = omega + self._duration_sec = duration_sec + self._start_time = time.monotonic() + self._timer = self.create_timer(1.0 / max(1.0, rate_hz), self._timer_cb) + + def _timer_cb(self) -> None: + elapsed = time.monotonic() - self._start_time + if elapsed > self._duration_sec: + self.get_logger().info("Finished publishing /cmd_vel") + rclpy.shutdown() + return + msg = Twist() + msg.linear.x = self._vx + msg.linear.y = self._vy + msg.angular.z = self._omega + self._publisher.publish(msg) + self.get_logger().info(f"Publish /cmd_vel vx={self._vx:.3f} vy={self._vy:.3f} omega={self._omega:.3f}") + + +def build_arg_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="Publish test /cmd_vel") + parser.add_argument("--vx", type=float, default=0.1, help="linear.x in m/s") + parser.add_argument("--vy", type=float, default=0.0, help="linear.y in m/s") + parser.add_argument("--omega", type=float, default=0.0, help="angular.z in rad/s") + parser.add_argument("--rate-hz", type=float, default=10.0) + parser.add_argument("--duration-sec", type=float, default=3.0) + return parser + + +def main(args=None) -> None: + parser = build_arg_parser() + parsed_args, ros_args = parser.parse_known_args(args) + rclpy.init(args=ros_args) + node = CmdVelPublisher(parsed_args.vx, parsed_args.vy, parsed_args.omega, parsed_args.rate_hz, parsed_args.duration_sec) + rclpy.spin(node) + + +if __name__ == "__main__": + main()