feat(nav2_ws): 方案四——先验地图 + Nav2 + 动作原语 + 行为树

新增独立工作区,与 minco_ws(方案 A/B)、sru_ws(方案 C)平级:
不共享包、不共享参数文件、不改方案 A 一行代码。两套分别启动,不可同时跑
(都占用 /cmd_vel 与 Odin1)。

src/ 下五个包:
- primitives:d_move_actions、d_orient_actions、d_pid_core、d_ramp_drive
- behavior:d_behavior_tree
- interfaces:d_interfaces
- bringup:d_bringup
- exts:pointcloud_to_laserscan(第三方移植)

build/install/log 由 .gitignore 第 1 节排除,入库仅为源码。
设计见 docs/SOLUTION_D.md,移植记录见 docs/PORTING_NOTES.md。
This commit is contained in:
walunt5
2026-11-05 11:59:24 +08:00
parent af171dc11d
commit 9c914d92e1
104 changed files with 6850 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
# nav2_ws — 方案四:先验地图 + Nav2 + Action 原语 + 行为树
与 `minco_ws/`(方案 A/B)、`sru_ws/`(方案 C)**平级且完全独立**:
不共享包、不共享参数文件、不改方案 A 一行代码。
两套**分别启动,不可同时跑**(都占用 `/cmd_vel` 与 Odin1)。
- 设计文档:[`docs/SOLUTION_D.md`](docs/SOLUTION_D.md)
- 移植记录:[`docs/PORTING_NOTES.md`](docs/PORTING_NOTES.md)
## 构建
```bash
cd nav2_ws
source /opt/ros/humble/setup.bash
export PATH=/usr/bin:$PATH # 必须:本机 python3 默认是 3.13
export TMPDIR=$PWD/build/tmp # 必须:/tmp 是 10 MB tmpfs
MAKEFLAGS="-j2" colcon build --parallel-workers 1
```
首次构建失败过就必须加 `--cmake-clean-cache`(CMakeCache 会记住旧的 Python 解释器)。
根目录 `.gitignore` 已覆盖 `build/ install/ log/`。
## 单测(未 source ROS 也能跑)
```bash
cd src/primitives/d_pid_core && /usr/bin/python3 -m pytest test -q
cd src/primitives/d_move_actions && /usr/bin/python3 -m pytest test -q
cd src/primitives/d_orient_actions && /usr/bin/python3 -m pytest test -q
cd src/primitives/d_ramp_drive && /usr/bin/python3 -m pytest test -q
cd src/behavior/d_behavior_tree && /usr/bin/python3 -m pytest test -q
```
## 运行
```bash
# 建图(跑一圈后存盘)
ros2 launch d_bringup bringup.launch.py mode:=mapping
ros2 run nav2_map_server map_saver_cli -f my_map
# 定位 + 导航(先验地图)
ros2 launch d_bringup bringup.launch.py mode:=localization map:=$PWD/my_map.yaml
# 行为树示例流程
ros2 launch d_bringup bt_demo.launch.py
```
## 包结构
```
src/
├── exts/pointcloud_to_laserscan/ # Rc2026 改造版,原样复制(含 enable_second_scan)
├── interfaces/d_interfaces/ # MoveTo / OrientTo / RampDrive
├── primitives/
│ ├── d_pid_core/ # 纯逻辑,零 rclpy 依赖 → 单测可脱离 ROS
│ ├── d_move_actions/ # 车体系 XY 位移 PID
│ ├── d_orient_actions/ # odom 绝对 yaw PID
│ └── d_ramp_drive/ # 四段速度曲线 + 航向保持
├── behavior/d_behavior_tree/ # 共享叶子库 + 示例装配
└── bringup/d_bringup/ # launch + config + maps
```
## 三件事必须先做(上实车前)
1. `config/frames/sensor_mount.yaml` 的 `z` 改成**传感器离地高度取负**(现值 0.30 是占位)
2. 确认 Odin1 真的发布 `odom → imu` 的 TF:`ros2 run tf2_ros tf2_echo odom imu`
3. 建一张自己的先验地图(本仓库**不附带**任何示例地图)
+299
View File
@@ -0,0 +1,299 @@
# 移植笔记(方案四)
逐条记录:**从 Rc2026 复制了什么、改了什么、为什么改**。
参考目录 `/home/xie/26赛季一队BR源码/Rc2026` 在仓库之外,不入库。
---
## 1. 复制清单
只复制了一个包:
```
Rc2026/src/exts/pointcloud_to_laserscan → nav2_ws/src/exts/pointcloud_to_laserscan
```
| 项 | 结果 |
|---|---|
| 文件数 | 15 个(含 `include/`、`src/`、`launch/`、`config/`、`CMakeLists.txt`、`package.xml`、LICENSE、README) |
| 体积 | 120 KB |
| `files/`(423 MB) | **未复制** |
| `.git` | **未复制** |
| 代码改动 | **零改动**(按你的决定:源码里没有自车裁剪就先不加) |
新增的只有本仓自己的参数文件:
```
nav2_ws/src/bringup/d_bringup/config/scan/scan_dual.yaml # 双高度带(路线 2)
nav2_ws/src/bringup/d_bringup/config/scan/scan_single.yaml # 单带(路线 1,排查用)
```
### 1.1 绝对路径检查
```bash
# 只看真正的代码与参数(launch / config / 源码)
grep -rn "/home/" nav2_ws/src --include=*.py --include=*.yaml --include=*.cpp --include=*.hpp --include=*.xml
grep -rn "/home/" nav2_ws/src/bringup/d_bringup/launch/
```
结果:**launch 与 config 全部为空**;`src/**/*.py` 里命中的只有注释
(`d_bringup/utils.py` 的说明文字、`PORTING_NOTES` 里对参考目录的引用),
没有一处是运行时路径。
参考实现里那 9 处 `/home/inkc/inkc/Rc2026/...`
(`launch/stable/challenge1.launch.py` 8 处 + `launch/common/__init__.py` 3 处)
**都没有被带进来**,因为它们属于 `src/action/bringup`,本轮只借用了它的**写法**,
没有复制它的 launch。
本仓所有路径都经 `d_bringup/utils.py` 的 `get_package_share_directory` 解析:
```python
config_path('scan', 'scan_dual.yaml') # → <install>/d_bringup/share/.../config/scan/scan_dual.yaml
```
---
## 2. 逐包改动明细
### 2.1 `pointcloud_to_laserscan`(复制,零改动)
保留上游包名与插件名,**不要**再 apt 安装同名的 `ros-humble-pointcloud-to-laserscan`:
apt 版本没有 `enable_second_scan` 改造,两者同时在环境里会互相覆盖。
已知的改造版特征(读代码确认,不是猜的):
| 特征 | 位置 | 影响 |
|---|---|---|
| `cloudCallback` 对**同一份 `cloud_in`** 调两次 `processLaserScan` | `src/pointcloud_to_laserscan_node.cpp:198-215` | 第二路**不是**第二台传感器;想接 MID360 必须改 C++ 或先合并点云 |
| 第一路用 `filter_frame_`、第二路用 `target_frame2_` 当目标坐标系 | 同上 | 不对称的写法,两者都填 `base_link` 即可 |
| 高度比较是 `z > max \|\| z < min`(闭区间) | 同文件 274 行附近 | `min_height: 0.0` 会放进 `z≈0` 的地面点 → 参数里用 `0.08` |
| 无任何自车裁剪 | 全文 | `range_min` 必须 ≥ 车体外接圆 0.569,否则扫到自己 |
### 2.2 `d_interfaces`(新写)
从 Rc2026 的 `custom/interfaces/*/action/*.action` 借**语义**,字段重写:
| 参考 | 本仓 | 改动 |
|---|---|---|
| `MoveTo.action` | 同 | 注释补全坐标系约定;去掉与本仓无关的字段 |
| `OrientTo.action` | 同 | 同上 |
| `RampDrive.action`(Rc2026 有,用于坡道) | 新增 | 去掉升降/舵机/串口相关字段,只留 `distance_m` / `max_speed` |
| `MerlinStairs` / `FineTuneAlign` / `PickKfs` / `PlaceKfs` / `NavToR1` | **不要** | 赛题/硬件专用 |
### 2.3 `d_pid_core`(新写,参考的 PID 结构)
从 `move_actions/move_action_server.py` 抽出可测的数学,**没有**复制它的节点骨架:
| 参考里的东西 | 处置 |
|---|---|
| `class PID`(积分限幅、条件积分) | 重写为 `d_pid_core/pid.py`,加 `dt` 异常保护、微分先行、可配置低通 |
| `_yaw_from_quaternion` / `_clamp` / `_apply_min_motion_speed` | 拆到 `angles.py` / `motion.py` |
| `_project_body` | 重写为 `planar_delta_in_start_frame`,并明确"为什么以起点车体系为基准" |
| `rc2026_logger`(`MissionLogger`、CSV 落盘、`/home/.../logs`) | **不要**:自带绝对路径日志目录 |
| `CmdVelConflictGuard`(`angular.y` 水印判冲突) | **不要**:本仓用"行为树先 PauseNav2"的流程约束代替,理由见 `primitives.launch.py` 注释 |
### 2.4 `d_move_actions` / `d_orient_actions`(新写,参考的 Action 服务器结构)
| 改动 | 说明 |
|---|---|
| 定位源 | TF(`odom→base_link`)→ **`/odin1/odometry` 话题**。AMCL 重定位会让 `world→odom` 瞬移,按 TF 算位移会误判到位 |
| 参数 | 抽到 `params.py`,启动时 `validate()` 自检(守住 `output_limit ≤ 0.5`) |
| 日志 | `rc2026_logger` → `self.get_logger()` |
| 多线程 | 保留 `MultiThreadedExecutor` + `ReentrantCallbackGroup`(execute 回调里要收 odom) |
### 2.5 `d_ramp_drive`(新写,只借曲线思路)
| 参考 | 本仓 | 为什么 |
|---|---|---|
| 速度 `0.5 / 0.7 / 0.7 / 0.3` | **`0.20 / 0.28 / 0.40 / 0.15`** | 底盘限幅 0.5 且静默截断:0.7 会被压成 0.5,四段曲线形状失真(中段两档并成一档) |
| 升降抬升(`LIFT_*` 话题、mm 单位、超时 5 s) | **删除** | RC2027 底盘协议不同,本轮不重写底盘协议 |
| 舵机/吸盘/串口相关 | **删除** | 同上 |
| 阶段只前进不回退 | 保留 | z 抖动时来回切档 = 在坡面上自己制造冲击载荷 |
| 滑退检测(`z_rise` 下降) | 保留 | 抽出为纯函数 `is_slipping()`,可单测 |
| yaw PD(用 yaw 差分,不用 `twist.angular.z`) | 保留 | 400 Hz IMU 角速度噪声直接进 D 项会把舵量打成锯齿 |
### 2.6 `d_behavior_tree`(新写,借分层方式)
| 参考 | 本仓 |
|---|---|
| `challenge1/common/nodes.py` 的 `ActionClientNode` / `ServiceNode` / `PubWaitNode` / `WaitForStatusNode` | 抽象成 `ActionLeaf` / `ServiceLeaf` / `WaitLeaf` |
| `challenge1/common/retry.py` 的 `_R()`(Retry 包装) | `composites.retry()` |
| `challenge1/z1/tree.py` 的装配方式(Sequence/Selector 组合成子树) | `demo_tree.create_demo_tree()` |
| `py_trees_ros` 的 ROS 叶子 | **不用**(见 3.2),自己写 rclpy 版叶子 |
| 各赛题子树(z1/z2/competition) | **不要** |
新增了一层参考实现没有的东西:`status.py` —— 把 goal 状态映射成 SUCCESS/FAILURE/RUNNING 的
纯逻辑模块。这是行为树里最容易出静默错误的地方(比如把 `CANCELED` 当成功),
单独拆出来才能无 ROS 单测。
### 2.7 `d_bringup`(新写,借参数组织方式)
| 参考 | 本仓 | 改动 |
|---|---|---|
| `config/challenge1/{nav2,slam_toolbox,exts,maps}/` 分目录 | `config/{nav2,slam_toolbox,scan,frames,primitives}/` | 目录结构照搬,按方案四的模块重分 |
| `config/challenge1/nav2/v1,v2,backup/nav2v2.yaml` 三份历史版本共存 | **只留一份** | 历史版本靠 git,不靠目录 |
| `launch/stable/challenge1.launch.py`(硬编码路径 + 赛题节点) | `launch/bringup.launch.py` | 去绝对路径、去赛题节点、`mode:=` 分建图/定位 |
| `config/challenge1/maps/sysv1/`(别队场地地图) | **不放** | 避免"拿着别人的场地地图跑出定位很好"的错觉;`maps/` 只放 README |
| 底盘 `vehicle_driver`(串口协议) | 复用 `minco_ws/src/chassis/techx_r2_chassis_control` | 不重写协议 |
| `odin_ros_driver` | 复用 `sru_ws/src/odin_ros_driver` | 一行不改 |
---
## 3. 环境事实与偏差
### 3.0 构建本机的三个坑(都实际踩过)
```bash
cd nav2_ws
source /opt/ros/humble/setup.bash
export PATH=/usr/bin:$PATH # 坑 1
export TMPDIR=$PWD/build/tmp # 坑 2
MAKEFLAGS="-j2" colcon build --parallel-workers 1 # 坑 3 见下
```
| 坑 | 现象 | 原因与对策 |
|---|---|---|
| 1. `python3` 指向 3.13 | `ModuleNotFoundError: No module named 'em'`(rosidl_adapter 生成接口时) | 本机 PATH 里 `python3` 是 WorkBuddy 管理的 3.13,`empy` 只装在 3.10 的 dist-packages。**必须让 `/usr/bin` 优先** |
| 1b. CMakeCache 记住旧解释器 | 改了 PATH 仍然报同样的错 | `Python3_EXECUTABLE` 被缓存在 `build/<pkg>/CMakeCache.txt`。首次构建失败过就必须 `--cmake-clean-cache` |
| 2. `/tmp` 只有 10 MB(tmpfs) | `fatal error: error writing to /tmp/ccXXXX.s: 设备上没有空间` | gcc 的临时汇编文件写不下。把 `TMPDIR` 指到根盘(本机放在 `build/tmp`,`build/` 已被 `.gitignore` 覆盖,不污染 `git status`) |
| 3. 并行编译 OOM | 24 核机器编大包会 OOM | 沿用仓库既有约定:`--parallel-workers 1` + `MAKEFLAGS="-j2"` |
### 3.1 构建结果(本机实测)
```
Summary: 8 packages finished
d_interfaces · d_pid_core · pointcloud_to_laserscan · d_move_actions
d_orient_actions · d_ramp_drive · d_behavior_tree · d_bringup
```
冒烟验证:
| 检查 | 结果 |
|---|---|
| 纯逻辑单测(未 source ROS) | **92 项全绿**(29 + 8 + 8 + 23 + 24) |
| 7 个 launch 的 `--show-args` | 全部正常解析,参数齐全 |
| `localization.launch.py` 不传 `map:=` | 给出可执行的错误提示(而不是静默起半套栈) |
| 三个原语节点实起 | 参数自检通过,日志打出 `限幅=0.45` 与四段速度 `0.20/0.28/0.40/0.15` |
| 6 个 ROS 模块 import | 全部通过 |
### 3.2 `py_trees`:apt 装不了,改用 pip
`apt-get install ros-humble-py-trees-ros` 在本容器里失败:
```
E: 无法打开锁文件 /var/lib/dpkg/lock-frontend ... 不允许的操作
```
原因不是权限配错,而是 `uid=0` 实际映射到 `nobody`(`/var/lib/dpkg` 属主是 `nobody:nogroup`),
拿不到真正的 root。**在正常机器上请用 apt 装**(版本对齐 ROS 发行版):
```bash
sudo apt install ros-humble-py-trees ros-humble-py-trees-ros
```
本机的替代方案:
```bash
/usr/bin/python3 -m pip install --user "py-trees<2.4" # → py_trees 2.3.0
```
`py_trees_ros` **没有装**(PyPI 上没有对应包)。影响与对策:
- 本仓的叶子节点**不依赖 `py_trees_ros`**,只用 `py_trees` 的组合/装饰器 + 自己的 `rclpy` 叶子;
- 参考实现的叶子也是自己写的(`ActionClientNode` 等),所以这条不算偏离;
- 若日后要用 `py_trees_ros` 的现成叶子(如 `py_trees_ros.actions`),先 apt 装再改。
**py_trees 版本差异(已踩过,写进单测)**:2.3+ 的 `Behaviour.tick()` 是**生成器**,
必须被消费才推进状态;直接 `root.tick()` 什么都不会发生。统一改用
`py_trees.trees.BehaviourTree.tick()`,2.2 与 2.3+ 行为一致。
### 3.3 单测在未 source ROS 的环境下运行
```bash
cd nav2_ws/src/primitives/d_pid_core && /usr/bin/python3 -m pytest test -q
cd nav2_ws/src/primitives/d_move_actions && /usr/bin/python3 -m pytest test -q
cd nav2_ws/src/primitives/d_orient_actions && /usr/bin/python3 -m pytest test -q
cd nav2_ws/src/primitives/d_ramp_drive && /usr/bin/python3 -m pytest test -q
cd nav2_ws/src/behavior/d_behavior_tree && /usr/bin/python3 -m pytest test -q
```
机制:每个包根目录放 `conftest.py`,把**源码目录**插进 `sys.path`,
于是 `import d_pid_core` 命中源码树而不是 `install/`。所以这些命令
不依赖 `colcon build`、不依赖任何 `setup.bash`。
> 注意:`d_pid_core` 的模块顶层**不许出现 `import rclpy`**,否则这套机制立刻失效。
### 3.4 参考实现里的三个坑(交叉核对源码后补记)
**1. `bringup/config/challenge1/odin_ros2_driver/control_command.yaml` 是死配置**
它的 `sendodom: 0`、`custom_map_mode: 0` 等值**根本不会生效**:6 个 launch 全部走
`get_package_share_directory('odin_ros_driver')`,取的是驱动包内那份
(`src/driver/odin_ros_driver/config/control_command.yaml`,`sendodom: 1`)。
坑在哪:改这份副本时所有参数"都没反应",而排查方向通常是"驱动坏了"或"TF 断了"。
本仓的等价教训:**参数文件只有一处真源**,跨包的配置拷贝必须删掉或注明"非生效副本"。
**2. `ramp_drive` 的速度值在同一文件里三处不一致**
| 来源 | 值 |
|---|---|
| `ramp_drive/config.py` 常量 | `0.5 / 0.7 / 0.7 / 0.3` |
| 同文件上方注释 | `0.20 / 0.25 / 0.45 / 0.18` |
| 第三方解读文档(按注释写) | `0.20 / 0.25 / 0.45 / 0.18` |
结论:**速度值不能照抄**,只能实车标定。本仓重标定为 `0.20/0.28/0.40/0.15`,
并用 `validate()` 把"任一段超过底盘限幅 0.5"变成启动期错误——这样即使以后有人
把值改成 0.7,也不会静默跑成失真曲线。
**3. 恢复行为会抢 `/cmd_vel`**
参考实现的 `navigate_to_pose_fast_recovery.xml` 里**没有** Spin/Wait/BackUp,
只留 `ClearEntireCostmap`。核对 XML 结构确认:`RecoveryNode retries=2` +
`ReactiveFallback`,恢复分支只有一个清图 Sequence。
本仓同步做了两件事,防止这个坑复发:
- `config/nav2/bt_nav_to_pose.xml`:删掉这三个动作;
- `navigation.yaml` 的 `behavior_plugins` 只留 `wait`(不发速度),
这样即使有人把 BT 换回 Nav2 默认树,`spin`/`backup` 也没被加载、不会复活成抢控制权。
同时 `nav2.launch.py` 改成自己起 6 个节点 + lifecycle_manager,
原因是 BT XML 的路径必须在运行时由 `get_package_share_directory` 注入;
写死在 yaml 里换机会静默退回默认树(于是 Spin/BackUp 又回来),且不报错。
实现上刻意不用 `RewrittenYaml`:`parameters=[params_file, {覆盖项}]`
按顺序应用、后者胜,少一个 `nav2_common` 依赖。
### 3.5 两个只有实跑才会暴露的参数坑
`colcon build` 通过 ≠ 配置正确。这两条都是启动 Nav2 栈时立刻崩、但静态检查发现不了的:
| 现象 | 原因 | 修法 |
|---|---|---|
| `controller_server` 启动即崩:`parameter 'height' has invalid type: parameter {height} is of type {integer}, setting it to {double} is not allowed` | Nav2 把局部代价地图的 `width` / `height` 声明为 **int** 参数(单位是米),写成 `5.0` 就类型冲突 | 写 `width: 5` / `height: 5`(上游默认与 Rc2026 也都是整数) |
| `controller_server` 卡在 unconfigured:`Controller period more then model dt, set it equal to model dt` | MPPI 要求 `1/controller_frequency <= FollowPath.model_dt`。我写了 15 Hz(周期 0.0667)配 `model_dt: 0.05` | `controller_frequency: 20.0`(周期 = 0.05 = model_dt),与参考实现一致。若 CPU 扛不住,**先改 `model_dt` 再降频率**,只改频率会再次触发 |
验证方式(配三条静态 TF 模拟驱动的 `odom→imu` 与 AMCL 的 `world→odom`):
```bash
ros2 run tf2_ros static_transform_publisher --frame-id world --child-frame-id odom ... &
ros2 run tf2_ros static_transform_publisher --frame-id odom --child-frame-id imu ... &
ros2 launch d_bringup tf.launch.py &
ros2 launch d_bringup nav2.launch.py
# 期望日志末行:lifecycle_manager_navigation: Managed nodes are active
```
缺 `world` 时 `planner_server` 会一直刷 `Timed out waiting for transform from base_link to world`
——那不是配置错,是 AMCL/slam_toolbox 还没起,属正常现象。
---
## 4. 本轮明确没做的事
| 项 | 原因 |
|---|---|
| 给 `pointcloud_to_laserscan` 加自车裁剪(`crop_*`) | 你的决定:源码里没有就先不加。代价写在 `SOLUTION_D.md` 4.3 |
| 两台 Odin1(路线 3) | 需两台相对位姿标定,本轮无硬件 |
| 实车调试 | 本轮范围外 |
| 多楼层(`floor_manager`、层间换图) | 无比赛地图、无抬升机构;接口约定记在 `SOLUTION_D.md` 8.1 |
| 爬楼原语(`StairClimb`) | 抬升机构与爬楼程序都还没出来 |
| 拨杆心跳重试(`RetrySupervisor`) | 暂无遥控接管需求;机制记在 `SOLUTION_D.md` 8.4 |
+353
View File
@@ -0,0 +1,353 @@
# 方案四:先验地图 + Nav2 + Action 原语 + 行为树
> 第四套定位与导航方案,代码在 **`nav2_ws/`**,与 `minco_ws/`(方案 A/B)、
> `sru_ws/`(方案 C)平级、**完全独立**:不共享包、不共享参数、不改方案 A 一行代码。
> 参考实现为仓库外的 Rc2026(`/home/xie/26赛季一队BR源码/Rc2026`,不入库)。
---
## 1. 与前三套的关系
| | 方案 A(在用) | 方案 B(备用) | 方案 C(备用) | **方案四** |
|---|---|---|---|---|
| 位置 | `minco_ws/src/scan` | `minco_ws/src/navigation` | `sru_ws` | **`nav2_ws`** |
| 传感器 | MID360 | MID360 | Odin1 | **Odin1(车上有两台,用一台)** |
| 先验地图 | 无,上电原点重置 | 无 | 无 | **有,跨上电全局定位** |
| 定位 | Point-LIO(无回环) | Point-LIO | Odin1 里程计 | **slam_toolbox 建图 + AMCL 定位** |
| 规划 | 局部滑窗 A*(3.5 m) | Nav2 + SMAC + MINCO | 无 | **NavFn 全局(地图系)** |
| 控制 | 自写轨迹跟踪 | MINCO MPC(qpOASES) | 网络直接出速度 | **Nav2 MPPI(Omni 模型)** |
| 处理特例 | 靠调参 | 靠调参 | 靠训练 | **切成离散 Action 原语** |
| 编排 | FSM | Nav2 BT | 单节点循环 | **py_trees 行为树** |
| 输出 | `/cmd_vel` | `/cmd_vel` | `/cmd_vel` | `/cmd_vel` |
新东西只有三件:**先验地图带来的全局定位**、**Action 原语层**、**行为树编排**。
执行层完全复用:四套都只写 `/cmd_vel`,都由
`minco_ws/src/chassis/techx_r2_chassis_control` 落到串口。
---
## 2. 数据流
```
┌─────────────── Odin1(高位,/odin1/cloud_slam)───────────────┐
│ │
▼ │
pointcloud_to_laserscan(单实例,enable_second_scan=true) │
├── 低带 0.08–0.45 m ──► /odin1/scan_low ──┐ │
└── 高带 0.30–1.20 m ──► /odin1/scan_slam ──┼──┐ │
│ │ │
Odin1 里程计 /odin1/odometry ──► TF: odom ────────────┘ │ │
▼ │
建图模式: slam_toolbox(mapping) ──► /map + TF world→odom │
定位模式: map_server(先验地图) + AMCL ──► TF world→odom │
│ │
TF 树: world → odom → imu → base_link │
▼ │
┌─────────────────────── Nav2 ───────────────────┐ │
│ global_costmap(world, static+obstacle+inflation)│ │
│ NavFn ──► SimpleSmoother ──► MPPI(Omni) │ │
│ bt_navigator(默认行为树) │ │
└──────────────────────┬─────────────────────────┘ │
│ │
特例动作(行为树先暂停 Nav2) │ │
MoveTo / OrientTo / RampDrive ───┤ │
▼ │
/cmd_vel │
│ │
底盘桥(minco_ws,omega_sign=-1,限幅 0.5) │
▼ │
STM32 ──────────────────────────────┘
```
TF 责任划分:
| 变换 | 谁发布 |
|---|---|
| `world → odom` | slam_toolbox(建图)或 AMCL(定位),**二选一** |
| `odom → imu` | Odin1 驱动(`send_odom_baselink_tf: 1`),不改驱动 |
| `imu → base_link` | `d_bringup/launch/tf.launch.py`,外参在 `config/frames/sensor_mount.yaml` |
`base_link` **定义在车体中心的地面投影点**(不是方案 A 的离地 0.25 m 碰撞参考高度)。
理由:Nav2 的 2D 代价地图天生假设 `robot_base_frame` 在地面上;这样定之后,
高度带参数就直接等于"离地高度",不必每次改安装高度都做一次换算。
---
## 3. 插件选型(照参考实现,参数按 RC2027 重调)
出处:Rc2026 `src/action/bringup/config/challenge1/nav2/v2/nav2v2.yaml`
| 角色 | 插件 | 本仓库位置 |
|---|---|---|
| 全局规划 | `nav2_navfn_planner/NavfnPlanner` | `config/nav2/navigation.yaml` |
| 控制器 | `nav2_mppi_controller::MPPIController`(`motion_model: Omni`) | 同上 |
| 平滑器 | `nav2_smoother::SimpleSmoother` | 同上 |
| 目标判定 | `nav2_controller::SimpleGoalChecker` | 同上 |
| 进度检查 | `nav2_controller::SimpleProgressChecker` | 同上 |
| 恢复行为 | ~~`spin` / `backup` / `drive_on_heading` / `assisted_teleop` / `wait`~~ → **只留 `wait`(不被行为树引用)**,恢复手段改为「清代价地图 + 重规划」 | 同上,但**刻意减配**,理由见 3.2 |
| 定位 | `nav2_amcl`(`OmnidirectionalMotionModel`) | `config/nav2/localization.yaml` |
代价地图:局部 `obstacle_layer + inflation_layer`(滚动窗口 5×5 m),
全局 `static_layer + obstacle_layer + inflation_layer`,`resolution: 0.05`。
### 3.1 车体与速度:必须改的两个数
```
车体 0.81 × 0.80 m → 半长 0.405、半宽 0.400、外接圆半径 0.5694、内切圆 0.400
footprint: "[[0.405, 0.400], [0.405, -0.400], [-0.405, -0.400], [-0.405, 0.400]]"
footprint_padding: 局部 0.03 / 全局 0.01
```
| 项 | Rc2026 | 方案四 | 原因 |
|---|---|---|---|
| footprint | 0.5×0.5 | **0.81×0.80** | 实车尺寸(验收文档含裕度为 0.99×0.98,那是场地验证口径,导航按实车算) |
| 速度上限 | `[1.5, 1.5, 3.0]` | **`[0.45, 0.45, 0.45]`** | 底盘桥限幅 0.5 且**静默截断**;给 1.5 时车只走 0.5,MPPI 仍按 1.5 规划,跟踪误差持续累积 |
| `min_y_velocity_threshold` | 0.5(差分默认) | **0.001** | 麦轮用 Omni 模型,0.5 会把所有横移指令抹成 0 |
| costmap 分辨率 | 0.1 | **0.05** | 0.16 m 的箱在 0.1 m 栅格上只占 1–2 格,膨胀后仍可能被判成可穿越缝隙 |
留 10% 余量取 0.45 而不是 0.5:长期顶在限幅上时,PID/MPPI 的输出与真实执行量
永远差一个常数,等于引入持续的稳态误差。
### 3.2 恢复行为:为什么必须删掉 Spin / BackUp
参考实现的 `navigate_to_pose_fast_recovery.xml` 里**没有** Spin / Wait / BackUp,
只有 `ClearEntireCostmap`(我核对过 XML 结构:`RecoveryNode retries=2` +
`ReactiveFallback`,恢复分支只有一个清图 Sequence)。
照抄默认 Nav2 行为树会出问题,原因很具体:**`Spin` 与 `BackUp` 都往 `/cmd_vel`
写速度,而方案四的 `MoveTo` / `OrientTo` / `RampDrive` 也写同一个话题**,
跨节点没有仲裁。MPPI 判定卡住触发 backup 的那一刻,行为树可能正在跑 `OrientTo`,
两个发布者互相覆盖——车在原地抽搐,而两边日志都显示"正常"。
所以本仓:
- `config/nav2/bt_nav_to_pose.xml`:删掉这三个动作,只留清图 + 重规划;
- `navigation.yaml` 的 `behavior_plugins` 只留 `wait`(它不发速度),
防止"某天有人把 BT 换回默认树"时它们突然复活成抢控制权;
- "真的卡死"交给上层行为树报 FAILURE,由外层决定重试还是放弃,而不是让 Nav2 自己瞎动。
全向底盘不需要 Backup 让位:NavFn + Omni MPPI 本来就能横移脱困,倒车是最差的逃离方式。
---
## 4. 第八节:2D 投影的高度带——选型、依据、放弃项
### 4.1 选型:路线 2(单台 Odin1,双高度带)
| 路线 | 做法 | 结论 |
|---|---|---|
| 1 单台单带 | 照抄 0–0.5 m | 保留为**排查手段**(`scan_profile:=single`),不作交付形态 |
| **2 单台双带** | `enable_second_scan`,低带 + 高带分别喂不同消费者 | ✅ **采用** |
| 3 两台 Odin1 各一路 | 两个实例、各吃各的云 | 架构预留(话题名已参数化),**本轮不做**:需两台相对位姿标定 |
| 4 Odin1 + MID360 | 合并点云或改节点吃第二路 | ❌ 排除:MID360 属方案 A 驱动栈,违反"两套完全独立" |
**为什么路线 2 够用**:担心"两带互相污染"的前提是两带都进 costmap。实际上
高带根本不需要进 costmap——它只喂 slam_toolbox / AMCL。消费者一分开,
污染问题就消失了:SLAM 拿到干净的墙面特征,避障拿到矮障碍信息。
### 4.2 高度带上下界的依据
| 参数 | 取值 | 依据 |
|---|---|---|
| 低带下界 | **+0.08 m** | 高于地面起伏 + 深度噪声 + TF 抖动。**不能取 0.0**:节点的比较是 `z > max \|\| z < min`(闭区间),`0.0` 会把 `z≈0` 的地面点放进来,在远距离渲染出一圈假障碍 |
| 低带上界 | **+0.45 m** | 覆盖 16 cm 箱到腰部障碍;再高会把桌面、椅面当障碍,窄道通过率下降 |
| 高带 | **+0.30 ~ +1.20 m** | 墙面特征最丰富的区间,避开地面杂波与顶部灯架 |
| 低带 `range_max` | 6.0 m | 远距低带点稀且噪声大 |
| 高带 `range_max` | 10.0 m | 与 slam_toolbox `max_laser_range` 一致 |
参考实现用 `0–0.5`,我们用 `0.08–0.45`:下界抬高是修地面点,上界下调是避开桌面。
### 4.3 `range_min` 与近距盲区
```
车体外接圆半径 = sqrt(0.405² + 0.400²) = 0.5694 m
低带 range_min = 0.60 m ≈ 外接圆 + 3 cm 裕度
```
`0.6` 不是"随手取的整":参考实现那份 `pointcloud_to_laserscan` **没有任何自车裁剪**
(全文无 self/footprint 逻辑),所以只能靠距离门限盖住自己的车体。代价非常具体:
- **0.6 m 内完全看不见**。车侧 0.45 m 处有墙时,它在车体之外(不碰撞)、
在 0.6 m 之内(看不见)→ costmap 认为自由 → MPPI 不做任何纠偏。
- 盲区环宽度 = 0.6 − 0.405(半长)= **0.195 m**(正前方)到 0.6 − 0.40 = **0.2 m**(正侧方)。
- **inflation 救不了**:从未被标记的障碍,膨胀不出来。
本轮按你的决定**不加自车裁剪**,因此保留 0.6。盲区的工程补偿手段(按优先级):
1. **降速通过窄道**:`.45` → 现场用 `nav2` 的 `/speed_limit` 或改 MPPI `vx_max` 临时压到 0.2;
2. **用原语做最后 0.6 m**:贴边对准交给 `MoveTo`(2 cm 容差、30 Hz 闭环),
它的反馈来自里程计而不是 costmap,不受盲区影响;
3. **上裁剪后再降 `range_min`**:节点加一组 `crop_*` 参数(`|x|≤0.50, |y|≤0.49`)
后,可按低带 `0.15` / 高带 `0.55` 配置。这是**下一步唯一值得动的 C++**,
本轮按要求不动源码。
> 取舍结论:**我们用"0.6 m 盲区"换"复制代码零改动"**。
> 如果窄道科目成为瓶颈,优先做第 3 条。
### 4.4 明确放弃的能力
1. **高低分层通过性判断**:2D 投影丢掉高度信息,16 cm 的箱和 2 m 的墙在 costmap 里
完全等价。方案四"看见了矮箱,但无法与高墙区分"——对"能不能压过去"的判断
比方案 A 更宽松,对"必须绕开这个矮箱"两者都做不到分层决策。
2. **0.6 m 内的障碍感知**(见 4.3)。
3. **坡面上的可靠 2D 感知**:车体俯仰会让高度带整体漂移,坡道改由 `RampDrive`
原语接管(暂停 Nav2)。
4. **动态障碍预测**:只有 costmap 的"当前占据",没有速度估计。
---
## 5. 依赖先验地图的失效条件
方案四的核心假设是"**场地几何在赛前建图后不再变化**,且上电位置在地图覆盖范围内"。
以下任一条被打破,定位即失效——**不会崩,但会给出自信的错误位姿**,这是最危险的形式:
| 失效条件 | 表现 | 现场判据 / 对策 |
|---|---|---|
| **场地被改动**(家具移位、道具增删) | AMCL 在旧地图上收敛到错误位置;static_layer 把不存在的墙当障碍 | 每场开赛前重跑 `mode:=mapping`;或建图后只用 obstacle_layer 动态避障,static_layer 仅作参考 |
| **上电位置在地图外 / 未给初始位姿** | 粒子云均匀撒在整张图上,可能收敛到镜像对称的位置 | 必须先给 `/initialpose`(RViz 的 2D Pose Estimate);`set_initial_pose: false` 是刻意的,避免用错原点 |
| **场地高度对称**(长走廊、两侧同构) | 多峰分布,粒子在两处来回跳,机器人"以为自己在另一侧" | 建图时留下不对称特征;或加 `pf_z`、减少 `max_particles` 抑制跳变 |
| **地面反光 / 强逆光 / 大雾** | Odin1 深度点缺失,扫描大段 `inf`,AMCL 更新退化 | 判据:`ros2 topic hz /odin1/scan_slam` 频率正常但有效点占比骤降;降速并切原语 |
| **建图时里程计漂移**(`use_scan_matching: false`) | 地图本身有重影,长距离回环处墙厚一倍 | 建图后目视检查 pgm;严重则开 `use_scan_matching: true` 重建 |
| **地图分辨率与车体不匹配** | 0.05 m 栅格 + 0.81 m 车 → 窄道在地图上被膨胀"封死",NavFn 报无路径 | 现场用 0.5 m 宽的实测通道验证;必要时只对全局图降 `inflation_radius` |
| **`sensor_mount.yaml` 的 z 填错** | 高度带整体平移:矮障碍消失或地面变障碍 | 静态 TF 的 z 必须等于"传感器离地高度取负";改安装必须重测 |
| **两套方案同时启动** | 都写 `/cmd_vel`、都抢 Odin1,行为随机 | **硬约定:方案 A 与方案四分别启动,不可同时跑** |
| **AMCL 重定位瞬间** | `world→odom` 跳变,按 TF 算位移的原语会误判"已到位" | 原语的位移反馈一律用 `/odin1/odometry`,不用 TF(已在代码里落实) |
---
## 6. 移植映射表
| Rc2026 来源 | 处置 | 落点 | 具体改动 |
|---|---|---|---|
| `src/exts/pointcloud_to_laserscan` | **要**(复制源码) | `src/exts/` | 原样复制,**未加裁剪补丁**;仅新增参数文件(双带/单带) |
| `config/.../nav2/v2/nav2v2.yaml` | **要**(参数组织方式) | `config/nav2/navigation.yaml` | 插件照抄;footprint/速度/分辨率/frame 全部重调 |
| `config/.../slam_toolbox/slamtoolbox_v1.yaml` | **要** | `config/slam_toolbox/mapping.yaml` | `map_frame: world`、`odom_frame: odom`、`resolution: 0.05`、`scan_topic: /odin1/scan_slam` |
| `custom/actions/move_actions` | **要接口 + PID 结构** | `d_interfaces` + `d_pid_core` + `d_move_actions` | 剥掉 `rc2026_logger`(换标准 logging);定位源改 `/odin1/odometry`;参数抽到 `params.py` 并加启动自检 |
| `custom/actions/orient_actions` | **要接口 + PID 结构** | `d_interfaces` + `d_orient_actions` | 同上;绝对 yaw 语义保留 |
| `custom/actions/ramp_drive` | **只要四段曲线 + 线保持** | `d_ramp_drive` | 速度 0.5/0.7/0.7/0.3 → **0.20/0.28/0.40/0.15**;删掉升降/舵机/串口相关 |
| `action/challenge1`(py_trees 分层) | **要分层方式** | `d_behavior_tree` | 叶子改为调 Nav2 生命周期服务 + 本仓 Action |
| `action/bringup` 分层 launch | **要写法** | `d_bringup/launch` | 全部经 `get_package_share_directory`,零绝对路径 |
| `common/rc2026_logger` | **不要** | — | 自带绝对路径日志目录 |
| `driver/vehicle_driver` | **不要** | — | 复用 `minco_ws/src/chassis/techx_r2_chassis_control` |
| `driver/odin_ros_driver` | **不要** | — | 复用 `sru_ws/src/odin_ros_driver`,一行不改 |
| `kfs6d_detect` / `kfs_tracker` / `arm_control` / `weapon_detect` / `merlin_stairs` / `fine_tune_align` / `merlin_planning` / `zone_detection` | **不要** | — | 赛题几何与硬件无关 |
| `files/`(423 MB)、`.git` | **不要** | — | 命令与数据不入库 |
### 必须改造(不属于"移植")
1. **frame 统一**:`map → world`、`base_link` 保留、`odom` 保留 Odin 原生名
(改它要动驱动或 TF 发布者,违背"不改驱动")。
2. **footprint / 速度限幅**:见 3.1。
3. **launch 去绝对路径**:参考实现有 9 处 `/home/inkc/...`,
复制过来不报错、会静默跑错脚本。
4. **坡道速度重标定**:参考实现的 0.7 m/s 会被底盘静默压成 0.5,四段曲线形状失真。
---
## 7. 代码结构
```
nav2_ws/src/
├── exts/pointcloud_to_laserscan/ # 参考实现改造版,原样复制
├── interfaces/d_interfaces/ # MoveTo / OrientTo / RampDrive
├── primitives/
│ ├── d_pid_core/ # 纯逻辑(零 rclpy),单测可脱离 ROS 跑
│ ├── d_move_actions/ # 车体系位移 PID
│ ├── d_orient_actions/ # odom 绝对 yaw PID
│ └── d_ramp_drive/ # 四段曲线 + 航向保持
├── behavior/d_behavior_tree/ # 叶子库 + 示例装配
└── bringup/d_bringup/ # launch + config + maps
```
分层的关键设计:**`d_pid_core` 是唯一不 import rclpy 的 Python 包**。
一旦 `import rclpy` 出现在模块顶层,`pytest` 就必须先 source ROS 才能 import,
"未 source 环境可跑单测"随即失效。结构上强制逻辑/ROS 壳分界。
---
## 8. 与参考实现的差异复核
来源:Rc2026 源码逐文件核对 + 两份第三方解读文档(`Rc2026_仓库全景解读`、
`Rc2026_Odin1无图端到端导航_源码剖析`)交叉验证。下面每一条都标了证据位置。
### 8.1 参考实现的"先验定位"到底是什么
它**不是**点云地图检索,而是**结构化地标检测 → 在 odom 下锁定一个坐标系 → 高频重发常值**:
| 环节 | 位置 | 做法 |
|---|---|---|
| 梅林前立面 | `zone2/detector_node.py` `_send_tf` / `_tf_timer_cb` | 点云 ROI → 高度归一 → 地面检测 → 取离地 200/400 两带 → 2D 直方图边缘 → RANSAC 拟合墙面 → 白/黄柱判决 → 靶心 → 发 `odom → blue_zone2_root` |
| 九宫格 | `zone3/localizer_node.py` docstring | **不用点云匹配**:用上坡轨迹(坡底点 + 坡顶点 + 坡向)拟合 `odom → blue_zone3_root` |
| 锁定后 | `DYNAMIC_TF_RATE = 200` | 多帧稳定判定后坐标变常值,靠 200 Hz 重发维持有效,**不再随点云抖动** |
| 场地静态几何 | `bringup/script/rc26_field.py` | 只发 zone_root **之下**的静态帧;`PUBLISH_FIELD_ROOT = 0` 时各 root 是独立根帧,由上面的检测节点接进 odom |
**关键限制**:父帧是 `odom`。所以这是"在里程计坐标系里对齐场地",不是全局重定位;
漂移之后没有任何纠正机制(文档自述只能 `set_param.sh algo_reset 1`)。
本质是**用"一次性对准 + 里程计不漂"换掉"持续地图匹配"**。
对三层地图的启示(未实现,仅记录):L1→L2 可以照 zone3_localizer 的思路,
用**坡底点 + 坡顶点 + 坡向**拟合出 `world_l2`;L2→L3 用爬楼结束时的 `z_rise` +
预设位姿发 `world_l3`。这样层间切换不需要换 `/map`、不需要重启 AMCL,
代价是每层仍要各自的 2D 图(三层的墙会在同一 `(x,y)` 上叠加,不能压平拼一张)。
### 8.2 三处"看起来一样、实际不同"的配置
| 项 | 参考实现 | 本仓 | 为什么 |
|---|---|---|---|
| 恢复行为 | 删掉 Spin/Wait/BackUp,只留清图 | 同(见 3.2) | 都会写 `/cmd_vel`,与行为树抢控制权 |
| `map→odom` 由谁发 | slam_toolbox(mapping 模式、关扫描匹配)→ 近似单位变换;AMCL `tf_broadcast: false` 完全禁用 | AMCL(定位模式)或 slam_toolbox(建图模式),**二选一** | 参考实现靠"起跑位姿可复现"把 map 当 odom 别名用;本仓要真先验定位 |
| `sendodom` | 生效值是 `1`(驱动包内那份);`bringup/config/challenge1/odin_ros2_driver/` 那份 `sendodom: 0` 是**死配置**——6 个 launch 全走 `get_package_share_directory('odin_ros_driver')`,没有任何一个引用它 | 驱动包内 `sendodom: 1` | 改 bringup 副本不会生效,极易误判"TF 断了" |
### 8.3 一条硬件事实,会直接改我们的外参设计
参考车底盘**升降行程 0–420 mm,且轮子始终接地**——升降改变的是**车体框架高度**。
Odin1 装在框架上,所以**升降一动,传感器离地高度就变**,而 `base_link` 定在地面投影点不动。
后果:`imu → base_link` 的 z 不是常量。抬升 10 cm,高度带 `0.08–0.45 m` 整体上移 10 cm,
**16 cm 的箱子从视野里消失、地面开始被当成障碍**,且完全不报错。
本仓处理:`sensor_mount.yaml` 拆成 `sensor_height_m`(静态安装高度)+
`lift_offset_m`(当前抬升量),z 由 `tf.launch.py` 合成。
抬升机构到位后应由 lift 节点在运行时改写这条 TF,**不要退回单一常量**。
### 8.4 两个可借鉴的工程机制(已部分落地)
| 机制 | 参考实现 | 本仓 |
|---|---|---|
| "失败也要收尾" | `Nav2LifecycleDecorator`:FAILURE 时仍执行 PAUSE,防生命周期泄漏 | `composites.with_cleanup()`:失败分支先恢复 Nav2 再把 FAILURE 传出去(6 项单测锁住语义) |
| 人手接管重试 | 拨杆心跳消失 → 停车等待;恢复 → 重跑(`RetrySupervisor` + 黑板 generation) | 未做。等有遥控接管需求时再补 |
### 8.5 两份解读文档自身的一处偏差
第一份文档把 `ramp_drive` 的描述为 v6 曲线 `0.20/0.25/0.45/0.18`,
但源码 `ramp_drive/config.py` 的**常量**是 `0.5/0.7/0.7/0.3`,
**同一文件上方注释**又写着 `0.20/0.25/0.45/0.18`。
三处不一致 → 结论是**不要照抄速度值**,必须实车标定。本仓已按底盘限幅 0.5 重新标定
为 `0.20/0.28/0.40/0.15`,并在 `validate()` 里把"任一段超过 0.5"变成启动期错误。
---
## 9. 当前状态
| 项 | 状态 |
|---|---|
| 编译 | `colcon build` 通过:8 个包全部 finished(`--parallel-workers 1` + `MAKEFLAGS=-j2`) |
| 单测 | **98 项全绿**(PID 29 / move 8 / orient 8 / ramp 23 / 行为树 30),**未 source ROS 也能跑** |
| launch | 8 个 launch 的 `--show-args` 正常;`localization` 缺 `map:=` 时给出可执行报错 |
| Nav2 栈 | 实起验证:6 个节点全部 `active`,日志末行 `Managed nodes are active`(配三条静态 TF 模拟驱动与 AMCL) |
| 冒烟 | 三个原语节点实起,参数自检通过,日志打出 `限幅=0.45` 与四段速度 `0.20/0.28/0.40/0.15` |
| 实车 | **未上实车**(本轮范围外) |
| 依赖 | `nav2_bringup` / `slam_toolbox` / `nav2_amcl` 已装;`pointcloud_to_laserscan` 用本仓源码;`py_trees` 见 PORTING_NOTES 3.2 |
### 上实车前必须逐项确认
1. `config/frames/sensor_mount.yaml` 的 **`sensor_height_m` = 传感器安装面离地高度**
(现在 0.30 是占位值,不是测量结果)
2. Odin1 是否真的发布 `odom → imu` 的 TF:`ros2 run tf2_ros tf2_echo odom imu`。
**前提是驱动配置 `sendodom: 1`**——那个开关关掉后,TF 发布分支根本不执行
3. `/odin1/scan_low` 与 `/odin1/scan_slam` 的有效点比例(盲区与高度带是否合理)
4. 用 0.5 m 宽实测通道验证 0.81 m 车能否被 NavFn 规划通过
5. 建图后目视检查 pgm 有无重影(里程计漂移直接进地图)
6. 短距动作时确认 Nav2 不会自动触发 backup(已删,但要确认 `behavior_plugins` 生效)
@@ -0,0 +1,46 @@
# d_behavior_tree — 共享叶子节点库 + 示例装配
## 分层方式(照 Rc2026 的组织,接口改成本仓库)
```
流程装配(tree) ← 只写"先做什么、失败了换什么"
├── 组合辅助(composites.py) Sequence / Selector / Retry / Timeout
├── 叶子库(leaves.py) ActionLeaf / ServiceLeaf / WaitLeaf 及具体叶子
└── 状态映射(status.py) goal 状态 → SUCCESS/FAILURE/RUNNING(纯逻辑,可测)
```
规则:**叶子只做一件事**(调一个 Action/Service 并映射状态),决策全部在装配层。
不把 `if 失败了就……` 塞进叶子里——那是行为树存在的意义。
## 三个容易踩的坑(都在单测里锁住了)
1. **被取消的动作不是成功**
`map_goal_status()` 把 `CANCELED` 归为 failure。当成成功放行,树干会带着
"其实没走到位"继续下一步。
2. **`Sequence(memory=True)` 不是"整段只跑一次"**
它只保证 RUNNING 期间不重放已成功的子节点;一旦 FAILURE,下一次 tick
从第一个子节点重来。所以序列里的动作必须**幂等**,或者用 Selector
让失败分支不再被选中。
3. **`Behaviour.tick()` 在 py_trees 2.3+ 是生成器**
必须被消费才会推进状态。统一用 `py_trees.trees.BehaviourTree.tick()`,
2.2 与 2.3+ 行为一致(单测与 demo 都这么写)。
## 叶子节点
| 叶子 | 作用 |
|---|---|
| `Nav2PauseLeaf` / `Nav2ResumeLeaf` | 调 `lifecycle_manager_navigation/manage_nodes`,把 `/cmd_vel` 让给原语 |
| `MoveToLeaf` | 调 `move_to`(车体系定距平移) |
| `OrientToLeaf` | 调 `orient_to`(odom 绝对 yaw) |
| `RampDriveLeaf` | 调 `ramp_drive`(四段曲线直行) |
| `WaitLeaf` | 纯等待 |
所有叶子都带超时(等 server、等结果),没有超时的叶子在赛场上表现为
"卡住不动、日志还在刷 RUNNING"。
## 运行示例
```bash
ros2 run d_behavior_tree bt_demo
ros2 param set /d_bt_demo tick_hz 10.0
```
@@ -0,0 +1,8 @@
"""让 pytest 在未 source ROS 的环境下直接跑源码目录。"""
import os
import sys
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
@@ -0,0 +1 @@
"""方案四的行为树包:共享叶子节点库 + 示例装配。"""
@@ -0,0 +1,96 @@
"""行为树组合辅助。只依赖 py_trees,不依赖 rclpy。
## memory=True 到底保证什么(实测,不是文档推断)
py_trees 的 Sequence(memory=True) **只保证"在本轮 RUNNING 期间不重放已成功的子节点"**。
一旦某个子节点返回 FAILURE,整个 Sequence 结束,下一次 tick 会**从第一个子节点重来**。
这对"暂停 Nav2 → 走一段 → 恢复 Nav2"这种有副作用的序列是个陷阱:
中途失败后下一轮会重新 PAUSE 一次。所以本仓库的约定是:
1. 序列里的每个动作**必须幂等**(重复下发不产生额外物理动作);
2. 整段失败要换策略,就用 `fallback_selector` 把它包进 Selector,
由上层决定放弃而不是原地重试;
3. 确实不能重复的步骤,在叶子里自己加一次性保护(例如 ActionLeaf 已保证
一个 tick 周期内只 send_goal 一次)。
## 为什么重试放在叶子层
Sequence 失败即整段重来;如果想让"某一步"重试,用 `retry()` 装饰器把
重试限制在那一步上,而不是靠整段重放。
"""
import py_trees
def retry(name: str, child: py_trees.behaviour.Behaviour, attempts: int):
"""attempts<=0 表示不包装;attempts=N 表示最多再重试 N 次。"""
if attempts <= 0:
return child
return py_trees.decorators.Retry(name=name, child=child, num_failures=attempts + 1)
def timeout(name: str, child: py_trees.behaviour.Behaviour, seconds: float):
if seconds <= 0.0:
return child
return py_trees.decorators.Timeout(
name=name, child=child, duration=seconds)
def guarded_sequence(name: str, children: list):
"""带记忆的顺序节点。
记忆只作用于 RUNNING 阶段:某子节点返回 RUNNING 时,已成功的不会被重放。
一旦 FAILURE,下一次 tick 从第一个子节点开始 —— 详见模块文档。
"""
return py_trees.composites.Sequence(name=name, memory=True, children=children)
def fallback_selector(name: str, children: list):
"""首选策略失败再换备选;任一成功即成功。"""
return py_trees.composites.Selector(name=name, memory=False, children=children)
def fail_leaf(name: str = '失败'):
"""恒返回 FAILURE 的叶子,用来在收尾之后把失败继续往外传。"""
return py_trees.behaviours.Failure(name=name)
def with_cleanup(name: str, body: list, cleanup: list, fail_node=None):
""""无论成败都要收尾"的包装。
## 解决什么问题
形如 `PauseNav2 → 原语 → ResumeNav2` 的序列,中间任何一步失败,
Resume 都不会执行 → **Nav2 永远停在 PAUSED**。之后所有导航目标都失败,
而日志里只会看到"NavigateToPose 失败",看不出是上一条动作把它挂住了。
参考实现 Rc2026 用 `Nav2LifecycleDecorator`(FAILURE 时仍执行 PAUSE)解决,
这里用纯组合解决,不写异步装饰器:
Selector(
Sequence(body...) ← 正常路径
Sequence(cleanup..., FAIL) ← 失败路径:先收尾,再把失败传出去
)
好处:不需要在装饰器里跑异步 service 调用,语义能用 py_trees 自带节点验证。
## 语义细节
- body 成功 → 返回 SUCCESS,cleanup **不执行**;
- body 失败 → 执行 cleanup;cleanup 成不成功都返回 FAILURE;
- cleanup 为空 → 直接返回 `guarded_sequence(body)`。
## 注意
Selector 不带记忆:本次 tick 失败后,下一次 tick 会从 body 重新开始
(也就是会再 PAUSE 一次)。所以调用方应当在树返回终态后停止 tick,
而不是把它放进一个永远循环的外层。
"""
if not cleanup:
return guarded_sequence(name, body)
tail = list(cleanup) + [fail_node or fail_leaf(f'{name}.失败')]
return fallback_selector(name, [
guarded_sequence(f'{name}.执行', body),
guarded_sequence(f'{name}.收尾', tail),
])
@@ -0,0 +1,111 @@
"""示例流程:把叶子节点装配成一棵树,并提供一个可直接跑的 tick 循环。
这不是赛题流程,而是**装配范式**的示范:
- 有副作用的步骤(写 /cmd_vel)必须包在 `PauseNav2 ... ResumeNav2` 里
- 单步可重试的用 Retry 装饰器,整段策略失败用 Selector 换方案
- 序列用 memory=True(注意它只在 RUNNING 期间生效,见 composites.py)
"""
import math
import time
import py_trees
import rclpy
from rclpy.executors import MultiThreadedExecutor, SingleThreadedExecutor
from rclpy.node import Node
from d_behavior_tree.composites import (
fallback_selector,
guarded_sequence,
retry,
with_cleanup,
)
from d_behavior_tree.leaves import (
MoveToLeaf,
Nav2PauseLeaf,
Nav2ResumeLeaf,
OrientToLeaf,
)
def create_demo_tree(node=None) -> py_trees.behaviour.Behaviour:
"""示意:"往前 30 cm → 左转 90°",失败则改成更保守的 20 cm 再来一次。
两条策略都用 `with_cleanup` 包了一层:中间任何一步失败,
**先恢复 Nav2 再把失败传出去**,避免 Nav2 被永久留在 PAUSED。
"""
def body(tag: str, distance: float):
return [
Nav2PauseLeaf(f'暂停Nav2{tag}', node=node),
retry(f'重试前进{tag}', MoveToLeaf(
f'前进{int(distance * 100)}cm{tag}', distance, 0.0, node=node), attempts=1),
OrientToLeaf(f'左转90度{tag}', math.pi / 2.0, node=node),
Nav2ResumeLeaf(f'恢复Nav2{tag}', node=node),
]
primary = with_cleanup(
'预对准-主策略',
body('', 0.30),
cleanup=[Nav2ResumeLeaf('恢复Nav2-主策略收尾', node=node)],
)
backup = guarded_sequence('预对准-保守策略', [
Nav2PauseLeaf('暂停Nav2(保守)', node=node),
retry('重试前进20cm', MoveToLeaf('前进20cm', 0.20, 0.0, node=node), attempts=2),
Nav2ResumeLeaf('恢复Nav2(保守)', node=node),
])
return fallback_selector('示例任务', [primary, backup])
class BtDemoNode(Node):
def __init__(self):
super().__init__('d_bt_demo')
self.declare_parameter('tick_hz', 10.0)
self.declare_parameter('max_seconds', 120.0)
self._hz = float(self.get_parameter('tick_hz').value)
self._max_seconds = float(self.get_parameter('max_seconds').value)
def run(self) -> bool:
root = create_demo_tree(node=self)
tree = py_trees.trees.BehaviourTree(root=root)
tree.setup(node=self)
self.get_logger().info('\n' + py_trees.display.unicode_tree(root=root))
period = 1.0 / max(self._hz, 1.0)
t0 = time.monotonic()
while rclpy.ok():
tree.tick()
status = tree.root.status
if status == py_trees.common.Status.SUCCESS:
self.get_logger().info('[bt] 示例流程完成')
return True
if status == py_trees.common.Status.FAILURE:
self.get_logger().error('[bt] 示例流程失败')
return False
if time.monotonic() - t0 > self._max_seconds:
self.get_logger().error('[bt] 超时,流程未在限定时间内结束')
return False
time.sleep(period)
return False
def main(args=None):
rclpy.init(args=args)
node = BtDemoNode()
executor = SingleThreadedExecutor()
executor.add_node(node)
try:
node.run()
except KeyboardInterrupt:
pass
finally:
executor.shutdown()
node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,297 @@
"""py_trees 的 ROS 叶子节点库(共享给所有赛题流程)。
设计约定:
1. **叶子只做一件事**:调用一个 Action / Service,把结果映射成 SUCCESS/FAILURE/RUNNING。
决策(先做什么、失败了换什么)全部写在流程装配里,不在叶子里藏 if。
2. **节点由外部注入**:`setup(node=...)` 传 rclpy node,叶子自己不建节点。
这样一个进程可以跑整棵树,也方便在测试里塞假 node。
3. **所有等待都有超时**:等 action server、等结果,全部设上限。
没有超时的叶子在赛场上表现为"卡住不动,日志还在刷 RUNNING"。
"""
import py_trees
from rclpy.action import ActionClient
from d_behavior_tree.status import format_failure_reason, map_goal_status
class RosLeaf(py_trees.behaviour.Behaviour):
"""所有 ROS 叶子的基类:管理 node 注入与黑板。"""
def __init__(self, name: str, node=None):
super().__init__(name)
self._node = node
self.blackboard = py_trees.blackboard.Client(name=name)
def setup(self, **kwargs):
self._node = kwargs.get('node', self._node)
if self._node is None:
raise RuntimeError(f'{self.name}: 未注入 rclpy node')
self._node.get_logger().debug(f'[bt] setup {self.name}')
@property
def node(self):
return self._node
class ActionLeaf(RosLeaf):
"""通用 Action 客户端叶子。
子类只需给出 `action_type` / `default_action_name` 并实现 `build_goal()`,
以及可选的 `result_ok()`(默认只看 goal 状态)。
"""
action_type = None
default_action_name = ''
def __init__(self, name: str, node=None, action_name: str = '',
server_timeout_sec: float = 3.0, result_timeout_sec: float = 30.0):
super().__init__(name, node)
self._action_name = action_name or self.default_action_name
self._server_timeout = server_timeout_sec
self._result_timeout = result_timeout_sec
self._client = None
self._send_future = None
self._goal_handle = None
self._result_future = None
self._start_time = None
self._last_failure = ''
# ---------------------------------------------------------------- 子类钩子
def build_goal(self):
raise NotImplementedError
def result_ok(self, result) -> bool:
return True
# ---------------------------------------------------------------- 生命周期
def setup(self, **kwargs):
super().setup(**kwargs)
self._client = ActionClient(self._node, self.action_type, self._action_name)
def initialise(self):
self._send_future = None
self._goal_handle = None
self._result_future = None
self._last_failure = ''
self._start_time = self._node.get_clock().now()
if not self._client.wait_for_server(timeout_sec=self._server_timeout):
self._last_failure = f'action server {self._action_name} 不在线'
self._goal_handle = None
return
self._send_future = self._client.send_goal_async(self.build_goal())
def update(self):
if self._last_failure:
self.node.get_logger().error(f'[bt] {format_failure_reason(self.name, self._last_failure)}')
return py_trees.common.Status.FAILURE
if self._send_future is None:
return py_trees.common.Status.FAILURE
if not self._send_future.done():
return py_trees.common.Status.RUNNING
if self._goal_handle is None:
self._goal_handle = self._send_future.result()
if self._goal_handle is None or not self._goal_handle.accepted:
self._last_failure = 'goal 被拒绝'
return py_trees.common.Status.FAILURE
self._result_future = self._goal_handle.get_result_async()
if not self._result_future.done():
if self._elapsed_sec() > self._result_timeout:
self._last_failure = f'超过 {self._result_timeout:.1f}s 未返回'
self._goal_handle.cancel_goal_async()
return py_trees.common.Status.FAILURE
return py_trees.common.Status.RUNNING
wrapped = self._result_future.result()
status = map_goal_status(wrapped.status)
if status == 'success' and not self.result_ok(wrapped.result):
self._last_failure = 'goal 状态成功但结果字段 success=False'
return py_trees.common.Status.FAILURE
if status == 'success':
return py_trees.common.Status.SUCCESS
if status == 'running':
return py_trees.common.Status.RUNNING
self._last_failure = f'goal 状态={wrapped.status}'
return py_trees.common.Status.FAILURE
def terminate(self, new_status):
if new_status == py_trees.common.Status.INVALID and self._goal_handle is not None:
self._goal_handle.cancel_goal_async()
def _elapsed_sec(self) -> float:
now = self._node.get_clock().now()
return (now - self._start_time).nanoseconds * 1e-9
class WaitLeaf(RosLeaf):
"""纯等待(给"等底盘稳住"这类场景用)。"""
def __init__(self, name: str = 'Wait', seconds: float = 1.0, node=None):
super().__init__(name, node)
self._seconds = float(seconds)
self._t0 = None
def initialise(self):
self._t0 = self.node.get_clock().now()
def update(self):
elapsed = (self.node.get_clock().now() - self._t0).nanoseconds * 1e-9
if elapsed >= self._seconds:
return py_trees.common.Status.SUCCESS
return py_trees.common.Status.RUNNING
class ServiceLeaf(RosLeaf):
"""通用 Service 调用叶子,用于 Nav2 生命周期暂停/恢复。"""
srv_type = None
default_service_name = ''
def __init__(self, name: str, node=None, service_name: str = '',
server_timeout_sec: float = 3.0, result_timeout_sec: float = 10.0):
super().__init__(name, node)
self._service_name = service_name or self.default_service_name
self._server_timeout = server_timeout_sec
self._result_timeout = result_timeout_sec
self._client = None
self._future = None
self._t0 = None
self._failure = ''
def build_request(self):
raise NotImplementedError
def setup(self, **kwargs):
super().setup(**kwargs)
self._client = self._node.create_client(self.srv_type, self._service_name)
def initialise(self):
self._future = None
self._failure = ''
self._t0 = self.node.get_clock().now()
if not self._client.wait_for_service(timeout_sec=self._server_timeout):
self._failure = f'service {self._service_name} 不在线'
return
self._future = self._client.call_async(self.build_request())
def update(self):
if self._failure:
self.node.get_logger().error(f'[bt] {format_failure_reason(self.name, self._failure)}')
return py_trees.common.Status.FAILURE
if self._future is None:
return py_trees.common.Status.FAILURE
if not self._future.done():
elapsed = (self.node.get_clock().now() - self._t0).nanoseconds * 1e-9
if elapsed > self._result_timeout:
self._failure = 'service 调用超时'
return py_trees.common.Status.FAILURE
return py_trees.common.Status.RUNNING
return py_trees.common.Status.SUCCESS
# --------------------------------------------------------------------- 具体叶子
class Nav2PauseLeaf(ServiceLeaf):
"""暂停 Nav2 生命周期(让出 /cmd_vel 给原语)。"""
default_service_name = '/lifecycle_manager_navigation/manage_nodes'
def __init__(self, name: str = 'PauseNav2', node=None, **kwargs):
from nav2_msgs.srv import ManageLifecycleNodes
self.srv_type = ManageLifecycleNodes
super().__init__(name, node, **kwargs)
self._srv = ManageLifecycleNodes
def build_request(self):
req = self._srv.Request()
req.command = self._srv.Request.PAUSE
return req
class Nav2ResumeLeaf(ServiceLeaf):
"""恢复 Nav2 生命周期。"""
default_service_name = '/lifecycle_manager_navigation/manage_nodes'
def __init__(self, name: str = 'ResumeNav2', node=None, **kwargs):
from nav2_msgs.srv import ManageLifecycleNodes
self.srv_type = ManageLifecycleNodes
super().__init__(name, node, **kwargs)
self._srv = ManageLifecycleNodes
def build_request(self):
req = self._srv.Request()
req.command = self._srv.Request.RESUME
return req
class MoveToLeaf(ActionLeaf):
default_action_name = 'move_to'
def __init__(self, name: str, target_x: float, target_y: float, node=None, **kwargs):
self._tx = float(target_x)
self._ty = float(target_y)
super().__init__(name, node, **kwargs)
def setup(self, **kwargs):
from d_interfaces.action import MoveTo
self.action_type = MoveTo
super().setup(**kwargs)
def build_goal(self):
goal = self.action_type.Goal()
goal.target_x = self._tx
goal.target_y = self._ty
return goal
def result_ok(self, result) -> bool:
return bool(result.success)
class OrientToLeaf(ActionLeaf):
default_action_name = 'orient_to'
def __init__(self, name: str, target_yaw: float, node=None, **kwargs):
self._yaw = float(target_yaw)
super().__init__(name, node, **kwargs)
def setup(self, **kwargs):
from d_interfaces.action import OrientTo
self.action_type = OrientTo
super().setup(**kwargs)
def build_goal(self):
goal = self.action_type.Goal()
goal.target_yaw = self._yaw
return goal
def result_ok(self, result) -> bool:
return bool(result.success)
class RampDriveLeaf(ActionLeaf):
default_action_name = 'ramp_drive'
def __init__(self, name: str, distance_m: float, max_speed: float = 0.4,
node=None, **kwargs):
self._distance = float(distance_m)
self._speed = float(max_speed)
super().__init__(name, node, **kwargs)
def setup(self, **kwargs):
from d_interfaces.action import RampDrive
self.action_type = RampDrive
super().setup(**kwargs)
def build_goal(self):
goal = self.action_type.Goal()
goal.distance_m = self._distance
goal.max_speed = self._speed
return goal
def result_ok(self, result) -> bool:
return bool(result.success)
@@ -0,0 +1,60 @@
"""动作执行结果 → py_trees 状态的映射,以及与 rclpy 无关的小工具。
单独成模块的理由:这是行为树里最容易出**静默逻辑错误**的地方
(比如把 ABORTED 当成 FAILURE 一直重试,或者把 CANCELED 当成 SUCCESS)。
放在无 rclpy 依赖的模块里,就能在未 source ROS 的环境下逐个断言。
"""
class NodeStatus:
"""等价于 action_msgs/msg/GoalStatus 的常量,避免测试时依赖 ROS 消息包。"""
UNKNOWN = 0
ACCEPTED = 1
EXECUTING = 2
CANCELING = 3
SUCCEEDED = 4
CANCELED = 5
ABORTED = 6
def map_goal_status(status_code: int) -> str:
"""把 goal 状态码映射成 'success' / 'failure' / 'running'。
刻意把 CANCELED 归为 failure:被取消的动作绝不能当成"做完了"放行,
否则行为树会在"其实没走到位"的情况下继续下一步。
"""
if status_code == NodeStatus.SUCCEEDED:
return 'success'
if status_code in (NodeStatus.CANCELED, NodeStatus.ABORTED):
return 'failure'
if status_code in (NodeStatus.ACCEPTED, NodeStatus.EXECUTING, NodeStatus.CANCELING):
return 'running'
return 'failure'
def result_flag_success(result) -> bool:
"""Action 自定义结果里的 `success` 字段才是真相。
nav2 的 action 用 goal 状态表达成功,我们自己定义的 Action 额外带
`success` 字段(例如 MoveTo 有 success/final_error)。两者可能不一致:
goal 被 abort 但 success 字段仍为默认 False —— 这里统一按
"status 成功 **且** success 为真"才算成功。
"""
return bool(getattr(result, 'success', False))
def should_retry(status: str, attempt: int, max_attempts: int) -> bool:
"""只有 failure 才重试;running 继续等,success 收工。
max_attempts <= 0 表示不重试。
"""
if status != 'failure':
return False
if max_attempts <= 0:
return False
return attempt < max_attempts
def format_failure_reason(action_name: str, reason: str) -> str:
return f'{action_name} 失败:{reason}'
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>d_behavior_tree</name>
<version>0.1.0</version>
<description>方案四:py_trees 共享叶子节点库与示例流程。</description>
<maintainer email="[email protected]">RC2027 BR</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_python</buildtool_depend>
<exec_depend>rclpy</exec_depend>
<exec_depend>py_trees</exec_depend>
<exec_depend>nav2_msgs</exec_depend>
<exec_depend>d_interfaces</exec_depend>
<exec_depend>d_pid_core</exec_depend>
<test_depend>python3-pytest</test_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
@@ -0,0 +1 @@
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/d_behavior_tree
[install]
install_scripts=$base/lib/d_behavior_tree
@@ -0,0 +1,26 @@
from setuptools import setup
package_name = 'd_behavior_tree'
setup(
name=package_name,
version='0.1.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml', 'README.md']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='RC2027 BR',
maintainer_email='[email protected]',
description='py_trees 共享叶子节点库与示例流程',
license='Apache-2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'bt_demo = d_behavior_tree.demo_tree:main',
],
},
)
@@ -0,0 +1,238 @@
"""组合节点语义单测(只用 py_trees,不碰 ROS)。
守住的其实是三条容易被"想当然"的语义:
1. memory=True 的 Sequence 失败后不重放已成功的步骤
2. Selector 首选失败会自动换备选
3. Retry 装饰器的次数语义是"可重试次数"而不是"总次数"
统一用 `py_trees.trees.BehaviourTree` 驱动而不是直接调 `root.tick()`:
py_trees 2.2 与 2.3+ 的 `Behaviour.tick()` 返回语义不同(2.3+ 是生成器,
必须被消费掉才会推进状态),BehaviourTree.tick() 两版行为一致。
"""
import py_trees
import pytest
from d_behavior_tree.composites import (
fallback_selector,
guarded_sequence,
retry,
timeout,
with_cleanup,
)
Status = py_trees.common.Status
class Scripted(py_trees.behaviour.Behaviour):
"""按预设序列返回状态,并记录被 tick 的次数。"""
def __init__(self, name, script):
super().__init__(name)
self.script = list(script)
self.calls = 0
def update(self):
self.calls += 1
if self.calls <= len(self.script):
return self.script[self.calls - 1]
return self.script[-1]
def make_tree(root):
tree = py_trees.trees.BehaviourTree(root)
tree.setup()
return tree
def test_guarded_sequence_stops_on_failure():
a = Scripted('a', [Status.SUCCESS])
b = Scripted('b', [Status.FAILURE])
root = guarded_sequence('seq', [a, b])
make_tree(root).tick()
assert root.status == Status.FAILURE
assert b.calls == 1
def test_guarded_sequence_does_not_replay_succeeded_child_while_running():
"""RUNNING 期间:已成功的子节点不会被重放(这才是 memory=True 的用途)。"""
a = Scripted('a', [Status.SUCCESS])
b = Scripted('b', [Status.RUNNING, Status.SUCCESS])
root = guarded_sequence('seq', [a, b])
tree = make_tree(root)
tree.tick() # a 成功,b 还在跑
tree.tick() # 记忆:直接从 b 继续,不该再 tick a
assert a.calls == 1
assert b.calls == 2
assert root.status == Status.SUCCESS
def test_guarded_sequence_restarts_from_first_child_after_failure():
"""FAILURE 之后整段从头重来——这是 py_trees 的实际语义,必须显式锁住。
陷阱:序列里有副作用(暂停 Nav2、下发位移)时,重放会重复执行。
对策见 d_behavior_tree/composites.py 模块文档与 README。
"""
a = Scripted('a', [Status.SUCCESS])
b = Scripted('b', [Status.FAILURE, Status.SUCCESS])
root = guarded_sequence('seq', [a, b])
tree = make_tree(root)
tree.tick()
assert root.status == Status.FAILURE
tree.tick()
assert a.calls == 2 # a 被重放了
assert root.status == Status.SUCCESS
def test_guarded_sequence_waits_on_running():
a = Scripted('a', [Status.RUNNING, Status.SUCCESS])
b = Scripted('b', [Status.SUCCESS])
root = guarded_sequence('seq', [a, b])
tree = make_tree(root)
tree.tick()
assert root.status == Status.RUNNING
assert b.calls == 0
tree.tick()
assert root.status == Status.SUCCESS
def test_fallback_selector_tries_backup():
first = Scripted('first', [Status.FAILURE])
backup = Scripted('backup', [Status.SUCCESS])
root = fallback_selector('sel', [first, backup])
make_tree(root).tick()
assert root.status == Status.SUCCESS
assert first.calls == 1
assert backup.calls == 1
def test_fallback_selector_fails_when_all_fail():
first = Scripted('first', [Status.FAILURE])
backup = Scripted('backup', [Status.FAILURE])
root = fallback_selector('sel', [first, backup])
make_tree(root).tick()
assert root.status == Status.FAILURE
def test_retry_allows_extra_attempts():
child = Scripted('c', [Status.FAILURE, Status.FAILURE, Status.SUCCESS])
root = retry('r', child, attempts=2)
tree = make_tree(root)
for _ in range(3):
tree.tick()
assert root.status == Status.SUCCESS
assert child.calls == 3
def test_retry_exhausts_and_fails():
child = Scripted('c', [Status.FAILURE])
root = retry('r', child, attempts=1)
tree = make_tree(root)
tree.tick()
tree.tick()
assert root.status == Status.FAILURE
assert child.calls == 2
def test_retry_zero_returns_child_unchanged():
child = Scripted('c', [Status.SUCCESS])
assert retry('r', child, attempts=0) is child
def test_timeout_zero_returns_child_unchanged():
child = Scripted('c', [Status.SUCCESS])
assert timeout('t', child, seconds=0.0) is child
def test_sequence_runs_children_in_order():
order = []
class Recorder(py_trees.behaviour.Behaviour):
def __init__(self, name, result):
super().__init__(name)
self.result = result
def update(self):
order.append(self.name)
return self.result
root = guarded_sequence('seq', [
Recorder('one', Status.SUCCESS),
Recorder('two', Status.SUCCESS),
Recorder('three', Status.SUCCESS),
])
make_tree(root).tick()
assert order == ['one', 'two', 'three']
assert root.status == Status.SUCCESS
# ---------------------------------------------------------------- 收尾语义
def test_cleanup_runs_only_on_failure():
body = Scripted('body', [Status.SUCCESS])
cleanup = Scripted('cleanup', [Status.SUCCESS])
root = with_cleanup('task', [body], [cleanup])
make_tree(root).tick()
assert root.status == Status.SUCCESS
assert body.calls == 1
assert cleanup.calls == 0
def test_cleanup_runs_when_body_fails():
"""核心场景:暂停 Nav2 → 原语失败 → 必须先恢复 Nav2 再把失败传出去。"""
body = Scripted('body', [Status.FAILURE])
cleanup = Scripted('cleanup', [Status.SUCCESS])
root = with_cleanup('task', [body], [cleanup])
make_tree(root).tick()
assert cleanup.calls == 1
assert root.status == Status.FAILURE
def test_cleanup_failure_still_reports_failure():
body = Scripted('body', [Status.FAILURE])
cleanup = Scripted('cleanup', [Status.FAILURE])
root = with_cleanup('task', [body], [cleanup])
make_tree(root).tick()
assert cleanup.calls == 1
assert root.status == Status.FAILURE
def test_cleanup_order_is_cleanup_then_failure():
order = []
class Rec(py_trees.behaviour.Behaviour):
def __init__(self, name, result):
super().__init__(name)
self.result = result
def update(self):
order.append(self.name)
return self.result
root = with_cleanup(
'task',
[Rec('body', Status.FAILURE)],
[Rec('resume_nav2', Status.SUCCESS)],
)
make_tree(root).tick()
assert order == ['body', 'resume_nav2']
def test_no_cleanup_keeps_plain_sequence():
body = Scripted('body', [Status.FAILURE])
root = with_cleanup('task', [body], [])
assert isinstance(root, py_trees.composites.Sequence)
make_tree(root).tick()
assert root.status == Status.FAILURE
def test_cleanup_runs_after_partial_body_success():
"""body 前半成功、后半失败时,收尾仍要执行(这正是 Pause 之后失败的情形)。"""
first = Scripted('pause_nav2', [Status.SUCCESS])
second = Scripted('move_to', [Status.FAILURE])
cleanup = Scripted('resume_nav2', [Status.SUCCESS])
root = with_cleanup('task', [first, second], [cleanup])
make_tree(root).tick()
assert first.calls == 1
assert second.calls == 1
assert cleanup.calls == 1
assert root.status == Status.FAILURE
@@ -0,0 +1,67 @@
"""goal 状态映射单测:行为树里最容易出静默错误的一处。"""
import pytest
from d_behavior_tree.status import (
NodeStatus,
format_failure_reason,
map_goal_status,
result_flag_success,
should_retry,
)
def test_success_maps_to_success():
assert map_goal_status(NodeStatus.SUCCEEDED) == 'success'
@pytest.mark.parametrize('code', [NodeStatus.CANCELED, NodeStatus.ABORTED])
def test_canceled_and_aborted_are_failures(code):
"""被取消绝不能当成功放行,否则树干会带着"其实没走到位"继续。"""
assert map_goal_status(code) == 'failure'
@pytest.mark.parametrize('code', [NodeStatus.ACCEPTED, NodeStatus.EXECUTING, NodeStatus.CANCELING])
def test_in_flight_is_running(code):
assert map_goal_status(code) == 'running'
def test_unknown_is_failure():
assert map_goal_status(NodeStatus.UNKNOWN) == 'failure'
assert map_goal_status(999) == 'failure'
class _Res:
def __init__(self, success):
self.success = success
def test_result_flag_reads_success_field():
assert result_flag_success(_Res(True)) is True
assert result_flag_success(_Res(False)) is False
def test_result_flag_handles_missing_field():
class _NoField:
pass
assert result_flag_success(_NoField()) is False
def test_retry_only_on_failure():
assert should_retry('failure', attempt=0, max_attempts=2)
assert not should_retry('success', attempt=0, max_attempts=2)
assert not should_retry('running', attempt=0, max_attempts=2)
def test_retry_respects_budget():
assert not should_retry('failure', attempt=2, max_attempts=2)
assert should_retry('failure', attempt=1, max_attempts=2)
def test_retry_disabled_when_zero():
assert not should_retry('failure', attempt=0, max_attempts=0)
def test_failure_reason_format():
assert format_failure_reason('前进30cm', '超时') == '前进30cm 失败:超时'
+47
View File
@@ -0,0 +1,47 @@
# d_bringup — 方案四的 launch 与参数
## 启动
```bash
# 建图:跑一圈,然后存盘
ros2 launch d_bringup bringup.launch.py mode:=mapping
ros2 run nav2_map_server map_saver_cli -f my_map
# 定位 + 导航:先验地图
ros2 launch d_bringup bringup.launch.py mode:=localization map:=$PWD/my_map.yaml
```
## 文件
| 文件 | 作用 |
|---|---|
| `launch/bringup.launch.py` | 总入口,`mode:=mapping\|localization` |
| `launch/scan.launch.py` | 点云 → 2D 扫描(`profile:=dual\|single`) |
| `launch/tf.launch.py` | 静态 TF `imu → base_link`(外参从 yaml 读) |
| `launch/slam.launch.py` | slam_toolbox 建图 + map_saver |
| `launch/localization.launch.py` | map_server + AMCL(`map:=` 必填) |
| `launch/nav2.launch.py` | Nav2 导航栈 |
| `launch/primitives.launch.py` | 三个 Action 原语 |
| `launch/bt_demo.launch.py` | 行为树示例流程 |
| `config/scan/` | 双带 / 单带两套投影参数 |
| `config/frames/sensor_mount.yaml` | 传感器安装外参(**必须现场实测**) |
| `config/slam_toolbox/mapping.yaml` | 建图参数 |
| `config/nav2/navigation.yaml` | Nav2 插件与代价地图 |
| `config/nav2/localization.yaml` | AMCL + map_server |
| `config/primitives/primitives.yaml` | 原语增益与限幅 |
| `maps/` | 先验地图存放处(**不附带示例地图**) |
## 三条硬约定
1. **launch 里没有绝对路径**。全部经 `get_package_share_directory` 解析
(`d_bringup/utils.py`)。Rc2026 的 launch 有 9 处 `/home/inkc/...`,
复制过来不报错、只会静默跑错脚本。
2. **建图与定位不能同时跑**:slam_toolbox 与 AMCL 都想当 `world→odom`
的唯一发布者。
3. **Odin 驱动与底盘桥来自别的工作空间**(`sru_ws` / `minco_ws`),
用"有就起、没有就 LogInfo 警告"的方式处理,不让方案四启动依赖方案 A 的安装状态。
## 与方案 A 的关系
完全独立:不共享包、不共享参数文件、不改 `minco_ws/src/scan` 一行代码。
两套**分别启动,不可同时跑**(都占用 `/cmd_vel` 与 Odin/MID360 硬件)。
@@ -0,0 +1,41 @@
# 方案四 · 传感器安装外参(决定 base_link 与 odom/imu 的关系)
#
# Odin1 驱动自己会发 odom → imu 的 TF(config 里 `send_odom_baselink_tf: 1`,
# 且只有 `sendodom: 1` 时才会走那条发布分支)。
# 本文件补的是 imu → base_link 这一段静态变换。
#
# ┌───────────────────────────────────────────────────────────────────────┐
# │ 为什么 z 拆成两项而不是一个常量: │
# │ 车上的升降机构改变的是**车体框架高度**(Rc2026 是 0–420 mm,轮子始终接地)│
# │ 升降一动,装在框架上的 Odin1 跟着抬,而 base_link 定在地面投影点不动, │
# │ 于是 imu→base_link 的 z 变成"随抬升量变化的量"。 │
# │ │
# │ 只写一个常量 z 的后果: │
# │ - 平地、升降归零时看着没问题; │
# │ - 一旦抬升,高度带(0.08–0.45 m)整体上移同样高度 → 16 cm 的箱子从 │
# │ 视野里消失,地面开始被当成障碍; │
# │ - 症状是"抬起来以后避障忽然变差",且完全不报错。 │
# │ │
# │ 所以拆成 sensor_height_m(静态安装高度)+ lift_offset_m(当前抬升量)。 │
# │ 抬升机构未装时 lift_offset_m 恒为 0;到位后由 lift 节点在运行时改写这条 │
# │ 静态 TF(或改用动态 TF),**不要再退回单一常量**。 │
# └───────────────────────────────────────────────────────────────────────┘
sensor_mount:
parent_frame: 'imu'
child_frame: 'base_link'
# 车体 0.81(长)×0.80(宽);Odin1 装在几何中心正上方时 x/y 为 0
x: 0.0
y: 0.0
# 传感器安装面到地面的垂直距离(m)——必须现场实测,0.30 只是占位值
sensor_height_m: 0.30
# 当前抬升量(m);抬升机构未装,恒为 0
lift_offset_m: 0.0
roll: 0.0
pitch: 0.0
yaw: 0.0
# 最终 imu→base_link 平移 = (x, y, -(sensor_height_m + lift_offset_m))
# z 取负是为了让 base_link 落在地面投影点,这样高度带参数就等于"离地高度"。
@@ -0,0 +1,52 @@
<!--
方案四 · Nav2 导航行为树(删减版)
与 Nav2 默认 navigate_to_pose_w_replanning_and_recovery.xml 的差异,
只有一处但很关键:**删掉 Spin / Wait / BackUp 三个恢复动作**。
为什么删(照参考实现 Rc2026 的 navigate_to_pose_fast_recovery.xml 的做法):
1. `Spin` 与 `BackUp` 都会往 /cmd_vel 写速度,而方案四的行为树里
MoveTo / OrientTo / RampDrive 也写同一个话题。一旦 MPPI 判定卡住
触发 backup,行为树可能正在跑 OrientTo —— 两个发布者互相覆盖,
表现是车在原地抽搐,日志两边都正常。
2. 全向底盘不需要"倒车让位":NavFn + Omni MPPI 本来就能横移脱困,
Backup 反而是最差的一种逃离方式。
3. 这三个动作在窄道里会把车推出通道,比原地不动更糟。
保留的恢复手段:清代价地图(局部 + 全局)+ 重规划。
剩下的"真的卡死了"交给上层:行为树报 FAILURE → RetrySupervisor 之类的外层
决定重试还是放弃,而不是让 Nav2 自己瞎动。
⚠️ 本文件路径由 launch 在运行时注入(config/nav2/navigation.yaml 里不写死),
见 launch/nav2.launch.py 的 RewrittenYaml。
-->
<root main_tree_to_execute="MainTree">
<BehaviorTree ID="MainTree">
<RecoveryNode number_of_retries="2" name="NavigateRecovery">
<PipelineSequence name="NavigateWithReplanning">
<RateController hz="1.0">
<RecoveryNode number_of_retries="1" name="ComputePathToPose">
<ComputePathToPose goal="{goal}" path="{path}" planner_id="GridBased"/>
<ClearEntireCostmap name="ClearGlobalCostmap-Context"
service_name="global_costmap/clear_entirely_global_costmap"/>
</RecoveryNode>
</RateController>
<RecoveryNode number_of_retries="1" name="FollowPath">
<FollowPath path="{path}" controller_id="FollowPath"/>
<ClearEntireCostmap name="ClearLocalCostmap-Context"
service_name="local_costmap/clear_entirely_local_costmap"/>
</RecoveryNode>
</PipelineSequence>
<ReactiveFallback name="RecoveryFallback">
<GoalUpdated/>
<Sequence name="ClearingActions">
<ClearEntireCostmap name="ClearLocalCostmap-Subtree"
service_name="local_costmap/clear_entirely_local_costmap"/>
<ClearEntireCostmap name="ClearGlobalCostmap-Subtree"
service_name="global_costmap/clear_entirely_global_costmap"/>
</Sequence>
</ReactiveFallback>
</RecoveryNode>
</BehaviorTree>
</root>
@@ -0,0 +1,64 @@
# 方案四 · 定位参数(先验地图 + AMCL)
#
# 只在定位模式启动:map_server 载入先验地图,AMCL 在图上做蒙特卡洛定位,
# 发 world → odom 的变换。此时**不能**同时跑 slam_toolbox,两者都想当
# world→odom 的唯一发布者。
#
# 与建图模式的分工:
# 建图:slam_toolbox(mapping) + 高带扫描 → 产出 map.yaml/map.pgm
# 定位:map_server + AMCL + 高带扫描 → 消费那张地图
amcl:
ros__parameters:
use_sim_time: false
alpha1: 0.2
alpha2: 0.2
alpha3: 0.2
alpha4: 0.2
alpha5: 0.2
# 麦轮全向底盘:必须用 OmnidirectionalMotionModel,
# 用默认的差分模型会把横移当成"噪声",粒子云在横移时发散。
base_frame_id: base_link
beam_skip_distance: 0.5
beam_skip_error_threshold: 0.9
beam_skip_threshold: 0.3
do_beamskip: false
global_frame_id: world
lambda_short: 0.1
laser_likelihood_max_dist: 2.0
laser_max_range: 10.0
laser_min_range: 0.55
laser_model_type: "likelihood_field"
max_beams: 90
max_particles: 2000
min_particles: 500
odom_frame_id: odom
pf_err: 0.05
pf_z: 0.99
recovery_alpha_fast: 0.0
recovery_alpha_slow: 0.0
resample_interval: 1
robot_model_type: "nav2_amcl::OmnidirectionalMotionModel"
save_pose_rate: 0.5
sigma_hit: 0.2
tf_broadcast: true
transform_tolerance: 0.5
# 0.10 m / 0.10 rad:场地不大,更新太频繁只会让粒子云更抖
update_min_a: 0.10
update_min_d: 0.10
z_hit: 0.5
z_max: 0.05
z_rand: 0.5
z_short: 0.05
scan_topic: /odin1/scan_slam
# 初始位姿不在这里写死:先验地图的原点取决于建图时的起点,
# 由现场用 RViz 的 "2D Pose Estimate" 或 /initialpose 指定。
set_initial_pose: false
always_reset_initial_pose: false
first_map_only: false
map_server:
ros__parameters:
use_sim_time: false
topic_name: map
# yaml_filename 由 launch 的 map:= 参数注入,见 launch/localization.launch.py
yaml_filename: ""
@@ -0,0 +1,289 @@
# 方案四 · Nav2 导航参数(navigation 侧:规划 / 控制 / 恢复 / 行为树)
#
# 插件选型照 Rc2026 `config/challenge1/nav2/v2/nav2v2.yaml`:
# NavFn 全局规划 + MPPI 控制 + SimpleSmoother 平滑 + Simple*Checker
# **参数值全部按 RC2027 重调**,两处关键改动:
# 1) footprint 0.5×0.5 正方 → 0.81×0.80 实车(半长 0.405 / 半宽 0.400)
# 2) 速度 1.5/1.5/3.0 → 0.45/0.45/0.45
# 底盘桥限幅 0.5 且**静默截断**:Nav2 给 1.5 时车只会走 0.5,
# MPPI 以为自己在按 1.5 规划,跟踪误差会持续累积,表现为"贴不住路径、冲过头"。
# 留 10% 余量取 0.45,避免长期顶在限幅上。
#
# ⚠️ 定位侧(AMCL / map_server)在 config/nav2/localization.yaml,
# 建图侧在 config/slam_toolbox/mapping.yaml。三者不要混在一份文件里。
bt_navigator:
ros__parameters:
global_frame: world
robot_base_frame: base_link
odom_topic: /odin1/odometry
bt_loop_duration: 10
default_server_timeout: 20
# 用本仓的删减版行为树(去掉 Spin/Wait/BackUp,只留清代价地图),
# 理由见 config/nav2/bt_nav_to_pose.xml 文件头。
# 下面两项是**占位值**,launch 会用 RewrittenYaml 替换成安装目录下的真实路径。
# 这样做的原因:写死路径换机后不报错,bt_navigator 会静默退回默认树,
# 于是 Spin/BackUp 又回来了,而你收不到任何提示。
# ⚠️ 绕过本仓 launch 直接起 nav2_bringup 时,这两项必须自己填,否则行为树为空。
default_nav_to_pose_bt_xml: ""
default_nav_through_poses_bt_xml: ""
controller_server:
ros__parameters:
# ⚠️ 必须满足 1/controller_frequency <= FollowPath.model_dt,否则 controller_server
# 启动即报 "Controller period more then model dt" 并卡在 unconfigured。
# 20 Hz → 0.05 s == model_dt 0.05,与参考实现一致。
# 若实车 CPU 扛不住(MPPI 400 batch × 56 steps),**改 model_dt 到 0.0667 再降到 15 Hz**,
# 不要只改频率——那会再次触发同一个报错。
controller_frequency: 20.0
min_x_velocity_threshold: 0.001
# 麦轮用 Omni 模型,横向速度必须原样透传:
# 上游默认值 0.5 会把所有 |vy| < 0.5 的横移指令抹成 0,
# 表现是"规划出横移但车只会前后走"。
min_y_velocity_threshold: 0.001
min_theta_velocity_threshold: 0.001
failure_tolerance: 0.3
progress_checker_plugin: "progress_checker"
goal_checker_plugins: ["goal_checker"]
controller_plugins: ["FollowPath"]
progress_checker:
plugin: "nav2_controller::SimpleProgressChecker"
# 0.3 m / 10 s:车速 0.45 时 0.67 s 就能走完,10 s 是给窄道蠕行留的余量
required_movement_radius: 0.30
movement_time_allowance: 10.0
goal_checker:
plugin: "nav2_controller::SimpleGoalChecker"
# Nav2 只负责"送到附近",厘米级对准交给 MoveTo 原语(容差 2 cm)
xy_goal_tolerance: 0.10
yaw_goal_tolerance: 0.15
stateful: true
FollowPath:
plugin: "nav2_mppi_controller::MPPIController"
time_steps: 56
model_dt: 0.05
batch_size: 400
iteration_count: 2
prune_distance: 1.5
transform_tolerance: 0.5
temperature: 0.3
gamma: 0.015
motion_model: "Omni"
retry_attempt_limit: 3
reset_period: 10.0
regenerate_noises: false
visualize: false
# 速度上限 = 底盘限幅 0.5 × 0.9
vx_max: 0.45
vx_min: -0.45
vy_max: 0.45
vy_min: -0.45
wz_max: 0.45
wz_min: -0.45
vx_std: 0.10
vy_std: 0.10
wz_std: 0.20
TrajectoryVisualizer:
trajectory_step: 5
time_step: 3
critics: ["ConstraintCritic", "CostCritic", "GoalCritic", "GoalAngleCritic",
"PathAlignCritic", "PathFollowCritic", "PathAngleCritic",
"PreferForwardCritic"]
ConstraintCritic:
enabled: true
cost_power: 1
cost_weight: 4.0
CostCritic:
enabled: true
cost_power: 1
cost_weight: 3.81
critical_cost: 300.0
consider_footprint: true
collision_cost: 1000000.0
near_goal_distance: 0.5
GoalCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 1.4
GoalAngleCritic:
enabled: true
cost_power: 1
cost_weight: 3.0
threshold_to_consider: 0.5
PathAlignCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
max_path_occupancy_ratio: 0.07
trajectory_point_step: 4
threshold_to_consider: 0.5
offset_from_furthest: 20
use_path_orientations: false
PathFollowCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
offset_from_furthest: 6
threshold_to_consider: 1.4
PathAngleCritic:
enabled: true
cost_power: 1
cost_weight: 2.0
offset_from_furthest: 4
threshold_to_consider: 0.5
max_angle_to_furthest: 1.2
forward_preference: true
PreferForwardCritic:
enabled: true
cost_power: 1
cost_weight: 5.0
threshold_to_consider: 0.5
local_costmap:
local_costmap:
ros__parameters:
update_frequency: 20.0
publish_frequency: 5.0
global_frame: odom
robot_base_frame: base_link
rolling_window: true
# ⚠️ width / height 必须写**整数**:Nav2 把这两项声明成 int 参数,
# 写成 5.0 会让 controller_server 启动时抛 InvalidParameterTypeException 直接崩,
# 报错长这样:parameter 'height' has invalid type: parameter {height} is of type
# {integer}, setting it to {double} is not allowed.
width: 5
height: 5
resolution: 0.05
footprint: "[[0.405, 0.400], [0.405, -0.400], [-0.405, -0.400], [-0.405, 0.400]]"
footprint_padding: 0.03
plugins: ["obstacle_layer", "inflation_layer"]
obstacle_layer:
plugin: "nav2_costmap_2d::ObstacleLayer"
enabled: true
observation_sources: scan_low
scan_low:
topic: /odin1/scan_low
max_obstacle_height: 0.6
clearing: true
marking: true
data_type: "LaserScan"
raytrace_max_range: 6.0
raytrace_min_range: 0.0
obstacle_max_range: 5.5
obstacle_min_range: 0.0
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.65
always_send_full_costmap: false
global_costmap:
global_costmap:
ros__parameters:
update_frequency: 2.0
publish_frequency: 1.0
global_frame: world
robot_base_frame: base_link
track_unknown_space: true
resolution: 0.05
footprint: "[[0.405, 0.400], [0.405, -0.400], [-0.405, -0.400], [-0.405, 0.400]]"
footprint_padding: 0.01
plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
static_layer:
plugin: "nav2_costmap_2d::StaticLayer"
map_subscribe_transient_local: true
transform_tolerance: 0.5
obstacle_layer:
plugin: "nav2_costmap_2d::ObstacleLayer"
enabled: true
observation_sources: scan_low
scan_low:
topic: /odin1/scan_low
max_obstacle_height: 0.6
clearing: true
marking: true
data_type: "LaserScan"
raytrace_max_range: 6.0
raytrace_min_range: 0.0
obstacle_max_range: 5.5
obstacle_min_range: 0.0
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.65
map_saver:
ros__parameters:
save_map_timeout: 5.0
free_thresh_default: 0.25
occupied_thresh_default: 0.65
map_subscribe_transient_local: true
planner_server:
ros__parameters:
expected_planner_frequency: 5.0
planner_plugins: ["GridBased"]
GridBased:
plugin: "nav2_navfn_planner/NavfnPlanner"
tolerance: 0.5
use_astar: true
allow_unknown: true
smoother_server:
ros__parameters:
smoother_plugins: ["simple_smoother"]
simple_smoother:
plugin: "nav2_smoother::SimpleSmoother"
tolerance: 1.0e-10
max_its: 1000
do_refinement: true
behavior_server:
ros__parameters:
# 恢复行为都在 odom 系里做,避免 AMCL 跳变把机器人"甩"出去
local_costmap_topic: local_costmap/costmap_raw
global_costmap_topic: global_costmap/costmap_raw
local_footprint_topic: local_costmap/published_footprint
global_footprint_topic: global_costmap/published_footprint
cycle_frequency: 10.0
# ⚠️ 只保留 wait,其余全部下掉,理由:
# spin / backup / drive_on_heading / assisted_teleop 都会往 /cmd_vel 写速度,
# 而方案四的 MoveTo / OrientTo / RampDrive 也写同一个话题,跨节点没有仲裁。
# Nav2 的行为树(config/nav2/bt_nav_to_pose.xml)已经不用它们了,
# 这里同步下掉,避免"某天有人把 BT 换回默认树"时突然复活成抢控制权。
behavior_plugins: ["wait"]
wait:
plugin: "nav2_behaviors/Wait"
global_frame: odom
robot_base_frame: base_link
transform_tolerance: 0.1
simulate_ahead_time: 2.0
robot_state_publisher:
ros__parameters:
use_sim_time: false
waypoint_follower:
ros__parameters:
loop_rate: 20
stop_on_failure: false
waypoint_task_executor_plugin: "wait_at_waypoint"
wait_at_waypoint:
plugin: "nav2_waypoint_follower::WaitAtWaypoint"
enabled: true
waypoint_pause_duration: 200
@@ -0,0 +1,51 @@
# 方案四 · 原语节点参数
#
# 增益与限幅的"为什么"写在对应包的 params.py 里(启动时会自检),
# 这里只做现场可调项的覆盖。改完不用改代码。
move_action_server:
ros__parameters:
odom_topic: /odin1/odometry
cmd_vel_topic: /cmd_vel
action_name: move_to
control_hz: 30.0
# 0.81×0.80 的车,短距位移以稳为主:P 主导,I 只负责压掉残余
kp: 1.6
ki: 0.15
kd: 0.0
output_limit: 0.45 # 底盘限幅 0.5,留 10% 余量
integral_limit: 0.12
deadband: 0.004
min_speed: 0.03 # 低于此速度麦轮不转,必须抬起
position_tolerance: 0.02 # 2 cm
stable_frames: 3
timeout_sec: 20.0
odom_timeout_sec: 0.3
orient_action_server:
ros__parameters:
odom_topic: /odin1/odometry
cmd_vel_topic: /cmd_vel
action_name: orient_to
control_hz: 50.0
kp: 2.2
ki: 0.0
kd: 0.25
output_limit: 0.45
deadband_rad: 0.0087 # 0.5°
min_speed_rad: 0.08
yaw_tolerance: 0.0175 # 1°
stable_frames: 5
timeout_sec: 15.0
odom_timeout_sec: 0.3
d_ramp_drive_server:
ros__parameters:
odom_topic: /odin1/odometry
cmd_vel_topic: /cmd_vel
action_name: ramp_drive
control_hz: 20.0
distance_tolerance: 0.02
timeout_sec: 30.0
odom_timeout_sec: 0.3
slip_drop_m: 0.05
@@ -0,0 +1,54 @@
# 方案四 · 2D 投影参数(路线 2:单台 Odin1,双高度带)
#
# 一个节点实例、两份点云切片(enable_second_scan=true),两个消费者:
# 低带 → /odin1/scan_low → Nav2 obstacle_layer(避障)
# 高带 → /odin1/scan_slam → slam_toolbox / AMCL(定位与建图)
#
# 为什么不把两带都塞进 costmap:低带里的桌椅腿、地面杂波会让静态地图长毛,
# 高带又看不见矮障碍。分开喂,污染问题就不存在了。
#
# ⚠️ 高度带的参考系是 base_link,而 base_link 已定义在**地面投影点**,
# 所以这里的 min_height / max_height 直接就是"离地高度"。
#
# ⚠️ 已知限制(见 docs/SOLUTION_D.md 第八节):本节点没有自车裁剪,
# range_min 必须盖住车体外接圆(0.81×0.80 → 0.569 m),否则会扫到自己的车体,
# 在 costmap 里长出一圈假障碍。代价是 0.6 m 内完全看不见。
pointcloud_to_laserscan:
ros__parameters:
target_frame: base_link
filter_frame: base_link
transform_tolerance: 0.05
input_queue_size: 5
cloud_in_topic: '/odin1/cloud_slam'
cloud_in_reliable: true
# ---------------- 第一路:低带,喂 obstacle_layer ----------------
min_height: 0.08 # 高于地面起伏/深度噪声;0.0 会放进地面点(比较是闭区间)
max_height: 0.45 # 覆盖 16 cm 箱到腰部障碍;再高会把桌面当障碍
angle_min: -3.14159
angle_max: 3.14159
angle_increment: 0.0043 # ≈0.25°
scan_time: 0.1
range_min: 0.60 # = 车体外接圆 0.569 + 3 cm 裕度,见文件头说明
range_max: 6.0 # 低带远距点稀且噪声大,不需要看太远
use_inf: true
inf_epsilon: 1.0
scan_out_topic: '/odin1/scan_low'
scan_out_reliable: true
# ---------------- 第二路:高带,喂 slam_toolbox / AMCL ----------------
enable_second_scan: true
scan_out_topic2: '/odin1/scan_slam'
target_frame2: base_link
min_height2: 0.30 # 避开地面杂波与低矮家具,取墙面特征最丰富的区间
max_height2: 1.20
angle_min2: -3.14159
angle_max2: 3.14159
angle_increment2: 0.0087 # ≈0.5°,SLAM 不需要那么细
scan_time2: 0.1
range_min2: 0.55
range_max2: 10.0
use_inf2: true
inf_epsilon2: 1.0
scan_out2_reliable: true
@@ -0,0 +1,32 @@
# 方案四 · 2D 投影参数(路线 1:单台 Odin1,单高度带)
#
# 只做一件事:把 0.08–0.45 m 的点云压成一条 /odin1/scan,同时喂 SLAM 与 costmap。
# 用于现场快速排查"到底是投影的问题还是 SLAM/Nav2 的问题":
# 单带跑得通再切双带,能省掉一半变量。
#
# 代价:SLAM 用的扫描里混着矮障碍与地面杂波,静态地图会长毛;
# 且没有高带的墙面特征,长走廊容易跟丢。
pointcloud_to_laserscan:
ros__parameters:
target_frame: base_link
filter_frame: base_link
transform_tolerance: 0.05
input_queue_size: 5
cloud_in_topic: '/odin1/cloud_slam'
cloud_in_reliable: true
min_height: 0.08
max_height: 0.45
angle_min: -3.14159
angle_max: 3.14159
angle_increment: 0.0043
scan_time: 0.1
range_min: 0.60
range_max: 10.0
use_inf: true
inf_epsilon: 1.0
scan_out_topic: '/odin1/scan'
scan_out_reliable: true
enable_second_scan: false
@@ -0,0 +1,85 @@
# 方案四 · slam_toolbox 建图参数
#
# 用途:只在**建图**时启动(mode: mapping)。定位阶段不跑 slam_toolbox,
# 改用 map_server + AMCL(见 config/nav2/localization.yaml)——
# 两者不能同时发 world→odom,会互相打架。
#
# frame 命名(RC2027 口径):
# world ← 地图系(slam_toolbox 的 map_frame)
# odom ← Odin1 原生的里程计系,保留原名,见 docs/SOLUTION_D.md
# base_link ← 车体中心在地面的投影点
slam_toolbox:
ros__parameters:
solver_plugin: solver_plugins::CeresSolver
ceres_linear_solver: SPARSE_NORMAL_CHOLESKY
ceres_preconditioner: SCHUR_JACOBI
ceres_trust_strategy: LEVENBERG_MARQUARDT
ceres_dogleg_type: TRADITIONAL_DOGLEG
ceres_loss_function: None
odom_frame: odom
map_frame: world
base_frame: base_link
scan_topic: /odin1/scan_slam
use_map_saver: false
mode: mapping
debug_logging: false
throttle_scans: 2
# 0.02 → 50 Hz。低于扫频(10 Hz)时 world→odom 会明显滞后,
# MPPI 在转弯时会拿到过期位姿。
transform_publish_period: 0.02
restamp_tf: true
map_update_interval: 1.0
# 0.05 而不是参考实现的 0.1:0.16 m 的箱在 0.1 m 栅格上只占 1–2 格,
# 膨胀后仍可能被 NavFn 判成"可穿越的缝"。
resolution: 0.05
min_laser_range: 0.55
max_laser_range: 10.0
minimum_time_interval: 0.3
transform_timeout: 0.5
tf_buffer_duration: 30.
stack_size_to_use: 40000000
enable_interactive_mode: false
# ⚠️ 关键取舍:关掉扫描匹配,完全信任 Odin1 的里程计。
# 这是参考实现的选择,好处是建图不会被错误匹配拉歪;
# 代价是**里程计漂移会直接进地图**,长距离回环处会重影。
# 若实测重影严重,把它改成 true 并同时恢复 minimum_travel_distance。
use_scan_matching: false
use_scan_barycenter: false
minimum_travel_distance: 0.0
minimum_travel_heading: 0.0
scan_buffer_size: 30
scan_buffer_maximum_scan_distance: 10.0
link_match_minimum_response_fine: 0.1
link_scan_maximum_distance: 1.0
# 不做回环闭合(参考实现同样关闭)。先验地图靠"人工保证场地不改",
# 而不是靠回环自动纠正。
do_loop_closing: false
loop_search_maximum_distance: 0.0
loop_match_minimum_chain_size: 8
loop_match_maximum_variance_coarse: 3.0
loop_match_minimum_response_coarse: 0.25
loop_match_minimum_response_fine: 0.35
correlation_search_space_dimension: 0.5
correlation_search_space_resolution: 0.01
correlation_search_space_smear_deviation: 0.1
loop_search_space_dimension: 5.0
loop_search_space_resolution: 0.05
loop_search_space_smear_deviation: 0.03
distance_variance_penalty: 0.5
angle_variance_penalty: 1.0
fine_search_angle_offset: 0.00349
coarse_search_angle_offset: 0.349
coarse_angle_resolution: 0.0349
minimum_angle_penalty: 0.9
minimum_distance_penalty: 0.5
use_response_expansion: true
min_pass_through: 2
occupancy_threshold: 0.15
@@ -0,0 +1 @@
"""方案四的 launch 与参数包。"""
@@ -0,0 +1,50 @@
"""launch 公共工具。
这里存在的唯一目的:**任何 launch 文件都不许出现 /home/ 开头的绝对路径**。
Rc2026 的 launch 里有 9 处 `/home/inkc/inkc/Rc2026/...`,复制过来不会报错,
只会静默跑错脚本——这类问题在赛场上表现为"某个节点行为莫名其妙",
排查成本极高。所以路径一律经由 `get_package_share_directory` 解析。
"""
import os
import yaml
from ament_index_python.packages import get_package_share_directory, PackageNotFoundError
PKG = 'd_bringup'
def share_dir(pkg: str = PKG) -> str:
return get_package_share_directory(pkg)
def config_path(*parts: str) -> str:
"""拼出 config/ 下的参数文件绝对路径(由 ament index 解析,不写死)。"""
return os.path.join(share_dir(), 'config', *parts)
def launch_path(filename: str) -> str:
return os.path.join(share_dir(), 'launch', filename)
def map_path(*parts: str) -> str:
return os.path.join(share_dir(), 'maps', *parts)
def load_yaml(path: str) -> dict:
with open(path, 'r', encoding='utf-8') as handle:
return yaml.safe_load(handle) or {}
def has_package(name: str) -> bool:
"""判断另一个工作空间的包是否可用(底盘桥在 minco_ws、Odin 驱动在 sru_ws)。
跨工作空间依赖用"有就起、没有就跳过并警告"的方式处理:
方案四与方案 A 是两个独立的 colcon 工作空间,不应该因为对方案 A 的
安装状态一无所知就启动失败。
"""
try:
get_package_share_directory(name)
return True
except PackageNotFoundError:
return False
@@ -0,0 +1,146 @@
"""方案四总入口。
# 建图(跑一圈,再用 map_saver 存盘)
ros2 launch d_bringup bringup.launch.py mode:=mapping
# 定位 + 导航(先验地图)
ros2 launch d_bringup bringup.launch.py mode:=localization map:=/path/to/my_map.yaml
启动链(与 Rc2026 的 challenge1.launch.py 同构,但去掉绝对路径与赛题节点):
Odin1 驱动 ──点云/里程计──► pointcloud_to_laserscan(双高度带)
├─ /odin1/scan_low ─► Nav2 obstacle_layer
└─ /odin1/scan_slam ─► slam_toolbox 或 AMCL
TF: world ─(slam/AMCL)─► odom ─(Odin)─► imu ─(static)─► base_link
Nav2 ─┐
原语 ─┴─► /cmd_vel ─► 底盘桥(minco_ws)
跨工作空间的包(Odin 驱动在 sru_ws、底盘桥在 minco_ws)用"有就起、没有就警告",
不让方案四的启动依赖方案 A 的安装状态。
"""
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
IncludeLaunchDescription,
LogInfo,
OpaqueFunction,
)
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.substitutions import FindPackageShare
from d_bringup.utils import config_path, has_package, launch_path
def _arg(context, name):
return LaunchConfiguration(name).perform(context)
def _include(launch_file, arguments):
return IncludeLaunchDescription(
PythonLaunchDescriptionSource(launch_file),
launch_arguments=arguments.items(),
)
def _pkg_launch(context, package, *relative):
return PathJoinSubstitution(
[FindPackageShare(package), *relative]).perform(context)
def _launch_setup(context, *args, **kwargs):
mode = _arg(context, 'mode')
map_yaml = _arg(context, 'map')
scan_profile = _arg(context, 'scan_profile')
start_nav2 = _arg(context, 'start_nav2')
start_odin = _arg(context, 'start_odin')
start_chassis = _arg(context, 'start_chassis')
use_sim_time = _arg(context, 'use_sim_time')
if mode not in ('mapping', 'localization'):
raise RuntimeError(f'mode 只能是 mapping 或 localization,收到 {mode!r}')
actions = [LogInfo(
msg=f'[方案四] mode={mode} scan={scan_profile} nav2={start_nav2}')]
# 1) 静态 TF:imu → base_link
actions.append(_include(launch_path('tf.launch.py'), {}))
# 2) 点云 → 2D 扫描
scan_params = 'scan_single.yaml' if scan_profile == 'single' else 'scan_dual.yaml'
actions.append(_include(launch_path('scan.launch.py'), {
'profile': scan_profile,
'scan_params_file': config_path('scan', scan_params),
}))
# 3) 建图 / 定位(二选一,不能同时跑)
if mode == 'mapping':
actions.append(_include(launch_path('slam.launch.py'), {
'use_sim_time': use_sim_time,
}))
else:
if not map_yaml:
raise RuntimeError(
'localization 模式必须传 map:=<先验地图 yaml 路径>;'
'本仓库刻意不附带示例地图')
actions.append(_include(launch_path('localization.launch.py'), {
'map': map_yaml,
'use_sim_time': use_sim_time,
}))
# 4) Nav2:默认只在定位模式起(建图时没有静态地图,全局代价地图起不来)
want_nav2 = start_nav2 == 'true' or (start_nav2 == 'auto' and mode == 'localization')
if want_nav2:
actions.append(_include(launch_path('nav2.launch.py'), {
'use_sim_time': use_sim_time,
}))
else:
actions.append(LogInfo(msg='[方案四] 不启动 Nav2'))
# 5) Action 原语
actions.append(_include(launch_path('primitives.launch.py'), {}))
# 6) Odin1 驱动(sru_ws)——不动它一行代码,只 include 它的 launch
if start_odin == 'true':
if has_package('odin_ros_driver'):
actions.append(_include(
_pkg_launch(context, 'odin_ros_driver', 'launch_ROS2', 'odin1_ros2.launch.py'),
{}))
else:
actions.append(LogInfo(
msg='[方案四] 未找到 odin_ros_driver,跳过驱动;'
'如需启动请先 source sru_ws/install/setup.bash'))
# 7) 底盘桥(minco_ws)——共用的唯一执行接口
if start_chassis == 'true':
if has_package('techx_r2_chassis_control'):
actions.append(_include(
_pkg_launch(context, 'techx_r2_chassis_control', 'launch',
'chassis_serial.launch.py'),
{}))
else:
actions.append(LogInfo(
msg='[方案四] 未找到 techx_r2_chassis_control,跳过底盘桥;'
'如需启动请先 source minco_ws/install/setup.bash'))
return actions
def generate_launch_description():
return LaunchDescription([
DeclareLaunchArgument('mode', default_value='mapping',
description='mapping=建图;localization=先验地图定位导航'),
DeclareLaunchArgument('map', default_value='',
description='localization 模式的先验地图 yaml 路径'),
DeclareLaunchArgument('scan_profile', default_value='dual',
description='dual=双高度带(route 2);single=单带排查用'),
DeclareLaunchArgument('start_nav2', default_value='auto',
description='auto=仅定位模式启动;true/false 强制'),
DeclareLaunchArgument('start_odin', default_value='true',
description='是否 include Odin1 驱动(sru_ws)'),
DeclareLaunchArgument('start_chassis', default_value='false',
description='是否 include 底盘桥(minco_ws);与方案 A 二选一'),
DeclareLaunchArgument('use_sim_time', default_value='false'),
OpaqueFunction(function=_launch_setup),
])
@@ -0,0 +1,27 @@
"""行为树示例流程启动(需要 Nav2 与原语已在跑)。
ros2 launch d_bringup bringup.launch.py mode:=localization map:=...
ros2 launch d_bringup bt_demo.launch.py
"""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription([
DeclareLaunchArgument('tick_hz', default_value='10.0'),
DeclareLaunchArgument('max_seconds', default_value='120.0'),
Node(
package='d_behavior_tree',
executable='bt_demo',
name='d_bt_demo',
output='screen',
parameters=[{
'tick_hz': LaunchConfiguration('tick_hz'),
'max_seconds': LaunchConfiguration('max_seconds'),
}],
),
])
@@ -0,0 +1,65 @@
"""定位模式:map_server 载入先验地图 + AMCL 全局定位。
两件事必须成立,否则起不来(脚本会直接报错而不是静默失败):
1. `map:=` 必须给出**先验地图的 yaml 路径**(本仓刻意不带示例地图,
避免有人拿着别的队的场地地图跑出"定位很好"的错觉);
2. 此刻不能同时跑 slam_toolbox —— 两个节点都想发布 world→odom。
"""
import os
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
IncludeLaunchDescription,
OpaqueFunction,
)
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.substitutions import FindPackageShare
from d_bringup.utils import config_path
def _validate_map(context, *args, **kwargs):
map_yaml = LaunchConfiguration('map').perform(context)
if not map_yaml:
raise RuntimeError(
'定位模式必须传 map:=<先验地图 yaml 的绝对路径>。\n'
' 先建图:ros2 launch d_bringup bringup.launch.py mode:=mapping\n'
' 存地图:ros2 run nav2_map_server map_saver_cli -f my_map\n'
' 再启动:ros2 launch d_bringup bringup.launch.py mode:=localization '
'map:=/path/to/my_map.yaml')
if not os.path.isfile(map_yaml):
raise RuntimeError(f'map 文件不存在:{map_yaml}')
return []
def generate_launch_description():
localization = IncludeLaunchDescription(
PythonLaunchDescriptionSource([
PathJoinSubstitution([
FindPackageShare('nav2_bringup'), 'launch',
'localization_launch.py',
]),
]),
launch_arguments={
'map': LaunchConfiguration('map'),
'use_sim_time': LaunchConfiguration('use_sim_time'),
'params_file': LaunchConfiguration('amcl_params_file'),
'autostart': 'true',
'use_composition': 'False',
}.items(),
)
return LaunchDescription([
DeclareLaunchArgument(
'map', default_value='',
description='先验地图 yaml 的绝对路径(必填)'),
DeclareLaunchArgument('use_sim_time', default_value='false'),
DeclareLaunchArgument(
'amcl_params_file', default_value=config_path('nav2', 'localization.yaml'),
description='AMCL + map_server 参数'),
OpaqueFunction(function=_validate_map),
localization,
])
@@ -0,0 +1,93 @@
"""Nav2 导航栈:planner / controller / smoother / behaviors / bt_navigator。
和上一版的区别:不再 include `nav2_bringup/navigation_launch.py`,而是自己起节点。
唯一原因是**行为树 XML 的路径必须在运行时解析**:
- 写死在 yaml 里 → 换机后静默指向不存在的文件,bt_navigator 退回默认树,
Spin/BackUp 又回来了,而且没有任何报错;
- 在 launch 里用 `get_package_share_directory` 解析 → 永远指向 install 目录。
实现方式刻意选最笨的那种:**参数表按顺序应用、后者胜**。
`parameters=[params_file, {覆盖项}]` 不需要 RewrittenYaml、不需要 nav2_common,
少了两个可能在别的机器上不存在的依赖。
代价:要自己维护 6 个节点的生命周期,`node_names` 必须与下面 `name=` 逐字一致,
否则 lifecycle_manager 配不到节点、栈卡在 unconfigured。
"""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, OpaqueFunction
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
from d_bringup.utils import config_path
# 与下方 Node(name=...) 必须逐字一致;漏一个就是生命周期卡死
LIFECYCLE_NODES = [
'controller_server',
'smoother_server',
'planner_server',
'behavior_server',
'bt_navigator',
'waypoint_follower',
]
def _launch_setup(context, *args, **kwargs):
params_file = LaunchConfiguration('nav2_params_file').perform(context)
use_sim_time = ParameterValue(
LaunchConfiguration('use_sim_time'), value_type=bool)
autostart = LaunchConfiguration('autostart').perform(context)
log_level = LaunchConfiguration('log_level').perform(context)
# 在这里解析,而不是写进 yaml —— 见模块 docstring
bt_xml = config_path('nav2', 'bt_nav_to_pose.xml')
base = [params_file, {'use_sim_time': use_sim_time}]
bt_params = [params_file, {
'use_sim_time': use_sim_time,
'default_nav_to_pose_bt_xml': bt_xml,
'default_nav_through_poses_bt_xml': bt_xml,
}]
def node(package, executable, name, parameters):
return Node(
package=package,
executable=executable,
name=name,
output='screen',
parameters=parameters,
arguments=['--ros-args', '--log-level', log_level],
)
nodes = [
node('nav2_controller', 'controller_server', 'controller_server', base),
node('nav2_smoother', 'smoother_server', 'smoother_server', base),
node('nav2_planner', 'planner_server', 'planner_server', base),
node('nav2_behaviors', 'behavior_server', 'behavior_server', base),
node('nav2_bt_navigator', 'bt_navigator', 'bt_navigator', bt_params),
node('nav2_waypoint_follower', 'waypoint_follower', 'waypoint_follower', base),
Node(
package='nav2_lifecycle_manager',
executable='lifecycle_manager',
name='lifecycle_manager_navigation',
output='screen',
parameters=[{
'autostart': autostart == 'true',
'node_names': LIFECYCLE_NODES,
}],
),
]
return nodes
def generate_launch_description():
return LaunchDescription([
DeclareLaunchArgument('use_sim_time', default_value='false'),
DeclareLaunchArgument(
'nav2_params_file', default_value=config_path('nav2', 'navigation.yaml'),
description='Nav2 插件与代价地图参数'),
DeclareLaunchArgument('autostart', default_value='true'),
DeclareLaunchArgument('log_level', default_value='info'),
OpaqueFunction(function=_launch_setup),
])
@@ -0,0 +1,55 @@
"""三个 Action 原语节点:move_to / orient_to / ramp_drive。
它们与 Nav2 **共用 /cmd_vel**,所以:
- 行为树调用前必须先 PauseNav2(Nav2PauseLeaf)
- 三者不要同时触发;目前没有仲裁层,靠流程约束保证
这不是偷懒:加一个"速度指令仲裁器"会把问题变成"谁赢了",而赛场上的
正确做法是让决策层明确知道自己此刻在用哪个执行器。
"""
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 d_bringup.utils import config_path
def generate_launch_description():
params = LaunchConfiguration('primitives_params_file')
return LaunchDescription([
DeclareLaunchArgument(
'primitives_params_file',
default_value=config_path('primitives', 'primitives.yaml')),
DeclareLaunchArgument('start_move', default_value='true'),
DeclareLaunchArgument('start_orient', default_value='true'),
DeclareLaunchArgument('start_ramp', default_value='true'),
Node(
package='d_move_actions',
executable='move_action_server',
name='move_action_server',
output='screen',
parameters=[params],
condition=IfCondition(LaunchConfiguration('start_move')),
),
Node(
package='d_orient_actions',
executable='orient_action_server',
name='orient_action_server',
output='screen',
parameters=[params],
condition=IfCondition(LaunchConfiguration('start_orient')),
),
Node(
package='d_ramp_drive',
executable='ramp_drive_server',
name='d_ramp_drive_server',
output='screen',
parameters=[params],
condition=IfCondition(LaunchConfiguration('start_ramp')),
),
])
@@ -0,0 +1,51 @@
"""Odin1 点云 → 2D 激光扫描(双高度带或单带)。
两个消费者分离:
低带 0.08–0.45 m → /odin1/scan_low → Nav2 obstacle_layer
高带 0.30–1.20 m → /odin1/scan_slam → slam_toolbox / AMCL
profile:=dual 时一个节点实例出两路扫描(enable_second_scan);
profile:=single 时只出一路 /odin1/scan,用于现场排查变量。
"""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from d_bringup.utils import config_path
def generate_launch_description():
profile = LaunchConfiguration('profile')
cloud_topic = LaunchConfiguration('cloud_topic')
default_params = config_path('scan', 'scan_dual.yaml')
return LaunchDescription([
DeclareLaunchArgument(
'profile', default_value='dual',
description='dual=双高度带(route 2);single=单带(route 1)'),
DeclareLaunchArgument(
'cloud_topic', default_value='/odin1/cloud_slam',
description='Odin1 点云话题'),
DeclareLaunchArgument(
'scan_params_file', default_value=default_params,
description='投影参数文件;profile:=single 时请指向 scan_single.yaml'),
Node(
package='pointcloud_to_laserscan',
executable='pointcloud_to_laserscan_node',
name='pointcloud_to_laserscan',
output='screen',
parameters=[
LaunchConfiguration('scan_params_file'),
{'cloud_in_topic': cloud_topic},
],
remappings=[
# 上游改造版把输入写死在参数里,remap 只在参数缺省时生效;
# 这里保留 remap 是为了兼容未改造的 apt 版本。
('cloud_in', cloud_topic),
],
),
])
@@ -0,0 +1,49 @@
"""建图模式:slam_toolbox(mapping) + 高带扫描 → 产出先验地图。
不启动 Nav2:建图时不需要规划,同时跑只会让 costmap 与地图互相干扰。
建完图后用 map_saver 存盘,再切到 localization.launch.py。
ros2 run nav2_map_server map_saver_cli -f <输出名> --ros-args -p save_map_timeout:=5.0
"""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from d_bringup.utils import config_path
def generate_launch_description():
use_sim_time = LaunchConfiguration('use_sim_time')
params_file = LaunchConfiguration('slam_params_file')
slam_node = Node(
package='slam_toolbox',
executable='async_slam_toolbox_node',
name='slam_toolbox',
output='screen',
parameters=[params_file, {'use_sim_time': use_sim_time}],
)
map_saver_server = Node(
package='nav2_map_server',
executable='map_saver_server',
name='map_saver',
output='screen',
parameters=[{
'save_map_timeout': 5.0,
'free_thresh_default': 0.25,
'occupied_thresh_default': 0.65,
'map_subscribe_transient_local': True,
}],
)
return LaunchDescription([
DeclareLaunchArgument('use_sim_time', default_value='false'),
DeclareLaunchArgument(
'slam_params_file', default_value=config_path('slam_toolbox', 'mapping.yaml'),
description='slam_toolbox 参数(mode 必须是 mapping)'),
slam_node,
map_saver_server,
])
@@ -0,0 +1,99 @@
"""静态 TF:imu → base_link(传感器安装外参)。
TF 树在方案四里是这样接起来的:
world ──(slam_toolbox 或 AMCL)──► odom ──(Odin1 驱动)──► imu ──(本文件)──► base_link
├── /odin1/scan_low
└── /odin1/scan_slam
- `odom → imu` 由 Odin 驱动自己发(config 里 `send_odom_baselink_tf: 1`,
且只在 `sendodom: 1` 时走那条分支),驱动不动一行代码,父帧名沿用驱动发的那个。
- `imu → base_link` 是本文件补的:把原点从传感器挪到**车体中心的地面投影点**。
之所以定在地面:Nav2 的 2D costmap 假设 robot_base_frame 在地面上,
定在地面之后 height band 参数就等价于"离地高度",不用二次换算。
z 不是独立常量,而是 `-(sensor_height_m + lift_offset_m)`:
升降机构改变车体框架高度 → 传感器跟着抬 → 高度带必须同步换算(理由见外参文件注释)。
外参从 config/frames/sensor_mount.yaml 读,launch 参数可逐项覆盖。
"""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, LogInfo, OpaqueFunction
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from d_bringup.utils import config_path, load_yaml
def _launch_setup(context, *args, **kwargs):
mount_file = LaunchConfiguration('mount_file').perform(context)
data = load_yaml(mount_file).get('sensor_mount', {})
def pick(name, override, default=0.0):
if override not in (None, '', 'auto'):
return float(override)
return float(data.get(name, default))
x = pick('x', LaunchConfiguration('x').perform(context))
y = pick('y', LaunchConfiguration('y').perform(context))
roll = pick('roll', LaunchConfiguration('roll').perform(context))
pitch = pick('pitch', LaunchConfiguration('pitch').perform(context))
yaw = pick('yaw', LaunchConfiguration('yaw').perform(context))
# z 不是独立参数,而是由两段高度合成:
# z = -(静态安装高度 + 当前抬升量)
# 取负是因为 base_link 定在地面投影点,而 imu 在传感器处。
# 升降机构改变的是车体框架高度 → 传感器跟着抬 → 高度带必须跟着一起算,
# 否则抬升之后"16cm 箱子看不见、地面变障碍",且不报任何错。
override_z = LaunchConfiguration('z').perform(context)
if override_z not in (None, '', 'auto'):
z = float(override_z)
source = f'launch 覆盖 {z:.3f}'
else:
height = pick('sensor_height_m', 'auto', default=0.0)
lift = pick('lift_offset_m', LaunchConfiguration('lift_offset_m').perform(context),
default=0.0)
z = -(height + lift)
source = (f'sensor_height_m={height:.3f} + lift_offset_m={lift:.3f} '
f'→ z={z:.3f}')
parent = LaunchConfiguration('parent_frame').perform(context) or data.get('parent_frame', 'imu')
child = LaunchConfiguration('child_frame').perform(context) or data.get('child_frame', 'base_link')
node = Node(
package='tf2_ros',
executable='static_transform_publisher',
name='tf_imu_to_base_link',
output='screen',
arguments=[
'--x', str(x), '--y', str(y), '--z', str(z),
'--roll', str(roll), '--pitch', str(pitch), '--yaw', str(yaw),
'--frame-id', parent, '--child-frame-id', child,
],
)
log = LogInfo(msg=(
f'[tf] {parent} → {child}: x={x:.3f} y={y:.3f} z={z:.3f} '
f'({source})'))
return [log, node]
def generate_launch_description():
return LaunchDescription([
DeclareLaunchArgument(
'mount_file', default_value=config_path('frames', 'sensor_mount.yaml'),
description='传感器安装外参文件'),
# 默认 auto = 用 yaml 里的值;显式传数值可临时覆盖,不必改文件
DeclareLaunchArgument('x', default_value='auto'),
DeclareLaunchArgument('y', default_value='auto'),
# z 默认由 sensor_height_m + lift_offset_m 合成,一般不要直接给 z
DeclareLaunchArgument('z', default_value='auto'),
DeclareLaunchArgument('lift_offset_m', default_value='auto',
description='当前抬升量(m),抬升机构未装时保持 0'),
DeclareLaunchArgument('roll', default_value='auto'),
DeclareLaunchArgument('pitch', default_value='auto'),
DeclareLaunchArgument('yaw', default_value='auto'),
DeclareLaunchArgument('parent_frame', default_value=''),
DeclareLaunchArgument('child_frame', default_value=''),
OpaqueFunction(function=_launch_setup),
])
@@ -0,0 +1 @@
@@ -0,0 +1,3 @@
# 先验地图目录
本目录**不附带示例地图**。
+37
View File
@@ -0,0 +1,37 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>d_bringup</name>
<version>0.1.0</version>
<description>方案四启动与参数:Odin1 双高度带 → slam_toolbox/AMCL → Nav2 → 原语 → /cmd_vel。</description>
<maintainer email="[email protected]">RC2027 BR</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_python</buildtool_depend>
<exec_depend>launch</exec_depend>
<exec_depend>launch_ros</exec_depend>
<exec_depend>ament_index_python</exec_depend>
<exec_depend>pointcloud_to_laserscan</exec_depend>
<exec_depend>slam_toolbox</exec_depend>
<exec_depend>nav2_bringup</exec_depend>
<exec_depend>nav2_amcl</exec_depend>
<exec_depend>nav2_map_server</exec_depend>
<exec_depend>nav2_controller</exec_depend>
<exec_depend>nav2_planner</exec_depend>
<exec_depend>nav2_smoother</exec_depend>
<exec_depend>nav2_behaviors</exec_depend>
<exec_depend>nav2_bt_navigator</exec_depend>
<exec_depend>nav2_waypoint_follower</exec_depend>
<exec_depend>nav2_lifecycle_manager</exec_depend>
<exec_depend>d_interfaces</exec_depend>
<exec_depend>d_move_actions</exec_depend>
<exec_depend>d_orient_actions</exec_depend>
<exec_depend>d_ramp_drive</exec_depend>
<exec_depend>d_behavior_tree</exec_depend>
<exec_depend>tf2_ros</exec_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
@@ -0,0 +1 @@
+4
View File
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/d_bringup
[install]
install_scripts=$base/lib/d_bringup
+42
View File
@@ -0,0 +1,42 @@
import os
from glob import glob
from setuptools import setup
package_name = 'd_bringup'
def _tree(root):
entries = []
for path in glob(os.path.join(root, '**', '*'), recursive=True):
if os.path.isdir(path):
continue
rel_dir = os.path.dirname(os.path.relpath(path, root))
target = os.path.join('share', package_name, root, rel_dir) \
if rel_dir else os.path.join('share', package_name, root)
entries.append((target, [path]))
return entries
data_files = [
('share/ament_index/resource_index/packages', ['resource/' + package_name]),
('share/' + package_name, ['package.xml', 'README.md']),
]
data_files += [(os.path.join('share', package_name, 'launch'), glob('launch/*.launch.py'))]
data_files += _tree('config')
data_files += _tree('maps')
setup(
name=package_name,
version='0.1.0',
packages=[package_name],
data_files=data_files,
install_requires=['setuptools'],
zip_safe=True,
maintainer='RC2027 BR',
maintainer_email='[email protected]',
description='方案四的 launch 与参数',
license='Apache-2.0',
tests_require=['pytest'],
entry_points={'console_scripts': []},
)
@@ -0,0 +1,95 @@
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package pointcloud_to_laserscan
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2.0.1 (2021-10-19)
------------------
* Replace deprecated launch api (`#56 <https://github.com/ros-perception/pointcloud_to_laserscan/issues/56>`_)
* Fix linting errors in the code (`#52 <https://github.com/ros-perception/pointcloud_to_laserscan/issues/52>`_)
* Update README.md
* Contributors: Chris Lalancette, Daisuke Nishimatsu, Paul Bovbel
2.0.0 (2020-02-10)
------------------
* ROS 2 Migration (`#33 <https://github.com/ros-perception/pointcloud_to_laserscan/issues/33>`_)
* ROS 2 Migration
Signed-off-by: Michel Hidalgo <[email protected]>
* Contributors: Michel Hidalgo
1.4.1 (2019-08-30)
------------------
* LaserScan to PointCloud node + nodelet (`#28 <https://github.com/ros-perception/pointcloud_to_laserscan/issues/28>`_)
* fix roslint (`#29 <https://github.com/ros-perception/pointcloud_to_laserscan/issues/29>`_)
* Merge pull request `#20 <https://github.com/ros-perception/pointcloud_to_laserscan/issues/20>`_ from ros-perception/range_max_check
Add check for range_max
* Add check for range_max
* Contributors: Paul Bovbel, Rein Appeldoorn
1.4.0 (2017-11-14)
------------------
* Added inf_epsilon parameter that determines the value added to max range when use_infs parameter is set to false
* Merge pull request `#11 <https://github.com/ros-perception/pointcloud_to_laserscan/issues/11>`_ from ros-perception/mikaelarguedas-patch-1
update to use non deprecated pluginlib macro
* Migrate to package format 2; add roslint
* Add sane parameter defaults; fixup lint warnings
* update to use non deprecated pluginlib macro
* Contributors: Mikael Arguedas, Paul Bovbel, Prasanna Kannappan
1.3.1 (2017-04-26)
------------------
* Merge pull request `#4 <https://github.com/ros-perception/pointcloud_to_laserscan/issues/4>`_ from yoshimalucky/fix-miscalculation-in-angle-increment
Fixed miscalculation in angle_increment in the launch files.
* fixed miscalculation in angle_increment in the launchfiles.
* Contributors: Paul Bovbel, yoshimalucky
1.3.0 (2015-06-09)
------------------
* Fix pointcloud to laserscan transform tolerance issues
* Move pointcloud_to_laserscan to new repository
* Contributors: Paul Bovbel
1.2.7 (2015-06-08)
------------------
* Cleanup pointcloud_to_laserscan launch files
* Contributors: Paul Bovbel
1.2.6 (2015-02-04)
------------------
* Fix default value for concurrency
* Fix multithreaded lazy pub sub
* Contributors: Paul Bovbel
1.2.5 (2015-01-20)
------------------
* Switch to tf_sensor_msgs for transform
* Set parameters in sample launch files to default
* Add tolerance parameter
* Contributors: Paul Bovbel
1.2.4 (2015-01-15)
------------------
* Remove stray dependencies
* Refactor with tf2 and message filters
* Remove roslaunch check
* Fix regressions
* Refactor to allow debug messages from node and nodelet
* Contributors: Paul Bovbel
1.2.3 (2015-01-10)
------------------
* add launch tests
* refactor naming and fix nodelet export
* set default target frame to empty
* clean up package.xml
* Contributors: Paul Bovbel
1.2.2 (2014-10-25)
------------------
* clean up package.xml
* Fix header reference
* Fix flow
* Fix pointer assertion
* Finalize pointcloud to laserscan
* Initial pointcloud to laserscan commit
* Contributors: Paul Bovbel
@@ -0,0 +1,34 @@
cmake_minimum_required(VERSION 3.5)
project(pointcloud_to_laserscan)
find_package(ament_cmake_auto REQUIRED)
ament_auto_find_build_dependencies()
ament_auto_add_library(laserscan_to_pointcloud SHARED
src/laserscan_to_pointcloud_node.cpp)
rclcpp_components_register_node(laserscan_to_pointcloud
PLUGIN "pointcloud_to_laserscan::LaserScanToPointCloudNode"
EXECUTABLE laserscan_to_pointcloud_node)
ament_auto_add_library(pointcloud_to_laserscan SHARED
src/pointcloud_to_laserscan_node.cpp)
rclcpp_components_register_node(pointcloud_to_laserscan
PLUGIN "pointcloud_to_laserscan::PointCloudToLaserScanNode"
EXECUTABLE pointcloud_to_laserscan_node)
ament_auto_add_executable(dummy_pointcloud_publisher
src/dummy_pointcloud_publisher.cpp
)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
ament_lint_auto_find_test_dependencies()
endif()
ament_auto_package(
INSTALL_TO_SHARE
launch
config
)
@@ -0,0 +1,12 @@
Copyright (c) 2010-2012, Willow Garage, Inc.
Copyright (c) 2019, Eurotec, Netherlands
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,112 @@
# ROS 2 点云 <-> 激光扫描转换器
本包提供将 `sensor_msgs/msg/PointCloud2` 消息转换为 `sensor_msgs/msg/LaserScan` 消息,以及反向转换的组件。
基于原 ROS 1 包的 ROS 2 移植,并新增支持同时输出两个独立激光扫描的功能(适用于多层高度投影,如 Livox LiDAR)。
## pointcloud_to_laserscan::PointCloudToLaserScanNode
将 `sensor_msgs/msg/PointCloud2` 投影为一个或两个 `sensor_msgs/msg/LaserScan`。
### 发布话题
- `scan_out_topic`(默认 `/scan`,`sensor_msgs/msg/LaserScan`) - 主激光扫描输出。
- `scan_out_topic2`(可选,`sensor_msgs/msg/LaserScan`) - 第二激光扫描输出(需启用 `enable_second_scan`)。
### 订阅话题
- `cloud_in_topic`(默认 `/cloud_in`,`sensor_msgs/msg/PointCloud2`) - 输入点云。只有当输出话题有订阅者时才处理。
### 参数
#### 公共参数
- `target_frame` (str, 默认: 无) - 转换前将点云变换到的目标坐标系。
- `transform_tolerance` (double, 默认: 0.01) - 变换查找时间容差。
- `cloud_in_topic` (str, 默认: `/livox/lidar`) - 输入点云话题(可自定义)。
- `cloud_in_reliable` (bool, 默认: `false`) - 输入点云订阅 QoS 可靠性开关。`false=best_effort`,`true=reliable`。
#### 第一激光扫描参数
- `min_height` (double, 默认: 极小值) - 采样最小高度(米)。
- `max_height` (double, 默认: 极大值) - 采样最大高度(米)。
- `angle_min` (double, 默认: -π) - 最小扫描角度(弧度)。
- `angle_max` (double, 默认: π) - 最大扫描角度(弧度)。
- `angle_increment` (double, 默认: π/180) - 角度分辨率(弧度/射线)。
- `scan_time` (double, 默认: 0.033) - 扫描时间(秒)。
- `range_min` (double, 默认: 0.0) - 最小有效距离(米)。
- `range_max` (double, 默认: 极大值) - 最大有效距离(米)。
- `use_inf` (bool, 默认: true) - 是否用 +inf 表示无穷远。
- `inf_epsilon` (double, 默认: 1.0) - 无穷大容差(可选,原包无此参数)。
- `scan_out_topic` (str, 默认: `/scan`) - 输出话题。
- `scan_out_reliable` (bool, 默认: `false`) - 第一激光扫描发布 QoS 可靠性开关。`false=best_effort`,`true=reliable`。
#### 第二激光扫描参数(新增功能)
- `enable_second_scan` (bool, 默认: false) - 是否启用第二扫描输出。
- `target_frame2` (str, 默认: `target_frame` 值) - 第二扫描目标坐标系。
- `min_height2` / `max_height2` - 第二高度范围。
- `angle_min2` / `angle_max2` / `angle_increment2` - 第二角度参数。
- `scan_time2` / `range_min2` / `range_max2` - 第二扫描时间与距离范围。
- `use_inf2` (bool) / `inf_epsilon2` (double) - 第二无穷大设置。
- `scan_out_topic2` (str, 默认: `/scan2`) - 第二输出话题。
- `scan_out2_reliable` (bool, 默认: `false`) - 第二激光扫描发布 QoS 可靠性开关。`false=best_effort`,`true=reliable`。
## pointcloud_to_laserscan::LaserScanToPointCloudNode
将 `sensor_msgs/msg/LaserScan` 重新发布为 `sensor_msgs/msg/PointCloud2`(未修改)。
### 发布话题
- `cloud` (`sensor_msgs/msg/PointCloud2`) - 输出点云。
### 订阅话题
- `scan_in` (`sensor_msgs/msg/LaserScan`) - 输入激光扫描。
### 参数
- `queue_size` (int, 默认: 核心数) - 输入队列大小。
- `target_frame` (str, 默认: 无) - 目标坐标系。
- `transform_tolerance` (double, 默认: 0.01) - 变换容差。
- `scan_in_reliable` (bool, 默认: `false`) - 输入激光订阅 QoS 可靠性开关。`false=best_effort`,`true=reliable`。
- `cloud_out_reliable` (bool, 默认: `false`) - 输出点云发布 QoS 可靠性开关。`false=best_effort`,`true=reliable`。
### 示例配置(YAML)
见提供的 yaml 示例,支持双扫描配置。
## QoS 问题排查记录(2026-04)
### 现象
- 上游 `/odin1/cloud_render` 在 RViz 看似连续,但下游订阅(尤其命令行或某些节点)出现低频、断续或几乎收不到。
- `/odin1/scan` 更新不稳定,表现为偶发 1~2Hz 或短时无数据。
### 根因分析
- 原实现中 `pointcloud_to_laserscan` 的输入订阅与输出发布均固定 `SensorDataQoS`(通常为 `best_effort`)。
- 在链路压力较高、订阅端实现差异(RViz vs CLI/Python)、或网络/调度抖动场景下,`best_effort` 更容易丢帧。
- 当上游为可靠发布(reliable)而下游关键链路仍按 `best_effort` 消费时,容易出现“上游看起来有,关键下游却不稳定”的问题。
### 本次修复
- 为包内两类节点新增 QoS 可靠性参数(bool)并支持按话题方向单独配置:
- PointCloud2 -> LaserScan:
- `cloud_in_reliable`
- `scan_out_reliable`
- `scan_out2_reliable`
- LaserScan -> PointCloud2:
- `scan_in_reliable`
- `cloud_out_reliable`
- 参数语义统一为:
- `false`: `best_effort`
- `true`: `reliable`
- 默认值保持 `false`,保证历史行为兼容,不引入默认负收益。
### challenge1 实际配置建议(已验证有效)
- 输入端跟随上游可靠性:
- `cloud_in_reliable: true`(当上游 `/odin1/cloud_render` 为 reliable)
- 输出端按用途分层:
- 实时可视化/低延迟链路:`scan_out_reliable: false`
- 关键决策链路(定位/导航)可按需改为 `true`
### 验证结果
- 在 challenge1 配置下,修复后问题消失,订阅稳定性明显提升。
- 包内代码已完成编译验证:
- `CCACHE_DISABLE=1 colcon build --packages-select pointcloud_to_laserscan`
### 经验总结
- 不建议“一刀切”把所有话题都设为 reliable。
- 推荐策略是“输入跟随上游可靠性,输出按业务分层”:
- 可视化与调试优先低延迟(best_effort)
- 关键控制与规划优先可达性(reliable)
@@ -0,0 +1,39 @@
pointcloud_to_laserscan:
ros__parameters:
# 坐标系设置
target_frame: base_link
transform_tolerance: 0.01
# 输入话题配置
cloud_in_topic: '/odin1/cloud_raw'
cloud_in_reliable: false # 输入点云QoS: false=best_effort, true=reliable
# 第一个激光扫描参数
min_height: 0.0 # 最小高度
max_height: 1.5 # 最大高度
angle_min: -3.14159 # 起始角度
angle_max: 3.14159 # 结束角度
angle_increment: 0.0043 # 角度增量
scan_time: 0.1 # 扫描时间
range_min: 0.2 # 最小距离
range_max: 15.0 # 最大距离
use_inf: true # 是否使用无穷大
inf_epsilon: 1.0 # 无穷大容差
scan_out_topic: '/odin1/scan' # 第一个扫描输出话题
scan_out_reliable: true # 第一个扫描输出QoS: false=best_effort, true=reliable
# 第二个激光扫描配置
enable_second_scan: false # 启用第二个扫描转换
scan_out_topic2: '/livox/scan2' # 第二个扫描输出话题
target_frame2: base_link # 第二个扫描的目标坐标系
min_height2: 0.4 # 第二个扫描的最小高度
max_height2: 0.5 # 第二个扫描的最大高度
angle_min2: -3.14159 # 第二个扫描的起始角度
angle_max2: 3.14159 # 第二个扫描的结束角度
angle_increment2: 0.0087 # 第二个扫描的角度增量
scan_time2: 0.1 # 第二个扫描的时间
range_min2: 0.2 # 第二个扫描的最小距离
range_max2: 7.0 # 第二个扫描的最大距离
use_inf2: true # 第二个扫描是否使用无穷大
inf_epsilon2: 1.0 # 第二个扫描的无穷大容差
scan_out2_reliable: false # 第二个扫描输出QoS: false=best_effort, true=reliable
@@ -0,0 +1,100 @@
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, Eurotec, Netherlands
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
/*
* Author: Rein Appeldoorn
*/
#ifndef POINTCLOUD_TO_LASERSCAN__LASERSCAN_TO_POINTCLOUD_NODE_HPP_
#define POINTCLOUD_TO_LASERSCAN__LASERSCAN_TO_POINTCLOUD_NODE_HPP_
#include <atomic>
#include <memory>
#include <string>
#include <thread>
#include "message_filters/subscriber.h"
#include "tf2_ros/buffer.h"
#include "tf2_ros/message_filter.h"
#include "tf2_ros/transform_listener.h"
#include "laser_geometry/laser_geometry.hpp"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/laser_scan.hpp"
#include "sensor_msgs/msg/point_cloud2.hpp"
#include "pointcloud_to_laserscan/visibility_control.h"
namespace pointcloud_to_laserscan
{
typedef tf2_ros::MessageFilter<sensor_msgs::msg::LaserScan> MessageFilter;
//! \brief The PointCloudToLaserScanNodelet class to process incoming laserscans into pointclouds.
//!
class LaserScanToPointCloudNode : public rclcpp::Node
{
public:
POINTCLOUD_TO_LASERSCAN_PUBLIC
explicit LaserScanToPointCloudNode(const rclcpp::NodeOptions & options);
~LaserScanToPointCloudNode() override;
private:
void scanCallback(sensor_msgs::msg::LaserScan::ConstSharedPtr scan_msg);
void subscriptionListenerThreadLoop();
std::unique_ptr<tf2_ros::Buffer> tf2_;
std::unique_ptr<tf2_ros::TransformListener> tf2_listener_;
message_filters::Subscriber<sensor_msgs::msg::LaserScan> sub_;
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::PointCloud2>> pub_;
std::unique_ptr<MessageFilter> message_filter_;
std::thread subscription_listener_thread_;
std::atomic_bool alive_{true};
laser_geometry::LaserProjection projector_;
// ROS Parameters
int input_queue_size_;
std::string target_frame_;
double tolerance_;
bool scan_in_reliable_; // 输入LaserScan QoS可靠性:true=reliable, false=best_effort
bool cloud_out_reliable_; // 输出PointCloud2 QoS可靠性
};
} // namespace pointcloud_to_laserscan
#endif // POINTCLOUD_TO_LASERSCAN__LASERSCAN_TO_POINTCLOUD_NODE_HPP_
@@ -0,0 +1,132 @@
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010-2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
/*
* Author: Paul Bovbel
*/
#ifndef POINTCLOUD_TO_LASERSCAN__POINTCLOUD_TO_LASERSCAN_NODE_HPP_
#define POINTCLOUD_TO_LASERSCAN__POINTCLOUD_TO_LASERSCAN_NODE_HPP_
#include <atomic>
#include <memory>
#include <string>
#include <thread>
#include "message_filters/subscriber.h"
#include "tf2_ros/buffer.h"
#include "tf2_ros/message_filter.h"
#include "tf2_ros/transform_listener.h"
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/laser_scan.hpp"
#include "sensor_msgs/msg/point_cloud2.hpp"
#include "pointcloud_to_laserscan/visibility_control.h"
namespace pointcloud_to_laserscan
{
typedef tf2_ros::MessageFilter<sensor_msgs::msg::PointCloud2> MessageFilter;
/**
* Class to process incoming pointclouds into laserscans.
* Some initial code was pulled from the defunct turtlebot pointcloud_to_laserscan implementation.
*/
class PointCloudToLaserScanNode : public rclcpp::Node
{
public:
POINTCLOUD_TO_LASERSCAN_PUBLIC
explicit PointCloudToLaserScanNode(const rclcpp::NodeOptions & options);
~PointCloudToLaserScanNode() override;
private:
void cloudCallback(sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg);
void subscriptionListenerThreadLoop();
// 新增:处理单个激光扫描转换的辅助函数
void processLaserScan(
sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg,
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::LaserScan>> publisher,
const std::string& target_frame,
double min_height, double max_height,
double angle_min, double angle_max, double angle_increment,
double scan_time, double range_min, double range_max,
bool use_inf, double inf_epsilon);
std::unique_ptr<tf2_ros::Buffer> tf2_;
std::unique_ptr<tf2_ros::TransformListener> tf2_listener_;
message_filters::Subscriber<sensor_msgs::msg::PointCloud2> sub_;
// 修改:支持两个激光扫描发布器
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::LaserScan>> pub1_; // 第一个激光扫描发布器
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::LaserScan>> pub2_; // 第二个激光扫描发布器
std::unique_ptr<MessageFilter> message_filter_;
std::thread subscription_listener_thread_;
std::atomic_bool alive_{true};
// ROS Parameters - 主要参数(用于第一个扫描)
int input_queue_size_;
std::string target_frame_;
std::string filter_frame_; // 新增:用于高度过滤的坐标系(通常设置为 base_link)
double tolerance_;
double min_height_, max_height_, angle_min_, angle_max_, angle_increment_, scan_time_, range_min_, range_max_;
bool use_inf_;
double inf_epsilon_;
// 新增:第二个激光扫描的参数
bool enable_second_scan_; // 是否启用第二个扫描转换
std::string target_frame2_; // 第二个扫描的目标坐标系
double min_height2_, max_height2_; // 第二个扫描的高度过滤范围
double angle_min2_, angle_max2_, angle_increment2_; // 第二个扫描的角度参数
double scan_time2_, range_min2_, range_max2_; // 第二个扫描的时间距离参数
bool use_inf2_; // 第二个扫描是否使用无穷大
double inf_epsilon2_; // 第二个扫描的无穷大容差值
// 新增:话题名称配置
std::string scan_out_topic1_; // 第一个扫描输出话题
std::string scan_out_topic2_; // 第二个扫描输出话题
bool cloud_in_reliable_; // 输入点云QoS可靠性:true=reliable, false=best_effort
bool scan_out_reliable_; // 第一个扫描输出QoS可靠性
bool scan_out2_reliable_; // 第二个扫描输出QoS可靠性
};
} // namespace pointcloud_to_laserscan
#endif // POINTCLOUD_TO_LASERSCAN__POINTCLOUD_TO_LASERSCAN_NODE_HPP_
@@ -0,0 +1,80 @@
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, Eurotec, Netherlands
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
#ifndef POINTCLOUD_TO_LASERSCAN__VISIBILITY_CONTROL_H_
#define POINTCLOUD_TO_LASERSCAN__VISIBILITY_CONTROL_H_
#ifdef __cplusplus
extern "C"
{
#endif
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define POINTCLOUD_TO_LASERSCAN_EXPORT __attribute__ ((dllexport))
#define POINTCLOUD_TO_LASERSCAN_IMPORT __attribute__ ((dllimport))
#else
#define POINTCLOUD_TO_LASERSCAN_EXPORT __declspec(dllexport)
#define POINTCLOUD_TO_LASERSCAN_IMPORT __declspec(dllimport)
#endif
#ifdef POINTCLOUD_TO_LASERSCAN_BUILDING_DLL
#define POINTCLOUD_TO_LASERSCAN_PUBLIC POINTCLOUD_TO_LASERSCAN_EXPORT
#else
#define POINTCLOUD_TO_LASERSCAN_PUBLIC POINTCLOUD_TO_LASERSCAN_IMPORT
#endif
#define POINTCLOUD_TO_LASERSCAN_PUBLIC_TYPE POINTCLOUD_TO_LASERSCAN_PUBLIC
#define POINTCLOUD_TO_LASERSCAN_LOCAL
#else
#define POINTCLOUD_TO_LASERSCAN_EXPORT __attribute__ ((visibility("default")))
#define POINTCLOUD_TO_LASERSCAN_IMPORT
#if __GNUC__ >= 4
#define POINTCLOUD_TO_LASERSCAN_PUBLIC __attribute__ ((visibility("default")))
#define POINTCLOUD_TO_LASERSCAN_LOCAL __attribute__ ((visibility("hidden")))
#else
#define POINTCLOUD_TO_LASERSCAN_PUBLIC
#define POINTCLOUD_TO_LASERSCAN_LOCAL
#endif
#define POINTCLOUD_TO_LASERSCAN_PUBLIC_TYPE
#endif
#ifdef __cplusplus
}
#endif
#endif // POINTCLOUD_TO_LASERSCAN__VISIBILITY_CONTROL_H_
@@ -0,0 +1,33 @@
import launch_ros
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from ament_index_python.packages import get_package_share_directory
import os
import yaml
def generate_launch_description():
config_dir = os.path.join(
get_package_share_directory('pointcloud_to_laserscan'),
'config',
'params_pointcloud_to_laserscan.yaml'
)
# 加载并解析 YAML 文件
with open(config_dir, 'r') as f:
params = yaml.safe_load(f)
cloud_in_topic = params['pointcloud_to_laserscan']['ros__parameters']['cloud_in_topic']
scan_out_topic = params['pointcloud_to_laserscan']['ros__parameters']['scan_out_topic']
action_pointcloud_to_laserscan = launch_ros.actions.Node(
package='pointcloud_to_laserscan', executable='pointcloud_to_laserscan_node',
remappings=[('cloud_in', [cloud_in_topic]),
('scan', [scan_out_topic])],
parameters=[config_dir],
name='pointcloud_to_laserscan'
)
return LaunchDescription([
action_pointcloud_to_laserscan,
])
@@ -0,0 +1,47 @@
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.actions import ExecuteProcess
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
import yaml
def generate_launch_description():
return LaunchDescription([
DeclareLaunchArgument(
name='scanner', default_value='scanner',
description='Namespace for sample topics'
),
ExecuteProcess(
cmd=[
'ros2', 'topic', 'pub', '-r', '10',
'--qos-profile', 'sensor_data',
[LaunchConfiguration(variable_name='scanner'), '/scan'],
'sensor_msgs/msg/LaserScan', yaml.dump({
'header': {'frame_id': 'scan'}, 'angle_min': -1.0,
'angle_max': 1.0, 'angle_increment': 0.1, 'range_max': 10.0,
'ranges': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
})
],
name='scan_publisher'
),
Node(
package='tf2_ros',
executable='static_transform_publisher',
name='static_transform_publisher',
arguments=[
'--x', '0', '--y', '0', '--z', '0',
'--qx', '0', '--qy', '0', '--qz', '0', '--qw', '1',
'--frame-id', 'map', '--child-frame-id', 'scan'
]
),
Node(
package='pointcloud_to_laserscan',
executable='laserscan_to_pointcloud_node',
name='laserscan_to_pointcloud',
remappings=[('scan_in', [LaunchConfiguration(variable_name='scanner'), '/scan']),
('cloud', [LaunchConfiguration(variable_name='scanner'), '/cloud'])],
parameters=[{'target_frame': 'scan', 'transform_tolerance': 0.01}]
),
])
@@ -0,0 +1,49 @@
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription([
DeclareLaunchArgument(
name='scanner', default_value='scanner',
description='Namespace for sample topics'
),
Node(
package='pointcloud_to_laserscan', executable='dummy_pointcloud_publisher',
remappings=[('cloud', [LaunchConfiguration(variable_name='scanner'), '/cloud'])],
parameters=[{'cloud_frame_id': 'cloud', 'cloud_extent': 2.0, 'cloud_size': 500}],
name='cloud_publisher'
),
Node(
package='tf2_ros',
executable='static_transform_publisher',
name='static_transform_publisher',
arguments=[
'--x', '0', '--y', '0', '--z', '0',
'--qx', '0', '--qy', '0', '--qz', '0', '--qw', '1',
'--frame-id', 'map', '--child-frame-id', 'cloud'
]
),
Node(
package='pointcloud_to_laserscan', executable='pointcloud_to_laserscan_node',
remappings=[('cloud_in', [LaunchConfiguration(variable_name='scanner'), '/cloud']),
('scan', [LaunchConfiguration(variable_name='scanner'), '/scan'])],
parameters=[{
'target_frame': 'cloud',
'transform_tolerance': 0.01,
'min_height': 0.0,
'max_height': 1.0,
'angle_min': -1.5708, # -M_PI/2
'angle_max': 1.5708, # M_PI/2
'angle_increment': 0.0087, # M_PI/360.0
'scan_time': 0.3333,
'range_min': 0.45,
'range_max': 4.0,
'use_inf': True,
'inf_epsilon': 1.0
}],
name='pointcloud_to_laserscan'
)
])
@@ -0,0 +1,46 @@
<?xml version="1.0"?>
<package format="2">
<name>pointcloud_to_laserscan</name>
<version>2.0.1</version>
<description>Converts a 3D Point Cloud into a 2D laser scan. This is useful for making devices like the Kinect appear like a laser scanner for 2D-based algorithms (e.g. laser-based SLAM).</description>
<maintainer email="[email protected]">Paul Bovbel</maintainer>
<maintainer email="[email protected]">Michel Hidalgo</maintainer>
<author email="[email protected]">Paul Bovbel</author>
<author email="[email protected]">Michel Hidalgo</author>
<author>Tully Foote</author>
<license>BSD</license>
<url type="website">http://ros.org/wiki/perception_pcl</url>
<url type="bugtracker">https://github.com/ros-perception/perception_pcl/issues</url>
<url type="repository">https://github.com/ros-perception/perception_pcl</url>
<buildtool_depend>ament_cmake_auto</buildtool_depend>
<depend>laser_geometry</depend>
<depend>message_filters</depend>
<depend>rclcpp</depend>
<depend>rclcpp_components</depend>
<depend>sensor_msgs</depend>
<depend>tf2</depend>
<depend>tf2_ros</depend>
<depend>tf2_sensor_msgs</depend>
<exec_depend>launch</exec_depend>
<exec_depend>launch_ros</exec_depend>
<test_depend>ament_lint_auto</test_depend>
<!-- <exec_depend>ament_cmake_copyright</exec_depend> -->
<test_depend>ament_cmake_cppcheck</test_depend>
<test_depend>ament_cmake_cpplint</test_depend>
<test_depend>ament_cmake_flake8</test_depend>
<test_depend>ament_cmake_lint_cmake</test_depend>
<test_depend>ament_cmake_pep257</test_depend>
<test_depend>ament_cmake_uncrustify</test_depend>
<test_depend>ament_cmake_xmllint</test_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
@@ -0,0 +1,85 @@
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2020, Open Source Robotics Foundation, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
#include <memory>
#include <random>
#include "rclcpp/rclcpp.hpp"
#include "sensor_msgs/msg/point_cloud2.hpp"
#include "sensor_msgs/point_cloud2_iterator.hpp"
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
auto node = std::make_shared<rclcpp::Node>("dummy_pointcloud_publisher");
auto pub =
node->create_publisher<sensor_msgs::msg::PointCloud2>("cloud", rclcpp::SensorDataQoS());
sensor_msgs::msg::PointCloud2 dummy_cloud;
sensor_msgs::PointCloud2Modifier modifier(dummy_cloud);
modifier.setPointCloud2Fields(
3,
"x", 1, sensor_msgs::msg::PointField::FLOAT32,
"y", 1, sensor_msgs::msg::PointField::FLOAT32,
"z", 1, sensor_msgs::msg::PointField::FLOAT32);
modifier.resize(node->declare_parameter("cloud_size", 100));
std::mt19937 gen(node->declare_parameter("cloud_seed", 0));
double extent = node->declare_parameter("cloud_extent", 10.0);
std::uniform_real_distribution<float> distribution(-extent / 2, extent / 2);
sensor_msgs::PointCloud2Iterator<float> it_x(dummy_cloud, "x");
sensor_msgs::PointCloud2Iterator<float> it_y(dummy_cloud, "y");
sensor_msgs::PointCloud2Iterator<float> it_z(dummy_cloud, "z");
for (; it_x != it_x.end(); ++it_x, ++it_y, ++it_z) {
*it_x = distribution(gen);
*it_y = distribution(gen);
*it_z = distribution(gen);
}
dummy_cloud.header.frame_id = node->declare_parameter("cloud_frame_id", "");
rclcpp::executors::SingleThreadedExecutor executor;
executor.add_node(node);
rclcpp::Rate rate(1.0);
while (rclcpp::ok()) {
dummy_cloud.header.stamp = node->get_clock()->now();
pub->publish(dummy_cloud);
executor.spin_some();
rate.sleep();
}
rclcpp::shutdown();
return 0;
}
@@ -0,0 +1,164 @@
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, Eurotec, Netherlands
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
/*
* Author: Rein Appeldoorn
*/
#include "pointcloud_to_laserscan/laserscan_to_pointcloud_node.hpp"
#include <chrono>
#include <functional>
#include <limits>
#include <memory>
#include <string>
#include <thread>
#include <utility>
#include <rmw/types.h>
#include "sensor_msgs/point_cloud2_iterator.hpp"
#include "tf2_sensor_msgs/tf2_sensor_msgs.hpp"
#include "tf2_ros/create_timer_ros.h"
namespace pointcloud_to_laserscan
{
LaserScanToPointCloudNode::LaserScanToPointCloudNode(const rclcpp::NodeOptions & options)
: rclcpp::Node("laserscan_to_pointcloud", options)
{
target_frame_ = this->declare_parameter("target_frame", "");
tolerance_ = this->declare_parameter("transform_tolerance", 0.01);
scan_in_reliable_ = this->declare_parameter("scan_in_reliable", false);
cloud_out_reliable_ = this->declare_parameter("cloud_out_reliable", false);
// TODO(hidmic): adjust default input queue size based on actual concurrency levels
// achievable by the associated executor
input_queue_size_ = this->declare_parameter(
"queue_size", static_cast<int>(std::thread::hardware_concurrency()));
rclcpp::SensorDataQoS cloud_qos;
if (cloud_out_reliable_) {
cloud_qos.reliability(RMW_QOS_POLICY_RELIABILITY_RELIABLE);
} else {
cloud_qos.reliability(RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT);
}
pub_ = this->create_publisher<sensor_msgs::msg::PointCloud2>("cloud", cloud_qos);
using std::placeholders::_1;
// if pointcloud target frame specified, we need to filter by transform availability
if (!target_frame_.empty()) {
tf2_ = std::make_unique<tf2_ros::Buffer>(this->get_clock());
auto timer_interface = std::make_shared<tf2_ros::CreateTimerROS>(
this->get_node_base_interface(), this->get_node_timers_interface());
tf2_->setCreateTimerInterface(timer_interface);
tf2_listener_ = std::make_unique<tf2_ros::TransformListener>(*tf2_);
message_filter_ = std::make_unique<MessageFilter>(
sub_, *tf2_, target_frame_, input_queue_size_,
this->get_node_logging_interface(),
this->get_node_clock_interface());
message_filter_->registerCallback(
std::bind(
&LaserScanToPointCloudNode::scanCallback, this, _1));
} else { // otherwise setup direct subscription
sub_.registerCallback(std::bind(&LaserScanToPointCloudNode::scanCallback, this, _1));
}
subscription_listener_thread_ = std::thread(
std::bind(&LaserScanToPointCloudNode::subscriptionListenerThreadLoop, this));
}
LaserScanToPointCloudNode::~LaserScanToPointCloudNode()
{
alive_.store(true);
subscription_listener_thread_.join();
}
void LaserScanToPointCloudNode::subscriptionListenerThreadLoop()
{
rclcpp::Context::SharedPtr context = this->get_node_base_interface()->get_context();
const std::chrono::milliseconds timeout(100);
while (rclcpp::ok(context) && alive_.load()) {
int subscription_count = pub_->get_subscription_count() +
pub_->get_intra_process_subscription_count();
if (subscription_count > 0) {
if (!sub_.getSubscriber()) {
RCLCPP_INFO(
this->get_logger(),
"Got a subscriber to pointcloud, starting laserscan subscriber");
rclcpp::SensorDataQoS qos;
if (scan_in_reliable_) {
qos.reliability(RMW_QOS_POLICY_RELIABILITY_RELIABLE);
} else {
qos.reliability(RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT);
}
qos.keep_last(input_queue_size_);
sub_.subscribe(this, "scan_in", qos.get_rmw_qos_profile());
}
} else if (sub_.getSubscriber()) {
RCLCPP_INFO(
this->get_logger(),
"No subscribers to pointcloud, shutting down laserscan subscriber");
sub_.unsubscribe();
}
rclcpp::Event::SharedPtr event = this->get_graph_event();
this->wait_for_graph_change(event, timeout);
}
sub_.unsubscribe();
}
void LaserScanToPointCloudNode::scanCallback(sensor_msgs::msg::LaserScan::ConstSharedPtr scan_msg)
{
auto cloud_msg = std::make_unique<sensor_msgs::msg::PointCloud2>();
projector_.projectLaser(*scan_msg, *cloud_msg);
// Transform cloud if necessary
if (!target_frame_.empty() && cloud_msg->header.frame_id != target_frame_) {
try {
*cloud_msg = tf2_->transform(*cloud_msg, target_frame_, tf2::durationFromSec(tolerance_));
} catch (tf2::TransformException & ex) {
RCLCPP_ERROR_STREAM(this->get_logger(), "Transform failure: " << ex.what());
return;
}
}
pub_->publish(std::move(cloud_msg));
}
} // namespace pointcloud_to_laserscan
#include "rclcpp_components/register_node_macro.hpp"
RCLCPP_COMPONENTS_REGISTER_NODE(pointcloud_to_laserscan::LaserScanToPointCloudNode)
@@ -0,0 +1,335 @@
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010-2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
*/
/*
* Author: Paul Bovbel
*/
#include "pointcloud_to_laserscan/pointcloud_to_laserscan_node.hpp"
#include <chrono>
#include <functional>
#include <limits>
#include <memory>
#include <string>
#include <thread>
#include <utility>
#include <rmw/types.h>
#include "sensor_msgs/point_cloud2_iterator.hpp"
#include "tf2_sensor_msgs/tf2_sensor_msgs.hpp"
#include "tf2_ros/create_timer_ros.h"
namespace pointcloud_to_laserscan
{
PointCloudToLaserScanNode::PointCloudToLaserScanNode(const rclcpp::NodeOptions & options)
: rclcpp::Node("pointcloud_to_laserscan", options)
{
// 主要参数声明(第一个扫描)
target_frame_ = this->declare_parameter("target_frame", "");
// 新增:filter_frame 用于指定在哪个坐标系下进行高度过滤
// 通常设置为 base_link,确保提取的激光扫描是水平的
// 如果不设置,默认使用 target_frame
filter_frame_ = this->declare_parameter("filter_frame", target_frame_);
tolerance_ = this->declare_parameter("transform_tolerance", 0.01);
input_queue_size_ = this->declare_parameter(
"queue_size", static_cast<int>(std::thread::hardware_concurrency()));
min_height_ = this->declare_parameter("min_height", std::numeric_limits<double>::min());
max_height_ = this->declare_parameter("max_height", std::numeric_limits<double>::max());
angle_min_ = this->declare_parameter("angle_min", -M_PI);
angle_max_ = this->declare_parameter("angle_max", M_PI);
angle_increment_ = this->declare_parameter("angle_increment", M_PI / 180.0);
scan_time_ = this->declare_parameter("scan_time", 1.0 / 30.0);
range_min_ = this->declare_parameter("range_min", 0.0);
range_max_ = this->declare_parameter("range_max", std::numeric_limits<double>::max());
inf_epsilon_ = this->declare_parameter("inf_epsilon", 1.0);
use_inf_ = this->declare_parameter("use_inf", true);
scan_out_topic1_ = this->declare_parameter("scan_out_topic", "scan"); // 第一个扫描输出话题
cloud_in_reliable_ = this->declare_parameter("cloud_in_reliable", false);
scan_out_reliable_ = this->declare_parameter("scan_out_reliable", false);
// 新增:第二个扫描的参数声明
enable_second_scan_ = this->declare_parameter("enable_second_scan", false); // 默认关闭第二个扫描
target_frame2_ = this->declare_parameter("target_frame2", target_frame_); // 默认与第一个相同
min_height2_ = this->declare_parameter("min_height2", min_height_);
max_height2_ = this->declare_parameter("max_height2", max_height_);
angle_min2_ = this->declare_parameter("angle_min2", angle_min_);
angle_max2_ = this->declare_parameter("angle_max2", angle_max_);
angle_increment2_ = this->declare_parameter("angle_increment2", angle_increment_);
scan_time2_ = this->declare_parameter("scan_time2", scan_time_);
range_min2_ = this->declare_parameter("range_min2", range_min_);
range_max2_ = this->declare_parameter("range_max2", range_max_);
use_inf2_ = this->declare_parameter("use_inf2", use_inf_);
inf_epsilon2_ = this->declare_parameter("inf_epsilon2", inf_epsilon_);
scan_out_topic2_ = this->declare_parameter("scan_out_topic2", "scan2"); // 第二个扫描输出话题
scan_out2_reliable_ = this->declare_parameter("scan_out2_reliable", false);
rclcpp::SensorDataQoS scan_qos;
if (scan_out_reliable_) {
scan_qos.reliability(RMW_QOS_POLICY_RELIABILITY_RELIABLE);
} else {
scan_qos.reliability(RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT);
}
// 创建第一个激光扫描发布器
pub1_ = this->create_publisher<sensor_msgs::msg::LaserScan>(
scan_out_topic1_, scan_qos);
// 如果启用第二个扫描,创建第二个发布器
if (enable_second_scan_) {
rclcpp::SensorDataQoS scan_qos2;
if (scan_out2_reliable_) {
scan_qos2.reliability(RMW_QOS_POLICY_RELIABILITY_RELIABLE);
} else {
scan_qos2.reliability(RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT);
}
pub2_ = this->create_publisher<sensor_msgs::msg::LaserScan>(
scan_out_topic2_, scan_qos2);
RCLCPP_INFO(this->get_logger(), "Second laser scan enabled, publishing to topic: %s",
scan_out_topic2_.c_str());
}
RCLCPP_INFO(this->get_logger(), "First laser scan publishing to topic: %s", scan_out_topic1_.c_str());
using std::placeholders::_1;
// 如果指定了 filter_frame,需要通过 TF 变换可用性进行过滤
// filter_frame 用于确保点云可以转换到指定的坐标系进行高度过滤
if (!filter_frame_.empty()) {
tf2_ = std::make_unique<tf2_ros::Buffer>(this->get_clock());
auto timer_interface = std::make_shared<tf2_ros::CreateTimerROS>(
this->get_node_base_interface(), this->get_node_timers_interface());
tf2_->setCreateTimerInterface(timer_interface);
tf2_listener_ = std::make_unique<tf2_ros::TransformListener>(*tf2_);
message_filter_ = std::make_unique<MessageFilter>(
sub_, *tf2_, filter_frame_, input_queue_size_,
this->get_node_logging_interface(),
this->get_node_clock_interface());
message_filter_->registerCallback(
std::bind(&PointCloudToLaserScanNode::cloudCallback, this, _1));
} else { // 否则设置直接订阅
sub_.registerCallback(std::bind(&PointCloudToLaserScanNode::cloudCallback, this, _1));
}
subscription_listener_thread_ = std::thread(
std::bind(&PointCloudToLaserScanNode::subscriptionListenerThreadLoop, this));
}
PointCloudToLaserScanNode::~PointCloudToLaserScanNode()
{
alive_.store(false);
subscription_listener_thread_.join();
}
void PointCloudToLaserScanNode::subscriptionListenerThreadLoop()
{
rclcpp::Context::SharedPtr context = this->get_node_base_interface()->get_context();
const std::chrono::milliseconds timeout(100);
while (rclcpp::ok(context) && alive_.load()) {
// 修改:检查两个发布器的订阅状态
int subscription_count = 0;
if (pub1_) {
subscription_count += pub1_->get_subscription_count() + pub1_->get_intra_process_subscription_count();
}
if (enable_second_scan_ && pub2_) {
subscription_count += pub2_->get_subscription_count() + pub2_->get_intra_process_subscription_count();
}
if (subscription_count > 0) {
if (!sub_.getSubscriber()) {
RCLCPP_INFO(
this->get_logger(),
"Got subscribers to laserscan, starting pointcloud subscriber");
rclcpp::SensorDataQoS qos;
if (cloud_in_reliable_) {
qos.reliability(RMW_QOS_POLICY_RELIABILITY_RELIABLE);
} else {
qos.reliability(RMW_QOS_POLICY_RELIABILITY_BEST_EFFORT);
}
qos.keep_last(input_queue_size_);
sub_.subscribe(this, "cloud_in", qos.get_rmw_qos_profile());
}
} else if (sub_.getSubscriber()) {
RCLCPP_INFO(
this->get_logger(),
"No subscribers to laserscan, shutting down pointcloud subscriber");
sub_.unsubscribe();
}
rclcpp::Event::SharedPtr event = this->get_graph_event();
this->wait_for_graph_change(event, timeout);
}
sub_.unsubscribe();
}
void PointCloudToLaserScanNode::cloudCallback(
sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg)
{
// 处理第一个激光扫描,使用 filter_frame_ 进行高度过滤
processLaserScan(cloud_msg, pub1_, filter_frame_,
min_height_, max_height_,
angle_min_, angle_max_, angle_increment_,
scan_time_, range_min_, range_max_,
use_inf_, inf_epsilon_);
// 如果启用第二个扫描,处理第二个激光扫描
if (enable_second_scan_ && pub2_) {
processLaserScan(cloud_msg, pub2_, target_frame2_,
min_height2_, max_height2_,
angle_min2_, angle_max2_, angle_increment2_,
scan_time2_, range_min2_, range_max2_,
use_inf2_, inf_epsilon2_);
}
}
// 新增:处理单个激光扫描转换的辅助函数
void PointCloudToLaserScanNode::processLaserScan(
sensor_msgs::msg::PointCloud2::ConstSharedPtr cloud_msg,
std::shared_ptr<rclcpp::Publisher<sensor_msgs::msg::LaserScan>> publisher,
const std::string& target_frame,
double min_height, double max_height,
double angle_min, double angle_max, double angle_increment,
double scan_time, double range_min, double range_max,
bool use_inf, double inf_epsilon)
{
// 构建激光扫描输出
auto scan_msg = std::make_unique<sensor_msgs::msg::LaserScan>();
scan_msg->header = cloud_msg->header;
// 使用 target_frame 作为输出的 frame_id
// target_frame 是进行高度过滤的坐标系,通常是水平的 base_link
if (!target_frame.empty()) {
scan_msg->header.frame_id = target_frame;
}
scan_msg->angle_min = angle_min;
scan_msg->angle_max = angle_max;
scan_msg->angle_increment = angle_increment;
scan_msg->time_increment = 0.0;
scan_msg->scan_time = scan_time;
scan_msg->range_min = range_min;
scan_msg->range_max = range_max;
// 确定要创建的射线数量
uint32_t ranges_size = std::ceil(
(scan_msg->angle_max - scan_msg->angle_min) / scan_msg->angle_increment);
// 确定没有障碍物数据的激光扫描射线将评估为无穷大还是最大范围
if (use_inf) {
scan_msg->ranges.assign(ranges_size, std::numeric_limits<double>::infinity());
} else {
scan_msg->ranges.assign(ranges_size, scan_msg->range_max + inf_epsilon);
}
// ===== 坐标转换:使用 target_frame 进行高度过滤 =====
// 将点云转换到 target_frame 坐标系(通常是水平的 base_link)
// 这样可以确保高度过滤(min_height/max_height)是在水平方向上进行的
// 从而提取出平行于地面的激光扫描切片
if (!target_frame.empty() && scan_msg->header.frame_id != cloud_msg->header.frame_id) {
try {
auto cloud = std::make_shared<sensor_msgs::msg::PointCloud2>();
tf2_->transform(*cloud_msg, *cloud, target_frame, tf2::durationFromSec(tolerance_));
cloud_msg = cloud;
} catch (tf2::TransformException & ex) {
RCLCPP_ERROR_STREAM(this->get_logger(), "Transform failure: " << ex.what());
return;
}
}
// 迭代处理点云数据
for (sensor_msgs::PointCloud2ConstIterator<float> iter_x(*cloud_msg, "x"),
iter_y(*cloud_msg, "y"), iter_z(*cloud_msg, "z");
iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z)
{
if (std::isnan(*iter_x) || std::isnan(*iter_y) || std::isnan(*iter_z)) {
RCLCPP_DEBUG(
this->get_logger(),
"rejected for nan in point(%f, %f, %f)\n",
*iter_x, *iter_y, *iter_z);
continue;
}
// 高度过滤
if (*iter_z > max_height || *iter_z < min_height) {
RCLCPP_DEBUG(
this->get_logger(),
"rejected for height %f not in range (%f, %f)\n",
*iter_z, min_height, max_height);
continue;
}
double range = hypot(*iter_x, *iter_y);
// 距离过滤
if (range < range_min) {
RCLCPP_DEBUG(
this->get_logger(),
"rejected for range %f below minimum value %f. Point: (%f, %f, %f)",
range, range_min, *iter_x, *iter_y, *iter_z);
continue;
}
if (range > range_max) {
RCLCPP_DEBUG(
this->get_logger(),
"rejected for range %f above maximum value %f. Point: (%f, %f, %f)",
range, range_max, *iter_x, *iter_y, *iter_z);
continue;
}
double angle = atan2(*iter_y, *iter_x);
// 角度过滤
if (angle < scan_msg->angle_min || angle > scan_msg->angle_max) {
RCLCPP_DEBUG(
this->get_logger(),
"rejected for angle %f not in range (%f, %f)\n",
angle, scan_msg->angle_min, scan_msg->angle_max);
continue;
}
// 如果新距离更小,覆盖激光扫描射线上的距离
int index = (angle - scan_msg->angle_min) / scan_msg->angle_increment;
if (range < scan_msg->ranges[index]) {
scan_msg->ranges[index] = range;
}
}
// 发布激光扫描数据
publisher->publish(std::move(scan_msg));
}
} // namespace pointcloud_to_laserscan
#include "rclcpp_components/register_node_macro.hpp"
RCLCPP_COMPONENTS_REGISTER_NODE(pointcloud_to_laserscan::PointCloudToLaserScanNode)
@@ -0,0 +1,18 @@
cmake_minimum_required(VERSION 3.8)
project(d_interfaces)
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 17)
endif()
find_package(ament_cmake REQUIRED)
find_package(rosidl_default_generators REQUIRED)
rosidl_generate_interfaces(${PROJECT_NAME}
"action/MoveTo.action"
"action/OrientTo.action"
"action/RampDrive.action"
)
ament_export_dependencies(rosidl_default_runtime)
ament_package()
@@ -0,0 +1,32 @@
# 平面位移控制 Action(方案四专用,与 Rc2026 的 MoveTo 语义一致)。
#
# 用途:Nav2 做不了的"精确短距位移"退化成这个离散原语,由行为树调用。
#
# 坐标约定:
# - 目标位移以 **goal 起始时刻的车体坐标系** 为参考,单位 m。
# - target_x > 0 前进,< 0 后退;target_y > 0 向左平移,< 0 向右平移。
# - 本接口不含 yaw 控制,旋转请用 OrientTo.action。
#
# 成功条件:两轴误差同时进入 position_tolerance 并保持 stable_frames 帧。
float64 target_x
float64 target_y
---
# success=true 表示位移进入容差;false 表示取消、超时或里程计失效。
bool success
# 结束时的残余误差,单位 m。
float64 final_error_x
float64 final_error_y
# 本次 goal 的执行耗时,单位 s。
float64 duration_sec
---
# 从 goal 起点累计的车体坐标位移,单位 m。
float64 current_dx
float64 current_dy
# 剩余误差,单位 m。
float64 error_x
float64 error_y
# 当前下发给 /cmd_vel 的速度,单位 m/s。
float64 cmd_vx
float64 cmd_vy
@@ -0,0 +1,19 @@
# 原地转向控制 Action。
#
# 坐标约定:
# - target_yaw 是 **odom 系**下的绝对 yaw,单位 rad,范围已归一化到 (-pi, pi]。
# - 调用方若只有场地坐标朝向,需先用世界→odom 的变换换算出 odom yaw。
# - 本接口只出 angular.z,不产生平移。
#
# 成功条件:角度误差进入 yaw_tolerance 并连续 stable_frames 帧保持。
float64 target_yaw
---
bool success
float64 final_error_rad
float64 duration_sec
---
float64 current_yaw
float64 error_rad
float64 cmd_wz
@@ -0,0 +1,27 @@
# 坡道/直线定距行驶 Action:四段速度曲线 + 航向保持。
#
# 用途:Nav2 在坡度上会因 2D 投影的高度带漂移而失效,此时暂停 Nav2,
# 交给本原语按固定速度曲线直行,靠 yaw PD 保持方向。
#
# 坐标约定:沿 **goal 起始时刻的车头方向** 前进,distance_m 为带符号的行程。
# 成功条件:|已行驶距离 - distance_m| <= distance_tolerance。
float64 distance_m
# 期望最大速度,会被底盘限幅(0.5 m/s)与本节点 max_speed 参数取小。
float64 max_speed
---
bool success
float64 traveled_m
float64 final_error_m
float64 duration_sec
# 结束原因:done / timeout / odom_lost / canceled。
string reason
---
float64 traveled_m
# 相对起点的抬升量,来自里程计 z,单位 m。
float64 z_rise_m
float64 cmd_vx
float64 cmd_wz
# 当前所处阶段:GROUND / CLIMB_INIT / CLIMB_FULL / SUMMIT_APPROACH / CREEP
string stage
@@ -0,0 +1,20 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>d_interfaces</name>
<version>0.1.0</version>
<description>方案四(先验地图 + Nav2)的 Action 原语接口定义。</description>
<maintainer email="[email protected]">RC2027 BR</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_cmake</buildtool_depend>
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
@@ -0,0 +1,47 @@
# d_move_actions — 车体系位移 PID 原语
## 为什么需要它
Nav2 负责"从 A 走到 B",但赛场上有大量动作 Nav2 天生做不好:
- 贴边 3 cm 再停(costmap 精度、MPPI 采样噪声都顶不住)
- 指定方向横移固定距离(麦轮特性,全局规划器不保证方向)
- 由行为树精确复现"退 15 cm 再转 30°"这类固定动作
这些退化成**离散原语**:给定车体系位移,PID 闭环到 2 cm。
## 接口
`d_interfaces/action/MoveTo.action`
```
goal: target_x, target_y # 相对 goal 起始车体系,m
result: success, final_error_x/y, duration_sec
feedback: current_dx/dy, error_x/y, cmd_vx/vy
```
## 定位来源
订阅 `odom_topic`(默认 `/odin1/odometry`),**不用 TF**。
理由:AMCL 重定位会让 `world→odom` 瞬移,如果按 TF 算"走了多少",
一次粒子收敛就可能被判成"已经到位"或"还差半米"。里程计局部连续,
更适合小位移闭环。
## 参数
默认值在 `d_move_actions/params.py`,`validate()` 会在节点启动时自检。
被守住的关键约束:**`output_limit` 不得超过底盘限幅 0.5**——底盘是静默截断,
超了不会有任何报错,只会表现为"车不动、误差不降"。
## 运行
```bash
ros2 run d_move_actions move_action_server
ros2 action send_goal /move_to d_interfaces/action/MoveTo "{target_x: 0.5, target_y: 0.0}"
```
## 前置条件
调用前必须暂停 Nav2(两者都写 `/cmd_vel`)。行为树里用
`PauseNav2 → MoveTo → ResumeNav2` 的顺序保证,本节点不做仲裁。
@@ -0,0 +1,8 @@
"""让 pytest 在未 source ROS 的环境下直接跑源码目录。"""
import os
import sys
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
@@ -0,0 +1 @@
"""方案四的 Action 原语包。"""
@@ -0,0 +1,264 @@
"""车体系 XY 位移 PID Action 服务器(MoveTo 原语)。
定位来源用**里程计话题**而不是 TF:
- 方案四的 Nav2 与 AMCL 会同时往 TF 里发 world→odom,Action 原语关心的是
里程计局部连续性("从起步点走了多少"),用 /odin1/odometry 更直接,
也不受 AMCL 跳变影响(重定位一跳,TF 会瞬移,按 TF 算位移会误判到位)。
- 目标是 **goal 起始时刻车体系** 的固定量,见 d_pid_core.motion 的说明。
安全约定:本节点被调用前,行为树必须已暂停 Nav2(两者都写 /cmd_vel,
同时活跃会互相覆盖)。这里不做仲裁,只在日志里提示。
"""
import time
import rclpy
from rclpy.action import ActionServer, CancelResponse, GoalResponse
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from d_interfaces.action import MoveTo
from d_move_actions.params import default_params, validate
from d_pid_core import (
PID,
PIDConfig,
apply_min_motion_speed,
planar_error,
speed_limit,
yaw_from_quaternion,
)
class MoveActionServer(Node):
"""把 (target_x, target_y) 变成 /cmd_vel 的双轴 PID。"""
def __init__(self):
super().__init__('d_move_action_server')
p = default_params()
problems = validate(p)
if problems:
for item in problems:
self.get_logger().error(f'[move] 参数自检失败:{item}')
raise ValueError('d_move_actions 默认参数非法')
self.declare_parameter('odom_topic', '/odin1/odometry')
self.declare_parameter('cmd_vel_topic', '/cmd_vel')
self.declare_parameter('action_name', 'move_to')
self.declare_parameter('control_hz', p.control_hz)
# 增益:车 0.81×0.80,底盘限幅 0.5,短距(<1 m)为主
self.declare_parameter('kp', p.kp)
self.declare_parameter('ki', p.ki)
self.declare_parameter('kd', p.kd)
self.declare_parameter('output_limit', p.output_limit)
self.declare_parameter('integral_limit', p.integral_limit)
self.declare_parameter('deadband', p.deadband)
self.declare_parameter('min_speed', p.min_speed)
self.declare_parameter('position_tolerance', p.position_tolerance)
self.declare_parameter('stable_frames', p.stable_frames)
self.declare_parameter('timeout_sec', p.timeout_sec)
self.declare_parameter('odom_timeout_sec', p.odom_timeout_sec)
self._odom_topic = str(self.get_parameter('odom_topic').value)
self._cmd_topic = str(self.get_parameter('cmd_vel_topic').value)
self._hz = float(self.get_parameter('control_hz').value)
cfg = PIDConfig(
kp=float(self.get_parameter('kp').value),
ki=float(self.get_parameter('ki').value),
kd=float(self.get_parameter('kd').value),
output_limit=float(self.get_parameter('output_limit').value),
integral_limit=float(self.get_parameter('integral_limit').value),
deadband=float(self.get_parameter('deadband').value),
d_filter_alpha=0.3,
)
self._pid_x = PID(cfg)
self._pid_y = PID(cfg)
# 最新位姿
self._x = 0.0
self._y = 0.0
self._yaw = 0.0
self._odom_stamp = None
self._cb_group = ReentrantCallbackGroup()
self.create_subscription(
Odometry, self._odom_topic, self._on_odom, 10,
callback_group=self._cb_group)
self._pub = self.create_publisher(Twist, self._cmd_topic, 10)
self._server = ActionServer(
self,
MoveTo,
str(self.get_parameter('action_name').value),
execute_callback=self._execute,
goal_callback=lambda _goal: GoalResponse.ACCEPT,
cancel_callback=lambda _goal: CancelResponse.ACCEPT,
callback_group=self._cb_group,
)
self.get_logger().info(
f'[move] 就绪:odom={self._odom_topic} cmd={self._cmd_topic} '
f'kp={cfg.kp} 限幅={cfg.output_limit:.2f} '
f'容差={float(self.get_parameter("position_tolerance").value):.3f} m')
# ------------------------------------------------------------------ 回调
def _on_odom(self, msg: Odometry) -> None:
p = msg.pose.pose
self._x = float(p.position.x)
self._y = float(p.position.y)
q = p.orientation
self._yaw = yaw_from_quaternion(q.x, q.y, q.z, q.w)
self._odom_stamp = time.monotonic()
def _odom_fresh(self) -> bool:
if self._odom_stamp is None:
return False
limit = float(self.get_parameter('odom_timeout_sec').value)
return (time.monotonic() - self._odom_stamp) <= limit
def _stop(self) -> None:
self._pub.publish(Twist())
# ------------------------------------------------------------------ 执行
def _execute(self, goal_handle):
goal = goal_handle.request
result = MoveTo.Result()
feedback = MoveTo.Feedback()
target_x = float(goal.target_x)
target_y = float(goal.target_y)
tol = float(self.get_parameter('position_tolerance').value)
stable_need = int(self.get_parameter('stable_frames').value)
min_speed = float(self.get_parameter('min_speed').value)
timeout = float(self.get_parameter('timeout_sec').value)
if not self._odom_fresh():
self.get_logger().error('[move] 里程计无数据,拒绝执行')
goal_handle.abort()
result.success = False
result.final_error_x = target_x
result.final_error_y = target_y
return result
start_x, start_y, start_yaw = self._x, self._y, self._yaw
self._pid_x.reset()
self._pid_y.reset()
t0 = time.monotonic()
last = t0
stable = 0
circ = 0.0
last_dx = 0.0
last_dy = 0.0
self.get_logger().info(
f'[move] 开始 target=({target_x:+.3f}, {target_y:+.3f}) m')
while rclpy.ok():
if goal_handle.is_cancel_requested:
self._stop()
goal_handle.canceled()
result.success = False
result.final_error_x = target_x - last_dx
result.final_error_y = target_y - last_dy
result.duration_sec = time.monotonic() - t0
return result
now = time.monotonic()
dt = now - last
last = now
if now - t0 > timeout:
self._stop()
self.get_logger().warn(f'[move] 超时 {timeout:.1f}s')
goal_handle.abort()
result.success = False
result.final_error_x = target_x - last_dx
result.final_error_y = target_y - last_dy
result.duration_sec = now - t0
return result
if not self._odom_fresh():
self._stop()
self.get_logger().error('[move] 里程计中断,急停')
goal_handle.abort()
result.success = False
result.final_error_x = target_x - last_dx
result.final_error_y = target_y - last_dy
result.duration_sec = now - t0
return result
ex, ey, dx, dy = planar_error(
start_x, start_y, start_yaw, self._x, self._y, target_x, target_y)
last_dx, last_dy = dx, dy
if abs(ex) <= tol and abs(ey) <= tol:
stable += 1
if stable >= stable_need:
self._stop()
goal_handle.succeed()
result.success = True
result.final_error_x = ex
result.final_error_y = ey
result.duration_sec = time.monotonic() - t0
self.get_logger().info(
f'[move] 到位 误差=({ex:+.4f}, {ey:+.4f}) m '
f'耗时={result.duration_sec:.2f}s')
return result
else:
stable = 0
vx = self._pid_x.compute(ex, dt, measurement=dx)
vy = self._pid_y.compute(ey, dt, measurement=dy)
vx = apply_min_motion_speed(vx, min_speed, ex, tol)
vy = apply_min_motion_speed(vy, min_speed, ey, tol)
lim = float(self.get_parameter('output_limit').value)
vx, vy, _ = speed_limit(vx, vy, 0.0, lim, lim, 0.0)
cmd = Twist()
cmd.linear.x = vx
cmd.linear.y = vy
self._pub.publish(cmd)
circ += dt
if circ >= 0.2:
circ = 0.0
feedback.current_dx = dx
feedback.current_dy = dy
feedback.error_x = ex
feedback.error_y = ey
feedback.cmd_vx = vx
feedback.cmd_vy = vy
goal_handle.publish_feedback(feedback)
time.sleep(1.0 / max(self._hz, 1.0))
self._stop()
goal_handle.abort()
result.success = False
return result
def main(args=None):
rclpy.init(args=args)
node = MoveActionServer()
executor = MultiThreadedExecutor(num_threads=3)
try:
rclpy.spin(node, executor=executor)
except KeyboardInterrupt:
pass
finally:
node._stop()
node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,57 @@
"""MoveTo 原语的默认参数与自检。纯逻辑,不 import rclpy。
为什么参数要单独抽一层:
"输出上限不能超过底盘限幅"这类约束,如果只写在节点里,就只能等上实车
发现车不动才察觉(底盘是**静默**截断,没有任何反馈)。放在这里可以被
无 ROS 环境下的单测直接守住。
"""
from dataclasses import dataclass
# RC2027 底盘桥 techx_r2_chassis_control 的静默限幅(config/chassis_serial.yaml)
CHASSIS_MAX_LINEAR = 0.5
CHASSIS_MAX_ANGULAR = 0.5
@dataclass
class MoveParams:
control_hz: float = 30.0
kp: float = 1.6
ki: float = 0.15
kd: float = 0.0
output_limit: float = 0.45
integral_limit: float = 0.12
deadband: float = 0.004
min_speed: float = 0.03
position_tolerance: float = 0.02
stable_frames: int = 3
timeout_sec: float = 20.0
odom_timeout_sec: float = 0.3
def default_params() -> MoveParams:
return MoveParams()
def validate(p: MoveParams) -> list:
"""返回问题列表,空列表表示通过。"""
problems = []
if p.output_limit > CHASSIS_MAX_LINEAR:
problems.append(
f'output_limit={p.output_limit} 超过底盘限幅 {CHASSIS_MAX_LINEAR},'
'会被静默截断')
if p.output_limit <= 0.0:
problems.append('output_limit 必须为正')
if p.min_speed > p.output_limit:
problems.append('min_speed 不能大于 output_limit,否则永远顶在限幅上')
if p.position_tolerance <= 0.0:
problems.append('position_tolerance 必须为正')
if p.ki > 0.0 and p.integral_limit <= 0.0:
problems.append('启用积分却没有 integral_limit,等于没有抗饱和')
if p.stable_frames < 1:
problems.append('stable_frames 至少为 1')
if p.control_hz <= 0.0:
problems.append('control_hz 必须为正')
if p.odom_timeout_sec <= 1.0 / max(p.control_hz, 1e-6):
problems.append('odom_timeout_sec 小于一个控制周期,会误判断流')
return problems
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>d_move_actions</name>
<version>0.1.0</version>
<description>方案四:车体系 XY 位移 PID Action 服务器(MoveTo 原语)。</description>
<maintainer email="[email protected]">RC2027 BR</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_python</buildtool_depend>
<exec_depend>rclpy</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>d_interfaces</exec_depend>
<exec_depend>d_pid_core</exec_depend>
<test_depend>python3-pytest</test_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
@@ -0,0 +1 @@
#
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/d_move_actions
[install]
install_scripts=$base/lib/d_move_actions
@@ -0,0 +1,26 @@
from setuptools import setup
package_name = 'd_move_actions'
setup(
name=package_name,
version='0.1.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml', 'README.md']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='RC2027 BR',
maintainer_email='[email protected]',
description='车体系 XY 位移 PID Action 服务器',
license='Apache-2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'move_action_server = d_move_actions.move_action_server:main',
],
},
)
@@ -0,0 +1,53 @@
"""MoveTo 参数自检单测:守住"输出不超过底盘限幅"这条硬约束。"""
import pytest
from d_move_actions.params import (
CHASSIS_MAX_LINEAR,
MoveParams,
default_params,
validate,
)
def test_defaults_are_valid():
assert validate(default_params()) == []
def test_default_output_limit_below_chassis_clamp():
assert default_params().output_limit <= CHASSIS_MAX_LINEAR
def test_rejects_output_limit_above_chassis():
p = default_params()
p.output_limit = 1.5
problems = validate(p)
assert any('超过底盘限幅' in item for item in problems)
def test_rejects_non_positive_output_limit():
p = default_params()
p.output_limit = 0.0
assert validate(p) != []
def test_rejects_min_speed_above_limit():
p = MoveParams(min_speed=0.6, output_limit=0.45)
assert any('min_speed' in item for item in validate(p))
def test_rejects_integral_without_limit():
p = MoveParams(ki=0.2, integral_limit=0.0)
assert any('抗饱和' in item for item in validate(p))
def test_rejects_odom_timeout_shorter_than_period():
p = MoveParams(control_hz=30.0, odom_timeout_sec=0.01)
assert any('断流' in item for item in validate(p))
def test_rejects_bad_tolerance_and_frames():
p = MoveParams(position_tolerance=0.0, stable_frames=0)
problems = validate(p)
assert any('position_tolerance' in item for item in problems)
assert any('stable_frames' in item for item in problems)
@@ -0,0 +1,38 @@
# d_orient_actions — 绝对 yaw PID 原语
## 为什么用绝对角而不是相对角
行为树里"原地转 90°"如果写成相对角(转多少度),前一条动作超时少转了 5°,
这个 5° 会一路累积到后面所有动作;写成 **odom 系绝对 yaw**,每一步都回到
绝对参考,误差不累积。代价是调用方要把场地朝向换算成 odom yaw。
## 接口
`d_interfaces/action/OrientTo.action`
```
goal: target_yaw # odom 系绝对 yaw,rad
result: success, final_error_rad, duration_sec
feedback: current_yaw, error_rad, cmd_wz
```
## 角速度符号
本节点按 REP-103 输出:**正值 = 逆时针**。
底盘桥 `techx_r2_chassis_control` 配置 `omega_sign: -1.0`,由它在打包时翻转
(实车实测电机方向与 REP-103 相反)。**不要在本节点再翻一次**——翻两次
等于没翻,症状是"给正角速度车往右转、PI 正反馈原地打转"。
## 参数
`d_orient_actions/params.py`,启动自检。守住的两条:
- `output_limit <= 0.5`(底盘角速度静默限幅)
- `deadband < yaw_tolerance`(否则永远判不到位)
## 运行
```bash
ros2 run d_orient_actions orient_action_server
ros2 action send_goal /orient_to d_interfaces/action/OrientTo "{target_yaw: 1.5708}"
```
@@ -0,0 +1,32 @@
"""让 pytest 在未 source ROS 的环境下直接跑源码目录。
同时把同工作空间的 d_pid_core 源码目录加进来——单测跑在源码树上,
不依赖 colcon build 之后的 install 布局。
"""
import os
import sys
def _find_src_root(start: str):
cur = start
for _ in range(8):
if os.path.isdir(os.path.join(cur, 'primitives')) and \
os.path.isdir(os.path.join(cur, 'interfaces')):
return cur
parent = os.path.dirname(cur)
if parent == cur:
break
cur = parent
return None
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
_SRC = _find_src_root(_HERE)
if _SRC is not None:
_core = os.path.join(_SRC, 'primitives', 'd_pid_core')
if os.path.isdir(_core) and _core not in sys.path:
sys.path.append(_core)
@@ -0,0 +1 @@
"""方案四的 Action 原语包。"""
@@ -0,0 +1,224 @@
"""odom 系绝对 yaw 的 PID Action 服务器(OrientTo 原语)。
只出 angular.z。目标 yaw 用 **odom 系绝对角**,不是相对角:
行为树里"转到 90°"这种动作,如果写成相对角,一旦上一条原语因超时少转了 5°,
误差会一路累积到后面所有动作。绝对角天然免累积。
注意角速度符号:底盘桥配置 `omega_sign: -1.0`(实车转向与 REP-103 相反),
本节点按 REP-103 输出正值=逆时针,符号适配由底盘桥负责,**这里不要自己再翻**。
"""
import time
import rclpy
from rclpy.action import ActionServer, CancelResponse, GoalResponse
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from d_interfaces.action import OrientTo
from d_orient_actions.params import default_params, validate
from d_pid_core import PID, PIDConfig, angle_error, clamp, normalize_angle, yaw_from_quaternion
class OrientActionServer(Node):
"""把 target_yaw 变成 angular.z 的 PD。"""
def __init__(self):
super().__init__('d_orient_action_server')
p = default_params()
problems = validate(p)
if problems:
for item in problems:
self.get_logger().error(f'[orient] 参数自检失败:{item}')
raise ValueError('d_orient_actions 默认参数非法')
self.declare_parameter('odom_topic', '/odin1/odometry')
self.declare_parameter('cmd_vel_topic', '/cmd_vel')
self.declare_parameter('action_name', 'orient_to')
self.declare_parameter('control_hz', p.control_hz)
self.declare_parameter('kp', p.kp)
self.declare_parameter('ki', p.ki)
self.declare_parameter('kd', p.kd)
self.declare_parameter('output_limit', p.output_limit)
self.declare_parameter('integral_limit', p.integral_limit)
self.declare_parameter('deadband_rad', p.deadband_rad)
self.declare_parameter('min_speed_rad', p.min_speed_rad)
self.declare_parameter('yaw_tolerance', p.yaw_tolerance)
self.declare_parameter('stable_frames', p.stable_frames)
self.declare_parameter('timeout_sec', p.timeout_sec)
self.declare_parameter('odom_timeout_sec', p.odom_timeout_sec)
self._odom_topic = str(self.get_parameter('odom_topic').value)
self._cmd_topic = str(self.get_parameter('cmd_vel_topic').value)
self._hz = float(self.get_parameter('control_hz').value)
cfg = PIDConfig(
kp=float(self.get_parameter('kp').value),
ki=float(self.get_parameter('ki').value),
kd=float(self.get_parameter('kd').value),
output_limit=float(self.get_parameter('output_limit').value),
integral_limit=float(self.get_parameter('integral_limit').value),
deadband=float(self.get_parameter('deadband_rad').value),
d_filter_alpha=0.3,
)
self._pid = PID(cfg)
self._yaw = 0.0
self._odom_stamp = None
self._cb_group = ReentrantCallbackGroup()
self.create_subscription(
Odometry, self._odom_topic, self._on_odom, 10,
callback_group=self._cb_group)
self._pub = self.create_publisher(Twist, self._cmd_topic, 10)
self._server = ActionServer(
self,
OrientTo,
str(self.get_parameter('action_name').value),
execute_callback=self._execute,
goal_callback=lambda _goal: GoalResponse.ACCEPT,
cancel_callback=lambda _goal: CancelResponse.ACCEPT,
callback_group=self._cb_group,
)
self.get_logger().info(
f'[orient] 就绪:odom={self._odom_topic} 容差='
f'{float(self.get_parameter("yaw_tolerance").value):.4f} rad')
# ------------------------------------------------------------------ 回调
def _on_odom(self, msg: Odometry) -> None:
q = msg.pose.pose.orientation
self._yaw = yaw_from_quaternion(q.x, q.y, q.z, q.w)
self._odom_stamp = time.monotonic()
def _odom_fresh(self) -> bool:
if self._odom_stamp is None:
return False
return (time.monotonic() - self._odom_stamp) <= float(
self.get_parameter('odom_timeout_sec').value)
def _stop(self) -> None:
self._pub.publish(Twist())
# ------------------------------------------------------------------ 执行
def _execute(self, goal_handle):
target = normalize_angle(float(goal_handle.request.target_yaw))
result = OrientTo.Result()
feedback = OrientTo.Feedback()
tol = float(self.get_parameter('yaw_tolerance').value)
stable_need = int(self.get_parameter('stable_frames').value)
min_speed = float(self.get_parameter('min_speed_rad').value)
timeout = float(self.get_parameter('timeout_sec').value)
if not self._odom_fresh():
self.get_logger().error('[orient] 里程计无数据,拒绝执行')
goal_handle.abort()
result.success = False
result.final_error_rad = target
return result
self._pid.reset()
t0 = time.monotonic()
last = t0
stable = 0
err = angle_error(target, self._yaw)
self.get_logger().info(
f'[orient] 开始 target={target:+.4f} rad ({target * 57.2958:+.1f}°),'
f'当前误差 {err * 57.2958:+.1f}°')
while rclpy.ok():
now = time.monotonic()
dt = now - last
last = now
if goal_handle.is_cancel_requested:
self._stop()
goal_handle.canceled()
result.success = False
result.final_error_rad = err
result.duration_sec = now - t0
return result
if now - t0 > timeout:
self._stop()
self.get_logger().warn(
f'[orient] 超时 {timeout:.1f}s,残余 {err * 57.2958:+.1f}°')
goal_handle.abort()
result.success = False
result.final_error_rad = err
result.duration_sec = now - t0
return result
if not self._odom_fresh():
self._stop()
self.get_logger().error('[orient] 里程计中断,急停')
goal_handle.abort()
result.success = False
result.final_error_rad = err
result.duration_sec = now - t0
return result
err = angle_error(target, self._yaw)
if abs(err) <= tol:
stable += 1
if stable >= stable_need:
self._stop()
goal_handle.succeed()
result.success = True
result.final_error_rad = err
result.duration_sec = time.monotonic() - t0
self.get_logger().info(
f'[orient] 到位 残余 {err * 57.2958:+.2f}° '
f'耗时={result.duration_sec:.2f}s')
return result
else:
stable = 0
wz = self._pid.compute(err, dt, measurement=self._yaw)
if wz != 0.0 and abs(wz) < min_speed:
wz = min_speed if wz > 0.0 else -min_speed
if abs(err) <= tol:
wz = 0.0
lim = float(self.get_parameter('output_limit').value)
wz = clamp(wz, -lim, lim)
cmd = Twist()
cmd.angular.z = wz
self._pub.publish(cmd)
feedback.current_yaw = self._yaw
feedback.error_rad = err
feedback.cmd_wz = wz
goal_handle.publish_feedback(feedback)
time.sleep(1.0 / max(self._hz, 1.0))
self._stop()
goal_handle.abort()
result.success = False
return result
def main(args=None):
rclpy.init(args=args)
node = OrientActionServer()
executor = MultiThreadedExecutor(num_threads=3)
try:
rclpy.spin(node, executor=executor)
except KeyboardInterrupt:
pass
finally:
node._stop()
node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,59 @@
"""OrientTo 原语的默认参数与自检。纯逻辑,不 import rclpy。"""
import math
from dataclasses import dataclass
# 底盘角速度静默限幅(rad/s)
CHASSIS_MAX_ANGULAR = 0.5
@dataclass
class OrientParams:
control_hz: float = 50.0
kp: float = 2.2
ki: float = 0.0
kd: float = 0.25
output_limit: float = 0.45
integral_limit: float = 0.0
deadband_rad: float = 0.0087 # 0.5°
min_speed_rad: float = 0.08 # 低于此角速度轮子不转
yaw_tolerance: float = 0.0175 # 1°
stable_frames: int = 5
timeout_sec: float = 15.0
odom_timeout_sec: float = 0.3
def default_params() -> OrientParams:
return OrientParams()
def validate(p: OrientParams) -> list:
problems = []
if p.output_limit > CHASSIS_MAX_ANGULAR:
problems.append(
f'output_limit={p.output_limit} 超过底盘角速度限幅 {CHASSIS_MAX_ANGULAR},'
'会被静默截断')
if p.output_limit <= 0.0:
problems.append('output_limit 必须为正')
if p.min_speed_rad > p.output_limit:
problems.append('min_speed_rad 不能大于 output_limit')
if p.yaw_tolerance <= 0.0:
problems.append('yaw_tolerance 必须为正')
if p.deadband_rad >= p.yaw_tolerance:
problems.append('deadband 不小于容差,会永远判不到位')
if p.ki > 0.0 and p.integral_limit <= 0.0:
problems.append('启用积分却没有 integral_limit,等于没有抗饱和')
if p.stable_frames < 1:
problems.append('stable_frames 至少为 1')
if p.odom_timeout_sec <= 1.0 / max(p.control_hz, 1e-6):
problems.append('odom_timeout_sec 小于一个控制周期,会误判断流')
return problems
def wrap_to_tolerance_matrix() -> dict:
"""给单测/文档用的角度样例表:目标、当前、期望误差(rad)。"""
return {
'same': (0.0, 0.0, 0.0),
'quarter': (math.pi / 2, 0.0, math.pi / 2),
'across_pi': (math.radians(-179), math.radians(179), math.radians(2)),
}
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>d_orient_actions</name>
<version>0.1.0</version>
<description>方案四:odom 系绝对 yaw 的 PID Action 服务器(OrientTo 原语)。</description>
<maintainer email="[email protected]">RC2027 BR</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_python</buildtool_depend>
<exec_depend>rclpy</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>d_interfaces</exec_depend>
<exec_depend>d_pid_core</exec_depend>
<test_depend>python3-pytest</test_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/d_orient_actions
[install]
install_scripts=$base/lib/d_orient_actions
@@ -0,0 +1,26 @@
from setuptools import setup
package_name = 'd_orient_actions'
setup(
name=package_name,
version='0.1.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml', 'README.md']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='RC2027 BR',
maintainer_email='[email protected]',
description='odom 系绝对 yaw 的 PID Action 服务器',
license='Apache-2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'orient_action_server = d_orient_actions.orient_action_server:main',
],
},
)
@@ -0,0 +1,52 @@
"""OrientTo 参数自检 + 角度边界单测。"""
import math
import pytest
from d_orient_actions.params import (
CHASSIS_MAX_ANGULAR,
OrientParams,
default_params,
validate,
wrap_to_tolerance_matrix,
)
from d_pid_core import angle_error
def test_defaults_are_valid():
assert validate(default_params()) == []
def test_default_limit_below_chassis_angular_clamp():
assert default_params().output_limit <= CHASSIS_MAX_ANGULAR
def test_default_tolerance_is_one_degree():
assert default_params().yaw_tolerance == pytest.approx(math.radians(1.0), abs=1e-3)
def test_rejects_limit_above_chassis():
p = default_params()
p.output_limit = 3.0
assert any('超过底盘角速度限幅' in item for item in validate(p))
def test_rejects_deadband_not_below_tolerance():
p = OrientParams(deadband_rad=0.05, yaw_tolerance=0.0175)
assert any('永远判不到位' in item for item in validate(p))
def test_rejects_min_speed_above_limit():
p = OrientParams(min_speed_rad=0.8, output_limit=0.45)
assert validate(p) != []
def test_rejects_integral_without_limit():
p = OrientParams(ki=0.5, integral_limit=0.0)
assert any('抗饱和' in item for item in validate(p))
def test_wrap_matrix_matches_shortest_path():
for name, (target, current, expected) in wrap_to_tolerance_matrix().items():
assert angle_error(target, current) == pytest.approx(expected, abs=1e-9), name
@@ -0,0 +1,14 @@
# d_pid_core — 纯逻辑控制内核算
本包是整个方案四里**唯一不 import rclpy 的 Python 包**。存在意义只有一条:
让 PID、角度归一、车体系投影这些"算错了就是撞墙"的数学,可以在
**没有 ROS、没有硬件、没有 source 任何 setup.bash** 的环境下被测试。
命名约定:
- 所有函数/类都是纯函数或纯状态机,不订阅话题、不碰时间源(dt 由调用方传入)。
- 时间单位 s,长度单位 m,角度单位 rad。
为什么单独成包而不是塞进 d_move_actions:
- 一旦 `import rclpy` 出现在模块顶层,`pytest` 就必须先 source ROS 才能 import,
验收标准里的"未 source ROS 也能跑单测"立刻失效。
- 结构上强制了"逻辑 / ROS 壳"分界,日后换掉 rclpy 或加仿真回放不用动数学。
@@ -0,0 +1,15 @@
"""让 `pytest` 在**未 source ROS** 的环境下直接跑源码目录。
机制:把本包所在目录塞进 sys.path,于是 `import d_pid_core` 命中源码树,
而不是 install/ 下的副本。这样单测不依赖 colcon build、不依赖 ROS 环境变量。
用法(任意目录均可):
/usr/bin/python3 -m pytest nav2_ws/src/primitives/d_pid_core/test -q
"""
import os
import sys
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
@@ -0,0 +1,34 @@
"""纯逻辑内核导出。
这里刻意不写任何 `import rclpy`:本包被 pytest 直接以源码目录方式导入,
一旦顶层引入 ROS Python 绑定,未 source 环境下的单测就会失败。
"""
from .angles import (
angle_error,
normalize_angle,
quaternion_from_yaw,
yaw_from_quaternion,
)
from .motion import (
apply_min_motion_speed,
clamp,
planar_delta_in_start_frame,
planar_error,
speed_limit,
)
from .pid import PID, PIDConfig
__all__ = [
'angle_error',
'normalize_angle',
'quaternion_from_yaw',
'yaw_from_quaternion',
'apply_min_motion_speed',
'clamp',
'planar_delta_in_start_frame',
'planar_error',
'speed_limit',
'PID',
'PIDConfig',
]
@@ -0,0 +1,35 @@
"""角度工具:归一化、最短误差、四元数↔yaw。纯逻辑,不依赖 tf2。"""
import math
TWO_PI = 2.0 * math.pi
def normalize_angle(angle: float) -> float:
"""把角度归一化到 (-pi, pi]。"""
a = math.fmod(angle + math.pi, TWO_PI)
if a <= 0.0:
a += TWO_PI
return a - math.pi
def angle_error(target: float, current: float) -> float:
"""目标相对当前的最短角差,落在 (-pi, pi]。
为什么不用 target - current 直接减:+179° 到 -179° 的"实际只差 2°"
会被算成 -358°,输出直接顶到反方向限幅,车会原地甩头。
"""
return normalize_angle(target - current)
def yaw_from_quaternion(x: float, y: float, z: float, w: float) -> float:
"""四元数 → yaw(ZYX 顺序)。"""
siny_cosp = 2.0 * (w * z + x * y)
cosy_cosp = 1.0 - 2.0 * (y * y + z * z)
return math.atan2(siny_cosp, cosy_cosp)
def quaternion_from_yaw(yaw: float) -> tuple:
"""yaw → 四元数 (x, y, z, w)。"""
half = 0.5 * yaw
return (0.0, 0.0, math.sin(half), math.cos(half))
@@ -0,0 +1,71 @@
"""平面运动学工具:限幅、最小起步速度、车体系投影。纯逻辑,不依赖 ROS。"""
import math
def clamp(value: float, low: float, high: float) -> float:
if value < low:
return low
if value > high:
return high
return value
def speed_limit(vx: float, vy: float, wz: float,
vx_limit: float, vy_limit: float, wz_limit: float) -> tuple:
"""三轴独立限幅。
RC2027 底盘桥(techx_r2_chassis_control)对 /cmd_vel 做**静默**截断
(0.5 / 0.5 / 0.5),上游收不到任何反馈。所以限幅必须在原语层先做一遍,
否则 PID 会以为"已经给到位了",误差靠积分硬顶,实际车不动。
"""
return (clamp(vx, -vx_limit, vx_limit),
clamp(vy, -vy_limit, vy_limit),
clamp(wz, -wz_limit, wz_limit))
def apply_min_motion_speed(value: float, minimum: float,
error: float, tolerance: float) -> float:
"""把"有输出但太小"的速度抬到最小可动速度,或直接归零。
麦轮底盘有静摩擦:给 0.02 m/s 时轮子根本不转,PID 却认为在动作,
误差不降、积分慢慢涨,最后猛地窜一下。这里做两件事:
- |error| <= tolerance:直接 0(别在容差边界来回蹭)
- 0 < |value| < minimum:抬到 ±minimum(借 error 的符号判方向)
"""
if abs(error) <= tolerance:
return 0.0
if value == 0.0:
return 0.0
if abs(value) < minimum:
sign = 1.0 if value > 0.0 else -1.0
return sign * minimum
return value
def planar_delta_in_start_frame(start_x: float, start_y: float, start_yaw: float,
cur_x: float, cur_y: float) -> tuple:
"""把"世界系的位移"投影到 **goal 起始时刻的车体系**。
为什么要以起点车体系为基准,而不是当前车体系:
目标 (target_x, target_y) 是相对起步姿态的固定量。若每周期都用当前 yaw
投影,车一边平移一边轻微转头时,目标会跟着转,形成"追着自己跑"的正反馈。
"""
dx_world = cur_x - start_x
dy_world = cur_y - start_y
c = math.cos(start_yaw)
s = math.sin(start_yaw)
dx_body = c * dx_world + s * dy_world
dy_body = -s * dx_world + c * dy_world
return dx_body, dy_body
def planar_error(start_x: float, start_y: float, start_yaw: float,
cur_x: float, cur_y: float,
target_x: float, target_y: float) -> tuple:
"""返回 (error_x, error_y, delta_x, delta_y),单位 m。
error_* = target - delta:正值表示"还差这么多要往这个方向走"。
"""
dx, dy = planar_delta_in_start_frame(start_x, start_y, start_yaw, cur_x, cur_y)
return target_x - dx, target_y - dy, dx, dy
@@ -0,0 +1,114 @@
"""位置式 PID,带抗积分饱和与微分先行。纯逻辑,不依赖 ROS。"""
import math
from dataclasses import dataclass
@dataclass
class PIDConfig:
"""一组 PID 增益与限幅。
为什么把限幅和增益放一起:Action 原语里"输出多少"必须和"底盘能吃多少"对齐
(RC2027 底盘静默限幅 0.5),把这些常量散落在节点里最容易漏改一侧。
"""
kp: float
ki: float = 0.0
kd: float = 0.0
# 输出绝对值上限(m/s 或 rad/s)
output_limit: float = 0.45
# 积分**输出项**上限,不是误差积分的上限:量纲与输出一致,好调
integral_limit: float = 0.2
# 误差死区:|error| <= deadband 时输出 0,抑制稳态抖动
deadband: float = 0.0
# 微分低通系数(0 < alpha <= 1),1 表示不滤波
d_filter_alpha: float = 1.0
class PID:
"""单轴位置式 PID。
三项约定,都是为了实车不抖:
1. **条件积分**:输出已饱和且误差同向时不再累加,避免"饱和后积分继续涨"。
2. **微分先行**:优先对测量值(measurement)求导,避免目标突变时的微分冲击。
3. **dt 异常保护**:dt <= 0 或 dt > max_dt 时按一步正常 dt 处理,
防止 ROS 定时器抖动/暂停恢复瞬间除零或积分爆炸。
"""
MAX_DT = 0.5
def __init__(self, cfg: PIDConfig):
self.cfg = cfg
self._integral = 0.0
self._prev_error = None
self._prev_meas = None
self._d_filtered = 0.0
# ------------------------------------------------------------------ 状态
def reset(self) -> None:
self._integral = 0.0
self._prev_error = None
self._prev_meas = None
self._d_filtered = 0.0
@property
def integral(self) -> float:
return self._integral
# ------------------------------------------------------------------ 计算
def compute(self, error: float, dt: float, measurement: float | None = None) -> float:
"""返回本周期输出(已限幅)。
error : 目标 - 当前
dt : 距上周期的时间,s
measurement : 当前测量值;给了就走"微分先行",没给就对误差求导
"""
cfg = self.cfg
if dt is None or dt <= 0.0 or not math.isfinite(dt):
dt = 0.0
elif dt > self.MAX_DT:
dt = self.MAX_DT
# 死区
if abs(error) <= cfg.deadband:
error = 0.0
p_term = cfg.kp * error
# 微分
if cfg.kd != 0.0 and dt > 0.0:
if measurement is not None:
base = measurement
prev = self._prev_meas
self._prev_meas = base
raw_d = 0.0 if prev is None else -(base - prev) / dt
else:
prev = self._prev_error
self._prev_error = error
raw_d = 0.0 if prev is None else (error - prev) / dt
alpha = min(max(cfg.d_filter_alpha, 1e-3), 1.0)
self._d_filtered += alpha * (raw_d - self._d_filtered)
d_term = cfg.kd * self._d_filtered
else:
d_term = 0.0
# 条件积分:输出饱和且误差同向时不累加
tentative = p_term + self._integral + d_term
saturated = abs(tentative) >= cfg.output_limit
same_sign = (tentative > 0 and error > 0) or (tentative < 0 and error < 0)
if dt > 0.0 and not (saturated and same_sign):
self._integral += cfg.ki * error * dt
self._integral = _clamp(self._integral, -cfg.integral_limit, cfg.integral_limit)
out = p_term + self._integral + d_term
return _clamp(out, -cfg.output_limit, cfg.output_limit)
def _clamp(value: float, low: float, high: float) -> float:
if value < low:
return low
if value > high:
return high
return value
@@ -0,0 +1,17 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>d_pid_core</name>
<version>0.1.0</version>
<description>方案四 Action 原语的纯逻辑内核:PID、角度归一、车体系投影。不依赖 rclpy。</description>
<maintainer email="[email protected]">RC2027 BR</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_python</buildtool_depend>
<test_depend>python3-pytest</test_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>
@@ -0,0 +1 @@
#
@@ -0,0 +1,4 @@
[develop]
script_dir=$base/lib/d_pid_core
[install]
install_scripts=$base/lib/d_pid_core
@@ -0,0 +1,26 @@
from glob import glob
from setuptools import setup
package_name = 'd_pid_core'
setup(
name=package_name,
version='0.1.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml', 'README.md']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='RC2027 BR',
maintainer_email='[email protected]',
description='纯逻辑 PID / 角度 / 车体系投影内核,不依赖 rclpy',
license='Apache-2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [],
},
)
@@ -0,0 +1,49 @@
"""角度工具单测。"""
import math
import pytest
from d_pid_core.angles import (
angle_error,
normalize_angle,
quaternion_from_yaw,
yaw_from_quaternion,
)
PI = math.pi
def test_normalize_basic():
assert normalize_angle(0.0) == pytest.approx(0.0)
assert normalize_angle(2 * PI) == pytest.approx(0.0)
assert normalize_angle(PI) == pytest.approx(PI)
def test_normalize_wraps_beyond_range():
assert normalize_angle(3 * PI / 2) == pytest.approx(-PI / 2)
assert normalize_angle(-3 * PI / 2) == pytest.approx(PI / 2)
assert normalize_angle(5 * PI) == pytest.approx(PI)
def test_angle_error_crosses_boundary_short_way():
"""+179° → -179° 实际只差 2°,绝不能算成 -358°。"""
err = angle_error(math.radians(-179), math.radians(179))
assert abs(err) == pytest.approx(math.radians(2), abs=1e-9)
assert err > 0
def test_angle_error_zero_on_equal():
assert angle_error(1.0, 1.0) == pytest.approx(0.0)
def test_yaw_quaternion_roundtrip():
for yaw in (-3.0, -1.0, 0.0, 0.7, 3.0):
qx, qy, qz, qw = quaternion_from_yaw(yaw)
assert yaw_from_quaternion(qx, qy, qz, qw) == pytest.approx(yaw, abs=1e-9)
def test_quaternion_identity():
qx, qy, qz, qw = quaternion_from_yaw(0.0)
assert (qx, qy, qz) == pytest.approx((0.0, 0.0, 0.0))
assert qw == pytest.approx(1.0)
@@ -0,0 +1,77 @@
"""平面运动学工具单测。"""
import math
import pytest
from d_pid_core.motion import (
apply_min_motion_speed,
clamp,
planar_delta_in_start_frame,
planar_error,
speed_limit,
)
def test_clamp():
assert clamp(5.0, -1.0, 1.0) == pytest.approx(1.0)
assert clamp(-5.0, -1.0, 1.0) == pytest.approx(-1.0)
assert clamp(0.3, -1.0, 1.0) == pytest.approx(0.3)
def test_speed_limit_matches_chassis_clamp():
"""底盘桥限幅 0.5,原语层必须先截断,否则误差靠积分硬顶。"""
vx, vy, wz = speed_limit(2.0, -2.0, 3.0, 0.5, 0.5, 0.5)
assert (vx, vy, wz) == pytest.approx((0.5, -0.5, 0.5))
def test_min_motion_speed_lifts_small_output():
assert apply_min_motion_speed(0.02, 0.05, error=0.3, tolerance=0.01) == pytest.approx(0.05)
assert apply_min_motion_speed(-0.02, 0.05, error=-0.3, tolerance=0.01) == pytest.approx(-0.05)
def test_min_motion_speed_zero_inside_tolerance():
assert apply_min_motion_speed(0.02, 0.05, error=0.005, tolerance=0.01) == pytest.approx(0.0)
def test_min_motion_speed_passes_through_large_output():
assert apply_min_motion_speed(0.3, 0.05, error=0.5, tolerance=0.01) == pytest.approx(0.3)
def test_min_motion_speed_keeps_zero():
assert apply_min_motion_speed(0.0, 0.05, error=0.5, tolerance=0.01) == pytest.approx(0.0)
def test_delta_zero_motion():
dx, dy = planar_delta_in_start_frame(1.0, 2.0, 0.7, 1.0, 2.0)
assert (dx, dy) == pytest.approx((0.0, 0.0))
def test_delta_forward_when_yaw_zero():
dx, dy = planar_delta_in_start_frame(0.0, 0.0, 0.0, 1.0, 0.0)
assert (dx, dy) == pytest.approx((1.0, 0.0))
def test_delta_left_is_positive_y():
dx, dy = planar_delta_in_start_frame(0.0, 0.0, 0.0, 0.0, 0.5)
assert (dx, dy) == pytest.approx((0.0, 0.5))
def test_delta_respects_start_heading():
"""起点车头朝 +y(yaw=90°)时,世界系 +y 前进应投影成 body +x。"""
dx, dy = planar_delta_in_start_frame(0.0, 0.0, math.pi / 2, 0.0, 1.0)
assert dx == pytest.approx(1.0, abs=1e-9)
assert dy == pytest.approx(0.0, abs=1e-9)
def test_planar_error_signs():
# 起点朝 +x,已前进 0.3,目标 1.0 → 还差 +0.7
ex, ey, dx, dy = planar_error(0.0, 0.0, 0.0, 0.3, 0.0, 1.0, 0.0)
assert (ex, ey) == pytest.approx((0.7, 0.0))
assert (dx, dy) == pytest.approx((0.3, 0.0))
def test_planar_error_zero_when_arrived():
ex, ey, _, _ = planar_error(2.0, 2.0, 1.0, 2.0 + math.cos(1.0), 2.0 + math.sin(1.0), 1.0, 0.0)
assert ex == pytest.approx(0.0, abs=1e-9)
assert ey == pytest.approx(0.0, abs=1e-9)
@@ -0,0 +1,91 @@
"""PID 内核单测。可在未 source ROS 的环境下运行。"""
import math
import pytest
from d_pid_core.pid import PID, PIDConfig
def test_proportional_only():
pid = PID(PIDConfig(kp=2.0, output_limit=10.0))
assert pid.compute(1.0, 0.1) == pytest.approx(2.0)
assert pid.compute(-0.5, 0.1) == pytest.approx(-1.0)
def test_output_is_clamped():
pid = PID(PIDConfig(kp=100.0, output_limit=0.45))
assert pid.compute(10.0, 0.1) == pytest.approx(0.45)
assert pid.compute(-10.0, 0.1) == pytest.approx(-0.45)
def test_deadband_suppresses_output():
pid = PID(PIDConfig(kp=1.0, deadband=0.05, output_limit=1.0))
assert pid.compute(0.03, 0.1) == pytest.approx(0.0)
assert pid.compute(0.10, 0.1) == pytest.approx(0.10)
def test_integral_accumulates_then_saturates():
pid = PID(PIDConfig(kp=0.0, ki=1.0, output_limit=10.0, integral_limit=0.2))
pid.compute(1.0, 0.1)
assert pid.integral == pytest.approx(0.1)
for _ in range(50):
pid.compute(1.0, 0.1)
assert pid.integral == pytest.approx(0.2)
def test_anti_windup_stops_integration_when_saturated():
# kp=10 会让 e=1 直接饱和,此时 integrator 不该再涨
pid = PID(PIDConfig(kp=10.0, ki=1.0, output_limit=1.0, integral_limit=10.0))
for _ in range(20):
pid.compute(1.0, 0.1)
assert pid.integral == pytest.approx(0.0)
def test_integral_unwinds_when_error_reverses():
"""误差反向后积分必须能退,否则"冲过头再慢慢爬回来"这种症状会一直在。"""
pid = PID(PIDConfig(kp=0.0, ki=1.0, output_limit=1.0, integral_limit=0.5))
for _ in range(3):
pid.compute(1.0, 0.1) # 未饱和,积分正常累加
before = pid.integral
assert before > 0.0
pid.compute(-1.0, 0.1) # 反向,允许退饱和积分
assert pid.integral < before
def test_derivative_uses_measurement_not_error_step():
"""目标阶跃时不该有微分冲击:测量值没变,D 项就该是 0。"""
pid = PID(PIDConfig(kp=0.0, kd=1.0, output_limit=10.0))
pid.compute(0.5, 0.1, measurement=0.0)
out = pid.compute(5.0, 0.1, measurement=0.0) # error 阶跃,measurement 不变
assert out == pytest.approx(0.0)
def test_derivative_responds_to_measurement_change():
pid = PID(PIDConfig(kp=0.0, kd=1.0, output_limit=10.0))
pid.compute(0.0, 0.1, measurement=0.0)
out = pid.compute(0.0, 0.1, measurement=0.1) # 测量前进 0.1 m / 0.1 s
assert out == pytest.approx(-1.0)
def test_nonpositive_dt_is_ignored():
pid = PID(PIDConfig(kp=0.0, ki=1.0, output_limit=10.0, integral_limit=1.0))
pid.compute(1.0, 0.0)
pid.compute(1.0, -1.0)
pid.compute(1.0, float('nan'))
assert pid.integral == pytest.approx(0.0)
assert math.isfinite(pid.compute(1.0, 0.1))
def test_huge_dt_is_capped():
"""暂停恢复时定时器可能报几秒的 dt,不能让它一次性灌爆积分。"""
pid = PID(PIDConfig(kp=0.0, ki=1.0, output_limit=100.0, integral_limit=100.0))
pid.compute(1.0, 100.0)
assert pid.integral == pytest.approx(pid.MAX_DT)
def test_reset_clears_state():
pid = PID(PIDConfig(kp=1.0, ki=1.0, output_limit=10.0, integral_limit=1.0))
pid.compute(1.0, 0.1)
pid.reset()
assert pid.integral == pytest.approx(0.0)
@@ -0,0 +1,43 @@
# d_ramp_drive — 四段速度曲线 + 航向保持
## 为什么需要它
坡道是 Nav2 的天然盲区:2D 投影把点云压成平面后,车体一旦俯仰,
"离地高度带"就整体漂移,costmap 时真时假。参考实现的做法是**不让 Nav2 上坡**——
暂停 Nav2,交给固定速度曲线直行,靠 yaw PD 保方向,坡顶后恢复。
## 四段曲线
| 阶段 | 速度 | 为什么 |
|---|---|---|
| `GROUND` | 0.20 | 上坡前对准,横移纠偏在这段 |
| `CLIMB_INIT` | 0.28 | 前轮刚吃坡,给一点动量,太小会在坡脚反复打滑 |
| `CLIMB_FULL` | 0.40 | 全轮在坡面:越慢侧滑累积越多 |
| `SUMMIT_APPROACH` | 0.15 | 坡顶过渡最容易被甩方向,也最容易撞东西 |
| `CREEP` | 0.12 | 距目标 < 5 cm 的收尾 |
切换靠里程计 `z_rise`(相对起点的抬升),阈值 `climb_init_z=0.10`、
`summit_z=0.47`。阶段**只前进不回退**:z 抖动时来回切档等于在坡面上
自己制造冲击载荷;真的滑下来属于失败,由 `is_slipping()` 检测并中止。
## 与参考实现的差异(重要)
Rc2026 用的是 **0.5 / 0.7 / 0.7 / 0.3**。RC2027 底盘桥限幅 0.5 且**静默截断**,
0.7 的两段会被压成 0.5——曲线形状直接失真(中段两档并成一档)。
这里不是等比缩小,而是按"何时该慢、何时该快"重新标定,
并用 `validate()` 把"任一段超过 0.5"变成启动期错误。
## 为什么用 yaw 差分而不是 twist.angular.z
400 Hz IMU 的角速度噪声直接进 D 项会把舵量打成锯齿;yaw 差分天然低通。
角速度还有 3°/s 的死区,避免静止时的噪声灌进舵机。
## 运行
```bash
ros2 run d_ramp_drive ramp_drive_server
ros2 action send_goal /ramp_drive d_interfaces/action/RampDrive \
"{distance_m: 2.5, max_speed: 0.4}"
```
调用前必须暂停 Nav2。
@@ -0,0 +1,28 @@
"""让 pytest 在未 source ROS 的环境下直接跑源码目录。"""
import os
import sys
def _find_src_root(start: str):
cur = start
for _ in range(8):
if os.path.isdir(os.path.join(cur, 'primitives')) and \
os.path.isdir(os.path.join(cur, 'interfaces')):
return cur
parent = os.path.dirname(cur)
if parent == cur:
break
cur = parent
return None
_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
sys.path.insert(0, _HERE)
_SRC = _find_src_root(_HERE)
if _SRC is not None:
_core = os.path.join(_SRC, 'primitives', 'd_pid_core')
if os.path.isdir(_core) and _core not in sys.path:
sys.path.append(_core)
@@ -0,0 +1 @@
"""方案四的坡道/定距原语包。"""
@@ -0,0 +1,178 @@
"""四段速度曲线 + 航向保持的纯逻辑。不 import rclpy。
## 为什么要改参考实现的速度值
Rc2026 的曲线是 0.5 / 0.7 / 0.7 / 0.3 m/s。RC2027 底盘桥限幅
`max_vx_m_s: 0.5`,且是**静默截断**——0.7 的两段会被硬压到 0.5,
四段曲线的形状(本质是"何时慢、何时快")直接失真:中段两档变成同一档,
爬坡时该加速的地方与不该加速的地方给一样的指令。
所以这里不是"调小一点",而是**重新标定四段的相对比例**,
并让 `validate()` 把"任何一段超过底盘限幅"变成启动期错误。
"""
import math
from dataclasses import dataclass
# 底盘静默限幅(m/s)
CHASSIS_MAX_LINEAR = 0.5
# 阶段名,顺序即推进顺序
GROUND = 'GROUND'
CLIMB_INIT = 'CLIMB_INIT'
CLIMB_FULL = 'CLIMB_FULL'
SUMMIT_APPROACH = 'SUMMIT_APPROACH'
CREEP = 'CREEP'
STAGE_ORDER = (GROUND, CLIMB_INIT, CLIMB_FULL, SUMMIT_APPROACH)
@dataclass
class ProfileParams:
"""四段速度与切换阈值。
速度取值依据(车 0.81×0.80,麦轮):
- GROUND 慢:上坡前要对准,横移纠偏主要发生在这里
- CLIMB_INIT 略快:前轮刚吃上坡时给一点动量,过小会在坡脚反复打滑
- CLIMB_FULL 最快:全轮在坡面上,速度越小侧滑累积越多,反而更危险
- SUMMIT_APPROACH 慢:坡顶到平地的过渡最容易被甩出方向,也最容易撞东西
"""
ground_speed: float = 0.20
climb_init_speed: float = 0.28
climb_full_speed: float = 0.40
summit_speed: float = 0.15
creep_speed: float = 0.12
# z 抬升阈值(相对起点),来自里程计 z
climb_init_z: float = 0.10
summit_z: float = 0.47
# z 抬升低于此值认为还在平地(噪声带)
ground_z_band: float = 0.02
# 最快允许速度,必须 <= 底盘限幅
speed_cap: float = 0.45
# 接近终点时的减速加速度,用于生成减速包络
decel: float = 0.6
# 到达容差
distance_tolerance: float = 0.02
# 航向保持 PD
yaw_kp: float = 3.0
yaw_kp_climb: float = 3.4
yaw_kd: float = 0.8
yaw_deadband_deg: float = 1.5
yaw_deadband_climb_deg: float = 0.5
yaw_rate_deadband_dps: float = 3.0
max_wz: float = 0.45
def default_params() -> ProfileParams:
return ProfileParams()
def validate(p: ProfileParams) -> list:
problems = []
for name in ('ground_speed', 'climb_init_speed', 'climb_full_speed',
'summit_speed', 'creep_speed', 'speed_cap'):
value = getattr(p, name)
if value <= 0.0:
problems.append(f'{name} 必须为正')
if value > CHASSIS_MAX_LINEAR:
problems.append(
f'{name}={value} 超过底盘限幅 {CHASSIS_MAX_LINEAR},会被静默截断')
if p.speed_cap > CHASSIS_MAX_LINEAR:
problems.append('speed_cap 超过底盘限幅')
if p.climb_full_speed > p.speed_cap:
problems.append('climb_full_speed 高于 speed_cap,减速包络会把它压回,曲线失真')
if p.climb_init_z >= p.summit_z:
problems.append('climb_init_z 必须小于 summit_z,否则跳过 CLIMB_FULL')
if p.ground_z_band >= p.climb_init_z:
problems.append('ground_z_band 不能吃掉 climb_init_z')
if p.max_wz > 0.5:
problems.append('max_wz 超过底盘角速度限幅 0.5')
if p.distance_tolerance <= 0.0:
problems.append('distance_tolerance 必须为正')
if p.decel <= 0.0:
problems.append('decel 必须为正')
return problems
def select_stage(z_rise: float, p: ProfileParams) -> str:
"""按相对起点的 z 抬升选阶段。上升沿单向推进,不回退。"""
if z_rise >= p.summit_z:
return SUMMIT_APPROACH
if z_rise >= p.climb_init_z:
return CLIMB_FULL
if z_rise > p.ground_z_band:
return CLIMB_INIT
return GROUND
def advance_stage(current: str, z_rise: float, p: ProfileParams) -> str:
"""阶段只允许前进,不允许回退。
为什么不直接 `select_stage`:里程计 z 会抖,骑在阈值上时阶段来回跳,
速度跟着跳,在坡面上等于人为制造冲击载荷。真实赛道上"上去了又滑下来"
才是需要回退的场合,那属于失败,交给 z_rise 下降检测(见 is_slipping)。
"""
target = select_stage(z_rise, p)
try:
cur_idx = STAGE_ORDER.index(current)
tgt_idx = STAGE_ORDER.index(target)
except ValueError:
return target
return STAGE_ORDER[max(cur_idx, tgt_idx)]
def stage_speed(stage: str, p: ProfileParams) -> float:
table = {
GROUND: p.ground_speed,
CLIMB_INIT: p.climb_init_speed,
CLIMB_FULL: p.climb_full_speed,
SUMMIT_APPROACH: p.summit_speed,
CREEP: p.creep_speed,
}
return table.get(stage, p.ground_speed)
def approach_speed(remaining: float, base_speed: float, decel: float) -> float:
"""减速包络:v = min(base, sqrt(2*a*remaining))。
定距原语最容易犯的错是"到点才停",0.4 m/s 下单周期就冲过 1-2 cm 容差。
用物理可达的减速曲线把最后几厘米压下来,比事后调小容差有效。
注意 remaining **为负(已冲过头)返回 0 而不是取绝对值**:取绝对值会让
车减速后又反向加速,在容差边界来回蹭。
"""
if remaining <= 0.0:
return 0.0
envelope = math.sqrt(2.0 * max(decel, 1e-6) * remaining)
return min(base_speed, envelope)
def is_slipping(z_rise_history: list, window: int, drop_threshold: float) -> bool:
"""检测滑退:最近 window 个 z_rise 的最大值比当前高出 drop_threshold。"""
if len(z_rise_history) < 2:
return False
tail = z_rise_history[-max(window, 2):]
return (max(tail) - tail[-1]) > drop_threshold
def yaw_hold_command(yaw_err: float, yaw_rate: float, climbing: bool,
p: ProfileParams) -> float:
"""航向保持 PD → wz(rad/s)。
为什么用 yaw 差分得到的 yaw_rate 而不是 twist.angular.z:
400 Hz IMU 的角速度噪声直接进 D 项会把舵量打成锯齿;yaw 差分天然低通。
"""
deadband = math.radians(p.yaw_deadband_climb_deg if climbing else p.yaw_deadband_deg)
if abs(yaw_err) <= deadband:
return 0.0
rate_deadband = math.radians(p.yaw_rate_deadband_dps)
rate = 0.0 if abs(yaw_rate) < rate_deadband else yaw_rate
kp = p.yaw_kp_climb if climbing else p.yaw_kp
cmd = kp * yaw_err + p.yaw_kd * rate
return max(-p.max_wz, min(p.max_wz, cmd))
@@ -0,0 +1,269 @@
"""四段速度曲线 + 航向保持的定距行驶 Action 服务器(RampDrive 原语)。
用在 Nav2 覆盖不了的场合:
- 坡度上 2D 投影的高度带随车体俯仰漂移,costmap 会时真时假
- 台阶/坡道这类"必须按固定方式通过"的地形,交给曲线比交给采样更靠谱
典型用法(行为树):`PauseNav2 → RampDrive(2.5 m) → ResumeNav2`。
"""
import math
import time
import rclpy
from rclpy.action import ActionServer, CancelResponse, GoalResponse
from rclpy.callback_groups import ReentrantCallbackGroup
from rclpy.executors import MultiThreadedExecutor
from rclpy.node import Node
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from d_interfaces.action import RampDrive
from d_pid_core import angle_error, clamp, yaw_from_quaternion
from d_ramp_drive.profile import (
CLIMB_FULL,
CLIMB_INIT,
CREEP,
GROUND,
SUMMIT_APPROACH,
advance_stage,
approach_speed,
default_params,
is_slipping,
stage_speed,
validate,
yaw_hold_command,
)
class RampDriveServer(Node):
"""沿起步车头方向定距行驶,速度由四段曲线 + 减速包络决定。"""
def __init__(self):
super().__init__('d_ramp_drive_server')
p = default_params()
problems = validate(p)
if problems:
for item in problems:
self.get_logger().error(f'[ramp] 参数自检失败:{item}')
raise ValueError('d_ramp_drive 默认参数非法')
self._p = p
self.declare_parameter('odom_topic', '/odin1/odometry')
self.declare_parameter('cmd_vel_topic', '/cmd_vel')
self.declare_parameter('action_name', 'ramp_drive')
self.declare_parameter('control_hz', 20.0)
self.declare_parameter('distance_tolerance', p.distance_tolerance)
self.declare_parameter('timeout_sec', 30.0)
self.declare_parameter('odom_timeout_sec', 0.3)
self.declare_parameter('slip_drop_m', 0.05)
self._odom_topic = str(self.get_parameter('odom_topic').value)
self._cmd_topic = str(self.get_parameter('cmd_vel_topic').value)
self._hz = float(self.get_parameter('control_hz').value)
self._x = 0.0
self._y = 0.0
self._z = 0.0
self._yaw = 0.0
self._odom_stamp = None
self._cb_group = ReentrantCallbackGroup()
self.create_subscription(
Odometry, self._odom_topic, self._on_odom, 10,
callback_group=self._cb_group)
self._pub = self.create_publisher(Twist, self._cmd_topic, 10)
self._server = ActionServer(
self,
RampDrive,
str(self.get_parameter('action_name').value),
execute_callback=self._execute,
goal_callback=lambda _goal: GoalResponse.ACCEPT,
cancel_callback=lambda _goal: CancelResponse.ACCEPT,
callback_group=self._cb_group,
)
self.get_logger().info(
'[ramp] 就绪:四段速度 '
f'{stage_speed(GROUND, p):.2f}/{stage_speed(CLIMB_INIT, p):.2f}/'
f'{stage_speed(CLIMB_FULL, p):.2f}/{stage_speed(SUMMIT_APPROACH, p):.2f} m/s,'
'底盘上限 0.5')
# ------------------------------------------------------------------ 回调
def _on_odom(self, msg: Odometry) -> None:
pose = msg.pose.pose
self._x = float(pose.position.x)
self._y = float(pose.position.y)
self._z = float(pose.position.z)
q = pose.orientation
self._yaw = yaw_from_quaternion(q.x, q.y, q.z, q.w)
self._odom_stamp = time.monotonic()
def _odom_fresh(self) -> bool:
if self._odom_stamp is None:
return False
return (time.monotonic() - self._odom_stamp) <= float(
self.get_parameter('odom_timeout_sec').value)
def _stop(self) -> None:
self._pub.publish(Twist())
# ------------------------------------------------------------------ 执行
def _execute(self, goal_handle):
p = self._p
goal = goal_handle.request
result = RampDrive.Result()
feedback = RampDrive.Feedback()
distance = float(goal.distance_m)
max_speed = float(goal.max_speed) if goal.max_speed > 0.0 else p.speed_cap
max_speed = min(max_speed, p.speed_cap)
tol = float(self.get_parameter('distance_tolerance').value)
timeout = float(self.get_parameter('timeout_sec').value)
slip_drop = float(self.get_parameter('slip_drop_m').value)
if not self._odom_fresh():
self.get_logger().error('[ramp] 里程计无数据,拒绝执行')
goal_handle.abort()
result.reason = 'odom_lost'
return result
sx, sy, sz, syaw = self._x, self._y, self._z, self._yaw
direction = 1.0 if distance >= 0.0 else -1.0
target = abs(distance)
heading = (math.cos(syaw), math.sin(syaw))
stage = GROUND
z_hist = []
prev_yaw = self._yaw
t0 = time.monotonic()
last = t0
traveled = 0.0
z_rise = 0.0
self.get_logger().info(
f'[ramp] 开始 distance={distance:+.2f} m max_speed={max_speed:.2f}')
while rclpy.ok():
now = time.monotonic()
dt = now - last
last = now
if goal_handle.is_cancel_requested:
self._stop()
goal_handle.canceled()
result.reason = 'canceled'
result.success = False
result.traveled_m = traveled * direction
result.final_error_m = target - traveled
result.duration_sec = now - t0
return result
if now - t0 > timeout:
self._stop()
goal_handle.abort()
result.reason = 'timeout'
result.success = False
result.traveled_m = traveled * direction
result.final_error_m = target - traveled
result.duration_sec = now - t0
return result
if not self._odom_fresh():
self._stop()
self.get_logger().error('[ramp] 里程计中断,急停')
goal_handle.abort()
result.reason = 'odom_lost'
result.success = False
result.traveled_m = traveled * direction
result.final_error_m = target - traveled
result.duration_sec = now - t0
return result
# 沿起步航向的有符号行程
traveled = (self._x - sx) * heading[0] + (self._y - sy) * heading[1]
z_rise = self._z - sz
if target - traveled <= tol:
self._stop()
goal_handle.succeed()
result.success = True
result.reason = 'done'
result.traveled_m = traveled * direction
result.final_error_m = target - traveled
result.duration_sec = time.monotonic() - t0
self.get_logger().info(
f'[ramp] 完成 行程={result.traveled_m:+.3f} m '
f'z_rise={z_rise:+.3f} m 耗时={result.duration_sec:.2f}s')
return result
z_hist.append(z_rise)
if len(z_hist) > 20:
z_hist.pop(0)
if is_slipping(z_hist, window=8, drop_threshold=slip_drop):
self._stop()
self.get_logger().error(
f'[ramp] 检测到滑退(峰值 {max(z_hist):.3f} → 现 {z_rise:.3f} m),中止')
goal_handle.abort()
result.reason = 'slip'
result.success = False
result.traveled_m = traveled * direction
result.final_error_m = target - traveled
result.duration_sec = time.monotonic() - t0
return result
stage = advance_stage(stage, z_rise, p)
base = min(stage_speed(stage, p), max_speed)
remaining = target - traveled
if remaining <= 0.05:
speed = min(p.creep_speed, base)
stage = CREEP
else:
speed = approach_speed(remaining, base, p.decel)
yaw_err = angle_error(syaw, self._yaw)
yaw_rate = angle_error(self._yaw, prev_yaw) / dt if dt > 0.0 else 0.0
prev_yaw = self._yaw
climbing = z_rise > p.ground_z_band
wz = yaw_hold_command(yaw_err, yaw_rate, climbing, p)
cmd = Twist()
cmd.linear.x = clamp(speed * direction, -p.speed_cap, p.speed_cap)
cmd.angular.z = clamp(wz, -p.max_wz, p.max_wz)
self._pub.publish(cmd)
feedback.traveled_m = traveled * direction
feedback.z_rise_m = z_rise
feedback.cmd_vx = cmd.linear.x
feedback.cmd_wz = cmd.angular.z
feedback.stage = stage
goal_handle.publish_feedback(feedback)
time.sleep(1.0 / max(self._hz, 1.0))
self._stop()
goal_handle.abort()
result.reason = 'shutdown'
return result
def main(args=None):
rclpy.init(args=args)
node = RampDriveServer()
executor = MultiThreadedExecutor(num_threads=3)
try:
rclpy.spin(node, executor=executor)
except KeyboardInterrupt:
pass
finally:
node._stop()
node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
main()
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
<name>d_ramp_drive</name>
<version>0.1.0</version>
<description>方案四:四段速度曲线 + 航向保持的坡道/直线定距原语。</description>
<maintainer email="[email protected]">RC2027 BR</maintainer>
<license>Apache-2.0</license>
<buildtool_depend>ament_python</buildtool_depend>
<exec_depend>rclpy</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>d_interfaces</exec_depend>
<exec_depend>d_pid_core</exec_depend>
<test_depend>python3-pytest</test_depend>
<export>
<build_type>ament_python</build_type>
</export>
</package>

Some files were not shown because too many files have changed in this diff Show More