diff --git a/README.md b/README.md index 69f8cb3..abb903c 100644 --- a/README.md +++ b/README.md @@ -126,7 +126,7 @@ ros2 launch src/sentry_sim/launch/sentry_arena.launch.py headless:=true rviz:=fa cd ~/Gazebo_projects/sentry_nav_dev HEADLESS=0 scripts/sentry_up.sh # 启动 python3 tools/check_stack.py # 体检(只读) -python3 tools/nav_client.py 2.0 2.0 # 发一个导航目标 +build/linux/x86_64/release/nav_client 2.0 2.0 # 发一个导航目标(C++ 版,先 xmake) ros2 topic pub -r 10 /cmd_vel geometry_msgs/msg/Twist "{linear: {x: 0.5}}" # 手动前进 ``` @@ -163,20 +163,22 @@ SolidWorks 装配体是 **Y 轴向上**,转换关系:`ROS_x = SW_z`、`ROS_y | 整车质量 / 轮质量 | 25 kg / 1.5 kg | ⚠️ 估算,待机械给 | | 场地 | 12 × 8 m,围挡高 0.42 m | 迁移包 | -**出生点**:场地坐标 (0.9, 4.0),`map → odom` 固定平移 (0.9, 4.0)。 +**出生点**:场地坐标 (-5.0, 3.0),`map → odom` 固定平移 (-5.0, 3.0)。 -**两套坐标系**(`sentry_up.sh` 同时发布两条静态变换): +**坐标系**(世界与地图已整体平移,场地中心 = (0,0)): | | `map` 系 | `field` 系 | |---|---|---| -| 原点 | 西南内角(官方 `parameters.json` 定义) | **场地中心** | -| 场地范围 | x[0,12] y[0,8] | x[−6,6] y[−4,4] | -| 场地中心 | (6.0, 4.0) | **(0, 0)** | -| 出生点 | (0.9, 4.0) | (−5.1, 0.0) | +| 原点 | **场地中心**(世界已平移 −6,−4) | **场地中心** | +| 场地范围 | x[−6,6] y[−4,4] | x[−6,6] y[−4,4] | +| 场地中心 | **(0, 0)** | **(0, 0)** | +| 出生点 | (-5.0, 3.0) | (-5.0, 3.0) | -`map` 是官方栅格图/代价地图/AMCL 的锚点,不要改;`field` 是叠在上面的 -`map → field` 平移 (6.0, 4.0),给决策代码用「中心零点」的直觉坐标。 -用法:`patrol -p frame_id:=field`。 +`map` 是栅格图/代价地图/AMCL 的锚点(`rmul_2027.yaml` 的 origin 已改为 +`[-6.4, -4.4]`);`field` 是恒等别名(`map → field` 平移 0,0,0), +给决策代码用「中心零点」坐标。官方迁移包原始定义是「西南内角 = (0,0)」, +本工程把整个场地平移 (−6,−4),使中心落在 (0,0)。 +用法:`patrol -p frame_id:=field`(与 map 等价)。 --- @@ -222,7 +224,7 @@ python3 tools/decimate.py src/sentry_sim/meshes/full/wheel.stl src/sentry_sim/me | `tools/decimate.py` | 顶点聚类减面(纯 numpy,不依赖 MeshLab) | | `tools/gen_sdf.sh` | URDF(xacro) → Gazebo 用的 model.sdf | | `tools/demo.py` | 驱动演示(前进/转向/打印雷达+里程计) | -| `tools/nav_client.py` | 发 Nav2 目标,**发前先查地图预检**(障碍/未知/净空不足直接拦),再打位置/重试/结果 | +| `build/linux/x86_64/release/nav_client` | 发 Nav2 目标(C++ 版,源码 `src/sentry_nav/src/nav_client.cpp`;原 `tools/nav_client.py` 已删除),**发前先查地图预检**(障碍/未知/净空不足直接拦),再打位置/重试/结果与导航耗时 | | `tools/free_goals.py` | 从栅格图算连通安全区,列出可去目标点(不需要起 ROS) | | `tools/tf_watch.py` | 实时盯三条 TF 边 + Gazebo 真值 + 雷达有效率,抓定位瞬移 | | `tools/scan_probe.py` | 雷达质量体检(默认 `/scan2d`,可传话题名) | @@ -246,9 +248,9 @@ python3 tools/decimate.py src/sentry_sim/meshes/full/wheel.stl src/sentry_sim/me | 目标点 | 结果 | 实际到位 | |---|---|---| - | (2.0, 2.0) | ✅ | (1.91, 2.20) | - | (4.0, 2.0) | ✅ | (3.76, 2.07) | - | (6.0, 4.0) | ✅ | (5.95, 3.76) | + | (−4.0, −2.0) | ✅ | (−4.09, −1.80) | + | (−2.0, −2.0) | ✅ | (−2.24, −1.93) | + | (0.0, 0.0) | ✅ | (−0.05, −0.24) | 定位用**里程计当真值**(仿真里本来就准),地图用迁移包提供的静态栅格图。 @@ -294,7 +296,7 @@ python3 tools/decimate.py src/sentry_sim/meshes/full/wheel.stl src/sentry_sim/me ### ⚠️ 仍有局限 -1. **定位是"作弊"的**:`map→odom` 是写死的静态平移 (0.9, 4.0),位置靠 Gazebo 的 +1. **定位是"作弊"的**:`map→odom` 是写死的静态平移 (-5.0, 3.0),位置靠 Gazebo 的 轮式里程计积分。打滑/被推之后**永远不会自愈**;真机上完全不可用。 真定位需要:点云转 2D → AMCL(当前 `/scan` 因真机视场已基本失效, 得先加 `pointcloud_to_laserscan`)。详见 `docs/仿真场地外壳.md` @@ -352,7 +354,7 @@ python3 tools/check_stack.py |---|---|---| | ~~1~~ | ~~修 `patrol` 的朝向~~ | ✅ **已做**(2026-11-17)。原来 `orientation.w` 写死 1.0(永远朝 +X),现在按 `face_mode` 算:默认朝下一个航点,可选顺着来路。角度计算在 `src/core/`,有 190 项单测覆盖 | | 2 | **写决策状态机**(PATROL / ENGAGE / RETREAT) | 还没有。骨架是 `patrol`,纯逻辑该写在 `src/core/` 里配单测(5 ms 跑完,不用起 Gazebo) | -| 3 | **把定位做成真的** | 现在是**作弊**的:`map→odom` 写死 (0.9, 4.0),位置靠轮速积分,打滑/被撞永远不会自愈。真做要 `/scan/points` → `pointcloud_to_laserscan` → AMCL | +| 3 | **把定位做成真的** | 现在是**作弊**的:`map→odom` 写死 (-5.0, 3.0),位置靠轮速积分,打滑/被撞永远不会自愈。真做要 `/scan/points` → `pointcloud_to_laserscan` → AMCL | | 4 | **雷达量程 12 → 20 m** | 现在 14 m 外的场馆墙打不到、10 m 天花板差 4 cm。改法见 `docs/仿真场地外壳.md` | | 5 | **补真实参数** | 整车质量 25 kg / 轮 1.5 kg 是估的。找机械要 SolidWorks「评估 → 质量属性」(kg·m²) | | 6 | **障碍测试补齐** | `models/test_box/` 有模型但世界没 include;加进去后曾出现规划失败(车跑到角落出不来),需要查是代价地图被点云糊住还是控制器问题 | diff --git a/docs/仿真场地外壳.md b/docs/仿真场地外壳.md index 439d8f2..0b6ed3a 100644 --- a/docs/仿真场地外壳.md +++ b/docs/仿真场地外壳.md @@ -29,11 +29,11 @@ ### 3.1 `arena_walls` —— 墙壁 + 大厅地面 -以场地中心 **(6, 4)** 为中心: +以场地中心 **(0, 0)** 为中心(世界坐标已整体平移 −6,−4): | 项 | 值 | |---|---| -| **内空** | **40.0 × 28.0 m**(x ∈ [−14, 26],y ∈ [−10, 18]) | +| **内空** | **40.0 × 28.0 m**(x ∈ [−20, 20],y ∈ [−14, 14]) | | 外沿 | 40.8 × 28.8 m | | 墙厚 / 墙高 | 0.4 m / **10.0 m** | | 大厅地面 | 40.8 × 28.8 × 0.1 m,顶面 **z = −0.02** | @@ -44,16 +44,16 @@ | 部件 | 尺寸 | 位置 | |---|---|---| -| 顶棚平板 | **40.8 × 28.8 × 0.2 m** | 中心 (6, 4, **10.0**) | -| 东西向主梁 ×5 | 40.8 × 0.3 × 0.4 m | y = −8 / −2 / 4 / 10 / 16,z = 9.55 | -| 南北向次梁 ×3 | 0.3 × 28.8 × 0.4 m | x = −8 / 6 / 20,z = 9.30 | +| 顶棚平板 | **40.8 × 28.8 × 0.2 m** | 中心 (0, 0, **10.0**) | +| 东西向主梁 ×5 | 40.8 × 0.3 × 0.4 m | y = −12 / −6 / 0 / 6 / 12,z = 9.55 | +| 南北向次梁 ×3 | 0.3 × 28.8 × 0.4 m | x = −14 / 0 / 14,z = 9.30 | | 照明灯带 ×12 | 3.0 × 0.5 × 0.08 m | 3 列 × 4 排,z = 9.05,`emissive` 自发光 | ### 3.3 `catch_net` —— 拦截网(**已停用**) | 项 | 值 | |---|---| -| 位置 | 围挡外框再外扩 0.25 m → x = −0.55 / 12.55,y = −0.55 / 8.55 | +| 位置 | 围挡外框再外扩 0.25 m → x = −6.55 / 6.55,y = −4.55 / 4.55 | | 网内净空 | 13.10 × 9.10 m | | 高度 / 板厚 | 3.50 m / 0.03 m | | 材质 | 半透明(`transparency 0.65`)+ 四角金属立柱 | @@ -81,9 +81,9 @@ | 决定 | 原因 | |---|---| -| **墙有碰撞,但依然打不到** | 墙内侧到出生点 (0.9, 4.0):南/北墙各 14.0 m、西墙 14.9 m、东墙 25.1 m。最近 14.0 m > 量程 12 m。**东墙永远进不了量程** —— 场地本身 12 m 宽、机器人又出生在西边 | +| **墙有碰撞,但依然打不到** | 墙内侧到出生点 (1.0, 1.0):北墙 13.0 m、南墙 15.0 m、西墙 21.0 m、东墙 19.0 m。最近 13.0 m > 量程 12 m。**东墙永远进不了量程** —— 大厅东墙在 x=20,离出生点 19 m | | **屋顶有碰撞,但高度超量程上限** | 射线是斜的,斜距 = 高度 / sin(仰角)。天花板下沿需要仰角 ≥ 52.3°,最高只有 52.0°。见 §1 的「差 4 cm」 | -| **屋顶 `cast_shadows = false`** | 有平行光 `sun` 从 (6,4,10) 往下照,屋顶一投影**整个大厅瞬间变黑**,得补一堆室内灯才救得回来 | +| **屋顶 `cast_shadows = false`** | 有平行光 `sun` 从 (0,0,10) 往下照,屋顶一投影**整个大厅瞬间变黑**,得补一堆室内灯才救得回来 | | **大厅地面放 z = −0.02** | ① 避免两块地板共面 → z-fighting(画面闪白斑)② 2 cm 台阶肉眼看不出,且低于 `self_filter` 的 `keep_min_z`(0.02),不会被当障碍 | | **灯带用 `emissive`,不是 ``** | `emissive` 只让材质自发光(便宜的视觉效果),不真照亮场景;照明仍由平行光 + 环境光负责。作用是**制造亮度对比**,让人一眼认出「头顶有东西」 | diff --git a/docs/定位接入AMCL.md b/docs/定位接入AMCL.md index 604315f..ebf6935 100644 --- a/docs/定位接入AMCL.md +++ b/docs/定位接入AMCL.md @@ -1,8 +1,9 @@ # 定位接入(AMCL) -> **状态**:🔴 **AMCL 已接通,但在仿真里会跑飞** —— `scan2d` 装在 0.4052 m, -> 看不见场地里 0.42 m 的悬空平板,粒子滤波失配后整体瞬移(最严重一次偏 **4.4 m**)。 -> 根因见 §4.1 的更正与 [`踩过的坑.md`](踩过的坑.md) §G3–§G5;修法见 §4.2 末尾(**代码尚未落地**)。 +> **状态**:🟢 **已修复(2026-11-19)** —— `scan2d` 改为由 `self_filter` 从 3D 点云投影生成 +> (取 `z ∈ [0.05, 0.50] m` 车体碰撞带、360 方位取最小距离),消除了「雷达看不见 0.42 m +> 悬空平板、地图却有」的高度失配跑飞。原问题复盘见 §4.1 的更正与 +> [`踩过的坑.md`](踩过的坑.md) §G3–§G5。 > **最后更新**:2026-11-19 > **涉及**:`src/sentry_sim/urdf/sentry.urdf.xacro`、`config/nav2_params.yaml`、 > `scripts/sentry_up.sh`、`launch/sentry_arena.launch.py` @@ -24,7 +25,7 @@ TF 链是三段拼起来的(见根 `README.md` §4): ``` map ──(谁发?)──► odom ──(Gazebo 轮式里程计)──► base_link ↑ - 改造前:static_transform_publisher 发一个常数 (0.9, 4.0) + 改造前:static_transform_publisher 发一个常数 (-5.0, 3.0) 改造后:nav2_amcl 发 ``` @@ -121,25 +122,23 @@ laser_min_range: 0.6 > 按 360 个方位角取**最小距离**,合成 `/scan2d`。这个带已被验证足够: > `体积投影(z>0.02)` 与 `体积投影(z∈[0.05,0.50])` **完全相同(100%)**,不存在带外还有障碍的情况。 > -> **待办(代码尚未落地)**: -> 1. `src/sentry_nav/` 加一个投影节点(或给 `self_filter` 加一路输出), -> 输入 `/scan/points_filtered`、输出 `/scan2d`; -> 2. 删掉 `sentry.urdf.xacro` 里那个单线 `scan2d` 传感器; -> 3. `sentry_up.sh` / `bridge_after_gz.sh` 各少一条 `/scan2d` 桥,多起一个节点; -> 4. `nav2_params.yaml` 的 `laser_min_range` 可以降到 0.15(自击在投影前已被 `self_filter` 剔掉)。 +> **✅ 已落地(2026-11-19)**: +> 1. `src/sentry_nav/src/self_filter.cpp` 给自滤节点加了一路 `/scan2d` 输出:同一份过滤结果 +> 投影成 2D 激光(`z ∈ [0.05, 0.50] m`、360 方位取最小距离、帧 `base_link`)。 +> 不新增进程、不新增话题桥;参数 `scan_*` 可在命令行覆盖。 +> 2. 已删掉 `sentry.urdf.xacro` 里那个单线 `scan2d` 传感器(连带重新生成 SDF)。 +> 3. `sentry_up.sh` / `bridge_after_gz.sh` 各删一条 `/scan2d` gz→ROS 桥。 +> 4. `nav2_params.yaml` 的 `laser_min_range` 降到 0.15(自击在投影时已被 `self_filter` 剔掉)。 -### 4.3 桥加话题(**两处都要改**) +### 4.3 桥加话题(**已移除,2026-11-19**) -| 文件 | 行 | +单线雷达时期需要在这两处加桥;投影方案落地后**不再有 `/scan2d` 的 gz→ROS 桥**—— +`/scan2d` 现在由 `self_filter` 直接在 ROS 内发布: + +| 文件 | 原行号 | |---|---| -| `src/sentry_sim/scripts/sentry_up.sh` | 86 | -| `src/sentry_sim/scripts/bridge_after_gz.sh` | 27 | - -```bash - '/scan2d@sensor_msgs/msg/LaserScan[gz.msgs.LaserScan' \ -``` - -> 只改一处 → 另一个入口的桥就没有这个话题。 +| `src/sentry_sim/scripts/sentry_up.sh` | 139(已删) | +| `src/sentry_sim/scripts/bridge_after_gz.sh` | 27(已删) | ### 4.4 `nav2_params.yaml` 四处 @@ -150,11 +149,11 @@ laser_min_range: 0.6 | 29 | `robot_model_type` | `DifferentialMotionModel` | **`OmniMotionModel`** | **麦轮是全向的**,差速模型会低估侧移 | | 41 | `scan_topic` | `scan` | **`scan2d`** | `/scan` 仰角 +22.5°,射向天空 | -初始位姿本来就配好了,正好是红方出生点: +初始位姿配的是当前出生点(世界已整体平移,场地中心 = (0,0)): ```yaml set_initial_pose: true -initial_pose: {x: 0.9, y: 4.0, z: 0.0, yaw: 0.0} +initial_pose: {x: -5.0, y: 3.0, z: 0.0, yaw: 0.0} ``` ### 4.5 ⚠️ 必须拆掉两处会冲突的东西 @@ -263,7 +262,7 @@ ros2 action list | grep -E "^/wait$" **在仿真里直接看不出来** —— 因为 Gazebo 的 `/odom` 是物理真值, `odom→base_link` 永远正确,AMCL 只需确认"你没漂",输出和"作弊定位"一模一样。 -要看它干活,必须**让里程计说谎**。`odom_tf.py` 有一个调试参数: +要看它干活,必须**让里程计说谎**。`odom_tf`(C++)有一个调试参数: ```bash SENTRY_ODOM_SCALE=1.15 HEADLESS=1 scripts/sentry_up.sh # 里程计报的距离偏大 15% @@ -298,7 +297,7 @@ python3 tools/amcl_drift_demo.py # 对比三列 - 走 Nav2 的话,代价地图会把它绕开,就制造不出「轮子转了但车没动」的漂移场景 - 而那个场景(打滑)正是 AMCL 唯一能体现价值的地方 -要验证 Nav2 自己的避障,得用 `python3 tools/nav_client.py x y` 发导航目标。 +要验证 Nav2 自己的避障,得用 `build/linux/x86_64/release/nav_client x y` 发导航目标。 --- diff --git a/docs/排错速查.md b/docs/排错速查.md index dbf6d45..b8d2d3a 100644 --- a/docs/排错速查.md +++ b/docs/排错速查.md @@ -71,7 +71,7 @@ TF 链(`map→odom` / `odom→base_link` / `map→base_link`),结尾直接 | `Costmap timed out waiting for update` / 代价地图 100×100 | `map_server` 没起(关 AMCL 时最容易发生) | 检查 `ros2 topic hz /map`;`sentry_up.sh` 第 5.7 步专门起它 | | 目标成功但位置偏差大 | 控制器有到达容差,正常 0.1~0.3 m | 调 `goal_checker` 的 `xy_goal_tolerance` | | 打滑 / 被撞后位置永远不对 | **定位是「作弊」的**:静态 `map→odom` + 轮速积分,不会自愈 | 见根 `../README.md` §7 | -| `failed to create plan with tolerance of: 0.500000` | 这条报错**不区分**「目标点在障碍里 / 起点在障碍里 / 中间真没路」,只能靠人排查 | `python3 tools/free_goals.py` 找安全点;`nav_client.py` 已内置预检会先拦一道 | +| `failed to create plan with tolerance of: 0.500000` | 这条报错**不区分**「目标点在障碍里 / 起点在障碍里 / 中间真没路」,只能靠人排查 | `python3 tools/free_goals.py` 找安全点;`build/linux/x86_64/release/nav_client` 已内置预检会先拦一道 | | 导航目标 `ABORTED`,日志是 `failed to plan from (<一个奇怪的位置>)` | **定位瞬移**:AMCL 跑飞后,起点落到障碍格里。报错落在规划器上,真凶在 AMCL | `python3 tools/tf_watch.py --time 60` 一个窗口盯着,另一个窗口发目标;再用 `gz model -m sentry --pose` 对真值 | | `nav_client` 反馈的位置一路平滑,**最后一行 TF 却差好几米** | 同上。另外 `NavigateToPose` 的 `distance_remaining` 在 Nav2 1.5 里**永远返回 0**,别拿它判断进度 | 同上。仿真的已知根因见 [`踩过的坑.md`](踩过的坑.md) §G4 | | AMCL 认为的位置和 Gazebo 真值差好几米 | `scan2d` 在 0.4052 m,看不见 0.42 m 的悬空平板 → 粒子滤波失配 | 见 [`踩过的坑.md`](踩过的坑.md) §G4/§G5 与 [`定位接入AMCL.md`](定位接入AMCL.md) §4.1 的更正 | diff --git a/docs/操作手册.md b/docs/操作手册.md index 00baad1..fddf375 100644 --- a/docs/操作手册.md +++ b/docs/操作手册.md @@ -23,11 +23,11 @@ HEADLESS=0 scripts/sentry_up.sh Gazebo(系统版 10.6) → ros_gz 桥(等 /clock 就绪后才订阅) → robot_state_publisher(TF 树) - → odom_tf.py(补 odom -> base_link) - → cmd_vel_relay.py(/cmd_vel 改名到 /model/sentry/cmd_vel) + → odom_tf(xmake 产物,补 odom -> base_link) + → cmd_vel_relay(xmake 产物,/cmd_vel 改名到 /model/sentry/cmd_vel) → self_filter(点云自滤,xmake 产物) - → map->odom 静态变换(0.9, 4.0) - → map->field 静态变换(6.0, 4.0)— 场地中心 = 零点 + → map->odom 静态变换(1.0, 1.0) + → map->field 恒等变换(两者都是场地中心 = 零点) → map_server + lifecycle_manager → Nav2(非组合模式)+ RViz ``` @@ -49,7 +49,7 @@ Gazebo(系统版 10.6) ```bash build/linux/x86_64/release/self_filter --ros-args -p use_sim_time:=true build/linux/x86_64/release/patrol --ros-args -p use_sim_time:=true -p loop:=false -python3 src/sentry_sim/scripts/odom_tf.py --ros-args -p use_sim_time:=true +build/linux/x86_64/release/odom_tf --ros-args -p use_sim_time:=true ``` --- @@ -103,7 +103,7 @@ ros2 topic pub --once /cmd_vel geometry_msgs/msg/Twist "{}" ## 3. 发导航目标 ```bash -python3 tools/nav_client.py 2.0 2.0 # 目标 x=2.0 y=2.0(场地坐标,米) +build/linux/x86_64/release/nav_client 2.0 2.0 # 目标 x=2.0 y=2.0(场地坐标,米) ``` **发之前它会先查地图**,占据值 ≥65、落在未知格、净空 <0.5 m(车体半对角 0.422 m)都直接拦下: @@ -231,23 +231,23 @@ python3 tools/probe_all.py # 一次性检查多个话题有没有 场地 **12 × 8 m**(内圈)。**有两套坐标系**,按需选用: -| | `map` 系 | `field` 系(场地中心 = 零点) | +| | `map` 系 | `field` 系(与 map 相同) | |---|---|---| -| 原点 | 西南内角(官方定义) | **场地中心** | -| 可走范围 | x ∈ [0, 12],y ∈ [0, 8] | **x ∈ [−6, 6],y ∈ [−4, 4]** | -| 场地中心 | (6.0, 4.0) | **(0.0, 0.0)** | -| 出生点 | (0.9, 4.0) | **(−5.1, 0.0)** | -| 己方半场 | x < 6 | **x < 0** | -| 对面半场 | x > 6 | **x > 0** | +| 原点 | **场地中心**(世界已整体平移 −6,−4) | **场地中心** | +| 可走范围 | **x ∈ [−6, 6],y ∈ [−4, 4]** | x ∈ [−6, 6],y ∈ [−4, 4] | +| 场地中心 | **(0.0, 0.0)** | **(0.0, 0.0)** | +| 出生点 | (-5.0, 3.0) | (-5.0, 3.0) | +| 己方半场 | x < 0 | x < 0 | +| 对面半场 | x > 0 | x > 0 | -> `map` 是官方栅格图的坐标系(`rmul_2027.yaml` 的 `origin: [-0.4, -0.4]`), -> Nav2 的地图/代价地图/AMCL 都锚在它上面,**不要改**。 -> `field` 只是叠在上面的一个静态 TF(`map → field` 平移 6.0, 4.0), -> 让决策代码写 `(0,0)` 就是场地中心、`x>0` 就是对面半场。 +> 世界与地图已整体平移:`rmul_2027.yaml` 的 `origin` 改为 `[-6.4, -4.4]`, +> 使场地中心落在 `map=(0,0)`。`field` 是恒等别名(保留给决策代码用)。 +> 官方迁移包原始定义是「西南内角 = (0,0)」(内场 0..12 × 0..8),平移后中心 = 0。 **几何依据**(不是估的):官方 `parameters.json` 定义坐标系为「西南内角 = (0,0)」; 场地网格 `step_textured.dae` 实测 x ∈ [−0.3, 12.3]、y ∈ [−0.3, 8.3] -→ 内圈正好 [0,12]×[0,8],**几何中心 = (6.0, 4.0)**。 +→ 内圈正好 [0,12]×[0,8],几何中心 = (6,4)。本工程把世界/地图整体平移 (−6,−4), +故中心 = (0,0),内圈 = [−6,6]×[−4,4]。 ### 怎么亲眼确认中心点在哪 @@ -255,7 +255,7 @@ python3 tools/probe_all.py # 一次性检查多个话题有没有 ```bash ros2 run tf2_ros tf2_echo map field -# 打印 translation = (6.000, 4.000, 0.000),说明 field 原点就在 map 的 (6,4) +# 现在 map→field 是恒等变换:translation = (0.000, 0.000, 0.000) ``` **方法二:RViz 里画出来(推荐,能肉眼比对)** @@ -268,11 +268,11 @@ python3 tools/mark_field_center.py # 另开一个终端,仿真跑着时执 | 画出什么 | 含义 | |---|---| -| 🟡 黄色线框 | 场地内圈 12×8 边界(map 系 x[0,12] y[0,8]) | +| 🟡 黄色线框 | 场地内圈 12×8 边界(map 系 x[-6,6] y[-4,4]) | | 🔵 蓝色十字 | 场地中线,交点在中心 | -| 🔴 红色圆柱 | 用 **map** 帧画的中心 (6.0, 4.0) | +| 🔴 红色圆柱 | 用 **map** 帧画的中心 (0.0, 0.0) | | 🟢 绿色球 | 用 **field** 帧画的中心 (0.0, 0.0) | -| 文字标签 | `field(0,0) = map(6.0,4.0)` | +| 文字标签 | `field(0,0) = map(0,0)` | **红圆柱和绿球必须完全重合** —— 重合就说明 `map→field` 这条变换是对的。 黄框应该正好套在 RViz 地图里场地围挡的内沿上。 @@ -281,20 +281,20 @@ python3 tools/mark_field_center.py # 另开一个终端,仿真跑着时执 ```bash ros2 run ros_gz_sim create -world rmul_arena -name center_check \ - -x 6.0 -y 4.0 -z 0.3 \ + -x 0.0 -y 0.0 -z 0.3 \ -string 'true0.30.61 0 0 11 0 0 1' ``` -会在世界坐标 (6.0, 4.0) 立一根红柱子(**纯视觉,没有碰撞**,不挡车)。 +会在世界坐标 (0.0, 0.0) 立一根红柱子(**纯视觉,没有碰撞**,不挡车)。 它应该正好立在场地中央那个治理机关上。重启仿真就没了。 -围挡高度 0.42 m。之前实测通过的三个点(**map 系**): +围挡高度 0.42 m。之前实测通过的三个点(**map 系**,与 field 系相同): | 目标 | 结果 | field 系等价坐标 | |---|---|---| -| (2.0, 2.0) | ✅ 到位 (1.91, 2.20) | (−4.0, −2.0) | -| (4.0, 2.0) | ✅ 到位 (3.76, 2.07) | (−2.0, −2.0) | -| (6.0, 4.0) | ✅ 到位 (5.95, 3.76) | (−0.05, −0.24) | +| (−4.0, −2.0) | ✅ 到位 (−4.09, −1.80) | (−4.0, −2.0) | +| (−2.0, −2.0) | ✅ 到位 (−2.24, −1.93) | (−2.0, −2.0) | +| (0.0, 0.0) | ✅ 到位 (−0.05, −0.24) | (−0.05, −0.24) | **用 field 系发目标**: @@ -308,9 +308,9 @@ build/linux/x86_64/release/patrol --ros-args \ | 目标 | 结果 | |---|---| -| (2.0, 2.0) | ✅ 到位 (1.91, 2.20) | -| (4.0, 2.0) | ✅ 到位 (3.76, 2.07) | -| (6.0, 4.0) | ✅ 到位 (5.95, 3.76) | +| (−4.0, −2.0) | ✅ 到位 (−4.09, −1.80) | +| (−2.0, −2.0) | ✅ 到位 (−2.24, −1.93) | +| (0.0, 0.0) | ✅ 到位 (−0.05, −0.24) | > **想测避障**:障碍箱模型在 `src/sentry_sim/models/test_box/`,但**默认没放进世界**。 > 在 `worlds/sentry_arena.sdf` 里加一段: diff --git a/docs/构建体系与代码分层.md b/docs/构建体系与代码分层.md index 256d215..b4d5bfd 100644 --- a/docs/构建体系与代码分层.md +++ b/docs/构建体系与代码分层.md @@ -95,7 +95,7 @@ add_linkgroups(libs, {group = true}) -- → -Wl,--start-group … -Wl,--end- | 失去的东西 | 现在的替代做法 | |---|---| | `ros2 run sentry_nav self_filter` | 直接跑 `build/linux/x86_64/release/self_filter` | -| `ros2 run sentry_sim odom_tf.py` | `python3 src/sentry_sim/scripts/odom_tf.py` | +| `ros2 run sentry_sim odom_tf.py` | `build/linux/x86_64/release/odom_tf` | | `ros2 pkg prefix sentry_sim` | `SENTRY_SIM_SHARE` 环境变量(默认 `<仓库>/src/sentry_sim`) | | `xacro` 的 `$(find sentry_sim)` | 改成 `$(env SENTRY_SIM_SHARE)`;不设变量会明确报错 | | `ros2 launch sentry_sim …`(备用入口) | 只保留 `scripts/sentry_up.sh`(本来就是主入口) | diff --git a/docs/踩过的坑.md b/docs/踩过的坑.md index fc2033d..d3562fd 100644 --- a/docs/踩过的坑.md +++ b/docs/踩过的坑.md @@ -87,7 +87,7 @@ velocity_smoother collision_monitor docking_server following_server ### C3. MecanumDrive 插件的话题名带模型名 插件用 `/model/sentry/cmd_vel`,而 `parameter_bridge` **只支持两端同名** → 桥不上。 -解法是 `cmd_vel_relay.py` 在 ROS 侧改一次名 +解法是 `cmd_vel_relay`(C++,xmake 产物)在 ROS 侧改一次名 (`/cmd_vel` `/cmd_vel_nav` `/cmd_vel_smoothed` → `/model/sentry/cmd_vel`)。 --- @@ -350,7 +350,7 @@ env -u LD_LIBRARY_PATH GZ_PARTITION=sentry gz topic -e -t /scan2d -n 1 而这条报错**不区分**「目标在障碍里」和「起点在障碍里」和「中间没路」,只能靠人排查。 -**现在的做法**:`tools/nav_client.py` 发目标前先读 `/map`,检查 +**现在的做法**:`build/linux/x86_64/release/nav_client` 发目标前先读 `/map`,检查 **占据值 / 是否未知格 / 净空是否 ≥ 0.5 m**(车体半对角 0.422 m),不合格直接拦下并说明原因。 找安全点用 `tools/free_goals.py`(直读 `rmul_2027.yaml` + `.pgm`,不需要起 ROS)。 diff --git a/field/RMUL2027_map_transfer_20261016_STEP_R1/src/guodong_sentry_sim/maps/rmul_2027/rmul_2027.yaml b/field/RMUL2027_map_transfer_20261016_STEP_R1/src/guodong_sentry_sim/maps/rmul_2027/rmul_2027.yaml index 65ba9c0..49c64a3 100644 --- a/field/RMUL2027_map_transfer_20261016_STEP_R1/src/guodong_sentry_sim/maps/rmul_2027/rmul_2027.yaml +++ b/field/RMUL2027_map_transfer_20261016_STEP_R1/src/guodong_sentry_sim/maps/rmul_2027/rmul_2027.yaml @@ -1,7 +1,7 @@ image: rmul_2027.pgm mode: trinary resolution: 0.025 -origin: [-0.4, -0.4, 0.0] +origin: [-6.4, -4.4, 0.0] negate: 0 occupied_thresh: 0.65 free_thresh: 0.196 diff --git a/src/sentry_nav/src/cmd_vel_relay.cpp b/src/sentry_nav/src/cmd_vel_relay.cpp new file mode 100644 index 0000000..ce97597 --- /dev/null +++ b/src/sentry_nav/src/cmd_vel_relay.cpp @@ -0,0 +1,95 @@ +// Copyright 2026 sentry_nav_dev +// +// cmd_vel_relay:把 Nav2 的 /cmd_vel_smoothed(及兼容的 /cmd_vel、/cmd_vel_nav) +// 转发到 ros_gz 桥用的 /model/sentry/cmd_vel。 +// (C++ 版,2026-11-17 从 scripts/cmd_vel_relay.py 移植;用户要求能 C++ 就 C++。) +// +// 为什么需要:Gazebo 的 MecanumDrive 插件订阅的是「模型名/cmd_vel」(即 +// /model/sentry/cmd_vel),而 ros_gz_bridge 只支持「两端同名」的桥接, +// 它无法把 ROS 的 /cmd_vel 映射到 gz 的 /model/sentry/cmd_vel。 +// 所以这里做一次 ROS 侧的改名转发。 +// +// 平滑命令优先:Nav2 的速度链是「控制器发 /cmd_vel(原始)→ velocity_smoother +// 订阅 /cmd_vel 并发布 /cmd_vel_smoothed(限加速度、去死区)」。车只该吃最终 +// 那条命令。之前三路都转发 → 平滑前后的命令在 gz 侧交替打架,车会抖、走着 +// 走着就 "Failed to make progress"。现在:/cmd_vel_smoothed 优先;它最近 +// 200 ms 内有消息时丢弃其它来源;只在平滑器没输出时(如 NAV2=0 手发 /cmd_vel) +// 回退到原始命令。 +// +// 参数: +// out_topic /model/sentry/cmd_vel 转发目标 +// in_topics [/cmd_vel_smoothed, /cmd_vel, /cmd_vel_nav] + +#include +#include +#include +#include + +#include +#include + +namespace sentry_nav +{ + +class CmdVelRelay : public rclcpp::Node +{ +public: + CmdVelRelay() : Node("cmd_vel_relay") + { + const std::string out_topic = + declare_parameter("out_topic", "/model/sentry/cmd_vel"); + in_topics_ = declare_parameter>( + "in_topics", std::vector{"/cmd_vel_smoothed", "/cmd_vel", "/cmd_vel_nav"}); + + pub_ = create_publisher(out_topic, 10); + for (const std::string & topic : in_topics_) { + subs_.push_back( + create_subscription( + topic, 10, + [this, topic](const geometry_msgs::msg::Twist::SharedPtr msg) { + OnTwist(topic, msg); + })); + } + + std::string joined; + for (size_t i = 0; i < in_topics_.size(); ++i) { + joined += (i == 0 ? "" : ", ") + in_topics_[i]; + } + RCLCPP_INFO( + get_logger(), "cmd_vel_relay: [%s] -> %s(平滑命令优先)", + joined.c_str(), out_topic.c_str()); + } + +private: + void OnTwist( + const std::string & topic, + const geometry_msgs::msg::Twist::SharedPtr & msg) + { + const int64_t now_ns = now().nanoseconds(); + if (topic == "/cmd_vel_smoothed") { + last_smoothed_ns_ = now_ns; + pub_->publish(*msg); + return; + } + // 平滑器正在输出:丢弃原始/其它来源,避免两路命令打架 + if (last_smoothed_ns_ != 0 && now_ns - last_smoothed_ns_ < 200'000'000LL) { + return; + } + pub_->publish(*msg); + } + + rclcpp::Publisher::SharedPtr pub_; + std::vector::SharedPtr> subs_; + std::vector in_topics_; + int64_t last_smoothed_ns_ = 0; +}; + +} // namespace sentry_nav + +int main(int argc, char * argv[]) +{ + rclcpp::init(argc, argv); + rclcpp::spin(std::make_shared()); + rclcpp::shutdown(); + return 0; +} diff --git a/src/sentry_nav/src/nav_client.cpp b/src/sentry_nav/src/nav_client.cpp new file mode 100644 index 0000000..df4ecb7 --- /dev/null +++ b/src/sentry_nav/src/nav_client.cpp @@ -0,0 +1,339 @@ +// Copyright 2026 sentry_nav_dev +// +// 导航测试客户端(C++ 版,替代原 tools/nav_client.py)。 +// +// 用法(本工程不用 ament/colcon,直接跑 xmake 产物): +// build/linux/x86_64/release/nav_client [yaw度] +// build/linux/x86_64/release/nav_client 0.0 0.0 # 走到场地中心 +// build/linux/x86_64/release/nav_client 0.0 0.0 90 # 到位置后朝向 +90° +// build/linux/x86_64/release/nav_client -4.0 0.0 --force # 明知在障碍里也发(调试用) +// +// 坐标是 map 帧(场地中心 = (0,0)):x∈[-6,6],y∈[-4,4]。 +// +// 发目标前先用 /map 做可达性预检:Nav2 的规划器对「目标点落在障碍格里」 +// 只会吐一句 "Failed to create plan with tolerance of: 0.500000",看不出原因。 +// 这里直接读 /map,把目标点的占据值和净空算出来,不合格就在发之前拦住。 +// +// 为什么换成 C++(2026-11-17):用户要求能 C++ 就 C++;另外 rclpy 启动要 +// 1~2 秒且依赖 Python 环境,二进制版启动快、无解释器。 +// 输出格式与原 Python 版保持一致,文档/脚本都按这个格式写。 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using namespace std::chrono_literals; +using NavigateToPose = nav2_msgs::action::NavigateToPose; +using GoalHandle = rclcpp_action::ClientGoalHandle; + +namespace { + +// 车体是 0.65 x 0.54 矩形,半对角 0.422 m;小于这个值必然车身压障碍。 +constexpr double kHalfDiagonal = 0.422; +// 低于这个净空就不建议去(膨胀层默认 0.45)。 +constexpr double kMinClearance = 0.50; +// 判定「被占据」的阈值,和 rmul_2027.yaml 的 occupied_thresh 对齐。 +constexpr int kOccupiedThreshold = 65; +// 净空搜索半径上限(米)。 +constexpr double kClearanceSearch = 2.0; +// 圆周率(避开 M_PI —— 严格 C++ 里它不是标准宏)。 +constexpr double kPi = 3.14159265358979323846; + +struct Args +{ + double gx = 0.0; + double gy = 0.0; + double yaw_deg = 0.0; + bool force = false; +}; + +// 分出位置参数和 --force。 +bool ParseArgs(int argc, char * argv[], Args & args, bool & ok) +{ + ok = true; + std::vector pos; + for (int i = 1; i < argc; ++i) { + const std::string a = argv[i]; + if (a == "--force") { + args.force = true; + } else if (a.rfind("--", 0) == 0) { + ok = false; + } else { + pos.push_back(a); + } + } + for (size_t i = 0; i < pos.size(); ++i) { + char * end = nullptr; + const double v = std::strtod(pos[i].c_str(), &end); + if (end == nullptr || *end != '\0') { + ok = false; + return false; + } + if (i == 0) { + args.gx = v; + } else if (i == 1) { + args.gy = v; + } else { + args.yaw_deg = v; + } + } + return true; +} + +// 世界坐标 -> 栅格下标;越界返回 false。 +bool WorldToCell( + const nav_msgs::msg::MapMetaData & info, double x, double y, + int & r, int & c) +{ + c = static_cast(std::floor((x - info.origin.position.x) / info.resolution)); + r = static_cast(std::floor((y - info.origin.position.y) / info.resolution)); + return r >= 0 && r < static_cast(info.height) && c >= 0 && c < static_cast(info.width); +} + +// 返回 (r, c) 到最近障碍格的距离(米),超过 search 就返回 search。 +// 未知格(-1)也算障碍 —— 代价地图开了 track_unknown_space,在未知区里 +// 规划同样会失败,按障碍处理更接近实际行为。 +double ClearanceAt( + const std::vector & data, const nav_msgs::msg::MapMetaData & info, + int r, int c, double search) +{ + const int w = static_cast(info.width); + const double res = info.resolution; + const int n = std::max(1, static_cast(search / res)); + const int r0 = std::max(0, r - n); + const int r1 = std::min(static_cast(info.height), r + n + 1); + const int c0 = std::max(0, c - n); + const int c1 = std::min(w, c + n + 1); + double best = search; + for (int rr = r0; rr < r1; ++rr) { + for (int cc = c0; cc < c1; ++cc) { + const int v = data[static_cast(rr) * w + cc]; + if (v >= kOccupiedThreshold || v < 0) { + const double d = std::hypot(rr - r, cc - c) * res; + best = std::min(best, d); + } + } + } + return best; +} + +const char * StateName(int8_t value) +{ + if (value >= kOccupiedThreshold) { + return "障碍"; + } + if (value < 0) { + return "未知"; + } + return "空闲"; +} + +} // namespace + +int main(int argc, char * argv[]) +{ + Args args; + bool ok = true; + if (!ParseArgs(argc, argv, args, ok) || !ok) { + std::printf("用法: nav_client [yaw度] [--force]\n"); + return 1; + } + + rclcpp::init(argc, argv); + rclcpp::NodeOptions options; + // 整套栈都是 use_sim_time:=true(Gazebo 时钟),客户端必须一致, + // 否则本节点算出的时间戳跟 TF 里的仿真时间对不上。 + options.parameter_overrides({{"use_sim_time", true}}); + auto node = std::make_shared("nav_client", options); + + tf2_ros::Buffer tf_buffer(node->get_clock()); + tf2_ros::TransformListener tf_listener(tf_buffer); + + // /map 是 TRANSIENT_LOCAL 发布的,用默认 QoS 会一条都收不到。 + auto map_qos = rclcpp::QoS(rclcpp::KeepLast(1)) + .reliability(RMW_QOS_POLICY_RELIABILITY_RELIABLE) + .durability(RMW_QOS_POLICY_DURABILITY_TRANSIENT_LOCAL); + + struct MapHolder + { + nav_msgs::msg::OccupancyGrid last; + bool got = false; + } holder; + + auto map_sub = node->create_subscription( + "/map", map_qos, + [&holder](nav_msgs::msg::OccupancyGrid::SharedPtr msg) { + holder.last = *msg; + holder.got = true; + }); + + const auto wait_start = std::chrono::steady_clock::now(); + while (!holder.got && + std::chrono::steady_clock::now() - wait_start < 15s) + { + rclcpp::spin_some(node); + std::this_thread::sleep_for(20ms); + } + + if (!holder.got) { + std::printf("⚠️ 15 秒内没收到 /map,跳过预检直接发目标\n"); + } else { + const auto & info = holder.last.info; + const auto & data = holder.last.data; + std::printf( + "地图 %dx%d @ %.2f m/px origin=(%.2f, %.2f)\n", + static_cast(info.width), static_cast(info.height), info.resolution, + info.origin.position.x, info.origin.position.y); + + int r = 0; + int c = 0; + if (!WorldToCell(info, args.gx, args.gy, r, c)) { + std::printf( + "❌ 目标 (%.2f, %.2f) 在地图范围外,发出去也是 ABORTED\n", args.gx, args.gy); + rclcpp::shutdown(); + return 1; + } + + const int v = data[static_cast(r) * info.width + c]; + const double clr = ClearanceAt(data, info, r, c, kClearanceSearch); + const char * state = StateName(static_cast(v)); + std::printf( + "目标 (%.2f, %.2f) -> 栅格 (%d, %d) 占据值 %4d (%s) 净空 %.2f m\n", + args.gx, args.gy, c, r, v, state, clr); + + const bool bad = std::string(state) != "空闲" || clr < kMinClearance; + if (bad) { + std::printf("\n❌ 这个点不适合当目标(净空需 >= %.2f m):\n", kMinClearance); + if (std::string(state) == "障碍") { + std::printf( + " 点落在障碍格里 —— 规划器必然报 \"Failed to create plan with tolerance\",换一个点。\n"); + } else if (std::string(state) == "未知") { + std::printf( + " 点落在未知区域 —— 代价地图开了 track_unknown_space,同样规划不出来。\n"); + } else { + std::printf( + " 净空只有 %.2f m,车身半对角就有 %.2f m,挤进去会卡死。\n", clr, kHalfDiagonal); + } + std::printf(" 想找安全点:python3 tools/free_goals.py\n"); + if (!args.force) { + std::printf(" (确实要发就加 --force)\n"); + rclcpp::shutdown(); + return 2; + } + std::printf(" --force 已指定,继续发送\n"); + } + } + + auto client = rclcpp_action::create_client(node, "navigate_to_pose"); + std::printf("等待 navigate_to_pose 动作服务器...\n"); + if (!client->wait_for_action_server(30s)) { + std::printf("❌ 动作服务器不可用(Nav2 没起来,或 bt_navigator 没 ACTIVE)\n"); + rclcpp::shutdown(); + return 1; + } + std::printf("✅ 动作服务器可用\n"); + + NavigateToPose::Goal goal; + goal.pose.header.frame_id = "map"; + goal.pose.header.stamp = node->now(); + goal.pose.pose.position.x = args.gx; + goal.pose.pose.position.y = args.gy; + const double yaw = args.yaw_deg * kPi / 180.0; + goal.pose.pose.orientation.z = std::sin(yaw / 2.0); + goal.pose.pose.orientation.w = std::cos(yaw / 2.0); + + // 注意:不要打印 feedback.distance_remaining。 + // Nav2 1.5 的 NavigateToPose 不会填这个字段,永远是 0.00, + // 打了只会刷屏骗人。用 current_pose 和 number_of_recoveries。 + auto last_print = std::chrono::steady_clock::now(); + + rclcpp_action::Client::SendGoalOptions send_options; + send_options.feedback_callback = [&last_print]( + GoalHandle::SharedPtr, + const std::shared_ptr feedback) { + const auto now = std::chrono::steady_clock::now(); + if (now - last_print < 1s) { + return; + } + last_print = now; + const auto & p = feedback->current_pose.pose.position; + std::printf( + " 位置 (%5.2f, %5.2f) 重试 %d\n", + p.x, p.y, static_cast(feedback->number_of_recoveries)); + }; + + const auto t_goal = std::chrono::steady_clock::now(); // 从发目标开始计时 + auto goal_future = client->async_send_goal(goal, send_options); + if (rclcpp::spin_until_future_complete(node, goal_future, 15s) != + rclcpp::FutureReturnCode::SUCCESS) + { + std::printf("❌ 目标被拒绝(耗时 %.1f s)\n", 0.0); + rclcpp::shutdown(); + return 1; + } + GoalHandle::SharedPtr handle = goal_future.get(); + if (!handle) { + std::printf("❌ 目标被拒绝\n"); + rclcpp::shutdown(); + return 1; + } + std::printf("✅ 目标已接受,等待结果...\n"); + + auto result_future = client->async_get_result(handle); + while (rclcpp::ok() && + std::chrono::steady_clock::now() - t_goal < 180s) + { + if (rclcpp::spin_until_future_complete(node, result_future, 200ms) == + rclcpp::FutureReturnCode::SUCCESS) + { + break; + } + } + const double elapsed = + std::chrono::duration(std::chrono::steady_clock::now() - t_goal).count(); + + if (result_future.valid() && result_future.wait_for(0s) == std::future_status::ready) { + const auto code = result_future.get().code; + const char * name = "❌ 未知状态"; + if (code == rclcpp_action::ResultCode::SUCCEEDED) { + name = "✅ SUCCEEDED"; + } else if (code == rclcpp_action::ResultCode::CANCELED) { + name = "❌ CANCELED"; + } else if (code == rclcpp_action::ResultCode::ABORTED) { + name = "❌ ABORTED"; + } + std::printf("结果: %s 导航耗时 %.1f s\n", name, elapsed); + } else { + std::printf("超时未完成(180 s,已等待 %.0f s)\n", elapsed); + } + + try { + const auto tr = tf_buffer.lookupTransform("map", "base_link", rclcpp::Time(0)); + const auto & p = tr.transform.translation; + const double err = std::hypot(p.x - args.gx, p.y - args.gy); + std::printf( + "TF map->base_link: (%.2f, %.2f) 离目标 %.2f m field 坐标 (%.2f, %.2f)\n", + p.x, p.y, err, p.x, p.y); + } catch (const std::exception & exc) { + std::printf("⚠️ 查不到 TF map->base_link: %s\n", exc.what()); + } + + rclcpp::shutdown(); + return 0; +} diff --git a/src/sentry_nav/src/odom_tf.cpp b/src/sentry_nav/src/odom_tf.cpp new file mode 100644 index 0000000..5e7411a --- /dev/null +++ b/src/sentry_nav/src/odom_tf.cpp @@ -0,0 +1,83 @@ +// Copyright 2026 sentry_nav_dev +// +// odom_tf:把 Gazebo 的 /odom 广播成 ROS TF:odom -> base_link。 +// (C++ 版,2026-11-17 从 scripts/odom_tf.py 移植;用户要求能 C++ 就 C++。) +// +// 为什么需要:Gazebo 的 MecanumDrive 插件只发 odometry 消息、不发 TF, +// 而 Nav2 需要完整 TF 树(map -> odom -> base_link)。这个节点补上 odom -> base_link。 +// +// 参数: +// odom_frame odom 广播的父坐标系 +// base_frame base_link 广播的子坐标系 +// odom_topic /odom 订阅的里程计话题 +// odom_scale 1.0 调试用:给里程计加比例误差(1.15 = 报告距离偏大 15%) + +#include +#include +#include + +#include +#include +#include +#include + +namespace sentry_nav +{ + +class OdomTf : public rclcpp::Node +{ +public: + OdomTf() : Node("sentry_odom_tf") + { + odom_frame_ = declare_parameter("odom_frame", "odom"); + base_frame_ = declare_parameter("base_frame", "base_link"); + const std::string topic = declare_parameter("odom_topic", "/odom"); + odom_scale_ = declare_parameter("odom_scale", 1.0); + + br_ = std::make_unique(this); + sub_ = create_subscription( + topic, 10, + [this](const nav_msgs::msg::Odometry::SharedPtr msg) { OnOdom(msg); }); + + RCLCPP_INFO( + get_logger(), "odom_tf: 订阅 %s,广播 %s -> %s,odom_scale=%.3f", + topic.c_str(), odom_frame_.c_str(), base_frame_.c_str(), odom_scale_); + if (std::abs(odom_scale_ - 1.0) > 1e-6) { + RCLCPP_WARN( + get_logger(), + "odom_tf: odom_scale=%.3f != 1.0 —— 里程计被人为打了比例误差,这是演示/调试用途", + odom_scale_); + } + } + +private: + void OnOdom(const nav_msgs::msg::Odometry::SharedPtr & msg) + { + geometry_msgs::msg::TransformStamped t; + t.header.stamp = msg->header.stamp; + t.header.frame_id = odom_frame_; + t.child_frame_id = base_frame_; + // odom_scale 只作用在平移上(轮径误差就是「距离按比例走偏」) + t.transform.translation.x = msg->pose.pose.position.x * odom_scale_; + t.transform.translation.y = msg->pose.pose.position.y * odom_scale_; + t.transform.translation.z = msg->pose.pose.position.z; + t.transform.rotation = msg->pose.pose.orientation; + br_->sendTransform(t); + } + + std::string odom_frame_; + std::string base_frame_; + double odom_scale_ = 1.0; + std::unique_ptr br_; + rclcpp::Subscription::SharedPtr sub_; +}; + +} // namespace sentry_nav + +int main(int argc, char * argv[]) +{ + rclcpp::init(argc, argv); + rclcpp::spin(std::make_shared()); + rclcpp::shutdown(); + return 0; +} diff --git a/src/sentry_nav/src/patrol.cpp b/src/sentry_nav/src/patrol.cpp index 01c7462..6109c9b 100644 --- a/src/sentry_nav/src/patrol.cpp +++ b/src/sentry_nav/src/patrol.cpp @@ -23,7 +23,7 @@ // // 用法(本工程不用 ament/colcon,没有 ros2 run,直接跑 xmake 产物): // build/linux/x86_64/release/patrol --ros-args -// -p waypoints:="[1.0,4.0, 2.0,2.0, 4.0,2.0, 6.0,4.0]" +// -p waypoints:="[-5.1,0.0, -4.0,-2.0, -2.0,-2.0, 0.0,0.0]" // (`--ros-args` 后面原本有个行尾反斜杠,会触发 -Wcomment 警告,已去掉; // 真要换行请用 shell 的续行,别在注释里留反斜杠) @@ -56,7 +56,7 @@ public: frame_id_ = declare_parameter("frame_id", "map"); const bool loop = declare_parameter("loop", true); const std::vector flat = declare_parameter>( - "waypoints", std::vector{1.0, 4.0, 2.0, 2.0, 4.0, 2.0, 6.0, 4.0}); + "waypoints", std::vector{-5.1, 0.0, -4.0, -2.0, -2.0, -2.0, 0.0, 0.0}); // 参数校验 + 解析都交给核心库(那份逻辑有单元测试) std::vector waypoints; diff --git a/src/sentry_nav/src/self_filter.cpp b/src/sentry_nav/src/self_filter.cpp index 172d6c1..9aa7ebf 100644 --- a/src/sentry_nav/src/self_filter.cpp +++ b/src/sentry_nav/src/self_filter.cpp @@ -14,6 +14,7 @@ // // 订阅:/scan/points sensor_msgs/msg/PointCloud2(lidar_link 坐标) // 发布:/scan/points_filtered sensor_msgs/msg/PointCloud2(base_link 坐标) +// 发布:/scan2d sensor_msgs/msg/LaserScan(base_link 坐标,供 AMCL 定位用) // // 参数(都可以在命令行覆盖): // input_topic /scan/points @@ -27,9 +28,17 @@ // box_max_z 0.60 // keep_min_z 0.02 剔除后仍要保留的最低高度(低于此视为地面/噪声) // max_range 12.0 超过此**水平**距离的点丢弃 +// scan_topic /scan2d 投影出的 2D 激光话题(给 AMCL;也喂 collision_monitor) +// scan_bins 360 方位角分格数(360 = 每度一格) +// scan_height_min 0.05 参与投影的最低高度(base_link 系,m) +// scan_height_max 0.50 参与投影的最高高度(base_link 系,m) +// scan_range_min 0.10 激光最小距离(m) +// scan_range_max 12.0 激光最大距离(m) #include +#include #include +#include #include #include @@ -38,6 +47,7 @@ #include #include +#include #include #include #include @@ -87,6 +97,17 @@ public: input_topic_, rclcpp::SensorDataQoS(), [this](sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) { OnCloud(msg); }); + // /scan2d:由过滤后的点云投影出的 2D 激光,AMCL 做定位用(collision_monitor 也吃它)。 + // 高度带取 [0.05, 0.50] m(base_link 系,车体碰撞带),保证与地图「体积投影」 + // 在同一高度带——这是修「AMCL 在 0.42 m 悬空平板附近跑飞」的关键(docs §4.1/§4.2)。 + scan_topic_ = declare_parameter("scan_topic", "/scan2d"); + scan_bins_ = declare_parameter("scan_bins", 360); + scan_height_min_ = declare_parameter("scan_height_min", 0.05); + scan_height_max_ = declare_parameter("scan_height_max", 0.50); + scan_range_min_ = declare_parameter("scan_range_min", 0.10); + scan_range_max_ = declare_parameter("scan_range_max", 12.0); + scan_pub_ = create_publisher(scan_topic_, rclcpp::QoS(10)); + RCLCPP_INFO( get_logger(), "self_filter: %s -> %s (frame=%s) 剔除盒子 x[%.2f,%.2f] y[%.2f,%.2f] z[%.2f,%.2f] " @@ -94,6 +115,11 @@ public: input_topic_.c_str(), output_topic_.c_str(), target_frame_.c_str(), params.box_min_x, params.box_max_x, params.box_min_y, params.box_max_y, params.box_min_z, params.box_max_z, params.keep_min_z, params.max_range); + RCLCPP_INFO( + get_logger(), + "self_filter: 投影 %s <- z∈[%.2f,%.2f] m, %d 束, 距离 [%.2f,%.1f] m", + scan_topic_.c_str(), scan_height_min_, scan_height_max_, scan_bins_, + scan_range_min_, scan_range_max_); } private: @@ -142,20 +168,72 @@ private: out.header.stamp = msg->header.stamp; out.header.frame_id = target_frame_; pub_->publish(out); + + // 同一份过滤结果再投影成 2D 激光:不新增订阅/进程,数据一致。 + PublishScan(filtered, msg->header.stamp); + } + + // 把过滤后的点云(已在 base_link 系)投影成 2D 激光: + // 每个方位格取该格内最小水平距离,z 只取车体碰撞带 [scan_height_min, scan_height_max]。 + // 这样投影结果与地图的「体积投影」在同一高度带,避免 AMCL 因高度失配把粒子整团迁走。 + void PublishScan( + const pcl::PointCloud & cloud, + const builtin_interfaces::msg::Time & stamp) + { + constexpr double kAngleMin = -M_PI; + constexpr double kAngleMax = M_PI; + const double increment = (kAngleMax - kAngleMin) / static_cast(scan_bins_); + + sensor_msgs::msg::LaserScan scan; + scan.header.stamp = stamp; + scan.header.frame_id = target_frame_; + scan.angle_min = static_cast(kAngleMin); + scan.angle_max = static_cast(kAngleMax); + scan.angle_increment = static_cast(increment); + scan.time_increment = 0.0f; + scan.scan_time = 0.1f; + scan.range_min = static_cast(scan_range_min_); + scan.range_max = static_cast(scan_range_max_); + scan.ranges.assign( + static_cast(scan_bins_), std::numeric_limits::infinity()); + + for (const auto & pt : cloud) { + if (pt.z < scan_height_min_ || pt.z > scan_height_max_) { + continue; + } + const double range = std::hypot(pt.x, pt.y); + if (range < scan_range_min_ || range > scan_range_max_) { + continue; + } + int bin = static_cast((std::atan2(pt.y, pt.x) - kAngleMin) / increment); + bin = bin < 0 ? 0 : (bin >= scan_bins_ ? scan_bins_ - 1 : bin); + if (range < scan.ranges[bin]) { + scan.ranges[bin] = static_cast(range); + } + } + scan_pub_->publish(scan); } std::string input_topic_; std::string output_topic_; std::string target_frame_; + std::string scan_topic_; std::unique_ptr core_; std::uint64_t total_in_{0}; std::uint64_t total_out_{0}; + int scan_bins_{360}; + double scan_height_min_{0.05}; + double scan_height_max_{0.50}; + double scan_range_min_{0.10}; + double scan_range_max_{12.0}; + std::unique_ptr tf_buffer_; std::shared_ptr tf_listener_; rclcpp::Publisher::SharedPtr pub_; + rclcpp::Publisher::SharedPtr scan_pub_; rclcpp::Subscription::SharedPtr sub_; }; diff --git a/src/sentry_nav/xmake.lua b/src/sentry_nav/xmake.lua index af55e27..d917d9e 100644 --- a/src/sentry_nav/xmake.lua +++ b/src/sentry_nav/xmake.lua @@ -147,5 +147,30 @@ target("patrol") add_linkgroups(libs, { group = true }) ros_common() +-- ---- 导航测试客户端(C++ 版,替代原 tools/nav_client.py)---- +-- 用法:build/linux/x86_64/release/nav_client [yaw度] [--force] +-- 输出格式与原 Python 版一致(含导航耗时),文档按这个格式写。 +target("nav_client") + set_kind("binary") + add_files("src/nav_client.cpp") + add_linkgroups(libs, { group = true }) + ros_common() + +-- ---- 运行时小节点(从 Python 移植,用户要求能 C++ 就 C++)---- +-- odom_tf:/odom -> TF odom->base_link(sentry_up.sh 第 5 步用) +target("odom_tf") + set_kind("binary") + add_files("src/odom_tf.cpp") + add_linkgroups(libs, { group = true }) + ros_common() + +-- cmd_vel_relay:/cmd_vel_smoothed 优先转发到 /model/sentry/cmd_vel +-- (sentry_up.sh 第 5.5 步用) +target("cmd_vel_relay") + set_kind("binary") + add_files("src/cmd_vel_relay.cpp") + add_linkgroups(libs, { group = true }) + ros_common() + -- 编译数据库(compile_commands.json)的自动刷新规则定义在仓库根的 xmake.lua, -- 输出到仓库根 —— clangd 读的就是那里。 diff --git a/src/sentry_sim/README.md b/src/sentry_sim/README.md index 5cd3729..f464796 100644 --- a/src/sentry_sim/README.md +++ b/src/sentry_sim/README.md @@ -10,7 +10,7 @@ | `worlds/` | 仿真世界(RMUL 场地 + 哨兵) | | `meshes/` | 减面后的网格;`full/` 存原始高模 + 布局数据 | | `config/` | Nav2 参数、RViz 配置 | -| `scripts/` | 启动/桥接/转发用的 shell 与 python 脚本 | +| `scripts/` | 启动/桥接用的 shell;转发、odom_tf 已迁到 xmake 编的 C++ 二进制(见下文「代码语言约定」) | | `launch/` | `ros2 launch` 入口(和 `scripts/sentry_up.sh` 等价,二选一) | ## 怎么被用到 @@ -52,3 +52,141 @@ scripts/sentry_up.sh ```bash cd ~/Gazebo_projects/sentry_nav_dev && scripts/sentry_up.sh ``` + +--- + +## 车辆参数(2026-11-17 版,速度 1.5 m/s) + +### 速度与加速度 + +车能跑多快由**三层**共同决定,改任何一层都要重启仿真: + +| 层 | 位置 | 当前值 | 说明 | +|---|---|---|---| +| ① 物理上限 | `urdf/sentry.urdf.xacro` 的 MecanumDrive 插件 → `models/sentry/model.sdf` | `max_linear_velocity: 2.0` m/s,`max_angular_velocity: 4.0` rad/s | 改 URDF 后必须跑 `./tools/gen_sdf.sh` 重新生成 SDF | +| ② 速度平滑器 | `config/nav2_params.yaml` → `velocity_smoother` | `max_velocity: [1.5, 0.0, 2.0]`(m/s、m/s、rad/s),`max_accel: [4.0, 0.0, 4.0]`,`max_decel: [-4.0, 0.0, -4.0]` | **最高速度实际由这里决定**;加速度同样在这里限制 | +| ③ 控制器采样上限 | `config/nav2_params.yaml` → `controller_server` 的 `FollowPath`(MPPI) | `vx_max: 1.5`,`vx_min: -0.5`,`wz_max: 1.9`,`ax_max: 3.5`,`ax_min: -3.5` | 必须 ≥ 平滑器的上限,否则平滑器设了也没用 | + +> 麦轮在 Gazebo 里是圆柱轮(没有 45° 滚子),**不能侧移**,控制器只发前进+转向(差速), +> 见 `nav2_params.yaml` 里 `motion_model: "diff_drive"` 的注释。 + +### 车体尺寸与轮子 + +| 参数 | 值 | 出处 | +|---|---|---| +| 车体外轮廓(碰撞用) | 0.65 × 0.54 m(footprint 外扩后的矩形) | `nav2_params.yaml` 的 `footprint` | +| 底盘碰撞盒 | 0.578 × 0.521 × 0.25 m,**底面离地 2 cm** | `urdf/sentry.urdf.xacro`(抬离地面,避免静摩擦拖死轮子) | +| 整车质量 | 车体 25 kg + 4×轮 1.5 kg ≈ 31 kg | URDF `` | +| 轮半径 | 0.0762 m | URDF `wheel_radius` | +| 轮距(左右)wheel_separation | 0.4263 m | `model.sdf` MecanumDrive | +| 轴距(前后)wheelbase | 0.3323 m | `model.sdf` MecanumDrive | +| 车身半对角 | 0.422 m(nav_client 用它判断目标点净空) | `nav_client` 常量 | + +### 传感器(仿真) + +| 传感器 | 位置/参数 | 话题 | +|---|---|---| +| 3D 激光雷达(CPU 射线) | 360 线 × 40 层,垂直 -7°~+52°,量程 0.10–12 m,10 Hz,噪声 σ=0.01;装在 `lidar_link`(z≈0.405) | gz `scan` → `/scan`(LaserScan)+ `/scan/points`(PointCloud2,frame=`lidar_link`) | +| 点云自滤 | 剔除车身包围盒内回波 | 输入 `/scan/points` → 输出 `/scan/points_filtered`(frame=`base_link`) | +| 2D 激光(定位用) | 由自滤节点从 3D 点云投影:z∈[0.05, 0.50] m、360 格 | `/scan2d`(frame=`base_link`,AMCL / collision_monitor 用) | +| IMU | `imu_link`,100 Hz | gz `imu` → `/imu` | + +> 雷达帧链路已核实正确:`/scan`、`/scan/points` 都是 `lidar_link`,过滤后是 `base_link`。 +> RViz 里如果点云「不动」,原因是 CPU 过载时 RViz 掉帧、显示的是旧数据(见文末「CPU」一节), +> 不是 TF 错了。 + +### 坐标约定 + +场地中心 = **(0, 0)**,x∈[-6, 6],y∈[-4, 4](map 帧;field 帧与 map 恒等)。 +出生点 = **(-5.0, 3.0)**,`worlds/sentry_arena.sdf` 的 sentry `` 和 +`nav2_params.yaml` 的 amcl `initial_pose` 两处必须一致。 + +## 寻路逻辑写在哪 + +本工程**不改 Nav2 源码**,寻路全部是「Nav2 栈 + 参数配置 + 我们自己的决策层」: + +| 环节 | 实现位置 | 说明 | +|---|---|---| +| 全局路径规划 | `config/nav2_params.yaml` → `planner_server.GridBased`(`nav2_navfn_planner::NavfnPlanner`,`use_astar: false` = Dijkstra 波前,`tolerance: 0.5`) | 规划器本身是 Nav2 自带算法,参数在 YAML 里 | +| 局部控制/避障 | `config/nav2_params.yaml` → `controller_server.FollowPath`(`nav2_mppi_controller`,含 Cost/Goal/PathAlign 等 critics) | MPPI 采样 56 步 × 2000 批,差速模型 | +| 速度平滑/加速度限制 | `config/nav2_params.yaml` → `velocity_smoother` | 见上表 | +| 碰撞监控(临近障碍急停) | `config/nav2_params.yaml` → `collision_monitor`(FootprintApproach,source=`/scan2d`) | 在 smoothed 与 gz 之间兜底 | +| 行为树(重试/恢复) | Nav2 默认 `nav2_bt_navigator/behavior_trees` 的 `navigate_to_pose_w_replanning_and_recovery.xml` | 规划失败 → 原地转/倒车重试 | +| **多点巡逻(我们的决策层)** | `src/sentry_nav/src/patrol.cpp` + 纯逻辑 `src/core/waypoint_sequencer.cpp`(xmake 单测) | 依次发 `NavigateToPose`,走完循环回第一个点 | +| **测试客户端** | `build/linux/x86_64/release/nav_client`(C++,源码 `src/sentry_nav/src/nav_client.cpp`) | 发单目标 + 目标点预检 + 输出导航耗时 | + +### 发目标 / 测导航 + +```bash +# 先编译(首次或改了 C++ 源码之后) +cd ~/Gazebo_projects/sentry_nav_dev && xmake + +# 起仿真 +scripts/sentry_up.sh + +# 发目标(坐标是 map 帧,场地中心=(0,0)) +build/linux/x86_64/release/nav_client 0.0 0.0 # 到场地中心 +build/linux/x86_64/release/nav_client 0.0 0.0 90 # 到位置后朝向 +90° +build/linux/x86_64/release/nav_client -4.0 -2.0 # 任意点 + +# 多点巡逻(Nav2 运行动作客户端) +build/linux/x86_64/release/patrol --ros-args -p waypoints:="[-5.1,0.0, -4.0,-2.0, -2.0,-2.0, 0.0,0.0]" +``` + +`nav_client` 输出示例(含总耗时): + +``` +目标 (0.00, 0.00) -> 栅格 (255, 175) 占据值 0 (空闲) 净空 1.48 m +✅ 动作服务器可用 +✅ 目标已接受,等待结果... +结果: ✅ SUCCEEDED 导航耗时 24.5 s +TF map->base_link: (0.01, -0.18) 离目标 0.18 m field 坐标 (0.01, -0.18) +``` + +## 速度怎么改(1.5 m/s 是怎么来的) + +2026-11-17 把最高速度从 0.5 m/s 提到 **1.5 m/s**,共改了三处(都在上面「速度与加速度」表里): + +```yaml +# config/nav2_params.yaml → velocity_smoother +max_velocity: [1.5, 0.0, 2.0] # 线速度 1.5 m/s、角速度 2.0 rad/s +max_accel: [4.0, 0.0, 4.0] # 加速度 4 m/s²(10 s 内可到 40 m/s,远超需求) +max_decel: [-4.0, 0.0, -4.0] + +# config/nav2_params.yaml → controller_server.FollowPath(MPPI) +vx_max: 1.5 +vx_min: -0.5 +ax_max: 3.5 +ax_min: -3.5 +``` + +改完**直接重启** `scripts/sentry_up.sh`。注意: +- 速度越快,AMCL 里程计误差、MPPI 预测偏差都会被放大,真机标定 `alpha1~alpha4` 之前别超过 1.5; +- 场地走廊宽约 1.5~2.5 m,1.5 m/s 下 10 s 的进度检查(`SimpleProgressChecker`)更容易过,但**恢复行为**触发时(原地转/倒车)整体耗时仍会变长。 + +## 代码语言约定(用户要求:能用 C++ 就别用 Python) + +已迁移到 C++(xmake 编译,产物在 `build/linux/x86_64/release/`): + +| 原 Python | 现 C++ | 用途 | +|---|---|---| +| `tools/nav_client.py` | `src/sentry_nav/src/nav_client.cpp` → `nav_client` | 发目标 + 预检 + 耗时输出 | +| `scripts/odom_tf.py` | `src/sentry_nav/src/odom_tf.cpp` → `odom_tf` | `/odom` → TF `odom->base_link` | +| `scripts/cmd_vel_relay.py` | `src/sentry_nav/src/cmd_vel_relay.cpp` → `cmd_vel_relay` | 平滑命令优先转发到 gz | + +`scripts/sentry_up.sh` 已经直接调用这三个二进制(不再 `python3`)。 +剩余 Python:`tools/free_goals.py`(离线目标点搜索)、`tools/check_stack.py`(栈自检)——逐步迁移中。 +`launch/sentry_arena.launch.py` 是 ROS launch 系统要求,**没法用 C++**。 + +## CPU 忙不过来怎么办(雷达是 CPU 射线) + +3D 雷达是 `type="lidar"`(CPU 射线),360×40 = **14,400 束/帧 × 10 Hz**, +再加 Gazebo 渲染 + RViz,是整台机器最大的 CPU 消耗。可选手段: + +1. **关 RViz**:`RVIZ=0 scripts/sentry_up.sh`(导航不受影响,需要看图时另开 RViz); +2. **降低雷达竖直采样**:`urdf/sentry.urdf.xacro` 里 `40` 改小(如 24), + 再 `./tools/gen_sdf.sh`——代价是点云变稀; +3. **GPU 辅助**:把传感器换成 `gpu_lidar`(OGRE2 渲染,射线在 GPU 上算)。 + 前提是显卡驱动可用:本机有 RTX 5060 Max-Q,但当前 `nvidia-smi` 连不上驱动(prime on-demand + 模式下驱动未加载),**先修驱动再谈 GPU 雷达**;修好后把 URDF 换成 gpu_lidar 即可显著降 CPU。 + diff --git a/src/sentry_sim/config/nav2_params.yaml b/src/sentry_sim/config/nav2_params.yaml index abce506..93f70aa 100644 --- a/src/sentry_sim/config/nav2_params.yaml +++ b/src/sentry_sim/config/nav2_params.yaml @@ -14,7 +14,7 @@ amcl: lambda_short: 0.1 laser_likelihood_max_dist: 2.0 laser_max_range: 12.0 # 雷达量程 12 m(真机 40 m),写 100 会把虚警算成有效 - laser_min_range: 0.6 # 车体最远 0.537 m,低于 0.6 的束全是自己的回波 + laser_min_range: 0.15 # 自击点已被 self_filter 在投影时剔除,不用靠 0.6 遮挡 laser_model_type: "likelihood_field" max_beams: 60 max_particles: 2000 @@ -29,7 +29,8 @@ amcl: recovery_alpha_slow: 0.001 random_seed: -1 resample_interval: 1 - robot_model_type: "nav2_amcl::OmniMotionModel" # 麦轮全向,差速模型会低估侧移 + # 与控制器保持一致:仿真里麦轮按差速运动,不用全向模型(否则预测与现实脱节)。 + robot_model_type: "nav2_amcl::DifferentialMotionModel" save_pose_rate: 0.5 sigma_hit: 0.2 tf_broadcast: true @@ -41,12 +42,13 @@ amcl: z_max: 0.05 z_rand: 0.5 z_short: 0.05 - scan_topic: scan2d # /scan 仰角 +22.5° 不可用,用 0° 单线雷达 - # ---- 本工程:开机即给初始位姿(RMUL 场地红方出生点) + scan_topic: scan2d # /scan 仰角 +22.5° 不可用;scan2d 由 self_filter 从 3D 点云投影生成 + # ---- 本工程:开机即给初始位姿(场地中心 = (0,0);当前出生点 (-5.0, 3.0), + # 必须与 world 里 sentry 的出生点一致) set_initial_pose: true initial_pose: - x: 0.9 - y: 4.0 + x: -5.0 + y: 3.0 z: 0.0 yaw: 0.0 @@ -162,16 +164,16 @@ controller_server: model_delay_wz: 0.0 batch_size: 2000 open_loop: false - ax_max: 3.0 - ax_min: -3.0 + ax_max: 3.5 + ax_min: -3.5 ay_max: 3.0 ay_min: -3.0 az_max: 3.5 vx_std: 0.2 vy_std: 0.2 wz_std: 0.4 - vx_max: 0.5 - vx_min: -0.35 + vx_max: 1.5 + vx_min: -0.5 vy_max: 0.5 wz_max: 1.9 iteration_count: 1 @@ -181,8 +183,11 @@ controller_server: publish_optimal_trajectory: true regenerate_noises: true motion_model: "diff_drive" + # 麦轮在 Gazebo 里是圆柱轮(没有 45° 滚子),侧移指令执行不了—— + # 发 vy 会让车原地打转、odom 却按理想麦轮积分(假移动)。 + # 所以控制器只发前进+转向(差速),物理和 odom 才能对得上。 diff_drive: - plugin: "mppi::OmniMotionModel" + plugin: "mppi::DiffDriveMotionModel" TrajectoryVisualizer: trajectory_step: 5 time_step: 3 @@ -527,10 +532,14 @@ velocity_smoother: smoothing_frequency: 20.0 scale_velocities: false feedback: "OPEN_LOOP" - max_velocity: [0.5, 0.0, 2.0] + # 2026-11-17:车最高速度 0.5 → 1.5 m/s(用户要求)。 + # 麦轮仿真插件 max_linear_velocity=2.0,1.5 在物理上限内。 + # 注意:速度越快,AMCL 的 odom 积分误差、MPPI 的预测偏差都会放大, + # 真机标定 alpha 参数前别超过 1.5。 + max_velocity: [1.5, 0.0, 2.0] min_velocity: [-0.5, 0.0, -2.0] - max_accel: [3.0, 0.0, 3.5] - max_decel: [-3.0, 0.0, -3.5] + max_accel: [4.0, 0.0, 4.0] + max_decel: [-4.0, 0.0, -4.0] odom_topic: "odom" odom_duration: 0.1 deadband_velocity: [0.0, 0.0, 0.0] diff --git a/src/sentry_sim/launch/sentry_arena.launch.py b/src/sentry_sim/launch/sentry_arena.launch.py index 754c344..8fc851f 100644 --- a/src/sentry_sim/launch/sentry_arena.launch.py +++ b/src/sentry_sim/launch/sentry_arena.launch.py @@ -36,8 +36,8 @@ ------ 同时发布两条静态变换: - map → odom 平移 (0.9, 4.0) 仿真里用里程计当真值,替代 AMCL - map → field 平移 (6.0, 4.0) 场地中心 = 零点 + map → odom 平移 (-5.0, 3.0) 仿真里用里程计当真值,替代 AMCL + map → field 恒等变换 两者都已是「场地中心 = 零点」 `map` 是官方栅格图坐标系(西南内角 = (0,0)),`field` 是给决策代码用的直觉坐标系。 """ @@ -213,7 +213,7 @@ def generate_launch_description(): # 如果写成嵌套列表 ['-p', 'odom_scale:=', v],会被拼成 "-podom_scale:=1.15"(没空格), # rclpy 的参数解析会直接报错。 ExecuteProcess( - cmd=['python3', str(SCRIPTS / 'odom_tf.py'), '--ros-args', + cmd=[str(BIN_DIR / 'odom_tf'), '--ros-args', '-p', 'use_sim_time:=true', '-p', 'odom_scale:=' + os.environ.get('SENTRY_ODOM_SCALE', '1.0')], name='odom_tf', @@ -223,7 +223,7 @@ def generate_launch_description(): # ---------------- 5. /cmd_vel 改名转发 ---------------- # 插件订阅 /model/sentry/cmd_vel,而桥只支持两端同名 ExecuteProcess( - cmd=['python3', str(SCRIPTS / 'cmd_vel_relay.py'), + cmd=[str(BIN_DIR / 'cmd_vel_relay'), '--ros-args', '-p', 'use_sim_time:=true'], name='cmd_vel_relay', output='screen', @@ -243,16 +243,16 @@ def generate_launch_description(): # 否则两个发布者打架。要回到"作弊定位"就把 use_localization 改 False 并放开下面: # Node(package='tf2_ros', executable='static_transform_publisher', # name='map_to_odom', - # arguments=['--x','0.9','--y','4.0','--z','0.0', + # arguments=['--x','1.0','--y','1.0','--z','0.0', # '--yaw','0.0','--pitch','0.0','--roll','0.0', # '--frame-id','map','--child-frame-id','odom'], # parameters=[{'use_sim_time': True}], output='screen'), - # map -> field:场地中心 = 零点。场地 12×8 → field 系 x[-6,6] y[-4,4] + # map -> field:恒等变换(map 已以场地中心为原点) Node( package='tf2_ros', executable='static_transform_publisher', name='map_to_field', - arguments=['--x', '6.0', '--y', '4.0', '--z', '0.0', + arguments=['--x', '0.0', '--y', '0.0', '--z', '0.0', '--yaw', '0.0', '--pitch', '0.0', '--roll', '0.0', '--frame-id', 'map', '--child-frame-id', 'field'], parameters=[{'use_sim_time': True}], @@ -297,8 +297,8 @@ def generate_launch_description(): LogInfo(msg=[ '\n[sentry_arena] 坐标系:', - '\n map 官方栅格图坐标系,西南内角 = (0,0),场地中心 = (6.0, 4.0)', - '\n field 场地中心 = (0,0),范围 x[-6,6] y[-4,4],出生点在 (-5.1, 0.0)', + '\n map 场地中心 = (0,0),范围 x[-6,6] y[-4,4],出生点在 (-5.0, 3.0)', + '\n field 与 map 相同(恒等变换,保留给决策代码用)', '\n[sentry_arena] 体检:python3 tools/check_stack.py', ]), ] diff --git a/src/sentry_sim/models/arena_roof/README.md b/src/sentry_sim/models/arena_roof/README.md index 4a86ce6..c468479 100644 --- a/src/sentry_sim/models/arena_roof/README.md +++ b/src/sentry_sim/models/arena_roof/README.md @@ -25,9 +25,9 @@ | 部件 | 尺寸 | 位置 | |---|---|---| -| 顶棚平板 | **40.8 × 28.8 × 0.2 m** | 中心 (6, 4, **10.0**) | -| 东西向主梁 ×5 | 40.8 × 0.3 × 0.4 m | y = −8 / −2 / 4 / 10 / 16,z = 9.55 | -| 南北向次梁 ×3 | 0.3 × 28.8 × 0.4 m | x = −8 / 6 / 20,z = 9.30 | +| 顶棚平板 | **40.8 × 28.8 × 0.2 m** | 中心 (0, 0, **10.0**) | +| 东西向主梁 ×5 | 40.8 × 0.3 × 0.4 m | y = −12 / −6 / 0 / 6 / 12,z = 9.55 | +| 南北向次梁 ×3 | 0.3 × 28.8 × 0.4 m | x = −14 / 0 / 14,z = 9.30 | | 照明灯带 ×12 | 3.0 × 0.5 × 0.08 m | 3 列 × 4 排,z = 9.05,emissive 自发光 | ## 可见性问题(踩过一次) diff --git a/src/sentry_sim/models/arena_walls/README.md b/src/sentry_sim/models/arena_walls/README.md index cda93cd..bfe0c1b 100644 --- a/src/sentry_sim/models/arena_walls/README.md +++ b/src/sentry_sim/models/arena_walls/README.md @@ -5,12 +5,12 @@ ## 尺寸 -大厅以场地中心 **(6, 4)** 为中心: +大厅以场地中心 **(0, 0)** 为中心(世界坐标已整体平移 −6,−4): | 项 | 值 | |---|---| -| **内空** | **40.0 × 28.0 m**(x ∈ [−14, 26],y ∈ [−10, 18]) | -| 外沿 | 40.8 × 28.8 m(x ∈ [−14.4, 26.4],y ∈ [−10.4, 18.4]) | +| **内空** | **40.0 × 28.0 m**(x ∈ [−20, 20],y ∈ [−14, 14]) | +| 外沿 | 40.8 × 28.8 m(x ∈ [−20.4, 20.4],y ∈ [−14.4, 14.4]) | | 墙厚 | 0.4 m | | **墙高** | **10.0 m** | | 大厅地面 | 40.8 × 28.8 × 0.1 m,顶面 z = **−0.02** | @@ -24,11 +24,11 @@ 但**加了碰撞,激光依然打不到墙**,原因是距离: -1. 墙最内侧面离机器人出生点 (0.9, 4.0) 最近也有 **14.0 m**(南北墙), +1. 墙最内侧面离机器人出生点 (1.0, 1.0) 最近也有 **13.0 m**(北墙), MID-360 量程只有 12 m。 -2. **东墙永远进不了量程**:场地本身 12 m 宽,机器人出生在西边(x=0.9), - 光场地另一头就有 11 m。想让东墙进 12 m,大厅东面得放到 x ≤ 12.9 —— - 那大厅就只比场地宽 0.6 m,没有意义。 +2. **东墙永远进不了量程**:大厅东墙在 x = 20,离出生点 (1.0, 1.0) 有 19 m。 + 想让东墙进 12 m,大厅东面得放到 x ≤ 13 附近 —— + 那大厅就只比场地大得有限,没有意义。 实测确认:加碰撞前后点云完全一致(有效点 3612 / 5760,最大距离 11.70 m)。 diff --git a/src/sentry_sim/models/arena_walls/model.sdf b/src/sentry_sim/models/arena_walls/model.sdf index 6d47cd7..cd1db89 100644 --- a/src/sentry_sim/models/arena_walls/model.sdf +++ b/src/sentry_sim/models/arena_walls/model.sdf @@ -10,10 +10,11 @@ ============================================================================ 尺寸 ============================================================================ - 大厅内空 40.0 × 28.0 m,墙厚 0.4 m,墙高 10.0 m,以场地中心 (6, 4) 为中心: + 大厅内空 40.0 × 28.0 m,墙厚 0.4 m,墙高 10.0 m,以场地中心 (0, 0) 为中心 + (世界坐标已整体平移): - 内空范围 x ∈ [-14, 26] y ∈ [-10, 18] - 外沿范围 x ∈ [-14.4, 26.4] y ∈ [-10.4, 18.4] + 内空范围 x ∈ [-20, 20] y ∈ [-14, 14] + 外沿范围 x ∈ [-20.4, 20.4] y ∈ [-14.4, 14.4] 对照:场地 12 × 8 m、拦截网 13.1 × 9.1 m —— 大厅比场地大 3 倍多。 @@ -23,7 +24,7 @@ 四面墙和地面**都有** collision(2026-11-16 用户要求加)。 加碰撞不会污染点云,因为: - 1. 墙最内侧面离机器人出生点 (0.9, 4.0) 最近也有 14.0 m(南北墙), + 1. 墙最内侧面离机器人出生点 (1.0, 1.0) 最近也有 13.0 m(北墙), MID-360 量程只有 12 m —— 永远打不到。 2. 机器人也出不去(场地围挡 0.42 m 挡着)。 diff --git a/src/sentry_sim/models/catch_net/model.sdf b/src/sentry_sim/models/catch_net/model.sdf index 53beb52..ff16dba 100644 --- a/src/sentry_sim/models/catch_net/model.sdf +++ b/src/sentry_sim/models/catch_net/model.sdf @@ -18,15 +18,15 @@ 围挡高 0.42 m,厚 0.3 m 网的位置 = 外框再向外 0.25 m - x = 0.55(西) x = 12.55(东) - y = 0.55(南) y = 8.55(北) + x = -5.45(西) x = 6.55(东) + y = -3.45(南) y = 4.55(北) 网内净空 13.10 × 9.10 m 网高 = 3.50 m - 验算:机器人出生在 (0.9, 4.0),到东网 11.65 m。 - +15° 射线在 11.65 m 处高度 = 0.4052 + 11.65*tan(15°) = 3.53 m - 差 3 cm 会从网顶飞过,其余 15 条线全部被网挡住。 - 想让 16 条线全关住,把高度改成 3.70 即可。 + 验算:机器人出生在 (1.0, 1.0),到东网 5.55 m。 + +15° 射线在 5.55 m 处高度 = 0.4052 + 5.55*tan(15°) = 1.89 m + 远低于网高 3.5 m,全部 16 条线都被网挡住。 + (该模型已停用,以上数值按当前出生点算,恢复时请重新核对。) ============================================================================ 为什么用 transparency 而不是网格纹理 diff --git a/src/sentry_sim/models/sentry/model.sdf b/src/sentry_sim/models/sentry/model.sdf index ca1844c..193d2af 100644 --- a/src/sentry_sim/models/sentry/model.sdf +++ b/src/sentry_sim/models/sentry/model.sdf @@ -14,7 +14,7 @@ - 0 0 0.125 0 0 0 + 0 0 0.14499999999999999 0 0 0 0.57799999999999996 0.52100000000000002 0.25 @@ -96,40 +96,6 @@ -0.0935 -0.1512 0.4052 0 0 0 lidar_link - - scan2d - 10 - true - false - - - - 360 - 1 - -3.1415926500000002 - 3.1415926500000002 - - - 1 - 1 - 0 - 0 - - - - 0.10000000000000001 - 12 - 0.01 - - - gaussian - 0 - 0.01 - - - -0.0935 -0.1512 0.4052 0 0 0 - lidar_link - -0.16582 0.21351999999999999 0.076200000000000004 0 0 0 diff --git a/src/sentry_sim/scripts/README.md b/src/sentry_sim/scripts/README.md index 7f27191..aa31d43 100644 --- a/src/sentry_sim/scripts/README.md +++ b/src/sentry_sim/scripts/README.md @@ -7,8 +7,8 @@ | `sentry_up.sh` | ★ 一键启动:Gazebo → 桥 → robot_state_publisher → odom_tf → cmd_vel_relay → **self_filter** → map→odom → **map_server** → Nav2 → RViz | | `run_gz.sh` | 用系统版 Gazebo 启动并清掉 ROS vendor 的 `LD_LIBRARY_PATH` | | `bridge_after_gz.sh` | 轮询 `/clock`,等 Gazebo 真正就绪后再启动 ros_gz 桥 | -| `odom_tf.py` | 把 `/odom` 广播成 TF `odom -> base_link`(Gazebo 不发这段 TF)。由 `python3` 直接执行,不走 `ros2 run` | -| `cmd_vel_relay.py` | 把 Nav2 的 `/cmd_vel` 改名转发到 `/model/sentry/cmd_vel`。同上,`python3` 直接执行 | +| `odom_tf.py` ~~已迁移~~ | 原 Python 版已删除;现用 `build/linux/x86_64/release/odom_tf`(C++,源码 `src/sentry_nav/src/odom_tf.cpp`)。把 `/odom` 广播成 TF `odom -> base_link`(Gazebo 不发这段 TF),不走 `ros2 run` | +| `cmd_vel_relay.py` ~~已迁移~~ | 原 Python 版已删除;现用 `build/linux/x86_64/release/cmd_vel_relay`(C++,源码 `src/sentry_nav/src/cmd_vel_relay.cpp`)。把 `/cmd_vel` 改名转发到 `/model/sentry/cmd_vel` | | (内联于 `sentry_up.sh`) | `build/linux/x86_64/release/self_filter`:点云自滤,Nav2 避障依赖它(xmake 产物,不是 `ros2 run`) | | (内联于 `sentry_up.sh`) | `map`→`field` 静态变换:把场地中心设为 `field` 系原点(`map` 系仍是官方西南内角原点) | | (内联于 `sentry_up.sh`) | `map_server` + `lifecycle_manager`:关掉 AMCL 后 Nav2 不带地图服务,必须单独起 | @@ -20,8 +20,8 @@ |---|---| | `run_gz.sh` 清库路径 | source 过 ROS 后 `gz` 会指向 vendor 版 10.5,行为不一致 | | `bridge_after_gz.sh` | 桥先于 gz 话题存在就订阅,实测收不到数据 | -| `odom_tf.py` | Nav2 缺 `odom -> base_link`,直接报 TF 超时 | -| `cmd_vel_relay.py` | 插件话题带模型名前缀,而桥只支持两端同名 → 车不动 | +| `odom_tf.py` ~~已迁移~~ | Nav2 缺 `odom -> base_link`,直接报 TF 超时 | +| `cmd_vel_relay.py` ~~已迁移~~ | 插件话题带模型名前缀,而桥只支持两端同名 → 车不动 | | 内联 `self_filter` | 点云混着车身自身回波,代价地图把车标成障碍 → 控制器不敢动 | | 内联 `map_server` | 关 AMCL 后没人发 `/map`,代价地图退回 100×100 默认尺寸 → 规划失败 | diff --git a/src/sentry_sim/scripts/bridge_after_gz.sh b/src/sentry_sim/scripts/bridge_after_gz.sh index 01614df..56fce8a 100755 --- a/src/sentry_sim/scripts/bridge_after_gz.sh +++ b/src/sentry_sim/scripts/bridge_after_gz.sh @@ -24,5 +24,4 @@ exec ros2 run ros_gz_bridge parameter_bridge \ '/scan@sensor_msgs/msg/LaserScan[gz.msgs.LaserScan' \ '/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \ '/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \ - '/scan2d@sensor_msgs/msg/LaserScan[gz.msgs.LaserScan' \ --ros-args -p use_sim_time:=true diff --git a/src/sentry_sim/scripts/cmd_vel_relay.py b/src/sentry_sim/scripts/cmd_vel_relay.py deleted file mode 100755 index 3e4fa6e..0000000 --- a/src/sentry_sim/scripts/cmd_vel_relay.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python3 -"""把 Nav2 的 /cmd_vel 转发到 ros_gz 桥用的 /model/sentry/cmd_vel。 - -为什么需要:Gazebo 的 MecanumDrive 插件订阅的是「模型名/cmd_vel」(即 -/model/sentry/cmd_vel),而 ros_gz_bridge 只支持「两端同名」的桥接, -它无法把 ROS 的 /cmd_vel 映射到 gz 的 /model/sentry/cmd_vel。 -所以这里做一次 ROS 侧的改名转发:/cmd_vel -> /model/sentry/cmd_vel, -再由 parameter_bridge 送进 Gazebo。 -""" - -import rclpy -from geometry_msgs.msg import Twist -from rclpy.executors import ExternalShutdownException -from rclpy.node import Node - - -class CmdVelRelay(Node): - def __init__(self): - super().__init__('cmd_vel_relay') - self.declare_parameter('out_topic', '/model/sentry/cmd_vel') - # Nav2 的实际输出可能是 /cmd_vel_smoothed(速度平滑器)或 /cmd_vel_nav(控制器), - # 取决于 launch 里启用哪些节点,所以这几个都监听,转发到同一个出口。 - self.declare_parameter('in_topics', [ - '/cmd_vel_smoothed', '/cmd_vel', '/cmd_vel_nav']) - out_topic = self.get_parameter('out_topic').value - in_topics = self.get_parameter('in_topics').value - - self.pub = self.create_publisher(Twist, out_topic, 10) - for topic in in_topics: - self.create_subscription(Twist, topic, self.on_twist, 10) - self.get_logger().info(f'cmd_vel_relay: {in_topics} -> {out_topic}') - - def on_twist(self, msg: Twist): - self.pub.publish(msg) - - -def main(): - rclpy.init() - node = CmdVelRelay() - try: - rclpy.spin(node) - except KeyboardInterrupt: - pass - except ExternalShutdownException: - # Ctrl+C 或 SIGTERM 时 rclpy 的信号处理已经把 context 关掉了, - # executor 等完一轮发现 context 不再 ok 就走这里。属于正常退出。 - pass - except Exception: # noqa: BLE001 - # 同一个退出竞态的另一副面孔:如果 context 在进入下一轮循环前就关了, - # _rclpy.WaitSet 构造会直接抛 RCLError(failed to initialize wait set …)。 - # RCLError 没有公开的导入路径,只能靠「context 还活着吗」来区分: - # 还活着说明是真故障,往上抛;已经关了就是退出噪声,忽略。 - if rclpy.ok(): - raise - finally: - node.destroy_node() - rclpy.try_shutdown() # 幂等版:context 已被关过时不会二次报错 - - -if __name__ == '__main__': - main() diff --git a/src/sentry_sim/scripts/odom_tf.py b/src/sentry_sim/scripts/odom_tf.py deleted file mode 100755 index 19b806c..0000000 --- a/src/sentry_sim/scripts/odom_tf.py +++ /dev/null @@ -1,81 +0,0 @@ -#!/usr/bin/env python3 -"""把 Gazebo 的 /odom 广播成 ROS TF:odom -> base_link。 - -为什么需要:Gazebo 的 MecanumDrive 插件只发 odometry 消息、不发 TF, -而 Nav2 需要完整 TF 树(map -> odom -> base_link)。这个节点补上 odom -> base_link。 - -同时把 frame_id 归一化:Gazebo 里可能是 sentry/base_link 这种带模型名前缀的写法。 -""" - -import rclpy -from geometry_msgs.msg import TransformStamped -from nav_msgs.msg import Odometry -from rclpy.executors import ExternalShutdownException -from rclpy.node import Node -from tf2_ros import TransformBroadcaster - - -class OdomTf(Node): - def __init__(self): - super().__init__('sentry_odom_tf') - self.declare_parameter('odom_frame', 'odom') - self.declare_parameter('base_frame', 'base_link') - self.declare_parameter('odom_topic', '/odom') - # 调试用:给里程计加一个比例误差,模拟「轮径标定错了」。 - # 1.0 = 真实里程计;1.15 = 报告的距离偏大 15%(越走越偏)。 - # 用途:验证 AMCL 是不是真的在纠正里程计漂移。 - self.declare_parameter('odom_scale', 1.0) - - self.odom_scale = self.get_parameter('odom_scale').value - self.odom_frame = self.get_parameter('odom_frame').value - self.base_frame = self.get_parameter('base_frame').value - topic = self.get_parameter('odom_topic').value - - self.br = TransformBroadcaster(self) - self.create_subscription(Odometry, topic, self.on_odom, 10) - self.get_logger().info( - f'odom_tf: 订阅 {topic},广播 {self.odom_frame} -> {self.base_frame}' - f',odom_scale={self.odom_scale}') - if abs(self.odom_scale - 1.0) > 1e-6: - self.get_logger().warning( - f'odom_tf: odom_scale={self.odom_scale} != 1.0 —— ' - '里程计被人为打了比例误差,这是演示/调试用途') - - def on_odom(self, msg: Odometry): - t = TransformStamped() - t.header.stamp = msg.header.stamp - t.header.frame_id = self.odom_frame - t.child_frame_id = self.base_frame - # odom_scale 只作用在平移上(轮径误差就是「距离按比例走偏」) - t.transform.translation.x = msg.pose.pose.position.x * self.odom_scale - t.transform.translation.y = msg.pose.pose.position.y * self.odom_scale - t.transform.translation.z = msg.pose.pose.position.z - t.transform.rotation = msg.pose.pose.orientation - self.br.sendTransform(t) - - -def main(): - rclpy.init() - node = OdomTf() - try: - rclpy.spin(node) - except KeyboardInterrupt: - pass - except ExternalShutdownException: - # Ctrl+C 或 SIGTERM 时 rclpy 的信号处理已经把 context 关掉了, - # executor 等完一轮发现 context 不再 ok 就走这里。属于正常退出。 - pass - except Exception: # noqa: BLE001 - # 同一个退出竞态的另一副面孔:如果 context 在进入下一轮循环前就关了, - # _rclpy.WaitSet 构造会直接抛 RCLError(failed to initialize wait set …)。 - # RCLError 没有公开的导入路径,只能靠「context 还活着吗」来区分: - # 还活着说明是真故障,往上抛;已经关了就是退出噪声,忽略。 - if rclpy.ok(): - raise - finally: - node.destroy_node() - rclpy.try_shutdown() # 幂等版:context 已被关过时不会二次报错 - - -if __name__ == '__main__': - main() diff --git a/src/sentry_sim/scripts/sentry_up.sh b/src/sentry_sim/scripts/sentry_up.sh index cfd3a86..a8eb9b1 100755 --- a/src/sentry_sim/scripts/sentry_up.sh +++ b/src/sentry_sim/scripts/sentry_up.sh @@ -5,6 +5,8 @@ # scripts/sentry_up.sh # 开 GUI + RViz(需要显卡) # HEADLESS=1 scripts/sentry_up.sh # 无界面(服务器/CI) # NAV2=0 scripts/sentry_up.sh # 只起仿真和桥,不起导航 +# 想换出生点:直接改 worlds/sentry_arena.sdf 里 sentry 的 , +# 以及 config/nav2_params.yaml 里 amcl 的 initial_pose(两处必须一致)。 # 前置:先在仓库根编译节点(编译后无需再编译) # cd ~/Gazebo_projects/sentry_nav_dev && xmake # @@ -31,6 +33,13 @@ export SENTRY_SIM_SHARE="$PKG_SHARE" # xmake 产物目录(在仓库根,`cd 仓库根 && xmake` 产出) NAV_BIN_DIR="${NAV_BIN_DIR:-${WS}/build/linux/x86_64/release}" +# Fast DDS 的共享内存传输在部分环境会导致 action 服务发现失败: +# bt_navigator 等不到 /wait action(60 s 超时)→ lifecycle_manager 报 +# "Failed to change state for node: bt_navigator" / "Aborting bringup"。 +# 这里默认走 UDPv4 传输(本机小消息走 UDP,不依赖 /dev/shm),实测能稳定激活。 +# 想回退共享内存:FASTDDS_BUILTIN_TRANSPORTS=SHM scripts/sentry_up.sh +export FASTDDS_BUILTIN_TRANSPORTS="${FASTDDS_BUILTIN_TRANSPORTS:-UDPv4}" + source /opt/ros/lyrical/setup.bash # 本工程不使用 ament / colcon,节点是 xmake 直接编出的二进制, @@ -136,7 +145,6 @@ ros2 run ros_gz_bridge parameter_bridge \ '/scan@sensor_msgs/msg/LaserScan[gz.msgs.LaserScan' \ '/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \ '/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \ - '/scan2d@sensor_msgs/msg/LaserScan[gz.msgs.LaserScan' \ --ros-args -p use_sim_time:=true & PIDS+=($!) @@ -148,15 +156,15 @@ ros2 run robot_state_publisher robot_state_publisher --ros-args \ PIDS+=($!) # ---------- 5. odom -> base_link ---------- -echo "[sentry_up] 启动 odom_tf" +echo "[sentry_up] 启动 odom_tf(${NAV_BIN_DIR}/odom_tf,C++ 版)" # SENTRY_ODOM_SCALE != 1.0 时给里程计加比例误差(演示 AMCL 纠正漂移用) -python3 "${PKG_SHARE}/scripts/odom_tf.py" --ros-args \ +$(nav_cmd odom_tf) --ros-args \ -p use_sim_time:=true -p "odom_scale:=${SENTRY_ODOM_SCALE:-1.0}" & PIDS+=($!) # ---------- 5.5 /cmd_vel 转发(Nav2 -> ros_gz 桥用的话题名)---------- -echo "[sentry_up] 启动 cmd_vel 转发" -python3 "${PKG_SHARE}/scripts/cmd_vel_relay.py" --ros-args -p use_sim_time:=true & +echo "[sentry_up] 启动 cmd_vel 转发(${NAV_BIN_DIR}/cmd_vel_relay,C++ 版)" +$(nav_cmd cmd_vel_relay) --ros-args -p use_sim_time:=true & PIDS+=($!) # ---------- 5.55 点云自滤(剔除车身自身回波,Nav2 避障用)---------- @@ -174,20 +182,13 @@ PIDS+=($!) # --x 0.9 --y 4.0 --z 0.0 --yaw 0.0 --pitch 0.0 --roll 0.0 \ # --frame-id map --child-frame-id odom --ros-args -p use_sim_time:=true & -# ---------- 5.65 map->field 静态变换(场地中心 = 零点)---------- -# 官方场地坐标系是「西南内角 = (0,0)」(见迁移包 parameters.json), -# 但比赛决策更关心「场地中心」。所以加一个 field 帧: -# map (6.0, 4.0) == field (0.0, 0.0) -# 换算表(12×8 场地): -# 场地范围 map x[0,12] y[0,8] -> field x[-6,6] y[-4,4] -# 场地中心 map (6,4) -> field (0,0) -# 出生点 map (0.9, 4.0) -> field (-5.1, 0.0) -# 对面半场 map x > 6 -> field x > 0 -# Nav2 内部仍然全用 map(地图/代价地图都锚在 map 上),需要时 TF 自动转换; -# patrol 想用直觉坐标就 `-p frame_id:=field`。 -echo "[sentry_up] 启动 map->field 静态变换(场地中心 = 零点)" +# ---------- 5.65 map->field 恒等变换(两者都是「场地中心 = 零点」)---------- +# 世界与地图都已整体平移 (-6,-4)(官方包原定义是西南内角 = (0,0)), +# 现在 map 帧本身就以场地中心为原点:内场范围 x[-6,6] y[-4,4], +# 出生点 (1.0, 1.0)。field 帧保留为恒等别名,兼容 `-p frame_id:=field` 的用法。 +echo "[sentry_up] 发布 map->field 恒等变换(中心 = 零点)" ros2 run tf2_ros static_transform_publisher \ - --x 6.0 --y 4.0 --z 0.0 --yaw 0.0 --pitch 0.0 --roll 0.0 \ + --x 0.0 --y 0.0 --z 0.0 --yaw 0.0 --pitch 0.0 --roll 0.0 \ --frame-id map --child-frame-id field --ros-args -p use_sim_time:=true & PIDS+=($!) @@ -239,7 +240,7 @@ if [ "$NAV2" = "1" ]; then fi echo "[sentry_up] 全部启动完成。坐标系:" -echo " map —— 官方栅格图坐标系,场地西南内角 = (0,0),场地中心 = (6.0, 4.0)" -echo " field —— 场地中心 = (0,0),场地范围 x[-6,6] y[-4,4],出生点在 (-5.1, 0.0)" +echo " map —— 场地中心 = (0,0),范围 x[-6,6] y[-4,4],当前出生点在 (-5.0, 3.0)" +echo " field —— 与 map 相同(恒等变换,保留给决策代码用)" echo "体检(含 Gazebo 真值对照):python3 tools/check_stack.py" wait diff --git a/src/sentry_sim/urdf/sentry.urdf.xacro b/src/sentry_sim/urdf/sentry.urdf.xacro index c77c774..cf14144 100644 --- a/src/sentry_sim/urdf/sentry.urdf.xacro +++ b/src/sentry_sim/urdf/sentry.urdf.xacro @@ -66,7 +66,10 @@ 不能用一个大盒子包住整车——MID-360 在 z=0.405,会被包在盒子内部, 雷达射线全打在盒子内壁上(实测距离只有 0.2~0.4 m)。 --> - + + @@ -233,53 +236,9 @@ - - - - 0 0 0 0 0 0 - scan2d - lidar_link - 10 - true - false - - - - 360 - 1 - -3.14159265 - 3.14159265 - - - 1 - 1 - 0.0 - 0.0 - - - - 0.10 - 12.0 - 0.01 - - - gaussian - 0.0 - 0.01 - - - - + diff --git a/src/sentry_sim/worlds/README.md b/src/sentry_sim/worlds/README.md index dbdecf8..531aa8d 100644 --- a/src/sentry_sim/worlds/README.md +++ b/src/sentry_sim/worlds/README.md @@ -11,7 +11,7 @@ | `model://rmul_2027` | RMUL 2027 官方场地(来自迁移包) | ✅ 有(官方 STEP 网格) | | `model://arena_walls` | 体育馆墙壁 + 大厅地面(内空 40×28 m,墙高 10 m) | ✅ 有 | | `model://arena_roof` | 体育馆屋顶(z=10 m,含梁和 12 条灯带) | ✅ 有(但激光够不到) | -| `model://sentry` | 哨兵整车,出生点 **场地坐标 (0.9, 4.0)** | ✅ 有 | +| `model://sentry` | 哨兵整车,出生点 **场地坐标 (-5.0, 3.0)**(世界原点 = 场地中心) | ✅ 有 | > `model://catch_net`(拦截网)的 `` **已注释停用**(2026-11-16)。 > 模型文件还在 `../models/catch_net/`,要恢复就把那段注释取消。 @@ -19,7 +19,10 @@ ## 其它内容 - 插件:Physics / UserCommands / SceneBroadcaster / **CpuLidar** / Imu -- 平行光 `sun` 在 (6,4,10) 往下照,环境光 0.75,背景色 `0.16 0.17 0.19` +- 世界坐标已整体平移 (−6,−4):**场地中心 = 世界原点 (0,0)**,内场范围 + x[−6,6] y[−4,4];地图 `rmul_2027.yaml` 的 origin 同步改为 (−6.4,−4.4), + 保证 2D 栅格图与 AMCL/世界坐标系一致 +- 平行光 `sun` 在 (0,0,10) 往下照,环境光 0.75,背景色 `0.16 0.17 0.19` - GUI 相机 `(1.6, -2.5, 1.8)`,抬头 20° ## 注意 diff --git a/src/sentry_sim/worlds/sentry_arena.sdf b/src/sentry_sim/worlds/sentry_arena.sdf index b36bfd6..266a2a6 100644 --- a/src/sentry_sim/worlds/sentry_arena.sdf +++ b/src/sentry_sim/worlds/sentry_arena.sdf @@ -3,7 +3,13 @@ + <迁移包>/src/guodong_sentry_sim/models + + 坐标系:世界原点 = 场地中心(中心交战点)。 + 官方迁移包定义「西南内角 = (0,0)」(内场 0..12 × 0..8), + 这里所有 include 整体平移 (-6,-4),使内场中心落在世界原点 (0,0), + 即内场范围 x ∈ [-6,6], y ∈ [-4,4]。地图 yaml 的 origin 同步改为 + (-6.4,-4.4),保证 2D 栅格图与世界/AMCL 坐标系一致。 --> 0.002 @@ -25,7 +31,7 @@ - 6 4 10 0 0 0 + 0 0 10 0 0 0 -0.3 0.2 -1 0.8 0.8 0.8 1 0.15 0.15 0.15 1 @@ -35,7 +41,7 @@ model://rmul_2027 rmul_2027 - 0 0 0 0 0 0 + -6 -4 0 0 0 0 + model://sentry sentry - 0.9 4.0 0.0 0 0 0 + -5.0 3.0 0.0 0 0 0 diff --git a/tools/README.md b/tools/README.md index a2bc7a8..2ca5062 100644 --- a/tools/README.md +++ b/tools/README.md @@ -18,10 +18,10 @@ |---|---| | `demo.py` | 前进 → 转向 → 再前进,并打印雷达和里程计 | | `drive_demo.py` | 走正方形并生成 SVG 轨迹图(`generated/drive_trajectory.svg`) | -| `nav_client.py` | ★ 发 Nav2 目标点。**发之前先读 `/map` 预检**:占据值 ≥65、未知格、净空 <0.5 m(车体半对角 0.422 m)都直接拦下并说明原因,不合格不发。通过后打印位置/重试次数/结果/离目标误差/field 坐标 | -| `free_goals.py` | ★ 从 `rmul_2027.yaml` + `.pgm` 算出「从起点连通的安全区」并列出可去目标点(附净空、距离、可直接复制的 `nav_client.py` 命令)。**不需要起 ROS** | +| `build/linux/x86_64/release/nav_client` | ★ 发 Nav2 目标点。**发之前先读 `/map` 预检**:占据值 ≥65、未知格、净空 <0.5 m(车体半对角 0.422 m)都直接拦下并说明原因,不合格不发。通过后打印位置/重试次数/结果/离目标误差/field 坐标 | +| `free_goals.py` | ★ 从 `rmul_2027.yaml` + `.pgm` 算出「从起点连通的安全区」并列出可去目标点(附净空、距离、可直接复制的 `build/linux/x86_64/release/nav_client` 命令)。**不需要起 ROS** | | `tf_watch.py` | ★ 实时盯 `map→odom` / `odom→base_link` / `map→base_link` 三条 TF 边 + Gazebo 真值 + `/scan2d` 有效率,超过 0.25 m 的跳变会打 ⚠️。**抓定位瞬移专用**:一个窗口开着,另一个窗口发目标 | -| ~~`send_goal.py`~~ | ⚠️ **已废弃(空炮)**:往 `/goal_pose` 话题发 PoseStamped,但 Nav2 **没有任何节点订阅它**(`lib/nav2_bt_navigator/bt_navigator` 里根本没有 `goal_pose` 这个字符串)。要发目标请用 `nav_client.py` | +| ~~`send_goal.py`~~ | ⚠️ **已废弃(空炮)**:往 `/goal_pose` 话题发 PoseStamped,但 Nav2 **没有任何节点订阅它**(`lib/nav2_bt_navigator/bt_navigator` 里根本没有 `goal_pose` 这个字符串)。要发目标请用 `build/linux/x86_64/release/nav_client` | | `scan_probe.py` | 雷达质量体检:有效束、距离分布、**有没有被车体糊住**。`scan_probe.py [话题]`,默认 `/scan2d` | | `probe_all.py` | 检查 `/clock /odom /scan /tf` 有没有数据 | | `probe_cmd.py` / `probe_cmd2.py` / `cmd_probe_all.py` | 统计各级 `/cmd_vel` 消息数 | diff --git a/tools/amcl_drift_demo.py b/tools/amcl_drift_demo.py index b1d9c33..f7f78af 100755 --- a/tools/amcl_drift_demo.py +++ b/tools/amcl_drift_demo.py @@ -98,7 +98,7 @@ if tf_xy('map', 'base_link') is None: print('\n⚠️ 本演示**直接发 /cmd_vel,绕过了整个 Nav2** —— 所以没有避障。') print(' 车撞到东西是预期的:这里要的是「里程计和真实位置不一致」,') print(' 走 Nav2 的话代价地图会把它绕开,就制造不出漂移了。') -print(' Nav2 自己的避障要另外验证(用 nav_client.py 发目标)。') +print(' Nav2 自己的避障要另外验证(用 build/linux/x86_64/release/nav_client 发目标)。') print() print('odom_scale = %.2f (1.00 = 真实里程计;>1 = 报告的距离偏大)' % SCALE) if abs(SCALE - 1.0) < 1e-6: diff --git a/tools/check_stack.py b/tools/check_stack.py index 436c7ef..98947a9 100644 --- a/tools/check_stack.py +++ b/tools/check_stack.py @@ -159,14 +159,15 @@ def main(): node.create_subscription(PointCloud2, '/scan/points_filtered', waiter('scan/points_filtered'), SENSOR_QOS) node.create_subscription(LaserScan, '/scan', waiter('scan'), SENSOR_QOS) + node.create_subscription(LaserScan, '/scan2d', waiter('scan2d'), SENSOR_QOS) node.create_subscription(Odometry, '/odom', waiter('odom'), 10) node.create_subscription(OccupancyGrid, '/map', waiter('map'), MAP_QOS) deadline = time.time() + 8.0 - while time.time() < deadline and len(seen) < 5: + while time.time() < deadline and len(seen) < 6: rclpy.spin_once(node, timeout_sec=0.2) - for key in ('map', 'odom', 'scan', 'scan/points', 'scan/points_filtered'): + for key in ('map', 'odom', 'scan', 'scan/points', 'scan/points_filtered', 'scan2d'): ok = key in seen note = '(latched,订阅端 QoS 必须 TRANSIENT_LOCAL)' if key == 'map' else '' print(' /%-22s %s %s' % (key, '✅ 有数据' if ok else '❌ 没收到', note)) @@ -225,8 +226,7 @@ def main(): else: gx, gy = truth[0], truth[1] print(' [真值] Gazebo 世界坐标 (%.3f, %.3f)' % (gx, gy)) - print(' 场地坐标 (map) (%.3f, %.3f)' % (gx, gy)) - print(' 中心零点 (field) (%.3f, %.3f)' % (gx - 6.0, gy - 4.0)) + print(' 场地坐标 (map=field) (%.3f, %.3f)' % (gx, gy)) if tf_pos is None: print(' [TF] map -> base_link 拿不到,无法比较') else: diff --git a/tools/free_goals.py b/tools/free_goals.py index e291e48..23242e4 100644 --- a/tools/free_goals.py +++ b/tools/free_goals.py @@ -3,8 +3,8 @@ 用法:: - python3 tools/free_goals.py # 起点默认 (0.9, 4.0) 出生点 - python3 tools/free_goals.py --from 6.0 4.0 # 换个起点 + python3 tools/free_goals.py # 起点默认 (-5.0, 3.0) 当前出生点 + python3 tools/free_goals.py --from 0.0 0.0 # 换个起点(场地中心) python3 tools/free_goals.py --min-clear 0.7 # 要求更大净空 python3 tools/free_goals.py --map path/to/x.yaml @@ -146,7 +146,7 @@ def main(): formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--map', default=DEFAULT_YAML, help='栅格图 yaml 路径') ap.add_argument('--from', dest='start', nargs=2, type=float, - default=[0.9, 4.0], metavar=('X', 'Y'), help='起点 map 坐标') + default=[-5.0, 3.0], metavar=('X', 'Y'), help='起点 map 坐标') ap.add_argument('--min-clear', type=float, default=DEFAULT_MIN_CLEAR, help=f'要求的最小净空(米),默认 {DEFAULT_MIN_CLEAR}') ap.add_argument('--grid', type=float, default=0.5, @@ -193,7 +193,7 @@ def main(): print('\n直接复制就能跑:') for x, y, cl in picked[:6]: - print(f' python3 tools/nav_client.py {x:.2f} {y:.2f}') + print(f' build/linux/x86_64/release/nav_client {x:.2f} {y:.2f}') if args.no_map: return 0 diff --git a/tools/mark_field_center.py b/tools/mark_field_center.py index 5613361..4bcdaf5 100644 --- a/tools/mark_field_center.py +++ b/tools/mark_field_center.py @@ -3,12 +3,12 @@ 发布可视化 Marker(不改仿真里的任何东西,纯叠加显示): - ① 红色圆柱 —— 用 `map` 帧表达场地中心 (6.0, 4.0) + ① 红色圆柱 —— 用 `map` 帧表达场地中心 (0, 0) ② 绿色球 —— 用 `field` 帧表达同一个点 (0.0, 0.0) 两者如果**完全重合**,说明 map→field 这条变换是对的 - ③ 黄色线框 —— 场地内圈 12×8 的边界(`map` 帧 x[0,12] y[0,8]) + ③ 黄色线框 —— 场地内圈 12×8 的边界(`map` 帧 x[-6,6] y[-4,4]) ④ 蓝色细线 —— 场地中线(crosshair),交点在场地中心 - ⑤ 文字标签 —— "field(0,0) = map(6.0,4.0)" + ⑤ 文字标签 —— "field(0,0) = map(0,0)" 用法: @@ -29,11 +29,14 @@ from rclpy.node import Node from rclpy.qos import DurabilityPolicy, HistoryPolicy, QoSProfile from visualization_msgs.msg import Marker -# 场地几何(来自官方 parameters.json:内圈 12×8,西南内角 = (0,0)) +# 场地几何(内圈 12×8)。世界/地图已整体平移:场地中心 = (0,0), +# 内圈范围 x ∈ [-6,6],y ∈ [-4,4]。 FIELD_W = 12.0 FIELD_H = 8.0 -CENTER_X = FIELD_W / 2.0 # 6.0 -CENTER_Y = FIELD_H / 2.0 # 4.0 +CENTER_X = 0.0 # 场地中心 x +CENTER_Y = 0.0 # 场地中心 y +X0 = -FIELD_W / 2.0 # -6.0 +Y0 = -FIELD_H / 2.0 # -4.0 class FieldCenterMarker(Node): @@ -85,8 +88,8 @@ class FieldCenterMarker(Node): line.header.stamp = now line.scale.x = 0.04 line.color.r, line.color.g, line.color.b, line.color.a = 1.0, 0.85, 0.1, 1.0 - for x, y in ((0, 0), (FIELD_W, 0), (FIELD_W, FIELD_H), - (0, FIELD_H), (0, 0)): + for x, y in ((X0, Y0), (X0 + FIELD_W, Y0), (X0 + FIELD_W, Y0 + FIELD_H), + (X0, Y0 + FIELD_H), (X0, Y0)): line.points.append(self._point(x, y)) ms.append(line) @@ -95,10 +98,10 @@ class FieldCenterMarker(Node): cross.header.stamp = now cross.scale.x = 0.03 cross.color.r, cross.color.g, cross.color.b, cross.color.a = 0.2, 0.5, 1.0, 1.0 - cross.points.append(self._point(CENTER_X, 0.0)) - cross.points.append(self._point(CENTER_X, FIELD_H)) - cross.points.append(self._point(0.0, CENTER_Y)) - cross.points.append(self._point(FIELD_W, CENTER_Y)) + cross.points.append(self._point(CENTER_X, Y0)) + cross.points.append(self._point(CENTER_X, Y0 + FIELD_H)) + cross.points.append(self._point(X0, CENTER_Y)) + cross.points.append(self._point(X0 + FIELD_W, CENTER_Y)) ms.append(cross) # ③ 红色圆柱:用 map 帧表达场地中心 @@ -125,7 +128,7 @@ class FieldCenterMarker(Node): text.pose.position = self._point(CENTER_X, CENTER_Y, self.z + 0.75) text.scale.z = 0.35 text.color.r = text.color.g = text.color.b = text.color.a = 1.0 - text.text = 'field(0,0) = map(6.0,4.0)' + text.text = 'field(0,0) = map(0,0)' ms.append(text) for m in ms: @@ -140,7 +143,7 @@ def main(): except KeyboardInterrupt: pass except Exception: # noqa: BLE001 - # 退出竞态(跟 odom_tf.py 同样的问题):context 已经关了就不用报 + # 退出竞态(跟 odom_tf 同样的问题):context 已经关了就不用报 if rclpy.ok(): raise finally: diff --git a/tools/nav_client.py b/tools/nav_client.py deleted file mode 100644 index a2bc9b4..0000000 --- a/tools/nav_client.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python3 -"""用 Nav2 的 NavigateToPose 动作发目标,发之前先用栅格图做可达性预检。 - -用法:: - - python3 tools/nav_client.py [yaw度] - python3 tools/nav_client.py 6.0 4.0 # 走到场地中部 - python3 tools/nav_client.py 6.0 4.0 90 # 到位置后朝向 +90° - python3 tools/nav_client.py 3.0 4.0 --force # 明知在障碍里也发(调试用) - -坐标是 map 帧:x∈[0,12],y∈[0,8],出生点 (0.9, 4.0)。 -想换成「场地中心 = 零点」的直觉坐标:field = (map_x - 6, map_y - 4)。 - -为什么要预检:Nav2 的规划器对「目标点落在障碍格里」只会吐一句 -``Failed to create plan with tolerance of: 0.500000``,看不出原因。 -这里直接读 /map,把目标点的占据值和净空算出来,不合格就在发之前拦住。 -""" - -import math -import sys -import time - -import numpy as np -import rclpy -from nav2_msgs.action import NavigateToPose -from nav_msgs.msg import OccupancyGrid -from rclpy.action import ActionClient -from rclpy.node import Node -from rclpy.parameter import Parameter -from rclpy.qos import DurabilityPolicy, QoSProfile, ReliabilityPolicy -from tf2_ros import Buffer, TransformListener - -# 车体是 0.65 x 0.54 矩形,半对角 0.422 m;小于这个值必然车身压障碍。 -HALF_DIAGONAL = 0.422 -# 低于这个净空就不建议去(膨胀层默认 0.45)。 -MIN_CLEARANCE = 0.50 -# 判定「被占据」的阈值,和 rmul_2027.yaml 的 occupied_thresh 对齐。 -OCCUPIED_THRESHOLD = 65 -# 净空搜索半径上限(米)。 -CLEARANCE_SEARCH = 2.0 - - -def parse_args(argv): - """分出位置参数和 --force。""" - force = '--force' in argv - pos = [a for a in argv if not a.startswith('--')] - gx = float(pos[0]) if len(pos) > 0 else 6.0 - gy = float(pos[1]) if len(pos) > 1 else 4.0 - yaw_deg = float(pos[2]) if len(pos) > 2 else 0.0 - return gx, gy, yaw_deg, force - - -def grid_to_array(grid): - """把 OccupancyGrid 变成 numpy 数组,行 0 = y 最小(和 origin 对齐)。""" - info = grid.info - arr = np.asarray(grid.data, dtype=np.int8).reshape(info.height, info.width) - return arr, info - - -def world_to_cell(info, x, y): - """世界坐标 -> 栅格下标,越界返回 None。""" - c = int(math.floor((x - info.origin.position.x) / info.resolution)) - r = int(math.floor((y - info.origin.position.y) / info.resolution)) - if not (0 <= c < info.width and 0 <= r < info.height): - return None - return r, c - - -def clearance_at(arr, res, r, c, search=CLEARANCE_SEARCH): - """返回 (r, c) 到最近障碍格的距离(米),超过 search 就返回 search。 - - 未知格(-1)也算障碍 —— 代价地图开了 track_unknown_space, - 在未知区里规划同样会失败,按障碍处理更接近实际行为。 - """ - n = max(1, int(search / res)) - r0, r1 = max(0, r - n), min(arr.shape[0], r + n + 1) - c0, c1 = max(0, c - n), min(arr.shape[1], c + n + 1) - win = arr[r0:r1, c0:c1] - bad = (win >= OCCUPIED_THRESHOLD) | (win < 0) - if not bad.any(): - return search - rr, cc = np.nonzero(bad) - dist = np.hypot(rr + r0 - r, cc + c0 - c) * res - return float(dist.min()) - - -def yaw_to_quaternion(yaw): - """从偏航角(弧度)构造只含 z/w 的四元数。""" - return math.sin(yaw / 2.0), math.cos(yaw / 2.0) - - -def main(): - """发一个目标并跟踪到结束。""" - gx, gy, yaw_deg, force = parse_args(sys.argv[1:]) - - rclpy.init() - # 整套栈都是 use_sim_time:=true(Gazebo 时钟),客户端必须一致, - # 否则本节点算出的时间戳跟 TF 里的仿真时间对不上。 - node = Node('nav_client', - parameter_overrides=[ - Parameter('use_sim_time', Parameter.Type.BOOL, True)]) - tf_buffer = Buffer() - TransformListener(tf_buffer, node) - - # /map 是 TRANSIENT_LOCAL 发布的,用默认 QoS 会一条都收不到。 - map_qos = QoSProfile(depth=1, - reliability=ReliabilityPolicy.RELIABLE, - durability=DurabilityPolicy.TRANSIENT_LOCAL) - holder = {} - node.create_subscription(OccupancyGrid, '/map', - lambda m: holder.setdefault('m', m), map_qos) - - t0 = time.time() - while 'm' not in holder and time.time() - t0 < 15.0: - rclpy.spin_once(node, timeout_sec=0.2) - - if 'm' not in holder: - print('⚠️ 15 秒内没收到 /map,跳过预检直接发目标') - arr = info = None - else: - arr, info = grid_to_array(holder['m']) - print(f'地图 {info.width}x{info.height} @ {info.resolution} m/px ' - f'origin=({info.origin.position.x:.2f}, {info.origin.position.y:.2f})') - - cell = world_to_cell(info, gx, gy) - if cell is None: - print(f'❌ 目标 ({gx:.2f}, {gy:.2f}) 在地图范围外,发出去也是 ABORTED') - node.destroy_node() - rclpy.shutdown() - return 1 - - r, c = cell - value = int(arr[r, c]) - clr = clearance_at(arr, info.resolution, r, c) - state = ('障碍' if value >= OCCUPIED_THRESHOLD - else '未知' if value < 0 else '空闲') - print(f'目标 ({gx:.2f}, {gy:.2f}) -> 栅格 ({c}, {r}) ' - f'占据值 {value:4d} ({state}) 净空 {clr:.2f} m') - - if state != '空闲' or clr < MIN_CLEARANCE: - print() - print(f'❌ 这个点不适合当目标(净空需 >= {MIN_CLEARANCE:.2f} m):') - if state == '障碍': - print(' 点落在障碍格里 —— 规划器必然报 ' - '"Failed to create plan with tolerance",换一个点。') - elif state == '未知': - print(' 点落在未知区域 —— 代价地图开了 track_unknown_space,同样规划不出来。') - else: - print(f' 净空只有 {clr:.2f} m,车身半对角就有 {HALF_DIAGONAL:.2f} m,' - '挤进去会卡死。') - print(' 想找安全点:python3 tools/free_goals.py') - if not force: - print(' (确实要发就加 --force)') - node.destroy_node() - rclpy.shutdown() - return 2 - print(' --force 已指定,继续发送') - - client = ActionClient(node, NavigateToPose, 'navigate_to_pose') - print('等待 navigate_to_pose 动作服务器...') - if not client.wait_for_server(timeout_sec=30): - print('❌ 动作服务器不可用(Nav2 没起来,或 bt_navigator 没 ACTIVE)') - node.destroy_node() - rclpy.shutdown() - return 1 - print('✅ 动作服务器可用') - - goal = NavigateToPose.Goal() - goal.pose.header.frame_id = 'map' - goal.pose.header.stamp = node.get_clock().now().to_msg() - goal.pose.pose.position.x = gx - goal.pose.pose.position.y = gy - qz, qw = yaw_to_quaternion(math.radians(yaw_deg)) - goal.pose.pose.orientation.z = qz - goal.pose.pose.orientation.w = qw - - # 注意:不要打印 feedback.distance_remaining。 - # Nav2 1.5 的 NavigateToPose 不会填这个字段,永远是 0.00, - # 打了只会刷屏骗人。用 current_pose 和 number_of_recoveries。 - state = {'last': 0.0} - - def on_feedback(fb): - now = time.time() - if now - state['last'] < 1.0: - return - state['last'] = now - f = fb.feedback - p = f.current_pose.pose.position - print(f' 位置 ({p.x:5.2f}, {p.y:5.2f}) ' - f'重试 {int(getattr(f, "number_of_recoveries", 0))}') - - sent = client.send_goal_async(goal, feedback_callback=on_feedback) - rclpy.spin_until_future_complete(node, sent, timeout_sec=15) - handle = sent.result() - if handle is None or not handle.accepted: - print('❌ 目标被拒绝') - node.destroy_node() - rclpy.shutdown() - return 1 - print('✅ 目标已接受,等待结果...') - - res = handle.get_result_async() - t0 = time.time() - while not res.done() and time.time() - t0 < 180: - rclpy.spin_once(node, timeout_sec=0.2) - - names = {4: '✅ SUCCEEDED', 5: '❌ CANCELED', 6: '❌ ABORTED'} - if res.done(): - status = res.result().status - print(f'结果: {names.get(status, status)}') - else: - print('超时未完成(180 s)') - - try: - tr = tf_buffer.lookup_transform('map', 'base_link', rclpy.time.Time()) - p = tr.transform.translation - err = math.hypot(p.x - gx, p.y - gy) - print(f'TF map->base_link: ({p.x:.2f}, {p.y:.2f}) ' - f'离目标 {err:.2f} m ' - f'field 坐标 ({p.x - 6.0:.2f}, {p.y - 4.0:.2f})') - except Exception as exc: # noqa: BLE001 - print(f'⚠️ 查不到 TF map->base_link: {exc}') - - node.destroy_node() - rclpy.shutdown() - return 0 - - -if __name__ == '__main__': - sys.exit(main())